Skip to content

⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.

Rename icon to packs-v2.png to bust browser cache

Daniel Miessler3ba311031460
diff --git a/Bundles/Kai/README.md b/Bundles/Kai/README.md
index 1c86c0ee..815c5d15 100644
--- a/Bundles/Kai/README.md
+++ b/Bundles/Kai/README.md
@@ -74,57 +74,187 @@ When fully installed, the Kai bundle gives you a number of features that elevate
### Prerequisites
- [Bun](https://bun.sh): `curl -fsSL https://bun.sh/install | bash`
-- [Claude Code](https://claude.com/claude-code) installed
+- [Claude Code](https://claude.com/claude-code) or compatible AI coding assistant
-### Install (AI-Assisted)
+### Quick Start: Interactive Wizard (Recommended)
-For each available Pack in order:
+The Kai Bundle includes an interactive installation wizard that guides you through setup:
+```bash
+# Navigate to the bundle directory
+cd ~/Projects/PAI/Bundles/Kai
+
+# Run the wizard
+bun run install.ts
```
-1. Give your AI the Pack file
-2. Say: "Install this Pack into my system"
-3. Verify installation before proceeding to next Pack
+
+**The wizard will:**
+1. **Prompt for configuration** - Ask where to install, what to name your AI, timezone, etc.
+2. **Detect conflicts** - Find existing PAI installations or Claude hooks
+3. **Offer resolution** - Merge, replace, or cancel based on your preference
+4. **Create backup** - Optionally backup existing files before changes
+5. **Set up structure** - Create all required directories
+6. **Configure environment** - Add variables to your shell profile
+7. **Guide pack installation** - Provide prompts for each pack in order
+
+### Configuration Variables
+
+The wizard will ask for these values:
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `PAI_DIR` | `~/.config/pai` | Where PAI stores files (hooks, history, skills) |
+| `DA` | `PAI` | Your AI assistant's name (e.g., Kai, Atlas, Nova) |
+| `TIME_ZONE` | System default | Timezone for timestamps |
+| `ELEVENLABS_API_KEY` | - | Optional: For voice notifications |
+| `ELEVENLABS_VOICE_ID` | Default voice | Optional: Which voice to use |
+
+### Conflict Detection
+
+The wizard automatically detects and handles:
+
+- **Existing PAI directories** - Files already in your PAI_DIR
+- **Claude settings hooks** - Existing hooks in `~/.claude/settings.json`
+- **Environment variables** - PAI_DIR, DA, etc. already set
+
+**Resolution options:**
+- **Merge** - Add Kai hooks alongside your existing hooks
+- **Replace** - Start fresh (with optional backup)
+- **Cancel** - Exit without changes
+
+### Manual Installation (Alternative)
+
+If you prefer not to use the wizard, follow these steps:
+
+#### Step 1: System Analysis (REQUIRED)
+
+Before installing, analyze your current system state:
+
+```bash
+# 1. Check existing PAI installation
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+echo "=== PAI Installation Check ==="
+echo "PAI_DIR: ${PAI_DIR:-'NOT SET - will use ~/.config/pai'}"
+
+if [ -d "$PAI_CHECK" ]; then
+ echo "⚠️ PAI directory EXISTS at: $PAI_CHECK"
+ echo "Contents:"
+ ls -la "$PAI_CHECK" 2>/dev/null
+else
+ echo "✓ Clean install - no existing PAI directory"
+fi
+
+# 2. Check Claude settings for existing hooks
+echo ""
+echo "=== Claude Settings Check ==="
+if [ -f "$HOME/.claude/settings.json" ]; then
+ if grep -q '"hooks"' "$HOME/.claude/settings.json"; then
+ echo "⚠️ Existing hooks found in settings.json:"
+ grep -A 10 '"hooks"' "$HOME/.claude/settings.json" | head -15
+ else
+ echo "✓ No existing hooks in settings.json"
+ fi
+else
+ echo "✓ No settings.json (will be created)"
+fi
+
+# 3. Check environment
+echo ""
+echo "=== Environment Check ==="
+echo "DA (AI name): ${DA:-'NOT SET'}"
+echo "TIME_ZONE: ${TIME_ZONE:-'NOT SET'}"
+echo "ELEVENLABS_API_KEY: ${ELEVENLABS_API_KEY:+'SET'}${ELEVENLABS_API_KEY:-'NOT SET'}"
```
-**Current installation sequence:**
+#### Step 2: Backup (If Conflicts Detected)
```bash
-# Step 1: Hook System (available) - Foundation
-Give AI: ~/Projects/PAI/Packs/kai-hook-system.md
-# Verify: ls $PAI_DIR/hooks/
+BACKUP_DIR="$HOME/.pai-backup/$(date +%Y%m%d-%H%M%S)"
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+
+# Backup existing PAI directory
+if [ -d "$PAI_CHECK" ]; then
+ mkdir -p "$BACKUP_DIR"
+ cp -r "$PAI_CHECK" "$BACKUP_DIR/pai"
+ echo "✓ Backed up PAI to $BACKUP_DIR/pai"
+fi
+
+# Backup Claude settings
+if [ -f "$HOME/.claude/settings.json" ]; then
+ mkdir -p "$BACKUP_DIR"
+ cp "$HOME/.claude/settings.json" "$BACKUP_DIR/settings.json"
+ echo "✓ Backed up settings.json to $BACKUP_DIR/"
+fi
+```
-# Step 2: History System (available)
-Give AI: ~/Projects/PAI/Packs/kai-history-system.md
-# Verify: ls $PAI_DIR/history/
+#### Step 3: Set Up Environment
-# Step 3: Skill System (available)
-Give AI: ~/Projects/PAI/Packs/kai-skill-system.md
-# Verify: ls $PAI_DIR/skills/ && bun run $PAI_DIR/tools/SkillSearch.ts --list
+```bash
+# Add to your shell profile (~/.zshrc or ~/.bashrc)
+export PAI_DIR="$HOME/.config/pai"
+export DA="YourAIName" # Your AI's name
+export TIME_ZONE="America/Los_Angeles" # Your timezone
+export PAI_SOURCE_APP="$DA"
+
+# Reload shell
+source ~/.zshrc # or ~/.bashrc
+```
+
+#### Step 4: Create Directory Structure
+
+```bash
+mkdir -p $PAI_DIR/{hooks/lib,History/{Sessions,Learnings,Research,Decisions},Skills/CORE,Tools,voice}
+```
+
+#### Step 5: Install Packs In Order
+
+Give each pack file to your AI with the context:
+```
+Install this pack using PAI_DIR="[your path]" and DA="[your AI name]".
+Run the Pre-Installation System Analysis section first to check for conflicts.
+```
+
+### Pack Installation Sequence
+
+After running the wizard, install each pack in order by giving your AI the pack file:
-# Step 4: Voice System (available)
-Give AI: ~/Projects/PAI/Packs/kai-voice-system.md
-# Verify: Check stop-hook.ts exists and notification server pattern is configured
+| # | Pack | Command | Verification |
+|---|------|---------|--------------|
+| 1 | Hook System | Give AI: `Packs/kai-hook-system.md` | `ls $PAI_DIR/hooks/` |
+| 2 | History System | Give AI: `Packs/kai-history-system.md` | `ls $PAI_DIR/History/` |
+| 3 | Skill System | Give AI: `Packs/kai-skill-system.md` | `bun run $PAI_DIR/Tools/SkillSearch.ts --list` |
+| 4 | Voice System | Give AI: `Packs/kai-voice-system.md` | Check stop-hook.ts exists |
+| 5 | Identity | Give AI: `Packs/kai-identity.md` | `ls $PAI_DIR/Skills/CORE/` |
-# Step 5: Identity System (available)
-Give AI: ~/Projects/PAI/Packs/kai-identity.md
-# Verify: ls $PAI_DIR/Skills/CORE/ && check response format in SKILL.md
+**For each pack, tell your AI:**
+```
+Install this pack using:
+- PAI_DIR: [your configured path]
+- DA: [your AI name]
```
### Verify Bundle
-After installing available Packs:
+After installing all packs:
```bash
-# Check History
-ls $PAI_DIR/History/
-# Should show: Sessions/, Learnings/, Research/, Decisions/
+# Check complete directory structure
+ls -la $PAI_DIR/
-# Check Skills
-ls $PAI_DIR/Skills/
-# Should show: CORE/, CreateSkill/, skill-index.json
+# Expected directories:
+# hooks/ - Event-driven automation
+# History/ - Sessions, Learnings, Research, Decisions
+# Skills/ - CORE and other skills
+# Tools/ - CLI utilities
+# voice/ - Voice server files
-# Search capabilities
+# Check hooks are registered
+cat ~/.claude/settings.json | grep -A 5 "hooks"
+
+# Check skills are indexed
bun run $PAI_DIR/Tools/SkillSearch.ts --list
+
+# Restart Claude Code to activate all hooks
```
---
diff --git a/Bundles/Kai/install.ts b/Bundles/Kai/install.ts
new file mode 100644
index 00000000..74629ca4
--- /dev/null
+++ b/Bundles/Kai/install.ts
@@ -0,0 +1,722 @@
+#!/usr/bin/env bun
+/**
+ * PAI Kai Bundle Interactive Installer
+ *
+ * A wizard-style installer that guides users through setting up the complete
+ * Kai Personal AI Infrastructure bundle with conflict detection and resolution.
+ *
+ * Usage: bun run install.ts
+ *
+ * @author Daniel Miessler
+ * @license MIT
+ */
+
+import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } from 'fs';
+import { join, dirname, resolve } from 'path';
+import { homedir } from 'os';
+import { $ } from 'bun';
+
+// ============================================================================
+// Types and Interfaces
+// ============================================================================
+
+interface WizardConfig {
+ paiDir: string;
+ daName: string;
+ timeZone: string;
+ elevenLabsApiKey: string;
+ elevenLabsVoiceId: string;
+ observabilityUrl: string;
+ shellProfile: string;
+}
+
+interface ConflictResult {
+ type: 'none' | 'merge' | 'replace' | 'skip';
+ details?: string;
+}
+
+interface PackInfo {
+ id: string;
+ name: string;
+ file: string;
+ description: string;
+ dependencies: string[];
+}
+
+interface InstallResult {
+ success: boolean;
+ message: string;
+ details?: string[];
+}
+
+// ============================================================================
+// Constants
+// ============================================================================
+
+const COLORS = {
+ reset: '\x1b[0m',
+ bold: '\x1b[1m',
+ dim: '\x1b[2m',
+ red: '\x1b[31m',
+ green: '\x1b[32m',
+ yellow: '\x1b[33m',
+ blue: '\x1b[34m',
+ magenta: '\x1b[35m',
+ cyan: '\x1b[36m',
+ white: '\x1b[37m',
+};
+
+const PACKS: PackInfo[] = [
+ {
+ id: 'kai-hook-system',
+ name: 'Hook System',
+ file: '../../Packs/kai-hook-system.md',
+ description: 'Event-driven automation foundation',
+ dependencies: [],
+ },
+ {
+ id: 'kai-history-system',
+ name: 'History System',
+ file: '../../Packs/kai-history-system.md',
+ description: 'Memory and automatic capture',
+ dependencies: ['kai-hook-system'],
+ },
+ {
+ id: 'kai-skill-system',
+ name: 'Skill System',
+ file: '../../Packs/kai-skill-system.md',
+ description: 'Capability routing',
+ dependencies: ['kai-hook-system', 'kai-history-system'],
+ },
+ {
+ id: 'kai-voice-system',
+ name: 'Voice System',
+ file: '../../Packs/kai-voice-system.md',
+ description: 'Voice notifications via ElevenLabs',
+ dependencies: ['kai-hook-system', 'kai-skill-system'],
+ },
+ {
+ id: 'kai-identity',
+ name: 'Identity',
+ file: '../../Packs/kai-identity.md',
+ description: 'Personality layer (CORE skill)',
+ dependencies: ['kai-hook-system', 'kai-history-system', 'kai-skill-system', 'kai-voice-system'],
+ },
+];
+
+const DEFAULT_CONFIG: WizardConfig = {
+ paiDir: join(homedir(), '.config', 'pai'),
+ daName: 'PAI',
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ elevenLabsApiKey: '',
+ elevenLabsVoiceId: 's3TPKV1kjDlVtZbl4Ksh',
+ observabilityUrl: 'http://localhost:4000/events',
+ shellProfile: '',
+};
+
+// ============================================================================
+// Utility Functions
+// ============================================================================
+
+function c(color: keyof typeof COLORS, text: string): string {
+ return `${COLORS[color]}${text}${COLORS.reset}`;
+}
+
+function log(message: string): void {
+ console.log(message);
+}
+
+function logSection(title: string): void {
+ log('');
+ log(c('cyan', '━'.repeat(60)));
+ log(c('bold', ` ${title}`));
+ log(c('cyan', '━'.repeat(60)));
+ log('');
+}
+
+function logSuccess(message: string): void {
+ log(`${c('green', '✓')} ${message}`);
+}
+
+function logWarning(message: string): void {
+ log(`${c('yellow', '⚠')} ${message}`);
+}
+
+function logError(message: string): void {
+ log(`${c('red', '✗')} ${message}`);
+}
+
+function logInfo(message: string): void {
+ log(`${c('blue', 'ℹ')} ${message}`);
+}
+
+async function prompt(question: string, defaultValue: string = ''): Promise<string> {
+ const defaultDisplay = defaultValue ? c('dim', ` [${defaultValue}]`) : '';
+ process.stdout.write(`${c('cyan', '?')} ${question}${defaultDisplay}: `);
+
+ const reader = Bun.stdin.stream().getReader();
+ const decoder = new TextDecoder();
+ let input = '';
+
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ const chunk = decoder.decode(value);
+ input += chunk;
+
+ if (input.includes('\n')) {
+ reader.releaseLock();
+ break;
+ }
+ }
+
+ const result = input.trim();
+ return result || defaultValue;
+}
+
+async function promptYesNo(question: string, defaultYes: boolean = true): Promise<boolean> {
+ const hint = defaultYes ? 'Y/n' : 'y/N';
+ const answer = await prompt(`${question} (${hint})`, defaultYes ? 'yes' : 'no');
+ return answer.toLowerCase().startsWith('y');
+}
+
+async function promptChoice(question: string, choices: string[], defaultIndex: number = 0): Promise<number> {
+ log(`${c('cyan', '?')} ${question}`);
+ choices.forEach((choice, i) => {
+ const marker = i === defaultIndex ? c('green', '●') : c('dim', '○');
+ log(` ${marker} ${i + 1}. ${choice}`);
+ });
+
+ const answer = await prompt('Enter number', String(defaultIndex + 1));
+ const parsed = parseInt(answer, 10);
+
+ if (isNaN(parsed) || parsed < 1 || parsed > choices.length) {
+ return defaultIndex;
+ }
+
+ return parsed - 1;
+}
+
+function detectShellProfile(): string {
+ const shell = process.env.SHELL || '/bin/zsh';
+ const home = homedir();
+
+ if (shell.includes('zsh')) {
+ const zshrc = join(home, '.zshrc');
+ if (existsSync(zshrc)) return zshrc;
+ return join(home, '.zprofile');
+ }
+
+ if (shell.includes('bash')) {
+ const bashrc = join(home, '.bashrc');
+ if (existsSync(bashrc)) return bashrc;
+ const profile = join(home, '.bash_profile');
+ if (existsSync(profile)) return profile;
+ return join(home, '.profile');
+ }
+
+ // Fallback
+ return join(home, '.profile');
+}
+
+function detectExistingInstallation(paiDir: string): {
+ exists: boolean;
+ directories: string[];
+ files: string[];
+} {
+ if (!existsSync(paiDir)) {
+ return { exists: false, directories: [], files: [] };
+ }
+
+ const directories: string[] = [];
+ const files: string[] = [];
+
+ try {
+ const entries = readdirSync(paiDir);
+ for (const entry of entries) {
+ const fullPath = join(paiDir, entry);
+ const stat = statSync(fullPath);
+ if (stat.isDirectory()) {
+ directories.push(entry);
+ } else {
+ files.push(entry);
+ }
+ }
+ } catch {
+ // Directory exists but unreadable
+ }
+
+ return { exists: true, directories, files };
+}
+
+function detectClaudeSettings(): {
+ exists: boolean;
+ hasHooks: boolean;
+ hookCount: number;
+ path: string;
+} {
+ const claudeDir = join(homedir(), '.claude');
+ const settingsPath = join(claudeDir, 'settings.json');
+
+ if (!existsSync(settingsPath)) {
+ return { exists: false, hasHooks: false, hookCount: 0, path: settingsPath };
+ }
+
+ try {
+ const content = readFileSync(settingsPath, 'utf-8');
+ const settings = JSON.parse(content);
+
+ const hooks = settings.hooks || {};
+ let hookCount = 0;
+
+ for (const eventType of Object.keys(hooks)) {
+ if (Array.isArray(hooks[eventType])) {
+ hookCount += hooks[eventType].length;
+ }
+ }
+
+ return {
+ exists: true,
+ hasHooks: hookCount > 0,
+ hookCount,
+ path: settingsPath,
+ };
+ } catch {
+ return { exists: true, hasHooks: false, hookCount: 0, path: settingsPath };
+ }
+}
+
+function detectEnvironmentVariables(): {
+ paiDir?: string;
+ daName?: string;
+ timeZone?: string;
+ elevenLabsKey?: string;
+} {
+ return {
+ paiDir: process.env.PAI_DIR,
+ daName: process.env.DA,
+ timeZone: process.env.TIME_ZONE,
+ elevenLabsKey: process.env.ELEVENLABS_API_KEY,
+ };
+}
+
+// ============================================================================
+// Wizard Steps
+// ============================================================================
+
+async function showWelcome(): Promise<void> {
+ console.clear();
+ log('');
+ log(c('cyan', ' ╔═══════════════════════════════════════════════════════════╗'));
+ log(c('cyan', ' ║') + c('bold', ' PAI Kai Bundle Installation Wizard ') + c('cyan', '║'));
+ log(c('cyan', ' ╚═══════════════════════════════════════════════════════════╝'));
+ log('');
+ log(' Welcome! This wizard will guide you through installing the complete');
+ log(' Kai Personal AI Infrastructure bundle.');
+ log('');
+ log(' ' + c('bold', 'What you\'ll get:'));
+ log(' • Hook System - Event-driven automation foundation');
+ log(' • History System - Automatic memory and capture');
+ log(' • Skill System - Modular capability routing');
+ log(' • Voice System - Voice notifications (optional)');
+ log(' • Identity - Personality layer and CORE skill');
+ log('');
+ log(' ' + c('dim', 'Press Enter to continue or Ctrl+C to exit...'));
+ await prompt('');
+}
+
+async function gatherConfiguration(): Promise<WizardConfig> {
+ logSection('Configuration');
+
+ const config = { ...DEFAULT_CONFIG };
+ const existingEnv = detectEnvironmentVariables();
+
+ // PAI Directory
+ log(c('bold', 'PAI Directory'));
+ log(c('dim', 'Where should PAI store its files (hooks, history, skills)?'));
+ if (existingEnv.paiDir) {
+ logInfo(`Detected existing PAI_DIR: ${existingEnv.paiDir}`);
+ }
+ config.paiDir = await prompt('PAI directory', existingEnv.paiDir || DEFAULT_CONFIG.paiDir);
+ log('');
+
+ // AI Assistant Name
+ log(c('bold', 'AI Assistant Name'));
+ log(c('dim', 'What should your AI be called? (e.g., Kai, Atlas, Nova, Jarvis)'));
+ if (existingEnv.daName) {
+ logInfo(`Detected existing DA name: ${existingEnv.daName}`);
+ }
+ config.daName = await prompt('Assistant name', existingEnv.daName || DEFAULT_CONFIG.daName);
+ log('');
+
+ // Timezone
+ log(c('bold', 'Timezone'));
+ log(c('dim', 'Your timezone for accurate timestamps'));
+ const detectedTz = Intl.DateTimeFormat().resolvedOptions().timeZone;
+ config.timeZone = await prompt('Timezone', existingEnv.timeZone || detectedTz);
+ log('');
+
+ // Shell Profile
+ log(c('bold', 'Shell Profile'));
+ log(c('dim', 'Which shell profile should we add environment variables to?'));
+ const detectedProfile = detectShellProfile();
+ config.shellProfile = await prompt('Shell profile', detectedProfile);
+ log('');
+
+ // Voice System (Optional)
+ log(c('bold', 'Voice System (Optional)'));
+ log(c('dim', 'The voice system uses ElevenLabs for text-to-speech notifications.'));
+ log(c('dim', 'You can skip this and add it later.'));
+
+ const setupVoice = await promptYesNo('Configure voice system now?', false);
+
+ if (setupVoice) {
+ config.elevenLabsApiKey = await prompt('ElevenLabs API key', existingEnv.elevenLabsKey || '');
+ if (config.elevenLabsApiKey) {
+ config.elevenLabsVoiceId = await prompt('Voice ID', DEFAULT_CONFIG.elevenLabsVoiceId);
+ }
+ }
+ log('');
+
+ return config;
+}
+
+async function checkForConflicts(config: WizardConfig): Promise<{
+ hasConflicts: boolean;
+ paiDirConflict: boolean;
+ settingsConflict: boolean;
+ envConflict: boolean;
+ details: string[];
+}> {
+ logSection('Checking for Conflicts');
+
+ const details: string[] = [];
+ let hasConflicts = false;
+
+ // Check PAI directory
+ const paiStatus = detectExistingInstallation(config.paiDir);
+ const paiDirConflict = paiStatus.exists && (paiStatus.directories.length > 0 || paiStatus.files.length > 0);
+
+ if (paiDirConflict) {
+ hasConflicts = true;
+ logWarning(`Existing PAI installation found at ${config.paiDir}`);
+ details.push(`PAI directory has ${paiStatus.directories.length} directories and ${paiStatus.files.length} files`);
+ paiStatus.directories.forEach(d => details.push(` - ${d}/`));
+ } else if (paiStatus.exists) {
+ logSuccess('PAI directory exists but is empty');
+ } else {
+ logSuccess('PAI directory does not exist (will be created)');
+ }
+
+ // Check Claude settings
+ const claudeStatus = detectClaudeSettings();
+ const settingsConflict = claudeStatus.hasHooks;
+
+ if (settingsConflict) {
+ hasConflicts = true;
+ logWarning(`Existing hooks found in Claude settings (${claudeStatus.hookCount} hooks)`);
+ details.push(`Claude settings has ${claudeStatus.hookCount} existing hooks`);
+ } else if (claudeStatus.exists) {
+ logSuccess('Claude settings exists but has no hooks');
+ } else {
+ logSuccess('Claude settings does not exist (will be created)');
+ }
+
+ // Check environment variables
+ const envVars = detectEnvironmentVariables();
+ const envConflict = !!(envVars.paiDir || envVars.daName);
+
+ if (envConflict) {
+ logInfo('Existing environment variables detected (will update)');
+ if (envVars.paiDir) details.push(`PAI_DIR=${envVars.paiDir}`);
+ if (envVars.daName) details.push(`DA=${envVars.daName}`);
+ } else {
+ logSuccess('No existing PAI environment variables');
+ }
+
+ return { hasConflicts, paiDirConflict, settingsConflict, envConflict, details };
+}
+
+async function resolveConflicts(
+ config: WizardConfig,
+ conflicts: Awaited<ReturnType<typeof checkForConflicts>>
+): Promise<{
+ proceed: boolean;
+ mergeSettings: boolean;
+ backupExisting: boolean;
+}> {
+ if (!conflicts.hasConflicts) {
+ return { proceed: true, mergeSettings: false, backupExisting: false };
+ }
+
+ logSection('Conflict Resolution');
+
+ log('The installer found existing configurations that may conflict.');
+ log('');
+ conflicts.details.forEach(d => log(` ${c('dim', '•')} ${d}`));
+ log('');
+
+ const choiceIndex = await promptChoice('How would you like to proceed?', [
+ 'Merge - Add PAI hooks alongside existing hooks (recommended)',
+ 'Replace - Remove existing configuration and start fresh',
+ 'Cancel - Exit without making changes',
+ ], 0);
+
+ if (choiceIndex === 2) {
+ return { proceed: false, mergeSettings: false, backupExisting: false };
+ }
+
+ const mergeSettings = choiceIndex === 0;
+
+ let backupExisting = false;
+ if (conflicts.paiDirConflict || conflicts.settingsConflict) {
+ log('');
+ backupExisting = await promptYesNo('Create backup of existing files before proceeding?', true);
+ }
+
+ return { proceed: true, mergeSettings, backupExisting };
+}
+
+async function createBackup(config: WizardConfig): Promise<void> {
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
+ const backupDir = join(homedir(), '.pai-backup', timestamp);
+
+ logInfo(`Creating backup at ${backupDir}`);
+ mkdirSync(backupDir, { recursive: true });
+
+ // Backup PAI directory if exists
+ if (existsSync(config.paiDir)) {
+ await $`cp -r ${config.paiDir} ${join(backupDir, 'pai')}`.quiet();
+ logSuccess('Backed up PAI directory');
+ }
+
+ // Backup Claude settings if exists
+ const claudeSettings = join(homedir(), '.claude', 'settings.json');
+ if (existsSync(claudeSettings)) {
+ mkdirSync(join(backupDir, 'claude'), { recursive: true });
+ await $`cp ${claudeSettings} ${join(backupDir, 'claude', 'settings.json')}`.quiet();
+ logSuccess('Backed up Claude settings');
+ }
+}
+
+async function createDirectoryStructure(config: WizardConfig): Promise<void> {
+ logSection('Creating Directory Structure');
+
+ const directories = [
+ config.paiDir,
+ join(config.paiDir, 'hooks'),
+ join(config.paiDir, 'hooks', 'lib'),
+ join(config.paiDir, 'History'),
+ join(config.paiDir, 'History', 'Sessions'),
+ join(config.paiDir, 'History', 'Learnings'),
+ join(config.paiDir, 'History', 'Research'),
+ join(config.paiDir, 'History', 'Decisions'),
+ join(config.paiDir, 'Skills'),
+ join(config.paiDir, 'Skills', 'CORE'),
+ join(config.paiDir, 'Tools'),
+ join(config.paiDir, 'voice'),
+ ];
+
+ for (const dir of directories) {
+ if (!existsSync(dir)) {
+ mkdirSync(dir, { recursive: true });
+ logSuccess(`Created ${dir.replace(homedir(), '~')}`);
+ } else {
+ logInfo(`Exists: ${dir.replace(homedir(), '~')}`);
+ }
+ }
+}
+
+async function writeEnvironmentVariables(config: WizardConfig): Promise<void> {
+ logSection('Configuring Environment');
+
+ const envBlock = `
+# PAI Configuration (added by Kai Bundle installer)
+export PAI_DIR="${config.paiDir}"
+export DA="${config.daName}"
+export TIME_ZONE="${config.timeZone}"
+export PAI_SOURCE_APP="${config.daName}"
+${config.elevenLabsApiKey ? `export ELEVENLABS_API_KEY="${config.elevenLabsApiKey}"` : '# export ELEVENLABS_API_KEY="your-key-here"'}
+${config.elevenLabsVoiceId ? `export ELEVENLABS_VOICE_ID="${config.elevenLabsVoiceId}"` : ''}
+export PAI_OBSERVABILITY_URL="${config.observabilityUrl}"
+# End PAI Configuration
+`;
+
+ if (!existsSync(config.shellProfile)) {
+ writeFileSync(config.shellProfile, envBlock);
+ logSuccess(`Created ${config.shellProfile}`);
+ } else {
+ const existing = readFileSync(config.shellProfile, 'utf-8');
+
+ // Check if PAI config already exists
+ if (existing.includes('# PAI Configuration')) {
+ // Replace existing block
+ const updated = existing.replace(
+ /# PAI Configuration.*# End PAI Configuration\n?/s,
+ envBlock
+ );
+ writeFileSync(config.shellProfile, updated);
+ logSuccess(`Updated PAI configuration in ${config.shellProfile}`);
+ } else {
+ // Append new block
+ writeFileSync(config.shellProfile, existing + '\n' + envBlock);
+ logSuccess(`Added PAI configuration to ${config.shellProfile}`);
+ }
+ }
+
+ // Also write to ~/.env for tools that read from there
+ const envFile = join(homedir(), '.env');
+ const envContent = `# PAI Environment Variables
+PAI_DIR=${config.paiDir}
+DA=${config.daName}
+TIME_ZONE=${config.timeZone}
+${config.elevenLabsApiKey ? `ELEVENLABS_API_KEY=${config.elevenLabsApiKey}` : ''}
+${config.elevenLabsVoiceId ? `ELEVENLABS_VOICE_ID=${config.elevenLabsVoiceId}` : ''}
+`;
+
+ if (existsSync(envFile)) {
+ const existing = readFileSync(envFile, 'utf-8');
+ if (!existing.includes('PAI_DIR=')) {
+ writeFileSync(envFile, existing + '\n' + envContent);
+ logSuccess('Added PAI variables to ~/.env');
+ }
+ } else {
+ writeFileSync(envFile, envContent);
+ logSuccess('Created ~/.env with PAI variables');
+ }
+}
+
+function generatePackInstallPrompt(pack: PackInfo, config: WizardConfig): string {
+ return `You are receiving Pack ${pack.id} from the PAI Kai Bundle.
+
+INSTALLATION CONTEXT:
+- PAI_DIR: ${config.paiDir}
+- DA (AI Name): ${config.daName}
+- TIME_ZONE: ${config.timeZone}
+
+IMPORTANT: Replace all instances of $PAI_DIR with "${config.paiDir}" in the code files.
+Replace all instances of "PAI" with "${config.daName}" where it refers to the assistant name.
+
+Please read the Pack file and install it by:
+1. Creating all required files in their correct locations
+2. The files should use the configured PAI_DIR path: ${config.paiDir}
+3. Update settings.json with the required hooks (merge with existing if present)
+4. Run the verification steps to confirm installation
+
+Pack file location: ${resolve(dirname(import.meta.path), pack.file)}`;
+}
+
+async function showPackInstallInstructions(config: WizardConfig): Promise<void> {
+ logSection('Pack Installation');
+
+ log('The directory structure and environment are configured.');
+ log('');
+ log('Now you need to install each Pack. Give these prompts to your AI in order:');
+ log('');
+
+ for (let i = 0; i < PACKS.length; i++) {
+ const pack = PACKS[i];
+ log(c('bold', `${i + 1}. ${pack.name}`));
+ log(c('dim', ` ${pack.description}`));
+ log('');
+ log(c('cyan', ' Prompt to give your AI:'));
+ log('');
+ log(c('dim', ' ─────────────────────────────────────────────────────'));
+ log(` Install the ${pack.name} pack from:`);
+ log(` ${resolve(dirname(import.meta.path), pack.file)}`);
+ log('');
+ log(` Use PAI_DIR="${config.paiDir}" and DA="${config.daName}"`);
+ log(c('dim', ' ─────────────────────────────────────────────────────'));
+ log('');
+
+ if (i < PACKS.length - 1) {
+ log(c('yellow', ' ⚠ Verify this pack works before installing the next one!'));
+ log('');
+ }
+ }
+}
+
+async function showCompletion(config: WizardConfig): Promise<void> {
+ logSection('Setup Complete!');
+
+ log(c('green', '✓ Directory structure created'));
+ log(c('green', '✓ Environment variables configured'));
+ log('');
+ log(c('bold', 'Next Steps:'));
+ log('');
+ log(`1. ${c('cyan', 'Restart your terminal')} to load the new environment variables`);
+ log(' Or run: source ${config.shellProfile}');
+ log('');
+ log(`2. ${c('cyan', 'Install each Pack')} by giving your AI the Pack files in order:`);
+
+ for (let i = 0; i < PACKS.length; i++) {
+ const pack = PACKS[i];
+ log(` ${i + 1}. ${pack.name} - ${resolve(dirname(import.meta.path), pack.file)}`);
+ }
+
+ log('');
+ log(`3. ${c('cyan', 'Restart Claude Code')} after installing all packs to activate hooks`);
+ log('');
+ log(c('dim', '─'.repeat(60)));
+ log('');
+ log(`Your AI assistant ${c('bold', config.daName)} is being set up at:`);
+ log(` ${c('cyan', config.paiDir)}`);
+ log('');
+ log(c('dim', 'For help, see: https://github.com/danielmiessler/PAI'));
+ log('');
+}
+
+// ============================================================================
+// Main Entry Point
+// ============================================================================
+
+async function main(): Promise<void> {
+ try {
+ // Welcome
+ await showWelcome();
+
+ // Gather configuration
+ const config = await gatherConfiguration();
+
+ // Check for conflicts
+ const conflicts = await checkForConflicts(config);
+
+ // Resolve conflicts if any
+ const resolution = await resolveConflicts(config, conflicts);
+
+ if (!resolution.proceed) {
+ log('');
+ log(c('yellow', 'Installation cancelled. No changes were made.'));
+ process.exit(0);
+ }
+
+ // Create backup if requested
+ if (resolution.backupExisting) {
+ await createBackup(config);
+ }
+
+ // Create directory structure
+ await createDirectoryStructure(config);
+
+ // Write environment variables
+ await writeEnvironmentVariables(config);
+
+ // Show pack installation instructions
+ await showPackInstallInstructions(config);
+
+ // Show completion
+ await showCompletion(config);
+
+ } catch (error) {
+ if (error instanceof Error && error.message.includes('EOF')) {
+ log('');
+ log(c('yellow', 'Installation cancelled.'));
+ process.exit(0);
+ }
+ throw error;
+ }
+}
+
+// Run
+main().catch(console.error);
diff --git a/PAIPackTemplate.md b/PAIPackTemplate.md
index 037765ba..a12cecac 100644
--- a/PAIPackTemplate.md
+++ b/PAIPackTemplate.md
@@ -8,6 +8,58 @@ Each pack is a single flat markdown file with YAML frontmatter and structured se
---
+## 🔴 END-TO-END REQUIREMENT (MANDATORY)
+
+**Every pack MUST be end-to-end complete.** This is the most important requirement.
+
+### What End-to-End Means
+
+If your pack has a data flow, EVERY component in that flow must be included:
+
+```
+Hook → sends to → Server → calls → API → plays → Audio
+ ✅ ✅ ✅ ✅ ✅ ✅
+ ALL of these must be in the pack
+```
+
+### Anti-Patterns (NEVER DO THESE)
+
+| ❌ WRONG | ✅ RIGHT |
+|----------|----------|
+| "A full server implementation is beyond this pack's scope" | Include the complete server implementation |
+| "You can implement your own TTS provider" | Include the TTS integration code |
+| "See the skeleton pattern below" | Include production-ready code |
+| "Adapt to your preferred system" | Include the complete working system |
+| "The voice server is a required dependency" | Include the voice server |
+
+### The Chain Test
+
+Before publishing, trace every data flow:
+
+1. **Identify the chain**: What calls what? (Hook → Server → API → Output)
+2. **Check each link**: Is the code for this component in the pack?
+3. **Find the gaps**: Any "implement your own" or "beyond scope"?
+4. **Fill the gaps**: Add the missing components
+
+**If ANY link says "you implement this" or "beyond scope" - the pack is INCOMPLETE.**
+
+### Example: Voice System
+
+A voice system pack MUST include:
+
+| Component | What It Does | Included? |
+|-----------|--------------|-----------|
+| Stop hook | Extracts completion message | ✅ Required |
+| Prosody enhancer | Adds emotional markers | ✅ Required |
+| Voice server | HTTP server on port 8888 | ✅ Required |
+| ElevenLabs integration | Calls TTS API | ✅ Required |
+| Audio playback | Plays the audio | ✅ Required |
+| Server management | Start/stop/restart script | ✅ Required |
+
+**NOT:** "The voice server is beyond scope." That makes the pack useless.
+
+---
+
## Frontmatter (Metadata)
```yaml
@@ -365,6 +417,12 @@ This sounds similar to [ALTERNATIVE] which also does [CAPABILITY]. What makes th
INSTRUCTIONS FOR AI: Provide step-by-step installation instructions.
Include:
- Prerequisites (dependencies, API keys, system requirements)
+- PRE-INSTALLATION SYSTEM ANALYSIS (REQUIRED):
+ - Scripts to detect existing PAI installation
+ - Scripts to check for conflicting files/hooks
+ - Scripts to verify dependencies are installed
+ - Conflict Resolution Matrix table
+ - Backup instructions for existing files
- Numbered steps with clear actions
- All code needed (use fenced code blocks with language tags)
- Code languages: typescript (bun), bash, python (uv), json, html
@@ -374,6 +432,10 @@ Include:
Write for an AI assistant that will execute these steps. Be explicit about file
paths, commands to run, and expected outputs. Include ALL code - no snippets,
no "add more patterns here", no placeholders.
+
+The Pre-Installation section is CRITICAL - it ensures the AI understands the
+current system state before making changes. This prevents conflicts and allows
+for proper merge/replace/skip decisions.
-->
### Prerequisites
@@ -382,6 +444,112 @@ no "add more patterns here", no placeholders.
- **Claude Code** (or compatible agent system with hook support)
- **Write access** to `$PAI_DIR/` (or your PAI directory)
+---
+
+### Pre-Installation: System Analysis
+
+**IMPORTANT:** Before installing, analyze the current system state to detect conflicts and ensure dependencies are met.
+
+#### Step 0.1: Detect Current Configuration
+
+Run these commands to understand your current system:
+
+```bash
+# 1. Check if PAI_DIR is set
+echo "PAI_DIR: ${PAI_DIR:-'NOT SET - will use ~/.config/pai'}"
+
+# 2. Check for existing PAI directory
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+if [ -d "$PAI_CHECK" ]; then
+ echo "⚠️ PAI directory EXISTS at: $PAI_CHECK"
+ echo "Contents:"
+ ls -la "$PAI_CHECK" 2>/dev/null || echo " (empty or inaccessible)"
+else
+ echo "✓ PAI directory does not exist (clean install)"
+fi
+
+# 3. Check for existing files that this pack will create
+# TODO: Add pack-specific file checks here
+echo ""
+echo "Checking for files this pack will create..."
+# if [ -f "$PAI_CHECK/path/to/file" ]; then
+# echo "⚠️ file.ts already exists"
+# fi
+
+# 4. Check Claude settings for existing hooks
+CLAUDE_SETTINGS="$HOME/.claude/settings.json"
+if [ -f "$CLAUDE_SETTINGS" ]; then
+ echo "Claude settings.json EXISTS"
+ if grep -q '"hooks"' "$CLAUDE_SETTINGS" 2>/dev/null; then
+ echo "⚠️ Existing hooks configuration found"
+ else
+ echo "✓ No hooks configured in settings.json"
+ fi
+else
+ echo "✓ No Claude settings.json (will be created)"
+fi
+
+# 5. Check environment variables
+echo ""
+echo "Environment variables:"
+echo " DA: ${DA:-'NOT SET'}"
+echo " TIME_ZONE: ${TIME_ZONE:-'NOT SET'}"
+echo " PAI_DIR: ${PAI_DIR:-'NOT SET'}"
+```
+
+#### Step 0.2: Verify Dependencies
+
+```bash
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+
+# Check for required packs (customize for your pack)
+# Example: Check if hook system is installed
+if [ -f "$PAI_CHECK/hooks/lib/observability.ts" ]; then
+ echo "✓ kai-hook-system is installed"
+else
+ echo "⚠️ kai-hook-system not installed (may be required)"
+fi
+
+# Add checks for other dependencies your pack needs
+```
+
+#### Step 0.3: Conflict Resolution Matrix
+
+Based on the detection above, follow the appropriate path:
+
+| Scenario | Existing State | Action |
+|----------|---------------|--------|
+| **Clean Install** | No PAI_DIR, no conflicts | Proceed normally with Step 1 |
+| **Directory Exists** | PAI_DIR has files | Review files, backup if needed, then proceed |
+| **Files Exist** | Pack files already present | Backup old files, compare versions, then replace |
+| **Hooks Exist** | Claude settings has hooks | **MERGE** - add new hooks to existing array |
+| **Missing Dependencies** | Required packs missing | Install dependencies first |
+
+#### Step 0.4: Backup Existing Configuration (If Needed)
+
+If conflicts were detected, create a backup before proceeding:
+
+```bash
+# Create timestamped backup
+BACKUP_DIR="$HOME/.pai-backup/$(date +%Y%m%d-%H%M%S)"
+mkdir -p "$BACKUP_DIR"
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+
+# Backup files this pack will modify
+# TODO: Add pack-specific backup commands
+# Example:
+# if [ -d "$PAI_CHECK/history" ]; then
+# cp -r "$PAI_CHECK/history" "$BACKUP_DIR/history"
+# echo "✓ Backed up history directory"
+# fi
+
+echo "Backup location: $BACKUP_DIR"
+```
+
+**After completing system analysis, proceed to Step 1.**
+
+---
+
### Step 1: Create Directory Structure
```bash
@@ -830,6 +998,13 @@ Format: ### {version} - {YYYY-MM-DD}
> **FOR AI AGENTS:** Before publishing, verify your pack includes ALL of these:
+### End-to-End Chain (MOST IMPORTANT)
+- [ ] **Chain test passed**: Traced every data flow - no "implement your own" gaps
+- [ ] **Server included**: If pack needs a server, full server code is in the pack
+- [ ] **Server management**: Start/stop/restart scripts included (if server required)
+- [ ] **No "beyond scope"**: Every component mentioned is fully implemented
+
+### Standard Requirements
- [ ] **Why Different**: 64-word paragraph + 4 eight-word bullets
- [ ] **Full context**: What, why, who needs it
- [ ] **All code**: Complete, working implementations (no snippets, no placeholders)
@@ -844,6 +1019,8 @@ Format: ### {version} - {YYYY-MM-DD}
**The test:** Can someone go from fresh Claude Code to fully working system using ONLY this pack?
+**The chain test:** Trace every data flow. If ANY link is missing, the pack is incomplete.
+
---
## File Naming Convention
diff --git a/Packs/README.md b/Packs/README.md
index b037226c..db5fe67e 100644
--- a/Packs/README.md
+++ b/Packs/README.md
@@ -1,5 +1,5 @@
<p align="center">
- <img src="icons/packs.png" alt="PAI Packs" width="256">
+ <img src="icons/packs-v2.png" alt="PAI Packs" width="256">
</p>
# PAI Packs
diff --git a/Packs/icons/packs.png b/Packs/icons/packs-v2.png
similarity index 100%
rename from Packs/icons/packs.png
rename to Packs/icons/packs-v2.png
diff --git a/README.md b/README.md
index bc3c160b..d96aa184 100644
--- a/README.md
+++ b/README.md
@@ -200,7 +200,7 @@ The packs are extracted from Kai - real capabilities that have been running in p
| Bundle | Description | Packs | Tier |
|--------|-------------|-------|------|
-| [**Kai Bundle**](Bundles/Kai/) | The official PAI bundle - complete personal AI infrastructure extracted from Daniel Miessler's production system | 15 | Complete |
+| [**Kai Bundle**](Bundles/Kai/) | The official PAI bundle - complete personal AI infrastructure extracted from Daniel Miessler's production system | 5 | Complete |
### Why Bundles?
@@ -208,9 +208,15 @@ The packs are extracted from Kai - real capabilities that have been running in p
- **Proper installation order** - Dependencies handled correctly
- **Emergent capabilities** - The whole is greater than the sum of parts
- **Complete experience** - Everything needed for a specific goal
+- **Interactive wizard** - Guided setup with conflict detection
**The Kai Bundle** is the flagship bundle. Installing all its packs recreates the PAI v1.0 "mirrored system" experience - but through modular, maintainable packs instead of a monolithic copy.
+**Quick install:**
+```bash
+cd ~/Projects/PAI/Bundles/Kai && bun run install.ts
+```
+
[**Learn more about bundles →**](Bundles/)
---
@@ -219,15 +225,37 @@ The packs are extracted from Kai - real capabilities that have been running in p
> **FOR AI AGENTS:** The entire PAI system is designed to be used by AI. You can read this README to understand how PAI works with its Packs and Bundles. A recommended approach: evaluate the entire system, then interact with your principal and ask them which Bundles or Packs they'd like to install—give them options based on their needs. From there, you should be able to read any Bundle or Pack file (including new ones as they're released) and guide your principal on whether they want to install it.
-### Option 1: AI-Assisted Installation (Recommended)
+### Option 1: Install the Complete Kai Bundle (Recommended)
+
+The fastest way to get started is with the interactive bundle wizard:
+
+```bash
+# Clone the repo
+git clone https://github.com/danielmiessler/PAI.git
+cd PAI/Bundles/Kai
+
+# Run the interactive wizard
+bun run install.ts
+```
+
+**The wizard will:**
+- Ask for your preferences (AI name, install location, timezone)
+- Detect any existing installations and offer to merge or replace
+- Create the required directory structure
+- Configure environment variables
+- Guide you through installing each pack in order
+
+### Option 2: AI-Assisted Pack Installation
+
+Install individual packs by giving them to your AI:
1. **Browse packs** - Find a pack you want in [Packs/](Packs/)
2. **Give it to your AI** - Provide the entire pack markdown file
3. **Ask your AI to install it:**
```
-Install the History System pack into my system. Set up the hooks,
-save the code, verify dependencies, and test it works.
+Install this pack into my system. Use PAI_DIR="~/.config/pai"
+and DA="MyAI". Set up the hooks, save the code, and verify it works.
```
Your AI will:
@@ -237,11 +265,11 @@ Your AI will:
- Validate the installation
- Run a test to ensure it works
-### Option 2: Manual Installation
+### Option 3: Manual Installation
Each pack includes detailed manual installation instructions. Open the pack file and follow the "Installation → Manual" section.
-### Option 3: Browse and Cherry-Pick
+### Option 4: Browse and Cherry-Pick
Packs are self-contained markdown files. You can:
- Read the code directly in the pack