forked from rar-file/claude-rpc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner.js
More file actions
1291 lines (1226 loc) · 52.7 KB
/
Copy pathscanner.js
File metadata and controls
1291 lines (1226 loc) · 52.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { readdirSync, readFileSync, statSync, existsSync, writeFileSync, mkdirSync, openSync, readSync, closeSync, realpathSync } from 'node:fs';
import { join, dirname, basename } from 'node:path';
import { homedir } from 'node:os';
import { CLAUDE_PROJECTS, SCAN_CACHE_PATH, AGGREGATE_PATH, DATA_DIR, EVENTS_LOG_PATH } from './paths.js';
import { languageOf } from './languages.js';
import { costFor, pricingKeyFor } from './pricing.js';
import { classifyShip } from './ships.js';
import { renameSyncRetry } from './atomic-rename.js';
// Bumping this forces a full re-parse on next scan. Increment whenever the
// per-transcript summary schema changes in a way old caches can't satisfy.
// v5: per-day ships/shipKinds + per-day project attribution (recap).
// v6: day/week/hour buckets carry firstTs/lastTs (they were declared but
// never assigned, leaving {startTimeLabel} permanently blank).
// v7: per-day byModel buckets in transcript summaries — bump forces the one
// full rescan that backfills model-mix history for already-scanned files.
const CACHE_VERSION = 7;
// Cap counted gap between consecutive timestamps. Anything larger is treated
// as the user walking away — we count only what's plausibly active time.
const ACTIVE_GAP_CAP_MS = 5 * 60 * 1000;
// Local-time YYYY-MM-DD key for bucketing.
function dayKey(ts) {
const d = new Date(ts);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
// ISO week key like "2026-W21" using local time. Monday-start.
function weekKey(ts) {
const d = new Date(ts);
d.setHours(0, 0, 0, 0);
// ISO 8601: week starts Monday; week 1 contains Jan 4.
const day = (d.getDay() + 6) % 7; // Mon = 0
d.setDate(d.getDate() - day + 3); // move to Thursday of this week
const firstThursday = new Date(d.getFullYear(), 0, 4);
const week = 1 + Math.round(((d - firstThursday) / 86_400_000 - 3 + ((firstThursday.getDay() + 6) % 7)) / 7);
return `${d.getFullYear()}-W${String(week).padStart(2, '0')}`;
}
function hourKey(ts) {
return new Date(ts).getHours();
}
// Reject malformed or implausible transcript timestamps before they poison
// firstTs/lastTs (which drive wallMs) and the day/week/hour buckets. A NaN from
// a bad string, a year-0 epoch artifact, or a far-future entry from a skewed
// clock would otherwise inflate lifetime totals. Floor: before Claude Code
// could plausibly exist. Ceiling: now + a generous clock-skew margin.
const TS_FLOOR = Date.UTC(2020, 0, 1);
const TS_SKEW_MS = 48 * 60 * 60 * 1000;
function parseTs(raw) {
if (!raw) return null;
const t = Date.parse(raw);
if (!Number.isFinite(t)) return null;
if (t < TS_FLOOR || t > Date.now() + TS_SKEW_MS) return null;
return t;
}
// Calendar day index (whole days since the Unix epoch) anchored at UTC noon.
// Subtracting two of these always yields an exact number of calendar days —
// immune to DST, where subtracting two local-midnight Dates gives a 23h or 25h
// span that Math.floor/Math.round can turn into an off-by-one day.
function dayNum(y, mZeroBased, d) {
return Math.floor(Date.UTC(y, mZeroBased, d, 12) / 86_400_000);
}
function dayKeyNum(key) {
const [y, m, d] = key.split('-').map(Number);
return dayNum(y, m - 1, d);
}
const EDITING_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit']);
// First non-env token of a shell command. `FOO=bar git status` → `git`.
// Strips `sudo`, `time`, and tee-style decorators that aren't the "real" command.
function firstShellToken(cmd) {
if (!cmd || typeof cmd !== 'string') return '';
// Strip leading whitespace + env assignments (VAR=value chains).
const stripped = cmd.replace(/^\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S+\s+)+/, '').trim();
// First token, then strip path: `/usr/bin/python3` → `python3`.
let first = stripped.split(/\s+/)[0] || '';
if (first === 'sudo' || first === 'time') {
const rest = stripped.slice(first.length).trim();
return firstShellToken(rest);
}
// Drop pipe/redirect prefix oddities and trailing chars.
first = first.replace(/^[`(]+|[`)]+$/g, '');
const slash = first.lastIndexOf('/');
if (slash !== -1) first = first.slice(slash + 1);
return first.toLowerCase();
}
function domainOf(url) {
if (!url || typeof url !== 'string') return '';
try {
const u = new URL(url);
return u.hostname.replace(/^www\./, '');
} catch {
const m = url.match(/^https?:\/\/([^/?#]+)/i);
return m ? m[1].replace(/^www\./, '') : '';
}
}
function countLines(text) {
if (!text || typeof text !== 'string') return 0;
// Treat empty trailing newline as not contributing — line count is the
// number of "\n"-separated chunks that actually have content, plus one for
// the final segment if non-empty.
if (text === '') return 0;
const lines = text.split('\n');
// Drop a single trailing empty string from a trailing newline.
if (lines.length && lines[lines.length - 1] === '') lines.pop();
return lines.length;
}
// Trailing ISO-ish datetime suffix (e.g. "-2026-04-25T185311Z"). When a cwd's
// basename ends with one of these, collapse it so all "archive-*" snapshots
// aggregate under a single project name.
export const DATE_SUFFIX_RE = /[-_.]\d{4}[-_.]?\d{2}[-_.]?\d{2}(?:[Tt._-]?\d{0,6})?Z?$/;
export function cleanProjectName(name) {
if (!name) return name;
return name.replace(DATE_SUFFIX_RE, '') || name;
}
function blankDay() {
return {
activeMs: 0,
userMessages: 0,
toolCalls: 0,
inputTokens: 0,
outputTokens: 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
sessions: 0,
linesAdded: 0,
linesRemoved: 0,
cost: 0,
notifications: 0,
ships: 0,
firstTs: null,
lastTs: null,
// Day buckets may also lazily carry:
// shipKinds — { push|commit|pr|issue|tag → count } (only when a ship lands)
// projects — { name → { activeMs, tokens } } (aggregate-level only,
// attributed at merge time where the file's project is known)
// byModel — { pricingKey → { turns, tokens, cost } } (day buckets only —
// week/hour stay lean; powers model-mix-over-time)
};
}
function mergeDay(target, src) {
target.activeMs += src.activeMs || 0;
target.userMessages += src.userMessages || 0;
target.toolCalls += src.toolCalls || 0;
target.inputTokens += src.inputTokens || 0;
target.outputTokens += src.outputTokens || 0;
target.cacheReadTokens += src.cacheReadTokens || 0;
target.cacheWriteTokens += src.cacheWriteTokens || 0;
target.sessions += src.sessions || 0;
target.linesAdded += src.linesAdded || 0;
target.linesRemoved += src.linesRemoved || 0;
target.cost += src.cost || 0;
target.notifications += src.notifications || 0;
target.ships += src.ships || 0;
for (const [k, n] of Object.entries(src.shipKinds || {})) {
(target.shipKinds ||= {})[k] = (target.shipKinds[k] || 0) + n;
}
for (const [m, v] of Object.entries(src.byModel || {})) {
const t = ((target.byModel ||= {})[m] ||= { turns: 0, tokens: 0, cost: 0 });
t.turns += v.turns || 0;
t.tokens += v.tokens || 0;
t.cost += v.cost || 0;
}
if (src.firstTs && (!target.firstTs || src.firstTs < target.firstTs)) target.firstTs = src.firstTs;
if (src.lastTs && (!target.lastTs || src.lastTs > target.lastTs)) target.lastTs = src.lastTs;
}
function ensureDataDir() {
if (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR, { recursive: true });
}
function safeJson(line) {
try { return JSON.parse(line); } catch { return null; }
}
function isRealUserMessage(record) {
if (record.type !== 'user' || record.isMeta) return false;
const c = record.message?.content;
if (typeof c === 'string') {
if (c.startsWith('<local-command') || c.startsWith('<system-reminder') || c.startsWith('<command-')) return false;
return c.trim().length > 0;
}
if (Array.isArray(c)) {
const hasToolResult = c.some((b) => b.type === 'tool_result');
if (hasToolResult) return false;
return c.some((b) => b.type === 'text' && String(b.text || '').trim().length > 0);
}
return false;
}
function collectFilePath(input = {}) {
return input.file_path || input.path || input.notebook_path || null;
}
// Iterate newline-delimited lines of a string without materializing the full
// `.split('\n')` array (a second full-size copy of the file). Peak overhead is
// one line slice instead of N strings — meaningful for multi-MB transcripts.
function* iterLines(raw) {
let start = 0;
let nl;
while ((nl = raw.indexOf('\n', start)) !== -1) {
yield raw.slice(start, nl);
start = nl + 1;
}
if (start < raw.length) yield raw.slice(start);
}
// Read up to `maxBytes` from the head of a file without loading the whole
// thing. Used to pull the cwd from a transcript's first lines — reading a
// multi-MB transcript in full just to inspect its head was pure waste.
function readHead(path, maxBytes = 65536) {
let fd;
try {
fd = openSync(path, 'r');
const buf = Buffer.allocUnsafe(maxBytes);
const n = readSync(fd, buf, 0, maxBytes, 0);
return buf.toString('utf8', 0, n);
} finally {
if (fd !== undefined) {
try { closeSync(fd); } catch { /* already closed */ }
}
}
}
function blankTranscriptSummary() {
return {
sessionId: null,
project: null,
cwd: null,
model: null,
inputTokens: 0,
outputTokens: 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
userMessages: 0,
toolCalls: 0,
toolBreakdown: {},
files: [],
firstTs: null,
lastTs: null,
activeMs: 0,
byDay: {}, // day-key → blankDay
byWeek: {}, // ISO week key → blankDay
byHour: {}, // hour-of-day (0..23) → blankDay
fileEdits: {}, // absolute path → edit count
fileEditTs: {}, // absolute path → most-recent edit timestamp (hotspot aging)
// Phase 1 enrichments
linesAdded: 0,
linesRemoved: 0,
bashCommands: {}, // first token → count
webDomains: {}, // hostname → count
subagents: {}, // subagent_type → count
ships: 0, // shipped-command count (git commit/push, gh pr/issue/release create)
shipKinds: {}, // ship kind → count
cost: 0, // estimated USD
costByModel: {}, // pricing key → USD
modelsUsed: {}, // raw model id → assistant turns
byModel: {}, // pricing key → { turns, tokens, cost } (model split)
};
}
// Sliding window for assistant message-id dedup (see parseChunkInto). Blocks
// of one message land on ADJACENT lines, so a small window catches every real
// split while staying cheap to persist in the scan cache.
const RECENT_IDS_MAX = 200;
// Parse complete JSONL lines into `summary`, mutating it in place. `pstate`
// carries the cross-chunk bookkeeping that incremental (append-only) parsing
// needs to behave exactly like a full parse:
// recentIds — recently counted assistant message.ids. Claude Code splits
// one assistant message (a single message.id) across several
// JSONL lines — one per content block — repeating the SAME
// `usage` object on every line. Token/cost/turn counting must
// happen once per message.id, or a 3-block turn counts 3×.
// Content blocks themselves are distinct per line, so those
// stay counted per line.
// lastRec — the previous chunk's final timestamped record, so the
// active-time gap across a chunk boundary still accrues.
function parseChunkInto(text, summary, pstate) {
const fileSet = new Set(summary.files || []);
// Records in their original order, retaining timestamps for per-day bucketing.
const records = [];
for (const line of iterLines(text)) {
if (!line) continue;
const r = safeJson(line);
if (!r) continue;
if (r.sessionId && !summary.sessionId) summary.sessionId = r.sessionId;
if (r.cwd && !summary.cwd) {
summary.cwd = r.cwd;
summary.project = cleanProjectName(basename(r.cwd));
}
const ts = parseTs(r.timestamp);
const day = ts ? dayKey(ts) : null;
const week = ts ? weekKey(ts) : null;
const hour = ts ? hourKey(ts) : null;
const dayBucket = day ? (summary.byDay[day] ||= blankDay()) : null;
const weekBucket = week ? (summary.byWeek[week] ||= blankDay()) : null;
const hourBucket = hour !== null ? (summary.byHour[hour] ||= blankDay()) : null;
const allBuckets = [dayBucket, weekBucket, hourBucket].filter(Boolean);
// First/last activity within each bucket — blankDay declares these and
// mergeDay merges them, but nothing assigned them, so "started 09:14"-style
// labels never rendered.
if (ts) {
for (const bucket of allBuckets) {
if (!bucket.firstTs || ts < bucket.firstTs) bucket.firstTs = ts;
if (!bucket.lastTs || ts > bucket.lastTs) bucket.lastTs = ts;
}
}
if (r.type === 'assistant') {
const turnModel = r.message?.model || summary.model;
const u = r.message?.usage;
// Count usage/cost/turn only the first time we see this message.id (see
// the pstate.recentIds note above). No id (rare/legacy) → count it.
const msgId = r.message?.id;
const firstSeen = !msgId || !pstate.recentIds.includes(msgId);
if (msgId && firstSeen) {
pstate.recentIds.push(msgId);
if (pstate.recentIds.length > RECENT_IDS_MAX) pstate.recentIds.shift();
}
// Per-model split bucket, keyed by pricing key so cost/tokens/turns align.
const mkey = turnModel ? pricingKeyFor(turnModel) : null;
const mb = mkey ? (summary.byModel[mkey] ||= { turns: 0, tokens: 0, cost: 0 }) : null;
if (u && firstSeen) {
summary.inputTokens += u.input_tokens || 0;
summary.outputTokens += u.output_tokens || 0;
summary.cacheReadTokens += u.cache_read_input_tokens || 0;
summary.cacheWriteTokens += u.cache_creation_input_tokens || 0;
for (const bucket of allBuckets) {
bucket.inputTokens += u.input_tokens || 0;
bucket.outputTokens += u.output_tokens || 0;
bucket.cacheReadTokens += u.cache_read_input_tokens || 0;
bucket.cacheWriteTokens += u.cache_creation_input_tokens || 0;
}
if (mb) {
mb.tokens += (u.input_tokens || 0) + (u.output_tokens || 0)
+ (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);
}
// Per-day model split (day granularity only — week/hour stay lean).
// Powers model-mix-over-time; the all-time byModel can't trend.
if (mkey && dayBucket) {
const dm = ((dayBucket.byModel ||= {})[mkey] ||= { turns: 0, tokens: 0, cost: 0 });
dm.tokens += (u.input_tokens || 0) + (u.output_tokens || 0)
+ (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);
}
// Per-turn cost — uses this turn's model id, not the session's first-seen one.
const turnCost = costFor({ model: turnModel, usage: u });
if (turnCost > 0) {
summary.cost += turnCost;
// When the turn has no model id, mkey is null but costFor charged it
// at sonnet rates (pricing's default) — bucket it under 'sonnet', not
// a literal "null" key that renders as a "null" bar on the dashboard.
const ck = mkey || 'sonnet';
summary.costByModel[ck] = (summary.costByModel[ck] || 0) + turnCost;
if (mb) mb.cost += turnCost;
if (dayBucket) {
const dm = ((dayBucket.byModel ||= {})[ck] ||= { turns: 0, tokens: 0, cost: 0 });
dm.cost += turnCost;
}
for (const bucket of allBuckets) bucket.cost += turnCost;
}
}
if (turnModel) {
if (!summary.model) summary.model = turnModel;
if (firstSeen) {
summary.modelsUsed[turnModel] = (summary.modelsUsed[turnModel] || 0) + 1;
if (mb) mb.turns += 1;
if (mkey && dayBucket) {
const dm = ((dayBucket.byModel ||= {})[mkey] ||= { turns: 0, tokens: 0, cost: 0 });
dm.turns += 1;
}
}
}
const blocks = r.message?.content || [];
for (const b of blocks) {
if (b.type === 'tool_use') {
summary.toolCalls += 1;
summary.toolBreakdown[b.name] = (summary.toolBreakdown[b.name] || 0) + 1;
for (const bucket of allBuckets) bucket.toolCalls += 1;
const input = b.input || {};
const f = collectFilePath(input);
if (f) {
fileSet.add(f);
if (EDITING_TOOLS.has(b.name)) {
summary.fileEdits[f] = (summary.fileEdits[f] || 0) + 1;
if (ts && ts > (summary.fileEditTs[f] || 0)) summary.fileEditTs[f] = ts;
}
}
// Code churn — lines added/removed. For Edit, we count
// new_string / old_string lines once; `replace_all` would technically
// multiply by the number of occurrences in the target file, but we
// can't see file contents here, so we under-count those uniformly.
if (b.name === 'Edit') {
const adds = countLines(input.new_string);
const rems = countLines(input.old_string);
summary.linesAdded += adds;
summary.linesRemoved += rems;
for (const bucket of allBuckets) {
bucket.linesAdded += adds;
bucket.linesRemoved += rems;
}
} else if (b.name === 'MultiEdit') {
// One MultiEdit carries N independent edits; sum their churn the
// same way Edit does. (File-edit count above already credited it
// once, the right granularity for hotspots.)
for (const e of (Array.isArray(input.edits) ? input.edits : [])) {
const adds = countLines(e.new_string);
const rems = countLines(e.old_string);
summary.linesAdded += adds;
summary.linesRemoved += rems;
for (const bucket of allBuckets) {
bucket.linesAdded += adds;
bucket.linesRemoved += rems;
}
}
} else if (b.name === 'Write') {
const adds = countLines(input.content);
summary.linesAdded += adds;
for (const bucket of allBuckets) bucket.linesAdded += adds;
} else if (b.name === 'NotebookEdit') {
const adds = countLines(input.new_source);
summary.linesAdded += adds;
for (const bucket of allBuckets) bucket.linesAdded += adds;
} else if (b.name === 'Bash') {
const cmd = firstShellToken(input.command);
if (cmd) summary.bashCommands[cmd] = (summary.bashCommands[cmd] || 0) + 1;
const shipKind = classifyShip(input.command);
if (shipKind) {
summary.ships = (summary.ships || 0) + 1;
summary.shipKinds[shipKind] = (summary.shipKinds[shipKind] || 0) + 1;
for (const bucket of allBuckets) bucket.ships = (bucket.ships || 0) + 1;
if (dayBucket) (dayBucket.shipKinds ||= {})[shipKind] = (dayBucket.shipKinds[shipKind] || 0) + 1;
}
} else if (b.name === 'WebFetch' || b.name === 'WebSearch') {
const host = b.name === 'WebFetch' ? domainOf(input.url) : '';
if (host) summary.webDomains[host] = (summary.webDomains[host] || 0) + 1;
} else if (b.name === 'Agent' || b.name === 'Task') {
const kind = input.subagent_type || 'general-purpose';
summary.subagents[kind] = (summary.subagents[kind] || 0) + 1;
}
}
}
} else if (isRealUserMessage(r)) {
summary.userMessages += 1;
for (const bucket of allBuckets) bucket.userMessages += 1;
}
if (ts) records.push({ ts, day, week, hour });
}
summary.files = Array.from(fileSet);
if (records.length) {
records.sort((a, b) => a.ts - b.ts);
if (!summary.firstTs || records[0].ts < summary.firstTs) summary.firstTs = records[0].ts;
const chunkLast = records[records.length - 1].ts;
if (!summary.lastTs || chunkLast > summary.lastTs) summary.lastTs = chunkLast;
// Charge each gap's active time to the day/week/hour of the earlier
// record. The first record's "earlier" is the previous chunk's last.
let prev = pstate.lastRec;
for (const rec of records) {
if (prev) {
const gap = rec.ts - prev.ts;
if (gap > 0 && gap < ACTIVE_GAP_CAP_MS) {
summary.activeMs += gap;
if (prev.day) (summary.byDay[prev.day] ||= blankDay()).activeMs += gap;
if (prev.week) (summary.byWeek[prev.week] ||= blankDay()).activeMs += gap;
if (prev.hour !== null && prev.hour !== undefined) {
(summary.byHour[prev.hour] ||= blankDay()).activeMs += gap;
}
}
}
prev = rec;
}
pstate.lastRec = prev;
}
}
// Parse a single transcript JSONL into a per-file summary.
//
// With a prior cache entry (`prev`), parses only the bytes appended since the
// last scan — transcripts are append-only, and an active session's multi-MB
// file otherwise gets fully re-read every rescan tick. The entry carries
// `_offset` (bytes consumed through the last complete line) and `_parse`
// (the cross-chunk bookkeeping for parseChunkInto); anything that breaks the
// append assumption (file shrank, entry predates these fields, `_offset`
// null) falls back to a from-scratch parse.
export function parseTranscript(filePath, prev = null) {
const st = statSync(filePath);
// Append only if this is the SAME file that grew: the current size must be
// >= the size at the last parse (mirrors readSessionTokens). The old check,
// `st.size >= prev._offset`, was too weak — a rewrite to a size between the
// consumed offset and the prior file size would wrongly append onto stale
// counts (the leading bytes are now different content), silently corrupting
// lifetime stats. A cache entry predating _size has no size to compare, so it
// falls back to a full re-parse (which then stamps _size going forward).
const canAppend = !!(prev && prev._parse && typeof prev._offset === 'number'
&& typeof prev._size === 'number' && st.size >= prev._size);
const summary = canAppend ? structuredClone(prev) : blankTranscriptSummary();
const pstate = canAppend
? { recentIds: (prev._parse.recentIds || []).slice(), lastRec: prev._parse.lastRec || null }
: { recentIds: [], lastRec: null };
const startOffset = canAppend ? prev._offset : 0;
let text = '';
const len = st.size - startOffset;
if (len > 0) {
let fd;
try {
fd = openSync(filePath, 'r');
const buf = Buffer.allocUnsafe(len);
const n = readSync(fd, buf, 0, len, startOffset);
text = buf.toString('utf8', 0, n);
} finally {
if (fd !== undefined) {
try { closeSync(fd); } catch { /* already closed */ }
}
}
}
// Consume through the last newline; \n is single-byte ASCII so the boundary
// is exact even with multi-byte content in the lines.
const lastNl = text.lastIndexOf('\n');
const complete = lastNl === -1 ? '' : text.slice(0, lastNl + 1);
const remainder = lastNl === -1 ? text : text.slice(lastNl + 1);
parseChunkInto(complete, summary, pstate);
let offset = startOffset + Buffer.byteLength(complete, 'utf8');
if (remainder.trim()) {
if (safeJson(remainder) !== null) {
// A complete final line that just isn't newline-terminated (fully
// written file). Count it, but mark the entry non-appendable — if more
// bytes ever land we can't tell whether they extend this line.
parseChunkInto(remainder, summary, pstate);
offset = null;
}
// else: a partial line mid-write — leave it for the next (append) read.
}
summary._offset = offset;
summary._size = st.size; // file size at this parse — guards the append fast-path above
summary._parse = { recentIds: pstate.recentIds, lastRec: pstate.lastRec };
return summary;
}
function listTranscripts(projectsDir) {
if (!existsSync(projectsDir)) return [];
const results = [];
const walk = (dir) => {
let entries;
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
for (const e of entries) {
const full = join(dir, e.name);
if (e.isDirectory()) walk(full);
else if (e.isFile() && e.name.endsWith('.jsonl')) results.push(full);
}
};
walk(projectsDir);
return results;
}
// Walk multiple project roots in one pass. Used by scan() to support
// `additionalProjectsDirs` config + the `claude-rpc backfill <path>` command
// for ad-hoc imports. Deduplicates by absolute path so overlapping roots
// don't double-count.
function listAllTranscripts(dirs) {
const all = new Set();
for (const d of dirs) {
for (const fp of listTranscripts(d)) all.add(fp);
}
return Array.from(all);
}
function isSubagentPath(p) {
return /[\\/]subagents[\\/]/.test(p);
}
// The daemon runs for weeks; these per-transcript caches would otherwise grow
// one entry per file ever observed. LRU with a generous cap — the hot set is
// the handful of live sessions, so an eviction just costs one re-read.
const CACHE_MAX_ENTRIES = 512;
function lruTouch(map, key, value) {
if (map.has(key)) map.delete(key);
map.set(key, value);
if (map.size > CACHE_MAX_ENTRIES) map.delete(map.keys().next().value);
}
// Pull the real cwd from the head of a transcript so live sessions can show
// "my-app" instead of the slugified directory name.
const cwdCache = new Map(); // path → { mtime, cwd }
function readTranscriptCwd(path, mtimeMs) {
const cached = cwdCache.get(path);
if (cached && cached.mtime === mtimeMs) {
lruTouch(cwdCache, path, cached);
return cached.cwd;
}
let cwd = null;
try {
let seen = 0;
for (const line of iterLines(readHead(path))) {
if (++seen > 25) break;
if (!line) continue;
const r = safeJson(line);
if (r?.cwd) { cwd = r.cwd; break; }
}
} catch { /* transcript head unreadable — cwd stays null, project name falls back to slug */ }
lruTouch(cwdCache, path, { mtime: mtimeMs, cwd });
return cwd;
}
// Per-transcript token cache. Reading a multi-MB .jsonl on every push tick
// (4s) would be wasteful, so we only re-parse when the file's mtime has
// advanced since the last read.
const sessionTokenCache = new Map(); // path → { mtime, size, offset, tokens, seenIds, model }
// Accumulate assistant-usage tokens from a chunk of complete JSONL lines.
// Claude Code repeats the same `usage` object on every content-block line of
// one assistant message, so count each message.id once (`seenIds`, the same
// bounded-ring dedup parseChunkInto uses) — otherwise the live count drifts
// above the lifetime aggregate on multi-block turns. Lines with no id
// (rare/legacy) are counted every time, matching the full scanner. Also
// captures the newest turn's model so a mid-session /model switch is visible.
function sumUsageLines(text, tokens, seenIds, meta) {
for (const line of iterLines(text)) {
if (!line) continue;
const r = safeJson(line);
if (!r || r.type !== 'assistant') continue;
if (meta && r.message?.model) meta.model = r.message.model;
const u = r.message?.usage;
if (!u) continue;
const msgId = r.message?.id;
if (msgId && seenIds) {
if (seenIds.includes(msgId)) continue;
seenIds.push(msgId);
if (seenIds.length > RECENT_IDS_MAX) seenIds.shift();
}
tokens.input += u.input_tokens || 0;
tokens.output += u.output_tokens || 0;
tokens.cacheRead += u.cache_read_input_tokens || 0;
tokens.cacheWrite += u.cache_creation_input_tokens || 0;
}
}
// Sum input/output/cache tokens from a single transcript JSONL.
//
// We need this because Claude Code's hook payloads don't carry usage data —
// tokens are an assistant-message field, not a tool-call field, so PostToolUse
// hooks fire with no `usage` block to capture. The live transcript is the
// only source of truth for the current session's running token count.
//
// Returns null when the file can't be read; { input, output, cacheRead,
// cacheWrite } otherwise. Cached by mtime — repeat calls with no file
// activity are O(1).
export function readSessionTokens(path) {
let st;
try { st = statSync(path); } catch { return null; }
const cached = sessionTokenCache.get(path);
if (cached && cached.mtime === st.mtimeMs) {
lruTouch(sessionTokenCache, path, cached);
return cached.tokens;
}
// Transcripts are append-only JSONL. If the file only grew since the last
// read, parse just the appended tail from the cached byte offset instead of
// re-reading the whole (growing) file on every 4s daemon tick. Anything else
// (shrunk/truncated/rewritten) falls back to a full re-read.
const canAppend = cached && st.size >= cached.size && cached.offset <= st.size;
const tokens = canAppend
? { ...cached.tokens }
: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
const seenIds = canAppend ? (cached.seenIds || []) : [];
const meta = { model: canAppend ? cached.model : null };
const startOffset = canAppend ? cached.offset : 0;
let newOffset = startOffset;
let fd;
try {
fd = openSync(path, 'r');
const len = st.size - startOffset;
if (len > 0) {
const buf = Buffer.allocUnsafe(len);
const n = readSync(fd, buf, 0, len, startOffset);
const text = buf.toString('utf8', 0, n);
// Only consume through the last newline; a trailing partial line is left
// for a later read (offset stays before it). \n is single-byte ASCII so
// the boundary is exact even with multi-byte content in the lines.
const lastNl = text.lastIndexOf('\n');
if (lastNl !== -1) {
const complete = text.slice(0, lastNl + 1);
newOffset = startOffset + Buffer.byteLength(complete, 'utf8');
sumUsageLines(complete, tokens, seenIds, meta);
}
}
} catch {
return null;
} finally {
if (fd !== undefined) {
try { closeSync(fd); } catch { /* already closed */ }
}
}
lruTouch(sessionTokenCache, path, { mtime: st.mtimeMs, size: st.size, offset: newOffset, tokens, seenIds, model: meta.model });
return tokens;
}
// Latest assistant-turn model seen in a transcript — the live answer to "which
// model is this session on NOW". SessionStart is the only hook that carries a
// model, so a mid-session /model switch never reaches the state file; the
// transcript is the only source of truth. Piggybacks on readSessionTokens'
// cache entry (same parse, same mtime discipline) — call it AFTER
// readSessionTokens for O(1); standalone calls populate the cache themselves.
export function readSessionModel(path) {
const cached = sessionTokenCache.get(path);
let mtime;
try { mtime = statSync(path).mtimeMs; } catch { return null; }
if (!cached || cached.mtime !== mtime) {
if (readSessionTokens(path) === null) return null;
}
return sessionTokenCache.get(path)?.model || null;
}
// Detect live sessions by transcript mtime. Returns array of { path, project, cwd, mtime, ageSec }.
// A session is "live" if its .jsonl was modified within thresholdMs.
// Roots default to the same set scan() uses — the canonical ~/.claude/projects
// plus any discovered alt locations — so live presence, concurrent-session
// detection, the web API, doctor and the TUI don't go silent on XDG-strict /
// AppData / Library-relocated installs. Legacy single-root `projectsDir` and
// explicit multi-root `projectsDirs` are both still accepted.
export function findLiveSessions({ projectsDir, projectsDirs, thresholdMs = 90_000 } = {}) {
const dirs = projectsDirs && projectsDirs.length ? projectsDirs
: projectsDir ? [projectsDir]
: [CLAUDE_PROJECTS, ...discoverAltProjectDirs()];
const now = Date.now();
const live = [];
for (const root of dirs) {
if (!existsSync(root)) continue;
let projects;
try { projects = readdirSync(root); } catch { continue; }
for (const proj of projects) {
const projPath = join(root, proj);
let entries;
try { entries = readdirSync(projPath, { withFileTypes: true }); } catch { continue; }
for (const e of entries) {
// Only top-level transcripts count as sessions, not subagent files.
if (!e.isFile() || !e.name.endsWith('.jsonl')) continue;
const full = join(projPath, e.name);
let st;
try { st = statSync(full); } catch { continue; }
const age = now - st.mtimeMs;
if (age <= thresholdMs) {
const cwd = readTranscriptCwd(full, st.mtimeMs);
const project = cleanProjectName(cwd ? basename(cwd) : proj);
live.push({ path: full, project, cwd: cwd || '', mtime: st.mtimeMs, ageSec: Math.round(age / 1000) });
}
}
}
}
live.sort((a, b) => b.mtime - a.mtime);
return live;
}
function readCache() {
ensureDataDir();
if (!existsSync(SCAN_CACHE_PATH)) return { _v: CACHE_VERSION, files: {} };
try {
const raw = JSON.parse(readFileSync(SCAN_CACHE_PATH, 'utf8'));
if (!raw || raw._v !== CACHE_VERSION) return { _v: CACHE_VERSION, files: {} };
return raw;
} catch { return { _v: CACHE_VERSION, files: {} }; }
}
function writeCache(cache) {
ensureDataDir();
cache._v = CACHE_VERSION;
// Pid-suffixed like state.js: the daemon's background rescan and a user-run
// `claude-rpc scan` can overlap, and a shared tmp name lets one writer's
// rename land a half-written file (or ENOENT the other's rename).
const tmp = `${SCAN_CACHE_PATH}.${process.pid}.tmp`;
writeFileSync(tmp, JSON.stringify(cache));
renameSyncRetry(tmp, SCAN_CACHE_PATH);
}
// Per-day notification counts come from a hook-side append log, since
// transcripts don't carry Notification events reliably.
function readEventsByDay() {
const out = { notifications: {}, compactions: {} };
// The hook rotates events.jsonl to `.1` at 5MB; read both (oldest first) so a
// rotation doesn't silently drop a day's counts. PreCompact events have been
// appended since the hook first shipped them — counting them here finally
// surfaces how hard sessions push context.
for (const path of [EVENTS_LOG_PATH + '.1', EVENTS_LOG_PATH]) {
if (!existsSync(path)) continue;
try {
const raw = readFileSync(path, 'utf8');
for (const line of raw.split('\n')) {
if (!line) continue;
const e = safeJson(line);
if (!e || !e.ts) continue;
const bucket = e.type === 'notification' ? out.notifications
: e.type === 'precompact' ? out.compactions
: null;
if (!bucket) continue;
const k = dayKey(e.ts);
bucket[k] = (bucket[k] || 0) + 1;
}
} catch { /* a rotation file unreadable/truncated — count what we can */ }
}
return out;
}
export function writeAggregate(agg) {
ensureDataDir();
const tmp = `${AGGREGATE_PATH}.${process.pid}.tmp`;
writeFileSync(tmp, JSON.stringify(agg, null, 2));
renameSyncRetry(tmp, AGGREGATE_PATH);
}
export function readAggregate() {
if (!existsSync(AGGREGATE_PATH)) return null;
try { return JSON.parse(readFileSync(AGGREGATE_PATH, 'utf8')); }
catch { return null; }
}
export { dayKey, weekKey, hourKey };
export function aggregateFrom(cache) {
const agg = {
sessions: 0,
subagentRuns: 0,
subagentActiveMs: 0,
// Session-length distribution (ACTIVE time, top-level sessions only —
// subagents overlap their parent). Wall clock was tried first and lies:
// a transcript left open across a week reads as a 170h "session".
// activeMs already excludes ≥5-min gaps, so it measures the sitting, not
// the tab. Histogram, not raw durations, to keep aggregate.json lean.
sessionLengths: {
count: 0, totalMs: 0, longestMs: 0,
buckets: { lt15m: 0, m15to30: 0, m30to60: 0, h1to2: 0, h2to4: 0, gt4h: 0 },
},
inputTokens: 0,
outputTokens: 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
userMessages: 0,
toolCalls: 0,
toolBreakdown: {},
projects: {},
activeMs: 0,
wallMs: 0,
uniqueFiles: 0,
firstTs: null,
lastTs: null,
byDay: {},
byWeek: {},
byHour: {},
byWeekday: {},
fileEdits: {},
fileEditTs: {},
streak: 0,
longestStreak: 0,
daysSinceFirst: 0,
bestDay: null,
peakHour: null,
topEditedFiles: [],
// Phase 1 enrichments
linesAdded: 0,
linesRemoved: 0,
linesNet: 0,
ships: 0,
shipKinds: {},
bashCommands: {},
webDomains: {},
subagents: {},
languages: {},
mcpToolCalls: 0,
builtinToolCalls: 0,
estimatedCost: 0,
costByModel: {},
modelsUsed: {},
byModel: {},
modelSplit: [],
notifications: 0,
generatedAt: Date.now(),
_v: CACHE_VERSION,
};
const fileSet = new Set();
for (const [path, summary] of Object.entries(cache.files)) {
if (!summary) continue;
const isSub = summary.isSubagent ?? isSubagentPath(path);
// Tokens and tools always count.
agg.inputTokens += summary.inputTokens || 0;
agg.outputTokens += summary.outputTokens || 0;
agg.cacheReadTokens += summary.cacheReadTokens || 0;
agg.cacheWriteTokens += summary.cacheWriteTokens || 0;
agg.toolCalls += summary.toolCalls || 0;
for (const [name, count] of Object.entries(summary.toolBreakdown || {})) {
agg.toolBreakdown[name] = (agg.toolBreakdown[name] || 0) + count;
}
for (const f of summary.files || []) fileSet.add(f);
// Lines/cost from this transcript roll up regardless of subagent vs top-level
// — they represent real work done by Claude.
agg.linesAdded += summary.linesAdded || 0;
agg.linesRemoved += summary.linesRemoved || 0;
agg.ships += summary.ships || 0;
for (const [k, n] of Object.entries(summary.shipKinds || {})) {
agg.shipKinds[k] = (agg.shipKinds[k] || 0) + n;
}
agg.estimatedCost += summary.cost || 0;
for (const [m, v] of Object.entries(summary.costByModel || {})) {
agg.costByModel[m] = (agg.costByModel[m] || 0) + v;
}
for (const [m, v] of Object.entries(summary.modelsUsed || {})) {
agg.modelsUsed[m] = (agg.modelsUsed[m] || 0) + v;
}
for (const [m, v] of Object.entries(summary.byModel || {})) {
const t = agg.byModel[m] ||= { turns: 0, tokens: 0, cost: 0 };
t.turns += v.turns || 0;
t.tokens += v.tokens || 0;
t.cost += v.cost || 0;
}
for (const [f, t] of Object.entries(summary.fileEditTs || {})) {
if (t > (agg.fileEditTs[f] || 0)) agg.fileEditTs[f] = t;
}
for (const [c, n] of Object.entries(summary.bashCommands || {})) {
agg.bashCommands[c] = (agg.bashCommands[c] || 0) + n;
}
for (const [d, n] of Object.entries(summary.webDomains || {})) {
agg.webDomains[d] = (agg.webDomains[d] || 0) + n;
}
for (const [k, n] of Object.entries(summary.subagents || {})) {
agg.subagents[k] = (agg.subagents[k] || 0) + n;
}
if (isSub) {
agg.subagentRuns += 1;
// Subagent active time is tracked separately and deliberately NOT folded
// into agg.activeMs. A subagent's wall-time overlaps its parent session
// (and parallel subagents overlap each other), and gaps >=5min are already
// excluded from the parent's activeMs (see ACTIVE_GAP_CAP_MS) — so summing
// the scalar would double-count short subagents. agg.activeMs stays an
// interactive-session measure; subagentActiveMs exposes delegated work as
// its own honest number. A single unified figure would need interval-union
// across parent+subagents, not scalar sums.
agg.subagentActiveMs += summary.activeMs || 0;
// Subagents still contribute tokens/tools/lines/cost to per-day/week/hour buckets.
const mergeSubBuckets = (srcMap, destMap) => {
for (const [k, src] of Object.entries(srcMap || {})) {
const target = destMap[k] ||= blankDay();
target.inputTokens += src.inputTokens || 0;
target.outputTokens += src.outputTokens || 0;
target.cacheReadTokens += src.cacheReadTokens || 0;
target.cacheWriteTokens += src.cacheWriteTokens || 0;
target.toolCalls += src.toolCalls || 0;
target.linesAdded += src.linesAdded || 0;
target.linesRemoved += src.linesRemoved || 0;
target.cost += src.cost || 0;
target.ships += src.ships || 0;
for (const [kind, n] of Object.entries(src.shipKinds || {})) {
(target.shipKinds ||= {})[kind] = (target.shipKinds[kind] || 0) + n;
}
for (const [m, v] of Object.entries(src.byModel || {})) {
const t = ((target.byModel ||= {})[m] ||= { turns: 0, tokens: 0, cost: 0 });
t.turns += v.turns || 0;
t.tokens += v.tokens || 0;
t.cost += v.cost || 0;
}
}
};
mergeSubBuckets(summary.byDay, agg.byDay);
mergeSubBuckets(summary.byWeek, agg.byWeek);
mergeSubBuckets(summary.byHour, agg.byHour);
// Subagent file edits also count toward hotspots.
for (const [f, n] of Object.entries(summary.fileEdits || {})) {
agg.fileEdits[f] = (agg.fileEdits[f] || 0) + n;
}
} else {
// Top-level sessions only — these are the real "chats".
agg.sessions += 1;
agg.userMessages += summary.userMessages || 0;
agg.activeMs += summary.activeMs || 0;
if (summary.firstTs && summary.lastTs) agg.wallMs += summary.lastTs - summary.firstTs;
const durMs = summary.activeMs || 0;
if (durMs > 0) {
const sl = agg.sessionLengths;
sl.count += 1;
sl.totalMs += durMs;
if (durMs > sl.longestMs) sl.longestMs = durMs;
const mins = durMs / 60_000;
const bucket = mins < 15 ? 'lt15m' : mins < 30 ? 'm15to30' : mins < 60 ? 'm30to60'
: mins < 120 ? 'h1to2' : mins < 240 ? 'h2to4' : 'gt4h';
sl.buckets[bucket] += 1;
}
if (summary.project) {
const p = agg.projects[summary.project] = agg.projects[summary.project] || {