@katlux/toolkit 0.1.1-alpha.146 → 0.1.1-alpha.148

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 (228) hide show
  1. package/README.md +32 -22
  2. package/bin/ai-init.mjs +71 -13
  3. package/bin/ai-tokens/adapters/antigravityAdapter.mjs +22 -0
  4. package/bin/ai-tokens/adapters/claudeCodeAdapter.mjs +192 -0
  5. package/bin/ai-tokens/adapters/codexAdapter.mjs +176 -0
  6. package/bin/ai-tokens/adapters/cursorAdapter.mjs +202 -0
  7. package/bin/ai-tokens/adapters/index.mjs +30 -0
  8. package/bin/ai-tokens/cliViews.mjs +301 -0
  9. package/bin/ai-tokens/formatAndDates.mjs +89 -0
  10. package/bin/ai-tokens/reportGenerator.mjs +232 -0
  11. package/bin/ai-tokens/transcriptParser.mjs +299 -0
  12. package/bin/ai-tokens.mjs +38 -1030
  13. package/bin/cli.mjs +14 -10
  14. package/bin/preset-contracts.json +66 -10
  15. package/dist/compiled/composables/locales/asianAndPacific.mjs +296 -0
  16. package/dist/compiled/composables/locales/northernAndEasternEuropean.mjs +342 -0
  17. package/dist/compiled/composables/locales/westernEuropean.mjs +268 -0
  18. package/dist/compiled/composables/locales.mjs +28 -895
  19. package/dist/compiled/composables/useDataProvider.mjs +3 -1
  20. package/dist/compiled/composables/useKatluxForm.mjs +7 -7
  21. package/dist/compiled/composables/usePresetComponent.mjs +2 -0
  22. package/dist/compiled/composables/useRequestQueue.mjs +3 -1
  23. package/dist/compiled/composables/useVirtualDataset.mjs +322 -354
  24. package/dist/compiled/composables/useVirtualScroll.mjs +69 -62
  25. package/dist/compiled/composables/virtualDataset/cacheStateHelpers.mjs +76 -0
  26. package/dist/compiled/composables/virtualDataset/keyboardNavHelpers.mjs +60 -0
  27. package/dist/compiled/composables/virtualDataset/treeSelectionHelpers.mjs +103 -0
  28. package/dist/compiled/composables/virtualDataset/types.mjs +0 -0
  29. package/dist/compiled/utils/deprecation.mjs +44 -0
  30. package/dist/compiled/utils/dom.mjs +124 -0
  31. package/dist/module.cjs +0 -5
  32. package/dist/module.json +1 -1
  33. package/dist/module.mjs +1 -6
  34. package/dist/runtime/app.config.d.ts +3 -0
  35. package/dist/runtime/components/KBulkActions/KBulkActions.logic.d.ts +8 -0
  36. package/dist/runtime/components/KBulkActions/KBulkActions.logic.js +21 -55
  37. package/dist/runtime/components/KButton/KButton.global.d.vue.ts +1 -1
  38. package/dist/runtime/components/KButton/KButton.global.vue.d.ts +1 -1
  39. package/dist/runtime/components/KButton/KButton.logic.d.ts +1 -1
  40. package/dist/runtime/components/KCalendar/KCalendar.global.d.vue.ts +4 -4
  41. package/dist/runtime/components/KCalendar/KCalendar.global.vue.d.ts +4 -4
  42. package/dist/runtime/components/KCalendar/KCalendar.logic.js +8 -4
  43. package/dist/runtime/components/KCalendar/KCalendarMonth.global.vue +4 -0
  44. package/dist/runtime/components/KCalendar/KCalendarMonth.logic.d.ts +2 -0
  45. package/dist/runtime/components/KCalendar/KCalendarMonth.logic.js +41 -26
  46. package/dist/runtime/components/KCalendar/recurringUtils.js +6 -5
  47. package/dist/runtime/components/KCheckbox/KCheckbox.global.d.vue.ts +1 -1
  48. package/dist/runtime/components/KCheckbox/KCheckbox.global.vue.d.ts +1 -1
  49. package/dist/runtime/components/KCombobox/KCombobox.global.d.vue.ts +17 -2
  50. package/dist/runtime/components/KCombobox/KCombobox.global.vue +9 -4
  51. package/dist/runtime/components/KCombobox/KCombobox.global.vue.d.ts +17 -2
  52. package/dist/runtime/components/KCombobox/KCombobox.logic.d.ts +10 -2
  53. package/dist/runtime/components/KCombobox/KCombobox.logic.js +32 -13
  54. package/dist/runtime/components/KCompositeInput/KCompositeInput.global.d.vue.ts +1 -1
  55. package/dist/runtime/components/KCompositeInput/KCompositeInput.global.vue.d.ts +1 -1
  56. package/dist/runtime/components/KContextMenu/KContextMenu.global.d.vue.ts +3 -3
  57. package/dist/runtime/components/KContextMenu/KContextMenu.global.vue +4 -1
  58. package/dist/runtime/components/KContextMenu/KContextMenu.global.vue.d.ts +3 -3
  59. package/dist/runtime/components/KContextMenu/KContextMenu.logic.d.ts +24 -4
  60. package/dist/runtime/components/KContextMenu/KContextMenu.logic.js +43 -27
  61. package/dist/runtime/components/KDatatable/KDataIterator.global.d.vue.ts +24 -1
  62. package/dist/runtime/components/KDatatable/KDataIterator.global.vue +19 -7
  63. package/dist/runtime/components/KDatatable/KDataIterator.global.vue.d.ts +24 -1
  64. package/dist/runtime/components/KDatatable/KDataIterator.logic.d.ts +20 -0
  65. package/dist/runtime/components/KDatatable/KDataIterator.logic.js +54 -14
  66. package/dist/runtime/components/KDatatable/KDatatable.global.d.vue.ts +1 -1
  67. package/dist/runtime/components/KDatatable/KDatatable.global.vue.d.ts +1 -1
  68. package/dist/runtime/components/KDatatable/KDatatable.logic.js +6 -5
  69. package/dist/runtime/components/KDatePicker/KDatePicker.global.d.vue.ts +6 -4
  70. package/dist/runtime/components/KDatePicker/KDatePicker.global.vue +45 -26
  71. package/dist/runtime/components/KDatePicker/KDatePicker.global.vue.d.ts +6 -4
  72. package/dist/runtime/components/KDatePicker/KDatePicker.logic.d.ts +2 -0
  73. package/dist/runtime/components/KDatePicker/KDatePicker.logic.js +66 -20
  74. package/dist/runtime/components/KDateTimePicker/KDateTimePicker.global.d.vue.ts +3 -3
  75. package/dist/runtime/components/KDateTimePicker/KDateTimePicker.global.vue.d.ts +3 -3
  76. package/dist/runtime/components/KDropdown/KDropdown.global.d.vue.ts +4 -4
  77. package/dist/runtime/components/KDropdown/KDropdown.global.vue.d.ts +4 -4
  78. package/dist/runtime/components/KDropdown/KDropdown.logic.d.ts +3 -2
  79. package/dist/runtime/components/KDropdown/KDropdown.logic.js +14 -13
  80. package/dist/runtime/components/KGantt/KGantt.global.d.vue.ts +3 -1
  81. package/dist/runtime/components/KGantt/KGantt.global.vue +7 -1
  82. package/dist/runtime/components/KGantt/KGantt.global.vue.d.ts +3 -1
  83. package/dist/runtime/components/KGrid/KGrid.global.d.vue.ts +1 -1
  84. package/dist/runtime/components/KGrid/KGrid.global.vue.d.ts +1 -1
  85. package/dist/runtime/components/KHourPicker/KHourPicker.global.d.vue.ts +1 -1
  86. package/dist/runtime/components/KHourPicker/KHourPicker.global.vue.d.ts +1 -1
  87. package/dist/runtime/components/KIcon/KIcon.global.d.vue.ts +1 -1
  88. package/dist/runtime/components/KIcon/KIcon.global.vue.d.ts +1 -1
  89. package/dist/runtime/components/KLayout/KLayout.global.d.vue.ts +4 -1
  90. package/dist/runtime/components/KLayout/KLayout.global.vue +4 -1
  91. package/dist/runtime/components/KLayout/KLayout.global.vue.d.ts +4 -1
  92. package/dist/runtime/components/KLoader/KLoader.global.d.vue.ts +9 -0
  93. package/dist/runtime/components/KLoader/KLoader.global.vue +1 -0
  94. package/dist/runtime/components/KLoader/KLoader.global.vue.d.ts +9 -0
  95. package/dist/runtime/components/KLoader/KLoader.logic.d.ts +5 -0
  96. package/dist/runtime/components/KLoader/KLoader.logic.js +4 -0
  97. package/dist/runtime/components/KMaskTextbox/KMaskTextbox.logic.js +30 -7
  98. package/dist/runtime/components/KMultiTabs/KMultiTabs.logic.d.ts +1 -0
  99. package/dist/runtime/components/KMultiTabs/MultiTabs.global.vue +6 -4
  100. package/dist/runtime/components/KPagination/KPagination.logic.d.ts +1 -1
  101. package/dist/runtime/components/KPagination/KPagination.logic.js +17 -9
  102. package/dist/runtime/components/KRangeSlider/KRangeSlider.global.d.vue.ts +1 -1
  103. package/dist/runtime/components/KRangeSlider/KRangeSlider.global.vue.d.ts +1 -1
  104. package/dist/runtime/components/KSlider/KSlider.global.d.vue.ts +1 -1
  105. package/dist/runtime/components/KSlider/KSlider.global.vue.d.ts +1 -1
  106. package/dist/runtime/components/KTabs/KTabs.logic.js +33 -11
  107. package/dist/runtime/components/KTextarea/KTextarea.global.d.vue.ts +1 -1
  108. package/dist/runtime/components/KTextarea/KTextarea.global.vue.d.ts +1 -1
  109. package/dist/runtime/components/KTextbox/KTextbox.global.d.vue.ts +12 -1
  110. package/dist/runtime/components/KTextbox/KTextbox.global.vue +8 -2
  111. package/dist/runtime/components/KTextbox/KTextbox.global.vue.d.ts +12 -1
  112. package/dist/runtime/components/KTextbox/KTextbox.logic.d.ts +5 -0
  113. package/dist/runtime/components/KTextbox/KTextbox.logic.js +4 -0
  114. package/dist/runtime/components/KTooltip/KTooltip.global.d.vue.ts +1 -1
  115. package/dist/runtime/components/KTooltip/KTooltip.global.vue.d.ts +1 -1
  116. package/dist/runtime/components/KTooltip/KTooltip.logic.d.ts +11 -2
  117. package/dist/runtime/components/KTooltip/KTooltip.logic.js +7 -5
  118. package/dist/runtime/components/KTree/KTree.global.d.vue.ts +1 -1
  119. package/dist/runtime/components/KTree/KTree.global.vue.d.ts +1 -1
  120. package/dist/runtime/components/KTree/KTree.logic.js +21 -1
  121. package/dist/runtime/components/KTreePicker/KTreePicker.global.d.vue.ts +8 -4
  122. package/dist/runtime/components/KTreePicker/KTreePicker.global.vue +4 -2
  123. package/dist/runtime/components/KTreePicker/KTreePicker.global.vue.d.ts +8 -4
  124. package/dist/runtime/components/KTreePicker/KTreePicker.logic.d.ts +3 -2
  125. package/dist/runtime/components/KTreePicker/KTreePicker.logic.js +10 -1
  126. package/dist/runtime/components/KTreeView/KTreeView.global.d.vue.ts +3 -3
  127. package/dist/runtime/components/KTreeView/KTreeView.global.vue.d.ts +3 -3
  128. package/dist/runtime/components/KTreeView/KTreeView.logic.d.ts +1 -1
  129. package/dist/runtime/components/KTreeView/KTreeView.logic.js +36 -12
  130. package/dist/runtime/composables/locales/asianAndPacific.d.ts +11 -0
  131. package/dist/runtime/composables/locales/asianAndPacific.js +296 -0
  132. package/dist/runtime/composables/locales/northernAndEasternEuropean.d.ts +12 -0
  133. package/dist/runtime/composables/locales/northernAndEasternEuropean.js +342 -0
  134. package/dist/runtime/composables/locales/westernEuropean.d.ts +10 -0
  135. package/dist/runtime/composables/locales/westernEuropean.js +268 -0
  136. package/dist/runtime/composables/locales.d.ts +4 -24
  137. package/dist/runtime/composables/locales.js +28 -895
  138. package/dist/runtime/composables/useDataProvider.js +3 -1
  139. package/dist/runtime/composables/useKatluxForm.js +7 -7
  140. package/dist/runtime/composables/usePresetComponent.js +2 -0
  141. package/dist/runtime/composables/useRequestQueue.d.ts +2 -0
  142. package/dist/runtime/composables/useRequestQueue.js +3 -1
  143. package/dist/runtime/composables/useVirtualDataset.d.ts +6 -118
  144. package/dist/runtime/composables/useVirtualDataset.js +322 -354
  145. package/dist/runtime/composables/useVirtualScroll.d.ts +9 -9
  146. package/dist/runtime/composables/useVirtualScroll.js +69 -62
  147. package/dist/runtime/composables/virtualDataset/cacheStateHelpers.d.ts +49 -0
  148. package/dist/runtime/composables/virtualDataset/cacheStateHelpers.js +76 -0
  149. package/dist/runtime/composables/virtualDataset/keyboardNavHelpers.d.ts +26 -0
  150. package/dist/runtime/composables/virtualDataset/keyboardNavHelpers.js +60 -0
  151. package/dist/runtime/composables/virtualDataset/treeSelectionHelpers.d.ts +24 -0
  152. package/dist/runtime/composables/virtualDataset/treeSelectionHelpers.js +103 -0
  153. package/dist/runtime/composables/virtualDataset/types.d.ts +113 -0
  154. package/dist/runtime/composables/virtualDataset/types.js +0 -0
  155. package/dist/runtime/directives/clickOutside.d.ts +1 -1
  156. package/dist/runtime/directives/clickOutside.js +41 -13
  157. package/dist/runtime/plugins/nuxtCompatPlugin.d.ts +2 -1
  158. package/dist/runtime/plugins/nuxtCompatPlugin.js +7 -0
  159. package/dist/runtime/plugins/toastPlugin.client.js +2 -2
  160. package/dist/runtime/presets/default/components/KCalendar/KCalendarMonth.d.vue.ts +2 -0
  161. package/dist/runtime/presets/default/components/KCalendar/KCalendarMonth.vue +24 -0
  162. package/dist/runtime/presets/default/components/KCalendar/KCalendarMonth.vue.d.ts +2 -0
  163. package/dist/runtime/presets/default/components/KCalendar/KCalendarWeek.vue +6 -5
  164. package/dist/runtime/presets/default/components/KCombobox/KCombobox.d.vue.ts +4 -1
  165. package/dist/runtime/presets/default/components/KCombobox/KCombobox.vue +27 -17
  166. package/dist/runtime/presets/default/components/KCombobox/KCombobox.vue.d.ts +4 -1
  167. package/dist/runtime/presets/default/components/KCombobox/KComboboxList.d.vue.ts +1 -1
  168. package/dist/runtime/presets/default/components/KCombobox/KComboboxList.vue +10 -10
  169. package/dist/runtime/presets/default/components/KCombobox/KComboboxList.vue.d.ts +1 -1
  170. package/dist/runtime/presets/default/components/KContextMenu/KContextMenu.d.vue.ts +2 -0
  171. package/dist/runtime/presets/default/components/KContextMenu/KContextMenu.vue +60 -21
  172. package/dist/runtime/presets/default/components/KContextMenu/KContextMenu.vue.d.ts +2 -0
  173. package/dist/runtime/presets/default/components/KDataIterator/KDataIterator.d.vue.ts +12 -1
  174. package/dist/runtime/presets/default/components/KDataIterator/KDataIterator.vue +109 -15
  175. package/dist/runtime/presets/default/components/KDataIterator/KDataIterator.vue.d.ts +12 -1
  176. package/dist/runtime/presets/default/components/KDatatable/KDatatable.d.vue.ts +1 -1
  177. package/dist/runtime/presets/default/components/KDatatable/KDatatable.vue +14 -0
  178. package/dist/runtime/presets/default/components/KDatatable/KDatatable.vue.d.ts +1 -1
  179. package/dist/runtime/presets/default/components/KDropdown/KDropdown.d.vue.ts +5 -2
  180. package/dist/runtime/presets/default/components/KDropdown/KDropdown.vue +15 -12
  181. package/dist/runtime/presets/default/components/KDropdown/KDropdown.vue.d.ts +5 -2
  182. package/dist/runtime/presets/default/components/KGantt/KGantt.d.vue.ts +10 -0
  183. package/dist/runtime/presets/default/components/KGantt/KGantt.vue +23 -69
  184. package/dist/runtime/presets/default/components/KGantt/KGantt.vue.d.ts +10 -0
  185. package/dist/runtime/presets/default/components/KGantt/KGanttTimeline.d.vue.ts +6 -2
  186. package/dist/runtime/presets/default/components/KGantt/KGanttTimeline.vue +22 -8
  187. package/dist/runtime/presets/default/components/KGantt/KGanttTimeline.vue.d.ts +6 -2
  188. package/dist/runtime/presets/default/components/KLayout/KLayout.vue +2 -2
  189. package/dist/runtime/presets/default/components/KLoader/KLoader.d.vue.ts +1 -0
  190. package/dist/runtime/presets/default/components/KLoader/KLoader.vue +13 -2
  191. package/dist/runtime/presets/default/components/KLoader/KLoader.vue.d.ts +1 -0
  192. package/dist/runtime/presets/default/components/KMaskTextbox/KMaskTextbox.vue +1 -94
  193. package/dist/runtime/presets/default/components/KMultiTabs/KMultiTabs.vue +69 -4
  194. package/dist/runtime/presets/default/components/KRangeSlider/KRangeSlider.vue +18 -46
  195. package/dist/runtime/presets/default/components/KSlider/KSlider.vue +11 -23
  196. package/dist/runtime/presets/default/components/KTextbox/KTextbox.d.vue.ts +4 -1
  197. package/dist/runtime/presets/default/components/KTextbox/KTextbox.vue +24 -8
  198. package/dist/runtime/presets/default/components/KTextbox/KTextbox.vue.d.ts +4 -1
  199. package/dist/runtime/presets/default/components/KTree/KTree.d.vue.ts +1 -1
  200. package/dist/runtime/presets/default/components/KTree/KTree.vue +51 -80
  201. package/dist/runtime/presets/default/components/KTree/KTree.vue.d.ts +1 -1
  202. package/dist/runtime/presets/default/components/KTree/KTreeNodeItem.d.vue.ts +1 -0
  203. package/dist/runtime/presets/default/components/KTree/KTreeNodeItem.vue +12 -2
  204. package/dist/runtime/presets/default/components/KTree/KTreeNodeItem.vue.d.ts +1 -0
  205. package/dist/runtime/server/middleware/session.js +7 -0
  206. package/dist/runtime/utils/deprecation.d.ts +14 -0
  207. package/dist/runtime/utils/deprecation.js +44 -0
  208. package/dist/runtime/utils/dom.d.ts +31 -0
  209. package/dist/runtime/utils/dom.js +124 -0
  210. package/dist/skills/KATLUX_INDEX.md +15 -19
  211. package/dist/skills/katlux-components/components/KBulkActions.md +1 -1
  212. package/dist/skills/katlux-components/components/KDataIterator.md +5 -0
  213. package/dist/skills/katlux-components/components/KLayout.md +4 -0
  214. package/dist/skills/katlux-components/components/KLoader.md +3 -0
  215. package/dist/skills/katlux-components/components/KTextbox.md +1 -0
  216. package/dist/skills/katlux-config/SKILL.md +15 -7
  217. package/dist/skills/katlux-presets/SKILL.md +42 -2
  218. package/dist/skills/katlux-providers/SKILL.md +12 -0
  219. package/dist/skills/katlux-providers/providers/ADataProvider.md +1 -0
  220. package/dist/skills/katlux-providers/providers/CAPITreeServerDataProvider.md +13 -0
  221. package/dist/skills/katlux-providers/providers/RequestProvider.md +2 -2
  222. package/dist/skills/katlux-providers/providers/encryption-field-level.md +5 -2
  223. package/dist/skills/katlux-providers/providers/encryption-key-management.md +5 -2
  224. package/dist/skills/katlux-providers/providers/encryption-searchable.md +150 -27
  225. package/dist/skills/katlux-providers/providers/encryption-symmetric.md +4 -1
  226. package/dist/skills/katlux-providers/providers/encryption-threat-model.md +12 -6
  227. package/dist/skills/katlux-providers/providers/encryption.md +1 -1
  228. package/package.json +3 -3
@@ -0,0 +1,232 @@
1
+ import { writeFileSync } from 'node:fs'
2
+ import { resolve } from 'node:path'
3
+ import {
4
+ ANSI,
5
+ formatTokens,
6
+ getWeekDateRange
7
+ } from './formatAndDates.mjs'
8
+ import { getIdeAdapter } from './adapters/index.mjs'
9
+
10
+ const { RESET, BOLD, DIM, CYAN, GREEN, YELLOW, RED } = ANSI
11
+
12
+ /** Prints all detected workspace projects with session counts and token totals. */
13
+ export function listDetectedProjects(conversations, adapter = getIdeAdapter('antigravity')) {
14
+ const headerTitle = `DETECTED ${adapter.displayName.toUpperCase()} PROJECTS`.padStart(48).padEnd(76)
15
+ console.log(`\n${BOLD}╭──────────────────────────────────────────────────────────────────────────────╮${RESET}`)
16
+ console.log(`${BOLD}│${headerTitle}│${RESET}`)
17
+ console.log(`${BOLD}╰──────────────────────────────────────────────────────────────────────────────╯${RESET}`)
18
+
19
+ const projectMap = new Map()
20
+ conversations.forEach(c => {
21
+ const prj = c.preview.project
22
+ if (prj === 'Unknown' || c.preview.rawSize === 0) return
23
+ if (!projectMap.has(prj)) projectMap.set(prj, { name: prj, count: 0, tokens: 0, latest: c.mtime })
24
+ const p = projectMap.get(prj)
25
+ p.count++
26
+ p.tokens += c.preview.estimatedTokens
27
+ if (c.mtime > p.latest) p.latest = c.mtime
28
+ })
29
+
30
+ console.log(` ${'#'.padStart(3)} ${'PROJECT NAME'.padEnd(26)} ${'SESSIONS'.padStart(10)} ${'TOTAL TOKENS'.padStart(14)} LAST ACTIVE`)
31
+ console.log(` ${'─'.repeat(3)} ${'─'.repeat(26)} ${'─'.repeat(10)} ${'─'.repeat(14)} ${'─'.repeat(16)}`)
32
+
33
+ let idx = 1
34
+ for (const p of projectMap.values()) {
35
+ const dateStr = p.latest.toLocaleDateString() + ' ' + p.latest.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
36
+ console.log(
37
+ ` ${CYAN}${String(idx++).padStart(3)}${RESET} ` +
38
+ `${BOLD}${p.name.padEnd(26)}${RESET} ` +
39
+ `${String(p.count).padStart(10)} ` +
40
+ `${formatTokens(p.tokens).padStart(14)} ` +
41
+ `${DIM}${dateStr}${RESET}`
42
+ )
43
+ }
44
+
45
+ console.log(`\n${BOLD}Filter Commands:${RESET}`)
46
+ for (const p of projectMap.values()) {
47
+ console.log(` • View ${p.name}: ${CYAN}npm run ai:tokens -- -P ${p.name} --report${RESET}`)
48
+ }
49
+ console.log()
50
+ }
51
+
52
+ /** Generates week-by-week Markdown and visual terminal reports across conversations. */
53
+ export function generateWeekReport({ weekFilter = '', projectFilter = '', asMarkdown = false, saveFile = false, adapter = getIdeAdapter('antigravity') }) {
54
+ const all = adapter.getConversations()
55
+ if (all.length === 0) {
56
+ console.log(`${RED}${adapter.emptyMessage}${RESET}`)
57
+ return
58
+ }
59
+
60
+ const mapped = all.map((c, i) => ({
61
+ ...c,
62
+ originalIndex: i + 1,
63
+ preview: adapter.getConversationPreviewFast(c.path)
64
+ }))
65
+
66
+ let filtered = mapped
67
+ if (projectFilter) {
68
+ const q = projectFilter.toLowerCase()
69
+ filtered = mapped.filter(c => c.preview.project.toLowerCase().includes(q))
70
+ if (filtered.length === 0) {
71
+ console.log(`\n${RED}No sessions found for project matching "${projectFilter}".${RESET}`)
72
+ console.log(`Run ${CYAN}npm run ai:tokens -- --projects${RESET} to view all detected projects.\n`)
73
+ return
74
+ }
75
+ }
76
+
77
+ const activeConversations = filtered.filter(c => c.preview.rawSize > 0)
78
+ const weeklyMap = new Map()
79
+
80
+ activeConversations.forEach(conv => {
81
+ const wk = conv.weekKey
82
+ if (!weeklyMap.has(wk)) {
83
+ weeklyMap.set(wk, { weekKey: wk, dateRange: getWeekDateRange(wk), dirs: [] })
84
+ }
85
+ weeklyMap.get(wk).dirs.push(conv)
86
+ })
87
+
88
+ const weeklyStats = []
89
+ for (const [wk, entry] of weeklyMap.entries()) {
90
+ if (weekFilter && !wk.toLowerCase().includes(weekFilter.toLowerCase())) continue
91
+ const analyzedSessions = entry.dirs.map(d => {
92
+ const steps = adapter.parseTranscript(d.path)
93
+ return steps ? adapter.analyzeSession(steps, d.id, d.mtime, d.preview.project) : null
94
+ }).filter(Boolean)
95
+ if (analyzedSessions.length === 0) continue
96
+
97
+ const realTasks = analyzedSessions.filter(s => s.totalSteps >= 6)
98
+ const targetSessions = realTasks.length > 0 ? realTasks : analyzedSessions
99
+ const trivialCount = analyzedSessions.length - targetSessions.length
100
+ const count = targetSessions.length
101
+ const sum = (fn) => targetSessions.reduce((s, x) => s + fn(x), 0)
102
+ const avg = (fn) => Math.round(sum(fn) / count)
103
+
104
+ const avgInputTokens = avg(s => s.inputTokens)
105
+ const avgOutputTokens = avg(s => s.outputTokens)
106
+ const weekCategories = {}
107
+ const weekViewedFiles = new Map()
108
+ const weekModifiedFiles = new Map()
109
+
110
+ targetSessions.forEach(s => {
111
+ Object.entries(s.categories).forEach(([k, cat]) => {
112
+ if (!weekCategories[k]) weekCategories[k] = { label: cat.label, count: 0, tokens: 0 }
113
+ weekCategories[k].count += cat.count
114
+ weekCategories[k].tokens += cat.tokens
115
+ })
116
+ s.allFilesViewed.forEach((c, f) => weekViewedFiles.set(f, (weekViewedFiles.get(f) || 0) + c))
117
+ s.allFilesModified.forEach((c, f) => weekModifiedFiles.set(f, (weekModifiedFiles.get(f) || 0) + c))
118
+ })
119
+
120
+ weeklyStats.push({
121
+ weekKey: wk,
122
+ dateRange: entry.dateRange,
123
+ sessionCount: count,
124
+ trivialCount,
125
+ totalTokensSum: sum(s => s.totalTokens),
126
+ avgTotalTokens: avg(s => s.totalTokens),
127
+ avgRunCmdTokens: avg(s => s.categories.RUN_COMMAND?.tokens || 0),
128
+ avgViewFileTokens: avg(s => s.categories.VIEW_FILE?.tokens || 0),
129
+ avgMcpTokens: avg(s => s.categories.MCP_TOOL?.tokens || 0),
130
+ avgMcpCalls: avg(s => s.mcpCalls?.total || 0),
131
+ avgSteps: avg(s => s.totalSteps),
132
+ claudeCost: ((avgInputTokens / 1_000_000) * 3.00 + (avgOutputTokens / 1_000_000) * 15.00).toFixed(2),
133
+ geminiCost: ((avgInputTokens / 1_000_000) * 0.35 + (avgOutputTokens / 1_000_000) * 1.05).toFixed(3),
134
+ categories: weekCategories,
135
+ topViewed: [...weekViewedFiles.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5),
136
+ topModified: [...weekModifiedFiles.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5)
137
+ })
138
+ }
139
+
140
+ weeklyStats.sort((a, b) => b.weekKey.localeCompare(a.weekKey))
141
+ for (let i = 0; i < weeklyStats.length; i++) {
142
+ const current = weeklyStats[i]
143
+ const prior = weeklyStats[i + 1]
144
+ current.wowPct = prior && prior.avgTotalTokens > 0
145
+ ? (((current.avgTotalTokens - prior.avgTotalTokens) / prior.avgTotalTokens) * 100).toFixed(1)
146
+ : null
147
+ }
148
+
149
+ const projectLabel = projectFilter ? `Project: ${projectFilter}` : 'All Projects'
150
+ const md = [
151
+ `# Antigravity AI Token Usage: Week-by-Week Report`,
152
+ `*Scope: ${projectLabel} | Analyzed ${activeConversations.length} sessions across ${weeklyStats.length} calendar weeks*\n`,
153
+ `## 1. Week-by-Week Token & Efficiency Progression\n`,
154
+ `| Calendar Week | Date Range | Tasks | Avg Tokens / Task | Avg Test Tokens | Avg File View | Avg MCP Tokens | Avg Steps | Avg Cost (Claude) | WoW Trend |`,
155
+ `| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |`
156
+ ]
157
+
158
+ weeklyStats.forEach((w, idx) => {
159
+ const isCurrent = idx === 0 ? ' **(Current)**' : ''
160
+ const wowStr = w.wowPct !== null ? `${Number(w.wowPct) <= 0 ? w.wowPct + '%' : '+' + w.wowPct + '%'}` : '—'
161
+ md.push(`| **${w.weekKey}**${isCurrent} | ${w.dateRange} | ${w.sessionCount} | **${formatTokens(w.avgTotalTokens)}** | ${formatTokens(w.avgRunCmdTokens)} | ${formatTokens(w.avgViewFileTokens)} | ${formatTokens(w.avgMcpTokens)} | ${w.avgSteps} | $${w.claudeCost} | ${wowStr} |`)
162
+ })
163
+ md.push('', `## 2. Weekly Details & Most Frequent Files\n`)
164
+
165
+ weeklyStats.forEach(w => {
166
+ const trivialSuffix = w.trivialCount > 0 ? ` (+${w.trivialCount} trivial)` : ''
167
+ md.push(`### ${w.weekKey} (${w.dateRange}) — ${w.sessionCount} Tasks${trivialSuffix} | Avg ${formatTokens(w.avgTotalTokens)} Tokens | Cost $${w.claudeCost}`)
168
+ if (w.topViewed.length > 0) md.push(`- **Most Read Files:** ${w.topViewed.map(([f, n]) => `\`${f}\` (${n}x)`).join(', ')}`)
169
+ if (w.topModified.length > 0) md.push(`- **Most Edited Files:** ${w.topModified.map(([f, n]) => `\`${f}\` (${n}x)`).join(', ')}`)
170
+ const totalWeekTokens = Object.values(w.categories).reduce((s, x) => s + x.tokens, 0)
171
+ const catPcts = Object.values(w.categories).filter(c => c.tokens > 0).sort((a, b) => b.tokens - a.tokens)
172
+ .map(c => `${c.label}: ${((c.tokens / totalWeekTokens) * 100).toFixed(0)}%`).slice(0, 4).join(' | ')
173
+ if (catPcts) md.push(`- **Key Categories:** ${catPcts}`)
174
+ md.push('')
175
+ })
176
+
177
+ const mdOutput = md.join('\n')
178
+ if (saveFile) {
179
+ const outPath = resolve(process.cwd(), 'token-report.md')
180
+ writeFileSync(outPath, mdOutput, 'utf-8')
181
+ console.log(`${GREEN}✓ Week-by-week report saved to ${outPath}${RESET}\n`)
182
+ }
183
+ if (asMarkdown) {
184
+ console.log(mdOutput)
185
+ return
186
+ }
187
+
188
+ console.log(`\n${BOLD}╭──────────────────────────────────────────────────────────────────────────────╮${RESET}`)
189
+ console.log(`${BOLD}│ ANTIGRAVITY AI TOKEN USAGE: WEEK-BY-WEEK REPORT │${RESET}`)
190
+ console.log(`${BOLD}╰──────────────────────────────────────────────────────────────────────────────╯${RESET}`)
191
+ console.log(` Scope: ${BOLD}${projectLabel}${RESET} (${activeConversations.length} total sessions analyzed across ${weeklyStats.length} calendar weeks)\n`)
192
+ console.log(`${BOLD}1. WEEK-BY-WEEK PROGRESSION TABLE${RESET}`)
193
+ console.log(` ${'WEEK'.padEnd(10)} ${'DATE RANGE'.padEnd(16)} ${'TASKS'.padStart(6)} ${'AVG TOKENS'.padStart(11)} ${'TESTS'.padStart(8)} ${'VIEW'.padStart(8)} ${'MCP'.padStart(8)} ${'STEPS'.padStart(6)} ${'COST'.padStart(7)} ${'WoW TREND'.padStart(10)}`)
194
+ console.log(` ${'─'.repeat(10)} ${'─'.repeat(16)} ${'─'.repeat(6)} ${'─'.repeat(11)} ${'─'.repeat(8)} ${'─'.repeat(8)} ${'─'.repeat(8)} ${'─'.repeat(6)} ${'─'.repeat(7)} ${'─'.repeat(10)}`)
195
+
196
+ weeklyStats.forEach((w, idx) => {
197
+ const isCurrent = idx === 0
198
+ const weekLabel = (w.weekKey.replace('2026-', '') + (isCurrent ? '*' : '')).padEnd(10)
199
+ const wowColor = w.wowPct && Number(w.wowPct) <= 0 ? GREEN : (w.wowPct ? RED : DIM)
200
+ const wowStr = w.wowPct !== null ? (Number(w.wowPct) <= 0 ? w.wowPct + '%' : '+' + w.wowPct + '%') : '—'
201
+ console.log(
202
+ ` ${isCurrent ? GREEN : CYAN}${weekLabel}${RESET} ` +
203
+ `${w.dateRange.padEnd(16)} ${String(w.sessionCount).padStart(6)} ` +
204
+ `${BOLD}${formatTokens(w.avgTotalTokens).padStart(11)}${RESET} ` +
205
+ `${formatTokens(w.avgRunCmdTokens).padStart(8)} ${formatTokens(w.avgViewFileTokens).padStart(8)} ` +
206
+ `${formatTokens(w.avgMcpTokens).padStart(8)} ${String(w.avgSteps).padStart(6)} ` +
207
+ `${('$' + w.claudeCost).padStart(7)} ${wowColor}${wowStr.padStart(10)}${RESET}`
208
+ )
209
+ })
210
+
211
+ console.log(` ${DIM}* Current calendar week. Costs estimated using Claude 3.5 Sonnet.${RESET}\n`)
212
+ console.log(`${BOLD}2. WEEKLY DETAILS & MOST FREQUENT FILES${RESET}`)
213
+ weeklyStats.forEach(w => {
214
+ const totalWeekTokens = Object.values(w.categories).reduce((s, x) => s + x.tokens, 0)
215
+ const trivialSuffix = w.trivialCount > 0 ? ` (+${w.trivialCount} trivial)` : ''
216
+ console.log(` ${CYAN}${BOLD}[Week ${w.weekKey}: ${w.dateRange}]${RESET} — ${w.sessionCount} Tasks${trivialSuffix} | Avg ${formatTokens(w.avgTotalTokens)} Tokens | Avg Steps: ${w.avgSteps}`)
217
+ if (w.topViewed.length > 0) console.log(` ${CYAN}Most Read:${RESET} ${w.topViewed.map(([f, n]) => `${f} (${n}x)`).join(', ')}`)
218
+ if (w.topModified.length > 0) console.log(` ${YELLOW}Most Edited:${RESET} ${w.topModified.map(([f, n]) => `${f} (${n}x)`).join(', ')}`)
219
+ const topCats = Object.values(w.categories).filter(c => c.tokens > 0).sort((a, b) => b.tokens - a.tokens)
220
+ .slice(0, 4).map(c => `${c.label}: ${((c.tokens / totalWeekTokens) * 100).toFixed(0)}%`).join(' | ')
221
+ if (topCats) console.log(` ${DIM}Categories:${RESET} ${DIM}${topCats}${RESET}`)
222
+ console.log()
223
+ })
224
+
225
+ console.log(`${DIM}Commands:${RESET}`)
226
+ console.log(` • Filter project: ${CYAN}npm run ai:tokens -- -P <projectName> --report${RESET}`)
227
+ console.log(` • List projects: ${CYAN}npm run ai:tokens -- --projects${RESET}`)
228
+ console.log(` • Save as Markdown: ${CYAN}npm run ai:tokens -- --report --save${RESET}`)
229
+ console.log(` • Filter single week:${CYAN}npm run ai:tokens -- -w W43${RESET}`)
230
+ console.log(` • Browse sessions: ${CYAN}npm run ai:tokens -- -p 1${RESET}\n`)
231
+ }
232
+
@@ -0,0 +1,299 @@
1
+ import { existsSync, readdirSync, statSync, readFileSync, openSync, readSync, closeSync } from 'node:fs'
2
+ import { join, basename } from 'node:path'
3
+ import {
4
+ BRAIN_DIRS,
5
+ cleanString,
6
+ estimateTokens,
7
+ formatDateTime,
8
+ getWeekKey
9
+ } from './formatAndDates.mjs'
10
+
11
+ /**
12
+ * Performs fast 16KB header inspection of a conversation transcript without loading the full JSONL.
13
+ */
14
+ export function getConversationPreviewFast(dirPath, searchQuery = '') {
15
+ const pFull = join(dirPath, '.system_generated/logs/transcript_full.jsonl')
16
+ const pNorm = join(dirPath, '.system_generated/logs/transcript.jsonl')
17
+ const p = existsSync(pFull) ? pFull : pNorm
18
+ if (!existsSync(p)) return { project: 'Unknown', title: '(empty transcript)', fullTitle: '', rawSize: 0, estimatedTokens: 0, matchesSearch: false, stepsCount: 0 }
19
+
20
+ try {
21
+ const stat = statSync(p)
22
+ if (stat.size === 0) return { project: 'Unknown', title: '(empty transcript)', fullTitle: '', rawSize: 0, estimatedTokens: 0, matchesSearch: false, stepsCount: 0 }
23
+
24
+ let fd
25
+ let chunk = ''
26
+ try {
27
+ fd = openSync(p, 'r')
28
+ const buf = Buffer.alloc(16384)
29
+ const bytesRead = readSync(fd, buf, 0, 16384, 0)
30
+ closeSync(fd)
31
+ chunk = buf.toString('utf-8', 0, bytesRead)
32
+ } catch {
33
+ if (fd !== undefined) try { closeSync(fd) } catch {}
34
+ }
35
+
36
+ let project = 'Unknown'
37
+ const m1 = chunk.match(/\[URI\] -> \[CorpusName\]:\s*\n([^\s\n\r]+)\s*->/)
38
+ if (m1) {
39
+ project = basename(m1[1])
40
+ } else {
41
+ const m2 = chunk.match(/\/Desktop\/projects\/([a-zA-Z0-9_\-]+)/)
42
+ if (m2) project = m2[1]
43
+ else {
44
+ const m3 = chunk.match(/\/projects\/([a-zA-Z0-9_\-]+)/)
45
+ if (m3) project = m3[1]
46
+ }
47
+ }
48
+
49
+ let title = '(no user prompt recorded)'
50
+ const reqMatch = chunk.match(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/)
51
+ if (reqMatch) {
52
+ title = reqMatch[1].replace(/\\n/g, ' ').replace(/[\r\n\t]+/g, ' ').trim()
53
+ } else {
54
+ const contentMatch = chunk.match(/"type":"USER_INPUT"[\s\S]*?"content":"([^"]+)"/)
55
+ if (contentMatch) title = contentMatch[1].replace(/\\n/g, ' ').replace(/[\r\n\t]+/g, ' ').trim()
56
+ }
57
+
58
+ let matchesSearch = false
59
+ if (searchQuery) {
60
+ matchesSearch = chunk.toLowerCase().includes(searchQuery)
61
+ }
62
+
63
+ const estimatedTokens = Math.ceil(stat.size / 3.75)
64
+ const approxSteps = Math.max(1, Math.round(stat.size / 1450))
65
+
66
+ return {
67
+ project,
68
+ title: title.slice(0, 42),
69
+ fullTitle: title,
70
+ rawSize: stat.size,
71
+ estimatedTokens,
72
+ matchesSearch,
73
+ stepsCount: approxSteps
74
+ }
75
+ } catch {
76
+ return { project: 'Unknown', title: '(read error)', fullTitle: '', rawSize: 0, estimatedTokens: 0, matchesSearch: false, stepsCount: 0 }
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Lists all Antigravity conversation directories sorted newest-first by activity time.
82
+ */
83
+ export function getConversations() {
84
+ const validDirs = BRAIN_DIRS.filter(d => existsSync(d))
85
+ if (validDirs.length === 0) return []
86
+
87
+ const seen = new Set()
88
+ const results = []
89
+
90
+ for (const bDir of validDirs) {
91
+ const entries = readdirSync(bDir, { withFileTypes: true })
92
+ for (const e of entries) {
93
+ if (!e.isDirectory() || e.name === 'tempmediaStorage' || e.name.startsWith('.')) continue
94
+ if (seen.has(e.name)) continue
95
+ seen.add(e.name)
96
+
97
+ const dirPath = join(bDir, e.name)
98
+ const transcriptPath = join(dirPath, '.system_generated/logs/transcript.jsonl')
99
+ const dirStat = statSync(dirPath)
100
+ let lastActive = dirStat.mtime
101
+ if (existsSync(transcriptPath)) {
102
+ try {
103
+ lastActive = statSync(transcriptPath).mtime
104
+ } catch {}
105
+ }
106
+ results.push({
107
+ id: e.name,
108
+ path: dirPath,
109
+ createdAt: dirStat.mtime,
110
+ lastActive,
111
+ mtime: lastActive,
112
+ weekKey: getWeekKey(lastActive)
113
+ })
114
+ }
115
+ }
116
+
117
+ return results.sort((a, b) => b.lastActive.getTime() - a.lastActive.getTime())
118
+ }
119
+
120
+ /**
121
+ * Parses a conversation's JSONL transcript into structured step entries.
122
+ */
123
+ export function parseTranscript(conversationDir) {
124
+ const transcriptFullPath = join(conversationDir, '.system_generated/logs/transcript_full.jsonl')
125
+ const transcriptPath = join(conversationDir, '.system_generated/logs/transcript.jsonl')
126
+ const targetPath = existsSync(transcriptFullPath) ? transcriptFullPath : transcriptPath
127
+ if (!existsSync(targetPath)) return null
128
+
129
+ const raw = readFileSync(targetPath, 'utf-8')
130
+ const lines = raw.trim().split('\n').filter(Boolean)
131
+
132
+ const steps = []
133
+ for (let i = 0; i < lines.length; i++) {
134
+ try {
135
+ const obj = JSON.parse(lines[i])
136
+ steps.push(obj)
137
+ } catch {}
138
+ }
139
+ return steps
140
+ }
141
+
142
+ function resolveStepContent(step) {
143
+ const type = step.type || 'OTHER'
144
+ if (type === 'PLANNER_RESPONSE') {
145
+ const parts = []
146
+ if (typeof step.content === 'string' && step.content) parts.push(step.content)
147
+ else if (step.content && typeof step.content !== 'string') parts.push(JSON.stringify(step.content))
148
+ if (step.thinking && typeof step.thinking === 'string') parts.push(step.thinking)
149
+ if (step.tool_calls) parts.push(JSON.stringify(step.tool_calls))
150
+ return parts.join('\n')
151
+ }
152
+ if (typeof step.content === 'string') return step.content
153
+ if (step.tool_calls) return JSON.stringify(step.tool_calls)
154
+ if (step.content) return JSON.stringify(step.content)
155
+ return ''
156
+ }
157
+
158
+ function mapGenericToolCategory(toolName) {
159
+ if (toolName === 'read_file' || toolName === 'view_file') return 'VIEW_FILE'
160
+ if (toolName === 'run_command' || toolName === 'manage_task') return 'RUN_COMMAND'
161
+ if (['edit_file', 'write_file', 'replace_file_content', 'multi_replace_file_content', 'write_to_file'].includes(toolName)) {
162
+ return 'CODE_ACTION'
163
+ }
164
+ if (toolName === 'call_mcp_tool' || toolName.startsWith('mcp_') || toolName.startsWith('katlux_')) return 'MCP_TOOL'
165
+ if (toolName === 'grep_search') return 'GREP_SEARCH'
166
+ if (toolName === 'list_dir' || toolName === 'find_by_name') return 'LIST_DIRECTORY'
167
+ return 'OTHER'
168
+ }
169
+
170
+ /**
171
+ * Analyzes parsed session steps to compute token totals, category splits, MCP usage, and spikes.
172
+ */
173
+ export function analyzeSession(steps, conversationId, mtime = new Date(), previewProject = 'Unknown') {
174
+ let totalChars = 0
175
+ let inputChars = 0
176
+ let outputChars = 0
177
+
178
+ const categories = {
179
+ USER_INPUT: { count: 0, chars: 0, tokens: 0, label: 'User Prompts' },
180
+ PLANNER_RESPONSE: { count: 0, chars: 0, tokens: 0, label: 'Assistant / Model' },
181
+ VIEW_FILE: { count: 0, chars: 0, tokens: 0, label: 'view_file / read_file' },
182
+ MCP_TOOL: { count: 0, chars: 0, tokens: 0, label: 'MCP Tools' },
183
+ CODE_ACTION: { count: 0, chars: 0, tokens: 0, label: 'Code Edit / Write' },
184
+ RUN_COMMAND: { count: 0, chars: 0, tokens: 0, label: 'run_command Outputs' },
185
+ GREP_SEARCH: { count: 0, chars: 0, tokens: 0, label: 'grep_search Outputs' },
186
+ LIST_DIRECTORY: { count: 0, chars: 0, tokens: 0, label: 'list_dir Outputs' },
187
+ CONVERSATION_HISTORY: { count: 0, chars: 0, tokens: 0, label: 'Injected History' },
188
+ SYSTEM_MESSAGE: { count: 0, chars: 0, tokens: 0, label: 'System Notifications' },
189
+ OTHER: { count: 0, chars: 0, tokens: 0, label: 'Other Metadata' }
190
+ }
191
+
192
+ const spikes = []
193
+ const userPrompts = []
194
+ const filesViewed = new Map()
195
+ const filesModified = new Map()
196
+ const mcpCalls = { inspectProject: 0, validateCode: 0, otherMcp: 0, total: 0 }
197
+ let sessionTitle = ''
198
+ let detectedProject = previewProject
199
+ const pendingToolCalls = []
200
+
201
+ steps.forEach(step => {
202
+ const type = step.type || 'OTHER'
203
+ const content = resolveStepContent(step)
204
+
205
+ if (detectedProject === 'Unknown' && content) {
206
+ const m1 = content.match(/\[URI\] -> \[CorpusName\]:\s*\n([^\s\n\r]+)\s*->/)
207
+ if (m1) detectedProject = basename(m1[1])
208
+ else {
209
+ const m2 = content.match(/\/Desktop\/projects\/([a-zA-Z0-9_\-]+)/)
210
+ if (m2) detectedProject = m2[1]
211
+ }
212
+ }
213
+
214
+ if (type === 'USER_INPUT' && content) {
215
+ const match = content.match(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/)
216
+ const promptText = (match ? match[1] : content).replace(/[\r\n\t]+/g, ' ').trim()
217
+ if (!sessionTitle) sessionTitle = promptText
218
+ const timeStr = step.created_at ? formatDateTime(new Date(step.created_at)) : ''
219
+ userPrompts.push({ step: step.step_index, text: promptText, time: timeStr })
220
+ }
221
+
222
+ if (step.tool_calls && Array.isArray(step.tool_calls)) {
223
+ step.tool_calls.forEach(tc => {
224
+ pendingToolCalls.push(tc)
225
+ const args = tc.args || {}
226
+ let toolName = tc.name
227
+ if (tc.name === 'call_mcp_tool') toolName = cleanString(args.ToolName)
228
+ if (toolName === 'katlux_inspect_project') {
229
+ mcpCalls.inspectProject++
230
+ mcpCalls.total++
231
+ } else if (toolName === 'katlux_validate_code') {
232
+ mcpCalls.validateCode++
233
+ mcpCalls.total++
234
+ } else if (tc.name === 'call_mcp_tool' || (toolName && toolName.startsWith('katlux_'))) {
235
+ mcpCalls.otherMcp++
236
+ mcpCalls.total++
237
+ }
238
+
239
+ if ((tc.name === 'view_file' || tc.name === 'read_file') && (args.AbsolutePath || args.Path)) {
240
+ const fn = basename(cleanString(args.AbsolutePath || args.Path))
241
+ if (fn) filesViewed.set(fn, (filesViewed.get(fn) || 0) + 1)
242
+ } else if (['replace_file_content', 'multi_replace_file_content', 'write_to_file', 'edit_file', 'write_file'].includes(tc.name) && (args.TargetFile || args.Path)) {
243
+ const fn = basename(cleanString(args.TargetFile || args.Path))
244
+ if (fn) filesModified.set(fn, (filesModified.get(fn) || 0) + 1)
245
+ }
246
+ })
247
+ }
248
+
249
+ const chars = content.length
250
+ const tokens = estimateTokens(chars)
251
+ totalChars += chars
252
+ if (type === 'PLANNER_RESPONSE') outputChars += chars
253
+ else inputChars += chars
254
+
255
+ let catType = type
256
+ if (type === 'READ_FILE') catType = 'VIEW_FILE'
257
+ if (type === 'MCP_TOOL' || type === 'CALL_MCP_TOOL') catType = 'MCP_TOOL'
258
+ if (type === 'GENERIC') {
259
+ const correspondingTool = pendingToolCalls.shift()
260
+ catType = correspondingTool ? mapGenericToolCategory(correspondingTool.name || '') : 'OTHER'
261
+ }
262
+
263
+ const cat = categories[catType] || categories.OTHER
264
+ cat.count++
265
+ cat.chars += chars
266
+ cat.tokens += tokens
267
+
268
+ spikes.push({
269
+ step_index: step.step_index,
270
+ type: type === 'GENERIC' && catType !== 'OTHER' ? `${type} (${catType})` : type,
271
+ tokens,
272
+ chars,
273
+ preview: content.replace(/[\r\n\t]+/g, ' ').slice(0, 80).trim()
274
+ })
275
+ })
276
+
277
+ spikes.sort((a, b) => b.tokens - a.tokens)
278
+ return {
279
+ conversationId,
280
+ project: detectedProject,
281
+ sessionTitle: sessionTitle || '(no title)',
282
+ mtime,
283
+ weekKey: getWeekKey(mtime),
284
+ totalSteps: steps.length,
285
+ totalChars,
286
+ totalTokens: estimateTokens(totalChars),
287
+ inputTokens: estimateTokens(inputChars),
288
+ outputTokens: estimateTokens(outputChars),
289
+ categories,
290
+ mcpCalls,
291
+ spikes: spikes.slice(0, 5),
292
+ userPrompts,
293
+ topViewedFiles: [...filesViewed.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5),
294
+ topModifiedFiles: [...filesModified.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5),
295
+ allFilesViewed: filesViewed,
296
+ allFilesModified: filesModified
297
+ }
298
+ }
299
+