⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
feat(hooks): add comprehensive event capture system with updated settings
Daniel Miessler857790cfda55
diff --git a/.claude/hooks/capture-all-events.ts b/.claude/hooks/capture-all-events.tsnew file mode 100755index 00000000..4471646d--- /dev/null+++ b/.claude/hooks/capture-all-events.ts@@ -0,0 +1,174 @@+#!/usr/bin/env bun+/**+ * Capture All Events Hook+ * Captures ALL Claude Code hook events (not just tools) to JSONL+ * This replaces the Python send_event.py hook+ * Enhanced with agent instance metadata extraction+ */++import { readFileSync, appendFileSync, mkdirSync, existsSync, writeFileSync } from 'fs';+import { join } from 'path';+import { homedir } from 'os';+import { enrichEventWithAgentMetadata, isAgentSpawningCall } from './lib/metadata-extraction';++interface HookEvent {+ source_app: string;+ session_id: string;+ hook_event_type: string;+ payload: Record<string, any>;+ timestamp: number;+ timestamp_pst: string;+}++// Get PST timestamp+function getPSTTimestamp(): string {+ const date = new Date();+ const pstDate = new Date(date.toLocaleString('en-US', { timeZone: 'America/Los_Angeles' }));++ const year = pstDate.getFullYear();+ const month = String(pstDate.getMonth() + 1).padStart(2, '0');+ const day = String(pstDate.getDate()).padStart(2, '0');+ const hours = String(pstDate.getHours()).padStart(2, '0');+ const minutes = String(pstDate.getMinutes()).padStart(2, '0');+ const seconds = String(pstDate.getSeconds()).padStart(2, '0');++ return `${year}-${month}-${day} ${hours}:${minutes}:${seconds} PST`;+}++// Get current events file path+function getEventsFilePath(): string {+ const paiDir = join(homedir(), '.claude');+ const now = new Date();+ const pstDate = new Date(now.toLocaleString('en-US', { timeZone: 'America/Los_Angeles' }));+ const year = pstDate.getFullYear();+ const month = String(pstDate.getMonth() + 1).padStart(2, '0');+ const day = String(pstDate.getDate()).padStart(2, '0');++ const monthDir = join(paiDir, 'history', 'raw-outputs', `${year}-${month}`);++ // Ensure directory exists+ if (!existsSync(monthDir)) {+ mkdirSync(monthDir, { recursive: true });+ }++ return join(monthDir, `${year}-${month}-${day}_all-events.jsonl`);+}++// Session-to-agent mapping functions+function getSessionMappingFile(): string {+ return join(homedir(), '.claude', 'agent-sessions.json');+}++function getAgentForSession(sessionId: string): string {+ try {+ const mappingFile = getSessionMappingFile();+ if (existsSync(mappingFile)) {+ const mappings = JSON.parse(readFileSync(mappingFile, 'utf-8'));+ return mappings[sessionId] || 'pai';+ }+ } catch (error) {+ // Ignore errors, default to pai+ }+ return 'pai';+}++function setAgentForSession(sessionId: string, agentName: string): void {+ try {+ const mappingFile = getSessionMappingFile();+ let mappings: Record<string, string> = {};++ if (existsSync(mappingFile)) {+ mappings = JSON.parse(readFileSync(mappingFile, 'utf-8'));+ }++ mappings[sessionId] = agentName;+ writeFileSync(mappingFile, JSON.stringify(mappings, null, 2), 'utf-8');+ } catch (error) {+ // Silently fail - don't block+ }+}++async function main() {+ try {+ // Get event type from command line args+ const args = process.argv.slice(2);+ const eventTypeIndex = args.indexOf('--event-type');++ if (eventTypeIndex === -1) {+ console.error('Missing --event-type argument');+ process.exit(0); // Don't block Claude Code+ }++ const eventType = args[eventTypeIndex + 1];++ // Read hook data from stdin+ const stdinData = await Bun.stdin.text();+ const hookData = JSON.parse(stdinData);++ // Detect agent type from session mapping or payload+ const sessionId = hookData.session_id || 'main';+ let agentName = getAgentForSession(sessionId);++ // If this is a Task tool launching a subagent, update the session mapping+ if (hookData.tool_name === 'Task' && hookData.tool_input?.subagent_type) {+ agentName = hookData.tool_input.subagent_type;+ setAgentForSession(sessionId, agentName);+ }+ // If this is a SubagentStop or Stop event, reset to pai+ else if (eventType === 'SubagentStop' || eventType === 'Stop') {+ agentName = 'pai';+ setAgentForSession(sessionId, 'pai');+ }+ // Check if CLAUDE_CODE_AGENT env variable is set (for subagents)+ else if (process.env.CLAUDE_CODE_AGENT) {+ agentName = process.env.CLAUDE_CODE_AGENT;+ setAgentForSession(sessionId, agentName);+ }+ // Check if agent type is in the payload (alternative detection method)+ else if (hookData.agent_type) {+ agentName = hookData.agent_type;+ setAgentForSession(sessionId, agentName);+ }+ // Check if this is from a subagent based on cwd containing 'agent'+ else if (hookData.cwd && hookData.cwd.includes('/agents/')) {+ // Extract agent name from path like "/agents/designer/"+ const agentMatch = hookData.cwd.match(/\/agents\/([^\/]+)/);+ if (agentMatch) {+ agentName = agentMatch[1];+ setAgentForSession(sessionId, agentName);+ }+ }++ // Create base event object+ let event: HookEvent = {+ source_app: agentName,+ session_id: hookData.session_id || 'main',+ hook_event_type: eventType,+ payload: hookData,+ timestamp: Date.now(),+ timestamp_pst: getPSTTimestamp()+ };++ // Enrich with agent instance metadata if this is a Task tool call+ if (isAgentSpawningCall(hookData.tool_name, hookData.tool_input)) {+ event = enrichEventWithAgentMetadata(+ event,+ hookData.tool_input,+ hookData.description+ );+ }++ // Append to events file+ const eventsFile = getEventsFilePath();+ const jsonLine = JSON.stringify(event) + '\n';+ appendFileSync(eventsFile, jsonLine, 'utf-8');++ } catch (error) {+ // Silently fail - don't block Claude Code+ console.error('Event capture error:', error);+ }++ process.exit(0);+}++main();diff --git a/.claude/hooks/lib/metadata-extraction.ts b/.claude/hooks/lib/metadata-extraction.tsnew file mode 100644index 00000000..dc74fd11--- /dev/null+++ b/.claude/hooks/lib/metadata-extraction.ts@@ -0,0 +1,145 @@+#!/usr/bin/env bun+/**+ * Metadata Extraction Library for UOCS Enhancement+ *+ * Extracts agent instance IDs, parent-child relationships, and session info+ * from Task tool calls and other tool inputs.+ *+ * Design Philosophy: Optional extraction with graceful fallbacks+ * - If instance IDs are present in descriptions/prompts, extract them+ * - If not present, fall back to agent type only+ * - Never fail - always return usable metadata+ */++export interface AgentInstanceMetadata {+ agent_instance_id?: string; // "perplexity-researcher-1" (full ID)+ agent_type?: string; // "perplexity-researcher" (base type)+ instance_number?: number; // 1 (sequence number)+ parent_session_id?: string; // Session that spawned this agent+ parent_task_id?: string; // Task ID that spawned this agent+}++/**+ * Extract agent instance ID from Task tool input+ *+ * Looks for patterns in priority order:+ * 1. [agent-type-N] in description (e.g., "Research topic [perplexity-researcher-1]")+ * 2. [AGENT_INSTANCE: agent-type-N] in prompt+ * 3. subagent_type field (fallback to just type, no instance number)+ *+ * @param toolInput The tool input object from PreToolUse/PostToolUse hooks+ * @param description Optional description field from tool input+ * @returns Metadata object with extracted information+ */+export function extractAgentInstanceId(+ toolInput: any,+ description?: string+): AgentInstanceMetadata {+ const result: AgentInstanceMetadata = {};++ // Strategy 1: Extract from description [agent-type-N]+ // Example: "Research consumer complaints [perplexity-researcher-1]"+ if (description) {+ const descMatch = description.match(/\[([a-z-]+-researcher)-(\d+)\]/);+ if (descMatch) {+ result.agent_type = descMatch[1];+ result.instance_number = parseInt(descMatch[2], 10);+ result.agent_instance_id = `${result.agent_type}-${result.instance_number}`;+ }+ }++ // Strategy 2: Extract from prompt [AGENT_INSTANCE: ...]+ // Example: "[AGENT_INSTANCE: perplexity-researcher-1]"+ if (!result.agent_instance_id && toolInput?.prompt && typeof toolInput.prompt === 'string') {+ const promptMatch = toolInput.prompt.match(/\[AGENT_INSTANCE:\s*([^\]]+)\]/);+ if (promptMatch) {+ result.agent_instance_id = promptMatch[1].trim();++ // Parse agent type and instance number from ID+ const parts = result.agent_instance_id.match(/^([a-z-]+)-(\d+)$/);+ if (parts) {+ result.agent_type = parts[1];+ result.instance_number = parseInt(parts[2], 10);+ }+ }+ }++ // Strategy 3: Extract parent session from prompt+ // Example: "[PARENT_SESSION: b7062b5a-03d3-4168-9555-a748e0b2efa3]"+ if (toolInput?.prompt && typeof toolInput.prompt === 'string') {+ const parentSessionMatch = toolInput.prompt.match(/\[PARENT_SESSION:\s*([^\]]+)\]/);+ if (parentSessionMatch) {+ result.parent_session_id = parentSessionMatch[1].trim();+ }++ // Extract parent task from prompt+ // Example: "[PARENT_TASK: research_1731445892345]"+ const parentTaskMatch = toolInput.prompt.match(/\[PARENT_TASK:\s*([^\]]+)\]/);+ if (parentTaskMatch) {+ result.parent_task_id = parentTaskMatch[1].trim();+ }+ }++ // Strategy 4: Fallback to subagent_type if available (no instance number)+ // This ensures we at least capture the agent type even without instance IDs+ if (!result.agent_type && toolInput?.subagent_type) {+ result.agent_type = toolInput.subagent_type;+ }++ return result;+}++/**+ * Enrich event with agent metadata+ *+ * Takes a base event object and adds agent instance metadata to it.+ * Returns a new object with merged metadata.+ *+ * @param event Base event object (from PreToolUse/PostToolUse)+ * @param toolInput Tool input object+ * @param description Optional description field+ * @returns Enriched event with agent metadata+ */+export function enrichEventWithAgentMetadata(+ event: any,+ toolInput: any,+ description?: string+): any {+ const metadata = extractAgentInstanceId(toolInput, description);++ // Only add fields that have values (keep events clean)+ const enrichedEvent = { ...event };++ if (metadata.agent_instance_id) {+ enrichedEvent.agent_instance_id = metadata.agent_instance_id;+ }++ if (metadata.agent_type) {+ enrichedEvent.agent_type = metadata.agent_type;+ }++ if (metadata.instance_number !== undefined) {+ enrichedEvent.instance_number = metadata.instance_number;+ }++ if (metadata.parent_session_id) {+ enrichedEvent.parent_session_id = metadata.parent_session_id;+ }++ if (metadata.parent_task_id) {+ enrichedEvent.parent_task_id = metadata.parent_task_id;+ }++ return enrichedEvent;+}++/**+ * Check if a tool call is spawning a subagent+ *+ * @param toolName Name of the tool being called+ * @param toolInput Tool input object+ * @returns true if this is a Task tool call spawning an agent+ */+export function isAgentSpawningCall(toolName: string, toolInput: any): boolean {+ return toolName === 'Task' && toolInput?.subagent_type !== undefined;+}diff --git a/.claude/settings.json b/.claude/settings.jsonindex b3577782..6b7e7511 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -1,10 +1,9 @@{"$schema": "https://json.schemastore.org/claude-code-settings.json","env": {- "MCP_API_KEY": "REDACTED",- "DISABLE_INTERLEAVED_THINKING": "true",- "DA": "Kai",- "PAI_DIR": "$HOME/.claude"+ "DA": "PAI",+ "PAI_DIR": "$HOME/.claude",+ "CLAUDE_CODE_MAX_OUTPUT_TOKENS": "64000"},"permissions": {"allow": [@@ -36,7 +35,7 @@"Bash(diskutil coreStorage)","Bash(diskutil cs)","Bash(diskutil disableJournal)",- "Bash(diskutil resetFusion)",+ "Bash(diskutil resetFusion)","Bash(diskutil disableOwnership)","Bash(diskutil apfs deleteContainer)","Bash(diskutil apfs eraseVolume)",@@ -63,7 +62,17 @@"enableAllProjectMcpServers": true,"enabledMcpjsonServers": [],"hooks": {- "PreToolUse": [],+ "PreToolUse": [+ {+ "matcher": "*",+ "hooks": [+ {+ "type": "command",+ "command": "${PAI_DIR}/hooks/capture-all-events.ts --event-type PreToolUse"+ }+ ]+ }+ ],"PostToolUse": [{"matcher": "*",@@ -71,6 +80,10 @@{"type": "command","command": "${PAI_DIR}/hooks/capture-tool-output.ts"+ },+ {+ "type": "command",+ "command": "${PAI_DIR}/hooks/capture-all-events.ts --event-type PostToolUse"}]}@@ -81,17 +94,24 @@{"type": "command","command": "${PAI_DIR}/hooks/capture-session-summary.ts"+ },+ {+ "type": "command",+ "command": "${PAI_DIR}/hooks/capture-all-events.ts --event-type SessionEnd"}]}],- "Notification": [],"UserPromptSubmit": [{"hooks": [{"type": "command","command": "${PAI_DIR}/hooks/update-tab-titles.ts"+ },+ {+ "type": "command",+ "command": "${PAI_DIR}/hooks/capture-all-events.ts --event-type UserPromptSubmit"}]}@@ -106,6 +126,10 @@{"type": "command","command": "${PAI_DIR}/hooks/initialize-pai-session.ts"+ },+ {+ "type": "command",+ "command": "${PAI_DIR}/hooks/capture-all-events.ts --event-type SessionStart"}]}@@ -116,6 +140,10 @@{"type": "command","command": "${PAI_DIR}/hooks/stop-hook.ts"+ },+ {+ "type": "command",+ "command": "${PAI_DIR}/hooks/capture-all-events.ts --event-type Stop"}]}@@ -126,6 +154,10 @@{"type": "command","command": "${PAI_DIR}/hooks/subagent-stop-hook.ts"+ },+ {+ "type": "command",+ "command": "${PAI_DIR}/hooks/capture-all-events.ts --event-type SubagentStop"}]}@@ -137,6 +169,10 @@{"type": "command","command": "${PAI_DIR}/hooks/context-compression-hook.ts"+ },+ {+ "type": "command",+ "command": "${PAI_DIR}/hooks/capture-all-events.ts --event-type PreCompact"}]}@@ -146,7 +182,9 @@"type": "command","command": "bash ${PAI_DIR}/statusline-command.sh"},- "feedbackSurveyState": {- "lastShownTime": 1754071370324- }+ "enabledPlugins": {+ "browser-automation@browser-tools": true+ },+ "alwaysThinkingEnabled": true,+ "max_tokens": 4096}