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