pi-mega-compact 0.11.3 → 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 +3 -0
  14. package/dist/extensions/mega-events/agent-handlers.js +41 -6
  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 +118 -128
  19. package/dist/extensions/mega-events/mirror-append.js +107 -0
  20. package/dist/extensions/mega-events/outage-advisor.js +59 -0
  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 +6 -0
  25. package/dist/extensions/mega-runtime/runtime.js +7 -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 +18 -0
  98. package/extensions/mega-events/agent-handlers.ts +44 -5
  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 +156 -124
  103. package/extensions/mega-events/mirror-append.ts +155 -0
  104. package/extensions/mega-events/outage-advisor.ts +79 -0
  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 +14 -0
  109. package/extensions/mega-runtime/reset-runtime.ts +6 -0
  110. package/extensions/mega-runtime/runtime.ts +7 -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 -820
  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 -872
  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
@@ -13,6 +13,11 @@ import { loadMetrics, fpRate, p95, defaultMetricsPath } from "../src/monitoring.
13
13
  import { C, recentUserQuery } from "./mega-runtime.js";
14
14
  import { runCompact, doRecall, doRecallAsync } from "./mega-pipeline.js";
15
15
  import { vectorStats, vectorRepoStats, vectorDataInvariant } from "../src/vectorStore.js";
16
+ import { spawnSync } from "node:child_process"; // guardrails-allow PREVENT-PI-004: local subprocess detection only (no network)
17
+ import { mkdirSync, writeFileSync } from "node:fs";
18
+ import path from "node:path";
19
+ import os from "node:os";
20
+ import { createRequire } from "node:module";
16
21
  /** Resolve a checkpoint by id (or "recent"/"last") from this session's store. */
17
22
  export function findCheckpoint(runtime, sid, ref) {
18
23
  const all = listCheckpoints(sid, runtime.currentStateDir);
@@ -73,7 +78,7 @@ export function registerCommands(pi, runtime, config) {
73
78
  runtime.logger.info("recall", { query, crossRepo, injected: r.toInject.map((h) => h.checkpoint.checkpointId) });
74
79
  runtime.setStatus(ctx, `mega-compact: recalled ${r.toInject.length} chkpt${crossRepo ? " (cross-repo)" : ""}`);
75
80
  ctx.ui.notify(`[mega-compact] recall staged ${r.toInject.length} checkpoint(s) for "${query}"${crossRepo ? " (cross-repo)" : ""}:\n${list}\n` +
76
- `(injected at the next turn via system prompt)`);
81
+ `(injected at the tail of the next turn's context)`);
77
82
  }
78
83
  catch (e) {
79
84
  ctx.ui.notify(`[mega-compact] /mega-recall failed: ${String(e)}`);
@@ -255,6 +260,189 @@ export function registerCommands(pi, runtime, config) {
255
260
  `• data safety — every compressed region is kept verbatim; nothing is permanently deleted. /mega-restore brings any of it back.`);
256
261
  },
257
262
  });
263
+ pi.registerCommand("mega-setup", {
264
+ description: "Local embedding setup wizard — detect available embedders and configure mega-compact.",
265
+ handler: async (_args, ctx) => {
266
+ try {
267
+ const log = (msg) => ctx.ui.notify(msg);
268
+ // --- 1. Current config ---
269
+ const embeddingUrl = process.env["MEGACOMPACT_EMBEDDING_URL"];
270
+ const minilm = process.env["MEGACOMPACT_MINILM"];
271
+ let currentEmbedder = "TrigramEmbedder (heuristic, default)";
272
+ if (embeddingUrl)
273
+ currentEmbedder = `httpEmbedder → ${embeddingUrl}`;
274
+ else if (minilm)
275
+ currentEmbedder = "MiniLM (experimental)";
276
+ // --- 2. Detection ---
277
+ let ollamaDetected = false;
278
+ let ollamaModels = [];
279
+ let ollamaRunning = false;
280
+ let llamaDetected = false;
281
+ let onnxDetected = false;
282
+ try {
283
+ const ollamaVer = spawnSync("ollama", ["--version"], {
284
+ timeout: 5000,
285
+ encoding: "utf-8",
286
+ stdio: ["ignore", "pipe", "pipe"],
287
+ }); // guardrails-allow PREVENT-PI-004: local subprocess detection only
288
+ if (ollamaVer.status === 0) {
289
+ ollamaDetected = true;
290
+ try {
291
+ const listResult = spawnSync("ollama", ["list"], {
292
+ timeout: 5000,
293
+ encoding: "utf-8",
294
+ stdio: ["ignore", "pipe", "pipe"],
295
+ }); // guardrails-allow PREVENT-PI-004: local subprocess detection only
296
+ if (listResult.status === 0) {
297
+ ollamaRunning = true;
298
+ const lines = listResult.stdout?.split("\n") ?? [];
299
+ for (const line of lines) {
300
+ const name = line.split(/\s+/)[0];
301
+ if (name && name !== "NAME")
302
+ ollamaModels.push(name);
303
+ }
304
+ }
305
+ }
306
+ catch {
307
+ // ollama list fails if server not running — that's fine
308
+ }
309
+ }
310
+ }
311
+ catch {
312
+ // ollama not found
313
+ }
314
+ try {
315
+ const whichLlama = spawnSync("which", ["llama-server"], {
316
+ timeout: 3000,
317
+ encoding: "utf-8",
318
+ stdio: ["ignore", "pipe", "pipe"],
319
+ }); // guardrails-allow PREVENT-PI-004: local subprocess detection only
320
+ llamaDetected = whichLlama.status === 0;
321
+ }
322
+ catch {
323
+ // not found
324
+ }
325
+ try {
326
+ const req = createRequire(import.meta.url);
327
+ try {
328
+ req.resolve("onnxruntime-node");
329
+ onnxDetected = true;
330
+ }
331
+ catch {
332
+ // not in node_modules
333
+ }
334
+ }
335
+ catch {
336
+ // require error
337
+ }
338
+ const choices = [];
339
+ if (ollamaDetected && ollamaRunning) {
340
+ const model = ollamaModels.find((m) => m.includes("nomic-embed") ||
341
+ m.includes("embed") ||
342
+ m.includes("mxbai"));
343
+ const suggestedModel = model ?? "nomic-embed-text";
344
+ choices.push({
345
+ label: `Use Ollama (${suggestedModel}) at localhost:11434`,
346
+ value: `ollama:${suggestedModel}`,
347
+ });
348
+ }
349
+ else if (ollamaDetected && !ollamaRunning) {
350
+ choices.push({
351
+ label: "Ollama detected but server is not running — start it first",
352
+ value: "ollama:offline",
353
+ });
354
+ }
355
+ if (llamaDetected) {
356
+ choices.push({
357
+ label: "Use llama.cpp server at localhost:8080",
358
+ value: "llama:default",
359
+ });
360
+ }
361
+ if (onnxDetected) {
362
+ choices.push({
363
+ label: "Use ONNX Runtime (experimental, requires config)",
364
+ value: "onnx:default",
365
+ });
366
+ }
367
+ choices.push({
368
+ label: "Keep TrigramEmbedder (default, no setup)",
369
+ value: "trigram",
370
+ });
371
+ // --- 4. Prompt user ---
372
+ log(`Current embedder: ${currentEmbedder}`);
373
+ let selected = "trigram";
374
+ if (choices.length > 1) {
375
+ try {
376
+ const labels = choices.map((c) => c.label);
377
+ const picked = await ctx.ui.select("Select an embedder to configure:", labels);
378
+ if (picked === undefined) {
379
+ log("Setup cancelled by user.");
380
+ return;
381
+ }
382
+ const match = choices.find((c) => c.label === picked);
383
+ selected = match?.value ?? "trigram";
384
+ }
385
+ catch {
386
+ log("Setup cancelled by user.");
387
+ return;
388
+ }
389
+ }
390
+ else {
391
+ log("No local embedders detected. Keeping TrigramEmbedder default.");
392
+ }
393
+ // --- 5. Apply selection ---
394
+ if (selected.startsWith("ollama:")) {
395
+ const model = selected.split(":")[1];
396
+ const url = `http://localhost:11434/api/embeddings`; // guardrails-allow PREVENT-PI-004: localhost-only config string, not a runtime fetch
397
+ const lines = [
398
+ `# Mega-Compact Embedder Configuration — Ollama`,
399
+ `# Generated by /megasetup at ${new Date().toISOString()}`,
400
+ `export MEGACOMPACT_EMBEDDING_URL="${url}"`,
401
+ `# Optional: uncomment to set cache size (default 1000)`,
402
+ `# export MEGACOMPACT_EMBED_CACHE=1000`,
403
+ ];
404
+ const envContent = lines.join("\n") + "\n";
405
+ // Write .mega-compact.env to state dir
406
+ const stateDir = process.env["MEGACOMPACT_STATE_DIR"] ?? path.join(os.homedir(), ".pi", "mega-compact");
407
+ try {
408
+ mkdirSync(stateDir, { recursive: true });
409
+ writeFileSync(path.join(stateDir, ".mega-compact.env"), envContent, "utf-8");
410
+ }
411
+ catch {
412
+ // non-fatal
413
+ }
414
+ log(`Configured for Ollama (${model}).\n\nAdd to your shell profile (~/.bashrc, ~/.zshrc, or ~/.config/fish/config.fish):\n\n source "${path.join(stateDir, ".mega-compact.env")}"\n\nOr export manually:\n\n export MEGACOMPACT_EMBEDDING_URL="${url}"\n\nThen restart pi to activate the http embedder.`);
415
+ }
416
+ else if (selected.startsWith("llama:")) {
417
+ const url = "http://localhost:8080/v1/embeddings"; // guardrails-allow PREVENT-PI-004: localhost-only config string, not a runtime fetch
418
+ const lines = [
419
+ `# Mega-Compact Embedder Configuration — llama.cpp`,
420
+ `# Generated by /megasetup at ${new Date().toISOString()}`,
421
+ `export MEGACOMPACT_EMBEDDING_URL="${url}"`,
422
+ ];
423
+ const envContent = lines.join("\n") + "\n";
424
+ const stateDir = process.env["MEGACOMPACT_STATE_DIR"] ?? path.join(os.homedir(), ".pi", "mega-compact");
425
+ try {
426
+ mkdirSync(stateDir, { recursive: true });
427
+ writeFileSync(path.join(stateDir, ".mega-compact.env"), envContent, "utf-8");
428
+ }
429
+ catch {
430
+ // non-fatal
431
+ }
432
+ log(`Configured for llama.cpp server.\n\nAdd to your shell profile:\n\n source "${path.join(stateDir, ".mega-compact.env")}"\n\nOr export manually:\n\n export MEGACOMPACT_EMBEDDING_URL="${url}"\n\nThen restart pi to activate the http embedder.`);
433
+ }
434
+ else if (selected.startsWith("onnx:")) {
435
+ log("ONNX Runtime configuration is experimental.\n\nSet MEGACOMPACT_EMBEDDING_URL to your local ONNX server URL, or see docs for manual setup.\nKeeping TrigramEmbedder for now.");
436
+ }
437
+ else {
438
+ log("Keeping TrigramEmbedder (default). No configuration needed.");
439
+ }
440
+ }
441
+ catch (e) {
442
+ ctx.ui.notify(`[mega-compact] /mega-setup failed: ${String(e)}`);
443
+ }
444
+ },
445
+ });
258
446
  // NOTE: /mega-tier was removed in S24. The tier the user sees is now the LIVE
259
447
  // pressure band (low/medium/high/ultra/mega), which climbs automatically as
260
448
  // context fills — there is no manual tier to set. See docs/specs/s24-unified-pressure.md.
@@ -148,6 +148,8 @@ export function loadConfig() {
148
148
  errorRetryBackoffMs: envFlag("MEGACOMPACT_ERROR_RETRY_BACKOFF_MS", 5000),
149
149
  errorRetrySessionMax: envFlag("MEGACOMPACT_ERROR_RETRY_SESSION_MAX", 3),
150
150
  poisonedContextRepeatThreshold: envFlag("MEGACOMPACT_POISONED_REPEAT_THRESHOLD", 3),
151
+ providerOutageAdviseThreshold: envFlag("MEGACOMPACT_PROVIDER_OUTAGE_THRESHOLD", 3),
152
+ advisoryChannel: envBool("MEGACOMPACT_ADVISORY_CHANNEL", true),
151
153
  autoPctTrigger,
152
154
  autoInlineK: envFlag("MEGACOMPACT_AUTO_INLINE_K", 3),
153
155
  dedupSim: Number(process.env.MEGACOMPACT_DEDUP_SIM ?? "0.9"),
@@ -164,6 +166,7 @@ export function loadConfig() {
164
166
  memoryReviewInterval: envFlag("MEGACOMPACT_MEMORY_REVIEW_INTERVAL", 10),
165
167
  recallMaxTokens: envFlag("MEGACOMPACT_RECALL_MAX_TOKENS", 1500),
166
168
  windowDedupe: envBool("MEGACOMPACT_WINDOW_DEDUPE", true),
169
+ recallTailInject: envBool("MEGACOMPACT_RECALL_TAIL_INJECT", true),
167
170
  tuiWidget: envBool("MEGACOMPACT_TUI_WIDGET", true),
168
171
  // D.1: env-overridable recompact delta (minimum context growth % before
169
172
  // re-compacting instead of replaying the cached live trim). Default 50.
@@ -5,8 +5,9 @@ import { evaluateAndUnlockAchievements } from "../../src/store/sqlite/game-achie
5
5
  import { ensureConversationIdFor, recordTurnWrite, } from "../mega-turn-store.js";
6
6
  import { isMegaCache } from "../../src/game/scoring.js";
7
7
  import { resolveRepoRoot } from "../mega-config.js";
8
- import { classifyError, errorRetryBackoffMs, extractErrorSignature, isKnownRetryableTransient, } from "./error-classifier.js";
8
+ import { classifyError, classifyErrorDetailed, errorRetryBackoffMs, extractErrorSignature, isKnownRetryableTransient, } from "./error-classifier.js";
9
9
  import { safeSendUserMessage } from "./send-safe.js";
10
+ import { maybeSendProviderOutageAdvisory } from "./outage-advisor.js";
10
11
  import { vectorStats } from "../../src/vectorStore.js";
11
12
  /** Register agent/turn tracking event handlers. */
12
13
  export function registerAgentHandlers(pi, runtime, config) {
@@ -153,7 +154,10 @@ export function registerAgentHandlers(pi, runtime, config) {
153
154
  try {
154
155
  if (runtime.rt.sessionId !== liveSid)
155
156
  return; // session reset
156
- const since2 = now - (runtime.rt.lastNativeCompactAt ?? 0);
157
+ // IMPORTANT: recompute Date.now() inside the timeout.
158
+ // `now` above is the durable-trim handler's timestamp and can be
159
+ // ~500ms stale by the time this callback runs.
160
+ const since2 = Date.now() - (runtime.rt.lastNativeCompactAt ?? 0);
157
161
  if (runtime.rt.lastNativeCompactAt !== stamp &&
158
162
  since2 < cooldownMs)
159
163
  return;
@@ -226,6 +230,15 @@ export function registerAgentHandlers(pi, runtime, config) {
226
230
  pi.on("turn_end", async (event, ctx) => {
227
231
  runtime.dashboard.event("turn_end", { turnIndex: event.turnIndex });
228
232
  runtime.snapshot(ctx);
233
+ // S53: consume staged recall blocks ONLY if they were actually injected
234
+ // into a view this turn. If no context event fired (edge: turn ended
235
+ // before any LLM call), recallInjectedThisTurn stays false and the blocks
236
+ // remain staged for the next turn's first context event.
237
+ if (config.recallTailInject && runtime.rt.recallInjectedThisTurn) {
238
+ runtime.pendingRecallBlock = undefined;
239
+ runtime.pendingMemoryRecallBlock = undefined;
240
+ runtime.rt.recallInjectedThisTurn = false;
241
+ }
229
242
  // S43 (per-turn tracking): record one turn row with the cached metrics so
230
243
  // the turn layer is queryable + forkable. Best-effort + non-fatal: a write
231
244
  // failure never breaks the agent loop.
@@ -336,6 +349,7 @@ export function registerAgentHandlers(pi, runtime, config) {
336
349
  }
337
350
  else {
338
351
  const category = classifyError(event.message);
352
+ const detail = classifyErrorDetailed(event.message);
339
353
  // R3: stateful poisoned-context signal — repeated identical error text
340
354
  // across consecutive turns. The classifier is stateless, so this
341
355
  // upgrade happens here. A 'transient' (or 'poisoned-context') turn
@@ -373,6 +387,13 @@ export function registerAgentHandlers(pi, runtime, config) {
373
387
  if (!isKnownRetryableTransient(errSig)) {
374
388
  effectiveCategory = "poisoned-context";
375
389
  }
390
+ else {
391
+ runtime.logger.info("repeat-upgrade-declined", {
392
+ sessionId: runtime.rt.sessionId,
393
+ signature: (errSig || '').slice(0, 500),
394
+ repeatCount: runtime.rt.errorTextRepeatCount,
395
+ });
396
+ }
376
397
  }
377
398
  }
378
399
  }
@@ -388,6 +409,9 @@ export function registerAgentHandlers(pi, runtime, config) {
388
409
  runtime.rt.consecutiveErrors = 0; // S38.6: circuit-breaker reset on success
389
410
  // R4: a successful assistant turn consumes any queued nudge.
390
411
  runtime.rt.retryNudgePending = false;
412
+ // R10: reset outage advisory so a recovered-then-flapping
413
+ // provider re-advises once per episode.
414
+ runtime.rt.providerOutageAdvised = false;
391
415
  }
392
416
  else if (effectiveCategory === "compaction-noop") {
393
417
  // (4) pi race / manual compact catch — NOT retryable. The compaction
@@ -487,22 +511,31 @@ export function registerAgentHandlers(pi, runtime, config) {
487
511
  runtime.rt.consecutiveErrors++; // still counts toward the circuit breaker
488
512
  runtime.rt.poisonedCount++; // R7: dashboard counter
489
513
  const sig = errSig || "unknown";
490
- // (a) dashboard + log
514
+ // (a) dashboard + log — R11: include signal + rawText for forensics
491
515
  runtime.dashboard.event("poisoned_context", {
492
516
  signature: sig,
493
517
  repeatCount: runtime.rt.errorTextRepeatCount,
494
518
  turnIndex: event.turnIndex,
495
519
  sessionId: runtime.rt.sessionId,
520
+ signal: detail.signal,
521
+ rawText: (errSig || '').slice(0, 500),
522
+ ...(detail.httpStatus !== undefined ? { httpStatus: detail.httpStatus } : {}),
496
523
  });
497
524
  runtime.logger.warn("poisoned-context", {
498
525
  sessionId: runtime.rt.sessionId,
499
526
  turnIndex: event.turnIndex,
500
527
  signature: sig,
501
528
  repeatCount: runtime.rt.errorTextRepeatCount,
529
+ signal: detail.signal,
530
+ rawText: (errSig || '').slice(0, 500),
531
+ ...(detail.httpStatus !== undefined ? { httpStatus: detail.httpStatus } : {}),
502
532
  });
503
- // (b) one-per-session advise message (throttled by poisonedAdviseSent)
504
- if (!runtime.rt.poisonedAdviseSent) {
505
- runtime.rt.poisonedAdviseSent = true;
533
+ // (b) throttle flag: set unconditionally so the advise fires at
534
+ // most once per session regardless of channel.
535
+ runtime.rt.poisonedAdviseSent = true;
536
+ // Legacy flag-OFF path: user-role advise message.
537
+ // Default ON (advisoryChannel=true): dashboard-only, no user message.
538
+ if (!config.advisoryChannel) {
506
539
  // PREVENT-PI-003: user-role sendUserMessage only.
507
540
  await safeSendUserMessage(pi, "[mega-compact] this session's context may be poisoned (the provider is rejecting every request). Run /clear or /new to start a fresh context.");
508
541
  }
@@ -552,6 +585,8 @@ export function registerAgentHandlers(pi, runtime, config) {
552
585
  }
553
586
  // S38.6: circuit-breaker — stop retrying after too many consecutive errors.
554
587
  runtime.rt.consecutiveErrors++;
588
+ // R10: send calm "provider outage" advisory once per episode.
589
+ await maybeSendProviderOutageAdvisory(effectiveCategory, runtime, pi, config, { signal: detail.signal, rawText: (errSig || '').slice(0, 500) });
555
590
  if (runtime.rt.consecutiveErrors > config.maxConsecutiveErrors) {
556
591
  runtime.dashboard.event("error_retry_circuit_open", {
557
592
  consecutive: runtime.rt.consecutiveErrors,
@@ -46,6 +46,7 @@ async function nudgeResume(pi, runtime) {
46
46
  const now = Date.now();
47
47
  if (now >= runtime.resumeNudgeUntil) {
48
48
  runtime.resumeNudgeUntil = now + 30_000;
49
+ runtime.rt.extensionInitiatedTurn = true; // R13: suppress self-classification
49
50
  await safeSendUserMessage(pi, "[mega-compact] continue from the compacted context above.");
50
51
  }
51
52
  }
@@ -1,4 +1,4 @@
1
- import { openStore, appendRawTranscript, writeCheckpointEpoch, } from "../../src/store/sqlite.js";
1
+ import { openStore, writeCheckpointEpoch, } from "../../src/store/sqlite.js";
2
2
  import { epochIdFor } from "../../src/mirror/epoch.js";
3
3
  import { autoCompactCheck } from "../../src/compact.js";
4
4
  import { estimateSessionTokens } from "../../src/tokens.js";
@@ -9,75 +9,8 @@ import { openTurnStore } from "../../src/store/turns/connection.js";
9
9
  import { buildTopicModel, createTopicStore, bumpWikiCompactCounter, } from "../../src/topics/index.js";
10
10
  import { computeLiveTrimCut, liveTrimSummaryMessage } from "../mega-trim.js";
11
11
  import { pressureFromPct, pressureRatio, } from "../mega-config.js";
12
- import { computeContentDigest } from "../../src/dedup/digest.js";
13
- /**
14
- * Recursively canonicalize a value for deterministic JSON serialization:
15
- * - Objects: keys sorted alphabetically, values recursively canonicalized
16
- * - Arrays: elements recursively canonicalized (array ORDER is preserved)
17
- * - Primitives: returned as-is
18
- *
19
- * F5 fix: shallow-sorted JSON.stringify(content, Object.keys(content).sort())
20
- * omitted nested keys not in the top-level keys array and only sorted one level.
21
- * This recursively sorts every object at every depth so semantically-equal
22
- * differently-ordered content hashes identically.
23
- */
24
- function canonicalize(value) {
25
- if (value === null || value === undefined)
26
- return value;
27
- if (typeof value !== "object")
28
- return value;
29
- if (Array.isArray(value))
30
- return value.map(canonicalize);
31
- // Plain object: sort keys, recursively canonicalize values.
32
- const sorted = Object.keys(value).sort();
33
- const out = {};
34
- for (const k of sorted) {
35
- out[k] = canonicalize(value[k]);
36
- }
37
- return out;
38
- }
39
- /**
40
- * Convert a pi AgentMessage to a RawTranscriptRow for the DB mirror.
41
- * content_bytes is canonical JSON (sorted keys, recursive) for deterministic
42
- * storage; contentHash is the canonical digest (normalize + hash) that matches
43
- * what dedupTranscript computes so the two pipelines use the same linkage key.
44
- *
45
- * F4 fix: the hash key MUST match on both sides of the append/dedup split.
46
- * Using computeContentDigest here (normalize → hash) ensures content_ref set
47
- * by dedupTranscript always resolves to an existing dedup_mirror row even for
48
- * whitespace/case-variant content. F5 fix: recursive canonicalize replaces the
49
- * broken shallow-sorted JSON.stringify replacer.
50
- */
51
- function toRawTranscriptRow(msg, sessionId, epochId, currentTurn) {
52
- // Narrow to Message union (has content + timestamp).
53
- const m = msg;
54
- const content = m.content;
55
- if (content == null || content === "")
56
- return null;
57
- // Canonical bytes: string content → normalize for consistent byte content;
58
- // object content → recursive canonicalize then JSON (no replacer).
59
- const contentBytes = typeof content === "string"
60
- ? content // F5: strings are primitives; their byte content is fixed
61
- : JSON.stringify(canonicalize(content));
62
- // F4 fix: use the same digest as dedupTranscript so contentHash is consistent
63
- // on both sides of the append/dedup split. computeContentDigest normalizes
64
- // (strip ANSI, NFC, case-fold, collapse whitespace) then hashes → the same
65
- // key is stored in raw_transcript.content_hash AND used as the dedup link.
66
- const { contentHash } = computeContentDigest(contentBytes);
67
- return {
68
- contentHash,
69
- sessionId,
70
- seq: 0, // assigned by appendRawTranscript (COALESCE(MAX(seq),0)+1)
71
- role: m.role ?? "unknown",
72
- contentBytes,
73
- toolName: m.toolName ?? null,
74
- messageTimestamp: m.timestamp ?? null,
75
- checkpointEpoch: epochId,
76
- // S50: label the row with the turn that produced it (per-turn dedup /
77
- // compression-by-turn metrics). Null when the writer omits it (back-compat).
78
- turnIndex: currentTurn ?? null,
79
- };
80
- }
12
+ import { appendMirrorMessages } from "./mirror-append.js";
13
+ import { stagedForTail, withRecallTail } from "./recall-tail.js";
81
14
  /** Register the context event handler (live-trim auto-trigger). */
82
15
  export function registerContextHandler(pi, runtime, config) {
83
16
  // ---- Auto-trigger: live trim (compact and continue) + native durable ----
@@ -98,6 +31,17 @@ export function registerContextHandler(pi, runtime, config) {
98
31
  const usage = ctx.getContextUsage();
99
32
  const pct = usage?.percent;
100
33
  const messages = event.messages;
34
+ // S53: helper to inject the staged recall/memory block as a user-role
35
+ // tail message at any view-return point. Returns undefined when nothing
36
+ // is staged (or the flag is OFF) so the caller falls through to its
37
+ // normal return. The F3 mirror append (above the gates) runs on the
38
+ // REAL transcript before any view is built, so the injected tail never
39
+ // reaches raw_transcript (PREVENT-PI: append-only, view-only).
40
+ const tailResult = (msgs) => {
41
+ if (!stagedForTail(runtime, config))
42
+ return undefined;
43
+ return { messages: withRecallTail(msgs ?? messages, runtime, config) };
44
+ };
101
45
  // Always track context for the dashboard/widget, even when auto is off.
102
46
  // (v0.8 regression: !config.auto gate sat above this, leaving ctx stats
103
47
  // null -> widget '?% / ?/?' when auto disabled. Track first, THEN gate.)
@@ -118,21 +62,24 @@ export function registerContextHandler(pi, runtime, config) {
118
62
  runtime.lastCtxPercent = pct ?? null;
119
63
  runtime.lastCtxWindow = usage?.contextWindow ?? 0;
120
64
  runtime.snapshot(ctx);
121
- if (!config.auto)
65
+ if (!config.auto) {
66
+ const tailed = tailResult();
67
+ if (tailed)
68
+ return tailed;
122
69
  return;
70
+ }
123
71
  const view = viewForFallback ?? runtime.engineView(messages);
124
- // S27 DB-mirror: append ALL incoming messages to raw_transcript.
72
+ // S27 DB-mirror: append incoming messages to raw_transcript.
125
73
  // Runs BEFORE fast-gate so every message is captured, even if we
126
74
  // don't compact this turn. Append is idempotent (content_hash PK).
75
+ // F3: high-water mark (mirror-append.ts) skips already-processed
76
+ // messages on subsequent events. On fork/rewind (shorter list or
77
+ // boundary hash mismatch) the mark is dropped, falling back to a
78
+ // full reprocess.
127
79
  if (config.dbMirror) {
128
80
  try {
129
81
  const db = openStore(runtime.currentStateDir);
130
- const epochId = epochIdFor(runtime.rt.sessionId);
131
- for (const msg of messages) {
132
- const raw = toRawTranscriptRow(msg, runtime.rt.sessionId, epochId, runtime.currentTurn);
133
- if (raw)
134
- appendRawTranscript(db, raw);
135
- }
82
+ appendMirrorMessages(db, messages, runtime.rt.sessionId, epochIdFor(runtime.rt.sessionId), runtime.currentTurn);
136
83
  }
137
84
  catch (e) {
138
85
  runtime.logger.warn("db-mirror-append-fail", { error: String(e) });
@@ -157,18 +104,18 @@ export function registerContextHandler(pi, runtime, config) {
157
104
  // custom tier OR tiered-but-pct-unavailable → token gate (S27 fallback).
158
105
  if (currentTokens < runtime.effectiveThreshold) {
159
106
  runtime.diagCtxFastGate++;
160
- return;
107
+ return tailResult() ?? undefined;
161
108
  }
162
109
  const check = autoCompactCheck(currentTokens, runtime.effectiveThreshold); // SERVER-STYLE CONFIRM (local)
163
110
  if (!check.shouldCompact) {
164
111
  runtime.diagCtxNoCompact++;
165
- return;
112
+ return tailResult() ?? undefined;
166
113
  }
167
114
  gatePassed = true;
168
115
  }
169
116
  if (!gatePassed) {
170
117
  runtime.diagCtxFastGate++;
171
- return;
118
+ return tailResult() ?? undefined;
172
119
  }
173
120
  // D.2: Replay MUST be exempt from debounce — replay is free (no compute,
174
121
  // no re-write) and prevents unnecessary KV-cache invalidation. Check
@@ -197,9 +144,8 @@ export function registerContextHandler(pi, runtime, config) {
197
144
  runtime.snapshot(ctx);
198
145
  // v0.8.7: shallow-copy the cached summary so pi's transformContext can't
199
146
  // mutate the shared reference across replays (audit P3).
200
- return {
201
- messages: [{ ...runtime.trimCache.summaryAgentMsg }, ...recent],
202
- };
147
+ const replayView = [{ ...runtime.trimCache.summaryAgentMsg }, ...recent];
148
+ return tailResult(replayView) ?? { messages: replayView };
203
149
  }
204
150
  // else: context grew enough → fall through to re-compact (cache is stale)
205
151
  }
@@ -208,7 +154,7 @@ export function registerContextHandler(pi, runtime, config) {
208
154
  const now = Date.now();
209
155
  if (now < runtime.debounceUntil) {
210
156
  runtime.diagCtxDebounce++;
211
- return;
157
+ return tailResult() ?? undefined;
212
158
  }
213
159
  runtime.debounceUntil = now + 2000;
214
160
  // Adaptive compression (Fix E): scale compression strength + keepFrom depth
@@ -233,11 +179,10 @@ export function registerContextHandler(pi, runtime, config) {
233
179
  runtime.diagLiveTrimFires++;
234
180
  runtime.diagLiveTrimReplays++;
235
181
  runtime.snapshot(ctx);
236
- return {
237
- messages: [{ ...runtime.trimCache.summaryAgentMsg }, ...recent],
238
- };
182
+ const skipView = [{ ...runtime.trimCache.summaryAgentMsg }, ...recent];
183
+ return tailResult(skipView) ?? { messages: skipView };
239
184
  }
240
- return;
185
+ return tailResult() ?? undefined;
241
186
  }
242
187
  // S27 DB-mirror: write checkpoint_epoch with deterministic nonce.
243
188
  // This makes the cache key stable across identical compactions.
@@ -392,7 +337,7 @@ export function registerContextHandler(pi, runtime, config) {
392
337
  viewLen: view.length,
393
338
  anchorUserMessages,
394
339
  });
395
- return; // unsafe / below anchor floor — no trim this call
340
+ return tailResult() ?? undefined; // unsafe / below anchor floor — no trim this call
396
341
  }
397
342
  const summaryMsg = liveTrimSummaryMessage({
398
343
  compactedFrom: ran.result.compactedFrom,
@@ -446,11 +391,11 @@ export function registerContextHandler(pi, runtime, config) {
446
391
  ctxPct: pct,
447
392
  ctxTokens: usage?.tokens ?? null,
448
393
  });
449
- return { messages: [summaryAgentMsg, ...recent] };
394
+ return tailResult([summaryAgentMsg, ...recent]) ?? { messages: [summaryAgentMsg, ...recent] };
450
395
  }
451
396
  catch {
452
397
  runtime.diagCtxThrown++;
453
- return; // non-fatal: no trim this call; the next context event retries
398
+ return tailResult() ?? undefined; // non-fatal: no trim this call; the next context event retries
454
399
  }
455
400
  });
456
401
  }
@@ -0,0 +1,51 @@
1
+ const TABLE_DDL = `CREATE TABLE IF NOT EXISTS context_hwm (
2
+ session_id TEXT PRIMARY KEY,
3
+ last_seq INTEGER NOT NULL,
4
+ last_content_hash TEXT NOT NULL
5
+ )`;
6
+ /** Ensure the context_hwm table exists. Idempotent. */
7
+ export function ensureHwmTable(db) {
8
+ try {
9
+ db.exec(TABLE_DDL);
10
+ }
11
+ catch {
12
+ // non-fatal
13
+ }
14
+ }
15
+ /** Read the high-water mark for a session. Returns undefined if none. */
16
+ export function readHwm(db, sessionId) {
17
+ try {
18
+ const row = db
19
+ .prepare("SELECT session_id, last_seq, last_content_hash FROM context_hwm WHERE session_id = ?")
20
+ .get(sessionId);
21
+ if (!row)
22
+ return undefined;
23
+ return {
24
+ sessionId: row.session_id,
25
+ lastSeq: Number(row.last_seq),
26
+ lastContentHash: row.last_content_hash,
27
+ };
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ }
33
+ /** Write (INSERT OR REPLACE) the high-water mark for a session. */
34
+ export function writeHwm(db, hwm) {
35
+ try {
36
+ db.prepare("INSERT OR REPLACE INTO context_hwm (session_id, last_seq, last_content_hash) VALUES (?, ?, ?)").run(hwm.sessionId, hwm.lastSeq, hwm.lastContentHash);
37
+ }
38
+ catch {
39
+ // non-fatal
40
+ }
41
+ }
42
+ /** Drop the high-water mark for a session (invalidation). */
43
+ export function dropHwm(db, sessionId) {
44
+ try {
45
+ db.prepare("DELETE FROM context_hwm WHERE session_id = ?").run(sessionId);
46
+ }
47
+ catch {
48
+ // non-fatal
49
+ }
50
+ }
51
+ export const TEST_ONLY = { TABLE_DDL };