@tekmidian/pai 0.5.3 → 0.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/hooks/cleanup-session-files.mjs.map +1 -1
- package/dist/hooks/context-compression-hook.mjs +284 -124
- package/dist/hooks/context-compression-hook.mjs.map +3 -3
- package/dist/hooks/initialize-session.mjs.map +1 -1
- package/dist/hooks/load-project-context.mjs.map +2 -2
- package/dist/hooks/stop-hook.mjs.map +2 -2
- package/dist/hooks/sync-todo-to-md.mjs.map +2 -2
- package/package.json +1 -1
- package/src/hooks/ts/lib/project-utils.ts +90 -4
- package/src/hooks/ts/pre-compact/context-compression-hook.ts +205 -146
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/hooks/ts/pre-compact/context-compression-hook.ts", "../../src/hooks/ts/lib/project-utils.ts", "../../src/hooks/ts/lib/pai-paths.ts"],
|
|
4
|
-
"sourcesContent": ["#!/usr/bin/env node\n/**\n * PreCompact Hook - Triggered before context compression\n *\n * Two critical jobs:\n * 1. Save checkpoint to session note + send notification (existing)\n * 2. OUTPUT session state to stdout so it gets injected into the conversation\n * as a <system-reminder> BEFORE compaction. This ensures the compaction\n * summary retains awareness of what was being worked on.\n *\n * Without (2), compaction produces a generic summary and the session loses\n * critical context: current task, recent requests, file paths, decisions.\n */\n\nimport { readFileSync, writeFileSync } from 'fs';\nimport { basename, dirname, join } from 'path';\nimport { tmpdir } from 'os';\nimport {\n sendNtfyNotification,\n getCurrentNotePath,\n appendCheckpoint,\n addWorkToSessionNote,\n findNotesDir,\n findTodoPath,\n addTodoCheckpoint,\n calculateSessionTokens,\n WorkItem,\n} from '../lib/project-utils';\n\ninterface HookInput {\n session_id: string;\n transcript_path: string;\n cwd?: string;\n hook_event_name: string;\n compact_type?: string;\n trigger?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Turn Claude content (string or content block array) into plain text. */\nfunction contentToText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n return content\n .map((c) => {\n if (typeof c === 'string') return c;\n if (c?.text) return c.text;\n if (c?.content) return String(c.content);\n return '';\n })\n .join(' ')\n .trim();\n }\n return '';\n}\n\nfunction getTranscriptStats(transcriptPath: string): { messageCount: number; isLarge: boolean } {\n try {\n const content = readFileSync(transcriptPath, 'utf-8');\n const lines = content.trim().split('\\n');\n let userMessages = 0;\n let assistantMessages = 0;\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const entry = JSON.parse(line);\n if (entry.type === 'user') userMessages++;\n else if (entry.type === 'assistant') assistantMessages++;\n } catch { /* skip */ }\n }\n const totalMessages = userMessages + assistantMessages;\n return { messageCount: totalMessages, isLarge: totalMessages > 50 };\n } catch {\n return { messageCount: 0, isLarge: false };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Session state extraction\n// ---------------------------------------------------------------------------\n\n/**\n * Extract structured session state from the transcript JSONL.\n * Returns a human-readable summary (<2000 chars) suitable for injection\n * into the conversation before compaction.\n */\nfunction extractSessionState(transcriptPath: string, cwd?: string): string | null {\n try {\n const raw = readFileSync(transcriptPath, 'utf-8');\n const lines = raw.trim().split('\\n');\n\n const userMessages: string[] = [];\n const summaries: string[] = [];\n const captures: string[] = [];\n let lastCompleted = '';\n const filesModified = new Set<string>();\n\n for (const line of lines) {\n if (!line.trim()) continue;\n let entry: any;\n try { entry = JSON.parse(line); } catch { continue; }\n\n // --- User messages ---\n if (entry.type === 'user' && entry.message?.content) {\n const text = contentToText(entry.message.content).slice(0, 300);\n if (text) userMessages.push(text);\n }\n\n // --- Assistant structured sections ---\n if (entry.type === 'assistant' && entry.message?.content) {\n const text = contentToText(entry.message.content);\n\n const summaryMatch = text.match(/SUMMARY:\\s*(.+?)(?:\\n|$)/i);\n if (summaryMatch) {\n const s = summaryMatch[1].trim();\n if (s.length > 5 && !summaries.includes(s)) summaries.push(s);\n }\n\n const captureMatch = text.match(/CAPTURE:\\s*(.+?)(?:\\n|$)/i);\n if (captureMatch) {\n const c = captureMatch[1].trim();\n if (c.length > 5 && !captures.includes(c)) captures.push(c);\n }\n\n const completedMatch = text.match(/COMPLETED:\\s*(.+?)(?:\\n|$)/i);\n if (completedMatch) {\n lastCompleted = completedMatch[1].trim().replace(/\\*+/g, '');\n }\n }\n\n // --- Tool use: file modifications ---\n if (entry.type === 'assistant' && entry.message?.content && Array.isArray(entry.message.content)) {\n for (const block of entry.message.content) {\n if (block.type === 'tool_use') {\n const tool = block.name;\n if ((tool === 'Edit' || tool === 'Write') && block.input?.file_path) {\n filesModified.add(block.input.file_path);\n }\n }\n }\n }\n }\n\n // Build the output \u2014 keep it concise\n const parts: string[] = [];\n\n if (cwd) {\n parts.push(`Working directory: ${cwd}`);\n }\n\n // Last 3 user messages\n const recentUser = userMessages.slice(-3);\n if (recentUser.length > 0) {\n parts.push('\\nRecent user requests:');\n for (const msg of recentUser) {\n // Trim to first line or 200 chars\n const firstLine = msg.split('\\n')[0].slice(0, 200);\n parts.push(`- ${firstLine}`);\n }\n }\n\n // Summaries (last 3)\n const recentSummaries = summaries.slice(-3);\n if (recentSummaries.length > 0) {\n parts.push('\\nWork summaries:');\n for (const s of recentSummaries) {\n parts.push(`- ${s.slice(0, 150)}`);\n }\n }\n\n // Captures (last 5)\n const recentCaptures = captures.slice(-5);\n if (recentCaptures.length > 0) {\n parts.push('\\nCaptured context:');\n for (const c of recentCaptures) {\n parts.push(`- ${c.slice(0, 150)}`);\n }\n }\n\n // Files modified (last 10)\n const files = Array.from(filesModified).slice(-10);\n if (files.length > 0) {\n parts.push('\\nFiles modified this session:');\n for (const f of files) {\n parts.push(`- ${f}`);\n }\n }\n\n if (lastCompleted) {\n parts.push(`\\nLast completed: ${lastCompleted.slice(0, 150)}`);\n }\n\n const result = parts.join('\\n');\n return result.length > 50 ? result : null;\n } catch (err) {\n console.error(`extractSessionState error: ${err}`);\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Work item extraction (same pattern as stop-hook.ts)\n// ---------------------------------------------------------------------------\n\nfunction extractWorkFromTranscript(transcriptPath: string): WorkItem[] {\n try {\n const raw = readFileSync(transcriptPath, 'utf-8');\n const lines = raw.trim().split('\\n');\n const workItems: WorkItem[] = [];\n const seenSummaries = new Set<string>();\n\n for (const line of lines) {\n if (!line.trim()) continue;\n let entry: any;\n try { entry = JSON.parse(line); } catch { continue; }\n\n if (entry.type === 'assistant' && entry.message?.content) {\n const text = contentToText(entry.message.content);\n\n const summaryMatch = text.match(/SUMMARY:\\s*(.+?)(?:\\n|$)/i);\n if (summaryMatch) {\n const summary = summaryMatch[1].trim();\n if (summary && !seenSummaries.has(summary) && summary.length > 5) {\n seenSummaries.add(summary);\n const details: string[] = [];\n const actionsMatch = text.match(/ACTIONS:\\s*(.+?)(?=\\n[A-Z]+:|$)/is);\n if (actionsMatch) {\n const actionLines = actionsMatch[1].split('\\n')\n .map(l => l.replace(/^[-*\u2022]\\s*/, '').replace(/^\\d+\\.\\s*/, '').trim())\n .filter(l => l.length > 3 && l.length < 100);\n details.push(...actionLines.slice(0, 3));\n }\n workItems.push({ title: summary, details: details.length > 0 ? details : undefined, completed: true });\n }\n }\n\n const completedMatch = text.match(/COMPLETED:\\s*(.+?)(?:\\n|$)/i);\n if (completedMatch && workItems.length === 0) {\n const completed = completedMatch[1].trim().replace(/\\*+/g, '');\n if (completed && !seenSummaries.has(completed) && completed.length > 5) {\n seenSummaries.add(completed);\n workItems.push({ title: completed, completed: true });\n }\n }\n }\n }\n return workItems;\n } catch {\n return [];\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main\n// ---------------------------------------------------------------------------\n\nasync function main() {\n let hookInput: HookInput | null = null;\n\n try {\n const decoder = new TextDecoder();\n let input = '';\n const timeoutPromise = new Promise<void>((resolve) => { setTimeout(resolve, 500); });\n const readPromise = (async () => {\n for await (const chunk of process.stdin) {\n input += decoder.decode(chunk, { stream: true });\n }\n })();\n await Promise.race([readPromise, timeoutPromise]);\n if (input.trim()) {\n hookInput = JSON.parse(input) as HookInput;\n }\n } catch {\n // Silently handle input errors\n }\n\n const compactType = hookInput?.compact_type || hookInput?.trigger || 'auto';\n let tokenCount = 0;\n\n if (hookInput?.transcript_path) {\n const stats = getTranscriptStats(hookInput.transcript_path);\n tokenCount = calculateSessionTokens(hookInput.transcript_path);\n const tokenDisplay = tokenCount > 1000\n ? `${Math.round(tokenCount / 1000)}k`\n : String(tokenCount);\n\n // -----------------------------------------------------------------\n // Persist session state to numbered session note (like \"pause session\")\n // -----------------------------------------------------------------\n const state = extractSessionState(hookInput.transcript_path, hookInput.cwd);\n\n try {\n // Find notes dir \u2014 prefer local, fallback to central\n const notesInfo = hookInput.cwd\n ? findNotesDir(hookInput.cwd)\n : { path: join(dirname(hookInput.transcript_path), 'Notes'), isLocal: false };\n const currentNotePath = getCurrentNotePath(notesInfo.path);\n\n if (currentNotePath) {\n // 1. Write rich checkpoint with full session state\n const checkpointBody = state\n ? `Context compression triggered at ~${tokenDisplay} tokens with ${stats.messageCount} messages.\\n\\n${state}`\n : `Context compression triggered at ~${tokenDisplay} tokens with ${stats.messageCount} messages.`;\n appendCheckpoint(currentNotePath, checkpointBody);\n\n // 2. Write work items to \"Work Done\" section (same as stop-hook)\n const workItems = extractWorkFromTranscript(hookInput.transcript_path);\n if (workItems.length > 0) {\n addWorkToSessionNote(currentNotePath, workItems, `Pre-Compact (~${tokenDisplay} tokens)`);\n console.error(`Added ${workItems.length} work item(s) to session note`);\n }\n\n console.error(`Rich checkpoint saved: ${basename(currentNotePath)}`);\n }\n } catch (noteError) {\n console.error(`Could not save checkpoint: ${noteError}`);\n }\n\n // -----------------------------------------------------------------\n // Update TODO.md with checkpoint (like \"pause session\")\n // -----------------------------------------------------------------\n if (hookInput.cwd && state) {\n try {\n addTodoCheckpoint(hookInput.cwd, `Pre-compact checkpoint (~${tokenDisplay} tokens):\\n${state}`);\n console.error('TODO.md checkpoint added');\n } catch (todoError) {\n console.error(`Could not update TODO.md: ${todoError}`);\n }\n }\n\n // -----------------------------------------------------------------------\n // Save session state to temp file for post-compact injection.\n //\n // PreCompact hooks have NO stdout support (Claude Code ignores it).\n // Instead, we write the injection payload to a temp file keyed by\n // session_id. The SessionStart(compact) hook reads it and outputs\n // to stdout, which IS injected into the post-compaction context.\n // -----------------------------------------------------------------------\n if (state && hookInput.session_id) {\n const injection = [\n '<system-reminder>',\n `SESSION STATE RECOVERED AFTER COMPACTION (${compactType}, ~${tokenDisplay} tokens)`,\n '',\n state,\n '',\n 'IMPORTANT: This session state was captured before context compaction.',\n 'Use it to maintain continuity. Continue the conversation from where',\n 'it left off without asking the user to repeat themselves.',\n 'Continue with the last task that you were asked to work on.',\n '</system-reminder>',\n ].join('\\n');\n\n try {\n const stateFile = join(tmpdir(), `pai-compact-state-${hookInput.session_id}.txt`);\n writeFileSync(stateFile, injection, 'utf-8');\n console.error(`Session state saved to ${stateFile} (${injection.length} chars)`);\n } catch (err) {\n console.error(`Failed to save state file: ${err}`);\n }\n }\n }\n\n // Send ntfy.sh notification\n const ntfyMessage = tokenCount > 0\n ? `Auto-pause: ~${Math.round(tokenCount / 1000)}k tokens`\n : 'Context compressing';\n await sendNtfyNotification(ntfyMessage);\n\n process.exit(0);\n}\n\nmain().catch(() => {\n process.exit(0);\n});\n", "/**\n * project-utils.ts - Shared utilities for project context management\n *\n * Provides:\n * - Path encoding (matching Claude Code's scheme)\n * - ntfy.sh notifications (mandatory, synchronous)\n * - Session notes management\n * - Session token calculation\n */\n\nimport { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, renameSync } from 'fs';\nimport { join, basename } from 'path';\n\n// Import from pai-paths which handles .env loading and path resolution\nimport { PAI_DIR } from './pai-paths.js';\n\n// Re-export PAI_DIR for consumers\nexport { PAI_DIR };\nexport const PROJECTS_DIR = join(PAI_DIR, 'projects');\n\n/**\n * Encode a path the same way Claude Code does:\n * - Replace / with -\n * - Replace . with - (hidden directories become --name)\n *\n * This matches Claude Code's internal encoding to ensure Notes\n * are stored in the same project directory as transcripts.\n */\nexport function encodePath(path: string): string {\n return path\n .replace(/\\//g, '-') // Slashes become dashes\n .replace(/\\./g, '-') // Dots also become dashes\n .replace(/ /g, '-'); // Spaces become dashes (matches Claude Code native encoding)\n}\n\n/**\n * Get the project directory for a given working directory\n */\nexport function getProjectDir(cwd: string): string {\n const encoded = encodePath(cwd);\n return join(PROJECTS_DIR, encoded);\n}\n\n/**\n * Get the Notes directory for a project (central location)\n */\nexport function getNotesDir(cwd: string): string {\n return join(getProjectDir(cwd), 'Notes');\n}\n\n/**\n * Find Notes directory - check local first, fallback to central\n * DOES NOT create the directory - just finds the right location\n *\n * Logic:\n * - If cwd itself IS a Notes directory \u2192 use it directly\n * - If local Notes/ exists \u2192 use it (can be checked into git)\n * - Otherwise \u2192 use central ~/.claude/projects/.../Notes/\n */\nexport function findNotesDir(cwd: string): { path: string; isLocal: boolean } {\n // FIRST: Check if cwd itself IS a Notes directory\n const cwdBasename = basename(cwd).toLowerCase();\n if (cwdBasename === 'notes' && existsSync(cwd)) {\n return { path: cwd, isLocal: true };\n }\n\n // Check local locations\n const localPaths = [\n join(cwd, 'Notes'),\n join(cwd, 'notes'),\n join(cwd, '.claude', 'Notes')\n ];\n\n for (const path of localPaths) {\n if (existsSync(path)) {\n return { path, isLocal: true };\n }\n }\n\n // Fallback to central location\n return { path: getNotesDir(cwd), isLocal: false };\n}\n\n/**\n * Get the Sessions directory for a project (stores .jsonl transcripts)\n */\nexport function getSessionsDir(cwd: string): string {\n return join(getProjectDir(cwd), 'sessions');\n}\n\n/**\n * Get the Sessions directory from a project directory path\n */\nexport function getSessionsDirFromProjectDir(projectDir: string): string {\n return join(projectDir, 'sessions');\n}\n\n/**\n * Check if WhatsApp (Whazaa) is configured as an enabled MCP server.\n *\n * Uses standard Claude Code config at ~/.claude/settings.json.\n * No PAI dependency \u2014 works for any Claude Code user with whazaa installed.\n */\nexport function isWhatsAppEnabled(): boolean {\n try {\n const { homedir } = require('os');\n const settingsPath = join(homedir(), '.claude', 'settings.json');\n if (!existsSync(settingsPath)) return false;\n\n const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n const enabled: string[] = settings.enabledMcpjsonServers || [];\n return enabled.includes('whazaa');\n } catch {\n return false;\n }\n}\n\n/**\n * Send push notification \u2014 WhatsApp-aware with ntfy fallback.\n *\n * When WhatsApp (Whazaa) is enabled in MCP config, ntfy is SKIPPED\n * because the AI sends WhatsApp messages directly via MCP. Sending both\n * would cause duplicate notifications.\n *\n * When WhatsApp is NOT configured, ntfy fires as the fallback channel.\n */\nexport async function sendNtfyNotification(message: string, retries = 2): Promise<boolean> {\n // Skip ntfy when WhatsApp is configured \u2014 the AI handles notifications via MCP\n if (isWhatsAppEnabled()) {\n console.error(`WhatsApp (Whazaa) enabled in MCP config \u2014 skipping ntfy`);\n return true;\n }\n\n const topic = process.env.NTFY_TOPIC;\n\n if (!topic) {\n console.error('NTFY_TOPIC not set and WhatsApp not active \u2014 notifications disabled');\n return false;\n }\n\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n const response = await fetch(`https://ntfy.sh/${topic}`, {\n method: 'POST',\n body: message,\n headers: {\n 'Title': 'Claude Code',\n 'Priority': 'default'\n }\n });\n\n if (response.ok) {\n console.error(`ntfy.sh notification sent (WhatsApp inactive): \"${message}\"`);\n return true;\n } else {\n console.error(`ntfy.sh attempt ${attempt + 1} failed: ${response.status}`);\n }\n } catch (error) {\n console.error(`ntfy.sh attempt ${attempt + 1} error: ${error}`);\n }\n\n // Wait before retry\n if (attempt < retries) {\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n }\n\n console.error('ntfy.sh notification failed after all retries');\n return false;\n}\n\n/**\n * Ensure the Notes directory exists for a project\n * DEPRECATED: Use ensureNotesDirSmart() instead\n */\nexport function ensureNotesDir(cwd: string): string {\n const notesDir = getNotesDir(cwd);\n\n if (!existsSync(notesDir)) {\n mkdirSync(notesDir, { recursive: true });\n console.error(`Created Notes directory: ${notesDir}`);\n }\n\n return notesDir;\n}\n\n/**\n * Smart Notes directory handling:\n * - If local Notes/ exists \u2192 use it (don't create anything new)\n * - If no local Notes/ \u2192 ensure central exists and use that\n *\n * This respects the user's choice:\n * - Projects with local Notes/ keep notes there (git-trackable)\n * - Other directories don't get cluttered with auto-created Notes/\n */\nexport function ensureNotesDirSmart(cwd: string): { path: string; isLocal: boolean } {\n const found = findNotesDir(cwd);\n\n if (found.isLocal) {\n // Local Notes/ exists - use it as-is\n return found;\n }\n\n // No local Notes/ - ensure central exists\n if (!existsSync(found.path)) {\n mkdirSync(found.path, { recursive: true });\n console.error(`Created central Notes directory: ${found.path}`);\n }\n\n return found;\n}\n\n/**\n * Ensure the Sessions directory exists for a project\n */\nexport function ensureSessionsDir(cwd: string): string {\n const sessionsDir = getSessionsDir(cwd);\n\n if (!existsSync(sessionsDir)) {\n mkdirSync(sessionsDir, { recursive: true });\n console.error(`Created sessions directory: ${sessionsDir}`);\n }\n\n return sessionsDir;\n}\n\n/**\n * Ensure the Sessions directory exists (from project dir path)\n */\nexport function ensureSessionsDirFromProjectDir(projectDir: string): string {\n const sessionsDir = getSessionsDirFromProjectDir(projectDir);\n\n if (!existsSync(sessionsDir)) {\n mkdirSync(sessionsDir, { recursive: true });\n console.error(`Created sessions directory: ${sessionsDir}`);\n }\n\n return sessionsDir;\n}\n\n/**\n * Move all .jsonl session files from project root to sessions/ subdirectory\n * @param projectDir - The project directory path\n * @param excludeFile - Optional filename to exclude (e.g., current active session)\n * @param silent - If true, suppress console output\n * Returns the number of files moved\n */\nexport function moveSessionFilesToSessionsDir(\n projectDir: string,\n excludeFile?: string,\n silent: boolean = false\n): number {\n const sessionsDir = ensureSessionsDirFromProjectDir(projectDir);\n\n if (!existsSync(projectDir)) {\n return 0;\n }\n\n const files = readdirSync(projectDir);\n let movedCount = 0;\n\n for (const file of files) {\n // Match session files: uuid.jsonl or agent-*.jsonl\n // Skip the excluded file (typically the current active session)\n if (file.endsWith('.jsonl') && file !== excludeFile) {\n const sourcePath = join(projectDir, file);\n const destPath = join(sessionsDir, file);\n\n try {\n renameSync(sourcePath, destPath);\n if (!silent) {\n console.error(`Moved ${file} \u2192 sessions/`);\n }\n movedCount++;\n } catch (error) {\n if (!silent) {\n console.error(`Could not move ${file}: ${error}`);\n }\n }\n }\n }\n\n return movedCount;\n}\n\n/**\n * Get the YYYY/MM subdirectory for the current month inside notesDir.\n * Creates the directory if it doesn't exist.\n */\nfunction getMonthDir(notesDir: string): string {\n const now = new Date();\n const year = String(now.getFullYear());\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const monthDir = join(notesDir, year, month);\n if (!existsSync(monthDir)) {\n mkdirSync(monthDir, { recursive: true });\n }\n return monthDir;\n}\n\n/**\n * Get the next note number (4-digit format: 0001, 0002, etc.)\n * ALWAYS uses 4-digit format with space-dash-space separators\n * Format: NNNN - YYYY-MM-DD - Description.md\n * Numbers reset per month (each YYYY/MM directory has its own sequence).\n */\nexport function getNextNoteNumber(notesDir: string): string {\n const monthDir = getMonthDir(notesDir);\n\n // Match CORRECT format: \"0001 - \" (4-digit with space-dash-space)\n // Also match legacy formats for backwards compatibility when detecting max number\n const files = readdirSync(monthDir)\n .filter(f => f.match(/^\\d{3,4}[\\s_-]/)) // Starts with 3-4 digits followed by separator\n .filter(f => f.endsWith('.md'))\n .sort();\n\n if (files.length === 0) {\n return '0001'; // Default to 4-digit\n }\n\n // Find the highest number across all formats\n let maxNumber = 0;\n for (const file of files) {\n const digitMatch = file.match(/^(\\d+)/);\n if (digitMatch) {\n const num = parseInt(digitMatch[1], 10);\n if (num > maxNumber) maxNumber = num;\n }\n }\n\n // ALWAYS return 4-digit format\n return String(maxNumber + 1).padStart(4, '0');\n}\n\n/**\n * Get the current (latest) note file path, or null if none exists.\n * Searches in the current month's YYYY/MM subdirectory first,\n * then falls back to previous month (for sessions spanning month boundaries),\n * then falls back to flat notesDir for legacy notes.\n * Supports multiple formats for backwards compatibility:\n * - CORRECT: \"0001 - YYYY-MM-DD - Description.md\" (space-dash-space)\n * - Legacy: \"001_YYYY-MM-DD_description.md\" (underscores)\n */\nexport function getCurrentNotePath(notesDir: string): string | null {\n if (!existsSync(notesDir)) {\n return null;\n }\n\n // Helper: find latest session note in a directory\n const findLatestIn = (dir: string): string | null => {\n if (!existsSync(dir)) return null;\n const files = readdirSync(dir)\n .filter(f => f.match(/^\\d{3,4}[\\s_-].*\\.md$/))\n .sort((a, b) => {\n const numA = parseInt(a.match(/^(\\d+)/)?.[1] || '0', 10);\n const numB = parseInt(b.match(/^(\\d+)/)?.[1] || '0', 10);\n return numA - numB;\n });\n if (files.length === 0) return null;\n return join(dir, files[files.length - 1]);\n };\n\n // 1. Check current month's YYYY/MM directory\n const now = new Date();\n const year = String(now.getFullYear());\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const currentMonthDir = join(notesDir, year, month);\n const found = findLatestIn(currentMonthDir);\n if (found) return found;\n\n // 2. Check previous month (for sessions spanning month boundaries)\n const prevDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);\n const prevYear = String(prevDate.getFullYear());\n const prevMonth = String(prevDate.getMonth() + 1).padStart(2, '0');\n const prevMonthDir = join(notesDir, prevYear, prevMonth);\n const prevFound = findLatestIn(prevMonthDir);\n if (prevFound) return prevFound;\n\n // 3. Fallback: check flat notesDir (legacy notes not yet filed)\n return findLatestIn(notesDir);\n}\n\n/**\n * Create a new session note\n * CORRECT FORMAT: \"NNNN - YYYY-MM-DD - Description.md\"\n * - 4-digit zero-padded number\n * - Space-dash-space separators (NOT underscores)\n * - Title case description\n *\n * IMPORTANT: The initial description is just a PLACEHOLDER.\n * Claude MUST rename the file at session end with a meaningful description\n * based on the actual work done. Never leave it as \"New Session\" or project name.\n */\nexport function createSessionNote(notesDir: string, description: string): string {\n const noteNumber = getNextNoteNumber(notesDir);\n const date = new Date().toISOString().split('T')[0]; // YYYY-MM-DD\n\n // Use \"New Session\" as placeholder - Claude MUST rename at session end!\n // The project name alone is NOT descriptive enough.\n const safeDescription = 'New Session';\n\n // CORRECT FORMAT: space-dash-space separators, filed into YYYY/MM subdirectory\n const monthDir = getMonthDir(notesDir);\n const filename = `${noteNumber} - ${date} - ${safeDescription}.md`;\n const filepath = join(monthDir, filename);\n\n const content = `# Session ${noteNumber}: ${description}\n\n**Date:** ${date}\n**Status:** In Progress\n\n---\n\n## Work Done\n\n<!-- PAI will add completed work here during session -->\n\n---\n\n## Next Steps\n\n<!-- To be filled at session end -->\n\n---\n\n**Tags:** #Session\n`;\n\n writeFileSync(filepath, content);\n console.error(`Created session note: ${filename}`);\n\n return filepath;\n}\n\n/**\n * Append checkpoint to current session note\n */\nexport function appendCheckpoint(notePath: string, checkpoint: string): void {\n if (!existsSync(notePath)) {\n console.error(`Note file not found: ${notePath}`);\n return;\n }\n\n const content = readFileSync(notePath, 'utf-8');\n const timestamp = new Date().toISOString();\n const checkpointText = `\\n### Checkpoint ${timestamp}\\n\\n${checkpoint}\\n`;\n\n // Insert before \"## Next Steps\" if it exists, otherwise append\n const nextStepsIndex = content.indexOf('## Next Steps');\n let newContent: string;\n\n if (nextStepsIndex !== -1) {\n newContent = content.substring(0, nextStepsIndex) + checkpointText + content.substring(nextStepsIndex);\n } else {\n newContent = content + checkpointText;\n }\n\n writeFileSync(notePath, newContent);\n console.error(`Checkpoint added to: ${basename(notePath)}`);\n}\n\n/**\n * Work item for session notes\n */\nexport interface WorkItem {\n title: string;\n details?: string[];\n completed?: boolean;\n}\n\n/**\n * Add work items to the \"Work Done\" section of a session note\n * This is the main way to capture what was accomplished in a session\n */\nexport function addWorkToSessionNote(notePath: string, workItems: WorkItem[], sectionTitle?: string): void {\n if (!existsSync(notePath)) {\n console.error(`Note file not found: ${notePath}`);\n return;\n }\n\n let content = readFileSync(notePath, 'utf-8');\n\n // Build the work section content\n let workText = '';\n if (sectionTitle) {\n workText += `\\n### ${sectionTitle}\\n\\n`;\n }\n\n for (const item of workItems) {\n const checkbox = item.completed !== false ? '[x]' : '[ ]';\n workText += `- ${checkbox} **${item.title}**\\n`;\n if (item.details && item.details.length > 0) {\n for (const detail of item.details) {\n workText += ` - ${detail}\\n`;\n }\n }\n }\n\n // Find the Work Done section and insert after the comment/placeholder\n const workDoneMatch = content.match(/## Work Done\\n\\n(<!-- .*? -->)?/);\n if (workDoneMatch) {\n const insertPoint = content.indexOf(workDoneMatch[0]) + workDoneMatch[0].length;\n content = content.substring(0, insertPoint) + workText + content.substring(insertPoint);\n } else {\n // Fallback: insert before Next Steps\n const nextStepsIndex = content.indexOf('## Next Steps');\n if (nextStepsIndex !== -1) {\n content = content.substring(0, nextStepsIndex) + workText + '\\n' + content.substring(nextStepsIndex);\n }\n }\n\n writeFileSync(notePath, content);\n console.error(`Added ${workItems.length} work item(s) to: ${basename(notePath)}`);\n}\n\n/**\n * Update the session note title to be more descriptive\n * Called when we know what work was done\n */\nexport function updateSessionNoteTitle(notePath: string, newTitle: string): void {\n if (!existsSync(notePath)) {\n console.error(`Note file not found: ${notePath}`);\n return;\n }\n\n let content = readFileSync(notePath, 'utf-8');\n\n // Update the H1 title\n content = content.replace(/^# Session \\d+:.*$/m, (match) => {\n const sessionNum = match.match(/Session (\\d+)/)?.[1] || '';\n return `# Session ${sessionNum}: ${newTitle}`;\n });\n\n writeFileSync(notePath, content);\n\n // Also rename the file\n renameSessionNote(notePath, sanitizeForFilename(newTitle));\n}\n\n/**\n * Sanitize a string for use in a filename (exported for use elsewhere)\n */\nexport function sanitizeForFilename(str: string): string {\n return str\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, '') // Remove special chars\n .replace(/\\s+/g, '-') // Spaces to hyphens\n .replace(/-+/g, '-') // Collapse multiple hyphens\n .replace(/^-|-$/g, '') // Trim hyphens\n .substring(0, 50); // Limit length\n}\n\n/**\n * Extract a meaningful name from session note content\n * Looks at Work Done section and summary to generate a descriptive name\n */\nexport function extractMeaningfulName(noteContent: string, summary: string): string {\n // Try to extract from Work Done section headers (### headings)\n const workDoneMatch = noteContent.match(/## Work Done\\n\\n([\\s\\S]*?)(?=\\n---|\\n## Next)/);\n\n if (workDoneMatch) {\n const workDoneSection = workDoneMatch[1];\n\n // Look for ### subheadings which typically describe what was done\n const subheadings = workDoneSection.match(/### ([^\\n]+)/g);\n if (subheadings && subheadings.length > 0) {\n // Use the first subheading, clean it up\n const firstHeading = subheadings[0].replace('### ', '').trim();\n if (firstHeading.length > 5 && firstHeading.length < 60) {\n return sanitizeForFilename(firstHeading);\n }\n }\n\n // Look for bold text which often indicates key topics\n const boldMatches = workDoneSection.match(/\\*\\*([^*]+)\\*\\*/g);\n if (boldMatches && boldMatches.length > 0) {\n const firstBold = boldMatches[0].replace(/\\*\\*/g, '').trim();\n if (firstBold.length > 3 && firstBold.length < 50) {\n return sanitizeForFilename(firstBold);\n }\n }\n\n // Look for numbered list items (1. Something)\n const numberedItems = workDoneSection.match(/^\\d+\\.\\s+\\*\\*([^*]+)\\*\\*/m);\n if (numberedItems) {\n return sanitizeForFilename(numberedItems[1]);\n }\n }\n\n // Fall back to summary if provided\n if (summary && summary.length > 5 && summary !== 'Session completed.') {\n // Take first meaningful phrase from summary\n const cleanSummary = summary\n .replace(/[^\\w\\s-]/g, ' ')\n .trim()\n .split(/\\s+/)\n .slice(0, 5)\n .join(' ');\n\n if (cleanSummary.length > 3) {\n return sanitizeForFilename(cleanSummary);\n }\n }\n\n return '';\n}\n\n/**\n * Rename session note with a meaningful name\n * ALWAYS uses correct format: \"NNNN - YYYY-MM-DD - Description.md\"\n * Returns the new path, or original path if rename fails\n */\nexport function renameSessionNote(notePath: string, meaningfulName: string): string {\n if (!meaningfulName || !existsSync(notePath)) {\n return notePath;\n }\n\n const dir = join(notePath, '..');\n const oldFilename = basename(notePath);\n\n // Parse existing filename - support multiple formats:\n // CORRECT: \"0001 - 2026-01-02 - Description.md\"\n // Legacy: \"001_2026-01-02_description.md\"\n const correctMatch = oldFilename.match(/^(\\d{3,4}) - (\\d{4}-\\d{2}-\\d{2}) - .*\\.md$/);\n const legacyMatch = oldFilename.match(/^(\\d{3,4})_(\\d{4}-\\d{2}-\\d{2})_.*\\.md$/);\n\n const match = correctMatch || legacyMatch;\n if (!match) {\n return notePath; // Can't parse, don't rename\n }\n\n const [, noteNumber, date] = match;\n\n // Convert to Title Case\n const titleCaseName = meaningfulName\n .split(/[\\s_-]+/)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(' ')\n .trim();\n\n // ALWAYS use correct format with 4-digit number\n const paddedNumber = noteNumber.padStart(4, '0');\n const newFilename = `${paddedNumber} - ${date} - ${titleCaseName}.md`;\n const newPath = join(dir, newFilename);\n\n // Don't rename if name is the same\n if (newFilename === oldFilename) {\n return notePath;\n }\n\n try {\n renameSync(notePath, newPath);\n console.error(`Renamed note: ${oldFilename} \u2192 ${newFilename}`);\n return newPath;\n } catch (error) {\n console.error(`Could not rename note: ${error}`);\n return notePath;\n }\n}\n\n/**\n * Finalize session note (mark as complete, add summary, rename with meaningful name)\n * IDEMPOTENT: Will only finalize once, subsequent calls are no-ops\n * Returns the final path (may be renamed)\n */\nexport function finalizeSessionNote(notePath: string, summary: string): string {\n if (!existsSync(notePath)) {\n console.error(`Note file not found: ${notePath}`);\n return notePath;\n }\n\n let content = readFileSync(notePath, 'utf-8');\n\n // IDEMPOTENT CHECK: If already completed, don't modify again\n if (content.includes('**Status:** Completed')) {\n console.error(`Note already finalized: ${basename(notePath)}`);\n return notePath;\n }\n\n // Update status\n content = content.replace('**Status:** In Progress', '**Status:** Completed');\n\n // Add completion timestamp (only if not already present)\n if (!content.includes('**Completed:**')) {\n const completionTime = new Date().toISOString();\n content = content.replace(\n '---\\n\\n## Work Done',\n `**Completed:** ${completionTime}\\n\\n---\\n\\n## Work Done`\n );\n }\n\n // Add summary to Next Steps section (only if placeholder exists)\n const nextStepsMatch = content.match(/## Next Steps\\n\\n(<!-- .*? -->)/);\n if (nextStepsMatch) {\n content = content.replace(\n nextStepsMatch[0],\n `## Next Steps\\n\\n${summary || 'Session completed.'}`\n );\n }\n\n writeFileSync(notePath, content);\n console.error(`Session note finalized: ${basename(notePath)}`);\n\n // Extract meaningful name and rename the file\n const meaningfulName = extractMeaningfulName(content, summary);\n if (meaningfulName) {\n const newPath = renameSessionNote(notePath, meaningfulName);\n return newPath;\n }\n\n return notePath;\n}\n\n/**\n * Calculate total tokens from a session .jsonl file\n */\nexport function calculateSessionTokens(jsonlPath: string): number {\n if (!existsSync(jsonlPath)) {\n return 0;\n }\n\n try {\n const content = readFileSync(jsonlPath, 'utf-8');\n const lines = content.trim().split('\\n');\n let totalTokens = 0;\n\n for (const line of lines) {\n try {\n const entry = JSON.parse(line);\n if (entry.message?.usage) {\n const usage = entry.message.usage;\n totalTokens += (usage.input_tokens || 0);\n totalTokens += (usage.output_tokens || 0);\n totalTokens += (usage.cache_creation_input_tokens || 0);\n totalTokens += (usage.cache_read_input_tokens || 0);\n }\n } catch {\n // Skip invalid JSON lines\n }\n }\n\n return totalTokens;\n } catch (error) {\n console.error(`Error calculating tokens: ${error}`);\n return 0;\n }\n}\n\n/**\n * Find TODO.md - check local first, fallback to central\n */\nexport function findTodoPath(cwd: string): string {\n // Check local locations first\n const localPaths = [\n join(cwd, 'TODO.md'),\n join(cwd, 'notes', 'TODO.md'),\n join(cwd, 'Notes', 'TODO.md'),\n join(cwd, '.claude', 'TODO.md')\n ];\n\n for (const path of localPaths) {\n if (existsSync(path)) {\n return path;\n }\n }\n\n // Fallback to central location (inside Notes/)\n return join(getNotesDir(cwd), 'TODO.md');\n}\n\n/**\n * Find CLAUDE.md - check local locations\n * Returns the FIRST found path (for backwards compatibility)\n */\nexport function findClaudeMdPath(cwd: string): string | null {\n const paths = findAllClaudeMdPaths(cwd);\n return paths.length > 0 ? paths[0] : null;\n}\n\n/**\n * Find ALL CLAUDE.md files in local locations\n * Returns paths in priority order (most specific first):\n * 1. .claude/CLAUDE.md (project-specific config dir)\n * 2. CLAUDE.md (project root)\n * 3. Notes/CLAUDE.md (notes directory)\n * 4. Prompts/CLAUDE.md (prompts directory)\n *\n * All found files will be loaded and injected into context.\n */\nexport function findAllClaudeMdPaths(cwd: string): string[] {\n const foundPaths: string[] = [];\n\n // Priority order: most specific first\n const localPaths = [\n join(cwd, '.claude', 'CLAUDE.md'),\n join(cwd, 'CLAUDE.md'),\n join(cwd, 'Notes', 'CLAUDE.md'),\n join(cwd, 'notes', 'CLAUDE.md'),\n join(cwd, 'Prompts', 'CLAUDE.md'),\n join(cwd, 'prompts', 'CLAUDE.md')\n ];\n\n for (const path of localPaths) {\n if (existsSync(path)) {\n foundPaths.push(path);\n }\n }\n\n return foundPaths;\n}\n\n/**\n * Ensure TODO.md exists\n */\nexport function ensureTodoMd(cwd: string): string {\n const todoPath = findTodoPath(cwd);\n\n if (!existsSync(todoPath)) {\n // Ensure parent directory exists\n const parentDir = join(todoPath, '..');\n if (!existsSync(parentDir)) {\n mkdirSync(parentDir, { recursive: true });\n }\n\n const content = `# TODO\n\n## Current Session\n\n- [ ] (Tasks will be tracked here)\n\n## Backlog\n\n- [ ] (Future tasks)\n\n---\n\n*Last updated: ${new Date().toISOString()}*\n`;\n\n writeFileSync(todoPath, content);\n console.error(`Created TODO.md: ${todoPath}`);\n }\n\n return todoPath;\n}\n\n/**\n * Task item for TODO.md\n */\nexport interface TodoItem {\n content: string;\n completed: boolean;\n}\n\n/**\n * Update TODO.md with current session tasks\n * Preserves the Backlog section\n * Ensures only ONE timestamp line at the end\n */\nexport function updateTodoMd(cwd: string, tasks: TodoItem[], sessionSummary?: string): void {\n const todoPath = ensureTodoMd(cwd);\n const content = readFileSync(todoPath, 'utf-8');\n\n // Find Backlog section to preserve it (but strip any trailing timestamps/separators)\n const backlogMatch = content.match(/## Backlog[\\s\\S]*?(?=\\n---|\\n\\*Last updated|$)/);\n let backlogSection = backlogMatch ? backlogMatch[0].trim() : '## Backlog\\n\\n- [ ] (Future tasks)';\n\n // Format tasks\n const taskLines = tasks.length > 0\n ? tasks.map(t => `- [${t.completed ? 'x' : ' '}] ${t.content}`).join('\\n')\n : '- [ ] (No active tasks)';\n\n // Build new content with exactly ONE timestamp at the end\n const newContent = `# TODO\n\n## Current Session\n\n${taskLines}\n\n${sessionSummary ? `**Session Summary:** ${sessionSummary}\\n\\n` : ''}${backlogSection}\n\n---\n\n*Last updated: ${new Date().toISOString()}*\n`;\n\n writeFileSync(todoPath, newContent);\n console.error(`Updated TODO.md: ${todoPath}`);\n}\n\n/**\n * Add a checkpoint entry to TODO.md (without replacing tasks)\n * Ensures only ONE timestamp line at the end\n */\nexport function addTodoCheckpoint(cwd: string, checkpoint: string): void {\n const todoPath = ensureTodoMd(cwd);\n let content = readFileSync(todoPath, 'utf-8');\n\n // Remove ALL existing timestamp lines and trailing separators\n content = content.replace(/(\\n---\\s*)*(\\n\\*Last updated:.*\\*\\s*)+$/g, '');\n\n // Add checkpoint before Backlog section\n const backlogIndex = content.indexOf('## Backlog');\n if (backlogIndex !== -1) {\n const checkpointText = `\\n**Checkpoint (${new Date().toISOString()}):** ${checkpoint}\\n\\n`;\n content = content.substring(0, backlogIndex) + checkpointText + content.substring(backlogIndex);\n }\n\n // Add exactly ONE timestamp at the end\n content = content.trimEnd() + `\\n\\n---\\n\\n*Last updated: ${new Date().toISOString()}*\\n`;\n\n writeFileSync(todoPath, content);\n console.error(`Checkpoint added to TODO.md`);\n}\n", "/**\n * PAI Path Resolution - Single Source of Truth\n *\n * This module provides consistent path resolution across all PAI hooks.\n * It handles PAI_DIR detection whether set explicitly or defaulting to ~/.claude\n *\n * ALSO loads .env file from PAI_DIR so all hooks get environment variables\n * without relying on Claude Code's settings.json injection.\n *\n * Usage in hooks:\n * import { PAI_DIR, HOOKS_DIR, SKILLS_DIR } from './lib/pai-paths';\n */\n\nimport { homedir } from 'os';\nimport { resolve, join } from 'path';\nimport { existsSync, readFileSync } from 'fs';\n\n/**\n * Load .env file and inject into process.env\n * Must run BEFORE PAI_DIR resolution so .env can set PAI_DIR if needed\n */\nfunction loadEnvFile(): void {\n // Check common locations for .env\n const possiblePaths = [\n resolve(process.env.PAI_DIR || '', '.env'),\n resolve(homedir(), '.claude', '.env'),\n ];\n\n for (const envPath of possiblePaths) {\n if (existsSync(envPath)) {\n try {\n const content = readFileSync(envPath, 'utf-8');\n for (const line of content.split('\\n')) {\n const trimmed = line.trim();\n // Skip comments and empty lines\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n const eqIndex = trimmed.indexOf('=');\n if (eqIndex > 0) {\n const key = trimmed.substring(0, eqIndex).trim();\n let value = trimmed.substring(eqIndex + 1).trim();\n\n // Remove surrounding quotes if present\n if ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.slice(1, -1);\n }\n\n // Expand $HOME and ~ in values\n value = value.replace(/\\$HOME/g, homedir());\n value = value.replace(/^~(?=\\/|$)/, homedir());\n\n // Only set if not already defined (env vars take precedence)\n if (process.env[key] === undefined) {\n process.env[key] = value;\n }\n }\n }\n // Found and loaded, don't check other paths\n break;\n } catch {\n // Silently continue if .env can't be read\n }\n }\n }\n}\n\n// Load .env FIRST, before any other initialization\nloadEnvFile();\n\n/**\n * Smart PAI_DIR detection with fallback\n * Priority:\n * 1. PAI_DIR environment variable (if set)\n * 2. ~/.claude (standard location)\n */\nexport const PAI_DIR = process.env.PAI_DIR\n ? resolve(process.env.PAI_DIR)\n : resolve(homedir(), '.claude');\n\n/**\n * Common PAI directories\n */\nexport const HOOKS_DIR = join(PAI_DIR, 'Hooks');\nexport const SKILLS_DIR = join(PAI_DIR, 'Skills');\nexport const AGENTS_DIR = join(PAI_DIR, 'Agents');\nexport const HISTORY_DIR = join(PAI_DIR, 'History');\nexport const COMMANDS_DIR = join(PAI_DIR, 'Commands');\n\n/**\n * Validate PAI directory structure on first import\n * This fails fast with a clear error if PAI is misconfigured\n */\nfunction validatePAIStructure(): void {\n if (!existsSync(PAI_DIR)) {\n console.error(`PAI_DIR does not exist: ${PAI_DIR}`);\n console.error(` Expected ~/.claude or set PAI_DIR environment variable`);\n process.exit(1);\n }\n\n if (!existsSync(HOOKS_DIR)) {\n console.error(`PAI hooks directory not found: ${HOOKS_DIR}`);\n console.error(` Your PAI_DIR may be misconfigured`);\n console.error(` Current PAI_DIR: ${PAI_DIR}`);\n process.exit(1);\n }\n}\n\n// Run validation on module import\n// This ensures any hook that imports this module will fail fast if paths are wrong\nvalidatePAIStructure();\n\n/**\n * Helper to get history file path with date-based organization\n */\nexport function getHistoryFilePath(subdir: string, filename: string): string {\n const now = new Date();\n const tz = process.env.TIME_ZONE || Intl.DateTimeFormat().resolvedOptions().timeZone;\n const localDate = new Date(now.toLocaleString('en-US', { timeZone: tz }));\n const year = localDate.getFullYear();\n const month = String(localDate.getMonth() + 1).padStart(2, '0');\n\n return join(HISTORY_DIR, subdir, `${year}-${month}`, filename);\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;AAcA,SAAS,gBAAAA,eAAc,iBAAAC,sBAAqB;AAC5C,SAAS,YAAAC,WAAU,SAAS,QAAAC,aAAY;AACxC,SAAS,cAAc;;;ACNvB,SAAS,cAAAC,aAAY,WAAW,aAAa,gBAAAC,eAAc,eAAe,kBAAkB;AAC5F,SAAS,QAAAC,OAAM,gBAAgB;;;ACE/B,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAC9B,SAAS,YAAY,oBAAoB;AAMzC,SAAS,cAAoB;AAE3B,QAAM,gBAAgB;AAAA,IACpB,QAAQ,QAAQ,IAAI,WAAW,IAAI,MAAM;AAAA,IACzC,QAAQ,QAAQ,GAAG,WAAW,MAAM;AAAA,EACtC;AAEA,aAAW,WAAW,eAAe;AACnC,QAAI,WAAW,OAAO,GAAG;AACvB,UAAI;AACF,cAAM,UAAU,aAAa,SAAS,OAAO;AAC7C,mBAAW,QAAQ,QAAQ,MAAM,IAAI,GAAG;AACtC,gBAAM,UAAU,KAAK,KAAK;AAE1B,cAAI,CAAC,WAAW,QAAQ,WAAW,GAAG,EAAG;AAEzC,gBAAM,UAAU,QAA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AClB,gBAAQ,MAAM,6BAA6B,SAAS,EAAE;AAAA,MACxD;AAAA,IACF;AAUA,QAAI,SAAS,UAAU,YAAY;AACjC,YAAM,YAAY;AAAA,QAChB;AAAA,QACA,6CAA6C,WAAW,MAAM,YAAY;AAAA,QAC1E;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,EAAE,KAAK,IAAI;AAEX,UAAI;AACF,cAAM,YAAYD,MAAK,OAAO,GAAG,qBAAqB,UAAU,UAAU,MAAM;AAChF,QAAAE,eAAc,WAAW,WAAW,OAAO;AAC3C,gBAAQ,MAAM,0BAA0B,SAAS,KAAK,UAAU,MAAM,SAAS;AAAA,MACjF,SAAS,KAAK;AACZ,gBAAQ,MAAM,8BAA8B,GAAG,EAAE;AAAA,MACnD;AAAA,IACF;AAAA,EACF;AAGA,QAAM,cAAc,aAAa,IAC7B,gBAAgB,KAAK,MAAM,aAAa,GAAI,CAAC,aAC7C;AACJ,QAAM,qBAAqB,WAAW;AAEtC,UAAQ,KAAK,CAAC;AAChB;AAEA,KAAK,EAAE,MAAM,MAAM;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;",
|
|
6
|
-
"names": ["readFileSync", "writeFileSync", "basename", "join", "existsSync", "readFileSync", "join", "join", "existsSync", "homedir", "join", "existsSync", "readFileSync", "resolve", "existsSync", "
|
|
4
|
+
"sourcesContent": ["#!/usr/bin/env node\n/**\n * PreCompact Hook - Triggered before context compression\n *\n * Three critical jobs:\n * 1. Save rich checkpoint to session note \u2014 work items, state, meaningful rename\n * 2. Update TODO.md with a proper ## Continue section for the next session\n * 3. Save session state to temp file for post-compact injection via SessionStart(compact)\n *\n * This hook now mirrors \"pause session\" behavior: the session note gets a\n * descriptive name, rich content, and TODO.md gets a continuation prompt.\n */\n\nimport { readFileSync, writeFileSync } from 'fs';\nimport { basename, dirname, join } from 'path';\nimport { tmpdir } from 'os';\nimport {\n sendNtfyNotification,\n getCurrentNotePath,\n createSessionNote,\n appendCheckpoint,\n addWorkToSessionNote,\n findNotesDir,\n renameSessionNote,\n updateTodoContinue,\n calculateSessionTokens,\n WorkItem,\n} from '../lib/project-utils';\n\ninterface HookInput {\n session_id: string;\n transcript_path: string;\n cwd?: string;\n hook_event_name: string;\n compact_type?: string;\n trigger?: string;\n}\n\n/** Structured data extracted from a transcript in a single pass. */\ninterface TranscriptData {\n userMessages: string[];\n summaries: string[];\n captures: string[];\n lastCompleted: string;\n filesModified: string[];\n workItems: WorkItem[];\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Turn Claude content (string or content block array) into plain text. */\nfunction contentToText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n return content\n .map((c) => {\n if (typeof c === 'string') return c;\n if (c?.text) return c.text;\n if (c?.content) return String(c.content);\n return '';\n })\n .join(' ')\n .trim();\n }\n return '';\n}\n\nfunction getTranscriptStats(transcriptPath: string): { messageCount: number; isLarge: boolean } {\n try {\n const content = readFileSync(transcriptPath, 'utf-8');\n const lines = content.trim().split('\\n');\n let userMessages = 0;\n let assistantMessages = 0;\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const entry = JSON.parse(line);\n if (entry.type === 'user') userMessages++;\n else if (entry.type === 'assistant') assistantMessages++;\n } catch { /* skip */ }\n }\n const totalMessages = userMessages + assistantMessages;\n return { messageCount: totalMessages, isLarge: totalMessages > 50 };\n } catch {\n return { messageCount: 0, isLarge: false };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Unified transcript parser \u2014 single pass extracts everything\n// ---------------------------------------------------------------------------\n\nfunction parseTranscript(transcriptPath: string): TranscriptData {\n const data: TranscriptData = {\n userMessages: [],\n summaries: [],\n captures: [],\n lastCompleted: '',\n filesModified: [],\n workItems: [],\n };\n\n try {\n const raw = readFileSync(transcriptPath, 'utf-8');\n const lines = raw.trim().split('\\n');\n const seenSummaries = new Set<string>();\n\n for (const line of lines) {\n if (!line.trim()) continue;\n let entry: any;\n try { entry = JSON.parse(line); } catch { continue; }\n\n // --- User messages ---\n if (entry.type === 'user' && entry.message?.content) {\n const text = contentToText(entry.message.content).slice(0, 300);\n if (text) data.userMessages.push(text);\n }\n\n // --- Assistant content ---\n if (entry.type === 'assistant' && entry.message?.content) {\n const text = contentToText(entry.message.content);\n\n // Summaries \u2192 also create work items\n const summaryMatch = text.match(/SUMMARY:\\s*(.+?)(?:\\n|$)/i);\n if (summaryMatch) {\n const s = summaryMatch[1].trim();\n if (s.length > 5 && !data.summaries.includes(s)) {\n data.summaries.push(s);\n if (!seenSummaries.has(s)) {\n seenSummaries.add(s);\n const details: string[] = [];\n const actionsMatch = text.match(/ACTIONS:\\s*(.+?)(?=\\n[A-Z]+:|$)/is);\n if (actionsMatch) {\n const actionLines = actionsMatch[1].split('\\n')\n .map(l => l.replace(/^[-*\u2022]\\s*/, '').replace(/^\\d+\\.\\s*/, '').trim())\n .filter(l => l.length > 3 && l.length < 100);\n details.push(...actionLines.slice(0, 3));\n }\n data.workItems.push({ title: s, details: details.length > 0 ? details : undefined, completed: true });\n }\n }\n }\n\n // Captures\n const captureMatch = text.match(/CAPTURE:\\s*(.+?)(?:\\n|$)/i);\n if (captureMatch) {\n const c = captureMatch[1].trim();\n if (c.length > 5 && !data.captures.includes(c)) data.captures.push(c);\n }\n\n // Completed\n const completedMatch = text.match(/COMPLETED:\\s*(.+?)(?:\\n|$)/i);\n if (completedMatch) {\n data.lastCompleted = completedMatch[1].trim().replace(/\\*+/g, '');\n if (data.workItems.length === 0 && !seenSummaries.has(data.lastCompleted) && data.lastCompleted.length > 5) {\n seenSummaries.add(data.lastCompleted);\n data.workItems.push({ title: data.lastCompleted, completed: true });\n }\n }\n\n // File modifications (from tool_use blocks)\n if (Array.isArray(entry.message.content)) {\n for (const block of entry.message.content) {\n if (block.type === 'tool_use') {\n const tool = block.name;\n if ((tool === 'Edit' || tool === 'Write') && block.input?.file_path) {\n if (!data.filesModified.includes(block.input.file_path)) {\n data.filesModified.push(block.input.file_path);\n }\n }\n }\n }\n }\n }\n }\n } catch (err) {\n console.error(`parseTranscript error: ${err}`);\n }\n\n return data;\n}\n\n// ---------------------------------------------------------------------------\n// Format session state as human-readable string\n// ---------------------------------------------------------------------------\n\nfunction formatSessionState(data: TranscriptData, cwd?: string): string | null {\n const parts: string[] = [];\n\n if (cwd) parts.push(`Working directory: ${cwd}`);\n\n const recentUser = data.userMessages.slice(-3);\n if (recentUser.length > 0) {\n parts.push('\\nRecent user requests:');\n for (const msg of recentUser) {\n parts.push(`- ${msg.split('\\n')[0].slice(0, 200)}`);\n }\n }\n\n const recentSummaries = data.summaries.slice(-3);\n if (recentSummaries.length > 0) {\n parts.push('\\nWork summaries:');\n for (const s of recentSummaries) parts.push(`- ${s.slice(0, 150)}`);\n }\n\n const recentCaptures = data.captures.slice(-5);\n if (recentCaptures.length > 0) {\n parts.push('\\nCaptured context:');\n for (const c of recentCaptures) parts.push(`- ${c.slice(0, 150)}`);\n }\n\n const files = data.filesModified.slice(-10);\n if (files.length > 0) {\n parts.push('\\nFiles modified this session:');\n for (const f of files) parts.push(`- ${f}`);\n }\n\n if (data.lastCompleted) {\n parts.push(`\\nLast completed: ${data.lastCompleted.slice(0, 150)}`);\n }\n\n const result = parts.join('\\n');\n return result.length > 50 ? result : null;\n}\n\n// ---------------------------------------------------------------------------\n// Derive a meaningful title for the session note\n// ---------------------------------------------------------------------------\n\nfunction deriveTitle(data: TranscriptData): string {\n let title = '';\n\n // 1. Last work item title (most descriptive of what was accomplished)\n if (data.workItems.length > 0) {\n title = data.workItems[data.workItems.length - 1].title;\n }\n // 2. Last summary\n else if (data.summaries.length > 0) {\n title = data.summaries[data.summaries.length - 1];\n }\n // 3. Last completed marker\n else if (data.lastCompleted && data.lastCompleted.length > 5) {\n title = data.lastCompleted;\n }\n // 4. Last substantive user message\n else if (data.userMessages.length > 0) {\n for (let i = data.userMessages.length - 1; i >= 0; i--) {\n const msg = data.userMessages[i].split('\\n')[0].trim();\n if (msg.length > 10 && msg.length < 80 &&\n !msg.toLowerCase().startsWith('yes') &&\n !msg.toLowerCase().startsWith('ok')) {\n title = msg;\n break;\n }\n }\n }\n // 5. Derive from files modified\n if (!title && data.filesModified.length > 0) {\n const basenames = data.filesModified.slice(-5).map(f => {\n const b = basename(f);\n return b.replace(/\\.[^.]+$/, '');\n });\n const unique = [...new Set(basenames)];\n title = unique.length <= 3\n ? `Updated ${unique.join(', ')}`\n : `Modified ${data.filesModified.length} files`;\n }\n\n // Clean up for filename use\n return title\n .replace(/[^\\w\\s-]/g, ' ') // Remove special chars\n .replace(/\\s+/g, ' ') // Normalize whitespace\n .trim()\n .substring(0, 60);\n}\n\n// ---------------------------------------------------------------------------\n// Main\n// ---------------------------------------------------------------------------\n\nasync function main() {\n let hookInput: HookInput | null = null;\n\n try {\n const decoder = new TextDecoder();\n let input = '';\n const timeoutPromise = new Promise<void>((resolve) => { setTimeout(resolve, 500); });\n const readPromise = (async () => {\n for await (const chunk of process.stdin) {\n input += decoder.decode(chunk, { stream: true });\n }\n })();\n await Promise.race([readPromise, timeoutPromise]);\n if (input.trim()) {\n hookInput = JSON.parse(input) as HookInput;\n }\n } catch {\n // Silently handle input errors\n }\n\n const compactType = hookInput?.compact_type || hookInput?.trigger || 'auto';\n let tokenCount = 0;\n\n if (hookInput?.transcript_path) {\n const stats = getTranscriptStats(hookInput.transcript_path);\n tokenCount = calculateSessionTokens(hookInput.transcript_path);\n const tokenDisplay = tokenCount > 1000\n ? `${Math.round(tokenCount / 1000)}k`\n : String(tokenCount);\n\n // -----------------------------------------------------------------\n // Single-pass transcript parsing\n // -----------------------------------------------------------------\n const data = parseTranscript(hookInput.transcript_path);\n const state = formatSessionState(data, hookInput.cwd);\n\n // -----------------------------------------------------------------\n // Persist session state to numbered session note (like \"pause session\")\n // -----------------------------------------------------------------\n let notePath: string | null = null;\n\n try {\n const notesInfo = hookInput.cwd\n ? findNotesDir(hookInput.cwd)\n : { path: join(dirname(hookInput.transcript_path), 'Notes'), isLocal: false };\n notePath = getCurrentNotePath(notesInfo.path);\n\n // If no note found, or the latest note is completed, create a new one\n if (!notePath) {\n console.error('No session note found \u2014 creating one for checkpoint');\n notePath = createSessionNote(notesInfo.path, 'Recovered Session');\n } else {\n try {\n const noteContent = readFileSync(notePath, 'utf-8');\n if (noteContent.includes('**Status:** Completed') || noteContent.includes('**Completed:**')) {\n console.error(`Latest note is completed (${basename(notePath)}) \u2014 creating new one`);\n notePath = createSessionNote(notesInfo.path, 'Continued Session');\n }\n } catch { /* proceed with existing note */ }\n }\n\n // 1. Write rich checkpoint with full session state\n const checkpointBody = state\n ? `Context compression triggered at ~${tokenDisplay} tokens with ${stats.messageCount} messages.\\n\\n${state}`\n : `Context compression triggered at ~${tokenDisplay} tokens with ${stats.messageCount} messages.`;\n appendCheckpoint(notePath, checkpointBody);\n\n // 2. Write work items to \"Work Done\" section\n if (data.workItems.length > 0) {\n addWorkToSessionNote(notePath, data.workItems, `Pre-Compact (~${tokenDisplay} tokens)`);\n console.error(`Added ${data.workItems.length} work item(s) to session note`);\n }\n\n // 3. Rename session note with a meaningful title (instead of \"New Session\")\n const title = deriveTitle(data);\n if (title) {\n const newPath = renameSessionNote(notePath, title);\n if (newPath !== notePath) {\n // Update H1 title inside the note to match\n try {\n let noteContent = readFileSync(newPath, 'utf-8');\n noteContent = noteContent.replace(\n /^(# Session \\d+:)\\s*.*$/m,\n `$1 ${title}`\n );\n writeFileSync(newPath, noteContent);\n console.error(`Updated note H1 to match rename`);\n } catch { /* ignore */ }\n notePath = newPath;\n }\n }\n\n console.error(`Rich checkpoint saved: ${basename(notePath)}`);\n } catch (noteError) {\n console.error(`Could not save checkpoint: ${noteError}`);\n }\n\n // -----------------------------------------------------------------\n // Update TODO.md with proper ## Continue section (like \"pause session\")\n // -----------------------------------------------------------------\n if (hookInput.cwd && notePath) {\n try {\n const noteFilename = basename(notePath);\n updateTodoContinue(hookInput.cwd, noteFilename, state, tokenDisplay);\n console.error('TODO.md ## Continue section updated');\n } catch (todoError) {\n console.error(`Could not update TODO.md: ${todoError}`);\n }\n }\n\n // -----------------------------------------------------------------------\n // Save session state to temp file for post-compact injection.\n //\n // PreCompact hooks have NO stdout support (Claude Code ignores it).\n // Instead, we write the injection payload to a temp file keyed by\n // session_id. The SessionStart(compact) hook reads it and outputs\n // to stdout, which IS injected into the post-compaction context.\n // -----------------------------------------------------------------------\n if (state && hookInput.session_id) {\n const injection = [\n '<system-reminder>',\n `SESSION STATE RECOVERED AFTER COMPACTION (${compactType}, ~${tokenDisplay} tokens)`,\n '',\n state,\n '',\n 'IMPORTANT: This session state was captured before context compaction.',\n 'Use it to maintain continuity. Continue the conversation from where',\n 'it left off without asking the user to repeat themselves.',\n 'Continue with the last task that you were asked to work on.',\n '</system-reminder>',\n ].join('\\n');\n\n try {\n const stateFile = join(tmpdir(), `pai-compact-state-${hookInput.session_id}.txt`);\n writeFileSync(stateFile, injection, 'utf-8');\n console.error(`Session state saved to ${stateFile} (${injection.length} chars)`);\n } catch (err) {\n console.error(`Failed to save state file: ${err}`);\n }\n }\n }\n\n // Send ntfy.sh notification\n const ntfyMessage = tokenCount > 0\n ? `Auto-pause: ~${Math.round(tokenCount / 1000)}k tokens`\n : 'Context compressing';\n await sendNtfyNotification(ntfyMessage);\n\n process.exit(0);\n}\n\nmain().catch(() => {\n process.exit(0);\n});\n", "/**\n * project-utils.ts - Shared utilities for project context management\n *\n * Provides:\n * - Path encoding (matching Claude Code's scheme)\n * - ntfy.sh notifications (mandatory, synchronous)\n * - Session notes management\n * - Session token calculation\n */\n\nimport { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, renameSync } from 'fs';\nimport { join, basename } from 'path';\n\n// Import from pai-paths which handles .env loading and path resolution\nimport { PAI_DIR } from './pai-paths.js';\n\n// Re-export PAI_DIR for consumers\nexport { PAI_DIR };\nexport const PROJECTS_DIR = join(PAI_DIR, 'projects');\n\n/**\n * Encode a path the same way Claude Code does:\n * - Replace / with -\n * - Replace . with - (hidden directories become --name)\n *\n * This matches Claude Code's internal encoding to ensure Notes\n * are stored in the same project directory as transcripts.\n */\nexport function encodePath(path: string): string {\n return path\n .replace(/\\//g, '-') // Slashes become dashes\n .replace(/\\./g, '-') // Dots also become dashes\n .replace(/ /g, '-'); // Spaces become dashes (matches Claude Code native encoding)\n}\n\n/**\n * Get the project directory for a given working directory\n */\nexport function getProjectDir(cwd: string): string {\n const encoded = encodePath(cwd);\n return join(PROJECTS_DIR, encoded);\n}\n\n/**\n * Get the Notes directory for a project (central location)\n */\nexport function getNotesDir(cwd: string): string {\n return join(getProjectDir(cwd), 'Notes');\n}\n\n/**\n * Find Notes directory - check local first, fallback to central\n * DOES NOT create the directory - just finds the right location\n *\n * Logic:\n * - If cwd itself IS a Notes directory \u2192 use it directly\n * - If local Notes/ exists \u2192 use it (can be checked into git)\n * - Otherwise \u2192 use central ~/.claude/projects/.../Notes/\n */\nexport function findNotesDir(cwd: string): { path: string; isLocal: boolean } {\n // FIRST: Check if cwd itself IS a Notes directory\n const cwdBasename = basename(cwd).toLowerCase();\n if (cwdBasename === 'notes' && existsSync(cwd)) {\n return { path: cwd, isLocal: true };\n }\n\n // Check local locations\n const localPaths = [\n join(cwd, 'Notes'),\n join(cwd, 'notes'),\n join(cwd, '.claude', 'Notes')\n ];\n\n for (const path of localPaths) {\n if (existsSync(path)) {\n return { path, isLocal: true };\n }\n }\n\n // Fallback to central location\n return { path: getNotesDir(cwd), isLocal: false };\n}\n\n/**\n * Get the Sessions directory for a project (stores .jsonl transcripts)\n */\nexport function getSessionsDir(cwd: string): string {\n return join(getProjectDir(cwd), 'sessions');\n}\n\n/**\n * Get the Sessions directory from a project directory path\n */\nexport function getSessionsDirFromProjectDir(projectDir: string): string {\n return join(projectDir, 'sessions');\n}\n\n/**\n * Check if WhatsApp (Whazaa) is configured as an enabled MCP server.\n *\n * Uses standard Claude Code config at ~/.claude/settings.json.\n * No PAI dependency \u2014 works for any Claude Code user with whazaa installed.\n */\nexport function isWhatsAppEnabled(): boolean {\n try {\n const { homedir } = require('os');\n const settingsPath = join(homedir(), '.claude', 'settings.json');\n if (!existsSync(settingsPath)) return false;\n\n const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n const enabled: string[] = settings.enabledMcpjsonServers || [];\n return enabled.includes('whazaa');\n } catch {\n return false;\n }\n}\n\n/**\n * Send push notification \u2014 WhatsApp-aware with ntfy fallback.\n *\n * When WhatsApp (Whazaa) is enabled in MCP config, ntfy is SKIPPED\n * because the AI sends WhatsApp messages directly via MCP. Sending both\n * would cause duplicate notifications.\n *\n * When WhatsApp is NOT configured, ntfy fires as the fallback channel.\n */\nexport async function sendNtfyNotification(message: string, retries = 2): Promise<boolean> {\n // Skip ntfy when WhatsApp is configured \u2014 the AI handles notifications via MCP\n if (isWhatsAppEnabled()) {\n console.error(`WhatsApp (Whazaa) enabled in MCP config \u2014 skipping ntfy`);\n return true;\n }\n\n const topic = process.env.NTFY_TOPIC;\n\n if (!topic) {\n console.error('NTFY_TOPIC not set and WhatsApp not active \u2014 notifications disabled');\n return false;\n }\n\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n const response = await fetch(`https://ntfy.sh/${topic}`, {\n method: 'POST',\n body: message,\n headers: {\n 'Title': 'Claude Code',\n 'Priority': 'default'\n }\n });\n\n if (response.ok) {\n console.error(`ntfy.sh notification sent (WhatsApp inactive): \"${message}\"`);\n return true;\n } else {\n console.error(`ntfy.sh attempt ${attempt + 1} failed: ${response.status}`);\n }\n } catch (error) {\n console.error(`ntfy.sh attempt ${attempt + 1} error: ${error}`);\n }\n\n // Wait before retry\n if (attempt < retries) {\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n }\n\n console.error('ntfy.sh notification failed after all retries');\n return false;\n}\n\n/**\n * Ensure the Notes directory exists for a project\n * DEPRECATED: Use ensureNotesDirSmart() instead\n */\nexport function ensureNotesDir(cwd: string): string {\n const notesDir = getNotesDir(cwd);\n\n if (!existsSync(notesDir)) {\n mkdirSync(notesDir, { recursive: true });\n console.error(`Created Notes directory: ${notesDir}`);\n }\n\n return notesDir;\n}\n\n/**\n * Smart Notes directory handling:\n * - If local Notes/ exists \u2192 use it (don't create anything new)\n * - If no local Notes/ \u2192 ensure central exists and use that\n *\n * This respects the user's choice:\n * - Projects with local Notes/ keep notes there (git-trackable)\n * - Other directories don't get cluttered with auto-created Notes/\n */\nexport function ensureNotesDirSmart(cwd: string): { path: string; isLocal: boolean } {\n const found = findNotesDir(cwd);\n\n if (found.isLocal) {\n // Local Notes/ exists - use it as-is\n return found;\n }\n\n // No local Notes/ - ensure central exists\n if (!existsSync(found.path)) {\n mkdirSync(found.path, { recursive: true });\n console.error(`Created central Notes directory: ${found.path}`);\n }\n\n return found;\n}\n\n/**\n * Ensure the Sessions directory exists for a project\n */\nexport function ensureSessionsDir(cwd: string): string {\n const sessionsDir = getSessionsDir(cwd);\n\n if (!existsSync(sessionsDir)) {\n mkdirSync(sessionsDir, { recursive: true });\n console.error(`Created sessions directory: ${sessionsDir}`);\n }\n\n return sessionsDir;\n}\n\n/**\n * Ensure the Sessions directory exists (from project dir path)\n */\nexport function ensureSessionsDirFromProjectDir(projectDir: string): string {\n const sessionsDir = getSessionsDirFromProjectDir(projectDir);\n\n if (!existsSync(sessionsDir)) {\n mkdirSync(sessionsDir, { recursive: true });\n console.error(`Created sessions directory: ${sessionsDir}`);\n }\n\n return sessionsDir;\n}\n\n/**\n * Move all .jsonl session files from project root to sessions/ subdirectory\n * @param projectDir - The project directory path\n * @param excludeFile - Optional filename to exclude (e.g., current active session)\n * @param silent - If true, suppress console output\n * Returns the number of files moved\n */\nexport function moveSessionFilesToSessionsDir(\n projectDir: string,\n excludeFile?: string,\n silent: boolean = false\n): number {\n const sessionsDir = ensureSessionsDirFromProjectDir(projectDir);\n\n if (!existsSync(projectDir)) {\n return 0;\n }\n\n const files = readdirSync(projectDir);\n let movedCount = 0;\n\n for (const file of files) {\n // Match session files: uuid.jsonl or agent-*.jsonl\n // Skip the excluded file (typically the current active session)\n if (file.endsWith('.jsonl') && file !== excludeFile) {\n const sourcePath = join(projectDir, file);\n const destPath = join(sessionsDir, file);\n\n try {\n renameSync(sourcePath, destPath);\n if (!silent) {\n console.error(`Moved ${file} \u2192 sessions/`);\n }\n movedCount++;\n } catch (error) {\n if (!silent) {\n console.error(`Could not move ${file}: ${error}`);\n }\n }\n }\n }\n\n return movedCount;\n}\n\n/**\n * Get the YYYY/MM subdirectory for the current month inside notesDir.\n * Creates the directory if it doesn't exist.\n */\nfunction getMonthDir(notesDir: string): string {\n const now = new Date();\n const year = String(now.getFullYear());\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const monthDir = join(notesDir, year, month);\n if (!existsSync(monthDir)) {\n mkdirSync(monthDir, { recursive: true });\n }\n return monthDir;\n}\n\n/**\n * Get the next note number (4-digit format: 0001, 0002, etc.)\n * ALWAYS uses 4-digit format with space-dash-space separators\n * Format: NNNN - YYYY-MM-DD - Description.md\n * Numbers reset per month (each YYYY/MM directory has its own sequence).\n */\nexport function getNextNoteNumber(notesDir: string): string {\n const monthDir = getMonthDir(notesDir);\n\n // Match CORRECT format: \"0001 - \" (4-digit with space-dash-space)\n // Also match legacy formats for backwards compatibility when detecting max number\n const files = readdirSync(monthDir)\n .filter(f => f.match(/^\\d{3,4}[\\s_-]/)) // Starts with 3-4 digits followed by separator\n .filter(f => f.endsWith('.md'))\n .sort();\n\n if (files.length === 0) {\n return '0001'; // Default to 4-digit\n }\n\n // Find the highest number across all formats\n let maxNumber = 0;\n for (const file of files) {\n const digitMatch = file.match(/^(\\d+)/);\n if (digitMatch) {\n const num = parseInt(digitMatch[1], 10);\n if (num > maxNumber) maxNumber = num;\n }\n }\n\n // ALWAYS return 4-digit format\n return String(maxNumber + 1).padStart(4, '0');\n}\n\n/**\n * Get the current (latest) note file path, or null if none exists.\n * Searches in the current month's YYYY/MM subdirectory first,\n * then falls back to previous month (for sessions spanning month boundaries),\n * then falls back to flat notesDir for legacy notes.\n * Supports multiple formats for backwards compatibility:\n * - CORRECT: \"0001 - YYYY-MM-DD - Description.md\" (space-dash-space)\n * - Legacy: \"001_YYYY-MM-DD_description.md\" (underscores)\n */\nexport function getCurrentNotePath(notesDir: string): string | null {\n if (!existsSync(notesDir)) {\n return null;\n }\n\n // Helper: find latest session note in a directory\n const findLatestIn = (dir: string): string | null => {\n if (!existsSync(dir)) return null;\n const files = readdirSync(dir)\n .filter(f => f.match(/^\\d{3,4}[\\s_-].*\\.md$/))\n .sort((a, b) => {\n const numA = parseInt(a.match(/^(\\d+)/)?.[1] || '0', 10);\n const numB = parseInt(b.match(/^(\\d+)/)?.[1] || '0', 10);\n return numA - numB;\n });\n if (files.length === 0) return null;\n return join(dir, files[files.length - 1]);\n };\n\n // 1. Check current month's YYYY/MM directory\n const now = new Date();\n const year = String(now.getFullYear());\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const currentMonthDir = join(notesDir, year, month);\n const found = findLatestIn(currentMonthDir);\n if (found) return found;\n\n // 2. Check previous month (for sessions spanning month boundaries)\n const prevDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);\n const prevYear = String(prevDate.getFullYear());\n const prevMonth = String(prevDate.getMonth() + 1).padStart(2, '0');\n const prevMonthDir = join(notesDir, prevYear, prevMonth);\n const prevFound = findLatestIn(prevMonthDir);\n if (prevFound) return prevFound;\n\n // 3. Fallback: check flat notesDir (legacy notes not yet filed)\n return findLatestIn(notesDir);\n}\n\n/**\n * Create a new session note\n * CORRECT FORMAT: \"NNNN - YYYY-MM-DD - Description.md\"\n * - 4-digit zero-padded number\n * - Space-dash-space separators (NOT underscores)\n * - Title case description\n *\n * IMPORTANT: The initial description is just a PLACEHOLDER.\n * Claude MUST rename the file at session end with a meaningful description\n * based on the actual work done. Never leave it as \"New Session\" or project name.\n */\nexport function createSessionNote(notesDir: string, description: string): string {\n const noteNumber = getNextNoteNumber(notesDir);\n const date = new Date().toISOString().split('T')[0]; // YYYY-MM-DD\n\n // Use \"New Session\" as placeholder - Claude MUST rename at session end!\n // The project name alone is NOT descriptive enough.\n const safeDescription = 'New Session';\n\n // CORRECT FORMAT: space-dash-space separators, filed into YYYY/MM subdirectory\n const monthDir = getMonthDir(notesDir);\n const filename = `${noteNumber} - ${date} - ${safeDescription}.md`;\n const filepath = join(monthDir, filename);\n\n const content = `# Session ${noteNumber}: ${description}\n\n**Date:** ${date}\n**Status:** In Progress\n\n---\n\n## Work Done\n\n<!-- PAI will add completed work here during session -->\n\n---\n\n## Next Steps\n\n<!-- To be filled at session end -->\n\n---\n\n**Tags:** #Session\n`;\n\n writeFileSync(filepath, content);\n console.error(`Created session note: ${filename}`);\n\n return filepath;\n}\n\n/**\n * Append checkpoint to current session note\n */\nexport function appendCheckpoint(notePath: string, checkpoint: string): void {\n if (!existsSync(notePath)) {\n // Note vanished (cloud sync, cleanup, etc.) \u2014 recreate it\n console.error(`Note file not found, recreating: ${notePath}`);\n try {\n const parentDir = join(notePath, '..');\n if (!existsSync(parentDir)) {\n mkdirSync(parentDir, { recursive: true });\n }\n const noteFilename = basename(notePath);\n const numberMatch = noteFilename.match(/^(\\d+)/);\n const noteNumber = numberMatch ? numberMatch[1] : '0000';\n const date = new Date().toISOString().split('T')[0];\n const content = `# Session ${noteNumber}: Recovered\\n\\n**Date:** ${date}\\n**Status:** In Progress\\n\\n---\\n\\n## Work Done\\n\\n<!-- PAI will add completed work here during session -->\\n\\n---\\n\\n## Next Steps\\n\\n<!-- To be filled at session end -->\\n\\n---\\n\\n**Tags:** #Session\\n`;\n writeFileSync(notePath, content);\n console.error(`Recreated session note: ${noteFilename}`);\n } catch (err) {\n console.error(`Failed to recreate note: ${err}`);\n return;\n }\n }\n\n const content = readFileSync(notePath, 'utf-8');\n const timestamp = new Date().toISOString();\n const checkpointText = `\\n### Checkpoint ${timestamp}\\n\\n${checkpoint}\\n`;\n\n // Insert before \"## Next Steps\" if it exists, otherwise append\n const nextStepsIndex = content.indexOf('## Next Steps');\n let newContent: string;\n\n if (nextStepsIndex !== -1) {\n newContent = content.substring(0, nextStepsIndex) + checkpointText + content.substring(nextStepsIndex);\n } else {\n newContent = content + checkpointText;\n }\n\n writeFileSync(notePath, newContent);\n console.error(`Checkpoint added to: ${basename(notePath)}`);\n}\n\n/**\n * Work item for session notes\n */\nexport interface WorkItem {\n title: string;\n details?: string[];\n completed?: boolean;\n}\n\n/**\n * Add work items to the \"Work Done\" section of a session note\n * This is the main way to capture what was accomplished in a session\n */\nexport function addWorkToSessionNote(notePath: string, workItems: WorkItem[], sectionTitle?: string): void {\n if (!existsSync(notePath)) {\n console.error(`Note file not found: ${notePath}`);\n return;\n }\n\n let content = readFileSync(notePath, 'utf-8');\n\n // Build the work section content\n let workText = '';\n if (sectionTitle) {\n workText += `\\n### ${sectionTitle}\\n\\n`;\n }\n\n for (const item of workItems) {\n const checkbox = item.completed !== false ? '[x]' : '[ ]';\n workText += `- ${checkbox} **${item.title}**\\n`;\n if (item.details && item.details.length > 0) {\n for (const detail of item.details) {\n workText += ` - ${detail}\\n`;\n }\n }\n }\n\n // Find the Work Done section and insert after the comment/placeholder\n const workDoneMatch = content.match(/## Work Done\\n\\n(<!-- .*? -->)?/);\n if (workDoneMatch) {\n const insertPoint = content.indexOf(workDoneMatch[0]) + workDoneMatch[0].length;\n content = content.substring(0, insertPoint) + workText + content.substring(insertPoint);\n } else {\n // Fallback: insert before Next Steps\n const nextStepsIndex = content.indexOf('## Next Steps');\n if (nextStepsIndex !== -1) {\n content = content.substring(0, nextStepsIndex) + workText + '\\n' + content.substring(nextStepsIndex);\n }\n }\n\n writeFileSync(notePath, content);\n console.error(`Added ${workItems.length} work item(s) to: ${basename(notePath)}`);\n}\n\n/**\n * Update the session note title to be more descriptive\n * Called when we know what work was done\n */\nexport function updateSessionNoteTitle(notePath: string, newTitle: string): void {\n if (!existsSync(notePath)) {\n console.error(`Note file not found: ${notePath}`);\n return;\n }\n\n let content = readFileSync(notePath, 'utf-8');\n\n // Update the H1 title\n content = content.replace(/^# Session \\d+:.*$/m, (match) => {\n const sessionNum = match.match(/Session (\\d+)/)?.[1] || '';\n return `# Session ${sessionNum}: ${newTitle}`;\n });\n\n writeFileSync(notePath, content);\n\n // Also rename the file\n renameSessionNote(notePath, sanitizeForFilename(newTitle));\n}\n\n/**\n * Sanitize a string for use in a filename (exported for use elsewhere)\n */\nexport function sanitizeForFilename(str: string): string {\n return str\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, '') // Remove special chars\n .replace(/\\s+/g, '-') // Spaces to hyphens\n .replace(/-+/g, '-') // Collapse multiple hyphens\n .replace(/^-|-$/g, '') // Trim hyphens\n .substring(0, 50); // Limit length\n}\n\n/**\n * Extract a meaningful name from session note content\n * Looks at Work Done section and summary to generate a descriptive name\n */\nexport function extractMeaningfulName(noteContent: string, summary: string): string {\n // Try to extract from Work Done section headers (### headings)\n const workDoneMatch = noteContent.match(/## Work Done\\n\\n([\\s\\S]*?)(?=\\n---|\\n## Next)/);\n\n if (workDoneMatch) {\n const workDoneSection = workDoneMatch[1];\n\n // Look for ### subheadings which typically describe what was done\n const subheadings = workDoneSection.match(/### ([^\\n]+)/g);\n if (subheadings && subheadings.length > 0) {\n // Use the first subheading, clean it up\n const firstHeading = subheadings[0].replace('### ', '').trim();\n if (firstHeading.length > 5 && firstHeading.length < 60) {\n return sanitizeForFilename(firstHeading);\n }\n }\n\n // Look for bold text which often indicates key topics\n const boldMatches = workDoneSection.match(/\\*\\*([^*]+)\\*\\*/g);\n if (boldMatches && boldMatches.length > 0) {\n const firstBold = boldMatches[0].replace(/\\*\\*/g, '').trim();\n if (firstBold.length > 3 && firstBold.length < 50) {\n return sanitizeForFilename(firstBold);\n }\n }\n\n // Look for numbered list items (1. Something)\n const numberedItems = workDoneSection.match(/^\\d+\\.\\s+\\*\\*([^*]+)\\*\\*/m);\n if (numberedItems) {\n return sanitizeForFilename(numberedItems[1]);\n }\n }\n\n // Fall back to summary if provided\n if (summary && summary.length > 5 && summary !== 'Session completed.') {\n // Take first meaningful phrase from summary\n const cleanSummary = summary\n .replace(/[^\\w\\s-]/g, ' ')\n .trim()\n .split(/\\s+/)\n .slice(0, 5)\n .join(' ');\n\n if (cleanSummary.length > 3) {\n return sanitizeForFilename(cleanSummary);\n }\n }\n\n return '';\n}\n\n/**\n * Rename session note with a meaningful name\n * ALWAYS uses correct format: \"NNNN - YYYY-MM-DD - Description.md\"\n * Returns the new path, or original path if rename fails\n */\nexport function renameSessionNote(notePath: string, meaningfulName: string): string {\n if (!meaningfulName || !existsSync(notePath)) {\n return notePath;\n }\n\n const dir = join(notePath, '..');\n const oldFilename = basename(notePath);\n\n // Parse existing filename - support multiple formats:\n // CORRECT: \"0001 - 2026-01-02 - Description.md\"\n // Legacy: \"001_2026-01-02_description.md\"\n const correctMatch = oldFilename.match(/^(\\d{3,4}) - (\\d{4}-\\d{2}-\\d{2}) - .*\\.md$/);\n const legacyMatch = oldFilename.match(/^(\\d{3,4})_(\\d{4}-\\d{2}-\\d{2})_.*\\.md$/);\n\n const match = correctMatch || legacyMatch;\n if (!match) {\n return notePath; // Can't parse, don't rename\n }\n\n const [, noteNumber, date] = match;\n\n // Convert to Title Case\n const titleCaseName = meaningfulName\n .split(/[\\s_-]+/)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(' ')\n .trim();\n\n // ALWAYS use correct format with 4-digit number\n const paddedNumber = noteNumber.padStart(4, '0');\n const newFilename = `${paddedNumber} - ${date} - ${titleCaseName}.md`;\n const newPath = join(dir, newFilename);\n\n // Don't rename if name is the same\n if (newFilename === oldFilename) {\n return notePath;\n }\n\n try {\n renameSync(notePath, newPath);\n console.error(`Renamed note: ${oldFilename} \u2192 ${newFilename}`);\n return newPath;\n } catch (error) {\n console.error(`Could not rename note: ${error}`);\n return notePath;\n }\n}\n\n/**\n * Finalize session note (mark as complete, add summary, rename with meaningful name)\n * IDEMPOTENT: Will only finalize once, subsequent calls are no-ops\n * Returns the final path (may be renamed)\n */\nexport function finalizeSessionNote(notePath: string, summary: string): string {\n if (!existsSync(notePath)) {\n console.error(`Note file not found: ${notePath}`);\n return notePath;\n }\n\n let content = readFileSync(notePath, 'utf-8');\n\n // IDEMPOTENT CHECK: If already completed, don't modify again\n if (content.includes('**Status:** Completed')) {\n console.error(`Note already finalized: ${basename(notePath)}`);\n return notePath;\n }\n\n // Update status\n content = content.replace('**Status:** In Progress', '**Status:** Completed');\n\n // Add completion timestamp (only if not already present)\n if (!content.includes('**Completed:**')) {\n const completionTime = new Date().toISOString();\n content = content.replace(\n '---\\n\\n## Work Done',\n `**Completed:** ${completionTime}\\n\\n---\\n\\n## Work Done`\n );\n }\n\n // Add summary to Next Steps section (only if placeholder exists)\n const nextStepsMatch = content.match(/## Next Steps\\n\\n(<!-- .*? -->)/);\n if (nextStepsMatch) {\n content = content.replace(\n nextStepsMatch[0],\n `## Next Steps\\n\\n${summary || 'Session completed.'}`\n );\n }\n\n writeFileSync(notePath, content);\n console.error(`Session note finalized: ${basename(notePath)}`);\n\n // Extract meaningful name and rename the file\n const meaningfulName = extractMeaningfulName(content, summary);\n if (meaningfulName) {\n const newPath = renameSessionNote(notePath, meaningfulName);\n return newPath;\n }\n\n return notePath;\n}\n\n/**\n * Calculate total tokens from a session .jsonl file\n */\nexport function calculateSessionTokens(jsonlPath: string): number {\n if (!existsSync(jsonlPath)) {\n return 0;\n }\n\n try {\n const content = readFileSync(jsonlPath, 'utf-8');\n const lines = content.trim().split('\\n');\n let totalTokens = 0;\n\n for (const line of lines) {\n try {\n const entry = JSON.parse(line);\n if (entry.message?.usage) {\n const usage = entry.message.usage;\n totalTokens += (usage.input_tokens || 0);\n totalTokens += (usage.output_tokens || 0);\n totalTokens += (usage.cache_creation_input_tokens || 0);\n totalTokens += (usage.cache_read_input_tokens || 0);\n }\n } catch {\n // Skip invalid JSON lines\n }\n }\n\n return totalTokens;\n } catch (error) {\n console.error(`Error calculating tokens: ${error}`);\n return 0;\n }\n}\n\n/**\n * Find TODO.md - check local first, fallback to central\n */\nexport function findTodoPath(cwd: string): string {\n // Check local locations first\n const localPaths = [\n join(cwd, 'TODO.md'),\n join(cwd, 'notes', 'TODO.md'),\n join(cwd, 'Notes', 'TODO.md'),\n join(cwd, '.claude', 'TODO.md')\n ];\n\n for (const path of localPaths) {\n if (existsSync(path)) {\n return path;\n }\n }\n\n // Fallback to central location (inside Notes/)\n return join(getNotesDir(cwd), 'TODO.md');\n}\n\n/**\n * Find CLAUDE.md - check local locations\n * Returns the FIRST found path (for backwards compatibility)\n */\nexport function findClaudeMdPath(cwd: string): string | null {\n const paths = findAllClaudeMdPaths(cwd);\n return paths.length > 0 ? paths[0] : null;\n}\n\n/**\n * Find ALL CLAUDE.md files in local locations\n * Returns paths in priority order (most specific first):\n * 1. .claude/CLAUDE.md (project-specific config dir)\n * 2. CLAUDE.md (project root)\n * 3. Notes/CLAUDE.md (notes directory)\n * 4. Prompts/CLAUDE.md (prompts directory)\n *\n * All found files will be loaded and injected into context.\n */\nexport function findAllClaudeMdPaths(cwd: string): string[] {\n const foundPaths: string[] = [];\n\n // Priority order: most specific first\n const localPaths = [\n join(cwd, '.claude', 'CLAUDE.md'),\n join(cwd, 'CLAUDE.md'),\n join(cwd, 'Notes', 'CLAUDE.md'),\n join(cwd, 'notes', 'CLAUDE.md'),\n join(cwd, 'Prompts', 'CLAUDE.md'),\n join(cwd, 'prompts', 'CLAUDE.md')\n ];\n\n for (const path of localPaths) {\n if (existsSync(path)) {\n foundPaths.push(path);\n }\n }\n\n return foundPaths;\n}\n\n/**\n * Ensure TODO.md exists\n */\nexport function ensureTodoMd(cwd: string): string {\n const todoPath = findTodoPath(cwd);\n\n if (!existsSync(todoPath)) {\n // Ensure parent directory exists\n const parentDir = join(todoPath, '..');\n if (!existsSync(parentDir)) {\n mkdirSync(parentDir, { recursive: true });\n }\n\n const content = `# TODO\n\n## Current Session\n\n- [ ] (Tasks will be tracked here)\n\n## Backlog\n\n- [ ] (Future tasks)\n\n---\n\n*Last updated: ${new Date().toISOString()}*\n`;\n\n writeFileSync(todoPath, content);\n console.error(`Created TODO.md: ${todoPath}`);\n }\n\n return todoPath;\n}\n\n/**\n * Task item for TODO.md\n */\nexport interface TodoItem {\n content: string;\n completed: boolean;\n}\n\n/**\n * Update TODO.md with current session tasks\n * Preserves the Backlog section\n * Ensures only ONE timestamp line at the end\n */\nexport function updateTodoMd(cwd: string, tasks: TodoItem[], sessionSummary?: string): void {\n const todoPath = ensureTodoMd(cwd);\n const content = readFileSync(todoPath, 'utf-8');\n\n // Find Backlog section to preserve it (but strip any trailing timestamps/separators)\n const backlogMatch = content.match(/## Backlog[\\s\\S]*?(?=\\n---|\\n\\*Last updated|$)/);\n let backlogSection = backlogMatch ? backlogMatch[0].trim() : '## Backlog\\n\\n- [ ] (Future tasks)';\n\n // Format tasks\n const taskLines = tasks.length > 0\n ? tasks.map(t => `- [${t.completed ? 'x' : ' '}] ${t.content}`).join('\\n')\n : '- [ ] (No active tasks)';\n\n // Build new content with exactly ONE timestamp at the end\n const newContent = `# TODO\n\n## Current Session\n\n${taskLines}\n\n${sessionSummary ? `**Session Summary:** ${sessionSummary}\\n\\n` : ''}${backlogSection}\n\n---\n\n*Last updated: ${new Date().toISOString()}*\n`;\n\n writeFileSync(todoPath, newContent);\n console.error(`Updated TODO.md: ${todoPath}`);\n}\n\n/**\n * Add a checkpoint entry to TODO.md (without replacing tasks)\n * Ensures only ONE timestamp line at the end\n * Works regardless of TODO.md structure \u2014 appends if no known section found\n */\nexport function addTodoCheckpoint(cwd: string, checkpoint: string): void {\n const todoPath = ensureTodoMd(cwd);\n let content = readFileSync(todoPath, 'utf-8');\n\n // Remove ALL existing timestamp lines and trailing separators\n content = content.replace(/(\\n---\\s*)*(\\n\\*Last updated:.*\\*\\s*)+$/g, '');\n\n const checkpointText = `\\n**Checkpoint (${new Date().toISOString()}):** ${checkpoint}\\n\\n`;\n\n // Try to insert before Backlog section\n const backlogIndex = content.indexOf('## Backlog');\n if (backlogIndex !== -1) {\n content = content.substring(0, backlogIndex) + checkpointText + content.substring(backlogIndex);\n } else {\n // No Backlog section \u2014 try before Continue section, or just append\n const continueIndex = content.indexOf('## Continue');\n if (continueIndex !== -1) {\n // Insert after the Continue section (find the next ## or ---)\n const afterContinue = content.indexOf('\\n---', continueIndex);\n if (afterContinue !== -1) {\n const insertAt = afterContinue + 4; // after \\n---\n content = content.substring(0, insertAt) + '\\n' + checkpointText + content.substring(insertAt);\n } else {\n content = content.trimEnd() + '\\n' + checkpointText;\n }\n } else {\n // No known section \u2014 just append before the end\n content = content.trimEnd() + '\\n' + checkpointText;\n }\n }\n\n // Add exactly ONE timestamp at the end\n content = content.trimEnd() + `\\n\\n---\\n\\n*Last updated: ${new Date().toISOString()}*\\n`;\n\n writeFileSync(todoPath, content);\n console.error(`Checkpoint added to TODO.md`);\n}\n\n/**\n * Update the ## Continue section at the top of TODO.md.\n * This mirrors \"pause session\" behavior \u2014 gives the next session a starting point.\n * Replaces any existing ## Continue section.\n */\nexport function updateTodoContinue(\n cwd: string,\n noteFilename: string,\n state: string | null,\n tokenDisplay: string\n): void {\n const todoPath = ensureTodoMd(cwd);\n let content = readFileSync(todoPath, 'utf-8');\n\n // Remove existing ## Continue section (from ## Continue to the first standalone --- line)\n content = content.replace(/## Continue\\n[\\s\\S]*?\\n---\\n+/, '');\n\n const now = new Date().toISOString();\n const stateLines = state\n ? state.split('\\n').filter(l => l.trim()).slice(0, 10).map(l => `> ${l}`).join('\\n')\n : `> Check the latest session note for details.`;\n\n const continueSection = `## Continue\n\n> **Last session:** ${noteFilename.replace('.md', '')}\n> **Paused at:** ${now}\n>\n${stateLines}\n\n---\n\n`;\n\n // Remove leading whitespace from content\n content = content.replace(/^\\s+/, '');\n\n // If content starts with # title, insert after it\n const titleMatch = content.match(/^(# [^\\n]+\\n+)/);\n if (titleMatch) {\n content = titleMatch[1] + continueSection + content.substring(titleMatch[0].length);\n } else {\n content = continueSection + content;\n }\n\n // Clean up trailing timestamps and add fresh one\n content = content.replace(/(\\n---\\s*)*(\\n\\*Last updated:.*\\*\\s*)+$/g, '');\n content = content.trimEnd() + `\\n\\n---\\n\\n*Last updated: ${now}*\\n`;\n\n writeFileSync(todoPath, content);\n console.error('TODO.md ## Continue section updated');\n}\n", "/**\n * PAI Path Resolution - Single Source of Truth\n *\n * This module provides consistent path resolution across all PAI hooks.\n * It handles PAI_DIR detection whether set explicitly or defaulting to ~/.claude\n *\n * ALSO loads .env file from PAI_DIR so all hooks get environment variables\n * without relying on Claude Code's settings.json injection.\n *\n * Usage in hooks:\n * import { PAI_DIR, HOOKS_DIR, SKILLS_DIR } from './lib/pai-paths';\n */\n\nimport { homedir } from 'os';\nimport { resolve, join } from 'path';\nimport { existsSync, readFileSync } from 'fs';\n\n/**\n * Load .env file and inject into process.env\n * Must run BEFORE PAI_DIR resolution so .env can set PAI_DIR if needed\n */\nfunction loadEnvFile(): void {\n // Check common locations for .env\n const possiblePaths = [\n resolve(process.env.PAI_DIR || '', '.env'),\n resolve(homedir(), '.claude', '.env'),\n ];\n\n for (const envPath of possiblePaths) {\n if (existsSync(envPath)) {\n try {\n const content = readFileSync(envPath, 'utf-8');\n for (const line of content.split('\\n')) {\n const trimmed = line.trim();\n // Skip comments and empty lines\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n const eqIndex = trimmed.indexOf('=');\n if (eqIndex > 0) {\n const key = trimmed.substring(0, eqIndex).trim();\n let value = trimmed.substring(eqIndex + 1).trim();\n\n // Remove surrounding quotes if present\n if ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.slice(1, -1);\n }\n\n // Expand $HOME and ~ in values\n value = value.replace(/\\$HOME/g, homedir());\n value = value.replace(/^~(?=\\/|$)/, homedir());\n\n // Only set if not already defined (env vars take precedence)\n if (process.env[key] === undefined) {\n process.env[key] = value;\n }\n }\n }\n // Found and loaded, don't check other paths\n break;\n } catch {\n // Silently continue if .env can't be read\n }\n }\n }\n}\n\n// Load .env FIRST, before any other initialization\nloadEnvFile();\n\n/**\n * Smart PAI_DIR detection with fallback\n * Priority:\n * 1. PAI_DIR environment variable (if set)\n * 2. ~/.claude (standard location)\n */\nexport const PAI_DIR = process.env.PAI_DIR\n ? resolve(process.env.PAI_DIR)\n : resolve(homedir(), '.claude');\n\n/**\n * Common PAI directories\n */\nexport const HOOKS_DIR = join(PAI_DIR, 'Hooks');\nexport const SKILLS_DIR = join(PAI_DIR, 'Skills');\nexport const AGENTS_DIR = join(PAI_DIR, 'Agents');\nexport const HISTORY_DIR = join(PAI_DIR, 'History');\nexport const COMMANDS_DIR = join(PAI_DIR, 'Commands');\n\n/**\n * Validate PAI directory structure on first import\n * This fails fast with a clear error if PAI is misconfigured\n */\nfunction validatePAIStructure(): void {\n if (!existsSync(PAI_DIR)) {\n console.error(`PAI_DIR does not exist: ${PAI_DIR}`);\n console.error(` Expected ~/.claude or set PAI_DIR environment variable`);\n process.exit(1);\n }\n\n if (!existsSync(HOOKS_DIR)) {\n console.error(`PAI hooks directory not found: ${HOOKS_DIR}`);\n console.error(` Your PAI_DIR may be misconfigured`);\n console.error(` Current PAI_DIR: ${PAI_DIR}`);\n process.exit(1);\n }\n}\n\n// Run validation on module import\n// This ensures any hook that imports this module will fail fast if paths are wrong\nvalidatePAIStructure();\n\n/**\n * Helper to get history file path with date-based organization\n */\nexport function getHistoryFilePath(subdir: string, filename: string): string {\n const now = new Date();\n const tz = process.env.TIME_ZONE || Intl.DateTimeFormat().resolvedOptions().timeZone;\n const localDate = new Date(now.toLocaleString('en-US', { timeZone: tz }));\n const year = localDate.getFullYear();\n const month = String(localDate.getMonth() + 1).padStart(2, '0');\n\n return join(HISTORY_DIR, subdir, `${year}-${month}`, filename);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;AAaA,SAAS,gBAAAA,eAAc,iBAAAC,sBAAqB;AAC5C,SAAS,YAAAC,WAAU,SAAS,QAAAC,aAAY;AACxC,SAAS,cAAc;;;ACLvB,SAAS,cAAAC,aAAY,WAAW,aAAa,g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,UAAS,QAAQ;AACtC,2BAAmB,UAAU,KAAK,cAAc,OAAO,YAAY;AACnE,gBAAQ,MAAM,qCAAqC;AAAA,MACrD,SAAS,WAAW;AAClB,gBAAQ,MAAM,6BAA6B,SAAS,EAAE;AAAA,MACxD;AAAA,IACF;AAUA,QAAI,SAAS,UAAU,YAAY;AACjC,YAAM,YAAY;AAAA,QAChB;AAAA,QACA,6CAA6C,WAAW,MAAM,YAAY;AAAA,QAC1E;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,EAAE,KAAK,IAAI;AAEX,UAAI;AACF,cAAM,YAAYE,MAAK,OAAO,GAAG,qBAAqB,UAAU,UAAU,MAAM;AAChF,QAAAC,eAAc,WAAW,WAAW,OAAO;AAC3C,gBAAQ,MAAM,0BAA0B,SAAS,KAAK,UAAU,MAAM,SAAS;AAAA,MACjF,SAAS,KAAK;AACZ,gBAAQ,MAAM,8BAA8B,GAAG,EAAE;AAAA,MACnD;AAAA,IACF;AAAA,EACF;AAGA,QAAM,cAAc,aAAa,IAC7B,gBAAgB,KAAK,MAAM,aAAa,GAAI,CAAC,aAC7C;AACJ,QAAM,qBAAqB,WAAW;AAEtC,UAAQ,KAAK,CAAC;AAChB;AAEA,KAAK,EAAE,MAAM,MAAM;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;",
|
|
6
|
+
"names": ["readFileSync", "writeFileSync", "basename", "join", "existsSync", "readFileSync", "join", "join", "existsSync", "homedir", "join", "existsSync", "readFileSync", "resolve", "join", "existsSync", "content", "readFileSync", "existsSync", "join", "existsSync", "readFileSync", "join", "existsSync", "join", "readFileSync", "readFileSync", "basename", "resolve", "join", "writeFileSync"]
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/hooks/ts/session-start/initialize-session.ts", "../../src/hooks/ts/lib/pai-paths.ts", "../../src/hooks/ts/lib/project-utils.ts"],
|
|
4
|
-
"sourcesContent": ["#!/usr/bin/env node\n\n/**\n * initialize-session.ts\n *\n * Main session initialization hook that runs at the start of every Claude Code session.\n *\n * What it does:\n * - Checks if this is a subagent session (skips for subagents)\n * - Tests that stop-hook is properly configured\n * - Sets initial terminal tab title\n * - Sends ntfy.sh notification for global PAI system initialization\n *\n * Setup:\n * 1. Set environment variables in settings.json:\n * - DA: Your AI's name (e.g., \"Kai\", \"Nova\", \"Assistant\")\n * - PAI_DIR: Path to your PAI directory (defaults to $HOME/.claude)\n * 2. Ensure load-core-context.ts exists in hooks/session-start/ directory\n * 3. Add all three SessionStart hooks to settings.json in this order:\n * initialize-session.ts, load-core-context.ts, load-project-context.ts\n */\n\nimport { existsSync, statSync, readFileSync, writeFileSync } from 'fs';\nimport { join } from 'path';\nimport { tmpdir } from 'os';\nimport { PAI_DIR } from '../lib/pai-paths';\nimport { sendNtfyNotification, isWhatsAppEnabled } from '../lib/project-utils';\n\n// Debounce duration in milliseconds (prevents duplicate SessionStart events)\nconst DEBOUNCE_MS = 2000;\nconst LOCKFILE = join(tmpdir(), 'pai-session-start.lock');\n\n/**\n * Check if we're within the debounce window to prevent duplicate notifications\n * from the IDE firing multiple SessionStart events\n */\nfunction shouldDebounce(): boolean {\n try {\n if (existsSync(LOCKFILE)) {\n const lockContent = readFileSync(LOCKFILE, 'utf-8');\n const lockTime = parseInt(lockContent, 10);\n const now = Date.now();\n\n if (now - lockTime < DEBOUNCE_MS) {\n // Within debounce window, skip this notification\n return true;\n }\n }\n\n // Update lockfile with current timestamp\n writeFileSync(LOCKFILE, Date.now().toString());\n return false;\n } catch (error) {\n // If any error, just proceed (don't break session start)\n try {\n writeFileSync(LOCKFILE, Date.now().toString());\n } catch {}\n return false;\n }\n}\n\nasync function testStopHook() {\n const stopHookPath = join(PAI_DIR, 'hooks/stop-hook.ts');\n\n console.error('\\nTesting stop-hook configuration...');\n\n // Check if stop-hook exists\n if (!existsSync(stopHookPath)) {\n console.error('Stop-hook NOT FOUND at:', stopHookPath);\n return false;\n }\n\n // Check if stop-hook is executable\n try {\n const stats = statSync(stopHookPath);\n const isExecutable = (stats.mode & 0o111) !== 0;\n\n if (!isExecutable) {\n console.error('Stop-hook exists but is NOT EXECUTABLE');\n return false;\n }\n\n console.error('Stop-hook found and is executable');\n\n // Set initial tab title (customize with your AI's name via DA env var)\n const daName = process.env.DA || 'AI Assistant';\n const tabTitle = `${daName} Ready`;\n\n process.stderr.write(`\\x1b]0;${tabTitle}\\x07`);\n process.stderr.write(`\\x1b]2;${tabTitle}\\x07`);\n process.stderr.write(`\\x1b]30;${tabTitle}\\x07`);\n console.error(`Set initial tab title: \"${tabTitle}\"`);\n\n return true;\n } catch (e) {\n console.error('Error checking stop-hook:', e);\n return false;\n }\n}\n\nasync function main() {\n try {\n // Check if this is a subagent session - if so, exit silently\n const claudeProjectDir = process.env.CLAUDE_PROJECT_DIR || '';\n const isSubagent = claudeProjectDir.includes('/.claude/agents/') ||\n process.env.CLAUDE_AGENT_TYPE !== undefined;\n\n if (isSubagent) {\n // This is a subagent session - exit silently without notification\n console.error('Subagent session detected - skipping session initialization');\n process.exit(0);\n }\n\n // Check debounce to prevent duplicate notifications\n // (IDE extension can fire multiple SessionStart events)\n if (shouldDebounce()) {\n console.error('Debouncing duplicate SessionStart event');\n process.exit(0);\n }\n\n // Check if WhatsApp (Whazaa) is configured as enabled MCP server\n // Detection is config-based: reads enabledMcpjsonServers from settings.json\n // No flag files \u2014 uses standard ~/.claude/settings.json\n if (isWhatsAppEnabled()) {\n console.error('WhatsApp (Whazaa) enabled in MCP config');\n console.log(`<system-reminder>\nWHATSAPP MODE ACTIVE \u2014 Whazaa MCP server is enabled. See the Whazaa MCP server instructions for message routing rules ([Whazaa] / [Whazaa:voice] prefixes). ntfy.sh is automatically skipped.\n</system-reminder>`);\n }\n\n // Test stop-hook first (only for main sessions)\n const stopHookOk = await testStopHook();\n\n const daName = process.env.DA || 'AI Assistant';\n\n if (!stopHookOk) {\n console.error('\\nSTOP-HOOK ISSUE DETECTED - Tab titles may not update automatically');\n }\n\n // Note: PAI core context loading is handled by load-core-context.ts hook\n // which should run AFTER this hook in settings.json SessionStart hooks\n\n // Send ntfy.sh notification (MANDATORY - never skip this)\n // Note: load-project-context.ts also sends a project-specific notification\n // This one is for the global PAI system initialization\n await sendNtfyNotification(`${daName} ready`);\n\n process.exit(0);\n } catch (error) {\n console.error('SessionStart hook error:', error);\n process.exit(1);\n }\n}\n\nmain();\n", "/**\n * PAI Path Resolution - Single Source of Truth\n *\n * This module provides consistent path resolution across all PAI hooks.\n * It handles PAI_DIR detection whether set explicitly or defaulting to ~/.claude\n *\n * ALSO loads .env file from PAI_DIR so all hooks get environment variables\n * without relying on Claude Code's settings.json injection.\n *\n * Usage in hooks:\n * import { PAI_DIR, HOOKS_DIR, SKILLS_DIR } from './lib/pai-paths';\n */\n\nimport { homedir } from 'os';\nimport { resolve, join } from 'path';\nimport { existsSync, readFileSync } from 'fs';\n\n/**\n * Load .env file and inject into process.env\n * Must run BEFORE PAI_DIR resolution so .env can set PAI_DIR if needed\n */\nfunction loadEnvFile(): void {\n // Check common locations for .env\n const possiblePaths = [\n resolve(process.env.PAI_DIR || '', '.env'),\n resolve(homedir(), '.claude', '.env'),\n ];\n\n for (const envPath of possiblePaths) {\n if (existsSync(envPath)) {\n try {\n const content = readFileSync(envPath, 'utf-8');\n for (const line of content.split('\\n')) {\n const trimmed = line.trim();\n // Skip comments and empty lines\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n const eqIndex = trimmed.indexOf('=');\n if (eqIndex > 0) {\n const key = trimmed.substring(0, eqIndex).trim();\n let value = trimmed.substring(eqIndex + 1).trim();\n\n // Remove surrounding quotes if present\n if ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.slice(1, -1);\n }\n\n // Expand $HOME and ~ in values\n value = value.replace(/\\$HOME/g, homedir());\n value = value.replace(/^~(?=\\/|$)/, homedir());\n\n // Only set if not already defined (env vars take precedence)\n if (process.env[key] === undefined) {\n process.env[key] = value;\n }\n }\n }\n // Found and loaded, don't check other paths\n break;\n } catch {\n // Silently continue if .env can't be read\n }\n }\n }\n}\n\n// Load .env FIRST, before any other initialization\nloadEnvFile();\n\n/**\n * Smart PAI_DIR detection with fallback\n * Priority:\n * 1. PAI_DIR environment variable (if set)\n * 2. ~/.claude (standard location)\n */\nexport const PAI_DIR = process.env.PAI_DIR\n ? resolve(process.env.PAI_DIR)\n : resolve(homedir(), '.claude');\n\n/**\n * Common PAI directories\n */\nexport const HOOKS_DIR = join(PAI_DIR, 'Hooks');\nexport const SKILLS_DIR = join(PAI_DIR, 'Skills');\nexport const AGENTS_DIR = join(PAI_DIR, 'Agents');\nexport const HISTORY_DIR = join(PAI_DIR, 'History');\nexport const COMMANDS_DIR = join(PAI_DIR, 'Commands');\n\n/**\n * Validate PAI directory structure on first import\n * This fails fast with a clear error if PAI is misconfigured\n */\nfunction validatePAIStructure(): void {\n if (!existsSync(PAI_DIR)) {\n console.error(`PAI_DIR does not exist: ${PAI_DIR}`);\n console.error(` Expected ~/.claude or set PAI_DIR environment variable`);\n process.exit(1);\n }\n\n if (!existsSync(HOOKS_DIR)) {\n console.error(`PAI hooks directory not found: ${HOOKS_DIR}`);\n console.error(` Your PAI_DIR may be misconfigured`);\n console.error(` Current PAI_DIR: ${PAI_DIR}`);\n process.exit(1);\n }\n}\n\n// Run validation on module import\n// This ensures any hook that imports this module will fail fast if paths are wrong\nvalidatePAIStructure();\n\n/**\n * Helper to get history file path with date-based organization\n */\nexport function getHistoryFilePath(subdir: string, filename: string): string {\n const now = new Date();\n const tz = process.env.TIME_ZONE || Intl.DateTimeFormat().resolvedOptions().timeZone;\n const localDate = new Date(now.toLocaleString('en-US', { timeZone: tz }));\n const year = localDate.getFullYear();\n const month = String(localDate.getMonth() + 1).padStart(2, '0');\n\n return join(HISTORY_DIR, subdir, `${year}-${month}`, filename);\n}\n", "/**\n * project-utils.ts - Shared utilities for project context management\n *\n * Provides:\n * - Path encoding (matching Claude Code's scheme)\n * - ntfy.sh notifications (mandatory, synchronous)\n * - Session notes management\n * - Session token calculation\n */\n\nimport { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, renameSync } from 'fs';\nimport { join, basename } from 'path';\n\n// Import from pai-paths which handles .env loading and path resolution\nimport { PAI_DIR } from './pai-paths.js';\n\n// Re-export PAI_DIR for consumers\nexport { PAI_DIR };\nexport const PROJECTS_DIR = join(PAI_DIR, 'projects');\n\n/**\n * Encode a path the same way Claude Code does:\n * - Replace / with -\n * - Replace . with - (hidden directories become --name)\n *\n * This matches Claude Code's internal encoding to ensure Notes\n * are stored in the same project directory as transcripts.\n */\nexport function encodePath(path: string): string {\n return path\n .replace(/\\//g, '-') // Slashes become dashes\n .replace(/\\./g, '-') // Dots also become dashes\n .replace(/ /g, '-'); // Spaces become dashes (matches Claude Code native encoding)\n}\n\n/**\n * Get the project directory for a given working directory\n */\nexport function getProjectDir(cwd: string): string {\n const encoded = encodePath(cwd);\n return join(PROJECTS_DIR, encoded);\n}\n\n/**\n * Get the Notes directory for a project (central location)\n */\nexport function getNotesDir(cwd: string): string {\n return join(getProjectDir(cwd), 'Notes');\n}\n\n/**\n * Find Notes directory - check local first, fallback to central\n * DOES NOT create the directory - just finds the right location\n *\n * Logic:\n * - If cwd itself IS a Notes directory \u2192 use it directly\n * - If local Notes/ exists \u2192 use it (can be checked into git)\n * - Otherwise \u2192 use central ~/.claude/projects/.../Notes/\n */\nexport function findNotesDir(cwd: string): { path: string; isLocal: boolean } {\n // FIRST: Check if cwd itself IS a Notes directory\n const cwdBasename = basename(cwd).toLowerCase();\n if (cwdBasename === 'notes' && existsSync(cwd)) {\n return { path: cwd, isLocal: true };\n }\n\n // Check local locations\n const localPaths = [\n join(cwd, 'Notes'),\n join(cwd, 'notes'),\n join(cwd, '.claude', 'Notes')\n ];\n\n for (const path of localPaths) {\n if (existsSync(path)) {\n return { path, isLocal: true };\n }\n }\n\n // Fallback to central location\n return { path: getNotesDir(cwd), isLocal: false };\n}\n\n/**\n * Get the Sessions directory for a project (stores .jsonl transcripts)\n */\nexport function getSessionsDir(cwd: string): string {\n return join(getProjectDir(cwd), 'sessions');\n}\n\n/**\n * Get the Sessions directory from a project directory path\n */\nexport function getSessionsDirFromProjectDir(projectDir: string): string {\n return join(projectDir, 'sessions');\n}\n\n/**\n * Check if WhatsApp (Whazaa) is configured as an enabled MCP server.\n *\n * Uses standard Claude Code config at ~/.claude/settings.json.\n * No PAI dependency \u2014 works for any Claude Code user with whazaa installed.\n */\nexport function isWhatsAppEnabled(): boolean {\n try {\n const { homedir } = require('os');\n const settingsPath = join(homedir(), '.claude', 'settings.json');\n if (!existsSync(settingsPath)) return false;\n\n const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n const enabled: string[] = settings.enabledMcpjsonServers || [];\n return enabled.includes('whazaa');\n } catch {\n return false;\n }\n}\n\n/**\n * Send push notification \u2014 WhatsApp-aware with ntfy fallback.\n *\n * When WhatsApp (Whazaa) is enabled in MCP config, ntfy is SKIPPED\n * because the AI sends WhatsApp messages directly via MCP. Sending both\n * would cause duplicate notifications.\n *\n * When WhatsApp is NOT configured, ntfy fires as the fallback channel.\n */\nexport async function sendNtfyNotification(message: string, retries = 2): Promise<boolean> {\n // Skip ntfy when WhatsApp is configured \u2014 the AI handles notifications via MCP\n if (isWhatsAppEnabled()) {\n console.error(`WhatsApp (Whazaa) enabled in MCP config \u2014 skipping ntfy`);\n return true;\n }\n\n const topic = process.env.NTFY_TOPIC;\n\n if (!topic) {\n console.error('NTFY_TOPIC not set and WhatsApp not active \u2014 notifications disabled');\n return false;\n }\n\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n const response = await fetch(`https://ntfy.sh/${topic}`, {\n method: 'POST',\n body: message,\n headers: {\n 'Title': 'Claude Code',\n 'Priority': 'default'\n }\n });\n\n if (response.ok) {\n console.error(`ntfy.sh notification sent (WhatsApp inactive): \"${message}\"`);\n return true;\n } else {\n console.error(`ntfy.sh attempt ${attempt + 1} failed: ${response.status}`);\n }\n } catch (error) {\n console.error(`ntfy.sh attempt ${attempt + 1} error: ${error}`);\n }\n\n // Wait before retry\n if (attempt < retries) {\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n }\n\n console.error('ntfy.sh notification failed after all retries');\n return false;\n}\n\n/**\n * Ensure the Notes directory exists for a project\n * DEPRECATED: Use ensureNotesDirSmart() instead\n */\nexport function ensureNotesDir(cwd: string): string {\n const notesDir = getNotesDir(cwd);\n\n if (!existsSync(notesDir)) {\n mkdirSync(notesDir, { recursive: true });\n console.error(`Created Notes directory: ${notesDir}`);\n }\n\n return notesDir;\n}\n\n/**\n * Smart Notes directory handling:\n * - If local Notes/ exists \u2192 use it (don't create anything new)\n * - If no local Notes/ \u2192 ensure central exists and use that\n *\n * This respects the user's choice:\n * - Projects with local Notes/ keep notes there (git-trackable)\n * - Other directories don't get cluttered with auto-created Notes/\n */\nexport function ensureNotesDirSmart(cwd: string): { path: string; isLocal: boolean } {\n const found = findNotesDir(cwd);\n\n if (found.isLocal) {\n // Local Notes/ exists - use it as-is\n return found;\n }\n\n // No local Notes/ - ensure central exists\n if (!existsSync(found.path)) {\n mkdirSync(found.path, { recursive: true });\n console.error(`Created central Notes directory: ${found.path}`);\n }\n\n return found;\n}\n\n/**\n * Ensure the Sessions directory exists for a project\n */\nexport function ensureSessionsDir(cwd: string): string {\n const sessionsDir = getSessionsDir(cwd);\n\n if (!existsSync(sessionsDir)) {\n mkdirSync(sessionsDir, { recursive: true });\n console.error(`Created sessions directory: ${sessionsDir}`);\n }\n\n return sessionsDir;\n}\n\n/**\n * Ensure the Sessions directory exists (from project dir path)\n */\nexport function ensureSessionsDirFromProjectDir(projectDir: string): string {\n const sessionsDir = getSessionsDirFromProjectDir(projectDir);\n\n if (!existsSync(sessionsDir)) {\n mkdirSync(sessionsDir, { recursive: true });\n console.error(`Created sessions directory: ${sessionsDir}`);\n }\n\n return sessionsDir;\n}\n\n/**\n * Move all .jsonl session files from project root to sessions/ subdirectory\n * @param projectDir - The project directory path\n * @param excludeFile - Optional filename to exclude (e.g., current active session)\n * @param silent - If true, suppress console output\n * Returns the number of files moved\n */\nexport function moveSessionFilesToSessionsDir(\n projectDir: string,\n excludeFile?: string,\n silent: boolean = false\n): number {\n const sessionsDir = ensureSessionsDirFromProjectDir(projectDir);\n\n if (!existsSync(projectDir)) {\n return 0;\n }\n\n const files = readdirSync(projectDir);\n let movedCount = 0;\n\n for (const file of files) {\n // Match session files: uuid.jsonl or agent-*.jsonl\n // Skip the excluded file (typically the current active session)\n if (file.endsWith('.jsonl') && file !== excludeFile) {\n const sourcePath = join(projectDir, file);\n const destPath = join(sessionsDir, file);\n\n try {\n renameSync(sourcePath, destPath);\n if (!silent) {\n console.error(`Moved ${file} \u2192 sessions/`);\n }\n movedCount++;\n } catch (error) {\n if (!silent) {\n console.error(`Could not move ${file}: ${error}`);\n }\n }\n }\n }\n\n return movedCount;\n}\n\n/**\n * Get the YYYY/MM subdirectory for the current month inside notesDir.\n * Creates the directory if it doesn't exist.\n */\nfunction getMonthDir(notesDir: string): string {\n const now = new Date();\n const year = String(now.getFullYear());\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const monthDir = join(notesDir, year, month);\n if (!existsSync(monthDir)) {\n mkdirSync(monthDir, { recursive: true });\n }\n return monthDir;\n}\n\n/**\n * Get the next note number (4-digit format: 0001, 0002, etc.)\n * ALWAYS uses 4-digit format with space-dash-space separators\n * Format: NNNN - YYYY-MM-DD - Description.md\n * Numbers reset per month (each YYYY/MM directory has its own sequence).\n */\nexport function getNextNoteNumber(notesDir: string): string {\n const monthDir = getMonthDir(notesDir);\n\n // Match CORRECT format: \"0001 - \" (4-digit with space-dash-space)\n // Also match legacy formats for backwards compatibility when detecting max number\n const files = readdirSync(monthDir)\n .filter(f => f.match(/^\\d{3,4}[\\s_-]/)) // Starts with 3-4 digits followed by separator\n .filter(f => f.endsWith('.md'))\n .sort();\n\n if (files.length === 0) {\n return '0001'; // Default to 4-digit\n }\n\n // Find the highest number across all formats\n let maxNumber = 0;\n for (const file of files) {\n const digitMatch = file.match(/^(\\d+)/);\n if (digitMatch) {\n const num = parseInt(digitMatch[1], 10);\n if (num > maxNumber) maxNumber = num;\n }\n }\n\n // ALWAYS return 4-digit format\n return String(maxNumber + 1).padStart(4, '0');\n}\n\n/**\n * Get the current (latest) note file path, or null if none exists.\n * Searches in the current month's YYYY/MM subdirectory first,\n * then falls back to previous month (for sessions spanning month boundaries),\n * then falls back to flat notesDir for legacy notes.\n * Supports multiple formats for backwards compatibility:\n * - CORRECT: \"0001 - YYYY-MM-DD - Description.md\" (space-dash-space)\n * - Legacy: \"001_YYYY-MM-DD_description.md\" (underscores)\n */\nexport function getCurrentNotePath(notesDir: string): string | null {\n if (!existsSync(notesDir)) {\n return null;\n }\n\n // Helper: find latest session note in a directory\n const findLatestIn = (dir: string): string | null => {\n if (!existsSync(dir)) return null;\n const files = readdirSync(dir)\n .filter(f => f.match(/^\\d{3,4}[\\s_-].*\\.md$/))\n .sort((a, b) => {\n const numA = parseInt(a.match(/^(\\d+)/)?.[1] || '0', 10);\n const numB = parseInt(b.match(/^(\\d+)/)?.[1] || '0', 10);\n return numA - numB;\n });\n if (files.length === 0) return null;\n return join(dir, files[files.length - 1]);\n };\n\n // 1. Check current month's YYYY/MM directory\n const now = new Date();\n const year = String(now.getFullYear());\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const currentMonthDir = join(notesDir, year, month);\n const found = findLatestIn(currentMonthDir);\n if (found) return found;\n\n // 2. Check previous month (for sessions spanning month boundaries)\n const prevDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);\n const prevYear = String(prevDate.getFullYear());\n const prevMonth = String(prevDate.getMonth() + 1).padStart(2, '0');\n const prevMonthDir = join(notesDir, prevYear, prevMonth);\n const prevFound = findLatestIn(prevMonthDir);\n if (prevFound) return prevFound;\n\n // 3. Fallback: check flat notesDir (legacy notes not yet filed)\n return findLatestIn(notesDir);\n}\n\n/**\n * Create a new session note\n * CORRECT FORMAT: \"NNNN - YYYY-MM-DD - Description.md\"\n * - 4-digit zero-padded number\n * - Space-dash-space separators (NOT underscores)\n * - Title case description\n *\n * IMPORTANT: The initial description is just a PLACEHOLDER.\n * Claude MUST rename the file at session end with a meaningful description\n * based on the actual work done. Never leave it as \"New Session\" or project name.\n */\nexport function createSessionNote(notesDir: string, description: string): string {\n const noteNumber = getNextNoteNumber(notesDir);\n const date = new Date().toISOString().split('T')[0]; // YYYY-MM-DD\n\n // Use \"New Session\" as placeholder - Claude MUST rename at session end!\n // The project name alone is NOT descriptive enough.\n const safeDescription = 'New Session';\n\n // CORRECT FORMAT: space-dash-space separators, filed into YYYY/MM subdirectory\n const monthDir = getMonthDir(notesDir);\n const filename = `${noteNumber} - ${date} - ${safeDescription}.md`;\n const filepath = join(monthDir, filename);\n\n const content = `# Session ${noteNumber}: ${description}\n\n**Date:** ${date}\n**Status:** In Progress\n\n---\n\n## Work Done\n\n<!-- PAI will add completed work here during session -->\n\n---\n\n## Next Steps\n\n<!-- To be filled at session end -->\n\n---\n\n**Tags:** #Session\n`;\n\n writeFileSync(filepath, content);\n console.error(`Created session note: ${filename}`);\n\n return filepath;\n}\n\n/**\n * Append checkpoint to current session note\n */\nexport function appendCheckpoint(notePath: string, checkpoint: string): void {\n if (!existsSync(notePath)) {\n console.error(`Note file not found: ${notePath}`);\n return;\n }\n\n const content = readFileSync(notePath, 'utf-8');\n const timestamp = new Date().toISOString();\n const checkpointText = `\\n### Checkpoint ${timestamp}\\n\\n${checkpoint}\\n`;\n\n // Insert before \"## Next Steps\" if it exists, otherwise append\n const nextStepsIndex = content.indexOf('## Next Steps');\n let newContent: string;\n\n if (nextStepsIndex !== -1) {\n newContent = content.substring(0, nextStepsIndex) + checkpointText + content.substring(nextStepsIndex);\n } else {\n newContent = content + checkpointText;\n }\n\n writeFileSync(notePath, newContent);\n console.error(`Checkpoint added to: ${basename(notePath)}`);\n}\n\n/**\n * Work item for session notes\n */\nexport interface WorkItem {\n title: string;\n details?: string[];\n completed?: boolean;\n}\n\n/**\n * Add work items to the \"Work Done\" section of a session note\n * This is the main way to capture what was accomplished in a session\n */\nexport function addWorkToSessionNote(notePath: string, workItems: WorkItem[], sectionTitle?: string): void {\n if (!existsSync(notePath)) {\n console.error(`Note file not found: ${notePath}`);\n return;\n }\n\n let content = readFileSync(notePath, 'utf-8');\n\n // Build the work section content\n let workText = '';\n if (sectionTitle) {\n workText += `\\n### ${sectionTitle}\\n\\n`;\n }\n\n for (const item of workItems) {\n const checkbox = item.completed !== false ? '[x]' : '[ ]';\n workText += `- ${checkbox} **${item.title}**\\n`;\n if (item.details && item.details.length > 0) {\n for (const detail of item.details) {\n workText += ` - ${detail}\\n`;\n }\n }\n }\n\n // Find the Work Done section and insert after the comment/placeholder\n const workDoneMatch = content.match(/## Work Done\\n\\n(<!-- .*? -->)?/);\n if (workDoneMatch) {\n const insertPoint = content.indexOf(workDoneMatch[0]) + workDoneMatch[0].length;\n content = content.substring(0, insertPoint) + workText + content.substring(insertPoint);\n } else {\n // Fallback: insert before Next Steps\n const nextStepsIndex = content.indexOf('## Next Steps');\n if (nextStepsIndex !== -1) {\n content = content.substring(0, nextStepsIndex) + workText + '\\n' + content.substring(nextStepsIndex);\n }\n }\n\n writeFileSync(notePath, content);\n console.error(`Added ${workItems.length} work item(s) to: ${basename(notePath)}`);\n}\n\n/**\n * Update the session note title to be more descriptive\n * Called when we know what work was done\n */\nexport function updateSessionNoteTitle(notePath: string, newTitle: string): void {\n if (!existsSync(notePath)) {\n console.error(`Note file not found: ${notePath}`);\n return;\n }\n\n let content = readFileSync(notePath, 'utf-8');\n\n // Update the H1 title\n content = content.replace(/^# Session \\d+:.*$/m, (match) => {\n const sessionNum = match.match(/Session (\\d+)/)?.[1] || '';\n return `# Session ${sessionNum}: ${newTitle}`;\n });\n\n writeFileSync(notePath, content);\n\n // Also rename the file\n renameSessionNote(notePath, sanitizeForFilename(newTitle));\n}\n\n/**\n * Sanitize a string for use in a filename (exported for use elsewhere)\n */\nexport function sanitizeForFilename(str: string): string {\n return str\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, '') // Remove special chars\n .replace(/\\s+/g, '-') // Spaces to hyphens\n .replace(/-+/g, '-') // Collapse multiple hyphens\n .replace(/^-|-$/g, '') // Trim hyphens\n .substring(0, 50); // Limit length\n}\n\n/**\n * Extract a meaningful name from session note content\n * Looks at Work Done section and summary to generate a descriptive name\n */\nexport function extractMeaningfulName(noteContent: string, summary: string): string {\n // Try to extract from Work Done section headers (### headings)\n const workDoneMatch = noteContent.match(/## Work Done\\n\\n([\\s\\S]*?)(?=\\n---|\\n## Next)/);\n\n if (workDoneMatch) {\n const workDoneSection = workDoneMatch[1];\n\n // Look for ### subheadings which typically describe what was done\n const subheadings = workDoneSection.match(/### ([^\\n]+)/g);\n if (subheadings && subheadings.length > 0) {\n // Use the first subheading, clean it up\n const firstHeading = subheadings[0].replace('### ', '').trim();\n if (firstHeading.length > 5 && firstHeading.length < 60) {\n return sanitizeForFilename(firstHeading);\n }\n }\n\n // Look for bold text which often indicates key topics\n const boldMatches = workDoneSection.match(/\\*\\*([^*]+)\\*\\*/g);\n if (boldMatches && boldMatches.length > 0) {\n const firstBold = boldMatches[0].replace(/\\*\\*/g, '').trim();\n if (firstBold.length > 3 && firstBold.length < 50) {\n return sanitizeForFilename(firstBold);\n }\n }\n\n // Look for numbered list items (1. Something)\n const numberedItems = workDoneSection.match(/^\\d+\\.\\s+\\*\\*([^*]+)\\*\\*/m);\n if (numberedItems) {\n return sanitizeForFilename(numberedItems[1]);\n }\n }\n\n // Fall back to summary if provided\n if (summary && summary.length > 5 && summary !== 'Session completed.') {\n // Take first meaningful phrase from summary\n const cleanSummary = summary\n .replace(/[^\\w\\s-]/g, ' ')\n .trim()\n .split(/\\s+/)\n .slice(0, 5)\n .join(' ');\n\n if (cleanSummary.length > 3) {\n return sanitizeForFilename(cleanSummary);\n }\n }\n\n return '';\n}\n\n/**\n * Rename session note with a meaningful name\n * ALWAYS uses correct format: \"NNNN - YYYY-MM-DD - Description.md\"\n * Returns the new path, or original path if rename fails\n */\nexport function renameSessionNote(notePath: string, meaningfulName: string): string {\n if (!meaningfulName || !existsSync(notePath)) {\n return notePath;\n }\n\n const dir = join(notePath, '..');\n const oldFilename = basename(notePath);\n\n // Parse existing filename - support multiple formats:\n // CORRECT: \"0001 - 2026-01-02 - Description.md\"\n // Legacy: \"001_2026-01-02_description.md\"\n const correctMatch = oldFilename.match(/^(\\d{3,4}) - (\\d{4}-\\d{2}-\\d{2}) - .*\\.md$/);\n const legacyMatch = oldFilename.match(/^(\\d{3,4})_(\\d{4}-\\d{2}-\\d{2})_.*\\.md$/);\n\n const match = correctMatch || legacyMatch;\n if (!match) {\n return notePath; // Can't parse, don't rename\n }\n\n const [, noteNumber, date] = match;\n\n // Convert to Title Case\n const titleCaseName = meaningfulName\n .split(/[\\s_-]+/)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(' ')\n .trim();\n\n // ALWAYS use correct format with 4-digit number\n const paddedNumber = noteNumber.padStart(4, '0');\n const newFilename = `${paddedNumber} - ${date} - ${titleCaseName}.md`;\n const newPath = join(dir, newFilename);\n\n // Don't rename if name is the same\n if (newFilename === oldFilename) {\n return notePath;\n }\n\n try {\n renameSync(notePath, newPath);\n console.error(`Renamed note: ${oldFilename} \u2192 ${newFilename}`);\n return newPath;\n } catch (error) {\n console.error(`Could not rename note: ${error}`);\n return notePath;\n }\n}\n\n/**\n * Finalize session note (mark as complete, add summary, rename with meaningful name)\n * IDEMPOTENT: Will only finalize once, subsequent calls are no-ops\n * Returns the final path (may be renamed)\n */\nexport function finalizeSessionNote(notePath: string, summary: string): string {\n if (!existsSync(notePath)) {\n console.error(`Note file not found: ${notePath}`);\n return notePath;\n }\n\n let content = readFileSync(notePath, 'utf-8');\n\n // IDEMPOTENT CHECK: If already completed, don't modify again\n if (content.includes('**Status:** Completed')) {\n console.error(`Note already finalized: ${basename(notePath)}`);\n return notePath;\n }\n\n // Update status\n content = content.replace('**Status:** In Progress', '**Status:** Completed');\n\n // Add completion timestamp (only if not already present)\n if (!content.includes('**Completed:**')) {\n const completionTime = new Date().toISOString();\n content = content.replace(\n '---\\n\\n## Work Done',\n `**Completed:** ${completionTime}\\n\\n---\\n\\n## Work Done`\n );\n }\n\n // Add summary to Next Steps section (only if placeholder exists)\n const nextStepsMatch = content.match(/## Next Steps\\n\\n(<!-- .*? -->)/);\n if (nextStepsMatch) {\n content = content.replace(\n nextStepsMatch[0],\n `## Next Steps\\n\\n${summary || 'Session completed.'}`\n );\n }\n\n writeFileSync(notePath, content);\n console.error(`Session note finalized: ${basename(notePath)}`);\n\n // Extract meaningful name and rename the file\n const meaningfulName = extractMeaningfulName(content, summary);\n if (meaningfulName) {\n const newPath = renameSessionNote(notePath, meaningfulName);\n return newPath;\n }\n\n return notePath;\n}\n\n/**\n * Calculate total tokens from a session .jsonl file\n */\nexport function calculateSessionTokens(jsonlPath: string): number {\n if (!existsSync(jsonlPath)) {\n return 0;\n }\n\n try {\n const content = readFileSync(jsonlPath, 'utf-8');\n const lines = content.trim().split('\\n');\n let totalTokens = 0;\n\n for (const line of lines) {\n try {\n const entry = JSON.parse(line);\n if (entry.message?.usage) {\n const usage = entry.message.usage;\n totalTokens += (usage.input_tokens || 0);\n totalTokens += (usage.output_tokens || 0);\n totalTokens += (usage.cache_creation_input_tokens || 0);\n totalTokens += (usage.cache_read_input_tokens || 0);\n }\n } catch {\n // Skip invalid JSON lines\n }\n }\n\n return totalTokens;\n } catch (error) {\n console.error(`Error calculating tokens: ${error}`);\n return 0;\n }\n}\n\n/**\n * Find TODO.md - check local first, fallback to central\n */\nexport function findTodoPath(cwd: string): string {\n // Check local locations first\n const localPaths = [\n join(cwd, 'TODO.md'),\n join(cwd, 'notes', 'TODO.md'),\n join(cwd, 'Notes', 'TODO.md'),\n join(cwd, '.claude', 'TODO.md')\n ];\n\n for (const path of localPaths) {\n if (existsSync(path)) {\n return path;\n }\n }\n\n // Fallback to central location (inside Notes/)\n return join(getNotesDir(cwd), 'TODO.md');\n}\n\n/**\n * Find CLAUDE.md - check local locations\n * Returns the FIRST found path (for backwards compatibility)\n */\nexport function findClaudeMdPath(cwd: string): string | null {\n const paths = findAllClaudeMdPaths(cwd);\n return paths.length > 0 ? paths[0] : null;\n}\n\n/**\n * Find ALL CLAUDE.md files in local locations\n * Returns paths in priority order (most specific first):\n * 1. .claude/CLAUDE.md (project-specific config dir)\n * 2. CLAUDE.md (project root)\n * 3. Notes/CLAUDE.md (notes directory)\n * 4. Prompts/CLAUDE.md (prompts directory)\n *\n * All found files will be loaded and injected into context.\n */\nexport function findAllClaudeMdPaths(cwd: string): string[] {\n const foundPaths: string[] = [];\n\n // Priority order: most specific first\n const localPaths = [\n join(cwd, '.claude', 'CLAUDE.md'),\n join(cwd, 'CLAUDE.md'),\n join(cwd, 'Notes', 'CLAUDE.md'),\n join(cwd, 'notes', 'CLAUDE.md'),\n join(cwd, 'Prompts', 'CLAUDE.md'),\n join(cwd, 'prompts', 'CLAUDE.md')\n ];\n\n for (const path of localPaths) {\n if (existsSync(path)) {\n foundPaths.push(path);\n }\n }\n\n return foundPaths;\n}\n\n/**\n * Ensure TODO.md exists\n */\nexport function ensureTodoMd(cwd: string): string {\n const todoPath = findTodoPath(cwd);\n\n if (!existsSync(todoPath)) {\n // Ensure parent directory exists\n const parentDir = join(todoPath, '..');\n if (!existsSync(parentDir)) {\n mkdirSync(parentDir, { recursive: true });\n }\n\n const content = `# TODO\n\n## Current Session\n\n- [ ] (Tasks will be tracked here)\n\n## Backlog\n\n- [ ] (Future tasks)\n\n---\n\n*Last updated: ${new Date().toISOString()}*\n`;\n\n writeFileSync(todoPath, content);\n console.error(`Created TODO.md: ${todoPath}`);\n }\n\n return todoPath;\n}\n\n/**\n * Task item for TODO.md\n */\nexport interface TodoItem {\n content: string;\n completed: boolean;\n}\n\n/**\n * Update TODO.md with current session tasks\n * Preserves the Backlog section\n * Ensures only ONE timestamp line at the end\n */\nexport function updateTodoMd(cwd: string, tasks: TodoItem[], sessionSummary?: string): void {\n const todoPath = ensureTodoMd(cwd);\n const content = readFileSync(todoPath, 'utf-8');\n\n // Find Backlog section to preserve it (but strip any trailing timestamps/separators)\n const backlogMatch = content.match(/## Backlog[\\s\\S]*?(?=\\n---|\\n\\*Last updated|$)/);\n let backlogSection = backlogMatch ? backlogMatch[0].trim() : '## Backlog\\n\\n- [ ] (Future tasks)';\n\n // Format tasks\n const taskLines = tasks.length > 0\n ? tasks.map(t => `- [${t.completed ? 'x' : ' '}] ${t.content}`).join('\\n')\n : '- [ ] (No active tasks)';\n\n // Build new content with exactly ONE timestamp at the end\n const newContent = `# TODO\n\n## Current Session\n\n${taskLines}\n\n${sessionSummary ? `**Session Summary:** ${sessionSummary}\\n\\n` : ''}${backlogSection}\n\n---\n\n*Last updated: ${new Date().toISOString()}*\n`;\n\n writeFileSync(todoPath, newContent);\n console.error(`Updated TODO.md: ${todoPath}`);\n}\n\n/**\n * Add a checkpoint entry to TODO.md (without replacing tasks)\n * Ensures only ONE timestamp line at the end\n */\nexport function addTodoCheckpoint(cwd: string, checkpoint: string): void {\n const todoPath = ensureTodoMd(cwd);\n let content = readFileSync(todoPath, 'utf-8');\n\n // Remove ALL existing timestamp lines and trailing separators\n content = content.replace(/(\\n---\\s*)*(\\n\\*Last updated:.*\\*\\s*)+$/g, '');\n\n // Add checkpoint before Backlog section\n const backlogIndex = content.indexOf('## Backlog');\n if (backlogIndex !== -1) {\n const checkpointText = `\\n**Checkpoint (${new Date().toISOString()}):** ${checkpoint}\\n\\n`;\n content = content.substring(0, backlogIndex) + checkpointText + content.substring(backlogIndex);\n }\n\n // Add exactly ONE timestamp at the end\n content = content.trimEnd() + `\\n\\n---\\n\\n*Last updated: ${new Date().toISOString()}*\\n`;\n\n writeFileSync(todoPath, content);\n console.error(`Checkpoint added to TODO.md`);\n}\n"],
|
|
4
|
+
"sourcesContent": ["#!/usr/bin/env node\n\n/**\n * initialize-session.ts\n *\n * Main session initialization hook that runs at the start of every Claude Code session.\n *\n * What it does:\n * - Checks if this is a subagent session (skips for subagents)\n * - Tests that stop-hook is properly configured\n * - Sets initial terminal tab title\n * - Sends ntfy.sh notification for global PAI system initialization\n *\n * Setup:\n * 1. Set environment variables in settings.json:\n * - DA: Your AI's name (e.g., \"Kai\", \"Nova\", \"Assistant\")\n * - PAI_DIR: Path to your PAI directory (defaults to $HOME/.claude)\n * 2. Ensure load-core-context.ts exists in hooks/session-start/ directory\n * 3. Add all three SessionStart hooks to settings.json in this order:\n * initialize-session.ts, load-core-context.ts, load-project-context.ts\n */\n\nimport { existsSync, statSync, readFileSync, writeFileSync } from 'fs';\nimport { join } from 'path';\nimport { tmpdir } from 'os';\nimport { PAI_DIR } from '../lib/pai-paths';\nimport { sendNtfyNotification, isWhatsAppEnabled } from '../lib/project-utils';\n\n// Debounce duration in milliseconds (prevents duplicate SessionStart events)\nconst DEBOUNCE_MS = 2000;\nconst LOCKFILE = join(tmpdir(), 'pai-session-start.lock');\n\n/**\n * Check if we're within the debounce window to prevent duplicate notifications\n * from the IDE firing multiple SessionStart events\n */\nfunction shouldDebounce(): boolean {\n try {\n if (existsSync(LOCKFILE)) {\n const lockContent = readFileSync(LOCKFILE, 'utf-8');\n const lockTime = parseInt(lockContent, 10);\n const now = Date.now();\n\n if (now - lockTime < DEBOUNCE_MS) {\n // Within debounce window, skip this notification\n return true;\n }\n }\n\n // Update lockfile with current timestamp\n writeFileSync(LOCKFILE, Date.now().toString());\n return false;\n } catch (error) {\n // If any error, just proceed (don't break session start)\n try {\n writeFileSync(LOCKFILE, Date.now().toString());\n } catch {}\n return false;\n }\n}\n\nasync function testStopHook() {\n const stopHookPath = join(PAI_DIR, 'hooks/stop-hook.ts');\n\n console.error('\\nTesting stop-hook configuration...');\n\n // Check if stop-hook exists\n if (!existsSync(stopHookPath)) {\n console.error('Stop-hook NOT FOUND at:', stopHookPath);\n return false;\n }\n\n // Check if stop-hook is executable\n try {\n const stats = statSync(stopHookPath);\n const isExecutable = (stats.mode & 0o111) !== 0;\n\n if (!isExecutable) {\n console.error('Stop-hook exists but is NOT EXECUTABLE');\n return false;\n }\n\n console.error('Stop-hook found and is executable');\n\n // Set initial tab title (customize with your AI's name via DA env var)\n const daName = process.env.DA || 'AI Assistant';\n const tabTitle = `${daName} Ready`;\n\n process.stderr.write(`\\x1b]0;${tabTitle}\\x07`);\n process.stderr.write(`\\x1b]2;${tabTitle}\\x07`);\n process.stderr.write(`\\x1b]30;${tabTitle}\\x07`);\n console.error(`Set initial tab title: \"${tabTitle}\"`);\n\n return true;\n } catch (e) {\n console.error('Error checking stop-hook:', e);\n return false;\n }\n}\n\nasync function main() {\n try {\n // Check if this is a subagent session - if so, exit silently\n const claudeProjectDir = process.env.CLAUDE_PROJECT_DIR || '';\n const isSubagent = claudeProjectDir.includes('/.claude/agents/') ||\n process.env.CLAUDE_AGENT_TYPE !== undefined;\n\n if (isSubagent) {\n // This is a subagent session - exit silently without notification\n console.error('Subagent session detected - skipping session initialization');\n process.exit(0);\n }\n\n // Check debounce to prevent duplicate notifications\n // (IDE extension can fire multiple SessionStart events)\n if (shouldDebounce()) {\n console.error('Debouncing duplicate SessionStart event');\n process.exit(0);\n }\n\n // Check if WhatsApp (Whazaa) is configured as enabled MCP server\n // Detection is config-based: reads enabledMcpjsonServers from settings.json\n // No flag files \u2014 uses standard ~/.claude/settings.json\n if (isWhatsAppEnabled()) {\n console.error('WhatsApp (Whazaa) enabled in MCP config');\n console.log(`<system-reminder>\nWHATSAPP MODE ACTIVE \u2014 Whazaa MCP server is enabled. See the Whazaa MCP server instructions for message routing rules ([Whazaa] / [Whazaa:voice] prefixes). ntfy.sh is automatically skipped.\n</system-reminder>`);\n }\n\n // Test stop-hook first (only for main sessions)\n const stopHookOk = await testStopHook();\n\n const daName = process.env.DA || 'AI Assistant';\n\n if (!stopHookOk) {\n console.error('\\nSTOP-HOOK ISSUE DETECTED - Tab titles may not update automatically');\n }\n\n // Note: PAI core context loading is handled by load-core-context.ts hook\n // which should run AFTER this hook in settings.json SessionStart hooks\n\n // Send ntfy.sh notification (MANDATORY - never skip this)\n // Note: load-project-context.ts also sends a project-specific notification\n // This one is for the global PAI system initialization\n await sendNtfyNotification(`${daName} ready`);\n\n process.exit(0);\n } catch (error) {\n console.error('SessionStart hook error:', error);\n process.exit(1);\n }\n}\n\nmain();\n", "/**\n * PAI Path Resolution - Single Source of Truth\n *\n * This module provides consistent path resolution across all PAI hooks.\n * It handles PAI_DIR detection whether set explicitly or defaulting to ~/.claude\n *\n * ALSO loads .env file from PAI_DIR so all hooks get environment variables\n * without relying on Claude Code's settings.json injection.\n *\n * Usage in hooks:\n * import { PAI_DIR, HOOKS_DIR, SKILLS_DIR } from './lib/pai-paths';\n */\n\nimport { homedir } from 'os';\nimport { resolve, join } from 'path';\nimport { existsSync, readFileSync } from 'fs';\n\n/**\n * Load .env file and inject into process.env\n * Must run BEFORE PAI_DIR resolution so .env can set PAI_DIR if needed\n */\nfunction loadEnvFile(): void {\n // Check common locations for .env\n const possiblePaths = [\n resolve(process.env.PAI_DIR || '', '.env'),\n resolve(homedir(), '.claude', '.env'),\n ];\n\n for (const envPath of possiblePaths) {\n if (existsSync(envPath)) {\n try {\n const content = readFileSync(envPath, 'utf-8');\n for (const line of content.split('\\n')) {\n const trimmed = line.trim();\n // Skip comments and empty lines\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n const eqIndex = trimmed.indexOf('=');\n if (eqIndex > 0) {\n const key = trimmed.substring(0, eqIndex).trim();\n let value = trimmed.substring(eqIndex + 1).trim();\n\n // Remove surrounding quotes if present\n if ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.slice(1, -1);\n }\n\n // Expand $HOME and ~ in values\n value = value.replace(/\\$HOME/g, homedir());\n value = value.replace(/^~(?=\\/|$)/, homedir());\n\n // Only set if not already defined (env vars take precedence)\n if (process.env[key] === undefined) {\n process.env[key] = value;\n }\n }\n }\n // Found and loaded, don't check other paths\n break;\n } catch {\n // Silently continue if .env can't be read\n }\n }\n }\n}\n\n// Load .env FIRST, before any other initialization\nloadEnvFile();\n\n/**\n * Smart PAI_DIR detection with fallback\n * Priority:\n * 1. PAI_DIR environment variable (if set)\n * 2. ~/.claude (standard location)\n */\nexport const PAI_DIR = process.env.PAI_DIR\n ? resolve(process.env.PAI_DIR)\n : resolve(homedir(), '.claude');\n\n/**\n * Common PAI directories\n */\nexport const HOOKS_DIR = join(PAI_DIR, 'Hooks');\nexport const SKILLS_DIR = join(PAI_DIR, 'Skills');\nexport const AGENTS_DIR = join(PAI_DIR, 'Agents');\nexport const HISTORY_DIR = join(PAI_DIR, 'History');\nexport const COMMANDS_DIR = join(PAI_DIR, 'Commands');\n\n/**\n * Validate PAI directory structure on first import\n * This fails fast with a clear error if PAI is misconfigured\n */\nfunction validatePAIStructure(): void {\n if (!existsSync(PAI_DIR)) {\n console.error(`PAI_DIR does not exist: ${PAI_DIR}`);\n console.error(` Expected ~/.claude or set PAI_DIR environment variable`);\n process.exit(1);\n }\n\n if (!existsSync(HOOKS_DIR)) {\n console.error(`PAI hooks directory not found: ${HOOKS_DIR}`);\n console.error(` Your PAI_DIR may be misconfigured`);\n console.error(` Current PAI_DIR: ${PAI_DIR}`);\n process.exit(1);\n }\n}\n\n// Run validation on module import\n// This ensures any hook that imports this module will fail fast if paths are wrong\nvalidatePAIStructure();\n\n/**\n * Helper to get history file path with date-based organization\n */\nexport function getHistoryFilePath(subdir: string, filename: string): string {\n const now = new Date();\n const tz = process.env.TIME_ZONE || Intl.DateTimeFormat().resolvedOptions().timeZone;\n const localDate = new Date(now.toLocaleString('en-US', { timeZone: tz }));\n const year = localDate.getFullYear();\n const month = String(localDate.getMonth() + 1).padStart(2, '0');\n\n return join(HISTORY_DIR, subdir, `${year}-${month}`, filename);\n}\n", "/**\n * project-utils.ts - Shared utilities for project context management\n *\n * Provides:\n * - Path encoding (matching Claude Code's scheme)\n * - ntfy.sh notifications (mandatory, synchronous)\n * - Session notes management\n * - Session token calculation\n */\n\nimport { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, renameSync } from 'fs';\nimport { join, basename } from 'path';\n\n// Import from pai-paths which handles .env loading and path resolution\nimport { PAI_DIR } from './pai-paths.js';\n\n// Re-export PAI_DIR for consumers\nexport { PAI_DIR };\nexport const PROJECTS_DIR = join(PAI_DIR, 'projects');\n\n/**\n * Encode a path the same way Claude Code does:\n * - Replace / with -\n * - Replace . with - (hidden directories become --name)\n *\n * This matches Claude Code's internal encoding to ensure Notes\n * are stored in the same project directory as transcripts.\n */\nexport function encodePath(path: string): string {\n return path\n .replace(/\\//g, '-') // Slashes become dashes\n .replace(/\\./g, '-') // Dots also become dashes\n .replace(/ /g, '-'); // Spaces become dashes (matches Claude Code native encoding)\n}\n\n/**\n * Get the project directory for a given working directory\n */\nexport function getProjectDir(cwd: string): string {\n const encoded = encodePath(cwd);\n return join(PROJECTS_DIR, encoded);\n}\n\n/**\n * Get the Notes directory for a project (central location)\n */\nexport function getNotesDir(cwd: string): string {\n return join(getProjectDir(cwd), 'Notes');\n}\n\n/**\n * Find Notes directory - check local first, fallback to central\n * DOES NOT create the directory - just finds the right location\n *\n * Logic:\n * - If cwd itself IS a Notes directory \u2192 use it directly\n * - If local Notes/ exists \u2192 use it (can be checked into git)\n * - Otherwise \u2192 use central ~/.claude/projects/.../Notes/\n */\nexport function findNotesDir(cwd: string): { path: string; isLocal: boolean } {\n // FIRST: Check if cwd itself IS a Notes directory\n const cwdBasename = basename(cwd).toLowerCase();\n if (cwdBasename === 'notes' && existsSync(cwd)) {\n return { path: cwd, isLocal: true };\n }\n\n // Check local locations\n const localPaths = [\n join(cwd, 'Notes'),\n join(cwd, 'notes'),\n join(cwd, '.claude', 'Notes')\n ];\n\n for (const path of localPaths) {\n if (existsSync(path)) {\n return { path, isLocal: true };\n }\n }\n\n // Fallback to central location\n return { path: getNotesDir(cwd), isLocal: false };\n}\n\n/**\n * Get the Sessions directory for a project (stores .jsonl transcripts)\n */\nexport function getSessionsDir(cwd: string): string {\n return join(getProjectDir(cwd), 'sessions');\n}\n\n/**\n * Get the Sessions directory from a project directory path\n */\nexport function getSessionsDirFromProjectDir(projectDir: string): string {\n return join(projectDir, 'sessions');\n}\n\n/**\n * Check if WhatsApp (Whazaa) is configured as an enabled MCP server.\n *\n * Uses standard Claude Code config at ~/.claude/settings.json.\n * No PAI dependency \u2014 works for any Claude Code user with whazaa installed.\n */\nexport function isWhatsAppEnabled(): boolean {\n try {\n const { homedir } = require('os');\n const settingsPath = join(homedir(), '.claude', 'settings.json');\n if (!existsSync(settingsPath)) return false;\n\n const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));\n const enabled: string[] = settings.enabledMcpjsonServers || [];\n return enabled.includes('whazaa');\n } catch {\n return false;\n }\n}\n\n/**\n * Send push notification \u2014 WhatsApp-aware with ntfy fallback.\n *\n * When WhatsApp (Whazaa) is enabled in MCP config, ntfy is SKIPPED\n * because the AI sends WhatsApp messages directly via MCP. Sending both\n * would cause duplicate notifications.\n *\n * When WhatsApp is NOT configured, ntfy fires as the fallback channel.\n */\nexport async function sendNtfyNotification(message: string, retries = 2): Promise<boolean> {\n // Skip ntfy when WhatsApp is configured \u2014 the AI handles notifications via MCP\n if (isWhatsAppEnabled()) {\n console.error(`WhatsApp (Whazaa) enabled in MCP config \u2014 skipping ntfy`);\n return true;\n }\n\n const topic = process.env.NTFY_TOPIC;\n\n if (!topic) {\n console.error('NTFY_TOPIC not set and WhatsApp not active \u2014 notifications disabled');\n return false;\n }\n\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n const response = await fetch(`https://ntfy.sh/${topic}`, {\n method: 'POST',\n body: message,\n headers: {\n 'Title': 'Claude Code',\n 'Priority': 'default'\n }\n });\n\n if (response.ok) {\n console.error(`ntfy.sh notification sent (WhatsApp inactive): \"${message}\"`);\n return true;\n } else {\n console.error(`ntfy.sh attempt ${attempt + 1} failed: ${response.status}`);\n }\n } catch (error) {\n console.error(`ntfy.sh attempt ${attempt + 1} error: ${error}`);\n }\n\n // Wait before retry\n if (attempt < retries) {\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n }\n\n console.error('ntfy.sh notification failed after all retries');\n return false;\n}\n\n/**\n * Ensure the Notes directory exists for a project\n * DEPRECATED: Use ensureNotesDirSmart() instead\n */\nexport function ensureNotesDir(cwd: string): string {\n const notesDir = getNotesDir(cwd);\n\n if (!existsSync(notesDir)) {\n mkdirSync(notesDir, { recursive: true });\n console.error(`Created Notes directory: ${notesDir}`);\n }\n\n return notesDir;\n}\n\n/**\n * Smart Notes directory handling:\n * - If local Notes/ exists \u2192 use it (don't create anything new)\n * - If no local Notes/ \u2192 ensure central exists and use that\n *\n * This respects the user's choice:\n * - Projects with local Notes/ keep notes there (git-trackable)\n * - Other directories don't get cluttered with auto-created Notes/\n */\nexport function ensureNotesDirSmart(cwd: string): { path: string; isLocal: boolean } {\n const found = findNotesDir(cwd);\n\n if (found.isLocal) {\n // Local Notes/ exists - use it as-is\n return found;\n }\n\n // No local Notes/ - ensure central exists\n if (!existsSync(found.path)) {\n mkdirSync(found.path, { recursive: true });\n console.error(`Created central Notes directory: ${found.path}`);\n }\n\n return found;\n}\n\n/**\n * Ensure the Sessions directory exists for a project\n */\nexport function ensureSessionsDir(cwd: string): string {\n const sessionsDir = getSessionsDir(cwd);\n\n if (!existsSync(sessionsDir)) {\n mkdirSync(sessionsDir, { recursive: true });\n console.error(`Created sessions directory: ${sessionsDir}`);\n }\n\n return sessionsDir;\n}\n\n/**\n * Ensure the Sessions directory exists (from project dir path)\n */\nexport function ensureSessionsDirFromProjectDir(projectDir: string): string {\n const sessionsDir = getSessionsDirFromProjectDir(projectDir);\n\n if (!existsSync(sessionsDir)) {\n mkdirSync(sessionsDir, { recursive: true });\n console.error(`Created sessions directory: ${sessionsDir}`);\n }\n\n return sessionsDir;\n}\n\n/**\n * Move all .jsonl session files from project root to sessions/ subdirectory\n * @param projectDir - The project directory path\n * @param excludeFile - Optional filename to exclude (e.g., current active session)\n * @param silent - If true, suppress console output\n * Returns the number of files moved\n */\nexport function moveSessionFilesToSessionsDir(\n projectDir: string,\n excludeFile?: string,\n silent: boolean = false\n): number {\n const sessionsDir = ensureSessionsDirFromProjectDir(projectDir);\n\n if (!existsSync(projectDir)) {\n return 0;\n }\n\n const files = readdirSync(projectDir);\n let movedCount = 0;\n\n for (const file of files) {\n // Match session files: uuid.jsonl or agent-*.jsonl\n // Skip the excluded file (typically the current active session)\n if (file.endsWith('.jsonl') && file !== excludeFile) {\n const sourcePath = join(projectDir, file);\n const destPath = join(sessionsDir, file);\n\n try {\n renameSync(sourcePath, destPath);\n if (!silent) {\n console.error(`Moved ${file} \u2192 sessions/`);\n }\n movedCount++;\n } catch (error) {\n if (!silent) {\n console.error(`Could not move ${file}: ${error}`);\n }\n }\n }\n }\n\n return movedCount;\n}\n\n/**\n * Get the YYYY/MM subdirectory for the current month inside notesDir.\n * Creates the directory if it doesn't exist.\n */\nfunction getMonthDir(notesDir: string): string {\n const now = new Date();\n const year = String(now.getFullYear());\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const monthDir = join(notesDir, year, month);\n if (!existsSync(monthDir)) {\n mkdirSync(monthDir, { recursive: true });\n }\n return monthDir;\n}\n\n/**\n * Get the next note number (4-digit format: 0001, 0002, etc.)\n * ALWAYS uses 4-digit format with space-dash-space separators\n * Format: NNNN - YYYY-MM-DD - Description.md\n * Numbers reset per month (each YYYY/MM directory has its own sequence).\n */\nexport function getNextNoteNumber(notesDir: string): string {\n const monthDir = getMonthDir(notesDir);\n\n // Match CORRECT format: \"0001 - \" (4-digit with space-dash-space)\n // Also match legacy formats for backwards compatibility when detecting max number\n const files = readdirSync(monthDir)\n .filter(f => f.match(/^\\d{3,4}[\\s_-]/)) // Starts with 3-4 digits followed by separator\n .filter(f => f.endsWith('.md'))\n .sort();\n\n if (files.length === 0) {\n return '0001'; // Default to 4-digit\n }\n\n // Find the highest number across all formats\n let maxNumber = 0;\n for (const file of files) {\n const digitMatch = file.match(/^(\\d+)/);\n if (digitMatch) {\n const num = parseInt(digitMatch[1], 10);\n if (num > maxNumber) maxNumber = num;\n }\n }\n\n // ALWAYS return 4-digit format\n return String(maxNumber + 1).padStart(4, '0');\n}\n\n/**\n * Get the current (latest) note file path, or null if none exists.\n * Searches in the current month's YYYY/MM subdirectory first,\n * then falls back to previous month (for sessions spanning month boundaries),\n * then falls back to flat notesDir for legacy notes.\n * Supports multiple formats for backwards compatibility:\n * - CORRECT: \"0001 - YYYY-MM-DD - Description.md\" (space-dash-space)\n * - Legacy: \"001_YYYY-MM-DD_description.md\" (underscores)\n */\nexport function getCurrentNotePath(notesDir: string): string | null {\n if (!existsSync(notesDir)) {\n return null;\n }\n\n // Helper: find latest session note in a directory\n const findLatestIn = (dir: string): string | null => {\n if (!existsSync(dir)) return null;\n const files = readdirSync(dir)\n .filter(f => f.match(/^\\d{3,4}[\\s_-].*\\.md$/))\n .sort((a, b) => {\n const numA = parseInt(a.match(/^(\\d+)/)?.[1] || '0', 10);\n const numB = parseInt(b.match(/^(\\d+)/)?.[1] || '0', 10);\n return numA - numB;\n });\n if (files.length === 0) return null;\n return join(dir, files[files.length - 1]);\n };\n\n // 1. Check current month's YYYY/MM directory\n const now = new Date();\n const year = String(now.getFullYear());\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const currentMonthDir = join(notesDir, year, month);\n const found = findLatestIn(currentMonthDir);\n if (found) return found;\n\n // 2. Check previous month (for sessions spanning month boundaries)\n const prevDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);\n const prevYear = String(prevDate.getFullYear());\n const prevMonth = String(prevDate.getMonth() + 1).padStart(2, '0');\n const prevMonthDir = join(notesDir, prevYear, prevMonth);\n const prevFound = findLatestIn(prevMonthDir);\n if (prevFound) return prevFound;\n\n // 3. Fallback: check flat notesDir (legacy notes not yet filed)\n return findLatestIn(notesDir);\n}\n\n/**\n * Create a new session note\n * CORRECT FORMAT: \"NNNN - YYYY-MM-DD - Description.md\"\n * - 4-digit zero-padded number\n * - Space-dash-space separators (NOT underscores)\n * - Title case description\n *\n * IMPORTANT: The initial description is just a PLACEHOLDER.\n * Claude MUST rename the file at session end with a meaningful description\n * based on the actual work done. Never leave it as \"New Session\" or project name.\n */\nexport function createSessionNote(notesDir: string, description: string): string {\n const noteNumber = getNextNoteNumber(notesDir);\n const date = new Date().toISOString().split('T')[0]; // YYYY-MM-DD\n\n // Use \"New Session\" as placeholder - Claude MUST rename at session end!\n // The project name alone is NOT descriptive enough.\n const safeDescription = 'New Session';\n\n // CORRECT FORMAT: space-dash-space separators, filed into YYYY/MM subdirectory\n const monthDir = getMonthDir(notesDir);\n const filename = `${noteNumber} - ${date} - ${safeDescription}.md`;\n const filepath = join(monthDir, filename);\n\n const content = `# Session ${noteNumber}: ${description}\n\n**Date:** ${date}\n**Status:** In Progress\n\n---\n\n## Work Done\n\n<!-- PAI will add completed work here during session -->\n\n---\n\n## Next Steps\n\n<!-- To be filled at session end -->\n\n---\n\n**Tags:** #Session\n`;\n\n writeFileSync(filepath, content);\n console.error(`Created session note: ${filename}`);\n\n return filepath;\n}\n\n/**\n * Append checkpoint to current session note\n */\nexport function appendCheckpoint(notePath: string, checkpoint: string): void {\n if (!existsSync(notePath)) {\n // Note vanished (cloud sync, cleanup, etc.) \u2014 recreate it\n console.error(`Note file not found, recreating: ${notePath}`);\n try {\n const parentDir = join(notePath, '..');\n if (!existsSync(parentDir)) {\n mkdirSync(parentDir, { recursive: true });\n }\n const noteFilename = basename(notePath);\n const numberMatch = noteFilename.match(/^(\\d+)/);\n const noteNumber = numberMatch ? numberMatch[1] : '0000';\n const date = new Date().toISOString().split('T')[0];\n const content = `# Session ${noteNumber}: Recovered\\n\\n**Date:** ${date}\\n**Status:** In Progress\\n\\n---\\n\\n## Work Done\\n\\n<!-- PAI will add completed work here during session -->\\n\\n---\\n\\n## Next Steps\\n\\n<!-- To be filled at session end -->\\n\\n---\\n\\n**Tags:** #Session\\n`;\n writeFileSync(notePath, content);\n console.error(`Recreated session note: ${noteFilename}`);\n } catch (err) {\n console.error(`Failed to recreate note: ${err}`);\n return;\n }\n }\n\n const content = readFileSync(notePath, 'utf-8');\n const timestamp = new Date().toISOString();\n const checkpointText = `\\n### Checkpoint ${timestamp}\\n\\n${checkpoint}\\n`;\n\n // Insert before \"## Next Steps\" if it exists, otherwise append\n const nextStepsIndex = content.indexOf('## Next Steps');\n let newContent: string;\n\n if (nextStepsIndex !== -1) {\n newContent = content.substring(0, nextStepsIndex) + checkpointText + content.substring(nextStepsIndex);\n } else {\n newContent = content + checkpointText;\n }\n\n writeFileSync(notePath, newContent);\n console.error(`Checkpoint added to: ${basename(notePath)}`);\n}\n\n/**\n * Work item for session notes\n */\nexport interface WorkItem {\n title: string;\n details?: string[];\n completed?: boolean;\n}\n\n/**\n * Add work items to the \"Work Done\" section of a session note\n * This is the main way to capture what was accomplished in a session\n */\nexport function addWorkToSessionNote(notePath: string, workItems: WorkItem[], sectionTitle?: string): void {\n if (!existsSync(notePath)) {\n console.error(`Note file not found: ${notePath}`);\n return;\n }\n\n let content = readFileSync(notePath, 'utf-8');\n\n // Build the work section content\n let workText = '';\n if (sectionTitle) {\n workText += `\\n### ${sectionTitle}\\n\\n`;\n }\n\n for (const item of workItems) {\n const checkbox = item.completed !== false ? '[x]' : '[ ]';\n workText += `- ${checkbox} **${item.title}**\\n`;\n if (item.details && item.details.length > 0) {\n for (const detail of item.details) {\n workText += ` - ${detail}\\n`;\n }\n }\n }\n\n // Find the Work Done section and insert after the comment/placeholder\n const workDoneMatch = content.match(/## Work Done\\n\\n(<!-- .*? -->)?/);\n if (workDoneMatch) {\n const insertPoint = content.indexOf(workDoneMatch[0]) + workDoneMatch[0].length;\n content = content.substring(0, insertPoint) + workText + content.substring(insertPoint);\n } else {\n // Fallback: insert before Next Steps\n const nextStepsIndex = content.indexOf('## Next Steps');\n if (nextStepsIndex !== -1) {\n content = content.substring(0, nextStepsIndex) + workText + '\\n' + content.substring(nextStepsIndex);\n }\n }\n\n writeFileSync(notePath, content);\n console.error(`Added ${workItems.length} work item(s) to: ${basename(notePath)}`);\n}\n\n/**\n * Update the session note title to be more descriptive\n * Called when we know what work was done\n */\nexport function updateSessionNoteTitle(notePath: string, newTitle: string): void {\n if (!existsSync(notePath)) {\n console.error(`Note file not found: ${notePath}`);\n return;\n }\n\n let content = readFileSync(notePath, 'utf-8');\n\n // Update the H1 title\n content = content.replace(/^# Session \\d+:.*$/m, (match) => {\n const sessionNum = match.match(/Session (\\d+)/)?.[1] || '';\n return `# Session ${sessionNum}: ${newTitle}`;\n });\n\n writeFileSync(notePath, content);\n\n // Also rename the file\n renameSessionNote(notePath, sanitizeForFilename(newTitle));\n}\n\n/**\n * Sanitize a string for use in a filename (exported for use elsewhere)\n */\nexport function sanitizeForFilename(str: string): string {\n return str\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, '') // Remove special chars\n .replace(/\\s+/g, '-') // Spaces to hyphens\n .replace(/-+/g, '-') // Collapse multiple hyphens\n .replace(/^-|-$/g, '') // Trim hyphens\n .substring(0, 50); // Limit length\n}\n\n/**\n * Extract a meaningful name from session note content\n * Looks at Work Done section and summary to generate a descriptive name\n */\nexport function extractMeaningfulName(noteContent: string, summary: string): string {\n // Try to extract from Work Done section headers (### headings)\n const workDoneMatch = noteContent.match(/## Work Done\\n\\n([\\s\\S]*?)(?=\\n---|\\n## Next)/);\n\n if (workDoneMatch) {\n const workDoneSection = workDoneMatch[1];\n\n // Look for ### subheadings which typically describe what was done\n const subheadings = workDoneSection.match(/### ([^\\n]+)/g);\n if (subheadings && subheadings.length > 0) {\n // Use the first subheading, clean it up\n const firstHeading = subheadings[0].replace('### ', '').trim();\n if (firstHeading.length > 5 && firstHeading.length < 60) {\n return sanitizeForFilename(firstHeading);\n }\n }\n\n // Look for bold text which often indicates key topics\n const boldMatches = workDoneSection.match(/\\*\\*([^*]+)\\*\\*/g);\n if (boldMatches && boldMatches.length > 0) {\n const firstBold = boldMatches[0].replace(/\\*\\*/g, '').trim();\n if (firstBold.length > 3 && firstBold.length < 50) {\n return sanitizeForFilename(firstBold);\n }\n }\n\n // Look for numbered list items (1. Something)\n const numberedItems = workDoneSection.match(/^\\d+\\.\\s+\\*\\*([^*]+)\\*\\*/m);\n if (numberedItems) {\n return sanitizeForFilename(numberedItems[1]);\n }\n }\n\n // Fall back to summary if provided\n if (summary && summary.length > 5 && summary !== 'Session completed.') {\n // Take first meaningful phrase from summary\n const cleanSummary = summary\n .replace(/[^\\w\\s-]/g, ' ')\n .trim()\n .split(/\\s+/)\n .slice(0, 5)\n .join(' ');\n\n if (cleanSummary.length > 3) {\n return sanitizeForFilename(cleanSummary);\n }\n }\n\n return '';\n}\n\n/**\n * Rename session note with a meaningful name\n * ALWAYS uses correct format: \"NNNN - YYYY-MM-DD - Description.md\"\n * Returns the new path, or original path if rename fails\n */\nexport function renameSessionNote(notePath: string, meaningfulName: string): string {\n if (!meaningfulName || !existsSync(notePath)) {\n return notePath;\n }\n\n const dir = join(notePath, '..');\n const oldFilename = basename(notePath);\n\n // Parse existing filename - support multiple formats:\n // CORRECT: \"0001 - 2026-01-02 - Description.md\"\n // Legacy: \"001_2026-01-02_description.md\"\n const correctMatch = oldFilename.match(/^(\\d{3,4}) - (\\d{4}-\\d{2}-\\d{2}) - .*\\.md$/);\n const legacyMatch = oldFilename.match(/^(\\d{3,4})_(\\d{4}-\\d{2}-\\d{2})_.*\\.md$/);\n\n const match = correctMatch || legacyMatch;\n if (!match) {\n return notePath; // Can't parse, don't rename\n }\n\n const [, noteNumber, date] = match;\n\n // Convert to Title Case\n const titleCaseName = meaningfulName\n .split(/[\\s_-]+/)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(' ')\n .trim();\n\n // ALWAYS use correct format with 4-digit number\n const paddedNumber = noteNumber.padStart(4, '0');\n const newFilename = `${paddedNumber} - ${date} - ${titleCaseName}.md`;\n const newPath = join(dir, newFilename);\n\n // Don't rename if name is the same\n if (newFilename === oldFilename) {\n return notePath;\n }\n\n try {\n renameSync(notePath, newPath);\n console.error(`Renamed note: ${oldFilename} \u2192 ${newFilename}`);\n return newPath;\n } catch (error) {\n console.error(`Could not rename note: ${error}`);\n return notePath;\n }\n}\n\n/**\n * Finalize session note (mark as complete, add summary, rename with meaningful name)\n * IDEMPOTENT: Will only finalize once, subsequent calls are no-ops\n * Returns the final path (may be renamed)\n */\nexport function finalizeSessionNote(notePath: string, summary: string): string {\n if (!existsSync(notePath)) {\n console.error(`Note file not found: ${notePath}`);\n return notePath;\n }\n\n let content = readFileSync(notePath, 'utf-8');\n\n // IDEMPOTENT CHECK: If already completed, don't modify again\n if (content.includes('**Status:** Completed')) {\n console.error(`Note already finalized: ${basename(notePath)}`);\n return notePath;\n }\n\n // Update status\n content = content.replace('**Status:** In Progress', '**Status:** Completed');\n\n // Add completion timestamp (only if not already present)\n if (!content.includes('**Completed:**')) {\n const completionTime = new Date().toISOString();\n content = content.replace(\n '---\\n\\n## Work Done',\n `**Completed:** ${completionTime}\\n\\n---\\n\\n## Work Done`\n );\n }\n\n // Add summary to Next Steps section (only if placeholder exists)\n const nextStepsMatch = content.match(/## Next Steps\\n\\n(<!-- .*? -->)/);\n if (nextStepsMatch) {\n content = content.replace(\n nextStepsMatch[0],\n `## Next Steps\\n\\n${summary || 'Session completed.'}`\n );\n }\n\n writeFileSync(notePath, content);\n console.error(`Session note finalized: ${basename(notePath)}`);\n\n // Extract meaningful name and rename the file\n const meaningfulName = extractMeaningfulName(content, summary);\n if (meaningfulName) {\n const newPath = renameSessionNote(notePath, meaningfulName);\n return newPath;\n }\n\n return notePath;\n}\n\n/**\n * Calculate total tokens from a session .jsonl file\n */\nexport function calculateSessionTokens(jsonlPath: string): number {\n if (!existsSync(jsonlPath)) {\n return 0;\n }\n\n try {\n const content = readFileSync(jsonlPath, 'utf-8');\n const lines = content.trim().split('\\n');\n let totalTokens = 0;\n\n for (const line of lines) {\n try {\n const entry = JSON.parse(line);\n if (entry.message?.usage) {\n const usage = entry.message.usage;\n totalTokens += (usage.input_tokens || 0);\n totalTokens += (usage.output_tokens || 0);\n totalTokens += (usage.cache_creation_input_tokens || 0);\n totalTokens += (usage.cache_read_input_tokens || 0);\n }\n } catch {\n // Skip invalid JSON lines\n }\n }\n\n return totalTokens;\n } catch (error) {\n console.error(`Error calculating tokens: ${error}`);\n return 0;\n }\n}\n\n/**\n * Find TODO.md - check local first, fallback to central\n */\nexport function findTodoPath(cwd: string): string {\n // Check local locations first\n const localPaths = [\n join(cwd, 'TODO.md'),\n join(cwd, 'notes', 'TODO.md'),\n join(cwd, 'Notes', 'TODO.md'),\n join(cwd, '.claude', 'TODO.md')\n ];\n\n for (const path of localPaths) {\n if (existsSync(path)) {\n return path;\n }\n }\n\n // Fallback to central location (inside Notes/)\n return join(getNotesDir(cwd), 'TODO.md');\n}\n\n/**\n * Find CLAUDE.md - check local locations\n * Returns the FIRST found path (for backwards compatibility)\n */\nexport function findClaudeMdPath(cwd: string): string | null {\n const paths = findAllClaudeMdPaths(cwd);\n return paths.length > 0 ? paths[0] : null;\n}\n\n/**\n * Find ALL CLAUDE.md files in local locations\n * Returns paths in priority order (most specific first):\n * 1. .claude/CLAUDE.md (project-specific config dir)\n * 2. CLAUDE.md (project root)\n * 3. Notes/CLAUDE.md (notes directory)\n * 4. Prompts/CLAUDE.md (prompts directory)\n *\n * All found files will be loaded and injected into context.\n */\nexport function findAllClaudeMdPaths(cwd: string): string[] {\n const foundPaths: string[] = [];\n\n // Priority order: most specific first\n const localPaths = [\n join(cwd, '.claude', 'CLAUDE.md'),\n join(cwd, 'CLAUDE.md'),\n join(cwd, 'Notes', 'CLAUDE.md'),\n join(cwd, 'notes', 'CLAUDE.md'),\n join(cwd, 'Prompts', 'CLAUDE.md'),\n join(cwd, 'prompts', 'CLAUDE.md')\n ];\n\n for (const path of localPaths) {\n if (existsSync(path)) {\n foundPaths.push(path);\n }\n }\n\n return foundPaths;\n}\n\n/**\n * Ensure TODO.md exists\n */\nexport function ensureTodoMd(cwd: string): string {\n const todoPath = findTodoPath(cwd);\n\n if (!existsSync(todoPath)) {\n // Ensure parent directory exists\n const parentDir = join(todoPath, '..');\n if (!existsSync(parentDir)) {\n mkdirSync(parentDir, { recursive: true });\n }\n\n const content = `# TODO\n\n## Current Session\n\n- [ ] (Tasks will be tracked here)\n\n## Backlog\n\n- [ ] (Future tasks)\n\n---\n\n*Last updated: ${new Date().toISOString()}*\n`;\n\n writeFileSync(todoPath, content);\n console.error(`Created TODO.md: ${todoPath}`);\n }\n\n return todoPath;\n}\n\n/**\n * Task item for TODO.md\n */\nexport interface TodoItem {\n content: string;\n completed: boolean;\n}\n\n/**\n * Update TODO.md with current session tasks\n * Preserves the Backlog section\n * Ensures only ONE timestamp line at the end\n */\nexport function updateTodoMd(cwd: string, tasks: TodoItem[], sessionSummary?: string): void {\n const todoPath = ensureTodoMd(cwd);\n const content = readFileSync(todoPath, 'utf-8');\n\n // Find Backlog section to preserve it (but strip any trailing timestamps/separators)\n const backlogMatch = content.match(/## Backlog[\\s\\S]*?(?=\\n---|\\n\\*Last updated|$)/);\n let backlogSection = backlogMatch ? backlogMatch[0].trim() : '## Backlog\\n\\n- [ ] (Future tasks)';\n\n // Format tasks\n const taskLines = tasks.length > 0\n ? tasks.map(t => `- [${t.completed ? 'x' : ' '}] ${t.content}`).join('\\n')\n : '- [ ] (No active tasks)';\n\n // Build new content with exactly ONE timestamp at the end\n const newContent = `# TODO\n\n## Current Session\n\n${taskLines}\n\n${sessionSummary ? `**Session Summary:** ${sessionSummary}\\n\\n` : ''}${backlogSection}\n\n---\n\n*Last updated: ${new Date().toISOString()}*\n`;\n\n writeFileSync(todoPath, newContent);\n console.error(`Updated TODO.md: ${todoPath}`);\n}\n\n/**\n * Add a checkpoint entry to TODO.md (without replacing tasks)\n * Ensures only ONE timestamp line at the end\n * Works regardless of TODO.md structure \u2014 appends if no known section found\n */\nexport function addTodoCheckpoint(cwd: string, checkpoint: string): void {\n const todoPath = ensureTodoMd(cwd);\n let content = readFileSync(todoPath, 'utf-8');\n\n // Remove ALL existing timestamp lines and trailing separators\n content = content.replace(/(\\n---\\s*)*(\\n\\*Last updated:.*\\*\\s*)+$/g, '');\n\n const checkpointText = `\\n**Checkpoint (${new Date().toISOString()}):** ${checkpoint}\\n\\n`;\n\n // Try to insert before Backlog section\n const backlogIndex = content.indexOf('## Backlog');\n if (backlogIndex !== -1) {\n content = content.substring(0, backlogIndex) + checkpointText + content.substring(backlogIndex);\n } else {\n // No Backlog section \u2014 try before Continue section, or just append\n const continueIndex = content.indexOf('## Continue');\n if (continueIndex !== -1) {\n // Insert after the Continue section (find the next ## or ---)\n const afterContinue = content.indexOf('\\n---', continueIndex);\n if (afterContinue !== -1) {\n const insertAt = afterContinue + 4; // after \\n---\n content = content.substring(0, insertAt) + '\\n' + checkpointText + content.substring(insertAt);\n } else {\n content = content.trimEnd() + '\\n' + checkpointText;\n }\n } else {\n // No known section \u2014 just append before the end\n content = content.trimEnd() + '\\n' + checkpointText;\n }\n }\n\n // Add exactly ONE timestamp at the end\n content = content.trimEnd() + `\\n\\n---\\n\\n*Last updated: ${new Date().toISOString()}*\\n`;\n\n writeFileSync(todoPath, content);\n console.error(`Checkpoint added to TODO.md`);\n}\n\n/**\n * Update the ## Continue section at the top of TODO.md.\n * This mirrors \"pause session\" behavior \u2014 gives the next session a starting point.\n * Replaces any existing ## Continue section.\n */\nexport function updateTodoContinue(\n cwd: string,\n noteFilename: string,\n state: string | null,\n tokenDisplay: string\n): void {\n const todoPath = ensureTodoMd(cwd);\n let content = readFileSync(todoPath, 'utf-8');\n\n // Remove existing ## Continue section (from ## Continue to the first standalone --- line)\n content = content.replace(/## Continue\\n[\\s\\S]*?\\n---\\n+/, '');\n\n const now = new Date().toISOString();\n const stateLines = state\n ? state.split('\\n').filter(l => l.trim()).slice(0, 10).map(l => `> ${l}`).join('\\n')\n : `> Check the latest session note for details.`;\n\n const continueSection = `## Continue\n\n> **Last session:** ${noteFilename.replace('.md', '')}\n> **Paused at:** ${now}\n>\n${stateLines}\n\n---\n\n`;\n\n // Remove leading whitespace from content\n content = content.replace(/^\\s+/, '');\n\n // If content starts with # title, insert after it\n const titleMatch = content.match(/^(# [^\\n]+\\n+)/);\n if (titleMatch) {\n content = titleMatch[1] + continueSection + content.substring(titleMatch[0].length);\n } else {\n content = continueSection + content;\n }\n\n // Clean up trailing timestamps and add fresh one\n content = content.replace(/(\\n---\\s*)*(\\n\\*Last updated:.*\\*\\s*)+$/g, '');\n content = content.trimEnd() + `\\n\\n---\\n\\n*Last updated: ${now}*\\n`;\n\n writeFileSync(todoPath, content);\n console.error('TODO.md ## Continue section updated');\n}\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;AAsBA,SAAS,cAAAA,aAAY,UAAU,gBAAAC,eAAc,iBAAAC,sBAAqB;AAClE,SAAS,QAAAC,aAAY;AACrB,SAAS,cAAc;;;ACXvB,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAC9B,SAAS,YAAY,oBAAoB;AAMzC,SAAS,cAAoB;AAE3B,QAAM,gBAAgB;AAAA,IACpB,QAAQ,QAAQ,IAAI,WAAW,IAAI,MAAM;AAAA,IACzC,QAAQ,QAAQ,GAAG,WAAW,MAAM;AAAA,EACtC;AAEA,aAAW,WAAW,eAAe;AACnC,QAAI,WAAW,OAAO,GAAG;AACvB,UAAI;AACF,cAAM,UAAU,aAAa,SAAS,OAAO;AAC7C,mBAAW,QAAQ,QAAQ,MAAM,IAAI,GAAG;AACtC,gBAAM,UAAU,KAAK,KAAK;AAE1B,cAAI,CAAC,WAAW,QAAQ,WAAW,GAAG,EAAG;AAEzC,gBAAM,UAAU,QAAQ,QAAQ,GAAG;AACnC,cAAI,UAAU,GAAG;AACf,kBAAM,MAAM,QAAQ,UAAU,GAAG,OAAO,EAAE,KAAK;AAC/C,gBAAI,QAAQ,QAAQ,UAAU,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;AAAA,EACT;AACF;AAEA,eAAe,OAAO;AACpB,MAAI;AAEF,UAAM,mBAAmB,QAAQ,IAAI,sBAAsB;AAC3D,UAAM,aAAa,iBAAiB,SAAS,kBAAkB,KAC7C,QAAQ,IAAI,sBAAsB;AAEpD,QAAI,YAAY;AAEd,cAAQ,MAAM,6DAA6D;AAC3E,cAAQ,KAAK,CAAC;AAAA,IAChB;AAIA,QAAI,eAAe,GAAG;AACpB,cAAQ,MAAM,yCAAyC;AACvD,cAAQ,KAAK,CAAC;AAAA,IAChB;AAKA,QAAI,kBAAkB,GAAG;AACvB,cAAQ,MAAM,yCAAyC;AACvD,cAAQ,IAAI;AAAA;AAAA,mBAEC;AAAA,IACf;AAGA,UAAM,aAAa,MAAM,aAAa;AAEtC,UAAM,SAAS,QAAQ,IAAI,MAAM;AAEjC,QAAI,CAAC,YAAY;AACf,cAAQ,MAAM,sEAAsE;AAAA,IACtF;AAQA,UAAM,qBAAqB,GAAG,MAAM,QAAQ;AAE5C,YAAQ,KAAK,CAAC;AAAA,EAChB,SAAS,OAAO;AACd,YAAQ,MAAM,4BAA4B,KAAK;AAC/C,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;AAEA,KAAK;",
|
|
6
6
|
"names": ["existsSync", "readFileSync", "writeFileSync", "join", "existsSync", "readFileSync", "join", "join", "homedir", "join", "existsSync", "readFileSync", "resolve", "join", "existsSync", "readFileSync", "writeFileSync"]
|
|
7
7
|
}
|