GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — claude-code-source-code/src/commands/insights.ts at main · wangwang4git/claude-code-source-code Expand file tree/ Copy pathinsights.tsMore file actions 3200 lines (2892 loc) · 113 KB / Copy pathinsights.tsFile metadata and controls3200 lines (2892 loc) · 113 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 import { execFileSync } from 'child_process' import { diffLines } from 'diff' import { constants as fsConstants } from 'fs' import { copyFile, mkdir, mkdtemp, readdir, readFile, rm, unlink, writeFile, } from 'fs/promises' import { tmpdir } from 'os' import { extname, join } from 'path' import type { Command } from '../commands.js' import { queryWithModel } from '../services/api/claude.js' import { AGENT_TOOL_NAME, LEGACY_AGENT_TOOL_NAME, } from '../tools/AgentTool/constants.js' import type { LogOption } from '../types/logs.js' import { getClaudeConfigHomeDir } from '../utils/envUtils.js' import { toError } from '../utils/errors.js' import { execFileNoThrow } from '../utils/execFileNoThrow.js' import { logError } from '../utils/log.js' import { extractTextContent } from '../utils/messages.js' import { getDefaultOpusModel } from '../utils/model/model.js' import { getProjectsDir, getSessionFilesWithMtime, getSessionIdFromLog, loadAllLogsFromSessionFile, } from '../utils/sessionStorage.js' import { jsonParse, jsonStringify } from '../utils/slowOperations.js' import { countCharInString } from '../utils/stringUtils.js' import { asSystemPrompt } from '../utils/systemPromptType.js' import { escapeXmlAttr as escapeHtml } from '../utils/xml.js' // Model for facet extraction and summarization (Opus - best quality) function getAnalysisModel(): string { return getDefaultOpusModel() } // Model for narrative insights (Opus - best quality) function getInsightsModel(): string { return getDefaultOpusModel() } // ============================================================================ // Homespace Data Collection // ============================================================================ type RemoteHostInfo = { name: string sessionCount: number } /* eslint-disable custom-rules/no-process-env-top-level */ const getRunningRemoteHosts: () => Promise<string[]> = process.env.USER_TYPE === 'ant' ? async () => { const { stdout, code } = await execFileNoThrow( 'coder', ['list', '-o', 'json'], { timeout: 30000 }, ) if (code !== 0) return [] try { const workspaces = jsonParse(stdout) as Array<{ name: string latest_build?: { status?: string } }> return workspaces .filter(w => w.latest_build?.status === 'running') .map(w => w.name) } catch { return [] } } : async () => [] const getRemoteHostSessionCount: (hs: string) => Promise<number> = process.env.USER_TYPE === 'ant' ? async (homespace: string) => { const { stdout, code } = await execFileNoThrow( 'ssh', [ `${homespace}.coder`, 'find /root/.claude/projects -name "*.jsonl" 2>/dev/null | wc -l', ], { timeout: 30000 }, ) if (code !== 0) return 0 return parseInt(stdout.trim(), 10) || 0 } : async () => 0 const collectFromRemoteHost: ( hs: string, destDir: string, ) => Promise<{ copied: number; skipped: number }> = process.env.USER_TYPE === 'ant' ? async (homespace: string, destDir: string) => { const result = { copied: 0, skipped: 0 } // Create temp directory const tempDir = await mkdtemp(join(tmpdir(), 'claude-hs-')) try { // SCP the projects folder const scpResult = await execFileNoThrow( 'scp', ['-rq', `${homespace}.coder:/root/.claude/projects/`, tempDir], { timeout: 300000 }, ) if (scpResult.code !== 0) { // SCP failed return result } const projectsDir = join(tempDir, 'projects') let projectDirents: Awaited<ReturnType<typeof readdir>> try { projectDirents = await readdir(projectsDir, { withFileTypes: true }) } catch { return result } // Merge into destination (parallel per project directory) await Promise.all( projectDirents.map(async dirent => { const projectName = dirent.name const projectPath = join(projectsDir, projectName) // Skip if not a directory if (!dirent.isDirectory()) return const destProjectName = `${projectName}__${homespace}` const destProjectPath = join(destDir, destProjectName) try { await mkdir(destProjectPath, { recursive: true }) } catch { // Directory may already exist } // Copy session files (skip existing) let files: Awaited<ReturnType<typeof readdir>> try { files = await readdir(projectPath, { withFileTypes: true }) } catch { return } await Promise.all( files.map(async fileDirent => { const fileName = fileDirent.name if (!fileName.endsWith('.jsonl')) return const srcFile = join(projectPath, fileName) const destFile = join(destProjectPath, fileName) try { await copyFile(srcFile, destFile, fsConstants.COPYFILE_EXCL) result.copied++ } catch { // EEXIST from COPYFILE_EXCL means dest already exists result.skipped++ } }), ) }), ) } finally { try { await rm(tempDir, { recursive: true, force: true }) } catch { // Ignore cleanup errors } } return result } : async () => ({ copied: 0, skipped: 0 }) const collectAllRemoteHostData: (destDir: string) => Promise<{ hosts: RemoteHostInfo[] totalCopied: number totalSkipped: number }> = process.env.USER_TYPE === 'ant' ? async (destDir: string) => { const rHosts = await getRunningRemoteHosts() const result: RemoteHostInfo[] = [] let totalCopied = 0 let totalSkipped = 0 // Collect from all hosts in parallel (SCP per host can take seconds) const hostResults = await Promise.all( rHosts.map(async hs => { const sessionCount = await getRemoteHostSessionCount(hs) if (sessionCount > 0) { const { copied, skipped } = await collectFromRemoteHost( hs, destDir, ) return { name: hs, sessionCount, copied, skipped } } return { name: hs, sessionCount, copied: 0, skipped: 0 } }), ) for (const hr of hostResults) { result.push({ name: hr.name, sessionCount: hr.sessionCount }) totalCopied += hr.copied totalSkipped += hr.skipped } return { hosts: result, totalCopied, totalSkipped } } : async () => ({ hosts: [], totalCopied: 0, totalSkipped: 0 }) /* eslint-enable custom-rules/no-process-env-top-level */ // ============================================================================ // Types // ============================================================================ type SessionMeta = { session_id: string project_path: string start_time: string duration_minutes: number user_message_count: number assistant_message_count: number tool_counts: Record<string, number> languages: Record<string, number> git_commits: number git_pushes: number input_tokens: number output_tokens: number first_prompt: string summary?: string // New stats user_interruptions: number user_response_times: number[] tool_errors: number tool_error_categories: Record<string, number> uses_task_agent: boolean uses_mcp: boolean uses_web_search: boolean uses_web_fetch: boolean // Additional stats lines_added: number lines_removed: number files_modified: number message_hours: number[] user_message_timestamps: string[] // ISO timestamps for multi-clauding detection } type SessionFacets = { session_id: string underlying_goal: string goal_categories: Record<string, number> outcome: string user_satisfaction_counts: Record<string, number> claude_helpfulness: string session_type: string friction_counts: Record<string, number> friction_detail: string primary_success: string brief_summary: string user_instructions_to_claude?: string[] } type AggregatedData = { total_sessions: number total_sessions_scanned?: number sessions_with_facets: number date_range: { start: string; end: string } total_messages: number total_duration_hours: number total_input_tokens: number total_output_tokens: number tool_counts: Record<string, number> languages: Record<string, number> git_commits: number git_pushes: number projects: Record<string, number> goal_categories: Record<string, number> outcomes: Record<string, number> satisfaction: Record<string, number> helpfulness: Record<string, number> session_types: Record<string, number> friction: Record<string, number> success: Record<string, number> session_summaries: Array<{ id: string date: string summary: string goal?: string }> // New aggregated stats total_interruptions: number total_tool_errors: number tool_error_categories: Record<string, number> user_response_times: number[] median_response_time: number avg_response_time: number sessions_using_task_agent: number sessions_using_mcp: number sessions_using_web_search: number sessions_using_web_fetch: number // Additional stats from Python reference total_lines_added: number total_lines_removed: number total_files_modified: number days_active: number messages_per_day: number message_hours: number[] // Hour of day for each user message (for time of day chart) // Multi-clauding stats (matching Python reference) multi_clauding: { overlap_events: number sessions_involved: number user_messages_during: number } } // ============================================================================ // Constants // ============================================================================ const EXTENSION_TO_LANGUAGE: Record<string, string> = { '.ts': 'TypeScript', '.tsx': 'TypeScript', '.js': 'JavaScript', '.jsx': 'JavaScript', '.py': 'Python', '.rb': 'Ruby', '.go': 'Go', '.rs': 'Rust', '.java': 'Java', '.md': 'Markdown', '.json': 'JSON', '.yaml': 'YAML', '.yml': 'YAML', '.sh': 'Shell', '.css': 'CSS', '.html': 'HTML', } // Label map for cleaning up category names (matching Python reference) const LABEL_MAP: Record<string, string> = { // Goal categories debug_investigate: 'Debug/Investigate', implement_feature: 'Implement Feature', fix_bug: 'Fix Bug', write_script_tool: 'Write Script/Tool', refactor_code: 'Refactor Code', configure_system: 'Configure System', create_pr_commit: 'Create PR/Commit', analyze_data: 'Analyze Data', understand_codebase: 'Understand Codebase', write_tests: 'Write Tests', write_docs: 'Write Docs', deploy_infra: 'Deploy/Infra', warmup_minimal: 'Cache Warmup', // Success factors fast_accurate_search: 'Fast/Accurate Search', correct_code_edits: 'Correct Code Edits', good_explanations: 'Good Explanations', proactive_help: 'Proactive Help', multi_file_changes: 'Multi-file Changes', handled_complexity: 'Multi-file Changes', good_debugging: 'Good Debugging', // Friction types misunderstood_request: 'Misunderstood Request', wrong_approach: 'Wrong Approach', buggy_code: 'Buggy Code', user_rejected_action: 'User Rejected Action', claude_got_blocked: 'Claude Got Blocked', user_stopped_early: 'User Stopped Early', wrong_file_or_location: 'Wrong File/Location', excessive_changes: 'Excessive Changes', slow_or_verbose: 'Slow/Verbose', tool_failed: 'Tool Failed', user_unclear: 'User Unclear', external_issue: 'External Issue', // Satisfaction labels frustrated: 'Frustrated', dissatisfied: 'Dissatisfied', likely_satisfied: 'Likely Satisfied', satisfied: 'Satisfied', happy: 'Happy', unsure: 'Unsure', neutral: 'Neutral', delighted: 'Delighted', // Session types single_task: 'Single Task', multi_task: 'Multi Task', iterative_refinement: 'Iterative Refinement', exploration: 'Exploration', quick_question: 'Quick Question', // Outcomes fully_achieved: 'Fully Achieved', mostly_achieved: 'Mostly Achieved', partially_achieved: 'Partially Achieved', not_achieved: 'Not Achieved', unclear_from_transcript: 'Unclear', // Helpfulness unhelpful: 'Unhelpful', slightly_helpful: 'Slightly Helpful', moderately_helpful: 'Moderately Helpful', very_helpful: 'Very Helpful', essential: 'Essential', } // Lazy getters: getClaudeConfigHomeDir() is memoized and reads process.env. // Calling it at module scope would populate the memoize cache before // entrypoints can set CLAUDE_CONFIG_DIR, breaking all 150+ other callers. function getDataDir(): string { return join(getClaudeConfigHomeDir(), 'usage-data') } function getFacetsDir(): string { return join(getDataDir(), 'facets') } function getSessionMetaDir(): string { return join(getDataDir(), 'session-meta') } const FACET_EXTRACTION_PROMPT = `Analyze this Claude Code session and extract structured facets. CRITICAL GUIDELINES: 1. **goal_categories**: Count ONLY what the USER explicitly asked for. - DO NOT count Claude's autonomous codebase exploration - DO NOT count work Claude decided to do on its own - ONLY count when user says "can you...", "please...", "I need...", "let's..." 2. **user_satisfaction_counts**: Base ONLY on explicit user signals. - "Yay!", "great!", "perfect!" → happy - "thanks", "looks good", "that works" → satisfied - "ok, now let's..." (continuing without complaint) → likely_satisfied - "that's not right", "try again" → dissatisfied - "this is broken", "I give up" → frustrated 3. **friction_counts**: Be specific about what went wrong. - misunderstood_request: Claude interpreted incorrectly - wrong_approach: Right goal, wrong solution method - buggy_code: Code didn't work correctly - user_rejected_action: User said no/stop to a tool call - excessive_changes: Over-engineered or changed too much 4. If very short or just warmup, use warmup_minimal for goal_category SESSION: ` // ============================================================================ // Helper Functions // ============================================================================ function getLanguageFromPath(filePath: string): string | null { const ext = extname(filePath).toLowerCase() return EXTENSION_TO_LANGUAGE[ext] || null } function extractToolStats(log: LogOption): { toolCounts: Record<string, number> languages: Record<string, number> gitCommits: number gitPushes: number inputTokens: number outputTokens: number // New stats userInterruptions: number userResponseTimes: number[] toolErrors: number toolErrorCategories: Record<string, number> usesTaskAgent: boolean usesMcp: boolean usesWebSearch: boolean usesWebFetch: boolean // Additional stats linesAdded: number linesRemoved: number filesModified: Set<string> messageHours: number[] userMessageTimestamps: string[] // ISO timestamps for multi-clauding detection } { const toolCounts: Record<string, number> = {} const languages: Record<string, number> = {} let gitCommits = 0 let gitPushes = 0 let inputTokens = 0 let outputTokens = 0 // New stats let userInterruptions = 0 const userResponseTimes: number[] = [] let toolErrors = 0 const toolErrorCategories: Record<string, number> = {} let usesTaskAgent = false // Additional stats let linesAdded = 0 let linesRemoved = 0 const filesModified = new Set<string>() const messageHours: number[] = [] const userMessageTimestamps: string[] = [] // For multi-clauding detection let usesMcp = false let usesWebSearch = false let usesWebFetch = false let lastAssistantTimestamp: string | null = null for (const msg of log.messages) { // Get message timestamp for response time calculation const msgTimestamp = (msg as { timestamp?: string }).timestamp if (msg.type === 'assistant' && msg.message) { // Track timestamp for response time calculation if (msgTimestamp) { lastAssistantTimestamp = msgTimestamp } const usage = ( msg.message as { usage?: { input_tokens?: number; output_tokens?: number } } ).usage if (usage) { inputTokens += usage.input_tokens || 0 outputTokens += usage.output_tokens || 0 } const content = msg.message.content if (Array.isArray(content)) { for (const block of content) { if (block.type === 'tool_use' && 'name' in block) { const toolName = block.name as string toolCounts[toolName] = (toolCounts[toolName] || 0) + 1 // Check for special tool usage if ( toolName === AGENT_TOOL_NAME || toolName === LEGACY_AGENT_TOOL_NAME ) usesTaskAgent = true if (toolName.startsWith('mcp__')) usesMcp = true if (toolName === 'WebSearch') usesWebSearch = true if (toolName === 'WebFetch') usesWebFetch = true const input = (block as { input?: Record<string, unknown> }).input if (input) { const filePath = (input.file_path as string) || '' if (filePath) { const lang = getLanguageFromPath(filePath) if (lang) { languages[lang] = (languages[lang] || 0) + 1 } // Track files modified by Edit/Write tools if (toolName === 'Edit' || toolName === 'Write') { filesModified.add(filePath) } } if (toolName === 'Edit') { const oldString = (input.old_string as string) || '' const newString = (input.new_string as string) || '' for (const change of diffLines(oldString, newString)) { if (change.added) linesAdded += change.count || 0 if (change.removed) linesRemoved += change.count || 0 } } // Track lines from Write tool (all added) if (toolName === 'Write') { const writeContent = (input.content as string) || '' if (writeContent) { linesAdded += countCharInString(writeContent, '\n') + 1 } } const command = (input.command as string) || '' if (command.includes('git commit')) gitCommits++ if (command.includes('git push')) gitPushes++ } } } } } // Check user messages if (msg.type === 'user' && msg.message) { const content = msg.message.content // Check if this is an actual human message (has text) vs just tool_result // matching Python reference logic let isHumanMessage = false if (typeof content === 'string' && content.trim()) { isHumanMessage = true } else if (Array.isArray(content)) { for (const block of content) { if (block.type === 'text' && 'text' in block) { isHumanMessage = true break } } } // Only track message hours and response times for actual human messages if (isHumanMessage) { // Track message hour for time-of-day analysis and timestamp for multi-clauding if (msgTimestamp) { try { const msgDate = new Date(msgTimestamp) const hour = msgDate.getHours() // Local hour 0-23 messageHours.push(hour) // Collect timestamp for multi-clauding detection (matching Python) userMessageTimestamps.push(msgTimestamp) } catch { // Skip invalid timestamps } } // Calculate response time (time from last assistant message to this user message) // Only count gaps > 2 seconds (real user think time, not tool results) if (lastAssistantTimestamp && msgTimestamp) { const assistantTime = new Date(lastAssistantTimestamp).getTime() const userTime = new Date(msgTimestamp).getTime() const responseTimeSec = (userTime - assistantTime) / 1000 // Only count reasonable response times (2s-1 hour) matching Python if (responseTimeSec > 2 && responseTimeSec < 3600) { userResponseTimes.push(responseTimeSec) } } } // Process tool results (for error tracking) if (Array.isArray(content)) { for (const block of content) { if (block.type === 'tool_result' && 'content' in block) { const isError = (block as { is_error?: boolean }).is_error // Count and categorize tool errors (matching Python reference logic) if (isError) { toolErrors++ const resultContent = (block as { content?: string }).content let category = 'Other' if (typeof resultContent === 'string') { const lowerContent = resultContent.toLowerCase() if (lowerContent.includes('exit code')) { category = 'Command Failed' } else if ( lowerContent.includes('rejected') || lowerContent.includes("doesn't want") ) { category = 'User Rejected' } else if ( lowerContent.includes('string to replace not found') || lowerContent.includes('no changes') ) { category = 'Edit Failed' } else if (lowerContent.includes('modified since read')) { category = 'File Changed' } else if ( lowerContent.includes('exceeds maximum') || lowerContent.includes('too large') ) { category = 'File Too Large' } else if ( lowerContent.includes('file not found') || lowerContent.includes('does not exist') ) { category = 'File Not Found' } } toolErrorCategories[category] = (toolErrorCategories[category] || 0) + 1 } } } } // Check for interruptions (matching Python reference) if (typeof content === 'string') { if (content.includes('[Request interrupted by user')) { userInterruptions++ } } else if (Array.isArray(content)) { for (const block of content) { if ( block.type === 'text' && 'text' in block && (block.text as string).includes('[Request interrupted by user') ) { userInterruptions++ break } } } } } return { toolCounts, languages, gitCommits, gitPushes, inputTokens, outputTokens, // New stats userInterruptions, userResponseTimes, toolErrors, toolErrorCategories, usesTaskAgent, usesMcp, usesWebSearch, usesWebFetch, // Additional stats linesAdded, linesRemoved, filesModified, messageHours, userMessageTimestamps, } } function hasValidDates(log: LogOption): boolean { return ( !Number.isNaN(log.created.getTime()) && !Number.isNaN(log.modified.getTime()) ) } function logToSessionMeta(log: LogOption): SessionMeta { const stats = extractToolStats(log) const sessionId = getSessionIdFromLog(log) || 'unknown' const startTime = log.created.toISOString() const durationMinutes = Math.round( (log.modified.getTime() - log.created.getTime()) / 1000 / 60, ) let userMessageCount = 0 let assistantMessageCount = 0 for (const msg of log.messages) { if (msg.type === 'assistant') assistantMessageCount++ // Only count user messages that have actual text content (human messages) // not just tool_result messages (matching Python reference) if (msg.type === 'user' && msg.message) { const content = msg.message.content let isHumanMessage = false if (typeof content === 'string' && content.trim()) { isHumanMessage = true } else if (Array.isArray(content)) { for (const block of content) { if (block.type === 'text' && 'text' in block) { isHumanMessage = true break } } } if (isHumanMessage) { userMessageCount++ } } } return { session_id: sessionId, project_path: log.projectPath || '', start_time: startTime, duration_minutes: durationMinutes, user_message_count: userMessageCount, assistant_message_count: assistantMessageCount, tool_counts: stats.toolCounts, languages: stats.languages, git_commits: stats.gitCommits, git_pushes: stats.gitPushes, input_tokens: stats.inputTokens, output_tokens: stats.outputTokens, first_prompt: log.firstPrompt || '', summary: log.summary, // New stats user_interruptions: stats.userInterruptions, user_response_times: stats.userResponseTimes, tool_errors: stats.toolErrors, tool_error_categories: stats.toolErrorCategories, uses_task_agent: stats.usesTaskAgent, uses_mcp: stats.usesMcp, uses_web_search: stats.usesWebSearch, uses_web_fetch: stats.usesWebFetch, // Additional stats lines_added: stats.linesAdded, lines_removed: stats.linesRemoved, files_modified: stats.filesModified.size, message_hours: stats.messageHours, user_message_timestamps: stats.userMessageTimestamps, } } /** * Deduplicate conversation branches within the same session. * * When a session file has multiple leaf messages (from retries or branching), * loadAllLogsFromSessionFile produces one LogOption per leaf. Each branch * shares the same root message, so its duration overlaps with sibling * branches. This keeps only the branch with the most user messages * (tie-break by longest duration) per session_id. */ export function deduplicateSessionBranches( entries: Array<{ log: LogOption; meta: SessionMeta }>, ): Array<{ log: LogOption; meta: SessionMeta }> { const bestBySession = new Map<string, { log: LogOption; meta: SessionMeta }>() for (const entry of entries) { const id = entry.meta.session_id const existing = bestBySession.get(id) if ( !existing || entry.meta.user_message_count > existing.meta.user_message_count || (entry.meta.user_message_count === existing.meta.user_message_count && entry.meta.duration_minutes > existing.meta.duration_minutes) ) { bestBySession.set(id, entry) } } return [...bestBySession.values()] } function formatTranscriptForFacets(log: LogOption): string { const lines: string[] = [] const meta = logToSessionMeta(log) lines.push(`Session: ${meta.session_id.slice(0, 8)}`) lines.push(`Date: ${meta.start_time}`) lines.push(`Project: ${meta.project_path}`) lines.push(`Duration: ${meta.duration_minutes} min`) lines.push('') for (const msg of log.messages) { if (msg.type === 'user' && msg.message) { const content = msg.message.content if (typeof content === 'string') { lines.push(`[User]: ${content.slice(0, 500)}`) } else if (Array.isArray(content)) { for (const block of content) { if (block.type === 'text' && 'text' in block) { lines.push(`[User]: ${(block.text as string).slice(0, 500)}`) } } } } else if (msg.type === 'assistant' && msg.message) { const content = msg.message.content if (Array.isArray(content)) { for (const block of content) { if (block.type === 'text' && 'text' in block) { lines.push(`[Assistant]: ${(block.text as string).slice(0, 300)}`) } else if (block.type === 'tool_use' && 'name' in block) { lines.push(`[Tool: ${block.name}]`) } } } } } return lines.join('\n') } const SUMMARIZE_CHUNK_PROMPT = `Summarize this portion of a Claude Code session transcript. Focus on: 1. What the user asked for 2. What Claude did (tools used, files modified) 3. Any friction or issues 4. The outcome Keep it concise - 3-5 sentences. Preserve specific details like file names, error messages, and user feedback. TRANSCRIPT CHUNK: ` async function summarizeTranscriptChunk(chunk: string): Promise<string> { try { const result = await queryWithModel({ systemPrompt: asSystemPrompt([]), userPrompt: SUMMARIZE_CHUNK_PROMPT + chunk, signal: new AbortController().signal, options: { model: getAnalysisModel(), querySource: 'insights', agents: [], isNonInteractiveSession: true, hasAppendSystemPrompt: false, mcpTools: [], maxOutputTokensOverride: 500, }, }) const text = extractTextContent(result.message.content) return text || chunk.slice(0, 2000) } catch { // On error, just return truncated chunk return chunk.slice(0, 2000) } } async function formatTranscriptWithSummarization( log: LogOption, ): Promise<string> { const fullTranscript = formatTranscriptForFacets(log) // If under 30k chars, use as-is if (fullTranscript.length <= 30000) { return fullTranscript } // For long transcripts, split into chunks and summarize in parallel const CHUNK_SIZE = 25000 const chunks: string[] = [] for (let i = 0; i < fullTranscript.length; i += CHUNK_SIZE) { chunks.push(fullTranscript.slice(i, i + CHUNK_SIZE)) } // Summarize all chunks in parallel const summaries = await Promise.all(chunks.map(summarizeTranscriptChunk)) // Combine summaries with session header const meta = logToSessionMeta(log) const header = [ `Session: ${meta.session_id.slice(0, 8)}`, `Date: ${meta.start_time}`, `Project: ${meta.project_path}`, `Duration: ${meta.duration_minutes} min`, `[Long session - ${chunks.length} parts summarized]`, '', ].join('\n') return header + summaries.join('\n\n---\n\n') } async function loadCachedFacets( sessionId: string, ): Promise<SessionFacets | null> { const facetPath = join(getFacetsDir(), `${sessionId}.json`) try { const content = await readFile(facetPath, { encoding: 'utf-8' }) const parsed: unknown = jsonParse(content) if (!isValidSessionFacets(parsed)) { // Delete corrupted cache file so it gets re-extracted next run try { await unlink(facetPath) } catch { // Ignore deletion errors } return null } return parsed } catch { return null } } async function saveFacets(facets: SessionFacets): Promise<void> { try { await mkdir(getFacetsDir(), { recursive: true }) } catch { // Directory may already exist } const facetPath = join(getFacetsDir(), `${facets.session_id}.json`) await writeFile(facetPath, jsonStringify(facets, null, 2), { encoding: 'utf-8', mode: 0o600, }) } async function loadCachedSessionMeta( sessionId: string, ): Promise<SessionMeta | null> { const metaPath = join(getSessionMetaDir(), `${sessionId}.json`) try { const content = await readFile(metaPath, { encoding: 'utf-8' }) return jsonParse(content) } catch { return null } } async function saveSessionMeta(meta: SessionMeta): Promise<void> { try { await mkdir(getSessionMetaDir(), { recursive: true }) } catch { // Directory may already exist } const metaPath = join(getSessionMetaDir(), `${meta.session_id}.json`) await writeFile(metaPath, jsonStringify(meta, null, 2), { encoding: 'utf-8', mode: 0o600, }) } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |