pi-mega-compact 0.7.9 → 0.8.1

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 (81) hide show
  1. package/dist/extensions/dashboard-server/html.js +333 -66
  2. package/dist/extensions/dashboard-server/html.test.js +41 -0
  3. package/dist/extensions/dashboard-server/server.js +170 -4
  4. package/dist/extensions/dashboard-server/server.test.js +120 -0
  5. package/dist/extensions/dashboard-server-s32.test.js +181 -0
  6. package/dist/extensions/mega-compact.js +3 -0
  7. package/dist/extensions/mega-events/agent-handlers.js +49 -0
  8. package/dist/extensions/mega-events/compact-handlers.js +29 -0
  9. package/dist/extensions/mega-events/context-handler.js +5 -3
  10. package/dist/extensions/mega-game-cmds.js +119 -0
  11. package/dist/extensions/mega-game-cmds.test.js +118 -0
  12. package/dist/extensions/mega-runtime/state.js +181 -1
  13. package/dist/extensions/mega-runtime/state.test.js +171 -0
  14. package/dist/extensions/mega-runtime/widget.js +93 -20
  15. package/dist/extensions/mega-runtime/widget.test.js +160 -0
  16. package/dist/src/config/themes.js +84 -0
  17. package/dist/src/config/themes.test.js +94 -0
  18. package/dist/src/game/scoring.js +105 -0
  19. package/dist/src/game/scoring.test.js +98 -0
  20. package/dist/src/store/sqlite/game-achievements.js +111 -0
  21. package/dist/src/store/sqlite/game-achievements.test.js +67 -0
  22. package/dist/src/store/sqlite/game-scores.js +105 -0
  23. package/dist/src/store/sqlite/game-scores.test.js +106 -0
  24. package/dist/src/store/sqlite/game-state.js +54 -0
  25. package/dist/src/store/sqlite/game-state.test.js +76 -0
  26. package/dist/src/store/sqlite/schema.js +44 -0
  27. package/dist/src/store/sqlite.js +3 -0
  28. package/extensions/dashboard-server/html.test.ts +50 -0
  29. package/extensions/dashboard-server/html.ts +334 -66
  30. package/extensions/dashboard-server/server.test.ts +131 -0
  31. package/extensions/dashboard-server/server.ts +157 -4
  32. package/extensions/dashboard-server-s32.test.ts +195 -0
  33. package/extensions/mega-compact.ts +3 -0
  34. package/extensions/mega-events/agent-handlers.ts +48 -0
  35. package/extensions/mega-events/compact-handlers.ts +28 -0
  36. package/extensions/mega-events/context-handler.ts +4 -2
  37. package/extensions/mega-game-cmds.test.ts +143 -0
  38. package/extensions/mega-game-cmds.ts +142 -0
  39. package/extensions/mega-runtime/state.test.ts +171 -0
  40. package/extensions/mega-runtime/state.ts +184 -0
  41. package/extensions/mega-runtime/widget.test.ts +185 -0
  42. package/extensions/mega-runtime/widget.ts +119 -18
  43. package/package.json +1 -1
  44. package/src/config/themes.test.ts +116 -0
  45. package/src/config/themes.ts +124 -0
  46. package/src/game/scoring.test.ts +103 -0
  47. package/src/game/scoring.ts +158 -0
  48. package/src/store/sqlite/game-achievements.test.ts +80 -0
  49. package/src/store/sqlite/game-achievements.ts +147 -0
  50. package/src/store/sqlite/game-scores.test.ts +132 -0
  51. package/src/store/sqlite/game-scores.ts +168 -0
  52. package/src/store/sqlite/game-state.test.ts +89 -0
  53. package/src/store/sqlite/game-state.ts +87 -0
  54. package/src/store/sqlite/schema.ts +47 -0
  55. package/src/store/sqlite.ts +3 -0
  56. package/dist/extensions/dashboard-server/helpers.js +0 -37
  57. package/dist/extensions/dashboard-server/html/all-repos-tab.js +0 -26
  58. package/dist/extensions/dashboard-server/html/body-open.js +0 -23
  59. package/dist/extensions/dashboard-server/html/current-repo-tab.js +0 -130
  60. package/dist/extensions/dashboard-server/html/head-open.js +0 -16
  61. package/dist/extensions/dashboard-server/html/high-score-tab.js +0 -25
  62. package/dist/extensions/dashboard-server/html/repo-detail-modal.js +0 -26
  63. package/dist/extensions/dashboard-server/html/script.js +0 -259
  64. package/dist/extensions/dashboard-server/html/styles.js +0 -103
  65. package/dist/extensions/dashboard-server/html/summary-tab.js +0 -19
  66. package/dist/extensions/dashboard-server/html-template.js +0 -41
  67. package/dist/src/store/sqlite/connection.js +0 -35
  68. package/dist/src/store/sqlite/index-store.js +0 -167
  69. package/dist/src/store/sqlite/memory.js +0 -54
  70. package/dist/src/store/sqlite/minhash-lsh.js +0 -47
  71. package/dist/src/store/sqlite/sessions.js +0 -39
  72. package/dist/src/store/sqlite/transaction.js +0 -19
  73. package/dist/src/vectorStore/add.js +0 -260
  74. package/dist/src/vectorStore/dedup.js +0 -52
  75. package/dist/src/vectorStore/index.js +0 -10
  76. package/dist/src/vectorStore/queries.js +0 -83
  77. package/dist/src/vectorStore/search.js +0 -95
  78. package/dist/src/vectorStore/session.js +0 -19
  79. package/dist/src/vectorStore/store.js +0 -105
  80. package/dist/src/vectorStore/types.js +0 -6
  81. package/dist/src/vectorStore/utils.js +0 -23
@@ -27,7 +27,9 @@ import {
27
27
  getCompactCount,
28
28
  getRecallInjected,
29
29
  getCacheHitTokensSaved,
30
+ getGameState,
30
31
  type ModelSnapshot,
32
+ type GameState,
31
33
  } from "../../src/store/sqlite.js";
32
34
  import { detectCrossRepoDrift } from "../../src/driftDetection.js";
33
35
  import {
@@ -54,6 +56,9 @@ import {
54
56
  type TickerEntry,
55
57
  type WidgetData,
56
58
  } from "./widget.js";
59
+ import { getTheme } from "../../src/config/themes.js";
60
+ import { watch, type FSWatcher } from "node:fs";
61
+ import { turnLevel } from "../../src/game/scoring.js";
57
62
 
58
63
  export class MegaRuntime {
59
64
  config: MegaConfig;
@@ -88,6 +93,22 @@ export class MegaRuntime {
88
93
  // Agent tracking for real-time widget updates
89
94
  activeAgents = 0;
90
95
  currentTurn = 0;
96
+ // S33: transient MEGA CACHE flare flag (armed by the turn_end scoring hook
97
+ // when cachePct > 100). Copied into widgetData.megaCacheFlare on the next
98
+ // snapshot() so the widget renders the oopsie gag, then reset (one cycle).
99
+ megaCacheFlare = false;
100
+ megaCacheFlarePct = 0;
101
+ levelUpFlare = false;
102
+ lastLevel = 0;
103
+ // S35: transient achievement-unlock flare (armed by the scoring hooks after
104
+ // evaluateAndUnlockAchievements returns newly-unlocked titles). Copied into
105
+ // widgetData.achievementFlare on the next snapshot() so the widget renders the
106
+ // unlock toast, then reset (one cycle — mirrors megaCacheFlare/levelUpFlare).
107
+ achievementFlare = false;
108
+ achievementFlareTitles: string[] = [];
109
+ // S33: last cumulative dedup-collapsed count seen by the session_compact
110
+ // hook, so we only record the DELTA as the dedupe score (leaderboard sums).
111
+ lastDedupCollapsed = 0;
91
112
  // Recall block produced by auto-inline (resume/branch) that the next
92
113
  // before_agent_start should prepend to the system prompt. Unset after use.
93
114
  pendingRecallBlock: string | undefined;
@@ -134,6 +155,23 @@ export class MegaRuntime {
134
155
  // Cached cross-repo drift status (recomputed at most every 30s — it opens the
135
156
  // machine-wide registry DB, so we don't want to do it on every render frame).
136
157
  private driftCache: { at: number; status: "ok" | "warn" } | null = 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
+ private cachedGameState: GameState | undefined;
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
+ private gameStateWatcher?: FSWatcher;
174
+ private gameStateWatchDir?: string;
137
175
 
138
176
  /**
139
177
  * DIAG counters for the "team run doesn't relieve context" investigation.
@@ -235,6 +273,7 @@ export class MegaRuntime {
235
273
  });
236
274
  this.dashboard = new Dashboard(config.stateDir);
237
275
  this.currentStateDir = config.stateDir;
276
+ this.ensureGameStateWatcher();
238
277
  }
239
278
 
240
279
  // ---- per-repo binding -----------------------------------------------------
@@ -252,6 +291,15 @@ export class MegaRuntime {
252
291
  if (key === this.activeRepoRoot) return dir;
253
292
  this.activeRepoRoot = key;
254
293
  this.currentStateDir = dir;
294
+ // S31 audit P2: bindRepo switched currentStateDir but left cachedGameState
295
+ // memoized -> the widget kept showing the previous repo's theme/mode/toggle
296
+ // until /mega-game or a restart. The game_state row is per-repo (per
297
+ // stateDir), so evict the memo on every repo switch; the next widget render
298
+ // re-queries lazily via getCachedGameState().
299
+ this.cachedGameState = undefined;
300
+ // S32: re-target the fs.watch cache-eviction watcher at the NEW stateDir's
301
+ // sqlite.db so cross-process writes (dashboard server) still evict the memo.
302
+ this.ensureGameStateWatcher();
255
303
  this.store = new VectorStore({
256
304
  dedupSim: this.config.dedupSim,
257
305
  stateDir: dir,
@@ -520,6 +568,15 @@ export class MegaRuntime {
520
568
  const driftStatus = this.driftStatus();
521
569
  const agentsActive = this.activeAgents > 0;
522
570
 
571
+ // S31: game-mode state for the widget (theme/mode/level + MEGA CACHE).
572
+ // Pulled from the cached game_state row; cachePct is the REAL dedup hit
573
+ // rate (may exceed 100% — that's the MEGA CACHE trigger). megaCacheFlare
574
+ // is false for now (S33.4 scoring hook arms it when cachePct > 100).
575
+ const gs = this.getCachedGameState();
576
+ // S34: derive the level-up flare from the turn count each snapshot.
577
+ const curLevel = this.getTurnLevel();
578
+ if (curLevel > this.lastLevel) this.levelUpFlare = true;
579
+ const cachePct = st.dedupHitRate * 100;
523
580
  this.widgetData = {
524
581
  version: ownVersion(),
525
582
  tierLabel,
@@ -551,7 +608,31 @@ export class MegaRuntime {
551
608
  lastWhy: this.lastWhy,
552
609
  tierTrace: this.tierTrace,
553
610
  pulsing: this.pulsing,
611
+ // S31 game-mode fields:
612
+ gameMode: gs.game_mode_on,
613
+ theme: getTheme(gs.theme) ? gs.theme : "transparent",
614
+ tuiMode: gs.tui_display_mode,
615
+ level: this.getTurnLevel(),
616
+ cachePct,
617
+ megaCacheFlare: this.megaCacheFlare,
618
+ megaCacheFlarePct: this.megaCacheFlarePct,
619
+ levelUpFlare: this.levelUpFlare,
620
+ achievementFlare: this.achievementFlare,
621
+ achievementFlareTitles: this.achievementFlareTitles,
554
622
  };
623
+ // S33: consume the flare after copying it into widgetData so it fires
624
+ // for exactly one render cycle (the gag flares once, then clears).
625
+ this.megaCacheFlare = false;
626
+ this.megaCacheFlarePct = 0;
627
+
628
+ // S34: consume the level-up flare after one render cycle (mirrors the
629
+ // megaCacheFlare one-shot semantics), and advance lastLevel.
630
+ this.levelUpFlare = false;
631
+ this.lastLevel = curLevel;
632
+ // S35: consume the achievement-unlock flare after one render cycle
633
+ // (mirrors the megaCacheFlare/levelUpFlare one-shot semantics).
634
+ this.achievementFlare = false;
635
+ this.achievementFlareTitles = [];
555
636
  // Auto-fit: register a factory so pi re-renders the panel at the REAL
556
637
  // terminal width every frame (tui.columns), instead of guessing with
557
638
  // process.stdout.columns. buildWidgetLines reads this.widgetData live.
@@ -638,6 +719,10 @@ export class MegaRuntime {
638
719
  this.pulsing = false;
639
720
  this.savedGoal = 50_000;
640
721
  this.lastWhy = undefined;
722
+ // S31 audit P2: symmetry with bindRepo — a reset can coincide with a context
723
+ // that re-binds the repo, so drop the memo too. Cheap; the next
724
+ // getCachedGameState() re-queries lazily.
725
+ this.cachedGameState = undefined;
641
726
  }
642
727
 
643
728
  /**
@@ -745,6 +830,105 @@ export class MegaRuntime {
745
830
  return this.currentStateDir;
746
831
  }
747
832
 
833
+ /** S32: (re)target the fs.watch cache-eviction watcher at the current
834
+ * stateDir's sqlite.db. Called from the constructor + every bindRepo repo
835
+ * switch so the watcher always tracks the NEW repo's db file. If a watcher
836
+ * already exists for this dir, no-op; if the dir changed, close the old one
837
+ * first. fs.watch can throw on a missing file / platform issues — wrapped
838
+ * non-fatal; the next getCachedGameState() re-queries the DB anyway. */
839
+ private ensureGameStateWatcher(): void {
840
+ if (this.gameStateWatcher && this.gameStateWatchDir === this.currentStateDir) {
841
+ return;
842
+ }
843
+ if (this.gameStateWatcher) {
844
+ try { this.gameStateWatcher.close(); } catch { /* non-fatal */ }
845
+ this.gameStateWatcher = undefined;
846
+ this.gameStateWatchDir = undefined;
847
+ }
848
+ try {
849
+ // Watch the state DIR (not just sqlite.db) and filter by filename.
850
+ // Why: the store is WAL-mode (openStore sets PRAGMA journal_mode=WAL).
851
+ // Cross-process writes (dashboard server child) append to sqlite.db-wal
852
+ // and do NOT modify sqlite.db until a checkpoint — and a long-lived
853
+ // parent connection (VectorStore + dashboard readers) keeps the WAL
854
+ // uncheckpointed, so a watcher on sqlite.db alone never fires and
855
+ // cachedGameState stays stale (theme stuck after a dashboard edit).
856
+ // Watching the dir + matching sqlite.db* catches the main db, the -wal
857
+ // sidecar, and -shm, so the memo evicts on any cross-process write. The
858
+ // filter also excludes events.log / *.log noise in the same dir.
859
+ this.gameStateWatcher = watch(
860
+ this.currentStateDir,
861
+ (_eventType, filename) => {
862
+ if (typeof filename === "string" && filename.startsWith("sqlite.db")) {
863
+ this.cachedGameState = undefined;
864
+ }
865
+ },
866
+ );
867
+ this.gameStateWatchDir = this.currentStateDir;
868
+ } catch {
869
+ /* non-fatal: missing dir / platform issue — next snapshot re-queries */
870
+ }
871
+ }
872
+
873
+ /** S32: release the fs.watch game-state watcher. Called when the runtime is
874
+ * torn down (no existing dispose path — the process exit reclaims the fd,
875
+ * but explicit close is correct for any in-process reload / test reuse). */
876
+ dispose(): void {
877
+ if (this.gameStateWatcher) {
878
+ try { this.gameStateWatcher.close(); } catch { /* non-fatal */ }
879
+ this.gameStateWatcher = undefined;
880
+ this.gameStateWatchDir = undefined;
881
+ }
882
+ }
883
+
884
+ /** S31: the cached game-mode state (game_mode_on/theme/tui_display_mode).
885
+ * Lazily read from the game_state SQLite row on the first call, then
886
+ * memoized until `bumpGameState()` evicts it. Reading is non-throwing
887
+ * (getGameState returns DEFAULT_GAME_STATE on any error), so the widget
888
+ * can call this on every render safely. */
889
+ getCachedGameState(): GameState {
890
+ if (!this.cachedGameState) {
891
+ try {
892
+ this.cachedGameState = getGameState(this.currentStateDir);
893
+ } catch {
894
+ this.cachedGameState = {
895
+ game_mode_on: false,
896
+ theme: "transparent",
897
+ tui_display_mode: "full",
898
+ };
899
+ }
900
+ }
901
+ return this.cachedGameState;
902
+ }
903
+
904
+ /** S31: evict the cached game-mode state so the next widget render re-reads
905
+ * the game_state row. Called by /mega-game after every setGameState() so
906
+ * the panel picks up theme/mode/toggle changes live. */
907
+ bumpGameState(): void {
908
+ this.cachedGameState = undefined;
909
+ }
910
+
911
+ /** S33: player level for game mode — floor(log2(turns+1))+1 (gentle).
912
+ * Defensive: non-finite/negative collapses to 1 (never NaN). */
913
+ private getTurnLevel(): number {
914
+ return turnLevel(this.currentTurn);
915
+ }
916
+
917
+ /** S33: arm the transient MEGA CACHE flare so the next snapshot() copies it
918
+ * into widgetData and the widget renders the oopsie gag for one cycle. */
919
+ armMegaCacheFlare(peakPct: number): void {
920
+ this.megaCacheFlare = true;
921
+ this.megaCacheFlarePct = peakPct;
922
+ }
923
+
924
+ /** S35: arm the transient achievement-unlock flare with the newly-unlocked
925
+ * titles so the next snapshot() copies them into widgetData and the widget
926
+ * renders the one-time unlock toast for one render cycle. */
927
+ armAchievementFlare(titles: string[]): void {
928
+ this.achievementFlare = true;
929
+ this.achievementFlareTitles = titles;
930
+ }
931
+
748
932
  /** Build the sync onTier callback that paints the live per-tier trace. */
749
933
  makeTierCallback(
750
934
  ctx: ExtensionContext,
@@ -0,0 +1,185 @@
1
+ /**
2
+ * widget.test.ts — S31 buildWidgetLines render snapshot matrix.
3
+ *
4
+ * buildWidgetLines is a free function (no pi runtime needed), so we drive it
5
+ * directly with a fake WidgetData across the full matrix:
6
+ * 6 themes × {full,minimal} × {gameMode on/off} × {cachePct<100, >=100}
7
+ * and assert the S31 invariants:
8
+ * (a) transparent theme → no '\x1b[48;' bg fill on any line
9
+ * (b) non-transparent themes → at least one line carries '\x1b[48;'
10
+ * (c) minimal mode → exactly one content line (between the two panel bars)
11
+ * (d) gameMode off → no 'LVL' + no 'MEGA CACHE'
12
+ * (e) megaCacheFlare + gameMode on + cachePct>=100 → 'MEGA CACHE' text present
13
+ * (f) every line visibleWidth <= the terminal width passed in
14
+ *
15
+ * Uses MEGACOMPACT_STATE_DIR + mkdtemp (G7). No pi runtime.
16
+ */
17
+ import { describe, it, before, after } from "node:test";
18
+ import assert from "node:assert/strict";
19
+ import { tmpdir } from "node:os";
20
+ import { join } from "node:path";
21
+ import { mkdtempSync, rmSync } from "node:fs";
22
+ import { visibleWidth } from "@earendil-works/pi-tui";
23
+ import { buildWidgetLines, type WidgetData } from "./widget.js";
24
+ import { THEME_IDS, DEFAULT_THEME, getTheme } from "../../src/config/themes.js";
25
+
26
+ /** A minimal but complete WidgetData (all required fields populated). The S31
27
+ * game-mode fields are overridden per-case. */
28
+ function baseWd(overrides: Partial<WidgetData> = {}): WidgetData {
29
+ return {
30
+ version: "0.0.0-test",
31
+ tierLabel: "low",
32
+ triggerLabel: "idle",
33
+ pctStr: "42%",
34
+ tokStr: "10k",
35
+ maxStr: "200k",
36
+ ctxPct: 0.42,
37
+ chk: 3,
38
+ agentStr: "",
39
+ turnStr: "",
40
+ dedupStr: "12%",
41
+ sessIn: 1000,
42
+ sessKept: 800,
43
+ sTxt: "20",
44
+ repoIn: 5000,
45
+ repoKept: 4000,
46
+ rTxt: "20",
47
+ repoChk: 9,
48
+ repoSess: 2,
49
+ modelStr: "test-model",
50
+ sinceCompact: null,
51
+ embedderName: "Trigram",
52
+ compStr: "1.2x",
53
+ driftStatus: "ok",
54
+ agentsActive: false,
55
+ fresh: false,
56
+ ticker: [],
57
+ lastWhy: undefined,
58
+ tierTrace: undefined,
59
+ pulsing: false,
60
+ ...overrides,
61
+ };
62
+ }
63
+
64
+ const WIDTH = 120;
65
+
66
+ function contentLines(lines: string[]): string[] {
67
+ // Strip the top + bottom panel bars; what's left is the content body.
68
+ return lines.slice(1, lines.length - 1);
69
+ }
70
+
71
+ describe("buildWidgetLines (S31)", () => {
72
+ let dir: string;
73
+ before(() => {
74
+ dir = mkdtempSync(join(tmpdir(), "mc-widget-"));
75
+ process.env.MEGACOMPACT_STATE_DIR = dir;
76
+ });
77
+ after(() => {
78
+ delete process.env.MEGACOMPACT_STATE_DIR;
79
+ rmSync(dir, { recursive: true, force: true });
80
+ });
81
+
82
+ it("null wd → warm-up panel (3 lines, all width-safe)", () => {
83
+ const lines = buildWidgetLines(null, WIDTH, 0);
84
+ assert.equal(lines.length, 3);
85
+ for (const l of lines) assert.ok(visibleWidth(l) <= WIDTH, "width safe");
86
+ });
87
+
88
+ for (const theme of THEME_IDS) {
89
+ for (const tuiMode of ["full", "minimal"] as const) {
90
+ for (const gameMode of [false, true] as const) {
91
+ for (const cachePct of [42, 150] as const) {
92
+ const flare = cachePct >= 100;
93
+ const label = `theme=${theme} tui=${tuiMode} game=${gameMode} cache=${cachePct}`;
94
+ it(label, () => {
95
+ const wd = baseWd({
96
+ theme,
97
+ tuiMode,
98
+ gameMode,
99
+ level: 1,
100
+ cachePct,
101
+ megaCacheFlare: flare,
102
+ });
103
+ const lines = buildWidgetLines(wd, WIDTH, 0);
104
+ const body = contentLines(lines);
105
+ const joined = lines.join("\n");
106
+
107
+ // (f) every line width <= terminal (truncateToWidth respected)
108
+ for (const l of lines) {
109
+ assert.ok(
110
+ visibleWidth(l) <= WIDTH,
111
+ `width safe: ${visibleWidth(l)} > ${WIDTH}`,
112
+ );
113
+ }
114
+
115
+ // (a) transparent theme → no '\x1b[48;' bg fill anywhere
116
+ if (theme === DEFAULT_THEME) {
117
+ assert.ok(
118
+ !joined.includes("\x1b[48;"),
119
+ `transparent has no 48; bg fill: ${label}`,
120
+ );
121
+ } else {
122
+ // (b) non-transparent themes → their bg SGR appears on some line.
123
+ // (Themes may use 3-bit bg like \x1b[40m, not just 48;5; form.)
124
+ const bgParams = getTheme(theme)!.ansi.bg!;
125
+ const bgEsc = `\x1b[${bgParams}m`;
126
+ assert.ok(
127
+ joined.includes(bgEsc),
128
+ `themed has bg fill ${bgEsc}: ${label}`,
129
+ );
130
+ }
131
+
132
+ // (c) minimal mode → exactly one content line
133
+ if (tuiMode === "minimal") {
134
+ assert.equal(body.length, 1, `minimal one line: ${label}`);
135
+ }
136
+
137
+ // (d) gameMode off → no LVL + no MEGA CACHE
138
+ if (!gameMode) {
139
+ assert.ok(!joined.includes("LVL"), `no LVL when off: ${label}`);
140
+ assert.ok(
141
+ !joined.includes("MEGA CACHE"),
142
+ `no MEGA CACHE when off: ${label}`,
143
+ );
144
+ } else {
145
+ // gameMode on → LVL shown (in full mode header, or minimal line)
146
+ assert.ok(joined.includes("LVL"), `LVL shown when on: ${label}`);
147
+ }
148
+
149
+ // (e) MEGA CACHE flare text appears only when flare + gameMode on
150
+ const expectMega = flare && gameMode;
151
+ const hasMega = joined.includes("MEGA CACHE");
152
+ assert.equal(
153
+ hasMega,
154
+ expectMega,
155
+ `MEGA CACHE flare: ${label} (got ${hasMega}, want ${expectMega})`,
156
+ );
157
+ });
158
+ }
159
+ }
160
+ }
161
+ }
162
+ });
163
+
164
+
165
+ describe("buildWidgetLines achievement flare (S35)", () => {
166
+ const achBase = (overrides: Partial<WidgetData> = {}): WidgetData => baseWd({
167
+ theme: DEFAULT_THEME, tuiMode: "full", gameMode: true, level: 1, cachePct: 42, ...overrides,
168
+ });
169
+ it("achievementFlare + titles -> renders the unlock toast line", () => {
170
+ const lines = buildWidgetLines(achBase({ achievementFlare: true, achievementFlareTitles: ["First Compact"] }), WIDTH, 0);
171
+ assert.ok(lines.some((l) => l.includes("Achievement unlocked: First Compact")), "toast line present");
172
+ });
173
+ it("achievementFlare off -> no toast line", () => {
174
+ const lines = buildWidgetLines(achBase({ achievementFlare: false, achievementFlareTitles: ["First Compact"] }), WIDTH, 0);
175
+ assert.ok(!lines.some((l) => l.includes("Achievement unlocked")), "no toast when flare off");
176
+ });
177
+ it("gameMode off -> no toast even if flare set", () => {
178
+ const lines = buildWidgetLines(achBase({ gameMode: false, achievementFlare: true, achievementFlareTitles: ["X"] }), WIDTH, 0);
179
+ assert.ok(!lines.some((l) => l.includes("Achievement unlocked")), "no toast when game off");
180
+ });
181
+ it("achievement toast is width-safe", () => {
182
+ const lines = buildWidgetLines(achBase({ achievementFlare: true, achievementFlareTitles: ["First Compact", "Turn Veteran"] }), 60, 0);
183
+ for (const l of lines) assert.ok(visibleWidth(l) <= 60, "width safe");
184
+ });
185
+ });
@@ -14,6 +14,7 @@
14
14
  // off-by-one can trip the strict `> width` guard. (Fix for the
15
15
  // `Rendered line N exceeds terminal width (W > W-1)` crash.)
16
16
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
17
+ import { getTheme, DEFAULT_THEME } from "../../src/config/themes.js";
17
18
 
18
19
  // ── ANSI palette ───────────────────────────────────────────────────────────
19
20
  // The pi TUI's Text component preserves ANSI escape codes (see wrapTextWithAnsi),
@@ -43,16 +44,47 @@ const PULSE = ["◐", "◓", "◑", "◒"];
43
44
  // real terminal width with a background fill. NOTE: C.reset is a FULL SGR
44
45
  // reset, so we re-apply the panel bg after every reset to keep the background
45
46
  // continuous under colored text (and under pi's own trailing reset).
46
- const PANEL_BG = "\x1b[48;5;236m"; // dark slate panel background
47
- const PANEL_RST = "\x1b[0m" + PANEL_BG; // reset fg but retain panel bg
47
+ /** Default panel background (dark slate). Used when no theme is threaded or
48
+ * the theme is transparent (no bg fill). Parametrized per-render via the
49
+ * `panelTheme` arg so game-mode themes can restyle the panel background.
50
+ * A transparent theme yields `""` so panelLine/panelBar still call
51
+ * truncateToWidth (the width guard holds — empty prefix adds zero cells). */
52
+ const DEFAULT_PANEL_BG = "\x1b[48;5;236m"; // dark slate panel background
53
+
54
+ /** Resolve the panel-background SGR prefix for a theme id. Transparent themes
55
+ * (bg=null) and unknown themes yield `""` (no bg fill) — the width guard in
56
+ * panelLine/panelBar still applies via truncateToWidth. */
57
+ function panelBgFor(theme: string | undefined): string {
58
+ if (!theme || theme === DEFAULT_THEME) return "";
59
+ const t = getTheme(theme);
60
+ const bg = t?.ansi.bg;
61
+ return bg ? `\x1b[${bg}m` : "";
62
+ }
63
+
64
+ /** Resolve a theme ANSI accent/mega/fg SGR prefix (`\x1b[<params>m`) for the
65
+ * given role. Falls back to `""` (no SGR) for transparent/unknown themes so
66
+ * game-mode text still renders in the default fg without color noise. */
67
+ function themeAnsi(theme: string | undefined, role: "fg" | "accent" | "mega"): string {
68
+ const t = theme ? getTheme(theme) : undefined;
69
+ const params = t?.ansi[role];
70
+ return params ? `\x1b[${params}m` : "";
71
+ }
72
+
73
+ /** Emit a full SGR reset, OR `""` if `sgr` is empty (transparent theme). Keeps
74
+ * the panel bg continuous by NOT clobbering it with a bare reset when the
75
+ * accent/mega prefix was a no-op. */
76
+ function sgrReset(sgr: string): string {
77
+ return sgr ? "\x1b[0m" : "";
78
+ }
48
79
 
49
80
  // (Visible-width measurement is delegated to pi-tui's `visibleWidth` — imported
50
81
  // above — so our width math can never diverge from pi-tui's render-width check.)
51
82
 
52
83
  /** Wrap a string (with ANSI codes) to fit within `maxWidth` visible chars.
53
84
  * Splits at │ separators or whitespace when possible. */
54
- function wrapLine(text: string, maxWidth: number): string[] {
85
+ function wrapLine(text: string, maxWidth: number, panelBg: string): string[] {
55
86
  if (maxWidth <= 0) return [text];
87
+ const panelRst = "\x1b[0m" + panelBg;
56
88
  const result: string[] = [];
57
89
  let current = "";
58
90
  let currentW = 0;
@@ -60,7 +92,7 @@ function wrapLine(text: string, maxWidth: number): string[] {
60
92
  const segments = text.split("│");
61
93
  for (let i = 0; i < segments.length; i++) {
62
94
  const seg = (i > 0 ? "│" : "") + segments[i];
63
- const segW = visibleWidth(PANEL_BG + seg.replace(/\x1b\[0m/g, PANEL_RST));
95
+ const segW = visibleWidth(panelBg + seg.replace(/\x1b\[0m/g, panelRst));
64
96
  if (currentW + segW <= maxWidth || currentW === 0) {
65
97
  current += seg;
66
98
  currentW += segW;
@@ -74,11 +106,12 @@ function wrapLine(text: string, maxWidth: number): string[] {
74
106
  return result;
75
107
  }
76
108
 
77
- function panelLine(content: string, width: number): string {
109
+ function panelLine(content: string, width: number, panelBg: string = DEFAULT_PANEL_BG): string {
78
110
  if (width <= 0) return "";
111
+ const panelRst = "\x1b[0m" + panelBg;
79
112
  // Apply the panel background; swap every inner full-reset for a reset that
80
113
  // re-applies the bg so the fill stays continuous under colored text.
81
- const withBg = PANEL_BG + content.replace(/\x1b\[0m/g, PANEL_RST);
114
+ const withBg = panelBg + content.replace(/\x1b\[0m/g, panelRst);
82
115
  // truncateToWidth(line, width, "", true) returns EXACTLY `width` visible cells
83
116
  // (by pi-tui's measure), ANSI-preserved, space-padded. It hard-clips overflow
84
117
  // — so even a segment wider than `width` (or a width-rule mismatch) can never
@@ -87,12 +120,12 @@ function panelLine(content: string, width: number): string {
87
120
  }
88
121
 
89
122
  /** A full-width hairline bar (top/bottom border of the panel). */
90
- function panelBar(width: number, ch = "─"): string {
123
+ function panelBar(width: number, ch = "─", panelBg: string = DEFAULT_PANEL_BG): string {
91
124
  // `─` (U+2500) is narrow (1 cell) in both our measure and pi-tui's, so a
92
125
  // `ch.repeat(width)` bar is exactly `width` cells and already passes the
93
126
  // `> width` guard. truncateToWidth is belt-and-suspenders in case `ch` is
94
127
  // ever swapped for a wide/fullwidth character.
95
- return truncateToWidth(PANEL_BG + ch.repeat(Math.max(0, width)), width, "", false) + "\x1b[0m";
128
+ return truncateToWidth(panelBg + ch.repeat(Math.max(0, width)), width, "", false) + "\x1b[0m";
96
129
  }
97
130
 
98
131
  /** Token-count formatter: M at/above 1e6, k at/above 1e3, raw below.
@@ -177,6 +210,27 @@ export interface WidgetData {
177
210
  lastWhy: string | undefined;
178
211
  tierTrace: string | undefined;
179
212
  pulsing: boolean;
213
+ // ── S31: game-mode theming + display modes + level + MEGA CACHE flare ──
214
+ /** Game mode on (shows level + MEGA CACHE flare; hides them when off). */
215
+ gameMode?: boolean;
216
+ /** Theme id (src/config/themes). Drives the panel bg + accent/mega ANSI. */
217
+ theme?: string;
218
+ /** TUI display mode: 'full' (default) = the full stats panel; 'minimal' = a
219
+ * one-line `LVL n | cache NN%` view flanked by panel bars. */
220
+ tuiMode?: "full" | "minimal";
221
+ /** Player level (game-mode). Stub = 1 until S33 wires the real scoring. */
222
+ level?: number;
223
+ /** Cache hit rate as a percent (0..100+, may exceed 100 → MEGA CACHE). */
224
+ cachePct?: number;
225
+ /** MEGA CACHE flare armed (fires at cachePct >= 100 + gameMode on). Adds the
226
+ * ANSI MEGA CACHE banner + the oopsie gag to the header. */
227
+ megaCacheFlare?: boolean;
228
+ /** The peak cache % that armed the flare (for the oopsie toast text). */
229
+ megaCacheFlarePct?: number;
230
+ levelUpFlare?: boolean;
231
+ /** S35: achievement-unlock flare -- renders a one-line toast for one cycle. */
232
+ achievementFlare?: boolean;
233
+ achievementFlareTitles?: string[];
180
234
  }
181
235
 
182
236
  // ── buildWidgetLines ───────────────────────────────────────────────────────
@@ -191,20 +245,59 @@ export function buildWidgetLines(
191
245
  width: number,
192
246
  activeAgents: number,
193
247
  ): string[] {
248
+ // Resolve the panel background from the threaded theme (transparent → "",
249
+ // unknown → default dark slate). Computed once per render; threaded into
250
+ // every panelLine/panelBar/wrapLine so the bg stays continuous and the width
251
+ // guard (truncateToWidth) still holds for transparent themes.
252
+ const panelBg = wd?.theme ? panelBgFor(wd.theme) : DEFAULT_PANEL_BG;
194
253
  if (!wd) {
195
254
  return [
196
- panelBar(width, "─"),
197
- panelLine(" mega-compact: warming up…", width),
198
- panelBar(width, "─"),
255
+ panelBar(width, "─", panelBg),
256
+ panelLine(" mega-compact: warming up…", width, panelBg),
257
+ panelBar(width, "─", panelBg),
258
+ ];
259
+ }
260
+ // S31: minimal TUI mode — a single content line `LVL n | cache NN%` flanked
261
+ // by panel bars. Built through the same panelLine/panelBar helpers so the
262
+ // width guard + theme bg apply identically to the full panel. Level is shown
263
+ // only when game mode is on (otherwise just the cache %).
264
+ if (wd.tuiMode === "minimal") {
265
+ const lvl = wd.gameMode ? wd.level ?? 1 : undefined;
266
+ const cachePct = wd.cachePct ?? 0;
267
+ const cacheStr = `${Math.round(cachePct * 10) / 10}%`;
268
+ const accent = themeAnsi(wd.theme, "accent");
269
+ const mega = themeAnsi(wd.theme, "mega");
270
+ const megaFlare =
271
+ wd.gameMode && wd.megaCacheFlare && cachePct >= 100
272
+ ? ` ${mega}MEGA CACHE${sgrReset(mega)}`
273
+ : "";
274
+ const body =
275
+ lvl != null
276
+ ? `${accent}${wd.gameMode && wd.levelUpFlare ? "\x1b[5m" : ""}LVL ${lvl}${wd.gameMode && wd.levelUpFlare ? "\x1b[0m" : ""}${sgrReset(accent)} ${C.dim}|${C.reset} cache ${cacheStr}${megaFlare}`
277
+ : `cache ${cacheStr}${megaFlare}`;
278
+ return [
279
+ panelBar(width, "─", panelBg),
280
+ panelLine(` ${body}`, width, panelBg),
281
+ panelBar(width, "─", panelBg),
199
282
  ];
200
283
  }
201
284
  const pulse = wd.pulsing
202
285
  ? `${C.cyan}${PULSE[Math.floor(Date.now() / 250) % PULSE.length]}${C.reset} `
203
286
  : "";
204
287
  const sep = ` ${C.dim}│${C.reset} `;
288
+ // S31: game-mode header prefix — `LVL n` (accent) prepended to content[0],
289
+ // and a MEGA CACHE flare (mega ansi) + oopsie gag appended when armed. Both
290
+ // hidden when game mode is off (keeps the legacy panel byte-for-byte).
291
+ const lvlPrefix = wd.gameMode
292
+ ? `${themeAnsi(wd.theme, "accent")}${wd.gameMode && wd.levelUpFlare ? "\x1b[5m" : ""}LVL ${wd.level ?? 1}${wd.gameMode && wd.levelUpFlare ? "\x1b[0m" : ""}${sgrReset(themeAnsi(wd.theme, "accent"))} `
293
+ : "";
294
+ const megaFlareSuffix =
295
+ wd.gameMode && wd.megaCacheFlare && (wd.cachePct ?? 0) >= 100
296
+ ? `${sep}${themeAnsi(wd.theme, "mega")}MEGA CACHE! (oops, you cached so hard the dedup caught fire)${sgrReset(themeAnsi(wd.theme, "mega"))}`
297
+ : "";
205
298
  // Build one long content line — let terminal wrap it naturally
206
299
  const content = [
207
- `${C.amber}⚡ ${wd.tierLabel}${C.reset} v${C.bold}${wd.version}${C.reset} ${ramp(wd.ctxPct, 20)} ${C.bold}${wd.pctStr}${C.reset} ${wd.tokStr}/${wd.maxStr}`,
300
+ `${lvlPrefix}${C.amber}⚡ ${wd.tierLabel}${C.reset} v${C.bold}${wd.version}${C.reset} ${ramp(wd.ctxPct, 20)} ${C.bold}${wd.pctStr}${C.reset} ${wd.tokStr}/${wd.maxStr}${megaFlareSuffix}`,
208
301
  wd.triggerLabel,
209
302
  `${C.cyan}${wd.modelStr}${C.reset}`,
210
303
  `${wd.chk} chk${wd.agentStr}${wd.turnStr}`,
@@ -217,10 +310,10 @@ export function buildWidgetLines(
217
310
  `${C.gray}compact${C.reset} ${sinceCompactStr(wd.sinceCompact)}`,
218
311
  ].join(sep);
219
312
  // Wrap to terminal width and pad each line
220
- const wrapped = wrapLine(content, width - 2); // 2-char indent
313
+ const wrapped = wrapLine(content, width - 2, panelBg); // 2-char indent
221
314
  const lines: string[] = [
222
- panelBar(width, "─"),
223
- ...wrapped.map((l) => panelLine(l, width)),
315
+ panelBar(width, "─", panelBg),
316
+ ...wrapped.map((l) => panelLine(l, width, panelBg)),
224
317
  ];
225
318
  // L4 — agents block (S27, count + status; per-agent tokens gated on P0)
226
319
  if (wd.agentsActive) {
@@ -228,12 +321,13 @@ export function buildWidgetLines(
228
321
  panelLine(
229
322
  ` ${C.cyan}🤖 ${activeAgents} active${wd.turnStr}${C.reset}`,
230
323
  width,
324
+ panelBg,
231
325
  ),
232
326
  );
233
327
  }
234
328
  // L5 — live ticker / activity (♻ deduped … why, or tier trace, or pulsing)
235
329
  if (wd.tierTrace && wd.fresh) {
236
- lines.push(panelLine(` ${pulse}${wd.tierTrace}`, width));
330
+ lines.push(panelLine(` ${pulse}${wd.tierTrace}`, width, panelBg));
237
331
  } else if (wd.ticker.length > 0) {
238
332
  const step = Math.floor(Date.now() / 250);
239
333
  const idx = wd.ticker.length - 1 - (step % wd.ticker.length);
@@ -247,12 +341,19 @@ export function buildWidgetLines(
247
341
  panelLine(
248
342
  ` ${wd.fresh ? C.teal : C.dim}${head}${why}${more}${C.reset}`,
249
343
  width,
344
+ panelBg,
250
345
  ),
251
346
  );
252
347
  } else if (wd.pulsing) {
253
- lines.push(panelLine(` ${pulse}${C.teal}compacting…${C.reset}`, width));
348
+ lines.push(panelLine(` ${pulse}${C.teal}compacting…${C.reset}`, width, panelBg));
349
+ }
350
+ // S35: achievement-unlock toast (one-line, accent) -- fires for one render cycle.
351
+ if (wd.gameMode && wd.achievementFlare && wd.achievementFlareTitles?.length) {
352
+ const accentSgr = themeAnsi(wd.theme, "accent");
353
+ const titlesStr = wd.achievementFlareTitles.join(", ");
354
+ lines.push(panelLine(` ${accentSgr}🏆 Achievement unlocked: ${titlesStr}${sgrReset(accentSgr)}`, width, panelBg));
254
355
  }
255
356
  // bottom border
256
- lines.push(panelBar(width, "─"));
357
+ lines.push(panelBar(width, "─", panelBg));
257
358
  return lines;
258
359
  }