bashstats 0.2.0 → 0.2.2
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/NUL +0 -0
- package/README.md +159 -46
- package/dist/chunk-YAJO5WNW.js +2961 -0
- package/dist/chunk-YAJO5WNW.js.map +1 -0
- package/dist/cli.js +103 -40
- package/dist/cli.js.map +1 -1
- package/dist/hooks/{chunk-7K77JJRD.js → chunk-CLSVLWCR.js} +263 -40
- package/dist/hooks/chunk-CLSVLWCR.js.map +1 -0
- package/dist/hooks/notification.js +1 -1
- package/dist/hooks/permission-request.js +1 -1
- package/dist/hooks/post-tool-failure.js +1 -1
- package/dist/hooks/post-tool-use.js +1 -1
- package/dist/hooks/pre-compact.js +1 -1
- package/dist/hooks/pre-tool-use.js +1 -1
- package/dist/hooks/session-start.js +1 -1
- package/dist/hooks/setup.js +1 -1
- package/dist/hooks/stop.js +1 -1
- package/dist/hooks/subagent-start.js +1 -1
- package/dist/hooks/subagent-stop.js +1 -1
- package/dist/hooks/user-prompt-submit.js +1 -1
- package/dist/index.d.ts +194 -17
- package/dist/index.js +31 -5
- package/dist/static/index.html +836 -64
- package/package.json +1 -1
- package/dist/chunk-OYLQHCOY.js +0 -1489
- package/dist/chunk-OYLQHCOY.js.map +0 -1
- package/dist/hooks/chunk-7K77JJRD.js.map +0 -1
|
@@ -0,0 +1,2961 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/constants.ts
|
|
4
|
+
var BADGE_DEFINITIONS = [
|
|
5
|
+
// ===================================================================
|
|
6
|
+
// VOLUME (5)
|
|
7
|
+
// ===================================================================
|
|
8
|
+
{ id: "first_prompt", name: "First Prompt", icon: "\u{1F4AC}", description: "Submit prompts to Claude", category: "volume", stat: "totalPrompts", tiers: [1, 250, 2500, 1e4, 5e4], trigger: "Total prompts submitted across all sessions" },
|
|
9
|
+
{ id: "tool_time", name: "Tool Time", icon: "\u{1F527}", description: "Make tool calls", category: "volume", stat: "totalToolCalls", tiers: [50, 2500, 25e3, 1e5, 5e5], trigger: "Total tool calls made across all sessions" },
|
|
10
|
+
{ id: "marathon", name: "Marathon", icon: "\u{1F3C3}", description: "Spend hours in sessions", category: "volume", stat: "totalSessionHours", tiers: [1, 25, 250, 1e3, 5e3], trigger: "Total hours spent in sessions (rounded down)" },
|
|
11
|
+
{ id: "wordsmith", name: "Wordsmith", icon: "\u270D", description: "Type characters in prompts", category: "volume", stat: "totalCharsTyped", tiers: [1e3, 1e5, 1e6, 5e6, 25e6], trigger: "Total characters typed in prompts" },
|
|
12
|
+
{ id: "session_vet", name: "Session Vet", icon: "\u{1F3C5}", description: "Complete sessions", category: "volume", stat: "totalSessions", tiers: [1, 50, 500, 2500, 1e4], trigger: "Total sessions completed" },
|
|
13
|
+
// ===================================================================
|
|
14
|
+
// TOOL MASTERY (7)
|
|
15
|
+
// ===================================================================
|
|
16
|
+
{ id: "shell_lord", name: "Shell Lord", icon: "\u{1F4BB}", description: "Execute Bash commands", category: "tool_mastery", stat: "totalBashCommands", tiers: [25, 250, 2500, 1e4, 5e4], trigger: "Bash commands executed via PostToolUse" },
|
|
17
|
+
{ id: "bookworm", name: "Bookworm", icon: "\u{1F4D6}", description: "Read files", category: "tool_mastery", stat: "totalFilesRead", tiers: [50, 500, 5e3, 25e3, 1e5], trigger: "Files read with the Read tool" },
|
|
18
|
+
{ id: "editor_in_chief", name: "Editor-in-Chief", icon: "\u{1F4DD}", description: "Edit files", category: "tool_mastery", stat: "totalFilesEdited", tiers: [25, 250, 2500, 1e4, 5e4], trigger: "Files edited with the Edit tool" },
|
|
19
|
+
{ id: "architect", name: "Architect", icon: "\u{1F3D7}", description: "Create files", category: "tool_mastery", stat: "totalFilesCreated", tiers: [10, 100, 500, 2500, 1e4], trigger: "Files created with the Write tool" },
|
|
20
|
+
{ id: "detective", name: "Detective", icon: "\u{1F50D}", description: "Search with Grep and Glob", category: "tool_mastery", stat: "totalSearches", tiers: [50, 500, 5e3, 25e3, 1e5], trigger: "Grep and Glob searches performed" },
|
|
21
|
+
{ id: "web_crawler", name: "Web Crawler", icon: "\u{1F310}", description: "Fetch web pages", category: "tool_mastery", stat: "totalWebFetches", tiers: [5, 50, 200, 1e3, 5e3], trigger: "WebFetch calls made" },
|
|
22
|
+
{ id: "delegator", name: "Delegator", icon: "\u{1F916}", description: "Spawn subagents", category: "tool_mastery", stat: "totalSubagents", tiers: [10, 100, 500, 2500, 1e4], trigger: "Subagents spawned via SubagentStart events" },
|
|
23
|
+
// ===================================================================
|
|
24
|
+
// TIME & PATTERNS (10)
|
|
25
|
+
// ===================================================================
|
|
26
|
+
{ id: "iron_streak", name: "Iron Streak", icon: "\u{1F525}", description: "Maintain a daily streak", category: "time", stat: "longestStreak", tiers: [3, 7, 30, 100, 365], trigger: "Longest streak of consecutive days with activity" },
|
|
27
|
+
{ id: "night_owl", name: "Night Owl", icon: "\u{1F989}", description: "Prompts between midnight and 5am", category: "time", stat: "nightOwlCount", tiers: [10, 50, 200, 1e3, 5e3], trigger: "Prompts submitted between midnight and 5 AM" },
|
|
28
|
+
{ id: "early_bird", name: "Early Bird", icon: "\u{1F426}", description: "Prompts between 5am and 8am", category: "time", stat: "earlyBirdCount", tiers: [10, 50, 200, 1e3, 5e3], trigger: "Prompts submitted between 5 AM and 8 AM" },
|
|
29
|
+
{ id: "weekend_warrior", name: "Weekend Warrior", icon: "\u2694", description: "Weekend sessions", category: "time", stat: "weekendSessions", tiers: [5, 25, 100, 500, 2e3], trigger: "Sessions started on Saturday or Sunday" },
|
|
30
|
+
{ id: "witching_hour", name: "Witching Hour", icon: "\u{1F9D9}", description: "3 AM hits different when you're debugging.", category: "time", stat: "witchingHourPrompts", tiers: [1, 10, 50, 200, 1e3], trigger: "Prompts submitted between 2 AM and 4 AM" },
|
|
31
|
+
{ id: "lunch_break_coder", name: "Lunch Break Coder", icon: "\u{1F354}", description: "Who needs food when you have Claude?", category: "time", stat: "lunchBreakDays", tiers: [5, 15, 30, 60, 120], trigger: "Distinct days with sessions during 12-1 PM" },
|
|
32
|
+
{ id: "monday_motivation", name: "Monday Motivation", icon: "\u{1F4AA}", description: "Starting the week strong (or desperate).", category: "time", stat: "mondaySessions", tiers: [5, 25, 75, 200, 500], trigger: "Sessions started on Monday" },
|
|
33
|
+
{ id: "friday_shipper", name: "Friday Shipper", icon: "\u{1F6A2}", description: "Deploy on Friday? You absolute madlad.", category: "time", stat: "fridayCommits", tiers: [1, 10, 50, 200, 1e3], trigger: "Git commits made on Friday (via Bash tool)" },
|
|
34
|
+
{ id: "timezone_traveler", name: "Timezone Traveler", icon: "\u2708", description: "Your sleep schedule is a suggestion.", category: "time", stat: "maxUniqueHoursInDay", tiers: [6, 8, 12, 16, 20], trigger: "Most unique hours with prompts in a single day" },
|
|
35
|
+
{ id: "seasonal_coder", name: "Seasonal Coder", icon: "\u{1F343}", description: "You've coded through all four seasons.", category: "time", stat: "uniqueQuarters", tiers: [1, 2, 4, 6, 8], trigger: "Unique quarter-year combos (e.g. Q1-2025, Q2-2025) with activity" },
|
|
36
|
+
// ===================================================================
|
|
37
|
+
// SESSION BEHAVIOR (6)
|
|
38
|
+
// ===================================================================
|
|
39
|
+
{ id: "one_more_thing", name: "One More Thing", icon: "\u261D", description: "You said you were done 5 prompts ago.", category: "session_behavior", stat: "extendedSessionCount", tiers: [1, 5, 25, 100, 500], trigger: "Sessions over 1 hour with 15+ prompts" },
|
|
40
|
+
{ id: "quick_draw", name: "Quick Draw", icon: "\u{1F52B}", description: "In and out. 20 second adventure.", category: "session_behavior", stat: "quickDrawSessions", tiers: [5, 25, 100, 500, 2500], trigger: "Sessions under 2 minutes with successful tool use" },
|
|
41
|
+
{ id: "the_pivot", name: "The Pivot", icon: "\u{1F504}", description: "Started with CSS, ended with Kubernetes.", category: "session_behavior", stat: "diverseToolSessions", tiers: [5, 25, 100, 500, 2500], trigger: "Sessions using 5+ distinct tool types" },
|
|
42
|
+
{ id: "context_crunch", name: "Context Crunch", icon: "\u{1F4A6}", description: "Your context window is sweating.", category: "session_behavior", stat: "totalCompactions", tiers: [1, 5, 25, 100, 500], trigger: "PreCompact events triggered (manual or auto)" },
|
|
43
|
+
{ id: "permission_slip", name: "Permission Slip", icon: "\u{1F4DD}", description: "Always asking for permission. So polite.", category: "session_behavior", stat: "permissionRequests", tiers: [10, 100, 500, 2500, 1e4], trigger: "PermissionRequest events recorded" },
|
|
44
|
+
{ id: "the_returner", name: "The Returner", icon: "\u{1F519}", description: "Back so soon? Missed me?", category: "session_behavior", stat: "returnerDays", tiers: [1, 5, 25, 100, 500], trigger: "Days with 5+ sessions on the same project" },
|
|
45
|
+
// ===================================================================
|
|
46
|
+
// BEHAVIORAL (5)
|
|
47
|
+
// ===================================================================
|
|
48
|
+
{ id: "creature_of_habit", name: "Creature of Habit", icon: "\u{1F501}", description: "Repeat your most-used prompt", category: "behavioral", stat: "mostRepeatedPromptCount", tiers: [25, 100, 500, 2e3, 1e4], trigger: "Count of your single most repeated prompt" },
|
|
49
|
+
{ id: "explorer", name: "Explorer", icon: "\u{1F9ED}", description: "Use unique tool types", category: "behavioral", stat: "uniqueToolsUsed", tiers: [3, 5, 8, 12, 18], trigger: "Distinct tool types used across all sessions" },
|
|
50
|
+
{ id: "planner", name: "Planner", icon: "\u{1F4CB}", description: "Use plan mode", category: "behavioral", stat: "planModeUses", tiers: [5, 25, 100, 500, 2e3], trigger: "Task tool invocations (plan mode)" },
|
|
51
|
+
{ id: "novelist", name: "Novelist", icon: "\u{1F4D6}", description: "Write prompts over 1000 characters", category: "behavioral", stat: "longPromptCount", tiers: [5, 25, 100, 500, 2e3], trigger: "Prompts with over 1,000 characters" },
|
|
52
|
+
{ id: "speed_demon", name: "Speed Demon", icon: "\u26A1", description: "Complete sessions in under 5 minutes", category: "behavioral", stat: "quickSessionCount", tiers: [5, 25, 100, 500, 2e3], trigger: "Sessions under 5 minutes with tool use" },
|
|
53
|
+
// ===================================================================
|
|
54
|
+
// PROMPT PATTERNS (6)
|
|
55
|
+
// ===================================================================
|
|
56
|
+
{ id: "minimalist", name: "Minimalist", icon: "\u{1F90F}", description: "A person of few words.", category: "prompt_patterns", stat: "shortPromptCount", tiers: [5, 25, 100, 500, 2e3], trigger: "Prompts with fewer than 10 words" },
|
|
57
|
+
{ id: "question_master", name: "Question Master", icon: "\u2753", description: "So many questions, so little time.", category: "prompt_patterns", stat: "questionPromptCount", tiers: [10, 50, 200, 1e3, 5e3], trigger: "Prompts ending with a question mark" },
|
|
58
|
+
{ id: "the_apologizer", name: "The Apologizer", icon: "\u{1F625}", description: "Sorry for asking, but...", category: "prompt_patterns", stat: "sorryPromptCount", tiers: [1, 10, 50, 200, 1e3], trigger: "Prompts containing the word 'sorry'" },
|
|
59
|
+
{ id: "caps_lock_energy", name: "CAPS LOCK ENERGY", icon: "\u{1F4E2}", description: "WHY ARE WE YELLING?", category: "prompt_patterns", stat: "capsLockPromptCount", tiers: [1, 5, 25, 100, 500], trigger: "Prompts that are fully uppercase (10+ characters)" },
|
|
60
|
+
{ id: "emoji_whisperer", name: "Emoji Whisperer", icon: "\u{1F680}", description: "Deploying vibes", category: "prompt_patterns", stat: "emojiPromptCount", tiers: [5, 25, 100, 500, 2e3], trigger: "Prompts containing emoji characters" },
|
|
61
|
+
{ id: "code_dump", name: "Code Dump", icon: "\u{1F4E6}", description: "Here's 500 lines, figure it out.", category: "prompt_patterns", stat: "codeDumpPromptCount", tiers: [1, 10, 50, 200, 1e3], trigger: "Prompts with 50+ lines of text" },
|
|
62
|
+
// ===================================================================
|
|
63
|
+
// RESILIENCE (3)
|
|
64
|
+
// ===================================================================
|
|
65
|
+
{ id: "clean_hands", name: "Clean Hands", icon: "\u2728", description: "Longest error-free tool streak", category: "resilience", stat: "longestErrorFreeStreak", tiers: [50, 200, 500, 2e3, 1e4], trigger: "Consecutive successful tool calls without any error" },
|
|
66
|
+
{ id: "resilient", name: "Resilient", icon: "\u{1F6E1}", description: "Survive errors", category: "resilience", stat: "totalErrors", tiers: [10, 50, 200, 1e3, 5e3], trigger: "Total errors survived across all sessions" },
|
|
67
|
+
{ id: "rate_limited", name: "Rate Limited", icon: "\u{1F6A7}", description: "Hit rate limits", category: "resilience", stat: "totalRateLimits", tiers: [3, 10, 25, 50, 100], trigger: "Rate limit notification events received" },
|
|
68
|
+
// ===================================================================
|
|
69
|
+
// ERROR & RECOVERY (5)
|
|
70
|
+
// ===================================================================
|
|
71
|
+
{ id: "rubber_duck", name: "Rubber Duck", icon: "\u{1F986}", description: "Explaining the problem IS the solution.", category: "error_recovery", stat: "rubberDuckCount", tiers: [1, 5, 25, 100, 500], trigger: "Tool failure followed by same tool success without Edit in between" },
|
|
72
|
+
{ id: "third_times_charm", name: "Third Time's the Charm", icon: "\u{1F340}", description: "Persistence is a virtue.", category: "error_recovery", stat: "thirdTimeCharmCount", tiers: [1, 5, 25, 100, 500], trigger: "Tool success after 2+ consecutive failures of same tool" },
|
|
73
|
+
{ id: "the_undoer", name: "The Undoer", icon: "\u21A9", description: "Ctrl+Z energy.", category: "error_recovery", stat: "undoEditCount", tiers: [1, 10, 50, 200, 1e3], trigger: "Back-to-back Edit calls on the same file in a session" },
|
|
74
|
+
{ id: "crash_test_dummy", name: "Crash Test Dummy", icon: "\u{1F4A5}", description: "Testing in production, I see.", category: "error_recovery", stat: "crashySessions", tiers: [1, 5, 25, 100, 500], trigger: "Sessions with 10+ errors" },
|
|
75
|
+
{ id: "phoenix", name: "Phoenix", icon: "\u{1F985}", description: "From the ashes of 100 errors, you rise.", category: "error_recovery", stat: "totalLifetimeErrors", tiers: [100, 500, 1e3, 5e3, 1e4], trigger: "Total lifetime errors survived across all sessions" },
|
|
76
|
+
// ===================================================================
|
|
77
|
+
// TOOL COMBOS (5)
|
|
78
|
+
// ===================================================================
|
|
79
|
+
{ id: "read_edit_run", name: "Read-Edit-Run", icon: "\u{1F3AF}", description: "The holy trinity.", category: "tool_combos", stat: "readEditRunCount", tiers: [25, 100, 500, 2e3, 1e4], trigger: "Read \u2192 Edit \u2192 Bash sequences detected in events" },
|
|
80
|
+
{ id: "grep_ninja", name: "Grep Ninja", icon: "\u{1F977}", description: "Finding needles in haystacks since day one.", category: "tool_combos", stat: "totalSearches", tiers: [250, 1e3, 5e3, 25e3, 1e5], trigger: "Total Grep and Glob searches performed" },
|
|
81
|
+
{ id: "file_factory", name: "File Factory", icon: "\u{1F3ED}", description: "You're not creating files, you're creating art.", category: "tool_combos", stat: "maxFilesCreatedInSession", tiers: [10, 20, 50, 100, 200], trigger: "Max Write tool calls in a single session" },
|
|
82
|
+
{ id: "the_refactorer", name: "The Refactorer", icon: "\u267B", description: "Same file, different day.", category: "tool_combos", stat: "maxSameFileEditsLifetime", tiers: [50, 100, 250, 500, 2e3], trigger: "Max Edit calls to any single file path across all sessions" },
|
|
83
|
+
{ id: "search_and_destroy", name: "Search and Destroy", icon: "\u{1F4A2}", description: "Grep it, then wreck it.", category: "tool_combos", stat: "searchThenEditCount", tiers: [25, 100, 500, 2500, 1e4], trigger: "Grep/Glob followed by Edit within same session" },
|
|
84
|
+
// ===================================================================
|
|
85
|
+
// SHIPPING & PROJECTS (4)
|
|
86
|
+
// ===================================================================
|
|
87
|
+
{ id: "shipper", name: "Shipper", icon: "\u{1F4E6}", description: "Make commits via Claude", category: "shipping", stat: "totalCommits", tiers: [5, 50, 200, 1e3, 5e3], trigger: "Bash tool calls containing 'git commit'" },
|
|
88
|
+
{ id: "pr_machine", name: "PR Machine", icon: "\u{1F500}", description: "Create pull requests", category: "shipping", stat: "totalPRs", tiers: [3, 25, 100, 500, 2e3], trigger: "Bash tool calls containing 'gh pr create'" },
|
|
89
|
+
{ id: "empire", name: "Empire", icon: "\u{1F3F0}", description: "Work on unique projects", category: "shipping", stat: "uniqueProjects", tiers: [2, 5, 10, 25, 50], trigger: "Unique project directories worked in" },
|
|
90
|
+
{ id: "polyglot", name: "Polyglot", icon: "\u{1F30D}", description: "Use different programming languages", category: "shipping", stat: "uniqueLanguages", tiers: [3, 5, 8, 15, 25], trigger: "Distinct file extensions in Edit/Write/Read events" },
|
|
91
|
+
// ===================================================================
|
|
92
|
+
// PROJECT DEDICATION (5)
|
|
93
|
+
// ===================================================================
|
|
94
|
+
{ id: "monogamous", name: "Monogamous", icon: "\u{1F48D}", description: "One project. True love.", category: "project_dedication", stat: "maxProjectSessions", tiers: [50, 100, 250, 500, 1e3], trigger: "Max sessions on any single project" },
|
|
95
|
+
{ id: "project_hopper", name: "Project Hopper", icon: "\u{1F407}", description: "Commitment issues? Never heard of her.", category: "project_dedication", stat: "maxProjectsInDay", tiers: [3, 5, 8, 10, 15], trigger: "Max unique projects worked on in a single day" },
|
|
96
|
+
{ id: "the_finisher", name: "The Finisher", icon: "\u{1F3C1}", description: "You actually completed something.", category: "project_dedication", stat: "finishedProjects", tiers: [1, 3, 5, 10, 25], trigger: "Projects with git commits followed by 7+ days of inactivity" },
|
|
97
|
+
{ id: "legacy_code", name: "Legacy Code", icon: "\u{1F9D3}", description: "Revisiting your past mistakes.", category: "project_dedication", stat: "legacyReturns", tiers: [1, 3, 5, 10, 25], trigger: "Returns to a project after 30+ days of inactivity" },
|
|
98
|
+
{ id: "greenfield", name: "Greenfield", icon: "\u{1F331}", description: "That new project smell.", category: "project_dedication", stat: "totalUniqueProjects", tiers: [10, 25, 50, 100, 200], trigger: "Total unique projects initialized" },
|
|
99
|
+
// ===================================================================
|
|
100
|
+
// MULTI-AGENT (6)
|
|
101
|
+
// ===================================================================
|
|
102
|
+
{ id: "buddy_system", name: "Buddy System", icon: "\u{1F91D}", description: "Use concurrent agents", category: "multi_agent", stat: "concurrentAgentUses", tiers: [1, 5, 25, 100, 500], trigger: "Sessions with SubagentStart events" },
|
|
103
|
+
{ id: "hive_mind", name: "Hive Mind", icon: "\u{1F41D}", description: "Spawn subagents total", category: "multi_agent", stat: "totalSubagents", tiers: [25, 250, 1e3, 5e3, 25e3], trigger: "Total SubagentStart events across all sessions" },
|
|
104
|
+
{ id: "swarm_intelligence", name: "Swarm Intelligence", icon: "\u{1F41C}", description: "You've built an army.", category: "multi_agent", stat: "maxConcurrentSubagents", tiers: [3, 5, 8, 12, 20], trigger: "Max concurrent subagents active at any point" },
|
|
105
|
+
{ id: "micromanager", name: "Micromanager", icon: "\u{1F440}", description: "Let them cook? Never heard of it.", category: "multi_agent", stat: "quickSubagentStops", tiers: [1, 5, 25, 100, 500], trigger: "Subagents stopped within 30 seconds of starting" },
|
|
106
|
+
{ id: "the_orchestrator", name: "The Orchestrator", icon: "\u{1F3BC}", description: "You don't code. You conduct.", category: "multi_agent", stat: "totalSubagentSpawns", tiers: [50, 250, 1e3, 5e3, 25e3], trigger: "Total subagent spawns across all sessions" },
|
|
107
|
+
{ id: "agent_smith", name: "Agent Smith", icon: "\u{1F576}", description: "They're multiplying.", category: "multi_agent", stat: "maxSubagentsInSession", tiers: [10, 25, 50, 100, 250], trigger: "Max SubagentStart events in a single session" },
|
|
108
|
+
// --- Cross-agent badges (new) ---
|
|
109
|
+
{ id: "polyglot_agent", name: "Polyglot Agent", icon: "\u{1F30F}", description: "A tool for every occasion.", category: "multi_agent", stat: "distinctAgentsUsed", tiers: [2, 3, 4, 4, 4], trigger: "Distinct CLI agents used (Claude Code, Gemini, Copilot, OpenCode)" },
|
|
110
|
+
{ id: "gemini_whisperer", name: "Gemini Whisperer", icon: "\u264A", description: "The stars aligned for your Gemini sessions.", category: "multi_agent", stat: "geminiSessions", tiers: [10, 50, 200, 1e3, 5e3], trigger: "Sessions completed in Gemini CLI" },
|
|
111
|
+
{ id: "copilot_rider", name: "Copilot Rider", icon: "\u2708", description: "Your copilot is always on duty.", category: "multi_agent", stat: "copilotSessions", tiers: [10, 50, 200, 1e3, 5e3], trigger: "Sessions completed in Copilot CLI" },
|
|
112
|
+
{ id: "open_source_spirit", name: "Open Source Spirit", icon: "\u{1F4A1}", description: "Freedom in every keystroke.", category: "multi_agent", stat: "opencodeSessions", tiers: [10, 50, 200, 1e3, 5e3], trigger: "Sessions completed in OpenCode" },
|
|
113
|
+
{ id: "agent_hopper", name: "Agent Hopper", icon: "\u{1F407}", description: "Can't pick a favorite? Neither can we.", category: "multi_agent", stat: "agentSwitchDays", tiers: [2, 4, 6, 8, 10], trigger: "Days where you used 2+ different CLI agents" },
|
|
114
|
+
{ id: "double_agent", name: "Double Agent", icon: "\u{1F575}", description: "Playing both sides. Respect.", category: "multi_agent", stat: "doubleAgentDays", tiers: [5, 25, 100, 250, 500], trigger: "Days with sessions in 2+ different CLI agents" },
|
|
115
|
+
// ===================================================================
|
|
116
|
+
// WILD CARD (12)
|
|
117
|
+
// ===================================================================
|
|
118
|
+
{ id: "please_thank_you", name: "Please and Thank You", icon: "\u{1F64F}", description: "You're polite to the AI. When they take over, you'll be spared.", category: "wild_card", stat: "politePromptCount", tiers: [10, 50, 200, 1e3, 5e3], trigger: "Prompts containing 'please' or 'thank'" },
|
|
119
|
+
{ id: "wall_of_text", name: "Wall of Text", icon: "\u{1F4DC}", description: "Claude read your entire novel and didn't even complain.", category: "wild_card", stat: "hugePromptCount", tiers: [1, 10, 50, 200, 1e3], trigger: "Prompts over 5,000 characters" },
|
|
120
|
+
{ id: "the_fixer", name: "The Fixer", icon: "\u{1F6E0}", description: "At this point just rewrite the whole thing.", category: "wild_card", stat: "maxSameFileEdits", tiers: [10, 20, 50, 100, 200], trigger: "Max Edit calls to a single file" },
|
|
121
|
+
{ id: "what_day_is_it", name: "What Day Is It?", icon: "\u{1F62B}", description: "Your chair is now a part of you.", category: "wild_card", stat: "longSessionCount", tiers: [1, 5, 25, 100, 500], trigger: "Sessions exceeding 8 hours" },
|
|
122
|
+
{ id: "copy_pasta", name: "Copy Pasta", icon: "\u{1F35D}", description: "Maybe if I ask again it'll work differently.", category: "wild_card", stat: "repeatedPromptCount", tiers: [3, 10, 50, 200, 1e3], trigger: "Total duplicate prompts submitted" },
|
|
123
|
+
{ id: "error_magnet", name: "Error Magnet", icon: "\u{1F9F2}", description: "At this point, the errors are a feature.", category: "wild_card", stat: "maxErrorsInSession", tiers: [10, 25, 50, 100, 200], trigger: "Max errors in a single session" },
|
|
124
|
+
{ id: "deja_vu", name: "D\xE9j\xE0 Vu", icon: "\u{1F408}", description: "Didn't we just do this?", category: "wild_card", stat: "dejaVuCount", tiers: [1, 5, 25, 100, 500], trigger: "Same prompt submitted twice within 5 minutes" },
|
|
125
|
+
{ id: "trust_issues", name: "Trust Issues", icon: "\u{1F50E}", description: "You read the file Claude just wrote.", category: "wild_card", stat: "trustIssueCount", tiers: [1, 10, 50, 200, 1e3], trigger: "Read immediately after Write on the same file" },
|
|
126
|
+
{ id: "backseat_driver", name: "Backseat Driver", icon: "\u{1F697}", description: "Let me tell you exactly how to do your job.", category: "wild_card", stat: "backseatDriverCount", tiers: [1, 10, 50, 200, 1e3], trigger: "Prompts with numbered step-by-step instructions (e.g. '1.' '2.')" },
|
|
127
|
+
{ id: "the_negotiator", name: "The Negotiator", icon: "\u{1F91C}", description: "Can you try again but better?", category: "wild_card", stat: "negotiatorCount", tiers: [1, 10, 50, 200, 1e3], trigger: "Prompts containing 'try again' or 'one more time'" },
|
|
128
|
+
{ id: "rubber_stamp", name: "Rubber Stamp", icon: "\u2705", description: "Yes. Yes. Yes. Approved.", category: "wild_card", stat: "maxConsecutivePermissions", tiers: [25, 50, 100, 250, 500], trigger: "Max consecutive PermissionRequest events" },
|
|
129
|
+
{ id: "it_works_on_my_machine", name: "It Works On My Machine", icon: "\u{1F937}", description: "The classic excuse.", category: "wild_card", stat: "bashRetrySuccessCount", tiers: [1, 10, 50, 200, 1e3], trigger: "Bash success (exit code 0) after a previous Bash failure" },
|
|
130
|
+
// ===================================================================
|
|
131
|
+
// TOKEN USAGE (10)
|
|
132
|
+
// ===================================================================
|
|
133
|
+
{ id: "token_burner", name: "Token Burner", icon: "\u{1F525}", description: "Consume tokens across all sessions", category: "token_usage", stat: "totalTokens", tiers: [5e7, 5e8, 5e9, 5e10, 5e11], trigger: "Total tokens consumed (input + output + cache read + cache creation)" },
|
|
134
|
+
{ id: "output_machine", name: "Output Machine", icon: "\u{1F5A8}", description: "Generate output tokens from Claude", category: "token_usage", stat: "totalOutputTokens", tiers: [1e6, 1e7, 1e8, 5e8, 2e9], trigger: "Total output tokens generated by Claude across all sessions" },
|
|
135
|
+
{ id: "cache_royalty", name: "Cache Royalty", icon: "\u{1F451}", description: "Read tokens from prompt cache", category: "token_usage", stat: "totalCacheReadTokens", tiers: [5e7, 5e8, 5e9, 5e10, 5e11], trigger: "Total cache read tokens (cached context reused across turns)" },
|
|
136
|
+
{ id: "context_crafter", name: "Context Crafter", icon: "\u{1F9F1}", description: "Create new cache entries", category: "token_usage", stat: "totalCacheCreationTokens", tiers: [1e7, 1e8, 1e9, 1e10, 1e11], trigger: "Total cache creation tokens (new context written to cache)" },
|
|
137
|
+
{ id: "token_whale", name: "Token Whale", icon: "\u{1F40B}", description: "Massive token consumption in a single session", category: "token_usage", stat: "mostTokensInSession", tiers: [1e7, 5e7, 2e8, 5e8, 1e9], trigger: "Most total tokens consumed in any single session" },
|
|
138
|
+
{ id: "heavy_hitter", name: "Heavy Hitter", icon: "\u{1F4AA}", description: "Sessions exceeding 1M total tokens", category: "token_usage", stat: "heavyTokenSessions", tiers: [10, 50, 250, 1e3, 5e3], trigger: "Sessions with 1,000,000+ total tokens" },
|
|
139
|
+
{ id: "featherweight", name: "Featherweight", icon: "\u{1FAB6}", description: "Lean sessions that still get work done", category: "token_usage", stat: "lightTokenSessions", tiers: [1, 10, 50, 200, 1e3], trigger: "Sessions under 50,000 total tokens with at least 1 tool call" },
|
|
140
|
+
{ id: "token_velocity", name: "Token Velocity", icon: "\u26A1", description: "High average tokens per session", category: "token_usage", stat: "avgTokensPerSession", tiers: [5e6, 1e7, 25e6, 5e7, 1e8], trigger: "Average total tokens per session across all sessions" },
|
|
141
|
+
{ id: "prolific_session", name: "Prolific", icon: "\u270D", description: "Most output generated in one session", category: "token_usage", stat: "maxOutputInSession", tiers: [1e5, 5e5, 2e6, 1e7, 5e7], trigger: "Most output tokens generated by Claude in a single session" },
|
|
142
|
+
{ id: "input_flood", name: "Input Flood", icon: "\u{1F30A}", description: "Total raw input tokens sent to the API", category: "token_usage", stat: "totalInputTokens", tiers: [1e6, 1e7, 1e8, 5e8, 2e9], trigger: "Total non-cached input tokens (the small uncached portion of each request)" },
|
|
143
|
+
// ===================================================================
|
|
144
|
+
// ASPIRATIONAL (12) - Singularity-only
|
|
145
|
+
// ===================================================================
|
|
146
|
+
{ id: "the_machine", name: "The Machine", icon: "\u2699", description: "You are no longer using the tool. You are the tool.", category: "aspirational", stat: "totalToolCalls", tiers: [1e5, 1e5, 1e5, 1e5, 1e5], aspirational: true, trigger: "Reach 100,000 total tool calls" },
|
|
147
|
+
{ id: "year_of_code", name: "Year of Code", icon: "\u{1F4C5}", description: "365 days. No breaks. Absolute unit.", category: "aspirational", stat: "longestStreak", tiers: [365, 365, 365, 365, 365], aspirational: true, trigger: "Achieve a 365-day consecutive streak" },
|
|
148
|
+
{ id: "million_words", name: "Million Words", icon: "\u{1F4DA}", description: "You've written more to Claude than most people write in a lifetime.", category: "aspirational", stat: "totalCharsTyped", tiers: [1e7, 1e7, 1e7, 1e7, 1e7], aspirational: true, trigger: "Type 10 million characters in prompts" },
|
|
149
|
+
{ id: "lifer", name: "Lifer", icon: "\u{1F451}", description: "At this point, Claude is your cofounder.", category: "aspirational", stat: "totalSessions", tiers: [1e4, 1e4, 1e4, 1e4, 1e4], aspirational: true, trigger: "Complete 10,000 sessions" },
|
|
150
|
+
{ id: "transcendent", name: "Transcendent", icon: "\u2B50", description: "You've reached the peak. The view is nice up here.", category: "aspirational", stat: "totalXP", tiers: [1e5, 1e5, 1e5, 1e5, 1e5], aspirational: true, trigger: "Earn 100,000 total XP" },
|
|
151
|
+
{ id: "omniscient", name: "Omniscient", icon: "\u{1F441}", description: "You've mastered every tool. There is nothing left to teach you.", category: "aspirational", stat: "allToolsObsidian", tiers: [1, 1, 1, 1, 1], aspirational: true, trigger: "All tool mastery badges at Singularity tier" },
|
|
152
|
+
{ id: "ten_thousand_hours", name: "10,000 Hours", icon: "\u23F0", description: "Malcolm Gladwell would be proud.", category: "aspirational", stat: "totalSessionHours", tiers: [1e4, 1e4, 1e4, 1e4, 1e4], aspirational: true, trigger: "Spend 10,000 hours in sessions" },
|
|
153
|
+
{ id: "master_architect", name: "The Architect", icon: "\u{1F3DB}", description: "You've built more than most companies ship.", category: "aspirational", stat: "totalFilesCreated", tiers: [1e3, 1e3, 1e3, 1e3, 1e3], aspirational: true, trigger: "Create 1,000+ files with the Write tool" },
|
|
154
|
+
{ id: "eternal_flame", name: "Eternal Flame", icon: "\u{1F56F}", description: "Your streak outlasted relationships.", category: "aspirational", stat: "longestStreak", tiers: [180, 180, 180, 180, 180], aspirational: true, trigger: "Maintain a 180-day consecutive streak" },
|
|
155
|
+
{ id: "the_collector", name: "The Collector", icon: "\u{1F4BF}", description: "Gotta catch 'em all.", category: "aspirational", stat: "allNonSecretBadgesUnlocked", tiers: [1, 1, 1, 1, 1], aspirational: true, trigger: "Unlock every non-secret, non-aspirational badge" },
|
|
156
|
+
{ id: "centimillionaire", name: "Centimillionaire", icon: "\u2328", description: "100 million characters. Your keyboard weeps.", category: "aspirational", stat: "totalCharsTyped", tiers: [1e8, 1e8, 1e8, 1e8, 1e8], aspirational: true, trigger: "Type 100 million characters in prompts" },
|
|
157
|
+
{ id: "token_billionaire", name: "Token Billionaire", icon: "\u{1F4B0}", description: "A billion tokens. You single-handedly funded a GPU cluster.", category: "aspirational", stat: "totalTokens", tiers: [1e9, 1e9, 1e9, 1e9, 1e9], aspirational: true, trigger: "Consume 1 billion total tokens" },
|
|
158
|
+
// ===================================================================
|
|
159
|
+
// SECRET (17)
|
|
160
|
+
// ===================================================================
|
|
161
|
+
{ id: "rm_rf_survivor", name: "rm -rf Survivor", icon: "\u{1F4A3}", description: "You almost mass deleted that folder. But you didn't. And honestly, we're all better for it.", category: "secret", stat: "dangerousCommandBlocked", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "rm -rf or rm -r / detected in PreToolUse event" },
|
|
162
|
+
{ id: "touch_grass", name: "Touch Grass", icon: "\u{1F33F}", description: "Welcome back. The codebase missed you. (It didn't change, but still.)", category: "secret", stat: "returnAfterBreak", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Return after 7+ day gap between sessions" },
|
|
163
|
+
{ id: "three_am_coder", name: "3am Coder", icon: "\u{1F319}", description: "Nothing good happens at 3am. Except shipping code, apparently.", category: "secret", stat: "threeAmPrompt", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Submit a prompt at exactly 3 AM" },
|
|
164
|
+
{ id: "night_shift", name: "Night Shift", icon: "\u{1F303}", description: "Started yesterday, finishing today. Time is a construct.", category: "secret", stat: "midnightSpanSession", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Session that started before midnight and ended after" },
|
|
165
|
+
{ id: "inception", name: "Inception", icon: "\u{1F300}", description: "We need to go deeper.", category: "secret", stat: "nestedSubagent", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Any SubagentStart event detected" },
|
|
166
|
+
{ id: "holiday_hacker", name: "Holiday Hacker", icon: "\u{1F384}", description: "Your family is wondering where you are. You're deploying.", category: "secret", stat: "holidayActivity", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Session on Dec 25, Jan 1, or Jul 4" },
|
|
167
|
+
{ id: "speed_run", name: "Speed Run Any%", icon: "\u23F1", description: "In and out. Twenty-second adventure.", category: "secret", stat: "speedRunSession", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Session under 20 seconds with tool use" },
|
|
168
|
+
{ id: "full_send", name: "Full Send", icon: "\u{1F680}", description: "Bash, Read, Write, Edit, Grep, Glob, WebFetch -- the whole buffet.", category: "secret", stat: "allToolsInSession", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Use all 7 core tools in one session" },
|
|
169
|
+
{ id: "launch_day", name: "Launch Day", icon: "\u{1F389}", description: "Welcome to bashstats. Your stats are now being watched. Forever.", category: "secret", stat: "firstEverSession", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Complete your first ever session" },
|
|
170
|
+
{ id: "the_completionist", name: "The Completionist", icon: "\u{1F3C6}", description: "You absolute legend.", category: "secret", stat: "allBadgesGold", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "All non-secret, non-aspirational badges at Gold+ tier" },
|
|
171
|
+
{ id: "easter_egg_hunter", name: "Easter Egg Hunter", icon: "\u{1F95A}", description: "You found me!", category: "secret", stat: "easterEggActivity", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Session on Easter, Valentine's Day, or Thanksgiving" },
|
|
172
|
+
{ id: "full_moon_coder", name: "Full Moon Coder", icon: "\u{1F315}", description: "Lycanthropic debugging.", category: "secret", stat: "fullMoonSession", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Session during a full moon (calculated from lunar cycle)" },
|
|
173
|
+
{ id: "birthday_bash", name: "Birthday Bash", icon: "\u{1F382}", description: "Celebrating with Claude.", category: "secret", stat: "birthdaySession", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Session on your bashstats install anniversary" },
|
|
174
|
+
{ id: "lucky_number", name: "Lucky Number", icon: "\u{1F340}", description: "7-7-7", category: "secret", stat: "luckyNumber", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Reach 777 prompts or 7,777 tool calls" },
|
|
175
|
+
{ id: "ghost_session", name: "Ghost Session", icon: "\u{1F47B}", description: "Boo!", category: "secret", stat: "ghostSessions", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Complete a session with 0 tool calls" },
|
|
176
|
+
{ id: "bullseye", name: "Bullseye", icon: "\u{1F3AF}", description: "First try, no errors.", category: "secret", stat: "bullseyeSessions", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Session with 1 prompt, 0 errors, and 1+ tool calls" },
|
|
177
|
+
{ id: "token_singularity", name: "Token Singularity", icon: "\u{1F573}", description: "The context window stared into the abyss, and the abyss stared back.", category: "secret", stat: "hasTenMillionSession", tiers: [1, 1, 1, 1, 1], secret: true, trigger: "Complete a session exceeding 10 million total tokens" }
|
|
178
|
+
];
|
|
179
|
+
var RANK_TIER_BRACKETS = [
|
|
180
|
+
{ tier: "System Anomaly", minRank: 500, maxRank: 500 },
|
|
181
|
+
{ tier: "Obsidian", minRank: 401, maxRank: 499 },
|
|
182
|
+
{ tier: "Diamond", minRank: 301, maxRank: 400 },
|
|
183
|
+
{ tier: "Gold", minRank: 201, maxRank: 300 },
|
|
184
|
+
{ tier: "Silver", minRank: 101, maxRank: 200 },
|
|
185
|
+
{ tier: "Bronze", minRank: 1, maxRank: 100 }
|
|
186
|
+
];
|
|
187
|
+
function xpForRank(rank) {
|
|
188
|
+
if (rank <= 0) return 0;
|
|
189
|
+
return Math.floor(10 * Math.pow(rank, 2.2));
|
|
190
|
+
}
|
|
191
|
+
function rankTierForRank(rank) {
|
|
192
|
+
for (const bracket of RANK_TIER_BRACKETS) {
|
|
193
|
+
if (rank >= bracket.minRank && rank <= bracket.maxRank) {
|
|
194
|
+
return bracket.tier;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return "Unranked";
|
|
198
|
+
}
|
|
199
|
+
var TIER_XP = [0, 50, 100, 200, 500, 1e3];
|
|
200
|
+
var ACTIVITY_MULTIPLIERS = {
|
|
201
|
+
1: 1,
|
|
202
|
+
2: 1.1,
|
|
203
|
+
3: 1.2,
|
|
204
|
+
4: 1.3,
|
|
205
|
+
5: 1.5,
|
|
206
|
+
6: 1.75,
|
|
207
|
+
7: 2
|
|
208
|
+
};
|
|
209
|
+
var WEEKLY_CHALLENGES = [
|
|
210
|
+
{ id: "wk_diverse_tools", description: "Use 5+ distinct tools in 5 sessions", stat: "diverseToolSessions", threshold: 5, xpReward: 200, weekScoped: true },
|
|
211
|
+
{ id: "wk_200_prompts", description: "Submit 200 prompts this week", stat: "totalPrompts", threshold: 200, xpReward: 250, weekScoped: true },
|
|
212
|
+
{ id: "wk_quick_sessions", description: "Complete 3 sessions under 2 minutes", stat: "quickDrawSessions", threshold: 3, xpReward: 150, weekScoped: true },
|
|
213
|
+
{ id: "wk_5_day_commits", description: "Make git commits on 5 different days", stat: "commitDays", threshold: 5, xpReward: 300, weekScoped: true },
|
|
214
|
+
{ id: "wk_7_day_streak", description: "Be active all 7 days this week", stat: "daysActive", threshold: 7, xpReward: 400, weekScoped: true },
|
|
215
|
+
{ id: "wk_subagent_power", description: "Spawn 8+ subagents in a single session", stat: "maxSubagentsInSession", threshold: 8, xpReward: 200, weekScoped: true },
|
|
216
|
+
{ id: "wk_night_code", description: "Code after midnight on 3 different nights", stat: "nightOwlDays", threshold: 3, xpReward: 150, weekScoped: true },
|
|
217
|
+
{ id: "wk_2000_tools", description: "Make 2,000 tool calls this week", stat: "totalToolCalls", threshold: 2e3, xpReward: 250, weekScoped: true },
|
|
218
|
+
{ id: "wk_10_sessions", description: "Complete 10 sessions this week", stat: "totalSessions", threshold: 10, xpReward: 200, weekScoped: true },
|
|
219
|
+
{ id: "wk_20_sessions", description: "Complete 20 sessions this week", stat: "totalSessions", threshold: 20, xpReward: 350, weekScoped: true },
|
|
220
|
+
{ id: "wk_500_reads", description: "Read 500 files this week", stat: "totalFilesRead", threshold: 500, xpReward: 250, weekScoped: true },
|
|
221
|
+
{ id: "wk_100_edits", description: "Edit 100 files this week", stat: "totalFilesEdited", threshold: 100, xpReward: 250, weekScoped: true },
|
|
222
|
+
{ id: "wk_20_creates", description: "Create 20 new files this week", stat: "totalFilesCreated", threshold: 20, xpReward: 200, weekScoped: true },
|
|
223
|
+
{ id: "wk_3_projects", description: "Work on 3+ different projects this week", stat: "uniqueProjects", threshold: 3, xpReward: 200, weekScoped: true },
|
|
224
|
+
{ id: "wk_3_marathons", description: "Have 3 sessions lasting over 1 hour", stat: "extendedSessionCount", threshold: 3, xpReward: 250, weekScoped: true },
|
|
225
|
+
{ id: "wk_5_clean", description: "Complete 5 sessions with zero errors", stat: "cleanSessions", threshold: 5, xpReward: 200, weekScoped: true },
|
|
226
|
+
{ id: "wk_15_hours", description: "Spend 15+ total hours in sessions", stat: "totalHours", threshold: 15, xpReward: 300, weekScoped: true },
|
|
227
|
+
{ id: "wk_200_bash", description: "Run 200 Bash commands this week", stat: "totalBashCommands", threshold: 200, xpReward: 200, weekScoped: true },
|
|
228
|
+
{ id: "wk_250_searches", description: "Perform 250 searches (Grep/Glob)", stat: "totalSearches", threshold: 250, xpReward: 200, weekScoped: true },
|
|
229
|
+
{ id: "wk_10_long_prompts", description: "Write 10 prompts over 1,000 characters", stat: "longPromptCount", threshold: 10, xpReward: 150, weekScoped: true },
|
|
230
|
+
{ id: "wk_5_commits", description: "Make 5 git commits this week", stat: "totalCommits", threshold: 5, xpReward: 200, weekScoped: true },
|
|
231
|
+
{ id: "wk_2_prs", description: "Create 2 pull requests this week", stat: "totalPRs", threshold: 2, xpReward: 250, weekScoped: true },
|
|
232
|
+
{ id: "wk_5000_tools", description: "Make 5,000 tool calls this week", stat: "totalToolCalls", threshold: 5e3, xpReward: 400, weekScoped: true },
|
|
233
|
+
{ id: "wk_weekend_warrior", description: "Code on both Saturday and Sunday", stat: "weekendDays", threshold: 2, xpReward: 200, weekScoped: true },
|
|
234
|
+
{ id: "wk_3_early_birds", description: "Submit a prompt before 8am on 3 days", stat: "earlyBirdDays", threshold: 3, xpReward: 200, weekScoped: true }
|
|
235
|
+
];
|
|
236
|
+
var DATA_DIR = ".bashstats";
|
|
237
|
+
var DB_FILENAME = "bashstats.db";
|
|
238
|
+
var DEFAULT_PORT = 17900;
|
|
239
|
+
|
|
240
|
+
// src/db/database.ts
|
|
241
|
+
import Database from "better-sqlite3";
|
|
242
|
+
function localNow() {
|
|
243
|
+
const d = /* @__PURE__ */ new Date();
|
|
244
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
245
|
+
const ms = String(d.getMilliseconds()).padStart(3, "0");
|
|
246
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${ms}`;
|
|
247
|
+
}
|
|
248
|
+
var SCHEMA = `
|
|
249
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
250
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
251
|
+
session_id TEXT NOT NULL,
|
|
252
|
+
hook_type TEXT NOT NULL,
|
|
253
|
+
tool_name TEXT,
|
|
254
|
+
tool_input TEXT,
|
|
255
|
+
tool_output TEXT,
|
|
256
|
+
exit_code INTEGER,
|
|
257
|
+
success INTEGER,
|
|
258
|
+
cwd TEXT,
|
|
259
|
+
project TEXT,
|
|
260
|
+
timestamp TEXT NOT NULL
|
|
261
|
+
);
|
|
262
|
+
|
|
263
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
264
|
+
id TEXT PRIMARY KEY,
|
|
265
|
+
agent TEXT NOT NULL DEFAULT 'claude-code',
|
|
266
|
+
started_at TEXT NOT NULL,
|
|
267
|
+
ended_at TEXT,
|
|
268
|
+
stop_reason TEXT,
|
|
269
|
+
prompt_count INTEGER DEFAULT 0,
|
|
270
|
+
tool_count INTEGER DEFAULT 0,
|
|
271
|
+
error_count INTEGER DEFAULT 0,
|
|
272
|
+
project TEXT,
|
|
273
|
+
duration_seconds INTEGER,
|
|
274
|
+
input_tokens INTEGER DEFAULT 0,
|
|
275
|
+
output_tokens INTEGER DEFAULT 0,
|
|
276
|
+
cache_creation_input_tokens INTEGER DEFAULT 0,
|
|
277
|
+
cache_read_input_tokens INTEGER DEFAULT 0
|
|
278
|
+
);
|
|
279
|
+
|
|
280
|
+
CREATE TABLE IF NOT EXISTS prompts (
|
|
281
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
282
|
+
session_id TEXT NOT NULL,
|
|
283
|
+
content TEXT NOT NULL,
|
|
284
|
+
char_count INTEGER NOT NULL,
|
|
285
|
+
word_count INTEGER NOT NULL,
|
|
286
|
+
timestamp TEXT NOT NULL,
|
|
287
|
+
FOREIGN KEY (session_id) REFERENCES sessions(id)
|
|
288
|
+
);
|
|
289
|
+
|
|
290
|
+
CREATE TABLE IF NOT EXISTS daily_activity (
|
|
291
|
+
date TEXT PRIMARY KEY,
|
|
292
|
+
sessions INTEGER DEFAULT 0,
|
|
293
|
+
prompts INTEGER DEFAULT 0,
|
|
294
|
+
tool_calls INTEGER DEFAULT 0,
|
|
295
|
+
errors INTEGER DEFAULT 0,
|
|
296
|
+
duration_seconds INTEGER DEFAULT 0,
|
|
297
|
+
input_tokens INTEGER DEFAULT 0,
|
|
298
|
+
output_tokens INTEGER DEFAULT 0,
|
|
299
|
+
cache_creation_input_tokens INTEGER DEFAULT 0,
|
|
300
|
+
cache_read_input_tokens INTEGER DEFAULT 0
|
|
301
|
+
);
|
|
302
|
+
|
|
303
|
+
CREATE TABLE IF NOT EXISTS achievement_unlocks (
|
|
304
|
+
badge_id TEXT NOT NULL,
|
|
305
|
+
tier INTEGER NOT NULL,
|
|
306
|
+
unlocked_at TEXT NOT NULL,
|
|
307
|
+
notified INTEGER DEFAULT 0,
|
|
308
|
+
PRIMARY KEY (badge_id, tier)
|
|
309
|
+
);
|
|
310
|
+
|
|
311
|
+
CREATE TABLE IF NOT EXISTS metadata (
|
|
312
|
+
key TEXT PRIMARY KEY,
|
|
313
|
+
value TEXT
|
|
314
|
+
);
|
|
315
|
+
|
|
316
|
+
CREATE TABLE IF NOT EXISTS weekly_goals (
|
|
317
|
+
week_start TEXT NOT NULL,
|
|
318
|
+
challenge_id TEXT NOT NULL,
|
|
319
|
+
completed INTEGER DEFAULT 0,
|
|
320
|
+
xp_reward INTEGER NOT NULL,
|
|
321
|
+
PRIMARY KEY (week_start, challenge_id)
|
|
322
|
+
);
|
|
323
|
+
|
|
324
|
+
CREATE TABLE IF NOT EXISTS weekly_xp (
|
|
325
|
+
week_start TEXT PRIMARY KEY,
|
|
326
|
+
base_xp INTEGER DEFAULT 0,
|
|
327
|
+
multiplier REAL DEFAULT 1.0,
|
|
328
|
+
bonus_xp INTEGER DEFAULT 0
|
|
329
|
+
);
|
|
330
|
+
|
|
331
|
+
CREATE INDEX IF NOT EXISTS idx_events_session ON events(session_id);
|
|
332
|
+
CREATE INDEX IF NOT EXISTS idx_events_hook_type ON events(hook_type);
|
|
333
|
+
CREATE INDEX IF NOT EXISTS idx_events_tool_name ON events(tool_name);
|
|
334
|
+
CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
|
|
335
|
+
CREATE INDEX IF NOT EXISTS idx_events_project ON events(project);
|
|
336
|
+
CREATE INDEX IF NOT EXISTS idx_prompts_session ON prompts(session_id);
|
|
337
|
+
CREATE INDEX IF NOT EXISTS idx_prompts_timestamp ON prompts(timestamp);
|
|
338
|
+
`;
|
|
339
|
+
var BashStatsDB = class {
|
|
340
|
+
db;
|
|
341
|
+
constructor(dbPath) {
|
|
342
|
+
this.db = new Database(dbPath);
|
|
343
|
+
this.db.pragma("journal_mode = WAL");
|
|
344
|
+
this.db.pragma("busy_timeout = 5000");
|
|
345
|
+
this.db.pragma("foreign_keys = ON");
|
|
346
|
+
this.db.exec(SCHEMA);
|
|
347
|
+
this.migrate();
|
|
348
|
+
}
|
|
349
|
+
migrate() {
|
|
350
|
+
const sessionCols = this.db.pragma("table_info(sessions)");
|
|
351
|
+
const sessionColNames = new Set(sessionCols.map((c) => c.name));
|
|
352
|
+
if (!sessionColNames.has("agent")) {
|
|
353
|
+
this.db.exec("ALTER TABLE sessions ADD COLUMN agent TEXT NOT NULL DEFAULT 'claude-code'");
|
|
354
|
+
}
|
|
355
|
+
const tokenCols = ["input_tokens", "output_tokens", "cache_creation_input_tokens", "cache_read_input_tokens"];
|
|
356
|
+
for (const col of tokenCols) {
|
|
357
|
+
if (!sessionColNames.has(col)) {
|
|
358
|
+
this.db.exec(`ALTER TABLE sessions ADD COLUMN ${col} INTEGER DEFAULT 0`);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
const dailyCols = this.db.pragma("table_info(daily_activity)");
|
|
362
|
+
const dailyColNames = new Set(dailyCols.map((c) => c.name));
|
|
363
|
+
for (const col of tokenCols) {
|
|
364
|
+
if (!dailyColNames.has(col)) {
|
|
365
|
+
this.db.exec(`ALTER TABLE daily_activity ADD COLUMN ${col} INTEGER DEFAULT 0`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
close() {
|
|
370
|
+
this.db.close();
|
|
371
|
+
}
|
|
372
|
+
getTableNames() {
|
|
373
|
+
const rows = this.db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all();
|
|
374
|
+
return rows.map((r) => r.name);
|
|
375
|
+
}
|
|
376
|
+
// === Events ===
|
|
377
|
+
insertEvent(event) {
|
|
378
|
+
const stmt = this.db.prepare(`
|
|
379
|
+
INSERT INTO events (session_id, hook_type, tool_name, tool_input, tool_output, exit_code, success, cwd, project, timestamp)
|
|
380
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
381
|
+
`);
|
|
382
|
+
const result = stmt.run(
|
|
383
|
+
event.session_id,
|
|
384
|
+
event.hook_type,
|
|
385
|
+
event.tool_name,
|
|
386
|
+
event.tool_input,
|
|
387
|
+
event.tool_output,
|
|
388
|
+
event.exit_code,
|
|
389
|
+
event.success,
|
|
390
|
+
event.cwd,
|
|
391
|
+
event.project,
|
|
392
|
+
event.timestamp
|
|
393
|
+
);
|
|
394
|
+
return result.lastInsertRowid;
|
|
395
|
+
}
|
|
396
|
+
getEvents(filter) {
|
|
397
|
+
let sql = "SELECT * FROM events WHERE 1=1";
|
|
398
|
+
const params = [];
|
|
399
|
+
if (filter.session_id) {
|
|
400
|
+
sql += " AND session_id = ?";
|
|
401
|
+
params.push(filter.session_id);
|
|
402
|
+
}
|
|
403
|
+
if (filter.hook_type) {
|
|
404
|
+
sql += " AND hook_type = ?";
|
|
405
|
+
params.push(filter.hook_type);
|
|
406
|
+
}
|
|
407
|
+
if (filter.tool_name) {
|
|
408
|
+
sql += " AND tool_name = ?";
|
|
409
|
+
params.push(filter.tool_name);
|
|
410
|
+
}
|
|
411
|
+
sql += " ORDER BY timestamp ASC";
|
|
412
|
+
return this.db.prepare(sql).all(...params);
|
|
413
|
+
}
|
|
414
|
+
// === Sessions ===
|
|
415
|
+
insertSession(session) {
|
|
416
|
+
this.db.prepare(`
|
|
417
|
+
INSERT OR IGNORE INTO sessions (id, agent, started_at, project) VALUES (?, ?, ?, ?)
|
|
418
|
+
`).run(session.id, session.agent ?? "claude-code", session.started_at, session.project ?? null);
|
|
419
|
+
}
|
|
420
|
+
getSession(id) {
|
|
421
|
+
return this.db.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
|
|
422
|
+
}
|
|
423
|
+
updateSession(id, updates) {
|
|
424
|
+
const sets = [];
|
|
425
|
+
const params = [];
|
|
426
|
+
if (updates.ended_at !== void 0) {
|
|
427
|
+
sets.push("ended_at = ?");
|
|
428
|
+
params.push(updates.ended_at);
|
|
429
|
+
}
|
|
430
|
+
if (updates.stop_reason !== void 0) {
|
|
431
|
+
sets.push("stop_reason = ?");
|
|
432
|
+
params.push(updates.stop_reason);
|
|
433
|
+
}
|
|
434
|
+
if (updates.duration_seconds !== void 0) {
|
|
435
|
+
sets.push("duration_seconds = ?");
|
|
436
|
+
params.push(updates.duration_seconds);
|
|
437
|
+
}
|
|
438
|
+
if (sets.length === 0) return;
|
|
439
|
+
params.push(id);
|
|
440
|
+
this.db.prepare(`UPDATE sessions SET ${sets.join(", ")} WHERE id = ?`).run(...params);
|
|
441
|
+
}
|
|
442
|
+
updateSessionTokens(id, tokens) {
|
|
443
|
+
this.db.prepare(`
|
|
444
|
+
UPDATE sessions SET input_tokens = ?, output_tokens = ?, cache_creation_input_tokens = ?, cache_read_input_tokens = ? WHERE id = ?
|
|
445
|
+
`).run(tokens.input_tokens, tokens.output_tokens, tokens.cache_creation_input_tokens, tokens.cache_read_input_tokens, id);
|
|
446
|
+
}
|
|
447
|
+
incrementSessionCounters(id, counters) {
|
|
448
|
+
const sets = [];
|
|
449
|
+
const params = [];
|
|
450
|
+
if (counters.prompts) {
|
|
451
|
+
sets.push("prompt_count = prompt_count + ?");
|
|
452
|
+
params.push(counters.prompts);
|
|
453
|
+
}
|
|
454
|
+
if (counters.tools) {
|
|
455
|
+
sets.push("tool_count = tool_count + ?");
|
|
456
|
+
params.push(counters.tools);
|
|
457
|
+
}
|
|
458
|
+
if (counters.errors) {
|
|
459
|
+
sets.push("error_count = error_count + ?");
|
|
460
|
+
params.push(counters.errors);
|
|
461
|
+
}
|
|
462
|
+
if (sets.length === 0) return;
|
|
463
|
+
params.push(id);
|
|
464
|
+
this.db.prepare(`UPDATE sessions SET ${sets.join(", ")} WHERE id = ?`).run(...params);
|
|
465
|
+
}
|
|
466
|
+
// === Prompts ===
|
|
467
|
+
insertPrompt(prompt) {
|
|
468
|
+
const result = this.db.prepare(`
|
|
469
|
+
INSERT INTO prompts (session_id, content, char_count, word_count, timestamp) VALUES (?, ?, ?, ?, ?)
|
|
470
|
+
`).run(prompt.session_id, prompt.content, prompt.char_count, prompt.word_count, prompt.timestamp);
|
|
471
|
+
return result.lastInsertRowid;
|
|
472
|
+
}
|
|
473
|
+
getPrompts(sessionId) {
|
|
474
|
+
return this.db.prepare("SELECT * FROM prompts WHERE session_id = ? ORDER BY timestamp ASC").all(sessionId);
|
|
475
|
+
}
|
|
476
|
+
// === Daily Activity ===
|
|
477
|
+
incrementDailyActivity(date, increments) {
|
|
478
|
+
this.db.prepare(`
|
|
479
|
+
INSERT INTO daily_activity (date, sessions, prompts, tool_calls, errors, duration_seconds, input_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens)
|
|
480
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
481
|
+
ON CONFLICT(date) DO UPDATE SET
|
|
482
|
+
sessions = sessions + excluded.sessions,
|
|
483
|
+
prompts = prompts + excluded.prompts,
|
|
484
|
+
tool_calls = tool_calls + excluded.tool_calls,
|
|
485
|
+
errors = errors + excluded.errors,
|
|
486
|
+
duration_seconds = duration_seconds + excluded.duration_seconds,
|
|
487
|
+
input_tokens = input_tokens + excluded.input_tokens,
|
|
488
|
+
output_tokens = output_tokens + excluded.output_tokens,
|
|
489
|
+
cache_creation_input_tokens = cache_creation_input_tokens + excluded.cache_creation_input_tokens,
|
|
490
|
+
cache_read_input_tokens = cache_read_input_tokens + excluded.cache_read_input_tokens
|
|
491
|
+
`).run(
|
|
492
|
+
date,
|
|
493
|
+
increments.sessions ?? 0,
|
|
494
|
+
increments.prompts ?? 0,
|
|
495
|
+
increments.tool_calls ?? 0,
|
|
496
|
+
increments.errors ?? 0,
|
|
497
|
+
increments.duration_seconds ?? 0,
|
|
498
|
+
increments.input_tokens ?? 0,
|
|
499
|
+
increments.output_tokens ?? 0,
|
|
500
|
+
increments.cache_creation_input_tokens ?? 0,
|
|
501
|
+
increments.cache_read_input_tokens ?? 0
|
|
502
|
+
);
|
|
503
|
+
}
|
|
504
|
+
getDailyActivity(date) {
|
|
505
|
+
return this.db.prepare("SELECT * FROM daily_activity WHERE date = ?").get(date);
|
|
506
|
+
}
|
|
507
|
+
getAllDailyActivity(days) {
|
|
508
|
+
if (days) {
|
|
509
|
+
return this.db.prepare("SELECT * FROM daily_activity ORDER BY date DESC LIMIT ?").all(days);
|
|
510
|
+
}
|
|
511
|
+
return this.db.prepare("SELECT * FROM daily_activity ORDER BY date DESC").all();
|
|
512
|
+
}
|
|
513
|
+
// === Achievement Unlocks ===
|
|
514
|
+
insertUnlock(badgeId, tier) {
|
|
515
|
+
this.db.prepare(`
|
|
516
|
+
INSERT OR IGNORE INTO achievement_unlocks (badge_id, tier, unlocked_at) VALUES (?, ?, ?)
|
|
517
|
+
`).run(badgeId, tier, localNow());
|
|
518
|
+
}
|
|
519
|
+
getUnlocks() {
|
|
520
|
+
return this.db.prepare("SELECT * FROM achievement_unlocks ORDER BY unlocked_at DESC").all();
|
|
521
|
+
}
|
|
522
|
+
getUnnotifiedUnlocks() {
|
|
523
|
+
return this.db.prepare("SELECT * FROM achievement_unlocks WHERE notified = 0").all();
|
|
524
|
+
}
|
|
525
|
+
markNotified(badgeId, tier) {
|
|
526
|
+
this.db.prepare("UPDATE achievement_unlocks SET notified = 1 WHERE badge_id = ? AND tier = ?").run(badgeId, tier);
|
|
527
|
+
}
|
|
528
|
+
// === Metadata ===
|
|
529
|
+
setMetadata(key, value) {
|
|
530
|
+
this.db.prepare("INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)").run(key, value);
|
|
531
|
+
}
|
|
532
|
+
getMetadata(key) {
|
|
533
|
+
const row = this.db.prepare("SELECT value FROM metadata WHERE key = ?").get(key);
|
|
534
|
+
return row?.value ?? null;
|
|
535
|
+
}
|
|
536
|
+
// === Weekly Goals ===
|
|
537
|
+
insertWeeklyGoal(weekStart, challengeId, xpReward) {
|
|
538
|
+
this.db.prepare(`
|
|
539
|
+
INSERT OR IGNORE INTO weekly_goals (week_start, challenge_id, xp_reward) VALUES (?, ?, ?)
|
|
540
|
+
`).run(weekStart, challengeId, xpReward);
|
|
541
|
+
}
|
|
542
|
+
completeWeeklyGoal(weekStart, challengeId) {
|
|
543
|
+
this.db.prepare("UPDATE weekly_goals SET completed = 1 WHERE week_start = ? AND challenge_id = ?").run(weekStart, challengeId);
|
|
544
|
+
}
|
|
545
|
+
getWeeklyGoals(weekStart) {
|
|
546
|
+
return this.db.prepare("SELECT * FROM weekly_goals WHERE week_start = ?").all(weekStart);
|
|
547
|
+
}
|
|
548
|
+
// === Weekly XP ===
|
|
549
|
+
upsertWeeklyXP(weekStart, baseXP, multiplier, bonusXP) {
|
|
550
|
+
this.db.prepare(`
|
|
551
|
+
INSERT INTO weekly_xp (week_start, base_xp, multiplier, bonus_xp) VALUES (?, ?, ?, ?)
|
|
552
|
+
ON CONFLICT(week_start) DO UPDATE SET base_xp = ?, multiplier = ?, bonus_xp = ?
|
|
553
|
+
`).run(weekStart, baseXP, multiplier, bonusXP, baseXP, multiplier, bonusXP);
|
|
554
|
+
}
|
|
555
|
+
getWeeklyXP(weekStart) {
|
|
556
|
+
return this.db.prepare("SELECT * FROM weekly_xp WHERE week_start = ?").get(weekStart);
|
|
557
|
+
}
|
|
558
|
+
// === Raw DB access for stats engine ===
|
|
559
|
+
prepare(sql) {
|
|
560
|
+
return this.db.prepare(sql);
|
|
561
|
+
}
|
|
562
|
+
};
|
|
563
|
+
|
|
564
|
+
// src/installer/installer.ts
|
|
565
|
+
import fs from "fs";
|
|
566
|
+
import path from "path";
|
|
567
|
+
import os from "os";
|
|
568
|
+
import { fileURLToPath } from "url";
|
|
569
|
+
var HOOK_SCRIPTS = {
|
|
570
|
+
SessionStart: "session-start.js",
|
|
571
|
+
UserPromptSubmit: "user-prompt-submit.js",
|
|
572
|
+
PreToolUse: "pre-tool-use.js",
|
|
573
|
+
PostToolUse: "post-tool-use.js",
|
|
574
|
+
PostToolUseFailure: "post-tool-failure.js",
|
|
575
|
+
Stop: "stop.js",
|
|
576
|
+
Notification: "notification.js",
|
|
577
|
+
SubagentStart: "subagent-start.js",
|
|
578
|
+
SubagentStop: "subagent-stop.js",
|
|
579
|
+
PreCompact: "pre-compact.js",
|
|
580
|
+
PermissionRequest: "permission-request.js",
|
|
581
|
+
Setup: "setup.js"
|
|
582
|
+
};
|
|
583
|
+
var MARKER = "# bashstats-managed";
|
|
584
|
+
function mergeHooks(settings, hooksDir) {
|
|
585
|
+
const result = { ...settings };
|
|
586
|
+
if (!result.hooks) {
|
|
587
|
+
result.hooks = {};
|
|
588
|
+
}
|
|
589
|
+
for (const [event, scriptFile] of Object.entries(HOOK_SCRIPTS)) {
|
|
590
|
+
const command = `node "${path.join(hooksDir, scriptFile)}" ${MARKER}`;
|
|
591
|
+
const existing = result.hooks[event] ?? [];
|
|
592
|
+
const nonBashstats = existing.filter((entry) => {
|
|
593
|
+
return !entry.hooks?.some((h) => h.command?.includes(MARKER));
|
|
594
|
+
});
|
|
595
|
+
const bashstatsEntry = {
|
|
596
|
+
matcher: "",
|
|
597
|
+
hooks: [{ type: "command", command }]
|
|
598
|
+
};
|
|
599
|
+
result.hooks[event] = [...nonBashstats, bashstatsEntry];
|
|
600
|
+
}
|
|
601
|
+
return result;
|
|
602
|
+
}
|
|
603
|
+
function getClaudeSettingsPath() {
|
|
604
|
+
return path.join(os.homedir(), ".claude", "settings.json");
|
|
605
|
+
}
|
|
606
|
+
function getHooksDir() {
|
|
607
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
608
|
+
const __dirname = path.dirname(__filename);
|
|
609
|
+
return path.resolve(__dirname, "hooks");
|
|
610
|
+
}
|
|
611
|
+
function install() {
|
|
612
|
+
try {
|
|
613
|
+
const dataDir = path.join(os.homedir(), DATA_DIR);
|
|
614
|
+
fs.mkdirSync(dataDir, { recursive: true });
|
|
615
|
+
const dbPath = path.join(dataDir, DB_FILENAME);
|
|
616
|
+
const db = new BashStatsDB(dbPath);
|
|
617
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
618
|
+
db.setMetadata("installed_at", now);
|
|
619
|
+
if (!db.getMetadata("first_run")) {
|
|
620
|
+
db.setMetadata("first_run", now);
|
|
621
|
+
}
|
|
622
|
+
db.close();
|
|
623
|
+
const claudeDir = path.join(os.homedir(), ".claude");
|
|
624
|
+
fs.mkdirSync(claudeDir, { recursive: true });
|
|
625
|
+
const settingsPath = getClaudeSettingsPath();
|
|
626
|
+
let settings = {};
|
|
627
|
+
if (fs.existsSync(settingsPath)) {
|
|
628
|
+
const raw = fs.readFileSync(settingsPath, "utf-8");
|
|
629
|
+
settings = JSON.parse(raw);
|
|
630
|
+
}
|
|
631
|
+
const hooksDir = getHooksDir();
|
|
632
|
+
settings = mergeHooks(settings, hooksDir);
|
|
633
|
+
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), "utf-8");
|
|
634
|
+
return { success: true, message: "bashstats hooks installed successfully." };
|
|
635
|
+
} catch (err) {
|
|
636
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
637
|
+
return { success: false, message: `Installation failed: ${message}` };
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
function uninstall() {
|
|
641
|
+
try {
|
|
642
|
+
const settingsPath = getClaudeSettingsPath();
|
|
643
|
+
if (!fs.existsSync(settingsPath)) {
|
|
644
|
+
return { success: true, message: "No settings.json found; nothing to uninstall." };
|
|
645
|
+
}
|
|
646
|
+
const raw = fs.readFileSync(settingsPath, "utf-8");
|
|
647
|
+
const settings = JSON.parse(raw);
|
|
648
|
+
if (settings.hooks) {
|
|
649
|
+
for (const event of Object.keys(settings.hooks)) {
|
|
650
|
+
settings.hooks[event] = settings.hooks[event].filter((entry) => {
|
|
651
|
+
return !entry.hooks?.some((h) => h.command?.includes(MARKER));
|
|
652
|
+
});
|
|
653
|
+
if (settings.hooks[event].length === 0) {
|
|
654
|
+
delete settings.hooks[event];
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
if (Object.keys(settings.hooks).length === 0) {
|
|
658
|
+
delete settings.hooks;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), "utf-8");
|
|
662
|
+
return { success: true, message: "bashstats hooks removed successfully." };
|
|
663
|
+
} catch (err) {
|
|
664
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
665
|
+
return { success: false, message: `Uninstall failed: ${message}` };
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
function isInstalled() {
|
|
669
|
+
try {
|
|
670
|
+
const settingsPath = getClaudeSettingsPath();
|
|
671
|
+
if (!fs.existsSync(settingsPath)) return false;
|
|
672
|
+
const raw = fs.readFileSync(settingsPath, "utf-8");
|
|
673
|
+
const settings = JSON.parse(raw);
|
|
674
|
+
if (!settings.hooks) return false;
|
|
675
|
+
for (const event of Object.keys(settings.hooks)) {
|
|
676
|
+
const entries = settings.hooks[event];
|
|
677
|
+
for (const entry of entries) {
|
|
678
|
+
if (entry.hooks?.some((h) => h.command?.includes(MARKER))) {
|
|
679
|
+
return true;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
return false;
|
|
684
|
+
} catch {
|
|
685
|
+
return false;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// src/installer/gemini.ts
|
|
690
|
+
import fs2 from "fs";
|
|
691
|
+
import path2 from "path";
|
|
692
|
+
import os2 from "os";
|
|
693
|
+
var GEMINI_HOOK_SCRIPTS = {
|
|
694
|
+
SessionStart: "session-start.js",
|
|
695
|
+
SessionEnd: "stop.js",
|
|
696
|
+
BeforeAgent: "user-prompt-submit.js",
|
|
697
|
+
BeforeTool: "pre-tool-use.js",
|
|
698
|
+
AfterTool: "post-tool-use.js",
|
|
699
|
+
AfterModel: "stop.js",
|
|
700
|
+
PreCompress: "pre-compact.js",
|
|
701
|
+
Notification: "notification.js"
|
|
702
|
+
};
|
|
703
|
+
var MARKER2 = "# bashstats-managed";
|
|
704
|
+
var DEFAULT_TIMEOUT = 10;
|
|
705
|
+
function mergeGeminiHooks(settings, hooksDir) {
|
|
706
|
+
const result = { ...settings };
|
|
707
|
+
if (!result.hooks) {
|
|
708
|
+
result.hooks = {};
|
|
709
|
+
}
|
|
710
|
+
for (const [event, scriptFile] of Object.entries(GEMINI_HOOK_SCRIPTS)) {
|
|
711
|
+
const command = `node "${path2.join(hooksDir, scriptFile)}" ${MARKER2}`;
|
|
712
|
+
const existing = result.hooks[event] ?? [];
|
|
713
|
+
const nonBashstats = existing.filter((entry) => {
|
|
714
|
+
return !entry.hooks?.some((h) => h.command?.includes(MARKER2));
|
|
715
|
+
});
|
|
716
|
+
const bashstatsEntry = {
|
|
717
|
+
hooks: [{ name: "bashstats", type: "command", command, timeout: DEFAULT_TIMEOUT }]
|
|
718
|
+
};
|
|
719
|
+
result.hooks[event] = [...nonBashstats, bashstatsEntry];
|
|
720
|
+
}
|
|
721
|
+
return result;
|
|
722
|
+
}
|
|
723
|
+
function getGeminiSettingsPath() {
|
|
724
|
+
return path2.join(os2.homedir(), ".gemini", "settings.json");
|
|
725
|
+
}
|
|
726
|
+
function isGeminiAvailable() {
|
|
727
|
+
try {
|
|
728
|
+
const geminiDir = path2.join(os2.homedir(), ".gemini");
|
|
729
|
+
return fs2.existsSync(geminiDir) && fs2.statSync(geminiDir).isDirectory();
|
|
730
|
+
} catch {
|
|
731
|
+
return false;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
function installGemini() {
|
|
735
|
+
try {
|
|
736
|
+
const dataDir = path2.join(os2.homedir(), DATA_DIR);
|
|
737
|
+
fs2.mkdirSync(dataDir, { recursive: true });
|
|
738
|
+
const dbPath = path2.join(dataDir, DB_FILENAME);
|
|
739
|
+
const db = new BashStatsDB(dbPath);
|
|
740
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
741
|
+
db.setMetadata("installed_at", now);
|
|
742
|
+
if (!db.getMetadata("first_run")) {
|
|
743
|
+
db.setMetadata("first_run", now);
|
|
744
|
+
}
|
|
745
|
+
db.close();
|
|
746
|
+
const geminiDir = path2.join(os2.homedir(), ".gemini");
|
|
747
|
+
fs2.mkdirSync(geminiDir, { recursive: true });
|
|
748
|
+
const settingsPath = getGeminiSettingsPath();
|
|
749
|
+
let settings = {};
|
|
750
|
+
if (fs2.existsSync(settingsPath)) {
|
|
751
|
+
const raw = fs2.readFileSync(settingsPath, "utf-8");
|
|
752
|
+
settings = JSON.parse(raw);
|
|
753
|
+
}
|
|
754
|
+
const hooksDir = getHooksDir();
|
|
755
|
+
settings = mergeGeminiHooks(settings, hooksDir);
|
|
756
|
+
fs2.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), "utf-8");
|
|
757
|
+
return { success: true, message: "bashstats Gemini hooks installed successfully." };
|
|
758
|
+
} catch (err) {
|
|
759
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
760
|
+
return { success: false, message: `Gemini installation failed: ${message}` };
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
function uninstallGemini() {
|
|
764
|
+
try {
|
|
765
|
+
const settingsPath = getGeminiSettingsPath();
|
|
766
|
+
if (!fs2.existsSync(settingsPath)) {
|
|
767
|
+
return { success: true, message: "No Gemini settings.json found; nothing to uninstall." };
|
|
768
|
+
}
|
|
769
|
+
const raw = fs2.readFileSync(settingsPath, "utf-8");
|
|
770
|
+
const settings = JSON.parse(raw);
|
|
771
|
+
if (settings.hooks) {
|
|
772
|
+
for (const event of Object.keys(settings.hooks)) {
|
|
773
|
+
settings.hooks[event] = settings.hooks[event].filter((entry) => {
|
|
774
|
+
return !entry.hooks?.some((h) => h.command?.includes(MARKER2));
|
|
775
|
+
});
|
|
776
|
+
if (settings.hooks[event].length === 0) {
|
|
777
|
+
delete settings.hooks[event];
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
if (Object.keys(settings.hooks).length === 0) {
|
|
781
|
+
delete settings.hooks;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
fs2.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), "utf-8");
|
|
785
|
+
return { success: true, message: "bashstats Gemini hooks removed successfully." };
|
|
786
|
+
} catch (err) {
|
|
787
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
788
|
+
return { success: false, message: `Gemini uninstall failed: ${message}` };
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
// src/installer/copilot.ts
|
|
793
|
+
import fs3 from "fs";
|
|
794
|
+
import path3 from "path";
|
|
795
|
+
import os3 from "os";
|
|
796
|
+
import { execSync } from "child_process";
|
|
797
|
+
var COPILOT_HOOK_SCRIPTS = {
|
|
798
|
+
sessionStart: "session-start.js",
|
|
799
|
+
sessionEnd: "stop.js",
|
|
800
|
+
userPromptSubmitted: "user-prompt-submit.js",
|
|
801
|
+
preToolUse: "pre-tool-use.js",
|
|
802
|
+
postToolUse: "post-tool-use.js",
|
|
803
|
+
errorOccurred: "post-tool-failure.js"
|
|
804
|
+
};
|
|
805
|
+
var COMMENT_MARKER = "bashstats-managed";
|
|
806
|
+
function buildCopilotHooksConfig(hooksDir) {
|
|
807
|
+
const hooks = {};
|
|
808
|
+
for (const [event, scriptFile] of Object.entries(COPILOT_HOOK_SCRIPTS)) {
|
|
809
|
+
const scriptPath = path3.join(hooksDir, scriptFile);
|
|
810
|
+
hooks[event] = [
|
|
811
|
+
{
|
|
812
|
+
type: "command",
|
|
813
|
+
bash: `node "${scriptPath}"`,
|
|
814
|
+
powershell: `node "${scriptPath}"`,
|
|
815
|
+
timeoutSec: 30,
|
|
816
|
+
comment: COMMENT_MARKER
|
|
817
|
+
}
|
|
818
|
+
];
|
|
819
|
+
}
|
|
820
|
+
return { version: 1, hooks };
|
|
821
|
+
}
|
|
822
|
+
function getCopilotHooksPath() {
|
|
823
|
+
return path3.join(os3.homedir(), ".copilot", "hooks", "bashstats-hooks.json");
|
|
824
|
+
}
|
|
825
|
+
function installCopilot() {
|
|
826
|
+
try {
|
|
827
|
+
const hooksPath = getCopilotHooksPath();
|
|
828
|
+
const hooksDir = path3.dirname(hooksPath);
|
|
829
|
+
fs3.mkdirSync(hooksDir, { recursive: true });
|
|
830
|
+
const distHooksDir = getHooksDir();
|
|
831
|
+
const config = buildCopilotHooksConfig(distHooksDir);
|
|
832
|
+
fs3.writeFileSync(hooksPath, JSON.stringify(config, null, 2), "utf-8");
|
|
833
|
+
return { success: true, message: "Copilot bashstats hooks installed successfully." };
|
|
834
|
+
} catch (err) {
|
|
835
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
836
|
+
return { success: false, message: `Copilot installation failed: ${message}` };
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
function uninstallCopilot() {
|
|
840
|
+
try {
|
|
841
|
+
const hooksPath = getCopilotHooksPath();
|
|
842
|
+
if (!fs3.existsSync(hooksPath)) {
|
|
843
|
+
return { success: true, message: "No bashstats-hooks.json found; nothing to uninstall." };
|
|
844
|
+
}
|
|
845
|
+
fs3.unlinkSync(hooksPath);
|
|
846
|
+
return { success: true, message: "Copilot bashstats hooks removed successfully." };
|
|
847
|
+
} catch (err) {
|
|
848
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
849
|
+
return { success: false, message: `Copilot uninstall failed: ${message}` };
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
function isCopilotAvailable() {
|
|
853
|
+
try {
|
|
854
|
+
execSync("copilot --version", { stdio: "ignore", timeout: 5e3 });
|
|
855
|
+
return true;
|
|
856
|
+
} catch {
|
|
857
|
+
return false;
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
// src/installer/opencode.ts
|
|
862
|
+
import fs4 from "fs";
|
|
863
|
+
import path4 from "path";
|
|
864
|
+
import os4 from "os";
|
|
865
|
+
function getOpenCodePluginsDir() {
|
|
866
|
+
return path4.join(os4.homedir(), ".config", "opencode", "plugins");
|
|
867
|
+
}
|
|
868
|
+
function getOpenCodePluginPath() {
|
|
869
|
+
return path4.join(getOpenCodePluginsDir(), "bashstats.ts");
|
|
870
|
+
}
|
|
871
|
+
function isOpenCodeAvailable() {
|
|
872
|
+
try {
|
|
873
|
+
return fs4.existsSync(path4.join(os4.homedir(), ".config", "opencode"));
|
|
874
|
+
} catch {
|
|
875
|
+
return false;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
function getOpenCodePluginContent(dbPath) {
|
|
879
|
+
return `// bashstats plugin for OpenCode -- auto-generated, do not edit
|
|
880
|
+
// Tracks coding sessions, tool usage, and prompts for bashstats achievements.
|
|
881
|
+
|
|
882
|
+
import Database from "better-sqlite3";
|
|
883
|
+
|
|
884
|
+
const DB_PATH = ${JSON.stringify(dbPath)};
|
|
885
|
+
|
|
886
|
+
function today(): string {
|
|
887
|
+
const d = new Date();
|
|
888
|
+
const pad = (n: number) => String(n).padStart(2, "0");
|
|
889
|
+
return \`\${d.getFullYear()}-\${pad(d.getMonth() + 1)}-\${pad(d.getDate())}\`;
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
function localNow(): string {
|
|
893
|
+
const d = new Date();
|
|
894
|
+
const pad = (n: number) => String(n).padStart(2, "0");
|
|
895
|
+
const ms = String(d.getMilliseconds()).padStart(3, "0");
|
|
896
|
+
return \`\${d.getFullYear()}-\${pad(d.getMonth() + 1)}-\${pad(d.getDate())}T\${pad(d.getHours())}:\${pad(d.getMinutes())}:\${pad(d.getSeconds())}.\${ms}\`;
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
function withDb<T>(fn: (db: InstanceType<typeof Database>) => T): T | undefined {
|
|
900
|
+
let db: InstanceType<typeof Database> | undefined;
|
|
901
|
+
try {
|
|
902
|
+
db = new Database(DB_PATH);
|
|
903
|
+
db.pragma("journal_mode = WAL");
|
|
904
|
+
db.pragma("busy_timeout = 5000");
|
|
905
|
+
return fn(db);
|
|
906
|
+
} catch {
|
|
907
|
+
// silently ignore DB errors so we never break the host
|
|
908
|
+
} finally {
|
|
909
|
+
try { db?.close(); } catch {}
|
|
910
|
+
}
|
|
911
|
+
return undefined;
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
function insertEvent(db: InstanceType<typeof Database>, sessionId: string, hookType: string, toolName?: string, toolInput?: string, project?: string): void {
|
|
915
|
+
db.prepare(
|
|
916
|
+
"INSERT INTO events (session_id, hook_type, tool_name, tool_input, cwd, project, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)"
|
|
917
|
+
).run(sessionId, hookType, toolName ?? null, toolInput ?? null, null, project ?? null, localNow());
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
function incrementDaily(db: InstanceType<typeof Database>, increments: { sessions?: number; prompts?: number; tool_calls?: number; errors?: number; duration_seconds?: number }): void {
|
|
921
|
+
const date = today();
|
|
922
|
+
db.prepare(
|
|
923
|
+
\`INSERT INTO daily_activity (date, sessions, prompts, tool_calls, errors, duration_seconds, input_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens)
|
|
924
|
+
VALUES (?, ?, ?, ?, ?, ?, 0, 0, 0, 0)
|
|
925
|
+
ON CONFLICT(date) DO UPDATE SET
|
|
926
|
+
sessions = sessions + excluded.sessions,
|
|
927
|
+
prompts = prompts + excluded.prompts,
|
|
928
|
+
tool_calls = tool_calls + excluded.tool_calls,
|
|
929
|
+
errors = errors + excluded.errors,
|
|
930
|
+
duration_seconds = duration_seconds + excluded.duration_seconds\`
|
|
931
|
+
).run(
|
|
932
|
+
date,
|
|
933
|
+
increments.sessions ?? 0,
|
|
934
|
+
increments.prompts ?? 0,
|
|
935
|
+
increments.tool_calls ?? 0,
|
|
936
|
+
increments.errors ?? 0,
|
|
937
|
+
increments.duration_seconds ?? 0,
|
|
938
|
+
);
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
export default async ({ project, directory }: { project?: string; directory?: string }) => {
|
|
942
|
+
const sessionId = \`opencode-\${Date.now()}\`;
|
|
943
|
+
const startedAt = localNow();
|
|
944
|
+
const projectName = project ?? directory ?? null;
|
|
945
|
+
|
|
946
|
+
// Create session on plugin load
|
|
947
|
+
withDb((db) => {
|
|
948
|
+
db.prepare(
|
|
949
|
+
"INSERT OR IGNORE INTO sessions (id, agent, started_at, project) VALUES (?, ?, ?, ?)"
|
|
950
|
+
).run(sessionId, "opencode", startedAt, projectName);
|
|
951
|
+
incrementDaily(db, { sessions: 1 });
|
|
952
|
+
});
|
|
953
|
+
|
|
954
|
+
return {
|
|
955
|
+
event: async ({ event }: { event: { type: string; properties?: Record<string, unknown> } }) => {
|
|
956
|
+
const eventType = event.type;
|
|
957
|
+
const props = event.properties ?? {};
|
|
958
|
+
|
|
959
|
+
if (eventType === "session.created") {
|
|
960
|
+
withDb((db) => {
|
|
961
|
+
db.prepare(
|
|
962
|
+
"INSERT OR IGNORE INTO sessions (id, agent, started_at, project) VALUES (?, ?, ?, ?)"
|
|
963
|
+
).run(sessionId, "opencode", startedAt, projectName);
|
|
964
|
+
incrementDaily(db, { sessions: 1 });
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
else if (eventType === "session.idle" || eventType === "session.deleted") {
|
|
969
|
+
withDb((db) => {
|
|
970
|
+
const endedAt = localNow();
|
|
971
|
+
const startMs = new Date(startedAt).getTime();
|
|
972
|
+
const endMs = new Date(endedAt).getTime();
|
|
973
|
+
const durationSeconds = Math.max(0, Math.floor((endMs - startMs) / 1000));
|
|
974
|
+
const stopReason = eventType === "session.idle" ? "idle" : "deleted";
|
|
975
|
+
db.prepare(
|
|
976
|
+
"UPDATE sessions SET ended_at = ?, stop_reason = ?, duration_seconds = ? WHERE id = ?"
|
|
977
|
+
).run(endedAt, stopReason, durationSeconds, sessionId);
|
|
978
|
+
incrementDaily(db, { duration_seconds: durationSeconds });
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
else if (eventType === "tool.execute.before") {
|
|
983
|
+
withDb((db) => {
|
|
984
|
+
const toolName = (props.tool as string) ?? "unknown";
|
|
985
|
+
const toolInput = props.input ? JSON.stringify(props.input) : null;
|
|
986
|
+
insertEvent(db, sessionId, "PreToolUse", toolName, toolInput, projectName ?? undefined);
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
else if (eventType === "tool.execute.after") {
|
|
991
|
+
withDb((db) => {
|
|
992
|
+
const toolName = (props.tool as string) ?? "unknown";
|
|
993
|
+
const toolInput = props.input ? JSON.stringify(props.input) : null;
|
|
994
|
+
insertEvent(db, sessionId, "PostToolUse", toolName, toolInput, projectName ?? undefined);
|
|
995
|
+
db.prepare(
|
|
996
|
+
"UPDATE sessions SET tool_count = tool_count + 1 WHERE id = ?"
|
|
997
|
+
).run(sessionId);
|
|
998
|
+
incrementDaily(db, { tool_calls: 1 });
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
else if (eventType === "session.error") {
|
|
1003
|
+
withDb((db) => {
|
|
1004
|
+
const toolName = (props.tool as string) ?? null;
|
|
1005
|
+
insertEvent(db, sessionId, "PostToolUseFailure", toolName ?? undefined, undefined, projectName ?? undefined);
|
|
1006
|
+
db.prepare(
|
|
1007
|
+
"UPDATE sessions SET error_count = error_count + 1 WHERE id = ?"
|
|
1008
|
+
).run(sessionId);
|
|
1009
|
+
incrementDaily(db, { errors: 1 });
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
else if (eventType === "session.compacted") {
|
|
1014
|
+
withDb((db) => {
|
|
1015
|
+
insertEvent(db, sessionId, "PreCompact", undefined, undefined, projectName ?? undefined);
|
|
1016
|
+
});
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
else if (eventType === "message.updated") {
|
|
1020
|
+
const role = props.role as string | undefined;
|
|
1021
|
+
if (role === "user") {
|
|
1022
|
+
withDb((db) => {
|
|
1023
|
+
const content = (props.content as string) ?? "";
|
|
1024
|
+
const charCount = content.length;
|
|
1025
|
+
const wordCount = content.trim() === "" ? 0 : content.trim().split(/\\s+/).length;
|
|
1026
|
+
db.prepare(
|
|
1027
|
+
"INSERT INTO prompts (session_id, content, char_count, word_count, timestamp) VALUES (?, ?, ?, ?, ?)"
|
|
1028
|
+
).run(sessionId, content, charCount, wordCount, localNow());
|
|
1029
|
+
db.prepare(
|
|
1030
|
+
"UPDATE sessions SET prompt_count = prompt_count + 1 WHERE id = ?"
|
|
1031
|
+
).run(sessionId);
|
|
1032
|
+
incrementDaily(db, { prompts: 1 });
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
},
|
|
1037
|
+
};
|
|
1038
|
+
};
|
|
1039
|
+
`;
|
|
1040
|
+
}
|
|
1041
|
+
function installOpenCode() {
|
|
1042
|
+
try {
|
|
1043
|
+
const dataDir = path4.join(os4.homedir(), DATA_DIR);
|
|
1044
|
+
fs4.mkdirSync(dataDir, { recursive: true });
|
|
1045
|
+
const dbPath = path4.join(dataDir, DB_FILENAME);
|
|
1046
|
+
const pluginsDir = getOpenCodePluginsDir();
|
|
1047
|
+
fs4.mkdirSync(pluginsDir, { recursive: true });
|
|
1048
|
+
const pluginPath = getOpenCodePluginPath();
|
|
1049
|
+
const content = getOpenCodePluginContent(dbPath);
|
|
1050
|
+
fs4.writeFileSync(pluginPath, content, "utf-8");
|
|
1051
|
+
return { success: true, message: `bashstats plugin installed at ${pluginPath}` };
|
|
1052
|
+
} catch (err) {
|
|
1053
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1054
|
+
return { success: false, message: `OpenCode plugin install failed: ${message}` };
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
function uninstallOpenCode() {
|
|
1058
|
+
try {
|
|
1059
|
+
const pluginPath = getOpenCodePluginPath();
|
|
1060
|
+
if (fs4.existsSync(pluginPath)) {
|
|
1061
|
+
fs4.unlinkSync(pluginPath);
|
|
1062
|
+
return { success: true, message: "bashstats plugin removed from OpenCode." };
|
|
1063
|
+
}
|
|
1064
|
+
return { success: true, message: "No bashstats plugin found; nothing to uninstall." };
|
|
1065
|
+
} catch (err) {
|
|
1066
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1067
|
+
return { success: false, message: `OpenCode plugin uninstall failed: ${message}` };
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// src/db/writer.ts
|
|
1072
|
+
import path5 from "path";
|
|
1073
|
+
var BashStatsWriter = class {
|
|
1074
|
+
db;
|
|
1075
|
+
constructor(db) {
|
|
1076
|
+
this.db = db;
|
|
1077
|
+
}
|
|
1078
|
+
extractProject(cwd) {
|
|
1079
|
+
return path5.basename(cwd);
|
|
1080
|
+
}
|
|
1081
|
+
today() {
|
|
1082
|
+
const d = /* @__PURE__ */ new Date();
|
|
1083
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
1084
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
|
1085
|
+
}
|
|
1086
|
+
now() {
|
|
1087
|
+
const d = /* @__PURE__ */ new Date();
|
|
1088
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
1089
|
+
const ms = String(d.getMilliseconds()).padStart(3, "0");
|
|
1090
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${ms}`;
|
|
1091
|
+
}
|
|
1092
|
+
recordSessionStart(sessionId, cwd, source, agent) {
|
|
1093
|
+
const project = this.extractProject(cwd);
|
|
1094
|
+
const timestamp = this.now();
|
|
1095
|
+
this.db.insertSession({
|
|
1096
|
+
id: sessionId,
|
|
1097
|
+
agent,
|
|
1098
|
+
started_at: timestamp,
|
|
1099
|
+
project
|
|
1100
|
+
});
|
|
1101
|
+
this.db.insertEvent({
|
|
1102
|
+
session_id: sessionId,
|
|
1103
|
+
hook_type: "SessionStart",
|
|
1104
|
+
tool_name: null,
|
|
1105
|
+
tool_input: JSON.stringify({ source }),
|
|
1106
|
+
tool_output: null,
|
|
1107
|
+
exit_code: null,
|
|
1108
|
+
success: null,
|
|
1109
|
+
cwd,
|
|
1110
|
+
project,
|
|
1111
|
+
timestamp
|
|
1112
|
+
});
|
|
1113
|
+
this.db.incrementDailyActivity(this.today(), { sessions: 1 });
|
|
1114
|
+
}
|
|
1115
|
+
recordPrompt(sessionId, content) {
|
|
1116
|
+
const timestamp = this.now();
|
|
1117
|
+
const wordCount = content.split(/\s+/).filter((w) => w.length > 0).length;
|
|
1118
|
+
const charCount = content.length;
|
|
1119
|
+
this.db.insertPrompt({
|
|
1120
|
+
session_id: sessionId,
|
|
1121
|
+
content,
|
|
1122
|
+
char_count: charCount,
|
|
1123
|
+
word_count: wordCount,
|
|
1124
|
+
timestamp
|
|
1125
|
+
});
|
|
1126
|
+
this.db.insertEvent({
|
|
1127
|
+
session_id: sessionId,
|
|
1128
|
+
hook_type: "UserPromptSubmit",
|
|
1129
|
+
tool_name: null,
|
|
1130
|
+
tool_input: null,
|
|
1131
|
+
tool_output: null,
|
|
1132
|
+
exit_code: null,
|
|
1133
|
+
success: null,
|
|
1134
|
+
cwd: null,
|
|
1135
|
+
project: null,
|
|
1136
|
+
timestamp
|
|
1137
|
+
});
|
|
1138
|
+
this.db.incrementSessionCounters(sessionId, { prompts: 1 });
|
|
1139
|
+
this.db.incrementDailyActivity(this.today(), { prompts: 1 });
|
|
1140
|
+
}
|
|
1141
|
+
recordToolUse(sessionId, hookType, toolName, toolInput, toolOutput, exitCode, cwd) {
|
|
1142
|
+
const timestamp = this.now();
|
|
1143
|
+
const project = this.extractProject(cwd);
|
|
1144
|
+
const success = exitCode === 0 ? 1 : 0;
|
|
1145
|
+
this.db.insertEvent({
|
|
1146
|
+
session_id: sessionId,
|
|
1147
|
+
hook_type: hookType,
|
|
1148
|
+
tool_name: toolName,
|
|
1149
|
+
tool_input: JSON.stringify(toolInput),
|
|
1150
|
+
tool_output: JSON.stringify(toolOutput),
|
|
1151
|
+
exit_code: exitCode,
|
|
1152
|
+
success,
|
|
1153
|
+
cwd,
|
|
1154
|
+
project,
|
|
1155
|
+
timestamp
|
|
1156
|
+
});
|
|
1157
|
+
this.db.incrementSessionCounters(sessionId, {
|
|
1158
|
+
tools: 1,
|
|
1159
|
+
errors: success === 0 ? 1 : 0
|
|
1160
|
+
});
|
|
1161
|
+
this.db.incrementDailyActivity(this.today(), {
|
|
1162
|
+
tool_calls: 1,
|
|
1163
|
+
errors: success === 0 ? 1 : 0
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
recordSessionEnd(sessionId, stopReason, tokens) {
|
|
1167
|
+
const timestamp = this.now();
|
|
1168
|
+
const session = this.db.getSession(sessionId);
|
|
1169
|
+
let durationSeconds;
|
|
1170
|
+
if (session) {
|
|
1171
|
+
const startTime = new Date(session.started_at).getTime();
|
|
1172
|
+
const endTime = new Date(timestamp).getTime();
|
|
1173
|
+
durationSeconds = Math.round((endTime - startTime) / 1e3);
|
|
1174
|
+
}
|
|
1175
|
+
this.db.updateSession(sessionId, {
|
|
1176
|
+
ended_at: timestamp,
|
|
1177
|
+
stop_reason: stopReason,
|
|
1178
|
+
duration_seconds: durationSeconds
|
|
1179
|
+
});
|
|
1180
|
+
if (tokens) {
|
|
1181
|
+
this.db.updateSessionTokens(sessionId, tokens);
|
|
1182
|
+
}
|
|
1183
|
+
this.db.insertEvent({
|
|
1184
|
+
session_id: sessionId,
|
|
1185
|
+
hook_type: "Stop",
|
|
1186
|
+
tool_name: null,
|
|
1187
|
+
tool_input: JSON.stringify({ stop_reason: stopReason }),
|
|
1188
|
+
tool_output: null,
|
|
1189
|
+
exit_code: null,
|
|
1190
|
+
success: null,
|
|
1191
|
+
cwd: null,
|
|
1192
|
+
project: null,
|
|
1193
|
+
timestamp
|
|
1194
|
+
});
|
|
1195
|
+
const dailyIncrements = {};
|
|
1196
|
+
if (durationSeconds !== void 0) {
|
|
1197
|
+
dailyIncrements.duration_seconds = durationSeconds;
|
|
1198
|
+
}
|
|
1199
|
+
if (tokens) {
|
|
1200
|
+
dailyIncrements.input_tokens = tokens.input_tokens;
|
|
1201
|
+
dailyIncrements.output_tokens = tokens.output_tokens;
|
|
1202
|
+
dailyIncrements.cache_creation_input_tokens = tokens.cache_creation_input_tokens;
|
|
1203
|
+
dailyIncrements.cache_read_input_tokens = tokens.cache_read_input_tokens;
|
|
1204
|
+
}
|
|
1205
|
+
if (Object.keys(dailyIncrements).length > 0) {
|
|
1206
|
+
this.db.incrementDailyActivity(this.today(), dailyIncrements);
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
recordNotification(sessionId, message, notificationType) {
|
|
1210
|
+
const timestamp = this.now();
|
|
1211
|
+
const isError = notificationType === "error" || notificationType === "rate_limit";
|
|
1212
|
+
this.db.insertEvent({
|
|
1213
|
+
session_id: sessionId,
|
|
1214
|
+
hook_type: "Notification",
|
|
1215
|
+
tool_name: null,
|
|
1216
|
+
tool_input: JSON.stringify({ message, notification_type: notificationType }),
|
|
1217
|
+
tool_output: null,
|
|
1218
|
+
exit_code: null,
|
|
1219
|
+
success: null,
|
|
1220
|
+
cwd: null,
|
|
1221
|
+
project: null,
|
|
1222
|
+
timestamp
|
|
1223
|
+
});
|
|
1224
|
+
if (isError) {
|
|
1225
|
+
this.db.incrementSessionCounters(sessionId, { errors: 1 });
|
|
1226
|
+
this.db.incrementDailyActivity(this.today(), { errors: 1 });
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
recordSubagent(sessionId, hookType, agentId, agentType) {
|
|
1230
|
+
const timestamp = this.now();
|
|
1231
|
+
this.db.insertEvent({
|
|
1232
|
+
session_id: sessionId,
|
|
1233
|
+
hook_type: hookType,
|
|
1234
|
+
tool_name: null,
|
|
1235
|
+
tool_input: JSON.stringify({ agent_id: agentId, agent_type: agentType ?? null }),
|
|
1236
|
+
tool_output: null,
|
|
1237
|
+
exit_code: null,
|
|
1238
|
+
success: null,
|
|
1239
|
+
cwd: null,
|
|
1240
|
+
project: null,
|
|
1241
|
+
timestamp
|
|
1242
|
+
});
|
|
1243
|
+
}
|
|
1244
|
+
recordCompaction(sessionId, trigger) {
|
|
1245
|
+
const timestamp = this.now();
|
|
1246
|
+
this.db.insertEvent({
|
|
1247
|
+
session_id: sessionId,
|
|
1248
|
+
hook_type: "PreCompact",
|
|
1249
|
+
tool_name: null,
|
|
1250
|
+
tool_input: JSON.stringify({ trigger }),
|
|
1251
|
+
tool_output: null,
|
|
1252
|
+
exit_code: null,
|
|
1253
|
+
success: null,
|
|
1254
|
+
cwd: null,
|
|
1255
|
+
project: null,
|
|
1256
|
+
timestamp
|
|
1257
|
+
});
|
|
1258
|
+
}
|
|
1259
|
+
};
|
|
1260
|
+
|
|
1261
|
+
// src/hooks/handler.ts
|
|
1262
|
+
import path6 from "path";
|
|
1263
|
+
import os5 from "os";
|
|
1264
|
+
import fs6 from "fs";
|
|
1265
|
+
|
|
1266
|
+
// src/hooks/transcript.ts
|
|
1267
|
+
import fs5 from "fs";
|
|
1268
|
+
import readline from "readline";
|
|
1269
|
+
async function extractTokenUsage(transcriptPath) {
|
|
1270
|
+
try {
|
|
1271
|
+
if (!fs5.existsSync(transcriptPath)) return null;
|
|
1272
|
+
const stream = fs5.createReadStream(transcriptPath, { encoding: "utf-8" });
|
|
1273
|
+
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
|
|
1274
|
+
const seenMessages = /* @__PURE__ */ new Map();
|
|
1275
|
+
for await (const line of rl) {
|
|
1276
|
+
if (!line.trim()) continue;
|
|
1277
|
+
try {
|
|
1278
|
+
const entry = JSON.parse(line);
|
|
1279
|
+
const usage = entry.usage ?? entry.response?.usage ?? entry.message?.usage;
|
|
1280
|
+
if (usage && typeof usage === "object" && "input_tokens" in usage) {
|
|
1281
|
+
const msgId = entry.message?.id ?? entry.id ?? `_line_${seenMessages.size}`;
|
|
1282
|
+
seenMessages.set(msgId, {
|
|
1283
|
+
input_tokens: usage.input_tokens ?? 0,
|
|
1284
|
+
output_tokens: usage.output_tokens ?? 0,
|
|
1285
|
+
cache_creation_input_tokens: usage.cache_creation_input_tokens ?? 0,
|
|
1286
|
+
cache_read_input_tokens: usage.cache_read_input_tokens ?? 0
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
} catch {
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
if (seenMessages.size === 0) return null;
|
|
1293
|
+
let inputTokens = 0;
|
|
1294
|
+
let outputTokens = 0;
|
|
1295
|
+
let cacheCreation = 0;
|
|
1296
|
+
let cacheRead = 0;
|
|
1297
|
+
for (const u of seenMessages.values()) {
|
|
1298
|
+
inputTokens += u.input_tokens;
|
|
1299
|
+
outputTokens += u.output_tokens;
|
|
1300
|
+
cacheCreation += u.cache_creation_input_tokens;
|
|
1301
|
+
cacheRead += u.cache_read_input_tokens;
|
|
1302
|
+
}
|
|
1303
|
+
return {
|
|
1304
|
+
input_tokens: inputTokens,
|
|
1305
|
+
output_tokens: outputTokens,
|
|
1306
|
+
cache_creation_input_tokens: cacheCreation,
|
|
1307
|
+
cache_read_input_tokens: cacheRead
|
|
1308
|
+
};
|
|
1309
|
+
} catch {
|
|
1310
|
+
return null;
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
// src/hooks/normalizers/gemini.ts
|
|
1315
|
+
function normalizeGeminiEvent(geminiEvent, raw) {
|
|
1316
|
+
switch (geminiEvent) {
|
|
1317
|
+
case "SessionStart":
|
|
1318
|
+
return { hookType: "SessionStart", payload: raw };
|
|
1319
|
+
case "SessionEnd":
|
|
1320
|
+
return {
|
|
1321
|
+
hookType: "Stop",
|
|
1322
|
+
payload: { ...raw, stop_hook_active: false }
|
|
1323
|
+
};
|
|
1324
|
+
case "BeforeAgent":
|
|
1325
|
+
return { hookType: "UserPromptSubmit", payload: raw };
|
|
1326
|
+
case "BeforeTool":
|
|
1327
|
+
return { hookType: "PreToolUse", payload: raw };
|
|
1328
|
+
case "AfterTool":
|
|
1329
|
+
return { hookType: "PostToolUse", payload: raw };
|
|
1330
|
+
case "AfterModel": {
|
|
1331
|
+
const usageMetadata = raw.llm_response?.usageMetadata;
|
|
1332
|
+
const totalTokenCount = typeof usageMetadata?.totalTokenCount === "number" ? usageMetadata.totalTokenCount : void 0;
|
|
1333
|
+
return {
|
|
1334
|
+
hookType: "AfterModel",
|
|
1335
|
+
payload: raw,
|
|
1336
|
+
...totalTokenCount !== void 0 ? { tokenData: { totalTokenCount } } : {}
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
case "PreCompress":
|
|
1340
|
+
return { hookType: "PreCompact", payload: raw };
|
|
1341
|
+
case "Notification":
|
|
1342
|
+
return { hookType: "Notification", payload: raw };
|
|
1343
|
+
default:
|
|
1344
|
+
return null;
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
// src/hooks/normalizers/copilot.ts
|
|
1349
|
+
function parseToolArgs(toolArgs) {
|
|
1350
|
+
if (!toolArgs || typeof toolArgs !== "string") return {};
|
|
1351
|
+
try {
|
|
1352
|
+
return JSON.parse(toolArgs);
|
|
1353
|
+
} catch {
|
|
1354
|
+
return {};
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
function deriveSessionId() {
|
|
1358
|
+
const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
1359
|
+
const ppid = process.ppid ?? process.pid;
|
|
1360
|
+
return `copilot-${ppid}-${date}`;
|
|
1361
|
+
}
|
|
1362
|
+
function mapSource(source) {
|
|
1363
|
+
if (source === "resume") return "resume";
|
|
1364
|
+
return "startup";
|
|
1365
|
+
}
|
|
1366
|
+
function isToolFailure(toolResult) {
|
|
1367
|
+
if (!toolResult) return false;
|
|
1368
|
+
const resultType = toolResult.resultType;
|
|
1369
|
+
return resultType === "failure" || resultType === "denied";
|
|
1370
|
+
}
|
|
1371
|
+
function normalizeCopilotEvent(copilotEvent, raw) {
|
|
1372
|
+
const sessionId = deriveSessionId();
|
|
1373
|
+
switch (copilotEvent) {
|
|
1374
|
+
case "sessionStart": {
|
|
1375
|
+
return {
|
|
1376
|
+
hookType: "SessionStart",
|
|
1377
|
+
payload: {
|
|
1378
|
+
session_id: sessionId,
|
|
1379
|
+
source: mapSource(raw.source),
|
|
1380
|
+
...raw.model !== void 0 ? { model: raw.model } : {}
|
|
1381
|
+
}
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
case "sessionEnd": {
|
|
1385
|
+
return {
|
|
1386
|
+
hookType: "Stop",
|
|
1387
|
+
payload: {
|
|
1388
|
+
session_id: sessionId,
|
|
1389
|
+
...raw,
|
|
1390
|
+
stop_hook_active: false
|
|
1391
|
+
}
|
|
1392
|
+
};
|
|
1393
|
+
}
|
|
1394
|
+
case "userPromptSubmitted": {
|
|
1395
|
+
return {
|
|
1396
|
+
hookType: "UserPromptSubmit",
|
|
1397
|
+
payload: {
|
|
1398
|
+
session_id: sessionId,
|
|
1399
|
+
prompt: raw.prompt
|
|
1400
|
+
}
|
|
1401
|
+
};
|
|
1402
|
+
}
|
|
1403
|
+
case "preToolUse": {
|
|
1404
|
+
return {
|
|
1405
|
+
hookType: "PreToolUse",
|
|
1406
|
+
payload: {
|
|
1407
|
+
session_id: sessionId,
|
|
1408
|
+
tool_name: raw.toolName,
|
|
1409
|
+
tool_input: parseToolArgs(raw.toolArgs)
|
|
1410
|
+
}
|
|
1411
|
+
};
|
|
1412
|
+
}
|
|
1413
|
+
case "postToolUse": {
|
|
1414
|
+
const toolResult = raw.toolResult ?? {};
|
|
1415
|
+
const failed = isToolFailure(
|
|
1416
|
+
raw.toolResult
|
|
1417
|
+
);
|
|
1418
|
+
return {
|
|
1419
|
+
hookType: failed ? "PostToolUseFailure" : "PostToolUse",
|
|
1420
|
+
payload: {
|
|
1421
|
+
session_id: sessionId,
|
|
1422
|
+
tool_name: raw.toolName,
|
|
1423
|
+
tool_input: parseToolArgs(raw.toolArgs),
|
|
1424
|
+
tool_response: toolResult,
|
|
1425
|
+
exit_code: failed ? 1 : 0
|
|
1426
|
+
}
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
case "errorOccurred": {
|
|
1430
|
+
const error = raw.error ?? {};
|
|
1431
|
+
return {
|
|
1432
|
+
hookType: "PostToolUseFailure",
|
|
1433
|
+
payload: {
|
|
1434
|
+
session_id: sessionId,
|
|
1435
|
+
tool_name: "_error",
|
|
1436
|
+
tool_input: {},
|
|
1437
|
+
tool_response: {
|
|
1438
|
+
error_message: error.message ?? "",
|
|
1439
|
+
error_name: error.name ?? ""
|
|
1440
|
+
},
|
|
1441
|
+
exit_code: 1
|
|
1442
|
+
}
|
|
1443
|
+
};
|
|
1444
|
+
}
|
|
1445
|
+
default:
|
|
1446
|
+
return null;
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
// src/hooks/handler.ts
|
|
1451
|
+
function detectAgent() {
|
|
1452
|
+
if (process.env.GEMINI_SESSION_ID || process.env.GEMINI_PROJECT_DIR || process.env.GEMINI_CLI) return "gemini-cli";
|
|
1453
|
+
if (process.env.GITHUB_COPILOT_CLI) return "copilot-cli";
|
|
1454
|
+
if (process.env.OPENCODE) return "opencode";
|
|
1455
|
+
return "claude-code";
|
|
1456
|
+
}
|
|
1457
|
+
function parseHookEvent(input) {
|
|
1458
|
+
try {
|
|
1459
|
+
if (!input) return null;
|
|
1460
|
+
return JSON.parse(input);
|
|
1461
|
+
} catch {
|
|
1462
|
+
return null;
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
function getDataDir() {
|
|
1466
|
+
return path6.join(os5.homedir(), DATA_DIR);
|
|
1467
|
+
}
|
|
1468
|
+
function getDbPath() {
|
|
1469
|
+
return path6.join(os5.homedir(), DATA_DIR, DB_FILENAME);
|
|
1470
|
+
}
|
|
1471
|
+
async function readStdin() {
|
|
1472
|
+
if (process.env.CLAUDE_HOOK_EVENT) {
|
|
1473
|
+
return process.env.CLAUDE_HOOK_EVENT;
|
|
1474
|
+
}
|
|
1475
|
+
return new Promise((resolve) => {
|
|
1476
|
+
let data = "";
|
|
1477
|
+
process.stdin.setEncoding("utf-8");
|
|
1478
|
+
process.stdin.on("data", (chunk) => {
|
|
1479
|
+
data += chunk;
|
|
1480
|
+
});
|
|
1481
|
+
process.stdin.on("end", () => {
|
|
1482
|
+
resolve(data);
|
|
1483
|
+
});
|
|
1484
|
+
});
|
|
1485
|
+
}
|
|
1486
|
+
async function handleHookEvent(hookType) {
|
|
1487
|
+
const raw = await readStdin();
|
|
1488
|
+
const event = parseHookEvent(raw);
|
|
1489
|
+
if (!event) return;
|
|
1490
|
+
const dataDir = getDataDir();
|
|
1491
|
+
fs6.mkdirSync(dataDir, { recursive: true });
|
|
1492
|
+
const dbPath = getDbPath();
|
|
1493
|
+
const db = new BashStatsDB(dbPath);
|
|
1494
|
+
const writer = new BashStatsWriter(db);
|
|
1495
|
+
try {
|
|
1496
|
+
const agent = detectAgent();
|
|
1497
|
+
let effectiveHookType = hookType;
|
|
1498
|
+
let payload = event;
|
|
1499
|
+
if (agent === "gemini-cli") {
|
|
1500
|
+
const normalized = normalizeGeminiEvent(hookType, event);
|
|
1501
|
+
if (!normalized) return;
|
|
1502
|
+
if (normalized.hookType === "AfterModel") {
|
|
1503
|
+
if (normalized.tokenData) {
|
|
1504
|
+
const sessionId2 = event.session_id ?? "";
|
|
1505
|
+
const metaKey = `gemini_tokens_${sessionId2}`;
|
|
1506
|
+
const existing = db.getMetadata(metaKey);
|
|
1507
|
+
const prev = existing ? parseInt(existing, 10) : 0;
|
|
1508
|
+
db.setMetadata(metaKey, String(prev + normalized.tokenData.totalTokenCount));
|
|
1509
|
+
}
|
|
1510
|
+
return;
|
|
1511
|
+
}
|
|
1512
|
+
effectiveHookType = normalized.hookType;
|
|
1513
|
+
payload = normalized.payload;
|
|
1514
|
+
} else if (agent === "copilot-cli") {
|
|
1515
|
+
const normalized = normalizeCopilotEvent(hookType, event);
|
|
1516
|
+
if (!normalized) return;
|
|
1517
|
+
effectiveHookType = normalized.hookType;
|
|
1518
|
+
payload = normalized.payload;
|
|
1519
|
+
}
|
|
1520
|
+
const sessionId = payload.session_id ?? "";
|
|
1521
|
+
const cwd = payload.cwd ?? "";
|
|
1522
|
+
switch (effectiveHookType) {
|
|
1523
|
+
case "SessionStart": {
|
|
1524
|
+
const source = payload.source ?? "startup";
|
|
1525
|
+
writer.recordSessionStart(sessionId, cwd, source, agent);
|
|
1526
|
+
break;
|
|
1527
|
+
}
|
|
1528
|
+
case "UserPromptSubmit": {
|
|
1529
|
+
const prompt = payload.prompt ?? "";
|
|
1530
|
+
writer.recordPrompt(sessionId, prompt);
|
|
1531
|
+
break;
|
|
1532
|
+
}
|
|
1533
|
+
case "PreToolUse": {
|
|
1534
|
+
const toolName = payload.tool_name ?? "";
|
|
1535
|
+
const toolInput = payload.tool_input ?? {};
|
|
1536
|
+
writer.recordToolUse(sessionId, "PreToolUse", toolName, toolInput, {}, 0, cwd);
|
|
1537
|
+
break;
|
|
1538
|
+
}
|
|
1539
|
+
case "PostToolUse": {
|
|
1540
|
+
const toolName = payload.tool_name ?? "";
|
|
1541
|
+
const toolInput = payload.tool_input ?? {};
|
|
1542
|
+
const toolResponse = payload.tool_response ?? {};
|
|
1543
|
+
const exitCode = payload.exit_code ?? 0;
|
|
1544
|
+
writer.recordToolUse(sessionId, "PostToolUse", toolName, toolInput, toolResponse, exitCode, cwd);
|
|
1545
|
+
break;
|
|
1546
|
+
}
|
|
1547
|
+
case "PostToolUseFailure": {
|
|
1548
|
+
const toolName = payload.tool_name ?? "";
|
|
1549
|
+
const toolInput = payload.tool_input ?? {};
|
|
1550
|
+
const toolResponse = payload.tool_response ?? {};
|
|
1551
|
+
writer.recordToolUse(sessionId, "PostToolUseFailure", toolName, toolInput, toolResponse, 1, cwd);
|
|
1552
|
+
break;
|
|
1553
|
+
}
|
|
1554
|
+
case "Stop": {
|
|
1555
|
+
let tokens = null;
|
|
1556
|
+
if (agent === "gemini-cli") {
|
|
1557
|
+
const metaKey = `gemini_tokens_${sessionId}`;
|
|
1558
|
+
const stored = db.getMetadata(metaKey);
|
|
1559
|
+
if (stored) {
|
|
1560
|
+
const totalTokens = parseInt(stored, 10);
|
|
1561
|
+
const inputTokens = Math.round(totalTokens * 0.7);
|
|
1562
|
+
const outputTokens = totalTokens - inputTokens;
|
|
1563
|
+
tokens = {
|
|
1564
|
+
input_tokens: inputTokens,
|
|
1565
|
+
output_tokens: outputTokens,
|
|
1566
|
+
cache_creation_input_tokens: 0,
|
|
1567
|
+
cache_read_input_tokens: 0
|
|
1568
|
+
};
|
|
1569
|
+
}
|
|
1570
|
+
} else if (agent === "copilot-cli") {
|
|
1571
|
+
tokens = null;
|
|
1572
|
+
} else {
|
|
1573
|
+
const rawPath = payload.transcript_path ?? "";
|
|
1574
|
+
const transcriptPath = rawPath && rawPath.endsWith(".jsonl") ? path6.resolve(rawPath) : "";
|
|
1575
|
+
tokens = transcriptPath ? await extractTokenUsage(transcriptPath) : null;
|
|
1576
|
+
}
|
|
1577
|
+
writer.recordSessionEnd(sessionId, "stopped", tokens);
|
|
1578
|
+
break;
|
|
1579
|
+
}
|
|
1580
|
+
case "Notification": {
|
|
1581
|
+
const message = payload.message ?? "";
|
|
1582
|
+
const notificationType = payload.notification_type ?? "";
|
|
1583
|
+
writer.recordNotification(sessionId, message, notificationType);
|
|
1584
|
+
break;
|
|
1585
|
+
}
|
|
1586
|
+
case "SubagentStart": {
|
|
1587
|
+
const agentId = payload.agent_id ?? "";
|
|
1588
|
+
const agentType = payload.agent_type ?? "";
|
|
1589
|
+
writer.recordSubagent(sessionId, "SubagentStart", agentId, agentType);
|
|
1590
|
+
break;
|
|
1591
|
+
}
|
|
1592
|
+
case "SubagentStop": {
|
|
1593
|
+
const agentId = payload.agent_id ?? "";
|
|
1594
|
+
writer.recordSubagent(sessionId, "SubagentStop", agentId);
|
|
1595
|
+
break;
|
|
1596
|
+
}
|
|
1597
|
+
case "PreCompact": {
|
|
1598
|
+
const trigger = payload.trigger ?? "manual";
|
|
1599
|
+
writer.recordCompaction(sessionId, trigger);
|
|
1600
|
+
break;
|
|
1601
|
+
}
|
|
1602
|
+
case "PermissionRequest": {
|
|
1603
|
+
const toolName = payload.tool_name ?? "";
|
|
1604
|
+
const toolInput = payload.tool_input ?? {};
|
|
1605
|
+
writer.recordToolUse(sessionId, "PermissionRequest", toolName, toolInput, {}, 0, cwd);
|
|
1606
|
+
break;
|
|
1607
|
+
}
|
|
1608
|
+
case "Setup": {
|
|
1609
|
+
return;
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
} finally {
|
|
1613
|
+
db.close();
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
// src/stats/engine.ts
|
|
1618
|
+
function localDateStr(d = /* @__PURE__ */ new Date()) {
|
|
1619
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
1620
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
|
1621
|
+
}
|
|
1622
|
+
function selectWeekChallenges(weekStart) {
|
|
1623
|
+
let hash = 0;
|
|
1624
|
+
for (const c of weekStart) {
|
|
1625
|
+
hash = hash * 31 + c.charCodeAt(0) | 0;
|
|
1626
|
+
}
|
|
1627
|
+
hash = Math.abs(hash);
|
|
1628
|
+
const pool = [...WEEKLY_CHALLENGES];
|
|
1629
|
+
const selected = [];
|
|
1630
|
+
for (let i = 0; i < 3 && pool.length > 0; i++) {
|
|
1631
|
+
const idx = hash % pool.length;
|
|
1632
|
+
selected.push(pool.splice(idx, 1)[0]);
|
|
1633
|
+
hash = Math.abs(hash * 127 + 63 | 0);
|
|
1634
|
+
}
|
|
1635
|
+
return selected;
|
|
1636
|
+
}
|
|
1637
|
+
var StatsEngine = class {
|
|
1638
|
+
db;
|
|
1639
|
+
constructor(db) {
|
|
1640
|
+
this.db = db;
|
|
1641
|
+
}
|
|
1642
|
+
queryScalar(sql, ...params) {
|
|
1643
|
+
const row = this.db.prepare(sql).get(...params);
|
|
1644
|
+
if (!row) return 0;
|
|
1645
|
+
return Object.values(row)[0] ?? 0;
|
|
1646
|
+
}
|
|
1647
|
+
/** Returns a WHERE/AND clause filtering sessions by agent */
|
|
1648
|
+
agentWhere(agent, alias) {
|
|
1649
|
+
if (!agent) return { clause: "", params: [] };
|
|
1650
|
+
const col = alias ? `${alias}.agent` : "agent";
|
|
1651
|
+
return { clause: ` AND ${col} = ?`, params: [agent] };
|
|
1652
|
+
}
|
|
1653
|
+
/** Returns a subquery filter for events/prompts tables */
|
|
1654
|
+
agentSessionFilter(agent) {
|
|
1655
|
+
if (!agent) return { clause: "", params: [] };
|
|
1656
|
+
return { clause: ` AND session_id IN (SELECT id FROM sessions WHERE agent = ?)`, params: [agent] };
|
|
1657
|
+
}
|
|
1658
|
+
getLifetimeStats(agent) {
|
|
1659
|
+
const sf = this.agentWhere(agent);
|
|
1660
|
+
const ef = this.agentSessionFilter(agent);
|
|
1661
|
+
const totalSessions = this.queryScalar("SELECT COUNT(*) as c FROM sessions WHERE 1=1" + sf.clause, ...sf.params);
|
|
1662
|
+
const totalPrompts = this.queryScalar("SELECT COUNT(*) as c FROM prompts WHERE 1=1" + ef.clause, ...ef.params);
|
|
1663
|
+
const totalCharsTyped = this.queryScalar("SELECT COALESCE(SUM(char_count), 0) as c FROM prompts WHERE 1=1" + ef.clause, ...ef.params);
|
|
1664
|
+
const totalToolCalls = this.queryScalar(
|
|
1665
|
+
"SELECT COUNT(*) as c FROM events WHERE hook_type IN ('PostToolUse', 'PostToolUseFailure')" + ef.clause,
|
|
1666
|
+
...ef.params
|
|
1667
|
+
);
|
|
1668
|
+
const totalDurationSeconds = this.queryScalar(
|
|
1669
|
+
"SELECT COALESCE(SUM(duration_seconds), 0) as c FROM sessions WHERE 1=1" + sf.clause,
|
|
1670
|
+
...sf.params
|
|
1671
|
+
);
|
|
1672
|
+
const totalFilesRead = this.queryScalar(
|
|
1673
|
+
"SELECT COUNT(*) as c FROM events WHERE tool_name = 'Read' AND hook_type = 'PostToolUse'" + ef.clause,
|
|
1674
|
+
...ef.params
|
|
1675
|
+
);
|
|
1676
|
+
const totalFilesWritten = this.queryScalar(
|
|
1677
|
+
"SELECT COUNT(*) as c FROM events WHERE tool_name = 'Write' AND hook_type IN ('PostToolUse', 'PostToolUseFailure')" + ef.clause,
|
|
1678
|
+
...ef.params
|
|
1679
|
+
);
|
|
1680
|
+
const totalFilesEdited = this.queryScalar(
|
|
1681
|
+
"SELECT COUNT(*) as c FROM events WHERE tool_name = 'Edit' AND hook_type IN ('PostToolUse', 'PostToolUseFailure')" + ef.clause,
|
|
1682
|
+
...ef.params
|
|
1683
|
+
);
|
|
1684
|
+
const totalFilesCreated = totalFilesWritten;
|
|
1685
|
+
const totalBashCommands = this.queryScalar(
|
|
1686
|
+
"SELECT COUNT(*) as c FROM events WHERE tool_name = 'Bash' AND hook_type IN ('PostToolUse', 'PostToolUseFailure')" + ef.clause,
|
|
1687
|
+
...ef.params
|
|
1688
|
+
);
|
|
1689
|
+
const totalWebSearches = this.queryScalar(
|
|
1690
|
+
"SELECT COUNT(*) as c FROM events WHERE tool_name = 'WebSearch' AND hook_type IN ('PostToolUse', 'PostToolUseFailure')" + ef.clause,
|
|
1691
|
+
...ef.params
|
|
1692
|
+
);
|
|
1693
|
+
const totalWebFetches = this.queryScalar(
|
|
1694
|
+
"SELECT COUNT(*) as c FROM events WHERE tool_name = 'WebFetch' AND hook_type IN ('PostToolUse', 'PostToolUseFailure')" + ef.clause,
|
|
1695
|
+
...ef.params
|
|
1696
|
+
);
|
|
1697
|
+
const totalSubagents = this.queryScalar(
|
|
1698
|
+
"SELECT COUNT(*) as c FROM events WHERE hook_type = 'SubagentStart'" + ef.clause,
|
|
1699
|
+
...ef.params
|
|
1700
|
+
);
|
|
1701
|
+
const totalCompactions = this.queryScalar(
|
|
1702
|
+
"SELECT COUNT(*) as c FROM events WHERE hook_type = 'PreCompact'" + ef.clause,
|
|
1703
|
+
...ef.params
|
|
1704
|
+
);
|
|
1705
|
+
const totalErrors = this.queryScalar(
|
|
1706
|
+
`SELECT COUNT(*) as c FROM events WHERE (hook_type = 'PostToolUseFailure' OR (hook_type = 'Notification' AND (tool_input LIKE '%"notification_type":"error"%' OR tool_input LIKE '%"notification_type":"rate_limit"%')))` + ef.clause,
|
|
1707
|
+
...ef.params
|
|
1708
|
+
);
|
|
1709
|
+
const totalRateLimits = this.queryScalar(
|
|
1710
|
+
"SELECT COUNT(*) as c FROM events WHERE hook_type = 'Notification' AND tool_input LIKE '%rate_limit%'" + ef.clause,
|
|
1711
|
+
...ef.params
|
|
1712
|
+
);
|
|
1713
|
+
const totalInputTokens = this.queryScalar(
|
|
1714
|
+
"SELECT COALESCE(SUM(input_tokens), 0) as c FROM sessions WHERE 1=1" + sf.clause,
|
|
1715
|
+
...sf.params
|
|
1716
|
+
);
|
|
1717
|
+
const totalOutputTokens = this.queryScalar(
|
|
1718
|
+
"SELECT COALESCE(SUM(output_tokens), 0) as c FROM sessions WHERE 1=1" + sf.clause,
|
|
1719
|
+
...sf.params
|
|
1720
|
+
);
|
|
1721
|
+
const totalCacheCreationTokens = this.queryScalar(
|
|
1722
|
+
"SELECT COALESCE(SUM(cache_creation_input_tokens), 0) as c FROM sessions WHERE 1=1" + sf.clause,
|
|
1723
|
+
...sf.params
|
|
1724
|
+
);
|
|
1725
|
+
const totalCacheReadTokens = this.queryScalar(
|
|
1726
|
+
"SELECT COALESCE(SUM(cache_read_input_tokens), 0) as c FROM sessions WHERE 1=1" + sf.clause,
|
|
1727
|
+
...sf.params
|
|
1728
|
+
);
|
|
1729
|
+
const totalTokens = totalInputTokens + totalOutputTokens + totalCacheCreationTokens + totalCacheReadTokens;
|
|
1730
|
+
return {
|
|
1731
|
+
totalSessions,
|
|
1732
|
+
totalDurationSeconds,
|
|
1733
|
+
totalPrompts,
|
|
1734
|
+
totalCharsTyped,
|
|
1735
|
+
totalToolCalls,
|
|
1736
|
+
totalFilesRead,
|
|
1737
|
+
totalFilesWritten,
|
|
1738
|
+
totalFilesEdited,
|
|
1739
|
+
totalFilesCreated,
|
|
1740
|
+
totalBashCommands,
|
|
1741
|
+
totalWebSearches,
|
|
1742
|
+
totalWebFetches,
|
|
1743
|
+
totalSubagents,
|
|
1744
|
+
totalCompactions,
|
|
1745
|
+
totalErrors,
|
|
1746
|
+
totalRateLimits,
|
|
1747
|
+
totalInputTokens,
|
|
1748
|
+
totalOutputTokens,
|
|
1749
|
+
totalCacheCreationTokens,
|
|
1750
|
+
totalCacheReadTokens,
|
|
1751
|
+
totalTokens
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
getToolBreakdown(agent) {
|
|
1755
|
+
const ef = this.agentSessionFilter(agent);
|
|
1756
|
+
const rows = this.db.prepare(
|
|
1757
|
+
"SELECT tool_name, COUNT(*) as cnt FROM events WHERE hook_type = 'PostToolUse' AND tool_name IS NOT NULL" + ef.clause + " GROUP BY tool_name"
|
|
1758
|
+
).all(...ef.params);
|
|
1759
|
+
const breakdown = {};
|
|
1760
|
+
for (const row of rows) {
|
|
1761
|
+
breakdown[row.tool_name] = row.cnt;
|
|
1762
|
+
}
|
|
1763
|
+
return breakdown;
|
|
1764
|
+
}
|
|
1765
|
+
getTimeStats(agent) {
|
|
1766
|
+
const sf = this.agentWhere(agent);
|
|
1767
|
+
const ef = this.agentSessionFilter(agent);
|
|
1768
|
+
const dailyRows = this.db.prepare("SELECT date FROM daily_activity WHERE sessions > 0 OR prompts > 0 OR tool_calls > 0 ORDER BY date ASC").all();
|
|
1769
|
+
let longestStreak = 0;
|
|
1770
|
+
let currentStreak = 0;
|
|
1771
|
+
if (dailyRows.length > 0) {
|
|
1772
|
+
let streak = 1;
|
|
1773
|
+
for (let i = 1; i < dailyRows.length; i++) {
|
|
1774
|
+
const prevDate = /* @__PURE__ */ new Date(dailyRows[i - 1].date + "T00:00:00Z");
|
|
1775
|
+
const currDate = /* @__PURE__ */ new Date(dailyRows[i].date + "T00:00:00Z");
|
|
1776
|
+
const diffDays = (currDate.getTime() - prevDate.getTime()) / (1e3 * 60 * 60 * 24);
|
|
1777
|
+
if (diffDays === 1) {
|
|
1778
|
+
streak++;
|
|
1779
|
+
} else {
|
|
1780
|
+
longestStreak = Math.max(longestStreak, streak);
|
|
1781
|
+
streak = 1;
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
longestStreak = Math.max(longestStreak, streak);
|
|
1785
|
+
const activeDates = new Set(dailyRows.map((r) => r.date));
|
|
1786
|
+
const todayStr = localDateStr();
|
|
1787
|
+
let checkDate = /* @__PURE__ */ new Date();
|
|
1788
|
+
currentStreak = 0;
|
|
1789
|
+
if (activeDates.has(todayStr)) {
|
|
1790
|
+
currentStreak = 1;
|
|
1791
|
+
checkDate.setDate(checkDate.getDate() - 1);
|
|
1792
|
+
while (activeDates.has(localDateStr(checkDate))) {
|
|
1793
|
+
currentStreak++;
|
|
1794
|
+
checkDate.setDate(checkDate.getDate() - 1);
|
|
1795
|
+
}
|
|
1796
|
+
} else {
|
|
1797
|
+
checkDate.setDate(checkDate.getDate() - 1);
|
|
1798
|
+
const yesterdayStr = localDateStr(checkDate);
|
|
1799
|
+
if (activeDates.has(yesterdayStr)) {
|
|
1800
|
+
currentStreak = 1;
|
|
1801
|
+
checkDate.setDate(checkDate.getDate() - 1);
|
|
1802
|
+
while (activeDates.has(localDateStr(checkDate))) {
|
|
1803
|
+
currentStreak++;
|
|
1804
|
+
checkDate.setDate(checkDate.getDate() - 1);
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
const peakHourRow = this.db.prepare(
|
|
1810
|
+
"SELECT CAST(strftime('%H', timestamp) AS INTEGER) as hour, COUNT(*) as cnt FROM prompts WHERE 1=1" + ef.clause + " GROUP BY hour ORDER BY cnt DESC LIMIT 1"
|
|
1811
|
+
).get(...ef.params);
|
|
1812
|
+
const peakHour = peakHourRow?.hour ?? 0;
|
|
1813
|
+
const peakHourCount = peakHourRow?.cnt ?? 0;
|
|
1814
|
+
const nightOwlCount = this.queryScalar(
|
|
1815
|
+
"SELECT COUNT(*) as c FROM prompts WHERE CAST(strftime('%H', timestamp) AS INTEGER) < 5" + ef.clause,
|
|
1816
|
+
...ef.params
|
|
1817
|
+
);
|
|
1818
|
+
const earlyBirdCount = this.queryScalar(
|
|
1819
|
+
"SELECT COUNT(*) as c FROM prompts WHERE CAST(strftime('%H', timestamp) AS INTEGER) BETWEEN 5 AND 7" + ef.clause,
|
|
1820
|
+
...ef.params
|
|
1821
|
+
);
|
|
1822
|
+
const weekendSessions = this.queryScalar(
|
|
1823
|
+
"SELECT COUNT(*) as c FROM sessions WHERE CAST(strftime('%w', started_at) AS INTEGER) IN (0, 6)" + sf.clause,
|
|
1824
|
+
...sf.params
|
|
1825
|
+
);
|
|
1826
|
+
const mostActiveDayRow = this.db.prepare(
|
|
1827
|
+
"SELECT CAST(strftime('%w', started_at) AS INTEGER) as dow, COUNT(*) as cnt FROM sessions WHERE 1=1" + sf.clause + " GROUP BY dow ORDER BY cnt DESC LIMIT 1"
|
|
1828
|
+
).get(...sf.params);
|
|
1829
|
+
const mostActiveDay = mostActiveDayRow?.dow ?? 0;
|
|
1830
|
+
const busiestDateRow = this.db.prepare(
|
|
1831
|
+
"SELECT date, (sessions + prompts + tool_calls) as total FROM daily_activity ORDER BY total DESC LIMIT 1"
|
|
1832
|
+
).get();
|
|
1833
|
+
const busiestDate = busiestDateRow?.date ?? "";
|
|
1834
|
+
const busiestDateCount = busiestDateRow?.total ?? 0;
|
|
1835
|
+
return {
|
|
1836
|
+
currentStreak,
|
|
1837
|
+
longestStreak,
|
|
1838
|
+
peakHour,
|
|
1839
|
+
peakHourCount,
|
|
1840
|
+
nightOwlCount,
|
|
1841
|
+
earlyBirdCount,
|
|
1842
|
+
weekendSessions,
|
|
1843
|
+
mostActiveDay,
|
|
1844
|
+
busiestDate,
|
|
1845
|
+
busiestDateCount
|
|
1846
|
+
};
|
|
1847
|
+
}
|
|
1848
|
+
getSessionRecords(agent) {
|
|
1849
|
+
const sf = this.agentWhere(agent);
|
|
1850
|
+
const longestSessionSeconds = this.queryScalar(
|
|
1851
|
+
"SELECT COALESCE(MAX(duration_seconds), 0) as c FROM sessions WHERE 1=1" + sf.clause,
|
|
1852
|
+
...sf.params
|
|
1853
|
+
);
|
|
1854
|
+
const mostToolsInSession = this.queryScalar(
|
|
1855
|
+
"SELECT COALESCE(MAX(tool_count), 0) as c FROM sessions WHERE 1=1" + sf.clause,
|
|
1856
|
+
...sf.params
|
|
1857
|
+
);
|
|
1858
|
+
const mostPromptsInSession = this.queryScalar(
|
|
1859
|
+
"SELECT COALESCE(MAX(prompt_count), 0) as c FROM sessions WHERE 1=1" + sf.clause,
|
|
1860
|
+
...sf.params
|
|
1861
|
+
);
|
|
1862
|
+
const fastestSessionSeconds = this.queryScalar(
|
|
1863
|
+
"SELECT COALESCE(MIN(duration_seconds), 0) as c FROM sessions WHERE duration_seconds IS NOT NULL AND duration_seconds > 0" + sf.clause,
|
|
1864
|
+
...sf.params
|
|
1865
|
+
);
|
|
1866
|
+
const avgDurationSeconds = this.queryScalar(
|
|
1867
|
+
"SELECT COALESCE(AVG(duration_seconds), 0) as c FROM sessions WHERE duration_seconds IS NOT NULL" + sf.clause,
|
|
1868
|
+
...sf.params
|
|
1869
|
+
);
|
|
1870
|
+
const avgPromptsPerSession = this.queryScalar(
|
|
1871
|
+
"SELECT COALESCE(AVG(prompt_count), 0) as c FROM sessions WHERE 1=1" + sf.clause,
|
|
1872
|
+
...sf.params
|
|
1873
|
+
);
|
|
1874
|
+
const avgToolsPerSession = this.queryScalar(
|
|
1875
|
+
"SELECT COALESCE(AVG(tool_count), 0) as c FROM sessions WHERE 1=1" + sf.clause,
|
|
1876
|
+
...sf.params
|
|
1877
|
+
);
|
|
1878
|
+
const mostTokensInSession = this.queryScalar(
|
|
1879
|
+
"SELECT COALESCE(MAX(COALESCE(input_tokens, 0) + COALESCE(output_tokens, 0) + COALESCE(cache_creation_input_tokens, 0) + COALESCE(cache_read_input_tokens, 0)), 0) as c FROM sessions WHERE 1=1" + sf.clause,
|
|
1880
|
+
...sf.params
|
|
1881
|
+
);
|
|
1882
|
+
const avgTokensPerSession = this.queryScalar(
|
|
1883
|
+
"SELECT COALESCE(AVG(COALESCE(input_tokens, 0) + COALESCE(output_tokens, 0) + COALESCE(cache_creation_input_tokens, 0) + COALESCE(cache_read_input_tokens, 0)), 0) as c FROM sessions WHERE 1=1" + sf.clause,
|
|
1884
|
+
...sf.params
|
|
1885
|
+
);
|
|
1886
|
+
return {
|
|
1887
|
+
longestSessionSeconds,
|
|
1888
|
+
mostToolsInSession,
|
|
1889
|
+
mostPromptsInSession,
|
|
1890
|
+
fastestSessionSeconds,
|
|
1891
|
+
avgDurationSeconds: Math.round(avgDurationSeconds),
|
|
1892
|
+
avgPromptsPerSession: Math.round(avgPromptsPerSession * 100) / 100,
|
|
1893
|
+
avgToolsPerSession: Math.round(avgToolsPerSession * 100) / 100,
|
|
1894
|
+
mostTokensInSession,
|
|
1895
|
+
avgTokensPerSession: Math.round(avgTokensPerSession)
|
|
1896
|
+
};
|
|
1897
|
+
}
|
|
1898
|
+
getProjectStats(agent) {
|
|
1899
|
+
const sf = this.agentWhere(agent);
|
|
1900
|
+
const uniqueProjects = this.queryScalar(
|
|
1901
|
+
"SELECT COUNT(DISTINCT project) as c FROM sessions WHERE project IS NOT NULL" + sf.clause,
|
|
1902
|
+
...sf.params
|
|
1903
|
+
);
|
|
1904
|
+
const projectRows = this.db.prepare(
|
|
1905
|
+
"SELECT project, COUNT(*) as cnt FROM sessions WHERE project IS NOT NULL" + sf.clause + " GROUP BY project ORDER BY cnt DESC"
|
|
1906
|
+
).all(...sf.params);
|
|
1907
|
+
const mostVisitedProject = projectRows.length > 0 ? projectRows[0].project : "";
|
|
1908
|
+
const mostVisitedProjectCount = projectRows.length > 0 ? projectRows[0].cnt : 0;
|
|
1909
|
+
const projectBreakdown = {};
|
|
1910
|
+
for (const row of projectRows) {
|
|
1911
|
+
projectBreakdown[row.project] = row.cnt;
|
|
1912
|
+
}
|
|
1913
|
+
return {
|
|
1914
|
+
uniqueProjects,
|
|
1915
|
+
mostVisitedProject,
|
|
1916
|
+
mostVisitedProjectCount,
|
|
1917
|
+
projectBreakdown
|
|
1918
|
+
};
|
|
1919
|
+
}
|
|
1920
|
+
getAllStats(agent) {
|
|
1921
|
+
return {
|
|
1922
|
+
lifetime: this.getLifetimeStats(agent),
|
|
1923
|
+
tools: this.getToolBreakdown(agent),
|
|
1924
|
+
time: this.getTimeStats(agent),
|
|
1925
|
+
sessions: this.getSessionRecords(agent),
|
|
1926
|
+
projects: this.getProjectStats(agent)
|
|
1927
|
+
};
|
|
1928
|
+
}
|
|
1929
|
+
getAgentBreakdown() {
|
|
1930
|
+
const rows = this.db.prepare(
|
|
1931
|
+
"SELECT agent, COUNT(*) as cnt, COALESCE(SUM(duration_seconds), 0) as total_seconds FROM sessions GROUP BY agent ORDER BY cnt DESC"
|
|
1932
|
+
).all();
|
|
1933
|
+
const sessionsPerAgent = {};
|
|
1934
|
+
const hoursPerAgent = {};
|
|
1935
|
+
for (const row of rows) {
|
|
1936
|
+
sessionsPerAgent[row.agent] = row.cnt;
|
|
1937
|
+
hoursPerAgent[row.agent] = Math.round(row.total_seconds / 3600 * 10) / 10;
|
|
1938
|
+
}
|
|
1939
|
+
return {
|
|
1940
|
+
favoriteAgent: rows.length > 0 ? rows[0].agent : "unknown",
|
|
1941
|
+
sessionsPerAgent,
|
|
1942
|
+
hoursPerAgent,
|
|
1943
|
+
distinctAgents: rows.length
|
|
1944
|
+
};
|
|
1945
|
+
}
|
|
1946
|
+
getWeeklyGoalsPayload() {
|
|
1947
|
+
const today = /* @__PURE__ */ new Date();
|
|
1948
|
+
const dayOfWeek = today.getDay();
|
|
1949
|
+
const mondayOffset = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
|
|
1950
|
+
const monday = new Date(today);
|
|
1951
|
+
monday.setDate(monday.getDate() + mondayOffset);
|
|
1952
|
+
const sunday = new Date(monday);
|
|
1953
|
+
sunday.setDate(sunday.getDate() + 6);
|
|
1954
|
+
const nextMonday = new Date(monday);
|
|
1955
|
+
nextMonday.setDate(nextMonday.getDate() + 7);
|
|
1956
|
+
const weekStart = localDateStr(monday);
|
|
1957
|
+
const weekEnd = localDateStr(sunday);
|
|
1958
|
+
const nextWeekStart = localDateStr(nextMonday);
|
|
1959
|
+
const challenges = selectWeekChallenges(weekStart);
|
|
1960
|
+
const daysActive = this.queryScalar(
|
|
1961
|
+
"SELECT COUNT(*) as c FROM daily_activity WHERE date >= ? AND date <= ? AND (sessions > 0 OR prompts > 0)",
|
|
1962
|
+
weekStart,
|
|
1963
|
+
weekEnd
|
|
1964
|
+
);
|
|
1965
|
+
const multiplier = ACTIVITY_MULTIPLIERS[Math.min(7, Math.max(1, daysActive))] ?? 1;
|
|
1966
|
+
const results = challenges.map((c) => {
|
|
1967
|
+
const current = this.computeWeeklyStat(c.stat, weekStart, weekEnd, nextWeekStart);
|
|
1968
|
+
return {
|
|
1969
|
+
id: c.id,
|
|
1970
|
+
description: c.description,
|
|
1971
|
+
xpReward: c.xpReward,
|
|
1972
|
+
completed: current >= c.threshold,
|
|
1973
|
+
progress: Math.min(1, current / Math.max(1, c.threshold)),
|
|
1974
|
+
threshold: c.threshold,
|
|
1975
|
+
current
|
|
1976
|
+
};
|
|
1977
|
+
});
|
|
1978
|
+
return {
|
|
1979
|
+
weekStart,
|
|
1980
|
+
daysActive,
|
|
1981
|
+
multiplier,
|
|
1982
|
+
challenges: results
|
|
1983
|
+
};
|
|
1984
|
+
}
|
|
1985
|
+
computeWeeklyStat(stat, weekStart, weekEnd, nextWeekStart) {
|
|
1986
|
+
switch (stat) {
|
|
1987
|
+
case "totalPrompts":
|
|
1988
|
+
return this.queryScalar("SELECT COALESCE(SUM(prompts), 0) as c FROM daily_activity WHERE date >= ? AND date <= ?", weekStart, weekEnd);
|
|
1989
|
+
case "totalToolCalls":
|
|
1990
|
+
return this.queryScalar("SELECT COALESCE(SUM(tool_calls), 0) as c FROM daily_activity WHERE date >= ? AND date <= ?", weekStart, weekEnd);
|
|
1991
|
+
case "totalSessions":
|
|
1992
|
+
return this.queryScalar("SELECT COALESCE(SUM(sessions), 0) as c FROM daily_activity WHERE date >= ? AND date <= ?", weekStart, weekEnd);
|
|
1993
|
+
case "daysActive":
|
|
1994
|
+
return this.queryScalar("SELECT COUNT(*) as c FROM daily_activity WHERE date >= ? AND date <= ? AND (sessions > 0 OR prompts > 0)", weekStart, weekEnd);
|
|
1995
|
+
case "totalHours": {
|
|
1996
|
+
const secs = this.queryScalar("SELECT COALESCE(SUM(duration_seconds), 0) as c FROM daily_activity WHERE date >= ? AND date <= ?", weekStart, weekEnd);
|
|
1997
|
+
return Math.round(secs / 3600 * 10) / 10;
|
|
1998
|
+
}
|
|
1999
|
+
case "totalFilesRead":
|
|
2000
|
+
return this.queryScalar("SELECT COUNT(*) as c FROM events WHERE tool_name = 'Read' AND hook_type = 'PostToolUse' AND timestamp >= ? AND timestamp < ?", weekStart, nextWeekStart);
|
|
2001
|
+
case "totalFilesEdited":
|
|
2002
|
+
return this.queryScalar("SELECT COUNT(*) as c FROM events WHERE tool_name = 'Edit' AND hook_type IN ('PostToolUse', 'PostToolUseFailure') AND timestamp >= ? AND timestamp < ?", weekStart, nextWeekStart);
|
|
2003
|
+
case "totalFilesCreated":
|
|
2004
|
+
return this.queryScalar("SELECT COUNT(*) as c FROM events WHERE tool_name = 'Write' AND hook_type IN ('PostToolUse', 'PostToolUseFailure') AND timestamp >= ? AND timestamp < ?", weekStart, nextWeekStart);
|
|
2005
|
+
case "totalBashCommands":
|
|
2006
|
+
return this.queryScalar("SELECT COUNT(*) as c FROM events WHERE tool_name = 'Bash' AND hook_type IN ('PostToolUse', 'PostToolUseFailure') AND timestamp >= ? AND timestamp < ?", weekStart, nextWeekStart);
|
|
2007
|
+
case "totalSearches":
|
|
2008
|
+
return this.queryScalar("SELECT COUNT(*) as c FROM events WHERE tool_name IN ('Grep', 'Glob') AND hook_type = 'PostToolUse' AND timestamp >= ? AND timestamp < ?", weekStart, nextWeekStart);
|
|
2009
|
+
case "totalCommits":
|
|
2010
|
+
return this.queryScalar("SELECT COUNT(*) as c FROM events WHERE tool_name = 'Bash' AND hook_type = 'PostToolUse' AND tool_input LIKE '%git commit%' AND timestamp >= ? AND timestamp < ?", weekStart, nextWeekStart);
|
|
2011
|
+
case "totalPRs":
|
|
2012
|
+
return this.queryScalar("SELECT COUNT(*) as c FROM events WHERE tool_name = 'Bash' AND hook_type = 'PostToolUse' AND tool_input LIKE '%gh pr create%' AND timestamp >= ? AND timestamp < ?", weekStart, nextWeekStart);
|
|
2013
|
+
case "commitDays":
|
|
2014
|
+
return this.queryScalar("SELECT COUNT(DISTINCT substr(timestamp, 1, 10)) as c FROM events WHERE tool_name = 'Bash' AND hook_type = 'PostToolUse' AND tool_input LIKE '%git commit%' AND timestamp >= ? AND timestamp < ?", weekStart, nextWeekStart);
|
|
2015
|
+
case "longPromptCount":
|
|
2016
|
+
return this.queryScalar("SELECT COUNT(*) as c FROM prompts WHERE char_count > 1000 AND timestamp >= ? AND timestamp < ?", weekStart, nextWeekStart);
|
|
2017
|
+
case "nightOwlDays":
|
|
2018
|
+
return this.queryScalar("SELECT COUNT(DISTINCT substr(timestamp, 1, 10)) as c FROM prompts WHERE CAST(strftime('%H', timestamp) AS INTEGER) < 5 AND timestamp >= ? AND timestamp < ?", weekStart, nextWeekStart);
|
|
2019
|
+
case "earlyBirdDays":
|
|
2020
|
+
return this.queryScalar("SELECT COUNT(DISTINCT substr(timestamp, 1, 10)) as c FROM prompts WHERE CAST(strftime('%H', timestamp) AS INTEGER) BETWEEN 5 AND 7 AND timestamp >= ? AND timestamp < ?", weekStart, nextWeekStart);
|
|
2021
|
+
case "weekendDays":
|
|
2022
|
+
return this.queryScalar("SELECT COUNT(*) as c FROM daily_activity WHERE date >= ? AND date <= ? AND (sessions > 0 OR prompts > 0) AND CAST(strftime('%w', date) AS INTEGER) IN (0, 6)", weekStart, weekEnd);
|
|
2023
|
+
case "uniqueProjects":
|
|
2024
|
+
return this.queryScalar("SELECT COUNT(DISTINCT project) as c FROM sessions WHERE project IS NOT NULL AND started_at >= ? AND started_at < ?", weekStart, nextWeekStart);
|
|
2025
|
+
case "cleanSessions":
|
|
2026
|
+
return this.queryScalar("SELECT COUNT(*) as c FROM sessions WHERE error_count = 0 AND tool_count > 0 AND started_at >= ? AND started_at < ?", weekStart, nextWeekStart);
|
|
2027
|
+
case "extendedSessionCount":
|
|
2028
|
+
return this.queryScalar("SELECT COUNT(*) as c FROM sessions WHERE duration_seconds > 3600 AND prompt_count >= 15 AND started_at >= ? AND started_at < ?", weekStart, nextWeekStart);
|
|
2029
|
+
case "quickDrawSessions":
|
|
2030
|
+
return this.queryScalar("SELECT COUNT(*) as c FROM sessions WHERE duration_seconds IS NOT NULL AND duration_seconds < 120 AND tool_count > 0 AND started_at >= ? AND started_at < ?", weekStart, nextWeekStart);
|
|
2031
|
+
case "diverseToolSessions":
|
|
2032
|
+
return this.queryScalar("SELECT COUNT(*) as c FROM (SELECT session_id FROM events WHERE hook_type = 'PostToolUse' AND tool_name IS NOT NULL AND session_id IN (SELECT id FROM sessions WHERE started_at >= ? AND started_at < ?) GROUP BY session_id HAVING COUNT(DISTINCT tool_name) >= 5)", weekStart, nextWeekStart);
|
|
2033
|
+
case "maxSubagentsInSession":
|
|
2034
|
+
return this.queryScalar("SELECT COALESCE(MAX(cnt), 0) as c FROM (SELECT COUNT(*) as cnt FROM events WHERE hook_type = 'SubagentStart' AND session_id IN (SELECT id FROM sessions WHERE started_at >= ? AND started_at < ?) GROUP BY session_id)", weekStart, nextWeekStart);
|
|
2035
|
+
default:
|
|
2036
|
+
return 0;
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
};
|
|
2040
|
+
|
|
2041
|
+
// src/types.ts
|
|
2042
|
+
var AGENT_DISPLAY_NAMES = {
|
|
2043
|
+
"claude-code": "Claude Code",
|
|
2044
|
+
"gemini-cli": "Gemini CLI",
|
|
2045
|
+
"copilot-cli": "Copilot CLI",
|
|
2046
|
+
"opencode": "OpenCode",
|
|
2047
|
+
"unknown": "Unknown"
|
|
2048
|
+
};
|
|
2049
|
+
var TIER_NAMES = {
|
|
2050
|
+
0: "Locked",
|
|
2051
|
+
1: "Bronze",
|
|
2052
|
+
2: "Silver",
|
|
2053
|
+
3: "Gold",
|
|
2054
|
+
4: "Diamond",
|
|
2055
|
+
5: "Singularity"
|
|
2056
|
+
};
|
|
2057
|
+
|
|
2058
|
+
// src/achievements/compute.ts
|
|
2059
|
+
var AchievementEngine = class {
|
|
2060
|
+
db;
|
|
2061
|
+
stats;
|
|
2062
|
+
constructor(db, stats) {
|
|
2063
|
+
this.db = db;
|
|
2064
|
+
this.stats = stats;
|
|
2065
|
+
}
|
|
2066
|
+
computeBadges(agent) {
|
|
2067
|
+
const allStats = this.stats.getAllStats(agent);
|
|
2068
|
+
const flat = this.flattenStats(allStats);
|
|
2069
|
+
return BADGE_DEFINITIONS.map((badge) => {
|
|
2070
|
+
const value = flat[badge.stat] ?? 0;
|
|
2071
|
+
let tier = 0;
|
|
2072
|
+
if (badge.aspirational) {
|
|
2073
|
+
tier = value >= badge.tiers[4] ? 5 : 0;
|
|
2074
|
+
} else if (badge.secret) {
|
|
2075
|
+
tier = value >= badge.tiers[0] ? 1 : 0;
|
|
2076
|
+
} else {
|
|
2077
|
+
for (let i = 0; i < badge.tiers.length; i++) {
|
|
2078
|
+
if (value >= badge.tiers[i]) {
|
|
2079
|
+
tier = i + 1;
|
|
2080
|
+
} else {
|
|
2081
|
+
break;
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
let nextThreshold = 0;
|
|
2086
|
+
let progress = 0;
|
|
2087
|
+
let maxed = false;
|
|
2088
|
+
if (badge.aspirational) {
|
|
2089
|
+
nextThreshold = badge.tiers[4];
|
|
2090
|
+
progress = tier === 5 ? 1 : Math.min(value / nextThreshold, 0.99);
|
|
2091
|
+
maxed = tier === 5;
|
|
2092
|
+
} else if (badge.secret) {
|
|
2093
|
+
nextThreshold = badge.tiers[0];
|
|
2094
|
+
progress = tier >= 1 ? 1 : 0;
|
|
2095
|
+
maxed = tier >= 1;
|
|
2096
|
+
} else if (tier >= 5) {
|
|
2097
|
+
nextThreshold = badge.tiers[4];
|
|
2098
|
+
progress = 1;
|
|
2099
|
+
maxed = true;
|
|
2100
|
+
} else {
|
|
2101
|
+
const tierIdx = tier;
|
|
2102
|
+
nextThreshold = badge.tiers[tierIdx];
|
|
2103
|
+
const prevThreshold = tierIdx > 0 ? badge.tiers[tierIdx - 1] : 0;
|
|
2104
|
+
const range = nextThreshold - prevThreshold;
|
|
2105
|
+
progress = range > 0 ? Math.min((value - prevThreshold) / range, 0.99) : 0;
|
|
2106
|
+
}
|
|
2107
|
+
if (tier > 0) {
|
|
2108
|
+
for (let t = 1; t <= tier; t++) {
|
|
2109
|
+
this.db.insertUnlock(badge.id, t);
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
return {
|
|
2113
|
+
id: badge.id,
|
|
2114
|
+
name: badge.name,
|
|
2115
|
+
icon: badge.icon,
|
|
2116
|
+
description: badge.description,
|
|
2117
|
+
category: badge.category,
|
|
2118
|
+
stat: badge.stat,
|
|
2119
|
+
tiers: badge.tiers,
|
|
2120
|
+
tier,
|
|
2121
|
+
tierName: TIER_NAMES[tier],
|
|
2122
|
+
value,
|
|
2123
|
+
nextThreshold,
|
|
2124
|
+
progress,
|
|
2125
|
+
maxed,
|
|
2126
|
+
trigger: badge.trigger,
|
|
2127
|
+
secret: badge.secret ?? false,
|
|
2128
|
+
unlocked: tier > 0
|
|
2129
|
+
};
|
|
2130
|
+
});
|
|
2131
|
+
}
|
|
2132
|
+
computeXP(agent) {
|
|
2133
|
+
const allStats = this.stats.getAllStats(agent);
|
|
2134
|
+
const badges = this.computeBadges(agent);
|
|
2135
|
+
let totalXP = 0;
|
|
2136
|
+
totalXP += allStats.lifetime.totalPrompts * 1;
|
|
2137
|
+
totalXP += allStats.lifetime.totalSessions * 5;
|
|
2138
|
+
totalXP += Math.floor(allStats.lifetime.totalDurationSeconds / 3600) * 10;
|
|
2139
|
+
totalXP += allStats.time.longestStreak * 5;
|
|
2140
|
+
for (const badge of badges) {
|
|
2141
|
+
if (badge.tier > 0) {
|
|
2142
|
+
totalXP += TIER_XP[badge.tier] ?? 0;
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
let rankNumber = 0;
|
|
2146
|
+
for (let r = 500; r >= 1; r--) {
|
|
2147
|
+
if (totalXP >= xpForRank(r)) {
|
|
2148
|
+
rankNumber = r;
|
|
2149
|
+
break;
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
let nextRankXP;
|
|
2153
|
+
let progress;
|
|
2154
|
+
if (rankNumber >= 500) {
|
|
2155
|
+
nextRankXP = xpForRank(500);
|
|
2156
|
+
progress = 1;
|
|
2157
|
+
} else {
|
|
2158
|
+
const nextRank = rankNumber + 1;
|
|
2159
|
+
nextRankXP = xpForRank(nextRank);
|
|
2160
|
+
const currentThreshold = rankNumber > 0 ? xpForRank(rankNumber) : 0;
|
|
2161
|
+
const range = nextRankXP - currentThreshold;
|
|
2162
|
+
progress = range > 0 ? Math.min((totalXP - currentThreshold) / range, 0.99) : 0;
|
|
2163
|
+
}
|
|
2164
|
+
return {
|
|
2165
|
+
totalXP,
|
|
2166
|
+
rankNumber,
|
|
2167
|
+
rankTier: rankTierForRank(rankNumber || 1),
|
|
2168
|
+
nextRankXP,
|
|
2169
|
+
progress
|
|
2170
|
+
};
|
|
2171
|
+
}
|
|
2172
|
+
getAchievementsPayload(agent) {
|
|
2173
|
+
const allStats = this.stats.getAllStats(agent);
|
|
2174
|
+
return {
|
|
2175
|
+
stats: allStats,
|
|
2176
|
+
badges: this.computeBadges(agent),
|
|
2177
|
+
xp: this.computeXP(agent)
|
|
2178
|
+
};
|
|
2179
|
+
}
|
|
2180
|
+
flattenStats(allStats) {
|
|
2181
|
+
const flat = {};
|
|
2182
|
+
flat.totalPrompts = allStats.lifetime.totalPrompts;
|
|
2183
|
+
flat.totalToolCalls = allStats.lifetime.totalToolCalls;
|
|
2184
|
+
flat.totalSessions = allStats.lifetime.totalSessions;
|
|
2185
|
+
flat.totalCharsTyped = allStats.lifetime.totalCharsTyped;
|
|
2186
|
+
flat.totalBashCommands = allStats.lifetime.totalBashCommands;
|
|
2187
|
+
flat.totalFilesRead = allStats.lifetime.totalFilesRead;
|
|
2188
|
+
flat.totalFilesEdited = allStats.lifetime.totalFilesEdited;
|
|
2189
|
+
flat.totalFilesCreated = allStats.lifetime.totalFilesCreated;
|
|
2190
|
+
flat.totalSubagents = allStats.lifetime.totalSubagents;
|
|
2191
|
+
flat.totalErrors = allStats.lifetime.totalErrors;
|
|
2192
|
+
flat.totalRateLimits = allStats.lifetime.totalRateLimits;
|
|
2193
|
+
flat.totalWebFetches = allStats.lifetime.totalWebFetches;
|
|
2194
|
+
flat.totalWebSearches = allStats.lifetime.totalWebSearches;
|
|
2195
|
+
flat.totalCompactions = allStats.lifetime.totalCompactions;
|
|
2196
|
+
flat.totalSessionHours = Math.floor(allStats.lifetime.totalDurationSeconds / 3600);
|
|
2197
|
+
flat.longestStreak = allStats.time.longestStreak;
|
|
2198
|
+
flat.nightOwlCount = allStats.time.nightOwlCount;
|
|
2199
|
+
flat.earlyBirdCount = allStats.time.earlyBirdCount;
|
|
2200
|
+
flat.weekendSessions = allStats.time.weekendSessions;
|
|
2201
|
+
flat.totalSearches = this.queryTotalSearches();
|
|
2202
|
+
flat.mostRepeatedPromptCount = this.queryMostRepeatedPromptCount();
|
|
2203
|
+
flat.uniqueToolsUsed = this.queryUniqueToolsUsed();
|
|
2204
|
+
flat.planModeUses = this.queryPlanModeUses();
|
|
2205
|
+
flat.longPromptCount = this.queryLongPromptCount();
|
|
2206
|
+
flat.quickSessionCount = this.queryQuickSessionCount();
|
|
2207
|
+
flat.longestErrorFreeStreak = this.queryLongestErrorFreeStreak();
|
|
2208
|
+
flat.politePromptCount = this.queryPolitePromptCount();
|
|
2209
|
+
flat.hugePromptCount = this.queryHugePromptCount();
|
|
2210
|
+
flat.maxSameFileEdits = this.queryMaxSameFileEdits();
|
|
2211
|
+
flat.longSessionCount = this.queryLongSessionCount();
|
|
2212
|
+
flat.repeatedPromptCount = this.queryRepeatedPromptCount();
|
|
2213
|
+
flat.maxErrorsInSession = this.queryMaxErrorsInSession();
|
|
2214
|
+
flat.totalCommits = this.queryTotalCommits();
|
|
2215
|
+
flat.totalPRs = this.queryTotalPRs();
|
|
2216
|
+
flat.uniqueProjects = allStats.projects.uniqueProjects;
|
|
2217
|
+
flat.uniqueLanguages = this.queryUniqueLanguages();
|
|
2218
|
+
flat.concurrentAgentUses = this.queryConcurrentAgentUses();
|
|
2219
|
+
flat.dangerousCommandBlocked = this.queryDangerousCommandBlocked();
|
|
2220
|
+
flat.returnAfterBreak = this.queryReturnAfterBreak();
|
|
2221
|
+
flat.threeAmPrompt = this.queryThreeAmPrompt();
|
|
2222
|
+
flat.midnightSpanSession = this.queryMidnightSpanSession();
|
|
2223
|
+
flat.nestedSubagent = this.queryNestedSubagent();
|
|
2224
|
+
flat.holidayActivity = this.queryHolidayActivity();
|
|
2225
|
+
flat.speedRunSession = this.querySpeedRunSession();
|
|
2226
|
+
flat.allToolsInSession = this.queryAllToolsInSession();
|
|
2227
|
+
flat.firstEverSession = allStats.lifetime.totalSessions > 0 ? 1 : 0;
|
|
2228
|
+
flat.allBadgesGold = 0;
|
|
2229
|
+
flat.totalXP = 0;
|
|
2230
|
+
flat.allToolsObsidian = 0;
|
|
2231
|
+
flat.allNonSecretBadgesUnlocked = 0;
|
|
2232
|
+
flat.witchingHourPrompts = this.queryWitchingHourPrompts();
|
|
2233
|
+
flat.lunchBreakDays = this.queryLunchBreakDays();
|
|
2234
|
+
flat.mondaySessions = this.queryMondaySessions();
|
|
2235
|
+
flat.fridayCommits = this.queryFridayCommits();
|
|
2236
|
+
flat.maxUniqueHoursInDay = this.queryMaxUniqueHoursInDay();
|
|
2237
|
+
flat.uniqueQuarters = this.queryUniqueQuarters();
|
|
2238
|
+
flat.extendedSessionCount = this.queryExtendedSessionCount();
|
|
2239
|
+
flat.quickDrawSessions = this.queryQuickDrawSessions();
|
|
2240
|
+
flat.diverseToolSessions = this.queryDiverseToolSessions();
|
|
2241
|
+
flat.permissionRequests = this.queryPermissionRequests();
|
|
2242
|
+
flat.returnerDays = this.queryReturnerDays();
|
|
2243
|
+
flat.shortPromptCount = this.queryShortPromptCount();
|
|
2244
|
+
flat.questionPromptCount = this.queryQuestionPromptCount();
|
|
2245
|
+
flat.sorryPromptCount = this.querySorryPromptCount();
|
|
2246
|
+
flat.capsLockPromptCount = this.queryCapsLockPromptCount();
|
|
2247
|
+
flat.emojiPromptCount = this.queryEmojiPromptCount();
|
|
2248
|
+
flat.codeDumpPromptCount = this.queryCodeDumpPromptCount();
|
|
2249
|
+
flat.rubberDuckCount = this.queryRubberDuckCount();
|
|
2250
|
+
flat.thirdTimeCharmCount = this.queryThirdTimeCharmCount();
|
|
2251
|
+
flat.undoEditCount = this.queryUndoEditCount();
|
|
2252
|
+
flat.crashySessions = this.queryCrashySessions();
|
|
2253
|
+
flat.totalLifetimeErrors = allStats.lifetime.totalErrors;
|
|
2254
|
+
flat.readEditRunCount = this.queryReadEditRunCount();
|
|
2255
|
+
flat.maxFilesCreatedInSession = this.queryMaxFilesCreatedInSession();
|
|
2256
|
+
flat.maxSameFileEditsLifetime = this.queryMaxSameFileEditsLifetime();
|
|
2257
|
+
flat.searchThenEditCount = this.querySearchThenEditCount();
|
|
2258
|
+
flat.maxProjectSessions = this.queryMaxProjectSessions();
|
|
2259
|
+
flat.maxProjectsInDay = this.queryMaxProjectsInDay();
|
|
2260
|
+
flat.finishedProjects = this.queryFinishedProjects();
|
|
2261
|
+
flat.legacyReturns = this.queryLegacyReturns();
|
|
2262
|
+
flat.totalUniqueProjects = allStats.projects.uniqueProjects;
|
|
2263
|
+
flat.maxConcurrentSubagents = this.queryMaxConcurrentSubagents();
|
|
2264
|
+
flat.quickSubagentStops = this.queryQuickSubagentStops();
|
|
2265
|
+
flat.totalSubagentSpawns = allStats.lifetime.totalSubagents;
|
|
2266
|
+
flat.maxSubagentsInSession = this.queryMaxSubagentsInSession();
|
|
2267
|
+
flat.distinctAgentsUsed = this.queryScalar("SELECT COUNT(DISTINCT agent) FROM sessions");
|
|
2268
|
+
flat.geminiSessions = this.queryScalar("SELECT COUNT(*) FROM sessions WHERE agent = 'gemini-cli'");
|
|
2269
|
+
flat.copilotSessions = this.queryScalar("SELECT COUNT(*) FROM sessions WHERE agent = 'copilot-cli'");
|
|
2270
|
+
flat.opencodeSessions = this.queryScalar("SELECT COUNT(*) FROM sessions WHERE agent = 'opencode'");
|
|
2271
|
+
flat.doubleAgentDays = this.queryScalar(
|
|
2272
|
+
"SELECT COUNT(*) FROM (SELECT substr(started_at, 1, 10) as d FROM sessions GROUP BY d HAVING COUNT(DISTINCT agent) >= 2)"
|
|
2273
|
+
);
|
|
2274
|
+
flat.agentSwitchDays = flat.doubleAgentDays;
|
|
2275
|
+
flat.dejaVuCount = this.queryDejaVuCount();
|
|
2276
|
+
flat.trustIssueCount = this.queryTrustIssueCount();
|
|
2277
|
+
flat.backseatDriverCount = this.queryBackseatDriverCount();
|
|
2278
|
+
flat.negotiatorCount = this.queryNegotiatorCount();
|
|
2279
|
+
flat.maxConsecutivePermissions = this.queryMaxConsecutivePermissions();
|
|
2280
|
+
flat.bashRetrySuccessCount = this.queryBashRetrySuccessCount();
|
|
2281
|
+
flat.easterEggActivity = this.queryEasterEggActivity();
|
|
2282
|
+
flat.fullMoonSession = this.queryFullMoonSession();
|
|
2283
|
+
flat.birthdaySession = this.queryBirthdaySession();
|
|
2284
|
+
flat.luckyNumber = allStats.lifetime.totalPrompts >= 777 || allStats.lifetime.totalToolCalls >= 7777 ? 1 : 0;
|
|
2285
|
+
flat.ghostSessions = this.queryGhostSessions();
|
|
2286
|
+
flat.bullseyeSessions = this.queryBullseyeSessions();
|
|
2287
|
+
flat.hasTenMillionSession = this.queryHasTenMillionSession();
|
|
2288
|
+
flat.totalTokens = allStats.lifetime.totalTokens;
|
|
2289
|
+
flat.totalOutputTokens = allStats.lifetime.totalOutputTokens;
|
|
2290
|
+
flat.totalCacheReadTokens = allStats.lifetime.totalCacheReadTokens;
|
|
2291
|
+
flat.totalCacheCreationTokens = allStats.lifetime.totalCacheCreationTokens;
|
|
2292
|
+
flat.totalInputTokens = allStats.lifetime.totalInputTokens;
|
|
2293
|
+
flat.mostTokensInSession = allStats.sessions.mostTokensInSession;
|
|
2294
|
+
flat.avgTokensPerSession = allStats.sessions.avgTokensPerSession;
|
|
2295
|
+
flat.heavyTokenSessions = this.queryHeavyTokenSessions();
|
|
2296
|
+
flat.lightTokenSessions = this.queryLightTokenSessions();
|
|
2297
|
+
flat.maxOutputInSession = this.queryMaxOutputInSession();
|
|
2298
|
+
return flat;
|
|
2299
|
+
}
|
|
2300
|
+
// === Computed stat query helpers ===
|
|
2301
|
+
queryScalar(sql, ...params) {
|
|
2302
|
+
const row = this.db.prepare(sql).get(...params);
|
|
2303
|
+
if (!row) return 0;
|
|
2304
|
+
return Object.values(row)[0] ?? 0;
|
|
2305
|
+
}
|
|
2306
|
+
queryTotalSearches() {
|
|
2307
|
+
return this.queryScalar(
|
|
2308
|
+
"SELECT COUNT(*) as c FROM events WHERE tool_name IN ('Grep', 'Glob') AND hook_type = 'PostToolUse'"
|
|
2309
|
+
);
|
|
2310
|
+
}
|
|
2311
|
+
queryPolitePromptCount() {
|
|
2312
|
+
return this.queryScalar(
|
|
2313
|
+
"SELECT COUNT(*) as c FROM prompts WHERE LOWER(content) LIKE '%please%' OR LOWER(content) LIKE '%thank%'"
|
|
2314
|
+
);
|
|
2315
|
+
}
|
|
2316
|
+
queryHugePromptCount() {
|
|
2317
|
+
return this.queryScalar(
|
|
2318
|
+
"SELECT COUNT(*) as c FROM prompts WHERE char_count > 5000"
|
|
2319
|
+
);
|
|
2320
|
+
}
|
|
2321
|
+
queryLongPromptCount() {
|
|
2322
|
+
return this.queryScalar(
|
|
2323
|
+
"SELECT COUNT(*) as c FROM prompts WHERE char_count > 1000"
|
|
2324
|
+
);
|
|
2325
|
+
}
|
|
2326
|
+
queryMostRepeatedPromptCount() {
|
|
2327
|
+
return this.queryScalar(
|
|
2328
|
+
"SELECT COUNT(*) as c FROM prompts GROUP BY LOWER(TRIM(content)) ORDER BY c DESC LIMIT 1"
|
|
2329
|
+
);
|
|
2330
|
+
}
|
|
2331
|
+
queryUniqueToolsUsed() {
|
|
2332
|
+
return this.queryScalar(
|
|
2333
|
+
"SELECT COUNT(DISTINCT tool_name) as c FROM events WHERE hook_type = 'PostToolUse' AND tool_name IS NOT NULL"
|
|
2334
|
+
);
|
|
2335
|
+
}
|
|
2336
|
+
queryPlanModeUses() {
|
|
2337
|
+
return this.queryScalar(
|
|
2338
|
+
"SELECT COUNT(*) as c FROM events WHERE hook_type = 'PostToolUse' AND tool_name = 'Task'"
|
|
2339
|
+
);
|
|
2340
|
+
}
|
|
2341
|
+
queryQuickSessionCount() {
|
|
2342
|
+
return this.queryScalar(
|
|
2343
|
+
"SELECT COUNT(*) as c FROM sessions WHERE duration_seconds IS NOT NULL AND duration_seconds < 300 AND tool_count > 0"
|
|
2344
|
+
);
|
|
2345
|
+
}
|
|
2346
|
+
queryLongSessionCount() {
|
|
2347
|
+
return this.queryScalar(
|
|
2348
|
+
"SELECT COUNT(*) as c FROM sessions WHERE duration_seconds IS NOT NULL AND duration_seconds > 28800"
|
|
2349
|
+
);
|
|
2350
|
+
}
|
|
2351
|
+
queryMaxErrorsInSession() {
|
|
2352
|
+
return this.queryScalar(
|
|
2353
|
+
"SELECT COALESCE(MAX(error_count), 0) as c FROM sessions"
|
|
2354
|
+
);
|
|
2355
|
+
}
|
|
2356
|
+
queryMaxSameFileEdits() {
|
|
2357
|
+
return this.queryScalar(
|
|
2358
|
+
"SELECT COUNT(*) as c FROM events WHERE tool_name = 'Edit' AND hook_type = 'PostToolUse' GROUP BY json_extract(tool_input, '$.file_path') ORDER BY c DESC LIMIT 1"
|
|
2359
|
+
);
|
|
2360
|
+
}
|
|
2361
|
+
queryRepeatedPromptCount() {
|
|
2362
|
+
return this.queryScalar(
|
|
2363
|
+
"SELECT COALESCE(SUM(cnt), 0) as c FROM (SELECT COUNT(*) as cnt FROM prompts GROUP BY LOWER(TRIM(content)) HAVING cnt > 1)"
|
|
2364
|
+
);
|
|
2365
|
+
}
|
|
2366
|
+
queryLongestErrorFreeStreak() {
|
|
2367
|
+
const rows = this.db.prepare(
|
|
2368
|
+
"SELECT hook_type FROM events WHERE hook_type IN ('PostToolUse', 'PostToolUseFailure') ORDER BY timestamp ASC"
|
|
2369
|
+
).all();
|
|
2370
|
+
let longest = 0;
|
|
2371
|
+
let current = 0;
|
|
2372
|
+
for (const row of rows) {
|
|
2373
|
+
if (row.hook_type === "PostToolUse") {
|
|
2374
|
+
current++;
|
|
2375
|
+
longest = Math.max(longest, current);
|
|
2376
|
+
} else {
|
|
2377
|
+
current = 0;
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
return longest;
|
|
2381
|
+
}
|
|
2382
|
+
queryTotalCommits() {
|
|
2383
|
+
return this.queryScalar(
|
|
2384
|
+
"SELECT COUNT(*) as c FROM events WHERE tool_name = 'Bash' AND hook_type = 'PostToolUse' AND tool_input LIKE '%git commit%'"
|
|
2385
|
+
);
|
|
2386
|
+
}
|
|
2387
|
+
queryTotalPRs() {
|
|
2388
|
+
return this.queryScalar(
|
|
2389
|
+
"SELECT COUNT(*) as c FROM events WHERE tool_name = 'Bash' AND hook_type = 'PostToolUse' AND tool_input LIKE '%gh pr create%'"
|
|
2390
|
+
);
|
|
2391
|
+
}
|
|
2392
|
+
queryUniqueLanguages() {
|
|
2393
|
+
const rows = this.db.prepare(
|
|
2394
|
+
"SELECT DISTINCT json_extract(tool_input, '$.file_path') as fp FROM events WHERE tool_name IN ('Edit', 'Write', 'Read') AND hook_type = 'PostToolUse' AND tool_input IS NOT NULL"
|
|
2395
|
+
).all();
|
|
2396
|
+
const extensions = /* @__PURE__ */ new Set();
|
|
2397
|
+
for (const row of rows) {
|
|
2398
|
+
if (row.fp) {
|
|
2399
|
+
const match = row.fp.match(/\.([a-zA-Z0-9]+)$/);
|
|
2400
|
+
if (match) {
|
|
2401
|
+
extensions.add(match[1].toLowerCase());
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
return extensions.size;
|
|
2406
|
+
}
|
|
2407
|
+
queryConcurrentAgentUses() {
|
|
2408
|
+
return this.queryScalar(
|
|
2409
|
+
"SELECT COUNT(DISTINCT session_id) as c FROM events WHERE hook_type = 'SubagentStart'"
|
|
2410
|
+
);
|
|
2411
|
+
}
|
|
2412
|
+
// === Secret stat helpers ===
|
|
2413
|
+
queryDangerousCommandBlocked() {
|
|
2414
|
+
return this.queryScalar(
|
|
2415
|
+
"SELECT COUNT(*) as c FROM events WHERE hook_type = 'PreToolUse' AND tool_name = 'Bash' AND (tool_input LIKE '%rm -rf%' OR tool_input LIKE '%rm -r /%')"
|
|
2416
|
+
);
|
|
2417
|
+
}
|
|
2418
|
+
queryReturnAfterBreak() {
|
|
2419
|
+
const rows = this.db.prepare(
|
|
2420
|
+
"SELECT started_at FROM sessions ORDER BY started_at ASC"
|
|
2421
|
+
).all();
|
|
2422
|
+
if (rows.length < 2) return 0;
|
|
2423
|
+
for (let i = 1; i < rows.length; i++) {
|
|
2424
|
+
const prev = new Date(rows[i - 1].started_at).getTime();
|
|
2425
|
+
const curr = new Date(rows[i].started_at).getTime();
|
|
2426
|
+
const diffDays = (curr - prev) / (1e3 * 60 * 60 * 24);
|
|
2427
|
+
if (diffDays >= 7) return 1;
|
|
2428
|
+
}
|
|
2429
|
+
return 0;
|
|
2430
|
+
}
|
|
2431
|
+
queryThreeAmPrompt() {
|
|
2432
|
+
return this.queryScalar(
|
|
2433
|
+
"SELECT COUNT(*) as c FROM prompts WHERE CAST(strftime('%H', timestamp) AS INTEGER) = 3"
|
|
2434
|
+
) > 0 ? 1 : 0;
|
|
2435
|
+
}
|
|
2436
|
+
queryMidnightSpanSession() {
|
|
2437
|
+
const rows = this.db.prepare(
|
|
2438
|
+
"SELECT started_at, ended_at FROM sessions WHERE ended_at IS NOT NULL"
|
|
2439
|
+
).all();
|
|
2440
|
+
for (const row of rows) {
|
|
2441
|
+
const startDate = row.started_at.slice(0, 10);
|
|
2442
|
+
const endDate = row.ended_at.slice(0, 10);
|
|
2443
|
+
if (startDate !== endDate) return 1;
|
|
2444
|
+
}
|
|
2445
|
+
return 0;
|
|
2446
|
+
}
|
|
2447
|
+
queryNestedSubagent() {
|
|
2448
|
+
return this.queryScalar(
|
|
2449
|
+
"SELECT COUNT(*) as c FROM events WHERE hook_type = 'SubagentStart'"
|
|
2450
|
+
) > 0 ? 1 : 0;
|
|
2451
|
+
}
|
|
2452
|
+
queryHolidayActivity() {
|
|
2453
|
+
const holidays = this.queryScalar(
|
|
2454
|
+
"SELECT COUNT(*) as c FROM sessions WHERE strftime('%m-%d', started_at) IN ('12-25', '01-01', '07-04')"
|
|
2455
|
+
);
|
|
2456
|
+
return holidays > 0 ? 1 : 0;
|
|
2457
|
+
}
|
|
2458
|
+
querySpeedRunSession() {
|
|
2459
|
+
return this.queryScalar(
|
|
2460
|
+
"SELECT COUNT(*) as c FROM sessions WHERE duration_seconds IS NOT NULL AND duration_seconds <= 20 AND tool_count > 0"
|
|
2461
|
+
) > 0 ? 1 : 0;
|
|
2462
|
+
}
|
|
2463
|
+
queryAllToolsInSession() {
|
|
2464
|
+
const requiredTools = ["Bash", "Read", "Write", "Edit", "Grep", "Glob", "WebFetch"];
|
|
2465
|
+
const rows = this.db.prepare(
|
|
2466
|
+
"SELECT session_id, COUNT(DISTINCT tool_name) as cnt FROM events WHERE hook_type = 'PostToolUse' AND tool_name IN ('Bash', 'Read', 'Write', 'Edit', 'Grep', 'Glob', 'WebFetch') GROUP BY session_id"
|
|
2467
|
+
).all();
|
|
2468
|
+
for (const row of rows) {
|
|
2469
|
+
if (row.cnt >= requiredTools.length) return 1;
|
|
2470
|
+
}
|
|
2471
|
+
return 0;
|
|
2472
|
+
}
|
|
2473
|
+
// ===================================================================
|
|
2474
|
+
// NEW: Time & Patterns queries
|
|
2475
|
+
// ===================================================================
|
|
2476
|
+
queryWitchingHourPrompts() {
|
|
2477
|
+
return this.queryScalar(
|
|
2478
|
+
"SELECT COUNT(*) as c FROM prompts WHERE CAST(strftime('%H', timestamp) AS INTEGER) BETWEEN 2 AND 3"
|
|
2479
|
+
);
|
|
2480
|
+
}
|
|
2481
|
+
queryLunchBreakDays() {
|
|
2482
|
+
return this.queryScalar(
|
|
2483
|
+
"SELECT COUNT(DISTINCT strftime('%Y-%m-%d', started_at)) as c FROM sessions WHERE CAST(strftime('%H', started_at) AS INTEGER) = 12"
|
|
2484
|
+
);
|
|
2485
|
+
}
|
|
2486
|
+
queryMondaySessions() {
|
|
2487
|
+
return this.queryScalar(
|
|
2488
|
+
"SELECT COUNT(*) as c FROM sessions WHERE CAST(strftime('%w', started_at) AS INTEGER) = 1"
|
|
2489
|
+
);
|
|
2490
|
+
}
|
|
2491
|
+
queryFridayCommits() {
|
|
2492
|
+
return this.queryScalar(
|
|
2493
|
+
"SELECT COUNT(*) as c FROM events WHERE tool_name = 'Bash' AND hook_type = 'PostToolUse' AND tool_input LIKE '%git commit%' AND CAST(strftime('%w', timestamp) AS INTEGER) = 5"
|
|
2494
|
+
);
|
|
2495
|
+
}
|
|
2496
|
+
queryMaxUniqueHoursInDay() {
|
|
2497
|
+
return this.queryScalar(
|
|
2498
|
+
"SELECT COUNT(DISTINCT CAST(strftime('%H', timestamp) AS INTEGER)) as c FROM prompts GROUP BY strftime('%Y-%m-%d', timestamp) ORDER BY c DESC LIMIT 1"
|
|
2499
|
+
);
|
|
2500
|
+
}
|
|
2501
|
+
queryUniqueQuarters() {
|
|
2502
|
+
return this.queryScalar(
|
|
2503
|
+
"SELECT COUNT(DISTINCT (strftime('%Y', timestamp) || '-Q' || CASE WHEN CAST(strftime('%m', timestamp) AS INTEGER) BETWEEN 1 AND 3 THEN '1' WHEN CAST(strftime('%m', timestamp) AS INTEGER) BETWEEN 4 AND 6 THEN '2' WHEN CAST(strftime('%m', timestamp) AS INTEGER) BETWEEN 7 AND 9 THEN '3' ELSE '4' END)) as c FROM prompts"
|
|
2504
|
+
);
|
|
2505
|
+
}
|
|
2506
|
+
// ===================================================================
|
|
2507
|
+
// NEW: Session Behavior queries
|
|
2508
|
+
// ===================================================================
|
|
2509
|
+
queryExtendedSessionCount() {
|
|
2510
|
+
return this.queryScalar(
|
|
2511
|
+
"SELECT COUNT(*) as c FROM sessions WHERE duration_seconds IS NOT NULL AND duration_seconds > 3600 AND prompt_count >= 15"
|
|
2512
|
+
);
|
|
2513
|
+
}
|
|
2514
|
+
queryQuickDrawSessions() {
|
|
2515
|
+
return this.queryScalar(
|
|
2516
|
+
"SELECT COUNT(*) as c FROM sessions WHERE duration_seconds IS NOT NULL AND duration_seconds < 120 AND tool_count > 0"
|
|
2517
|
+
);
|
|
2518
|
+
}
|
|
2519
|
+
queryDiverseToolSessions() {
|
|
2520
|
+
return this.queryScalar(
|
|
2521
|
+
"SELECT COUNT(*) as c FROM (SELECT session_id FROM events WHERE hook_type = 'PostToolUse' AND tool_name IS NOT NULL GROUP BY session_id HAVING COUNT(DISTINCT tool_name) >= 5)"
|
|
2522
|
+
);
|
|
2523
|
+
}
|
|
2524
|
+
queryPermissionRequests() {
|
|
2525
|
+
return this.queryScalar(
|
|
2526
|
+
"SELECT COUNT(*) as c FROM events WHERE hook_type = 'PermissionRequest'"
|
|
2527
|
+
);
|
|
2528
|
+
}
|
|
2529
|
+
queryReturnerDays() {
|
|
2530
|
+
return this.queryScalar(
|
|
2531
|
+
"SELECT COUNT(*) as c FROM (SELECT strftime('%Y-%m-%d', started_at) as d, project FROM sessions WHERE project IS NOT NULL GROUP BY d, project HAVING COUNT(*) >= 5)"
|
|
2532
|
+
);
|
|
2533
|
+
}
|
|
2534
|
+
// ===================================================================
|
|
2535
|
+
// NEW: Prompt Patterns queries
|
|
2536
|
+
// ===================================================================
|
|
2537
|
+
queryShortPromptCount() {
|
|
2538
|
+
return this.queryScalar(
|
|
2539
|
+
"SELECT COUNT(*) as c FROM prompts WHERE word_count < 10"
|
|
2540
|
+
);
|
|
2541
|
+
}
|
|
2542
|
+
queryQuestionPromptCount() {
|
|
2543
|
+
return this.queryScalar(
|
|
2544
|
+
"SELECT COUNT(*) as c FROM prompts WHERE TRIM(content) LIKE '%?'"
|
|
2545
|
+
);
|
|
2546
|
+
}
|
|
2547
|
+
querySorryPromptCount() {
|
|
2548
|
+
return this.queryScalar(
|
|
2549
|
+
"SELECT COUNT(*) as c FROM prompts WHERE LOWER(content) LIKE '%sorry%'"
|
|
2550
|
+
);
|
|
2551
|
+
}
|
|
2552
|
+
queryCapsLockPromptCount() {
|
|
2553
|
+
return this.queryScalar(
|
|
2554
|
+
"SELECT COUNT(*) as c FROM prompts WHERE content = UPPER(content) AND char_count >= 10"
|
|
2555
|
+
);
|
|
2556
|
+
}
|
|
2557
|
+
queryEmojiPromptCount() {
|
|
2558
|
+
const rows = this.db.prepare(
|
|
2559
|
+
"SELECT content FROM prompts"
|
|
2560
|
+
).all();
|
|
2561
|
+
const emojiRegex = /[\u{1F300}-\u{1F9FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{FE00}-\u{FE0F}\u{1FA00}-\u{1FAFF}]/u;
|
|
2562
|
+
let count = 0;
|
|
2563
|
+
for (const row of rows) {
|
|
2564
|
+
if (emojiRegex.test(row.content)) {
|
|
2565
|
+
count++;
|
|
2566
|
+
}
|
|
2567
|
+
}
|
|
2568
|
+
return count;
|
|
2569
|
+
}
|
|
2570
|
+
queryCodeDumpPromptCount() {
|
|
2571
|
+
const rows = this.db.prepare(
|
|
2572
|
+
"SELECT content FROM prompts WHERE char_count > 200"
|
|
2573
|
+
).all();
|
|
2574
|
+
let count = 0;
|
|
2575
|
+
for (const row of rows) {
|
|
2576
|
+
const lineCount = row.content.split("\n").length;
|
|
2577
|
+
if (lineCount >= 50) count++;
|
|
2578
|
+
}
|
|
2579
|
+
return count;
|
|
2580
|
+
}
|
|
2581
|
+
// ===================================================================
|
|
2582
|
+
// NEW: Error & Recovery queries
|
|
2583
|
+
// ===================================================================
|
|
2584
|
+
queryRubberDuckCount() {
|
|
2585
|
+
const rows = this.db.prepare(
|
|
2586
|
+
"SELECT hook_type, tool_name FROM events WHERE hook_type IN ('PostToolUse', 'PostToolUseFailure') ORDER BY timestamp ASC"
|
|
2587
|
+
).all();
|
|
2588
|
+
let count = 0;
|
|
2589
|
+
for (let i = 1; i < rows.length; i++) {
|
|
2590
|
+
const prev = rows[i - 1];
|
|
2591
|
+
const curr = rows[i];
|
|
2592
|
+
if (prev.hook_type === "PostToolUseFailure" && curr.hook_type === "PostToolUse" && prev.tool_name === curr.tool_name && curr.tool_name !== "Edit") {
|
|
2593
|
+
count++;
|
|
2594
|
+
}
|
|
2595
|
+
}
|
|
2596
|
+
return count;
|
|
2597
|
+
}
|
|
2598
|
+
queryThirdTimeCharmCount() {
|
|
2599
|
+
const rows = this.db.prepare(
|
|
2600
|
+
"SELECT hook_type, tool_name FROM events WHERE hook_type IN ('PostToolUse', 'PostToolUseFailure') ORDER BY timestamp ASC"
|
|
2601
|
+
).all();
|
|
2602
|
+
let count = 0;
|
|
2603
|
+
let failStreak = 0;
|
|
2604
|
+
let failTool = null;
|
|
2605
|
+
for (const row of rows) {
|
|
2606
|
+
if (row.hook_type === "PostToolUseFailure") {
|
|
2607
|
+
if (row.tool_name === failTool) {
|
|
2608
|
+
failStreak++;
|
|
2609
|
+
} else {
|
|
2610
|
+
failStreak = 1;
|
|
2611
|
+
failTool = row.tool_name;
|
|
2612
|
+
}
|
|
2613
|
+
} else if (row.hook_type === "PostToolUse") {
|
|
2614
|
+
if (failStreak >= 2 && row.tool_name === failTool) {
|
|
2615
|
+
count++;
|
|
2616
|
+
}
|
|
2617
|
+
failStreak = 0;
|
|
2618
|
+
failTool = null;
|
|
2619
|
+
}
|
|
2620
|
+
}
|
|
2621
|
+
return count;
|
|
2622
|
+
}
|
|
2623
|
+
queryUndoEditCount() {
|
|
2624
|
+
const rows = this.db.prepare(
|
|
2625
|
+
"SELECT session_id, json_extract(tool_input, '$.file_path') as fp FROM events WHERE tool_name = 'Edit' AND hook_type = 'PostToolUse' AND tool_input IS NOT NULL ORDER BY timestamp ASC"
|
|
2626
|
+
).all();
|
|
2627
|
+
let count = 0;
|
|
2628
|
+
for (let i = 1; i < rows.length; i++) {
|
|
2629
|
+
if (rows[i].session_id === rows[i - 1].session_id && rows[i].fp === rows[i - 1].fp && rows[i].fp) {
|
|
2630
|
+
count++;
|
|
2631
|
+
}
|
|
2632
|
+
}
|
|
2633
|
+
return count;
|
|
2634
|
+
}
|
|
2635
|
+
queryCrashySessions() {
|
|
2636
|
+
return this.queryScalar(
|
|
2637
|
+
"SELECT COUNT(*) as c FROM sessions WHERE error_count >= 10"
|
|
2638
|
+
);
|
|
2639
|
+
}
|
|
2640
|
+
// ===================================================================
|
|
2641
|
+
// NEW: Tool Combos queries
|
|
2642
|
+
// ===================================================================
|
|
2643
|
+
queryReadEditRunCount() {
|
|
2644
|
+
const rows = this.db.prepare(
|
|
2645
|
+
"SELECT tool_name FROM events WHERE hook_type = 'PostToolUse' AND tool_name IN ('Read', 'Edit', 'Bash') ORDER BY timestamp ASC"
|
|
2646
|
+
).all();
|
|
2647
|
+
let count = 0;
|
|
2648
|
+
for (let i = 2; i < rows.length; i++) {
|
|
2649
|
+
if (rows[i - 2].tool_name === "Read" && rows[i - 1].tool_name === "Edit" && rows[i].tool_name === "Bash") {
|
|
2650
|
+
count++;
|
|
2651
|
+
}
|
|
2652
|
+
}
|
|
2653
|
+
return count;
|
|
2654
|
+
}
|
|
2655
|
+
queryMaxFilesCreatedInSession() {
|
|
2656
|
+
return this.queryScalar(
|
|
2657
|
+
"SELECT COUNT(*) as c FROM events WHERE tool_name = 'Write' AND hook_type = 'PostToolUse' GROUP BY session_id ORDER BY c DESC LIMIT 1"
|
|
2658
|
+
);
|
|
2659
|
+
}
|
|
2660
|
+
queryMaxSameFileEditsLifetime() {
|
|
2661
|
+
return this.queryScalar(
|
|
2662
|
+
"SELECT COUNT(*) as c FROM events WHERE tool_name = 'Edit' AND hook_type = 'PostToolUse' GROUP BY json_extract(tool_input, '$.file_path') ORDER BY c DESC LIMIT 1"
|
|
2663
|
+
);
|
|
2664
|
+
}
|
|
2665
|
+
querySearchThenEditCount() {
|
|
2666
|
+
const rows = this.db.prepare(
|
|
2667
|
+
"SELECT session_id, tool_name FROM events WHERE hook_type = 'PostToolUse' AND tool_name IN ('Grep', 'Glob', 'Edit') ORDER BY timestamp ASC"
|
|
2668
|
+
).all();
|
|
2669
|
+
let count = 0;
|
|
2670
|
+
for (let i = 1; i < rows.length; i++) {
|
|
2671
|
+
if (rows[i].tool_name === "Edit" && (rows[i - 1].tool_name === "Grep" || rows[i - 1].tool_name === "Glob") && rows[i].session_id === rows[i - 1].session_id) {
|
|
2672
|
+
count++;
|
|
2673
|
+
}
|
|
2674
|
+
}
|
|
2675
|
+
return count;
|
|
2676
|
+
}
|
|
2677
|
+
// ===================================================================
|
|
2678
|
+
// NEW: Project Dedication queries
|
|
2679
|
+
// ===================================================================
|
|
2680
|
+
queryMaxProjectSessions() {
|
|
2681
|
+
return this.queryScalar(
|
|
2682
|
+
"SELECT COUNT(*) as c FROM sessions WHERE project IS NOT NULL GROUP BY project ORDER BY c DESC LIMIT 1"
|
|
2683
|
+
);
|
|
2684
|
+
}
|
|
2685
|
+
queryMaxProjectsInDay() {
|
|
2686
|
+
return this.queryScalar(
|
|
2687
|
+
"SELECT COUNT(DISTINCT project) as c FROM sessions WHERE project IS NOT NULL GROUP BY strftime('%Y-%m-%d', started_at) ORDER BY c DESC LIMIT 1"
|
|
2688
|
+
);
|
|
2689
|
+
}
|
|
2690
|
+
queryFinishedProjects() {
|
|
2691
|
+
const projectRows = this.db.prepare(
|
|
2692
|
+
"SELECT DISTINCT project FROM events WHERE tool_name = 'Bash' AND hook_type = 'PostToolUse' AND tool_input LIKE '%git commit%' AND project IS NOT NULL"
|
|
2693
|
+
).all();
|
|
2694
|
+
let count = 0;
|
|
2695
|
+
for (const pr of projectRows) {
|
|
2696
|
+
const lastSession = this.db.prepare(
|
|
2697
|
+
"SELECT MAX(started_at) as last FROM sessions WHERE project = ?"
|
|
2698
|
+
).get(pr.project);
|
|
2699
|
+
if (lastSession?.last) {
|
|
2700
|
+
const daysSince = (Date.now() - new Date(lastSession.last).getTime()) / (1e3 * 60 * 60 * 24);
|
|
2701
|
+
if (daysSince >= 7) count++;
|
|
2702
|
+
}
|
|
2703
|
+
}
|
|
2704
|
+
return count;
|
|
2705
|
+
}
|
|
2706
|
+
queryLegacyReturns() {
|
|
2707
|
+
const rows = this.db.prepare(
|
|
2708
|
+
"SELECT project, started_at FROM sessions WHERE project IS NOT NULL ORDER BY project, started_at ASC"
|
|
2709
|
+
).all();
|
|
2710
|
+
let count = 0;
|
|
2711
|
+
for (let i = 1; i < rows.length; i++) {
|
|
2712
|
+
if (rows[i].project === rows[i - 1].project) {
|
|
2713
|
+
const prev = new Date(rows[i - 1].started_at).getTime();
|
|
2714
|
+
const curr = new Date(rows[i].started_at).getTime();
|
|
2715
|
+
const diffDays = (curr - prev) / (1e3 * 60 * 60 * 24);
|
|
2716
|
+
if (diffDays >= 30) count++;
|
|
2717
|
+
}
|
|
2718
|
+
}
|
|
2719
|
+
return count;
|
|
2720
|
+
}
|
|
2721
|
+
// ===================================================================
|
|
2722
|
+
// NEW: Multi-Agent queries
|
|
2723
|
+
// ===================================================================
|
|
2724
|
+
queryMaxConcurrentSubagents() {
|
|
2725
|
+
const rows = this.db.prepare(
|
|
2726
|
+
"SELECT hook_type, tool_input FROM events WHERE hook_type IN ('SubagentStart', 'SubagentStop') ORDER BY timestamp ASC"
|
|
2727
|
+
).all();
|
|
2728
|
+
let current = 0;
|
|
2729
|
+
let max = 0;
|
|
2730
|
+
for (const row of rows) {
|
|
2731
|
+
if (row.hook_type === "SubagentStart") {
|
|
2732
|
+
current++;
|
|
2733
|
+
max = Math.max(max, current);
|
|
2734
|
+
} else {
|
|
2735
|
+
current = Math.max(0, current - 1);
|
|
2736
|
+
}
|
|
2737
|
+
}
|
|
2738
|
+
return max;
|
|
2739
|
+
}
|
|
2740
|
+
queryQuickSubagentStops() {
|
|
2741
|
+
const starts = this.db.prepare(
|
|
2742
|
+
"SELECT tool_input, timestamp FROM events WHERE hook_type = 'SubagentStart'"
|
|
2743
|
+
).all();
|
|
2744
|
+
const stops = this.db.prepare(
|
|
2745
|
+
"SELECT tool_input, timestamp FROM events WHERE hook_type = 'SubagentStop'"
|
|
2746
|
+
).all();
|
|
2747
|
+
let count = 0;
|
|
2748
|
+
for (const start of starts) {
|
|
2749
|
+
if (!start.tool_input) continue;
|
|
2750
|
+
let agentId = null;
|
|
2751
|
+
try {
|
|
2752
|
+
const parsed = JSON.parse(start.tool_input);
|
|
2753
|
+
agentId = parsed.agent_id ?? null;
|
|
2754
|
+
} catch {
|
|
2755
|
+
continue;
|
|
2756
|
+
}
|
|
2757
|
+
if (!agentId) continue;
|
|
2758
|
+
for (const stop of stops) {
|
|
2759
|
+
if (!stop.tool_input) continue;
|
|
2760
|
+
try {
|
|
2761
|
+
const parsed = JSON.parse(stop.tool_input);
|
|
2762
|
+
if (parsed.agent_id === agentId) {
|
|
2763
|
+
const startTime = new Date(start.timestamp).getTime();
|
|
2764
|
+
const stopTime = new Date(stop.timestamp).getTime();
|
|
2765
|
+
if (stopTime - startTime < 3e4) count++;
|
|
2766
|
+
break;
|
|
2767
|
+
}
|
|
2768
|
+
} catch {
|
|
2769
|
+
continue;
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
}
|
|
2773
|
+
return count;
|
|
2774
|
+
}
|
|
2775
|
+
queryMaxSubagentsInSession() {
|
|
2776
|
+
return this.queryScalar(
|
|
2777
|
+
"SELECT COUNT(*) as c FROM events WHERE hook_type = 'SubagentStart' GROUP BY session_id ORDER BY c DESC LIMIT 1"
|
|
2778
|
+
);
|
|
2779
|
+
}
|
|
2780
|
+
// ===================================================================
|
|
2781
|
+
// NEW: Humor & Meta queries
|
|
2782
|
+
// ===================================================================
|
|
2783
|
+
queryDejaVuCount() {
|
|
2784
|
+
const rows = this.db.prepare(
|
|
2785
|
+
"SELECT LOWER(TRIM(content)) as content, timestamp FROM prompts ORDER BY timestamp ASC"
|
|
2786
|
+
).all();
|
|
2787
|
+
let count = 0;
|
|
2788
|
+
for (let i = 1; i < rows.length; i++) {
|
|
2789
|
+
if (rows[i].content === rows[i - 1].content) {
|
|
2790
|
+
const prev = new Date(rows[i - 1].timestamp).getTime();
|
|
2791
|
+
const curr = new Date(rows[i].timestamp).getTime();
|
|
2792
|
+
if (curr - prev < 3e5) count++;
|
|
2793
|
+
}
|
|
2794
|
+
}
|
|
2795
|
+
return count;
|
|
2796
|
+
}
|
|
2797
|
+
queryTrustIssueCount() {
|
|
2798
|
+
const rows = this.db.prepare(
|
|
2799
|
+
"SELECT tool_name, json_extract(tool_input, '$.file_path') as fp FROM events WHERE hook_type = 'PostToolUse' AND tool_name IN ('Write', 'Read') AND tool_input IS NOT NULL ORDER BY timestamp ASC"
|
|
2800
|
+
).all();
|
|
2801
|
+
let count = 0;
|
|
2802
|
+
for (let i = 1; i < rows.length; i++) {
|
|
2803
|
+
if (rows[i].tool_name === "Read" && rows[i - 1].tool_name === "Write" && rows[i].fp === rows[i - 1].fp && rows[i].fp) {
|
|
2804
|
+
count++;
|
|
2805
|
+
}
|
|
2806
|
+
}
|
|
2807
|
+
return count;
|
|
2808
|
+
}
|
|
2809
|
+
queryBackseatDriverCount() {
|
|
2810
|
+
const rows = this.db.prepare(
|
|
2811
|
+
"SELECT content FROM prompts WHERE char_count > 20"
|
|
2812
|
+
).all();
|
|
2813
|
+
let count = 0;
|
|
2814
|
+
const stepPattern = /(?:^|\n)\s*\d+\.\s/;
|
|
2815
|
+
for (const row of rows) {
|
|
2816
|
+
const matches = row.content.match(/(?:^|\n)\s*\d+\.\s/g);
|
|
2817
|
+
if (matches && matches.length >= 3) count++;
|
|
2818
|
+
}
|
|
2819
|
+
return count;
|
|
2820
|
+
}
|
|
2821
|
+
queryNegotiatorCount() {
|
|
2822
|
+
return this.queryScalar(
|
|
2823
|
+
"SELECT COUNT(*) as c FROM prompts WHERE LOWER(content) LIKE '%try again%' OR LOWER(content) LIKE '%one more time%'"
|
|
2824
|
+
);
|
|
2825
|
+
}
|
|
2826
|
+
queryMaxConsecutivePermissions() {
|
|
2827
|
+
const rows = this.db.prepare(
|
|
2828
|
+
"SELECT hook_type FROM events WHERE hook_type IN ('PermissionRequest', 'PostToolUse', 'UserPromptSubmit') ORDER BY timestamp ASC"
|
|
2829
|
+
).all();
|
|
2830
|
+
let maxStreak = 0;
|
|
2831
|
+
let current = 0;
|
|
2832
|
+
for (const row of rows) {
|
|
2833
|
+
if (row.hook_type === "PermissionRequest") {
|
|
2834
|
+
current++;
|
|
2835
|
+
maxStreak = Math.max(maxStreak, current);
|
|
2836
|
+
} else {
|
|
2837
|
+
current = 0;
|
|
2838
|
+
}
|
|
2839
|
+
}
|
|
2840
|
+
return maxStreak;
|
|
2841
|
+
}
|
|
2842
|
+
queryBashRetrySuccessCount() {
|
|
2843
|
+
const rows = this.db.prepare(
|
|
2844
|
+
"SELECT hook_type FROM events WHERE tool_name = 'Bash' AND hook_type IN ('PostToolUse', 'PostToolUseFailure') ORDER BY timestamp ASC"
|
|
2845
|
+
).all();
|
|
2846
|
+
let count = 0;
|
|
2847
|
+
for (let i = 1; i < rows.length; i++) {
|
|
2848
|
+
if (rows[i - 1].hook_type === "PostToolUseFailure" && rows[i].hook_type === "PostToolUse") {
|
|
2849
|
+
count++;
|
|
2850
|
+
}
|
|
2851
|
+
}
|
|
2852
|
+
return count;
|
|
2853
|
+
}
|
|
2854
|
+
// ===================================================================
|
|
2855
|
+
// NEW: Secret queries
|
|
2856
|
+
// ===================================================================
|
|
2857
|
+
queryEasterEggActivity() {
|
|
2858
|
+
const count = this.queryScalar(
|
|
2859
|
+
"SELECT COUNT(*) as c FROM sessions WHERE strftime('%m-%d', started_at) IN ('02-14', '11-28', '11-27', '11-26', '11-25', '11-24', '11-23', '11-22') OR (strftime('%m', started_at) = '04' AND CAST(strftime('%d', started_at) AS INTEGER) BETWEEN 1 AND 25)"
|
|
2860
|
+
);
|
|
2861
|
+
return count > 0 ? 1 : 0;
|
|
2862
|
+
}
|
|
2863
|
+
queryFullMoonSession() {
|
|
2864
|
+
const knownNewMoon = (/* @__PURE__ */ new Date("2024-01-11T11:57:00Z")).getTime();
|
|
2865
|
+
const lunarCycleMs = 29.53059 * 24 * 60 * 60 * 1e3;
|
|
2866
|
+
const fullMoonOffsetMs = 14.765 * 24 * 60 * 60 * 1e3;
|
|
2867
|
+
const oneDayMs = 24 * 60 * 60 * 1e3;
|
|
2868
|
+
const rows = this.db.prepare(
|
|
2869
|
+
"SELECT started_at FROM sessions"
|
|
2870
|
+
).all();
|
|
2871
|
+
for (const row of rows) {
|
|
2872
|
+
const sessionTime = new Date(row.started_at).getTime();
|
|
2873
|
+
const timeSinceFullMoon = ((sessionTime - knownNewMoon - fullMoonOffsetMs) % lunarCycleMs + lunarCycleMs) % lunarCycleMs;
|
|
2874
|
+
if (timeSinceFullMoon < oneDayMs || timeSinceFullMoon > lunarCycleMs - oneDayMs) {
|
|
2875
|
+
return 1;
|
|
2876
|
+
}
|
|
2877
|
+
}
|
|
2878
|
+
return 0;
|
|
2879
|
+
}
|
|
2880
|
+
queryBirthdaySession() {
|
|
2881
|
+
const first = this.db.prepare(
|
|
2882
|
+
"SELECT started_at FROM sessions ORDER BY started_at ASC LIMIT 1"
|
|
2883
|
+
).get();
|
|
2884
|
+
if (!first) return 0;
|
|
2885
|
+
const installMonthDay = first.started_at.slice(5, 10);
|
|
2886
|
+
const installYear = first.started_at.slice(0, 4);
|
|
2887
|
+
const anniversarySession = this.queryScalar(
|
|
2888
|
+
"SELECT COUNT(*) as c FROM sessions WHERE strftime('%m-%d', started_at) = ? AND strftime('%Y', started_at) != ?",
|
|
2889
|
+
installMonthDay,
|
|
2890
|
+
installYear
|
|
2891
|
+
);
|
|
2892
|
+
return anniversarySession > 0 ? 1 : 0;
|
|
2893
|
+
}
|
|
2894
|
+
queryGhostSessions() {
|
|
2895
|
+
return this.queryScalar(
|
|
2896
|
+
"SELECT COUNT(*) as c FROM sessions WHERE tool_count = 0 AND ended_at IS NOT NULL"
|
|
2897
|
+
) > 0 ? 1 : 0;
|
|
2898
|
+
}
|
|
2899
|
+
queryBullseyeSessions() {
|
|
2900
|
+
return this.queryScalar(
|
|
2901
|
+
"SELECT COUNT(*) as c FROM sessions WHERE prompt_count = 1 AND error_count = 0 AND tool_count > 0"
|
|
2902
|
+
) > 0 ? 1 : 0;
|
|
2903
|
+
}
|
|
2904
|
+
// === Token Usage queries ===
|
|
2905
|
+
queryHeavyTokenSessions() {
|
|
2906
|
+
return this.queryScalar(
|
|
2907
|
+
"SELECT COUNT(*) as c FROM sessions WHERE (COALESCE(input_tokens, 0) + COALESCE(output_tokens, 0) + COALESCE(cache_creation_input_tokens, 0) + COALESCE(cache_read_input_tokens, 0)) >= 1000000"
|
|
2908
|
+
);
|
|
2909
|
+
}
|
|
2910
|
+
queryLightTokenSessions() {
|
|
2911
|
+
return this.queryScalar(
|
|
2912
|
+
"SELECT COUNT(*) as c FROM sessions WHERE (COALESCE(input_tokens, 0) + COALESCE(output_tokens, 0) + COALESCE(cache_creation_input_tokens, 0) + COALESCE(cache_read_input_tokens, 0)) > 0 AND (COALESCE(input_tokens, 0) + COALESCE(output_tokens, 0) + COALESCE(cache_creation_input_tokens, 0) + COALESCE(cache_read_input_tokens, 0)) < 50000 AND tool_count > 0"
|
|
2913
|
+
);
|
|
2914
|
+
}
|
|
2915
|
+
queryMaxOutputInSession() {
|
|
2916
|
+
return this.queryScalar(
|
|
2917
|
+
"SELECT COALESCE(MAX(output_tokens), 0) as c FROM sessions"
|
|
2918
|
+
);
|
|
2919
|
+
}
|
|
2920
|
+
queryHasTenMillionSession() {
|
|
2921
|
+
return this.queryScalar(
|
|
2922
|
+
"SELECT COUNT(*) as c FROM sessions WHERE (COALESCE(input_tokens, 0) + COALESCE(output_tokens, 0) + COALESCE(cache_creation_input_tokens, 0) + COALESCE(cache_read_input_tokens, 0)) >= 10000000"
|
|
2923
|
+
) > 0 ? 1 : 0;
|
|
2924
|
+
}
|
|
2925
|
+
};
|
|
2926
|
+
|
|
2927
|
+
export {
|
|
2928
|
+
BADGE_DEFINITIONS,
|
|
2929
|
+
RANK_TIER_BRACKETS,
|
|
2930
|
+
xpForRank,
|
|
2931
|
+
rankTierForRank,
|
|
2932
|
+
TIER_XP,
|
|
2933
|
+
ACTIVITY_MULTIPLIERS,
|
|
2934
|
+
WEEKLY_CHALLENGES,
|
|
2935
|
+
DATA_DIR,
|
|
2936
|
+
DB_FILENAME,
|
|
2937
|
+
DEFAULT_PORT,
|
|
2938
|
+
BashStatsDB,
|
|
2939
|
+
install,
|
|
2940
|
+
uninstall,
|
|
2941
|
+
isInstalled,
|
|
2942
|
+
isGeminiAvailable,
|
|
2943
|
+
installGemini,
|
|
2944
|
+
uninstallGemini,
|
|
2945
|
+
installCopilot,
|
|
2946
|
+
uninstallCopilot,
|
|
2947
|
+
isCopilotAvailable,
|
|
2948
|
+
isOpenCodeAvailable,
|
|
2949
|
+
installOpenCode,
|
|
2950
|
+
uninstallOpenCode,
|
|
2951
|
+
BashStatsWriter,
|
|
2952
|
+
detectAgent,
|
|
2953
|
+
parseHookEvent,
|
|
2954
|
+
getDbPath,
|
|
2955
|
+
handleHookEvent,
|
|
2956
|
+
StatsEngine,
|
|
2957
|
+
AGENT_DISPLAY_NAMES,
|
|
2958
|
+
TIER_NAMES,
|
|
2959
|
+
AchievementEngine
|
|
2960
|
+
};
|
|
2961
|
+
//# sourceMappingURL=chunk-YAJO5WNW.js.map
|