pi-mega-compact 0.7.8 → 0.8.0

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 (122) hide show
  1. package/README.md +11 -12
  2. package/dist/extensions/dashboard-server/html.js +1023 -0
  3. package/dist/extensions/dashboard-server/html.test.js +41 -0
  4. package/dist/extensions/dashboard-server/index-reader.js +133 -0
  5. package/dist/extensions/dashboard-server/server.js +530 -0
  6. package/dist/extensions/dashboard-server/server.test.js +120 -0
  7. package/dist/extensions/dashboard-server/snapshot.js +43 -0
  8. package/dist/extensions/dashboard-server/state.js +30 -0
  9. package/dist/extensions/dashboard-server/types.js +5 -0
  10. package/dist/extensions/dashboard-server-s32.test.js +181 -0
  11. package/dist/extensions/dashboard-server.js +7 -1315
  12. package/dist/extensions/mega-commands.js +162 -134
  13. package/dist/extensions/mega-compact.js +3 -0
  14. package/dist/extensions/mega-compact.test.js +90 -21
  15. package/dist/extensions/mega-conflict-cmds.js +5 -1
  16. package/dist/extensions/mega-dashboard-cmds.js +29 -22
  17. package/dist/extensions/mega-db-cmds.js +11 -2
  18. package/dist/extensions/mega-events/agent-handlers.js +222 -0
  19. package/dist/extensions/mega-events/compact-handlers.js +162 -0
  20. package/dist/extensions/mega-events/context-handler.js +249 -0
  21. package/dist/extensions/mega-events/register.js +21 -0
  22. package/dist/extensions/mega-events/session-handlers.js +142 -0
  23. package/dist/extensions/mega-events.js +15 -699
  24. package/dist/extensions/mega-game-cmds.js +106 -0
  25. package/dist/extensions/mega-game-cmds.test.js +113 -0
  26. package/dist/extensions/mega-pipeline/compact.js +324 -0
  27. package/dist/extensions/mega-pipeline/memory-review.js +38 -0
  28. package/dist/extensions/mega-pipeline/recall.js +147 -0
  29. package/dist/extensions/mega-pipeline.js +9 -480
  30. package/dist/extensions/mega-runtime/helpers.js +40 -0
  31. package/dist/extensions/mega-runtime/query.js +29 -0
  32. package/dist/extensions/mega-runtime/state.js +877 -0
  33. package/dist/extensions/mega-runtime/state.test.js +171 -0
  34. package/dist/extensions/mega-runtime/widget.js +270 -0
  35. package/dist/extensions/mega-runtime/widget.test.js +160 -0
  36. package/dist/extensions/mega-runtime.js +15 -947
  37. package/dist/src/config/themes.js +84 -0
  38. package/dist/src/config/themes.test.js +94 -0
  39. package/dist/src/game/scoring.js +105 -0
  40. package/dist/src/game/scoring.test.js +98 -0
  41. package/dist/src/store/sqlite/checkpoints.js +145 -0
  42. package/dist/src/store/sqlite/dedup-mirror.js +64 -0
  43. package/dist/src/store/sqlite/foundation.js +38 -0
  44. package/dist/src/store/sqlite/game-achievements.js +111 -0
  45. package/dist/src/store/sqlite/game-achievements.test.js +67 -0
  46. package/dist/src/store/sqlite/game-scores.js +105 -0
  47. package/dist/src/store/sqlite/game-scores.test.js +106 -0
  48. package/dist/src/store/sqlite/game-state.js +54 -0
  49. package/dist/src/store/sqlite/game-state.test.js +76 -0
  50. package/dist/src/store/sqlite/global-index.js +224 -0
  51. package/dist/src/store/sqlite/maintenance.js +235 -0
  52. package/dist/src/store/sqlite/memories.js +164 -0
  53. package/dist/src/store/sqlite/meta.js +82 -0
  54. package/dist/src/store/sqlite/model-snapshots.js +47 -0
  55. package/dist/src/store/sqlite/raptor.js +57 -0
  56. package/dist/src/store/sqlite/raw-transcript.js +134 -0
  57. package/dist/src/store/sqlite/schema.js +294 -0
  58. package/dist/src/store/sqlite/session-state.js +28 -0
  59. package/dist/src/store/sqlite/stats.js +66 -0
  60. package/dist/src/store/sqlite/utils.js +120 -0
  61. package/dist/src/store/sqlite.js +23 -1607
  62. package/extensions/dashboard-server/html.test.ts +50 -0
  63. package/extensions/dashboard-server/html.ts +1026 -0
  64. package/extensions/dashboard-server/index-reader.ts +130 -0
  65. package/extensions/dashboard-server/server.test.ts +131 -0
  66. package/extensions/dashboard-server/server.ts +505 -0
  67. package/extensions/dashboard-server/snapshot.ts +44 -0
  68. package/extensions/dashboard-server/state.ts +33 -0
  69. package/extensions/dashboard-server/types.ts +134 -0
  70. package/extensions/dashboard-server-s32.test.ts +195 -0
  71. package/extensions/dashboard-server.ts +7 -1431
  72. package/extensions/mega-commands.ts +33 -10
  73. package/extensions/mega-compact.test.ts +198 -43
  74. package/extensions/mega-compact.ts +3 -0
  75. package/extensions/mega-conflict-cmds.ts +6 -2
  76. package/extensions/mega-dashboard-cmds.ts +30 -23
  77. package/extensions/mega-db-cmds.ts +11 -3
  78. package/extensions/mega-events/agent-handlers.ts +262 -0
  79. package/extensions/mega-events/compact-handlers.ts +192 -0
  80. package/extensions/mega-events/context-handler.ts +290 -0
  81. package/extensions/mega-events/register.ts +37 -0
  82. package/extensions/mega-events/session-handlers.ts +165 -0
  83. package/extensions/mega-events.ts +15 -780
  84. package/extensions/mega-game-cmds.test.ts +137 -0
  85. package/extensions/mega-game-cmds.ts +122 -0
  86. package/extensions/mega-pipeline/compact.ts +366 -0
  87. package/extensions/mega-pipeline/memory-review.ts +46 -0
  88. package/extensions/mega-pipeline/recall.ts +165 -0
  89. package/extensions/mega-pipeline.ts +9 -537
  90. package/extensions/mega-runtime/helpers.ts +68 -0
  91. package/extensions/mega-runtime/query.ts +29 -0
  92. package/extensions/mega-runtime/state.test.ts +171 -0
  93. package/extensions/mega-runtime/state.ts +967 -0
  94. package/extensions/mega-runtime/widget.test.ts +185 -0
  95. package/extensions/mega-runtime/widget.ts +359 -0
  96. package/extensions/mega-runtime.ts +15 -1093
  97. package/package.json +4 -3
  98. package/src/config/themes.test.ts +116 -0
  99. package/src/config/themes.ts +124 -0
  100. package/src/game/scoring.test.ts +103 -0
  101. package/src/game/scoring.ts +158 -0
  102. package/src/store/sqlite/checkpoints.ts +204 -0
  103. package/src/store/sqlite/dedup-mirror.ts +114 -0
  104. package/src/store/sqlite/foundation.ts +63 -0
  105. package/src/store/sqlite/game-achievements.test.ts +80 -0
  106. package/src/store/sqlite/game-achievements.ts +147 -0
  107. package/src/store/sqlite/game-scores.test.ts +132 -0
  108. package/src/store/sqlite/game-scores.ts +168 -0
  109. package/src/store/sqlite/game-state.test.ts +89 -0
  110. package/src/store/sqlite/game-state.ts +87 -0
  111. package/src/store/sqlite/global-index.ts +305 -0
  112. package/src/store/sqlite/maintenance.ts +294 -0
  113. package/src/store/sqlite/memories.ts +217 -0
  114. package/src/store/sqlite/meta.ts +108 -0
  115. package/src/store/sqlite/model-snapshots.ts +83 -0
  116. package/src/store/sqlite/raptor.ts +107 -0
  117. package/src/store/sqlite/raw-transcript.ts +221 -0
  118. package/src/store/sqlite/schema.ts +305 -0
  119. package/src/store/sqlite/session-state.ts +38 -0
  120. package/src/store/sqlite/stats.ts +127 -0
  121. package/src/store/sqlite/utils.ts +125 -0
  122. package/src/store/sqlite.ts +23 -2204
@@ -0,0 +1,877 @@
1
+ /**
2
+ * state.ts — the `MegaRuntime` class: shared live state of the mega-compact
3
+ * extension.
4
+ *
5
+ * The original mega-compact.ts was a single large closure over ~20 mutable
6
+ * variables. This module lifts that state into a `MegaRuntime` class so the
7
+ * event/command/pipeline modules can share it without re-declaring it. All
8
+ * behavior (store/dashboard rebinding, dashboard snapshot shape, the
9
+ * above-editor widget math, model capture) is preserved byte-for-byte from the
10
+ * original closure.
11
+ */
12
+ import { join } from "node:path";
13
+ import { appendFileSync, mkdirSync } from "node:fs";
14
+ import { VectorStore } from "../../src/vectorStore.js";
15
+ import { toEngineMessages } from "../../src/adapt.js";
16
+ import { normalizeSessionId } from "../../src/store.js";
17
+ import { Logger } from "../../src/log.js";
18
+ import { recordModelSnapshot, latestModelSnapshot, upsertRepoRegistry, recordRepoModel, getDedupStats, getCompactCount, getRecallInjected, getCacheHitTokensSaved, getGameState, } from "../../src/store/sqlite.js";
19
+ import { detectCrossRepoDrift } from "../../src/driftDetection.js";
20
+ import { repoStateDir, resolveRepoRoot, pressureRatio, pressureFromPct, pressureBand, effectiveThresholdTokens, } from "../mega-config.js";
21
+ import { Dashboard } from "../mega-dashboard.js";
22
+ import { STATUS_KEY, WIDGET_KEY, TOKENS_PER_SEC_ESTIMATE, ownVersion, } from "./helpers.js";
23
+ import { C, buildWidgetLines, } from "./widget.js";
24
+ import { getTheme } from "../../src/config/themes.js";
25
+ import { watch } from "node:fs";
26
+ import { turnLevel } from "../../src/game/scoring.js";
27
+ export class MegaRuntime {
28
+ config;
29
+ // Store/dashboard/logger are rebound per-repo by bindRepo() so each git repo
30
+ // gets its own isolated state dir. They start bound to the global default.
31
+ store;
32
+ logger;
33
+ dashboard;
34
+ activeRepoRoot = null;
35
+ currentStateDir;
36
+ // The only mutable per-session state. Reset on session_start / session_tree.
37
+ rt = {
38
+ sessionId: normalizeSessionId(undefined),
39
+ persistedThisSession: false,
40
+ lastCheckpointId: undefined,
41
+ lastCompactedFrom: 0,
42
+ lastCompactedTokens: 0,
43
+ dedupSkips: 0,
44
+ dedupAttempts: 0,
45
+ tokensSaved: 0,
46
+ lastCompactAt: null,
47
+ lastNativeCompactAt: null,
48
+ compactCount: 0,
49
+ recallInjections: 0,
50
+ cacheHitTokens: 0,
51
+ lengthStopPending: false,
52
+ };
53
+ debounceUntil = 0;
54
+ // S16: debounce for the agent_end resume nudge (avoid busy-loops).
55
+ resumeNudgeUntil = 0;
56
+ // Agent tracking for real-time widget updates
57
+ activeAgents = 0;
58
+ currentTurn = 0;
59
+ // S33: transient MEGA CACHE flare flag (armed by the turn_end scoring hook
60
+ // when cachePct > 100). Copied into widgetData.megaCacheFlare on the next
61
+ // snapshot() so the widget renders the oopsie gag, then reset (one cycle).
62
+ megaCacheFlare = false;
63
+ megaCacheFlarePct = 0;
64
+ levelUpFlare = false;
65
+ lastLevel = 0;
66
+ // S35: transient achievement-unlock flare (armed by the scoring hooks after
67
+ // evaluateAndUnlockAchievements returns newly-unlocked titles). Copied into
68
+ // widgetData.achievementFlare on the next snapshot() so the widget renders the
69
+ // unlock toast, then reset (one cycle — mirrors megaCacheFlare/levelUpFlare).
70
+ achievementFlare = false;
71
+ achievementFlareTitles = [];
72
+ // S33: last cumulative dedup-collapsed count seen by the session_compact
73
+ // hook, so we only record the DELTA as the dedupe score (leaderboard sums).
74
+ lastDedupCollapsed = 0;
75
+ // Recall block produced by auto-inline (resume/branch) that the next
76
+ // before_agent_start should prepend to the system prompt. Unset after use.
77
+ pendingRecallBlock;
78
+ // S21: memory recall block, parallel to pendingRecallBlock. Same one-shot
79
+ // semantics; composed with the checkpoint block in before_agent_start.
80
+ pendingMemoryRecallBlock;
81
+ statusKey; // current status text for dashboard
82
+ // Active model/provider (for real cost estimation). Captured from ctx.model
83
+ // on model_select + session_start; persisted to SQL so cost + the dashboard
84
+ // can read it without a live ctx.
85
+ currentModel;
86
+ // Live "what it's doing right now" timestamp, used for the fresh-window.
87
+ lastActivityAt = 0;
88
+ // Live per-tier dedup trace (Phase 1): e.g. "L0 ✓ → L1 ✓ → L2 0.91 → stored".
89
+ // Built from the store's sync onTier callback during a compaction so the user
90
+ // watches each tier evaluate in real time. Cleared once the outcome settles.
91
+ tierTrace;
92
+ // Phase 3 — standout toolbar state.
93
+ // Recall/activity ticker: a small ring buffer (≤5) of recent compact/recall
94
+ // events so the widget shows a live history instead of a single last action.
95
+ ticker = [];
96
+ TICKER_MAX = 5;
97
+ // Pulsing status: set true while a compaction is in flight, cleared on result.
98
+ pulsing = false;
99
+ // S21.2: set by `applyMemoryOps` when a memory add/replace/remove lands in
100
+ // the current compaction. The pipeline reads this after a successful compact
101
+ // to decide whether to fire `consolidateMemories` (skip the work entirely
102
+ // when no memory rows changed).
103
+ memoriesTouchedThisCompaction = 0;
104
+ // Rolling "saved" goal for the progress bar — grows as we save more, so the
105
+ // bar always has a meaningful denominator (never sits at 100% forever).
106
+ savedGoal = 50_000;
107
+ // Last explain-why line (dedup reason / anchor-kept / superseded), surfaced
108
+ // while fresh.
109
+ lastWhy = undefined;
110
+ // Context tracking for the dashboard (updated in the context handler).
111
+ lastCtxTokens = null;
112
+ lastCtxPercent = null;
113
+ lastCtxWindow = 0;
114
+ // Latest computed widget payload (recomputed per snapshot, rendered per frame).
115
+ widgetData = null;
116
+ // Cached cross-repo drift status (recomputed at most every 30s — it opens the
117
+ // machine-wide registry DB, so we don't want to do it on every render frame).
118
+ driftCache = null;
119
+ // S31: cached game-mode state (game_mode_on/theme/tui_display_mode). Lazily
120
+ // read from the game_state SQLite row on the first widget render, then
121
+ // memoized until bumpGameState() evicts it (called by /mega-game after a
122
+ // write) so the widget picks up theme/mode/level changes live without
123
+ // re-querying the DB on every render frame.
124
+ cachedGameState;
125
+ // S32: fs.watch on the current repo's sqlite.db so cross-process writes
126
+ // (e.g. the dashboard server's PUT /api/game-state, which runs as a detached
127
+ // child with no MegaRuntime ref) evict the cached game-state memo. Without
128
+ // this, /mega-game's in-process bumpGameState() is the only eviction trigger
129
+ // and the widget would keep showing stale theme/mode/toggle after a dashboard
130
+ // edit until a restart. The watcher tracks currentStateDir — closed + re-opened
131
+ // by ensureGameStateWatcher() on every bindRepo repo switch. Non-fatal: any
132
+ // fs.watch failure (missing file / platform issue) is swallowed; the next
133
+ // getCachedGameState() snapshot re-queries the DB anyway.
134
+ gameStateWatcher;
135
+ gameStateWatchDir;
136
+ /**
137
+ * DIAG counters for the "team run doesn't relieve context" investigation.
138
+ * Plain integers, incremented at the three compaction decision points. They
139
+ * let a headless test drive the real event handlers and assert the firing
140
+ * cadence without scraping log files. Inert in production (the live-trim and
141
+ * before-compact probes also emit logger.info, but these counters are always
142
+ * updated and cost nothing).
143
+ */
144
+ diagLiveTrimFires = 0; // context handler returned a trimmed view
145
+ diagBeforeCompactFires = 0; // session_before_compact handler entered
146
+ diagBeforeCompactSupplied = 0; // session_before_compact supplied our trim
147
+ diagAgentEndIdle = 0; // agent_end with activeAgents===0
148
+ diagAgentEndDurable = 0; // agent_end fired ctx.compact() (mid-run durable trim)
149
+ diagAgentEndDurableSkipRecent = 0; // agent_end skipped ctx.compact() — compaction in last 10s (race guard)
150
+ // Per-skip-path counters for the team-run diagnosis.
151
+ diagCtxFastGate = 0; // returned at token fast-gate (below threshold)
152
+ diagCtxNoCompact = 0; // autoCompactCheck().shouldCompact === false
153
+ diagCtxDebounce = 0; // debounceUntil not yet elapsed
154
+ diagCtxRunSkipped = 0; // runCompact() returned skipped
155
+ diagCtxCutNull = 0; // computeLiveTrimCut returned null (anchor/boundary)
156
+ diagCtxThrown = 0; // live-trim try threw (caught)
157
+ /**
158
+ * S26 capture instrumentation: the "model_snapshots empty → $0.00 cost card"
159
+ * bug was invisible because captureModel swallowed the DB write in a silent
160
+ * `catch {}`. These always-updated counters (zero cost) let a headless test or
161
+ * a live capture tell whether captureModel ran and whether the snapshot landed.
162
+ */
163
+ diagCaptureModelCalls = 0; // captureModel entered with a populated ctx.model
164
+ diagCaptureModelFails = 0; // recordModelSnapshot threw → model_snapshots stays empty
165
+ /**
166
+ * Live 0–1 pressure — how full the context window is relative to the
167
+ * compaction threshold.
168
+ *
169
+ * RECONCILE (BACKLOG dual-basis flicker): when the model context window is
170
+ * known we base pressure consistently on the *percentage* basis
171
+ * (`lastCtxPercent / (tierPct*100)`). This keeps the band stable whether the
172
+ * latest context event carried a token count or only a percentage, so the
173
+ * threshold comparison doesn't jump when a token-count event arrives vs a
174
+ * percent-only event. We only fall back to the token-count basis
175
+ * (`config.thresholdTokens`) when the window is unknown (e.g. before the first
176
+ * context event, or a `custom` tier with no tierPct). Always finite + in [0,1].
177
+ */
178
+ get pressure() {
179
+ if (this.lastCtxWindow > 0 &&
180
+ this.config.tierPct != null &&
181
+ this.lastCtxPercent != null) {
182
+ // pressureFromPct(x) = x/100, and x = lastCtxPercent/tierPct, so this is
183
+ // exactly the intended lastCtxPercent/(tierPct*100) 0–1 ratio: at the
184
+ // fire point (lastCtxPercent == tierPct*100) pressure == 1.0, matching the
185
+ // token-based pressureRatio(currentTokens, effectiveThreshold) reading so
186
+ // the band doesn't jump when a token-count vs percent-only event arrives.
187
+ return pressureFromPct(this.lastCtxPercent / this.config.tierPct);
188
+ }
189
+ if (this.lastCtxTokens != null &&
190
+ this.lastCtxTokens > 0 &&
191
+ this.config.thresholdTokens > 0) {
192
+ return pressureRatio(this.lastCtxTokens, this.config.thresholdTokens);
193
+ }
194
+ return pressureFromPct(this.lastCtxPercent);
195
+ }
196
+ /**
197
+ * The live compaction FIRE POINT in tokens: the effective threshold scaled by
198
+ * the current model context window (`tierPct * window`) when known, else the
199
+ * boot fallback `config.thresholdTokens`. This is what the FAST GATE /
200
+ * `autoCompactCheck` / agent_end durable-trigger compare against, so
201
+ * compaction fires at tier% of the window for ANY model size (200k or 1M),
202
+ * always below pi's native auto-compaction (~80% of window).
203
+ */
204
+ get effectiveThreshold() {
205
+ return effectiveThresholdTokens({
206
+ tierPct: this.config.tierPct,
207
+ fallbackThreshold: this.config.thresholdTokens,
208
+ window: this.lastCtxWindow,
209
+ });
210
+ }
211
+ /** Live discrete pressure band (low/medium/high/ultra/mega) over `pressure`. */
212
+ get pressureBand() {
213
+ return pressureBand(this.pressure);
214
+ }
215
+ constructor(config) {
216
+ this.config = config;
217
+ this.store = new VectorStore({
218
+ dedupSim: config.dedupSim,
219
+ stateDir: config.stateDir,
220
+ });
221
+ this.logger = new Logger({
222
+ enabled: config.debug,
223
+ path: join(config.stateDir, "mega-compact.log"),
224
+ });
225
+ this.dashboard = new Dashboard(config.stateDir);
226
+ this.currentStateDir = config.stateDir;
227
+ this.ensureGameStateWatcher();
228
+ }
229
+ // ---- per-repo binding -----------------------------------------------------
230
+ /**
231
+ * Point store/dashboard/logger at the current repo's state dir. Rebuilds the
232
+ * instances only when the repo root changes, so cross-repo dedup stats, db,
233
+ * and events are fully isolated. Falls back to the global default outside git.
234
+ */
235
+ bindRepo(cwd) {
236
+ const dir = cwd
237
+ ? repoStateDir(cwd, this.config.stateDir)
238
+ : this.config.stateDir;
239
+ const key = cwd ? (resolveRepoRoot(cwd) ?? dir) : dir;
240
+ if (key === this.activeRepoRoot)
241
+ return dir;
242
+ this.activeRepoRoot = key;
243
+ this.currentStateDir = dir;
244
+ // S31 audit P2: bindRepo switched currentStateDir but left cachedGameState
245
+ // memoized -> the widget kept showing the previous repo's theme/mode/toggle
246
+ // until /mega-game or a restart. The game_state row is per-repo (per
247
+ // stateDir), so evict the memo on every repo switch; the next widget render
248
+ // re-queries lazily via getCachedGameState().
249
+ this.cachedGameState = undefined;
250
+ // S32: re-target the fs.watch cache-eviction watcher at the NEW stateDir's
251
+ // sqlite.db so cross-process writes (dashboard server) still evict the memo.
252
+ this.ensureGameStateWatcher();
253
+ this.store = new VectorStore({
254
+ dedupSim: this.config.dedupSim,
255
+ stateDir: dir,
256
+ });
257
+ this.logger = new Logger({
258
+ enabled: this.config.debug,
259
+ path: join(dir, "mega-compact.log"),
260
+ });
261
+ this.dashboard = new Dashboard(dir);
262
+ // Aggregate this repo into the machine-wide index so the multi-repo
263
+ // dashboard (Summary / All-repos tabs) can show it alongside every other
264
+ // repo. Best-effort + non-fatal: a read-only index dir or contention must
265
+ // never break the per-repo compaction path. Runs only on repo-switch
266
+ // (this branch), so it's infrequent — not per-context-event.
267
+ try {
268
+ const repo = this.store.repoStats();
269
+ const di = this.store.dataInvariant();
270
+ const root = key !== dir ? key : (resolveRepoRoot(cwd ?? dir) ?? dir);
271
+ upsertRepoRegistry({
272
+ repoRoot: root,
273
+ displayName: root.split(/[\\/]/).filter(Boolean).pop() ?? root,
274
+ stateDir: dir,
275
+ checkpointCount: repo.checkpointCount,
276
+ tokensSaved: repo.tokensSaved,
277
+ compressedOriginalBytes: di.compressedOriginalBytes,
278
+ });
279
+ }
280
+ catch {
281
+ /* non-fatal: index aggregation must not block compaction */
282
+ }
283
+ return dir;
284
+ }
285
+ // ---- dashboard snapshot + widget ------------------------------------------
286
+ /** Collect live state and write it to disk (+ paint the above-editor widget). */
287
+ snapshot(ctx) {
288
+ if (ctx)
289
+ this.bindRepo(ctx.cwd);
290
+ const st = this.store.stats(this.rt.sessionId);
291
+ const repo = this.store.repoStats();
292
+ const di = this.store.dataInvariant();
293
+ // Live + store-wide cache-hit / compaction counters for the dashboard.
294
+ const ds = getDedupStats(this.currentStateDir);
295
+ const cacheHitsTotal = ds.deduped + getRecallInjected(this.currentStateDir);
296
+ const cacheHitsTotalTokens = getCacheHitTokensSaved(this.currentStateDir);
297
+ const cacheHitsSession = this.rt.dedupSkips + this.rt.recallInjections;
298
+ const sec = (tok) => (tok || 0) / TOKENS_PER_SEC_ESTIMATE;
299
+ // Active model/provider for the current-repo card + the multi-repo table.
300
+ const modelSnap = latestModelSnapshot(this.currentStateDir);
301
+ const model = modelSnap
302
+ ? {
303
+ name: modelSnap.modelName ?? modelSnap.modelId,
304
+ provider: modelSnap.provider,
305
+ providerName: modelSnap.providerName ?? "",
306
+ inputRate: modelSnap.inputRate,
307
+ outputRate: modelSnap.outputRate,
308
+ }
309
+ : undefined;
310
+ // effectiveThresholdPct: the live fire point as a % of the window (null for
311
+ // `custom`, which has no tierPct). S29: honors MEGACOMPACT_AUTO_PCT_TRIGGER
312
+ // override so the dashboard's armed/ready match the context-handler gate
313
+ // (which fires on this same %). Used by armed/ready + the dashboard.
314
+ const effectiveThresholdPct = this.config.tierPct != null
315
+ ? (this.config.autoPctTrigger ?? this.config.tierPct) * 100
316
+ : null;
317
+ // armed lights at/above the REAL fire point: max(effectiveThresholdPct,
318
+ // fastGatePct). fastGatePct already equals tierPct*100 by default, but a
319
+ // MEGACOMPACT_FAST_GATE_PCT override can raise it, so we take the max.
320
+ const armed = this.lastCtxPercent != null &&
321
+ this.lastCtxPercent >=
322
+ Math.max(effectiveThresholdPct ?? 0, this.config.fastGatePct);
323
+ // S29: ready mirrors the context-handler gate's basis — percent for tiered
324
+ // (the gate fires on pct), tokens for custom (the gate fires on tokens).
325
+ // Previously this always required tokens, so the dashboard could show
326
+ // "armed" (percent high) but never "ready" when tokens were under-reported
327
+ // — the same inconsistency the S29 gate fix removes.
328
+ const ready = this.config.tierPct != null
329
+ ? armed && (this.lastCtxPercent ?? 0) >= (effectiveThresholdPct ?? 0)
330
+ : armed && (this.lastCtxTokens ?? 0) >= this.effectiveThreshold;
331
+ this.dashboard.snapshot({
332
+ version: 1,
333
+ updatedAt: new Date().toISOString(),
334
+ // S24: the headline tier is the LIVE pressure band; the env preset is kept
335
+ // alongside as presetTier so the dashboard can show both.
336
+ tier: this.pressureBand,
337
+ presetTier: this.config.tier,
338
+ pressure: this.pressure,
339
+ config: {
340
+ fastGatePct: this.config.fastGatePct,
341
+ thresholdTokens: this.effectiveThreshold,
342
+ tierPct: this.config.tierPct,
343
+ effectiveThresholdPct,
344
+ anchorUserMessages: this.config.anchorUserMessages,
345
+ preserveRecent: this.config.preserveRecent,
346
+ auto: this.config.auto,
347
+ autoInline: this.config.autoInline,
348
+ },
349
+ session: {
350
+ id: this.rt.sessionId,
351
+ state: this.statusKey ?? "idle",
352
+ persistedThisSession: this.rt.persistedThisSession,
353
+ lastCheckpointId: this.rt.lastCheckpointId ?? null,
354
+ lastCompactedFrom: this.rt.lastCompactedFrom,
355
+ lastCompactedTokens: this.rt.lastCompactedTokens,
356
+ dedupSkips: this.rt.dedupSkips,
357
+ dedupAttempts: this.rt.dedupAttempts,
358
+ },
359
+ context: {
360
+ tokens: this.lastCtxTokens,
361
+ percent: this.lastCtxPercent,
362
+ contextWindow: this.lastCtxWindow,
363
+ },
364
+ trigger: {
365
+ armed,
366
+ ready,
367
+ currentTokens: this.lastCtxTokens,
368
+ thresholdTokens: this.effectiveThreshold,
369
+ fastGatePct: this.config.fastGatePct,
370
+ tierPct: this.config.tierPct,
371
+ effectiveThresholdPct,
372
+ },
373
+ crew: { activeAgents: this.activeAgents, currentTurn: this.currentTurn },
374
+ store: {
375
+ checkpointCount: st.checkpointCount,
376
+ totalTokenEstimate: st.totalTokenEstimate,
377
+ originalTokens: st.originalTokens,
378
+ tokensSaved: this.rt.tokensSaved,
379
+ injectedCount: st.injectedCount,
380
+ dedupHitRate: st.dedupHitRate,
381
+ storageDedupRate: st.storageDedupRate,
382
+ dedupAttempts: st.dedupAttempts,
383
+ dedupCollapsed: st.dedupCollapsed,
384
+ },
385
+ // Reconciled token accounting (single canonical formula, session + repo).
386
+ // Freed = In − Out; In = Freed + Out. session.Freed = rt.tokensSaved (incl.
387
+ // deduped-away originals); repo.Freed = repo.tokensSaved meta counter.
388
+ compression: {
389
+ session: {
390
+ tokensIn: this.rt.tokensSaved + st.totalTokenEstimate,
391
+ tokensOut: st.totalTokenEstimate,
392
+ tokensFreed: this.rt.tokensSaved,
393
+ compressionPct: this.rt.tokensSaved + st.totalTokenEstimate > 0
394
+ ? this.rt.tokensSaved /
395
+ (this.rt.tokensSaved + st.totalTokenEstimate)
396
+ : 0,
397
+ dedupPct: st.storageDedupRate,
398
+ },
399
+ repo: {
400
+ tokensIn: repo.tokensSaved + repo.totalTokenEstimate,
401
+ tokensOut: repo.totalTokenEstimate,
402
+ tokensFreed: repo.tokensSaved,
403
+ compressionPct: repo.tokensSaved + repo.totalTokenEstimate > 0
404
+ ? repo.tokensSaved / (repo.tokensSaved + repo.totalTokenEstimate)
405
+ : 0,
406
+ dedupPct: repo.storageDedupRate,
407
+ },
408
+ },
409
+ repo: {
410
+ checkpointCount: repo.checkpointCount,
411
+ totalTokenEstimate: repo.totalTokenEstimate,
412
+ originalTokens: repo.originalTokens,
413
+ tokensSaved: repo.tokensSaved,
414
+ sessionCount: repo.sessionCount,
415
+ dedupAttempts: repo.dedupAttempts,
416
+ dedupCollapsed: repo.dedupCollapsed,
417
+ storageDedupRate: repo.storageDedupRate,
418
+ },
419
+ integrity: {
420
+ regionsRetained: di.regionsRetained,
421
+ compressedOriginalBytes: di.compressedOriginalBytes,
422
+ duplicatesCollapsed: di.duplicatesCollapsed,
423
+ bytesPermanentlyDeleted: di.bytesPermanentlyDeleted,
424
+ },
425
+ cacheHits: {
426
+ session: cacheHitsSession,
427
+ total: cacheHitsTotal,
428
+ sessionTokensSaved: this.rt.cacheHitTokens,
429
+ totalTokensSaved: cacheHitsTotalTokens,
430
+ },
431
+ compacts: {
432
+ session: this.rt.compactCount,
433
+ total: getCompactCount(this.currentStateDir),
434
+ },
435
+ timeSaved: {
436
+ compact: { sessionSec: sec(this.rt.tokensSaved), totalSec: sec(this.store.repoStats().tokensSaved) },
437
+ cacheHit: { sessionSec: sec(this.rt.cacheHitTokens), totalSec: sec(cacheHitsTotalTokens) },
438
+ },
439
+ model,
440
+ });
441
+ // Live stats widget above the editor
442
+ if (ctx) {
443
+ // ── gather widget data (computed per snapshot, rendered per frame) ────
444
+ const tokStr = this.lastCtxTokens != null
445
+ ? `${Math.round(this.lastCtxTokens / 1000)}k`
446
+ : "?";
447
+ const maxStr = this.lastCtxWindow > 0
448
+ ? `${Math.round(this.lastCtxWindow / 1000)}k`
449
+ : "?";
450
+ const pctStr = this.lastCtxPercent != null
451
+ ? this.lastCtxPercent > 100
452
+ ? `>100%` // S29: overshoot warning, not a raw "250%" — the percent trigger now compacts before 100%, so this is the residual case where it can't keep up.
453
+ : `${Math.round(this.lastCtxPercent * 10) / 10}%`
454
+ : "?%";
455
+ // S24: the tier label is the LIVE pressure band (low/medium/high/ultra/
456
+ // mega), not the static env preset. It climbs as context fills.
457
+ const liveBand = this.pressureBand;
458
+ const tierLabel = `${C.bold}${liveBand}${C.reset}${C.gray}·${this.config.tier}${C.reset}`;
459
+ const triggerLabel = ready
460
+ ? `${C.green}● ready${C.reset}`
461
+ : armed
462
+ ? `${C.amber}◐ armed${C.reset}`
463
+ : `${C.gray}○ idle${C.reset}`;
464
+ // Storage dedup rate is cumulative (store-wide, per-repo) and survives
465
+ // session resets. Always show a number (decimal for sub-10%).
466
+ const storageRate = st.storageDedupRate; // 0..1
467
+ const dedupStr = storageRate * 100 >= 10
468
+ ? `${Math.round(storageRate * 100)}%`
469
+ : `${(storageRate * 100).toFixed(1)}%`;
470
+ // Agents view: count + status (S27 per-agent tokens are gated on P0).
471
+ const agentLabel = this.activeAgents > 0
472
+ ? `🤖 ${this.activeAgents} agent${this.activeAgents === 1 ? "" : "s"}`
473
+ : `${C.dim}🤖 idle${C.reset}`;
474
+ const agentStr = ` │ ${agentLabel}`;
475
+ const turnStr = this.currentTurn > 0 ? ` │ turn ${this.currentTurn}` : "";
476
+ // Reconciled in/out view (session + repo) — ONE canonical formula.
477
+ const sessIn = this.rt.tokensSaved + st.totalTokenEstimate;
478
+ const sessKept = st.totalTokenEstimate;
479
+ const sessPct = sessIn > 0 ? this.rt.tokensSaved / sessIn : 0;
480
+ const repoIn = repo.tokensSaved + repo.totalTokenEstimate;
481
+ const repoKept = repo.totalTokenEstimate;
482
+ const repoPct = repoIn > 0 ? repo.tokensSaved / repoIn : 0;
483
+ const sTxt = (sessPct * 100).toFixed(sessPct * 100 >= 10 ? 0 : 1);
484
+ const rTxt = (repoPct * 100).toFixed(repoPct * 100 >= 10 ? 0 : 1);
485
+ const ctxPct = this.lastCtxPercent != null ? this.lastCtxPercent / 100 : 0;
486
+ // Model + provider (S26 capture) for the header.
487
+ const modelName = modelSnap?.modelName ?? modelSnap?.modelId ?? "?";
488
+ const modelStr = modelSnap?.provider
489
+ ? `${modelName}·${modelSnap.provider}`
490
+ : modelName;
491
+ // Since-last-compact (ms; null until first compaction this session).
492
+ const sinceCompact = this.rt.lastCompactAt != null
493
+ ? Date.now() - this.rt.lastCompactAt
494
+ : null;
495
+ // Memory store: embedder + compression ratio (original / stored).
496
+ const embedderName = this.embedderName();
497
+ const compRatio = st.originalTokens > 0 && st.totalTokenEstimate > 0
498
+ ? st.originalTokens / st.totalTokenEstimate
499
+ : st.originalTokens > 0
500
+ ? 1
501
+ : 0;
502
+ const compStr = compRatio >= 1 ? `${compRatio.toFixed(1)}x` : "—";
503
+ // Cross-repo drift status (cached, read-only).
504
+ const driftStatus = this.driftStatus();
505
+ const agentsActive = this.activeAgents > 0;
506
+ // S31: game-mode state for the widget (theme/mode/level + MEGA CACHE).
507
+ // Pulled from the cached game_state row; cachePct is the REAL dedup hit
508
+ // rate (may exceed 100% — that's the MEGA CACHE trigger). megaCacheFlare
509
+ // is false for now (S33.4 scoring hook arms it when cachePct > 100).
510
+ const gs = this.getCachedGameState();
511
+ // S34: derive the level-up flare from the turn count each snapshot.
512
+ const curLevel = this.getTurnLevel();
513
+ if (curLevel > this.lastLevel)
514
+ this.levelUpFlare = true;
515
+ const cachePct = st.dedupHitRate * 100;
516
+ this.widgetData = {
517
+ version: ownVersion(),
518
+ tierLabel,
519
+ triggerLabel,
520
+ pctStr,
521
+ tokStr,
522
+ maxStr,
523
+ ctxPct,
524
+ chk: st.checkpointCount,
525
+ agentStr,
526
+ turnStr,
527
+ dedupStr,
528
+ sessIn,
529
+ sessKept,
530
+ sTxt,
531
+ repoIn,
532
+ repoKept,
533
+ rTxt,
534
+ repoChk: repo.checkpointCount,
535
+ repoSess: repo.sessionCount,
536
+ modelStr,
537
+ sinceCompact,
538
+ embedderName,
539
+ compStr,
540
+ driftStatus,
541
+ agentsActive,
542
+ fresh: Date.now() - this.lastActivityAt < 4000,
543
+ ticker: this.ticker,
544
+ lastWhy: this.lastWhy,
545
+ tierTrace: this.tierTrace,
546
+ pulsing: this.pulsing,
547
+ // S31 game-mode fields:
548
+ gameMode: gs.game_mode_on,
549
+ theme: getTheme(gs.theme) ? gs.theme : "transparent",
550
+ tuiMode: gs.tui_display_mode,
551
+ level: this.getTurnLevel(),
552
+ cachePct,
553
+ megaCacheFlare: this.megaCacheFlare,
554
+ megaCacheFlarePct: this.megaCacheFlarePct,
555
+ levelUpFlare: this.levelUpFlare,
556
+ achievementFlare: this.achievementFlare,
557
+ achievementFlareTitles: this.achievementFlareTitles,
558
+ };
559
+ // S33: consume the flare after copying it into widgetData so it fires
560
+ // for exactly one render cycle (the gag flares once, then clears).
561
+ this.megaCacheFlare = false;
562
+ this.megaCacheFlarePct = 0;
563
+ // S34: consume the level-up flare after one render cycle (mirrors the
564
+ // megaCacheFlare one-shot semantics), and advance lastLevel.
565
+ this.levelUpFlare = false;
566
+ this.lastLevel = curLevel;
567
+ // S35: consume the achievement-unlock flare after one render cycle
568
+ // (mirrors the megaCacheFlare/levelUpFlare one-shot semantics).
569
+ this.achievementFlare = false;
570
+ this.achievementFlareTitles = [];
571
+ // Auto-fit: register a factory so pi re-renders the panel at the REAL
572
+ // terminal width every frame (tui.columns), instead of guessing with
573
+ // process.stdout.columns. buildWidgetLines reads this.widgetData live.
574
+ this.renderWidget(ctx);
575
+ }
576
+ }
577
+ /** Register the above-editor widget as a width-aware factory so pi re-renders
578
+ * it at the REAL terminal width every frame (auto-fit wide/narrow). The
579
+ * factory returns a minimal Component whose render() reads this.widgetData.
580
+ */
581
+ renderWidget(ctx) {
582
+ ctx.ui.setWidget(WIDGET_KEY, (_tui, _theme) => ({
583
+ render: (width) => buildWidgetLines(this.widgetData, width > 0 ? width : 200, this.activeAgents),
584
+ invalidate: () => { },
585
+ }), { placement: "aboveEditor" });
586
+ }
587
+ /** Active embedder name for the memory-store line (Trigram default / MiniLM). */
588
+ embedderName() {
589
+ // MINILM_EMBEDDER flag lives in src/config/dedup.ts; read the same env var
590
+ // the embedder factory uses so the label matches what's actually running.
591
+ return process.env.MEGACOMPACT_MINILM === "true" ||
592
+ process.env.MEGACOMPACT_MINILM === "1"
593
+ ? "MiniLM"
594
+ : "Trigram";
595
+ }
596
+ /** Cross-repo drift status (ok | warn), cached for 30s (opens the registry DB). */
597
+ driftStatus() {
598
+ const now = Date.now();
599
+ if (this.driftCache && now - this.driftCache.at < 30_000)
600
+ return this.driftCache.status;
601
+ let status = "ok";
602
+ try {
603
+ const report = detectCrossRepoDrift();
604
+ status = report.totals.warn > 0 ? "warn" : "ok";
605
+ }
606
+ catch {
607
+ status = "ok";
608
+ }
609
+ this.driftCache = { at: now, status };
610
+ return status;
611
+ }
612
+ setStatus(ctx, text) {
613
+ this.statusKey = text;
614
+ ctx.ui.setStatus(STATUS_KEY, text);
615
+ }
616
+ resetRuntime(sessionId) {
617
+ const sid = normalizeSessionId(sessionId);
618
+ if (this.rt.sessionId === sid && this.rt.persistedThisSession)
619
+ return; // same session, keep checkpoint memory
620
+ this.rt = {
621
+ sessionId: sid,
622
+ persistedThisSession: false,
623
+ lastCheckpointId: undefined,
624
+ lastCompactedFrom: 0,
625
+ lastCompactedTokens: 0,
626
+ dedupSkips: 0,
627
+ dedupAttempts: 0,
628
+ tokensSaved: 0,
629
+ lastCompactAt: null,
630
+ lastNativeCompactAt: null,
631
+ compactCount: 0,
632
+ recallInjections: 0,
633
+ cacheHitTokens: 0,
634
+ lengthStopPending: false,
635
+ };
636
+ this.statusKey = undefined;
637
+ this.activeAgents = 0;
638
+ this.currentTurn = 0;
639
+ this.lastActivityAt = 0;
640
+ this.tierTrace = undefined;
641
+ this.ticker.length = 0;
642
+ this.pulsing = false;
643
+ this.savedGoal = 50_000;
644
+ this.lastWhy = undefined;
645
+ // S31 audit P2: symmetry with bindRepo — a reset can coincide with a context
646
+ // that re-binds the repo, so drop the memo too. Cheap; the next
647
+ // getCachedGameState() re-queries lazily.
648
+ this.cachedGameState = undefined;
649
+ }
650
+ /**
651
+ * Capture the active model/provider from ctx.model and persist it so cost
652
+ * estimation + the dashboard can read real pricing. Cheap + idempotent-ish:
653
+ * only writes a new row when the model id changes (models change rarely).
654
+ */
655
+ captureModel(ctx) {
656
+ const m = ctx.model;
657
+ if (!m) {
658
+ this.appendEvent("captureModel:no-model", { cwd: ctx.cwd });
659
+ return;
660
+ }
661
+ if (this.currentModel &&
662
+ this.currentModel.modelId === m.id &&
663
+ this.currentModel.provider === m.provider)
664
+ return;
665
+ let providerName = null;
666
+ try {
667
+ providerName =
668
+ ctx.modelRegistry?.getProviderDisplayName(m.provider) ?? null;
669
+ }
670
+ catch {
671
+ /* optional */
672
+ }
673
+ const snap = {
674
+ provider: m.provider,
675
+ providerName,
676
+ modelId: m.id,
677
+ modelName: m.name ?? null,
678
+ inputRate: m.cost?.input ?? 0,
679
+ outputRate: m.cost?.output ?? 0,
680
+ contextWindow: m.contextWindow ?? 0,
681
+ maxTokens: m.maxTokens ?? 0,
682
+ reasoning: !!m.reasoning,
683
+ };
684
+ this.currentModel = { ...snap, capturedAt: Date.now() };
685
+ this.diagCaptureModelCalls++;
686
+ const repo = resolveRepoRoot(ctx.cwd) ?? this.currentStateDir;
687
+ // S26: previously a single silent `catch {}` hid every capture failure, so
688
+ // model_snapshots stayed empty and the cost card read $0.00 with zero signal.
689
+ // Split per-write + append to events.log (always-on, dashboard live-streams
690
+ // it) + bump a DIAG counter so a live capture surfaces the root cause.
691
+ try {
692
+ recordModelSnapshot(repo, snap, this.currentStateDir);
693
+ this.appendEvent("captureModel:recorded", {
694
+ repo,
695
+ modelId: snap.modelId,
696
+ provider: snap.provider,
697
+ inputRate: snap.inputRate,
698
+ outputRate: snap.outputRate,
699
+ });
700
+ }
701
+ catch (e) {
702
+ this.diagCaptureModelFails++;
703
+ this.appendEvent("captureModel:record-failed", {
704
+ repo,
705
+ modelId: snap.modelId,
706
+ error: e instanceof Error ? e.message : String(e),
707
+ stack: e instanceof Error ? e.stack : undefined,
708
+ });
709
+ }
710
+ try {
711
+ // Denormalize the active model into the machine-wide index so the
712
+ // All-repos dashboard table can show provider/model per repo without
713
+ // opening every repo's DB. Best-effort + non-fatal.
714
+ recordRepoModel(repo, {
715
+ provider: snap.provider,
716
+ providerName: snap.providerName,
717
+ modelName: snap.modelName,
718
+ inputRate: snap.inputRate,
719
+ outputRate: snap.outputRate,
720
+ stateDir: this.currentStateDir,
721
+ displayName: repo.split(/[\\/]/).filter(Boolean).pop() ?? repo,
722
+ });
723
+ }
724
+ catch (e) {
725
+ this.appendEvent("captureModel:index-record-failed", {
726
+ repo,
727
+ modelId: snap.modelId,
728
+ error: e instanceof Error ? e.message : String(e),
729
+ });
730
+ }
731
+ }
732
+ /**
733
+ * Append a structured line to the repo's events.log — the always-on
734
+ * diagnostics sink the dashboard live-streams. Unlike this.logger (gated by
735
+ * config.debug), this fires in production, so capture failures surface during
736
+ * a real capture even with debugging off. Best-effort + non-fatal.
737
+ */
738
+ appendEvent(event, fields) {
739
+ try {
740
+ mkdirSync(this.currentStateDir, { recursive: true });
741
+ appendFileSync(join(this.currentStateDir, "events.log"), JSON.stringify({ ts: Date.now(), event, ...fields }) + "\n");
742
+ }
743
+ catch {
744
+ /* non-fatal */
745
+ }
746
+ }
747
+ /** S21: state dir of the currently bound repo (where memories live). */
748
+ getStateDir() {
749
+ return this.currentStateDir;
750
+ }
751
+ /** S32: (re)target the fs.watch cache-eviction watcher at the current
752
+ * stateDir's sqlite.db. Called from the constructor + every bindRepo repo
753
+ * switch so the watcher always tracks the NEW repo's db file. If a watcher
754
+ * already exists for this dir, no-op; if the dir changed, close the old one
755
+ * first. fs.watch can throw on a missing file / platform issues — wrapped
756
+ * non-fatal; the next getCachedGameState() re-queries the DB anyway. */
757
+ ensureGameStateWatcher() {
758
+ if (this.gameStateWatcher && this.gameStateWatchDir === this.currentStateDir) {
759
+ return;
760
+ }
761
+ if (this.gameStateWatcher) {
762
+ try {
763
+ this.gameStateWatcher.close();
764
+ }
765
+ catch { /* non-fatal */ }
766
+ this.gameStateWatcher = undefined;
767
+ this.gameStateWatchDir = undefined;
768
+ }
769
+ try {
770
+ this.gameStateWatcher = watch(join(this.currentStateDir, "sqlite.db"), () => { this.cachedGameState = undefined; });
771
+ this.gameStateWatchDir = this.currentStateDir;
772
+ }
773
+ catch {
774
+ /* non-fatal: missing file / platform issue — next snapshot re-queries */
775
+ }
776
+ }
777
+ /** S32: release the fs.watch game-state watcher. Called when the runtime is
778
+ * torn down (no existing dispose path — the process exit reclaims the fd,
779
+ * but explicit close is correct for any in-process reload / test reuse). */
780
+ dispose() {
781
+ if (this.gameStateWatcher) {
782
+ try {
783
+ this.gameStateWatcher.close();
784
+ }
785
+ catch { /* non-fatal */ }
786
+ this.gameStateWatcher = undefined;
787
+ this.gameStateWatchDir = undefined;
788
+ }
789
+ }
790
+ /** S31: the cached game-mode state (game_mode_on/theme/tui_display_mode).
791
+ * Lazily read from the game_state SQLite row on the first call, then
792
+ * memoized until `bumpGameState()` evicts it. Reading is non-throwing
793
+ * (getGameState returns DEFAULT_GAME_STATE on any error), so the widget
794
+ * can call this on every render safely. */
795
+ getCachedGameState() {
796
+ if (!this.cachedGameState) {
797
+ try {
798
+ this.cachedGameState = getGameState(this.currentStateDir);
799
+ }
800
+ catch {
801
+ this.cachedGameState = {
802
+ game_mode_on: false,
803
+ theme: "transparent",
804
+ tui_display_mode: "full",
805
+ };
806
+ }
807
+ }
808
+ return this.cachedGameState;
809
+ }
810
+ /** S31: evict the cached game-mode state so the next widget render re-reads
811
+ * the game_state row. Called by /mega-game after every setGameState() so
812
+ * the panel picks up theme/mode/toggle changes live. */
813
+ bumpGameState() {
814
+ this.cachedGameState = undefined;
815
+ }
816
+ /** S33: player level for game mode — floor(log2(turns+1))+1 (gentle).
817
+ * Defensive: non-finite/negative collapses to 1 (never NaN). */
818
+ getTurnLevel() {
819
+ return turnLevel(this.currentTurn);
820
+ }
821
+ /** S33: arm the transient MEGA CACHE flare so the next snapshot() copies it
822
+ * into widgetData and the widget renders the oopsie gag for one cycle. */
823
+ armMegaCacheFlare(peakPct) {
824
+ this.megaCacheFlare = true;
825
+ this.megaCacheFlarePct = peakPct;
826
+ }
827
+ /** S35: arm the transient achievement-unlock flare with the newly-unlocked
828
+ * titles so the next snapshot() copies them into widgetData and the widget
829
+ * renders the one-time unlock toast for one render cycle. */
830
+ armAchievementFlare(titles) {
831
+ this.achievementFlare = true;
832
+ this.achievementFlareTitles = titles;
833
+ }
834
+ /** Build the sync onTier callback that paints the live per-tier trace. */
835
+ makeTierCallback(ctx) {
836
+ const order = ["L0", "L1", "L2", "new"];
837
+ const seen = new Map();
838
+ const glyph = (status) => status === "deduped"
839
+ ? `${C.green}✓${C.reset}`
840
+ : status === "passed"
841
+ ? `${C.dim}○${C.reset}`
842
+ : status === "scanning"
843
+ ? `${C.amber}…${C.reset}`
844
+ : `${C.cyan}●${C.reset}`;
845
+ return (ev) => {
846
+ const label = ev.tier === "new"
847
+ ? `${C.cyan}stored${C.reset}`
848
+ : `${ev.tier} ${glyph(ev.status)}` +
849
+ (ev.detail ? ` ${C.gray}(${ev.detail})${C.reset}` : "");
850
+ // Show the most recent outcome per tier (collapses re-fires).
851
+ seen.set(ev.tier, label);
852
+ const show = [];
853
+ for (const t of order)
854
+ if (seen.has(t))
855
+ show.push(seen.get(t));
856
+ this.tierTrace = `${C.teal}⚙${C.reset} ${show.join(` ${C.gray}→${C.reset} `)}`;
857
+ this.lastActivityAt = Date.now();
858
+ try {
859
+ this.snapshot(ctx);
860
+ }
861
+ catch {
862
+ /* non-fatal */
863
+ }
864
+ };
865
+ }
866
+ // Phase 3 — recall/activity ticker ring buffer.
867
+ pushTicker(text) {
868
+ this.ticker.push({ text, at: Date.now() });
869
+ while (this.ticker.length > this.TICKER_MAX)
870
+ this.ticker.shift();
871
+ this.lastActivityAt = Date.now();
872
+ }
873
+ /** Convert the messages pi hands us in the `context` event into the engine view. */
874
+ engineView(messages) {
875
+ return toEngineMessages(messages);
876
+ }
877
+ }