pi-mega-compact 0.8.23 → 0.8.25

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 (157) hide show
  1. package/README.md +26 -0
  2. package/dist/extensions/dashboard-server/api-contracts/endpoints.js +8 -0
  3. package/dist/extensions/dashboard-server/api-contracts/game-types.js +7 -0
  4. package/dist/extensions/mega-compact-s38.test.js +263 -14
  5. package/dist/extensions/mega-compact.js +15 -0
  6. package/dist/extensions/mega-config.js +3 -0
  7. package/dist/extensions/mega-events/agent-handlers.js +211 -26
  8. package/dist/extensions/mega-events/context-handler.js +45 -7
  9. package/dist/extensions/mega-events/error-classifier.js +125 -18
  10. package/dist/extensions/mega-pipeline/compact.js +24 -13
  11. package/dist/extensions/mega-pipeline/recall.js +31 -2
  12. package/dist/extensions/mega-runtime/append-event.js +24 -0
  13. package/dist/extensions/mega-runtime/bind-repo.js +65 -0
  14. package/dist/extensions/mega-runtime/capture-model.js +87 -0
  15. package/dist/extensions/mega-runtime/dashboard-snapshot.js +122 -0
  16. package/dist/extensions/mega-runtime/effects.js +86 -0
  17. package/dist/extensions/mega-runtime/engine-view.js +11 -0
  18. package/dist/extensions/mega-runtime/game-state.js +116 -0
  19. package/dist/extensions/mega-runtime/get-state-dir.js +10 -0
  20. package/dist/extensions/mega-runtime/perf.js +49 -0
  21. package/dist/extensions/mega-runtime/pressure-getters.js +64 -0
  22. package/dist/extensions/mega-runtime/render-widget.js +17 -0
  23. package/dist/extensions/mega-runtime/reset-runtime.js +50 -0
  24. package/dist/extensions/mega-runtime/runtime-helpers.js +73 -0
  25. package/dist/extensions/mega-runtime/runtime-snapshot.js +208 -0
  26. package/dist/extensions/mega-runtime/runtime.js +405 -0
  27. package/dist/extensions/mega-runtime/snapshot.js +142 -0
  28. package/dist/extensions/mega-runtime/state.js +5 -1151
  29. package/dist/extensions/mega-runtime/status.js +11 -0
  30. package/dist/extensions/mega-runtime/widget-ansi.js +207 -0
  31. package/dist/extensions/mega-runtime/widget-types.js +8 -0
  32. package/dist/extensions/mega-runtime/widget.js +15 -204
  33. package/dist/extensions/openclaw-mega-compact.js +291 -0
  34. package/dist/src/boundary.js +79 -43
  35. package/dist/src/boundary.test.js +119 -2
  36. package/dist/src/canary.js +10 -0
  37. package/dist/src/config/dedup.js +14 -0
  38. package/dist/src/config.js +3 -1
  39. package/dist/src/dedup/raptor/buildHistory.js +164 -0
  40. package/dist/src/dedup/raptor/buildHistory.test.js +292 -0
  41. package/dist/src/dedup/raptor/index.js +38 -0
  42. package/dist/src/dedup/raptor/multilevel-serve.test.js +229 -0
  43. package/dist/src/dedup/raptor/multilevel.js +17 -5
  44. package/dist/src/dedup/raptor/multilevel.test.js +36 -1
  45. package/dist/src/dedup/raptor/raptor.test.js +43 -0
  46. package/dist/src/dedup/raptor/retrieval.js +14 -2
  47. package/dist/src/dedup/raptor/retrieval.test.js +95 -0
  48. package/dist/src/dedup/raptor/serve-gate.test.js +298 -0
  49. package/dist/src/dedup/raptor/summarizer.js +1 -0
  50. package/dist/src/dedup/raptor/tree.js +16 -2
  51. package/dist/src/engine.js +18 -2
  52. package/dist/src/httpEmbedder.js +96 -6
  53. package/dist/src/httpEmbedder.test.js +277 -0
  54. package/dist/src/mechanical-fix.test.js +65 -0
  55. package/dist/src/minilm.js +92 -0
  56. package/dist/src/raptor-inject-summaries.test.js +155 -0
  57. package/dist/src/recall.js +135 -21
  58. package/dist/src/recall.test.js +179 -4
  59. package/dist/src/store/sqlite/dedup-mirror.js +32 -15
  60. package/dist/src/store/sqlite/maintenance.js +2 -2
  61. package/dist/src/store/sqlite/mechanical-fix.test.js +146 -0
  62. package/dist/src/store/sqlite/memories.js +5 -5
  63. package/dist/src/store/sqlite/meta.js +1 -1
  64. package/dist/src/store/sqlite/raptor.js +56 -17
  65. package/dist/src/store/sqlite/raptor.test.js +106 -0
  66. package/dist/src/store/sqlite/schema.js +90 -1
  67. package/dist/src/store/sqlite/session-state.js +9 -3
  68. package/dist/src/store/sqlite/stats.js +9 -5
  69. package/dist/src/store/sqlite/turns.js +181 -0
  70. package/dist/src/store/sqlite/turns.test.js +183 -0
  71. package/dist/src/store/sqlite/utils.js +15 -4
  72. package/dist/src/store/sqlite.js +1 -0
  73. package/dist/src/store.js +2 -2
  74. package/dist/src/vector-search-cache.test.js +157 -0
  75. package/dist/src/vector-search.js +107 -15
  76. package/dist/src/vectorStore.js +36 -8
  77. package/dist/src/wordpiece.js +129 -0
  78. package/extensions/dashboard-client/dist/assets/index-D_WtU2TV.js.map +1 -1
  79. package/extensions/dashboard-server/api-contracts/endpoints.ts +30 -155
  80. package/extensions/dashboard-server/api-contracts/game-types.ts +172 -0
  81. package/extensions/mega-compact-s38.test.ts +259 -14
  82. package/extensions/mega-compact.ts +15 -0
  83. package/extensions/mega-config.ts +18 -0
  84. package/extensions/mega-dashboard.ts +10 -1
  85. package/extensions/mega-events/agent-handlers.ts +211 -26
  86. package/extensions/mega-events/context-handler.ts +43 -7
  87. package/extensions/mega-events/error-classifier.ts +125 -17
  88. package/extensions/mega-pipeline/compact.ts +28 -16
  89. package/extensions/mega-pipeline/recall.ts +34 -2
  90. package/extensions/mega-runtime/DECOMPOSITION.md +180 -0
  91. package/extensions/mega-runtime/README.md +38 -0
  92. package/extensions/mega-runtime/append-event.ts +40 -0
  93. package/extensions/mega-runtime/bind-repo.ts +81 -0
  94. package/extensions/mega-runtime/capture-model.ts +101 -0
  95. package/extensions/mega-runtime/dashboard-snapshot.ts +181 -0
  96. package/extensions/mega-runtime/effects.ts +129 -0
  97. package/extensions/mega-runtime/engine-view.ts +17 -0
  98. package/extensions/mega-runtime/game-state.ts +149 -0
  99. package/extensions/mega-runtime/get-state-dir.ts +19 -0
  100. package/extensions/mega-runtime/helpers.ts +25 -1
  101. package/extensions/mega-runtime/perf.ts +60 -0
  102. package/extensions/mega-runtime/pressure-getters.ts +96 -0
  103. package/extensions/mega-runtime/render-widget.ts +41 -0
  104. package/extensions/mega-runtime/runtime-helpers.ts +119 -0
  105. package/extensions/mega-runtime/runtime-snapshot.ts +293 -0
  106. package/extensions/mega-runtime/runtime.ts +483 -0
  107. package/extensions/mega-runtime/snapshot.ts +230 -0
  108. package/extensions/mega-runtime/state.ts +5 -1268
  109. package/extensions/mega-runtime/status.ts +26 -0
  110. package/extensions/mega-runtime/widget-ansi.ts +217 -0
  111. package/extensions/mega-runtime/widget-types.ts +80 -0
  112. package/extensions/mega-runtime/widget.ts +34 -285
  113. package/package.json +1 -1
  114. package/src/boundary.test.ts +128 -2
  115. package/src/boundary.ts +75 -39
  116. package/src/canary.ts +10 -0
  117. package/src/config/dedup.ts +25 -0
  118. package/src/config.ts +3 -1
  119. package/src/dedup/raptor/buildHistory.test.ts +353 -0
  120. package/src/dedup/raptor/buildHistory.ts +259 -0
  121. package/src/dedup/raptor/index.ts +38 -0
  122. package/src/dedup/raptor/multilevel-serve.test.ts +273 -0
  123. package/src/dedup/raptor/multilevel.test.ts +47 -0
  124. package/src/dedup/raptor/multilevel.ts +18 -8
  125. package/src/dedup/raptor/raptor.test.ts +59 -0
  126. package/src/dedup/raptor/retrieval.test.ts +118 -0
  127. package/src/dedup/raptor/retrieval.ts +14 -2
  128. package/src/dedup/raptor/serve-gate.test.ts +348 -0
  129. package/src/dedup/raptor/summarizer.ts +1 -0
  130. package/src/dedup/raptor/tree.ts +17 -2
  131. package/src/engine.ts +32 -3
  132. package/src/httpEmbedder.test.ts +286 -0
  133. package/src/httpEmbedder.ts +98 -8
  134. package/src/mechanical-fix.test.ts +70 -0
  135. package/src/raptor-inject-summaries.test.ts +212 -0
  136. package/src/recall.test.ts +220 -4
  137. package/src/recall.ts +151 -22
  138. package/src/store/sqlite/dedup-mirror.ts +35 -18
  139. package/src/store/sqlite/maintenance.ts +2 -2
  140. package/src/store/sqlite/mechanical-fix.test.ts +162 -0
  141. package/src/store/sqlite/memories.ts +5 -5
  142. package/src/store/sqlite/meta.ts +1 -1
  143. package/src/store/sqlite/raptor.test.ts +139 -0
  144. package/src/store/sqlite/raptor.ts +135 -81
  145. package/src/store/sqlite/schema.ts +90 -1
  146. package/src/store/sqlite/session-state.ts +9 -3
  147. package/src/store/sqlite/stats.ts +10 -8
  148. package/src/store/sqlite/turns.test.ts +218 -0
  149. package/src/store/sqlite/turns.ts +292 -0
  150. package/src/store/sqlite/utils.ts +14 -4
  151. package/src/store/sqlite.ts +1 -0
  152. package/src/store.ts +9 -2
  153. package/src/vector-search-cache.test.ts +190 -0
  154. package/src/vector-search.ts +273 -156
  155. package/src/vectorStore.ts +443 -382
  156. package/dist/extensions/dashboard-client/src/hooks/useApi.js +0 -51
  157. package/dist/extensions/dashboard-client/src/hooks/useSSE.js +0 -63
@@ -0,0 +1,483 @@
1
+ /**
2
+ * runtime.ts — the `MegaRuntime` class: shared live state of the mega-compact
3
+ * extension.
4
+ *
5
+ * Phase 2d (maximal split): the class body is field declarations, the
6
+ * constructor, and 1-line delegates only. Every method body lives in its own
7
+ * module following the context-interface + free-function + thin-delegate
8
+ * pattern: pressure-getters.ts / append-event.ts /
9
+ * get-state-dir.ts / render-widget.ts / status.ts / engine-view.ts /
10
+ * runtime-snapshot.ts / runtime-helpers.ts / effects.ts / game-state.ts /
11
+ * capture-model.ts / bind-repo.ts / perf.ts. state.ts re-exports the class for
12
+ * backwards compatibility.
13
+ */
14
+
15
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
16
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
17
+ import { join } from "node:path";
18
+ import type { FSWatcher } from "node:fs";
19
+ import { VectorStore } from "../../src/vectorStore.js";
20
+ import type { toEngineMessages } from "../../src/adapt.js";
21
+ import { normalizeSessionId } from "../../src/store.js";
22
+ import { Logger } from "../../src/log.js";
23
+ import type { ModelSnapshot, GameState } from "../../src/store/sqlite.js";
24
+ import type { MegaConfig, PressureBand } from "../mega-config.js";
25
+ import { Dashboard } from "../mega-dashboard.js";
26
+ import type { SessionRuntime } from "./helpers.js";
27
+ import type { TickerEntry, WidgetData } from "./widget.js";
28
+ import {
29
+ ensureGameStateWatcherImpl,
30
+ getCachedGameStateImpl,
31
+ refreshWidgetGameStateImpl,
32
+ bumpGameStateImpl,
33
+ disposeRuntimeImpl,
34
+ } from "./game-state.js";
35
+ import {
36
+ setEffectImpl,
37
+ armMegaCacheFlareImpl,
38
+ armAchievementFlareImpl,
39
+ makeTierCallbackImpl,
40
+ pushTickerImpl,
41
+ } from "./effects.js";
42
+ import { ensurePerfIntervalImpl } from "./perf.js";
43
+ import { captureModelImpl } from "./capture-model.js";
44
+ import { bindRepoImpl } from "./bind-repo.js";
45
+ import { snapshotImpl } from "./runtime-snapshot.js";
46
+ import {
47
+ pressureImpl,
48
+ effectiveThresholdImpl,
49
+ pressureBandImpl,
50
+ } from "./pressure-getters.js";
51
+ import { appendEventImpl } from "./append-event.js";
52
+ import { getStateDirImpl } from "./get-state-dir.js";
53
+ import { renderWidgetImpl } from "./render-widget.js";
54
+ import { setStatusImpl } from "./status.js";
55
+ import { engineViewImpl } from "./engine-view.js";
56
+
57
+ export class MegaRuntime {
58
+ config: MegaConfig;
59
+ // Store/dashboard/logger are rebound per-repo by bindRepo() so each git repo
60
+ // gets its own isolated state dir. They start bound to the global default.
61
+ store: VectorStore;
62
+ logger: Logger;
63
+ dashboard: Dashboard;
64
+ activeRepoRoot: string | null = null;
65
+ currentStateDir: string;
66
+
67
+ // The only mutable per-session state. Reset on session_start / session_tree.
68
+ rt: SessionRuntime = {
69
+ sessionId: normalizeSessionId(undefined),
70
+ persistedThisSession: false,
71
+ lastCheckpointId: undefined,
72
+ lastCompactedFrom: 0,
73
+ lastCompactedTokens: 0,
74
+ dedupSkips: 0,
75
+ dedupAttempts: 0,
76
+ tokensSaved: 0,
77
+ lastCompactAt: null,
78
+ lastNativeCompactAt: null,
79
+ compactCount: 0,
80
+ recallInjections: 0,
81
+ cacheHitTokens: 0,
82
+ lengthStopPending: false,
83
+ errorRetryCount: 0,
84
+ errorRetryUntil: 0,
85
+ consecutiveErrors: 0,
86
+ // R1-R3 (retry redesign): in-flight dedup, session cap, poisoned-context state.
87
+ lastErrorRetryAt: 0,
88
+ retryNudgePending: false,
89
+ errorRetrySessionCount: 0,
90
+ lastErrorText: undefined,
91
+ errorTextRepeatCount: 0,
92
+ poisonedAdviseSent: false,
93
+ poisonedCompactSignatures: new Set(),
94
+ poisonedCount: 0,
95
+ };
96
+ // v0.8.6 cache-stability: the cached live-trim view for the current
97
+ // compaction epoch. Set after a fresh runCompact + computeLiveTrimCut, and
98
+ // replayed verbatim on subsequent gated context events in the SAME epoch
99
+ // (same checkpointId) so the provider KV-cache prefix stays stable instead
100
+ // of being invalidated by a freshly regenerated summary + sentinel every
101
+ // fire. Invalidated on session restart (resetRuntime) and on any native
102
+ // durable compaction (session_compact) that truncates the transcript.
103
+ trimCache: {
104
+ checkpointId: string;
105
+ cut: number;
106
+ summaryAgentMsg: AgentMessage;
107
+ ctxPct: number | null;
108
+ ctxTokens: number | null;
109
+ } | null = null;
110
+ debounceUntil = 0;
111
+ // S16: debounce for the agent_end resume nudge (avoid busy-loops).
112
+ resumeNudgeUntil = 0;
113
+ // Agent tracking for real-time widget updates
114
+ activeAgents = 0;
115
+ currentTurn = 0;
116
+ // S33: transient MEGA CACHE flare flag (armed by the turn_end scoring hook
117
+ // when cachePct > 100). Copied into widgetData.megaCacheFlare on the next
118
+ // snapshot() so the widget renders the oopsie gag, then reset (one cycle).
119
+ megaCacheFlare = false;
120
+ /** v0.8.3: ambient effect state for animated panel borders keyed off
121
+ * status transitions (level-up, mega-cache overshoot, achievement unlock,
122
+ * compaction start). Threaded into widgetData as `activeEffect`; the widget
123
+ * computes the per-frame phase from startedAt vs Date.now() (non-expired).
124
+ * Null when idle/expired. */
125
+ activeEffect: {
126
+ type: "pulse" | "flash";
127
+ role: "accent" | "mega" | "red";
128
+ startedAt: number;
129
+ durationMs: number;
130
+ } | null = null;
131
+ megaCacheFlarePct = 0;
132
+ levelUpFlare = false;
133
+ lastLevel = 0;
134
+ // S35: transient achievement-unlock flare (armed by the scoring hooks after
135
+ // evaluateAndUnlockAchievements returns newly-unlocked titles). Copied into
136
+ // widgetData.achievementFlare on the next snapshot() so the widget renders the
137
+ // unlock toast, then reset (one cycle — mirrors megaCacheFlare/levelUpFlare).
138
+ achievementFlare = false;
139
+ achievementFlareTitles: string[] = [];
140
+ // S33: last cumulative dedup-collapsed count seen by the session_compact
141
+ // hook, so we only record the DELTA as the dedupe score (leaderboard sums).
142
+ lastDedupCollapsed = 0;
143
+ // Recall block produced by auto-inline (resume/branch) that the next
144
+ // before_agent_start should prepend to the system prompt. Unset after use.
145
+ pendingRecallBlock: string | undefined;
146
+ // S21: memory recall block, parallel to pendingRecallBlock. Same one-shot
147
+ // semantics; composed with the checkpoint block in before_agent_start.
148
+ pendingMemoryRecallBlock: string | undefined;
149
+ statusKey: string | undefined; // current status text for dashboard
150
+ // Active model/provider (for real cost estimation). Captured from ctx.model
151
+ // on model_select + session_start; persisted to SQL so cost + the dashboard
152
+ // can read it without a live ctx.
153
+ currentModel: ModelSnapshot | undefined;
154
+ // Live "what it's doing right now" timestamp, used for the fresh-window.
155
+ lastActivityAt = 0;
156
+ // Live per-tier dedup trace (Phase 1): e.g. "L0 ✓ → L1 ✓ → L2 0.91 → stored".
157
+ // Built from the store's sync onTier callback during a compaction so the user
158
+ // watches each tier evaluate in real time. Cleared once the outcome settles.
159
+ tierTrace: string | undefined;
160
+ // Phase 3 — standout toolbar state.
161
+ // Recall/activity ticker: a small ring buffer (≤5) of recent compact/recall
162
+ // events so the widget shows a live history instead of a single last action.
163
+ ticker: TickerEntry[] = [];
164
+ readonly TICKER_MAX = 5;
165
+ // Pulsing status: set true while a compaction is in flight, cleared on result.
166
+ pulsing = false;
167
+ // S21.2: set by `applyMemoryOps` when a memory add/replace/remove lands in
168
+ // the current compaction. The pipeline reads this after a successful compact
169
+ // to decide whether to fire `consolidateMemories` (skip the work entirely
170
+ // when no memory rows changed).
171
+ memoriesTouchedThisCompaction = 0;
172
+ // Rolling "saved" goal for the progress bar — grows as we save more, so the
173
+ // bar always has a meaningful denominator (never sits at 100% forever).
174
+ savedGoal = 50_000;
175
+ // Last explain-why line (dedup reason / anchor-kept / superseded), surfaced
176
+ // while fresh.
177
+ lastWhy: string | undefined = undefined;
178
+ // v0.8.8 Perf dashboard instrumentation: turn/provider start timestamps +
179
+ // the 5s cpu/mem interval handle (one per MegaRuntime, cleared in dispose()).
180
+ perfTurnStart = 0;
181
+ perfProviderStart = 0;
182
+ perfCpuInterval: ReturnType<typeof setInterval> | null = null;
183
+ perfCpuBaseline: { user: number; sys: number } | undefined;
184
+
185
+ // Context tracking for the dashboard (updated in the context handler).
186
+ lastCtxTokens: number | null = null;
187
+ lastCtxPercent: number | null = null;
188
+ lastCtxWindow = 0;
189
+
190
+ // Latest computed widget payload (recomputed per snapshot, rendered per frame).
191
+ widgetData: WidgetData | null = null;
192
+ // v0.8.5: material-change signature from the last full snapshot() body. When
193
+ // the next snapshot()'s signature matches, the expensive recompute (6 sync
194
+ // SQLite opens) + writeFileSync(dashboard.json) are skipped — only the
195
+ // (already-registered) widget factory is refreshed. Kills the per-event
196
+ // main-thread block during typing/idle streaming with no material change.
197
+ lastSnapshotSig: string | null = null;
198
+ // v0.8.5: bumped whenever the cached game-state memo is evicted (bumpGameState
199
+ // for in-process /mega-game writes, the fs.watch callback for cross-process
200
+ // dashboard-server writes, and bindRepo on repo switch) so the snapshot gate
201
+ // invalidates and the widget re-reads theme/mode after the change.
202
+ gameStateBump = 0;
203
+ // Cached cross-repo drift status (recomputed at most every 30s — it opens the
204
+ // machine-wide registry DB, so we don't want to do it on every render frame).
205
+ driftCache: { at: number; status: "ok" | "warn" } | null = null;
206
+ // S31: cached game-mode state (game_mode_on/theme/tui_display_mode). Lazily
207
+ // read from the game_state SQLite row on the first widget render, then
208
+ // memoized until bumpGameState() evicts it (called by /mega-game after a
209
+ // write) so the widget picks up theme/mode/level changes live without
210
+ // re-querying the DB on every render frame.
211
+ cachedGameState: GameState | undefined;
212
+ // S32: fs.watch on the current repo's sqlite.db so cross-process writes
213
+ // (e.g. the dashboard server's PUT /api/game-state, which runs as a detached
214
+ // child with no MegaRuntime ref) evict the cached game-state memo. Without
215
+ // this, /mega-game's in-process bumpGameState() is the only eviction trigger
216
+ // and the widget would keep showing stale theme/mode/toggle after a dashboard
217
+ // edit until a restart. The watcher tracks currentStateDir — closed + re-opened
218
+ // by ensureGameStateWatcher() on every bindRepo repo switch. Non-fatal: any
219
+ // fs.watch failure (missing file / platform issue) is swallowed; the next
220
+ // getCachedGameState() snapshot re-queries the DB anyway.
221
+ gameStateWatcher?: FSWatcher;
222
+ gameStateWatchDir?: string;
223
+ // P2: the last ExtensionContext handed to snapshot()/renderWidget(), stashed
224
+ // so the fs.watch game-state callback can force a widget re-render without
225
+ // a context event (cross-process dashboard edits while pi is idle). Cleared
226
+ // implicitly on construction (undefined → watcher skips until first snap).
227
+ lastWidgetCtx?: ExtensionContext;
228
+
229
+ /**
230
+ * DIAG counters for the "team run doesn't relieve context" investigation.
231
+ * Plain integers, incremented at the three compaction decision points. They
232
+ * let a headless test drive the real event handlers and assert the firing
233
+ * cadence without scraping log files. Inert in production (the live-trim and
234
+ * before-compact probes also emit logger.info, but these counters are always
235
+ * updated and cost nothing).
236
+ */
237
+ diagLiveTrimFires = 0; // context handler returned a trimmed view
238
+ diagLiveTrimReplays = 0; // v0.8.6: trim view returned via cached replay (skipped re-compact)
239
+ diagBeforeCompactFires = 0; // session_before_compact handler entered
240
+ diagBeforeCompactSupplied = 0; // session_before_compact supplied our trim
241
+ diagAgentEndIdle = 0; // agent_end with activeAgents===0
242
+ diagAgentEndDurable = 0; // agent_end fired ctx.compact() (mid-run durable trim)
243
+ diagAgentEndDurableSkipRecent = 0; // agent_end skipped ctx.compact() — compaction in last 10s (race guard)
244
+ // Per-skip-path counters for the team-run diagnosis.
245
+ diagCtxFastGate = 0; // returned at token fast-gate (below threshold)
246
+ diagCtxNoCompact = 0; // autoCompactCheck().shouldCompact === false
247
+ diagCtxDebounce = 0; // debounceUntil not yet elapsed
248
+ diagCtxRunSkipped = 0; // runCompact() returned skipped
249
+ diagCtxCutNull = 0; // computeLiveTrimCut returned null (anchor/boundary)
250
+ diagCtxThrown = 0; // live-trim try threw (caught)
251
+
252
+ /**
253
+ * S26 capture instrumentation: the "model_snapshots empty → $0.00 cost card"
254
+ * bug was invisible because captureModel swallowed the DB write in a silent
255
+ * `catch {}`. These always-updated counters (zero cost) let a headless test or
256
+ * a live capture tell whether captureModel ran and whether the snapshot landed.
257
+ */
258
+ diagCaptureModelCalls = 0; // captureModel entered with a populated ctx.model
259
+ diagCaptureModelFails = 0; // recordModelSnapshot threw → model_snapshots stays empty
260
+
261
+ // ---- pressure accessors (bodies in pressure-getters.ts) -------------------
262
+
263
+ /** Live 0–1 pressure — see `pressureImpl` in pressure-getters.ts for the
264
+ * dual-basis (percent vs token) reconciliation notes. Thin delegate. */
265
+ get pressure(): number {
266
+ return pressureImpl(this);
267
+ }
268
+
269
+ /** The live compaction fire point in tokens — thin delegate to
270
+ * `effectiveThresholdImpl` (pressure-getters.ts). */
271
+ get effectiveThreshold(): number {
272
+ return effectiveThresholdImpl(this);
273
+ }
274
+
275
+ /** Live discrete pressure band (low/medium/high/ultra/mega) — thin delegate
276
+ * to `pressureBandImpl` (pressure-getters.ts). */
277
+ get pressureBand(): PressureBand {
278
+ return pressureBandImpl(this);
279
+ }
280
+
281
+ constructor(config: MegaConfig) {
282
+ this.config = config;
283
+ this.store = new VectorStore({
284
+ dedupSim: config.dedupSim,
285
+ stateDir: config.stateDir,
286
+ });
287
+ this.logger = new Logger({
288
+ enabled: config.debug,
289
+ path: join(config.stateDir, "mega-compact.log"),
290
+ });
291
+ this.dashboard = new Dashboard(config.stateDir);
292
+ this.currentStateDir = config.stateDir;
293
+ this.ensureGameStateWatcher();
294
+ }
295
+
296
+ // ---- per-repo binding -----------------------------------------------------
297
+
298
+ bindRepo(cwd: string | undefined): string {
299
+ return bindRepoImpl(this, cwd);
300
+ }
301
+
302
+ // ---- dashboard snapshot + widget ------------------------------------------
303
+
304
+ /** Collect live state and write it to disk (+ paint the above-editor widget). */
305
+ snapshot(ctx?: ExtensionContext): void {
306
+ snapshotImpl(this, ctx);
307
+ }
308
+
309
+ /** Width-aware above-editor widget factory registration — thin delegate to
310
+ * `renderWidgetImpl` (render-widget.ts). */
311
+ renderWidget(ctx: ExtensionContext): void {
312
+ renderWidgetImpl(this, ctx);
313
+ }
314
+
315
+ /** Mirror the dashboard status text onto pi's status line — thin delegate to
316
+ * `setStatusImpl` (status.ts). */
317
+ setStatus(ctx: ExtensionContext, text: string | undefined): void {
318
+ setStatusImpl(this, ctx, text);
319
+ }
320
+
321
+ /** Per-session state reset (session_start / session_tree) — inlined by the
322
+ * raptor-promotion merge (R1–R3 retry-redesign fields); reset-runtime.ts was
323
+ * retired by that branch. */
324
+ resetRuntime(sessionId: string | undefined): void {
325
+ const sid = normalizeSessionId(sessionId);
326
+ if (this.rt.sessionId === sid && this.rt.persistedThisSession) return; // same session, keep checkpoint memory
327
+ this.rt = {
328
+ sessionId: sid,
329
+ persistedThisSession: false,
330
+ lastCheckpointId: undefined,
331
+ lastCompactedFrom: 0,
332
+ lastCompactedTokens: 0,
333
+ dedupSkips: 0,
334
+ dedupAttempts: 0,
335
+ tokensSaved: 0,
336
+ lastCompactAt: null,
337
+ lastNativeCompactAt: null,
338
+ compactCount: 0,
339
+ recallInjections: 0,
340
+ cacheHitTokens: 0,
341
+ lengthStopPending: false,
342
+ errorRetryCount: 0,
343
+ errorRetryUntil: 0,
344
+ consecutiveErrors: 0,
345
+ // R1-R3 (retry redesign): in-flight dedup, session cap, poisoned-context state.
346
+ lastErrorRetryAt: 0,
347
+ retryNudgePending: false,
348
+ errorRetrySessionCount: 0,
349
+ lastErrorText: undefined,
350
+ errorTextRepeatCount: 0,
351
+ poisonedAdviseSent: false,
352
+ poisonedCompactSignatures: new Set(),
353
+ poisonedCount: 0,
354
+ };
355
+ this.trimCache = null; // v0.8.6: never replay a stale trim into a new session
356
+ this.statusKey = undefined;
357
+ this.activeAgents = 0;
358
+ this.currentTurn = 0;
359
+ this.lastActivityAt = 0;
360
+ this.tierTrace = undefined;
361
+ this.ticker.length = 0;
362
+ this.pulsing = false;
363
+ this.savedGoal = 50_000;
364
+ this.lastWhy = undefined;
365
+ // S31 audit P2: symmetry with bindRepo — a reset can coincide with a context
366
+ // that re-binds the repo, so drop the memo too. Cheap; the next
367
+ // getCachedGameState() re-queries lazily.
368
+ this.cachedGameState = undefined;
369
+ }
370
+
371
+ captureModel(ctx: ExtensionContext): void {
372
+ captureModelImpl(this, ctx);
373
+ }
374
+
375
+ /** Structured events.log diagnostics sink (always-on) — thin delegate to
376
+ * `appendEventImpl` (append-event.ts). */
377
+ appendEvent(event: string, fields: Record<string, unknown>): void {
378
+ appendEventImpl(this, event, fields);
379
+ }
380
+
381
+ /** S21: state dir of the currently bound repo (where memories live) — thin
382
+ * delegate to `getStateDirImpl` (get-state-dir.ts). */
383
+ getStateDir(): string {
384
+ return getStateDirImpl(this);
385
+ }
386
+
387
+ /** S32: (re)target the fs.watch cache-eviction watcher at the current
388
+ * stateDir's sqlite.db. Called from the constructor + every bindRepo repo
389
+ * switch so the watcher always tracks the NEW repo's db file. If a watcher
390
+ * already exists for this dir, no-op; if the dir changed, close the old one
391
+ * first. fs.watch can throw on a missing file / platform issues — wrapped
392
+ * non-fatal; the next getCachedGameState() re-queries the DB anyway. */
393
+ ensureGameStateWatcher(): void {
394
+ ensureGameStateWatcherImpl(this, this);
395
+ }
396
+
397
+ /** S32: release the fs.watch game-state watcher + stop the v0.8.8 perf
398
+ * sampling interval. Called when the runtime is torn down (no existing
399
+ * dispose path — the process exit reclaims the fd, but explicit close is
400
+ * correct for any in-process reload / test reuse). Thin delegate to
401
+ * `disposeRuntimeImpl` (game-state.ts). */
402
+ dispose(): void {
403
+ disposeRuntimeImpl(this);
404
+ }
405
+
406
+ ensurePerfInterval(): void {
407
+ ensurePerfIntervalImpl(this);
408
+ }
409
+
410
+ /** S31: the cached game-mode state (game_mode_on/theme/tui_display_mode).
411
+ * Lazily read from the game_state SQLite row on the first call, then
412
+ * memoized until `bumpGameState()` evicts it. Reading is non-throwing
413
+ * (getGameState returns DEFAULT_GAME_STATE on any error), so the widget
414
+ * can call this on every render safely. */
415
+ getCachedGameState(): GameState {
416
+ return getCachedGameStateImpl(this);
417
+ }
418
+
419
+ /** P2 cross-process re-render: lightweight game-state refresh for the
420
+ * fs.watch callback. Eviction of cachedGameState + gameStateBump++ happens
421
+ * in the caller BEFORE this runs. Here we re-read ONLY the game_state row
422
+ * via getCachedGameState() (one SELECT; the cache is already evicted) and
423
+ * patch ONLY the three game-mode fields on the EXISTING widgetData, then
424
+ * re-register the widget factory via renderWidget() so pi redraws next
425
+ * frame.
426
+ *
427
+ * WHY a lightweight path: the full snapshot(ctx) recomputes 6 synchronous
428
+ * SQLite opens + writeFileSync(dashboard.json) + store writes, and those
429
+ * store writes RETRIGGER this same fs.watch callback → re-entrant thrash
430
+ * (the watcher fires on every sqlite.db* write, including context-event
431
+ * checkpoint writes) → 190s test timeout under mega-compact.test.js /
432
+ * mega-teamrun.test.js. This path writes NOTHING to the store or
433
+ * dashboard.json, so it cannot retrigger itself.
434
+ *
435
+ * Guard: no-op when widgetData is null (no snapshot has run yet → nothing
436
+ * to patch) or ctx is undefined. Field values mirror snapshot() exactly. */
437
+ refreshWidgetGameState(ctx: ExtensionContext): void {
438
+ refreshWidgetGameStateImpl(this, this, ctx);
439
+ }
440
+
441
+ /** S31: evict the cached game-mode state so the next widget render re-reads
442
+ * the game_state row. Called by /mega-game after every setGameState() so
443
+ * the panel picks up theme/mode/toggle changes live. */
444
+ bumpGameState(): void {
445
+ bumpGameStateImpl(this);
446
+ }
447
+
448
+ armMegaCacheFlare(peakPct: number): void {
449
+ armMegaCacheFlareImpl(this, peakPct);
450
+ }
451
+
452
+ armAchievementFlare(titles: string[]): void {
453
+ armAchievementFlareImpl(this, titles);
454
+ }
455
+
456
+ setEffect(
457
+ type: "pulse" | "flash",
458
+ role: "accent" | "mega" | "red",
459
+ durationMs: number,
460
+ ): void {
461
+ setEffectImpl(this, type, role, durationMs);
462
+ }
463
+
464
+ makeTierCallback(
465
+ ctx: ExtensionContext,
466
+ ): (ev: {
467
+ tier: "L0" | "L1" | "L2" | "new";
468
+ status: "scanning" | "deduped" | "passed" | "stored";
469
+ detail?: string;
470
+ }) => void {
471
+ return makeTierCallbackImpl(this, ctx);
472
+ }
473
+
474
+ pushTicker(text: string): void {
475
+ pushTickerImpl(this, text);
476
+ }
477
+
478
+ /** Convert the messages pi hands us in the `context` event into the engine
479
+ * view — thin delegate to `engineViewImpl` (engine-view.ts). */
480
+ engineView(messages: AgentMessage[]): ReturnType<typeof toEngineMessages> {
481
+ return engineViewImpl(messages);
482
+ }
483
+ }