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