pi-mega-compact 0.13.0 → 0.13.2

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 (212) hide show
  1. package/dist/extensions/dashboard-server/api-contracts/embedder-health.js +11 -0
  2. package/dist/extensions/dashboard-server/api-contracts/endpoints/registry.js +225 -0
  3. package/dist/extensions/dashboard-server/api-contracts/endpoints/types.js +1 -0
  4. package/dist/extensions/dashboard-server/api-contracts/endpoints.js +5 -224
  5. package/dist/extensions/dashboard-server/api-contracts/raptor.js +8 -0
  6. package/dist/extensions/dashboard-server/api-contracts.test/_helpers.js +32 -0
  7. package/dist/extensions/dashboard-server/routes-cache.test/_helpers.js +48 -0
  8. package/dist/extensions/dashboard-server/routes-embedder-health.js +67 -0
  9. package/dist/extensions/dashboard-server/routes-raptor.js +88 -0
  10. package/dist/extensions/dashboard-server/routes-setup.js +1 -1
  11. package/dist/extensions/dashboard-server/routes.js +2 -0
  12. package/dist/extensions/dashboard-server/server.js +5 -1
  13. package/dist/extensions/mega-cache-replay.test/_helpers.js +175 -0
  14. package/dist/extensions/mega-commands/dataCommands.js +151 -0
  15. package/dist/extensions/mega-commands/helpers.js +61 -0
  16. package/dist/extensions/mega-commands/historyCommands.js +97 -0
  17. package/dist/extensions/mega-commands/setupCommand.js +200 -0
  18. package/dist/extensions/mega-commands.js +14 -499
  19. package/dist/extensions/mega-compact-s38.test/_helpers.js +194 -0
  20. package/dist/extensions/mega-compact.js +12 -2
  21. package/dist/extensions/mega-compact.test/_helpers.js +225 -0
  22. package/dist/extensions/mega-events/agent-handlers/agentEndHandler.js +211 -0
  23. package/dist/extensions/mega-events/agent-handlers/turnEndHandler/cacheStripe.js +49 -0
  24. package/dist/extensions/mega-events/agent-handlers/turnEndHandler/contextHealth.js +33 -0
  25. package/dist/extensions/mega-events/agent-handlers/turnEndHandler/errorRetry.js +387 -0
  26. package/dist/extensions/mega-events/agent-handlers/turnEndHandler/event.js +7 -0
  27. package/dist/extensions/mega-events/agent-handlers/turnEndHandler/gameScoring.js +55 -0
  28. package/dist/extensions/mega-events/agent-handlers/turnEndHandler/lengthStop.js +12 -0
  29. package/dist/extensions/mega-events/agent-handlers/turnEndHandler/memoryReview.js +22 -0
  30. package/dist/extensions/mega-events/agent-handlers/turnEndHandler/recordTurnRow.js +38 -0
  31. package/dist/extensions/mega-events/agent-handlers/turnEndHandler.js +36 -0
  32. package/dist/extensions/mega-events/agent-handlers.js +4 -799
  33. package/dist/extensions/mega-events/context-handler/afterCompact.js +163 -0
  34. package/dist/extensions/mega-events/context-handler/messageText.js +12 -0
  35. package/dist/extensions/mega-events/context-handler/tailResult.js +46 -0
  36. package/dist/extensions/mega-events/context-handler.js +11 -198
  37. package/dist/extensions/mega-events/separated-prompt.test/_helpers.js +25 -0
  38. package/dist/src/config.js +2 -0
  39. package/dist/src/dedup-engine.test/_helpers.js +55 -0
  40. package/dist/src/e2e.test/_helpers.js +52 -0
  41. package/dist/src/embedder.js +1 -0
  42. package/dist/src/httpEmbedder.js +6 -0
  43. package/dist/src/hyde.js +146 -0
  44. package/dist/src/importance.test/_helpers.js +5 -0
  45. package/dist/src/memoryGraph/sources/checkpoints.js +78 -0
  46. package/dist/src/memoryGraph/sources/edges.js +17 -0
  47. package/dist/src/memoryGraph/sources/flags.js +22 -0
  48. package/dist/src/memoryGraph/sources/helpers.js +14 -0
  49. package/dist/src/memoryGraph/sources/memories.js +88 -0
  50. package/dist/src/memoryGraph/sources/raptor.js +26 -0
  51. package/dist/src/memoryGraph/sources/turns.js +176 -0
  52. package/dist/src/memoryGraph/sources.js +15 -441
  53. package/dist/src/memoryGraph-gates.test/_helpers.js +120 -0
  54. package/dist/src/ratio.bench.test/_helpers.js +198 -0
  55. package/dist/src/recall/async.js +112 -0
  56. package/dist/src/recall/format.js +149 -0
  57. package/dist/src/recall/memory.js +62 -0
  58. package/dist/src/recall/reformulate.js +82 -0
  59. package/dist/src/recall/sync.js +169 -0
  60. package/dist/src/recall/types.js +1 -0
  61. package/dist/src/recall.js +13 -530
  62. package/dist/src/store/sqlite/schema/core.js +232 -0
  63. package/dist/src/store/sqlite/schema/game.js +65 -0
  64. package/dist/src/store/sqlite/schema/plan-v2.js +107 -0
  65. package/dist/src/store/sqlite/schema/turns.js +59 -0
  66. package/dist/src/store/sqlite/schema.js +8 -441
  67. package/dist/src/store/turns/contract-compliance.test/_helpers.js +21 -0
  68. package/dist/src/store/turns/sqlite-store/admin.js +171 -0
  69. package/dist/src/store/turns/sqlite-store/ctx.js +1 -0
  70. package/dist/src/store/turns/sqlite-store/read.js +111 -0
  71. package/dist/src/store/turns/sqlite-store/rows.js +42 -0
  72. package/dist/src/store/turns/sqlite-store/write.js +102 -0
  73. package/dist/src/store/turns/sqlite-store.js +31 -367
  74. package/dist/src/vectorStore/class.js +356 -0
  75. package/dist/src/vectorStore/hash.js +10 -0
  76. package/dist/src/vectorStore/types.js +2 -0
  77. package/dist/src/vectorStore.js +8 -359
  78. package/dist/src/vectorStore.test/_helpers.js +17 -0
  79. package/extensions/dashboard-client/dist/assets/{CacheTab-BZNnKhh5.js → CacheTab-DPRHjYZ0.js} +2 -2
  80. package/extensions/dashboard-client/dist/assets/{CacheTab-BZNnKhh5.js.map → CacheTab-DPRHjYZ0.js.map} +1 -1
  81. package/extensions/dashboard-client/dist/assets/{EventsTab-CzF5L42U.js → EventsTab-CgwYq-Qf.js} +2 -2
  82. package/extensions/dashboard-client/dist/assets/{EventsTab-CzF5L42U.js.map → EventsTab-CgwYq-Qf.js.map} +1 -1
  83. package/extensions/dashboard-client/dist/assets/{HealthTab-BLpidMrX.js → HealthTab-BgOCjVzR.js} +2 -2
  84. package/extensions/dashboard-client/dist/assets/{HealthTab-BLpidMrX.js.map → HealthTab-BgOCjVzR.js.map} +1 -1
  85. package/extensions/dashboard-client/dist/assets/MaintenanceTab-Yw1yFpsy.js +2 -0
  86. package/extensions/dashboard-client/dist/assets/MaintenanceTab-Yw1yFpsy.js.map +1 -0
  87. package/extensions/dashboard-client/dist/assets/MemoryMapTab-yHUX7Yzi.js +2 -0
  88. package/extensions/dashboard-client/dist/assets/MemoryMapTab-yHUX7Yzi.js.map +1 -0
  89. package/extensions/dashboard-client/dist/assets/{MetricsTab-B0PCysqs.js → MetricsTab-CcH9fP8P.js} +2 -2
  90. package/extensions/dashboard-client/dist/assets/{MetricsTab-B0PCysqs.js.map → MetricsTab-CcH9fP8P.js.map} +1 -1
  91. package/extensions/dashboard-client/dist/assets/{OverviewTab-DsOhqFu4.js → OverviewTab-BOs8ZNev.js} +2 -2
  92. package/extensions/dashboard-client/dist/assets/{OverviewTab-DsOhqFu4.js.map → OverviewTab-BOs8ZNev.js.map} +1 -1
  93. package/extensions/dashboard-client/dist/assets/{ReposTab-B3YKYuOf.js → ReposTab-B-MfSPvg.js} +2 -2
  94. package/extensions/dashboard-client/dist/assets/{ReposTab-B3YKYuOf.js.map → ReposTab-B-MfSPvg.js.map} +1 -1
  95. package/extensions/dashboard-client/dist/assets/{SessionsTab-B96FWcrC.js → SessionsTab-BmeN649Q.js} +2 -2
  96. package/extensions/dashboard-client/dist/assets/{SessionsTab-B96FWcrC.js.map → SessionsTab-BmeN649Q.js.map} +1 -1
  97. package/extensions/dashboard-client/dist/assets/SetupTab-nOknoph5.js +2 -0
  98. package/extensions/dashboard-client/dist/assets/SetupTab-nOknoph5.js.map +1 -0
  99. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-BfkUVTvA.js → TimeSavedCard-DnPg0L0z.js} +2 -2
  100. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-BfkUVTvA.js.map → TimeSavedCard-DnPg0L0z.js.map} +1 -1
  101. package/extensions/dashboard-client/dist/assets/{TopicsTab-DLRsZmXJ.js → TopicsTab-BODHOg_b.js} +2 -2
  102. package/extensions/dashboard-client/dist/assets/{TopicsTab-DLRsZmXJ.js.map → TopicsTab-BODHOg_b.js.map} +1 -1
  103. package/extensions/dashboard-client/dist/assets/{TurnsTab-DKGU2Bf6.js → TurnsTab-BK0I7hKr.js} +2 -2
  104. package/extensions/dashboard-client/dist/assets/{TurnsTab-DKGU2Bf6.js.map → TurnsTab-BK0I7hKr.js.map} +1 -1
  105. package/extensions/dashboard-client/dist/assets/{index-D-lPLRWB.js → index-mOlljTFI.js} +10 -10
  106. package/extensions/dashboard-client/dist/assets/index-mOlljTFI.js.map +1 -0
  107. package/extensions/dashboard-client/dist/assets/{useSSE-ClbbcgIp.js → useSSE-BYOtv1-3.js} +2 -2
  108. package/extensions/dashboard-client/dist/assets/{useSSE-ClbbcgIp.js.map → useSSE-BYOtv1-3.js.map} +1 -1
  109. package/extensions/dashboard-client/dist/index.html +1 -1
  110. package/extensions/dashboard-client/src/App.tsx +0 -4
  111. package/extensions/dashboard-client/src/api/client.ts +16 -0
  112. package/extensions/dashboard-client/src/tabs/MaintenanceTab/ActionsCard.tsx +178 -0
  113. package/extensions/dashboard-client/src/tabs/MaintenanceTab/DbStatsCard.tsx +140 -0
  114. package/extensions/dashboard-client/src/tabs/MaintenanceTab/DebugBundleCard.tsx +109 -0
  115. package/extensions/dashboard-client/src/tabs/MaintenanceTab/HealthMitigationCard.tsx +98 -0
  116. package/extensions/dashboard-client/src/tabs/MaintenanceTab/SchemaHealthCard.tsx +108 -0
  117. package/extensions/dashboard-client/src/tabs/MaintenanceTab.tsx +12 -598
  118. package/extensions/dashboard-client/src/tabs/MemoryMapTab/MemoryMapView.tsx +476 -0
  119. package/extensions/dashboard-client/src/tabs/MemoryMapTab/RaptorTreeView.tsx +163 -0
  120. package/extensions/dashboard-client/src/tabs/MemoryMapTab.tsx +56 -466
  121. package/extensions/dashboard-client/src/tabs/SetupTab/EmbedderHealthCard.tsx +109 -0
  122. package/extensions/dashboard-client/src/tabs/SetupTab/EmbedderSetup.tsx +468 -0
  123. package/extensions/dashboard-client/src/tabs/SetupTab.tsx +23 -484
  124. package/extensions/dashboard-server/api-contracts/embedder-health.ts +32 -0
  125. package/extensions/dashboard-server/api-contracts/endpoints/registry.ts +360 -0
  126. package/extensions/dashboard-server/api-contracts/endpoints/types.ts +350 -0
  127. package/extensions/dashboard-server/api-contracts/endpoints.ts +27 -648
  128. package/extensions/dashboard-server/api-contracts/index.ts +6 -0
  129. package/extensions/dashboard-server/api-contracts/raptor.ts +49 -0
  130. package/extensions/dashboard-server/api-contracts.test/_helpers.ts +47 -0
  131. package/extensions/dashboard-server/routes-cache.test/_helpers.ts +94 -0
  132. package/extensions/dashboard-server/routes-embedder-health.ts +77 -0
  133. package/extensions/dashboard-server/routes-raptor.ts +128 -0
  134. package/extensions/dashboard-server/routes-setup.ts +1 -1
  135. package/extensions/dashboard-server/routes.ts +2 -0
  136. package/extensions/dashboard-server/server.ts +4 -0
  137. package/extensions/mega-cache-replay.test/_helpers.ts +188 -0
  138. package/extensions/mega-commands/dataCommands.ts +169 -0
  139. package/extensions/mega-commands/helpers.ts +62 -0
  140. package/extensions/mega-commands/historyCommands.ts +117 -0
  141. package/extensions/mega-commands/setupCommand.ts +235 -0
  142. package/extensions/mega-commands.ts +25 -538
  143. package/extensions/mega-compact-s38.test/_helpers.ts +201 -0
  144. package/extensions/mega-compact.test/_helpers.ts +237 -0
  145. package/extensions/mega-compact.ts +12 -2
  146. package/extensions/mega-events/agent-handlers/agentEndHandler.ts +238 -0
  147. package/extensions/mega-events/agent-handlers/turnEndHandler/cacheStripe.ts +74 -0
  148. package/extensions/mega-events/agent-handlers/turnEndHandler/contextHealth.ts +50 -0
  149. package/extensions/mega-events/agent-handlers/turnEndHandler/errorRetry.ts +421 -0
  150. package/extensions/mega-events/agent-handlers/turnEndHandler/event.ts +16 -0
  151. package/extensions/mega-events/agent-handlers/turnEndHandler/gameScoring.ts +73 -0
  152. package/extensions/mega-events/agent-handlers/turnEndHandler/lengthStop.ts +29 -0
  153. package/extensions/mega-events/agent-handlers/turnEndHandler/memoryReview.ts +42 -0
  154. package/extensions/mega-events/agent-handlers/turnEndHandler/recordTurnRow.ts +61 -0
  155. package/extensions/mega-events/agent-handlers/turnEndHandler.ts +64 -0
  156. package/extensions/mega-events/agent-handlers.ts +15 -861
  157. package/extensions/mega-events/context-handler/afterCompact.ts +213 -0
  158. package/extensions/mega-events/context-handler/messageText.ts +20 -0
  159. package/extensions/mega-events/context-handler/tailResult.ts +63 -0
  160. package/extensions/mega-events/context-handler.ts +17 -235
  161. package/extensions/mega-events/separated-prompt.test/_helpers.ts +35 -0
  162. package/package.json +1 -1
  163. package/src/config.ts +4 -0
  164. package/src/dedup-engine.test/_helpers.ts +79 -0
  165. package/src/e2e.test/_helpers.ts +59 -0
  166. package/src/embedder.ts +4 -0
  167. package/src/httpEmbedder.ts +7 -0
  168. package/src/hyde.ts +162 -0
  169. package/src/importance.test/_helpers.ts +5 -0
  170. package/src/memoryGraph/sources/checkpoints.ts +99 -0
  171. package/src/memoryGraph/sources/edges.ts +23 -0
  172. package/src/memoryGraph/sources/flags.ts +26 -0
  173. package/src/memoryGraph/sources/helpers.ts +13 -0
  174. package/src/memoryGraph/sources/memories.ts +108 -0
  175. package/src/memoryGraph/sources/raptor.ts +37 -0
  176. package/src/memoryGraph/sources/turns.ts +226 -0
  177. package/src/memoryGraph/sources.ts +19 -544
  178. package/src/memoryGraph-gates.test/_helpers.ts +164 -0
  179. package/src/ratio.bench.test/_helpers.ts +268 -0
  180. package/src/recall/async.ts +142 -0
  181. package/src/recall/format.ts +173 -0
  182. package/src/recall/memory.ts +90 -0
  183. package/src/recall/reformulate.ts +111 -0
  184. package/src/recall/sync.ts +196 -0
  185. package/src/recall/types.ts +63 -0
  186. package/src/recall.ts +25 -712
  187. package/src/store/sqlite/schema/core.ts +233 -0
  188. package/src/store/sqlite/schema/game.ts +66 -0
  189. package/src/store/sqlite/schema/plan-v2.ts +108 -0
  190. package/src/store/sqlite/schema/turns.ts +60 -0
  191. package/src/store/sqlite/schema.ts +13 -441
  192. package/src/store/turns/contract-compliance.test/_helpers.ts +38 -0
  193. package/src/store/turns/sqlite-store/admin.ts +249 -0
  194. package/src/store/turns/sqlite-store/ctx.ts +14 -0
  195. package/src/store/turns/sqlite-store/read.ts +174 -0
  196. package/src/store/turns/sqlite-store/rows.ts +55 -0
  197. package/src/store/turns/sqlite-store/write.ts +193 -0
  198. package/src/store/turns/sqlite-store.ts +33 -514
  199. package/src/vectorStore/class.ts +433 -0
  200. package/src/vectorStore/hash.ts +11 -0
  201. package/src/vectorStore/types.ts +58 -0
  202. package/src/vectorStore.test/_helpers.ts +20 -0
  203. package/src/vectorStore.ts +13 -489
  204. package/extensions/dashboard-client/dist/assets/ConfigTab-DG0WkuuG.js +0 -2
  205. package/extensions/dashboard-client/dist/assets/ConfigTab-DG0WkuuG.js.map +0 -1
  206. package/extensions/dashboard-client/dist/assets/MaintenanceTab-BQF7W7xX.js +0 -2
  207. package/extensions/dashboard-client/dist/assets/MaintenanceTab-BQF7W7xX.js.map +0 -1
  208. package/extensions/dashboard-client/dist/assets/MemoryMapTab-CPtHLv0A.js +0 -2
  209. package/extensions/dashboard-client/dist/assets/MemoryMapTab-CPtHLv0A.js.map +0 -1
  210. package/extensions/dashboard-client/dist/assets/SetupTab-hbzQ_NZv.js +0 -2
  211. package/extensions/dashboard-client/dist/assets/SetupTab-hbzQ_NZv.js.map +0 -1
  212. package/extensions/dashboard-client/dist/assets/index-D-lPLRWB.js.map +0 -1
@@ -1,18 +1,5 @@
1
- import { piCompactWouldNoop, runMemoryReview } from "../mega-pipeline.js";
2
- import { memoryReviewCadence } from "../mega-config.js";
3
- import { recordScore, readLatestCacheHitPct } from "../../src/store/sqlite.js";
4
- import { evaluateAndUnlockAchievements } from "../../src/store/sqlite/game-achievements.js";
5
- import { ensureConversationIdFor, recordTurnWrite, } from "../mega-turn-store.js";
6
- import { isMegaCache } from "../../src/game/scoring.js";
7
- import { resolveRepoRoot } from "../mega-config.js";
8
- import { classifyError, classifyErrorDetailed, errorRetryBackoffMs, extractErrorSignature, isKnownRetryableTransient, } from "./error-classifier.js";
9
- import { safeSendUserMessage } from "./send-safe.js";
10
- import { maybeSendProviderOutageAdvisory } from "./outage-advisor.js";
11
- import { vectorStats } from "../../src/vectorStore.js";
12
- import { defaultEmbedder } from "../../src/embedder.js";
13
- import { storeTopicEmbedding, loadTopicEmbedding, detectTopicShift, } from "./separated-prompt.js";
14
- import { refreshStripeAssignments as writeStripeAssignments, } from "../../src/cache-stripe-impl.js";
15
- import { handleTurnEndHealth } from "./health-handler.js";
1
+ import { handleAgentEnd } from "./agent-handlers/agentEndHandler.js";
2
+ import { handleTurnEnd } from "./agent-handlers/turnEndHandler.js";
16
3
  /** Register agent/turn tracking event handlers. */
17
4
  export function registerAgentHandlers(pi, runtime, config) {
18
5
  // ---- Agent tracking for real-time widget + status-line updates ---------
@@ -26,214 +13,7 @@ export function registerAgentHandlers(pi, runtime, config) {
26
13
  runtime.setStatus(ctx, `mega-compact: ▶ ${runtime.activeAgents} agent${runtime.activeAgents === 1 ? "" : "s"}`);
27
14
  runtime.snapshot(ctx);
28
15
  });
29
- pi.on("agent_end", async (_event, ctx) => {
30
- runtime.activeAgents = Math.max(0, runtime.activeAgents - 1);
31
- runtime.dashboard.event("agent_end", {
32
- activeAgents: runtime.activeAgents,
33
- });
34
- if (runtime.activeAgents > 0) {
35
- runtime.setStatus(ctx, `mega-compact: ▶ ${runtime.activeAgents} agent${runtime.activeAgents === 1 ? "" : "s"}`);
36
- }
37
- else {
38
- runtime.setStatus(ctx, config.auto ? "mega-compact: ready" : "mega-compact: manual only");
39
- }
40
- // S16 continuation fallback: if the turn settled idle right after a live-trim
41
- // compaction AND there is queued work AND we haven't nudged recently, nudge
42
- // once so the agent continues (the live trim should make this rare). Guarded
43
- // to never busy-loop: one nudge per 30s, only when truly idle + queued.
44
- if ((config.auto || config.autoContinueLengthStop) &&
45
- runtime.activeAgents === 0) {
46
- try {
47
- const idle = ctx.isIdle?.() ?? true;
48
- const queued = ctx.hasPendingMessages?.() ?? false;
49
- const now = Date.now();
50
- // S38.5: read LIVE pressure from ctx.getContextUsage() instead of the
51
- // stale runtime.lastCtxTokens (only updated by the `context` event).
52
- // agent_end may fire without a preceding context event this turn (e.g.
53
- // a sub-agent settling), so the cached value can be null/stale and the
54
- // durable-trim branch would be unreachable. ctx.getContextUsage() is the
55
- // authoritative live reading (mirrors context-handler.ts:86). Fall back
56
- // to the cached value only if the ctx omits it.
57
- const liveUsage = ctx.getContextUsage?.();
58
- const liveTokens = typeof liveUsage?.tokens === "number"
59
- ? liveUsage.tokens
60
- : (runtime.lastCtxTokens ?? 0);
61
- // Keep the cache fresh for snapshot()/diag regardless of which source we use.
62
- if (typeof liveUsage?.tokens === "number") {
63
- runtime.lastCtxTokens = liveUsage.tokens;
64
- }
65
- if (typeof liveUsage?.percent === "number") {
66
- runtime.lastCtxPercent = liveUsage.percent;
67
- }
68
- if (typeof liveUsage?.contextWindow === "number") {
69
- runtime.lastCtxWindow = liveUsage.contextWindow;
70
- }
71
- // DIAG (team-run relief): surface whether the agent is idle + over
72
- // threshold at agent_end so we can see if a mid-run durable-trim trigger
73
- // *should* have fired but didn't.
74
- const overThreshold = liveTokens >= runtime.effectiveThreshold;
75
- runtime.diagAgentEndIdle++;
76
- runtime.logger.info("agent-end-idle", {
77
- sessionId: runtime.rt.sessionId,
78
- idle,
79
- queued,
80
- overThreshold,
81
- ctxPct: runtime.lastCtxPercent,
82
- ctxTokens: runtime.lastCtxTokens,
83
- thresholdTokens: config.thresholdTokens,
84
- wouldNudge: idle &&
85
- (queued || overThreshold) &&
86
- now >= runtime.resumeNudgeUntil,
87
- });
88
- // S16+S24: MID-RUN DURABLE TRIM. During a long team run (sub-agents),
89
- // pi's native durable compaction only fires from _checkCompaction at
90
- // PARENT settle (agent-session.js:760/844), so the on-disk transcript +
91
- // context meter balloon to ~150k and never relieve until the very end
92
- // ("compacts but doesn't resume"). agent_end with activeAgents===0 is a
93
- // SAFE, settled point: calling ctx.compact() here does NOT abort an
94
- // in-flight turn (the S16 danger is only mid-turn). ctx.compact() runs
95
- // pi's flow, which fires our session_before_compact handler to supply
96
- // the durable trim (truncates the transcript from firstKeptEntryId).
97
- // Guarded three ways: only when truly idle + over threshold, only when
98
- // pi would actually compact (piCompactWouldNoop skips the user-facing
99
- // no-op throw), and debounced (one durable trim per 2s) to avoid
100
- // thrashing the transcript while sub-agents keep settling.
101
- //
102
- // FIX "compacts but doesn't resume": the manual ctx.compact() path
103
- // STOPS the agent loop (agent-session.js:1345). The old resume-nudge
104
- // was gated on `queued`, so when a sub-agent settled with no
105
- // *immediately* queued message, the trim fired but the nudge did not,
106
- // and the (stopped) session hung. The trim still fires on
107
- // `idle && overThreshold` — we intentionally do NOT add a `!queued`
108
- // guard, because that would suppress mid-run relief exactly during
109
- // team-run waves where queued is usually true and relief is needed
110
- // most. Instead we DECOUPLE the nudge from `queued`: after a durable
111
- // trim we ALWAYS nudge so the agent reliably restarts. Debounced 30s.
112
- let didDurableTrim = false;
113
- if (config.auto &&
114
- idle &&
115
- overThreshold &&
116
- now >= runtime.debounceUntil) {
117
- // COMPACT-DEDUP FIX: skip the manual durable-trim trigger when pi's
118
- // NATIVE auto-compaction just fired (or is in-flight). pi emits
119
- // agent_end BEFORE its own _checkCompaction (per its docstring:
120
- // "Called after agent_end and before prompt submission"), so a
121
- // synchronous `piCompactWouldNoop` branch check misses a native
122
- // compaction that hasn't appended its entry yet — calling
123
- // ctx.compact() then races with pi and throws "Already compacted"
124
- // to the user. The `lastNativeCompactAt` cooldown (updated by the
125
- // session_compact listener for EVERY compaction, native or
126
- // extension-supplied) closes that race window.
127
- //
128
- // S38.5: strict race guard widens the cooldown 10s -> 30s AND defers
129
- // ctx.compact() via setTimeout(500) with a re-check, so pi's
130
- // about-to-run native _checkCompaction can append its `compaction`
131
- // branch entry first (closes the first-race-in-burst window). Gated
132
- // by MEGACOMPACT_RACE_GUARD_STRICT (default true); false reverts to
133
- // the v0.7.4 synchronous 10s guard. Mirrors the legacy path in
134
- // context-handler.ts:258-287 so both call sites stay in sync.
135
- const cooldownMs = config.raceGuardStrict ? 30_000 : 10_000;
136
- const sinceCompact = now - (runtime.rt.lastNativeCompactAt ?? 0);
137
- // CRITICAL-OVER ESCAPE HATCH: when context is critically over the
138
- // window (>= 90%), force the durable ctx.compact() even if
139
- // piCompactWouldNoop says it would no-op ("Already compacted").
140
- // Without this, the on-disk transcript never truncates and the
141
- // session stays overflowed on every resume — the "Already
142
- // compacted" + overflow death-spiral (2026-08-01 incident). The
143
- // cooldown still applies (we don't spam compact), but the no-op
144
- // gate is bypassed when critical. pi's ctx.compact() may throw
145
- // "Already compacted" in the truly-no-op case — wrapped in
146
- // try/catch so the throw is non-fatal.
147
- const criticalOver = (runtime.lastCtxPercent ?? 0) >= 90;
148
- if (sinceCompact < cooldownMs) {
149
- runtime.diagAgentEndDurableSkipRecent++;
150
- }
151
- else if (criticalOver || !piCompactWouldNoop(ctx)) {
152
- runtime.debounceUntil = now + 2000;
153
- runtime.diagAgentEndDurable++;
154
- runtime.logger.info("agent-end-durable-trigger", {
155
- sessionId: runtime.rt.sessionId,
156
- ctxTokens: runtime.lastCtxTokens,
157
- thresholdTokens: config.thresholdTokens,
158
- queued,
159
- });
160
- if (config.raceGuardStrict) {
161
- // Strict: defer ctx.compact() with a re-check so pi's
162
- // about-to-run native _checkCompaction can append its
163
- // `compaction` branch entry first. setTimeout(500) — pi's
164
- // compaction-summary append is async I/O, so queueMicrotask
165
- // would re-check before it lands.
166
- const stamp = runtime.rt.lastNativeCompactAt;
167
- const liveSid = runtime.rt.sessionId;
168
- const liveCritical = criticalOver;
169
- setTimeout(() => {
170
- try {
171
- if (runtime.rt.sessionId !== liveSid)
172
- return; // session reset
173
- // IMPORTANT: recompute Date.now() inside the timeout.
174
- // `now` above is the durable-trim handler's timestamp and can be
175
- // ~500ms stale by the time this callback runs.
176
- const since2 = Date.now() - (runtime.rt.lastNativeCompactAt ?? 0);
177
- if (runtime.rt.lastNativeCompactAt !== stamp &&
178
- since2 < cooldownMs)
179
- return;
180
- // CRITICAL-OVER ESCAPE HATCH: bypass the no-op gate when
181
- // critical (captured at handler time) so the durable trim fires.
182
- if (!liveCritical && piCompactWouldNoop(ctx))
183
- return;
184
- ctx.compact({
185
- customInstructions: undefined,
186
- }); // guardrails-allow PREVENT-PI-004: local ctx.compact() — no network; deferred + re-validated. May throw "Already compacted" when the escape hatch forces it — caught below.
187
- }
188
- catch {
189
- /* non-fatal: "Already compacted" throws are expected when the critical-over hatch forces a no-op compact */
190
- }
191
- }, 500);
192
- }
193
- else {
194
- try {
195
- ctx.compact({ customInstructions: undefined }); // guardrails-allow PREVENT-PI-004: local ctx.compact() — no network; agent settled so no in-flight abort. May throw "Already compacted" when the critical-over escape hatch forces it — caught.
196
- }
197
- catch {
198
- /* non-fatal */
199
- }
200
- }
201
- didDurableTrim = true;
202
- }
203
- }
204
- // Restart the agent after a mid-run durable trim (which stopped it), or
205
- // when it settled idle with queued work. Decoupled from `queued` for the
206
- // durable-trim case — see FIX note above. Debounced 30s; never blocks.
207
- const lengthStop = config.autoContinueLengthStop && runtime.rt.lengthStopPending;
208
- if (idle &&
209
- now >= runtime.resumeNudgeUntil &&
210
- ((config.auto && (didDurableTrim || queued)) || lengthStop)) {
211
- runtime.resumeNudgeUntil = now + 30_000;
212
- if (runtime.rt.lengthStopPending) {
213
- runtime.rt.lengthStopPending = false; // one-shot: never re-fire for same stop
214
- runtime.dashboard.event("length_stop_continue", {
215
- turnIndex: runtime.currentTurn,
216
- });
217
- runtime.logger.info("length_stop_continue", {
218
- sessionId: runtime.rt.sessionId,
219
- didDurableTrim,
220
- queued,
221
- });
222
- }
223
- // S28: when a length-stop (max-output-token truncation) fired WITHOUT a durable trim, do NOT claim a compaction happened
224
- // (nothing was compacted on the low-pressure length path). Branch the message so the nudge matches reality.
225
- const nudgeMsg = lengthStop && !didDurableTrim
226
- ? "[mega-compact] the last response hit the output-token cap; continue from where it stopped."
227
- : "[mega-compact] continue from the compacted context above.";
228
- await safeSendUserMessage(pi, nudgeMsg);
229
- }
230
- }
231
- catch {
232
- /* non-fatal: a failed nudge never blocks */
233
- }
234
- }
235
- runtime.snapshot(ctx);
236
- });
16
+ pi.on("agent_end", (_event, ctx) => handleAgentEnd(ctx, pi, runtime, config));
237
17
  pi.on("turn_start", async (event, ctx) => {
238
18
  runtime.currentTurn = event.turnIndex;
239
19
  runtime.rt.lengthStopPending = false; // S28: re-arm defensively each user turn
@@ -250,580 +30,5 @@ export function registerAgentHandlers(pi, runtime, config) {
250
30
  runtime.dashboard.event("turn_start", { turnIndex: event.turnIndex });
251
31
  runtime.snapshot(ctx);
252
32
  });
253
- pi.on("turn_end", async (event, ctx) => {
254
- runtime.dashboard.event("turn_end", { turnIndex: event.turnIndex });
255
- runtime.snapshot(ctx);
256
- runtime.lastErrorCategory = null;
257
- // S53: consume staged recall blocks ONLY if they were actually injected
258
- // into a view this turn. If no context event fired (edge: turn ended
259
- // before any LLM call), recallInjectedThisTurn stays false and the blocks
260
- // remain staged for the next turn's first context event.
261
- if (config.recallTailInject && runtime.rt.recallInjectedThisTurn) {
262
- runtime.pendingRecallBlock = undefined;
263
- runtime.pendingMemoryRecallBlock = undefined;
264
- runtime.rt.recallInjectedThisTurn = false;
265
- }
266
- // S43 (per-turn tracking): record one turn row with the cached metrics so
267
- // the turn layer is queryable + forkable. Best-effort + non-fatal: a write
268
- // failure never breaks the agent loop. The catch logs the error (structured
269
- // JSON line to events.log) so a recurring turn-write failure is diagnosable
270
- // instead of silently producing a blank Turns tab.
271
- try {
272
- const convId = ensureConversationIdFor(config, runtime.rt.sessionId, runtime.currentStateDir);
273
- recordTurnWrite(config, {
274
- conversationId: convId,
275
- sessionId: runtime.rt.sessionId,
276
- turnIndex: event.turnIndex,
277
- role: event.role ?? "assistant",
278
- endedAt: Date.now(),
279
- startedAt: undefined,
280
- ctxTokens: runtime.lastCtxTokens ?? undefined,
281
- ctxPercent: runtime.lastCtxPercent ?? undefined,
282
- pressureBand: runtime.pressureBand ?? undefined,
283
- modelId: runtime.currentModel?.modelId ?? undefined,
284
- }, runtime.currentStateDir);
285
- runtime.dashboard.event("turn_written", {
286
- turnIndex: event.turnIndex,
287
- conversationId: convId,
288
- pressureBand: runtime.pressureBand ?? null,
289
- turnsDbEnabled: config.turnsDbEnabled,
290
- });
291
- }
292
- catch (e) {
293
- runtime.dashboard.event("turn_write_failed", {
294
- turnIndex: event.turnIndex,
295
- turnsDbEnabled: config.turnsDbEnabled,
296
- error: e instanceof Error ? e.message : String(e),
297
- stack: e instanceof Error ? e.stack?.split("\n").slice(0, 3).join(" | ") : undefined,
298
- });
299
- }
300
- // S33: game-mode scoring — record turns + cache metrics per repo, and arm
301
- // the MEGA CACHE flare (oopsie gag) when the real dedup hit rate exceeds
302
- // 100%. Gated behind game_mode_on (no scoring when off). Best-effort +
303
- // non-fatal: a scoring failure must never break the agent loop (G6).
304
- try {
305
- if (runtime.getCachedGameState().game_mode_on) {
306
- const repo = resolveRepoRoot(ctx.cwd) ?? runtime.currentStateDir;
307
- const st = vectorStats(runtime.store, runtime.rt.sessionId);
308
- // C.3: prefer provider cache hit rate, fall back to dedup hit rate
309
- const providerPct = readLatestCacheHitPct(runtime.currentStateDir);
310
- const cachePct = providerPct != null ? providerPct : st.dedupHitRate * 100;
311
- const modelId = runtime.currentModel?.modelId ?? "unknown";
312
- recordScore(runtime.currentStateDir, {
313
- repo_root: repo,
314
- metric: "turns",
315
- value: runtime.currentTurn,
316
- meta: { modelId, turnIndex: event.turnIndex },
317
- });
318
- recordScore(runtime.currentStateDir, {
319
- repo_root: repo,
320
- metric: "cache",
321
- value: cachePct,
322
- meta: {
323
- hits: st.dedupCollapsed + runtime.rt.recallInjections,
324
- lookups: st.checkpointCount,
325
- },
326
- });
327
- // MEGA CACHE: the real ratio >1 (dedupHitRate>1) → trophy row + flare.
328
- if (isMegaCache(cachePct)) {
329
- recordScore(runtime.currentStateDir, {
330
- repo_root: repo,
331
- metric: "mega_cache",
332
- value: cachePct,
333
- meta: { peakPct: cachePct, firstSeenTs: Date.now() },
334
- });
335
- runtime.armMegaCacheFlare(cachePct);
336
- }
337
- // S35: evaluate achievements after scoring; arm a one-time flare for
338
- // the newly-unlocked ones (consumed by snapshot() → widget toast).
339
- const newTitles = evaluateAndUnlockAchievements(runtime.currentStateDir);
340
- if (newTitles.length)
341
- runtime.armAchievementFlare(newTitles);
342
- }
343
- }
344
- catch {
345
- /* non-fatal: scoring must never break the agent loop */
346
- }
347
- // S20+S24: auto-review the conversation and persist durable memories. The
348
- // review cadence scales with pressure (memoryReviewCadence): as context
349
- // fills, the conversation is reviewed more often so memories keep pace with
350
- // faster churn. Best-effort + non-fatal: a review failure must never break
351
- // the agent loop. Debounced by the pressure-adjusted interval.
352
- if (config.memoryAutoReview && runtime.currentTurn > 0) {
353
- const cadence = memoryReviewCadence(runtime.pressureBand, config.memoryReviewInterval);
354
- if (runtime.currentTurn % cadence === 0) {
355
- // S20+S24: review the conversation and persist durable memories. The
356
- // cadence scales with pressure (memoryReviewCadence): as context fills,
357
- // the conversation is reviewed more often so memories keep pace with
358
- // faster churn. Shared runMemoryReview body (also used on compact).
359
- const entries = ctx.sessionManager.getEntries();
360
- const view = runtime.engineView(entries.flatMap((e) => (e.message ? [e.message] : [])));
361
- await runMemoryReview(runtime, view, "turn");
362
- }
363
- }
364
- // S28: detect max-output-token truncation. event.message.stopReason is the
365
- // pi-ai StopReason union; 'length' == generation hit max_tokens OUTPUT cap
366
- // (INPUT-orthogonal to context-window overflow). Arm the agent_end nudge.
367
- if (config.autoContinueLengthStop &&
368
- event.message.role === "assistant" &&
369
- event.message.stopReason === "length") {
370
- runtime.rt.lengthStopPending = true;
371
- runtime.dashboard.event("length_stop", { turnIndex: event.turnIndex });
372
- }
373
- // S38: broader error-retry safety net. S28 only catches stopReason==='length';
374
- // this catches ALL other error types (provider failure, network timeout, 5xx,
375
- // 429, auth, compaction-noop, poisoned-context) that surface at turn_end.
376
- // Non-fatal: wrapped in try/catch so a classifier/retry failure never breaks
377
- // the agent loop. PREVENT-PI-003: retry nudge fires via pi.sendUserMessage
378
- // (user-role). R1-R4 (retry redesign) bound the loop: in-flight dedup,
379
- // gating backoff, session-global cap, poisoned-context detection.
380
- try {
381
- // (1) S28 owns length — skip the classifier entirely for it.
382
- const sr = event.message
383
- ?.stopReason;
384
- if (sr === "length") {
385
- // S28 handles; nothing for S38 to do here.
386
- }
387
- else {
388
- const category = classifyError(event.message);
389
- const detail = classifyErrorDetailed(event.message);
390
- runtime.lastErrorCategory = category;
391
- // R3: stateful poisoned-context signal — repeated identical error text
392
- // across consecutive turns. The classifier is stateless, so this
393
- // upgrade happens here. A 'transient' (or 'poisoned-context') turn
394
- // whose normalized error signature matches the previous one bumps
395
- // errorTextRepeatCount; once it crosses the threshold, the category
396
- // is upgraded to 'poisoned-context' (the request is deterministic) —
397
- // R7: unless the signature carries a known-retryable network/
398
- // throughput marker (guard below). Conservative: only upgrade, never
399
- // downgrade, and only for transient (a 'permanent' auth error
400
- // repeating is still permanent).
401
- let effectiveCategory = category;
402
- const errSig = extractErrorSignature(event.message);
403
- if (category === "transient" || category === "poisoned-context") {
404
- if (errSig) {
405
- if (runtime.rt.lastErrorText === errSig) {
406
- runtime.rt.errorTextRepeatCount++;
407
- }
408
- else {
409
- runtime.rt.lastErrorText = errSig;
410
- runtime.rt.errorTextRepeatCount = 1;
411
- }
412
- if (runtime.rt.errorTextRepeatCount >=
413
- config.poisonedContextRepeatThreshold &&
414
- category === "transient") {
415
- // R3/R7: upgrade only when the repeating error carries NO
416
- // known-retryable marker. Network/throughput failures (timeout,
417
- // ECONNRESET, 5xx, 429, connection lost, …) that repeat are
418
- // still retryable — the API is just flaky, and /clear cannot fix
419
- // them (2026-07-30 false-alarm incident). Only upgrade
420
- // transient → poisoned-context for errors that repeat identically
421
- // with no known-retryable cause, like the 2026-07-28 incident
422
- // where the provider returned "Request failed — please retry."
423
- // deterministically. The marker set is shared with classifyError
424
- // (error-classifier.ts) so the two never drift.
425
- if (!isKnownRetryableTransient(errSig)) {
426
- effectiveCategory = "poisoned-context";
427
- }
428
- else {
429
- runtime.logger.info("repeat-upgrade-declined", {
430
- sessionId: runtime.rt.sessionId,
431
- signature: (errSig || '').slice(0, 500),
432
- repeatCount: runtime.rt.errorTextRepeatCount,
433
- });
434
- }
435
- }
436
- }
437
- }
438
- else {
439
- // Non-transient (success, cancelled, compaction-noop, context-overflow,
440
- // permanent): a fresh non-identical signal clears the repeat tracker.
441
- runtime.rt.lastErrorText = undefined;
442
- runtime.rt.errorTextRepeatCount = 0;
443
- }
444
- if (effectiveCategory === null) {
445
- // (3) success / normal flow / unknown-but-non-retryable — reset.
446
- runtime.rt.errorRetryCount = 0;
447
- runtime.rt.consecutiveErrors = 0; // S38.6: circuit-breaker reset on success
448
- // R4: a successful assistant turn consumes any queued nudge.
449
- runtime.rt.retryNudgePending = false;
450
- // R10: reset outage advisory so a recovered-then-flapping
451
- // provider re-advises once per episode.
452
- runtime.rt.providerOutageAdvised = false;
453
- }
454
- else if (effectiveCategory === "compaction-noop") {
455
- // (4) pi race / manual compact catch — NOT retryable. The compaction
456
- // already succeeded via pi's native path; retrying would race again
457
- // (FAIL-2026071701). Log a diagnostic, reset the counter, and surface
458
- // the original error WITHOUT firing a retry nudge.
459
- runtime.rt.errorRetryCount = 0;
460
- runtime.rt.consecutiveErrors = 0; // S38.6: circuit-breaker reset
461
- runtime.rt.retryNudgePending = false; // R4: terminal for this burst
462
- runtime.dashboard.event("compaction_noop_diagnostic", {
463
- turnIndex: event.turnIndex,
464
- sessionId: runtime.rt.sessionId,
465
- });
466
- runtime.logger.info("compaction-noop-diagnostic", {
467
- sessionId: runtime.rt.sessionId,
468
- turnIndex: event.turnIndex,
469
- });
470
- }
471
- else if (effectiveCategory === "cancelled") {
472
- // (4c) User ESC / Ctrl-C — stopReason === 'aborted'. NOT retryable:
473
- // nudging would restart a task the user explicitly stopped.
474
- // Reset both counters (a cancel is not an error for circuit-breaker
475
- // purposes). Emit a diagnostic so the dashboard shows it.
476
- runtime.rt.errorRetryCount = 0;
477
- runtime.rt.consecutiveErrors = 0;
478
- runtime.rt.retryNudgePending = false; // R4: terminal for this burst
479
- runtime.dashboard.event("error_retry_cancelled", {
480
- turnIndex: event.turnIndex,
481
- sessionId: runtime.rt.sessionId,
482
- });
483
- runtime.logger.info("error-retry-cancelled", {
484
- sessionId: runtime.rt.sessionId,
485
- turnIndex: event.turnIndex,
486
- });
487
- }
488
- else if (effectiveCategory === "context-overflow") {
489
- // (4b) context-window overflow 400 ("too long... even after compaction").
490
- // NOT a blind retry: re-submitting the same oversized prompt would just
491
- // re-400 and busy-loop. Reset the counters (this turn is terminal, not
492
- // retryable in the S38 sense) and force ONE best-effort re-compact with
493
- // the debounce bypassed + the same race-guard (lastNativeCompactAt
494
- // cooldown + deferred setTimeout re-check) as the agent_end durable
495
- // trim. Resume after that forced compact is handled by the existing
496
- // nudgeResume() inside session_before_compact (it fires after
497
- // driveNativeCompaction supplies the compaction) — do NOT add a
498
- // separate nudge here.
499
- runtime.rt.errorRetryCount = 0;
500
- runtime.rt.consecutiveErrors = 0;
501
- runtime.rt.retryNudgePending = false; // R4: terminal for this burst
502
- runtime.dashboard.event("context_overflow", {
503
- turnIndex: event.turnIndex,
504
- sessionId: runtime.rt.sessionId,
505
- });
506
- runtime.logger.warn("context-overflow", {
507
- sessionId: runtime.rt.sessionId,
508
- turnIndex: event.turnIndex,
509
- });
510
- if (config.auto) {
511
- const now2 = Date.now();
512
- const cooldownMs2 = config.raceGuardStrict ? 30_000 : 10_000;
513
- const sinceCompact2 = now2 - (runtime.rt.lastNativeCompactAt ?? 0);
514
- if (sinceCompact2 >= cooldownMs2 && !piCompactWouldNoop(ctx)) {
515
- runtime.debounceUntil = now2 + 0;
516
- const stamp2 = runtime.rt.lastNativeCompactAt;
517
- const liveSid2 = runtime.rt.sessionId;
518
- setTimeout(() => {
519
- try {
520
- if (runtime.rt.sessionId !== liveSid2)
521
- return; // session reset
522
- const since3 = Date.now() - (runtime.rt.lastNativeCompactAt ?? 0);
523
- if (runtime.rt.lastNativeCompactAt !== stamp2 &&
524
- since3 < cooldownMs2)
525
- return;
526
- if (piCompactWouldNoop(ctx))
527
- return;
528
- ctx.compact({ customInstructions: undefined }); // guardrails-allow PREVENT-PI-004: local ctx.compact() — no network; deferred + re-validated. Forced re-compact after a context-overflow 400.
529
- }
530
- catch {
531
- /* non-fatal */
532
- }
533
- }, 500);
534
- }
535
- }
536
- }
537
- else if (effectiveCategory === "poisoned-context") {
538
- // R3: poisoned context — a DETERMINISTIC request-rejection that
539
- // retrying cannot fix (0-token 'error', generic "request failed",
540
- // 400 non-overflow, or repeated identical error text). NO blind
541
- // retry nudge — re-submitting the same poisoned prompt re-triggers
542
- // the same rejection (the 2026-07-28 incident: ~60-message spam).
543
- // Instead: (a) dashboard event + warn log naming the suspected
544
- // poison; (b) ONE user-role advise message (/clear or /new) per
545
- // session, throttled; (c) if config.auto, ONE guarded compact per
546
- // error signature (same race-guarded deferred path as context-
547
- // overflow) — only if not already attempted for this signature.
548
- runtime.rt.errorRetryCount = 0; // poisoned is terminal for this burst
549
- runtime.rt.consecutiveErrors++; // still counts toward the circuit breaker
550
- runtime.rt.poisonedCount++; // R7: dashboard counter
551
- const sig = errSig || "unknown";
552
- // (a) dashboard + log — R11: include signal + rawText for forensics
553
- runtime.dashboard.event("poisoned_context", {
554
- signature: sig,
555
- repeatCount: runtime.rt.errorTextRepeatCount,
556
- turnIndex: event.turnIndex,
557
- sessionId: runtime.rt.sessionId,
558
- signal: detail.signal,
559
- rawText: (errSig || '').slice(0, 500),
560
- ...(detail.httpStatus !== undefined ? { httpStatus: detail.httpStatus } : {}),
561
- });
562
- runtime.logger.warn("poisoned-context", {
563
- sessionId: runtime.rt.sessionId,
564
- turnIndex: event.turnIndex,
565
- signature: sig,
566
- repeatCount: runtime.rt.errorTextRepeatCount,
567
- signal: detail.signal,
568
- rawText: (errSig || '').slice(0, 500),
569
- ...(detail.httpStatus !== undefined ? { httpStatus: detail.httpStatus } : {}),
570
- });
571
- // (b) throttle flag: set unconditionally so the advise fires at
572
- // most once per session regardless of channel.
573
- runtime.rt.poisonedAdviseSent = true;
574
- // Legacy flag-OFF path: user-role advise message.
575
- // Default ON (advisoryChannel=true): dashboard-only, no user message.
576
- if (!config.advisoryChannel) {
577
- // PREVENT-PI-003: user-role sendUserMessage only.
578
- 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.");
579
- }
580
- // (c) one guarded compact per error signature (attempt to remove
581
- // the poisoned region). Race-guarded + deferred, mirroring the
582
- // context-overflow path. Only if not already attempted for this
583
- // signature (poisonedCompactSignatures).
584
- if (config.auto && !runtime.rt.poisonedCompactSignatures.has(sig)) {
585
- runtime.rt.poisonedCompactSignatures.add(sig);
586
- const nowP = Date.now();
587
- const cooldownMsP = config.raceGuardStrict ? 30_000 : 10_000;
588
- const sinceCompactP = nowP - (runtime.rt.lastNativeCompactAt ?? 0);
589
- if (sinceCompactP >= cooldownMsP && !piCompactWouldNoop(ctx)) {
590
- runtime.debounceUntil = nowP + 0;
591
- const stampP = runtime.rt.lastNativeCompactAt;
592
- const liveSidP = runtime.rt.sessionId;
593
- setTimeout(() => {
594
- try {
595
- if (runtime.rt.sessionId !== liveSidP)
596
- return; // session reset
597
- const sinceP = Date.now() - (runtime.rt.lastNativeCompactAt ?? 0);
598
- if (runtime.rt.lastNativeCompactAt !== stampP &&
599
- sinceP < cooldownMsP)
600
- return;
601
- if (piCompactWouldNoop(ctx))
602
- return;
603
- ctx.compact({ customInstructions: undefined }); // guardrails-allow PREVENT-PI-004: local ctx.compact() — no network; deferred + re-validated. One guarded compact after a poisoned-context detection.
604
- }
605
- catch {
606
- /* non-fatal */
607
- }
608
- }, 500);
609
- }
610
- }
611
- }
612
- else {
613
- // (5) transient or permanent — retry with exponential backoff.
614
- // S38.7: hard-stop switch — bypass ALL retry logic when set.
615
- if (config.errorRetryHardStop) {
616
- runtime.rt.errorRetryCount = 0;
617
- runtime.dashboard.event("error_retry_disabled", {
618
- category: effectiveCategory,
619
- turnIndex: event.turnIndex,
620
- reason: "hard-stop",
621
- });
622
- return; // early exit — no retry
623
- }
624
- // S38.6: circuit-breaker — stop retrying after too many consecutive errors.
625
- runtime.rt.consecutiveErrors++;
626
- // R10: send calm "provider outage" advisory once per episode.
627
- await maybeSendProviderOutageAdvisory(effectiveCategory, runtime, pi, config, { signal: detail.signal, rawText: (errSig || '').slice(0, 500) });
628
- if (runtime.rt.consecutiveErrors > config.maxConsecutiveErrors) {
629
- runtime.dashboard.event("error_retry_circuit_open", {
630
- consecutive: runtime.rt.consecutiveErrors,
631
- max: config.maxConsecutiveErrors,
632
- turnIndex: event.turnIndex,
633
- });
634
- runtime.logger.warn("error-retry-circuit-open", {
635
- sessionId: runtime.rt.sessionId,
636
- consecutive: runtime.rt.consecutiveErrors,
637
- max: config.maxConsecutiveErrors,
638
- });
639
- return; // early exit — circuit breaker tripped
640
- }
641
- const max = effectiveCategory === "transient"
642
- ? config.autoRetryTransientMax
643
- : config.autoRetryPermanentMax;
644
- // max === 0 disables the category entirely (revert to S28-only).
645
- if (max <= 0) {
646
- runtime.rt.errorRetryCount = 0;
647
- }
648
- else {
649
- runtime.rt.errorRetryCount++;
650
- if (runtime.rt.errorRetryCount > max) {
651
- // Exhausted — surface the error, reset for the next burst.
652
- runtime.dashboard.event("error_retry_exhausted", {
653
- category: effectiveCategory,
654
- count: runtime.rt.errorRetryCount,
655
- max,
656
- turnIndex: event.turnIndex,
657
- });
658
- runtime.logger.info("error-retry-exhausted", {
659
- sessionId: runtime.rt.sessionId,
660
- category: effectiveCategory,
661
- count: runtime.rt.errorRetryCount,
662
- max,
663
- });
664
- runtime.rt.errorRetryCount = 0;
665
- }
666
- else {
667
- // R2: session-global cap — total S38 nudges per session across
668
- // ALL bursts. Independent of the per-burst max and the circuit
669
- // breaker. Hitting it is terminal for the session: log +
670
- // dashboard event, stop nudging. `0` disables (reverts to
671
- // per-burst + circuit-breaker only).
672
- if (config.errorRetrySessionMax > 0 &&
673
- runtime.rt.errorRetrySessionCount >= config.errorRetrySessionMax) {
674
- runtime.dashboard.event("error_retry_session_exhausted", {
675
- count: runtime.rt.errorRetrySessionCount,
676
- max: config.errorRetrySessionMax,
677
- category: effectiveCategory,
678
- turnIndex: event.turnIndex,
679
- });
680
- runtime.logger.warn("error-retry-session-exhausted", {
681
- sessionId: runtime.rt.sessionId,
682
- count: runtime.rt.errorRetrySessionCount,
683
- max: config.errorRetrySessionMax,
684
- category: effectiveCategory,
685
- });
686
- runtime.rt.errorRetryCount = 0;
687
- return; // terminal for the session — no nudge
688
- }
689
- // R1: in-flight nudge dedup — a nudge queued via
690
- // deliverAs:'followUp' must not be re-sent until it has been
691
- // consumed by an actual new agent turn (turn_start resets
692
- // retryNudgePending). Without this, a fast-erroring provider +
693
- // a per-turn nudge → N nudges queue up and pi dispatches N
694
- // retry turns, each re-submitting the same failing prompt
695
- // (the 2026-07-28 incident). errorRetryCount still advances
696
- // (this IS an error turn), so the per-burst max + circuit
697
- // breaker still bound the burst.
698
- if (runtime.rt.retryNudgePending) {
699
- runtime.dashboard.event("error_retry_dedup_skip", {
700
- category: effectiveCategory,
701
- count: runtime.rt.errorRetryCount,
702
- max,
703
- turnIndex: event.turnIndex,
704
- });
705
- return; // pending nudge not yet consumed — skip
706
- }
707
- // R1: gating backoff — errorRetryUntil is now GATING
708
- // (previously documented as non-gating). A nudge cannot fire
709
- // before the previous backoff elapses. This paces retries
710
- // (5s/10s/20s/30s by default) so a fast-erroring provider
711
- // doesn't slam N nudges in <1s.
712
- const now = Date.now();
713
- if (now < runtime.rt.errorRetryUntil) {
714
- runtime.dashboard.event("error_retry_backoff_skip", {
715
- category: effectiveCategory,
716
- count: runtime.rt.errorRetryCount,
717
- max,
718
- turnIndex: event.turnIndex,
719
- });
720
- return; // backoff not elapsed — skip
721
- }
722
- // Fire the retry nudge. Set pending (R1 dedup) + backoff
723
- // (R1 pacing) + session count (R2 cap) BEFORE the await so a
724
- // re-entrant turn_end during the send can't double-fire.
725
- runtime.rt.retryNudgePending = true;
726
- runtime.rt.lastErrorRetryAt = now;
727
- runtime.rt.errorRetryUntil =
728
- now +
729
- errorRetryBackoffMs(runtime.rt.errorRetryCount, config.errorRetryBackoffMs);
730
- runtime.rt.errorRetrySessionCount++;
731
- runtime.dashboard.event("error_retry", {
732
- category: effectiveCategory,
733
- count: runtime.rt.errorRetryCount,
734
- max,
735
- turnIndex: event.turnIndex,
736
- });
737
- runtime.logger.info("error-retry", {
738
- sessionId: runtime.rt.sessionId,
739
- category: effectiveCategory,
740
- count: runtime.rt.errorRetryCount,
741
- max,
742
- });
743
- // PREVENT-PI-003: user-role sendUserMessage only (queued + catch-guarded).
744
- await safeSendUserMessage(pi, "[mega-compact] the last turn ended with an error; please retry.");
745
- }
746
- }
747
- }
748
- }
749
- }
750
- catch {
751
- /* non-fatal: a classifier/retry failure never breaks the agent loop */
752
- }
753
- // P3.5: topic-shift stripe refresh. When MEGACOMPACT_CACHE_STRIPING is ON,
754
- // embed the current turn, detect topic shift vs. the previous turn, and
755
- // refresh cache stripe assignments when shifted (or first turn). Best-effort:
756
- // failures log + continue, never break the agent loop.
757
- if (config.cacheStriping) {
758
- try {
759
- const stateDir = runtime.currentStateDir;
760
- const sessionId = runtime.rt.sessionId;
761
- const currentTurn = event.turnIndex;
762
- const embedder = defaultEmbedder();
763
- // (a) Extract text from the assistant's response for topic embedding.
764
- let textToEmbed = "";
765
- const msg = event.message;
766
- if (msg.role === "assistant" && Array.isArray(msg.content)) {
767
- for (const part of msg.content) {
768
- if ("text" in part && typeof part.text === "string") {
769
- textToEmbed += part.text + " ";
770
- }
771
- }
772
- }
773
- textToEmbed = textToEmbed.trim() || `turn-${currentTurn}`;
774
- const embedding = new Float32Array(embedder.embed(textToEmbed));
775
- storeTopicEmbedding(stateDir, sessionId, currentTurn, embedding);
776
- // (b) Load previous turn's embedding and detect topic shift.
777
- const prevEmb = currentTurn > 0
778
- ? loadTopicEmbedding(stateDir, sessionId, currentTurn - 1)
779
- : null;
780
- const shifted = currentTurn === 0 || detectTopicShift(embedding, prevEmb);
781
- // (c) If shifted (or first turn), refresh stripe assignments (WRITE path).
782
- let chunkCount = 0;
783
- if (shifted) {
784
- chunkCount = writeStripeAssignments(stateDir, undefined, embedder, (detail) => runtime.logger.info("stripe_refresh_detail", {
785
- detail,
786
- turnIndex: currentTurn,
787
- }));
788
- }
789
- // (d) Log the refresh outcome.
790
- runtime.logger.info("stripe_refresh", {
791
- turnIndex: currentTurn,
792
- shifted,
793
- chunkCount,
794
- });
795
- }
796
- catch {
797
- /* non-fatal: stripe refresh never breaks the agent loop */
798
- }
799
- }
800
- // v0.12: Context Health — compute + persist health score. Non-fatal.
801
- // Mitigation signals are acted on here (ctx is in scope at turn_end).
802
- const healthSignal = handleTurnEndHealth(event, runtime, config);
803
- if (healthSignal.forceCompact) {
804
- runtime.logger?.info("health_mitigate_compact", {
805
- composite: healthSignal.composite,
806
- turnIndex: event.turnIndex,
807
- });
808
- try {
809
- // Force a compaction to flush degraded context. Same race-guarded
810
- // deferred path as the critical-over escape hatch above.
811
- if (!piCompactWouldNoop(ctx)) {
812
- ctx.compact();
813
- }
814
- }
815
- catch {
816
- /* non-fatal: mitigation never breaks the agent loop */
817
- }
818
- }
819
- if (healthSignal.breakPrefix) {
820
- runtime.logger?.info("health_mitigate_prefix_break", {
821
- turnIndex: event.turnIndex,
822
- });
823
- // Invalidate the cached trim so the next context event regenerates
824
- // from scratch — the prefix change forces a cache miss, bypassing
825
- // the corrupted KV state.
826
- runtime.trimCache = null;
827
- }
828
- });
33
+ pi.on("turn_end", (event, ctx) => handleTurnEnd(event, ctx, pi, runtime, config));
829
34
  }