pi-mega-compact 0.8.22 → 0.8.24

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