pi-mega-compact 0.7.8 → 0.7.9

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 (112) hide show
  1. package/README.md +11 -12
  2. package/dist/extensions/dashboard-server/helpers.js +37 -0
  3. package/dist/extensions/dashboard-server/html/all-repos-tab.js +26 -0
  4. package/dist/extensions/dashboard-server/html/body-open.js +23 -0
  5. package/dist/extensions/dashboard-server/html/current-repo-tab.js +130 -0
  6. package/dist/extensions/dashboard-server/html/head-open.js +16 -0
  7. package/dist/extensions/dashboard-server/html/high-score-tab.js +25 -0
  8. package/dist/extensions/dashboard-server/html/repo-detail-modal.js +26 -0
  9. package/dist/extensions/dashboard-server/html/script.js +259 -0
  10. package/dist/extensions/dashboard-server/html/styles.js +103 -0
  11. package/dist/extensions/dashboard-server/html/summary-tab.js +19 -0
  12. package/dist/extensions/dashboard-server/html-template.js +41 -0
  13. package/dist/extensions/dashboard-server/html.js +756 -0
  14. package/dist/extensions/dashboard-server/index-reader.js +133 -0
  15. package/dist/extensions/dashboard-server/server.js +370 -0
  16. package/dist/extensions/dashboard-server/snapshot.js +43 -0
  17. package/dist/extensions/dashboard-server/state.js +30 -0
  18. package/dist/extensions/dashboard-server/types.js +5 -0
  19. package/dist/extensions/dashboard-server.js +7 -1315
  20. package/dist/extensions/mega-commands.js +162 -134
  21. package/dist/extensions/mega-compact.test.js +90 -21
  22. package/dist/extensions/mega-conflict-cmds.js +5 -1
  23. package/dist/extensions/mega-dashboard-cmds.js +29 -22
  24. package/dist/extensions/mega-db-cmds.js +11 -2
  25. package/dist/extensions/mega-events/agent-handlers.js +173 -0
  26. package/dist/extensions/mega-events/compact-handlers.js +133 -0
  27. package/dist/extensions/mega-events/context-handler.js +249 -0
  28. package/dist/extensions/mega-events/register.js +21 -0
  29. package/dist/extensions/mega-events/session-handlers.js +142 -0
  30. package/dist/extensions/mega-events.js +15 -699
  31. package/dist/extensions/mega-pipeline/compact.js +324 -0
  32. package/dist/extensions/mega-pipeline/memory-review.js +38 -0
  33. package/dist/extensions/mega-pipeline/recall.js +147 -0
  34. package/dist/extensions/mega-pipeline.js +9 -480
  35. package/dist/extensions/mega-runtime/helpers.js +40 -0
  36. package/dist/extensions/mega-runtime/query.js +29 -0
  37. package/dist/extensions/mega-runtime/state.js +711 -0
  38. package/dist/extensions/mega-runtime/widget.js +197 -0
  39. package/dist/extensions/mega-runtime.js +15 -947
  40. package/dist/src/store/sqlite/checkpoints.js +145 -0
  41. package/dist/src/store/sqlite/connection.js +35 -0
  42. package/dist/src/store/sqlite/dedup-mirror.js +64 -0
  43. package/dist/src/store/sqlite/foundation.js +38 -0
  44. package/dist/src/store/sqlite/global-index.js +224 -0
  45. package/dist/src/store/sqlite/index-store.js +167 -0
  46. package/dist/src/store/sqlite/maintenance.js +235 -0
  47. package/dist/src/store/sqlite/memories.js +164 -0
  48. package/dist/src/store/sqlite/memory.js +54 -0
  49. package/dist/src/store/sqlite/meta.js +82 -0
  50. package/dist/src/store/sqlite/minhash-lsh.js +47 -0
  51. package/dist/src/store/sqlite/model-snapshots.js +47 -0
  52. package/dist/src/store/sqlite/raptor.js +57 -0
  53. package/dist/src/store/sqlite/raw-transcript.js +134 -0
  54. package/dist/src/store/sqlite/schema.js +250 -0
  55. package/dist/src/store/sqlite/session-state.js +28 -0
  56. package/dist/src/store/sqlite/sessions.js +39 -0
  57. package/dist/src/store/sqlite/stats.js +66 -0
  58. package/dist/src/store/sqlite/transaction.js +19 -0
  59. package/dist/src/store/sqlite/utils.js +120 -0
  60. package/dist/src/store/sqlite.js +20 -1607
  61. package/dist/src/vectorStore/add.js +260 -0
  62. package/dist/src/vectorStore/dedup.js +52 -0
  63. package/dist/src/vectorStore/index.js +10 -0
  64. package/dist/src/vectorStore/queries.js +83 -0
  65. package/dist/src/vectorStore/search.js +95 -0
  66. package/dist/src/vectorStore/session.js +19 -0
  67. package/dist/src/vectorStore/store.js +105 -0
  68. package/dist/src/vectorStore/types.js +6 -0
  69. package/dist/src/vectorStore/utils.js +23 -0
  70. package/extensions/dashboard-server/html.ts +758 -0
  71. package/extensions/dashboard-server/index-reader.ts +130 -0
  72. package/extensions/dashboard-server/server.ts +358 -0
  73. package/extensions/dashboard-server/snapshot.ts +44 -0
  74. package/extensions/dashboard-server/state.ts +33 -0
  75. package/extensions/dashboard-server/types.ts +134 -0
  76. package/extensions/dashboard-server.ts +7 -1431
  77. package/extensions/mega-commands.ts +33 -10
  78. package/extensions/mega-compact.test.ts +198 -43
  79. package/extensions/mega-conflict-cmds.ts +6 -2
  80. package/extensions/mega-dashboard-cmds.ts +30 -23
  81. package/extensions/mega-db-cmds.ts +11 -3
  82. package/extensions/mega-events/agent-handlers.ts +214 -0
  83. package/extensions/mega-events/compact-handlers.ts +164 -0
  84. package/extensions/mega-events/context-handler.ts +290 -0
  85. package/extensions/mega-events/register.ts +37 -0
  86. package/extensions/mega-events/session-handlers.ts +165 -0
  87. package/extensions/mega-events.ts +15 -780
  88. package/extensions/mega-pipeline/compact.ts +366 -0
  89. package/extensions/mega-pipeline/memory-review.ts +46 -0
  90. package/extensions/mega-pipeline/recall.ts +165 -0
  91. package/extensions/mega-pipeline.ts +9 -537
  92. package/extensions/mega-runtime/helpers.ts +68 -0
  93. package/extensions/mega-runtime/query.ts +29 -0
  94. package/extensions/mega-runtime/state.ts +797 -0
  95. package/extensions/mega-runtime/widget.ts +258 -0
  96. package/extensions/mega-runtime.ts +15 -1093
  97. package/package.json +4 -3
  98. package/src/store/sqlite/checkpoints.ts +204 -0
  99. package/src/store/sqlite/dedup-mirror.ts +114 -0
  100. package/src/store/sqlite/foundation.ts +63 -0
  101. package/src/store/sqlite/global-index.ts +305 -0
  102. package/src/store/sqlite/maintenance.ts +294 -0
  103. package/src/store/sqlite/memories.ts +217 -0
  104. package/src/store/sqlite/meta.ts +108 -0
  105. package/src/store/sqlite/model-snapshots.ts +83 -0
  106. package/src/store/sqlite/raptor.ts +107 -0
  107. package/src/store/sqlite/raw-transcript.ts +221 -0
  108. package/src/store/sqlite/schema.ts +258 -0
  109. package/src/store/sqlite/session-state.ts +38 -0
  110. package/src/store/sqlite/stats.ts +127 -0
  111. package/src/store/sqlite/utils.ts +125 -0
  112. package/src/store/sqlite.ts +20 -2204
@@ -1,701 +1,17 @@
1
- /**
2
- * mega-events.ts — the pi lifecycle event handlers.
1
+ /** mega-events.ts — barrel re-exporting all pi lifecycle event handlers.
3
2
  *
4
- * Wires every pi event the extension listens for: model/provider capture,
5
- * session lifecycle + state reset, auto-inline injection, agent/turn tracking,
6
- * and the auto-trigger compaction pipeline. Keeps the shared MegaRuntime in
7
- * sync and delegates the heavy lifting to the pipeline + command modules.
3
+ * Split into focused submodules under extensions/mega-events/:
4
+ * - register.ts: lastRuntime + registerEventHandlers (entry point)
5
+ * - session-handlers.ts: session lifecycle (model_select, session_start,
6
+ * session_tree, before_agent_start, session_shutdown)
7
+ * - agent-handlers.ts: agent/turn tracking (agent_start, agent_end,
8
+ * turn_start, turn_end)
9
+ * - context-handler.ts: live-trim auto-trigger (context event)
10
+ * - compact-handlers.ts: native compaction (session_before_compact,
11
+ * session_compact)
8
12
  */
9
- import { normalizeSessionId } from "../src/store.js";
10
- import { openStore, appendRawTranscript, writeCheckpointEpoch, autoMaintain } from "../src/store/sqlite.js";
11
- import { epochIdFor } from "../src/mirror/epoch.js";
12
- import { autoCompactCheck } from "../src/compact.js";
13
- import { estimateSessionTokens, estimateBlockTokens } from "../src/tokens.js";
14
- import { recentUserQuery, WIDGET_KEY, } from "./mega-runtime.js";
15
- import { runCompact, doRecall, doRecallAsync, piCompactWouldNoop, runMemoryReview, } from "./mega-pipeline.js";
16
- import { recallMemoriesAndInline } from "../src/recall.js";
17
- import { driveNativeCompaction, } from "./mega-compact-driver.js";
18
- import { computeLiveTrimCut, liveTrimSummaryMessage } from "./mega-trim.js";
19
- import { pressureFromPct, pressureRatio, memoryReviewCadence, } from "./mega-config.js";
20
- import { createHash } from "node:crypto";
21
- /**
22
- * Convert a pi AgentMessage to a RawTranscriptRow for the DB mirror.
23
- * content_bytes is canonical JSON (sorted keys) for deterministic hashing.
24
- * Returns null if the message has no usable content.
25
- */
26
- function toRawTranscriptRow(msg, sessionId, epochId) {
27
- // Narrow to Message union (has content + timestamp).
28
- const m = msg;
29
- const content = m.content;
30
- if (content == null || content === "")
31
- return null;
32
- // Canonical form: sort object keys for deterministic hashing.
33
- const contentBytes = typeof content === "string"
34
- ? content
35
- : JSON.stringify(content, Object.keys(content).sort());
36
- const contentHash = createHash("sha256").update(contentBytes).digest("hex");
37
- return {
38
- contentHash,
39
- sessionId,
40
- seq: 0, // assigned by appendRawTranscript (COALESCE(MAX(seq),0)+1)
41
- role: m.role ?? "unknown",
42
- contentBytes,
43
- toolName: m.toolName ?? null,
44
- messageTimestamp: m.timestamp ?? null,
45
- checkpointEpoch: epochId,
46
- };
47
- }
48
- /**
49
- * DIAG accessor for the headless test harness: the most recently constructed
50
- * MegaRuntime, so a test that loads the compiled extension via its default
51
- * export can read diag counters (diagLiveTrimFires / diagBeforeCompactFires /
52
- * diagBeforeCompactSupplied / diagAgentEndIdle) after firing synthetic events.
53
- * No-op in production — nothing reads this outside tests.
54
- */
55
- export let lastRuntime;
56
- /** Register all pi lifecycle event handlers. */
57
- export function registerEventHandlers(pi, runtime, config) {
58
- lastRuntime = runtime;
59
- // ---- Session lifecycle (state reset points) -------------------------------
60
- // Capture model/provider whenever it changes (drives real cost estimation).
61
- pi.on("model_select", async (_event, ctx) => {
62
- runtime.captureModel(ctx);
63
- runtime.snapshot(ctx);
64
- });
65
- pi.on("session_start", async (event, ctx) => {
66
- runtime.resetRuntime(ctx.sessionManager.getSessionId());
67
- runtime.captureModel(ctx); // best-effort: ctx.model may be set by session start
68
- runtime.setStatus(ctx, config.auto ? "mega-compact: ready" : "mega-compact: manual only");
69
- // S21: clear any stale memory block from a prior session.
70
- runtime.pendingMemoryRecallBlock = undefined;
71
- // Auto-inline on resume/fork/continue: stage the most relevant checkpoints
72
- // so the next before_agent_start prepends them to the system prompt.
73
- // Triggered whenever this session already has persisted checkpoints AND a
74
- // usable query — that covers reason "resume"/"fork" (explicit) and
75
- // reason "startup" (e.g. `pi --continue`s an existing session, which still
76
- // emits "startup" but with a populated message window). A brand-new empty
77
- // session has no checkpoints, so it's naturally excluded.
78
- if (config.autoInline) {
79
- const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
80
- const query = recentUserQuery(ctx);
81
- if (query && runtime.store.stats(sid).checkpointCount > 0) {
82
- // S17: use the async variant on resume so cross-repo HNSW recall can
83
- // augment when this repo's store is thin. session_start is an async-safe
84
- // point (unlike the mid-turn context handler, which stays sync).
85
- const r = await doRecallAsync(runtime, config, ctx, query, "resume", {
86
- crossRepo: config.crossRepoEnabled,
87
- });
88
- if (!r.empty) {
89
- runtime.pendingRecallBlock = r.block;
90
- const crossLabel = r.toInject.some((h) => h.repoId)
91
- ? " (cross-repo)"
92
- : "";
93
- runtime.setStatus(ctx, `mega-compact: recalled ${r.toInject.length} chkpt${crossLabel}`);
94
- runtime.logger.info("auto-inline", {
95
- reason: event.reason,
96
- query,
97
- injected: r.toInject.map((h) => h.checkpoint.checkpointId),
98
- crossRepo: r.toInject.some((h) => h.repoId),
99
- });
100
- }
101
- }
102
- // S21: parallel memory recall. Same async context so we can await without
103
- // breaking the handler contract. Best-effort — never throws.
104
- try {
105
- const mr = await recallMemoriesAndInline({
106
- query,
107
- stateDir: runtime.getStateDir(),
108
- limit: 5,
109
- crossRepo: config.crossRepoEnabled,
110
- crossRepoCosine: config.crossRepoCosine,
111
- });
112
- if (!mr.empty)
113
- runtime.pendingMemoryRecallBlock = mr.block;
114
- }
115
- catch (err) {
116
- runtime.logger.warn("memory-recall skipped", { err: String(err) });
117
- }
118
- }
119
- // S27 Task 10: best-effort auto-maintenance on session start (prune rows
120
- // older than 30d, checkpoint WAL if >10MB, VACUUM if DB >100MB + >20%
121
- // freelist). Never blocks session start — swallows errors and logs a
122
- // one-line summary for diagnostics.
123
- try {
124
- const m = autoMaintain(runtime.currentStateDir);
125
- if (m && !m.endsWith("nothing to do"))
126
- runtime.logger.info("db-auto-maintain", { result: m });
127
- }
128
- catch (e) {
129
- runtime.logger.warn("db-auto-maintain-fail", { error: String(e) });
130
- }
131
- runtime.dashboard.event("session_start", {
132
- reason: event.reason,
133
- sessionId: runtime.rt.sessionId,
134
- });
135
- runtime.snapshot(ctx);
136
- });
137
- pi.on("session_tree", async (_event, ctx) => {
138
- // Branch navigation invalidates region indexes — reset checkpoint memory but
139
- // keep the on-disk store (markers replayed from entries below if needed).
140
- runtime.resetRuntime(ctx.sessionManager.getSessionId());
141
- runtime.setStatus(ctx, "mega-compact: ready (branch)");
142
- if (config.autoInline) {
143
- const query = recentUserQuery(ctx);
144
- if (query) {
145
- const r = doRecall(runtime, config, ctx, query, "resume");
146
- if (!r.empty) {
147
- runtime.pendingRecallBlock = r.block;
148
- runtime.logger.info("auto-inline", {
149
- reason: "session_tree",
150
- query,
151
- injected: r.toInject.map((h) => h.checkpoint.checkpointId),
152
- });
153
- }
154
- // S21: parallel memory recall. Trigram embedder is sub-ms; await is fine.
155
- try {
156
- const mr = await recallMemoriesAndInline({
157
- query,
158
- stateDir: runtime.getStateDir(),
159
- limit: 5,
160
- crossRepo: config.crossRepoEnabled,
161
- crossRepoCosine: config.crossRepoCosine,
162
- });
163
- if (!mr.empty)
164
- runtime.pendingMemoryRecallBlock = mr.block;
165
- }
166
- catch (err) {
167
- runtime.logger.warn("memory-recall skipped", { err: String(err) });
168
- }
169
- }
170
- }
171
- runtime.dashboard.event("session_tree", {
172
- sessionId: runtime.rt.sessionId,
173
- });
174
- runtime.snapshot(ctx);
175
- });
176
- // ---- Auto-inline injection point: prepend staged recall to systemPrompt ----
177
- pi.on("before_agent_start", async (event, ctx) => {
178
- runtime.captureModel(ctx); // most reliable point ctx.model is populated
179
- const cpBlock = runtime.pendingRecallBlock;
180
- const memBlock = runtime.pendingMemoryRecallBlock;
181
- if (!cpBlock && !memBlock)
182
- return;
183
- runtime.pendingRecallBlock = undefined;
184
- runtime.pendingMemoryRecallBlock = undefined;
185
- const composed = [cpBlock, memBlock].filter(Boolean).join("\n\n");
186
- return { systemPrompt: `${event.systemPrompt}\n\n${composed}` };
187
- });
188
- pi.on("session_shutdown", async (_event, ctx) => {
189
- runtime.setStatus(ctx, undefined);
190
- runtime.activeAgents = 0;
191
- runtime.currentTurn = 0;
192
- ctx.ui.setWidget(WIDGET_KEY, [], { placement: "aboveEditor" });
193
- });
194
- // ---- Agent tracking for real-time widget + status-line updates ---------
195
- pi.on("agent_start", async (_event, ctx) => {
196
- runtime.activeAgents++;
197
- runtime.dashboard.event("agent_start", {
198
- activeAgents: runtime.activeAgents,
199
- });
200
- // Surface live agent activity on the status line (toolbar), not just the
201
- // above-editor widget — otherwise concurrent agents look frozen.
202
- runtime.setStatus(ctx, `mega-compact: ▶ ${runtime.activeAgents} agent${runtime.activeAgents === 1 ? "" : "s"}`);
203
- runtime.snapshot(ctx);
204
- });
205
- pi.on("agent_end", async (_event, ctx) => {
206
- runtime.activeAgents = Math.max(0, runtime.activeAgents - 1);
207
- runtime.dashboard.event("agent_end", {
208
- activeAgents: runtime.activeAgents,
209
- });
210
- if (runtime.activeAgents > 0) {
211
- runtime.setStatus(ctx, `mega-compact: ▶ ${runtime.activeAgents} agent${runtime.activeAgents === 1 ? "" : "s"}`);
212
- }
213
- else {
214
- runtime.setStatus(ctx, config.auto ? "mega-compact: ready" : "mega-compact: manual only");
215
- }
216
- // S16 continuation fallback: if the turn settled idle right after a live-trim
217
- // compaction AND there is queued work AND we haven't nudged recently, nudge
218
- // once so the agent continues (the live trim should make this rare). Guarded
219
- // to never busy-loop: one nudge per 30s, only when truly idle + queued.
220
- if ((config.auto || config.autoContinueLengthStop) && runtime.activeAgents === 0) {
221
- try {
222
- const idle = ctx.isIdle?.() ?? true;
223
- const queued = ctx.hasPendingMessages?.() ?? false;
224
- const now = Date.now();
225
- // DIAG (team-run relief): surface whether the agent is idle + over
226
- // threshold at agent_end so we can see if a mid-run durable-trim trigger
227
- // *should* have fired but didn't.
228
- const overThreshold = (runtime.lastCtxTokens ?? 0) >= runtime.effectiveThreshold;
229
- runtime.diagAgentEndIdle++;
230
- runtime.logger.info("agent-end-idle", {
231
- sessionId: runtime.rt.sessionId,
232
- idle,
233
- queued,
234
- overThreshold,
235
- ctxPct: runtime.lastCtxPercent,
236
- ctxTokens: runtime.lastCtxTokens,
237
- thresholdTokens: config.thresholdTokens,
238
- wouldNudge: idle &&
239
- (queued || overThreshold) &&
240
- now >= runtime.resumeNudgeUntil,
241
- });
242
- // S16+S24: MID-RUN DURABLE TRIM. During a long team run (sub-agents),
243
- // pi's native durable compaction only fires from _checkCompaction at
244
- // PARENT settle (agent-session.js:760/844), so the on-disk transcript +
245
- // context meter balloon to ~150k and never relieve until the very end
246
- // ("compacts but doesn't resume"). agent_end with activeAgents===0 is a
247
- // SAFE, settled point: calling ctx.compact() here does NOT abort an
248
- // in-flight turn (the S16 danger is only mid-turn). ctx.compact() runs
249
- // pi's flow, which fires our session_before_compact handler to supply
250
- // the durable trim (truncates the transcript from firstKeptEntryId).
251
- // Guarded three ways: only when truly idle + over threshold, only when
252
- // pi would actually compact (piCompactWouldNoop skips the user-facing
253
- // no-op throw), and debounced (one durable trim per 2s) to avoid
254
- // thrashing the transcript while sub-agents keep settling.
255
- //
256
- // FIX "compacts but doesn't resume": the manual ctx.compact() path
257
- // STOPS the agent loop (agent-session.js:1345). The old resume-nudge
258
- // was gated on `queued`, so when a sub-agent settled with no
259
- // *immediately* queued message, the trim fired but the nudge did not,
260
- // and the (stopped) session hung. The trim still fires on
261
- // `idle && overThreshold` — we intentionally do NOT add a `!queued`
262
- // guard, because that would suppress mid-run relief exactly during
263
- // team-run waves where queued is usually true and relief is needed
264
- // most. Instead we DECOUPLE the nudge from `queued`: after a durable
265
- // trim we ALWAYS nudge so the agent reliably restarts. Debounced 30s.
266
- let didDurableTrim = false;
267
- if (config.auto && idle && overThreshold && now >= runtime.debounceUntil) {
268
- // COMPACT-DEDUP FIX: skip the manual durable-trim trigger when pi's
269
- // NATIVE auto-compaction just fired (or is in-flight). pi emits
270
- // agent_end BEFORE its own _checkCompaction (per its docstring:
271
- // "Called after agent_end and before prompt submission"), so a
272
- // synchronous `piCompactWouldNoop` branch check misses a native
273
- // compaction that hasn't appended its entry yet — calling
274
- // ctx.compact() then races with pi and throws "Already compacted"
275
- // to the user. The `lastCompactAt` cooldown (updated by the
276
- // session_compact listener for EVERY compaction, native or
277
- // extension-supplied) closes that race window.
278
- const sinceCompact = now - (runtime.rt.lastNativeCompactAt ?? 0);
279
- if (sinceCompact < 10_000) {
280
- runtime.diagAgentEndDurableSkipRecent++;
281
- }
282
- else if (!piCompactWouldNoop(ctx)) {
283
- runtime.debounceUntil = now + 2000;
284
- runtime.diagAgentEndDurable++;
285
- runtime.logger.info("agent-end-durable-trigger", {
286
- sessionId: runtime.rt.sessionId,
287
- ctxTokens: runtime.lastCtxTokens,
288
- thresholdTokens: config.thresholdTokens,
289
- queued,
290
- });
291
- ctx.compact({ customInstructions: undefined }); // guardrails-allow PREVENT-PI-004: local ctx.compact() — no network; agent settled so no in-flight abort. Race-guarded by lastCompactAt cooldown above (ctx.compact returns void → throw is surfaced by pi as compaction_end; the cooldown prevents the call entirely).
292
- didDurableTrim = true;
293
- }
294
- }
295
- // Restart the agent after a mid-run durable trim (which stopped it), or
296
- // when it settled idle with queued work. Decoupled from `queued` for the
297
- // durable-trim case — see FIX note above. Debounced 30s; never blocks.
298
- const lengthStop = config.autoContinueLengthStop && runtime.rt.lengthStopPending;
299
- if (idle &&
300
- now >= runtime.resumeNudgeUntil &&
301
- ((config.auto && (didDurableTrim || queued)) || lengthStop)) {
302
- runtime.resumeNudgeUntil = now + 30_000;
303
- if (runtime.rt.lengthStopPending) {
304
- runtime.rt.lengthStopPending = false; // one-shot: never re-fire for same stop
305
- runtime.dashboard.event("length_stop_continue", { turnIndex: runtime.currentTurn });
306
- runtime.logger.info("length_stop_continue", {
307
- sessionId: runtime.rt.sessionId,
308
- didDurableTrim,
309
- queued,
310
- });
311
- }
312
- // S28: when a length-stop (max-output-token truncation) fired WITHOUT a durable trim, do NOT claim a compaction happened
313
- // (nothing was compacted on the low-pressure length path). Branch the message so the nudge matches reality.
314
- const nudgeMsg = lengthStop && !didDurableTrim
315
- ? "[mega-compact] the last response hit the output-token cap; continue from where it stopped."
316
- : "[mega-compact] continue from the compacted context above.";
317
- pi.sendUserMessage(nudgeMsg);
318
- }
319
- }
320
- catch {
321
- /* non-fatal: a failed nudge never blocks */
322
- }
323
- }
324
- runtime.snapshot(ctx);
325
- });
326
- pi.on("turn_start", async (event, ctx) => {
327
- runtime.currentTurn = event.turnIndex;
328
- runtime.rt.lengthStopPending = false; // S28: re-arm defensively each user turn
329
- runtime.dashboard.event("turn_start", { turnIndex: event.turnIndex });
330
- runtime.snapshot(ctx);
331
- });
332
- pi.on("turn_end", async (event, ctx) => {
333
- runtime.dashboard.event("turn_end", { turnIndex: event.turnIndex });
334
- runtime.snapshot(ctx);
335
- // S20+S24: auto-review the conversation and persist durable memories. The
336
- // review cadence scales with pressure (memoryReviewCadence): as context
337
- // fills, the conversation is reviewed more often so memories keep pace with
338
- // faster churn. Best-effort + non-fatal: a review failure must never break
339
- // the agent loop. Debounced by the pressure-adjusted interval.
340
- if (config.memoryAutoReview && runtime.currentTurn > 0) {
341
- const cadence = memoryReviewCadence(runtime.pressureBand, config.memoryReviewInterval);
342
- if (runtime.currentTurn % cadence === 0) {
343
- // S20+S24: review the conversation and persist durable memories. The
344
- // cadence scales with pressure (memoryReviewCadence): as context fills,
345
- // the conversation is reviewed more often so memories keep pace with
346
- // faster churn. Shared runMemoryReview body (also used on compact).
347
- const entries = ctx.sessionManager.getEntries();
348
- const view = runtime.engineView(entries.flatMap((e) => (e.message ? [e.message] : [])));
349
- await runMemoryReview(runtime, view, "turn");
350
- }
351
- }
352
- // S28: detect max-output-token truncation. event.message.stopReason is the
353
- // pi-ai StopReason union; 'length' == generation hit max_tokens OUTPUT cap
354
- // (INPUT-orthogonal to context-window overflow). Arm the agent_end nudge.
355
- if (config.autoContinueLengthStop &&
356
- event.message.role === "assistant" &&
357
- event.message.stopReason === "length") {
358
- runtime.rt.lengthStopPending = true;
359
- runtime.dashboard.event("length_stop", { turnIndex: event.turnIndex });
360
- }
361
- });
362
- // ---- Auto-trigger: live trim (compact and continue) + native durable ----
363
- // S16 redesign: we NO LONGER call ctx.compact() from the auto-trigger by
364
- // default. That mapped to pi's MANUAL compaction path, which abort()s the
365
- // in-flight turn (agent-session.js:1345) and stops the agent. Instead:
366
- // - LIVE: return { messages: trimmedView } from the context event. This
367
- // feeds pi's transformContext (sdk.js:226 → agent-loop.js:180) so the
368
- // model sees a compacted window EVERY LLM call, with no abort. The turn
369
- // continues. We persist our recall checkpoint (the durable value) first.
370
- // - DURABLE: pi's NATIVE auto-compaction fires at agent-end
371
- // (agent-session.js:1565), continues (return hasQueuedMessages()), and
372
- // emits session_before_compact — where OUR driveNativeCompaction supplies
373
- // the summary and pi truncates the transcript on disk. No ctx.compact().
374
- // Legacy: MEGACOMPACT_LEGACY_DURABLE_TRIM=true restores the v0.4.28 ctx.compact
375
- // path (kept one release as rollback).
376
- pi.on("context", async (event, ctx) => {
377
- if (!config.auto)
378
- return;
379
- const usage = ctx.getContextUsage();
380
- const pct = usage?.percent;
381
- // Always track context for the dashboard, even if we return early below.
382
- runtime.lastCtxTokens = usage?.tokens ?? null;
383
- runtime.lastCtxPercent = pct ?? null;
384
- runtime.lastCtxWindow = usage?.contextWindow ?? 0;
385
- runtime.snapshot(ctx);
386
- const messages = event.messages;
387
- const view = runtime.engineView(messages);
388
- const currentTokens = usage?.tokens ??
389
- estimateSessionTokens(view) ??
390
- Math.round(((pct ?? 0) / 100) * (usage?.contextWindow ?? 0));
391
- // S27 DB-mirror: append ALL incoming messages to raw_transcript.
392
- // Runs BEFORE fast-gate so every message is captured, even if we
393
- // don't compact this turn. Append is idempotent (content_hash PK).
394
- if (config.dbMirror) {
395
- try {
396
- const db = openStore(runtime.currentStateDir);
397
- const epochId = epochIdFor(runtime.rt.sessionId);
398
- for (const msg of messages) {
399
- const raw = toRawTranscriptRow(msg, runtime.rt.sessionId, epochId);
400
- if (raw)
401
- appendRawTranscript(db, raw);
402
- }
403
- }
404
- catch (e) {
405
- runtime.logger.warn("db-mirror-append-fail", { error: String(e) });
406
- }
407
- }
408
- // S29 FAST GATE: drive the auto-trigger off the context % (the number the
409
- // menu bar shows), NOT the token count — the model under-reports tokens,
410
- // so a token-only gate misses the overshoot that causes max-output-token
411
- // truncation. The fire point is the tier's percent threshold (tierPct)
412
- // unless overridden by MEGACOMPACT_AUTO_PCT_TRIGGER. `custom` (absolute
413
- // MEGACOMPACT_THRESHOLD_TOKENS, tierPct null) is an explicit opt-out of
414
- // percent scaling — it keeps the token gate. When pct is unavailable
415
- // (window unknown / a model that doesn't report percent) a tiered config
416
- // falls back to the token gate (S27 boot-fallback guarantee) instead of
417
- // skipping compaction — a percent-only gate would regress that.
418
- let gatePassed = false;
419
- if (config.tierPct != null && pct != null) {
420
- const firePct = config.autoPctTrigger ?? config.tierPct;
421
- gatePassed = pct / 100 >= firePct;
422
- }
423
- else {
424
- // custom tier OR tiered-but-pct-unavailable → token gate (S27 fallback).
425
- if (currentTokens < runtime.effectiveThreshold) {
426
- runtime.diagCtxFastGate++;
427
- return;
428
- }
429
- const check = autoCompactCheck(currentTokens, runtime.effectiveThreshold); // SERVER-STYLE CONFIRM (local)
430
- if (!check.shouldCompact) {
431
- runtime.diagCtxNoCompact++;
432
- return;
433
- }
434
- gatePassed = true;
435
- }
436
- if (!gatePassed) {
437
- runtime.diagCtxFastGate++;
438
- return;
439
- }
440
- // Debounce so we don't fire on every context event past threshold.
441
- const now = Date.now();
442
- if (now < runtime.debounceUntil) {
443
- runtime.diagCtxDebounce++;
444
- return;
445
- }
446
- runtime.debounceUntil = now + 2000;
447
- // Adaptive compression (Fix E): scale compression strength + keepFrom depth
448
- // with how close we are to the model context limit. Null-safe: when the
449
- // token-fallback path ran (pct unavailable) use the token-basis pressure
450
- // (the same basis the runtime `pressure` getter uses for custom/no-window).
451
- const pressure = pct != null ? pressureFromPct(pct) : pressureRatio(currentTokens, runtime.effectiveThreshold);
452
- const ran = runCompact(pi, runtime, config, ctx, messages, {
453
- compressionPressure: pressure,
454
- });
455
- if (ran.skipped) {
456
- runtime.diagCtxRunSkipped++;
457
- return;
458
- }
459
- // S27 DB-mirror: write checkpoint_epoch with deterministic nonce.
460
- // This makes the cache key stable across identical compactions.
461
- if (config.dbMirror) {
462
- try {
463
- const db = openStore(runtime.currentStateDir);
464
- const cpId = ran.result.checkpointId ?? `epoch-${Date.now()}`;
465
- const epoch = {
466
- epochId: epochIdFor(cpId),
467
- sessionId: runtime.rt.sessionId,
468
- startedSeq: 0,
469
- committedSeq: ran.result.compactedFrom,
470
- checkpointId: cpId,
471
- cutIndex: ran.result.compactedFrom,
472
- summaryMessageText: ran.result.summary,
473
- createdAt: Date.now(),
474
- };
475
- writeCheckpointEpoch(db, epoch);
476
- // S27 Task 6: Fire-and-forget dedup pipeline.
477
- // Deduplicates raw_transcript rows for the compacted range.
478
- try {
479
- const { dedupTranscript } = await import("../src/mirror/dedup.js");
480
- dedupTranscript(db, runtime.rt.sessionId, 0, ran.result.compactedFrom);
481
- }
482
- catch (_dedupErr) {
483
- // Fire-and-forget: dedup failure is non-fatal
484
- }
485
- }
486
- catch (e) {
487
- runtime.logger.warn("db-mirror-epoch-fail", { error: String(e) });
488
- }
489
- }
490
- // LEGACY path (rollback): v0.4.28 ctx.compact() + the no-op gate. The
491
- // manual compact path aborts the in-flight turn — only used behind the flag.
492
- // Read live from env (in addition to the load-time config) so the flag can be
493
- // toggled per-test without reloading the module; config.legacyDurableTrim is
494
- // the cached default. (Mirrors how piCompactWouldNoop re-reads its floor.)
495
- const legacy = config.legacyDurableTrim ||
496
- process.env.MEGACOMPACT_LEGACY_DURABLE_TRIM === "true" ||
497
- process.env.MEGACOMPACT_LEGACY_DURABLE_TRIM === "1";
498
- if (legacy) {
499
- // COMPACT-DEDUP FIX: same race guard as the agent_end path. Skip when a
500
- // NATIVE compaction just fired (avoids racing pi and surfacing a spurious
501
- // "Already compacted" / "Nothing to compact" toast). Uses lastNativeCompactAt
502
- // (NOT lastCompactAt, which runCompact also stamps for our own checkpoint).
503
- const sinceCompact = Date.now() - (runtime.rt.lastNativeCompactAt ?? 0);
504
- if (sinceCompact < 10_000 || piCompactWouldNoop(ctx))
505
- return;
506
- ctx.compact({ customInstructions: undefined }); // race-guarded by lastNativeCompactAt cooldown (ctx.compact returns void → not catchable; the cooldown prevents the call)
507
- return;
508
- }
509
- // S16 LIVE trim: collapse the compacted region to a summary + recent anchor.
510
- // Non-destructive: pi keeps the real transcript; only this LLM call sees the
511
- // trimmed window. We compute the cut on the engine view (pure, tested) then
512
- // slice the ORIGINAL pi AgentMessage[] from that index (lossless alignment,
513
- // mirroring dropCompactedRange) and prepend a user-role summary message.
514
- // A build failure or unsafe cut returns nothing (no trim this call — the
515
- // next context event retries). The anchor floor is read live from env (the
516
- // config value is the cached default) so it can be tuned per-test / per-run
517
- // without reloading the module.
518
- try {
519
- const anchorEnv = process.env.MEGACOMPACT_ANCHOR_USER_MESSAGES;
520
- const anchorUserMessages = anchorEnv != null &&
521
- anchorEnv !== "" &&
522
- Number.isFinite(Number(anchorEnv))
523
- ? Number(anchorEnv)
524
- : config.anchorUserMessages;
525
- const cut = computeLiveTrimCut(view, {
526
- compactedFrom: ran.result.compactedFrom,
527
- summary: ran.result.summary,
528
- anchorUserMessages,
529
- });
530
- if (cut === null) {
531
- runtime.diagCtxCutNull++;
532
- runtime.logger.info("live-trim-skip", {
533
- sessionId: runtime.rt.sessionId,
534
- compactedFrom: ran.result.compactedFrom,
535
- viewLen: view.length,
536
- anchorUserMessages,
537
- });
538
- return; // unsafe / below anchor floor — no trim this call
539
- }
540
- const summaryMsg = liveTrimSummaryMessage({
541
- compactedFrom: ran.result.compactedFrom,
542
- summary: ran.result.summary,
543
- anchorUserMessages: config.anchorUserMessages,
544
- });
545
- // Synthesize a user-role AgentMessage carrying the compacted summary.
546
- const summaryAgentMsg = {
547
- role: "user",
548
- content: summaryMsg.text,
549
- timestamp: Date.now(),
550
- };
551
- 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.
552
- runtime.snapshot(ctx);
553
- // DIAG (team-run relief): confirm the live trim actually fires + how big
554
- // the window still is. The return is non-durable (per-LLM-call only), so
555
- // this is the signal that the model is being fed a compacted view while
556
- // the on-disk transcript + context meter keep growing.
557
- runtime.diagLiveTrimFires++;
558
- runtime.logger.info("live-trim", {
559
- sessionId: runtime.rt.sessionId,
560
- inputMsgs: messages.length,
561
- outputMsgs: recent.length + 1,
562
- compactedFrom: cut,
563
- ctxPct: pct,
564
- ctxTokens: usage?.tokens ?? null,
565
- });
566
- return { messages: [summaryAgentMsg, ...recent] };
567
- }
568
- catch {
569
- runtime.diagCtxThrown++;
570
- return; // non-fatal: no trim this call; the next context event retries
571
- }
572
- });
573
- // ---- Supply a DURABLE trim to pi's native compaction (Fix B) ----------
574
- // We run the Trident pipeline to produce a compressed summary, then return
575
- // it as a CompactionResult. pi writes the summary into a compactionSummary
576
- // entry AND truncates the on-disk transcript from firstKeptEntryId. This is
577
- // the durable fix for "tokens grow on read": the trim survives resume, so
578
- // there is no full-reload + additive recall inflation.
579
- pi.on("session_before_compact", async (event, ctx) => {
580
- runtime.resetRuntime(ctx.sessionManager.getSessionId());
581
- // DIAG (team-run relief): this is the ONLY durable-trim entry point. Log
582
- // every fire + whether we supplied a compaction (truncates transcript) or
583
- // fell through to {} (pi runs its own). If this is sparse during a team
584
- // run, the durable trim is firing too late (only at parent settle).
585
- const prep = event.preparation;
586
- runtime.diagBeforeCompactFires++;
587
- runtime.logger.info("before-compact-entry", {
588
- sessionId: runtime.rt.sessionId,
589
- reason: event.reason,
590
- hasPrep: !!prep,
591
- msgsToSummarize: prep?.messagesToSummarize?.length ?? 0,
592
- firstKeptEntryId: prep?.firstKeptEntryId ?? null,
593
- activeAgents: runtime.activeAgents,
594
- });
595
- if (!config.auto)
596
- return {}; // let pi run its own native compaction
597
- try {
598
- const result = driveNativeCompaction(event, runtime, config);
599
- if (result && result.compaction.summary?.trim()) {
600
- runtime.diagBeforeCompactSupplied++;
601
- runtime.logger.info("native-compact", {
602
- sessionId: runtime.rt.sessionId,
603
- firstKeptEntryId: result.compaction.firstKeptEntryId,
604
- tokensBefore: result.compaction.tokensBefore,
605
- summaryTokens: result.compaction.estimatedTokensAfter,
606
- });
607
- nudgeResume(pi, runtime);
608
- return { compaction: result.compaction };
609
- }
610
- // FIX "compacts but doesn't resume" + "Nothing to compact" regression:
611
- // when we have nothing to summarize (anchor floor protects everything →
612
- // messagesToSummarize empty) or our Trident/RAPTOR summary came back
613
- // EMPTY, pi's OWN compact() throws "Nothing to compact (session too
614
- // small)" and leaves the session stuck with no resume context. Instead
615
- // of returning {} (which makes pi run its throwing compact()), supply a
616
- // fallback compaction from prep.firstKeptEntryId with a minimal resume
617
- // summary. This ALWAYS injects a compact summary so the session
618
- // resumes, and never surfaces the "Nothing to compact" error to the user.
619
- const fb = fallbackCompaction(event);
620
- if (fb) {
621
- runtime.diagBeforeCompactSupplied++;
622
- runtime.logger.info("native-compact-fallback", {
623
- sessionId: runtime.rt.sessionId,
624
- firstKeptEntryId: fb.compaction.firstKeptEntryId,
625
- tokensBefore: fb.compaction.tokensBefore,
626
- reason: event.reason,
627
- });
628
- nudgeResume(pi, runtime);
629
- return { compaction: fb.compaction };
630
- }
631
- }
632
- catch (err) {
633
- runtime.logger.error("native-compact-failed", {
634
- sessionId: runtime.rt.sessionId,
635
- error: String(err instanceof Error ? err.message : err),
636
- });
637
- }
638
- // Absolute last resort: let pi run its own (may throw "Nothing to compact").
639
- return {};
640
- });
641
- // COMPACT-DEDUP FIX: track EVERY compaction (native + extension-supplied)
642
- // so the agent_end durable-trim guard can skip a redundant ctx.compact()
643
- // when pi just compacted. Without this, agent_end fires ctx.compact()
644
- // synchronously AFTER pi's native auto-compaction appended a compaction
645
- // entry but BEFORE our branch read sees it on the next tick — racing
646
- // into a user-facing "Already compacted" throw. `lastCompactAt` is the
647
- // race-closing signal: any compaction (manual/threshold/overflow, ours
648
- // or pi's own) stamps it, and the agent_end guard skips for 10s.
649
- pi.on("session_compact", async (_event, _ctx) => {
650
- runtime.rt.lastNativeCompactAt = Date.now();
651
- runtime.rt.lastCompactAt = Date.now();
652
- runtime.logger.info("session-compacted", {
653
- sessionId: runtime.rt.sessionId,
654
- at: runtime.rt.lastCompactAt,
655
- });
656
- });
657
- /**
658
- * Build a minimal fallback compaction so pi never runs its throwing compact().
659
- *
660
- * Used when our Trident/RAPTOR summary is empty or there is nothing to
661
- * summarize (the anchor floor protects every message). We still record a
662
- * resume summary + truncate from prep.firstKeptEntryId so the session always
663
- * gets a compact summary and resumes. Returns undefined only if pi handed us
664
- * no preparation cut point at all.
665
- */
666
- function fallbackCompaction(event) {
667
- const prep = event.preparation;
668
- if (!prep?.firstKeptEntryId)
669
- return undefined;
670
- // When messagesToSummarize is empty the anchor floor protects everything,
671
- // so firstKeptEntryId == current first entry and the trim is a no-op — but
672
- // we still record a resume summary so the session has context after compaction.
673
- const tokensBefore = prep.tokensBefore ?? 0;
674
- const summary = `[mega-compact] context compacted at ${tokensBefore.toLocaleString()} tokens ` +
675
- `(anchor floor active). Continue from the most recent messages above.`;
676
- return {
677
- compaction: {
678
- summary,
679
- firstKeptEntryId: prep.firstKeptEntryId,
680
- tokensBefore,
681
- estimatedTokensAfter: estimateBlockTokens(summary),
682
- },
683
- };
684
- }
685
- /**
686
- * Debounced resume-nudge: restart the agent loop after a compaction (which
687
- * may have stopped it). Idempotent — one nudge per 30s, never blocks.
688
- */
689
- function nudgeResume(pi, runtime) {
690
- try {
691
- const now = Date.now();
692
- if (now >= runtime.resumeNudgeUntil) {
693
- runtime.resumeNudgeUntil = now + 30_000;
694
- pi.sendUserMessage("[mega-compact] continue from the compacted context above.");
695
- }
696
- }
697
- catch {
698
- /* non-fatal: a failed nudge never blocks */
699
- }
700
- }
701
- }
13
+ export * from "./mega-events/register.js";
14
+ export * from "./mega-events/session-handlers.js";
15
+ export * from "./mega-events/agent-handlers.js";
16
+ export * from "./mega-events/context-handler.js";
17
+ export * from "./mega-events/compact-handlers.js";