pi-mega-compact 0.7.9 → 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 (79) 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 +161 -1
  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-game-cmds.js +106 -0
  10. package/dist/extensions/mega-game-cmds.test.js +113 -0
  11. package/dist/extensions/mega-runtime/state.js +167 -1
  12. package/dist/extensions/mega-runtime/state.test.js +171 -0
  13. package/dist/extensions/mega-runtime/widget.js +93 -20
  14. package/dist/extensions/mega-runtime/widget.test.js +160 -0
  15. package/dist/src/config/themes.js +84 -0
  16. package/dist/src/config/themes.test.js +94 -0
  17. package/dist/src/game/scoring.js +105 -0
  18. package/dist/src/game/scoring.test.js +98 -0
  19. package/dist/src/store/sqlite/game-achievements.js +111 -0
  20. package/dist/src/store/sqlite/game-achievements.test.js +67 -0
  21. package/dist/src/store/sqlite/game-scores.js +105 -0
  22. package/dist/src/store/sqlite/game-scores.test.js +106 -0
  23. package/dist/src/store/sqlite/game-state.js +54 -0
  24. package/dist/src/store/sqlite/game-state.test.js +76 -0
  25. package/dist/src/store/sqlite/schema.js +44 -0
  26. package/dist/src/store/sqlite.js +3 -0
  27. package/extensions/dashboard-server/html.test.ts +50 -0
  28. package/extensions/dashboard-server/html.ts +334 -66
  29. package/extensions/dashboard-server/server.test.ts +131 -0
  30. package/extensions/dashboard-server/server.ts +148 -1
  31. package/extensions/dashboard-server-s32.test.ts +195 -0
  32. package/extensions/mega-compact.ts +3 -0
  33. package/extensions/mega-events/agent-handlers.ts +48 -0
  34. package/extensions/mega-events/compact-handlers.ts +28 -0
  35. package/extensions/mega-game-cmds.test.ts +137 -0
  36. package/extensions/mega-game-cmds.ts +122 -0
  37. package/extensions/mega-runtime/state.test.ts +171 -0
  38. package/extensions/mega-runtime/state.ts +170 -0
  39. package/extensions/mega-runtime/widget.test.ts +185 -0
  40. package/extensions/mega-runtime/widget.ts +119 -18
  41. package/package.json +1 -1
  42. package/src/config/themes.test.ts +116 -0
  43. package/src/config/themes.ts +124 -0
  44. package/src/game/scoring.test.ts +103 -0
  45. package/src/game/scoring.ts +158 -0
  46. package/src/store/sqlite/game-achievements.test.ts +80 -0
  47. package/src/store/sqlite/game-achievements.ts +147 -0
  48. package/src/store/sqlite/game-scores.test.ts +132 -0
  49. package/src/store/sqlite/game-scores.ts +168 -0
  50. package/src/store/sqlite/game-state.test.ts +89 -0
  51. package/src/store/sqlite/game-state.ts +87 -0
  52. package/src/store/sqlite/schema.ts +47 -0
  53. package/src/store/sqlite.ts +3 -0
  54. package/dist/extensions/dashboard-server/helpers.js +0 -37
  55. package/dist/extensions/dashboard-server/html/all-repos-tab.js +0 -26
  56. package/dist/extensions/dashboard-server/html/body-open.js +0 -23
  57. package/dist/extensions/dashboard-server/html/current-repo-tab.js +0 -130
  58. package/dist/extensions/dashboard-server/html/head-open.js +0 -16
  59. package/dist/extensions/dashboard-server/html/high-score-tab.js +0 -25
  60. package/dist/extensions/dashboard-server/html/repo-detail-modal.js +0 -26
  61. package/dist/extensions/dashboard-server/html/script.js +0 -259
  62. package/dist/extensions/dashboard-server/html/styles.js +0 -103
  63. package/dist/extensions/dashboard-server/html/summary-tab.js +0 -19
  64. package/dist/extensions/dashboard-server/html-template.js +0 -41
  65. package/dist/src/store/sqlite/connection.js +0 -35
  66. package/dist/src/store/sqlite/index-store.js +0 -167
  67. package/dist/src/store/sqlite/memory.js +0 -54
  68. package/dist/src/store/sqlite/minhash-lsh.js +0 -47
  69. package/dist/src/store/sqlite/sessions.js +0 -39
  70. package/dist/src/store/sqlite/transaction.js +0 -19
  71. package/dist/src/vectorStore/add.js +0 -260
  72. package/dist/src/vectorStore/dedup.js +0 -52
  73. package/dist/src/vectorStore/index.js +0 -10
  74. package/dist/src/vectorStore/queries.js +0 -83
  75. package/dist/src/vectorStore/search.js +0 -95
  76. package/dist/src/vectorStore/session.js +0 -19
  77. package/dist/src/vectorStore/store.js +0 -105
  78. package/dist/src/vectorStore/types.js +0 -6
  79. package/dist/src/vectorStore/utils.js +0 -23
@@ -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
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mega-compact",
3
- "version": "0.7.9",
3
+ "version": "0.8.0",
4
4
  "description": "Layered, local, vector-backed context compressor for pi — supersede/collapse/cluster compaction with deduped inline recall.",
5
5
  "type": "module",
6
6
  "license": "BSD-2-Clause",
@@ -0,0 +1,116 @@
1
+ /**
2
+ * themes.test.ts — S30 theme palette source-of-truth tests.
3
+ * Pi-agnostic: no pi runtime imports.
4
+ */
5
+ import { describe, it } from "node:test";
6
+ import assert from "node:assert/strict";
7
+ import {
8
+ THEMES,
9
+ THEME_IDS,
10
+ DEFAULT_THEME,
11
+ getTheme,
12
+ isValidTheme,
13
+ nextTheme,
14
+ themeCssVars,
15
+ themeDataBlock,
16
+ } from "./themes.js";
17
+
18
+ describe("themes (S30)", () => {
19
+ it("defines exactly 6 themes", () => {
20
+ assert.equal(THEMES.length, 6);
21
+ assert.equal(THEME_IDS.length, 6);
22
+ });
23
+
24
+ it("has unique ids", () => {
25
+ assert.equal(new Set(THEME_IDS).size, 6);
26
+ });
27
+
28
+ it("default theme is transparent", () => {
29
+ assert.equal(DEFAULT_THEME, "transparent");
30
+ assert.ok(isValidTheme(DEFAULT_THEME));
31
+ });
32
+
33
+ it("includes retro, orange-bold, cyan-neon, amber-mono, grayscale", () => {
34
+ for (const id of ["retro", "orange-bold", "cyan-neon", "amber-mono", "grayscale"]) {
35
+ assert.ok(isValidTheme(id), `missing ${id}`);
36
+ }
37
+ });
38
+
39
+ it("transparent theme has null bg (CSS + ANSI)", () => {
40
+ const t = getTheme("transparent");
41
+ assert.ok(t);
42
+ assert.equal(t!.css.bg, null);
43
+ assert.equal(t!.ansi.bg, null);
44
+ });
45
+
46
+ it("every non-transparent theme has a non-null bg", () => {
47
+ for (const t of THEMES) {
48
+ if (t.id === "transparent") continue;
49
+ assert.ok(t.css.bg, `${t.id} css.bg`);
50
+ assert.ok(t.ansi.bg, `${t.id} ansi.bg`);
51
+ }
52
+ });
53
+
54
+ it("every theme has css + ansi {fg,accent,mega} strings", () => {
55
+ for (const t of THEMES) {
56
+ assert.ok(typeof t.css.fg === "string" && t.css.fg.startsWith("#"));
57
+ assert.ok(typeof t.css.accent === "string");
58
+ assert.ok(typeof t.css.mega === "string");
59
+ assert.ok(typeof t.ansi.fg === "string");
60
+ assert.ok(typeof t.ansi.accent === "string");
61
+ assert.ok(typeof t.ansi.mega === "string");
62
+ }
63
+ });
64
+
65
+ it("getTheme returns undefined for unknown id", () => {
66
+ assert.equal(getTheme("nope"), undefined);
67
+ });
68
+
69
+ it("isValidTheme is false for unknown", () => {
70
+ assert.equal(isValidTheme("nope"), false);
71
+ });
72
+
73
+ it("nextTheme cycles through all themes and wraps", () => {
74
+ const seen: string[] = [];
75
+ let cur = DEFAULT_THEME;
76
+ for (let i = 0; i < THEME_IDS.length; i++) {
77
+ cur = nextTheme(cur);
78
+ seen.push(cur);
79
+ }
80
+ // after N steps we've visited every theme once
81
+ assert.equal(new Set(seen).size, THEME_IDS.length);
82
+ // wraps: one more step from the last returns to the first
83
+ const first = nextTheme(THEME_IDS[THEME_IDS.length - 1]!);
84
+ assert.equal(first, THEME_IDS[0]);
85
+ });
86
+
87
+ it("nextTheme falls back to DEFAULT_THEME for unknown current", () => {
88
+ assert.equal(nextTheme("garbage"), DEFAULT_THEME);
89
+ });
90
+ });
91
+
92
+ describe("themeCssVars / themeDataBlock (S32)", () => {
93
+ it("themeCssVars emits --bg/--fg/--accent/--mega for a normal theme", () => {
94
+ const t = getTheme("retro")!;
95
+ const vars = themeCssVars(t);
96
+ assert.match(vars, /--bg: #003300;/);
97
+ assert.match(vars, /--fg: #33ff33;/);
98
+ assert.match(vars, /--accent: #00ff41;/);
99
+ assert.match(vars, /--mega: #39ff14;/);
100
+ });
101
+
102
+ it("themeCssVars maps null bg to 'transparent'", () => {
103
+ const t = getTheme("transparent")!;
104
+ const vars = themeCssVars(t);
105
+ assert.match(vars, /--bg: transparent;/);
106
+ assert.match(vars, /--fg: #c9d1d9;/);
107
+ });
108
+
109
+ it("themeDataBlock wraps vars in a :root[data-theme=\"<id\"] selector", () => {
110
+ const t = getTheme("cyan-neon")!;
111
+ const block = themeDataBlock(t);
112
+ assert.equal(block.startsWith(':root[data-theme="cyan-neon"]{ '), true);
113
+ assert.equal(block.endsWith(" }"), true);
114
+ assert.ok(block.includes("--accent: #22d3ee;"));
115
+ });
116
+ });
@@ -0,0 +1,124 @@
1
+ /**
2
+ * themes.ts — SINGLE SOURCE OF TRUTH for game-mode visual-effect themes (S30).
3
+ *
4
+ * Each theme defines BOTH an HTML/CSS palette (dashboard) AND an ANSI accent
5
+ * mapping (TUI widget), since the TUI is ANSI and the dashboard is HTML.
6
+ *
7
+ * Theme scope (QA1 correction): themes restyle the mega-compact statusbar
8
+ * widget + the whole dashboard HTML page. We do NOT theme pi's chrome.
9
+ *
10
+ * `transparent` (default) semantics: no background fill, colored accents only —
11
+ * so game-mode stays visible against any terminal background.
12
+ *
13
+ * PREVENT-PI-004: pure config, no network. Pi-agnostic: no pi runtime types.
14
+ */
15
+
16
+ /** HTML/CSS palette for the dashboard (hex strings, or `null` for "no bg"). */
17
+ export interface ThemeCss {
18
+ /** Page/cell background hex, or `null` for transparent (no bg fill). */
19
+ bg: string | null;
20
+ /** Default foreground (text) hex. */
21
+ fg: string;
22
+ /** Accent hex (bars, highlights, level numbers). */
23
+ accent: string;
24
+ /** MEGA CACHE highlight hex (fires at cache >= 100%). */
25
+ mega: string;
26
+ }
27
+
28
+ /** ANSI accent mapping for the TUI widget (SGR parameter strings, no `\x1b[`).
29
+ * `bg` is `null` for transparent themes (no background fill). */
30
+ export interface ThemeAnsi {
31
+ /** Background SGR params (e.g. "48;5;23"), or `null` for no bg fill. */
32
+ bg: string | null;
33
+ /** Foreground SGR params (e.g. "39" for default, "92" for bright green). */
34
+ fg: string;
35
+ /** Accent SGR params. */
36
+ accent: string;
37
+ /** MEGA CACHE SGR params (fires at cache >= 100%). */
38
+ mega: string;
39
+ }
40
+
41
+ /** A complete theme = CSS palette + ANSI mapping + display metadata. */
42
+ export interface Theme {
43
+ id: string;
44
+ label: string;
45
+ css: ThemeCss;
46
+ ansi: ThemeAnsi;
47
+ }
48
+
49
+ export const DEFAULT_THEME = "transparent";
50
+
51
+ export const THEMES: readonly Theme[] = [
52
+ {
53
+ id: "transparent",
54
+ label: "Transparent (accents only)",
55
+ css: { bg: null, fg: "#c9d1d9", accent: "#3fb950", mega: "#f0883e" },
56
+ ansi: { bg: null, fg: "39", accent: "32", mega: "33" },
57
+ },
58
+ {
59
+ id: "retro",
60
+ label: "Retro 8-bit green",
61
+ css: { bg: "#003300", fg: "#33ff33", accent: "#00ff41", mega: "#39ff14" },
62
+ ansi: { bg: "40", fg: "92", accent: "92", mega: "1;92" },
63
+ },
64
+ {
65
+ id: "orange-bold",
66
+ label: "Orange bold",
67
+ css: { bg: "#1a0f00", fg: "#ff8c00", accent: "#ff6b00", mega: "#ff4500" },
68
+ ansi: { bg: "48;5;52", fg: "38;5;208", accent: "38;5;208", mega: "1;38;5;202" },
69
+ },
70
+ {
71
+ id: "cyan-neon",
72
+ label: "Cyan neon",
73
+ css: { bg: "#001a1a", fg: "#00ffff", accent: "#22d3ee", mega: "#7df9ff" },
74
+ ansi: { bg: "48;5;23", fg: "38;5;51", accent: "38;5;51", mega: "1;38;5;51" },
75
+ },
76
+ {
77
+ id: "amber-mono",
78
+ label: "Amber phosphor",
79
+ css: { bg: "#1a1200", fg: "#ffb000", accent: "#ff8c00", mega: "#ff5500" },
80
+ ansi: { bg: "48;5;58", fg: "38;5;214", accent: "38;5;214", mega: "1;38;5;208" },
81
+ },
82
+ {
83
+ id: "grayscale",
84
+ label: "Grayscale minimal",
85
+ css: { bg: "#161616", fg: "#b0b0b0", accent: "#8b949e", mega: "#e6edf3" },
86
+ ansi: { bg: "48;5;235", fg: "38;5;249", accent: "38;5;249", mega: "1;38;5;255" },
87
+ },
88
+ ] as const;
89
+
90
+ /** All valid theme ids, in definition order (used for `theme next` cycling). */
91
+ export const THEME_IDS: readonly string[] = THEMES.map((t) => t.id);
92
+
93
+ /** Look up a theme by id; returns `undefined` for an unknown id (caller
94
+ * validates + falls back to DEFAULT_THEME). */
95
+ export function getTheme(id: string): Theme | undefined {
96
+ return THEMES.find((t) => t.id === id);
97
+ }
98
+
99
+ /** True if `id` is a known theme id. */
100
+ export function isValidTheme(id: string): boolean {
101
+ return THEME_IDS.includes(id);
102
+ }
103
+
104
+ /** Cycle to the next theme id (wraps at the end). Falls back to DEFAULT_THEME
105
+ * if `current` is unknown (defensive — the stored id should always be valid). */
106
+ export function nextTheme(current: string): string {
107
+ const i = THEME_IDS.indexOf(current);
108
+ if (i < 0) return DEFAULT_THEME;
109
+ return THEME_IDS[(i + 1) % THEME_IDS.length]!;
110
+ }
111
+
112
+ /** CSS variable declarations for a theme's CSS palette. `bg` is `null` for the
113
+ * transparent theme → `--bg: transparent` (no page fill, accents only). Pure,
114
+ * no pi types. */
115
+ export function themeCssVars(theme: Theme): string {
116
+ const bg = theme.css.bg ?? "transparent";
117
+ return `--bg: ${bg}; --fg: ${theme.css.fg}; --accent: ${theme.css.accent}; --mega: ${theme.css.mega};`;
118
+ }
119
+
120
+ /** A `:root[data-theme="<id>"]` override block carrying the theme's CSS vars,
121
+ * for client-side instant theme switching. Pure, no pi types. */
122
+ export function themeDataBlock(theme: Theme): string {
123
+ return `:root[data-theme="${theme.id}"]{ ${themeCssVars(theme)} }`;
124
+ }