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
@@ -24,9 +24,11 @@
24
24
  * - `etimedout` is Node's timeout errno lowercased — does NOT contain the
25
25
  * substring "timeout".
26
26
  * - `socket hang up` is Node's ECONNRESET *message*; the errno lives in
27
- * error.code, which extractErrorSignature never sees. */
27
+ * error.code, which extractErrorSignature never sees.
28
+ * - router phrasings (all targets failed / no healthy target / too many
29
+ * concurrent) -- pi's status prefix is console-only (2026-07-30 incident). */
28
30
  export const KNOWN_RETRYABLE_TRANSIENT_PATTERN =
29
- /max(imum)? output token|rate[\s.-]?limit|429|too many requests|overloaded|5\d\d|internal server|bad gateway|service unavailable|network|time(?:d[\s-]?out|out)|etimedout|econnreset|econnrefused|epipe|eai_again|socket hang up|premature close|other side closed|connection (lost|refused|reset|aborted?)|stream (interrupted|closed|ended|failed)|disconnected/;
31
+ /max(imum)? output token|rate[\s.-]?limit|429|too many requests|too many concurrent|overloaded|5\d\d|internal server|bad gateway|service unavailable|all targets failed|no healthy target|fetch failed|network|time(?:d[\s-]?out|out)|etimedout|econnreset|econnrefused|epipe|eai_again|socket|closed unexpectedly|premature close|other side closed|connection (lost|refused|reset|aborted?|was closed)|stream (interrupted|closed|ended|failed)|disconnected/;
30
32
 
31
33
  /** R7: true when the error text carries a known-retryable transient marker.
32
34
  * Defensively lowercases so callers can pass raw or normalized text. */
@@ -34,32 +36,60 @@ export function isKnownRetryableTransient(text: string): boolean {
34
36
  return KNOWN_RETRYABLE_TRANSIENT_PATTERN.test(text.toLowerCase());
35
37
  }
36
38
 
37
- /** S38.2: classify a turn-end error/stop signal into a retry category.
38
- *
39
- * `length` is returned as null S28 owns the max-output-token length stopReason
40
- * exclusively (its agent_end nudge path is separate and must not be doubled).
41
- *
42
- * @param message the event.message (a pi AgentMessage) or an error string
43
- * @returns 'transient' | 'permanent' | 'compaction-noop' | 'context-overflow' | 'cancelled' | 'poisoned-context' | null (success/unknown)
44
- */
45
- export function classifyError(message: unknown):
39
+ /** R8: best-effort extraction of HTTP status from pi AgentMessage shapes. */
40
+ function extractHttpStatus(m: Record<string, unknown>): number | undefined {
41
+ for (const outer of [m.error, m] as Array<Record<string, unknown> | undefined>) {
42
+ if (!outer || typeof outer !== 'object') continue;
43
+ for (const key of ['status', 'statusCode', 'code']) {
44
+ const v = (outer as Record<string, unknown>)[key];
45
+ if (typeof v === 'number' && v >= 100 && v <= 599) return v;
46
+ }
47
+ }
48
+ return undefined;
49
+ }
50
+
51
+ /** R11: signal tag identifying which classification rule fired. */
52
+ export type ErrorSignal =
53
+ | 'length-guard'
54
+ | 'cancelled'
55
+ | 'success'
56
+ | 'stream-death-no-stopreason'
57
+ | 'compaction-noop'
58
+ | 'context-overflow'
59
+ | 'transient-marker'
60
+ | 'transient-status'
61
+ | 'permanent-status'
62
+ | 'poisoned-invalid-request'
63
+ | 'poisoned-request-failed'
64
+ | 'bare-0-token'
65
+ | 'generic-error'
66
+ | 'permanent-auth'
67
+ | 'unknown';
68
+
69
+ export type ErrorCategory =
46
70
  | 'transient'
47
71
  | 'permanent'
48
72
  | 'compaction-noop'
49
73
  | 'context-overflow'
50
74
  | 'cancelled'
51
75
  | 'poisoned-context'
52
- | null {
53
- // Resolve a searchable text blob from a pi AgentMessage or raw string.
76
+ | null;
77
+
78
+ /** R11: detailed classification result with the signal tag and optional httpStatus. */
79
+ export interface ClassifyErrorDetail {
80
+ category: ErrorCategory;
81
+ signal: ErrorSignal;
82
+ httpStatus?: number;
83
+ }
84
+
85
+ /** R11: classify a turn-end error/stop signal into a retry category with a
86
+ * diagnostic signal tag naming the rule that fired, plus the raw httpStatus
87
+ * when extractHttpStatus found one. */
88
+ export function classifyErrorDetailed(message: unknown): ClassifyErrorDetail {
54
89
  let text = '';
55
- // R3: usage-token signal. Only when `usage` is explicitly present with
56
- // inputTokens=0 AND outputTokens=0 do we know the turn never reached the
57
- // model. An ABSENT usage field means "unknown" (the event didn't carry
58
- // token counts) — we do NOT treat that as the 0-token poisoned signal,
59
- // because mid-response stream deaths and partial-content turns routinely
60
- // omit usage while still being transient (preserves all pre-R3 tests).
61
90
  let usagePresent = false;
62
91
  let totalTokens = 0;
92
+ let httpStatus: number | undefined;
63
93
  if (typeof message === 'string') {
64
94
  text = message;
65
95
  } else if (message && typeof message === 'object') {
@@ -70,14 +100,9 @@ export function classifyError(message: unknown):
70
100
  usage?: { inputTokens?: number; outputTokens?: number } | undefined;
71
101
  };
72
102
  const sr = typeof m.stopReason === 'string' ? m.stopReason : '';
73
- // S28 guard: length stopReason is handled exclusively by the S28 path.
74
- if (sr === 'length') return null;
75
- // User ESC / Ctrl-C abort stopReason === 'aborted'. Not retryable:
76
- // nudging would restart a task the user explicitly stopped.
77
- if (sr === 'aborted') return 'cancelled';
78
- // Success / normal tool flow — not an error, nothing to retry.
79
- if (sr === 'stop' || sr === 'toolUse' || sr === 'tool_use') return null;
80
- // R3: extract usage tokens for the 0-token poisoned-context signal.
103
+ if (sr === 'length') return { category: null, signal: 'length-guard' };
104
+ if (sr === 'aborted') return { category: 'cancelled', signal: 'cancelled' };
105
+ if (/^(stop|tool_?use|end_?turn|max_?tokens|complete|finished|done)$/i.test(sr)) return { category: null, signal: 'success' };
81
106
  const usage = m.usage;
82
107
  usagePresent = usage != null && typeof usage === 'object';
83
108
  if (usagePresent) {
@@ -86,6 +111,7 @@ export function classifyError(message: unknown):
86
111
  (typeof u.inputTokens === 'number' ? u.inputTokens : 0) +
87
112
  (typeof u.outputTokens === 'number' ? u.outputTokens : 0);
88
113
  }
114
+ httpStatus = extractHttpStatus(m as Record<string, unknown>);
89
115
  const parts: string[] = [];
90
116
  if (sr) parts.push(sr);
91
117
  const c = m.content;
@@ -98,119 +124,88 @@ export function classifyError(message: unknown):
98
124
  }
99
125
  }
100
126
  if (m.error) {
101
- // Extract message from error objects for pattern matching.
102
127
  const err = m.error;
103
- if (typeof err === 'string') {
104
- parts.push(err);
105
- } else if (err && typeof err === 'object') {
128
+ if (typeof err === 'string') parts.push(err);
129
+ else if (err && typeof err === 'object') {
106
130
  const errObj = err as Record<string, unknown>;
107
- if (typeof errObj.message === 'string') {
108
- parts.push(errObj.message);
109
- } else {
110
- parts.push(JSON.stringify(err));
111
- }
131
+ if (typeof errObj.message === 'string') parts.push(errObj.message);
132
+ else parts.push(JSON.stringify(err));
112
133
  }
113
134
  }
114
- // S38: detect mid-response errors where the stream died without a
115
- // proper stopReason (empty/undefined) — this catches provider failures
116
- // that cut off the response mid-stream, INCLUDING the case where the
117
- // provider emitted partial content before dying (a truncated response
118
- // with no stop reason is a mid-stream death, not a success).
119
- // A genuine success ALWAYS carries stop/tool_use/toolUse (which
120
- // short-circuit to null at the top), so any message reaching here with a
121
- // falsy stopReason is a stream failure → retryable.
122
135
  if (!sr) {
123
- return 'transient';
136
+ // A missing stopReason alone is not sufficient evidence of stream death.
137
+ // Require at least one corroborating signal: an error field, or 0 total tokens
138
+ // (indicating the stream died before producing anything). A normal completion
139
+ // from a runtime that omits stopReason has content and tokens — not an error.
140
+ const hasError = (m.error != null && m.error !== undefined && m.error !== '') ||
141
+ (typeof (m as { errorMessage?: unknown }).errorMessage === 'string' && (m as { errorMessage?: string }).errorMessage !== '');
142
+ if (hasError || (usagePresent && totalTokens === 0)) {
143
+ const r: ClassifyErrorDetail = { category: 'transient', signal: 'stream-death-no-stopreason' };
144
+ if (httpStatus !== undefined) r.httpStatus = httpStatus;
145
+ return r;
146
+ }
147
+ // No stopReason, no error field, tokens present — likely a normal completion
148
+ // from a runtime that omits stopReason (pi-crew, etc.). Not an error.
149
+ return { category: null, signal: 'success' };
124
150
  }
125
151
  text = parts.join(' ');
126
152
  }
127
- if (!text) return null;
153
+ if (!text) return { category: null, signal: 'unknown' };
128
154
  const s = text.toLowerCase();
129
- // --- compaction-noop (ORDER FIRST: pi race / manual compact catch) ---
130
- // FAIL-2026071701: these are NOT retryable — the compaction already
131
- // succeeded via pi's native path; retrying would race again.
132
- if (/already compacted/.test(s)) return 'compaction-noop';
133
- if (/compaction failed/.test(s)) return 'compaction-noop';
134
- if (/nothing to compact/.test(s)) return 'compaction-noop';
135
- if (/auto[\s-]?compaction failed/.test(s)) return 'compaction-noop';
136
- // --- context-overflow (ORDER BEFORE generic transient!) ---
137
- // A 400 from the model meaning "the prompt is bigger than the context window."
138
- // Catches BOTH provider phrasings so the classification does not depend on
139
- // which backend the router landed on:
140
- // - pi/Anthropic wrapper: "too long for this model's context window even
141
- // after compaction. Reduce the conversation length..." ->
142
- // too long | context window | even after compaction | reduce the conversation
143
- // - OpenAI/OpenRouter provider-side (often wrapped in "All targets failed:
144
- // <model>. Last error: ..."): "This model's maximum context length is N
145
- // tokens. Your request requires at least M tokens. Please reduce your
146
- // input or max_tokens." -> maximum context length | context length
147
- // exceeded | requires at least N tokens | reduce your input
148
- // All of these carry `invalid_request_error` (UNDERSCORE, not 'invalid
149
- // request' space) and would otherwise fall through to the generic
150
- // `s.includes('error')` transient branch below, misclassifying as
151
- // 'transient' and firing up to 5 blind retry nudges that re-submit the same
152
- // oversized prompt -> re-400 -> busy-loop. 'context-overflow' instead forces
153
- // ONE deferred re-compact (debounce-bypassed, race-guarded) and fires NO
154
- // blind retry nudge. The forced re-compact is shaped by the existing
155
- // session_before_compact durable trim (it cannot lower pi's firstKeptEntryId).
155
+ if (/already compacted|compaction failed|nothing to compact|auto[\s-]?compaction failed/.test(s)) {
156
+ return { category: 'compaction-noop', signal: 'compaction-noop' };
157
+ }
156
158
  if (/too long|context window|maximum context length|context length exceeded|requires at least \d+ tokens|even after compaction|reduce the conversation|reduce your input/.test(s)) {
157
- return 'context-overflow';
159
+ return { category: 'context-overflow', signal: 'context-overflow' };
160
+ }
161
+ if (isKnownRetryableTransient(s)) {
162
+ const r: ClassifyErrorDetail = { category: 'transient', signal: 'transient-marker' };
163
+ if (httpStatus !== undefined) r.httpStatus = httpStatus;
164
+ return r;
165
+ }
166
+ if (httpStatus === 429 || (httpStatus !== undefined && httpStatus >= 500)) {
167
+ return { category: 'transient', signal: 'transient-status', httpStatus };
168
+ }
169
+ if (httpStatus === 401 || httpStatus === 403) {
170
+ return { category: 'permanent', signal: 'permanent-status', httpStatus };
158
171
  }
159
- // --- transient (known-retryable markers FIRST — these override poisoned signals) ---
160
- // R3: network/throughput failures (timeout, ECONNRESET, 5xx, 429) MUST stay
161
- // transient even when usage is 0 tokens, because they are retryable and
162
- // /clear cannot fix them. 'connection aborted' is a network failure
163
- // (ECONNABORTED), NOT a user ESC (stopReason 'aborted', early-return above).
164
- // The marker set is shared with the agent-handlers R3 repeat-upgrade guard
165
- // (isKnownRetryableTransient) so the two never drift.
166
- if (isKnownRetryableTransient(s)) return 'transient';
167
- // --- poisoned-context (R3: ORDER AFTER specific transient markers, BEFORE
168
- // the generic 'error' transient fallthrough) ---
169
- // A DETERMINISTIC request-rejection that retrying cannot fix. Re-submitting
170
- // the same prompt re-triggers the same rejection. The 2026-07-28 incident
171
- // was a provider returning 0-token "Request failed — please retry." turns
172
- // for every request; classifyError mapped stopReason 'error' → 'transient'
173
- // and the session emitted ~9 nudge bursts (~60 context-bloating messages)
174
- // before stopping.
175
- //
176
- // Signal 1: provider request-validation 400 that is NOT context-overflow
177
- // (context-overflow already returned above). Orphaned tool result / malformed
178
- // message structure / unexpected role ordering / empty content. These were
179
- // previously classified 'permanent' (max 1 retry) — but a single retry
180
- // re-submits the SAME malformed structure and re-400s, so they are poisoned,
181
- // not permanent. Auth/permission 400s stay permanent (separate check below).
182
172
  if (/invalid_request_error|invalid request|malformed|bad request|orphaned tool|tool (result )?(without|for )|unexpected role|role (ordering|sequence)|empty (content|message|request)/.test(s)) {
183
- return 'poisoned-context';
173
+ return { category: 'poisoned-context', signal: 'poisoned-invalid-request' };
184
174
  }
185
- // Signal 2: generic catch-all "request failed" / "request error" with no
186
- // specific transient marker (transient markers already returned above).
187
- // This is the exact phrasing the 2026-07-28 incident used. Without a
188
- // specific retryable cause, treat the rejection as deterministic.
189
175
  if (/request failed|request error/.test(s)) {
190
- return 'poisoned-context';
176
+ return { category: 'poisoned-context', signal: 'poisoned-request-failed' };
191
177
  }
192
- // Signal 3: stopReason 'error' + usage explicitly 0 tokens (the turn never
193
- // reached the model). Conservative: only when `usage` is PRESENT and 0 — an
194
- // absent usage field means "unknown" and stays transient (mid-response
195
- // deaths / partial-content turns often omit usage). The transient markers
196
- // above already returned, so reaching here with 'error' text and 0 tokens
197
- // means the request was rejected before any model work.
198
178
  if (usagePresent && totalTokens === 0 && /error/.test(s)) {
199
- return 'poisoned-context';
179
+ return { category: 'transient', signal: 'bare-0-token' };
200
180
  }
201
- // --- transient (generic 'error' stopReason fallthrough) ---
202
- // Reaches here for a generic stopReason 'error' with no specific marker and
203
- // no 0-token signal (usage absent or > 0). Stays transient — conservative.
204
181
  if (s.includes('error') && !/\b(auth|unauthorized|invalid (api )?key|permission)\b/.test(s)) {
205
- return 'transient'; // generic pi stopReason 'error'
182
+ return { category: 'transient', signal: 'generic-error' };
183
+ }
184
+ if (/auth|unauthorized|invalid (api )?key|permission/.test(s)) {
185
+ return { category: 'permanent', signal: 'permanent-auth' };
206
186
  }
207
- // NOTE: 'aborted' stopReason is handled by the sr==='aborted' early-return above.
208
- // The text-based s.includes('aborted') was removed — it was the old path that
209
- // misclassified user ESC/Ctrl-C as 'transient' (5 retry nudges after cancel).
210
- // --- permanent (NOT retryable beyond 1) ---
211
- if (/auth|unauthorized|invalid (api )?key|permission/.test(s)) return 'permanent';
212
- // Unknown do not retry (avoid busy-looping on an unclassified signal).
213
- return null;
187
+ return { category: null, signal: 'unknown' };
188
+ }
189
+
190
+ /** S38.2: classify a turn-end error/stop signal into a retry category.
191
+ *
192
+ * `length` is returned as null S28 owns the max-output-token length stopReason
193
+ * exclusively (its agent_end nudge path is separate and must not be doubled).
194
+ *
195
+ * Thin wrapper around classifyErrorDetailed — returns only the category.
196
+ *
197
+ * @param message the event.message (a pi AgentMessage) or an error string
198
+ * @returns 'transient' | 'permanent' | 'compaction-noop' | 'context-overflow' | 'cancelled' | 'poisoned-context' | null (success/unknown)
199
+ */
200
+ export function classifyError(message: unknown):
201
+ | 'transient'
202
+ | 'permanent'
203
+ | 'compaction-noop'
204
+ | 'context-overflow'
205
+ | 'cancelled'
206
+ | 'poisoned-context'
207
+ | null {
208
+ return classifyErrorDetailed(message).category;
214
209
  }
215
210
 
216
211
  /** S38.2: exponential backoff for error-retry nudges.
@@ -233,13 +228,39 @@ export function errorRetryBackoffMs(count: number, baseMs = 5000): number {
233
228
  * 'error' for retryable turns) so two turns with the same error content share
234
229
  * a signature. Empty string when there is no error text (e.g. a bare
235
230
  * stopReason 'error' with no content) — the caller skips repeat detection in
236
- * that case (the stateless 0-token signal handles bare errors). */
231
+ * that case (the stateless 0-token signal handles bare errors).
232
+ *
233
+ * R9: when the joined text is empty AND stopReason is 'error' AND usage is
234
+ * present with 0 total tokens, returns the constant "bare-0-token-error" so
235
+ * the repeat detector can corroborate bare 0-token errors (first turn is
236
+ * transient; repeated occurrences upgrade to poisoned at threshold). Bare
237
+ * 'error' WITHOUT usage keeps returning '' (absent usage = unknown; mid-
238
+ * response deaths stay out of repeat tracking). */
239
+ /** R12: normalize volatile tokens in an already-lowercased error string so that
240
+ * equivalent errors with varied model aliases, IPs, hex request-ids, retry
241
+ * counts, and long numeric ids produce the same signature. Order matters.
242
+ * 3-digit HTTP status codes (429/500/502/etc.) survive — the long-number rule
243
+ * only covers 4+ digits. Invariant: normalizeVolatileTokens never empties a
244
+ * non-empty string (every regex replaces with a non-empty literal token). */
245
+ function normalizeVolatileTokens(s: string): string {
246
+ let n = s;
247
+ n = n.replace(/\b\d{1,3}(\.\d{1,3}){3}(:\d+)?\b/g, '<ip>'); // 1. IP:port / bare IPv4
248
+ n = n.replace(/\b[\w-]+(\/[\w.:+-]+)+/g, '<model>'); // 2. slash-separated paths
249
+ n = n.replace(/\b[0-9a-f]{8,}\b/g, '<hex>'); // 3. hex ids (8+ chars)
250
+ n = n.replace(/\b\d{4,}\b/g, '<n>'); // 4. long numbers (4+ digits)
251
+ n = n.replace(/\bafter \d+ attempts?\b/g, 'after <n> attempts'); // 5. attempt phrasing
252
+ n = n.replace(/\s+/g, ' ').trim(); // 6. collapse whitespace
253
+ return n;
254
+ }
255
+
237
256
  export function extractErrorSignature(message: unknown): string {
238
- if (typeof message === 'string') return message.toLowerCase().trim();
257
+ if (typeof message === 'string') return normalizeVolatileTokens(message.toLowerCase().trim());
239
258
  if (!message || typeof message !== 'object') return '';
240
259
  const m = message as {
241
260
  content?: unknown;
242
261
  error?: unknown;
262
+ stopReason?: string;
263
+ usage?: { inputTokens?: number; outputTokens?: number };
243
264
  };
244
265
  const parts: string[] = [];
245
266
  const c = m.content;
@@ -260,5 +281,16 @@ export function extractErrorSignature(message: unknown): string {
260
281
  else parts.push(JSON.stringify(err));
261
282
  }
262
283
  }
263
- return parts.join(' ').toLowerCase().trim();
284
+ const joined = parts.join(' ').toLowerCase().trim();
285
+ const normalized = normalizeVolatileTokens(joined);
286
+ if (
287
+ normalized === '' &&
288
+ m.stopReason === 'error' &&
289
+ m.usage &&
290
+ typeof m.usage === 'object' &&
291
+ (m.usage.inputTokens ?? 0) + (m.usage.outputTokens ?? 0) === 0
292
+ ) {
293
+ return 'bare-0-token-error';
294
+ }
295
+ return normalized;
264
296
  }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * mirror-append.ts — extracted DB-mirror append logic for context-handler.ts
3
+ * (F3 sprint: high-water mark incremental append).
4
+ *
5
+ * Follows the repo's delegate-shell pattern: the context handler shell delegates
6
+ * to this impl module for the mirror-append concern. Returns `rowsProcessed`
7
+ * so callers (including tests) can observe how many new rows were written
8
+ * without adding test-only hooks.
9
+ */
10
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
11
+ import type { DatabaseSync } from "node:sqlite";
12
+ import { appendRawTranscript, type RawTranscriptRow } from "../../src/store/sqlite.js";
13
+ import { computeContentDigest } from "../../src/dedup/digest.js";
14
+ import {
15
+ ensureHwmTable,
16
+ readHwm,
17
+ writeHwm,
18
+ dropHwm,
19
+ } from "./context-hwm.js";
20
+
21
+ export interface MirrorAppendResult {
22
+ rowsProcessed: number;
23
+ }
24
+
25
+ /**
26
+ * Append incoming messages to raw_transcript with HWM incremental support.
27
+ *
28
+ * On fork/rewind (shorter message list or boundary hash mismatch), the HWM
29
+ * is dropped and all messages are reprocessed.
30
+ */
31
+ export function appendMirrorMessages(
32
+ db: DatabaseSync,
33
+ messages: AgentMessage[],
34
+ sessionId: string,
35
+ epochId: string,
36
+ currentTurn: number | undefined,
37
+ ): MirrorAppendResult {
38
+ ensureHwmTable(db);
39
+ const hwm = readHwm(db, sessionId);
40
+
41
+ let tailStart = 0;
42
+ let needDrop = false;
43
+
44
+ if (hwm) {
45
+ if (messages.length <= hwm.lastSeq) {
46
+ // Session was shortened (fork/rewind/clear) — full reprocess.
47
+ needDrop = true;
48
+ } else {
49
+ // Verify boundary integrity: hash of message at hwm.lastSeq-1
50
+ // must match the stored hash.
51
+ const boundaryMsg = messages[hwm.lastSeq - 1];
52
+ const boundaryHash = contentHashOf(
53
+ (boundaryMsg as { content?: unknown }).content,
54
+ );
55
+ if (boundaryHash === hwm.lastContentHash) {
56
+ tailStart = hwm.lastSeq;
57
+ } else {
58
+ needDrop = true;
59
+ }
60
+ }
61
+ }
62
+
63
+ if (needDrop) {
64
+ dropHwm(db, sessionId);
65
+ }
66
+
67
+ // Process tail (or all if tailStart === 0).
68
+ let rowsProcessed = 0;
69
+ for (let i = tailStart; i < messages.length; i++) {
70
+ const raw = toRawRow(messages[i], sessionId, epochId, currentTurn);
71
+ if (raw) {
72
+ appendRawTranscript(db, raw);
73
+ rowsProcessed++;
74
+ }
75
+ }
76
+
77
+ // Write new HWM.
78
+ if (messages.length > 0) {
79
+ const lastMsg = messages[messages.length - 1];
80
+ writeHwm(db, {
81
+ sessionId,
82
+ lastSeq: messages.length,
83
+ lastContentHash: contentHashOf(
84
+ (lastMsg as { content?: unknown }).content,
85
+ ),
86
+ });
87
+ }
88
+
89
+ return { rowsProcessed };
90
+ }
91
+
92
+ /** Single rule for hashing message content on BOTH sides of the HWM
93
+ * (write + boundary check) — a mismatch here silently defeats the
94
+ * incremental path (every event would full-reprocess). null/undefined → "". */
95
+ function contentHashOf(content: unknown): string {
96
+ if (content == null) return "";
97
+ const bytes =
98
+ typeof content === "string"
99
+ ? content
100
+ : JSON.stringify(canonicalize(content));
101
+ return computeContentDigest(bytes).contentHash;
102
+ }
103
+
104
+ /**
105
+ * Canonicalize a value for deterministic JSON serialization (keys sorted).
106
+ * This is the same logic as the inline function in context-handler.ts.
107
+ */
108
+ function canonicalize(value: unknown): unknown {
109
+ if (value === null || value === undefined) return value;
110
+ if (typeof value !== "object") return value;
111
+ if (Array.isArray(value)) return value.map(canonicalize);
112
+ const sorted = Object.keys(value as Record<string, unknown>).sort();
113
+ const out: Record<string, unknown> = {};
114
+ for (const k of sorted) {
115
+ (out as Record<string, unknown>)[k] = canonicalize(
116
+ (value as Record<string, unknown>)[k],
117
+ );
118
+ }
119
+ return out;
120
+ }
121
+
122
+ /** Convert an AgentMessage to a RawTranscriptRow (same logic as toRawTranscriptRow in context-handler.ts). */
123
+ function toRawRow(
124
+ msg: AgentMessage,
125
+ sessionId: string,
126
+ epochId: string,
127
+ currentTurn: number | undefined,
128
+ ): RawTranscriptRow | null {
129
+ const m = msg as {
130
+ role?: string;
131
+ content?: unknown;
132
+ timestamp?: number;
133
+ toolName?: string;
134
+ };
135
+ const content = m.content;
136
+ if (content == null || content === "") return null;
137
+ const contentBytes =
138
+ typeof content === "string"
139
+ ? content
140
+ : JSON.stringify(canonicalize(content));
141
+ return {
142
+ contentHash: computeContentDigest(contentBytes).contentHash,
143
+ sessionId,
144
+ seq: 0, // assigned by appendRawTranscript
145
+ role: m.role ?? "unknown",
146
+ contentBytes,
147
+ toolName: m.toolName ?? null,
148
+ messageTimestamp: m.timestamp ?? null,
149
+ checkpointEpoch: epochId,
150
+ turnIndex: currentTurn ?? null,
151
+ };
152
+ }
153
+
154
+ // Re-export for convenience when the handler only needs the table ensure.
155
+ export { ensureHwmTable, readHwm, writeHwm, dropHwm };
@@ -0,0 +1,79 @@
1
+ /**
2
+ * outage-advisor.ts — R10: calm "provider outage" advisory.
3
+ *
4
+ * When a provider/router flaps (transient errors: timeouts, 5xx, 429s),
5
+ * the extension retries silently and eventually goes quiet after caps. This
6
+ * module sends ONE user-facing advisory per outage episode so the user knows
7
+ * to wait rather than running /clear.
8
+ *
9
+ * Distinct from the poisoned-context /clear advise: the outage advisory is
10
+ * for transient errors where the user's context is fine.
11
+ *
12
+ * PREVENT-PI-003: sends via safeSendUserMessage (user-role only).
13
+ * PREVENT-PI-004: local ctx call, no network.
14
+ */
15
+
16
+ import type { MegaRuntime } from "../mega-runtime.js";
17
+ import { safeSendUserMessage } from "./send-safe.js";
18
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
19
+
20
+ /** R11: optional diagnostic detail passed from the classifier. */
21
+ export interface OutageDetail {
22
+ signal?: string;
23
+ rawText?: string;
24
+ }
25
+
26
+ /**
27
+ * Check the provider-outage advisory condition and fire once per episode.
28
+ *
29
+ * Called from the transient/permanent retry branch of the turn_end handler,
30
+ * AFTER consecutiveErrors is incremented.
31
+ *
32
+ * @param effectiveCategory — must be "transient" for the advisory to fire.
33
+ * @param runtime — the live MegaRuntime (mutated on advisory fire).
34
+ * @param pi — pi ExtensionAPI for safeSendUserMessage.
35
+ * @param config — providerOutageAdviseThreshold config.
36
+ * @param detail — R11: optional signal + rawText for forensics.
37
+ */
38
+ export async function maybeSendProviderOutageAdvisory(
39
+ effectiveCategory: string,
40
+ runtime: MegaRuntime,
41
+ pi: ExtensionAPI,
42
+ config: { providerOutageAdviseThreshold: number; advisoryChannel?: boolean },
43
+ detail?: OutageDetail,
44
+ ): Promise<void> {
45
+ if (effectiveCategory !== "transient") return;
46
+ if (config.providerOutageAdviseThreshold <= 0) return;
47
+ if (runtime.rt.providerOutageAdvised) return;
48
+ if (runtime.rt.consecutiveErrors < config.providerOutageAdviseThreshold)
49
+ return;
50
+
51
+ runtime.rt.providerOutageAdvised = true;
52
+
53
+ runtime.dashboard.event("provider_outage_advised", {
54
+ consecutiveErrors: runtime.rt.consecutiveErrors,
55
+ turnIndex: runtime.currentTurn,
56
+ sessionId: runtime.rt.sessionId,
57
+ ...(detail?.signal !== undefined ? { signal: detail.signal } : {}),
58
+ ...(detail?.rawText !== undefined ? { rawText: detail.rawText } : {}),
59
+ });
60
+
61
+ runtime.logger.info("provider-outage-advised", {
62
+ sessionId: runtime.rt.sessionId,
63
+ consecutiveErrors: runtime.rt.consecutiveErrors,
64
+ turnIndex: runtime.currentTurn,
65
+ ...(detail?.signal !== undefined ? { signal: detail.signal } : {}),
66
+ ...(detail?.rawText !== undefined ? { rawText: detail.rawText } : {}),
67
+ });
68
+
69
+ // Advisory is dashboard-only (events tab + log). No user-visible message —
70
+ // injecting into the conversation scares users and triggers false-positive
71
+ // re-classification of the resulting turn (2026-07-31 incident).
72
+ if (!config.advisoryChannel) {
73
+ // Legacy path (flag OFF): user-role message injection.
74
+ await safeSendUserMessage(
75
+ pi,
76
+ `[mega-compact] the provider is having issues (${runtime.rt.consecutiveErrors} consecutive failures — timeouts/5xx/rate-limits). Retries are bounded and continue automatically; your context is fine — do NOT clear or reset it. Work resumes as soon as the provider recovers.`,
77
+ );
78
+ }
79
+ }