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
@@ -13,6 +13,7 @@
13
13
  // off-by-one can trip the strict `> width` guard. (Fix for the
14
14
  // `Rendered line N exceeds terminal width (W > W-1)` crash.)
15
15
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
16
+ import { getTheme, DEFAULT_THEME } from "../../src/config/themes.js";
16
17
  // ── ANSI palette ───────────────────────────────────────────────────────────
17
18
  // The pi TUI's Text component preserves ANSI escape codes (see wrapTextWithAnsi),
18
19
  // so raw escapes render as colors. No chalk dependency needed — these are just
@@ -39,15 +40,44 @@ const PULSE = ["◐", "◓", "◑", "◒"];
39
40
  // real terminal width with a background fill. NOTE: C.reset is a FULL SGR
40
41
  // reset, so we re-apply the panel bg after every reset to keep the background
41
42
  // continuous under colored text (and under pi's own trailing reset).
42
- const PANEL_BG = "\x1b[48;5;236m"; // dark slate panel background
43
- const PANEL_RST = "\x1b[0m" + PANEL_BG; // reset fg but retain panel bg
43
+ /** Default panel background (dark slate). Used when no theme is threaded or
44
+ * the theme is transparent (no bg fill). Parametrized per-render via the
45
+ * `panelTheme` arg so game-mode themes can restyle the panel background.
46
+ * A transparent theme yields `""` so panelLine/panelBar still call
47
+ * truncateToWidth (the width guard holds — empty prefix adds zero cells). */
48
+ const DEFAULT_PANEL_BG = "\x1b[48;5;236m"; // dark slate panel background
49
+ /** Resolve the panel-background SGR prefix for a theme id. Transparent themes
50
+ * (bg=null) and unknown themes yield `""` (no bg fill) — the width guard in
51
+ * panelLine/panelBar still applies via truncateToWidth. */
52
+ function panelBgFor(theme) {
53
+ if (!theme || theme === DEFAULT_THEME)
54
+ return "";
55
+ const t = getTheme(theme);
56
+ const bg = t?.ansi.bg;
57
+ return bg ? `\x1b[${bg}m` : "";
58
+ }
59
+ /** Resolve a theme ANSI accent/mega/fg SGR prefix (`\x1b[<params>m`) for the
60
+ * given role. Falls back to `""` (no SGR) for transparent/unknown themes so
61
+ * game-mode text still renders in the default fg without color noise. */
62
+ function themeAnsi(theme, role) {
63
+ const t = theme ? getTheme(theme) : undefined;
64
+ const params = t?.ansi[role];
65
+ return params ? `\x1b[${params}m` : "";
66
+ }
67
+ /** Emit a full SGR reset, OR `""` if `sgr` is empty (transparent theme). Keeps
68
+ * the panel bg continuous by NOT clobbering it with a bare reset when the
69
+ * accent/mega prefix was a no-op. */
70
+ function sgrReset(sgr) {
71
+ return sgr ? "\x1b[0m" : "";
72
+ }
44
73
  // (Visible-width measurement is delegated to pi-tui's `visibleWidth` — imported
45
74
  // above — so our width math can never diverge from pi-tui's render-width check.)
46
75
  /** Wrap a string (with ANSI codes) to fit within `maxWidth` visible chars.
47
76
  * Splits at │ separators or whitespace when possible. */
48
- function wrapLine(text, maxWidth) {
77
+ function wrapLine(text, maxWidth, panelBg) {
49
78
  if (maxWidth <= 0)
50
79
  return [text];
80
+ const panelRst = "\x1b[0m" + panelBg;
51
81
  const result = [];
52
82
  let current = "";
53
83
  let currentW = 0;
@@ -55,7 +85,7 @@ function wrapLine(text, maxWidth) {
55
85
  const segments = text.split("│");
56
86
  for (let i = 0; i < segments.length; i++) {
57
87
  const seg = (i > 0 ? "│" : "") + segments[i];
58
- const segW = visibleWidth(PANEL_BG + seg.replace(/\x1b\[0m/g, PANEL_RST));
88
+ const segW = visibleWidth(panelBg + seg.replace(/\x1b\[0m/g, panelRst));
59
89
  if (currentW + segW <= maxWidth || currentW === 0) {
60
90
  current += seg;
61
91
  currentW += segW;
@@ -70,12 +100,13 @@ function wrapLine(text, maxWidth) {
70
100
  result.push(current);
71
101
  return result;
72
102
  }
73
- function panelLine(content, width) {
103
+ function panelLine(content, width, panelBg = DEFAULT_PANEL_BG) {
74
104
  if (width <= 0)
75
105
  return "";
106
+ const panelRst = "\x1b[0m" + panelBg;
76
107
  // Apply the panel background; swap every inner full-reset for a reset that
77
108
  // re-applies the bg so the fill stays continuous under colored text.
78
- const withBg = PANEL_BG + content.replace(/\x1b\[0m/g, PANEL_RST);
109
+ const withBg = panelBg + content.replace(/\x1b\[0m/g, panelRst);
79
110
  // truncateToWidth(line, width, "", true) returns EXACTLY `width` visible cells
80
111
  // (by pi-tui's measure), ANSI-preserved, space-padded. It hard-clips overflow
81
112
  // — so even a segment wider than `width` (or a width-rule mismatch) can never
@@ -83,12 +114,12 @@ function panelLine(content, width) {
83
114
  return truncateToWidth(withBg, width, "", true) + "\x1b[0m";
84
115
  }
85
116
  /** A full-width hairline bar (top/bottom border of the panel). */
86
- function panelBar(width, ch = "─") {
117
+ function panelBar(width, ch = "─", panelBg = DEFAULT_PANEL_BG) {
87
118
  // `─` (U+2500) is narrow (1 cell) in both our measure and pi-tui's, so a
88
119
  // `ch.repeat(width)` bar is exactly `width` cells and already passes the
89
120
  // `> width` guard. truncateToWidth is belt-and-suspenders in case `ch` is
90
121
  // ever swapped for a wide/fullwidth character.
91
- return truncateToWidth(PANEL_BG + ch.repeat(Math.max(0, width)), width, "", false) + "\x1b[0m";
122
+ return truncateToWidth(panelBg + ch.repeat(Math.max(0, width)), width, "", false) + "\x1b[0m";
92
123
  }
93
124
  /** Token-count formatter: M at/above 1e6, k at/above 1e3, raw below.
94
125
  * 5,472,700 → "5.5mil", 24,100 → "24.1k", 142 → "142". */
@@ -139,20 +170,56 @@ function sinceCompactStr(ms) {
139
170
  /** Build the full-width panel lines from the latest snapshot. Cheap: reads
140
171
  * only the WidgetData + a couple of live counters; no DB/IO. */
141
172
  export function buildWidgetLines(wd, width, activeAgents) {
173
+ // Resolve the panel background from the threaded theme (transparent → "",
174
+ // unknown → default dark slate). Computed once per render; threaded into
175
+ // every panelLine/panelBar/wrapLine so the bg stays continuous and the width
176
+ // guard (truncateToWidth) still holds for transparent themes.
177
+ const panelBg = wd?.theme ? panelBgFor(wd.theme) : DEFAULT_PANEL_BG;
142
178
  if (!wd) {
143
179
  return [
144
- panelBar(width, "─"),
145
- panelLine(" mega-compact: warming up…", width),
146
- panelBar(width, "─"),
180
+ panelBar(width, "─", panelBg),
181
+ panelLine(" mega-compact: warming up…", width, panelBg),
182
+ panelBar(width, "─", panelBg),
183
+ ];
184
+ }
185
+ // S31: minimal TUI mode — a single content line `LVL n | cache NN%` flanked
186
+ // by panel bars. Built through the same panelLine/panelBar helpers so the
187
+ // width guard + theme bg apply identically to the full panel. Level is shown
188
+ // only when game mode is on (otherwise just the cache %).
189
+ if (wd.tuiMode === "minimal") {
190
+ const lvl = wd.gameMode ? wd.level ?? 1 : undefined;
191
+ const cachePct = wd.cachePct ?? 0;
192
+ const cacheStr = `${Math.round(cachePct * 10) / 10}%`;
193
+ const accent = themeAnsi(wd.theme, "accent");
194
+ const mega = themeAnsi(wd.theme, "mega");
195
+ const megaFlare = wd.gameMode && wd.megaCacheFlare && cachePct >= 100
196
+ ? ` ${mega}MEGA CACHE${sgrReset(mega)}`
197
+ : "";
198
+ const body = lvl != null
199
+ ? `${accent}${wd.gameMode && wd.levelUpFlare ? "\x1b[5m" : ""}LVL ${lvl}${wd.gameMode && wd.levelUpFlare ? "\x1b[0m" : ""}${sgrReset(accent)} ${C.dim}|${C.reset} cache ${cacheStr}${megaFlare}`
200
+ : `cache ${cacheStr}${megaFlare}`;
201
+ return [
202
+ panelBar(width, "─", panelBg),
203
+ panelLine(` ${body}`, width, panelBg),
204
+ panelBar(width, "─", panelBg),
147
205
  ];
148
206
  }
149
207
  const pulse = wd.pulsing
150
208
  ? `${C.cyan}${PULSE[Math.floor(Date.now() / 250) % PULSE.length]}${C.reset} `
151
209
  : "";
152
210
  const sep = ` ${C.dim}│${C.reset} `;
211
+ // S31: game-mode header prefix — `LVL n` (accent) prepended to content[0],
212
+ // and a MEGA CACHE flare (mega ansi) + oopsie gag appended when armed. Both
213
+ // hidden when game mode is off (keeps the legacy panel byte-for-byte).
214
+ const lvlPrefix = wd.gameMode
215
+ ? `${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"))} `
216
+ : "";
217
+ const megaFlareSuffix = wd.gameMode && wd.megaCacheFlare && (wd.cachePct ?? 0) >= 100
218
+ ? `${sep}${themeAnsi(wd.theme, "mega")}MEGA CACHE! (oops, you cached so hard the dedup caught fire)${sgrReset(themeAnsi(wd.theme, "mega"))}`
219
+ : "";
153
220
  // Build one long content line — let terminal wrap it naturally
154
221
  const content = [
155
- `${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}`,
222
+ `${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}`,
156
223
  wd.triggerLabel,
157
224
  `${C.cyan}${wd.modelStr}${C.reset}`,
158
225
  `${wd.chk} chk${wd.agentStr}${wd.turnStr}`,
@@ -165,18 +232,18 @@ export function buildWidgetLines(wd, width, activeAgents) {
165
232
  `${C.gray}compact${C.reset} ${sinceCompactStr(wd.sinceCompact)}`,
166
233
  ].join(sep);
167
234
  // Wrap to terminal width and pad each line
168
- const wrapped = wrapLine(content, width - 2); // 2-char indent
235
+ const wrapped = wrapLine(content, width - 2, panelBg); // 2-char indent
169
236
  const lines = [
170
- panelBar(width, "─"),
171
- ...wrapped.map((l) => panelLine(l, width)),
237
+ panelBar(width, "─", panelBg),
238
+ ...wrapped.map((l) => panelLine(l, width, panelBg)),
172
239
  ];
173
240
  // L4 — agents block (S27, count + status; per-agent tokens gated on P0)
174
241
  if (wd.agentsActive) {
175
- lines.push(panelLine(` ${C.cyan}🤖 ${activeAgents} active${wd.turnStr}${C.reset}`, width));
242
+ lines.push(panelLine(` ${C.cyan}🤖 ${activeAgents} active${wd.turnStr}${C.reset}`, width, panelBg));
176
243
  }
177
244
  // L5 — live ticker / activity (♻ deduped … why, or tier trace, or pulsing)
178
245
  if (wd.tierTrace && wd.fresh) {
179
- lines.push(panelLine(` ${pulse}${wd.tierTrace}`, width));
246
+ lines.push(panelLine(` ${pulse}${wd.tierTrace}`, width, panelBg));
180
247
  }
181
248
  else if (wd.ticker.length > 0) {
182
249
  const step = Math.floor(Date.now() / 250);
@@ -186,12 +253,18 @@ export function buildWidgetLines(wd, width, activeAgents) {
186
253
  const more = wd.ticker.length > 1
187
254
  ? ` ${C.dim}(+${wd.ticker.length - 1} more)${C.reset}`
188
255
  : "";
189
- lines.push(panelLine(` ${wd.fresh ? C.teal : C.dim}${head}${why}${more}${C.reset}`, width));
256
+ lines.push(panelLine(` ${wd.fresh ? C.teal : C.dim}${head}${why}${more}${C.reset}`, width, panelBg));
190
257
  }
191
258
  else if (wd.pulsing) {
192
- lines.push(panelLine(` ${pulse}${C.teal}compacting…${C.reset}`, width));
259
+ lines.push(panelLine(` ${pulse}${C.teal}compacting…${C.reset}`, width, panelBg));
260
+ }
261
+ // S35: achievement-unlock toast (one-line, accent) -- fires for one render cycle.
262
+ if (wd.gameMode && wd.achievementFlare && wd.achievementFlareTitles?.length) {
263
+ const accentSgr = themeAnsi(wd.theme, "accent");
264
+ const titlesStr = wd.achievementFlareTitles.join(", ");
265
+ lines.push(panelLine(` ${accentSgr}🏆 Achievement unlocked: ${titlesStr}${sgrReset(accentSgr)}`, width, panelBg));
193
266
  }
194
267
  // bottom border
195
- lines.push(panelBar(width, "─"));
268
+ lines.push(panelBar(width, "─", panelBg));
196
269
  return lines;
197
270
  }
@@ -0,0 +1,160 @@
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 } from "./widget.js";
24
+ import { THEME_IDS, DEFAULT_THEME, getTheme } from "../../src/config/themes.js";
25
+ /** A minimal but complete WidgetData (all required fields populated). The S31
26
+ * game-mode fields are overridden per-case. */
27
+ function baseWd(overrides = {}) {
28
+ return {
29
+ version: "0.0.0-test",
30
+ tierLabel: "low",
31
+ triggerLabel: "idle",
32
+ pctStr: "42%",
33
+ tokStr: "10k",
34
+ maxStr: "200k",
35
+ ctxPct: 0.42,
36
+ chk: 3,
37
+ agentStr: "",
38
+ turnStr: "",
39
+ dedupStr: "12%",
40
+ sessIn: 1000,
41
+ sessKept: 800,
42
+ sTxt: "20",
43
+ repoIn: 5000,
44
+ repoKept: 4000,
45
+ rTxt: "20",
46
+ repoChk: 9,
47
+ repoSess: 2,
48
+ modelStr: "test-model",
49
+ sinceCompact: null,
50
+ embedderName: "Trigram",
51
+ compStr: "1.2x",
52
+ driftStatus: "ok",
53
+ agentsActive: false,
54
+ fresh: false,
55
+ ticker: [],
56
+ lastWhy: undefined,
57
+ tierTrace: undefined,
58
+ pulsing: false,
59
+ ...overrides,
60
+ };
61
+ }
62
+ const WIDTH = 120;
63
+ function contentLines(lines) {
64
+ // Strip the top + bottom panel bars; what's left is the content body.
65
+ return lines.slice(1, lines.length - 1);
66
+ }
67
+ describe("buildWidgetLines (S31)", () => {
68
+ let dir;
69
+ before(() => {
70
+ dir = mkdtempSync(join(tmpdir(), "mc-widget-"));
71
+ process.env.MEGACOMPACT_STATE_DIR = dir;
72
+ });
73
+ after(() => {
74
+ delete process.env.MEGACOMPACT_STATE_DIR;
75
+ rmSync(dir, { recursive: true, force: true });
76
+ });
77
+ it("null wd → warm-up panel (3 lines, all width-safe)", () => {
78
+ const lines = buildWidgetLines(null, WIDTH, 0);
79
+ assert.equal(lines.length, 3);
80
+ for (const l of lines)
81
+ assert.ok(visibleWidth(l) <= WIDTH, "width safe");
82
+ });
83
+ for (const theme of THEME_IDS) {
84
+ for (const tuiMode of ["full", "minimal"]) {
85
+ for (const gameMode of [false, true]) {
86
+ for (const cachePct of [42, 150]) {
87
+ const flare = cachePct >= 100;
88
+ const label = `theme=${theme} tui=${tuiMode} game=${gameMode} cache=${cachePct}`;
89
+ it(label, () => {
90
+ const wd = baseWd({
91
+ theme,
92
+ tuiMode,
93
+ gameMode,
94
+ level: 1,
95
+ cachePct,
96
+ megaCacheFlare: flare,
97
+ });
98
+ const lines = buildWidgetLines(wd, WIDTH, 0);
99
+ const body = contentLines(lines);
100
+ const joined = lines.join("\n");
101
+ // (f) every line width <= terminal (truncateToWidth respected)
102
+ for (const l of lines) {
103
+ assert.ok(visibleWidth(l) <= WIDTH, `width safe: ${visibleWidth(l)} > ${WIDTH}`);
104
+ }
105
+ // (a) transparent theme → no '\x1b[48;' bg fill anywhere
106
+ if (theme === DEFAULT_THEME) {
107
+ assert.ok(!joined.includes("\x1b[48;"), `transparent has no 48; bg fill: ${label}`);
108
+ }
109
+ else {
110
+ // (b) non-transparent themes → their bg SGR appears on some line.
111
+ // (Themes may use 3-bit bg like \x1b[40m, not just 48;5; form.)
112
+ const bgParams = getTheme(theme).ansi.bg;
113
+ const bgEsc = `\x1b[${bgParams}m`;
114
+ assert.ok(joined.includes(bgEsc), `themed has bg fill ${bgEsc}: ${label}`);
115
+ }
116
+ // (c) minimal mode → exactly one content line
117
+ if (tuiMode === "minimal") {
118
+ assert.equal(body.length, 1, `minimal one line: ${label}`);
119
+ }
120
+ // (d) gameMode off → no LVL + no MEGA CACHE
121
+ if (!gameMode) {
122
+ assert.ok(!joined.includes("LVL"), `no LVL when off: ${label}`);
123
+ assert.ok(!joined.includes("MEGA CACHE"), `no MEGA CACHE when off: ${label}`);
124
+ }
125
+ else {
126
+ // gameMode on → LVL shown (in full mode header, or minimal line)
127
+ assert.ok(joined.includes("LVL"), `LVL shown when on: ${label}`);
128
+ }
129
+ // (e) MEGA CACHE flare text appears only when flare + gameMode on
130
+ const expectMega = flare && gameMode;
131
+ const hasMega = joined.includes("MEGA CACHE");
132
+ assert.equal(hasMega, expectMega, `MEGA CACHE flare: ${label} (got ${hasMega}, want ${expectMega})`);
133
+ });
134
+ }
135
+ }
136
+ }
137
+ }
138
+ });
139
+ describe("buildWidgetLines achievement flare (S35)", () => {
140
+ const achBase = (overrides = {}) => baseWd({
141
+ theme: DEFAULT_THEME, tuiMode: "full", gameMode: true, level: 1, cachePct: 42, ...overrides,
142
+ });
143
+ it("achievementFlare + titles -> renders the unlock toast line", () => {
144
+ const lines = buildWidgetLines(achBase({ achievementFlare: true, achievementFlareTitles: ["First Compact"] }), WIDTH, 0);
145
+ assert.ok(lines.some((l) => l.includes("Achievement unlocked: First Compact")), "toast line present");
146
+ });
147
+ it("achievementFlare off -> no toast line", () => {
148
+ const lines = buildWidgetLines(achBase({ achievementFlare: false, achievementFlareTitles: ["First Compact"] }), WIDTH, 0);
149
+ assert.ok(!lines.some((l) => l.includes("Achievement unlocked")), "no toast when flare off");
150
+ });
151
+ it("gameMode off -> no toast even if flare set", () => {
152
+ const lines = buildWidgetLines(achBase({ gameMode: false, achievementFlare: true, achievementFlareTitles: ["X"] }), WIDTH, 0);
153
+ assert.ok(!lines.some((l) => l.includes("Achievement unlocked")), "no toast when game off");
154
+ });
155
+ it("achievement toast is width-safe", () => {
156
+ const lines = buildWidgetLines(achBase({ achievementFlare: true, achievementFlareTitles: ["First Compact", "Turn Veteran"] }), 60, 0);
157
+ for (const l of lines)
158
+ assert.ok(visibleWidth(l) <= 60, "width safe");
159
+ });
160
+ });
@@ -0,0 +1,84 @@
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
+ export const DEFAULT_THEME = "transparent";
16
+ export const THEMES = [
17
+ {
18
+ id: "transparent",
19
+ label: "Transparent (accents only)",
20
+ css: { bg: null, fg: "#c9d1d9", accent: "#3fb950", mega: "#f0883e" },
21
+ ansi: { bg: null, fg: "39", accent: "32", mega: "33" },
22
+ },
23
+ {
24
+ id: "retro",
25
+ label: "Retro 8-bit green",
26
+ css: { bg: "#003300", fg: "#33ff33", accent: "#00ff41", mega: "#39ff14" },
27
+ ansi: { bg: "40", fg: "92", accent: "92", mega: "1;92" },
28
+ },
29
+ {
30
+ id: "orange-bold",
31
+ label: "Orange bold",
32
+ css: { bg: "#1a0f00", fg: "#ff8c00", accent: "#ff6b00", mega: "#ff4500" },
33
+ ansi: { bg: "48;5;52", fg: "38;5;208", accent: "38;5;208", mega: "1;38;5;202" },
34
+ },
35
+ {
36
+ id: "cyan-neon",
37
+ label: "Cyan neon",
38
+ css: { bg: "#001a1a", fg: "#00ffff", accent: "#22d3ee", mega: "#7df9ff" },
39
+ ansi: { bg: "48;5;23", fg: "38;5;51", accent: "38;5;51", mega: "1;38;5;51" },
40
+ },
41
+ {
42
+ id: "amber-mono",
43
+ label: "Amber phosphor",
44
+ css: { bg: "#1a1200", fg: "#ffb000", accent: "#ff8c00", mega: "#ff5500" },
45
+ ansi: { bg: "48;5;58", fg: "38;5;214", accent: "38;5;214", mega: "1;38;5;208" },
46
+ },
47
+ {
48
+ id: "grayscale",
49
+ label: "Grayscale minimal",
50
+ css: { bg: "#161616", fg: "#b0b0b0", accent: "#8b949e", mega: "#e6edf3" },
51
+ ansi: { bg: "48;5;235", fg: "38;5;249", accent: "38;5;249", mega: "1;38;5;255" },
52
+ },
53
+ ];
54
+ /** All valid theme ids, in definition order (used for `theme next` cycling). */
55
+ export const THEME_IDS = THEMES.map((t) => t.id);
56
+ /** Look up a theme by id; returns `undefined` for an unknown id (caller
57
+ * validates + falls back to DEFAULT_THEME). */
58
+ export function getTheme(id) {
59
+ return THEMES.find((t) => t.id === id);
60
+ }
61
+ /** True if `id` is a known theme id. */
62
+ export function isValidTheme(id) {
63
+ return THEME_IDS.includes(id);
64
+ }
65
+ /** Cycle to the next theme id (wraps at the end). Falls back to DEFAULT_THEME
66
+ * if `current` is unknown (defensive — the stored id should always be valid). */
67
+ export function nextTheme(current) {
68
+ const i = THEME_IDS.indexOf(current);
69
+ if (i < 0)
70
+ return DEFAULT_THEME;
71
+ return THEME_IDS[(i + 1) % THEME_IDS.length];
72
+ }
73
+ /** CSS variable declarations for a theme's CSS palette. `bg` is `null` for the
74
+ * transparent theme → `--bg: transparent` (no page fill, accents only). Pure,
75
+ * no pi types. */
76
+ export function themeCssVars(theme) {
77
+ const bg = theme.css.bg ?? "transparent";
78
+ return `--bg: ${bg}; --fg: ${theme.css.fg}; --accent: ${theme.css.accent}; --mega: ${theme.css.mega};`;
79
+ }
80
+ /** A `:root[data-theme="<id>"]` override block carrying the theme's CSS vars,
81
+ * for client-side instant theme switching. Pure, no pi types. */
82
+ export function themeDataBlock(theme) {
83
+ return `:root[data-theme="${theme.id}"]{ ${themeCssVars(theme)} }`;
84
+ }
@@ -0,0 +1,94 @@
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 { THEMES, THEME_IDS, DEFAULT_THEME, getTheme, isValidTheme, nextTheme, themeCssVars, themeDataBlock, } from "./themes.js";
8
+ describe("themes (S30)", () => {
9
+ it("defines exactly 6 themes", () => {
10
+ assert.equal(THEMES.length, 6);
11
+ assert.equal(THEME_IDS.length, 6);
12
+ });
13
+ it("has unique ids", () => {
14
+ assert.equal(new Set(THEME_IDS).size, 6);
15
+ });
16
+ it("default theme is transparent", () => {
17
+ assert.equal(DEFAULT_THEME, "transparent");
18
+ assert.ok(isValidTheme(DEFAULT_THEME));
19
+ });
20
+ it("includes retro, orange-bold, cyan-neon, amber-mono, grayscale", () => {
21
+ for (const id of ["retro", "orange-bold", "cyan-neon", "amber-mono", "grayscale"]) {
22
+ assert.ok(isValidTheme(id), `missing ${id}`);
23
+ }
24
+ });
25
+ it("transparent theme has null bg (CSS + ANSI)", () => {
26
+ const t = getTheme("transparent");
27
+ assert.ok(t);
28
+ assert.equal(t.css.bg, null);
29
+ assert.equal(t.ansi.bg, null);
30
+ });
31
+ it("every non-transparent theme has a non-null bg", () => {
32
+ for (const t of THEMES) {
33
+ if (t.id === "transparent")
34
+ continue;
35
+ assert.ok(t.css.bg, `${t.id} css.bg`);
36
+ assert.ok(t.ansi.bg, `${t.id} ansi.bg`);
37
+ }
38
+ });
39
+ it("every theme has css + ansi {fg,accent,mega} strings", () => {
40
+ for (const t of THEMES) {
41
+ assert.ok(typeof t.css.fg === "string" && t.css.fg.startsWith("#"));
42
+ assert.ok(typeof t.css.accent === "string");
43
+ assert.ok(typeof t.css.mega === "string");
44
+ assert.ok(typeof t.ansi.fg === "string");
45
+ assert.ok(typeof t.ansi.accent === "string");
46
+ assert.ok(typeof t.ansi.mega === "string");
47
+ }
48
+ });
49
+ it("getTheme returns undefined for unknown id", () => {
50
+ assert.equal(getTheme("nope"), undefined);
51
+ });
52
+ it("isValidTheme is false for unknown", () => {
53
+ assert.equal(isValidTheme("nope"), false);
54
+ });
55
+ it("nextTheme cycles through all themes and wraps", () => {
56
+ const seen = [];
57
+ let cur = DEFAULT_THEME;
58
+ for (let i = 0; i < THEME_IDS.length; i++) {
59
+ cur = nextTheme(cur);
60
+ seen.push(cur);
61
+ }
62
+ // after N steps we've visited every theme once
63
+ assert.equal(new Set(seen).size, THEME_IDS.length);
64
+ // wraps: one more step from the last returns to the first
65
+ const first = nextTheme(THEME_IDS[THEME_IDS.length - 1]);
66
+ assert.equal(first, THEME_IDS[0]);
67
+ });
68
+ it("nextTheme falls back to DEFAULT_THEME for unknown current", () => {
69
+ assert.equal(nextTheme("garbage"), DEFAULT_THEME);
70
+ });
71
+ });
72
+ describe("themeCssVars / themeDataBlock (S32)", () => {
73
+ it("themeCssVars emits --bg/--fg/--accent/--mega for a normal theme", () => {
74
+ const t = getTheme("retro");
75
+ const vars = themeCssVars(t);
76
+ assert.match(vars, /--bg: #003300;/);
77
+ assert.match(vars, /--fg: #33ff33;/);
78
+ assert.match(vars, /--accent: #00ff41;/);
79
+ assert.match(vars, /--mega: #39ff14;/);
80
+ });
81
+ it("themeCssVars maps null bg to 'transparent'", () => {
82
+ const t = getTheme("transparent");
83
+ const vars = themeCssVars(t);
84
+ assert.match(vars, /--bg: transparent;/);
85
+ assert.match(vars, /--fg: #c9d1d9;/);
86
+ });
87
+ it("themeDataBlock wraps vars in a :root[data-theme=\"<id\"] selector", () => {
88
+ const t = getTheme("cyan-neon");
89
+ const block = themeDataBlock(t);
90
+ assert.equal(block.startsWith(':root[data-theme="cyan-neon"]{ '), true);
91
+ assert.equal(block.endsWith(" }"), true);
92
+ assert.ok(block.includes("--accent: #22d3ee;"));
93
+ });
94
+ });
@@ -0,0 +1,105 @@
1
+ /** Canonical allow-list of game metrics (mirrors the schema CHECK constraint). */
2
+ export const METRICS = [
3
+ "cache",
4
+ "dedupe",
5
+ "turns",
6
+ "repos",
7
+ "mega_cache",
8
+ ];
9
+ /**
10
+ * Player level as a function of completed turns.
11
+ * Sequence: n=0→1, 1→2, 2→2, 3→3, 4→3, 7→4, 15→5, ...
12
+ * i.e. floor(log2(n+1)) + 1 (one level per doubling of turns). Defensive: any
13
+ * non-finite / negative input collapses to level 1 (never throws, never NaN).
14
+ */
15
+ export function turnLevel(n) {
16
+ if (!Number.isFinite(n) || n < 0)
17
+ return 1;
18
+ return Math.floor(Math.log2(n + 1)) + 1;
19
+ }
20
+ /**
21
+ * MEGA CACHE trigger test: the cache hit-rate (real ratio, may exceed 100%)
22
+ * has crossed the 100% threshold. Used to award the mega_cache trophy + arm
23
+ * the widget flare (the oopsie gag).
24
+ */
25
+ export function isMegaCache(pct) {
26
+ return Number.isFinite(pct) && pct >= 100;
27
+ }
28
+ /**
29
+ * Cache-hit percentage (0..100+). Returns 0 when there are no lookups so the
30
+ * ratio can never be NaN / Infinity (QA3). Safe against non-finite inputs.
31
+ */
32
+ export function cacheScore(hits, lookups) {
33
+ if (!Number.isFinite(hits) || !Number.isFinite(lookups))
34
+ return 0;
35
+ return lookups > 0 ? (hits / lookups) * 100 : 0;
36
+ }
37
+ /**
38
+ * The 9 achievements (8 visible + 1 hidden easter egg = Opie's Wild Ride).
39
+ * Seeded idempotently into the `game_achievements` table on first open
40
+ * (schema.ts). Pure, pi-agnostic — no I/O.
41
+ */
42
+ export const ACHIEVEMENT_DEFS = [
43
+ { id: "first_compact", title: "First Compact", description: "Compact a conversation once.", hidden: false, icon: "\u{1F476}" },
44
+ { id: "compact_streak", title: "Compact Streak", description: "Compact 5 times in one session.", hidden: false, icon: "\u{1F525}" },
45
+ { id: "turn_veteran", title: "Turn Veteran", description: "Reach 25 turns in a repo.", hidden: false, icon: "\u{1F3C3}" },
46
+ { id: "level_five", title: "Level 5", description: "Reach player level 5.", hidden: false, icon: "\u{2B50}" },
47
+ { id: "dedupe_master", title: "Dedupe Master", description: "Collapse 100 chunks total.", hidden: false, icon: "\u{1F5DC}\u{FE0F}" },
48
+ { id: "repo_explorer", title: "Repo Explorer", description: "Use game mode across 3 repos.", hidden: false, icon: "\u{1F30D}" },
49
+ { id: "night_owl", title: "Night Owl", description: "Record a score after midnight (00:00–05:00 local).", hidden: false, icon: "\u{1F989}" },
50
+ { id: "flawless", title: "Flawless", description: "Hit exactly 100% cache with no overshoot.", hidden: false, icon: "\u{1F4AF}" },
51
+ { id: "opie_wild_ride", title: "Opie's Wild Ride", description: "Push the cache past 100%.", hidden: true, icon: "\u{1F3C6}" },
52
+ ];
53
+ /**
54
+ * Max `compactCount` carried in a dedupe row's `meta` (S33 records
55
+ * `{ compactCount }` on each session_compact). Returns 0 when absent.
56
+ */
57
+ export function maxCompactCount(rows) {
58
+ return rows.reduce((m, r) => {
59
+ const meta = r.meta;
60
+ const cm = meta && typeof meta === "object" && "compactCount" in meta
61
+ ? Number(meta.compactCount) || 0
62
+ : 0;
63
+ return Math.max(m, cm);
64
+ }, 0);
65
+ }
66
+ /**
67
+ * Pure evaluation of the 9 achievements against the leaderboard aggregates.
68
+ * `alreadyUnlocked` is the set of ids already persisted (so `newlyUnlocked`
69
+ * excludes them). No I/O, no pi types. Mirrors the S35.9 condition table.
70
+ */
71
+ export function evaluateAchievements(ctx, alreadyUnlocked) {
72
+ const sumBy = (rows) => rows.reduce((s, r) => s + (Number(r.value) || 0), 0);
73
+ const maxBy = (rows) => rows.reduce((m, r) => Math.max(m, Number(r.value) || 0), 0);
74
+ const dedupeSum = sumBy(ctx.dedupe);
75
+ const maxTurns = maxBy(ctx.turns);
76
+ const maxCache = maxBy(ctx.cache);
77
+ const maxCompact = maxCompactCount(ctx.dedupe);
78
+ // Night owl: any row (across all metrics) recorded between 00:00–05:00 local.
79
+ const allTs = [
80
+ ...ctx.dedupe,
81
+ ...ctx.turns,
82
+ ...ctx.cache,
83
+ ...ctx.megaCache,
84
+ ];
85
+ const nightOwl = allTs.some((r) => {
86
+ const h = new Date(Number(r.ts) || 0).getHours();
87
+ return h >= 0 && h < 5;
88
+ });
89
+ // Flawless: cache hit 100%+, but NO mega_cache overshoot (>100).
90
+ const megaOvershoot = ctx.megaCache.some((r) => Number(r.value) > 100);
91
+ const conditions = {
92
+ first_compact: ctx.dedupe.length >= 1,
93
+ compact_streak: maxCompact >= 5,
94
+ turn_veteran: maxTurns >= 25,
95
+ level_five: turnLevel(maxTurns) >= 5,
96
+ dedupe_master: dedupeSum >= 100,
97
+ repo_explorer: ctx.reposCount >= 3,
98
+ night_owl: nightOwl,
99
+ flawless: maxCache >= 100 && !megaOvershoot,
100
+ opie_wild_ride: ctx.megaCache.length >= 1,
101
+ };
102
+ const unlocked = Object.keys(conditions).filter((id) => conditions[id]);
103
+ const newlyUnlocked = unlocked.filter((id) => !alreadyUnlocked.includes(id));
104
+ return { unlocked, newlyUnlocked };
105
+ }