@katlux/toolkit 0.1.1-alpha.144 → 0.1.1-alpha.145

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.
Files changed (61) hide show
  1. package/bin/ai-tokens.mjs +885 -0
  2. package/bin/cli.mjs +8 -0
  3. package/dist/module.json +1 -1
  4. package/dist/runtime/components/KAccordion/KAccordion.global.d.vue.ts +2 -2
  5. package/dist/runtime/components/KAccordion/KAccordion.global.vue.d.ts +2 -2
  6. package/dist/runtime/components/KAlert/KAlert.global.d.vue.ts +1 -1
  7. package/dist/runtime/components/KAlert/KAlert.global.vue.d.ts +1 -1
  8. package/dist/runtime/components/KButton/KButton.global.d.vue.ts +2 -2
  9. package/dist/runtime/components/KButton/KButton.global.vue.d.ts +2 -2
  10. package/dist/runtime/components/KButton/KButton.logic.d.ts +1 -1
  11. package/dist/runtime/components/KCheckbox/KCheckbox.global.d.vue.ts +3 -3
  12. package/dist/runtime/components/KCheckbox/KCheckbox.global.vue.d.ts +3 -3
  13. package/dist/runtime/components/KCombobox/KCombobox.global.d.vue.ts +8 -8
  14. package/dist/runtime/components/KCombobox/KCombobox.global.vue.d.ts +8 -8
  15. package/dist/runtime/components/KCompositeInput/KCompositeInput.global.d.vue.ts +14 -14
  16. package/dist/runtime/components/KCompositeInput/KCompositeInput.global.vue.d.ts +14 -14
  17. package/dist/runtime/components/KCompositeInput/KCompositeInput.logic.d.ts +3 -3
  18. package/dist/runtime/components/KDatatable/KDataIterator.global.d.vue.ts +1 -1
  19. package/dist/runtime/components/KDatatable/KDataIterator.global.vue.d.ts +1 -1
  20. package/dist/runtime/components/KDatePicker/KDatePicker.global.d.vue.ts +8 -8
  21. package/dist/runtime/components/KDatePicker/KDatePicker.global.vue.d.ts +8 -8
  22. package/dist/runtime/components/KDateTimePicker/KDateTimePicker.global.d.vue.ts +4 -4
  23. package/dist/runtime/components/KDateTimePicker/KDateTimePicker.global.vue.d.ts +4 -4
  24. package/dist/runtime/components/KDropdown/KDropdown.global.d.vue.ts +1 -1
  25. package/dist/runtime/components/KDropdown/KDropdown.global.vue.d.ts +1 -1
  26. package/dist/runtime/components/KHourPicker/KHourPicker.global.d.vue.ts +3 -3
  27. package/dist/runtime/components/KHourPicker/KHourPicker.global.vue.d.ts +3 -3
  28. package/dist/runtime/components/KHourSelect/KHourSelect.global.d.vue.ts +1 -1
  29. package/dist/runtime/components/KHourSelect/KHourSelect.global.vue.d.ts +1 -1
  30. package/dist/runtime/components/KMaskTextbox/KMaskTextbox.global.d.vue.ts +3 -3
  31. package/dist/runtime/components/KMaskTextbox/KMaskTextbox.global.vue.d.ts +3 -3
  32. package/dist/runtime/components/KPagination/KPagination.global.d.vue.ts +3 -3
  33. package/dist/runtime/components/KPagination/KPagination.global.vue.d.ts +3 -3
  34. package/dist/runtime/components/KRadiobox/KRadiobox.global.d.vue.ts +1 -1
  35. package/dist/runtime/components/KRadiobox/KRadiobox.global.vue.d.ts +1 -1
  36. package/dist/runtime/components/KRangeSlider/KRangeSlider.global.d.vue.ts +1 -1
  37. package/dist/runtime/components/KRangeSlider/KRangeSlider.global.vue.d.ts +1 -1
  38. package/dist/runtime/components/KSlider/KSlider.global.d.vue.ts +1 -1
  39. package/dist/runtime/components/KSlider/KSlider.global.vue.d.ts +1 -1
  40. package/dist/runtime/components/KTabs/KTabs.global.d.vue.ts +2 -2
  41. package/dist/runtime/components/KTabs/KTabs.global.vue.d.ts +2 -2
  42. package/dist/runtime/components/KTextarea/KTextarea.global.d.vue.ts +2 -2
  43. package/dist/runtime/components/KTextarea/KTextarea.global.vue.d.ts +2 -2
  44. package/dist/runtime/components/KTextbox/KTextbox.global.d.vue.ts +4 -4
  45. package/dist/runtime/components/KTextbox/KTextbox.global.vue.d.ts +4 -4
  46. package/dist/runtime/components/KToast/KToast.global.d.vue.ts +3 -3
  47. package/dist/runtime/components/KToast/KToast.global.vue.d.ts +3 -3
  48. package/dist/runtime/components/KTree/KTree.global.d.vue.ts +4 -4
  49. package/dist/runtime/components/KTree/KTree.global.vue.d.ts +4 -4
  50. package/dist/runtime/components/KTreePicker/KTreePicker.global.d.vue.ts +8 -8
  51. package/dist/runtime/components/KTreePicker/KTreePicker.global.vue.d.ts +8 -8
  52. package/dist/runtime/components/KTreeView/KTreeView.global.d.vue.ts +1 -1
  53. package/dist/runtime/components/KTreeView/KTreeView.global.vue.d.ts +1 -1
  54. package/dist/runtime/presets/default/components/KCheckbox/KCheckbox.d.vue.ts +2 -2
  55. package/dist/runtime/presets/default/components/KCheckbox/KCheckbox.vue.d.ts +2 -2
  56. package/dist/runtime/presets/default/components/KToast/KToast.d.vue.ts +2 -2
  57. package/dist/runtime/presets/default/components/KToast/KToast.vue.d.ts +2 -2
  58. package/dist/runtime/presets/default/components/KTree/KTree.d.vue.ts +2 -2
  59. package/dist/runtime/presets/default/components/KTree/KTree.vue.d.ts +2 -2
  60. package/dist/skills/katlux-config/SKILL.md +1 -1
  61. package/package.json +5 -3
@@ -0,0 +1,885 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * packages/katlux-toolkit/bin/ai-tokens.mjs
4
+ * Dynamic Week-by-Week Token Usage Analyzer, Project-by-Project Filter,
5
+ * and Efficiency Reporter for AI coding assistant sessions (Antigravity IDE transcripts).
6
+ *
7
+ * Shipped with @katlux/toolkit to measure real-world AI context efficiency,
8
+ * track week-over-week token trends, and identify token spikes per project.
9
+ *
10
+ * Usage:
11
+ * npx @katlux/toolkit tokens # Analyzes latest active session (#1)
12
+ * npx @katlux/toolkit tokens --report # Week-by-week executive report (all projects)
13
+ * npx @katlux/toolkit tokens -r -P KatluxShowcase # Week-by-week report for specific project
14
+ * npx @katlux/toolkit tokens --projects # List all detected projects and session counts
15
+ * npx @katlux/toolkit tokens -r -w W43 # Filter report to a specific calendar week
16
+ * npx @katlux/toolkit tokens -r --save # Saves week-by-week report to token-report.md
17
+ * npx @katlux/toolkit tokens -r --md # Outputs pure Markdown
18
+ * npx @katlux/toolkit tokens -p 1 # Paginated session browser (100 per page)
19
+ * npx @katlux/toolkit tokens -p 1 -P KazanLedger # Browse sessions of a specific project
20
+ * npx @katlux/toolkit tokens <#|id> # Inspect details of a specific conversation
21
+ * npx @katlux/toolkit tokens <#|id> -d # Full step-by-step chronology
22
+ */
23
+
24
+ import { existsSync, readdirSync, statSync, readFileSync, writeFileSync, openSync, readSync, closeSync } from 'node:fs'
25
+ import { join, resolve, basename } from 'node:path'
26
+ import { homedir } from 'node:os'
27
+
28
+ const RESET = '\x1b[0m'
29
+ const BOLD = '\x1b[1m'
30
+ const DIM = '\x1b[2m'
31
+ const CYAN = '\x1b[36m'
32
+ const GREEN = '\x1b[32m'
33
+ const YELLOW = '\x1b[33m'
34
+ const RED = '\x1b[31m'
35
+ const MAGENTA = '\x1b[35m'
36
+ const BLUE = '\x1b[34m'
37
+
38
+ const BRAIN_DIR = resolve(homedir(), '.gemini/antigravity-ide/brain')
39
+
40
+ // Standard token estimation for code and conversation JSON (~3.75 chars per token)
41
+ export function estimateTokens(input = 0) {
42
+ if (!input) return 0
43
+ const chars = typeof input === 'number' ? input : (input.length || 0)
44
+ return Math.ceil(chars / 3.75)
45
+ }
46
+
47
+ export function formatTokens(count) {
48
+ if (count >= 1_000_000) return (count / 1_000_000).toFixed(2) + 'M'
49
+ if (count >= 1_000) return (count / 1_000).toFixed(1) + 'k'
50
+ return (count || 0).toLocaleString()
51
+ }
52
+
53
+ export function formatBytes(bytes) {
54
+ if (bytes >= 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MB'
55
+ if (bytes >= 1024) return (bytes / 1024).toFixed(1) + ' KB'
56
+ return (bytes || 0) + ' B'
57
+ }
58
+
59
+ function cleanString(val) {
60
+ if (!val) return ''
61
+ return String(val).replace(/^["']|["']$/g, '').trim()
62
+ }
63
+
64
+ function makeBar(percent, maxLen = 16) {
65
+ const filled = Math.min(maxLen, Math.round((percent / 100) * maxLen))
66
+ return '█'.repeat(filled) + '░'.repeat(maxLen - filled)
67
+ }
68
+
69
+ // Calculate standard ISO Week (e.g. "2026-W43")
70
+ export function getWeekKey(date) {
71
+ const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()))
72
+ const dayNum = d.getUTCDay() || 7
73
+ d.setUTCDate(d.getUTCDate() + 4 - dayNum)
74
+ const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1))
75
+ const weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
76
+ return `${d.getUTCFullYear()}-W${String(weekNo).padStart(2, '0')}`
77
+ }
78
+
79
+ export function getWeekDateRange(weekKey) {
80
+ const match = weekKey.match(/^(\d{4})-W(\d{2})$/)
81
+ if (!match) return weekKey
82
+ const year = parseInt(match[1], 10)
83
+ const week = parseInt(match[2], 10)
84
+
85
+ // Jan 4th is always in week 1
86
+ const jan4 = new Date(Date.UTC(year, 0, 4))
87
+ const jan4Day = jan4.getUTCDay() || 7
88
+ const mondayWeek1 = new Date(jan4.getTime() - (jan4Day - 1) * 86400000)
89
+ const monday = new Date(mondayWeek1.getTime() + (week - 1) * 7 * 86400000)
90
+ const sunday = new Date(monday.getTime() + 6 * 86400000)
91
+
92
+ const monStr = monday.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })
93
+ const sunStr = sunday.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })
94
+ return `${monStr} – ${sunStr}`
95
+ }
96
+
97
+ // Fast 16KB header inspection to avoid loading full multimegabyte JSONL files into memory
98
+ export function getConversationPreviewFast(dirPath, searchQuery = '') {
99
+ const p = join(dirPath, '.system_generated/logs/transcript.jsonl')
100
+ if (!existsSync(p)) return { project: 'Unknown', title: '(empty transcript)', fullTitle: '', rawSize: 0, estimatedTokens: 0, matchesSearch: false, stepsCount: 0 }
101
+
102
+ try {
103
+ const stat = statSync(p)
104
+ if (stat.size === 0) return { project: 'Unknown', title: '(empty transcript)', fullTitle: '', rawSize: 0, estimatedTokens: 0, matchesSearch: false, stepsCount: 0 }
105
+
106
+ let fd
107
+ let chunk = ''
108
+ try {
109
+ fd = openSync(p, 'r')
110
+ const buf = Buffer.alloc(16384)
111
+ const bytesRead = readSync(fd, buf, 0, 16384, 0)
112
+ closeSync(fd)
113
+ chunk = buf.toString('utf-8', 0, bytesRead)
114
+ } catch {
115
+ if (fd !== undefined) try { closeSync(fd) } catch {}
116
+ }
117
+
118
+ // Detect project name dynamically
119
+ let project = 'Unknown'
120
+ const m1 = chunk.match(/\[URI\] -> \[CorpusName\]:\s*\n([^\s\n\r]+)\s*->/)
121
+ if (m1) {
122
+ project = basename(m1[1])
123
+ } else {
124
+ const m2 = chunk.match(/\/Desktop\/projects\/([a-zA-Z0-9_\-]+)/)
125
+ if (m2) project = m2[1]
126
+ else {
127
+ const m3 = chunk.match(/\/projects\/([a-zA-Z0-9_\-]+)/)
128
+ if (m3) project = m3[1]
129
+ }
130
+ }
131
+
132
+ // Detect initial prompt title
133
+ let title = '(no user prompt recorded)'
134
+ const reqMatch = chunk.match(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/)
135
+ if (reqMatch) {
136
+ title = reqMatch[1].replace(/\\n/g, ' ').replace(/[\r\n\t]+/g, ' ').trim()
137
+ } else {
138
+ const contentMatch = chunk.match(/"type":"USER_INPUT"[\s\S]*?"content":"([^"]+)"/)
139
+ if (contentMatch) title = contentMatch[1].replace(/\\n/g, ' ').replace(/[\r\n\t]+/g, ' ').trim()
140
+ }
141
+
142
+ let matchesSearch = false
143
+ if (searchQuery) {
144
+ matchesSearch = chunk.toLowerCase().includes(searchQuery)
145
+ }
146
+
147
+ // Approximate step count based on average JSONL line size (~1.5KB)
148
+ const estimatedTokens = Math.ceil(stat.size / 3.75)
149
+ const approxSteps = Math.max(1, Math.round(stat.size / 1450))
150
+
151
+ return {
152
+ project,
153
+ title: title.slice(0, 42),
154
+ fullTitle: title,
155
+ rawSize: stat.size,
156
+ estimatedTokens,
157
+ matchesSearch,
158
+ stepsCount: approxSteps
159
+ }
160
+ } catch {
161
+ return { project: 'Unknown', title: '(read error)', fullTitle: '', rawSize: 0, estimatedTokens: 0, matchesSearch: false, stepsCount: 0 }
162
+ }
163
+ }
164
+
165
+ export function getConversations() {
166
+ if (!existsSync(BRAIN_DIR)) return []
167
+ const entries = readdirSync(BRAIN_DIR, { withFileTypes: true })
168
+ return entries
169
+ .filter(e => e.isDirectory() && e.name !== 'tempmediaStorage' && !e.name.startsWith('.'))
170
+ .map(e => {
171
+ const dirPath = join(BRAIN_DIR, e.name)
172
+ const stats = statSync(dirPath)
173
+ return { id: e.name, path: dirPath, mtime: stats.mtime, weekKey: getWeekKey(stats.mtime) }
174
+ })
175
+ .sort((a, b) => b.mtime.getTime() - a.mtime.getTime())
176
+ }
177
+
178
+ export function parseTranscript(conversationDir) {
179
+ const transcriptPath = join(conversationDir, '.system_generated/logs/transcript.jsonl')
180
+ if (!existsSync(transcriptPath)) return null
181
+
182
+ const raw = readFileSync(transcriptPath, 'utf-8')
183
+ const lines = raw.trim().split('\n').filter(Boolean)
184
+
185
+ const steps = []
186
+ for (let i = 0; i < lines.length; i++) {
187
+ try {
188
+ const obj = JSON.parse(lines[i])
189
+ steps.push(obj)
190
+ } catch {}
191
+ }
192
+ return steps
193
+ }
194
+
195
+ export function analyzeSession(steps, conversationId, mtime = new Date(), previewProject = 'Unknown') {
196
+ let totalChars = 0
197
+ let inputChars = 0
198
+ let outputChars = 0
199
+
200
+ const categories = {
201
+ USER_INPUT: { count: 0, chars: 0, tokens: 0, label: 'User Prompts' },
202
+ PLANNER_RESPONSE: { count: 0, chars: 0, tokens: 0, label: 'Assistant / Model' },
203
+ VIEW_FILE: { count: 0, chars: 0, tokens: 0, label: 'view_file Outputs' },
204
+ CODE_ACTION: { count: 0, chars: 0, tokens: 0, label: 'Code Edit / Write' },
205
+ RUN_COMMAND: { count: 0, chars: 0, tokens: 0, label: 'run_command Outputs' },
206
+ GREP_SEARCH: { count: 0, chars: 0, tokens: 0, label: 'grep_search Outputs' },
207
+ LIST_DIRECTORY: { count: 0, chars: 0, tokens: 0, label: 'list_dir Outputs' },
208
+ CONVERSATION_HISTORY: { count: 0, chars: 0, tokens: 0, label: 'Injected History' },
209
+ SYSTEM_MESSAGE: { count: 0, chars: 0, tokens: 0, label: 'System Notifications' },
210
+ OTHER: { count: 0, chars: 0, tokens: 0, label: 'Other Metadata' }
211
+ }
212
+
213
+ const spikes = []
214
+ const userPrompts = []
215
+ const filesViewed = new Map()
216
+ const filesModified = new Map()
217
+ let sessionTitle = ''
218
+ let detectedProject = previewProject
219
+
220
+ steps.forEach(step => {
221
+ const type = step.type || 'OTHER'
222
+ let content = ''
223
+ if (typeof step.content === 'string') {
224
+ content = step.content
225
+ } else if (step.tool_calls) {
226
+ content = JSON.stringify(step.tool_calls)
227
+ } else if (step.content) {
228
+ content = JSON.stringify(step.content)
229
+ }
230
+
231
+ if (detectedProject === 'Unknown' && content) {
232
+ const m1 = content.match(/\[URI\] -> \[CorpusName\]:\s*\n([^\s\n\r]+)\s*->/)
233
+ if (m1) detectedProject = basename(m1[1])
234
+ else {
235
+ const m2 = content.match(/\/Desktop\/projects\/([a-zA-Z0-9_\-]+)/)
236
+ if (m2) detectedProject = m2[1]
237
+ }
238
+ }
239
+
240
+ if (type === 'USER_INPUT' && content) {
241
+ const match = content.match(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/)
242
+ const promptText = (match ? match[1] : content).replace(/[\r\n\t]+/g, ' ').trim()
243
+ if (!sessionTitle) sessionTitle = promptText
244
+ userPrompts.push({ step: step.step_index, text: promptText })
245
+ }
246
+
247
+ // Track tool call targets
248
+ if (step.tool_calls && Array.isArray(step.tool_calls)) {
249
+ step.tool_calls.forEach(tc => {
250
+ const args = tc.args || {}
251
+ if (tc.name === 'view_file' && args.AbsolutePath) {
252
+ const fn = basename(cleanString(args.AbsolutePath))
253
+ if (fn) filesViewed.set(fn, (filesViewed.get(fn) || 0) + 1)
254
+ } else if ((tc.name === 'replace_file_content' || tc.name === 'multi_replace_file_content' || tc.name === 'write_to_file') && args.TargetFile) {
255
+ const fn = basename(cleanString(args.TargetFile))
256
+ if (fn) filesModified.set(fn, (filesModified.get(fn) || 0) + 1)
257
+ }
258
+ })
259
+ }
260
+
261
+ const chars = content.length
262
+ const tokens = estimateTokens(chars)
263
+
264
+ totalChars += chars
265
+
266
+ if (type === 'PLANNER_RESPONSE') {
267
+ outputChars += chars
268
+ } else {
269
+ inputChars += chars
270
+ }
271
+
272
+ const cat = categories[type] || categories.OTHER
273
+ cat.count++
274
+ cat.chars += chars
275
+ cat.tokens += tokens
276
+
277
+ spikes.push({
278
+ step_index: step.step_index,
279
+ type,
280
+ tokens,
281
+ chars,
282
+ preview: content.replace(/[\r\n\t]+/g, ' ').slice(0, 80).trim()
283
+ })
284
+ })
285
+
286
+ const totalTokens = estimateTokens(totalChars)
287
+ const inputTokens = estimateTokens(inputChars)
288
+ const outputTokens = estimateTokens(outputChars)
289
+
290
+ spikes.sort((a, b) => b.tokens - a.tokens)
291
+
292
+ const topViewedFiles = [...filesViewed.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5)
293
+ const topModifiedFiles = [...filesModified.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5)
294
+
295
+ return {
296
+ conversationId,
297
+ project: detectedProject,
298
+ sessionTitle: sessionTitle || '(no title)',
299
+ mtime,
300
+ weekKey: getWeekKey(mtime),
301
+ totalSteps: steps.length,
302
+ totalChars,
303
+ totalTokens,
304
+ inputTokens,
305
+ outputTokens,
306
+ categories,
307
+ spikes: spikes.slice(0, 5),
308
+ userPrompts,
309
+ topViewedFiles,
310
+ topModifiedFiles,
311
+ allFilesViewed: filesViewed,
312
+ allFilesModified: filesModified
313
+ }
314
+ }
315
+
316
+ // ── Project List View ───────────────────────────────────────────────────────
317
+ export function listDetectedProjects(conversations) {
318
+ console.log(`\n${BOLD}╭──────────────────────────────────────────────────────────────────────────────╮${RESET}`)
319
+ console.log(`${BOLD}│ DETECTED ANTIGRAVITY PROJECTS │${RESET}`)
320
+ console.log(`${BOLD}╰──────────────────────────────────────────────────────────────────────────────╯${RESET}`)
321
+
322
+ const projectMap = new Map()
323
+
324
+ conversations.forEach(c => {
325
+ const prj = c.preview.project
326
+ if (prj === 'Unknown' || c.preview.rawSize === 0) return
327
+ if (!projectMap.has(prj)) {
328
+ projectMap.set(prj, { name: prj, count: 0, tokens: 0, latest: c.mtime })
329
+ }
330
+ const p = projectMap.get(prj)
331
+ p.count++
332
+ p.tokens += c.preview.estimatedTokens
333
+ if (c.mtime > p.latest) p.latest = c.mtime
334
+ })
335
+
336
+ console.log(` ${'#'.padStart(3)} ${'PROJECT NAME'.padEnd(26)} ${'SESSIONS'.padStart(10)} ${'TOTAL TOKENS'.padStart(14)} LAST ACTIVE`)
337
+ console.log(` ${'─'.repeat(3)} ${'─'.repeat(26)} ${'─'.repeat(10)} ${'─'.repeat(14)} ${'─'.repeat(16)}`)
338
+
339
+ let idx = 1
340
+ for (const p of projectMap.values()) {
341
+ const dateStr = p.latest.toLocaleDateString() + ' ' + p.latest.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
342
+ console.log(
343
+ ` ${CYAN}${String(idx++).padStart(3)}${RESET} ` +
344
+ `${BOLD}${p.name.padEnd(26)}${RESET} ` +
345
+ `${String(p.count).padStart(10)} ` +
346
+ `${formatTokens(p.tokens).padStart(14)} ` +
347
+ `${DIM}${dateStr}${RESET}`
348
+ )
349
+ }
350
+
351
+ console.log(`\n${BOLD}Filter Commands:${RESET}`)
352
+ for (const p of projectMap.values()) {
353
+ console.log(` • View ${p.name}: ${CYAN}npx @katlux/toolkit tokens -P ${p.name} --report${RESET}`)
354
+ }
355
+ console.log()
356
+ }
357
+
358
+ // ── Week-by-Week Executive Token Report Generator ───────────────────────────
359
+ export function generateWeekReport({ weekFilter = '', projectFilter = '', asMarkdown = false, saveFile = false }) {
360
+ const all = getConversations()
361
+ if (all.length === 0) {
362
+ console.log(`${RED}No conversations found in ${BRAIN_DIR}${RESET}`)
363
+ return
364
+ }
365
+
366
+ // Attach previews quickly using fast header scan
367
+ const mapped = all.map((c, i) => ({
368
+ ...c,
369
+ originalIndex: i + 1,
370
+ preview: getConversationPreviewFast(c.path)
371
+ }))
372
+
373
+ // Filter by project if requested
374
+ let filtered = mapped
375
+ if (projectFilter) {
376
+ const q = projectFilter.toLowerCase()
377
+ filtered = mapped.filter(c => c.preview.project.toLowerCase().includes(q))
378
+ if (filtered.length === 0) {
379
+ console.log(`\n${RED}No sessions found for project matching "${projectFilter}".${RESET}`)
380
+ console.log(`Run ${CYAN}npx @katlux/toolkit tokens --projects${RESET} to view all detected projects.\n`)
381
+ return
382
+ }
383
+ }
384
+
385
+ // Filter out completely empty bootstrap directories
386
+ const activeConversations = filtered.filter(c => c.preview.rawSize > 0)
387
+
388
+ // Group sessions into calendar weeks
389
+ const weeklyMap = new Map()
390
+
391
+ activeConversations.forEach(conv => {
392
+ const wk = conv.weekKey
393
+ if (!weeklyMap.has(wk)) {
394
+ weeklyMap.set(wk, {
395
+ weekKey: wk,
396
+ dateRange: getWeekDateRange(wk),
397
+ dirs: []
398
+ })
399
+ }
400
+ weeklyMap.get(wk).dirs.push(conv)
401
+ })
402
+
403
+ // Process each week's sessions
404
+ const weeklyStats = []
405
+
406
+ for (const [wk, entry] of weeklyMap.entries()) {
407
+ if (weekFilter && !wk.toLowerCase().includes(weekFilter.toLowerCase())) {
408
+ continue
409
+ }
410
+
411
+ const analyzedSessions = entry.dirs.map(d => {
412
+ const steps = parseTranscript(d.path)
413
+ return steps ? analyzeSession(steps, d.id, d.mtime, d.preview.project) : null
414
+ }).filter(Boolean)
415
+
416
+ if (analyzedSessions.length === 0) continue
417
+
418
+ const count = analyzedSessions.length
419
+ const sum = (fn) => analyzedSessions.reduce((s, x) => s + fn(x), 0)
420
+ const avg = (fn) => Math.round(sum(fn) / count)
421
+
422
+ const avgTotalTokens = avg(s => s.totalTokens)
423
+ const avgInputTokens = avg(s => s.inputTokens)
424
+ const avgOutputTokens = avg(s => s.outputTokens)
425
+ const avgRunCmdTokens = avg(s => s.categories.RUN_COMMAND.tokens)
426
+ const avgViewFileTokens = avg(s => s.categories.VIEW_FILE.tokens)
427
+ const avgSteps = avg(s => s.totalSteps)
428
+
429
+ const claudeCost = ((avgInputTokens / 1_000_000) * 3.00 + (avgOutputTokens / 1_000_000) * 15.00).toFixed(2)
430
+ const geminiCost = ((avgInputTokens / 1_000_000) * 0.35 + (avgOutputTokens / 1_000_000) * 1.05).toFixed(3)
431
+
432
+ // Aggregate files and categories for this specific week
433
+ const weekCategories = {}
434
+ const weekViewedFiles = new Map()
435
+ const weekModifiedFiles = new Map()
436
+
437
+ analyzedSessions.forEach(s => {
438
+ Object.entries(s.categories).forEach(([k, cat]) => {
439
+ if (!weekCategories[k]) weekCategories[k] = { label: cat.label, count: 0, tokens: 0 }
440
+ weekCategories[k].count += cat.count
441
+ weekCategories[k].tokens += cat.tokens
442
+ })
443
+ s.allFilesViewed.forEach((c, f) => weekViewedFiles.set(f, (weekViewedFiles.get(f) || 0) + c))
444
+ s.allFilesModified.forEach((c, f) => weekModifiedFiles.set(f, (weekModifiedFiles.get(f) || 0) + c))
445
+ })
446
+
447
+ weeklyStats.push({
448
+ weekKey: wk,
449
+ dateRange: entry.dateRange,
450
+ sessionCount: count,
451
+ totalTokensSum: sum(s => s.totalTokens),
452
+ avgTotalTokens,
453
+ avgRunCmdTokens,
454
+ avgViewFileTokens,
455
+ avgSteps,
456
+ claudeCost,
457
+ geminiCost,
458
+ categories: weekCategories,
459
+ topViewed: [...weekViewedFiles.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5),
460
+ topModified: [...weekModifiedFiles.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5)
461
+ })
462
+ }
463
+
464
+ // Sort newest week first
465
+ weeklyStats.sort((a, b) => b.weekKey.localeCompare(a.weekKey))
466
+
467
+ // Compute Week-over-Week (WoW) efficiency changes dynamically
468
+ for (let i = 0; i < weeklyStats.length; i++) {
469
+ const current = weeklyStats[i]
470
+ const prior = weeklyStats[i + 1]
471
+ if (prior && prior.avgTotalTokens > 0) {
472
+ const diff = current.avgTotalTokens - prior.avgTotalTokens
473
+ const pct = ((diff / prior.avgTotalTokens) * 100).toFixed(1)
474
+ current.wowPct = pct
475
+ } else {
476
+ current.wowPct = null
477
+ }
478
+ }
479
+
480
+ const projectLabel = projectFilter ? `Project: ${projectFilter}` : 'All Projects'
481
+
482
+ // Markdown generation
483
+ const md = []
484
+ md.push(`# Antigravity AI Token Usage: Week-by-Week Report`)
485
+ md.push(`*Scope: ${projectLabel} | Analyzed ${activeConversations.length} sessions across ${weeklyStats.length} calendar weeks*\n`)
486
+
487
+ md.push(`## 1. Week-by-Week Token & Efficiency Progression\n`)
488
+ md.push(`| Calendar Week | Date Range | Tasks | Avg Tokens / Task | Avg Test Tokens | Avg File View | Avg Steps | Avg Cost (Claude) | WoW Trend |`)
489
+ md.push(`| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: |`)
490
+
491
+ weeklyStats.forEach((w, idx) => {
492
+ const isCurrent = idx === 0 ? ' **(Current)**' : ''
493
+ const wowStr = w.wowPct !== null ? `${Number(w.wowPct) <= 0 ? w.wowPct + '%' : '+' + w.wowPct + '%'}` : '—'
494
+ md.push(`| **${w.weekKey}**${isCurrent} | ${w.dateRange} | ${w.sessionCount} | **${formatTokens(w.avgTotalTokens)}** | ${formatTokens(w.avgRunCmdTokens)} | ${formatTokens(w.avgViewFileTokens)} | ${w.avgSteps} | $${w.claudeCost} | ${wowStr} |`)
495
+ })
496
+ md.push('')
497
+
498
+ md.push(`## 2. Weekly Details & Most Frequent Files\n`)
499
+ weeklyStats.forEach(w => {
500
+ md.push(`### ${w.weekKey} (${w.dateRange}) — ${w.sessionCount} Tasks | Avg ${formatTokens(w.avgTotalTokens)} Tokens | Cost $${w.claudeCost}`)
501
+ if (w.topViewed.length > 0) {
502
+ md.push(`- **Most Read Files:** ${w.topViewed.map(([f, n]) => `\`${f}\` (${n}x)`).join(', ')}`)
503
+ }
504
+ if (w.topModified.length > 0) {
505
+ md.push(`- **Most Edited Files:** ${w.topModified.map(([f, n]) => `\`${f}\` (${n}x)`).join(', ')}`)
506
+ }
507
+ const totalWeekTokens = Object.values(w.categories).reduce((s, x) => s + x.tokens, 0)
508
+ const catPcts = Object.values(w.categories)
509
+ .filter(c => c.tokens > 0)
510
+ .sort((a, b) => b.tokens - a.tokens)
511
+ .map(c => `${c.label}: ${((c.tokens / totalWeekTokens) * 100).toFixed(0)}%`)
512
+ .slice(0, 4)
513
+ .join(' | ')
514
+ if (catPcts) {
515
+ md.push(`- **Key Categories:** ${catPcts}`)
516
+ }
517
+ md.push('')
518
+ })
519
+
520
+ const mdOutput = md.join('\n')
521
+
522
+ if (saveFile) {
523
+ const outPath = resolve(process.cwd(), 'token-report.md')
524
+ writeFileSync(outPath, mdOutput, 'utf-8')
525
+ console.log(`${GREEN}✓ Week-by-week report saved to ${outPath}${RESET}\n`)
526
+ }
527
+
528
+ if (asMarkdown) {
529
+ console.log(mdOutput)
530
+ return
531
+ }
532
+
533
+ // Terminal Visual Output
534
+ console.log(`\n${BOLD}╭──────────────────────────────────────────────────────────────────────────────╮${RESET}`)
535
+ console.log(`${BOLD}│ ANTIGRAVITY AI TOKEN USAGE: WEEK-BY-WEEK REPORT │${RESET}`)
536
+ console.log(`${BOLD}╰──────────────────────────────────────────────────────────────────────────────╯${RESET}`)
537
+ console.log(` Scope: ${BOLD}${projectLabel}${RESET} (${activeConversations.length} total sessions analyzed across ${weeklyStats.length} calendar weeks)\n`)
538
+
539
+ console.log(`${BOLD}1. WEEK-BY-WEEK PROGRESSION TABLE${RESET}`)
540
+ console.log(` ${'WEEK'.padEnd(10)} ${'DATE RANGE'.padEnd(16)} ${'TASKS'.padStart(6)} ${'AVG TOKENS'.padStart(11)} ${'TESTS'.padStart(8)} ${'VIEW'.padStart(8)} ${'STEPS'.padStart(6)} ${'COST'.padStart(7)} ${'WoW TREND'.padStart(10)}`)
541
+ console.log(` ${'─'.repeat(10)} ${'─'.repeat(16)} ${'─'.repeat(6)} ${'─'.repeat(11)} ${'─'.repeat(8)} ${'─'.repeat(8)} ${'─'.repeat(6)} ${'─'.repeat(7)} ${'─'.repeat(10)}`)
542
+
543
+ weeklyStats.forEach((w, idx) => {
544
+ const isCurrent = idx === 0
545
+ const weekLabel = (w.weekKey.replace('2026-', '') + (isCurrent ? '*' : '')).padEnd(10)
546
+ const wowColor = w.wowPct && Number(w.wowPct) <= 0 ? GREEN : (w.wowPct ? RED : DIM)
547
+ const wowStr = w.wowPct !== null ? (Number(w.wowPct) <= 0 ? w.wowPct + '%' : '+' + w.wowPct + '%') : '—'
548
+
549
+ console.log(
550
+ ` ${isCurrent ? GREEN : CYAN}${weekLabel}${RESET} ` +
551
+ `${w.dateRange.padEnd(16)} ` +
552
+ `${String(w.sessionCount).padStart(6)} ` +
553
+ `${BOLD}${formatTokens(w.avgTotalTokens).padStart(11)}${RESET} ` +
554
+ `${formatTokens(w.avgRunCmdTokens).padStart(8)} ` +
555
+ `${formatTokens(w.avgViewFileTokens).padStart(8)} ` +
556
+ `${String(w.avgSteps).padStart(6)} ` +
557
+ `${('$' + w.claudeCost).padStart(7)} ` +
558
+ `${wowColor}${wowStr.padStart(10)}${RESET}`
559
+ )
560
+ })
561
+
562
+ console.log(` ${DIM}* Current calendar week. Costs estimated using Claude 3.5 Sonnet.${RESET}\n`)
563
+
564
+ console.log(`${BOLD}2. WEEKLY DETAILS & MOST FREQUENT FILES${RESET}`)
565
+ weeklyStats.forEach(w => {
566
+ const totalWeekTokens = Object.values(w.categories).reduce((s, x) => s + x.tokens, 0)
567
+ console.log(` ${CYAN}${BOLD}[Week ${w.weekKey}: ${w.dateRange}]${RESET} — ${w.sessionCount} Tasks | Avg ${formatTokens(w.avgTotalTokens)} Tokens | Avg Steps: ${w.avgSteps}`)
568
+ if (w.topViewed.length > 0) {
569
+ console.log(` ${CYAN}Most Read:${RESET} ${w.topViewed.map(([f, n]) => `${f} (${n}x)`).join(', ')}`)
570
+ }
571
+ if (w.topModified.length > 0) {
572
+ console.log(` ${YELLOW}Most Edited:${RESET} ${w.topModified.map(([f, n]) => `${f} (${n}x)`).join(', ')}`)
573
+ }
574
+
575
+ // Top categories
576
+ const topCats = Object.values(w.categories)
577
+ .filter(c => c.tokens > 0)
578
+ .sort((a, b) => b.tokens - a.tokens)
579
+ .slice(0, 4)
580
+ .map(c => `${c.label}: ${((c.tokens / totalWeekTokens) * 100).toFixed(0)}%`)
581
+ .join(' | ')
582
+ if (topCats) {
583
+ console.log(` ${DIM}Categories:${RESET} ${DIM}${topCats}${RESET}`)
584
+ }
585
+ console.log()
586
+ })
587
+
588
+ console.log(`${DIM}Commands:${RESET}`)
589
+ console.log(` • Filter project: ${CYAN}npx @katlux/toolkit tokens -P <projectName> --report${RESET}`)
590
+ console.log(` • List projects: ${CYAN}npx @katlux/toolkit tokens --projects${RESET}`)
591
+ console.log(` • Save as Markdown: ${CYAN}npx @katlux/toolkit tokens --report --save${RESET}`)
592
+ console.log(` • Filter single week:${CYAN}npx @katlux/toolkit tokens -w W43${RESET}`)
593
+ console.log(` • Browse sessions: ${CYAN}npx @katlux/toolkit tokens -p 1${RESET}\n`)
594
+ }
595
+
596
+ // ── CLI Argument Parsing & Routing ──────────────────────────────────────────
597
+ const args = process.argv.slice(2)
598
+ const showDetail = args.includes('-d') || args.includes('--detail')
599
+
600
+ // Project filter flag
601
+ let projectFilter = ''
602
+ const prjArgIdx = args.findIndex(a => a === '-P' || a === '--project')
603
+ if (prjArgIdx !== -1 && args[prjArgIdx + 1] && !args[prjArgIdx + 1].startsWith('-')) {
604
+ projectFilter = args[prjArgIdx + 1]
605
+ if (projectFilter === 'current' || projectFilter === '.') {
606
+ projectFilter = basename(process.cwd())
607
+ }
608
+ }
609
+
610
+ // List projects mode
611
+ if (args.includes('--projects') || args.includes('-P') && !projectFilter) {
612
+ const all = getConversations().map(c => ({
613
+ ...c,
614
+ preview: getConversationPreviewFast(c.path)
615
+ }))
616
+ listDetectedProjects(all)
617
+ process.exit(0)
618
+ }
619
+
620
+ // Report mode (default if called with --report, -r, or if --week is provided)
621
+ const isReport = args.includes('--report') || args.includes('-r') || args.includes('--weekly')
622
+ const asMarkdown = args.includes('--md') || args.includes('--markdown')
623
+ const saveFile = args.includes('--save')
624
+
625
+ // Week filter
626
+ let weekFilter = ''
627
+ const weekArgIdx = args.findIndex(a => a === '-w' || a === '--week')
628
+ if (weekArgIdx !== -1 && args[weekArgIdx + 1]) {
629
+ weekFilter = args[weekArgIdx + 1]
630
+ }
631
+
632
+ if (isReport || weekFilter) {
633
+ generateWeekReport({ weekFilter, projectFilter, asMarkdown, saveFile })
634
+ process.exit(0)
635
+ }
636
+
637
+ // Search term
638
+ let searchQuery = ''
639
+ const searchArgIdx = args.findIndex(a => a === '-s' || a === '--search' || a === '-q')
640
+ if (searchArgIdx !== -1 && args[searchArgIdx + 1]) {
641
+ searchQuery = args[searchArgIdx + 1].toLowerCase()
642
+ }
643
+
644
+ // Extract page
645
+ let page = 1
646
+ const pageArgIdx = args.findIndex(a => a === '-p' || a === '--page')
647
+ if (pageArgIdx !== -1 && args[pageArgIdx + 1]) {
648
+ page = Math.max(1, parseInt(args[pageArgIdx + 1], 10) || 1)
649
+ }
650
+
651
+ // Extract limit (default 100 per page)
652
+ let limit = 100
653
+ const limitArgIdx = args.findIndex(a => a === '-l' || a === '--limit')
654
+ if (limitArgIdx !== -1 && args[limitArgIdx + 1]) {
655
+ limit = Math.max(1, parseInt(args[limitArgIdx + 1], 10) || 100)
656
+ }
657
+
658
+ const allConversations = getConversations()
659
+
660
+ if (allConversations.length === 0) {
661
+ console.log(`${RED}No conversations found in ${BRAIN_DIR}${RESET}`)
662
+ process.exit(1)
663
+ }
664
+
665
+ // Map previews quickly using fast header inspection
666
+ const mappedConversations = allConversations.map((c, i) => {
667
+ const preview = getConversationPreviewFast(c.path, searchQuery)
668
+ return {
669
+ ...c,
670
+ originalIndex: i + 1,
671
+ preview
672
+ }
673
+ })
674
+
675
+ // Filter by project if specified
676
+ let projectFilteredConversations = mappedConversations
677
+ if (projectFilter) {
678
+ const q = projectFilter.toLowerCase()
679
+ projectFilteredConversations = mappedConversations.filter(c => c.preview.project.toLowerCase().includes(q))
680
+ }
681
+
682
+ // Filter if search query provided
683
+ let filteredConversations = projectFilteredConversations
684
+ if (searchQuery) {
685
+ filteredConversations = projectFilteredConversations.filter(c =>
686
+ c.id.toLowerCase().includes(searchQuery) ||
687
+ (c.preview.fullTitle && c.preview.fullTitle.toLowerCase().includes(searchQuery)) ||
688
+ c.preview.matchesSearch
689
+ )
690
+ }
691
+
692
+ // Positional argument
693
+ const positionalArgs = args.filter(a =>
694
+ !a.startsWith('-') &&
695
+ a !== String(page) &&
696
+ a !== String(limit) &&
697
+ a !== searchQuery &&
698
+ a !== weekFilter &&
699
+ a !== projectFilter
700
+ )
701
+ const targetArg = positionalArgs[0]
702
+ const targetIndex = targetArg && /^\d+$/.test(targetArg) ? parseInt(targetArg, 10) : null
703
+
704
+ const isExplicitList = args.includes('--list') || pageArgIdx !== -1 || searchArgIdx !== -1 || projectFilter !== ''
705
+
706
+ // ── 1. Page-by-Page Conversation List View ──────────────────────────────────
707
+ if ((isExplicitList && !targetIndex) || (searchQuery && !targetIndex)) {
708
+ const total = filteredConversations.length
709
+ const totalPages = Math.max(1, Math.ceil(total / limit))
710
+ page = Math.min(page, totalPages)
711
+
712
+ const startIndex = (page - 1) * limit
713
+ const pageItems = filteredConversations.slice(startIndex, startIndex + limit)
714
+
715
+ console.log(`\n${BOLD}╭──────────────────────────────────────────────────────────────────────────────╮${RESET}`)
716
+ console.log(`${BOLD}│ ANTIGRAVITY CONVERSATIONS BROWSER │${RESET}`)
717
+ console.log(`${BOLD}╰──────────────────────────────────────────────────────────────────────────────╯${RESET}`)
718
+ if (projectFilter) {
719
+ console.log(` Project Filter: ${GREEN}${projectFilter}${RESET}`)
720
+ }
721
+ if (searchQuery) {
722
+ console.log(` Filtered by: ${YELLOW}"${searchQuery}"${RESET} (${total} matching)`)
723
+ }
724
+ console.log(` Showing Page ${BOLD}${page}${RESET} of ${BOLD}${totalPages}${RESET} (${total === 0 ? 0 : startIndex + 1}–${Math.min(startIndex + limit, total)} of ${total} conversations)\n`)
725
+
726
+ if (total === 0) {
727
+ console.log(` ${RED}No conversations found matching criteria.${RESET}\n`)
728
+ process.exit(0)
729
+ }
730
+
731
+ console.log(` ${'#'.padStart(4)} ${'ID'.padEnd(9)} ${'PROJECT'.padEnd(16)} ${'WEEK'.padEnd(6)} ${'TOPIC / PROMPT'.padEnd(36)} ${'TOKENS'.padStart(9)} DATE`)
732
+ console.log(` ${'─'.repeat(4)} ${'─'.repeat(9)} ${'─'.repeat(16)} ${'─'.repeat(6)} ${'─'.repeat(36)} ${'─'.repeat(9)} ${'─'.repeat(16)}`)
733
+
734
+ pageItems.forEach(conv => {
735
+ const preview = conv.preview
736
+ const shortId = conv.id.slice(0, 8)
737
+ const dateStr = conv.mtime.toLocaleDateString() + ' ' + conv.mtime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
738
+ const shortWeek = conv.weekKey.replace('2026-', '')
739
+ const prjStr = (preview.project || 'Unknown').slice(0, 15)
740
+
741
+ const indexColor = conv.originalIndex === 1 ? GREEN : CYAN
742
+ console.log(
743
+ ` ${indexColor}${String(conv.originalIndex).padStart(4)}${RESET} ` +
744
+ `${shortId.padEnd(9)} ` +
745
+ `${YELLOW}${prjStr.padEnd(16)}${RESET} ` +
746
+ `${DIM}${shortWeek.padEnd(6)}${RESET} ` +
747
+ `${preview.title.padEnd(36)} ` +
748
+ `${BOLD}${formatTokens(preview.estimatedTokens).padStart(9)}${RESET} ` +
749
+ `${DIM}${dateStr}${RESET}`
750
+ )
751
+ })
752
+
753
+ console.log(`\n${BOLD}Navigation & Actions:${RESET}`)
754
+ if (page < totalPages) {
755
+ console.log(` • Next page: ${CYAN}npx @katlux/toolkit tokens -p ${page + 1}${projectFilter ? ` -P ${projectFilter}` : ''}${RESET}`)
756
+ }
757
+ if (page > 1) {
758
+ console.log(` • Previous page: ${CYAN}npx @katlux/toolkit tokens -p ${page - 1}${projectFilter ? ` -P ${projectFilter}` : ''}${RESET}`)
759
+ }
760
+ console.log(` • Filter project:${CYAN}npx @katlux/toolkit tokens -P <projectName>${RESET}`)
761
+ console.log(` • Weekly report: ${CYAN}npx @katlux/toolkit tokens --report${projectFilter ? ` -P ${projectFilter}` : ''}${RESET}`)
762
+ console.log(` • Inspect one: ${CYAN}npx @katlux/toolkit tokens <#>${RESET} (e.g. ${CYAN}tokens ${pageItems[0]?.originalIndex}${RESET} or ${CYAN}tokens ${pageItems[0]?.id.slice(0, 8)}${RESET})`)
763
+ console.log(` • Detailed steps:${CYAN} npx @katlux/toolkit tokens <#> -d${RESET}\n`)
764
+ process.exit(0)
765
+ }
766
+
767
+ // ── 2. Single Conversation Detail View ──────────────────────────────────────
768
+ let selectedConv = allConversations[0]
769
+
770
+ if (targetIndex !== null) {
771
+ if (targetIndex < 1 || targetIndex > allConversations.length) {
772
+ console.log(`${RED}Invalid index #${targetIndex}. Available: 1 to ${allConversations.length}.${RESET}`)
773
+ process.exit(1)
774
+ }
775
+ selectedConv = allConversations[targetIndex - 1]
776
+ } else if (targetArg) {
777
+ const found = allConversations.find(c => c.id.toLowerCase().startsWith(targetArg.toLowerCase()))
778
+ if (!found) {
779
+ console.log(`${RED}Conversation matching "${targetArg}" not found.${RESET}`)
780
+ console.log(`Run ${CYAN}npx @katlux/toolkit tokens -p 1${RESET} to view all conversations.`)
781
+ process.exit(1)
782
+ }
783
+ selectedConv = found
784
+ }
785
+
786
+ const steps = parseTranscript(selectedConv.path)
787
+ if (!steps) {
788
+ console.log(`${RED}No transcript found for conversation ${selectedConv.id}${RESET}`)
789
+ process.exit(1)
790
+ }
791
+
792
+ const previewMeta = getConversationPreviewFast(selectedConv.path)
793
+ const data = analyzeSession(steps, selectedConv.id, selectedConv.mtime, previewMeta.project)
794
+ const convIndex = allConversations.findIndex(c => c.id === selectedConv.id) + 1
795
+
796
+ // Print Dashboard
797
+ console.log(`\n${BOLD}╭──────────────────────────────────────────────────────────────────────────╮${RESET}`)
798
+ console.log(`${BOLD}│ AI CONVERSATION TOKEN LOG │${RESET}`)
799
+ console.log(`${BOLD}╰──────────────────────────────────────────────────────────────────────────╯${RESET}`)
800
+ console.log(` ${BOLD}Conversation Index:${RESET} ${GREEN}#${convIndex}${RESET} of ${allConversations.length}`)
801
+ console.log(` ${BOLD}Project:${RESET} ${YELLOW}${data.project}${RESET} (${CYAN}${data.weekKey}${RESET})`)
802
+ console.log(` ${BOLD}Conversation ID:${RESET} ${CYAN}${data.conversationId}${RESET}`)
803
+ console.log(` ${BOLD}Topic / Prompt:${RESET} ${YELLOW}"${data.sessionTitle}"${RESET}`)
804
+ console.log(` ${BOLD}Total Steps:${RESET} ${data.totalSteps} recorded steps`)
805
+ console.log(` ${BOLD}Transcript Size:${RESET} ${formatBytes(data.totalChars)} total characters\n`)
806
+
807
+ console.log(`${BOLD}Token Summary (Estimated BPE):${RESET}`)
808
+ console.log(` ${GREEN}● Total Tokens:${RESET} ${BOLD}${formatTokens(data.totalTokens)}${RESET} tokens (~${data.totalTokens.toLocaleString()})`)
809
+ console.log(` ${BLUE}↳ Input Tokens:${RESET} ${formatTokens(data.inputTokens)} tokens (${Math.round((data.inputTokens / data.totalTokens) * 100 || 0)}%)`)
810
+ console.log(` ${MAGENTA}↳ Output Tokens:${RESET} ${formatTokens(data.outputTokens)} tokens (${Math.round((data.outputTokens / data.totalTokens) * 100 || 0)}%)\n`)
811
+
812
+ console.log(`${BOLD}Approximate Model Cost (if fresh API query):${RESET}`)
813
+ const geminiCost = ((data.inputTokens / 1_000_000) * 0.35 + (data.outputTokens / 1_000_000) * 1.05).toFixed(4)
814
+ const claudeCost = ((data.inputTokens / 1_000_000) * 3.00 + (data.outputTokens / 1_000_000) * 15.00).toFixed(4)
815
+ const gptCost = ((data.inputTokens / 1_000_000) * 2.50 + (data.outputTokens / 1_000_000) * 10.00).toFixed(4)
816
+ console.log(` Gemini 1.5/2.0 Flash : ${GREEN}$${geminiCost}${RESET}`)
817
+ console.log(` Claude 3.5 Sonnet : ${YELLOW}$${claudeCost}${RESET}`)
818
+ console.log(` GPT-4o : ${CYAN}$${gptCost}${RESET}\n`)
819
+
820
+ // User turns / questions in this conversation
821
+ if (data.userPrompts.length > 0) {
822
+ console.log(`${BOLD}Conversation Turns (${data.userPrompts.length} User Requests):${RESET}`)
823
+ const displayPrompts = data.userPrompts.slice(0, 6)
824
+ displayPrompts.forEach((p, idx) => {
825
+ console.log(` ${CYAN}Turn ${idx + 1}${RESET} [Step #${p.step}]: ${p.text.slice(0, 90)}${p.text.length > 90 ? '...' : ''}`)
826
+ })
827
+ if (data.userPrompts.length > 6) {
828
+ console.log(` ${DIM}... and ${data.userPrompts.length - 6} more turns (run with -d to see all steps)${RESET}`)
829
+ }
830
+ console.log()
831
+ }
832
+
833
+ console.log(`${BOLD}Token Breakdown by Event Category:${RESET}`)
834
+ console.log(` ${'CATEGORY'.padEnd(25)} ${'CALLS'.padStart(6)} ${'TOKENS'.padStart(10)} ${'PERCENT'.padStart(8)}`)
835
+ console.log(` ${'─'.repeat(25)} ${'─'.repeat(6)} ${'─'.repeat(10)} ${'─'.repeat(8)}`)
836
+
837
+ Object.entries(data.categories)
838
+ .filter(([_, cat]) => cat.count > 0)
839
+ .sort((a, b) => b[1].tokens - a[1].tokens)
840
+ .forEach(([type, cat]) => {
841
+ const pct = Math.round((cat.tokens / data.totalTokens) * 100) || 0
842
+ const color = pct > 40 ? RED : pct > 20 ? YELLOW : CYAN
843
+ console.log(
844
+ ` ${cat.label.padEnd(25)} ` +
845
+ `${String(cat.count).padStart(6)} ` +
846
+ `${BOLD}${formatTokens(cat.tokens).padStart(10)}${RESET} ` +
847
+ `${color}${String(pct + '%').padStart(8)}${RESET}`
848
+ )
849
+ })
850
+
851
+ // Top Files Accessed
852
+ if (data.topViewedFiles.length > 0 || data.topModifiedFiles.length > 0) {
853
+ console.log(`\n${BOLD}Key Files Touched in this Session:${RESET}`)
854
+ if (data.topModifiedFiles.length > 0) {
855
+ console.log(` ${YELLOW}Modified:${RESET} ${data.topModifiedFiles.map(([f, n]) => `${f} (${n}x)`).join(', ')}`)
856
+ }
857
+ if (data.topViewedFiles.length > 0) {
858
+ console.log(` ${CYAN}Viewed:${RESET} ${data.topViewedFiles.map(([f, n]) => `${f} (${n}x)`).join(', ')}`)
859
+ }
860
+ }
861
+
862
+ console.log(`\n${BOLD}Top 5 Largest Token Spikes in this Session:${RESET}`)
863
+ data.spikes.forEach((spike, idx) => {
864
+ console.log(` ${idx + 1}. [Step #${spike.step_index}] ${YELLOW}${formatTokens(spike.tokens)} tokens${RESET} (${spike.type})`)
865
+ console.log(` ${DIM}"${spike.preview}..."${RESET}`)
866
+ })
867
+
868
+ if (showDetail) {
869
+ console.log(`\n${BOLD}Full Step Chronology:${RESET}`)
870
+ steps.forEach(s => {
871
+ let c = ''
872
+ if (typeof s.content === 'string') c = s.content
873
+ else if (s.tool_calls) c = JSON.stringify(s.tool_calls)
874
+ else if (s.content) c = JSON.stringify(s.content)
875
+ const tok = estimateTokens(c)
876
+ const preview = c.replace(/[\r\n\t]+/g, ' ').slice(0, 60).trim()
877
+ console.log(` [#${String(s.step_index).padStart(3)}] ${s.type.padEnd(20)} ${formatTokens(tok).padStart(8)} tokens ${DIM}${preview}${RESET}`)
878
+ })
879
+ } else {
880
+ console.log(`\n${DIM}Commands:${RESET}`)
881
+ console.log(` • Weekly Report: ${CYAN}npx @katlux/toolkit tokens --report${RESET}`)
882
+ console.log(` • Browse list: ${CYAN}npx @katlux/toolkit tokens -p 1${RESET}`)
883
+ console.log(` • Search topic: ${CYAN}npx @katlux/toolkit tokens -s "<keyword>"${RESET}`)
884
+ console.log(` • View step log: ${CYAN}npx @katlux/toolkit tokens ${convIndex} -d${RESET}\n`)
885
+ }