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
@@ -33,179 +33,494 @@ process.env.MEGACOMPACT_PGLITE_DISABLED = "true"; // fast: skip WASM index
33
33
  let counter = 0;
34
34
 
35
35
  function harness() {
36
- const stateDir = join(baseTmp, `run-${counter++}`);
37
- process.env.MEGACOMPACT_STATE_DIR = stateDir;
38
- process.env.MEGACOMPACT_DEBUG = "true";
39
- process.env.MEGACOMPACT_THRESHOLD_TOKENS = "50";
40
- process.env.MEGACOMPACT_FAST_GATE_PCT = "1";
41
- process.env.MEGACOMPACT_ANCHOR_USER_MESSAGES = "1";
42
- process.env.MEGACOMPACT_DURABLE_TRIM_FLOOR = "0";
43
- process.env.MEGACOMPACT_MEMORY_AUTO_REVIEW = "false";
44
- process.env.MEGACOMPACT_RAPTOR_ENABLED = "false";
45
- // Disable the FUZZY dedup tiers (L1 MinHash/LSH + L2 cosine) so the DEDUP test
46
- // is controlled by L0 contentHash only: setB (different vocabulary) then
47
- // creates a genuinely NEW checkpoint instead of fuzzy-matching setA's, and
48
- // setA-re-again still L0-contentHash-dedups onto the first setA checkpoint.
49
- // The TrigramEmbedder otherwise matches on shared structural trigrams
50
- // ("— step N" / "Edit"), collapsing setB onto setA. Harmless for the REPLAY
51
- // test (pure replay, no dedup reliance).
52
- process.env.MEGACOMPACT_L1_ENABLED = "false";
53
- process.env.MEGACOMPACT_L2_ENABLED = "false";
54
- delete process.env.MEGACOMPACT_LEGACY_DURABLE_TRIM;
55
-
56
- // Mutable context-usage so tests can drive re-compact on the TOKEN basis by
57
- // raising `tokens` while keeping `percent` null (→ token gate + token
58
- // grewEnough path in context-handler.ts). The REPLAY test keeps percent=100 so
59
- // the percent-basis grewEnough (>=10) never trips (no re-compact → pure replay).
60
- const usage = { tokens: 200000, contextWindow: 200000, percent: 100 as number | null };
61
-
62
- const handlers: Record<string, Function[]> = {};
63
- const compactCalls: any[] = [];
64
-
65
- function msg(role: string, text: string, toolName?: string): AgentMessage {
66
- if (role === "assistant" && toolName) {
67
- return { role: "assistant", content: [{ type: "toolCall", name: toolName, id: "c1", arguments: {} }], api: "anthropic-messages", provider: "anthropic", model: "m", usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 }, stopReason: "tool_use", timestamp: 0 } as unknown as AgentMessage;
68
- }
69
- if (role === "toolResult" && toolName) {
70
- return { role: "toolResult", content: [{ type: "text", text }], toolCallId: "c1", toolName, isError: false, timestamp: 0 } as unknown as AgentMessage;
71
- }
72
- return { role: "user", content: text, timestamp: 0 } as unknown as AgentMessage;
73
- }
74
-
75
- // Build a session of `n` tool-call triples tagged `tag`. Set A and B differ in
76
- // content (so B never dedups against A) but A === A reproduces the same
77
- // regionText → same L0 contentHash → dedup onto the first A checkpoint.
78
- function buildSession(tag: string, n: number): AgentMessage[] {
79
- const s: AgentMessage[] = [];
80
- for (let i = 0; i < n; i++) {
81
- s.push(msg("user", `[${tag}] we decided to use approach ${i} for module ${i}`));
82
- s.push(msg("assistant", `[${tag}] edited module ${i}`, "Edit"));
83
- s.push(msg("toolResult", `[${tag}] edited module ${i}`, "Edit"));
84
- }
85
- return s;
86
- }
87
-
88
- const toEntry = (m: AgentMessage, i: number): any => ({ type: "message", id: `e${i}`, parentId: null, timestamp: String(i), message: m });
89
- const sessionManager = {
90
- getSessionId: () => "sess_cache_001",
91
- getEntries: () => buildSession("A", 14).map(toEntry),
92
- getBranch: () => buildSession("A", 14).map(toEntry),
93
- };
94
-
95
- function makeCtx(over: Partial<any> = {}) {
96
- return {
97
- ui: { setStatus: () => {}, notify: () => {}, select: () => {}, confirm: async () => true, input: async () => "", setWidget: () => {} },
98
- mode: "tui" as any, hasUI: true, cwd: stateDir, sessionManager,
99
- modelRegistry: {} as any, model: undefined, isIdle: () => true, isProjectTrusted: () => true,
100
- signal: undefined, abort: () => {}, hasPendingMessages: () => false, shutdown: () => {},
101
- getContextUsage: () => ({ ...usage }),
102
- compact: (opts?: any) => { compactCalls.push(opts); return undefined; },
103
- getSystemPrompt: () => "system base",
104
- ...over,
105
- } as any;
106
- }
107
-
108
- const pi = {
109
- on: (ev: string, h: Function) => { if (!handlers[ev]) handlers[ev] = []; handlers[ev].push(h); },
110
- registerCommand: () => {}, registerTool: () => {}, registerShortcut: () => {},
111
- registerFlag: () => {}, getFlag: () => undefined, registerMessageRenderer: () => {},
112
- registerEntryRenderer: () => {}, sendMessage: () => {}, sendUserMessage: () => {},
113
- appendEntry: () => {}, setSessionName: () => {}, getSessionName: () => undefined,
114
- setLabel: () => {}, exec: async () => ({ stdout: "", stderr: "", code: 0 }),
115
- getActiveTools: () => [], getAllTools: () => [], setActiveTools: () => {},
116
- getCommands: () => [], setModel: async () => false, getThinkingLevel: () => "off" as any,
117
- setThinkingLevel: () => {},
118
- } as any;
119
-
120
- const mod = require("./mega-compact.js") as { default: (p: any) => void };
121
- mod.default(pi);
122
- const { lastRuntime } = require("./mega-events.js") as { lastRuntime: any };
123
-
124
- const fire = async (ev: string, event: any, ctx: any) => { let r: any; for (const h of handlers[ev] || []) r = await h(event, ctx); return r; };
125
- return {
126
- stateDir, handlers, compactCalls, fire, ctx: makeCtx, usage, buildSession,
127
- runtime: lastRuntime, // MegaRuntime with diag* counters + rt + trimCache
128
- // Bypass the 2s debounce so each fire proceeds without real waiting.
129
- clearDebounce: () => { if (lastRuntime) lastRuntime.debounceUntil = 0; },
130
- };
36
+ const stateDir = join(baseTmp, `run-${counter++}`);
37
+ process.env.MEGACOMPACT_STATE_DIR = stateDir;
38
+ process.env.MEGACOMPACT_DEBUG = "true";
39
+ process.env.MEGACOMPACT_THRESHOLD_TOKENS = "50";
40
+ process.env.MEGACOMPACT_FAST_GATE_PCT = "1";
41
+ process.env.MEGACOMPACT_ANCHOR_USER_MESSAGES = "1";
42
+ process.env.MEGACOMPACT_DURABLE_TRIM_FLOOR = "0";
43
+ process.env.MEGACOMPACT_MEMORY_AUTO_REVIEW = "false";
44
+ process.env.MEGACOMPACT_RAPTOR_ENABLED = "false";
45
+ // Disable the FUZZY dedup tiers (L1 MinHash/LSH + L2 cosine) so the DEDUP test
46
+ // is controlled by L0 contentHash only: setB (different vocabulary) then
47
+ // creates a genuinely NEW checkpoint instead of fuzzy-matching setA's, and
48
+ // setA-re-again still L0-contentHash-dedups onto the first setA checkpoint.
49
+ // The TrigramEmbedder otherwise matches on shared structural trigrams
50
+ // ("— step N" / "Edit"), collapsing setB onto setA. Harmless for the REPLAY
51
+ // test (pure replay, no dedup reliance).
52
+ process.env.MEGACOMPACT_L1_ENABLED = "false";
53
+ process.env.MEGACOMPACT_L2_ENABLED = "false";
54
+ delete process.env.MEGACOMPACT_LEGACY_DURABLE_TRIM;
55
+
56
+ // Mutable context-usage so tests can drive re-compact on the TOKEN basis by
57
+ // raising `tokens` while keeping `percent` null (→ token gate + token
58
+ // grewEnough path in context-handler.ts). The REPLAY test keeps percent=100 so
59
+ // the percent-basis grewEnough (>=10) never trips (no re-compact → pure replay).
60
+ const usage = {
61
+ tokens: 200000,
62
+ contextWindow: 200000,
63
+ percent: 100 as number | null,
64
+ };
65
+
66
+ const handlers: Record<string, Function[]> = {};
67
+ const compactCalls: any[] = [];
68
+
69
+ function msg(role: string, text: string, toolName?: string): AgentMessage {
70
+ if (role === "assistant" && toolName) {
71
+ return {
72
+ role: "assistant",
73
+ content: [
74
+ { type: "toolCall", name: toolName, id: "c1", arguments: {} },
75
+ ],
76
+ api: "anthropic-messages",
77
+ provider: "anthropic",
78
+ model: "m",
79
+ usage: {
80
+ inputTokens: 1,
81
+ outputTokens: 1,
82
+ cacheReadTokens: 0,
83
+ cacheWriteTokens: 0,
84
+ },
85
+ stopReason: "tool_use",
86
+ timestamp: 0,
87
+ } as unknown as AgentMessage;
88
+ }
89
+ if (role === "toolResult" && toolName) {
90
+ return {
91
+ role: "toolResult",
92
+ content: [{ type: "text", text }],
93
+ toolCallId: "c1",
94
+ toolName,
95
+ isError: false,
96
+ timestamp: 0,
97
+ } as unknown as AgentMessage;
98
+ }
99
+ return {
100
+ role: "user",
101
+ content: text,
102
+ timestamp: 0,
103
+ } as unknown as AgentMessage;
104
+ }
105
+
106
+ // Build a session of `n` tool-call triples tagged `tag`. Set A and B differ in
107
+ // content (so B never dedups against A) but A === A reproduces the same
108
+ // regionText same L0 contentHash → dedup onto the first A checkpoint.
109
+ function buildSession(tag: string, n: number): AgentMessage[] {
110
+ const s: AgentMessage[] = [];
111
+ for (let i = 0; i < n; i++) {
112
+ s.push(
113
+ msg("user", `[${tag}] we decided to use approach ${i} for module ${i}`),
114
+ );
115
+ s.push(msg("assistant", `[${tag}] edited module ${i}`, "Edit"));
116
+ s.push(msg("toolResult", `[${tag}] edited module ${i}`, "Edit"));
117
+ }
118
+ return s;
119
+ }
120
+
121
+ const toEntry = (m: AgentMessage, i: number): any => ({
122
+ type: "message",
123
+ id: `e${i}`,
124
+ parentId: null,
125
+ timestamp: String(i),
126
+ message: m,
127
+ });
128
+ const sessionManager = {
129
+ getSessionId: () => "sess_cache_001",
130
+ getEntries: () => buildSession("A", 14).map(toEntry),
131
+ getBranch: () => buildSession("A", 14).map(toEntry),
132
+ };
133
+
134
+ function makeCtx(over: Partial<any> = {}) {
135
+ return {
136
+ ui: {
137
+ setStatus: () => {},
138
+ notify: () => {},
139
+ select: () => {},
140
+ confirm: async () => true,
141
+ input: async () => "",
142
+ setWidget: () => {},
143
+ },
144
+ mode: "tui" as any,
145
+ hasUI: true,
146
+ cwd: stateDir,
147
+ sessionManager,
148
+ modelRegistry: {} as any,
149
+ model: undefined,
150
+ isIdle: () => true,
151
+ isProjectTrusted: () => true,
152
+ signal: undefined,
153
+ abort: () => {},
154
+ hasPendingMessages: () => false,
155
+ shutdown: () => {},
156
+ getContextUsage: () => ({ ...usage }),
157
+ compact: (opts?: any) => {
158
+ compactCalls.push(opts);
159
+ return undefined;
160
+ },
161
+ getSystemPrompt: () => "system base",
162
+ ...over,
163
+ } as any;
164
+ }
165
+
166
+ const pi = {
167
+ on: (ev: string, h: Function) => {
168
+ if (!handlers[ev]) handlers[ev] = [];
169
+ handlers[ev].push(h);
170
+ },
171
+ registerCommand: () => {},
172
+ registerTool: () => {},
173
+ registerShortcut: () => {},
174
+ registerFlag: () => {},
175
+ getFlag: () => undefined,
176
+ registerMessageRenderer: () => {},
177
+ registerEntryRenderer: () => {},
178
+ sendMessage: () => {},
179
+ sendUserMessage: () => {},
180
+ appendEntry: () => {},
181
+ setSessionName: () => {},
182
+ getSessionName: () => undefined,
183
+ setLabel: () => {},
184
+ exec: async () => ({ stdout: "", stderr: "", code: 0 }),
185
+ getActiveTools: () => [],
186
+ getAllTools: () => [],
187
+ setActiveTools: () => {},
188
+ getCommands: () => [],
189
+ setModel: async () => false,
190
+ getThinkingLevel: () => "off" as any,
191
+ setThinkingLevel: () => {},
192
+ } as any;
193
+
194
+ const mod = require("./mega-compact.js") as { default: (p: any) => void };
195
+ mod.default(pi);
196
+ const { lastRuntime } = require("./mega-events.js") as { lastRuntime: any };
197
+
198
+ const fire = async (ev: string, event: any, ctx: any) => {
199
+ let r: any;
200
+ for (const h of handlers[ev] || []) r = await h(event, ctx);
201
+ return r;
202
+ };
203
+ return {
204
+ stateDir,
205
+ handlers,
206
+ compactCalls,
207
+ fire,
208
+ ctx: makeCtx,
209
+ usage,
210
+ buildSession,
211
+ runtime: lastRuntime, // MegaRuntime with diag* counters + rt + trimCache
212
+ // Bypass the 2s debounce so each fire proceeds without real waiting.
213
+ clearDebounce: () => {
214
+ if (lastRuntime) lastRuntime.debounceUntil = 0;
215
+ },
216
+ };
131
217
  }
132
218
 
133
219
  test("REPLAY: >=2 gated context events within one epoch replay verbatim (byte-identical)", async () => {
134
- const h = harness();
135
- const ctx = h.ctx();
136
- const session = h.buildSession("A", 14);
137
-
138
- // Fire 3 gated context events; clearDebounce between so each passes the gate.
139
- // percent stays 100 → percent-basis grewEnough (>=10) never trips → pure replay.
140
- h.clearDebounce();
141
- const r1 = await h.fire("context", { type: "context", messages: session }, ctx);
142
- h.clearDebounce();
143
- const r2 = await h.fire("context", { type: "context", messages: session }, ctx);
144
- h.clearDebounce();
145
- const r3 = await h.fire("context", { type: "context", messages: session }, ctx);
146
-
147
- const rt = h.runtime;
148
- assert.ok(rt.diagLiveTrimFires >= 1, "fresh trim fired on first event");
149
- assert.ok(rt.diagLiveTrimReplays >= 2, `replay fired >=2 (got ${rt.diagLiveTrimReplays})`);
150
- // byte-identical (stable KV-cache prefix) across replays
151
- assert.deepEqual(r2?.messages, r3?.messages, "replay messages byte-identical across replays");
152
- // replay matches the fresh-trim view (shallow-copy preserves content)
153
- assert.deepEqual(r1?.messages, r2?.messages, "replay matches fresh-trim view (stable prefix)");
220
+ const h = harness();
221
+ const ctx = h.ctx();
222
+ const session = h.buildSession("A", 14);
223
+
224
+ // Fire 3 gated context events; clearDebounce between so each passes the gate.
225
+ // percent stays 100 → percent-basis grewEnough (>=10) never trips → pure replay.
226
+ h.clearDebounce();
227
+ const r1 = await h.fire(
228
+ "context",
229
+ { type: "context", messages: session },
230
+ ctx,
231
+ );
232
+ h.clearDebounce();
233
+ const r2 = await h.fire(
234
+ "context",
235
+ { type: "context", messages: session },
236
+ ctx,
237
+ );
238
+ h.clearDebounce();
239
+ const r3 = await h.fire(
240
+ "context",
241
+ { type: "context", messages: session },
242
+ ctx,
243
+ );
244
+
245
+ const rt = h.runtime;
246
+ assert.ok(rt.diagLiveTrimFires >= 1, "fresh trim fired on first event");
247
+ assert.ok(
248
+ rt.diagLiveTrimReplays >= 2,
249
+ `replay fired >=2 (got ${rt.diagLiveTrimReplays})`,
250
+ );
251
+ // byte-identical (stable KV-cache prefix) across replays
252
+ assert.deepEqual(
253
+ r2?.messages,
254
+ r3?.messages,
255
+ "replay messages byte-identical across replays",
256
+ );
257
+ // replay matches the fresh-trim view (shallow-copy preserves content)
258
+ assert.deepEqual(
259
+ r1?.messages,
260
+ r2?.messages,
261
+ "replay matches fresh-trim view (stable prefix)",
262
+ );
154
263
  });
155
264
 
156
265
  test("DEDUP: re-compact that dedups onto a DIFFERENT checkpoint still replays next (P2 fix)", async () => {
157
- const h = harness();
158
- // Token-basis growth path: percent null → token gate + token grewEnough
159
- // (currentTokens - trimCache.ctxTokens >= effectiveThreshold * 0.5 = 25).
160
- h.usage.percent = null;
161
- h.usage.tokens = 200000;
162
- const ctx = h.ctx();
163
- const setA = h.buildSession("A", 14);
164
- const setB = h.buildSession("B", 14); // different content, same length
165
- const rt = h.runtime;
166
-
167
- // 1) Fresh trim on setA → genuinely new checkpoint cp_A. lastCheckpointId = cp_A.
168
- h.clearDebounce();
169
- await h.fire("context", { type: "context", messages: setA }, ctx);
170
- const cpA = rt.rt.lastCheckpointId;
171
- assert.ok(cpA, "cp_A created on fresh trim");
172
- assert.equal(rt.diagLiveTrimFires, 1, "first fire was a fresh trim");
173
-
174
- // 2) Re-compact on setB (grew tokens) → genuinely new checkpoint cp_B (not deduped).
175
- h.usage.tokens = 200100; // grew 100 >= 25
176
- h.clearDebounce();
177
- await h.fire("context", { type: "context", messages: setB }, ctx);
178
- const cpB = rt.rt.lastCheckpointId;
179
- assert.notEqual(cpB, cpA, "cp_B is a different, genuinely new checkpoint");
180
- assert.equal(rt.rt.dedupSkips, 0, "setB did not dedup (different vocabulary, fuzzy tiers off)");
181
-
182
- // 3) Re-compact on setA AGAIN (grew tokens) → L0 contentHash dedup onto cp_A.
183
- // result.checkpointId = cp_A (!= lastCheckpointId cp_B); lastCheckpointId is
184
- // NOT updated on a dedup (compact.ts:100-104), so it stays cp_B. With the
185
- // fix, trimCache.checkpointId is keyed on lastCheckpointId (cp_B), NOT the
186
- // dedup-volatile result.checkpointId (cp_A).
187
- h.usage.tokens = 200200; // grew 100 >= 25
188
- h.clearDebounce();
189
- await h.fire("context", { type: "context", messages: setA }, ctx);
190
- assert.equal(rt.rt.lastCheckpointId, cpB, "dedup did NOT bump lastCheckpointId (still cp_B)");
191
- assert.ok(rt.rt.dedupSkips >= 1, "setA re-compact deduped onto an existing checkpoint");
192
- // The P2 invariant: the cache key must equal the stable epoch signal.
193
- assert.equal(rt.trimCache?.checkpointId, rt.rt.lastCheckpointId,
194
- "trimCache.checkpointId keyed on lastCheckpointId (P2 fix), not dedup-volatile result.checkpointId");
195
-
196
- // 4) Next gated event (no growth) MUST replay instead of re-running runCompact.
197
- // Without the fix, trimCache.checkpointId (cp_A) != lastCheckpointId (cp_B)
198
- // → the replay condition is false → runCompact re-runs every fire → the
199
- // thrash silently persists in that path (the audit's finding).
200
- const replaysBefore = rt.diagLiveTrimReplays;
201
- h.usage.tokens = 200200; // no growth → replay
202
- h.clearDebounce();
203
- await h.fire("context", { type: "context", messages: setA }, ctx);
204
- assert.ok(rt.diagLiveTrimReplays > replaysBefore,
205
- `replay fired after dedup-onto-different-checkpoint (got ${rt.diagLiveTrimReplays}, was ${replaysBefore})`);
266
+ const h = harness();
267
+ // Token-basis growth path: percent null → token gate + token grewEnough
268
+ // (currentTokens - trimCache.ctxTokens >= effectiveThreshold * 0.5 = 25).
269
+ h.usage.percent = null;
270
+ h.usage.tokens = 200000;
271
+ const ctx = h.ctx();
272
+ const setA = h.buildSession("A", 14);
273
+ const setB = h.buildSession("B", 14); // different content, same length
274
+ const rt = h.runtime;
275
+
276
+ // 1) Fresh trim on setA → genuinely new checkpoint cp_A. lastCheckpointId = cp_A.
277
+ h.clearDebounce();
278
+ await h.fire("context", { type: "context", messages: setA }, ctx);
279
+ const cpA = rt.rt.lastCheckpointId;
280
+ assert.ok(cpA, "cp_A created on fresh trim");
281
+ assert.equal(rt.diagLiveTrimFires, 1, "first fire was a fresh trim");
282
+
283
+ // 2) Re-compact on setB (grew tokens) → genuinely new checkpoint cp_B (not deduped).
284
+ h.usage.tokens = 200100; // grew 100 >= 25
285
+ h.clearDebounce();
286
+ await h.fire("context", { type: "context", messages: setB }, ctx);
287
+ const cpB = rt.rt.lastCheckpointId;
288
+ assert.notEqual(cpB, cpA, "cp_B is a different, genuinely new checkpoint");
289
+ assert.equal(
290
+ rt.rt.dedupSkips,
291
+ 0,
292
+ "setB did not dedup (different vocabulary, fuzzy tiers off)",
293
+ );
294
+
295
+ // 3) Re-compact on setA AGAIN (grew tokens) → L0 contentHash dedup onto cp_A.
296
+ // result.checkpointId = cp_A (!= lastCheckpointId cp_B); lastCheckpointId is
297
+ // NOT updated on a dedup (compact.ts:100-104), so it stays cp_B. With the
298
+ // fix, trimCache.checkpointId is keyed on lastCheckpointId (cp_B), NOT the
299
+ // dedup-volatile result.checkpointId (cp_A).
300
+ h.usage.tokens = 200200; // grew 100 >= 25
301
+ h.clearDebounce();
302
+ await h.fire("context", { type: "context", messages: setA }, ctx);
303
+ assert.equal(
304
+ rt.rt.lastCheckpointId,
305
+ cpB,
306
+ "dedup did NOT bump lastCheckpointId (still cp_B)",
307
+ );
308
+ assert.ok(
309
+ rt.rt.dedupSkips >= 1,
310
+ "setA re-compact deduped onto an existing checkpoint",
311
+ );
312
+ // The P2 invariant: the cache key must equal the stable epoch signal.
313
+ assert.equal(
314
+ rt.trimCache?.checkpointId,
315
+ rt.rt.lastCheckpointId,
316
+ "trimCache.checkpointId keyed on lastCheckpointId (P2 fix), not dedup-volatile result.checkpointId",
317
+ );
318
+
319
+ // 4) Next gated event (no growth) MUST replay instead of re-running runCompact.
320
+ // Without the fix, trimCache.checkpointId (cp_A) != lastCheckpointId (cp_B)
321
+ // → the replay condition is false → runCompact re-runs every fire → the
322
+ // thrash silently persists in that path (the audit's finding).
323
+ const replaysBefore = rt.diagLiveTrimReplays;
324
+ h.usage.tokens = 200200; // no growth → replay
325
+ h.clearDebounce();
326
+ await h.fire("context", { type: "context", messages: setA }, ctx);
327
+ assert.ok(
328
+ rt.diagLiveTrimReplays > replaysBefore,
329
+ `replay fired after dedup-onto-different-checkpoint (got ${rt.diagLiveTrimReplays}, was ${replaysBefore})`,
330
+ );
331
+ });
332
+
333
+ // D.4-test-1 — Debounce exemption: the replay path sits BEFORE the debounce guard.
334
+ // Two gated events <2s apart (no clearDebounce) must both replay — diagCtxDebounce
335
+ // must NOT increment because the debounce guard is never reached when replay fires.
336
+ test("DEBOUNCE-EXEMPTION: two events <2s apart (no clearDebounce) both replay; debounce never reached", async () => {
337
+ const h = harness();
338
+ const ctx = h.ctx();
339
+ const session = h.buildSession("A", 14);
340
+
341
+ // 1) Fresh trim.
342
+ h.clearDebounce(); // first event always needs a clear to pass the time guard
343
+ await h.fire("context", { type: "context", messages: session }, ctx);
344
+ assert.equal(h.runtime.diagLiveTrimFires, 1, "first fire was fresh trim");
345
+
346
+ // 2) Fire two events IN QUICK SUCCESSION without clearing the debounce.
347
+ // The replay path (D.2) sits BEFORE the debounce guard, so both should
348
+ // replay the cached trim and the debounce guard is NEVER reached.
349
+ const dbgBefore = h.runtime.diagCtxDebounce;
350
+ const rpyBefore = h.runtime.diagLiveTrimReplays;
351
+
352
+ await h.fire("context", { type: "context", messages: session }, ctx);
353
+ await h.fire("context", { type: "context", messages: session }, ctx);
354
+
355
+ assert.equal(
356
+ h.runtime.diagCtxDebounce,
357
+ dbgBefore,
358
+ `debounce counter unchanged (${h.runtime.diagCtxDebounce} == ${dbgBefore}) — replay path was reached, not debounce`,
359
+ );
360
+ assert.ok(
361
+ h.runtime.diagLiveTrimReplays >= rpyBefore + 2,
362
+ `both events replayed (replays ${h.runtime.diagLiveTrimReplays} >= ${rpyBefore}+2)`,
363
+ );
364
+ });
365
+
366
+ // D.4-test-2 — Skip→replay fallback: when runCompact returns {skipped: true} and
367
+ // a valid trimCache exists, the handler replays the cached trim instead of returning
368
+ // empty. We force a skip by firing with a 1-message session (view.length ≤ 1) AFTER
369
+ // a fresh trim with a full session has populated trimCache.
370
+ test("SKIP-FALLBACK: runCompact skipped + valid trimCache → replays cached trim", async () => {
371
+ const h = harness();
372
+ const ctx = h.ctx();
373
+ const session = h.buildSession("A", 14);
374
+
375
+ // 1) Fresh trim with full session → populates trimCache with a valid cut.
376
+ h.clearDebounce();
377
+ await h.fire("context", { type: "context", messages: session }, ctx);
378
+ assert.equal(
379
+ h.runtime.diagLiveTrimFires,
380
+ 1,
381
+ "fresh trim populated trimCache",
382
+ );
383
+ assert.ok(h.runtime.trimCache, "trimCache is set");
384
+
385
+ // 2) Lower the cut so a 1-message session still passes the cut≤length guard.
386
+ // The skip→replay path checks cut <= messages.length before replaying.
387
+ h.runtime.trimCache.cut = 0;
388
+
389
+ // 3) Drive context growth so grewEnough=true (replay skipped → runCompact runs).
390
+ // Then fire with just 1 message → runCompact: view.length ≤ 1 → {skipped: true}.
391
+ h.usage.percent = null; // token-basis path
392
+ h.usage.tokens = 200100; // grew 100 >= 25 (effectiveThreshold * 0.5)
393
+ h.clearDebounce();
394
+ const oneMsg = [h.buildSession("X", 1)[0]]; // single user message
395
+ await h.fire("context", { type: "context", messages: oneMsg }, ctx);
396
+
397
+ assert.ok(
398
+ h.runtime.diagCtxRunSkipped >= 1,
399
+ `diagCtxRunSkipped incremented (got ${h.runtime.diagCtxRunSkipped})`,
400
+ );
401
+ // The skip path replays trimCache → diagLiveTrimReplays increments.
402
+ assert.ok(
403
+ h.runtime.diagLiveTrimReplays >= 1,
404
+ `skip→replay fired (replays ${h.runtime.diagLiveTrimReplays} >= 1)`,
405
+ );
406
+ });
407
+
408
+ // D.4-test-3 — Recompact delta boundary: config.recompactPctDelta = 50.
409
+ // 49% growth → replay (not enough to re-compact).
410
+ // 51% growth → fresh compaction (exceeds the 50% delta threshold).
411
+ //
412
+ // diagLiveTrimFires counts every trim response (replay OR fresh), including
413
+ // the initial fresh trim, so cumulative counts can't validate discrete steps.
414
+ // Instead we snapshot (fires, replays) before each step and assert the delta.
415
+ test("DELTA-BOUNDARY: 49% growth → replay; 51% growth → fresh compaction", async () => {
416
+ const h = harness();
417
+ const ctx = h.ctx();
418
+ const session = h.buildSession("A", 14);
419
+
420
+ // Start at low context (percent=5). The handler captures ctxPct from the first
421
+ // trim, then checks pct - ctxPct >= 50 (config.recompactPctDelta default=50).
422
+ h.usage.percent = 5;
423
+ h.usage.tokens = 200000;
424
+
425
+ // 1) Fresh trim at pct=5 → trimCache.ctxPct = 5.
426
+ h.clearDebounce();
427
+ await h.fire("context", { type: "context", messages: session }, ctx);
428
+ assert.ok(h.runtime.diagLiveTrimFires >= 1, "fresh trim at pct=5");
429
+ assert.equal(h.runtime.trimCache?.ctxPct, 5, "ctxPct captured as 5");
430
+
431
+ // 2) 49% growth: pct=54. grewEnough = 54-5 = 49 < 50 → replay.
432
+ // Replay increments BOTH fires and replays (line 247-248).
433
+ h.usage.percent = 54;
434
+ h.clearDebounce();
435
+ const { fires: f2, replays: r2 } = {
436
+ fires: h.runtime.diagLiveTrimFires,
437
+ replays: h.runtime.diagLiveTrimReplays,
438
+ };
439
+ await h.fire("context", { type: "context", messages: session }, ctx);
440
+ assert.equal(
441
+ h.runtime.diagLiveTrimFires,
442
+ f2 + 1,
443
+ `49% growth: fires +1 (replay counted as fire, ${f2}→${h.runtime.diagLiveTrimFires})`,
444
+ );
445
+ assert.equal(
446
+ h.runtime.diagLiveTrimReplays,
447
+ r2 + 1,
448
+ `49% growth: replays +1 (${r2}→${h.runtime.diagLiveTrimReplays})`,
449
+ );
450
+
451
+ // 3) 51% growth: pct=56. grewEnough = 56-5 = 51 >= 50 → falls through to
452
+ // debounce → runCompact → fresh compaction (line 509).
453
+ // Fresh compaction increments fires but NOT replays.
454
+ h.usage.percent = 56;
455
+ h.clearDebounce();
456
+ const { fires: f3, replays: r3 } = {
457
+ fires: h.runtime.diagLiveTrimFires,
458
+ replays: h.runtime.diagLiveTrimReplays,
459
+ };
460
+ await h.fire("context", { type: "context", messages: session }, ctx);
461
+ assert.equal(
462
+ h.runtime.diagLiveTrimFires,
463
+ f3 + 1,
464
+ `51% growth: fires +1 (fresh compaction, ${f3}→${h.runtime.diagLiveTrimFires})`,
465
+ );
466
+ assert.equal(
467
+ h.runtime.diagLiveTrimReplays,
468
+ r3,
469
+ `51% growth: replays unchanged (fresh compaction ≠ replay, stays ${r3})`,
470
+ );
471
+ });
472
+
473
+ // D.4-test-4 — Epoch invalidation (PREVENT-PI-001/002 guard): a checkpointId
474
+ // mismatch means the durable transcript was truncated (session_compact or
475
+ // resetRuntime). The replay guard MUST reject a stale trimCache in that case.
476
+ test("EPOCH-INVALIDATION: checkpointId mismatch → replay does NOT fire (PREVENT-PI-001/002)", async () => {
477
+ const h = harness();
478
+ const ctx = h.ctx();
479
+ const session = h.buildSession("A", 14);
480
+
481
+ // 1) Fresh trim → trimCache.checkpointId = lastCheckpointId = "cp-1".
482
+ h.clearDebounce();
483
+ await h.fire("context", { type: "context", messages: session }, ctx);
484
+ assert.equal(h.runtime.diagLiveTrimFires, 1, "fresh trim");
485
+ assert.ok(h.runtime.trimCache?.checkpointId, "trimCache has checkpointId");
486
+
487
+ // 2) Simulate a session_compact (durable truncation) by advancing
488
+ // lastCheckpointId (harder: the compact path tracks its own epoch).
489
+ // A mismatch between trimCache.checkpointId and rt.lastCheckpointId means
490
+ // the cached cut is for a truncated transcript → replay must NOT fire.
491
+ h.runtime.rt.lastCheckpointId = "cp-mismatch";
492
+ assert.notEqual(
493
+ h.runtime.trimCache?.checkpointId,
494
+ h.runtime.rt.lastCheckpointId,
495
+ "checkpointIds differ after simulated durable truncation",
496
+ );
497
+
498
+ // 3) Fire the same session (no growth → would normally replay if epoch matched).
499
+ const rpyBefore = h.runtime.diagLiveTrimReplays;
500
+ h.clearDebounce();
501
+ await h.fire("context", { type: "context", messages: session }, ctx);
502
+
503
+ // Replay path was blocked by the checkpointId guard → a fresh trim fires instead.
504
+ assert.equal(
505
+ h.runtime.diagLiveTrimReplays,
506
+ rpyBefore,
507
+ `replay NOT incremented (was ${rpyBefore}, still ${h.runtime.diagLiveTrimReplays}) — stale trimCache rejected`,
508
+ );
509
+ // A fresh compaction should have been triggered instead (grewEnough=false, but
510
+ // replay guard failed → falls through to debounce → runCompact → fresh trim).
511
+ // Actually: grewEnough is false (no growth since last fire), and the replay
512
+ // guard rejected → falls to debounce (cleared) → runCompact.
513
+ // runCompact may skip or produce a fresh trim; either way the stale replay is blocked.
514
+ assert.ok(
515
+ h.runtime.diagLiveTrimFires >= 2 || h.runtime.diagCtxRunSkipped >= 1,
516
+ `handler did NOT replay stale trimCache (fires=${h.runtime.diagLiveTrimFires}, skipped=${h.runtime.diagCtxRunSkipped}, replays=${h.runtime.diagLiveTrimReplays})`,
517
+ );
518
+
519
+ // Restore for cleanup.
520
+ h.runtime.rt.lastCheckpointId = "cp-1";
206
521
  });
207
522
 
208
523
  test("cleanup", async () => {
209
- await closeVectorIndex();
210
- rmSync(baseTmp, { recursive: true, force: true });
524
+ await closeVectorIndex();
525
+ rmSync(baseTmp, { recursive: true, force: true });
211
526
  });