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
|
@@ -85,6 +85,21 @@ CREATE TABLE IF NOT EXISTS metadata (
|
|
|
85
85
|
value TEXT
|
|
86
86
|
);
|
|
87
87
|
|
|
88
|
+
CREATE TABLE IF NOT EXISTS weekly_goals (
|
|
89
|
+
week_start TEXT NOT NULL,
|
|
90
|
+
challenge_id TEXT NOT NULL,
|
|
91
|
+
completed INTEGER DEFAULT 0,
|
|
92
|
+
xp_reward INTEGER NOT NULL,
|
|
93
|
+
PRIMARY KEY (week_start, challenge_id)
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
CREATE TABLE IF NOT EXISTS weekly_xp (
|
|
97
|
+
week_start TEXT PRIMARY KEY,
|
|
98
|
+
base_xp INTEGER DEFAULT 0,
|
|
99
|
+
multiplier REAL DEFAULT 1.0,
|
|
100
|
+
bonus_xp INTEGER DEFAULT 0
|
|
101
|
+
);
|
|
102
|
+
|
|
88
103
|
CREATE INDEX IF NOT EXISTS idx_events_session ON events(session_id);
|
|
89
104
|
CREATE INDEX IF NOT EXISTS idx_events_hook_type ON events(hook_type);
|
|
90
105
|
CREATE INDEX IF NOT EXISTS idx_events_tool_name ON events(tool_name);
|
|
@@ -290,6 +305,28 @@ var BashStatsDB = class {
|
|
|
290
305
|
const row = this.db.prepare("SELECT value FROM metadata WHERE key = ?").get(key);
|
|
291
306
|
return row?.value ?? null;
|
|
292
307
|
}
|
|
308
|
+
// === Weekly Goals ===
|
|
309
|
+
insertWeeklyGoal(weekStart, challengeId, xpReward) {
|
|
310
|
+
this.db.prepare(`
|
|
311
|
+
INSERT OR IGNORE INTO weekly_goals (week_start, challenge_id, xp_reward) VALUES (?, ?, ?)
|
|
312
|
+
`).run(weekStart, challengeId, xpReward);
|
|
313
|
+
}
|
|
314
|
+
completeWeeklyGoal(weekStart, challengeId) {
|
|
315
|
+
this.db.prepare("UPDATE weekly_goals SET completed = 1 WHERE week_start = ? AND challenge_id = ?").run(weekStart, challengeId);
|
|
316
|
+
}
|
|
317
|
+
getWeeklyGoals(weekStart) {
|
|
318
|
+
return this.db.prepare("SELECT * FROM weekly_goals WHERE week_start = ?").all(weekStart);
|
|
319
|
+
}
|
|
320
|
+
// === Weekly XP ===
|
|
321
|
+
upsertWeeklyXP(weekStart, baseXP, multiplier, bonusXP) {
|
|
322
|
+
this.db.prepare(`
|
|
323
|
+
INSERT INTO weekly_xp (week_start, base_xp, multiplier, bonus_xp) VALUES (?, ?, ?, ?)
|
|
324
|
+
ON CONFLICT(week_start) DO UPDATE SET base_xp = ?, multiplier = ?, bonus_xp = ?
|
|
325
|
+
`).run(weekStart, baseXP, multiplier, bonusXP, baseXP, multiplier, bonusXP);
|
|
326
|
+
}
|
|
327
|
+
getWeeklyXP(weekStart) {
|
|
328
|
+
return this.db.prepare("SELECT * FROM weekly_xp WHERE week_start = ?").get(weekStart);
|
|
329
|
+
}
|
|
293
330
|
// === Raw DB access for stats engine ===
|
|
294
331
|
prepare(sql) {
|
|
295
332
|
return this.db.prepare(sql);
|
|
@@ -494,27 +531,35 @@ async function extractTokenUsage(transcriptPath) {
|
|
|
494
531
|
if (!fs.existsSync(transcriptPath)) return null;
|
|
495
532
|
const stream = fs.createReadStream(transcriptPath, { encoding: "utf-8" });
|
|
496
533
|
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
|
|
497
|
-
|
|
498
|
-
let outputTokens = 0;
|
|
499
|
-
let cacheCreation = 0;
|
|
500
|
-
let cacheRead = 0;
|
|
501
|
-
let found = false;
|
|
534
|
+
const seenMessages = /* @__PURE__ */ new Map();
|
|
502
535
|
for await (const line of rl) {
|
|
503
536
|
if (!line.trim()) continue;
|
|
504
537
|
try {
|
|
505
538
|
const entry = JSON.parse(line);
|
|
506
539
|
const usage = entry.usage ?? entry.response?.usage ?? entry.message?.usage;
|
|
507
|
-
if (usage && typeof usage === "object") {
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
540
|
+
if (usage && typeof usage === "object" && "input_tokens" in usage) {
|
|
541
|
+
const msgId = entry.message?.id ?? entry.id ?? `_line_${seenMessages.size}`;
|
|
542
|
+
seenMessages.set(msgId, {
|
|
543
|
+
input_tokens: usage.input_tokens ?? 0,
|
|
544
|
+
output_tokens: usage.output_tokens ?? 0,
|
|
545
|
+
cache_creation_input_tokens: usage.cache_creation_input_tokens ?? 0,
|
|
546
|
+
cache_read_input_tokens: usage.cache_read_input_tokens ?? 0
|
|
547
|
+
});
|
|
513
548
|
}
|
|
514
549
|
} catch {
|
|
515
550
|
}
|
|
516
551
|
}
|
|
517
|
-
if (
|
|
552
|
+
if (seenMessages.size === 0) return null;
|
|
553
|
+
let inputTokens = 0;
|
|
554
|
+
let outputTokens = 0;
|
|
555
|
+
let cacheCreation = 0;
|
|
556
|
+
let cacheRead = 0;
|
|
557
|
+
for (const u of seenMessages.values()) {
|
|
558
|
+
inputTokens += u.input_tokens;
|
|
559
|
+
outputTokens += u.output_tokens;
|
|
560
|
+
cacheCreation += u.cache_creation_input_tokens;
|
|
561
|
+
cacheRead += u.cache_read_input_tokens;
|
|
562
|
+
}
|
|
518
563
|
return {
|
|
519
564
|
input_tokens: inputTokens,
|
|
520
565
|
output_tokens: outputTokens,
|
|
@@ -526,9 +571,145 @@ async function extractTokenUsage(transcriptPath) {
|
|
|
526
571
|
}
|
|
527
572
|
}
|
|
528
573
|
|
|
574
|
+
// src/hooks/normalizers/gemini.ts
|
|
575
|
+
function normalizeGeminiEvent(geminiEvent, raw) {
|
|
576
|
+
switch (geminiEvent) {
|
|
577
|
+
case "SessionStart":
|
|
578
|
+
return { hookType: "SessionStart", payload: raw };
|
|
579
|
+
case "SessionEnd":
|
|
580
|
+
return {
|
|
581
|
+
hookType: "Stop",
|
|
582
|
+
payload: { ...raw, stop_hook_active: false }
|
|
583
|
+
};
|
|
584
|
+
case "BeforeAgent":
|
|
585
|
+
return { hookType: "UserPromptSubmit", payload: raw };
|
|
586
|
+
case "BeforeTool":
|
|
587
|
+
return { hookType: "PreToolUse", payload: raw };
|
|
588
|
+
case "AfterTool":
|
|
589
|
+
return { hookType: "PostToolUse", payload: raw };
|
|
590
|
+
case "AfterModel": {
|
|
591
|
+
const usageMetadata = raw.llm_response?.usageMetadata;
|
|
592
|
+
const totalTokenCount = typeof usageMetadata?.totalTokenCount === "number" ? usageMetadata.totalTokenCount : void 0;
|
|
593
|
+
return {
|
|
594
|
+
hookType: "AfterModel",
|
|
595
|
+
payload: raw,
|
|
596
|
+
...totalTokenCount !== void 0 ? { tokenData: { totalTokenCount } } : {}
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
case "PreCompress":
|
|
600
|
+
return { hookType: "PreCompact", payload: raw };
|
|
601
|
+
case "Notification":
|
|
602
|
+
return { hookType: "Notification", payload: raw };
|
|
603
|
+
default:
|
|
604
|
+
return null;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// src/hooks/normalizers/copilot.ts
|
|
609
|
+
function parseToolArgs(toolArgs) {
|
|
610
|
+
if (!toolArgs || typeof toolArgs !== "string") return {};
|
|
611
|
+
try {
|
|
612
|
+
return JSON.parse(toolArgs);
|
|
613
|
+
} catch {
|
|
614
|
+
return {};
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
function deriveSessionId() {
|
|
618
|
+
const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
619
|
+
const ppid = process.ppid ?? process.pid;
|
|
620
|
+
return `copilot-${ppid}-${date}`;
|
|
621
|
+
}
|
|
622
|
+
function mapSource(source) {
|
|
623
|
+
if (source === "resume") return "resume";
|
|
624
|
+
return "startup";
|
|
625
|
+
}
|
|
626
|
+
function isToolFailure(toolResult) {
|
|
627
|
+
if (!toolResult) return false;
|
|
628
|
+
const resultType = toolResult.resultType;
|
|
629
|
+
return resultType === "failure" || resultType === "denied";
|
|
630
|
+
}
|
|
631
|
+
function normalizeCopilotEvent(copilotEvent, raw) {
|
|
632
|
+
const sessionId = deriveSessionId();
|
|
633
|
+
switch (copilotEvent) {
|
|
634
|
+
case "sessionStart": {
|
|
635
|
+
return {
|
|
636
|
+
hookType: "SessionStart",
|
|
637
|
+
payload: {
|
|
638
|
+
session_id: sessionId,
|
|
639
|
+
source: mapSource(raw.source),
|
|
640
|
+
...raw.model !== void 0 ? { model: raw.model } : {}
|
|
641
|
+
}
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
case "sessionEnd": {
|
|
645
|
+
return {
|
|
646
|
+
hookType: "Stop",
|
|
647
|
+
payload: {
|
|
648
|
+
session_id: sessionId,
|
|
649
|
+
...raw,
|
|
650
|
+
stop_hook_active: false
|
|
651
|
+
}
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
case "userPromptSubmitted": {
|
|
655
|
+
return {
|
|
656
|
+
hookType: "UserPromptSubmit",
|
|
657
|
+
payload: {
|
|
658
|
+
session_id: sessionId,
|
|
659
|
+
prompt: raw.prompt
|
|
660
|
+
}
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
case "preToolUse": {
|
|
664
|
+
return {
|
|
665
|
+
hookType: "PreToolUse",
|
|
666
|
+
payload: {
|
|
667
|
+
session_id: sessionId,
|
|
668
|
+
tool_name: raw.toolName,
|
|
669
|
+
tool_input: parseToolArgs(raw.toolArgs)
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
case "postToolUse": {
|
|
674
|
+
const toolResult = raw.toolResult ?? {};
|
|
675
|
+
const failed = isToolFailure(
|
|
676
|
+
raw.toolResult
|
|
677
|
+
);
|
|
678
|
+
return {
|
|
679
|
+
hookType: failed ? "PostToolUseFailure" : "PostToolUse",
|
|
680
|
+
payload: {
|
|
681
|
+
session_id: sessionId,
|
|
682
|
+
tool_name: raw.toolName,
|
|
683
|
+
tool_input: parseToolArgs(raw.toolArgs),
|
|
684
|
+
tool_response: toolResult,
|
|
685
|
+
exit_code: failed ? 1 : 0
|
|
686
|
+
}
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
case "errorOccurred": {
|
|
690
|
+
const error = raw.error ?? {};
|
|
691
|
+
return {
|
|
692
|
+
hookType: "PostToolUseFailure",
|
|
693
|
+
payload: {
|
|
694
|
+
session_id: sessionId,
|
|
695
|
+
tool_name: "_error",
|
|
696
|
+
tool_input: {},
|
|
697
|
+
tool_response: {
|
|
698
|
+
error_message: error.message ?? "",
|
|
699
|
+
error_name: error.name ?? ""
|
|
700
|
+
},
|
|
701
|
+
exit_code: 1
|
|
702
|
+
}
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
default:
|
|
706
|
+
return null;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
529
710
|
// src/hooks/handler.ts
|
|
530
711
|
function detectAgent() {
|
|
531
|
-
if (process.env.
|
|
712
|
+
if (process.env.GEMINI_SESSION_ID || process.env.GEMINI_PROJECT_DIR || process.env.GEMINI_CLI) return "gemini-cli";
|
|
532
713
|
if (process.env.GITHUB_COPILOT_CLI) return "copilot-cli";
|
|
533
714
|
if (process.env.OPENCODE) return "opencode";
|
|
534
715
|
return "claude-code";
|
|
@@ -572,73 +753,115 @@ async function handleHookEvent(hookType) {
|
|
|
572
753
|
const db = new BashStatsDB(dbPath);
|
|
573
754
|
const writer = new BashStatsWriter(db);
|
|
574
755
|
try {
|
|
575
|
-
const
|
|
576
|
-
|
|
577
|
-
|
|
756
|
+
const agent = detectAgent();
|
|
757
|
+
let effectiveHookType = hookType;
|
|
758
|
+
let payload = event;
|
|
759
|
+
if (agent === "gemini-cli") {
|
|
760
|
+
const normalized = normalizeGeminiEvent(hookType, event);
|
|
761
|
+
if (!normalized) return;
|
|
762
|
+
if (normalized.hookType === "AfterModel") {
|
|
763
|
+
if (normalized.tokenData) {
|
|
764
|
+
const sessionId2 = event.session_id ?? "";
|
|
765
|
+
const metaKey = `gemini_tokens_${sessionId2}`;
|
|
766
|
+
const existing = db.getMetadata(metaKey);
|
|
767
|
+
const prev = existing ? parseInt(existing, 10) : 0;
|
|
768
|
+
db.setMetadata(metaKey, String(prev + normalized.tokenData.totalTokenCount));
|
|
769
|
+
}
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
effectiveHookType = normalized.hookType;
|
|
773
|
+
payload = normalized.payload;
|
|
774
|
+
} else if (agent === "copilot-cli") {
|
|
775
|
+
const normalized = normalizeCopilotEvent(hookType, event);
|
|
776
|
+
if (!normalized) return;
|
|
777
|
+
effectiveHookType = normalized.hookType;
|
|
778
|
+
payload = normalized.payload;
|
|
779
|
+
}
|
|
780
|
+
const sessionId = payload.session_id ?? "";
|
|
781
|
+
const cwd = payload.cwd ?? "";
|
|
782
|
+
switch (effectiveHookType) {
|
|
578
783
|
case "SessionStart": {
|
|
579
|
-
const source =
|
|
580
|
-
const agent = detectAgent();
|
|
784
|
+
const source = payload.source ?? "startup";
|
|
581
785
|
writer.recordSessionStart(sessionId, cwd, source, agent);
|
|
582
786
|
break;
|
|
583
787
|
}
|
|
584
788
|
case "UserPromptSubmit": {
|
|
585
|
-
const prompt =
|
|
789
|
+
const prompt = payload.prompt ?? "";
|
|
586
790
|
writer.recordPrompt(sessionId, prompt);
|
|
587
791
|
break;
|
|
588
792
|
}
|
|
589
793
|
case "PreToolUse": {
|
|
590
|
-
const toolName =
|
|
591
|
-
const toolInput =
|
|
794
|
+
const toolName = payload.tool_name ?? "";
|
|
795
|
+
const toolInput = payload.tool_input ?? {};
|
|
592
796
|
writer.recordToolUse(sessionId, "PreToolUse", toolName, toolInput, {}, 0, cwd);
|
|
593
797
|
break;
|
|
594
798
|
}
|
|
595
799
|
case "PostToolUse": {
|
|
596
|
-
const toolName =
|
|
597
|
-
const toolInput =
|
|
598
|
-
const toolResponse =
|
|
599
|
-
const exitCode =
|
|
800
|
+
const toolName = payload.tool_name ?? "";
|
|
801
|
+
const toolInput = payload.tool_input ?? {};
|
|
802
|
+
const toolResponse = payload.tool_response ?? {};
|
|
803
|
+
const exitCode = payload.exit_code ?? 0;
|
|
600
804
|
writer.recordToolUse(sessionId, "PostToolUse", toolName, toolInput, toolResponse, exitCode, cwd);
|
|
601
805
|
break;
|
|
602
806
|
}
|
|
603
807
|
case "PostToolUseFailure": {
|
|
604
|
-
const toolName =
|
|
605
|
-
const toolInput =
|
|
606
|
-
const toolResponse =
|
|
808
|
+
const toolName = payload.tool_name ?? "";
|
|
809
|
+
const toolInput = payload.tool_input ?? {};
|
|
810
|
+
const toolResponse = payload.tool_response ?? {};
|
|
607
811
|
writer.recordToolUse(sessionId, "PostToolUseFailure", toolName, toolInput, toolResponse, 1, cwd);
|
|
608
812
|
break;
|
|
609
813
|
}
|
|
610
814
|
case "Stop": {
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
815
|
+
let tokens = null;
|
|
816
|
+
if (agent === "gemini-cli") {
|
|
817
|
+
const metaKey = `gemini_tokens_${sessionId}`;
|
|
818
|
+
const stored = db.getMetadata(metaKey);
|
|
819
|
+
if (stored) {
|
|
820
|
+
const totalTokens = parseInt(stored, 10);
|
|
821
|
+
const inputTokens = Math.round(totalTokens * 0.7);
|
|
822
|
+
const outputTokens = totalTokens - inputTokens;
|
|
823
|
+
tokens = {
|
|
824
|
+
input_tokens: inputTokens,
|
|
825
|
+
output_tokens: outputTokens,
|
|
826
|
+
cache_creation_input_tokens: 0,
|
|
827
|
+
cache_read_input_tokens: 0
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
} else if (agent === "copilot-cli") {
|
|
831
|
+
tokens = null;
|
|
832
|
+
} else {
|
|
833
|
+
const rawPath = payload.transcript_path ?? "";
|
|
834
|
+
const transcriptPath = rawPath && rawPath.endsWith(".jsonl") ? path2.resolve(rawPath) : "";
|
|
835
|
+
tokens = transcriptPath ? await extractTokenUsage(transcriptPath) : null;
|
|
836
|
+
}
|
|
614
837
|
writer.recordSessionEnd(sessionId, "stopped", tokens);
|
|
615
838
|
break;
|
|
616
839
|
}
|
|
617
840
|
case "Notification": {
|
|
618
|
-
const message =
|
|
619
|
-
const notificationType =
|
|
841
|
+
const message = payload.message ?? "";
|
|
842
|
+
const notificationType = payload.notification_type ?? "";
|
|
620
843
|
writer.recordNotification(sessionId, message, notificationType);
|
|
621
844
|
break;
|
|
622
845
|
}
|
|
623
846
|
case "SubagentStart": {
|
|
624
|
-
const agentId =
|
|
625
|
-
const agentType =
|
|
847
|
+
const agentId = payload.agent_id ?? "";
|
|
848
|
+
const agentType = payload.agent_type ?? "";
|
|
626
849
|
writer.recordSubagent(sessionId, "SubagentStart", agentId, agentType);
|
|
627
850
|
break;
|
|
628
851
|
}
|
|
629
852
|
case "SubagentStop": {
|
|
630
|
-
const agentId =
|
|
853
|
+
const agentId = payload.agent_id ?? "";
|
|
631
854
|
writer.recordSubagent(sessionId, "SubagentStop", agentId);
|
|
632
855
|
break;
|
|
633
856
|
}
|
|
634
857
|
case "PreCompact": {
|
|
635
|
-
const trigger =
|
|
858
|
+
const trigger = payload.trigger ?? "manual";
|
|
636
859
|
writer.recordCompaction(sessionId, trigger);
|
|
637
860
|
break;
|
|
638
861
|
}
|
|
639
862
|
case "PermissionRequest": {
|
|
640
|
-
const toolName =
|
|
641
|
-
const toolInput =
|
|
863
|
+
const toolName = payload.tool_name ?? "";
|
|
864
|
+
const toolInput = payload.tool_input ?? {};
|
|
642
865
|
writer.recordToolUse(sessionId, "PermissionRequest", toolName, toolInput, {}, 0, cwd);
|
|
643
866
|
break;
|
|
644
867
|
}
|
|
@@ -654,4 +877,4 @@ async function handleHookEvent(hookType) {
|
|
|
654
877
|
export {
|
|
655
878
|
handleHookEvent
|
|
656
879
|
};
|
|
657
|
-
//# sourceMappingURL=chunk-
|
|
880
|
+
//# sourceMappingURL=chunk-CLSVLWCR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/handler.ts","../../src/constants.ts","../../src/db/database.ts","../../src/db/writer.ts","../../src/hooks/transcript.ts","../../src/hooks/normalizers/gemini.ts","../../src/hooks/normalizers/copilot.ts"],"sourcesContent":["import path from 'path'\nimport os from 'os'\nimport fs from 'fs'\nimport { DATA_DIR, DB_FILENAME } from '../constants.js'\nimport { BashStatsDB } from '../db/database.js'\nimport { BashStatsWriter } from '../db/writer.js'\nimport type { AgentType, TokenUsage } from '../types.js'\nimport { extractTokenUsage } from './transcript.js'\nimport { normalizeGeminiEvent } from './normalizers/gemini.js'\nimport { normalizeCopilotEvent } from './normalizers/copilot.js'\n\n/**\n * Detect which CLI agent is running based on environment variables and process context.\n * Currently supports Claude Code (default), Gemini CLI, Copilot CLI, and OpenCode.\n */\nexport function detectAgent(): AgentType {\n if (process.env.GEMINI_SESSION_ID || process.env.GEMINI_PROJECT_DIR || process.env.GEMINI_CLI) return 'gemini-cli'\n if (process.env.GITHUB_COPILOT_CLI) return 'copilot-cli'\n if (process.env.OPENCODE) return 'opencode'\n return 'claude-code'\n}\n\nexport function parseHookEvent(input: string): Record<string, unknown> | null {\n try {\n if (!input) return null\n return JSON.parse(input) as Record<string, unknown>\n } catch {\n return null\n }\n}\n\nexport function getProjectFromCwd(cwd: string): string {\n return path.basename(cwd)\n}\n\nexport function getDataDir(): string {\n return path.join(os.homedir(), DATA_DIR)\n}\n\nexport function getDbPath(): string {\n return path.join(os.homedir(), DATA_DIR, DB_FILENAME)\n}\n\nexport async function readStdin(): Promise<string> {\n if (process.env.CLAUDE_HOOK_EVENT) {\n return process.env.CLAUDE_HOOK_EVENT\n }\n\n return new Promise<string>((resolve) => {\n let data = ''\n process.stdin.setEncoding('utf-8')\n process.stdin.on('data', (chunk: string) => {\n data += chunk\n })\n process.stdin.on('end', () => {\n resolve(data)\n })\n })\n}\n\nexport async function handleHookEvent(hookType: string): Promise<void> {\n const raw = await readStdin()\n const event = parseHookEvent(raw)\n if (!event) return\n\n const dataDir = getDataDir()\n fs.mkdirSync(dataDir, { recursive: true })\n\n const dbPath = getDbPath()\n const db = new BashStatsDB(dbPath)\n const writer = new BashStatsWriter(db)\n\n try {\n const agent = detectAgent()\n\n // Normalize events for non-Claude agents\n let effectiveHookType = hookType\n let payload: Record<string, unknown> = event\n\n if (agent === 'gemini-cli') {\n const normalized = normalizeGeminiEvent(hookType, event)\n if (!normalized) return\n\n // For AfterModel events, accumulate token counts in metadata and return early\n if (normalized.hookType === 'AfterModel') {\n if (normalized.tokenData) {\n const sessionId = (event.session_id as string) ?? ''\n const metaKey = `gemini_tokens_${sessionId}`\n const existing = db.getMetadata(metaKey)\n const prev = existing ? parseInt(existing, 10) : 0\n db.setMetadata(metaKey, String(prev + normalized.tokenData.totalTokenCount))\n }\n return\n }\n\n effectiveHookType = normalized.hookType\n payload = normalized.payload\n } else if (agent === 'copilot-cli') {\n const normalized = normalizeCopilotEvent(hookType, event)\n if (!normalized) return\n\n effectiveHookType = normalized.hookType\n payload = normalized.payload\n }\n\n const sessionId = (payload.session_id as string) ?? ''\n const cwd = (payload.cwd as string) ?? ''\n\n switch (effectiveHookType) {\n case 'SessionStart': {\n const source = (payload.source as string) ?? 'startup'\n writer.recordSessionStart(sessionId, cwd, source, agent)\n break\n }\n\n case 'UserPromptSubmit': {\n const prompt = (payload.prompt as string) ?? ''\n writer.recordPrompt(sessionId, prompt)\n break\n }\n\n case 'PreToolUse': {\n const toolName = (payload.tool_name as string) ?? ''\n const toolInput = (payload.tool_input as Record<string, unknown>) ?? {}\n writer.recordToolUse(sessionId, 'PreToolUse', toolName, toolInput, {}, 0, cwd)\n break\n }\n\n case 'PostToolUse': {\n const toolName = (payload.tool_name as string) ?? ''\n const toolInput = (payload.tool_input as Record<string, unknown>) ?? {}\n const toolResponse = (payload.tool_response as Record<string, unknown>) ?? {}\n const exitCode = (payload.exit_code as number) ?? 0\n writer.recordToolUse(sessionId, 'PostToolUse', toolName, toolInput, toolResponse, exitCode, cwd)\n break\n }\n\n case 'PostToolUseFailure': {\n const toolName = (payload.tool_name as string) ?? ''\n const toolInput = (payload.tool_input as Record<string, unknown>) ?? {}\n const toolResponse = (payload.tool_response as Record<string, unknown>) ?? {}\n writer.recordToolUse(sessionId, 'PostToolUseFailure', toolName, toolInput, toolResponse, 1, cwd)\n break\n }\n\n case 'Stop': {\n let tokens: TokenUsage | null = null\n\n if (agent === 'gemini-cli') {\n // Retrieve accumulated tokens from metadata\n const metaKey = `gemini_tokens_${sessionId}`\n const stored = db.getMetadata(metaKey)\n if (stored) {\n const totalTokens = parseInt(stored, 10)\n // Approximate 70/30 split for input/output\n const inputTokens = Math.round(totalTokens * 0.7)\n const outputTokens = totalTokens - inputTokens\n tokens = {\n input_tokens: inputTokens,\n output_tokens: outputTokens,\n cache_creation_input_tokens: 0,\n cache_read_input_tokens: 0,\n }\n }\n } else if (agent === 'copilot-cli') {\n // Copilot CLI does not provide token data through hooks\n tokens = null\n } else {\n // Claude Code: parse transcript file for tokens\n const rawPath = (payload.transcript_path as string) ?? ''\n const transcriptPath = rawPath && rawPath.endsWith('.jsonl') ? path.resolve(rawPath) : ''\n tokens = transcriptPath ? await extractTokenUsage(transcriptPath) : null\n }\n\n writer.recordSessionEnd(sessionId, 'stopped', tokens)\n break\n }\n\n case 'Notification': {\n const message = (payload.message as string) ?? ''\n const notificationType = (payload.notification_type as string) ?? ''\n writer.recordNotification(sessionId, message, notificationType)\n break\n }\n\n case 'SubagentStart': {\n const agentId = (payload.agent_id as string) ?? ''\n const agentType = (payload.agent_type as string) ?? ''\n writer.recordSubagent(sessionId, 'SubagentStart', agentId, agentType)\n break\n }\n\n case 'SubagentStop': {\n const agentId = (payload.agent_id as string) ?? ''\n writer.recordSubagent(sessionId, 'SubagentStop', agentId)\n break\n }\n\n case 'PreCompact': {\n const trigger = (payload.trigger as string) ?? 'manual'\n writer.recordCompaction(sessionId, trigger)\n break\n }\n\n case 'PermissionRequest': {\n const toolName = (payload.tool_name as string) ?? ''\n const toolInput = (payload.tool_input as Record<string, unknown>) ?? {}\n writer.recordToolUse(sessionId, 'PermissionRequest', toolName, toolInput, {}, 0, cwd)\n break\n }\n\n case 'Setup': {\n // no-op\n return\n }\n }\n } finally {\n db.close()\n }\n}\n","import type { BadgeDefinition } from './types.js'\nimport type { WeeklyChallenge, RankTierBracket } from './types.js'\n\nexport const BADGE_DEFINITIONS: BadgeDefinition[] = [\n // ===================================================================\n // VOLUME (5)\n // ===================================================================\n { id: 'first_prompt', name: 'First Prompt', icon: '\\u{1F4AC}', description: 'Submit prompts to Claude', category: 'volume', stat: 'totalPrompts', tiers: [1, 250, 2500, 10000, 50000], trigger: 'Total prompts submitted across all sessions' },\n { id: 'tool_time', name: 'Tool Time', icon: '\\u{1F527}', description: 'Make tool calls', category: 'volume', stat: 'totalToolCalls', tiers: [50, 2500, 25000, 100000, 500000], trigger: 'Total tool calls made across all sessions' },\n { id: 'marathon', name: 'Marathon', icon: '\\u{1F3C3}', description: 'Spend hours in sessions', category: 'volume', stat: 'totalSessionHours', tiers: [1, 25, 250, 1000, 5000], trigger: 'Total hours spent in sessions (rounded down)' },\n { id: 'wordsmith', name: 'Wordsmith', icon: '\\u{270D}', description: 'Type characters in prompts', category: 'volume', stat: 'totalCharsTyped', tiers: [1000, 100000, 1000000, 5000000, 25000000], trigger: 'Total characters typed in prompts' },\n { id: 'session_vet', name: 'Session Vet', icon: '\\u{1F3C5}', description: 'Complete sessions', category: 'volume', stat: 'totalSessions', tiers: [1, 50, 500, 2500, 10000], trigger: 'Total sessions completed' },\n\n // ===================================================================\n // TOOL MASTERY (7)\n // ===================================================================\n { id: 'shell_lord', name: 'Shell Lord', icon: '\\u{1F4BB}', description: 'Execute Bash commands', category: 'tool_mastery', stat: 'totalBashCommands', tiers: [25, 250, 2500, 10000, 50000], trigger: 'Bash commands executed via PostToolUse' },\n { id: 'bookworm', name: 'Bookworm', icon: '\\u{1F4D6}', description: 'Read files', category: 'tool_mastery', stat: 'totalFilesRead', tiers: [50, 500, 5000, 25000, 100000], trigger: 'Files read with the Read tool' },\n { id: 'editor_in_chief', name: 'Editor-in-Chief', icon: '\\u{1F4DD}', description: 'Edit files', category: 'tool_mastery', stat: 'totalFilesEdited', tiers: [25, 250, 2500, 10000, 50000], trigger: 'Files edited with the Edit tool' },\n { id: 'architect', name: 'Architect', icon: '\\u{1F3D7}', description: 'Create files', category: 'tool_mastery', stat: 'totalFilesCreated', tiers: [10, 100, 500, 2500, 10000], trigger: 'Files created with the Write tool' },\n { id: 'detective', name: 'Detective', icon: '\\u{1F50D}', description: 'Search with Grep and Glob', category: 'tool_mastery', stat: 'totalSearches', tiers: [50, 500, 5000, 25000, 100000], trigger: 'Grep and Glob searches performed' },\n { id: 'web_crawler', name: 'Web Crawler', icon: '\\u{1F310}', description: 'Fetch web pages', category: 'tool_mastery', stat: 'totalWebFetches', tiers: [5, 50, 200, 1000, 5000], trigger: 'WebFetch calls made' },\n { id: 'delegator', name: 'Delegator', icon: '\\u{1F916}', description: 'Spawn subagents', category: 'tool_mastery', stat: 'totalSubagents', tiers: [10, 100, 500, 2500, 10000], trigger: 'Subagents spawned via SubagentStart events' },\n\n // ===================================================================\n // TIME & PATTERNS (10)\n // ===================================================================\n { 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' },\n { id: 'night_owl', name: 'Night Owl', icon: '\\u{1F989}', description: 'Prompts between midnight and 5am', category: 'time', stat: 'nightOwlCount', tiers: [10, 50, 200, 1000, 5000], trigger: 'Prompts submitted between midnight and 5 AM' },\n { id: 'early_bird', name: 'Early Bird', icon: '\\u{1F426}', description: 'Prompts between 5am and 8am', category: 'time', stat: 'earlyBirdCount', tiers: [10, 50, 200, 1000, 5000], trigger: 'Prompts submitted between 5 AM and 8 AM' },\n { id: 'weekend_warrior', name: 'Weekend Warrior', icon: '\\u{2694}', description: 'Weekend sessions', category: 'time', stat: 'weekendSessions', tiers: [5, 25, 100, 500, 2000], trigger: 'Sessions started on Saturday or Sunday' },\n { 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, 1000], trigger: 'Prompts submitted between 2 AM and 4 AM' },\n { 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' },\n { 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' },\n { 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, 1000], trigger: 'Git commits made on Friday (via Bash tool)' },\n { id: 'timezone_traveler', name: 'Timezone Traveler', icon: '\\u{2708}', 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' },\n { 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' },\n\n // ===================================================================\n // SESSION BEHAVIOR (6)\n // ===================================================================\n { id: 'one_more_thing', name: 'One More Thing', icon: '\\u{261D}', 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' },\n { 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' },\n { 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' },\n { 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)' },\n { 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, 10000], trigger: 'PermissionRequest events recorded' },\n { 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' },\n\n // ===================================================================\n // BEHAVIORAL (5)\n // ===================================================================\n { 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, 2000, 10000], trigger: 'Count of your single most repeated prompt' },\n { 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' },\n { id: 'planner', name: 'Planner', icon: '\\u{1F4CB}', description: 'Use plan mode', category: 'behavioral', stat: 'planModeUses', tiers: [5, 25, 100, 500, 2000], trigger: 'Task tool invocations (plan mode)' },\n { id: 'novelist', name: 'Novelist', icon: '\\u{1F4D6}', description: 'Write prompts over 1000 characters', category: 'behavioral', stat: 'longPromptCount', tiers: [5, 25, 100, 500, 2000], trigger: 'Prompts with over 1,000 characters' },\n { id: 'speed_demon', name: 'Speed Demon', icon: '\\u{26A1}', description: 'Complete sessions in under 5 minutes', category: 'behavioral', stat: 'quickSessionCount', tiers: [5, 25, 100, 500, 2000], trigger: 'Sessions under 5 minutes with tool use' },\n\n // ===================================================================\n // PROMPT PATTERNS (6)\n // ===================================================================\n { id: 'minimalist', name: 'Minimalist', icon: '\\u{1F90F}', description: 'A person of few words.', category: 'prompt_patterns', stat: 'shortPromptCount', tiers: [5, 25, 100, 500, 2000], trigger: 'Prompts with fewer than 10 words' },\n { id: 'question_master', name: 'Question Master', icon: '\\u{2753}', description: 'So many questions, so little time.', category: 'prompt_patterns', stat: 'questionPromptCount', tiers: [10, 50, 200, 1000, 5000], trigger: 'Prompts ending with a question mark' },\n { id: 'the_apologizer', name: 'The Apologizer', icon: '\\u{1F625}', description: 'Sorry for asking, but...', category: 'prompt_patterns', stat: 'sorryPromptCount', tiers: [1, 10, 50, 200, 1000], trigger: \"Prompts containing the word 'sorry'\" },\n { 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)' },\n { id: 'emoji_whisperer', name: 'Emoji Whisperer', icon: '\\u{1F680}', description: 'Deploying vibes', category: 'prompt_patterns', stat: 'emojiPromptCount', tiers: [5, 25, 100, 500, 2000], trigger: 'Prompts containing emoji characters' },\n { 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, 1000], trigger: 'Prompts with 50+ lines of text' },\n\n // ===================================================================\n // RESILIENCE (3)\n // ===================================================================\n { id: 'clean_hands', name: 'Clean Hands', icon: '\\u{2728}', description: 'Longest error-free tool streak', category: 'resilience', stat: 'longestErrorFreeStreak', tiers: [50, 200, 500, 2000, 10000], trigger: 'Consecutive successful tool calls without any error' },\n { id: 'resilient', name: 'Resilient', icon: '\\u{1F6E1}', description: 'Survive errors', category: 'resilience', stat: 'totalErrors', tiers: [10, 50, 200, 1000, 5000], trigger: 'Total errors survived across all sessions' },\n { 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' },\n\n // ===================================================================\n // ERROR & RECOVERY (5)\n // ===================================================================\n { 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' },\n { 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' },\n { id: 'the_undoer', name: 'The Undoer', icon: '\\u{21A9}', description: 'Ctrl+Z energy.', category: 'error_recovery', stat: 'undoEditCount', tiers: [1, 10, 50, 200, 1000], trigger: 'Back-to-back Edit calls on the same file in a session' },\n { 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' },\n { id: 'phoenix', name: 'Phoenix', icon: '\\u{1F985}', description: 'From the ashes of 100 errors, you rise.', category: 'error_recovery', stat: 'totalLifetimeErrors', tiers: [100, 500, 1000, 5000, 10000], trigger: 'Total lifetime errors survived across all sessions' },\n\n // ===================================================================\n // TOOL COMBOS (5)\n // ===================================================================\n { id: 'read_edit_run', name: 'Read-Edit-Run', icon: '\\u{1F3AF}', description: 'The holy trinity.', category: 'tool_combos', stat: 'readEditRunCount', tiers: [25, 100, 500, 2000, 10000], trigger: 'Read \\u2192 Edit \\u2192 Bash sequences detected in events' },\n { id: 'grep_ninja', name: 'Grep Ninja', icon: '\\u{1F977}', description: 'Finding needles in haystacks since day one.', category: 'tool_combos', stat: 'totalSearches', tiers: [250, 1000, 5000, 25000, 100000], trigger: 'Total Grep and Glob searches performed' },\n { 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' },\n { id: 'the_refactorer', name: 'The Refactorer', icon: '\\u{267B}', description: 'Same file, different day.', category: 'tool_combos', stat: 'maxSameFileEditsLifetime', tiers: [50, 100, 250, 500, 2000], trigger: 'Max Edit calls to any single file path across all sessions' },\n { 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, 10000], trigger: 'Grep/Glob followed by Edit within same session' },\n\n // ===================================================================\n // SHIPPING & PROJECTS (4)\n // ===================================================================\n { id: 'shipper', name: 'Shipper', icon: '\\u{1F4E6}', description: 'Make commits via Claude', category: 'shipping', stat: 'totalCommits', tiers: [5, 50, 200, 1000, 5000], trigger: \"Bash tool calls containing 'git commit'\" },\n { id: 'pr_machine', name: 'PR Machine', icon: '\\u{1F500}', description: 'Create pull requests', category: 'shipping', stat: 'totalPRs', tiers: [3, 25, 100, 500, 2000], trigger: \"Bash tool calls containing 'gh pr create'\" },\n { 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' },\n { 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' },\n\n // ===================================================================\n // PROJECT DEDICATION (5)\n // ===================================================================\n { id: 'monogamous', name: 'Monogamous', icon: '\\u{1F48D}', description: 'One project. True love.', category: 'project_dedication', stat: 'maxProjectSessions', tiers: [50, 100, 250, 500, 1000], trigger: 'Max sessions on any single project' },\n { 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' },\n { 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' },\n { 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' },\n { 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' },\n\n // ===================================================================\n // MULTI-AGENT (6)\n // ===================================================================\n { 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' },\n { id: 'hive_mind', name: 'Hive Mind', icon: '\\u{1F41D}', description: 'Spawn subagents total', category: 'multi_agent', stat: 'totalSubagents', tiers: [25, 250, 1000, 5000, 25000], trigger: 'Total SubagentStart events across all sessions' },\n { 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' },\n { 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' },\n { id: 'the_orchestrator', name: 'The Orchestrator', icon: '\\u{1F3BC}', description: \"You don't code. You conduct.\", category: 'multi_agent', stat: 'totalSubagentSpawns', tiers: [50, 250, 1000, 5000, 25000], trigger: 'Total subagent spawns across all sessions' },\n { 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' },\n\n // --- Cross-agent badges (new) ---\n { 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)' },\n { id: 'gemini_whisperer', name: 'Gemini Whisperer', icon: '\\u{264A}', description: 'The stars aligned for your Gemini sessions.', category: 'multi_agent', stat: 'geminiSessions', tiers: [10, 50, 200, 1000, 5000], trigger: 'Sessions completed in Gemini CLI' },\n { id: 'copilot_rider', name: 'Copilot Rider', icon: '\\u{2708}', description: 'Your copilot is always on duty.', category: 'multi_agent', stat: 'copilotSessions', tiers: [10, 50, 200, 1000, 5000], trigger: 'Sessions completed in Copilot CLI' },\n { 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, 1000, 5000], trigger: 'Sessions completed in OpenCode' },\n { 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' },\n { 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' },\n\n // ===================================================================\n // WILD CARD (12)\n // ===================================================================\n { 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, 1000, 5000], trigger: \"Prompts containing 'please' or 'thank'\" },\n { 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, 1000], trigger: 'Prompts over 5,000 characters' },\n { 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' },\n { 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' },\n { 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, 1000], trigger: 'Total duplicate prompts submitted' },\n { 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' },\n { id: 'deja_vu', name: 'D\\u00E9j\\u00E0 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' },\n { 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, 1000], trigger: 'Read immediately after Write on the same file' },\n { 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, 1000], trigger: \"Prompts with numbered step-by-step instructions (e.g. '1.' '2.')\" },\n { 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, 1000], trigger: \"Prompts containing 'try again' or 'one more time'\" },\n { id: 'rubber_stamp', name: 'Rubber Stamp', icon: '\\u{2705}', description: 'Yes. Yes. Yes. Approved.', category: 'wild_card', stat: 'maxConsecutivePermissions', tiers: [25, 50, 100, 250, 500], trigger: 'Max consecutive PermissionRequest events' },\n { 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, 1000], trigger: 'Bash success (exit code 0) after a previous Bash failure' },\n\n // ===================================================================\n // TOKEN USAGE (10)\n // ===================================================================\n { id: 'token_burner', name: 'Token Burner', icon: '\\u{1F525}', description: 'Consume tokens across all sessions', category: 'token_usage', stat: 'totalTokens', tiers: [50000000, 500000000, 5000000000, 50000000000, 500000000000], trigger: 'Total tokens consumed (input + output + cache read + cache creation)' },\n { id: 'output_machine', name: 'Output Machine', icon: '\\u{1F5A8}', description: 'Generate output tokens from Claude', category: 'token_usage', stat: 'totalOutputTokens', tiers: [1000000, 10000000, 100000000, 500000000, 2000000000], trigger: 'Total output tokens generated by Claude across all sessions' },\n { id: 'cache_royalty', name: 'Cache Royalty', icon: '\\u{1F451}', description: 'Read tokens from prompt cache', category: 'token_usage', stat: 'totalCacheReadTokens', tiers: [50000000, 500000000, 5000000000, 50000000000, 500000000000], trigger: 'Total cache read tokens (cached context reused across turns)' },\n { id: 'context_crafter', name: 'Context Crafter', icon: '\\u{1F9F1}', description: 'Create new cache entries', category: 'token_usage', stat: 'totalCacheCreationTokens', tiers: [10000000, 100000000, 1000000000, 10000000000, 100000000000], trigger: 'Total cache creation tokens (new context written to cache)' },\n { id: 'token_whale', name: 'Token Whale', icon: '\\u{1F40B}', description: 'Massive token consumption in a single session', category: 'token_usage', stat: 'mostTokensInSession', tiers: [10000000, 50000000, 200000000, 500000000, 1000000000], trigger: 'Most total tokens consumed in any single session' },\n { id: 'heavy_hitter', name: 'Heavy Hitter', icon: '\\u{1F4AA}', description: 'Sessions exceeding 1M total tokens', category: 'token_usage', stat: 'heavyTokenSessions', tiers: [10, 50, 250, 1000, 5000], trigger: 'Sessions with 1,000,000+ total tokens' },\n { 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, 1000], trigger: 'Sessions under 50,000 total tokens with at least 1 tool call' },\n { id: 'token_velocity', name: 'Token Velocity', icon: '\\u{26A1}', description: 'High average tokens per session', category: 'token_usage', stat: 'avgTokensPerSession', tiers: [5000000, 10000000, 25000000, 50000000, 100000000], trigger: 'Average total tokens per session across all sessions' },\n { id: 'prolific_session', name: 'Prolific', icon: '\\u{270D}', description: 'Most output generated in one session', category: 'token_usage', stat: 'maxOutputInSession', tiers: [100000, 500000, 2000000, 10000000, 50000000], trigger: 'Most output tokens generated by Claude in a single session' },\n { id: 'input_flood', name: 'Input Flood', icon: '\\u{1F30A}', description: 'Total raw input tokens sent to the API', category: 'token_usage', stat: 'totalInputTokens', tiers: [1000000, 10000000, 100000000, 500000000, 2000000000], trigger: 'Total non-cached input tokens (the small uncached portion of each request)' },\n\n // ===================================================================\n // ASPIRATIONAL (12) - Singularity-only\n // ===================================================================\n { id: 'the_machine', name: 'The Machine', icon: '\\u{2699}', description: 'You are no longer using the tool. You are the tool.', category: 'aspirational', stat: 'totalToolCalls', tiers: [100000, 100000, 100000, 100000, 100000], aspirational: true, trigger: 'Reach 100,000 total tool calls' },\n { 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' },\n { 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: [10000000, 10000000, 10000000, 10000000, 10000000], aspirational: true, trigger: 'Type 10 million characters in prompts' },\n { id: 'lifer', name: 'Lifer', icon: '\\u{1F451}', description: 'At this point, Claude is your cofounder.', category: 'aspirational', stat: 'totalSessions', tiers: [10000, 10000, 10000, 10000, 10000], aspirational: true, trigger: 'Complete 10,000 sessions' },\n { id: 'transcendent', name: 'Transcendent', icon: '\\u{2B50}', description: \"You've reached the peak. The view is nice up here.\", category: 'aspirational', stat: 'totalXP', tiers: [100000, 100000, 100000, 100000, 100000], aspirational: true, trigger: 'Earn 100,000 total XP' },\n { 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' },\n { id: 'ten_thousand_hours', name: '10,000 Hours', icon: '\\u{23F0}', description: 'Malcolm Gladwell would be proud.', category: 'aspirational', stat: 'totalSessionHours', tiers: [10000, 10000, 10000, 10000, 10000], aspirational: true, trigger: 'Spend 10,000 hours in sessions' },\n { id: 'master_architect', name: 'The Architect', icon: '\\u{1F3DB}', description: \"You've built more than most companies ship.\", category: 'aspirational', stat: 'totalFilesCreated', tiers: [1000, 1000, 1000, 1000, 1000], aspirational: true, trigger: 'Create 1,000+ files with the Write tool' },\n { 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' },\n { 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' },\n { id: 'centimillionaire', name: 'Centimillionaire', icon: '\\u{2328}', description: '100 million characters. Your keyboard weeps.', category: 'aspirational', stat: 'totalCharsTyped', tiers: [100000000, 100000000, 100000000, 100000000, 100000000], aspirational: true, trigger: 'Type 100 million characters in prompts' },\n { 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: [1000000000, 1000000000, 1000000000, 1000000000, 1000000000], aspirational: true, trigger: 'Consume 1 billion total tokens' },\n\n // ===================================================================\n // SECRET (17)\n // ===================================================================\n { 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\" },\n { 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' },\n { 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' },\n { 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' },\n { 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' },\n { 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' },\n { id: 'speed_run', name: 'Speed Run Any%', icon: '\\u{23F1}', 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' },\n { 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' },\n { 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' },\n { 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' },\n { 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\" },\n { 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)' },\n { 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' },\n { 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' },\n { 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' },\n { 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' },\n { 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' },\n]\n\n// ===================================================================\n// RANK SYSTEM (1-500)\n// ===================================================================\n\nexport const RANK_TIER_BRACKETS: RankTierBracket[] = [\n { tier: 'System Anomaly', minRank: 500, maxRank: 500 },\n { tier: 'Obsidian', minRank: 401, maxRank: 499 },\n { tier: 'Diamond', minRank: 301, maxRank: 400 },\n { tier: 'Gold', minRank: 201, maxRank: 300 },\n { tier: 'Silver', minRank: 101, maxRank: 200 },\n { tier: 'Bronze', minRank: 1, maxRank: 100 },\n]\n\nexport function xpForRank(rank: number): number {\n if (rank <= 0) return 0\n return Math.floor(10 * Math.pow(rank, 2.2))\n}\n\nexport function rankTierForRank(rank: number): string {\n for (const bracket of RANK_TIER_BRACKETS) {\n if (rank >= bracket.minRank && rank <= bracket.maxRank) {\n return bracket.tier\n }\n }\n return 'Unranked'\n}\n\n// ===================================================================\n// BADGE TIER XP REWARDS\n// ===================================================================\n\nexport const TIER_XP = [0, 50, 100, 200, 500, 1000]\n\n// ===================================================================\n// WEEKLY GOALS\n// ===================================================================\n\nexport const ACTIVITY_MULTIPLIERS: Record<number, number> = {\n 1: 1.0,\n 2: 1.1,\n 3: 1.2,\n 4: 1.3,\n 5: 1.5,\n 6: 1.75,\n 7: 2.0,\n}\n\nexport const WEEKLY_CHALLENGES: WeeklyChallenge[] = [\n { id: 'wk_diverse_tools', description: 'Use 5+ distinct tools in 5 sessions', stat: 'diverseToolSessions', threshold: 5, xpReward: 200, weekScoped: true },\n { id: 'wk_200_prompts', description: 'Submit 200 prompts this week', stat: 'totalPrompts', threshold: 200, xpReward: 250, weekScoped: true },\n { id: 'wk_quick_sessions', description: 'Complete 3 sessions under 2 minutes', stat: 'quickDrawSessions', threshold: 3, xpReward: 150, weekScoped: true },\n { id: 'wk_5_day_commits', description: 'Make git commits on 5 different days', stat: 'commitDays', threshold: 5, xpReward: 300, weekScoped: true },\n { id: 'wk_7_day_streak', description: 'Be active all 7 days this week', stat: 'daysActive', threshold: 7, xpReward: 400, weekScoped: true },\n { id: 'wk_subagent_power', description: 'Spawn 8+ subagents in a single session', stat: 'maxSubagentsInSession', threshold: 8, xpReward: 200, weekScoped: true },\n { id: 'wk_night_code', description: 'Code after midnight on 3 different nights', stat: 'nightOwlDays', threshold: 3, xpReward: 150, weekScoped: true },\n { id: 'wk_2000_tools', description: 'Make 2,000 tool calls this week', stat: 'totalToolCalls', threshold: 2000, xpReward: 250, weekScoped: true },\n { id: 'wk_10_sessions', description: 'Complete 10 sessions this week', stat: 'totalSessions', threshold: 10, xpReward: 200, weekScoped: true },\n { id: 'wk_20_sessions', description: 'Complete 20 sessions this week', stat: 'totalSessions', threshold: 20, xpReward: 350, weekScoped: true },\n { id: 'wk_500_reads', description: 'Read 500 files this week', stat: 'totalFilesRead', threshold: 500, xpReward: 250, weekScoped: true },\n { id: 'wk_100_edits', description: 'Edit 100 files this week', stat: 'totalFilesEdited', threshold: 100, xpReward: 250, weekScoped: true },\n { id: 'wk_20_creates', description: 'Create 20 new files this week', stat: 'totalFilesCreated', threshold: 20, xpReward: 200, weekScoped: true },\n { id: 'wk_3_projects', description: 'Work on 3+ different projects this week', stat: 'uniqueProjects', threshold: 3, xpReward: 200, weekScoped: true },\n { id: 'wk_3_marathons', description: 'Have 3 sessions lasting over 1 hour', stat: 'extendedSessionCount', threshold: 3, xpReward: 250, weekScoped: true },\n { id: 'wk_5_clean', description: 'Complete 5 sessions with zero errors', stat: 'cleanSessions', threshold: 5, xpReward: 200, weekScoped: true },\n { id: 'wk_15_hours', description: 'Spend 15+ total hours in sessions', stat: 'totalHours', threshold: 15, xpReward: 300, weekScoped: true },\n { id: 'wk_200_bash', description: 'Run 200 Bash commands this week', stat: 'totalBashCommands', threshold: 200, xpReward: 200, weekScoped: true },\n { id: 'wk_250_searches', description: 'Perform 250 searches (Grep/Glob)', stat: 'totalSearches', threshold: 250, xpReward: 200, weekScoped: true },\n { id: 'wk_10_long_prompts', description: 'Write 10 prompts over 1,000 characters', stat: 'longPromptCount', threshold: 10, xpReward: 150, weekScoped: true },\n { id: 'wk_5_commits', description: 'Make 5 git commits this week', stat: 'totalCommits', threshold: 5, xpReward: 200, weekScoped: true },\n { id: 'wk_2_prs', description: 'Create 2 pull requests this week', stat: 'totalPRs', threshold: 2, xpReward: 250, weekScoped: true },\n { id: 'wk_5000_tools', description: 'Make 5,000 tool calls this week', stat: 'totalToolCalls', threshold: 5000, xpReward: 400, weekScoped: true },\n { id: 'wk_weekend_warrior', description: 'Code on both Saturday and Sunday', stat: 'weekendDays', threshold: 2, xpReward: 200, weekScoped: true },\n { id: 'wk_3_early_birds', description: 'Submit a prompt before 8am on 3 days', stat: 'earlyBirdDays', threshold: 3, xpReward: 200, weekScoped: true },\n]\n\n// ===================================================================\n// PATHS\n// ===================================================================\n\nexport const DATA_DIR = '.bashstats'\nexport const DB_FILENAME = 'bashstats.db'\nexport const DEFAULT_PORT = 17900\n","import Database from 'better-sqlite3'\nimport type { EventRow, SessionRow, PromptRow, DailyActivityRow, AchievementUnlockRow, TokenUsage, WeeklyGoalRow, WeeklyXPRow } from '../types.js'\n\nfunction localNow(): string {\n const d = new Date()\n const pad = (n: number) => String(n).padStart(2, '0')\n const ms = String(d.getMilliseconds()).padStart(3, '0')\n return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${ms}`\n}\n\nconst SCHEMA = `\nCREATE TABLE IF NOT EXISTS events (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n hook_type TEXT NOT NULL,\n tool_name TEXT,\n tool_input TEXT,\n tool_output TEXT,\n exit_code INTEGER,\n success INTEGER,\n cwd TEXT,\n project TEXT,\n timestamp TEXT NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n agent TEXT NOT NULL DEFAULT 'claude-code',\n started_at TEXT NOT NULL,\n ended_at TEXT,\n stop_reason TEXT,\n prompt_count INTEGER DEFAULT 0,\n tool_count INTEGER DEFAULT 0,\n error_count INTEGER DEFAULT 0,\n project TEXT,\n duration_seconds INTEGER,\n input_tokens INTEGER DEFAULT 0,\n output_tokens INTEGER DEFAULT 0,\n cache_creation_input_tokens INTEGER DEFAULT 0,\n cache_read_input_tokens INTEGER DEFAULT 0\n);\n\nCREATE TABLE IF NOT EXISTS prompts (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n content TEXT NOT NULL,\n char_count INTEGER NOT NULL,\n word_count INTEGER NOT NULL,\n timestamp TEXT NOT NULL,\n FOREIGN KEY (session_id) REFERENCES sessions(id)\n);\n\nCREATE TABLE IF NOT EXISTS daily_activity (\n date TEXT PRIMARY KEY,\n sessions INTEGER DEFAULT 0,\n prompts INTEGER DEFAULT 0,\n tool_calls INTEGER DEFAULT 0,\n errors INTEGER DEFAULT 0,\n duration_seconds INTEGER DEFAULT 0,\n input_tokens INTEGER DEFAULT 0,\n output_tokens INTEGER DEFAULT 0,\n cache_creation_input_tokens INTEGER DEFAULT 0,\n cache_read_input_tokens INTEGER DEFAULT 0\n);\n\nCREATE TABLE IF NOT EXISTS achievement_unlocks (\n badge_id TEXT NOT NULL,\n tier INTEGER NOT NULL,\n unlocked_at TEXT NOT NULL,\n notified INTEGER DEFAULT 0,\n PRIMARY KEY (badge_id, tier)\n);\n\nCREATE TABLE IF NOT EXISTS metadata (\n key TEXT PRIMARY KEY,\n value TEXT\n);\n\nCREATE TABLE IF NOT EXISTS weekly_goals (\n week_start TEXT NOT NULL,\n challenge_id TEXT NOT NULL,\n completed INTEGER DEFAULT 0,\n xp_reward INTEGER NOT NULL,\n PRIMARY KEY (week_start, challenge_id)\n);\n\nCREATE TABLE IF NOT EXISTS weekly_xp (\n week_start TEXT PRIMARY KEY,\n base_xp INTEGER DEFAULT 0,\n multiplier REAL DEFAULT 1.0,\n bonus_xp INTEGER DEFAULT 0\n);\n\nCREATE INDEX IF NOT EXISTS idx_events_session ON events(session_id);\nCREATE INDEX IF NOT EXISTS idx_events_hook_type ON events(hook_type);\nCREATE INDEX IF NOT EXISTS idx_events_tool_name ON events(tool_name);\nCREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);\nCREATE INDEX IF NOT EXISTS idx_events_project ON events(project);\nCREATE INDEX IF NOT EXISTS idx_prompts_session ON prompts(session_id);\nCREATE INDEX IF NOT EXISTS idx_prompts_timestamp ON prompts(timestamp);\n`\n\nexport class BashStatsDB {\n private db: Database.Database\n\n constructor(dbPath: string) {\n this.db = new Database(dbPath)\n this.db.pragma('journal_mode = WAL')\n this.db.pragma('busy_timeout = 5000')\n this.db.pragma('foreign_keys = ON')\n this.db.exec(SCHEMA)\n this.migrate()\n }\n\n private migrate(): void {\n const sessionCols = this.db.pragma('table_info(sessions)') as { name: string }[]\n const sessionColNames = new Set(sessionCols.map(c => c.name))\n\n if (!sessionColNames.has('agent')) {\n this.db.exec(\"ALTER TABLE sessions ADD COLUMN agent TEXT NOT NULL DEFAULT 'claude-code'\")\n }\n\n const tokenCols = ['input_tokens', 'output_tokens', 'cache_creation_input_tokens', 'cache_read_input_tokens']\n for (const col of tokenCols) {\n if (!sessionColNames.has(col)) {\n this.db.exec(`ALTER TABLE sessions ADD COLUMN ${col} INTEGER DEFAULT 0`)\n }\n }\n\n const dailyCols = this.db.pragma('table_info(daily_activity)') as { name: string }[]\n const dailyColNames = new Set(dailyCols.map(c => c.name))\n for (const col of tokenCols) {\n if (!dailyColNames.has(col)) {\n this.db.exec(`ALTER TABLE daily_activity ADD COLUMN ${col} INTEGER DEFAULT 0`)\n }\n }\n }\n\n close(): void {\n this.db.close()\n }\n\n getTableNames(): string[] {\n const rows = this.db.prepare(\"SELECT name FROM sqlite_master WHERE type='table'\").all() as { name: string }[]\n return rows.map(r => r.name)\n }\n\n // === Events ===\n\n insertEvent(event: Omit<EventRow, 'id'>): number {\n const stmt = this.db.prepare(`\n INSERT INTO events (session_id, hook_type, tool_name, tool_input, tool_output, exit_code, success, cwd, project, timestamp)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `)\n const result = stmt.run(\n event.session_id, event.hook_type, event.tool_name, event.tool_input,\n event.tool_output, event.exit_code, event.success, event.cwd, event.project, event.timestamp\n )\n return result.lastInsertRowid as number\n }\n\n getEvents(filter: { session_id?: string; hook_type?: string; tool_name?: string }): EventRow[] {\n let sql = 'SELECT * FROM events WHERE 1=1'\n const params: unknown[] = []\n if (filter.session_id) { sql += ' AND session_id = ?'; params.push(filter.session_id) }\n if (filter.hook_type) { sql += ' AND hook_type = ?'; params.push(filter.hook_type) }\n if (filter.tool_name) { sql += ' AND tool_name = ?'; params.push(filter.tool_name) }\n sql += ' ORDER BY timestamp ASC'\n return this.db.prepare(sql).all(...params) as EventRow[]\n }\n\n // === Sessions ===\n\n insertSession(session: { id: string; agent?: string; started_at: string; project?: string | null }): void {\n this.db.prepare(`\n INSERT OR IGNORE INTO sessions (id, agent, started_at, project) VALUES (?, ?, ?, ?)\n `).run(session.id, session.agent ?? 'claude-code', session.started_at, session.project ?? null)\n }\n\n getSession(id: string): SessionRow | null {\n return this.db.prepare('SELECT * FROM sessions WHERE id = ?').get(id) as SessionRow | null\n }\n\n updateSession(id: string, updates: Partial<Pick<SessionRow, 'ended_at' | 'stop_reason' | 'duration_seconds'>>): void {\n const sets: string[] = []\n const params: unknown[] = []\n if (updates.ended_at !== undefined) { sets.push('ended_at = ?'); params.push(updates.ended_at) }\n if (updates.stop_reason !== undefined) { sets.push('stop_reason = ?'); params.push(updates.stop_reason) }\n if (updates.duration_seconds !== undefined) { sets.push('duration_seconds = ?'); params.push(updates.duration_seconds) }\n if (sets.length === 0) return\n params.push(id)\n this.db.prepare(`UPDATE sessions SET ${sets.join(', ')} WHERE id = ?`).run(...params)\n }\n\n updateSessionTokens(id: string, tokens: TokenUsage): void {\n this.db.prepare(`\n UPDATE sessions SET input_tokens = ?, output_tokens = ?, cache_creation_input_tokens = ?, cache_read_input_tokens = ? WHERE id = ?\n `).run(tokens.input_tokens, tokens.output_tokens, tokens.cache_creation_input_tokens, tokens.cache_read_input_tokens, id)\n }\n\n incrementSessionCounters(id: string, counters: { prompts?: number; tools?: number; errors?: number }): void {\n const sets: string[] = []\n const params: unknown[] = []\n if (counters.prompts) { sets.push('prompt_count = prompt_count + ?'); params.push(counters.prompts) }\n if (counters.tools) { sets.push('tool_count = tool_count + ?'); params.push(counters.tools) }\n if (counters.errors) { sets.push('error_count = error_count + ?'); params.push(counters.errors) }\n if (sets.length === 0) return\n params.push(id)\n this.db.prepare(`UPDATE sessions SET ${sets.join(', ')} WHERE id = ?`).run(...params)\n }\n\n // === Prompts ===\n\n insertPrompt(prompt: Omit<PromptRow, 'id'>): number {\n const result = this.db.prepare(`\n INSERT INTO prompts (session_id, content, char_count, word_count, timestamp) VALUES (?, ?, ?, ?, ?)\n `).run(prompt.session_id, prompt.content, prompt.char_count, prompt.word_count, prompt.timestamp)\n return result.lastInsertRowid as number\n }\n\n getPrompts(sessionId: string): PromptRow[] {\n return this.db.prepare('SELECT * FROM prompts WHERE session_id = ? ORDER BY timestamp ASC').all(sessionId) as PromptRow[]\n }\n\n // === Daily Activity ===\n\n incrementDailyActivity(date: string, increments: { sessions?: number; prompts?: number; tool_calls?: number; errors?: number; duration_seconds?: number; input_tokens?: number; output_tokens?: number; cache_creation_input_tokens?: number; cache_read_input_tokens?: number }): void {\n this.db.prepare(`\n INSERT INTO daily_activity (date, sessions, prompts, tool_calls, errors, duration_seconds, input_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(date) DO UPDATE SET\n sessions = sessions + excluded.sessions,\n prompts = prompts + excluded.prompts,\n tool_calls = tool_calls + excluded.tool_calls,\n errors = errors + excluded.errors,\n duration_seconds = duration_seconds + excluded.duration_seconds,\n input_tokens = input_tokens + excluded.input_tokens,\n output_tokens = output_tokens + excluded.output_tokens,\n cache_creation_input_tokens = cache_creation_input_tokens + excluded.cache_creation_input_tokens,\n cache_read_input_tokens = cache_read_input_tokens + excluded.cache_read_input_tokens\n `).run(\n date,\n increments.sessions ?? 0,\n increments.prompts ?? 0,\n increments.tool_calls ?? 0,\n increments.errors ?? 0,\n increments.duration_seconds ?? 0,\n increments.input_tokens ?? 0,\n increments.output_tokens ?? 0,\n increments.cache_creation_input_tokens ?? 0,\n increments.cache_read_input_tokens ?? 0,\n )\n }\n\n getDailyActivity(date: string): DailyActivityRow | null {\n return this.db.prepare('SELECT * FROM daily_activity WHERE date = ?').get(date) as DailyActivityRow | null\n }\n\n getAllDailyActivity(days?: number): DailyActivityRow[] {\n if (days) {\n return this.db.prepare('SELECT * FROM daily_activity ORDER BY date DESC LIMIT ?').all(days) as DailyActivityRow[]\n }\n return this.db.prepare('SELECT * FROM daily_activity ORDER BY date DESC').all() as DailyActivityRow[]\n }\n\n // === Achievement Unlocks ===\n\n insertUnlock(badgeId: string, tier: number): void {\n this.db.prepare(`\n INSERT OR IGNORE INTO achievement_unlocks (badge_id, tier, unlocked_at) VALUES (?, ?, ?)\n `).run(badgeId, tier, localNow())\n }\n\n getUnlocks(): AchievementUnlockRow[] {\n return this.db.prepare('SELECT * FROM achievement_unlocks ORDER BY unlocked_at DESC').all() as AchievementUnlockRow[]\n }\n\n getUnnotifiedUnlocks(): AchievementUnlockRow[] {\n return this.db.prepare('SELECT * FROM achievement_unlocks WHERE notified = 0').all() as AchievementUnlockRow[]\n }\n\n markNotified(badgeId: string, tier: number): void {\n this.db.prepare('UPDATE achievement_unlocks SET notified = 1 WHERE badge_id = ? AND tier = ?').run(badgeId, tier)\n }\n\n // === Metadata ===\n\n setMetadata(key: string, value: string): void {\n this.db.prepare('INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)').run(key, value)\n }\n\n getMetadata(key: string): string | null {\n const row = this.db.prepare('SELECT value FROM metadata WHERE key = ?').get(key) as { value: string } | undefined\n return row?.value ?? null\n }\n\n // === Weekly Goals ===\n\n insertWeeklyGoal(weekStart: string, challengeId: string, xpReward: number): void {\n this.db.prepare(`\n INSERT OR IGNORE INTO weekly_goals (week_start, challenge_id, xp_reward) VALUES (?, ?, ?)\n `).run(weekStart, challengeId, xpReward)\n }\n\n completeWeeklyGoal(weekStart: string, challengeId: string): void {\n this.db.prepare('UPDATE weekly_goals SET completed = 1 WHERE week_start = ? AND challenge_id = ?').run(weekStart, challengeId)\n }\n\n getWeeklyGoals(weekStart: string): WeeklyGoalRow[] {\n return this.db.prepare('SELECT * FROM weekly_goals WHERE week_start = ?').all(weekStart) as WeeklyGoalRow[]\n }\n\n // === Weekly XP ===\n\n upsertWeeklyXP(weekStart: string, baseXP: number, multiplier: number, bonusXP: number): void {\n this.db.prepare(`\n INSERT INTO weekly_xp (week_start, base_xp, multiplier, bonus_xp) VALUES (?, ?, ?, ?)\n ON CONFLICT(week_start) DO UPDATE SET base_xp = ?, multiplier = ?, bonus_xp = ?\n `).run(weekStart, baseXP, multiplier, bonusXP, baseXP, multiplier, bonusXP)\n }\n\n getWeeklyXP(weekStart: string): WeeklyXPRow | null {\n return this.db.prepare('SELECT * FROM weekly_xp WHERE week_start = ?').get(weekStart) as WeeklyXPRow | null\n }\n\n // === Raw DB access for stats engine ===\n\n prepare(sql: string): Database.Statement {\n return this.db.prepare(sql)\n }\n}\n","import { BashStatsDB } from './database.js'\nimport type { TokenUsage } from '../types.js'\nimport path from 'path'\n\nexport class BashStatsWriter {\n private db: BashStatsDB\n\n constructor(db: BashStatsDB) {\n this.db = db\n }\n\n private extractProject(cwd: string): string {\n return path.basename(cwd)\n }\n\n private today(): string {\n const d = new Date()\n const pad = (n: number) => String(n).padStart(2, '0')\n return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`\n }\n\n private now(): string {\n const d = new Date()\n const pad = (n: number) => String(n).padStart(2, '0')\n const ms = String(d.getMilliseconds()).padStart(3, '0')\n return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${ms}`\n }\n\n recordSessionStart(sessionId: string, cwd: string, source: string, agent?: string): void {\n const project = this.extractProject(cwd)\n const timestamp = this.now()\n\n this.db.insertSession({\n id: sessionId,\n agent,\n started_at: timestamp,\n project,\n })\n\n this.db.insertEvent({\n session_id: sessionId,\n hook_type: 'SessionStart',\n tool_name: null,\n tool_input: JSON.stringify({ source }),\n tool_output: null,\n exit_code: null,\n success: null,\n cwd,\n project,\n timestamp,\n })\n\n this.db.incrementDailyActivity(this.today(), { sessions: 1 })\n }\n\n recordPrompt(sessionId: string, content: string): void {\n const timestamp = this.now()\n const wordCount = content.split(/\\s+/).filter(w => w.length > 0).length\n const charCount = content.length\n\n this.db.insertPrompt({\n session_id: sessionId,\n content,\n char_count: charCount,\n word_count: wordCount,\n timestamp,\n })\n\n this.db.insertEvent({\n session_id: sessionId,\n hook_type: 'UserPromptSubmit',\n tool_name: null,\n tool_input: null,\n tool_output: null,\n exit_code: null,\n success: null,\n cwd: null,\n project: null,\n timestamp,\n })\n\n this.db.incrementSessionCounters(sessionId, { prompts: 1 })\n this.db.incrementDailyActivity(this.today(), { prompts: 1 })\n }\n\n recordToolUse(\n sessionId: string,\n hookType: string,\n toolName: string,\n toolInput: Record<string, unknown>,\n toolOutput: Record<string, unknown>,\n exitCode: number | null,\n cwd: string,\n ): void {\n const timestamp = this.now()\n const project = this.extractProject(cwd)\n const success = exitCode === 0 ? 1 : 0\n\n this.db.insertEvent({\n session_id: sessionId,\n hook_type: hookType,\n tool_name: toolName,\n tool_input: JSON.stringify(toolInput),\n tool_output: JSON.stringify(toolOutput),\n exit_code: exitCode,\n success,\n cwd,\n project,\n timestamp,\n })\n\n this.db.incrementSessionCounters(sessionId, {\n tools: 1,\n errors: success === 0 ? 1 : 0,\n })\n\n this.db.incrementDailyActivity(this.today(), {\n tool_calls: 1,\n errors: success === 0 ? 1 : 0,\n })\n }\n\n recordSessionEnd(sessionId: string, stopReason: string, tokens?: TokenUsage | null): void {\n const timestamp = this.now()\n const session = this.db.getSession(sessionId)\n\n let durationSeconds: number | undefined\n if (session) {\n const startTime = new Date(session.started_at).getTime()\n const endTime = new Date(timestamp).getTime()\n durationSeconds = Math.round((endTime - startTime) / 1000)\n }\n\n this.db.updateSession(sessionId, {\n ended_at: timestamp,\n stop_reason: stopReason,\n duration_seconds: durationSeconds,\n })\n\n if (tokens) {\n this.db.updateSessionTokens(sessionId, tokens)\n }\n\n this.db.insertEvent({\n session_id: sessionId,\n hook_type: 'Stop',\n tool_name: null,\n tool_input: JSON.stringify({ stop_reason: stopReason }),\n tool_output: null,\n exit_code: null,\n success: null,\n cwd: null,\n project: null,\n timestamp,\n })\n\n const dailyIncrements: Record<string, number> = {}\n if (durationSeconds !== undefined) {\n dailyIncrements.duration_seconds = durationSeconds\n }\n if (tokens) {\n dailyIncrements.input_tokens = tokens.input_tokens\n dailyIncrements.output_tokens = tokens.output_tokens\n dailyIncrements.cache_creation_input_tokens = tokens.cache_creation_input_tokens\n dailyIncrements.cache_read_input_tokens = tokens.cache_read_input_tokens\n }\n if (Object.keys(dailyIncrements).length > 0) {\n this.db.incrementDailyActivity(this.today(), dailyIncrements)\n }\n }\n\n recordNotification(sessionId: string, message: string, notificationType: string): void {\n const timestamp = this.now()\n const isError = notificationType === 'error' || notificationType === 'rate_limit'\n\n this.db.insertEvent({\n session_id: sessionId,\n hook_type: 'Notification',\n tool_name: null,\n tool_input: JSON.stringify({ message, notification_type: notificationType }),\n tool_output: null,\n exit_code: null,\n success: null,\n cwd: null,\n project: null,\n timestamp,\n })\n\n if (isError) {\n this.db.incrementSessionCounters(sessionId, { errors: 1 })\n this.db.incrementDailyActivity(this.today(), { errors: 1 })\n }\n }\n\n recordSubagent(sessionId: string, hookType: string, agentId: string, agentType?: string): void {\n const timestamp = this.now()\n\n this.db.insertEvent({\n session_id: sessionId,\n hook_type: hookType,\n tool_name: null,\n tool_input: JSON.stringify({ agent_id: agentId, agent_type: agentType ?? null }),\n tool_output: null,\n exit_code: null,\n success: null,\n cwd: null,\n project: null,\n timestamp,\n })\n }\n\n recordCompaction(sessionId: string, trigger: string): void {\n const timestamp = this.now()\n\n this.db.insertEvent({\n session_id: sessionId,\n hook_type: 'PreCompact',\n tool_name: null,\n tool_input: JSON.stringify({ trigger }),\n tool_output: null,\n exit_code: null,\n success: null,\n cwd: null,\n project: null,\n timestamp,\n })\n }\n}\n","import fs from 'fs'\nimport readline from 'readline'\nimport type { TokenUsage } from '../types.js'\n\n/**\n * Read a Claude Code transcript JSONL file and sum all token usage.\n *\n * Claude Code writes multiple transcript entries per API call (one per streaming\n * content block), each carrying the same usage object. We deduplicate by message\n * ID so each API call's usage is counted exactly once.\n *\n * Returns null on any failure (missing file, no usage data, parse errors).\n */\nexport async function extractTokenUsage(transcriptPath: string): Promise<TokenUsage | null> {\n try {\n if (!fs.existsSync(transcriptPath)) return null\n\n const stream = fs.createReadStream(transcriptPath, { encoding: 'utf-8' })\n const rl = readline.createInterface({ input: stream, crlfDelay: Infinity })\n\n // Track usage per unique message ID to avoid counting streaming duplicates\n const seenMessages = new Map<string, {\n input_tokens: number\n output_tokens: number\n cache_creation_input_tokens: number\n cache_read_input_tokens: number\n }>()\n\n for await (const line of rl) {\n if (!line.trim()) continue\n try {\n const entry = JSON.parse(line)\n const usage = entry.usage ?? entry.response?.usage ?? entry.message?.usage\n if (usage && typeof usage === 'object' && 'input_tokens' in usage) {\n // Use message ID to deduplicate; fall back to a unique key if absent\n const msgId = entry.message?.id ?? entry.id ?? `_line_${seenMessages.size}`\n // Keep the last occurrence (most complete usage data for this message)\n seenMessages.set(msgId, {\n input_tokens: usage.input_tokens ?? 0,\n output_tokens: usage.output_tokens ?? 0,\n cache_creation_input_tokens: usage.cache_creation_input_tokens ?? 0,\n cache_read_input_tokens: usage.cache_read_input_tokens ?? 0,\n })\n }\n } catch {\n // skip unparseable lines\n }\n }\n\n if (seenMessages.size === 0) return null\n\n let inputTokens = 0\n let outputTokens = 0\n let cacheCreation = 0\n let cacheRead = 0\n for (const u of seenMessages.values()) {\n inputTokens += u.input_tokens\n outputTokens += u.output_tokens\n cacheCreation += u.cache_creation_input_tokens\n cacheRead += u.cache_read_input_tokens\n }\n\n return {\n input_tokens: inputTokens,\n output_tokens: outputTokens,\n cache_creation_input_tokens: cacheCreation,\n cache_read_input_tokens: cacheRead,\n }\n } catch {\n return null\n }\n}\n","/**\n * Gemini CLI hook event normalizer.\n *\n * Translates Gemini CLI hook event names and payloads into bashstats's\n * internal format so the shared handler can process them uniformly.\n */\n\nexport interface NormalizedEvent {\n hookType: string\n payload: Record<string, unknown>\n tokenData?: { totalTokenCount: number }\n}\n\n/**\n * Map a Gemini CLI hook event to a bashstats NormalizedEvent.\n * Returns null for events that have no bashstats equivalent.\n */\nexport function normalizeGeminiEvent(\n geminiEvent: string,\n raw: Record<string, unknown>,\n): NormalizedEvent | null {\n switch (geminiEvent) {\n case 'SessionStart':\n return { hookType: 'SessionStart', payload: raw }\n\n case 'SessionEnd':\n return {\n hookType: 'Stop',\n payload: { ...raw, stop_hook_active: false },\n }\n\n case 'BeforeAgent':\n return { hookType: 'UserPromptSubmit', payload: raw }\n\n case 'BeforeTool':\n return { hookType: 'PreToolUse', payload: raw }\n\n case 'AfterTool':\n return { hookType: 'PostToolUse', payload: raw }\n\n case 'AfterModel': {\n const usageMetadata = (\n raw.llm_response as Record<string, unknown> | undefined\n )?.usageMetadata as Record<string, unknown> | undefined\n\n const totalTokenCount =\n typeof usageMetadata?.totalTokenCount === 'number'\n ? usageMetadata.totalTokenCount\n : undefined\n\n return {\n hookType: 'AfterModel',\n payload: raw,\n ...(totalTokenCount !== undefined ? { tokenData: { totalTokenCount } } : {}),\n }\n }\n\n case 'PreCompress':\n return { hookType: 'PreCompact', payload: raw }\n\n case 'Notification':\n return { hookType: 'Notification', payload: raw }\n\n default:\n return null\n }\n}\n","/**\n * Copilot CLI hook event normalizer.\n *\n * Translates Copilot CLI hook event names and payloads into bashstats's\n * internal format so the shared handler can process them uniformly.\n *\n * Key differences from Claude/Gemini:\n * - Copilot uses camelCase event names (sessionStart, not SessionStart)\n * - toolArgs is a stringified JSON string, not an object\n * - No session_id in payloads -- derived from PPID + date (parent process\n * is the Copilot CLI process, consistent across all hook invocations)\n * - postToolUse can be success OR failure based on toolResult.resultType\n * - errorOccurred maps to PostToolUseFailure with tool_name=\"_error\"\n * - source values: \"new\" -> \"startup\", \"resume\" -> \"resume\"\n */\n\nimport type { NormalizedEvent } from './gemini.js'\n\n/**\n * Safely parse a stringified JSON toolArgs value.\n * Returns {} on any parse failure (malformed JSON, null, undefined, etc.).\n */\nexport function parseToolArgs(toolArgs: string): Record<string, unknown> {\n if (!toolArgs || typeof toolArgs !== 'string') return {}\n try {\n return JSON.parse(toolArgs)\n } catch {\n return {}\n }\n}\n\n/**\n * Derive a session ID for Copilot events.\n * Copilot doesn't provide session_id in hook payloads, so we construct one\n * from the parent process PID (PPID) and the current date (YYYY-MM-DD).\n * Each hook invocation spawns a new child process, but the parent (Copilot CLI)\n * stays the same for the entire session, so PPID is consistent across events.\n */\nfunction deriveSessionId(): string {\n const date = new Date().toISOString().slice(0, 10)\n const ppid = process.ppid ?? process.pid\n return `copilot-${ppid}-${date}`\n}\n\n/**\n * Map Copilot source values to bashstats internal source values.\n * \"new\" -> \"startup\", \"resume\" -> \"resume\", anything else -> \"startup\"\n */\nfunction mapSource(source: unknown): string {\n if (source === 'resume') return 'resume'\n return 'startup'\n}\n\n/**\n * Determine if a postToolUse result represents a failure.\n * resultType of \"failure\" or \"denied\" = failure, everything else = success.\n */\nfunction isToolFailure(toolResult: Record<string, unknown> | undefined): boolean {\n if (!toolResult) return false\n const resultType = toolResult.resultType\n return resultType === 'failure' || resultType === 'denied'\n}\n\n/**\n * Map a Copilot CLI hook event to a bashstats NormalizedEvent.\n * Returns null for events that have no bashstats equivalent.\n */\nexport function normalizeCopilotEvent(\n copilotEvent: string,\n raw: Record<string, unknown>,\n): NormalizedEvent | null {\n const sessionId = deriveSessionId()\n\n switch (copilotEvent) {\n case 'sessionStart': {\n return {\n hookType: 'SessionStart',\n payload: {\n session_id: sessionId,\n source: mapSource(raw.source),\n ...(raw.model !== undefined ? { model: raw.model } : {}),\n },\n }\n }\n\n case 'sessionEnd': {\n return {\n hookType: 'Stop',\n payload: {\n session_id: sessionId,\n ...raw,\n stop_hook_active: false,\n },\n }\n }\n\n case 'userPromptSubmitted': {\n return {\n hookType: 'UserPromptSubmit',\n payload: {\n session_id: sessionId,\n prompt: raw.prompt,\n },\n }\n }\n\n case 'preToolUse': {\n return {\n hookType: 'PreToolUse',\n payload: {\n session_id: sessionId,\n tool_name: raw.toolName as string,\n tool_input: parseToolArgs(raw.toolArgs as string),\n },\n }\n }\n\n case 'postToolUse': {\n const toolResult = (raw.toolResult as Record<string, unknown>) ?? {}\n const failed = isToolFailure(\n raw.toolResult as Record<string, unknown> | undefined,\n )\n\n return {\n hookType: failed ? 'PostToolUseFailure' : 'PostToolUse',\n payload: {\n session_id: sessionId,\n tool_name: raw.toolName as string,\n tool_input: parseToolArgs(raw.toolArgs as string),\n tool_response: toolResult,\n exit_code: failed ? 1 : 0,\n },\n }\n }\n\n case 'errorOccurred': {\n const error = (raw.error as Record<string, unknown>) ?? {}\n return {\n hookType: 'PostToolUseFailure',\n payload: {\n session_id: sessionId,\n tool_name: '_error',\n tool_input: {},\n tool_response: {\n error_message: (error.message as string) ?? '',\n error_name: (error.name as string) ?? '',\n },\n exit_code: 1,\n },\n }\n }\n\n default:\n return null\n }\n}\n"],"mappings":";;;AAAA,OAAOA,WAAU;AACjB,OAAO,QAAQ;AACf,OAAOC,SAAQ;;;ACgRR,IAAM,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