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,176 +0,0 @@
1
- /**
2
- * mega-teamrun.test.ts — regression test for the "auto-compact runs but context
3
- * never relieves during a team run (sub-agents)" bug.
4
- *
5
- * Loads the REAL compiled extension (extensions/mega-compact.js) through a
6
- * faithful mock pi (mirrors mega-compact.test.ts's harness) and drives the
7
- * exact event sequence a long team run produces:
8
- *
9
- * agent_start -> context (over threshold) xN -> agent_end (repeat x3)
10
- *
11
- * Asserts the TWO fixes:
12
- * 1. live trim FIRES per-call (computeLiveTrimCut no longer returns null on
13
- * the anchor floor — was `cutNull`, liveTrimFires===0 before the fix).
14
- * 2. the DURABLE trim fires at agent_end while idle + over threshold
15
- * (mid-run durable trigger), not only at parent settle.
16
- *
17
- * The mock ctx.compact() drives session_before_compact so we observe the
18
- * durable truncation. Counters come from MegaRuntime.diag* (set behind the
19
- * real handler code, inert in production).
20
- *
21
- * MEGACOMPACT_PGLITE_DISABLED keeps the run fast (no WASM index init).
22
- */
23
-
24
- import { test } from "node:test";
25
- import assert from "node:assert/strict";
26
- import { mkdtempSync, rmSync } from "node:fs";
27
- import { tmpdir } from "node:os";
28
- import { join } from "node:path";
29
- import { createRequire } from "node:module";
30
- import { closeVectorIndex } from "../src/store/vectorIndex.js";
31
- import type { AgentMessage } from "@earendil-works/pi-agent-core";
32
-
33
- const require = createRequire(import.meta.url);
34
- const baseTmp = mkdtempSync(join(tmpdir(), "mc-team-"));
35
- process.env.MEGACOMPACT_INDEX_DIR = join(baseTmp, "index");
36
- process.env.MEGACOMPACT_PGLITE_DISABLED = "true"; // fast: skip WASM index
37
- let counter = 0;
38
-
39
- function harness() {
40
- const stateDir = join(baseTmp, `run-${counter++}`);
41
- process.env.MEGACOMPACT_STATE_DIR = stateDir;
42
- process.env.MEGACOMPACT_DEBUG = "true";
43
- process.env.MEGACOMPACT_THRESHOLD_TOKENS = "50";
44
- process.env.MEGACOMPACT_FAST_GATE_PCT = "1";
45
- // Strict race-guard mode double-counts diagAgentEndDurable (sync++ at branch
46
- // entry + deferred++ in the setTimeout(500) callback = 6, not 3), lands
47
- // compactCalls after the synchronous assertions, and leaks timers that hang
48
- // `node --test`. The strict deferred path is covered by the two S38.5 tests
49
- // in mega-compact.test.ts. Use the synchronous v0.7.4 path here.
50
- process.env.MEGACOMPACT_RACE_GUARD_STRICT = "false";
51
- process.env.MEGACOMPACT_ANCHOR_USER_MESSAGES = "1";
52
- process.env.MEGACOMPACT_DURABLE_TRIM_FLOOR = "0"; // piCompactWouldNoop must not skip
53
- process.env.MEGACOMPACT_MEMORY_AUTO_REVIEW = "false";
54
- process.env.MEGACOMPACT_RAPTOR_ENABLED = "false";
55
- delete process.env.MEGACOMPACT_LEGACY_DURABLE_TRIM;
56
-
57
- const handlers: Record<string, Function> = {};
58
- const compactCalls: any[] = [];
59
-
60
- function msg(role: string, text: string, toolName?: string): AgentMessage {
61
- if (role === "assistant" && toolName) {
62
- return { role: "assistant", content: [{ type: "toolCall", name: toolName, id: "c1", arguments: {} }], api: "anthropic-messages", provider: "anthropic", model: "m", usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 }, stopReason: "tool_use", timestamp: 0 } as unknown as AgentMessage;
63
- }
64
- if (role === "toolResult" && toolName) {
65
- return { role: "toolResult", content: [{ type: "text", text }], toolCallId: "c1", toolName, isError: false, timestamp: 0 } as unknown as AgentMessage;
66
- }
67
- return { role: "user", content: text, timestamp: 0 } as unknown as AgentMessage;
68
- }
69
-
70
- const session: AgentMessage[] = [];
71
- for (let i = 0; i < 14; i++) {
72
- session.push(msg("user", `actually we decided to use approach ${i} for module ${i}`));
73
- session.push(msg("assistant", `edited module ${i}`, "Edit"));
74
- session.push(msg("toolResult", `edited module ${i}`, "Edit"));
75
- }
76
-
77
- const toEntry = (m: AgentMessage, i: number): any => ({ type: "message", id: `e${i}`, parentId: null, timestamp: String(i), message: m });
78
- const sessionManager = {
79
- getSessionId: () => "sess_team_001",
80
- getEntries: () => session.map(toEntry),
81
- getBranch: () => session.map(toEntry),
82
- };
83
-
84
- function makeCtx(over: Partial<any> = {}) {
85
- return {
86
- ui: { setStatus: () => {}, notify: () => {}, select: () => {}, confirm: async () => true, input: async () => "", setWidget: () => {} },
87
- mode: "tui" as any, hasUI: true, cwd: stateDir, sessionManager,
88
- modelRegistry: {} as any, model: undefined, isIdle: () => true, isProjectTrusted: () => true,
89
- signal: undefined, abort: () => {}, hasPendingMessages: () => false, shutdown: () => {},
90
- getContextUsage: () => ({ tokens: 200000, contextWindow: 200000, percent: 100 }),
91
- // Mock ctx.compact() runs pi's flow and fires session_before_compact.
92
- compact: (opts?: any) => {
93
- compactCalls.push(opts);
94
- if (handlers["session_before_compact"]) {
95
- return handlers["session_before_compact"](
96
- { type: "session_before_compact", reason: "threshold", willRetry: false, signal: undefined, preparation: { firstKeptEntryId: "e2", messagesToSummarize: session.slice(0, 2), tokensBefore: 500 } } as any,
97
- makeCtx(),
98
- );
99
- }
100
- return undefined;
101
- },
102
- getSystemPrompt: () => "system base",
103
- ...over,
104
- } as any;
105
- }
106
-
107
- const pi = {
108
- on: (ev: string, h: Function) => { handlers[ev] = h; },
109
- registerCommand: () => {}, registerTool: () => {}, registerShortcut: () => {},
110
- registerFlag: () => {}, getFlag: () => undefined, registerMessageRenderer: () => {},
111
- registerEntryRenderer: () => {}, sendMessage: () => {}, sendUserMessage: () => {},
112
- appendEntry: () => {}, setSessionName: () => {}, getSessionName: () => undefined,
113
- setLabel: () => {}, exec: async () => ({ stdout: "", stderr: "", code: 0 }),
114
- getActiveTools: () => [], getAllTools: () => [], setActiveTools: () => {},
115
- getCommands: () => [], setModel: async () => false, getThinkingLevel: () => "off" as any,
116
- setThinkingLevel: () => {},
117
- } as any;
118
-
119
- const mod = require("./mega-compact.js") as { default: (p: any) => void };
120
- mod.default(pi);
121
- const { lastRuntime } = require("./mega-events.js") as { lastRuntime: any };
122
-
123
- const fire = (ev: string, event: any, ctx: any) => handlers[ev](event, ctx);
124
- return {
125
- stateDir, handlers, compactCalls, fire, ctx: makeCtx, session,
126
- runtime: lastRuntime, // MegaRuntime with diag* counters
127
- // Advance the debounce so agent_end (same instant) can trigger durable trim.
128
- clearDebounce: () => { if (lastRuntime) lastRuntime.debounceUntil = 0; },
129
- };
130
- }
131
-
132
- test("team run: live trim fires AND durable trim fires per sub-agent (relieves context)", async () => {
133
- const h = harness();
134
- const ctx = h.ctx();
135
- for (let a = 0; a < 3; a++) {
136
- await h.fire("agent_start", { type: "agent_start", messages: [] }, ctx);
137
- for (let i = 0; i < 4; i++) {
138
- await h.fire("context", { type: "context", messages: h.session }, ctx);
139
- }
140
- // Real team runs settle seconds after the last context event; mimic that
141
- // so the 2s debounce has elapsed and the durable trigger can fire.
142
- await new Promise((r) => setTimeout(r, 2100));
143
- h.clearDebounce();
144
- await h.fire("agent_end", { type: "agent_end", messages: [] }, ctx);
145
- }
146
- const rt = h.runtime;
147
- // FIX 1: live trim must actually fire (was 0 — computeLiveTrimCut returned null).
148
- assert.ok(rt.diagLiveTrimFires > 0, "live trim fires during the team run (anchor-floor fix)");
149
- assert.equal(rt.diagCtxCutNull, 0, "no live-trim cut skipped on anchor floor");
150
- // FIX 2: durable trim must fire at each agent_end (was 0 — only at parent settle).
151
- assert.equal(rt.diagAgentEndDurable, 3, "mid-run durable trigger fired at each agent_end");
152
- assert.equal(rt.diagBeforeCompactSupplied, 3, "our durable trim supplied 3x (context relieved)");
153
- assert.ok(h.compactCalls.length >= 3, "ctx.compact() invoked for durable trim between sub-agents");
154
- });
155
-
156
- test("control: session_before_compact supplies a durable compaction (parent settles)", async () => {
157
- const h = harness();
158
- const res = await h.fire(
159
- "session_before_compact",
160
- { type: "session_before_compact", reason: "threshold", willRetry: false, signal: undefined, preparation: { firstKeptEntryId: "e2", messagesToSummarize: h.session.slice(0, 4), tokensBefore: 500 } } as any,
161
- h.ctx(),
162
- );
163
- assert.ok(res?.compaction, "compaction result returned to pi");
164
- assert.equal(res.compaction.firstKeptEntryId, "e2", "reuses pi's boundary (PREVENT-PI-002)");
165
- });
166
-
167
- test("cleanup", async () => {
168
- // Race closeVectorIndex with a timeout to prevent 40-min hangs.
169
- try {
170
- await Promise.race([
171
- closeVectorIndex(),
172
- new Promise((r) => setTimeout(r, 3000)),
173
- ]);
174
- } catch { /* ignore */ }
175
- rmSync(baseTmp, { recursive: true, force: true });
176
- });
@@ -1,64 +0,0 @@
1
- /**
2
- * mega-trim.test.ts — tests for the live compaction view builder (S16).
3
- */
4
- import { test } from "node:test";
5
- import assert from "node:assert/strict";
6
- import { buildLiveTrimmedView } from "./mega-trim.js";
7
- import type { EngineMessage } from "../src/types.js";
8
-
9
- function m(role: EngineMessage["role"], text: string, extra: Partial<EngineMessage> = {}): EngineMessage {
10
- return { role, text, toolName: undefined, input: undefined, output: undefined, ...extra };
11
- }
12
-
13
- test("buildLiveTrimmedView: prepends a compacted summary and keeps the recent anchor", () => {
14
- const view: EngineMessage[] = [
15
- m("user", "old request one"), m("assistant", "old answer one"),
16
- m("user", "old request two"), m("assistant", "old answer two"),
17
- m("user", "recent keep me"), m("assistant", "recent keep me too"),
18
- ];
19
- // Compacted region = first 4; recent anchor = last 2.
20
- const result = buildLiveTrimmedView(view, {
21
- compactedFrom: 4, // index where the compacted region ends
22
- summary: "<summary>earlier work on old requests</summary>",
23
- anchorUserMessages: 1,
24
- });
25
- // First element is the injected compacted summary as a user-role message.
26
- assert.equal(result[0].role, "user");
27
- assert.ok(String(result[0].text).includes("earlier work on old requests"));
28
- // Recent anchor preserved in order, no older messages leak through.
29
- assert.equal(result.length, 1 + 2, "summary + 2 recent");
30
- assert.ok(result.slice(1).some((x) => String(x.text).includes("recent keep me")));
31
- });
32
-
33
- test("buildLiveTrimmedView: empty summary returns the original view unchanged", () => {
34
- const view = [m("user", "x"), m("assistant", "y")];
35
- const result = buildLiveTrimmedView(view, { compactedFrom: 0, summary: "", anchorUserMessages: 1 });
36
- assert.deepEqual(result, view);
37
- });
38
-
39
- test("buildLiveTrimmedView: never splits a toolCall/toolResult pair (PREVENT-PI-002)", () => {
40
- const view: EngineMessage[] = [
41
- m("user", "q"), m("assistant", "calls tool", { toolName: "read" }), m("tool", "result"),
42
- m("user", "keep"), m("assistant", "ok"),
43
- ];
44
- // cut=3 would start the preserved run on the orphaned tool result at index 2 —
45
- // the builder must snap back so the toolCall/toolResult pair is not split.
46
- const result = buildLiveTrimmedView(view, { compactedFrom: 3, summary: "<summary>s</summary>", anchorUserMessages: 1 });
47
- // The tool result must never appear preserved WITHOUT its preceding toolCall.
48
- const preserved = result.slice(1);
49
- const hasToolResult = preserved.some((x) => x.role === "tool");
50
- const hasToolCall = preserved.some((x) => x.role === "assistant" && x.toolName);
51
- // Either the tool pair is kept together, or the tool result is dropped into
52
- // the compacted region — it is never left orphaned.
53
- assert.ok(!(hasToolResult && !hasToolCall), "no orphaned tool result in the preserved run");
54
- });
55
-
56
- test("buildLiveTrimmedView: honors the anchor floor (PREVENT-PI-001)", () => {
57
- // cut would leave zero user messages in the anchor — must skip the trim.
58
- const view: EngineMessage[] = [
59
- m("user", "old q"), m("assistant", "old a"),
60
- m("assistant", "only assistant kept"),
61
- ];
62
- const result = buildLiveTrimmedView(view, { compactedFrom: 2, summary: "<summary>s</summary>", anchorUserMessages: 1 });
63
- assert.deepEqual(result, view, "below anchor floor → no trim this call");
64
- });
@@ -1,108 +0,0 @@
1
- /**
2
- * mega-turn-store.test.ts — S49C adapter routing tests.
3
- *
4
- * Proves the adapter writes to the isolated turns.db when turnsDbEnabled is
5
- * true and to the legacy main-db helpers when false. No network; temp dirs.
6
- */
7
-
8
- import { test, beforeEach, afterEach } from "node:test";
9
- import assert from "node:assert/strict";
10
- import { mkdtempSync, rmSync, existsSync } from "node:fs";
11
- import { tmpdir } from "node:os";
12
- import { join } from "node:path";
13
- import { DatabaseSync } from "node:sqlite";
14
- import {
15
- ensureConversationIdFor,
16
- recordTurnWrite,
17
- recordRecallWrite,
18
- } from "./mega-turn-store.js";
19
- import { closeTurnStore, turnDbPath } from "../src/store/turns/index.js";
20
- import type { MegaConfig } from "./mega-config.js";
21
-
22
- let tmpDir: string;
23
- let counter = 0;
24
-
25
- beforeEach(() => {
26
- tmpDir = mkdtempSync(join(tmpdir(), "mc-adapter-"));
27
- });
28
-
29
- afterEach(() => {
30
- rmSync(tmpDir, { recursive: true, force: true });
31
- });
32
-
33
- function stateDir(): string {
34
- return join(tmpDir, `run-${counter++}`);
35
- }
36
-
37
- /** Minimal MegaConfig stub — only the flag the adapter reads. */
38
- function cfg(turnsDbEnabled: boolean): MegaConfig {
39
- return { turnsDbEnabled } as unknown as MegaConfig;
40
- }
41
-
42
- test("flag ON → writes land in turns.db (not main sqlite.db)", () => {
43
- const dir = stateDir();
44
- const c = cfg(true);
45
- const conv = ensureConversationIdFor(c, "sess_on", dir);
46
- const turnId = recordTurnWrite(
47
- c,
48
- {
49
- conversationId: conv,
50
- sessionId: "sess_on",
51
- turnIndex: 0,
52
- role: "assistant",
53
- endedAt: Date.now(),
54
- },
55
- dir,
56
- );
57
- recordRecallWrite(
58
- c,
59
- turnId,
60
- [{ checkpointId: "cp_on", score: 0.5, source: "flat" }],
61
- dir,
62
- );
63
- closeTurnStore(dir);
64
- assert.ok(existsSync(turnDbPath(dir)), "turns.db should exist");
65
- assert.ok(
66
- !existsSync(join(dir, "sqlite.db")),
67
- "main sqlite.db must NOT be created on the flag-ON path",
68
- );
69
- });
70
-
71
- test("flag OFF → writes land in main sqlite.db (legacy S48 path)", () => {
72
- const dir = stateDir();
73
- const c = cfg(false);
74
- const conv = ensureConversationIdFor(c, "sess_off", dir);
75
- const turnId = recordTurnWrite(
76
- c,
77
- {
78
- conversationId: conv,
79
- sessionId: "sess_off",
80
- turnIndex: 0,
81
- role: "assistant",
82
- endedAt: Date.now(),
83
- },
84
- dir,
85
- );
86
- recordRecallWrite(
87
- c,
88
- turnId,
89
- [{ checkpointId: "cp_off", score: 0.5, source: "flat" }],
90
- dir,
91
- );
92
- // Legacy helpers open the main sqlite.db.
93
- assert.ok(
94
- existsSync(join(dir, "sqlite.db")),
95
- "main sqlite.db should exist on the flag-OFF path",
96
- );
97
- assert.ok(
98
- !existsSync(turnDbPath(dir)),
99
- "turns.db must NOT be created on the flag-OFF path",
100
- );
101
- // And the row is actually in the main db's turns table.
102
- const main = new DatabaseSync(join(dir, "sqlite.db"));
103
- const rows = main
104
- .prepare("SELECT * FROM turns WHERE session_id = ?")
105
- .all("sess_off") as unknown[];
106
- assert.equal(rows.length, 1);
107
- main.close();
108
- });
@@ -1,187 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import type { EngineMessage } from "./types.js";
4
- import { computeDropRange, isBoundarySafe, dropBefore } from "./boundary.js";
5
-
6
- function user(t: string): EngineMessage { return { role: "user", text: t }; }
7
- function assistant(t: string): EngineMessage { return { role: "assistant", text: t }; }
8
- function toolUse(n: string, i = "{}"): EngineMessage { return { role: "assistant", text: "", toolName: n, input: i }; }
9
- function toolResult(n: string, o = "ok"): EngineMessage { return { role: "tool", text: "", toolName: n, output: o }; }
10
- function custom(t: string): EngineMessage { return { role: "custom", text: t }; }
11
-
12
- test("walks back so first preserved message is not an orphaned tool result", () => {
13
- const messages = [
14
- user("Search for files"),
15
- toolUse("search"),
16
- toolResult("search", "found 5 files"),
17
- assistant("Done."),
18
- ];
19
- // keepFrom=2 would start the preserved run on the tool result at index 2,
20
- // orphaning it. The guard walks back to include the assistant tool-call.
21
- const [start, end] = computeDropRange(messages, 2, 0);
22
- assert.equal(start, 0);
23
- assert.equal(end, 1);
24
- const kept = messages.slice(end);
25
- assert.notEqual(kept[0].role, "tool");
26
- assert.equal(kept[0].toolName, "search"); // assistant tool-call preserved
27
- });
28
-
29
- test("isBoundarySafe: cut that drops a toolCall but keeps its toolResult is unsafe (PREVENT-PI-002)", () => {
30
- const messages = [user("a"), toolUse("search"), toolResult("search")];
31
- // keepFrom=2 drops the toolUse at index 1 but keeps the toolResult at index 2 →
32
- // the preserved run starts on an orphaned tool result. This is the shape the old
33
- // check mis-validated (it only compared messages[keepFrom] to messages[keepFrom-1]).
34
- assert.equal(isBoundarySafe(messages, 2), false);
35
- // keepFrom=1 keeps the toolCall together with its toolResult → safe.
36
- assert.equal(isBoundarySafe(messages, 1), true);
37
- });
38
-
39
- test("isBoundarySafe: orphaned tool result without preceding tool use is unsafe", () => {
40
- const messages = [user("a"), toolResult("search", "orphan")];
41
- assert.equal(isBoundarySafe(messages, 1), false);
42
- });
43
-
44
- test("anchor floor preserves the last N user messages", () => {
45
- const messages = [
46
- user("u1"), user("u2"), user("u3"),
47
- assistant("a1"), assistant("a2"), assistant("a3"), assistant("a4"), assistant("a5"),
48
- ];
49
- // Caller wants to keep from index 2 (would drop u2). Anchor=2 forces keeping
50
- // from u2 (index 1) onward.
51
- const out = dropBefore(messages, 2, 2);
52
- assert.ok(out.some((m) => m.text === "u2"));
53
- assert.ok(out.some((m) => m.text === "u3"));
54
- });
55
-
56
- test("anchor floor is a no-op when fewer users than anchor", () => {
57
- const messages = [user("u1"), assistant("a1"), assistant("a2"), assistant("a3")];
58
- const out = dropBefore(messages, 1, 2);
59
- // only 1 user, anchor=2 → no floor; keep from index 1 (drop the user)
60
- assert.ok(!out.some((m) => m.text === "u1"));
61
- assert.equal(out.length, 3);
62
- });
63
-
64
- test("dropBefore returns original when range is empty", () => {
65
- const messages = [user("a"), assistant("b")];
66
- assert.equal(dropBefore(messages, 0, 1), messages);
67
- });
68
-
69
- // --- PREVENT-PI-002 regression cases for arbitrary interleavings ---
70
-
71
- test("interleaved custom message between toolCall and toolResult: walk-back keeps the call", () => {
72
- // [user, assistant(tc=read), custom/bashExecution, tool(read-result)] with
73
- // desired keepFrom=3. The old walk-back saw messages[2] was not a toolUse and
74
- // broke at k=2, dropping the assistant toolCall at index 1 while KEEPING its
75
- // tool result at index 3 → orphaned tool result → provider 400.
76
- const messages = [
77
- user("Search for files"),
78
- toolUse("read"),
79
- custom("bash: ls -la"),
80
- toolResult("read", "file contents"),
81
- assistant("Done."),
82
- ];
83
- const [start, end] = computeDropRange(messages, 3, 0);
84
- assert.equal(start, 0);
85
- assert.equal(end, 1); // keep the assistant toolCall at index 1 with its result
86
- const kept = messages.slice(end);
87
- assert.equal(kept[0].toolName, "read"); // assistant tool-call preserved
88
- assert.ok(kept.some((m) => m.role === "tool" && m.toolName === "read"));
89
- // The toolCall and its toolResult are both in the kept run.
90
- const callIdx = kept.findIndex((m) => m.role === "assistant" && m.toolName === "read");
91
- const resultIdx = kept.findIndex((m) => m.role === "tool" && m.toolName === "read");
92
- assert.ok(callIdx !== -1 && resultIdx !== -1 && callIdx < resultIdx);
93
- });
94
-
95
- test("consecutive tool results sharing one call: no-op when the call cannot be kept", () => {
96
- // [assistant(tc), T1, T2] with keepFrom=1: dropping the call orphans BOTH T1
97
- // and T2. No pair-safe positive cut exists below keepFrom → no-op compaction
98
- // (the [start,end) contract preserves a non-zero result only when one exists).
99
- const messages = [toolUse("multi"), toolResult("multi", "r1"), toolResult("multi", "r2")];
100
- const [start, end] = computeDropRange(messages, 1, 0);
101
- assert.equal(start, 0);
102
- assert.equal(end, 0); // no-op — pair rule outranks dropping
103
- assert.equal(dropBefore(messages, 1, 0), messages);
104
- });
105
-
106
- test("consecutive tool results sharing one call: safe cut keeps the call with both results", () => {
107
- // [user, assistant(tc), T1, T2, user2] — keepFrom=3 would orphan T2; the guard
108
- // walks back to keep the call (dropEnd=1, only the first user is dropped).
109
- const messages = [
110
- user("u1"),
111
- toolUse("multi"),
112
- toolResult("multi", "r1"),
113
- toolResult("multi", "r2"),
114
- user("u2"),
115
- ];
116
- const [start, end] = computeDropRange(messages, 3, 0);
117
- assert.equal(start, 0);
118
- assert.equal(end, 1); // keep [assistant(tc), T1, T2, user2]
119
- const kept = messages.slice(end);
120
- const callIdx = kept.findIndex((m) => m.role === "assistant" && m.toolName === "multi");
121
- const r1Idx = kept.findIndex((m) => m.role === "tool" && m.output === "r1");
122
- const r2Idx = kept.findIndex((m) => m.role === "tool" && m.output === "r2");
123
- assert.ok(callIdx < r1Idx && r1Idx < r2Idx);
124
- });
125
-
126
- test("consecutive shared-call results: dropping call + all results together is safe", () => {
127
- // keepFrom=4 preserves only the trailing user — the call and BOTH results are
128
- // dropped together, so nothing is orphaned.
129
- const messages = [
130
- user("u1"),
131
- toolUse("multi"),
132
- toolResult("multi", "r1"),
133
- toolResult("multi", "r2"),
134
- user("u2"),
135
- ];
136
- const [start, end] = computeDropRange(messages, 4, 0);
137
- assert.equal(start, 0);
138
- assert.equal(end, 4);
139
- assert.deepEqual(messages.slice(end), [user("u2")]);
140
- });
141
-
142
- test("keepFrom landing on a call whose results follow is safe", () => {
143
- // [user, assistant(tc1), T1, assistant(tc2), T2, user2] keepFrom=3 → preserved
144
- // run starts on assistant(tc2) at index 3, whose result T2 follows. Safe.
145
- const messages = [
146
- user("u1"),
147
- toolUse("read"),
148
- toolResult("read", "r1"),
149
- toolUse("write"),
150
- toolResult("write", "r2"),
151
- user("u2"),
152
- ];
153
- const [start, end] = computeDropRange(messages, 3, 0);
154
- assert.equal(start, 0);
155
- assert.equal(end, 3);
156
- const kept = messages.slice(end);
157
- assert.equal(kept[0].role, "assistant");
158
- assert.equal(kept[0].toolName, "write");
159
- assert.ok(kept.some((m) => m.role === "tool" && m.toolName === "write"));
160
- });
161
-
162
- test("anchor floor + pair-rule conflict: pair rule wins, drop less", () => {
163
- // [assistant(tc), user, T] with anchor=1: the anchor floor wants dropEnd<=1
164
- // (keep the user at index 1), but keeping from index 1 orphans T (its owner at
165
- // index 0 would be dropped). The pair rule outranks the floor — we drop LESS,
166
- // keeping everything (no-op) rather than cross a pair.
167
- const messages = [toolUse("read"), user("keep me"), toolResult("read", "r")];
168
- const out = dropBefore(messages, 2, 1);
169
- assert.equal(out, messages, "anchor floor would orphan the tool result → no-op");
170
- });
171
-
172
- test("isBoundarySafe: interleaved custom between call and result is detected unsafe", () => {
173
- const messages = [user("a"), toolUse("read"), custom("bash"), toolResult("read", "r")];
174
- // keepFrom=3 drops the call at index 1, keeps the result at index 3 → unsafe.
175
- assert.equal(isBoundarySafe(messages, 3), false);
176
- // keepFrom=2 ALSO drops the call at index 1 (drop [0,2) = [user, toolUse]) and
177
- // keeps the result at index 3 → still orphaned → unsafe.
178
- assert.equal(isBoundarySafe(messages, 2), false);
179
- // keepFrom=1 keeps the call (index 1) together with its result at index 3 → safe.
180
- assert.equal(isBoundarySafe(messages, 1), true);
181
- });
182
-
183
- test("isBoundarySafe: cut before any tool result is safe", () => {
184
- const messages = [user("a"), toolUse("read"), toolResult("read", "r"), assistant("done")];
185
- assert.equal(isBoundarySafe(messages, 0), true); // out of range → safe
186
- assert.equal(isBoundarySafe(messages, messages.length), true); // out of range → safe
187
- });
@@ -1,99 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import type { EngineMessage } from "./types.js";
4
- import {
5
- formatCompactSummary,
6
- summarizeMessages,
7
- mergeCompactSummaries,
8
- shouldCompact,
9
- autoCompactCheck,
10
- collectKeyFiles,
11
- inferPendingWork,
12
- extractFileCandidates,
13
- } from "./compact.js";
14
- import { estimateSessionTokens } from "./tokens.js";
15
-
16
- function user(text: string): EngineMessage { return { role: "user", text }; }
17
- function assistant(text: string): EngineMessage { return { role: "assistant", text }; }
18
- function toolUse(name: string, input: string): EngineMessage { return { role: "assistant", text: "", toolName: name, input }; }
19
- function toolResult(name: string, output: string): EngineMessage { return { role: "tool", text: "", toolName: name, output }; }
20
-
21
- test("formatCompactSummary strips analysis and formats summary block (claw-code parity)", () => {
22
- const summary = "<analysis>scratch</analysis>\n<summary>Kept work</summary>";
23
- assert.equal(formatCompactSummary(summary), "Summary:\nKept work");
24
- });
25
-
26
- test("leaves small sessions unchanged (shouldCompact false)", () => {
27
- const messages = [user("hello")];
28
- assert.equal(shouldCompact(messages, 1, 4), false);
29
- });
30
-
31
- test("compacts older messages into a summary with Scope + timeline", () => {
32
- const messages = [
33
- user("one ".repeat(200)),
34
- assistant("two ".repeat(200)),
35
- toolResult("bash", "ok ".repeat(200)),
36
- assistant("recent"),
37
- ];
38
- assert.equal(shouldCompact(messages, 1, 2), true);
39
- const summary = summarizeMessages(messages.slice(0, 2));
40
- const formatted = formatCompactSummary(summary);
41
- assert.ok(formatted.includes("Scope:"));
42
- assert.ok(formatted.includes("Key timeline:"));
43
- });
44
-
45
- test("merge keeps previous compacted context when compacting again", () => {
46
- const first = summarizeMessages([
47
- user("Investigate src/compact.ts"),
48
- assistant("I will inspect the compact flow."),
49
- ]);
50
- const second = summarizeMessages([
51
- user("Also update src/boundary.ts"),
52
- assistant("Next: preserve prior summary context."),
53
- ]);
54
- const merged = mergeCompactSummaries(first, second);
55
- assert.ok(merged.includes("Previously compacted context:"));
56
- assert.ok(merged.includes("Newly compacted context:"));
57
- assert.ok(merged.includes("src/boundary.ts"));
58
- });
59
-
60
- test("infers pending work from recent messages", () => {
61
- const pending = inferPendingWork([
62
- user("done"),
63
- assistant("Next: update tests and follow up on remaining CLI polish."),
64
- ]);
65
- assert.equal(pending.length, 1);
66
- assert.ok(pending[0].includes("Next: update tests"));
67
- });
68
-
69
- test("extracts key files from message content", () => {
70
- const files = collectKeyFiles([
71
- user("Update src/compact.ts and extensions/mega-compact.ts next."),
72
- ]);
73
- assert.ok(files.includes("src/compact.ts"));
74
- assert.ok(files.includes("extensions/mega-compact.ts"));
75
- });
76
-
77
- test("extractFileCandidates ignores plain words and non-interesting extensions", () => {
78
- const files = extractFileCandidates("look at foo/bar.png and src/x.ts and justaword");
79
- assert.deepEqual(files, ["src/x.ts"]);
80
- });
81
-
82
- test("summarizeMessages lists tool names sorted + deduped", () => {
83
- const summary = summarizeMessages([toolUse("search", "{}"), toolUse("bash", "{}"), toolResult("search", "ok")]);
84
- assert.ok(summary.includes("Tools mentioned: bash, search."));
85
- });
86
-
87
- test("autoCompactCheck reports utilization and threshold gate", () => {
88
- const under = autoCompactCheck(10000, 50000);
89
- assert.equal(under.shouldCompact, false);
90
- assert.equal(under.utilizationPct, 20);
91
- const over = autoCompactCheck(60000, 50000);
92
- assert.equal(over.shouldCompact, true);
93
- });
94
-
95
- test("token estimator counts text + tool payloads", () => {
96
- const total = estimateSessionTokens([user("abcd"), toolResult("bash", "abcd")]);
97
- // "abcd"/4+1 = 2 for user; tool: name "bash"/4+1=2 plus output "abcd"/4+1=2 => 4
98
- assert.equal(total, 2 + 4);
99
- });