Skip to content

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

Add automatic PAI context loading system

Daniel Miesslerd9e97bd860d0
diff --git a/README.md b/README.md
index ae99aaf1..76caf00b 100644
--- a/README.md
+++ b/README.md
@@ -31,6 +31,17 @@
> **✨ v0.5.0 NEW:** Skills-based PAI architecture with 92.5% token reduction! Core identity now in skill description, zero hook overhead. [See details below →](#-recent-updates)
+<details>
+<summary><strong>📅 2025-10-19 - Automated Documentation Update</strong></summary>
+
+- **Hooks:** 2 new, 1 removed
+- **Settings:** 1 updated
+
+*Updated by pre-commit hook: 3 added, 1 modified, 1 deleted*
+
+</details>
+
+
<details>
<summary><strong>📅 2025-10-19 - Automated Documentation Update</strong></summary>
diff --git a/documentation/hook-system.md b/documentation/hook-system.md
index 4a57717c..ef1c35a9 100644
--- a/documentation/hook-system.md
+++ b/documentation/hook-system.md
@@ -447,5 +447,15 @@ done
*Hook System Version 1.0.0*
*Last Updated: [Current Date]*
+
+## Recent Changes (2025-10-19)
+
+- ➕ `hooks/initialize-pai-session.ts` (added)
+ - +130 / -0 lines
+- ➕ `hooks/load-core-context.ts` (added)
+ - +88 / -0 lines
+- 🗑️ `hooks/session-start-hook.ts` (deleted)
+ - +0 / -86 lines
+
---
-<!-- Last Updated: 2025-10-18 -->
+<!-- Last Updated: 2025-10-19 -->
diff --git a/documentation/pai-context-loading.md b/documentation/pai-context-loading.md
new file mode 100644
index 00000000..70291f38
--- /dev/null
+++ b/documentation/pai-context-loading.md
@@ -0,0 +1,353 @@
+# PAI Context Loading System
+
+## Overview
+
+The PAI context loading system automatically injects your personal AI context from the `skills/PAI/SKILL.md` file into every Claude Code session at startup. This ensures your AI has immediate access to your preferences, contacts, security guidelines, and custom instructions without requiring manual skill activation.
+
+## How It Works
+
+PAI uses a **two-hook session initialization system**:
+
+### 1. Context Loading (`load-core-context.ts`)
+**Runs FIRST** - Loads your PAI skill context into the session
+
+- Reads `~/.claude/skills/PAI/SKILL.md`
+- Injects content as a `<system-reminder>` into Claude's context
+- Makes your complete PAI configuration immediately available
+- Skips execution for subagent sessions (they don't need PAI context)
+
+### 2. Session Initialization (`initialize-pai-session.ts`)
+**Runs SECOND** - Sets up your session environment
+
+- Tests stop-hook configuration
+- Sets terminal tab title (e.g., "Kai Ready")
+- Sends voice notification if voice server is running
+- Skips for subagent sessions
+
+## Architecture Benefits
+
+### Automatic Context Loading
+Before this system, you had to manually activate the PAI skill in each session. Now your AI has your complete context from the first message.
+
+### Modular Design
+Separating context loading from session setup provides:
+- **Easier maintenance** - Each hook has a single responsibility
+- **Better debugging** - Issues with context vs session setup are isolated
+- **Flexibility** - You can disable voice notifications while keeping context loading
+
+### Subagent Awareness
+Both hooks detect subagent sessions and skip unnecessary operations:
+- Subagents don't need PAI context (they have their own specialized instructions)
+- Subagents don't need voice notifications or tab title updates
+- Reduces overhead and prevents duplicate notifications
+
+## Configuration
+
+### Settings.json
+
+The hooks are configured in your `settings.json` SessionStart section:
+
+```json
+{
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "${PAI_DIR}/hooks/load-core-context.ts"
+ },
+ {
+ "type": "command",
+ "command": "${PAI_DIR}/hooks/initialize-pai-session.ts"
+ }
+ ]
+ }
+ ]
+ }
+}
+```
+
+**Order matters!** `load-core-context.ts` must run before `initialize-pai-session.ts`.
+
+### Environment Variables
+
+Set these in your `settings.json` `env` section:
+
+```json
+{
+ "env": {
+ "DA": "Kai", // Your AI's name (used in tab titles and notifications)
+ "DA_VOICE_ID": "your-voice-id", // ElevenLabs voice ID (optional, for voice notifications)
+ "PAI_DIR": "$HOME/.claude" // Path to your PAI directory
+ }
+}
+```
+
+## File Structure
+
+```
+~/.claude/
+├── skills/
+│ └── PAI/
+│ └── SKILL.md ← Your customized PAI context
+├── hooks/
+│ ├── load-core-context.ts ← Context loading hook
+│ └── initialize-pai-session.ts ← Session initialization hook
+└── settings.json ← Hook configuration
+```
+
+## Customizing Your PAI Context
+
+### Edit skills/PAI/SKILL.md
+
+This file contains your complete AI context. Customize these sections:
+
+1. **Core Identity**
+ - AI name and personality
+ - Operating environment preferences
+
+2. **Stack Preferences**
+ - Preferred languages (TypeScript, Python, etc.)
+ - Package managers (bun, npm, uv, pip)
+ - Frameworks and tools
+
+3. **Response Format**
+ - How you want responses structured
+ - Use emojis or plain text
+ - Verbosity level
+
+4. **Key Contacts**
+ - People you reference frequently
+ - Email addresses for quick lookup
+
+5. **Security Guidelines**
+ - Repository safety rules
+ - Sensitive file patterns to avoid
+ - Infrastructure caution
+
+6. **Social Media Accounts**
+ - Your online presence
+ - Account handles and URLs
+
+7. **Voice IDs** (Optional)
+ - ElevenLabs voice assignments for agents
+ - Only needed if using voice system
+
+### Template Files
+
+The `skills/PAI/` directory includes template files for organization:
+- `contacts.md` - Contact list template
+- `preferences.md` - Stack and tool preferences template
+- `response-format.md` - Response formatting template
+- `security-detailed.md` - Security guidelines template
+- `voice-ids.md` - Voice ID assignments template
+
+These are **templates for reference only**. The actual context loaded comes from `SKILL.md`.
+
+## How Context Loading Works (Technical)
+
+### 1. Hook Execution
+When you start a Claude Code session, `settings.json` SessionStart hooks execute in order.
+
+### 2. Subagent Detection
+```typescript
+const isSubagent = claudeProjectDir.includes('/.claude/agents/') ||
+ process.env.CLAUDE_AGENT_TYPE !== undefined;
+```
+
+If subagent detected, hook exits silently (subagents don't need PAI context).
+
+### 3. File Reading
+```typescript
+const paiDir = process.env.PAI_DIR || join(homedir(), '.claude');
+const paiSkillPath = join(paiDir, 'skills/PAI/SKILL.md');
+const paiContent = readFileSync(paiSkillPath, 'utf-8');
+```
+
+### 4. Context Injection
+```typescript
+const message = `<system-reminder>
+PAI CORE CONTEXT (Auto-loaded at Session Start)
+
+The following context has been loaded from ${paiSkillPath}:
+
+---
+${paiContent}
+---
+
+This context is now active for this session.
+</system-reminder>`;
+
+console.log(message); // Output to stdout (captured by Claude Code)
+```
+
+Claude Code captures this output and injects it into the conversation context as a system reminder, making it immediately available to Claude.
+
+### 5. Success Logging
+```
+📚 Reading PAI core context from skill file...
+✅ Read 12847 characters from PAI SKILL.md
+✅ PAI context injected into session
+```
+
+## Troubleshooting
+
+### PAI Context Not Loading
+
+**Problem**: AI doesn't seem to have your PAI context
+
+**Check**:
+1. Verify `skills/PAI/SKILL.md` exists
+2. Check `settings.json` has `load-core-context.ts` in SessionStart hooks
+3. Look for errors in session startup output
+4. Ensure `PAI_DIR` environment variable is set correctly
+
+### Hook Not Executing
+
+**Problem**: No "Reading PAI core context" message at session start
+
+**Check**:
+1. Hook file is executable: `chmod +x hooks/load-core-context.ts`
+2. Hook is in correct location: `${PAI_DIR}/hooks/load-core-context.ts`
+3. Bun is installed and accessible
+4. SessionStart hooks are properly configured in settings.json
+
+### Wrong Context Loaded
+
+**Problem**: AI seems to have old or incorrect context
+
+**Check**:
+1. Edit `skills/PAI/SKILL.md` and save changes
+2. Restart Claude Code session
+3. Verify changes are in SKILL.md (not template files)
+4. Check for multiple PAI installations
+
+## Migration from Old System
+
+### Before (Manual Skill Activation)
+```
+User: /PAI
+Assistant: [Loads PAI skill context]
+User: [Actual task]
+```
+
+### After (Automatic Context Loading)
+```
+[Session starts - PAI context automatically loaded]
+User: [Actual task - AI already has context]
+```
+
+### Steps to Migrate
+
+1. **Install new hooks**:
+ ```bash
+ chmod +x hooks/load-core-context.ts
+ chmod +x hooks/initialize-pai-session.ts
+ ```
+
+2. **Update settings.json**:
+ Replace:
+ ```json
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "${PAI_DIR}/hooks/session-start-hook.ts"
+ }
+ ]
+ }
+ ]
+ ```
+
+ With:
+ ```json
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "${PAI_DIR}/hooks/load-core-context.ts"
+ },
+ {
+ "type": "command",
+ "command": "${PAI_DIR}/hooks/initialize-pai-session.ts"
+ }
+ ]
+ }
+ ]
+ ```
+
+3. **Customize SKILL.md**:
+ Edit `skills/PAI/SKILL.md` with your personal context
+
+4. **Test**:
+ Start a new Claude Code session and verify PAI context loads
+
+5. **Remove old hook** (optional):
+ ```bash
+ rm hooks/session-start-hook.ts
+ ```
+
+## Best Practices
+
+### Keep SKILL.md Updated
+Your AI is only as good as the context you provide. Regularly update:
+- New contacts and their roles
+- Changed stack preferences
+- Security guidelines for new projects
+- Updated social media accounts
+
+### Use Environment Variables
+Don't hardcode paths or API keys. Use `settings.json` env section:
+```json
+{
+ "env": {
+ "PAI_DIR": "$HOME/.claude",
+ "DA": "YourAIName",
+ "DA_VOICE_ID": "your-voice-id"
+ }
+}
+```
+
+### Test After Changes
+After editing SKILL.md, restart a session and verify:
+1. Hook executes without errors
+2. AI responds according to new preferences
+3. New context is accessible
+
+### Version Control
+Keep your PAI configuration in git:
+```bash
+git add skills/PAI/SKILL.md
+git commit -m "Update PAI context with new preferences"
+```
+
+But **NEVER commit sensitive data** like:
+- Real contact email addresses
+- API keys or credentials
+- Personal/private information
+- Company-specific data
+
+For public repos, use generic placeholders.
+
+## Related Documentation
+
+- [Skills System](skills-system.md) - Overview of the PAI skills architecture
+- [Hook System](hook-system.md) - Complete hook system documentation
+- [Voice System](voice-system.md) - Voice notification setup
+- [Quick Reference](QUICK-REFERENCE.md) - Fast reference for common tasks
+
+## Summary
+
+The PAI context loading system provides:
+
+✅ **Automatic context injection** - No manual skill activation needed
+✅ **Modular architecture** - Separate context loading from session setup
+✅ **Subagent awareness** - Skips unnecessary operations for subagents
+✅ **Easy customization** - Edit SKILL.md to update your AI's context
+✅ **Voice integration** - Optional voice notifications at session start
+✅ **Flexible configuration** - Environment variables for portability
+
+Your AI now has your complete personal context from the moment each session starts.
diff --git a/hooks/initialize-pai-session.ts b/hooks/initialize-pai-session.ts
new file mode 100755
index 00000000..97efd07b
--- /dev/null
+++ b/hooks/initialize-pai-session.ts
@@ -0,0 +1,130 @@
+#!/usr/bin/env bun
+
+/**
+ * initialize-pai-session.ts
+ *
+ * Main PAI session initialization hook that runs at the start of every Claude Code session.
+ *
+ * What it does:
+ * - Checks if this is a subagent session (skips for subagents)
+ * - Tests that stop-hook is properly configured
+ * - Sets initial terminal tab title
+ * - Sends voice notification that system is ready (if voice server is running)
+ * - Calls load-core-context.ts to inject PAI context into the session
+ *
+ * Setup:
+ * 1. Set environment variables in settings.json:
+ * - DA: Your AI's name (e.g., "Kai", "Nova", "Assistant")
+ * - DA_VOICE_ID: Your ElevenLabs voice ID (if using voice system)
+ * - PAI_DIR: Path to your PAI directory (defaults to $HOME/.claude)
+ * 2. Ensure load-core-context.ts exists in hooks/ directory
+ * 3. Add both hooks to SessionStart in settings.json
+ */
+
+import { existsSync, statSync } from 'fs';
+import { homedir } from 'os';
+import { join } from 'path';
+
+async function sendNotification(title: string, message: string, priority: string = 'normal') {
+ try {
+ // Get voice ID from environment variable (customize in settings.json)
+ const voiceId = process.env.DA_VOICE_ID || 'default-voice-id';
+
+ const response = await fetch('http://localhost:8888/notify', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ title,
+ message,
+ voice_enabled: true,
+ priority,
+ voice_id: voiceId
+ }),
+ });
+
+ if (!response.ok) {
+ console.error(`Notification failed: ${response.status}`);
+ }
+ } catch (error) {
+ // Silently fail if voice server isn't running
+ // console.error('Failed to send notification:', error);
+ }
+}
+
+async function testStopHook() {
+ const paiDir = process.env.PAI_DIR || join(homedir(), '.claude');
+ const stopHookPath = join(paiDir, 'hooks/stop-hook.ts');
+
+ console.error('\n🔍 Testing stop-hook configuration...');
+
+ // Check if stop-hook exists
+ if (!existsSync(stopHookPath)) {
+ console.error('❌ Stop-hook NOT FOUND at:', stopHookPath);
+ return false;
+ }
+
+ // Check if stop-hook is executable
+ try {
+ const stats = statSync(stopHookPath);
+ const isExecutable = (stats.mode & 0o111) !== 0;
+
+ if (!isExecutable) {
+ console.error('❌ Stop-hook exists but is NOT EXECUTABLE');
+ return false;
+ }
+
+ console.error('✅ Stop-hook found and is executable');
+
+ // Set initial tab title (customize with your AI's name via DA env var)
+ const daName = process.env.DA || 'AI Assistant';
+ const tabTitle = `${daName} Ready`;
+
+ process.stderr.write(`\x1b]0;${tabTitle}\x07`);
+ process.stderr.write(`\x1b]2;${tabTitle}\x07`);
+ process.stderr.write(`\x1b]30;${tabTitle}\x07`);
+ console.error(`📍 Set initial tab title: "${tabTitle}"`);
+
+ return true;
+ } catch (e) {
+ console.error('❌ Error checking stop-hook:', e);
+ return false;
+ }
+}
+
+async function main() {
+ try {
+ // Check if this is a subagent session - if so, exit silently
+ const claudeProjectDir = process.env.CLAUDE_PROJECT_DIR || '';
+ const isSubagent = claudeProjectDir.includes('/.claude/agents/') ||
+ process.env.CLAUDE_AGENT_TYPE !== undefined;
+
+ if (isSubagent) {
+ // This is a subagent session - exit silently without notification
+ console.error('🤖 Subagent session detected - skipping session initialization');
+ process.exit(0);
+ }
+
+ // Test stop-hook first (only for main sessions)
+ const stopHookOk = await testStopHook();
+
+ const daName = process.env.DA || 'AI Assistant';
+ const message = `${daName} here, ready to go.`;
+
+ if (!stopHookOk) {
+ console.error('\n⚠️ STOP-HOOK ISSUE DETECTED - Tab titles may not update automatically');
+ }
+
+ // Note: PAI core context loading is handled by load-core-context.ts hook
+ // which should run BEFORE this hook in settings.json SessionStart hooks
+
+ await sendNotification(`${daName} Systems Initialized`, message, 'low');
+ process.exit(0);
+ } catch (error) {
+ console.error('SessionStart hook error:', error);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/hooks/load-core-context.ts b/hooks/load-core-context.ts
new file mode 100755
index 00000000..b987eb01
--- /dev/null
+++ b/hooks/load-core-context.ts
@@ -0,0 +1,88 @@
+#!/usr/bin/env bun
+
+/**
+ * load-core-context.ts
+ *
+ * Automatically loads your PAI skill context at session start by reading and injecting
+ * the PAI SKILL.md file contents directly into Claude's context as a system-reminder.
+ *
+ * Purpose:
+ * - Read PAI SKILL.md file content
+ * - Output content as system-reminder for Claude to process
+ * - Ensure complete context (contacts, preferences, security, identity) available at session start
+ * - Bypass skill activation logic by directly injecting context
+ *
+ * Setup:
+ * 1. Customize your ~/.claude/skills/PAI/SKILL.md with your personal context
+ * 2. Add this hook to settings.json SessionStart hooks
+ * 3. Ensure PAI_DIR environment variable is set (defaults to $HOME/.claude)
+ *
+ * How it works:
+ * - Runs at the start of every Claude Code session
+ * - Skips execution for subagent sessions (they don't need PAI context)
+ * - Reads your PAI SKILL.md file
+ * - Injects content as <system-reminder> which Claude processes automatically
+ * - Gives your AI immediate access to your complete personal context
+ */
+
+import { readFileSync, existsSync } from 'fs';
+import { join } from 'path';
+import { homedir } from 'os';
+
+async function main() {
+ try {
+ // Check if this is a subagent session - if so, exit silently
+ const claudeProjectDir = process.env.CLAUDE_PROJECT_DIR || '';
+ const isSubagent = claudeProjectDir.includes('/.claude/agents/') ||
+ process.env.CLAUDE_AGENT_TYPE !== undefined;
+
+ if (isSubagent) {
+ // Subagent sessions don't need PAI context loading
+ console.error('🤖 Subagent session - skipping PAI context loading');
+ process.exit(0);
+ }
+
+ // Get PAI directory from environment or use default
+ const paiDir = process.env.PAI_DIR || join(homedir(), '.claude');
+ const paiSkillPath = join(paiDir, 'skills/PAI/SKILL.md');
+
+ // Verify PAI skill file exists
+ if (!existsSync(paiSkillPath)) {
+ console.error(`❌ PAI skill not found at: ${paiSkillPath}`);
+ console.error(`💡 Create your PAI skill file or check PAI_DIR environment variable`);
+ process.exit(1);
+ }
+
+ console.error('📚 Reading PAI core context from skill file...');
+
+ // Read the PAI SKILL.md file content
+ const paiContent = readFileSync(paiSkillPath, 'utf-8');
+
+ console.error(`✅ Read ${paiContent.length} characters from PAI SKILL.md`);
+
+ // Output the PAI content as a system-reminder
+ // This will be injected into Claude's context at session start
+ const message = `<system-reminder>
+PAI CORE CONTEXT (Auto-loaded at Session Start)
+
+The following context has been loaded from ${paiSkillPath}:
+
+---
+${paiContent}
+---
+
+This context is now active for this session. Follow all instructions, preferences, and guidelines contained above.
+</system-reminder>`;
+
+ // Write to stdout (will be captured by Claude Code)
+ console.log(message);
+
+ console.error('✅ PAI context injected into session');
+ process.exit(0);
+ } catch (error) {
+ console.error('❌ Error in load-core-context hook:', error);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/hooks/session-start-hook.ts b/hooks/session-start-hook.ts
deleted file mode 100755
index ae431cb5..00000000
--- a/hooks/session-start-hook.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/env bun
-
-import { existsSync, statSync } from 'fs';
-
-async function sendNotification(title: string, message: string, priority: string = 'normal') {
- try {
- const response = await fetch('http://localhost:8888/notify', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- title,
- message,
- voice_enabled: true,
- priority,
- voice_id: 'jqcCZkN6Knx8BJ5TBdYR' // Assistant's voice ID
- }),
- });
-
- if (!response.ok) {
- console.error(`Notification failed: ${response.status}`);
- }
- } catch (error) {
- console.error('Failed to send notification:', error);
- }
-}
-
-async function testStopHook() {
- const paiDir = process.env.PAI_DIR || `${process.env.HOME}/PAI/PAI_DIRECTORY`;
- const stopHookPath = `${paiDir}/hooks/stop-hook.ts`;
-
- console.error('\n🔍 Testing stop-hook configuration...');
-
- // Check if stop-hook exists
- if (!existsSync(stopHookPath)) {
- console.error('❌ Stop-hook NOT FOUND at:', stopHookPath);
- return false;
- }
-
- // Check if stop-hook is executable
- try {
- const stats = statSync(stopHookPath);
- const isExecutable = (stats.mode & 0o111) !== 0;
-
- if (!isExecutable) {
- console.error('❌ Stop-hook exists but is NOT EXECUTABLE');
- return false;
- }
-
- console.error('✅ Stop-hook found and is executable');
-
- // Set initial tab title to show session started with Kai ready
- process.stderr.write('\x1b]0;Kai Ready\x07');
- process.stderr.write('\x1b]2;Kai Ready\x07');
- process.stderr.write('\x1b]30;Kai Ready\x07');
- console.error('📍 Set initial tab title: "Kai Ready"');
-
- return true;
- } catch (e) {
- console.error('❌ Error checking stop-hook:', e);
- return false;
- }
-}
-
-async function main() {
- try {
- // Test stop-hook first
- const stopHookOk = await testStopHook();
-
- const daName = process.env.DA || 'Kai';
- const message = `${daName} here, ready to go.`;
-
- if (!stopHookOk) {
- console.error('\n⚠️ STOP-HOOK ISSUE DETECTED - Tab titles may not update automatically');
- }
-
- await sendNotification(`${daName} Systems Initialized`, message, 'low');
- process.exit(0);
- } catch (error) {
- console.error('SessionStart hook error:', error);
- process.exit(1);
- }
-}
-
-main();
\ No newline at end of file
diff --git a/settings.json b/settings.json
index 3892e756..6e20494f 100644
--- a/settings.json
+++ b/settings.json
@@ -173,7 +173,11 @@
"hooks": [
{
"type": "command",
- "command": "${PAI_DIR}/hooks/session-start-hook.ts"
+ "command": "${PAI_DIR}/hooks/load-core-context.ts"
+ },
+ {
+ "type": "command",
+ "command": "${PAI_DIR}/hooks/initialize-pai-session.ts"
}
]
}