pi-mega-compact 0.11.4 → 0.11.5

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 (307) hide show
  1. package/dist/extensions/dashboard-server/api-contracts/endpoints.js +19 -0
  2. package/dist/extensions/dashboard-server/api-contracts/memory.js +8 -0
  3. package/dist/extensions/dashboard-server/api-contracts/provider-cache.js +1 -0
  4. package/dist/extensions/dashboard-server/api-contracts/setup.js +10 -0
  5. package/dist/extensions/dashboard-server/index-reader.js +6 -2
  6. package/dist/extensions/dashboard-server/routes-cache.js +115 -55
  7. package/dist/extensions/dashboard-server/routes-memory.js +51 -0
  8. package/dist/extensions/dashboard-server/routes-repo.js +2 -2
  9. package/dist/extensions/dashboard-server/routes-setup.js +162 -0
  10. package/dist/extensions/dashboard-server/routes.js +2 -0
  11. package/dist/extensions/dashboard-server/server.js +7 -1
  12. package/dist/extensions/mega-commands.js +189 -1
  13. package/dist/extensions/mega-config.js +2 -0
  14. package/dist/extensions/mega-events/agent-handlers.js +19 -4
  15. package/dist/extensions/mega-events/compact-handlers.js +1 -0
  16. package/dist/extensions/mega-events/context-handler.js +37 -92
  17. package/dist/extensions/mega-events/context-hwm.js +51 -0
  18. package/dist/extensions/mega-events/error-classifier.js +16 -5
  19. package/dist/extensions/mega-events/mirror-append.js +107 -0
  20. package/dist/extensions/mega-events/outage-advisor.js +7 -1
  21. package/dist/extensions/mega-events/perf-handler.js +51 -1
  22. package/dist/extensions/mega-events/recall-tail.js +59 -0
  23. package/dist/extensions/mega-events/session-handlers.js +15 -8
  24. package/dist/extensions/mega-runtime/reset-runtime.js +5 -0
  25. package/dist/extensions/mega-runtime/runtime.js +6 -0
  26. package/dist/src/embedder.js +41 -2
  27. package/dist/src/memoryStats.js +75 -0
  28. package/dist/src/prefix-break.js +43 -0
  29. package/dist/src/pricing.js +1 -1
  30. package/dist/src/store/sqlite/perf-samples.js +144 -16
  31. package/dist/src/store/turns/memory-store.js +8 -0
  32. package/dist/src/store/turns/sqlite-store.js +14 -3
  33. package/dist/src/store/turns/types.js +18 -1
  34. package/dist/src/store/vectorIndex.js +26 -5
  35. package/extensions/dashboard-client/dist/assets/{AchievementTiles-vEo2MtE2.js → AchievementTiles-BoL7qBOJ.js} +2 -2
  36. package/extensions/dashboard-client/dist/assets/{AchievementTiles-vEo2MtE2.js.map → AchievementTiles-BoL7qBOJ.js.map} +1 -1
  37. package/extensions/dashboard-client/dist/assets/AchievementsTab-BFDE3HYc.js +2 -0
  38. package/extensions/dashboard-client/dist/assets/{AchievementsTab-DjxfYrDc.js.map → AchievementsTab-BFDE3HYc.js.map} +1 -1
  39. package/extensions/dashboard-client/dist/assets/CacheTab-eKVc-NV1.js +2 -0
  40. package/extensions/dashboard-client/dist/assets/CacheTab-eKVc-NV1.js.map +1 -0
  41. package/extensions/dashboard-client/dist/assets/{ConfigTab-Cm6ymbmx.js → ConfigTab-DDFE-ckA.js} +2 -2
  42. package/extensions/dashboard-client/dist/assets/{ConfigTab-Cm6ymbmx.js.map → ConfigTab-DDFE-ckA.js.map} +1 -1
  43. package/extensions/dashboard-client/dist/assets/{EventsTab-DXWl_YzI.js → EventsTab-B6UxZ7PM.js} +2 -2
  44. package/extensions/dashboard-client/dist/assets/{EventsTab-DXWl_YzI.js.map → EventsTab-B6UxZ7PM.js.map} +1 -1
  45. package/extensions/dashboard-client/dist/assets/{GameTab-BLDudcO5.js → GameTab-DehUX-KE.js} +2 -2
  46. package/extensions/dashboard-client/dist/assets/{GameTab-BLDudcO5.js.map → GameTab-DehUX-KE.js.map} +1 -1
  47. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-DLkKCztn.js → MaintenanceTab-0GWRt4wn.js} +2 -2
  48. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-DLkKCztn.js.map → MaintenanceTab-0GWRt4wn.js.map} +1 -1
  49. package/extensions/dashboard-client/dist/assets/{MetricsTab-Cq4u-rZF.js → MetricsTab-C3rwMVsN.js} +2 -2
  50. package/extensions/dashboard-client/dist/assets/{MetricsTab-Cq4u-rZF.js.map → MetricsTab-C3rwMVsN.js.map} +1 -1
  51. package/extensions/dashboard-client/dist/assets/OverviewTab-39O9_x5j.js +2 -0
  52. package/extensions/dashboard-client/dist/assets/{OverviewTab-D4kGvsiQ.js.map → OverviewTab-39O9_x5j.js.map} +1 -1
  53. package/extensions/dashboard-client/dist/assets/ReposTab-Cfj6Q5sH.js +2 -0
  54. package/extensions/dashboard-client/dist/assets/ReposTab-Cfj6Q5sH.js.map +1 -0
  55. package/extensions/dashboard-client/dist/assets/{SessionsTab-DZC2-GCn.js → SessionsTab-DXDTCi3r.js} +2 -2
  56. package/extensions/dashboard-client/dist/assets/{SessionsTab-DZC2-GCn.js.map → SessionsTab-DXDTCi3r.js.map} +1 -1
  57. package/extensions/dashboard-client/dist/assets/SetupTab-mMlfunJa.js +2 -0
  58. package/extensions/dashboard-client/dist/assets/SetupTab-mMlfunJa.js.map +1 -0
  59. package/extensions/dashboard-client/dist/assets/TimeSavedCard-Cw1dJ4e9.js +2 -0
  60. package/extensions/dashboard-client/dist/assets/TimeSavedCard-Cw1dJ4e9.js.map +1 -0
  61. package/extensions/dashboard-client/dist/assets/{TopicsTab-01G71hv1.js → TopicsTab-BAw972BV.js} +2 -2
  62. package/extensions/dashboard-client/dist/assets/{TopicsTab-01G71hv1.js.map → TopicsTab-BAw972BV.js.map} +1 -1
  63. package/extensions/dashboard-client/dist/assets/{TurnsTab-DLRg0LZT.js → TurnsTab-Cf5mGIdl.js} +2 -2
  64. package/extensions/dashboard-client/dist/assets/{TurnsTab-DLRg0LZT.js.map → TurnsTab-Cf5mGIdl.js.map} +1 -1
  65. package/extensions/dashboard-client/dist/assets/format-COjDIVGj.js +2 -0
  66. package/extensions/dashboard-client/dist/assets/format-COjDIVGj.js.map +1 -0
  67. package/extensions/dashboard-client/dist/assets/{index-BX0bcgLu.js → index-4gQ7auad.js} +10 -10
  68. package/extensions/dashboard-client/dist/assets/index-4gQ7auad.js.map +1 -0
  69. package/extensions/dashboard-client/dist/assets/pricing-CvE4NllQ.js +2 -0
  70. package/extensions/dashboard-client/dist/assets/pricing-CvE4NllQ.js.map +1 -0
  71. package/extensions/dashboard-client/dist/assets/{useSSE-BBYt5UPB.js → useSSE-DNgMuyP6.js} +2 -2
  72. package/extensions/dashboard-client/dist/assets/{useSSE-BBYt5UPB.js.map → useSSE-DNgMuyP6.js.map} +1 -1
  73. package/extensions/dashboard-client/dist/index.html +1 -1
  74. package/extensions/dashboard-client/src/App.tsx +4 -0
  75. package/extensions/dashboard-client/src/api/client.ts +14 -0
  76. package/extensions/dashboard-client/src/components/ActiveReposTable.tsx +21 -12
  77. package/extensions/dashboard-client/src/components/ProviderCacheCard.tsx +56 -0
  78. package/extensions/dashboard-client/src/components/SavingsByModelTable.tsx +38 -57
  79. package/extensions/dashboard-client/src/tabs/CacheTab.tsx +1 -0
  80. package/extensions/dashboard-client/src/tabs/SetupTab.tsx +355 -0
  81. package/extensions/dashboard-client/tsconfig.json +3 -2
  82. package/extensions/dashboard-client/vite.config.ts +2 -0
  83. package/extensions/dashboard-server/api-contracts/endpoints.ts +36 -3
  84. package/extensions/dashboard-server/api-contracts/index.ts +7 -0
  85. package/extensions/dashboard-server/api-contracts/memory.ts +27 -0
  86. package/extensions/dashboard-server/api-contracts/multi-repo.ts +231 -231
  87. package/extensions/dashboard-server/api-contracts/provider-cache.ts +37 -0
  88. package/extensions/dashboard-server/api-contracts/setup.ts +58 -0
  89. package/extensions/dashboard-server/index-reader.ts +138 -121
  90. package/extensions/dashboard-server/routes-cache.ts +161 -85
  91. package/extensions/dashboard-server/routes-memory.ts +63 -0
  92. package/extensions/dashboard-server/routes-repo.ts +36 -36
  93. package/extensions/dashboard-server/routes-setup.ts +181 -0
  94. package/extensions/dashboard-server/routes.ts +2 -0
  95. package/extensions/dashboard-server/server.ts +6 -0
  96. package/extensions/mega-commands.ts +211 -1
  97. package/extensions/mega-config.ts +10 -0
  98. package/extensions/mega-events/agent-handlers.ts +20 -4
  99. package/extensions/mega-events/compact-handlers.ts +1 -0
  100. package/extensions/mega-events/context-handler.ts +45 -110
  101. package/extensions/mega-events/context-hwm.ts +85 -0
  102. package/extensions/mega-events/error-classifier.ts +15 -4
  103. package/extensions/mega-events/mirror-append.ts +155 -0
  104. package/extensions/mega-events/outage-advisor.ts +11 -5
  105. package/extensions/mega-events/perf-handler.ts +79 -5
  106. package/extensions/mega-events/recall-tail.ts +88 -0
  107. package/extensions/mega-events/session-handlers.ts +14 -7
  108. package/extensions/mega-runtime/helpers.ts +12 -0
  109. package/extensions/mega-runtime/reset-runtime.ts +5 -0
  110. package/extensions/mega-runtime/runtime.ts +6 -0
  111. package/package.json +5 -2
  112. package/src/embedder.ts +42 -2
  113. package/src/memoryStats.ts +107 -0
  114. package/src/prefix-break.ts +83 -0
  115. package/src/pricing.ts +2 -2
  116. package/src/store/sqlite/perf-samples.ts +215 -22
  117. package/src/store/turns/memory-store.ts +10 -1
  118. package/src/store/turns/sqlite-store.ts +27 -15
  119. package/src/store/turns/types.ts +21 -0
  120. package/src/store/vectorIndex.ts +33 -4
  121. package/dist/extensions/conflict-scan.test.js +0 -115
  122. package/dist/extensions/dashboard-server/api-contracts.test.js +0 -884
  123. package/dist/extensions/dashboard-server/html.test.js +0 -52
  124. package/dist/extensions/dashboard-server/perf-server.test.js +0 -80
  125. package/dist/extensions/dashboard-server/routes-cache.test.js +0 -248
  126. package/dist/extensions/dashboard-server/server.test.js +0 -120
  127. package/dist/extensions/dashboard-server-s32.test.js +0 -181
  128. package/dist/extensions/dashboard-server.test.js +0 -339
  129. package/dist/extensions/mega-cache-replay.test.js +0 -400
  130. package/dist/extensions/mega-compact-s38.test.js +0 -1383
  131. package/dist/extensions/mega-compact.test.js +0 -1112
  132. package/dist/extensions/mega-events.test.js +0 -47
  133. package/dist/extensions/mega-game-cmds.test.js +0 -163
  134. package/dist/extensions/mega-runtime/snapshot.test.js +0 -127
  135. package/dist/extensions/mega-runtime/state.test.js +0 -266
  136. package/dist/extensions/mega-runtime/widget.test.js +0 -343
  137. package/dist/extensions/mega-shutdown-widget.test.js +0 -121
  138. package/dist/extensions/mega-teamrun.test.js +0 -156
  139. package/dist/extensions/mega-trim.test.js +0 -58
  140. package/dist/extensions/mega-turn-store.test.js +0 -68
  141. package/dist/src/boundary.test.js +0 -170
  142. package/dist/src/compact.test.js +0 -78
  143. package/dist/src/config/themes.test.js +0 -94
  144. package/dist/src/dedup/dedup.test.js +0 -41
  145. package/dist/src/dedup/l1.test.js +0 -50
  146. package/dist/src/dedup/raptor/buildHistory.test.js +0 -292
  147. package/dist/src/dedup/raptor/multilevel-serve.test.js +0 -229
  148. package/dist/src/dedup/raptor/multilevel.test.js +0 -238
  149. package/dist/src/dedup/raptor/promote.test.js +0 -69
  150. package/dist/src/dedup/raptor/raptor.test.js +0 -248
  151. package/dist/src/dedup/raptor/retrieval.test.js +0 -95
  152. package/dist/src/dedup/raptor/serve-gate.test.js +0 -298
  153. package/dist/src/dedup/sprint12.test.js +0 -219
  154. package/dist/src/dedup-engine.test.js +0 -472
  155. package/dist/src/driftDetection.test.js +0 -87
  156. package/dist/src/e2e.test.js +0 -698
  157. package/dist/src/engine.test.js +0 -111
  158. package/dist/src/extractive.test.js +0 -147
  159. package/dist/src/fork.test.js +0 -81
  160. package/dist/src/game/scoring.test.js +0 -98
  161. package/dist/src/httpEmbedder.test.js +0 -277
  162. package/dist/src/importance.test.js +0 -372
  163. package/dist/src/intent.test.js +0 -78
  164. package/dist/src/log.test.js +0 -42
  165. package/dist/src/mechanical-fix.test.js +0 -65
  166. package/dist/src/memory.test.js +0 -70
  167. package/dist/src/memoryConsolidate.test.js +0 -38
  168. package/dist/src/memoryOps.test.js +0 -129
  169. package/dist/src/memoryRecall.test.js +0 -171
  170. package/dist/src/memoryRoundtrip.test.js +0 -137
  171. package/dist/src/metrics/turns.test.js +0 -152
  172. package/dist/src/mirror/mirror.test.js +0 -185
  173. package/dist/src/raptor-inject-summaries.test.js +0 -162
  174. package/dist/src/ratio.bench.test.js +0 -897
  175. package/dist/src/recall.integration.test.js +0 -77
  176. package/dist/src/recall.test.js +0 -379
  177. package/dist/src/sprint14.test.js +0 -219
  178. package/dist/src/sprint4x-rag-verification.test.js +0 -93
  179. package/dist/src/store/compression.test.js +0 -139
  180. package/dist/src/store/memoryIndex.test.js +0 -51
  181. package/dist/src/store/migrate.test.js +0 -139
  182. package/dist/src/store/pgOpenGuard.test.js +0 -74
  183. package/dist/src/store/phase01.test.js +0 -81
  184. package/dist/src/store/phase04.test.js +0 -54
  185. package/dist/src/store/sprint10.test.js +0 -186
  186. package/dist/src/store/sqlite/game-achievements.test.js +0 -67
  187. package/dist/src/store/sqlite/game-scores.test.js +0 -106
  188. package/dist/src/store/sqlite/game-state.test.js +0 -76
  189. package/dist/src/store/sqlite/global-index.test.js +0 -136
  190. package/dist/src/store/sqlite/mechanical-fix.test.js +0 -146
  191. package/dist/src/store/sqlite/perf-samples.test.js +0 -146
  192. package/dist/src/store/sqlite/raptor.test.js +0 -106
  193. package/dist/src/store/sqlite/turns.test.js +0 -183
  194. package/dist/src/store/sqlite.cachehit.test.js +0 -55
  195. package/dist/src/store/sqlite.dbmaint.test.js +0 -158
  196. package/dist/src/store/sqlite.dbmirror.test.js +0 -184
  197. package/dist/src/store/turns/contract-compliance.test.js +0 -428
  198. package/dist/src/store/turns/memory-store.test.js +0 -9
  199. package/dist/src/store/turns/migrations.test.js +0 -138
  200. package/dist/src/store/turns/sqlite-store.test.js +0 -144
  201. package/dist/src/store/vectorIndex.test.js +0 -123
  202. package/dist/src/store.test.js +0 -161
  203. package/dist/src/supersede.test.js +0 -36
  204. package/dist/src/topics/cluster.test.js +0 -150
  205. package/dist/src/topics/store.test.js +0 -117
  206. package/dist/src/types.test.js +0 -9
  207. package/dist/src/vector-search-cache.test.js +0 -157
  208. package/dist/src/vectorStore.test.js +0 -479
  209. package/dist/src/wiki.test.js +0 -171
  210. package/extensions/conflict-scan.test.ts +0 -129
  211. package/extensions/dashboard-client/dist/assets/AchievementsTab-DjxfYrDc.js +0 -2
  212. package/extensions/dashboard-client/dist/assets/CacheTab-Dnpv94wq.js +0 -2
  213. package/extensions/dashboard-client/dist/assets/CacheTab-Dnpv94wq.js.map +0 -1
  214. package/extensions/dashboard-client/dist/assets/OverviewTab-D4kGvsiQ.js +0 -2
  215. package/extensions/dashboard-client/dist/assets/ReposTab-C0Wnrf2u.js +0 -2
  216. package/extensions/dashboard-client/dist/assets/ReposTab-C0Wnrf2u.js.map +0 -1
  217. package/extensions/dashboard-client/dist/assets/TimeSavedCard-UqljSyP-.js +0 -2
  218. package/extensions/dashboard-client/dist/assets/TimeSavedCard-UqljSyP-.js.map +0 -1
  219. package/extensions/dashboard-client/dist/assets/index-BX0bcgLu.js.map +0 -1
  220. package/extensions/dashboard-server/api-contracts.test.ts +0 -1065
  221. package/extensions/dashboard-server/html.test.ts +0 -62
  222. package/extensions/dashboard-server/perf-server.test.ts +0 -101
  223. package/extensions/dashboard-server/routes-cache.test.ts +0 -302
  224. package/extensions/dashboard-server/server.test.ts +0 -131
  225. package/extensions/dashboard-server-s32.test.ts +0 -195
  226. package/extensions/dashboard-server.test.ts +0 -382
  227. package/extensions/mega-cache-replay.test.ts +0 -526
  228. package/extensions/mega-compact-s38.test.ts +0 -1433
  229. package/extensions/mega-compact.test.ts +0 -1509
  230. package/extensions/mega-events.test.ts +0 -55
  231. package/extensions/mega-game-cmds.test.ts +0 -197
  232. package/extensions/mega-runtime/snapshot.test.ts +0 -139
  233. package/extensions/mega-runtime/state.test.ts +0 -262
  234. package/extensions/mega-runtime/widget.test.ts +0 -468
  235. package/extensions/mega-shutdown-widget.test.ts +0 -141
  236. package/extensions/mega-teamrun.test.ts +0 -176
  237. package/extensions/mega-trim.test.ts +0 -64
  238. package/extensions/mega-turn-store.test.ts +0 -108
  239. package/src/boundary.test.ts +0 -187
  240. package/src/compact.test.ts +0 -99
  241. package/src/config/themes.test.ts +0 -116
  242. package/src/dedup/dedup.test.ts +0 -46
  243. package/src/dedup/l1.test.ts +0 -57
  244. package/src/dedup/raptor/buildHistory.test.ts +0 -353
  245. package/src/dedup/raptor/multilevel-serve.test.ts +0 -273
  246. package/src/dedup/raptor/multilevel.test.ts +0 -325
  247. package/src/dedup/raptor/promote.test.ts +0 -82
  248. package/src/dedup/raptor/raptor.test.ts +0 -297
  249. package/src/dedup/raptor/retrieval.test.ts +0 -118
  250. package/src/dedup/raptor/serve-gate.test.ts +0 -348
  251. package/src/dedup/sprint12.test.ts +0 -242
  252. package/src/dedup-engine.test.ts +0 -670
  253. package/src/driftDetection.test.ts +0 -100
  254. package/src/e2e.test.ts +0 -843
  255. package/src/engine.test.ts +0 -123
  256. package/src/extractive.test.ts +0 -174
  257. package/src/fork.test.ts +0 -94
  258. package/src/game/scoring.test.ts +0 -103
  259. package/src/httpEmbedder.test.ts +0 -286
  260. package/src/importance.test.ts +0 -538
  261. package/src/intent.test.ts +0 -87
  262. package/src/log.test.ts +0 -47
  263. package/src/mechanical-fix.test.ts +0 -70
  264. package/src/memory.test.ts +0 -92
  265. package/src/memoryConsolidate.test.ts +0 -47
  266. package/src/memoryOps.test.ts +0 -148
  267. package/src/memoryRecall.test.ts +0 -194
  268. package/src/memoryRoundtrip.test.ts +0 -155
  269. package/src/metrics/turns.test.ts +0 -165
  270. package/src/mirror/mirror.test.ts +0 -240
  271. package/src/raptor-inject-summaries.test.ts +0 -228
  272. package/src/ratio.bench.test.ts +0 -1316
  273. package/src/recall.integration.test.ts +0 -96
  274. package/src/recall.test.ts +0 -467
  275. package/src/sprint14.test.ts +0 -245
  276. package/src/sprint4x-rag-verification.test.ts +0 -119
  277. package/src/store/compression.test.ts +0 -168
  278. package/src/store/memoryIndex.test.ts +0 -61
  279. package/src/store/migrate.test.ts +0 -158
  280. package/src/store/pgOpenGuard.test.ts +0 -89
  281. package/src/store/phase01.test.ts +0 -88
  282. package/src/store/phase04.test.ts +0 -58
  283. package/src/store/sprint10.test.ts +0 -214
  284. package/src/store/sqlite/game-achievements.test.ts +0 -80
  285. package/src/store/sqlite/game-scores.test.ts +0 -132
  286. package/src/store/sqlite/game-state.test.ts +0 -89
  287. package/src/store/sqlite/global-index.test.ts +0 -222
  288. package/src/store/sqlite/mechanical-fix.test.ts +0 -162
  289. package/src/store/sqlite/perf-samples.test.ts +0 -169
  290. package/src/store/sqlite/raptor.test.ts +0 -139
  291. package/src/store/sqlite/turns.test.ts +0 -218
  292. package/src/store/sqlite.cachehit.test.ts +0 -68
  293. package/src/store/sqlite.dbmaint.test.ts +0 -193
  294. package/src/store/sqlite.dbmirror.test.ts +0 -229
  295. package/src/store/turns/contract-compliance.test.ts +0 -562
  296. package/src/store/turns/memory-store.test.ts +0 -15
  297. package/src/store/turns/migrations.test.ts +0 -161
  298. package/src/store/turns/sqlite-store.test.ts +0 -161
  299. package/src/store/vectorIndex.test.ts +0 -140
  300. package/src/store.test.ts +0 -191
  301. package/src/supersede.test.ts +0 -42
  302. package/src/topics/cluster.test.ts +0 -176
  303. package/src/topics/store.test.ts +0 -132
  304. package/src/types.test.ts +0 -10
  305. package/src/vector-search-cache.test.ts +0 -190
  306. package/src/vectorStore.test.ts +0 -533
  307. package/src/wiki.test.ts +0 -217
@@ -1,670 +0,0 @@
1
- /**
2
- * dedup-engine.test.ts — comprehensive compaction + dedup level test suite.
3
- *
4
- * Covers:
5
- * 1. Compaction tier thresholds (low/medium/high/ultra/mega)
6
- * 2. Dedup levels (L0/L1/L2/disabled, and combined)
7
- * 3. Compaction ratios across conversation sizes
8
- * 4. Store stats + injected-count tracking
9
- * 5. Recall & dedup sentinel behavior
10
- * 6. Edge cases (empty/single/near-end/unicode/large/mixed roles)
11
- * 7. Tier switching via MEGACOMPACT_TIER env var
12
- */
13
-
14
- import { describe, it, beforeEach, afterEach } from "node:test";
15
- import assert from "node:assert/strict";
16
- import fs from "fs";
17
- import path from "path";
18
- import os from "os";
19
- import { compactSession } from "./engine.js";
20
- import { VectorStore, vectorList, vectorStats, vectorWasInjected, vectorMarkInjected, vectorSearch } from "./vectorStore.js";
21
- import { extractiveSummarize } from "./extractive.js";
22
- import { estimateSessionTokens, estimateMessageTokens } from "./tokens.js";
23
- import { autoCompactCheck } from "./compact.js";
24
- import { loadDedupConfig, type DedupConfigShape } from "./config/dedup.js";
25
- import type { EngineMessage } from "./types.js";
26
-
27
- // Real percentage-based threshold config. Replaces the previous LOCAL replica of
28
- // COMPACT_TIERS + resolveThresholdFromEnv that asserted the OLD static token
29
- // amounts — importing the live source of truth keeps tests in sync with the
30
- // source (thresholds are tierPct × the model's context window, not fixed tokens).
31
- import { TIER_PCT, effectiveThresholdTokens, loadConfig } from "../extensions/mega-config.js";
32
-
33
- // recallAndInline may or may not be exported; import safely.
34
- import * as recallMod from "./recall.js";
35
-
36
- interface RecallInjectResult {
37
- toInject: unknown[];
38
- empty: boolean;
39
- }
40
-
41
- const recallAndInline = (recallMod as any).recallAndInline as
42
- | ((
43
- opts: {
44
- sessionId: string;
45
- query: string;
46
- limit?: number;
47
- source: "command";
48
- skipInjected?: boolean;
49
- },
50
- store: VectorStore,
51
- ) => RecallInjectResult)
52
- | undefined;
53
-
54
- // -------------------- Helpers --------------------
55
-
56
- function mkTmpDir(): string {
57
- return fs.mkdtempSync(path.join(os.tmpdir(), "mc-dedup-"));
58
- }
59
-
60
- let currentTmpDir: string | undefined;
61
-
62
- beforeEach(() => {
63
- currentTmpDir = mkTmpDir();
64
- });
65
-
66
- afterEach(() => {
67
- if (currentTmpDir && fs.existsSync(currentTmpDir)) {
68
- fs.rmSync(currentTmpDir, { recursive: true, force: true });
69
- }
70
- currentTmpDir = undefined;
71
- });
72
-
73
- function baseConfig(): DedupConfigShape {
74
- return loadDedupConfig();
75
- }
76
-
77
- function makeStore(over: Partial<DedupConfigShape> = {}): VectorStore {
78
- return new VectorStore({
79
- stateDir: currentTmpDir,
80
- config: { ...baseConfig(), ...over },
81
- });
82
- }
83
-
84
- function makeMsg(role: EngineMessage["role"], text: string): EngineMessage {
85
- return { role, text };
86
- }
87
-
88
- function buildConversation(n: number, prefix = "turn"): EngineMessage[] {
89
- const out: EngineMessage[] = [];
90
- for (let i = 0; i < n; i++) {
91
- const role = i % 2 === 0 ? "user" : "assistant";
92
- out.push(
93
- makeMsg(
94
- role,
95
- `${prefix} ${i + 1}: ${role} discusses implementation of feature ${i + 1} in src/module${i + 1}.ts and considers tradeoffs.`,
96
- ),
97
- );
98
- }
99
- return out;
100
- }
101
-
102
- function compactFull(
103
- store: VectorStore,
104
- sessionId: string,
105
- messages: EngineMessage[],
106
- keepFrom?: number,
107
- ): ReturnType<typeof compactSession> {
108
- return compactSession({ sessionId, messages, keepFrom: keepFrom ?? messages.length }, store);
109
- }
110
-
111
- // -------------------- 1. Compaction Levels --------------------
112
-
113
- describe("Compaction Levels (Tier Behavior)", () => {
114
- const TIER_CASES: Array<[string, number]> = [
115
- ["low", 50_000],
116
- ["medium", 100_000],
117
- ["high", 200_000],
118
- ["ultra", 1_000_000],
119
- ["mega", 10_000_000],
120
- ];
121
-
122
- for (const [tier, threshold] of TIER_CASES) {
123
- it(`tier "${tier}" (${threshold.toLocaleString()} threshold) triggers only when tokens exceed threshold`, () => {
124
- // One token below threshold => should not compact.
125
- const under = autoCompactCheck(threshold - 1, threshold);
126
- assert.equal(under.shouldCompact, false, "one token below threshold should not trigger");
127
- assert.equal(under.threshold, threshold);
128
-
129
- // At threshold => should compact.
130
- const at = autoCompactCheck(threshold, threshold);
131
- assert.equal(at.shouldCompact, true, "at threshold should trigger");
132
-
133
- // One token above threshold => should compact.
134
- const over = autoCompactCheck(threshold + 1, threshold);
135
- assert.equal(over.shouldCompact, true, "one token above threshold should trigger");
136
-
137
- // Generate deterministic conversation of known token size.
138
- const tokensPerMsg = estimateMessageTokens({
139
- text: "deterministic sample message of moderate length for threshold testing.",
140
- });
141
- assert.ok(tokensPerMsg > 0);
142
- const needed = Math.ceil((threshold + tokensPerMsg) / tokensPerMsg);
143
- const messages = buildConversation(needed);
144
- const estimate = estimateSessionTokens(messages);
145
- assert.ok(
146
- estimate >= threshold,
147
- `expected estimate ${estimate} >= threshold ${threshold}`,
148
- );
149
- const longCheck = autoCompactCheck(estimate, threshold);
150
- assert.equal(longCheck.shouldCompact, true);
151
-
152
- // Smaller conversation should not trigger. Derive the average per-message
153
- // cost from the large conversation we already tokenized, then leave margin below threshold.
154
- const avgTokensPerMsg = estimate / messages.length;
155
- const smallCount = Math.max(1, Math.floor((threshold * 0.95) / avgTokensPerMsg) - 5);
156
- const smallMessages = buildConversation(smallCount);
157
- const smallEstimate = estimateSessionTokens(smallMessages);
158
- assert.ok(
159
- smallEstimate < threshold,
160
- `expected small estimate ${smallEstimate} < threshold ${threshold}`,
161
- );
162
- const smallCheck = autoCompactCheck(smallEstimate, threshold);
163
- assert.equal(smallCheck.shouldCompact, false, "small conversation should not trigger tier");
164
- });
165
- }
166
- });
167
-
168
- // -------------------- 2. Dedupe Levels --------------------
169
-
170
- describe("Dedupe Levels", () => {
171
- const SESS = "sess_dedup";
172
-
173
- it("L0 only: identical content stored twice collapses to one checkpoint", () => {
174
- const s = makeStore({ L0_ENABLED: true, L1_ENABLED: false, L2_ENABLED: false });
175
- const region = "exact same user request about database migration and index setup";
176
-
177
- const r1 = compactFull(s, SESS, [makeMsg("user", region)]);
178
- assert.equal(r1.deduped, false);
179
- assert.ok(r1.checkpointId);
180
-
181
- const r2 = compactFull(s, SESS, [makeMsg("user", region)]);
182
- assert.equal(r2.deduped, true);
183
- assert.equal(r2.checkpointId, r1.checkpointId);
184
- assert.equal(vectorList(s,SESS).length, 1);
185
- });
186
-
187
- it("L0 only: distinct content stored twice creates two checkpoints", () => {
188
- const s = makeStore({ L0_ENABLED: true, L1_ENABLED: false, L2_ENABLED: false });
189
- const regionA = "first exact region about authentication module refactoring";
190
- const regionB = "second distinct region about frontend component testing";
191
-
192
- const r1 = compactFull(s, SESS, [makeMsg("user", regionA)]);
193
- const r2 = compactFull(s, SESS, [makeMsg("user", regionB)]);
194
- assert.equal(r1.deduped, false);
195
- assert.equal(r2.deduped, false);
196
- assert.notEqual(r1.checkpointId, r2.checkpointId);
197
- assert.equal(vectorList(s,SESS).length, 2);
198
- });
199
-
200
- it("L1 only: one-word variants collapse; major rewrites do not", () => {
201
- const s = makeStore({ L0_ENABLED: false, L1_ENABLED: true, L2_ENABLED: false });
202
-
203
- const base = "the database migration added three new indexes to the users table for faster lookups";
204
- const variant = "the database migration added three new indexes to the users table for faster lookup";
205
- const rewrite = "the frontend dark mode toggle uses css custom properties for theming";
206
-
207
- const r1 = s.add({ sessionId: SESS, summary: "migration", regionText: base, timestamp: 1 });
208
- assert.equal(r1.deduped, false);
209
-
210
- const r2 = s.add({ sessionId: SESS, summary: "migration", regionText: variant, timestamp: 2 });
211
- assert.equal(r2.deduped, true, "one-word variant should be collapsed by L1");
212
- assert.equal(vectorList(s,SESS).length, 1);
213
-
214
- const r3 = s.add({ sessionId: SESS, summary: "frontend", regionText: rewrite, timestamp: 3 });
215
- assert.equal(r3.deduped, false, "major rewrite should not be collapsed by L1");
216
- assert.equal(vectorList(s,SESS).length, 2);
217
- });
218
-
219
- it("L2 only: semantic paraphrases collapse; unrelated topics do not", () => {
220
- // Use a lower threshold and longer, lexically-overlapping paraphrase so the
221
- // deterministic trigram embedder reliably catches it while still distinguishing
222
- // unrelated topics.
223
- const s = makeStore({ L0_ENABLED: false, L1_ENABLED: false, L2_ENABLED: true, L2_COSINE: 0.60 });
224
-
225
- const original =
226
- "user authentication and session token management login validation session expiry handling secure cookie";
227
- const paraphrase =
228
- "login validation session expiry handling secure cookie user authentication and session token management";
229
- const unrelated = "the frontend added a dark mode toggle with css custom properties";
230
-
231
- const r1 = s.add({ sessionId: SESS, summary: "auth", regionText: original, timestamp: 1 });
232
- assert.equal(r1.deduped, false);
233
-
234
- const r2 = s.add({ sessionId: SESS, summary: "auth paraphrase", regionText: paraphrase, timestamp: 2 });
235
- assert.equal(r2.deduped, true, "semantic paraphrase should be collapsed by L2");
236
- assert.equal(vectorList(s,SESS).length, 1);
237
-
238
- const r3 = s.add({ sessionId: SESS, summary: "frontend", regionText: unrelated, timestamp: 3 });
239
- assert.equal(r3.deduped, false, "unrelated topic should not be collapsed by L2");
240
- assert.equal(vectorList(s,SESS).length, 2);
241
- });
242
-
243
- it("All tiers disabled: every store.add() with different region text creates a distinct checkpoint", () => {
244
- // Even with all dedup tiers disabled, the store still enforces a unique
245
- // content_hash constraint, so we vary the region text slightly for each add.
246
- const s = makeStore({ L0_ENABLED: false, L1_ENABLED: false, L2_ENABLED: false });
247
-
248
- const r1 = s.add({ sessionId: SESS, summary: "a", regionText: "region alpha", timestamp: 1 });
249
- const r2 = s.add({ sessionId: SESS, summary: "a", regionText: "region beta", timestamp: 2 });
250
- const r3 = s.add({ sessionId: SESS, summary: "a", regionText: "region gamma", timestamp: 3 });
251
-
252
- assert.equal(r1.deduped, false);
253
- assert.equal(r2.deduped, false);
254
- assert.equal(r3.deduped, false);
255
- assert.notEqual(r1.checkpoint.checkpointId, r2.checkpoint.checkpointId);
256
- assert.notEqual(r2.checkpoint.checkpointId, r3.checkpoint.checkpointId);
257
- assert.equal(vectorList(s,SESS).length, 3);
258
- });
259
-
260
- it("Combined L0+L1+L2: layered behavior exact -> near -> semantic", () => {
261
- const s = makeStore({ L0_ENABLED: true, L1_ENABLED: true, L2_ENABLED: true });
262
-
263
- // First checkpoint establishes baseline.
264
- const original = "implement user authentication with session tokens and secure cookies";
265
- const r1 = compactFull(s, SESS, [makeMsg("user", original)]);
266
- assert.equal(r1.deduped, false);
267
-
268
- // Exact duplicate -> L0.
269
- const r2 = compactFull(s, SESS, [makeMsg("user", original)]);
270
- assert.equal(r2.deduped, true);
271
- okReason(r2.dedupReason, ["regionHash", "contentHash", "summaryHash"]);
272
-
273
- // One-word edit -> L1 (if not caught by L0 first).
274
- const near = "implement user authentication with session token and secure cookies";
275
- const r3 = compactFull(s, SESS, [makeMsg("user", near)]);
276
- if (r3.deduped) {
277
- okReason(r3.dedupReason, ["l1MinHash", "contentSimilarity"]);
278
- }
279
-
280
- // Semantic paraphrase -> L2 (if distinct from above).
281
- const para = "build login validation and session cookie security for users";
282
- const r4 = compactFull(s, SESS, [makeMsg("user", para)]);
283
- if (r4.deduped) {
284
- okReason(r4.dedupReason, ["contentSimilarity", "l1MinHash"]);
285
- }
286
-
287
- assert.ok(vectorList(s,SESS).length >= 1, "layered dedup keeps at least one checkpoint");
288
- assert.ok(vectorList(s,SESS).length <= 4, "layered dedup should not explode to many checkpoints");
289
- });
290
- });
291
-
292
- function okReason(reason: string | undefined, expected: string[]): void {
293
- assert.ok(
294
- reason !== undefined && expected.includes(reason),
295
- `expected dedupReason one of ${expected.join(", ")}, got ${reason}`,
296
- );
297
- }
298
-
299
- // -------------------- 3. Compaction Ratios --------------------
300
-
301
- describe("Compaction Ratios", () => {
302
- const SESS = "sess_ratios";
303
-
304
- for (const n of [10, 50, 100, 200, 400]) {
305
- it(`${n} messages: extractive summary is smaller than input; strictly smaller when > 50`, () => {
306
- const s = makeStore();
307
- const messages = buildConversation(n, `feature work item ${n}`);
308
- const inputTokens = estimateSessionTokens(messages);
309
-
310
- const ext = extractiveSummarize(messages);
311
- const outputTokens = ext.tokenEstimate;
312
-
313
- console.log(
314
- `[ratio] ${n} messages: input=${inputTokens} output=${outputTokens} ratio=${
315
- inputTokens ? (outputTokens / inputTokens).toFixed(3) : "n/a"
316
- }`,
317
- );
318
-
319
- assert.ok(
320
- outputTokens <= inputTokens || inputTokens === 0,
321
- "output should not exceed input",
322
- );
323
- if (n > 50) {
324
- assert.ok(
325
- outputTokens < inputTokens,
326
- `expected output smaller than input for ${n} messages`,
327
- );
328
- }
329
-
330
- // Also run through compactSession and verify a checkpoint exists.
331
- const r = compactSession(
332
- { sessionId: SESS, messages, keepFrom: messages.length, useExtractiveSummary: true },
333
- s,
334
- );
335
- assert.equal(r.skipped, false);
336
- assert.ok(r.checkpointId);
337
- assert.ok(r.tokenEstimate <= inputTokens);
338
- });
339
- }
340
- });
341
-
342
- // -------------------- 4. Compression / Store Stats --------------------
343
-
344
- describe("Compression / Store Stats", () => {
345
- const SESS = "sess_stats";
346
-
347
- it("stats reflect checkpoints, tokens, injection and dedup hit rate", () => {
348
- const s = makeStore();
349
-
350
- // Mixed duplicate and unique stores.
351
- const unique = "unique topic about payment gateway integration";
352
- compactFull(s, SESS, [makeMsg("user", unique)], 1);
353
-
354
- const dup = "duplicate topic about payment gateway integration";
355
- compactFull(s, SESS, [makeMsg("user", dup)], 1);
356
-
357
- const statsBefore = vectorStats(s,SESS);
358
- assert.ok(statsBefore.checkpointCount >= 1, "checkpointCount should be positive");
359
- assert.ok(statsBefore.totalTokenEstimate >= 0, "totalTokenEstimate should be non-negative");
360
- assert.equal(statsBefore.dedupHitRate, 0, "no injections yet => dedupHitRate 0");
361
- assert.equal(statsBefore.injectedCount, 0, "no injections yet => injectedCount 0");
362
-
363
- const hits = vectorSearch(s, SESS, "payment gateway", 5);
364
- assert.ok(hits.length > 0, "should find the stored checkpoint");
365
- const cpId = hits[0].checkpoint.checkpointId;
366
-
367
- vectorMarkInjected(s,SESS, cpId);
368
- const statsAfter = vectorStats(s,SESS);
369
- assert.equal(statsAfter.injectedCount, 1, "injectedCount tracks markInjected");
370
- if (statsAfter.checkpointCount > 0) {
371
- assert.ok(
372
- Math.abs(statsAfter.dedupHitRate - 1 / statsAfter.checkpointCount) < 0.001,
373
- "dedupHitRate = injected / checkpoints",
374
- );
375
- }
376
- assert.ok(statsAfter.totalTokenEstimate > 0, "totalTokenEstimate positive after inserts");
377
- });
378
-
379
- it("dedupHitRate increases with duplicate content", () => {
380
- const s = makeStore();
381
- const base = "repeated region for hit-rate measurement";
382
-
383
- // Insert several duplicates; only first survives.
384
- for (let i = 0; i < 5; i++) {
385
- compactFull(s, SESS, [makeMsg("user", base)], 1);
386
- }
387
- compactFull(s, SESS, [makeMsg("user", "unique region for hit-rate measurement variant")], 1);
388
-
389
- // Mark the first as injected.
390
- const first = vectorSearch(s, SESS, base, 1)[0]?.checkpoint.checkpointId;
391
- if (first) vectorMarkInjected(s,SESS, first);
392
-
393
- const stats = vectorStats(s,SESS);
394
- assert.ok(stats.checkpointCount >= 1);
395
- assert.ok(
396
- stats.dedupHitRate > 0 || stats.checkpointCount === 1,
397
- "hit rate should be positive when there are multiple checkpoint",
398
- );
399
- });
400
- });
401
-
402
- // -------------------- 5. Recall & Dedup Sentinel --------------------
403
-
404
- describe("Recall & Dedup Sentinel", () => {
405
- const SESS = "sess_recall";
406
-
407
- it("recallAndInline returns toInject on first call and empty on second due to skipInjected", () => {
408
- const s = makeStore();
409
- const region = "detailed work on the vector store dedup sentinel and recall pipeline";
410
- compactFull(s, SESS, [makeMsg("user", region)]);
411
-
412
- assert.ok(
413
- recallAndInline,
414
- "recallAndInline should be exported from recall.js for this test",
415
- );
416
-
417
- const r1 = recallAndInline!(
418
- {
419
- sessionId: SESS,
420
- query: "dedup sentinel recall",
421
- limit: 3,
422
- source: "command",
423
- skipInjected: true,
424
- },
425
- s,
426
- );
427
- assert.ok(r1.toInject.length > 0, "first recall should return hits to inject");
428
-
429
- const r2 = recallAndInline!(
430
- {
431
- sessionId: SESS,
432
- query: "dedup sentinel recall",
433
- limit: 3,
434
- source: "command",
435
- skipInjected: true,
436
- },
437
- s,
438
- );
439
- assert.ok(r2.empty, "second recall should be empty because sentinel marked injected");
440
- });
441
-
442
- it("manual markInjected creates skip behavior when recallAndInline is unavailable", () => {
443
- const s = makeStore();
444
- const region = "manual sentinel tracking without recallAndInline";
445
- compactFull(s, SESS, [makeMsg("user", region)]);
446
-
447
- const hits = vectorSearch(s, SESS, "manual sentinel", 3);
448
- assert.ok(hits.length > 0, "search should return checkpoint");
449
- const cpId = hits[0].checkpoint.checkpointId;
450
- assert.equal(vectorWasInjected(s,SESS, cpId), false, "not yet injected");
451
-
452
- vectorMarkInjected(s,SESS, cpId);
453
- assert.equal(vectorWasInjected(s,SESS, cpId), true, "markInjected recorded");
454
-
455
- const hits2 = vectorSearch(s, SESS, "manual sentinel", 3).filter(
456
- (h) => !vectorWasInjected(s,SESS, h.checkpoint.checkpointId),
457
- );
458
- assert.equal(hits2.length, 0, "filtered search excludes injected checkpoint");
459
- });
460
- });
461
-
462
- // -------------------- 6. Edge Cases --------------------
463
-
464
- describe("Edge Cases", () => {
465
- const SESS = "sess_edge";
466
-
467
- it("empty message list returns skipped", () => {
468
- const s = makeStore();
469
- const r = compactSession({ sessionId: SESS, messages: [], keepFrom: 0 }, s);
470
- assert.equal(r.skipped, true);
471
- assert.equal(r.summary, "");
472
- assert.equal(vectorList(s,SESS).length, 0);
473
- });
474
-
475
- it("single message with keepFrom=0 returns skipped", () => {
476
- const s = makeStore();
477
- const r = compactSession(
478
- { sessionId: SESS, messages: [makeMsg("user", "only one message")], keepFrom: 0 },
479
- s,
480
- );
481
- assert.equal(r.skipped, true);
482
- assert.equal(vectorList(s,SESS).length, 0);
483
- });
484
-
485
- it("keepFrom at messages.length compacts all prior messages (verified behavior)", () => {
486
- // The engine treats keepFrom as the compactable boundary: messages[0..keepFrom)
487
- // are compacted. When keepFrom equals messages.length the entire conversation is
488
- // compactable, so it is NOT skipped. This test documents that behavior.
489
- const s = makeStore();
490
- const messages = buildConversation(6);
491
- const r = compactSession({ sessionId: SESS, messages, keepFrom: messages.length }, s);
492
- assert.equal(r.skipped, false);
493
- assert.ok(r.checkpointId);
494
- assert.equal(vectorList(s,SESS).length, 1);
495
- });
496
-
497
- it("unicode and emoji messages store and retrieve intact", () => {
498
- const s = makeStore();
499
- const text =
500
- "用户请求:创建 🎉 庆祝页面,包含 café 菜单 — déjà vu! " +
501
- "日本語テキスト 日本語テキスト 👍🔥";
502
- const r = compactFull(s, SESS, [makeMsg("user", text)], 1);
503
- assert.equal(r.skipped, false);
504
- const stored = vectorList(s,SESS)[0];
505
- assert.ok(stored);
506
- const recovered = Buffer.from(stored.compressedOriginal ?? Buffer.alloc(0));
507
- assert.ok(
508
- recovered.toString("utf-8").includes("🎉"),
509
- "emoji recovered from compressedOriginal",
510
- );
511
- assert.ok(stored.summary.includes("café") || stored.summary.includes("cafe"));
512
- });
513
-
514
- it("very large single message (>10k chars) compacts and stores successfully", () => {
515
- const s = makeStore();
516
- const big = "bigint ".repeat(2000);
517
- assert.ok(big.length > 10_000, `message length ${big.length}`);
518
- const r = compactFull(s, SESS, [makeMsg("user", big)], 1);
519
- assert.equal(r.skipped, false);
520
- assert.ok(r.checkpointId);
521
- assert.equal(vectorList(s,SESS).length, 1);
522
- const stats = vectorStats(s,SESS);
523
- assert.ok(stats.totalTokenEstimate > 0);
524
- });
525
-
526
- it("mixed roles (user/assistant/tool) are included in summary", () => {
527
- const s = makeStore();
528
- const messages: EngineMessage[] = [
529
- { role: "user", text: "fix the bug" },
530
- { role: "assistant", text: "will do", toolName: "Read", input: "src/bug.ts" },
531
- { role: "tool", text: "", toolName: "Read", output: "function foo() {}" },
532
- { role: "assistant", text: "fixed it", toolName: "Edit" },
533
- ];
534
- const r = compactFull(s, SESS, messages, messages.length);
535
- assert.equal(r.skipped, false);
536
- assert.ok(r.summary.length > 0);
537
- assert.ok(
538
- r.summary.includes("tool") ||
539
- r.summary.includes("Read") ||
540
- r.summary.includes("Edit") ||
541
- r.summary.includes("user") ||
542
- r.summary.includes("assistant"),
543
- "summary should reference roles or tools",
544
- );
545
- assert.equal(vectorList(s,SESS).length, 1);
546
- });
547
- });
548
-
549
- // -------------------- 7. Tier Switching (percentage-based) --------------------
550
-
551
- // Replaces the previous LOCAL replica of COMPACT_TIERS + resolveThresholdFromEnv
552
- // that asserted the OLD static token amounts. We now import the REAL config
553
- // helpers from extensions/mega-config.js so the tests track the live source of
554
- // truth: thresholds are tierPct × the model's context window (not fixed tokens).
555
-
556
- describe("Tier Switching — percentage-based thresholds", () => {
557
- // Documented tierPct fractions (single source of truth in mega-config.ts).
558
- it("each named tier carries the documented tierPct fraction", () => {
559
- assert.equal(TIER_PCT.low, 0.5);
560
- assert.equal(TIER_PCT.medium, 0.6);
561
- assert.equal(TIER_PCT.high, 0.7);
562
- assert.equal(TIER_PCT.ultra, 0.7);
563
- assert.equal(TIER_PCT.mega, 0.75);
564
- });
565
-
566
- // Boot fallback threshold (sane gate before the first context event supplies a
567
- // window): round(tierPct × 200_000). Resolved through the REAL loadConfig().
568
- it("MEGACOMPACT_TIER env resolves to the boot fallback threshold via real config", () => {
569
- const tiers: Array<[keyof typeof TIER_PCT, number]> = [
570
- ["low", 100_000], // 0.50 × 200_000
571
- ["medium", 120_000], // 0.60 × 200_000
572
- ["high", 140_000], // 0.70 × 200_000
573
- ["ultra", 140_000], // 0.70 × 200_000
574
- ["mega", 150_000], // 0.75 × 200_000
575
- ];
576
- for (const [tier, expectedBoot] of tiers) {
577
- const original = process.env.MEGACOMPACT_TIER;
578
- delete process.env.MEGACOMPACT_THRESHOLD_TOKENS;
579
- process.env.MEGACOMPACT_TIER = tier;
580
- try {
581
- const cfg = loadConfig();
582
- assert.equal(cfg.tier, tier, `tier ${tier} should resolve`);
583
- assert.equal(cfg.tierPct, TIER_PCT[tier], `tier ${tier} tierPct`);
584
- assert.equal(
585
- cfg.thresholdTokens,
586
- expectedBoot,
587
- `tier ${tier} boot fallback threshold should be ${expectedBoot}`,
588
- );
589
- } finally {
590
- if (original === undefined) delete process.env.MEGACOMPACT_TIER;
591
- else process.env.MEGACOMPACT_TIER = original;
592
- }
593
- }
594
- });
595
-
596
- it("explicit MEGACOMPACT_THRESHOLD_TOKENS overrides tier (custom stays absolute)", () => {
597
- const originalTier = process.env.MEGACOMPACT_TIER;
598
- const originalThreshold = process.env.MEGACOMPACT_THRESHOLD_TOKENS;
599
- delete process.env.MEGACOMPACT_TIER;
600
- process.env.MEGACOMPACT_THRESHOLD_TOKENS = "123456";
601
- try {
602
- const cfg = loadConfig();
603
- assert.equal(cfg.tier, "custom", "explicit token threshold → custom tier");
604
- assert.equal(cfg.tierPct, null, "custom tier has no tierPct (stays absolute)");
605
- assert.equal(cfg.thresholdTokens, 123_456, "explicit token threshold should win");
606
- } finally {
607
- if (originalTier === undefined) delete process.env.MEGACOMPACT_TIER;
608
- else process.env.MEGACOMPACT_TIER = originalTier;
609
- if (originalThreshold === undefined) delete process.env.MEGACOMPACT_THRESHOLD_TOKENS;
610
- else process.env.MEGACOMPACT_THRESHOLD_TOKENS = originalThreshold;
611
- }
612
- });
613
- });
614
-
615
- describe("effectiveThresholdTokens — tierPct × model window", () => {
616
- // The real compaction fire point. Tiered → scales with the window so it always
617
- // fires BELOW pi's native ~80% auto-compact for any model size. Custom (null
618
- // tierPct) → absolute explicitThreshold, never percent-scaled.
619
-
620
- it("scales tierPct × window for a 200k model", () => {
621
- assert.equal(
622
- effectiveThresholdTokens({ tierPct: TIER_PCT.low, fallbackThreshold: 100_000, window: 200_000 }),
623
- 100_000,
624
- );
625
- assert.equal(
626
- effectiveThresholdTokens({ tierPct: TIER_PCT.mega, fallbackThreshold: 150_000, window: 200_000 }),
627
- 150_000,
628
- );
629
- });
630
-
631
- it("scales tierPct × window for a 1M model", () => {
632
- assert.equal(
633
- effectiveThresholdTokens({ tierPct: TIER_PCT.low, fallbackThreshold: 500_000, window: 1_000_000 }),
634
- 500_000,
635
- );
636
- assert.equal(
637
- effectiveThresholdTokens({ tierPct: TIER_PCT.mega, fallbackThreshold: 750_000, window: 1_000_000 }),
638
- 750_000,
639
- );
640
- });
641
-
642
- it("falls back to the boot threshold when the window is 0/unknown", () => {
643
- assert.equal(
644
- effectiveThresholdTokens({ tierPct: TIER_PCT.mega, fallbackThreshold: 150_000, window: 0 }),
645
- 150_000,
646
- );
647
- assert.equal(
648
- effectiveThresholdTokens({ tierPct: TIER_PCT.low, fallbackThreshold: 100_000, window: -5 }),
649
- 100_000,
650
- );
651
- });
652
-
653
- it("custom (tierPct null) stays an absolute threshold regardless of window", () => {
654
- assert.equal(
655
- effectiveThresholdTokens({ tierPct: null, fallbackThreshold: 100_000, window: 200_000, explicitThreshold: 123456 }),
656
- 123456,
657
- "explicit absolute wins (200k window)",
658
- );
659
- assert.equal(
660
- effectiveThresholdTokens({ tierPct: null, fallbackThreshold: 100_000, window: 1_000_000, explicitThreshold: 123456 }),
661
- 123456,
662
- "explicit absolute wins (1M window)",
663
- );
664
- assert.equal(
665
- effectiveThresholdTokens({ tierPct: null, fallbackThreshold: 100_000, window: 200_000 }),
666
- 100_000,
667
- "no explicit → boot fallback",
668
- );
669
- });
670
- });