pi-mega-compact 0.11.2 → 0.11.3

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 (105) hide show
  1. package/dist/extensions/dashboard-server/api-contracts/endpoints.js +9 -1
  2. package/dist/extensions/dashboard-server/api-contracts/provider-cache.js +7 -0
  3. package/dist/extensions/dashboard-server/api-contracts.test.js +3 -2
  4. package/dist/extensions/dashboard-server/index-reader.js +22 -0
  5. package/dist/extensions/dashboard-server/routes-cache.js +80 -0
  6. package/dist/extensions/dashboard-server/routes-cache.test.js +248 -0
  7. package/dist/extensions/dashboard-server/routes-maintenance.js +7 -7
  8. package/dist/extensions/dashboard-server/routes-repo.js +24 -0
  9. package/dist/extensions/dashboard-server/routes.js +1 -0
  10. package/dist/extensions/dashboard-server/server.js +3 -1
  11. package/dist/extensions/mega-cache-replay.test.js +233 -24
  12. package/dist/extensions/mega-compact-s38.test.js +201 -6
  13. package/dist/extensions/mega-config.js +3 -0
  14. package/dist/extensions/mega-events/agent-handlers.js +23 -7
  15. package/dist/extensions/mega-events/context-handler.js +37 -19
  16. package/dist/extensions/mega-events/error-classifier.js +27 -16
  17. package/dist/extensions/mega-runtime/runtime-snapshot.js +14 -4
  18. package/dist/extensions/mega-runtime/snapshot.js +1 -1
  19. package/dist/extensions/mega-runtime/snapshot.test.js +127 -0
  20. package/dist/extensions/mega-runtime/widget.js +4 -4
  21. package/dist/extensions/mega-runtime/widget.test.js +103 -12
  22. package/dist/src/pricing.js +78 -0
  23. package/dist/src/store/sqlite/perf-samples.js +104 -0
  24. package/dist/src/store/sqlite/perf-samples.test.js +93 -1
  25. package/extensions/dashboard-client/dist/assets/{AchievementTiles-Cml6YC8w.js → AchievementTiles-vEo2MtE2.js} +2 -2
  26. package/extensions/dashboard-client/dist/assets/{AchievementTiles-Cml6YC8w.js.map → AchievementTiles-vEo2MtE2.js.map} +1 -1
  27. package/extensions/dashboard-client/dist/assets/AchievementsTab-DjxfYrDc.js +2 -0
  28. package/extensions/dashboard-client/dist/assets/{AchievementsTab-B8NqDt7I.js.map → AchievementsTab-DjxfYrDc.js.map} +1 -1
  29. package/extensions/dashboard-client/dist/assets/CacheTab-Dnpv94wq.js +2 -0
  30. package/extensions/dashboard-client/dist/assets/CacheTab-Dnpv94wq.js.map +1 -0
  31. package/extensions/dashboard-client/dist/assets/{ConfigTab-CBYvp2mV.js → ConfigTab-Cm6ymbmx.js} +2 -2
  32. package/extensions/dashboard-client/dist/assets/{ConfigTab-CBYvp2mV.js.map → ConfigTab-Cm6ymbmx.js.map} +1 -1
  33. package/extensions/dashboard-client/dist/assets/{EventsTab-DlTJqiDm.js → EventsTab-DXWl_YzI.js} +2 -2
  34. package/extensions/dashboard-client/dist/assets/{EventsTab-DlTJqiDm.js.map → EventsTab-DXWl_YzI.js.map} +1 -1
  35. package/extensions/dashboard-client/dist/assets/{GameTab-DkGTqKJW.js → GameTab-BLDudcO5.js} +2 -2
  36. package/extensions/dashboard-client/dist/assets/{GameTab-DkGTqKJW.js.map → GameTab-BLDudcO5.js.map} +1 -1
  37. package/extensions/dashboard-client/dist/assets/MaintenanceTab-DLkKCztn.js +2 -0
  38. package/extensions/dashboard-client/dist/assets/MaintenanceTab-DLkKCztn.js.map +1 -0
  39. package/extensions/dashboard-client/dist/assets/{MetricsTab-BFo7pKM-.js → MetricsTab-Cq4u-rZF.js} +2 -2
  40. package/extensions/dashboard-client/dist/assets/{MetricsTab-BFo7pKM-.js.map → MetricsTab-Cq4u-rZF.js.map} +1 -1
  41. package/extensions/dashboard-client/dist/assets/{OverviewTab-CClCUd3-.js → OverviewTab-D4kGvsiQ.js} +2 -2
  42. package/extensions/dashboard-client/dist/assets/{OverviewTab-CClCUd3-.js.map → OverviewTab-D4kGvsiQ.js.map} +1 -1
  43. package/extensions/dashboard-client/dist/assets/ReposTab-C0Wnrf2u.js +2 -0
  44. package/extensions/dashboard-client/dist/assets/ReposTab-C0Wnrf2u.js.map +1 -0
  45. package/extensions/dashboard-client/dist/assets/{SessionsTab-CCYd-kSz.js → SessionsTab-DZC2-GCn.js} +2 -2
  46. package/extensions/dashboard-client/dist/assets/{SessionsTab-CCYd-kSz.js.map → SessionsTab-DZC2-GCn.js.map} +1 -1
  47. package/extensions/dashboard-client/dist/assets/TimeSavedCard-UqljSyP-.js +2 -0
  48. package/extensions/dashboard-client/dist/assets/TimeSavedCard-UqljSyP-.js.map +1 -0
  49. package/extensions/dashboard-client/dist/assets/{TopicsTab-DRLJmVv0.js → TopicsTab-01G71hv1.js} +2 -2
  50. package/extensions/dashboard-client/dist/assets/{TopicsTab-DRLJmVv0.js.map → TopicsTab-01G71hv1.js.map} +1 -1
  51. package/extensions/dashboard-client/dist/assets/{TurnsTab-CLNM0T5R.js → TurnsTab-DLRg0LZT.js} +2 -2
  52. package/extensions/dashboard-client/dist/assets/{TurnsTab-CLNM0T5R.js.map → TurnsTab-DLRg0LZT.js.map} +1 -1
  53. package/extensions/dashboard-client/dist/assets/index-BEdKlpAB.css +1 -0
  54. package/extensions/dashboard-client/dist/assets/{index-BcoSz-L4.js → index-BX0bcgLu.js} +4 -4
  55. package/extensions/dashboard-client/dist/assets/{index-BcoSz-L4.js.map → index-BX0bcgLu.js.map} +1 -1
  56. package/extensions/dashboard-client/dist/assets/{useSSE-Cezlih5V.js → useSSE-BBYt5UPB.js} +2 -2
  57. package/extensions/dashboard-client/dist/assets/{useSSE-Cezlih5V.js.map → useSSE-BBYt5UPB.js.map} +1 -1
  58. package/extensions/dashboard-client/dist/index.html +2 -2
  59. package/extensions/dashboard-client/src/api/client.ts +6 -0
  60. package/extensions/dashboard-client/src/components/ActiveReposTable.tsx +13 -1
  61. package/extensions/dashboard-client/src/components/ProviderCacheCard.tsx +141 -0
  62. package/extensions/dashboard-client/src/components/SavingsByModelTable.tsx +31 -3
  63. package/extensions/dashboard-client/src/main.tsx +1 -0
  64. package/extensions/dashboard-client/src/styles/maintenance.css +267 -0
  65. package/extensions/dashboard-client/src/styles/overview-extra.css +9 -0
  66. package/extensions/dashboard-client/src/tabs/CacheTab.tsx +83 -29
  67. package/extensions/dashboard-client/src/tabs/MaintenanceTab.tsx +301 -136
  68. package/extensions/dashboard-client/src/utils/format.ts +42 -7
  69. package/extensions/dashboard-server/api-contracts/endpoints.ts +31 -8
  70. package/extensions/dashboard-server/api-contracts/index.ts +4 -0
  71. package/extensions/dashboard-server/api-contracts/multi-repo.ts +6 -0
  72. package/extensions/dashboard-server/api-contracts/provider-cache.ts +30 -0
  73. package/extensions/dashboard-server/api-contracts.test.ts +3 -2
  74. package/extensions/dashboard-server/index-reader.ts +23 -0
  75. package/extensions/dashboard-server/routes-cache.test.ts +302 -0
  76. package/extensions/dashboard-server/routes-cache.ts +123 -0
  77. package/extensions/dashboard-server/routes-maintenance.ts +18 -11
  78. package/extensions/dashboard-server/routes-repo.ts +31 -4
  79. package/extensions/dashboard-server/routes.ts +1 -0
  80. package/extensions/dashboard-server/server.ts +2 -0
  81. package/extensions/mega-cache-replay.test.ts +481 -166
  82. package/extensions/mega-compact-s38.test.ts +210 -6
  83. package/extensions/mega-config.ts +6 -0
  84. package/extensions/mega-events/agent-handlers.ts +24 -6
  85. package/extensions/mega-events/context-handler.ts +59 -24
  86. package/extensions/mega-events/error-classifier.ts +30 -13
  87. package/extensions/mega-runtime/runtime-snapshot.ts +31 -9
  88. package/extensions/mega-runtime/snapshot.test.ts +139 -0
  89. package/extensions/mega-runtime/snapshot.ts +6 -4
  90. package/extensions/mega-runtime/widget.test.ts +290 -105
  91. package/extensions/mega-runtime/widget.ts +29 -6
  92. package/package.json +1 -1
  93. package/src/pricing.ts +95 -0
  94. package/src/store/sqlite/perf-samples.test.ts +107 -3
  95. package/src/store/sqlite/perf-samples.ts +142 -6
  96. package/extensions/dashboard-client/dist/assets/AchievementsTab-B8NqDt7I.js +0 -2
  97. package/extensions/dashboard-client/dist/assets/CacheTab-BCLzVL4S.js +0 -2
  98. package/extensions/dashboard-client/dist/assets/CacheTab-BCLzVL4S.js.map +0 -1
  99. package/extensions/dashboard-client/dist/assets/MaintenanceTab-Cw43zmUx.js +0 -2
  100. package/extensions/dashboard-client/dist/assets/MaintenanceTab-Cw43zmUx.js.map +0 -1
  101. package/extensions/dashboard-client/dist/assets/ReposTab-_3R4RSLZ.js +0 -2
  102. package/extensions/dashboard-client/dist/assets/ReposTab-_3R4RSLZ.js.map +0 -1
  103. package/extensions/dashboard-client/dist/assets/TimeSavedCard-0TqsrY6y.js +0 -2
  104. package/extensions/dashboard-client/dist/assets/TimeSavedCard-0TqsrY6y.js.map +0 -1
  105. package/extensions/dashboard-client/dist/assets/index-gn66lYD2.css +0 -1
@@ -53,17 +53,48 @@ function harness() {
53
53
  // raising `tokens` while keeping `percent` null (→ token gate + token
54
54
  // grewEnough path in context-handler.ts). The REPLAY test keeps percent=100 so
55
55
  // the percent-basis grewEnough (>=10) never trips (no re-compact → pure replay).
56
- const usage = { tokens: 200000, contextWindow: 200000, percent: 100 };
56
+ const usage = {
57
+ tokens: 200000,
58
+ contextWindow: 200000,
59
+ percent: 100,
60
+ };
57
61
  const handlers = {};
58
62
  const compactCalls = [];
59
63
  function msg(role, text, toolName) {
60
64
  if (role === "assistant" && toolName) {
61
- return { role: "assistant", content: [{ type: "toolCall", name: toolName, id: "c1", arguments: {} }], api: "anthropic-messages", provider: "anthropic", model: "m", usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 }, stopReason: "tool_use", timestamp: 0 };
65
+ return {
66
+ role: "assistant",
67
+ content: [
68
+ { type: "toolCall", name: toolName, id: "c1", arguments: {} },
69
+ ],
70
+ api: "anthropic-messages",
71
+ provider: "anthropic",
72
+ model: "m",
73
+ usage: {
74
+ inputTokens: 1,
75
+ outputTokens: 1,
76
+ cacheReadTokens: 0,
77
+ cacheWriteTokens: 0,
78
+ },
79
+ stopReason: "tool_use",
80
+ timestamp: 0,
81
+ };
62
82
  }
63
83
  if (role === "toolResult" && toolName) {
64
- return { role: "toolResult", content: [{ type: "text", text }], toolCallId: "c1", toolName, isError: false, timestamp: 0 };
84
+ return {
85
+ role: "toolResult",
86
+ content: [{ type: "text", text }],
87
+ toolCallId: "c1",
88
+ toolName,
89
+ isError: false,
90
+ timestamp: 0,
91
+ };
65
92
  }
66
- return { role: "user", content: text, timestamp: 0 };
93
+ return {
94
+ role: "user",
95
+ content: text,
96
+ timestamp: 0,
97
+ };
67
98
  }
68
99
  // Build a session of `n` tool-call triples tagged `tag`. Set A and B differ in
69
100
  // content (so B never dedups against A) but A === A reproduces the same
@@ -77,7 +108,13 @@ function harness() {
77
108
  }
78
109
  return s;
79
110
  }
80
- const toEntry = (m, i) => ({ type: "message", id: `e${i}`, parentId: null, timestamp: String(i), message: m });
111
+ const toEntry = (m, i) => ({
112
+ type: "message",
113
+ id: `e${i}`,
114
+ parentId: null,
115
+ timestamp: String(i),
116
+ message: m,
117
+ });
81
118
  const sessionManager = {
82
119
  getSessionId: () => "sess_cache_001",
83
120
  getEntries: () => buildSession("A", 14).map(toEntry),
@@ -85,39 +122,86 @@ function harness() {
85
122
  };
86
123
  function makeCtx(over = {}) {
87
124
  return {
88
- ui: { setStatus: () => { }, notify: () => { }, select: () => { }, confirm: async () => true, input: async () => "", setWidget: () => { } },
89
- mode: "tui", hasUI: true, cwd: stateDir, sessionManager,
90
- modelRegistry: {}, model: undefined, isIdle: () => true, isProjectTrusted: () => true,
91
- signal: undefined, abort: () => { }, hasPendingMessages: () => false, shutdown: () => { },
125
+ ui: {
126
+ setStatus: () => { },
127
+ notify: () => { },
128
+ select: () => { },
129
+ confirm: async () => true,
130
+ input: async () => "",
131
+ setWidget: () => { },
132
+ },
133
+ mode: "tui",
134
+ hasUI: true,
135
+ cwd: stateDir,
136
+ sessionManager,
137
+ modelRegistry: {},
138
+ model: undefined,
139
+ isIdle: () => true,
140
+ isProjectTrusted: () => true,
141
+ signal: undefined,
142
+ abort: () => { },
143
+ hasPendingMessages: () => false,
144
+ shutdown: () => { },
92
145
  getContextUsage: () => ({ ...usage }),
93
- compact: (opts) => { compactCalls.push(opts); return undefined; },
146
+ compact: (opts) => {
147
+ compactCalls.push(opts);
148
+ return undefined;
149
+ },
94
150
  getSystemPrompt: () => "system base",
95
151
  ...over,
96
152
  };
97
153
  }
98
154
  const pi = {
99
- on: (ev, h) => { if (!handlers[ev])
100
- handlers[ev] = []; handlers[ev].push(h); },
101
- registerCommand: () => { }, registerTool: () => { }, registerShortcut: () => { },
102
- registerFlag: () => { }, getFlag: () => undefined, registerMessageRenderer: () => { },
103
- registerEntryRenderer: () => { }, sendMessage: () => { }, sendUserMessage: () => { },
104
- appendEntry: () => { }, setSessionName: () => { }, getSessionName: () => undefined,
105
- setLabel: () => { }, exec: async () => ({ stdout: "", stderr: "", code: 0 }),
106
- getActiveTools: () => [], getAllTools: () => [], setActiveTools: () => { },
107
- getCommands: () => [], setModel: async () => false, getThinkingLevel: () => "off",
155
+ on: (ev, h) => {
156
+ if (!handlers[ev])
157
+ handlers[ev] = [];
158
+ handlers[ev].push(h);
159
+ },
160
+ registerCommand: () => { },
161
+ registerTool: () => { },
162
+ registerShortcut: () => { },
163
+ registerFlag: () => { },
164
+ getFlag: () => undefined,
165
+ registerMessageRenderer: () => { },
166
+ registerEntryRenderer: () => { },
167
+ sendMessage: () => { },
168
+ sendUserMessage: () => { },
169
+ appendEntry: () => { },
170
+ setSessionName: () => { },
171
+ getSessionName: () => undefined,
172
+ setLabel: () => { },
173
+ exec: async () => ({ stdout: "", stderr: "", code: 0 }),
174
+ getActiveTools: () => [],
175
+ getAllTools: () => [],
176
+ setActiveTools: () => { },
177
+ getCommands: () => [],
178
+ setModel: async () => false,
179
+ getThinkingLevel: () => "off",
108
180
  setThinkingLevel: () => { },
109
181
  };
110
182
  const mod = require("./mega-compact.js");
111
183
  mod.default(pi);
112
184
  const { lastRuntime } = require("./mega-events.js");
113
- const fire = async (ev, event, ctx) => { let r; for (const h of handlers[ev] || [])
114
- r = await h(event, ctx); return r; };
185
+ const fire = async (ev, event, ctx) => {
186
+ let r;
187
+ for (const h of handlers[ev] || [])
188
+ r = await h(event, ctx);
189
+ return r;
190
+ };
115
191
  return {
116
- stateDir, handlers, compactCalls, fire, ctx: makeCtx, usage, buildSession,
192
+ stateDir,
193
+ handlers,
194
+ compactCalls,
195
+ fire,
196
+ ctx: makeCtx,
197
+ usage,
198
+ buildSession,
117
199
  runtime: lastRuntime, // MegaRuntime with diag* counters + rt + trimCache
118
200
  // Bypass the 2s debounce so each fire proceeds without real waiting.
119
- clearDebounce: () => { if (lastRuntime)
120
- lastRuntime.debounceUntil = 0; },
201
+ clearDebounce: () => {
202
+ if (lastRuntime)
203
+ lastRuntime.debounceUntil = 0;
204
+ },
121
205
  };
122
206
  }
123
207
  test("REPLAY: >=2 gated context events within one epoch replay verbatim (byte-identical)", async () => {
@@ -185,6 +269,131 @@ test("DEDUP: re-compact that dedups onto a DIFFERENT checkpoint still replays ne
185
269
  await h.fire("context", { type: "context", messages: setA }, ctx);
186
270
  assert.ok(rt.diagLiveTrimReplays > replaysBefore, `replay fired after dedup-onto-different-checkpoint (got ${rt.diagLiveTrimReplays}, was ${replaysBefore})`);
187
271
  });
272
+ // D.4-test-1 — Debounce exemption: the replay path sits BEFORE the debounce guard.
273
+ // Two gated events <2s apart (no clearDebounce) must both replay — diagCtxDebounce
274
+ // must NOT increment because the debounce guard is never reached when replay fires.
275
+ test("DEBOUNCE-EXEMPTION: two events <2s apart (no clearDebounce) both replay; debounce never reached", async () => {
276
+ const h = harness();
277
+ const ctx = h.ctx();
278
+ const session = h.buildSession("A", 14);
279
+ // 1) Fresh trim.
280
+ h.clearDebounce(); // first event always needs a clear to pass the time guard
281
+ await h.fire("context", { type: "context", messages: session }, ctx);
282
+ assert.equal(h.runtime.diagLiveTrimFires, 1, "first fire was fresh trim");
283
+ // 2) Fire two events IN QUICK SUCCESSION without clearing the debounce.
284
+ // The replay path (D.2) sits BEFORE the debounce guard, so both should
285
+ // replay the cached trim and the debounce guard is NEVER reached.
286
+ const dbgBefore = h.runtime.diagCtxDebounce;
287
+ const rpyBefore = h.runtime.diagLiveTrimReplays;
288
+ await h.fire("context", { type: "context", messages: session }, ctx);
289
+ await h.fire("context", { type: "context", messages: session }, ctx);
290
+ assert.equal(h.runtime.diagCtxDebounce, dbgBefore, `debounce counter unchanged (${h.runtime.diagCtxDebounce} == ${dbgBefore}) — replay path was reached, not debounce`);
291
+ assert.ok(h.runtime.diagLiveTrimReplays >= rpyBefore + 2, `both events replayed (replays ${h.runtime.diagLiveTrimReplays} >= ${rpyBefore}+2)`);
292
+ });
293
+ // D.4-test-2 — Skip→replay fallback: when runCompact returns {skipped: true} and
294
+ // a valid trimCache exists, the handler replays the cached trim instead of returning
295
+ // empty. We force a skip by firing with a 1-message session (view.length ≤ 1) AFTER
296
+ // a fresh trim with a full session has populated trimCache.
297
+ test("SKIP-FALLBACK: runCompact skipped + valid trimCache → replays cached trim", async () => {
298
+ const h = harness();
299
+ const ctx = h.ctx();
300
+ const session = h.buildSession("A", 14);
301
+ // 1) Fresh trim with full session → populates trimCache with a valid cut.
302
+ h.clearDebounce();
303
+ await h.fire("context", { type: "context", messages: session }, ctx);
304
+ assert.equal(h.runtime.diagLiveTrimFires, 1, "fresh trim populated trimCache");
305
+ assert.ok(h.runtime.trimCache, "trimCache is set");
306
+ // 2) Lower the cut so a 1-message session still passes the cut≤length guard.
307
+ // The skip→replay path checks cut <= messages.length before replaying.
308
+ h.runtime.trimCache.cut = 0;
309
+ // 3) Drive context growth so grewEnough=true (replay skipped → runCompact runs).
310
+ // Then fire with just 1 message → runCompact: view.length ≤ 1 → {skipped: true}.
311
+ h.usage.percent = null; // token-basis path
312
+ h.usage.tokens = 200100; // grew 100 >= 25 (effectiveThreshold * 0.5)
313
+ h.clearDebounce();
314
+ const oneMsg = [h.buildSession("X", 1)[0]]; // single user message
315
+ await h.fire("context", { type: "context", messages: oneMsg }, ctx);
316
+ assert.ok(h.runtime.diagCtxRunSkipped >= 1, `diagCtxRunSkipped incremented (got ${h.runtime.diagCtxRunSkipped})`);
317
+ // The skip path replays trimCache → diagLiveTrimReplays increments.
318
+ assert.ok(h.runtime.diagLiveTrimReplays >= 1, `skip→replay fired (replays ${h.runtime.diagLiveTrimReplays} >= 1)`);
319
+ });
320
+ // D.4-test-3 — Recompact delta boundary: config.recompactPctDelta = 50.
321
+ // 49% growth → replay (not enough to re-compact).
322
+ // 51% growth → fresh compaction (exceeds the 50% delta threshold).
323
+ //
324
+ // diagLiveTrimFires counts every trim response (replay OR fresh), including
325
+ // the initial fresh trim, so cumulative counts can't validate discrete steps.
326
+ // Instead we snapshot (fires, replays) before each step and assert the delta.
327
+ test("DELTA-BOUNDARY: 49% growth → replay; 51% growth → fresh compaction", async () => {
328
+ const h = harness();
329
+ const ctx = h.ctx();
330
+ const session = h.buildSession("A", 14);
331
+ // Start at low context (percent=5). The handler captures ctxPct from the first
332
+ // trim, then checks pct - ctxPct >= 50 (config.recompactPctDelta default=50).
333
+ h.usage.percent = 5;
334
+ h.usage.tokens = 200000;
335
+ // 1) Fresh trim at pct=5 → trimCache.ctxPct = 5.
336
+ h.clearDebounce();
337
+ await h.fire("context", { type: "context", messages: session }, ctx);
338
+ assert.ok(h.runtime.diagLiveTrimFires >= 1, "fresh trim at pct=5");
339
+ assert.equal(h.runtime.trimCache?.ctxPct, 5, "ctxPct captured as 5");
340
+ // 2) 49% growth: pct=54. grewEnough = 54-5 = 49 < 50 → replay.
341
+ // Replay increments BOTH fires and replays (line 247-248).
342
+ h.usage.percent = 54;
343
+ h.clearDebounce();
344
+ const { fires: f2, replays: r2 } = {
345
+ fires: h.runtime.diagLiveTrimFires,
346
+ replays: h.runtime.diagLiveTrimReplays,
347
+ };
348
+ await h.fire("context", { type: "context", messages: session }, ctx);
349
+ assert.equal(h.runtime.diagLiveTrimFires, f2 + 1, `49% growth: fires +1 (replay counted as fire, ${f2}→${h.runtime.diagLiveTrimFires})`);
350
+ assert.equal(h.runtime.diagLiveTrimReplays, r2 + 1, `49% growth: replays +1 (${r2}→${h.runtime.diagLiveTrimReplays})`);
351
+ // 3) 51% growth: pct=56. grewEnough = 56-5 = 51 >= 50 → falls through to
352
+ // debounce → runCompact → fresh compaction (line 509).
353
+ // Fresh compaction increments fires but NOT replays.
354
+ h.usage.percent = 56;
355
+ h.clearDebounce();
356
+ const { fires: f3, replays: r3 } = {
357
+ fires: h.runtime.diagLiveTrimFires,
358
+ replays: h.runtime.diagLiveTrimReplays,
359
+ };
360
+ await h.fire("context", { type: "context", messages: session }, ctx);
361
+ assert.equal(h.runtime.diagLiveTrimFires, f3 + 1, `51% growth: fires +1 (fresh compaction, ${f3}→${h.runtime.diagLiveTrimFires})`);
362
+ assert.equal(h.runtime.diagLiveTrimReplays, r3, `51% growth: replays unchanged (fresh compaction ≠ replay, stays ${r3})`);
363
+ });
364
+ // D.4-test-4 — Epoch invalidation (PREVENT-PI-001/002 guard): a checkpointId
365
+ // mismatch means the durable transcript was truncated (session_compact or
366
+ // resetRuntime). The replay guard MUST reject a stale trimCache in that case.
367
+ test("EPOCH-INVALIDATION: checkpointId mismatch → replay does NOT fire (PREVENT-PI-001/002)", async () => {
368
+ const h = harness();
369
+ const ctx = h.ctx();
370
+ const session = h.buildSession("A", 14);
371
+ // 1) Fresh trim → trimCache.checkpointId = lastCheckpointId = "cp-1".
372
+ h.clearDebounce();
373
+ await h.fire("context", { type: "context", messages: session }, ctx);
374
+ assert.equal(h.runtime.diagLiveTrimFires, 1, "fresh trim");
375
+ assert.ok(h.runtime.trimCache?.checkpointId, "trimCache has checkpointId");
376
+ // 2) Simulate a session_compact (durable truncation) by advancing
377
+ // lastCheckpointId (harder: the compact path tracks its own epoch).
378
+ // A mismatch between trimCache.checkpointId and rt.lastCheckpointId means
379
+ // the cached cut is for a truncated transcript → replay must NOT fire.
380
+ h.runtime.rt.lastCheckpointId = "cp-mismatch";
381
+ assert.notEqual(h.runtime.trimCache?.checkpointId, h.runtime.rt.lastCheckpointId, "checkpointIds differ after simulated durable truncation");
382
+ // 3) Fire the same session (no growth → would normally replay if epoch matched).
383
+ const rpyBefore = h.runtime.diagLiveTrimReplays;
384
+ h.clearDebounce();
385
+ await h.fire("context", { type: "context", messages: session }, ctx);
386
+ // Replay path was blocked by the checkpointId guard → a fresh trim fires instead.
387
+ assert.equal(h.runtime.diagLiveTrimReplays, rpyBefore, `replay NOT incremented (was ${rpyBefore}, still ${h.runtime.diagLiveTrimReplays}) — stale trimCache rejected`);
388
+ // A fresh compaction should have been triggered instead (grewEnough=false, but
389
+ // replay guard failed → falls through to debounce → runCompact → fresh trim).
390
+ // Actually: grewEnough is false (no growth since last fire), and the replay
391
+ // guard rejected → falls to debounce (cleared) → runCompact.
392
+ // runCompact may skip or produce a fresh trim; either way the stale replay is blocked.
393
+ assert.ok(h.runtime.diagLiveTrimFires >= 2 || h.runtime.diagCtxRunSkipped >= 1, `handler did NOT replay stale trimCache (fires=${h.runtime.diagLiveTrimFires}, skipped=${h.runtime.diagCtxRunSkipped}, replays=${h.runtime.diagLiveTrimReplays})`);
394
+ // Restore for cleanup.
395
+ h.runtime.rt.lastCheckpointId = "cp-1";
396
+ });
188
397
  test("cleanup", async () => {
189
398
  await closeVectorIndex();
190
399
  rmSync(baseTmp, { recursive: true, force: true });
@@ -576,9 +576,11 @@ test("R6(e): success resets retry-nudge-pending state", async () => {
576
576
  });
577
577
  test("R3: repeated identical transient error text upgrades to poisoned-context at threshold", async () => {
578
578
  // The stateful repeat signal: 3 consecutive identical transient errors
579
- // (default threshold) upgrade to poisoned. Uses "5xx server error" (5xx
580
- // marker transient) so the classifier returns transient, then the repeat
581
- // tracker upgrades it. auto=false to skip the compact attempt.
579
+ // (default threshold) upgrade to poisoned. Uses "5xx server error"
580
+ // deliberately NO known-retryable marker ("5xx" is not /5\d\d/, and
581
+ // "server error" alone matches nothing): the classifier returns transient
582
+ // via the generic 'error' fallthrough, then the repeat tracker upgrades it.
583
+ // auto=false to skip the compact attempt.
582
584
  const prevAuto = process.env.MEGACOMPACT_AUTO;
583
585
  const prevBackoff = process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
584
586
  process.env.MEGACOMPACT_AUTO = "false";
@@ -608,6 +610,195 @@ test("R3: repeated identical transient error text upgrades to poisoned-context a
608
610
  process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = prevBackoff;
609
611
  }
610
612
  });
613
+ // ---- R7 regression tests: network/throughput errors must NEVER upgrade to ----
614
+ // ---- poisoned-context (2026-07-30 false-alarm incident) ----
615
+ /** R7 helper: fire the same transient error text `count` times with turn_start
616
+ * + elapsed backoff between turns so each turn's nudge can fire. */
617
+ async function r7RepeatTurns(h, text, count) {
618
+ for (let i = 0; i < count; i++) {
619
+ await s38TurnEnd(h, "error", text);
620
+ await h.fire("turn_start", { type: "turn_start", turnIndex: i + 2 }, h.ctx());
621
+ await new Promise((r) => setTimeout(r, 3));
622
+ }
623
+ }
624
+ /** R7 helper: shared assertions for "stays transient" — no poisoned upgrade,
625
+ * no /clear advise, and the transient retry path actually ran. */
626
+ function assertStaysTransient(h, label) {
627
+ assert.ok(!eventTypes(h.stateDir).includes("poisoned_context"), `${label}: no poisoned_context event (network errors never upgrade)`);
628
+ assert.ok(!h.sendUserMessages.some((m) => m.includes("/clear")), `${label}: no /clear advise message`);
629
+ assert.ok(eventTypes(h.stateDir).includes("error_retry"), `${label}: transient retry path ran (error_retry event)`);
630
+ }
631
+ test("R7(a): repeated 'timed out' phrasing (2026-07-30 incident text) stays transient — no poisoned upgrade", async () => {
632
+ // The incident error text was "Request timed out or failed. Try again" —
633
+ // "timed out" (two words) does NOT match the old guard's /timeout/, so the
634
+ // 3rd repeat fired the /clear poisoned advise. Must stay transient.
635
+ const prevAuto = process.env.MEGACOMPACT_AUTO;
636
+ const prevBackoff = process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
637
+ process.env.MEGACOMPACT_AUTO = "false";
638
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = "1";
639
+ try {
640
+ const h = harness();
641
+ await r7RepeatTurns(h, "Request timed out or failed. Try again", 3);
642
+ assertStaysTransient(h, "timed out x3");
643
+ }
644
+ finally {
645
+ if (prevAuto === undefined)
646
+ delete process.env.MEGACOMPACT_AUTO;
647
+ else
648
+ process.env.MEGACOMPACT_AUTO = prevAuto;
649
+ if (prevBackoff === undefined)
650
+ delete process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
651
+ else
652
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = prevBackoff;
653
+ }
654
+ });
655
+ test("R7(b): repeated ETIMEDOUT errno stays transient", async () => {
656
+ // Node's timeout errno lowercases to "etimedout" — does NOT contain the
657
+ // substring "timeout". Slipped through the old guard.
658
+ const prevAuto = process.env.MEGACOMPACT_AUTO;
659
+ const prevBackoff = process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
660
+ process.env.MEGACOMPACT_AUTO = "false";
661
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = "1";
662
+ try {
663
+ const h = harness();
664
+ await r7RepeatTurns(h, "connect ETIMEDOUT 142.250.80.46:443", 3);
665
+ assertStaysTransient(h, "ETIMEDOUT x3");
666
+ }
667
+ finally {
668
+ if (prevAuto === undefined)
669
+ delete process.env.MEGACOMPACT_AUTO;
670
+ else
671
+ process.env.MEGACOMPACT_AUTO = prevAuto;
672
+ if (prevBackoff === undefined)
673
+ delete process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
674
+ else
675
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = prevBackoff;
676
+ }
677
+ });
678
+ test("R7(c): repeated 'socket hang up' stays transient", async () => {
679
+ // Node surfaces ECONNRESET as the message "socket hang up" (the errno lives
680
+ // in error.code, which extractErrorSignature never sees).
681
+ const prevAuto = process.env.MEGACOMPACT_AUTO;
682
+ const prevBackoff = process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
683
+ process.env.MEGACOMPACT_AUTO = "false";
684
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = "1";
685
+ try {
686
+ const h = harness();
687
+ await r7RepeatTurns(h, "socket hang up", 3);
688
+ assertStaysTransient(h, "socket hang up x3");
689
+ }
690
+ finally {
691
+ if (prevAuto === undefined)
692
+ delete process.env.MEGACOMPACT_AUTO;
693
+ else
694
+ process.env.MEGACOMPACT_AUTO = prevAuto;
695
+ if (prevBackoff === undefined)
696
+ delete process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
697
+ else
698
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = prevBackoff;
699
+ }
700
+ });
701
+ test("R7(d): repeated 429 rate-limit stays transient", async () => {
702
+ // /clear cannot fix a rate limit — the classifier explicitly keeps 429
703
+ // transient, so the repeat-upgrade must not override that verdict.
704
+ const prevAuto = process.env.MEGACOMPACT_AUTO;
705
+ const prevBackoff = process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
706
+ process.env.MEGACOMPACT_AUTO = "false";
707
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = "1";
708
+ try {
709
+ const h = harness();
710
+ await r7RepeatTurns(h, "429 Too Many Requests: rate limit exceeded", 3);
711
+ assertStaysTransient(h, "429 x3");
712
+ }
713
+ finally {
714
+ if (prevAuto === undefined)
715
+ delete process.env.MEGACOMPACT_AUTO;
716
+ else
717
+ process.env.MEGACOMPACT_AUTO = prevAuto;
718
+ if (prevBackoff === undefined)
719
+ delete process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
720
+ else
721
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = prevBackoff;
722
+ }
723
+ });
724
+ test("R7(e): 0-token 'timed out' turn is NOT poisoned on first occurrence", async () => {
725
+ // Deeper gap: with usage PRESENT at 0 tokens, the classifier's 0-token
726
+ // poisoned signal fires on turn ONE for "timed out" phrasing (the stopReason
727
+ // 'error' is in the text blob and no transient marker matched). The network
728
+ // markers must be checked before that signal so this returns transient.
729
+ const prevAuto = process.env.MEGACOMPACT_AUTO;
730
+ process.env.MEGACOMPACT_AUTO = "false";
731
+ try {
732
+ const h = harness();
733
+ await s38TurnEndUsage(h, "error", "Request timed out or failed. Try again", 0);
734
+ assert.ok(!eventTypes(h.stateDir).includes("poisoned_context"), "0-token timed out: no poisoned_context on first turn");
735
+ assert.ok(!h.sendUserMessages.some((m) => m.includes("/clear")), "0-token timed out: no /clear advise on first turn");
736
+ }
737
+ finally {
738
+ if (prevAuto === undefined)
739
+ delete process.env.MEGACOMPACT_AUTO;
740
+ else
741
+ process.env.MEGACOMPACT_AUTO = prevAuto;
742
+ }
743
+ });
744
+ test("R7(f): repeated non-network transient still upgrades to poisoned-context (control)", async () => {
745
+ // True-positive control: an error with NO known-retryable marker that
746
+ // repeats identically must still upgrade (the R3 feature itself).
747
+ const prevAuto = process.env.MEGACOMPACT_AUTO;
748
+ const prevBackoff = process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
749
+ process.env.MEGACOMPACT_AUTO = "false";
750
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = "1";
751
+ try {
752
+ const h = harness();
753
+ await r7RepeatTurns(h, "upstream rejected the request", 3);
754
+ assert.ok(eventTypes(h.stateDir).includes("poisoned_context"), "non-network repeat: poisoned_context event logged");
755
+ assert.ok(h.sendUserMessages.some((m) => m.includes("/clear")), "non-network repeat: /clear advise fired");
756
+ }
757
+ finally {
758
+ if (prevAuto === undefined)
759
+ delete process.env.MEGACOMPACT_AUTO;
760
+ else
761
+ process.env.MEGACOMPACT_AUTO = prevAuto;
762
+ if (prevBackoff === undefined)
763
+ delete process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
764
+ else
765
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = prevBackoff;
766
+ }
767
+ });
768
+ test("R7(g): 'Request failed — please retry.' 0-token stays poisoned-context (2026-07-28 control)", async () => {
769
+ // The deterministic-rejection incident that motivated R3 must remain
770
+ // poisoned: the shared marker pattern must NOT match this text.
771
+ const prevAuto = process.env.MEGACOMPACT_AUTO;
772
+ process.env.MEGACOMPACT_AUTO = "false";
773
+ try {
774
+ const h = harness();
775
+ await s38TurnEndUsage(h, "error", "Request failed — please retry.", 0);
776
+ assert.ok(eventTypes(h.stateDir).includes("poisoned_context"), "deterministic rejection: poisoned_context event logged");
777
+ assert.ok(h.sendUserMessages.some((m) => m.includes("/clear")), "deterministic rejection: /clear advise fired");
778
+ }
779
+ finally {
780
+ if (prevAuto === undefined)
781
+ delete process.env.MEGACOMPACT_AUTO;
782
+ else
783
+ process.env.MEGACOMPACT_AUTO = prevAuto;
784
+ }
785
+ });
786
+ test("R7 classifier: 0-token 'timed out' error → transient (not poisoned)", () => {
787
+ // Unit-level pin of the R7(e) gap.
788
+ assert.equal(classifyErrorFn({
789
+ stopReason: "error",
790
+ content: "Request timed out or failed. Try again",
791
+ usage: { inputTokens: 0, outputTokens: 0 },
792
+ }), "transient");
793
+ });
794
+ test("R7 classifier: bare network phrasings → transient", () => {
795
+ assert.equal(classifyErrorFn("socket hang up"), "transient");
796
+ assert.equal(classifyErrorFn("the operation timed out"), "transient");
797
+ assert.equal(classifyErrorFn("connect ETIMEDOUT 10.0.0.1:443"), "transient");
798
+ });
799
+ test("R7 classifier: 429/rate-limit → transient (control)", () => {
800
+ assert.equal(classifyErrorFn("429 Too Many Requests: rate limit exceeded"), "transient");
801
+ });
611
802
  test("cleanup", async () => {
612
803
  // PGlite WASM close can hang; race with a timeout to prevent 40-min hangs.
613
804
  try {
@@ -618,8 +809,12 @@ test("cleanup", async () => {
618
809
  // Force-exit: each harness() creates a MegaRuntime with an fs.watch
619
810
  // game-state watcher that is never disposed (no session_shutdown in tests).
620
811
  // Those handles keep the event loop alive indefinitely after all tests
621
- // complete, so `node --test` (without --test-force-exit) would hang. The
622
- // streaming reporter has already printed every test result by this point;
623
- // process.exit(0) just forces the exit the watchers are preventing.
812
+ // complete, so `node --test` (without --test-force-exit) would hang.
813
+ // Drain stdout/stderr, then defer the exit: a bare process.exit() discards
814
+ // unflushed pipe buffers observed 2026-07-30: when piped, the trailing
815
+ // tests' results and the run summary silently vanished from the report.
816
+ await new Promise((r) => process.stdout.write("", r));
817
+ await new Promise((r) => process.stderr.write("", r));
818
+ await new Promise((r) => setTimeout(r, 1500));
624
819
  process.exit(0);
625
820
  });
@@ -165,6 +165,9 @@ export function loadConfig() {
165
165
  recallMaxTokens: envFlag("MEGACOMPACT_RECALL_MAX_TOKENS", 1500),
166
166
  windowDedupe: envBool("MEGACOMPACT_WINDOW_DEDUPE", true),
167
167
  tuiWidget: envBool("MEGACOMPACT_TUI_WIDGET", true),
168
+ // D.1: env-overridable recompact delta (minimum context growth % before
169
+ // re-compacting instead of replaying the cached live trim). Default 50.
170
+ recompactPctDelta: envFlag("MEGACOMPACT_RECOMPACT_PCT_DELTA", 50),
168
171
  debug: envBool("MEGACOMPACT_DEBUG", false),
169
172
  };
170
173
  }
@@ -1,11 +1,11 @@
1
1
  import { piCompactWouldNoop, runMemoryReview } from "../mega-pipeline.js";
2
2
  import { memoryReviewCadence } from "../mega-config.js";
3
- import { recordScore } from "../../src/store/sqlite.js";
3
+ import { recordScore, readLatestCacheHitPct } from "../../src/store/sqlite.js";
4
4
  import { evaluateAndUnlockAchievements } from "../../src/store/sqlite/game-achievements.js";
5
5
  import { ensureConversationIdFor, recordTurnWrite, } from "../mega-turn-store.js";
6
6
  import { isMegaCache } from "../../src/game/scoring.js";
7
7
  import { resolveRepoRoot } from "../mega-config.js";
8
- import { classifyError, errorRetryBackoffMs, extractErrorSignature, } from "./error-classifier.js";
8
+ import { classifyError, errorRetryBackoffMs, extractErrorSignature, isKnownRetryableTransient, } from "./error-classifier.js";
9
9
  import { safeSendUserMessage } from "./send-safe.js";
10
10
  import { vectorStats } from "../../src/vectorStore.js";
11
11
  /** Register agent/turn tracking event handlers. */
@@ -255,7 +255,9 @@ export function registerAgentHandlers(pi, runtime, config) {
255
255
  if (runtime.getCachedGameState().game_mode_on) {
256
256
  const repo = resolveRepoRoot(ctx.cwd) ?? runtime.currentStateDir;
257
257
  const st = vectorStats(runtime.store, runtime.rt.sessionId);
258
- const cachePct = st.dedupHitRate * 100;
258
+ // C.3: prefer provider cache hit rate, fall back to dedup hit rate
259
+ const providerPct = readLatestCacheHitPct(runtime.currentStateDir);
260
+ const cachePct = providerPct != null ? providerPct : st.dedupHitRate * 100;
259
261
  const modelId = runtime.currentModel?.modelId ?? "unknown";
260
262
  recordScore(runtime.currentStateDir, {
261
263
  repo_root: repo,
@@ -339,9 +341,11 @@ export function registerAgentHandlers(pi, runtime, config) {
339
341
  // upgrade happens here. A 'transient' (or 'poisoned-context') turn
340
342
  // whose normalized error signature matches the previous one bumps
341
343
  // errorTextRepeatCount; once it crosses the threshold, the category
342
- // is upgraded to 'poisoned-context' (the request is deterministic).
343
- // Conservative: only upgrade, never downgrade, and only for transient
344
- // (a 'permanent' auth error repeating is still permanent).
344
+ // is upgraded to 'poisoned-context' (the request is deterministic)
345
+ // R7: unless the signature carries a known-retryable network/
346
+ // throughput marker (guard below). Conservative: only upgrade, never
347
+ // downgrade, and only for transient (a 'permanent' auth error
348
+ // repeating is still permanent).
345
349
  let effectiveCategory = category;
346
350
  const errSig = extractErrorSignature(event.message);
347
351
  if (category === "transient" || category === "poisoned-context") {
@@ -356,7 +360,19 @@ export function registerAgentHandlers(pi, runtime, config) {
356
360
  if (runtime.rt.errorTextRepeatCount >=
357
361
  config.poisonedContextRepeatThreshold &&
358
362
  category === "transient") {
359
- effectiveCategory = "poisoned-context";
363
+ // R3/R7: upgrade only when the repeating error carries NO
364
+ // known-retryable marker. Network/throughput failures (timeout,
365
+ // ECONNRESET, 5xx, 429, connection lost, …) that repeat are
366
+ // still retryable — the API is just flaky, and /clear cannot fix
367
+ // them (2026-07-30 false-alarm incident). Only upgrade
368
+ // transient → poisoned-context for errors that repeat identically
369
+ // with no known-retryable cause, like the 2026-07-28 incident
370
+ // where the provider returned "Request failed — please retry."
371
+ // deterministically. The marker set is shared with classifyError
372
+ // (error-classifier.ts) so the two never drift.
373
+ if (!isKnownRetryableTransient(errSig)) {
374
+ effectiveCategory = "poisoned-context";
375
+ }
360
376
  }
361
377
  }
362
378
  }