⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
fix: SessionEnd hooks — stdin timeout, session-scoped state, field name corrections
Daniel Miessler5878b6a6b063
diff --git a/Releases/v3.0/.claude/hooks/AutoWorkCreation.hook.ts b/Releases/v3.0/.claude/hooks/AutoWorkCreation.hook.tsindex c9b8995b..39905e03 100755--- a/Releases/v3.0/.claude/hooks/AutoWorkCreation.hook.ts+++ b/Releases/v3.0/.claude/hooks/AutoWorkCreation.hook.ts@@ -50,7 +50,11 @@ interface PromptClassification {const BASE_DIR = process.env.PAI_DIR || join(process.env.HOME!, '.claude');const WORK_DIR = join(BASE_DIR, 'MEMORY', 'WORK');const STATE_DIR = join(BASE_DIR, 'MEMORY', 'STATE');-const CURRENT_WORK_FILE = join(STATE_DIR, 'current-work.json');+// Session-scoped state files prevent parallel sessions from overwriting each other+function currentWorkFile(sessionId?: string): string {+ if (sessionId) return join(STATE_DIR, `current-work-${sessionId}.json`);+ return join(STATE_DIR, 'current-work.json'); // legacy fallback+}// No more inference — simple heuristic classification@@ -64,10 +68,18 @@ async function readStdinWithTimeout(timeout: number = 5000): Promise<string> {});}-function readCurrentWork(): CurrentWork | null {+function readCurrentWork(sessionId?: string): CurrentWork | null {try {- if (!existsSync(CURRENT_WORK_FILE)) return null;- return JSON.parse(readFileSync(CURRENT_WORK_FILE, 'utf-8'));+ // Try session-scoped file first, fall back to legacy+ const scopedFile = sessionId ? currentWorkFile(sessionId) : null;+ if (scopedFile && existsSync(scopedFile)) {+ return JSON.parse(readFileSync(scopedFile, 'utf-8'));+ }+ const legacyFile = currentWorkFile();+ if (existsSync(legacyFile)) {+ return JSON.parse(readFileSync(legacyFile, 'utf-8'));+ }+ return null;} catch {return null;}@@ -75,7 +87,8 @@ function readCurrentWork(): CurrentWork | null {function writeCurrentWork(state: CurrentWork): void {if (!existsSync(STATE_DIR)) mkdirSync(STATE_DIR, { recursive: true });- writeFileSync(CURRENT_WORK_FILE, JSON.stringify(state, null, 2), 'utf-8');+ // Write to session-scoped file+ writeFileSync(currentWorkFile(state.session_id), JSON.stringify(state, null, 2), 'utf-8');}function slugify(text: string, maxLen: number = 40): string {@@ -110,6 +123,7 @@ function createSessionDirectory(sessionDirName: string, sessionId: string, titletitle: "${title}"session_id: "${sessionId}"created_at: "${timestamp}"+completed_at: nullstatus: "ACTIVE"`;writeFileSync(join(sessionPath, 'META.yaml'), meta, 'utf-8');@@ -253,7 +267,7 @@ async function main() {if (!existsSync(WORK_DIR)) mkdirSync(WORK_DIR, { recursive: true });- let currentWork = readCurrentWork();+ let currentWork = readCurrentWork(sessionId);const isExistingSession = currentWork && currentWork.session_id === sessionId;const classification = classifyPrompt(prompt, !!isExistingSession);diff --git a/Releases/v3.0/.claude/hooks/SessionSummary.hook.ts b/Releases/v3.0/.claude/hooks/SessionSummary.hook.tsindex a80ea1a9..8b72db69 100755--- a/Releases/v3.0/.claude/hooks/SessionSummary.hook.ts+++ b/Releases/v3.0/.claude/hooks/SessionSummary.hook.ts@@ -53,46 +53,66 @@ import { join } from 'path';import { getISOTimestamp } from './lib/time';import { setTabState, cleanupKittySession } from './lib/tab-setter';-const MEMORY_DIR = join(process.env.HOME!, '.claude', 'MEMORY');+const BASE_DIR = process.env.PAI_DIR || join(process.env.HOME!, '.claude');+const MEMORY_DIR = join(BASE_DIR, 'MEMORY');const STATE_DIR = join(MEMORY_DIR, 'STATE');-const CURRENT_WORK_FILE = join(STATE_DIR, 'current-work.json');const WORK_DIR = join(MEMORY_DIR, 'WORK');+// Session-scoped state file lookup with legacy fallback+function findStateFile(sessionId?: string): string | null {+ if (sessionId) {+ const scoped = join(STATE_DIR, `current-work-${sessionId}.json`);+ if (existsSync(scoped)) return scoped;+ }+ const legacy = join(STATE_DIR, 'current-work.json');+ if (existsSync(legacy)) return legacy;+ return null;+}+interface CurrentWork {session_id: string;- work_dir: string;+ session_dir: string;+ current_task: string;+ task_title: string;+ task_count: number;created_at: string;- item_count: number;}/*** Mark work directory as completed and clear session state*/-function clearSessionWork(): void {+function clearSessionWork(sessionId?: string): void {try {- if (!existsSync(CURRENT_WORK_FILE)) {+ const stateFile = findStateFile(sessionId);+ if (!stateFile) {console.error('[SessionSummary] No current work to complete');return;}// Read current work state- const content = readFileSync(CURRENT_WORK_FILE, 'utf-8');+ const content = readFileSync(stateFile, 'utf-8');const currentWork: CurrentWork = JSON.parse(content);+ // Guard: don't process another session's state+ if (sessionId && currentWork.session_id !== sessionId) {+ console.error('[SessionSummary] State file belongs to different session, skipping');+ return;+ }+// Mark work directory as COMPLETED- if (currentWork.work_dir) {- const metaPath = join(WORK_DIR, currentWork.work_dir, 'META.yaml');+ if (currentWork.session_dir) {+ const metaPath = join(WORK_DIR, currentWork.session_dir, 'META.yaml');if (existsSync(metaPath)) {let metaContent = readFileSync(metaPath, 'utf-8');metaContent = metaContent.replace(/^status: "ACTIVE"$/m, 'status: "COMPLETED"');metaContent = metaContent.replace(/^completed_at: null$/m, `completed_at: "${getISOTimestamp()}"`);writeFileSync(metaPath, metaContent, 'utf-8');- console.error(`[SessionSummary] Marked work directory as COMPLETED: ${currentWork.work_dir}`);+ console.error(`[SessionSummary] Marked work directory as COMPLETED: ${currentWork.session_dir}`);}}// Delete state file- unlinkSync(CURRENT_WORK_FILE);+ unlinkSync(stateFile);console.error('[SessionSummary] Cleared session work state');} catch (error) {console.error(`[SessionSummary] Error clearing session work: ${error}`);@@ -101,22 +121,25 @@ function clearSessionWork(): void {async function main() {try {- // Read input from stdin- const input = await Bun.stdin.text();- if (!input || input.trim() === '') {- process.exit(0);- }-- // Extract session_id for correct tab targeting+ // Read input from stdin with timeout — SessionEnd hooks may receive+ // empty or slow stdin. Proceed regardless since state is read from disk.let sessionId: string | undefined;try {- const parsed = JSON.parse(input);- sessionId = parsed.session_id;- } catch { /* not JSON — continue without session_id */ }+ const input = await Promise.race([+ Bun.stdin.text(),+ new Promise<string>((_, reject) => setTimeout(() => reject(new Error('timeout')), 3000))+ ]);+ if (input && input.trim()) {+ const parsed = JSON.parse(input);+ sessionId = parsed.session_id;+ }+ } catch {+ // Timeout or parse error — proceed without session_id+ }// Mark work as complete and clear state// NOTE: Does NOT write to SESSIONS/ - WORK/ is the primary system- clearSessionWork();+ clearSessionWork(sessionId);// Reset Kitty tab to neutral styling — no lingering colored backgroundstry {diff --git a/Releases/v3.0/.claude/hooks/WorkCompletionLearning.hook.ts b/Releases/v3.0/.claude/hooks/WorkCompletionLearning.hook.tsindex bc35a108..afc83e0b 100755--- a/Releases/v3.0/.claude/hooks/WorkCompletionLearning.hook.ts+++ b/Releases/v3.0/.claude/hooks/WorkCompletionLearning.hook.ts@@ -55,17 +55,30 @@ import { join, dirname } from 'path';import { getISOTimestamp, getPSTDate } from './lib/time';import { getLearningCategory } from './lib/learning-utils';-const MEMORY_DIR = join(process.env.HOME!, '.claude', 'MEMORY');+const BASE_DIR = process.env.PAI_DIR || join(process.env.HOME!, '.claude');+const MEMORY_DIR = join(BASE_DIR, 'MEMORY');const STATE_DIR = join(MEMORY_DIR, 'STATE');-const CURRENT_WORK_FILE = join(STATE_DIR, 'current-work.json');const WORK_DIR = join(MEMORY_DIR, 'WORK');const LEARNING_DIR = join(MEMORY_DIR, 'LEARNING');+// Session-scoped state file lookup with legacy fallback+function findStateFile(sessionId?: string): string | null {+ if (sessionId) {+ const scoped = join(STATE_DIR, `current-work-${sessionId}.json`);+ if (existsSync(scoped)) return scoped;+ }+ const legacy = join(STATE_DIR, 'current-work.json');+ if (existsSync(legacy)) return legacy;+ return null;+}+interface CurrentWork {session_id: string;- work_dir: string;+ session_dir: string;+ current_task: string;+ task_title: string;+ task_count: number;created_at: string;- item_count: number;}interface WorkMeta {@@ -239,28 +252,45 @@ ${idealContent || 'Not specified'}async function main() {try {- // Read input from stdin (required for hook pattern)- const input = await Bun.stdin.text();- if (!input || input.trim() === '') {- process.exit(0);+ // Read input from stdin with timeout — SessionEnd hooks may receive+ // empty or slow stdin. Proceed regardless since state is read from disk.+ let sessionId: string | undefined;+ try {+ const input = await Promise.race([+ Bun.stdin.text(),+ new Promise<string>((_, reject) => setTimeout(() => reject(new Error('timeout')), 3000))+ ]);+ if (input && input.trim()) {+ const parsed = JSON.parse(input);+ sessionId = parsed.session_id;+ }+ } catch {+ // Timeout or parse error — proceed without session_id}- // Check if there's an active work session- if (!existsSync(CURRENT_WORK_FILE)) {+ // Check if there's an active work session (session-scoped with legacy fallback)+ const stateFile = findStateFile(sessionId);+ if (!stateFile) {console.error('[WorkCompletionLearning] No active work session');process.exit(0);}// Read current work state- const currentWork: CurrentWork = JSON.parse(readFileSync(CURRENT_WORK_FILE, 'utf-8'));+ const currentWork: CurrentWork = JSON.parse(readFileSync(stateFile, 'utf-8'));++ // Guard: don't process another session's state+ if (sessionId && currentWork.session_id !== sessionId) {+ console.error('[WorkCompletionLearning] State file belongs to different session, skipping');+ process.exit(0);+ }- if (!currentWork.work_dir) {+ if (!currentWork.session_dir) {console.error('[WorkCompletionLearning] No work directory in current session');process.exit(0);}// Read work directory metadata- const workPath = join(WORK_DIR, currentWork.work_dir);+ const workPath = join(WORK_DIR, currentWork.session_dir);const metaPath = join(workPath, 'META.yaml');if (!existsSync(metaPath)) {@@ -301,7 +331,7 @@ async function main() {// Check if this was significant work (has files changed or was manually created)const hasSignificantWork = ((workMeta.lineage?.files_changed?.length || 0) > 0 ||- currentWork.item_count > 1 ||+ currentWork.task_count > 1 ||workMeta.source === 'MANUAL');