pi-mega-compact 0.11.4 → 0.11.6

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 (381) hide show
  1. package/dist/extensions/dashboard-server/api-contracts/cache-stripes.js +8 -0
  2. package/dist/extensions/dashboard-server/api-contracts/endpoints.js +32 -0
  3. package/dist/extensions/dashboard-server/api-contracts/memory-map.js +1 -0
  4. package/dist/extensions/dashboard-server/api-contracts/memory.js +8 -0
  5. package/dist/extensions/dashboard-server/api-contracts/provider-cache.js +1 -0
  6. package/dist/extensions/dashboard-server/api-contracts/setup.js +10 -0
  7. package/dist/extensions/dashboard-server/index-reader.js +6 -2
  8. package/dist/extensions/dashboard-server/routes-cache.js +135 -47
  9. package/dist/extensions/dashboard-server/routes-game.js +3 -0
  10. package/dist/extensions/dashboard-server/routes-memory-map.js +50 -0
  11. package/dist/extensions/dashboard-server/routes-memory.js +51 -0
  12. package/dist/extensions/dashboard-server/routes-repo.js +2 -2
  13. package/dist/extensions/dashboard-server/routes-setup.js +267 -0
  14. package/dist/extensions/dashboard-server/routes.js +4 -0
  15. package/dist/extensions/dashboard-server/server.js +13 -1
  16. package/dist/extensions/mega-commands.js +189 -1
  17. package/dist/extensions/mega-compact.js +5 -0
  18. package/dist/extensions/mega-config.js +7 -0
  19. package/dist/extensions/mega-events/agent-handlers.js +19 -4
  20. package/dist/extensions/mega-events/compact-handlers.js +1 -0
  21. package/dist/extensions/mega-events/context-handler.js +45 -92
  22. package/dist/extensions/mega-events/context-hwm.js +51 -0
  23. package/dist/extensions/mega-events/error-classifier.js +16 -5
  24. package/dist/extensions/mega-events/mirror-append.js +107 -0
  25. package/dist/extensions/mega-events/outage-advisor.js +7 -1
  26. package/dist/extensions/mega-events/perf-handler.js +134 -2
  27. package/dist/extensions/mega-events/recall-tail.js +59 -0
  28. package/dist/extensions/mega-events/separated-prompt.js +248 -0
  29. package/dist/extensions/mega-events/session-handlers.js +15 -8
  30. package/dist/extensions/mega-runtime/env-loader.js +56 -0
  31. package/dist/extensions/mega-runtime/reset-runtime.js +6 -0
  32. package/dist/extensions/mega-runtime/runtime-snapshot.js +1 -0
  33. package/dist/extensions/mega-runtime/runtime.js +7 -0
  34. package/dist/extensions/mega-runtime/snapshot.js +1 -0
  35. package/dist/extensions/mega-runtime/widget.js +5 -0
  36. package/dist/src/cache-stripe-impl.js +288 -0
  37. package/dist/src/cache-stripe.js +11 -0
  38. package/dist/src/config/stopwords.js +24 -0
  39. package/dist/src/config.js +17 -0
  40. package/dist/src/embedder.js +41 -2
  41. package/dist/src/memoryGraph.js +299 -0
  42. package/dist/src/memoryStats.js +75 -0
  43. package/dist/src/monitoring.js +13 -0
  44. package/dist/src/prefix-break.js +43 -0
  45. package/dist/src/pricing.js +1 -1
  46. package/dist/src/queryExpansion.js +163 -0
  47. package/dist/src/queryReformulation/cache.js +123 -0
  48. package/dist/src/queryReformulation/rrf.js +29 -0
  49. package/dist/src/queryReformulation/tfidf.js +61 -0
  50. package/dist/src/queryReformulation/vagueness.js +33 -0
  51. package/dist/src/queryReformulation.js +225 -0
  52. package/dist/src/recallMetrics.js +258 -0
  53. package/dist/src/store/sqlite/cache-stripes.js +133 -0
  54. package/dist/src/store/sqlite/fts5-search.js +68 -0
  55. package/dist/src/store/sqlite/perf-samples.js +145 -16
  56. package/dist/src/store/sqlite/schema.js +60 -1
  57. package/dist/src/store/sqlite.js +1 -0
  58. package/dist/src/store/turns/memory-store.js +8 -0
  59. package/dist/src/store/turns/sqlite-store.js +14 -3
  60. package/dist/src/store/turns/types.js +18 -1
  61. package/dist/src/store/vectorIndex.js +55 -10
  62. package/dist/src/tiered-router/types.js +18 -0
  63. package/dist/src/tieredRouter.js +421 -0
  64. package/dist/src/vectorStore.js +8 -6
  65. package/extensions/dashboard-client/dist/assets/{AchievementTiles-vEo2MtE2.js → AchievementTiles-DR9cLGDL.js} +2 -2
  66. package/extensions/dashboard-client/dist/assets/{AchievementTiles-vEo2MtE2.js.map → AchievementTiles-DR9cLGDL.js.map} +1 -1
  67. package/extensions/dashboard-client/dist/assets/AchievementsTab-svNUgJ1e.js +2 -0
  68. package/extensions/dashboard-client/dist/assets/{AchievementsTab-DjxfYrDc.js.map → AchievementsTab-svNUgJ1e.js.map} +1 -1
  69. package/extensions/dashboard-client/dist/assets/CacheTab-ASwhOMjR.js +2 -0
  70. package/extensions/dashboard-client/dist/assets/CacheTab-ASwhOMjR.js.map +1 -0
  71. package/extensions/dashboard-client/dist/assets/{ConfigTab-Cm6ymbmx.js → ConfigTab-CmmWheuW.js} +2 -2
  72. package/extensions/dashboard-client/dist/assets/{ConfigTab-Cm6ymbmx.js.map → ConfigTab-CmmWheuW.js.map} +1 -1
  73. package/extensions/dashboard-client/dist/assets/{EventsTab-DXWl_YzI.js → EventsTab-CFE7jLsa.js} +2 -2
  74. package/extensions/dashboard-client/dist/assets/{EventsTab-DXWl_YzI.js.map → EventsTab-CFE7jLsa.js.map} +1 -1
  75. package/extensions/dashboard-client/dist/assets/GameTab-CJAX_th_.js +2 -0
  76. package/extensions/dashboard-client/dist/assets/{GameTab-BLDudcO5.js.map → GameTab-CJAX_th_.js.map} +1 -1
  77. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-DLkKCztn.js → MaintenanceTab-P4SUsvMf.js} +2 -2
  78. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-DLkKCztn.js.map → MaintenanceTab-P4SUsvMf.js.map} +1 -1
  79. package/extensions/dashboard-client/dist/assets/MemoryMapTab-BBiH76eF.js +2 -0
  80. package/extensions/dashboard-client/dist/assets/MemoryMapTab-BBiH76eF.js.map +1 -0
  81. package/extensions/dashboard-client/dist/assets/{MetricsTab-Cq4u-rZF.js → MetricsTab-CHQscixy.js} +2 -2
  82. package/extensions/dashboard-client/dist/assets/{MetricsTab-Cq4u-rZF.js.map → MetricsTab-CHQscixy.js.map} +1 -1
  83. package/extensions/dashboard-client/dist/assets/OverviewTab-DBs4DJdd.js +2 -0
  84. package/extensions/dashboard-client/dist/assets/{OverviewTab-D4kGvsiQ.js.map → OverviewTab-DBs4DJdd.js.map} +1 -1
  85. package/extensions/dashboard-client/dist/assets/ReposTab-DeFz76L5.js +2 -0
  86. package/extensions/dashboard-client/dist/assets/ReposTab-DeFz76L5.js.map +1 -0
  87. package/extensions/dashboard-client/dist/assets/{SessionsTab-DZC2-GCn.js → SessionsTab-BWNsj1OB.js} +2 -2
  88. package/extensions/dashboard-client/dist/assets/{SessionsTab-DZC2-GCn.js.map → SessionsTab-BWNsj1OB.js.map} +1 -1
  89. package/extensions/dashboard-client/dist/assets/SetupTab-uS6A0xmw.js +2 -0
  90. package/extensions/dashboard-client/dist/assets/SetupTab-uS6A0xmw.js.map +1 -0
  91. package/extensions/dashboard-client/dist/assets/TimeSavedCard-CiqCOQuL.js +2 -0
  92. package/extensions/dashboard-client/dist/assets/TimeSavedCard-CiqCOQuL.js.map +1 -0
  93. package/extensions/dashboard-client/dist/assets/{TopicsTab-01G71hv1.js → TopicsTab-BWWQxltv.js} +2 -2
  94. package/extensions/dashboard-client/dist/assets/{TopicsTab-01G71hv1.js.map → TopicsTab-BWWQxltv.js.map} +1 -1
  95. package/extensions/dashboard-client/dist/assets/{TurnsTab-DLRg0LZT.js → TurnsTab-CVz4f4-o.js} +2 -2
  96. package/extensions/dashboard-client/dist/assets/{TurnsTab-DLRg0LZT.js.map → TurnsTab-CVz4f4-o.js.map} +1 -1
  97. package/extensions/dashboard-client/dist/assets/format-COjDIVGj.js +2 -0
  98. package/extensions/dashboard-client/dist/assets/format-COjDIVGj.js.map +1 -0
  99. package/extensions/dashboard-client/dist/assets/index-CUNn22iV.css +1 -0
  100. package/extensions/dashboard-client/dist/assets/index-DrktNOoT.js +42 -0
  101. package/extensions/dashboard-client/dist/assets/index-DrktNOoT.js.map +1 -0
  102. package/extensions/dashboard-client/dist/assets/pricing-CvE4NllQ.js +2 -0
  103. package/extensions/dashboard-client/dist/assets/pricing-CvE4NllQ.js.map +1 -0
  104. package/extensions/dashboard-client/dist/assets/{useSSE-BBYt5UPB.js → useSSE-Bf5LOLSi.js} +2 -2
  105. package/extensions/dashboard-client/dist/assets/{useSSE-BBYt5UPB.js.map → useSSE-Bf5LOLSi.js.map} +1 -1
  106. package/extensions/dashboard-client/dist/index.html +2 -2
  107. package/extensions/dashboard-client/src/App.tsx +28 -8
  108. package/extensions/dashboard-client/src/api/client.ts +29 -0
  109. package/extensions/dashboard-client/src/components/ActiveReposTable.tsx +21 -12
  110. package/extensions/dashboard-client/src/components/CacheHitRateTrendCard.tsx +100 -0
  111. package/extensions/dashboard-client/src/components/ProviderCacheCard.tsx +56 -0
  112. package/extensions/dashboard-client/src/components/SavingsByModelTable.tsx +38 -57
  113. package/extensions/dashboard-client/src/components/StripeDistributionCard.tsx +110 -0
  114. package/extensions/dashboard-client/src/components/TabBar.tsx +49 -4
  115. package/extensions/dashboard-client/src/main.tsx +1 -0
  116. package/extensions/dashboard-client/src/styles/base.css +30 -0
  117. package/extensions/dashboard-client/src/styles/cache.css +167 -0
  118. package/extensions/dashboard-client/src/tabs/CacheTab.tsx +75 -12
  119. package/extensions/dashboard-client/src/tabs/MemoryMapTab.tsx +440 -0
  120. package/extensions/dashboard-client/src/tabs/SetupTab.tsx +418 -0
  121. package/extensions/dashboard-client/tsconfig.json +3 -2
  122. package/extensions/dashboard-client/vite.config.ts +2 -0
  123. package/extensions/dashboard-server/api-contracts/cache-stripes.ts +49 -0
  124. package/extensions/dashboard-server/api-contracts/endpoints.ts +66 -3
  125. package/extensions/dashboard-server/api-contracts/index.ts +22 -0
  126. package/extensions/dashboard-server/api-contracts/memory-map.ts +50 -0
  127. package/extensions/dashboard-server/api-contracts/memory.ts +27 -0
  128. package/extensions/dashboard-server/api-contracts/multi-repo.ts +231 -231
  129. package/extensions/dashboard-server/api-contracts/provider-cache.ts +37 -0
  130. package/extensions/dashboard-server/api-contracts/setup.ts +80 -0
  131. package/extensions/dashboard-server/index-reader.ts +138 -121
  132. package/extensions/dashboard-server/routes-cache.ts +186 -75
  133. package/extensions/dashboard-server/routes-game.ts +3 -0
  134. package/extensions/dashboard-server/routes-memory-map.ts +105 -0
  135. package/extensions/dashboard-server/routes-memory.ts +63 -0
  136. package/extensions/dashboard-server/routes-repo.ts +36 -36
  137. package/extensions/dashboard-server/routes-setup.ts +293 -0
  138. package/extensions/dashboard-server/routes.ts +4 -0
  139. package/extensions/dashboard-server/server.ts +12 -0
  140. package/extensions/mega-commands.ts +211 -1
  141. package/extensions/mega-compact.ts +5 -0
  142. package/extensions/mega-config.ts +27 -0
  143. package/extensions/mega-events/agent-handlers.ts +20 -4
  144. package/extensions/mega-events/compact-handlers.ts +1 -0
  145. package/extensions/mega-events/context-handler.ts +53 -110
  146. package/extensions/mega-events/context-hwm.ts +85 -0
  147. package/extensions/mega-events/error-classifier.ts +15 -4
  148. package/extensions/mega-events/mirror-append.ts +155 -0
  149. package/extensions/mega-events/outage-advisor.ts +11 -5
  150. package/extensions/mega-events/perf-handler.ts +190 -6
  151. package/extensions/mega-events/recall-tail.ts +88 -0
  152. package/extensions/mega-events/separated-prompt.ts +329 -0
  153. package/extensions/mega-events/session-handlers.ts +14 -7
  154. package/extensions/mega-runtime/env-loader.ts +55 -0
  155. package/extensions/mega-runtime/helpers.ts +14 -0
  156. package/extensions/mega-runtime/reset-runtime.ts +6 -0
  157. package/extensions/mega-runtime/runtime-snapshot.ts +1 -0
  158. package/extensions/mega-runtime/runtime.ts +7 -0
  159. package/extensions/mega-runtime/snapshot.ts +6 -0
  160. package/extensions/mega-runtime/widget-types.ts +3 -0
  161. package/extensions/mega-runtime/widget.ts +5 -0
  162. package/package.json +5 -2
  163. package/src/cache-stripe-impl.ts +385 -0
  164. package/src/cache-stripe.ts +18 -0
  165. package/src/config/stopwords.ts +25 -0
  166. package/src/config.ts +26 -0
  167. package/src/embedder.ts +42 -2
  168. package/src/memoryGraph.ts +438 -0
  169. package/src/memoryStats.ts +107 -0
  170. package/src/monitoring.ts +35 -0
  171. package/src/prefix-break.ts +83 -0
  172. package/src/pricing.ts +2 -2
  173. package/src/queryExpansion.ts +206 -0
  174. package/src/queryReformulation/cache.ts +169 -0
  175. package/src/queryReformulation/rrf.ts +51 -0
  176. package/src/queryReformulation/tfidf.ts +79 -0
  177. package/src/queryReformulation/vagueness.ts +38 -0
  178. package/src/queryReformulation.ts +355 -0
  179. package/src/recallMetrics.ts +388 -0
  180. package/src/store/sqlite/cache-stripes.ts +196 -0
  181. package/src/store/sqlite/fts5-search.ts +90 -0
  182. package/src/store/sqlite/perf-samples.ts +218 -23
  183. package/src/store/sqlite/schema.ts +60 -1
  184. package/src/store/sqlite.ts +1 -0
  185. package/src/store/turns/memory-store.ts +10 -1
  186. package/src/store/turns/sqlite-store.ts +27 -15
  187. package/src/store/turns/types.ts +21 -0
  188. package/src/store/vectorIndex.ts +71 -11
  189. package/src/tiered-router/types.ts +64 -0
  190. package/src/tieredRouter.ts +489 -0
  191. package/src/vectorStore.ts +9 -5
  192. package/dist/extensions/conflict-scan.test.js +0 -115
  193. package/dist/extensions/dashboard-server/api-contracts.test.js +0 -884
  194. package/dist/extensions/dashboard-server/html.test.js +0 -52
  195. package/dist/extensions/dashboard-server/perf-server.test.js +0 -80
  196. package/dist/extensions/dashboard-server/routes-cache.test.js +0 -248
  197. package/dist/extensions/dashboard-server/server.test.js +0 -120
  198. package/dist/extensions/dashboard-server-s32.test.js +0 -181
  199. package/dist/extensions/dashboard-server.test.js +0 -339
  200. package/dist/extensions/mega-cache-replay.test.js +0 -400
  201. package/dist/extensions/mega-compact-s38.test.js +0 -1383
  202. package/dist/extensions/mega-compact.test.js +0 -1112
  203. package/dist/extensions/mega-events.test.js +0 -47
  204. package/dist/extensions/mega-game-cmds.test.js +0 -163
  205. package/dist/extensions/mega-runtime/snapshot.test.js +0 -127
  206. package/dist/extensions/mega-runtime/state.test.js +0 -266
  207. package/dist/extensions/mega-runtime/widget.test.js +0 -343
  208. package/dist/extensions/mega-shutdown-widget.test.js +0 -121
  209. package/dist/extensions/mega-teamrun.test.js +0 -156
  210. package/dist/extensions/mega-trim.test.js +0 -58
  211. package/dist/extensions/mega-turn-store.test.js +0 -68
  212. package/dist/src/boundary.test.js +0 -170
  213. package/dist/src/compact.test.js +0 -78
  214. package/dist/src/config/themes.test.js +0 -94
  215. package/dist/src/dedup/dedup.test.js +0 -41
  216. package/dist/src/dedup/l1.test.js +0 -50
  217. package/dist/src/dedup/raptor/buildHistory.test.js +0 -292
  218. package/dist/src/dedup/raptor/multilevel-serve.test.js +0 -229
  219. package/dist/src/dedup/raptor/multilevel.test.js +0 -238
  220. package/dist/src/dedup/raptor/promote.test.js +0 -69
  221. package/dist/src/dedup/raptor/raptor.test.js +0 -248
  222. package/dist/src/dedup/raptor/retrieval.test.js +0 -95
  223. package/dist/src/dedup/raptor/serve-gate.test.js +0 -298
  224. package/dist/src/dedup/sprint12.test.js +0 -219
  225. package/dist/src/dedup-engine.test.js +0 -472
  226. package/dist/src/driftDetection.test.js +0 -87
  227. package/dist/src/e2e.test.js +0 -698
  228. package/dist/src/engine.test.js +0 -111
  229. package/dist/src/extractive.test.js +0 -147
  230. package/dist/src/fork.test.js +0 -81
  231. package/dist/src/game/scoring.test.js +0 -98
  232. package/dist/src/httpEmbedder.test.js +0 -277
  233. package/dist/src/importance.test.js +0 -372
  234. package/dist/src/intent.test.js +0 -78
  235. package/dist/src/log.test.js +0 -42
  236. package/dist/src/mechanical-fix.test.js +0 -65
  237. package/dist/src/memory.test.js +0 -70
  238. package/dist/src/memoryConsolidate.test.js +0 -38
  239. package/dist/src/memoryOps.test.js +0 -129
  240. package/dist/src/memoryRecall.test.js +0 -171
  241. package/dist/src/memoryRoundtrip.test.js +0 -137
  242. package/dist/src/metrics/turns.test.js +0 -152
  243. package/dist/src/mirror/mirror.test.js +0 -185
  244. package/dist/src/raptor-inject-summaries.test.js +0 -162
  245. package/dist/src/ratio.bench.test.js +0 -897
  246. package/dist/src/recall.integration.test.js +0 -77
  247. package/dist/src/recall.test.js +0 -379
  248. package/dist/src/sprint14.test.js +0 -219
  249. package/dist/src/sprint4x-rag-verification.test.js +0 -93
  250. package/dist/src/store/compression.test.js +0 -139
  251. package/dist/src/store/memoryIndex.test.js +0 -51
  252. package/dist/src/store/migrate.test.js +0 -139
  253. package/dist/src/store/pgOpenGuard.test.js +0 -74
  254. package/dist/src/store/phase01.test.js +0 -81
  255. package/dist/src/store/phase04.test.js +0 -54
  256. package/dist/src/store/sprint10.test.js +0 -186
  257. package/dist/src/store/sqlite/game-achievements.test.js +0 -67
  258. package/dist/src/store/sqlite/game-scores.test.js +0 -106
  259. package/dist/src/store/sqlite/game-state.test.js +0 -76
  260. package/dist/src/store/sqlite/global-index.test.js +0 -136
  261. package/dist/src/store/sqlite/mechanical-fix.test.js +0 -146
  262. package/dist/src/store/sqlite/perf-samples.test.js +0 -146
  263. package/dist/src/store/sqlite/raptor.test.js +0 -106
  264. package/dist/src/store/sqlite/turns.test.js +0 -183
  265. package/dist/src/store/sqlite.cachehit.test.js +0 -55
  266. package/dist/src/store/sqlite.dbmaint.test.js +0 -158
  267. package/dist/src/store/sqlite.dbmirror.test.js +0 -184
  268. package/dist/src/store/turns/contract-compliance.test.js +0 -428
  269. package/dist/src/store/turns/memory-store.test.js +0 -9
  270. package/dist/src/store/turns/migrations.test.js +0 -138
  271. package/dist/src/store/turns/sqlite-store.test.js +0 -144
  272. package/dist/src/store/vectorIndex.test.js +0 -123
  273. package/dist/src/store.test.js +0 -161
  274. package/dist/src/supersede.test.js +0 -36
  275. package/dist/src/topics/cluster.test.js +0 -150
  276. package/dist/src/topics/store.test.js +0 -117
  277. package/dist/src/types.test.js +0 -9
  278. package/dist/src/vector-search-cache.test.js +0 -157
  279. package/dist/src/vectorStore.test.js +0 -479
  280. package/dist/src/wiki.test.js +0 -171
  281. package/extensions/conflict-scan.test.ts +0 -129
  282. package/extensions/dashboard-client/dist/assets/AchievementsTab-DjxfYrDc.js +0 -2
  283. package/extensions/dashboard-client/dist/assets/CacheTab-Dnpv94wq.js +0 -2
  284. package/extensions/dashboard-client/dist/assets/CacheTab-Dnpv94wq.js.map +0 -1
  285. package/extensions/dashboard-client/dist/assets/GameTab-BLDudcO5.js +0 -2
  286. package/extensions/dashboard-client/dist/assets/OverviewTab-D4kGvsiQ.js +0 -2
  287. package/extensions/dashboard-client/dist/assets/ReposTab-C0Wnrf2u.js +0 -2
  288. package/extensions/dashboard-client/dist/assets/ReposTab-C0Wnrf2u.js.map +0 -1
  289. package/extensions/dashboard-client/dist/assets/TimeSavedCard-UqljSyP-.js +0 -2
  290. package/extensions/dashboard-client/dist/assets/TimeSavedCard-UqljSyP-.js.map +0 -1
  291. package/extensions/dashboard-client/dist/assets/index-BEdKlpAB.css +0 -1
  292. package/extensions/dashboard-client/dist/assets/index-BX0bcgLu.js +0 -42
  293. package/extensions/dashboard-client/dist/assets/index-BX0bcgLu.js.map +0 -1
  294. package/extensions/dashboard-server/api-contracts.test.ts +0 -1065
  295. package/extensions/dashboard-server/html.test.ts +0 -62
  296. package/extensions/dashboard-server/perf-server.test.ts +0 -101
  297. package/extensions/dashboard-server/routes-cache.test.ts +0 -302
  298. package/extensions/dashboard-server/server.test.ts +0 -131
  299. package/extensions/dashboard-server-s32.test.ts +0 -195
  300. package/extensions/dashboard-server.test.ts +0 -382
  301. package/extensions/mega-cache-replay.test.ts +0 -526
  302. package/extensions/mega-compact-s38.test.ts +0 -1433
  303. package/extensions/mega-compact.test.ts +0 -1509
  304. package/extensions/mega-events.test.ts +0 -55
  305. package/extensions/mega-game-cmds.test.ts +0 -197
  306. package/extensions/mega-runtime/snapshot.test.ts +0 -139
  307. package/extensions/mega-runtime/state.test.ts +0 -262
  308. package/extensions/mega-runtime/widget.test.ts +0 -468
  309. package/extensions/mega-shutdown-widget.test.ts +0 -141
  310. package/extensions/mega-teamrun.test.ts +0 -176
  311. package/extensions/mega-trim.test.ts +0 -64
  312. package/extensions/mega-turn-store.test.ts +0 -108
  313. package/src/boundary.test.ts +0 -187
  314. package/src/compact.test.ts +0 -99
  315. package/src/config/themes.test.ts +0 -116
  316. package/src/dedup/dedup.test.ts +0 -46
  317. package/src/dedup/l1.test.ts +0 -57
  318. package/src/dedup/raptor/buildHistory.test.ts +0 -353
  319. package/src/dedup/raptor/multilevel-serve.test.ts +0 -273
  320. package/src/dedup/raptor/multilevel.test.ts +0 -325
  321. package/src/dedup/raptor/promote.test.ts +0 -82
  322. package/src/dedup/raptor/raptor.test.ts +0 -297
  323. package/src/dedup/raptor/retrieval.test.ts +0 -118
  324. package/src/dedup/raptor/serve-gate.test.ts +0 -348
  325. package/src/dedup/sprint12.test.ts +0 -242
  326. package/src/dedup-engine.test.ts +0 -670
  327. package/src/driftDetection.test.ts +0 -100
  328. package/src/e2e.test.ts +0 -843
  329. package/src/engine.test.ts +0 -123
  330. package/src/extractive.test.ts +0 -174
  331. package/src/fork.test.ts +0 -94
  332. package/src/game/scoring.test.ts +0 -103
  333. package/src/httpEmbedder.test.ts +0 -286
  334. package/src/importance.test.ts +0 -538
  335. package/src/intent.test.ts +0 -87
  336. package/src/log.test.ts +0 -47
  337. package/src/mechanical-fix.test.ts +0 -70
  338. package/src/memory.test.ts +0 -92
  339. package/src/memoryConsolidate.test.ts +0 -47
  340. package/src/memoryOps.test.ts +0 -148
  341. package/src/memoryRecall.test.ts +0 -194
  342. package/src/memoryRoundtrip.test.ts +0 -155
  343. package/src/metrics/turns.test.ts +0 -165
  344. package/src/mirror/mirror.test.ts +0 -240
  345. package/src/raptor-inject-summaries.test.ts +0 -228
  346. package/src/ratio.bench.test.ts +0 -1316
  347. package/src/recall.integration.test.ts +0 -96
  348. package/src/recall.test.ts +0 -467
  349. package/src/sprint14.test.ts +0 -245
  350. package/src/sprint4x-rag-verification.test.ts +0 -119
  351. package/src/store/compression.test.ts +0 -168
  352. package/src/store/memoryIndex.test.ts +0 -61
  353. package/src/store/migrate.test.ts +0 -158
  354. package/src/store/pgOpenGuard.test.ts +0 -89
  355. package/src/store/phase01.test.ts +0 -88
  356. package/src/store/phase04.test.ts +0 -58
  357. package/src/store/sprint10.test.ts +0 -214
  358. package/src/store/sqlite/game-achievements.test.ts +0 -80
  359. package/src/store/sqlite/game-scores.test.ts +0 -132
  360. package/src/store/sqlite/game-state.test.ts +0 -89
  361. package/src/store/sqlite/global-index.test.ts +0 -222
  362. package/src/store/sqlite/mechanical-fix.test.ts +0 -162
  363. package/src/store/sqlite/perf-samples.test.ts +0 -169
  364. package/src/store/sqlite/raptor.test.ts +0 -139
  365. package/src/store/sqlite/turns.test.ts +0 -218
  366. package/src/store/sqlite.cachehit.test.ts +0 -68
  367. package/src/store/sqlite.dbmaint.test.ts +0 -193
  368. package/src/store/sqlite.dbmirror.test.ts +0 -229
  369. package/src/store/turns/contract-compliance.test.ts +0 -562
  370. package/src/store/turns/memory-store.test.ts +0 -15
  371. package/src/store/turns/migrations.test.ts +0 -161
  372. package/src/store/turns/sqlite-store.test.ts +0 -161
  373. package/src/store/vectorIndex.test.ts +0 -140
  374. package/src/store.test.ts +0 -191
  375. package/src/supersede.test.ts +0 -42
  376. package/src/topics/cluster.test.ts +0 -176
  377. package/src/topics/store.test.ts +0 -132
  378. package/src/types.test.ts +0 -10
  379. package/src/vector-search-cache.test.ts +0 -190
  380. package/src/vectorStore.test.ts +0 -533
  381. package/src/wiki.test.ts +0 -217
@@ -1,472 +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
- import { describe, it, beforeEach, afterEach } from "node:test";
14
- import assert from "node:assert/strict";
15
- import fs from "fs";
16
- import path from "path";
17
- import os from "os";
18
- import { compactSession } from "./engine.js";
19
- import { VectorStore, vectorList, vectorStats, vectorWasInjected, vectorMarkInjected, vectorSearch } from "./vectorStore.js";
20
- import { extractiveSummarize } from "./extractive.js";
21
- import { estimateSessionTokens, estimateMessageTokens } from "./tokens.js";
22
- import { autoCompactCheck } from "./compact.js";
23
- import { loadDedupConfig } from "./config/dedup.js";
24
- // Real percentage-based threshold config. Replaces the previous LOCAL replica of
25
- // COMPACT_TIERS + resolveThresholdFromEnv that asserted the OLD static token
26
- // amounts — importing the live source of truth keeps tests in sync with the
27
- // source (thresholds are tierPct × the model's context window, not fixed tokens).
28
- import { TIER_PCT, effectiveThresholdTokens, loadConfig } from "../extensions/mega-config.js";
29
- // recallAndInline may or may not be exported; import safely.
30
- import * as recallMod from "./recall.js";
31
- const recallAndInline = recallMod.recallAndInline;
32
- // -------------------- Helpers --------------------
33
- function mkTmpDir() {
34
- return fs.mkdtempSync(path.join(os.tmpdir(), "mc-dedup-"));
35
- }
36
- let currentTmpDir;
37
- beforeEach(() => {
38
- currentTmpDir = mkTmpDir();
39
- });
40
- afterEach(() => {
41
- if (currentTmpDir && fs.existsSync(currentTmpDir)) {
42
- fs.rmSync(currentTmpDir, { recursive: true, force: true });
43
- }
44
- currentTmpDir = undefined;
45
- });
46
- function baseConfig() {
47
- return loadDedupConfig();
48
- }
49
- function makeStore(over = {}) {
50
- return new VectorStore({
51
- stateDir: currentTmpDir,
52
- config: { ...baseConfig(), ...over },
53
- });
54
- }
55
- function makeMsg(role, text) {
56
- return { role, text };
57
- }
58
- function buildConversation(n, prefix = "turn") {
59
- const out = [];
60
- for (let i = 0; i < n; i++) {
61
- const role = i % 2 === 0 ? "user" : "assistant";
62
- out.push(makeMsg(role, `${prefix} ${i + 1}: ${role} discusses implementation of feature ${i + 1} in src/module${i + 1}.ts and considers tradeoffs.`));
63
- }
64
- return out;
65
- }
66
- function compactFull(store, sessionId, messages, keepFrom) {
67
- return compactSession({ sessionId, messages, keepFrom: keepFrom ?? messages.length }, store);
68
- }
69
- // -------------------- 1. Compaction Levels --------------------
70
- describe("Compaction Levels (Tier Behavior)", () => {
71
- const TIER_CASES = [
72
- ["low", 50_000],
73
- ["medium", 100_000],
74
- ["high", 200_000],
75
- ["ultra", 1_000_000],
76
- ["mega", 10_000_000],
77
- ];
78
- for (const [tier, threshold] of TIER_CASES) {
79
- it(`tier "${tier}" (${threshold.toLocaleString()} threshold) triggers only when tokens exceed threshold`, () => {
80
- // One token below threshold => should not compact.
81
- const under = autoCompactCheck(threshold - 1, threshold);
82
- assert.equal(under.shouldCompact, false, "one token below threshold should not trigger");
83
- assert.equal(under.threshold, threshold);
84
- // At threshold => should compact.
85
- const at = autoCompactCheck(threshold, threshold);
86
- assert.equal(at.shouldCompact, true, "at threshold should trigger");
87
- // One token above threshold => should compact.
88
- const over = autoCompactCheck(threshold + 1, threshold);
89
- assert.equal(over.shouldCompact, true, "one token above threshold should trigger");
90
- // Generate deterministic conversation of known token size.
91
- const tokensPerMsg = estimateMessageTokens({
92
- text: "deterministic sample message of moderate length for threshold testing.",
93
- });
94
- assert.ok(tokensPerMsg > 0);
95
- const needed = Math.ceil((threshold + tokensPerMsg) / tokensPerMsg);
96
- const messages = buildConversation(needed);
97
- const estimate = estimateSessionTokens(messages);
98
- assert.ok(estimate >= threshold, `expected estimate ${estimate} >= threshold ${threshold}`);
99
- const longCheck = autoCompactCheck(estimate, threshold);
100
- assert.equal(longCheck.shouldCompact, true);
101
- // Smaller conversation should not trigger. Derive the average per-message
102
- // cost from the large conversation we already tokenized, then leave margin below threshold.
103
- const avgTokensPerMsg = estimate / messages.length;
104
- const smallCount = Math.max(1, Math.floor((threshold * 0.95) / avgTokensPerMsg) - 5);
105
- const smallMessages = buildConversation(smallCount);
106
- const smallEstimate = estimateSessionTokens(smallMessages);
107
- assert.ok(smallEstimate < threshold, `expected small estimate ${smallEstimate} < threshold ${threshold}`);
108
- const smallCheck = autoCompactCheck(smallEstimate, threshold);
109
- assert.equal(smallCheck.shouldCompact, false, "small conversation should not trigger tier");
110
- });
111
- }
112
- });
113
- // -------------------- 2. Dedupe Levels --------------------
114
- describe("Dedupe Levels", () => {
115
- const SESS = "sess_dedup";
116
- it("L0 only: identical content stored twice collapses to one checkpoint", () => {
117
- const s = makeStore({ L0_ENABLED: true, L1_ENABLED: false, L2_ENABLED: false });
118
- const region = "exact same user request about database migration and index setup";
119
- const r1 = compactFull(s, SESS, [makeMsg("user", region)]);
120
- assert.equal(r1.deduped, false);
121
- assert.ok(r1.checkpointId);
122
- const r2 = compactFull(s, SESS, [makeMsg("user", region)]);
123
- assert.equal(r2.deduped, true);
124
- assert.equal(r2.checkpointId, r1.checkpointId);
125
- assert.equal(vectorList(s, SESS).length, 1);
126
- });
127
- it("L0 only: distinct content stored twice creates two checkpoints", () => {
128
- const s = makeStore({ L0_ENABLED: true, L1_ENABLED: false, L2_ENABLED: false });
129
- const regionA = "first exact region about authentication module refactoring";
130
- const regionB = "second distinct region about frontend component testing";
131
- const r1 = compactFull(s, SESS, [makeMsg("user", regionA)]);
132
- const r2 = compactFull(s, SESS, [makeMsg("user", regionB)]);
133
- assert.equal(r1.deduped, false);
134
- assert.equal(r2.deduped, false);
135
- assert.notEqual(r1.checkpointId, r2.checkpointId);
136
- assert.equal(vectorList(s, SESS).length, 2);
137
- });
138
- it("L1 only: one-word variants collapse; major rewrites do not", () => {
139
- const s = makeStore({ L0_ENABLED: false, L1_ENABLED: true, L2_ENABLED: false });
140
- const base = "the database migration added three new indexes to the users table for faster lookups";
141
- const variant = "the database migration added three new indexes to the users table for faster lookup";
142
- const rewrite = "the frontend dark mode toggle uses css custom properties for theming";
143
- const r1 = s.add({ sessionId: SESS, summary: "migration", regionText: base, timestamp: 1 });
144
- assert.equal(r1.deduped, false);
145
- const r2 = s.add({ sessionId: SESS, summary: "migration", regionText: variant, timestamp: 2 });
146
- assert.equal(r2.deduped, true, "one-word variant should be collapsed by L1");
147
- assert.equal(vectorList(s, SESS).length, 1);
148
- const r3 = s.add({ sessionId: SESS, summary: "frontend", regionText: rewrite, timestamp: 3 });
149
- assert.equal(r3.deduped, false, "major rewrite should not be collapsed by L1");
150
- assert.equal(vectorList(s, SESS).length, 2);
151
- });
152
- it("L2 only: semantic paraphrases collapse; unrelated topics do not", () => {
153
- // Use a lower threshold and longer, lexically-overlapping paraphrase so the
154
- // deterministic trigram embedder reliably catches it while still distinguishing
155
- // unrelated topics.
156
- const s = makeStore({ L0_ENABLED: false, L1_ENABLED: false, L2_ENABLED: true, L2_COSINE: 0.60 });
157
- const original = "user authentication and session token management login validation session expiry handling secure cookie";
158
- const paraphrase = "login validation session expiry handling secure cookie user authentication and session token management";
159
- const unrelated = "the frontend added a dark mode toggle with css custom properties";
160
- const r1 = s.add({ sessionId: SESS, summary: "auth", regionText: original, timestamp: 1 });
161
- assert.equal(r1.deduped, false);
162
- const r2 = s.add({ sessionId: SESS, summary: "auth paraphrase", regionText: paraphrase, timestamp: 2 });
163
- assert.equal(r2.deduped, true, "semantic paraphrase should be collapsed by L2");
164
- assert.equal(vectorList(s, SESS).length, 1);
165
- const r3 = s.add({ sessionId: SESS, summary: "frontend", regionText: unrelated, timestamp: 3 });
166
- assert.equal(r3.deduped, false, "unrelated topic should not be collapsed by L2");
167
- assert.equal(vectorList(s, SESS).length, 2);
168
- });
169
- it("All tiers disabled: every store.add() with different region text creates a distinct checkpoint", () => {
170
- // Even with all dedup tiers disabled, the store still enforces a unique
171
- // content_hash constraint, so we vary the region text slightly for each add.
172
- const s = makeStore({ L0_ENABLED: false, L1_ENABLED: false, L2_ENABLED: false });
173
- const r1 = s.add({ sessionId: SESS, summary: "a", regionText: "region alpha", timestamp: 1 });
174
- const r2 = s.add({ sessionId: SESS, summary: "a", regionText: "region beta", timestamp: 2 });
175
- const r3 = s.add({ sessionId: SESS, summary: "a", regionText: "region gamma", timestamp: 3 });
176
- assert.equal(r1.deduped, false);
177
- assert.equal(r2.deduped, false);
178
- assert.equal(r3.deduped, false);
179
- assert.notEqual(r1.checkpoint.checkpointId, r2.checkpoint.checkpointId);
180
- assert.notEqual(r2.checkpoint.checkpointId, r3.checkpoint.checkpointId);
181
- assert.equal(vectorList(s, SESS).length, 3);
182
- });
183
- it("Combined L0+L1+L2: layered behavior exact -> near -> semantic", () => {
184
- const s = makeStore({ L0_ENABLED: true, L1_ENABLED: true, L2_ENABLED: true });
185
- // First checkpoint establishes baseline.
186
- const original = "implement user authentication with session tokens and secure cookies";
187
- const r1 = compactFull(s, SESS, [makeMsg("user", original)]);
188
- assert.equal(r1.deduped, false);
189
- // Exact duplicate -> L0.
190
- const r2 = compactFull(s, SESS, [makeMsg("user", original)]);
191
- assert.equal(r2.deduped, true);
192
- okReason(r2.dedupReason, ["regionHash", "contentHash", "summaryHash"]);
193
- // One-word edit -> L1 (if not caught by L0 first).
194
- const near = "implement user authentication with session token and secure cookies";
195
- const r3 = compactFull(s, SESS, [makeMsg("user", near)]);
196
- if (r3.deduped) {
197
- okReason(r3.dedupReason, ["l1MinHash", "contentSimilarity"]);
198
- }
199
- // Semantic paraphrase -> L2 (if distinct from above).
200
- const para = "build login validation and session cookie security for users";
201
- const r4 = compactFull(s, SESS, [makeMsg("user", para)]);
202
- if (r4.deduped) {
203
- okReason(r4.dedupReason, ["contentSimilarity", "l1MinHash"]);
204
- }
205
- assert.ok(vectorList(s, SESS).length >= 1, "layered dedup keeps at least one checkpoint");
206
- assert.ok(vectorList(s, SESS).length <= 4, "layered dedup should not explode to many checkpoints");
207
- });
208
- });
209
- function okReason(reason, expected) {
210
- assert.ok(reason !== undefined && expected.includes(reason), `expected dedupReason one of ${expected.join(", ")}, got ${reason}`);
211
- }
212
- // -------------------- 3. Compaction Ratios --------------------
213
- describe("Compaction Ratios", () => {
214
- const SESS = "sess_ratios";
215
- for (const n of [10, 50, 100, 200, 400]) {
216
- it(`${n} messages: extractive summary is smaller than input; strictly smaller when > 50`, () => {
217
- const s = makeStore();
218
- const messages = buildConversation(n, `feature work item ${n}`);
219
- const inputTokens = estimateSessionTokens(messages);
220
- const ext = extractiveSummarize(messages);
221
- const outputTokens = ext.tokenEstimate;
222
- console.log(`[ratio] ${n} messages: input=${inputTokens} output=${outputTokens} ratio=${inputTokens ? (outputTokens / inputTokens).toFixed(3) : "n/a"}`);
223
- assert.ok(outputTokens <= inputTokens || inputTokens === 0, "output should not exceed input");
224
- if (n > 50) {
225
- assert.ok(outputTokens < inputTokens, `expected output smaller than input for ${n} messages`);
226
- }
227
- // Also run through compactSession and verify a checkpoint exists.
228
- const r = compactSession({ sessionId: SESS, messages, keepFrom: messages.length, useExtractiveSummary: true }, s);
229
- assert.equal(r.skipped, false);
230
- assert.ok(r.checkpointId);
231
- assert.ok(r.tokenEstimate <= inputTokens);
232
- });
233
- }
234
- });
235
- // -------------------- 4. Compression / Store Stats --------------------
236
- describe("Compression / Store Stats", () => {
237
- const SESS = "sess_stats";
238
- it("stats reflect checkpoints, tokens, injection and dedup hit rate", () => {
239
- const s = makeStore();
240
- // Mixed duplicate and unique stores.
241
- const unique = "unique topic about payment gateway integration";
242
- compactFull(s, SESS, [makeMsg("user", unique)], 1);
243
- const dup = "duplicate topic about payment gateway integration";
244
- compactFull(s, SESS, [makeMsg("user", dup)], 1);
245
- const statsBefore = vectorStats(s, SESS);
246
- assert.ok(statsBefore.checkpointCount >= 1, "checkpointCount should be positive");
247
- assert.ok(statsBefore.totalTokenEstimate >= 0, "totalTokenEstimate should be non-negative");
248
- assert.equal(statsBefore.dedupHitRate, 0, "no injections yet => dedupHitRate 0");
249
- assert.equal(statsBefore.injectedCount, 0, "no injections yet => injectedCount 0");
250
- const hits = vectorSearch(s, SESS, "payment gateway", 5);
251
- assert.ok(hits.length > 0, "should find the stored checkpoint");
252
- const cpId = hits[0].checkpoint.checkpointId;
253
- vectorMarkInjected(s, SESS, cpId);
254
- const statsAfter = vectorStats(s, SESS);
255
- assert.equal(statsAfter.injectedCount, 1, "injectedCount tracks markInjected");
256
- if (statsAfter.checkpointCount > 0) {
257
- assert.ok(Math.abs(statsAfter.dedupHitRate - 1 / statsAfter.checkpointCount) < 0.001, "dedupHitRate = injected / checkpoints");
258
- }
259
- assert.ok(statsAfter.totalTokenEstimate > 0, "totalTokenEstimate positive after inserts");
260
- });
261
- it("dedupHitRate increases with duplicate content", () => {
262
- const s = makeStore();
263
- const base = "repeated region for hit-rate measurement";
264
- // Insert several duplicates; only first survives.
265
- for (let i = 0; i < 5; i++) {
266
- compactFull(s, SESS, [makeMsg("user", base)], 1);
267
- }
268
- compactFull(s, SESS, [makeMsg("user", "unique region for hit-rate measurement variant")], 1);
269
- // Mark the first as injected.
270
- const first = vectorSearch(s, SESS, base, 1)[0]?.checkpoint.checkpointId;
271
- if (first)
272
- vectorMarkInjected(s, SESS, first);
273
- const stats = vectorStats(s, SESS);
274
- assert.ok(stats.checkpointCount >= 1);
275
- assert.ok(stats.dedupHitRate > 0 || stats.checkpointCount === 1, "hit rate should be positive when there are multiple checkpoint");
276
- });
277
- });
278
- // -------------------- 5. Recall & Dedup Sentinel --------------------
279
- describe("Recall & Dedup Sentinel", () => {
280
- const SESS = "sess_recall";
281
- it("recallAndInline returns toInject on first call and empty on second due to skipInjected", () => {
282
- const s = makeStore();
283
- const region = "detailed work on the vector store dedup sentinel and recall pipeline";
284
- compactFull(s, SESS, [makeMsg("user", region)]);
285
- assert.ok(recallAndInline, "recallAndInline should be exported from recall.js for this test");
286
- const r1 = recallAndInline({
287
- sessionId: SESS,
288
- query: "dedup sentinel recall",
289
- limit: 3,
290
- source: "command",
291
- skipInjected: true,
292
- }, s);
293
- assert.ok(r1.toInject.length > 0, "first recall should return hits to inject");
294
- const r2 = recallAndInline({
295
- sessionId: SESS,
296
- query: "dedup sentinel recall",
297
- limit: 3,
298
- source: "command",
299
- skipInjected: true,
300
- }, s);
301
- assert.ok(r2.empty, "second recall should be empty because sentinel marked injected");
302
- });
303
- it("manual markInjected creates skip behavior when recallAndInline is unavailable", () => {
304
- const s = makeStore();
305
- const region = "manual sentinel tracking without recallAndInline";
306
- compactFull(s, SESS, [makeMsg("user", region)]);
307
- const hits = vectorSearch(s, SESS, "manual sentinel", 3);
308
- assert.ok(hits.length > 0, "search should return checkpoint");
309
- const cpId = hits[0].checkpoint.checkpointId;
310
- assert.equal(vectorWasInjected(s, SESS, cpId), false, "not yet injected");
311
- vectorMarkInjected(s, SESS, cpId);
312
- assert.equal(vectorWasInjected(s, SESS, cpId), true, "markInjected recorded");
313
- const hits2 = vectorSearch(s, SESS, "manual sentinel", 3).filter((h) => !vectorWasInjected(s, SESS, h.checkpoint.checkpointId));
314
- assert.equal(hits2.length, 0, "filtered search excludes injected checkpoint");
315
- });
316
- });
317
- // -------------------- 6. Edge Cases --------------------
318
- describe("Edge Cases", () => {
319
- const SESS = "sess_edge";
320
- it("empty message list returns skipped", () => {
321
- const s = makeStore();
322
- const r = compactSession({ sessionId: SESS, messages: [], keepFrom: 0 }, s);
323
- assert.equal(r.skipped, true);
324
- assert.equal(r.summary, "");
325
- assert.equal(vectorList(s, SESS).length, 0);
326
- });
327
- it("single message with keepFrom=0 returns skipped", () => {
328
- const s = makeStore();
329
- const r = compactSession({ sessionId: SESS, messages: [makeMsg("user", "only one message")], keepFrom: 0 }, s);
330
- assert.equal(r.skipped, true);
331
- assert.equal(vectorList(s, SESS).length, 0);
332
- });
333
- it("keepFrom at messages.length compacts all prior messages (verified behavior)", () => {
334
- // The engine treats keepFrom as the compactable boundary: messages[0..keepFrom)
335
- // are compacted. When keepFrom equals messages.length the entire conversation is
336
- // compactable, so it is NOT skipped. This test documents that behavior.
337
- const s = makeStore();
338
- const messages = buildConversation(6);
339
- const r = compactSession({ sessionId: SESS, messages, keepFrom: messages.length }, s);
340
- assert.equal(r.skipped, false);
341
- assert.ok(r.checkpointId);
342
- assert.equal(vectorList(s, SESS).length, 1);
343
- });
344
- it("unicode and emoji messages store and retrieve intact", () => {
345
- const s = makeStore();
346
- const text = "用户请求:创建 🎉 庆祝页面,包含 café 菜单 — déjà vu! " +
347
- "日本語テキスト 日本語テキスト 👍🔥";
348
- const r = compactFull(s, SESS, [makeMsg("user", text)], 1);
349
- assert.equal(r.skipped, false);
350
- const stored = vectorList(s, SESS)[0];
351
- assert.ok(stored);
352
- const recovered = Buffer.from(stored.compressedOriginal ?? Buffer.alloc(0));
353
- assert.ok(recovered.toString("utf-8").includes("🎉"), "emoji recovered from compressedOriginal");
354
- assert.ok(stored.summary.includes("café") || stored.summary.includes("cafe"));
355
- });
356
- it("very large single message (>10k chars) compacts and stores successfully", () => {
357
- const s = makeStore();
358
- const big = "bigint ".repeat(2000);
359
- assert.ok(big.length > 10_000, `message length ${big.length}`);
360
- const r = compactFull(s, SESS, [makeMsg("user", big)], 1);
361
- assert.equal(r.skipped, false);
362
- assert.ok(r.checkpointId);
363
- assert.equal(vectorList(s, SESS).length, 1);
364
- const stats = vectorStats(s, SESS);
365
- assert.ok(stats.totalTokenEstimate > 0);
366
- });
367
- it("mixed roles (user/assistant/tool) are included in summary", () => {
368
- const s = makeStore();
369
- const messages = [
370
- { role: "user", text: "fix the bug" },
371
- { role: "assistant", text: "will do", toolName: "Read", input: "src/bug.ts" },
372
- { role: "tool", text: "", toolName: "Read", output: "function foo() {}" },
373
- { role: "assistant", text: "fixed it", toolName: "Edit" },
374
- ];
375
- const r = compactFull(s, SESS, messages, messages.length);
376
- assert.equal(r.skipped, false);
377
- assert.ok(r.summary.length > 0);
378
- assert.ok(r.summary.includes("tool") ||
379
- r.summary.includes("Read") ||
380
- r.summary.includes("Edit") ||
381
- r.summary.includes("user") ||
382
- r.summary.includes("assistant"), "summary should reference roles or tools");
383
- assert.equal(vectorList(s, SESS).length, 1);
384
- });
385
- });
386
- // -------------------- 7. Tier Switching (percentage-based) --------------------
387
- // Replaces the previous LOCAL replica of COMPACT_TIERS + resolveThresholdFromEnv
388
- // that asserted the OLD static token amounts. We now import the REAL config
389
- // helpers from extensions/mega-config.js so the tests track the live source of
390
- // truth: thresholds are tierPct × the model's context window (not fixed tokens).
391
- describe("Tier Switching — percentage-based thresholds", () => {
392
- // Documented tierPct fractions (single source of truth in mega-config.ts).
393
- it("each named tier carries the documented tierPct fraction", () => {
394
- assert.equal(TIER_PCT.low, 0.5);
395
- assert.equal(TIER_PCT.medium, 0.6);
396
- assert.equal(TIER_PCT.high, 0.7);
397
- assert.equal(TIER_PCT.ultra, 0.7);
398
- assert.equal(TIER_PCT.mega, 0.75);
399
- });
400
- // Boot fallback threshold (sane gate before the first context event supplies a
401
- // window): round(tierPct × 200_000). Resolved through the REAL loadConfig().
402
- it("MEGACOMPACT_TIER env resolves to the boot fallback threshold via real config", () => {
403
- const tiers = [
404
- ["low", 100_000], // 0.50 × 200_000
405
- ["medium", 120_000], // 0.60 × 200_000
406
- ["high", 140_000], // 0.70 × 200_000
407
- ["ultra", 140_000], // 0.70 × 200_000
408
- ["mega", 150_000], // 0.75 × 200_000
409
- ];
410
- for (const [tier, expectedBoot] of tiers) {
411
- const original = process.env.MEGACOMPACT_TIER;
412
- delete process.env.MEGACOMPACT_THRESHOLD_TOKENS;
413
- process.env.MEGACOMPACT_TIER = tier;
414
- try {
415
- const cfg = loadConfig();
416
- assert.equal(cfg.tier, tier, `tier ${tier} should resolve`);
417
- assert.equal(cfg.tierPct, TIER_PCT[tier], `tier ${tier} tierPct`);
418
- assert.equal(cfg.thresholdTokens, expectedBoot, `tier ${tier} boot fallback threshold should be ${expectedBoot}`);
419
- }
420
- finally {
421
- if (original === undefined)
422
- delete process.env.MEGACOMPACT_TIER;
423
- else
424
- process.env.MEGACOMPACT_TIER = original;
425
- }
426
- }
427
- });
428
- it("explicit MEGACOMPACT_THRESHOLD_TOKENS overrides tier (custom stays absolute)", () => {
429
- const originalTier = process.env.MEGACOMPACT_TIER;
430
- const originalThreshold = process.env.MEGACOMPACT_THRESHOLD_TOKENS;
431
- delete process.env.MEGACOMPACT_TIER;
432
- process.env.MEGACOMPACT_THRESHOLD_TOKENS = "123456";
433
- try {
434
- const cfg = loadConfig();
435
- assert.equal(cfg.tier, "custom", "explicit token threshold → custom tier");
436
- assert.equal(cfg.tierPct, null, "custom tier has no tierPct (stays absolute)");
437
- assert.equal(cfg.thresholdTokens, 123_456, "explicit token threshold should win");
438
- }
439
- finally {
440
- if (originalTier === undefined)
441
- delete process.env.MEGACOMPACT_TIER;
442
- else
443
- process.env.MEGACOMPACT_TIER = originalTier;
444
- if (originalThreshold === undefined)
445
- delete process.env.MEGACOMPACT_THRESHOLD_TOKENS;
446
- else
447
- process.env.MEGACOMPACT_THRESHOLD_TOKENS = originalThreshold;
448
- }
449
- });
450
- });
451
- describe("effectiveThresholdTokens — tierPct × model window", () => {
452
- // The real compaction fire point. Tiered → scales with the window so it always
453
- // fires BELOW pi's native ~80% auto-compact for any model size. Custom (null
454
- // tierPct) → absolute explicitThreshold, never percent-scaled.
455
- it("scales tierPct × window for a 200k model", () => {
456
- assert.equal(effectiveThresholdTokens({ tierPct: TIER_PCT.low, fallbackThreshold: 100_000, window: 200_000 }), 100_000);
457
- assert.equal(effectiveThresholdTokens({ tierPct: TIER_PCT.mega, fallbackThreshold: 150_000, window: 200_000 }), 150_000);
458
- });
459
- it("scales tierPct × window for a 1M model", () => {
460
- assert.equal(effectiveThresholdTokens({ tierPct: TIER_PCT.low, fallbackThreshold: 500_000, window: 1_000_000 }), 500_000);
461
- assert.equal(effectiveThresholdTokens({ tierPct: TIER_PCT.mega, fallbackThreshold: 750_000, window: 1_000_000 }), 750_000);
462
- });
463
- it("falls back to the boot threshold when the window is 0/unknown", () => {
464
- assert.equal(effectiveThresholdTokens({ tierPct: TIER_PCT.mega, fallbackThreshold: 150_000, window: 0 }), 150_000);
465
- assert.equal(effectiveThresholdTokens({ tierPct: TIER_PCT.low, fallbackThreshold: 100_000, window: -5 }), 100_000);
466
- });
467
- it("custom (tierPct null) stays an absolute threshold regardless of window", () => {
468
- assert.equal(effectiveThresholdTokens({ tierPct: null, fallbackThreshold: 100_000, window: 200_000, explicitThreshold: 123456 }), 123456, "explicit absolute wins (200k window)");
469
- assert.equal(effectiveThresholdTokens({ tierPct: null, fallbackThreshold: 100_000, window: 1_000_000, explicitThreshold: 123456 }), 123456, "explicit absolute wins (1M window)");
470
- assert.equal(effectiveThresholdTokens({ tierPct: null, fallbackThreshold: 100_000, window: 200_000 }), 100_000, "no explicit → boot fallback");
471
- });
472
- });
@@ -1,87 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { mkdtempSync, rmSync } from "node:fs";
4
- import { tmpdir } from "node:os";
5
- import { join } from "node:path";
6
- import { upsertRepoRegistry } from "./store/sqlite.js";
7
- import { detectCrossRepoDrift } from "./driftDetection.js";
8
- const NOW = Math.floor(Date.now() / 1000);
9
- const D = 86_400;
10
- test("driftDetection: empty registry returns ok report", () => {
11
- const dir = mkdtempSync(join(tmpdir(), "drift-empty-"));
12
- try {
13
- const report = detectCrossRepoDrift(dir);
14
- assert.equal(report.totals.ok, 0);
15
- assert.equal(report.totals.warn, 0);
16
- assert.equal(report.repos.length, 0);
17
- }
18
- finally {
19
- rmSync(dir, { recursive: true, force: true });
20
- }
21
- });
22
- test("driftDetection: flags stale repos older than 30 days", () => {
23
- const dir = mkdtempSync(join(tmpdir(), "drift-stale-"));
24
- try {
25
- upsertRepoRegistry({ repoRoot: "/r/old", displayName: "old", stateDir: "/r/old", checkpointCount: 1, tokensSaved: 0, compressedOriginalBytes: 0, lastSeen: NOW - 45 * D }, dir);
26
- const report = detectCrossRepoDrift(dir);
27
- assert.equal(report.repos.length, 1);
28
- assert.ok(report.repos[0].signals.some((s) => s.kind === "stale"), "stale signal present");
29
- assert.equal(report.repos[0].status, "ok", "stale alone is info, not warn");
30
- assert.equal(report.totals.stale, 1);
31
- }
32
- finally {
33
- rmSync(dir, { recursive: true, force: true });
34
- }
35
- });
36
- test("driftDetection: active repo with no compaction flagged as warn", () => {
37
- const dir = mkdtempSync(join(tmpdir(), "drift-lag-"));
38
- try {
39
- upsertRepoRegistry({ repoRoot: "/r/active", displayName: "active", stateDir: "/r/active", checkpointCount: 1, tokensSaved: 0, compressedOriginalBytes: 0, lastSeen: NOW - 1 * D }, dir);
40
- const report = detectCrossRepoDrift(dir);
41
- const r = report.repos[0];
42
- assert.ok(r.signals.some((s) => s.kind === "compaction_lag"), "lag signal present");
43
- assert.equal(r.status, "warn", "compaction lag is warn-level");
44
- assert.equal(report.totals.warn, 1);
45
- }
46
- finally {
47
- rmSync(dir, { recursive: true, force: true });
48
- }
49
- });
50
- test("driftDetection: active repo with recent compaction is ok", () => {
51
- const dir = mkdtempSync(join(tmpdir(), "drift-ok-"));
52
- try {
53
- upsertRepoRegistry({ repoRoot: "/r/healthy", displayName: "healthy", stateDir: "/r/healthy", checkpointCount: 1, tokensSaved: 0, compressedOriginalBytes: 0, lastSeen: NOW, lastCompactedAt: NOW }, dir);
54
- const report = detectCrossRepoDrift(dir);
55
- const r = report.repos[0];
56
- assert.equal(r.status, "ok");
57
- assert.equal(r.signals.length, 0);
58
- }
59
- finally {
60
- rmSync(dir, { recursive: true, force: true });
61
- }
62
- });
63
- test("driftDetection: recent model churn flagged as info", () => {
64
- const dir = mkdtempSync(join(tmpdir(), "drift-model-"));
65
- try {
66
- upsertRepoRegistry({
67
- repoRoot: "/r/swap",
68
- displayName: "swap",
69
- stateDir: "/r/swap",
70
- checkpointCount: 1,
71
- tokensSaved: 0,
72
- compressedOriginalBytes: 0,
73
- lastSeen: NOW,
74
- lastCompactedAt: NOW,
75
- provider: "anthropic",
76
- providerName: "Anthropic",
77
- modelName: "sonnet-4.6",
78
- modelCapturedAt: NOW - 1 * D,
79
- }, dir);
80
- const report = detectCrossRepoDrift(dir);
81
- assert.ok(report.repos[0].signals.some((s) => s.kind === "model_churn"), "model churn detected");
82
- assert.equal(report.totals.modelChurn, 1);
83
- }
84
- finally {
85
- rmSync(dir, { recursive: true, force: true });
86
- }
87
- });