pi-mega-compact 0.8.5 → 0.8.7

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.
@@ -0,0 +1,189 @@
1
+ /**
2
+ * mega-cache-replay.test.ts — locks the v0.8.7 cache-stability fix.
3
+ *
4
+ * Two tests (reuses the mega-teamrun.test.ts harness shape: mock pi + the REAL
5
+ * compiled extension at extensions/mega-compact.js):
6
+ * a. REPLAY: drive >=2 gated context events past the debounce within ONE epoch
7
+ * (same lastCheckpointId) and assert diagLiveTrimReplays > 0 AND the returned
8
+ * messages array is byte-identical (deepEqual) across replays (stable prefix).
9
+ * b. DEDUP-ON-DIFFERENT-CHECKPOINT: after a fresh trim, simulate a re-compact
10
+ * (context grew on the token basis) that DEDUPS onto a DIFFERENT existing
11
+ * checkpoint id (L0 contentHash match against an OLDER checkpoint, so
12
+ * result.checkpointId != rt.lastCheckpointId), then assert the NEXT gated
13
+ * event STILL replays (diagLiveTrimReplays increments) — i.e. the cache key
14
+ * trimCache.checkpointId === rt.lastCheckpointId holds. This is the P2 gap the
15
+ * v0.8.6 audit found: keying on the dedup-volatile result.checkpointId
16
+ * disabled replay for the rest of the epoch after such a dedup fire.
17
+ *
18
+ * MEGACOMPACT_PGLITE_DISABLED keeps the run fast (no WASM index init).
19
+ */
20
+ import { test } from "node:test";
21
+ import assert from "node:assert/strict";
22
+ import { mkdtempSync, rmSync } from "node:fs";
23
+ import { tmpdir } from "node:os";
24
+ import { join } from "node:path";
25
+ import { createRequire } from "node:module";
26
+ import { closeVectorIndex } from "../src/store/vectorIndex.js";
27
+ const require = createRequire(import.meta.url);
28
+ const baseTmp = mkdtempSync(join(tmpdir(), "mc-cache-"));
29
+ process.env.MEGACOMPACT_INDEX_DIR = join(baseTmp, "index");
30
+ process.env.MEGACOMPACT_PGLITE_DISABLED = "true"; // fast: skip WASM index
31
+ let counter = 0;
32
+ function harness() {
33
+ const stateDir = join(baseTmp, `run-${counter++}`);
34
+ process.env.MEGACOMPACT_STATE_DIR = stateDir;
35
+ process.env.MEGACOMPACT_DEBUG = "true";
36
+ process.env.MEGACOMPACT_THRESHOLD_TOKENS = "50";
37
+ process.env.MEGACOMPACT_FAST_GATE_PCT = "1";
38
+ process.env.MEGACOMPACT_ANCHOR_USER_MESSAGES = "1";
39
+ process.env.MEGACOMPACT_DURABLE_TRIM_FLOOR = "0";
40
+ process.env.MEGACOMPACT_MEMORY_AUTO_REVIEW = "false";
41
+ process.env.MEGACOMPACT_RAPTOR_ENABLED = "false";
42
+ // Disable the FUZZY dedup tiers (L1 MinHash/LSH + L2 cosine) so the DEDUP test
43
+ // is controlled by L0 contentHash only: setB (different vocabulary) then
44
+ // creates a genuinely NEW checkpoint instead of fuzzy-matching setA's, and
45
+ // setA-re-again still L0-contentHash-dedups onto the first setA checkpoint.
46
+ // The TrigramEmbedder otherwise matches on shared structural trigrams
47
+ // ("— step N" / "Edit"), collapsing setB onto setA. Harmless for the REPLAY
48
+ // test (pure replay, no dedup reliance).
49
+ process.env.MEGACOMPACT_L1_ENABLED = "false";
50
+ process.env.MEGACOMPACT_L2_ENABLED = "false";
51
+ delete process.env.MEGACOMPACT_LEGACY_DURABLE_TRIM;
52
+ // Mutable context-usage so tests can drive re-compact on the TOKEN basis by
53
+ // raising `tokens` while keeping `percent` null (→ token gate + token
54
+ // grewEnough path in context-handler.ts). The REPLAY test keeps percent=100 so
55
+ // the percent-basis grewEnough (>=10) never trips (no re-compact → pure replay).
56
+ const usage = { tokens: 200000, contextWindow: 200000, percent: 100 };
57
+ const handlers = {};
58
+ const compactCalls = [];
59
+ function msg(role, text, toolName) {
60
+ 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 };
62
+ }
63
+ if (role === "toolResult" && toolName) {
64
+ return { role: "toolResult", content: [{ type: "text", text }], toolCallId: "c1", toolName, isError: false, timestamp: 0 };
65
+ }
66
+ return { role: "user", content: text, timestamp: 0 };
67
+ }
68
+ // Build a session of `n` tool-call triples tagged `tag`. Set A and B differ in
69
+ // content (so B never dedups against A) but A === A reproduces the same
70
+ // regionText → same L0 contentHash → dedup onto the first A checkpoint.
71
+ function buildSession(tag, n) {
72
+ const s = [];
73
+ for (let i = 0; i < n; i++) {
74
+ s.push(msg("user", `[${tag}] we decided to use approach ${i} for module ${i}`));
75
+ s.push(msg("assistant", `[${tag}] edited module ${i}`, "Edit"));
76
+ s.push(msg("toolResult", `[${tag}] edited module ${i}`, "Edit"));
77
+ }
78
+ return s;
79
+ }
80
+ const toEntry = (m, i) => ({ type: "message", id: `e${i}`, parentId: null, timestamp: String(i), message: m });
81
+ const sessionManager = {
82
+ getSessionId: () => "sess_cache_001",
83
+ getEntries: () => buildSession("A", 14).map(toEntry),
84
+ getBranch: () => buildSession("A", 14).map(toEntry),
85
+ };
86
+ function makeCtx(over = {}) {
87
+ 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: () => { },
92
+ getContextUsage: () => ({ ...usage }),
93
+ compact: (opts) => { compactCalls.push(opts); return undefined; },
94
+ getSystemPrompt: () => "system base",
95
+ ...over,
96
+ };
97
+ }
98
+ const pi = {
99
+ on: (ev, h) => { handlers[ev] = h; },
100
+ registerCommand: () => { }, registerTool: () => { }, registerShortcut: () => { },
101
+ registerFlag: () => { }, getFlag: () => undefined, registerMessageRenderer: () => { },
102
+ registerEntryRenderer: () => { }, sendMessage: () => { }, sendUserMessage: () => { },
103
+ appendEntry: () => { }, setSessionName: () => { }, getSessionName: () => undefined,
104
+ setLabel: () => { }, exec: async () => ({ stdout: "", stderr: "", code: 0 }),
105
+ getActiveTools: () => [], getAllTools: () => [], setActiveTools: () => { },
106
+ getCommands: () => [], setModel: async () => false, getThinkingLevel: () => "off",
107
+ setThinkingLevel: () => { },
108
+ };
109
+ const mod = require("./mega-compact.js");
110
+ mod.default(pi);
111
+ const { lastRuntime } = require("./mega-events.js");
112
+ const fire = (ev, event, ctx) => handlers[ev](event, ctx);
113
+ return {
114
+ stateDir, handlers, compactCalls, fire, ctx: makeCtx, usage, buildSession,
115
+ runtime: lastRuntime, // MegaRuntime with diag* counters + rt + trimCache
116
+ // Bypass the 2s debounce so each fire proceeds without real waiting.
117
+ clearDebounce: () => { if (lastRuntime)
118
+ lastRuntime.debounceUntil = 0; },
119
+ };
120
+ }
121
+ test("REPLAY: >=2 gated context events within one epoch replay verbatim (byte-identical)", async () => {
122
+ const h = harness();
123
+ const ctx = h.ctx();
124
+ const session = h.buildSession("A", 14);
125
+ // Fire 3 gated context events; clearDebounce between so each passes the gate.
126
+ // percent stays 100 → percent-basis grewEnough (>=10) never trips → pure replay.
127
+ h.clearDebounce();
128
+ const r1 = await h.fire("context", { type: "context", messages: session }, ctx);
129
+ h.clearDebounce();
130
+ const r2 = await h.fire("context", { type: "context", messages: session }, ctx);
131
+ h.clearDebounce();
132
+ const r3 = await h.fire("context", { type: "context", messages: session }, ctx);
133
+ const rt = h.runtime;
134
+ assert.ok(rt.diagLiveTrimFires >= 1, "fresh trim fired on first event");
135
+ assert.ok(rt.diagLiveTrimReplays >= 2, `replay fired >=2 (got ${rt.diagLiveTrimReplays})`);
136
+ // byte-identical (stable KV-cache prefix) across replays
137
+ assert.deepEqual(r2?.messages, r3?.messages, "replay messages byte-identical across replays");
138
+ // replay matches the fresh-trim view (shallow-copy preserves content)
139
+ assert.deepEqual(r1?.messages, r2?.messages, "replay matches fresh-trim view (stable prefix)");
140
+ });
141
+ test("DEDUP: re-compact that dedups onto a DIFFERENT checkpoint still replays next (P2 fix)", async () => {
142
+ const h = harness();
143
+ // Token-basis growth path: percent null → token gate + token grewEnough
144
+ // (currentTokens - trimCache.ctxTokens >= effectiveThreshold * 0.5 = 25).
145
+ h.usage.percent = null;
146
+ h.usage.tokens = 200000;
147
+ const ctx = h.ctx();
148
+ const setA = h.buildSession("A", 14);
149
+ const setB = h.buildSession("B", 14); // different content, same length
150
+ const rt = h.runtime;
151
+ // 1) Fresh trim on setA → genuinely new checkpoint cp_A. lastCheckpointId = cp_A.
152
+ h.clearDebounce();
153
+ await h.fire("context", { type: "context", messages: setA }, ctx);
154
+ const cpA = rt.rt.lastCheckpointId;
155
+ assert.ok(cpA, "cp_A created on fresh trim");
156
+ assert.equal(rt.diagLiveTrimFires, 1, "first fire was a fresh trim");
157
+ // 2) Re-compact on setB (grew tokens) → genuinely new checkpoint cp_B (not deduped).
158
+ h.usage.tokens = 200100; // grew 100 >= 25
159
+ h.clearDebounce();
160
+ await h.fire("context", { type: "context", messages: setB }, ctx);
161
+ const cpB = rt.rt.lastCheckpointId;
162
+ assert.notEqual(cpB, cpA, "cp_B is a different, genuinely new checkpoint");
163
+ assert.equal(rt.rt.dedupSkips, 0, "setB did not dedup (different vocabulary, fuzzy tiers off)");
164
+ // 3) Re-compact on setA AGAIN (grew tokens) → L0 contentHash dedup onto cp_A.
165
+ // result.checkpointId = cp_A (!= lastCheckpointId cp_B); lastCheckpointId is
166
+ // NOT updated on a dedup (compact.ts:100-104), so it stays cp_B. With the
167
+ // fix, trimCache.checkpointId is keyed on lastCheckpointId (cp_B), NOT the
168
+ // dedup-volatile result.checkpointId (cp_A).
169
+ h.usage.tokens = 200200; // grew 100 >= 25
170
+ h.clearDebounce();
171
+ await h.fire("context", { type: "context", messages: setA }, ctx);
172
+ assert.equal(rt.rt.lastCheckpointId, cpB, "dedup did NOT bump lastCheckpointId (still cp_B)");
173
+ assert.ok(rt.rt.dedupSkips >= 1, "setA re-compact deduped onto an existing checkpoint");
174
+ // The P2 invariant: the cache key must equal the stable epoch signal.
175
+ assert.equal(rt.trimCache?.checkpointId, rt.rt.lastCheckpointId, "trimCache.checkpointId keyed on lastCheckpointId (P2 fix), not dedup-volatile result.checkpointId");
176
+ // 4) Next gated event (no growth) MUST replay instead of re-running runCompact.
177
+ // Without the fix, trimCache.checkpointId (cp_A) != lastCheckpointId (cp_B)
178
+ // → the replay condition is false → runCompact re-runs every fire → the
179
+ // thrash silently persists in that path (the audit's finding).
180
+ const replaysBefore = rt.diagLiveTrimReplays;
181
+ h.usage.tokens = 200200; // no growth → replay
182
+ h.clearDebounce();
183
+ await h.fire("context", { type: "context", messages: setA }, ctx);
184
+ assert.ok(rt.diagLiveTrimReplays > replaysBefore, `replay fired after dedup-onto-different-checkpoint (got ${rt.diagLiveTrimReplays}, was ${replaysBefore})`);
185
+ });
186
+ test("cleanup", async () => {
187
+ await closeVectorIndex();
188
+ rmSync(baseTmp, { recursive: true, force: true });
189
+ });
@@ -128,6 +128,7 @@ export function registerCompactHandlers(pi, runtime, config) {
128
128
  pi.on("session_compact", async (_event, _ctx) => {
129
129
  runtime.rt.lastNativeCompactAt = Date.now();
130
130
  runtime.rt.lastCompactAt = Date.now();
131
+ runtime.trimCache = null; // v0.8.6: durable truncation changes the transcript — never replay the stale cached cut (PREVENT-PI-001/002)
131
132
  runtime.logger.info("session-compacted", {
132
133
  sessionId: runtime.rt.sessionId,
133
134
  at: runtime.rt.lastCompactAt,
@@ -122,6 +122,36 @@ export function registerContextHandler(pi, runtime, config) {
122
122
  return;
123
123
  }
124
124
  runtime.debounceUntil = now + 2000;
125
+ // v0.8.6 cache-stability: replay the cached trim view when still in the
126
+ // same compaction epoch AND context hasn't grown enough to warrant a
127
+ // re-compact. This stabilizes the provider KV-cache prefix (the summary +
128
+ // cut are reused verbatim) instead of regenerating a fresh summary +
129
+ // sentinel every fire, which invalidated the prefix on every other turn
130
+ // (the alternating cache-miss regression). Re-compact only when context
131
+ // grew >=10% of the window (percent basis) or >=50% of the effective
132
+ // threshold (token basis, when percent is unavailable). The cached `cut`
133
+ // is only valid while the transcript grows within the epoch — it is
134
+ // cleared on session_compact (durable truncation) + resetRuntime, so we
135
+ // never replay a stale cut into a truncated transcript (PREVENT-PI-001/002).
136
+ const RECOMPACT_PCT_DELTA = 10;
137
+ if (runtime.trimCache &&
138
+ runtime.trimCache.checkpointId === runtime.rt.lastCheckpointId &&
139
+ runtime.trimCache.cut <= messages.length) {
140
+ const grewEnough = pct != null && runtime.trimCache.ctxPct != null
141
+ ? pct - runtime.trimCache.ctxPct >= RECOMPACT_PCT_DELTA
142
+ : currentTokens - (runtime.trimCache.ctxTokens ?? 0) >=
143
+ runtime.effectiveThreshold * 0.5;
144
+ if (!grewEnough) {
145
+ const recent = messages.slice(runtime.trimCache.cut); // guardrails-allow PREVENT-PI-002: cached `cut` was sanitized once by computeLiveTrimCut (src/boundary.ts) and replayed verbatim; the transcript only grows within an epoch (cache is cleared on durable truncation), so the preserved run still starts on a toolPair-safe index.
146
+ runtime.diagLiveTrimFires++; // trim view returned this call (replay counts as a fire)
147
+ runtime.diagLiveTrimReplays++;
148
+ runtime.snapshot(ctx);
149
+ // v0.8.7: shallow-copy the cached summary so pi's transformContext can't
150
+ // mutate the shared reference across replays (audit P3).
151
+ return { messages: [{ ...runtime.trimCache.summaryAgentMsg }, ...recent] };
152
+ }
153
+ // else: context grew enough → fall through to re-compact (cache is stale)
154
+ }
125
155
  // Adaptive compression (Fix E): scale compression strength + keepFrom depth
126
156
  // with how close we are to the model context limit. Null-safe: when the
127
157
  // token-fallback path ran (pct unavailable) use the token-basis pressure
@@ -224,9 +254,35 @@ export function registerContextHandler(pi, runtime, config) {
224
254
  const summaryAgentMsg = {
225
255
  role: "user",
226
256
  content: summaryMsg.text,
227
- timestamp: Date.now(),
257
+ // v0.8.6: stable timestamp across the epoch (NOT Date.now()) so the
258
+ // summary message bytes — and thus the KV-cache prefix — don't drift
259
+ // on every replay within the same compaction epoch.
260
+ timestamp: runtime.rt.lastCompactAt ?? Date.now(),
228
261
  };
229
262
  const recent = messages.slice(cut); // guardrails-allow PREVENT-PI-002: `cut` is the pre-sanitized `compactedFrom` produced by src/boundary.ts computeDropRange, so the preserved run begins on a toolPair-safe index.
263
+ // v0.8.6: cache the trim view so subsequent gated calls in this epoch
264
+ // replay it verbatim (stabilizing the KV-cache prefix) instead of
265
+ // regenerating a fresh summary + sentinel every fire.
266
+ runtime.trimCache = {
267
+ // v0.8.7: key the replay cache on the STABLE epoch signal
268
+ // (rt.lastCheckpointId) instead of ran.result.checkpointId, which is
269
+ // dedup-volatile: on a re-compact that dedups onto a DIFFERENT existing
270
+ // checkpoint, result.checkpointId is the matched id (engine.ts:188) while
271
+ // lastCheckpointId is only updated on a genuinely new checkpoint
272
+ // (compact.ts:100-104). Keying on result.checkpointId would make
273
+ // trimCache.checkpointId != rt.lastCheckpointId forever after that
274
+ // dedup fire, disabling replay for the rest of the epoch (the
275
+ // alternating cache-miss that 0.8.6 meant to fix). Prefer the stable
276
+ // signal; fall back to result.checkpointId then the epoch timestamp
277
+ // only for the no-checkpoint edge case.
278
+ checkpointId: runtime.rt.lastCheckpointId ??
279
+ ran.result.checkpointId ??
280
+ `epoch-${runtime.rt.lastCompactAt ?? Date.now()}`,
281
+ cut,
282
+ summaryAgentMsg,
283
+ ctxPct: pct ?? null,
284
+ ctxTokens: currentTokens,
285
+ };
230
286
  runtime.snapshot(ctx);
231
287
  // DIAG (team-run relief): confirm the live trim actually fires + how big
232
288
  // the window still is. The return is non-durable (per-LLM-call only), so
@@ -152,12 +152,19 @@ function doCompact(view, keepFrom, opts, sid, config, pi, ctx, runtime) {
152
152
  }
153
153
  // Sentinel marker: a non-LLM bookkeeping entry so subsequent triggers can
154
154
  // skip re-vectorizing an already-compacted region (zero token cost).
155
- pi.appendEntry(MARKER_TYPE, {
156
- checkpointId: result.checkpointId,
157
- regionHash: result.regionHash,
158
- tokenEstimate: result.tokenEstimate,
159
- deduped: result.deduped,
160
- });
155
+ // v0.8.6: gate on !result.deduped so the marker ONLY lands when a genuinely
156
+ // new checkpoint was created. Without this, every dedup re-fire appended a
157
+ // fresh sentinel to the real transcript, bloating it and perturbing the
158
+ // provider KV-cache prefix (the alternating cache-miss regression). Matches
159
+ // the RAPTOR + vector-index blocks above, which are already !deduped-gated.
160
+ if (!result.deduped) {
161
+ pi.appendEntry(MARKER_TYPE, {
162
+ checkpointId: result.checkpointId,
163
+ regionHash: result.regionHash,
164
+ tokenEstimate: result.tokenEstimate,
165
+ deduped: result.deduped,
166
+ });
167
+ }
161
168
  // Fix D: refresh the RAPTOR tree for this session so live recall (search) can
162
169
  // serve high-level summaries. Best-effort + non-fatal: never block compaction.
163
170
  // Budget-guarded (RAPTOR_BUDGET_MS) so it can't hang a large session.
@@ -50,6 +50,14 @@ export class MegaRuntime {
50
50
  cacheHitTokens: 0,
51
51
  lengthStopPending: false,
52
52
  };
53
+ // v0.8.6 cache-stability: the cached live-trim view for the current
54
+ // compaction epoch. Set after a fresh runCompact + computeLiveTrimCut, and
55
+ // replayed verbatim on subsequent gated context events in the SAME epoch
56
+ // (same checkpointId) so the provider KV-cache prefix stays stable instead
57
+ // of being invalidated by a freshly regenerated summary + sentinel every
58
+ // fire. Invalidated on session restart (resetRuntime) and on any native
59
+ // durable compaction (session_compact) that truncates the transcript.
60
+ trimCache = null;
53
61
  debounceUntil = 0;
54
62
  // S16: debounce for the agent_end resume nudge (avoid busy-loops).
55
63
  resumeNudgeUntil = 0;
@@ -159,6 +167,7 @@ export class MegaRuntime {
159
167
  * updated and cost nothing).
160
168
  */
161
169
  diagLiveTrimFires = 0; // context handler returned a trimmed view
170
+ diagLiveTrimReplays = 0; // v0.8.6: trim view returned via cached replay (skipped re-compact)
162
171
  diagBeforeCompactFires = 0; // session_before_compact handler entered
163
172
  diagBeforeCompactSupplied = 0; // session_before_compact supplied our trim
164
173
  diagAgentEndIdle = 0; // agent_end with activeAgents===0
@@ -714,6 +723,7 @@ export class MegaRuntime {
714
723
  cacheHitTokens: 0,
715
724
  lengthStopPending: false,
716
725
  };
726
+ this.trimCache = null; // v0.8.6: never replay a stale trim into a new session
717
727
  this.statusKey = undefined;
718
728
  this.activeAgents = 0;
719
729
  this.currentTurn = 0;
@@ -0,0 +1,211 @@
1
+ /**
2
+ * mega-cache-replay.test.ts — locks the v0.8.7 cache-stability fix.
3
+ *
4
+ * Two tests (reuses the mega-teamrun.test.ts harness shape: mock pi + the REAL
5
+ * compiled extension at extensions/mega-compact.js):
6
+ * a. REPLAY: drive >=2 gated context events past the debounce within ONE epoch
7
+ * (same lastCheckpointId) and assert diagLiveTrimReplays > 0 AND the returned
8
+ * messages array is byte-identical (deepEqual) across replays (stable prefix).
9
+ * b. DEDUP-ON-DIFFERENT-CHECKPOINT: after a fresh trim, simulate a re-compact
10
+ * (context grew on the token basis) that DEDUPS onto a DIFFERENT existing
11
+ * checkpoint id (L0 contentHash match against an OLDER checkpoint, so
12
+ * result.checkpointId != rt.lastCheckpointId), then assert the NEXT gated
13
+ * event STILL replays (diagLiveTrimReplays increments) — i.e. the cache key
14
+ * trimCache.checkpointId === rt.lastCheckpointId holds. This is the P2 gap the
15
+ * v0.8.6 audit found: keying on the dedup-volatile result.checkpointId
16
+ * disabled replay for the rest of the epoch after such a dedup fire.
17
+ *
18
+ * MEGACOMPACT_PGLITE_DISABLED keeps the run fast (no WASM index init).
19
+ */
20
+ import { test } from "node:test";
21
+ import assert from "node:assert/strict";
22
+ import { mkdtempSync, rmSync } from "node:fs";
23
+ import { tmpdir } from "node:os";
24
+ import { join } from "node:path";
25
+ import { createRequire } from "node:module";
26
+ import { closeVectorIndex } from "../src/store/vectorIndex.js";
27
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
28
+
29
+ const require = createRequire(import.meta.url);
30
+ const baseTmp = mkdtempSync(join(tmpdir(), "mc-cache-"));
31
+ process.env.MEGACOMPACT_INDEX_DIR = join(baseTmp, "index");
32
+ process.env.MEGACOMPACT_PGLITE_DISABLED = "true"; // fast: skip WASM index
33
+ let counter = 0;
34
+
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) => { handlers[ev] = 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 = (ev: string, event: any, ctx: any) => handlers[ev](event, ctx);
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
+ };
131
+ }
132
+
133
+ 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)");
154
+ });
155
+
156
+ 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})`);
206
+ });
207
+
208
+ test("cleanup", async () => {
209
+ await closeVectorIndex();
210
+ rmSync(baseTmp, { recursive: true, force: true });
211
+ });
@@ -159,6 +159,7 @@ export function registerCompactHandlers(
159
159
  pi.on("session_compact", async (_event: SessionCompactEvent, _ctx: ExtensionContext) => {
160
160
  runtime.rt.lastNativeCompactAt = Date.now();
161
161
  runtime.rt.lastCompactAt = Date.now();
162
+ runtime.trimCache = null; // v0.8.6: durable truncation changes the transcript — never replay the stale cached cut (PREVENT-PI-001/002)
162
163
  runtime.logger.info("session-compacted", {
163
164
  sessionId: runtime.rt.sessionId,
164
165
  at: runtime.rt.lastCompactAt,
@@ -157,6 +157,40 @@ export function registerContextHandler(
157
157
  }
158
158
  runtime.debounceUntil = now + 2000;
159
159
 
160
+ // v0.8.6 cache-stability: replay the cached trim view when still in the
161
+ // same compaction epoch AND context hasn't grown enough to warrant a
162
+ // re-compact. This stabilizes the provider KV-cache prefix (the summary +
163
+ // cut are reused verbatim) instead of regenerating a fresh summary +
164
+ // sentinel every fire, which invalidated the prefix on every other turn
165
+ // (the alternating cache-miss regression). Re-compact only when context
166
+ // grew >=10% of the window (percent basis) or >=50% of the effective
167
+ // threshold (token basis, when percent is unavailable). The cached `cut`
168
+ // is only valid while the transcript grows within the epoch — it is
169
+ // cleared on session_compact (durable truncation) + resetRuntime, so we
170
+ // never replay a stale cut into a truncated transcript (PREVENT-PI-001/002).
171
+ const RECOMPACT_PCT_DELTA = 10;
172
+ if (
173
+ runtime.trimCache &&
174
+ runtime.trimCache.checkpointId === runtime.rt.lastCheckpointId &&
175
+ runtime.trimCache.cut <= messages.length
176
+ ) {
177
+ const grewEnough =
178
+ pct != null && runtime.trimCache.ctxPct != null
179
+ ? pct - runtime.trimCache.ctxPct >= RECOMPACT_PCT_DELTA
180
+ : currentTokens - (runtime.trimCache.ctxTokens ?? 0) >=
181
+ runtime.effectiveThreshold * 0.5;
182
+ if (!grewEnough) {
183
+ const recent = messages.slice(runtime.trimCache.cut); // guardrails-allow PREVENT-PI-002: cached `cut` was sanitized once by computeLiveTrimCut (src/boundary.ts) and replayed verbatim; the transcript only grows within an epoch (cache is cleared on durable truncation), so the preserved run still starts on a toolPair-safe index.
184
+ runtime.diagLiveTrimFires++; // trim view returned this call (replay counts as a fire)
185
+ runtime.diagLiveTrimReplays++;
186
+ runtime.snapshot(ctx);
187
+ // v0.8.7: shallow-copy the cached summary so pi's transformContext can't
188
+ // mutate the shared reference across replays (audit P3).
189
+ return { messages: [{ ...runtime.trimCache.summaryAgentMsg }, ...recent] };
190
+ }
191
+ // else: context grew enough → fall through to re-compact (cache is stale)
192
+ }
193
+
160
194
  // Adaptive compression (Fix E): scale compression strength + keepFrom depth
161
195
  // with how close we are to the model context limit. Null-safe: when the
162
196
  // token-fallback path ran (pct unavailable) use the token-basis pressure
@@ -266,9 +300,36 @@ export function registerContextHandler(
266
300
  const summaryAgentMsg = {
267
301
  role: "user" as const,
268
302
  content: summaryMsg.text,
269
- timestamp: Date.now(),
303
+ // v0.8.6: stable timestamp across the epoch (NOT Date.now()) so the
304
+ // summary message bytes — and thus the KV-cache prefix — don't drift
305
+ // on every replay within the same compaction epoch.
306
+ timestamp: runtime.rt.lastCompactAt ?? Date.now(),
270
307
  } as unknown as AgentMessage;
271
308
  const recent = messages.slice(cut); // guardrails-allow PREVENT-PI-002: `cut` is the pre-sanitized `compactedFrom` produced by src/boundary.ts computeDropRange, so the preserved run begins on a toolPair-safe index.
309
+ // v0.8.6: cache the trim view so subsequent gated calls in this epoch
310
+ // replay it verbatim (stabilizing the KV-cache prefix) instead of
311
+ // regenerating a fresh summary + sentinel every fire.
312
+ runtime.trimCache = {
313
+ // v0.8.7: key the replay cache on the STABLE epoch signal
314
+ // (rt.lastCheckpointId) instead of ran.result.checkpointId, which is
315
+ // dedup-volatile: on a re-compact that dedups onto a DIFFERENT existing
316
+ // checkpoint, result.checkpointId is the matched id (engine.ts:188) while
317
+ // lastCheckpointId is only updated on a genuinely new checkpoint
318
+ // (compact.ts:100-104). Keying on result.checkpointId would make
319
+ // trimCache.checkpointId != rt.lastCheckpointId forever after that
320
+ // dedup fire, disabling replay for the rest of the epoch (the
321
+ // alternating cache-miss that 0.8.6 meant to fix). Prefer the stable
322
+ // signal; fall back to result.checkpointId then the epoch timestamp
323
+ // only for the no-checkpoint edge case.
324
+ checkpointId:
325
+ runtime.rt.lastCheckpointId ??
326
+ ran.result.checkpointId ??
327
+ `epoch-${runtime.rt.lastCompactAt ?? Date.now()}`,
328
+ cut,
329
+ summaryAgentMsg,
330
+ ctxPct: pct ?? null,
331
+ ctxTokens: currentTokens,
332
+ };
272
333
  runtime.snapshot(ctx);
273
334
  // DIAG (team-run relief): confirm the live trim actually fires + how big
274
335
  // the window still is. The return is non-durable (per-LLM-call only), so
@@ -192,12 +192,19 @@ function doCompact(
192
192
 
193
193
  // Sentinel marker: a non-LLM bookkeeping entry so subsequent triggers can
194
194
  // skip re-vectorizing an already-compacted region (zero token cost).
195
- pi.appendEntry(MARKER_TYPE, {
196
- checkpointId: result.checkpointId,
197
- regionHash: result.regionHash,
198
- tokenEstimate: result.tokenEstimate,
199
- deduped: result.deduped,
200
- });
195
+ // v0.8.6: gate on !result.deduped so the marker ONLY lands when a genuinely
196
+ // new checkpoint was created. Without this, every dedup re-fire appended a
197
+ // fresh sentinel to the real transcript, bloating it and perturbing the
198
+ // provider KV-cache prefix (the alternating cache-miss regression). Matches
199
+ // the RAPTOR + vector-index blocks above, which are already !deduped-gated.
200
+ if (!result.deduped) {
201
+ pi.appendEntry(MARKER_TYPE, {
202
+ checkpointId: result.checkpointId,
203
+ regionHash: result.regionHash,
204
+ tokenEstimate: result.tokenEstimate,
205
+ deduped: result.deduped,
206
+ });
207
+ }
201
208
 
202
209
  // Fix D: refresh the RAPTOR tree for this session so live recall (search) can
203
210
  // serve high-level summaries. Best-effort + non-fatal: never block compaction.
@@ -87,6 +87,20 @@ export class MegaRuntime {
87
87
  cacheHitTokens: 0,
88
88
  lengthStopPending: false,
89
89
  };
90
+ // v0.8.6 cache-stability: the cached live-trim view for the current
91
+ // compaction epoch. Set after a fresh runCompact + computeLiveTrimCut, and
92
+ // replayed verbatim on subsequent gated context events in the SAME epoch
93
+ // (same checkpointId) so the provider KV-cache prefix stays stable instead
94
+ // of being invalidated by a freshly regenerated summary + sentinel every
95
+ // fire. Invalidated on session restart (resetRuntime) and on any native
96
+ // durable compaction (session_compact) that truncates the transcript.
97
+ trimCache: {
98
+ checkpointId: string;
99
+ cut: number;
100
+ summaryAgentMsg: AgentMessage;
101
+ ctxPct: number | null;
102
+ ctxTokens: number | null;
103
+ } | null = null;
90
104
  debounceUntil = 0;
91
105
  // S16: debounce for the agent_end resume nudge (avoid busy-loops).
92
106
  resumeNudgeUntil = 0;
@@ -199,6 +213,7 @@ export class MegaRuntime {
199
213
  * updated and cost nothing).
200
214
  */
201
215
  diagLiveTrimFires = 0; // context handler returned a trimmed view
216
+ diagLiveTrimReplays = 0; // v0.8.6: trim view returned via cached replay (skipped re-compact)
202
217
  diagBeforeCompactFires = 0; // session_before_compact handler entered
203
218
  diagBeforeCompactSupplied = 0; // session_before_compact supplied our trim
204
219
  diagAgentEndIdle = 0; // agent_end with activeAgents===0
@@ -795,6 +810,7 @@ export class MegaRuntime {
795
810
  cacheHitTokens: 0,
796
811
  lengthStopPending: false,
797
812
  };
813
+ this.trimCache = null; // v0.8.6: never replay a stale trim into a new session
798
814
  this.statusKey = undefined;
799
815
  this.activeAgents = 0;
800
816
  this.currentTurn = 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mega-compact",
3
- "version": "0.8.5",
3
+ "version": "0.8.7",
4
4
  "description": "Layered, local, vector-backed context compressor for pi — supersede/collapse/cluster compaction with deduped inline recall.",
5
5
  "type": "module",
6
6
  "license": "BSD-2-Clause",