pi-mega-compact 0.7.8 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +11 -12
  2. package/dist/extensions/dashboard-server/html.js +1023 -0
  3. package/dist/extensions/dashboard-server/html.test.js +41 -0
  4. package/dist/extensions/dashboard-server/index-reader.js +133 -0
  5. package/dist/extensions/dashboard-server/server.js +530 -0
  6. package/dist/extensions/dashboard-server/server.test.js +120 -0
  7. package/dist/extensions/dashboard-server/snapshot.js +43 -0
  8. package/dist/extensions/dashboard-server/state.js +30 -0
  9. package/dist/extensions/dashboard-server/types.js +5 -0
  10. package/dist/extensions/dashboard-server-s32.test.js +181 -0
  11. package/dist/extensions/dashboard-server.js +7 -1315
  12. package/dist/extensions/mega-commands.js +162 -134
  13. package/dist/extensions/mega-compact.js +3 -0
  14. package/dist/extensions/mega-compact.test.js +90 -21
  15. package/dist/extensions/mega-conflict-cmds.js +5 -1
  16. package/dist/extensions/mega-dashboard-cmds.js +29 -22
  17. package/dist/extensions/mega-db-cmds.js +11 -2
  18. package/dist/extensions/mega-events/agent-handlers.js +222 -0
  19. package/dist/extensions/mega-events/compact-handlers.js +162 -0
  20. package/dist/extensions/mega-events/context-handler.js +249 -0
  21. package/dist/extensions/mega-events/register.js +21 -0
  22. package/dist/extensions/mega-events/session-handlers.js +142 -0
  23. package/dist/extensions/mega-events.js +15 -699
  24. package/dist/extensions/mega-game-cmds.js +106 -0
  25. package/dist/extensions/mega-game-cmds.test.js +113 -0
  26. package/dist/extensions/mega-pipeline/compact.js +324 -0
  27. package/dist/extensions/mega-pipeline/memory-review.js +38 -0
  28. package/dist/extensions/mega-pipeline/recall.js +147 -0
  29. package/dist/extensions/mega-pipeline.js +9 -480
  30. package/dist/extensions/mega-runtime/helpers.js +40 -0
  31. package/dist/extensions/mega-runtime/query.js +29 -0
  32. package/dist/extensions/mega-runtime/state.js +877 -0
  33. package/dist/extensions/mega-runtime/state.test.js +171 -0
  34. package/dist/extensions/mega-runtime/widget.js +270 -0
  35. package/dist/extensions/mega-runtime/widget.test.js +160 -0
  36. package/dist/extensions/mega-runtime.js +15 -947
  37. package/dist/src/config/themes.js +84 -0
  38. package/dist/src/config/themes.test.js +94 -0
  39. package/dist/src/game/scoring.js +105 -0
  40. package/dist/src/game/scoring.test.js +98 -0
  41. package/dist/src/store/sqlite/checkpoints.js +145 -0
  42. package/dist/src/store/sqlite/dedup-mirror.js +64 -0
  43. package/dist/src/store/sqlite/foundation.js +38 -0
  44. package/dist/src/store/sqlite/game-achievements.js +111 -0
  45. package/dist/src/store/sqlite/game-achievements.test.js +67 -0
  46. package/dist/src/store/sqlite/game-scores.js +105 -0
  47. package/dist/src/store/sqlite/game-scores.test.js +106 -0
  48. package/dist/src/store/sqlite/game-state.js +54 -0
  49. package/dist/src/store/sqlite/game-state.test.js +76 -0
  50. package/dist/src/store/sqlite/global-index.js +224 -0
  51. package/dist/src/store/sqlite/maintenance.js +235 -0
  52. package/dist/src/store/sqlite/memories.js +164 -0
  53. package/dist/src/store/sqlite/meta.js +82 -0
  54. package/dist/src/store/sqlite/model-snapshots.js +47 -0
  55. package/dist/src/store/sqlite/raptor.js +57 -0
  56. package/dist/src/store/sqlite/raw-transcript.js +134 -0
  57. package/dist/src/store/sqlite/schema.js +294 -0
  58. package/dist/src/store/sqlite/session-state.js +28 -0
  59. package/dist/src/store/sqlite/stats.js +66 -0
  60. package/dist/src/store/sqlite/utils.js +120 -0
  61. package/dist/src/store/sqlite.js +23 -1607
  62. package/extensions/dashboard-server/html.test.ts +50 -0
  63. package/extensions/dashboard-server/html.ts +1026 -0
  64. package/extensions/dashboard-server/index-reader.ts +130 -0
  65. package/extensions/dashboard-server/server.test.ts +131 -0
  66. package/extensions/dashboard-server/server.ts +505 -0
  67. package/extensions/dashboard-server/snapshot.ts +44 -0
  68. package/extensions/dashboard-server/state.ts +33 -0
  69. package/extensions/dashboard-server/types.ts +134 -0
  70. package/extensions/dashboard-server-s32.test.ts +195 -0
  71. package/extensions/dashboard-server.ts +7 -1431
  72. package/extensions/mega-commands.ts +33 -10
  73. package/extensions/mega-compact.test.ts +198 -43
  74. package/extensions/mega-compact.ts +3 -0
  75. package/extensions/mega-conflict-cmds.ts +6 -2
  76. package/extensions/mega-dashboard-cmds.ts +30 -23
  77. package/extensions/mega-db-cmds.ts +11 -3
  78. package/extensions/mega-events/agent-handlers.ts +262 -0
  79. package/extensions/mega-events/compact-handlers.ts +192 -0
  80. package/extensions/mega-events/context-handler.ts +290 -0
  81. package/extensions/mega-events/register.ts +37 -0
  82. package/extensions/mega-events/session-handlers.ts +165 -0
  83. package/extensions/mega-events.ts +15 -780
  84. package/extensions/mega-game-cmds.test.ts +137 -0
  85. package/extensions/mega-game-cmds.ts +122 -0
  86. package/extensions/mega-pipeline/compact.ts +366 -0
  87. package/extensions/mega-pipeline/memory-review.ts +46 -0
  88. package/extensions/mega-pipeline/recall.ts +165 -0
  89. package/extensions/mega-pipeline.ts +9 -537
  90. package/extensions/mega-runtime/helpers.ts +68 -0
  91. package/extensions/mega-runtime/query.ts +29 -0
  92. package/extensions/mega-runtime/state.test.ts +171 -0
  93. package/extensions/mega-runtime/state.ts +967 -0
  94. package/extensions/mega-runtime/widget.test.ts +185 -0
  95. package/extensions/mega-runtime/widget.ts +359 -0
  96. package/extensions/mega-runtime.ts +15 -1093
  97. package/package.json +4 -3
  98. package/src/config/themes.test.ts +116 -0
  99. package/src/config/themes.ts +124 -0
  100. package/src/game/scoring.test.ts +103 -0
  101. package/src/game/scoring.ts +158 -0
  102. package/src/store/sqlite/checkpoints.ts +204 -0
  103. package/src/store/sqlite/dedup-mirror.ts +114 -0
  104. package/src/store/sqlite/foundation.ts +63 -0
  105. package/src/store/sqlite/game-achievements.test.ts +80 -0
  106. package/src/store/sqlite/game-achievements.ts +147 -0
  107. package/src/store/sqlite/game-scores.test.ts +132 -0
  108. package/src/store/sqlite/game-scores.ts +168 -0
  109. package/src/store/sqlite/game-state.test.ts +89 -0
  110. package/src/store/sqlite/game-state.ts +87 -0
  111. package/src/store/sqlite/global-index.ts +305 -0
  112. package/src/store/sqlite/maintenance.ts +294 -0
  113. package/src/store/sqlite/memories.ts +217 -0
  114. package/src/store/sqlite/meta.ts +108 -0
  115. package/src/store/sqlite/model-snapshots.ts +83 -0
  116. package/src/store/sqlite/raptor.ts +107 -0
  117. package/src/store/sqlite/raw-transcript.ts +221 -0
  118. package/src/store/sqlite/schema.ts +305 -0
  119. package/src/store/sqlite/session-state.ts +38 -0
  120. package/src/store/sqlite/stats.ts +127 -0
  121. package/src/store/sqlite/utils.ts +125 -0
  122. package/src/store/sqlite.ts +23 -2204
@@ -0,0 +1,171 @@
1
+ /**
2
+ * state.test.ts — S31 MegaRuntime game-state cache round-trip.
3
+ *
4
+ * getCachedGameState() lazily reads the game_state row; bumpGameState()
5
+ * evicts so the next read re-queries. Uses MEGACOMPACT_STATE_DIR + mkdtemp
6
+ * (G7). A minimal MegaRuntime is constructed directly (no pi runtime).
7
+ */
8
+ import { describe, it, after } from "node:test";
9
+ import assert from "node:assert/strict";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+ import { mkdtempSync, rmSync } from "node:fs";
13
+ import { createRequire } from "node:module";
14
+ import { execSync } from "node:child_process";
15
+ import { closeStore, getGameState, setGameState } from "../../src/store/sqlite.js";
16
+ import { DEFAULT_GAME_STATE } from "../../src/store/sqlite/game-state.js";
17
+ const require = createRequire(import.meta.url);
18
+ // Require the compiled JS (build output) so ESM import of pi-tui etc. resolves.
19
+ const { MegaRuntime } = require("./state.js");
20
+ /** Minimal MegaConfig — enough fields for the constructor; the snapshot path
21
+ * isn't exercised here, only getCachedGameState/bumpGameState. */
22
+ function minimalConfig(stateDir) {
23
+ return {
24
+ tier: "custom",
25
+ tierPct: null,
26
+ thresholdTokens: 100_000,
27
+ stateDir,
28
+ fastGatePct: 70,
29
+ anchorUserMessages: 3,
30
+ preserveRecent: 4,
31
+ preserveRecentMin: 2,
32
+ auto: false,
33
+ autoInline: false,
34
+ autoContinueLengthStop: false,
35
+ autoPctTrigger: null,
36
+ dedupSim: 0.9,
37
+ raptorEnabled: false,
38
+ legacyDurableTrim: false,
39
+ dbMirror: false,
40
+ crossRepoEnabled: false,
41
+ crossRepoCosine: 0.9,
42
+ memoryAutoReview: false,
43
+ memoryReviewInterval: 10,
44
+ recallMaxTokens: 1500,
45
+ windowDedupe: false,
46
+ debug: false,
47
+ };
48
+ }
49
+ /** Fresh isolated state dir per test — the game_state row is global and
50
+ * persists across cases in a shared dir, so each case gets its own mkdtemp to
51
+ * avoid cross-test contamination. */
52
+ function freshDir() {
53
+ return mkdtempSync(join(tmpdir(), "mc-state-"));
54
+ }
55
+ describe("MegaRuntime game-state cache (S31)", () => {
56
+ const dirs = [];
57
+ after(() => {
58
+ for (const d of dirs) {
59
+ try {
60
+ closeStore(d);
61
+ }
62
+ catch { /* */ }
63
+ }
64
+ delete process.env.MEGACOMPACT_STATE_DIR;
65
+ for (const d of dirs)
66
+ rmSync(d, { recursive: true, force: true });
67
+ });
68
+ it("getCachedGameState returns defaults on a fresh install", () => {
69
+ const dir = freshDir();
70
+ dirs.push(dir);
71
+ process.env.MEGACOMPACT_STATE_DIR = dir;
72
+ const rt = new MegaRuntime(minimalConfig(dir));
73
+ const gs = rt.getCachedGameState();
74
+ assert.deepEqual(gs, { ...DEFAULT_GAME_STATE });
75
+ });
76
+ it("getCachedGameState memoizes (same ref across calls)", () => {
77
+ const dir = freshDir();
78
+ dirs.push(dir);
79
+ process.env.MEGACOMPACT_STATE_DIR = dir;
80
+ const rt = new MegaRuntime(minimalConfig(dir));
81
+ const a = rt.getCachedGameState();
82
+ const b = rt.getCachedGameState();
83
+ assert.equal(a, b, "memoized — same object ref");
84
+ });
85
+ it("bumpGameState evicts so the next read reflects a setGameState write", () => {
86
+ const dir = freshDir();
87
+ dirs.push(dir);
88
+ process.env.MEGACOMPACT_STATE_DIR = dir;
89
+ const rt = new MegaRuntime(minimalConfig(dir));
90
+ const before = rt.getCachedGameState();
91
+ assert.equal(before.game_mode_on, false);
92
+ // Write out-of-band (as /mega-game would).
93
+ setGameState({ game_mode_on: true, theme: "retro", tui_display_mode: "minimal" }, dir);
94
+ // Without bump, the stale memo is returned.
95
+ const stale = rt.getCachedGameState();
96
+ assert.equal(stale.game_mode_on, false, "stale cache before bump");
97
+ // After bump, the next read re-queries and reflects the write.
98
+ rt.bumpGameState();
99
+ const fresh = rt.getCachedGameState();
100
+ assert.equal(fresh.game_mode_on, true);
101
+ assert.equal(fresh.theme, "retro");
102
+ assert.equal(fresh.tui_display_mode, "minimal");
103
+ // And matches the authoritative getGameState read.
104
+ assert.deepEqual(fresh, getGameState(dir));
105
+ });
106
+ it("bumpGameState is idempotent (safe to call when cache is empty)", () => {
107
+ const dir = freshDir();
108
+ dirs.push(dir);
109
+ process.env.MEGACOMPACT_STATE_DIR = dir;
110
+ const rt = new MegaRuntime(minimalConfig(dir));
111
+ rt.bumpGameState(); // no cached state yet — must not throw
112
+ const gs = rt.getCachedGameState();
113
+ assert.deepEqual(gs, { ...DEFAULT_GAME_STATE });
114
+ });
115
+ it("bindRepo evicts cachedGameState so a repo switch reflects the new repo's game_state", () => {
116
+ // Two fresh git repos A and B simulate a real repo switch. Each holds its
117
+ // own per-repo state dir at <root>/.pi/mega-compact (what repoStateDir
118
+ // returns for a git cwd), and each holds its own game_state row, so a repo
119
+ // switch (bindRepo) must evict the cached memo or the widget shows A's
120
+ // theme/mode/toggle after moving to B. Uses MEGACOMPACT_STATE_DIR + mkdtemp
121
+ // + closeStore (G7); the global state dir stays separate.
122
+ const globalDir = freshDir();
123
+ dirs.push(globalDir);
124
+ const repoA = freshDir();
125
+ dirs.push(repoA);
126
+ const repoB = freshDir();
127
+ dirs.push(repoB);
128
+ const stateA = join(repoA, ".pi", "mega-compact");
129
+ const stateB = join(repoB, ".pi", "mega-compact");
130
+ // Make A and B real git roots so resolveRepoRoot(cwd) returns the root and
131
+ // repoStateDir produces <root>/.pi/mega-compact (the per-repo store).
132
+ execSync("git init -q", { cwd: repoA });
133
+ execSync("git init -q", { cwd: repoB });
134
+ // Seed A and B with distinct game_state rows in their per-repo dirs.
135
+ setGameState({ game_mode_on: true, theme: "retro", tui_display_mode: "minimal" }, stateA);
136
+ setGameState({ game_mode_on: false, theme: "cyan-neon", tui_display_mode: "full" }, stateB);
137
+ // Construct the runtime against the GLOBAL dir (the non-git fallback so a
138
+ // real bindRepo switch occurs once we point it at a git root).
139
+ process.env.MEGACOMPACT_STATE_DIR = globalDir;
140
+ const rt = new MegaRuntime(minimalConfig(globalDir));
141
+ // Point the runtime at repo A and prime the cache.
142
+ rt.bindRepo(repoA);
143
+ assert.equal(rt.currentStateDir, stateA, "bindRepo(A) switched to A's per-repo dir");
144
+ const a = rt.getCachedGameState();
145
+ assert.equal(a.game_mode_on, true, "A: game_mode_on primed");
146
+ assert.equal(a.theme, "retro", "A: theme primed");
147
+ assert.equal(a.tui_display_mode, "minimal", "A: tui_display_mode primed");
148
+ // Switch to repo B: bindRepo must evict cachedGameState so the next read
149
+ // re-queries B's row instead of returning A's stale memo.
150
+ rt.bindRepo(repoB);
151
+ assert.equal(rt.currentStateDir, stateB, "bindRepo(B) switched to B's per-repo dir");
152
+ const b = rt.getCachedGameState();
153
+ assert.equal(b.game_mode_on, false, "B: game_mode_on after switch (not A's stale true)");
154
+ assert.equal(b.theme, "cyan-neon", "B: theme after switch (not A's stale retro)");
155
+ assert.equal(b.tui_display_mode, "full", "B: tui_display_mode after switch (not A's stale minimal)");
156
+ assert.deepEqual(b, getGameState(stateB), "B matches authoritative getGameState read");
157
+ // Cleanup the per-repo DB handles.
158
+ try {
159
+ closeStore(globalDir);
160
+ }
161
+ catch { /* */ }
162
+ try {
163
+ closeStore(stateA);
164
+ }
165
+ catch { /* */ }
166
+ try {
167
+ closeStore(stateB);
168
+ }
169
+ catch { /* */ }
170
+ });
171
+ });
@@ -0,0 +1,270 @@
1
+ /**
2
+ * widget.ts — above-editor widget rendering helpers (free functions, consts,
3
+ * and interfaces) extracted from the original mega-runtime.ts monolith.
4
+ *
5
+ * These are pure rendering primitives with zero runtime-state dependencies;
6
+ * the `MegaRuntime` class (state.ts) imports them to paint the panel.
7
+ */
8
+ // pi-tui's OWN width measurers — the same functions pi-tui uses to enforce its
9
+ // render-width check ("visibleWidth(line) > width" → crash). Measuring with
10
+ // these guarantees we never disagree on a grapheme's width (e.g. RGI emoji
11
+ // like ⚡ which pi-tui counts as 2 but a naive regex counts as 1), and
12
+ // truncateToWidth both pads AND hard-clips to exactly `width` cells, so no
13
+ // off-by-one can trip the strict `> width` guard. (Fix for the
14
+ // `Rendered line N exceeds terminal width (W > W-1)` crash.)
15
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
16
+ import { getTheme, DEFAULT_THEME } from "../../src/config/themes.js";
17
+ // ── ANSI palette ───────────────────────────────────────────────────────────
18
+ // The pi TUI's Text component preserves ANSI escape codes (see wrapTextWithAnsi),
19
+ // so raw escapes render as colors. No chalk dependency needed — these are just
20
+ // strings. Exported because mega-pipeline.ts and mega-commands.ts import `C`
21
+ // from the mega-runtime barrel.
22
+ export const C = {
23
+ reset: "\x1b[0m",
24
+ dim: "\x1b[2m",
25
+ bold: "\x1b[1m",
26
+ amber: "\x1b[38;5;214m", // tier / ready
27
+ green: "\x1b[38;5;120m", // saved
28
+ cyan: "\x1b[38;5;51m", // used / live activity
29
+ teal: "\x1b[38;5;37m", // processing (compress/dedup)
30
+ magenta: "\x1b[38;5;201m", // dedup rate
31
+ blue: "\x1b[38;5;75m", // repo totals
32
+ gray: "\x1b[38;5;245m", // labels
33
+ red: "\x1b[38;5;203m", // pressure / overflow
34
+ };
35
+ const PULSE = ["◐", "◓", "◑", "◒"];
36
+ // ── Full-width widget panel helpers ────────────────────────────────────────
37
+ // pi's above-editor widget renderer (a Container of Text lines) does NOT pass
38
+ // a terminal width to setWidget(), so lines render left-aligned by default. To
39
+ // make the widget read as a full-width status panel we pad each line to the
40
+ // real terminal width with a background fill. NOTE: C.reset is a FULL SGR
41
+ // reset, so we re-apply the panel bg after every reset to keep the background
42
+ // continuous under colored text (and under pi's own trailing reset).
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
+ }
73
+ // (Visible-width measurement is delegated to pi-tui's `visibleWidth` — imported
74
+ // above — so our width math can never diverge from pi-tui's render-width check.)
75
+ /** Wrap a string (with ANSI codes) to fit within `maxWidth` visible chars.
76
+ * Splits at │ separators or whitespace when possible. */
77
+ function wrapLine(text, maxWidth, panelBg) {
78
+ if (maxWidth <= 0)
79
+ return [text];
80
+ const panelRst = "\x1b[0m" + panelBg;
81
+ const result = [];
82
+ let current = "";
83
+ let currentW = 0;
84
+ // Split at │ boundaries first
85
+ const segments = text.split("│");
86
+ for (let i = 0; i < segments.length; i++) {
87
+ const seg = (i > 0 ? "│" : "") + segments[i];
88
+ const segW = visibleWidth(panelBg + seg.replace(/\x1b\[0m/g, panelRst));
89
+ if (currentW + segW <= maxWidth || currentW === 0) {
90
+ current += seg;
91
+ currentW += segW;
92
+ }
93
+ else {
94
+ result.push(current);
95
+ current = seg;
96
+ currentW = segW;
97
+ }
98
+ }
99
+ if (current)
100
+ result.push(current);
101
+ return result;
102
+ }
103
+ function panelLine(content, width, panelBg = DEFAULT_PANEL_BG) {
104
+ if (width <= 0)
105
+ return "";
106
+ const panelRst = "\x1b[0m" + panelBg;
107
+ // Apply the panel background; swap every inner full-reset for a reset that
108
+ // re-applies the bg so the fill stays continuous under colored text.
109
+ const withBg = panelBg + content.replace(/\x1b\[0m/g, panelRst);
110
+ // truncateToWidth(line, width, "", true) returns EXACTLY `width` visible cells
111
+ // (by pi-tui's measure), ANSI-preserved, space-padded. It hard-clips overflow
112
+ // — so even a segment wider than `width` (or a width-rule mismatch) can never
113
+ // produce a line that trips pi-tui's strict `visibleWidth(line) > width` check.
114
+ return truncateToWidth(withBg, width, "", true) + "\x1b[0m";
115
+ }
116
+ /** A full-width hairline bar (top/bottom border of the panel). */
117
+ function panelBar(width, ch = "─", panelBg = DEFAULT_PANEL_BG) {
118
+ // `─` (U+2500) is narrow (1 cell) in both our measure and pi-tui's, so a
119
+ // `ch.repeat(width)` bar is exactly `width` cells and already passes the
120
+ // `> width` guard. truncateToWidth is belt-and-suspenders in case `ch` is
121
+ // ever swapped for a wide/fullwidth character.
122
+ return truncateToWidth(panelBg + ch.repeat(Math.max(0, width)), width, "", false) + "\x1b[0m";
123
+ }
124
+ /** Token-count formatter: M at/above 1e6, k at/above 1e3, raw below.
125
+ * 5,472,700 → "5.5mil", 24,100 → "24.1k", 142 → "142". */
126
+ function fmtTokens(x) {
127
+ return x >= 1_000_000
128
+ ? `${(x / 1_000_000).toFixed(1)}mil`
129
+ : x >= 1000
130
+ ? `${(x / 1000).toFixed(1)}k`
131
+ : `${Math.round(x)}`;
132
+ }
133
+ /** Retro gradient bar — `w` cells shaded by fill position (green→amber→red).
134
+ * Used for CONTEXT fill where low=green (room) and high=red (near the limit). */
135
+ function ramp(pct, w = 12) {
136
+ const cells = ["▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"];
137
+ const scaled = Math.max(0, Math.min(w, pct * w));
138
+ const full = Math.floor(scaled);
139
+ const frac = scaled - full;
140
+ const fracCell = frac > 0 ? cells[Math.round(frac * (cells.length - 1))] : "";
141
+ let out = "";
142
+ for (let i = 0; i < full; i++)
143
+ out += (i / w < 0.6 ? C.green : i / w < 0.85 ? C.amber : C.red) + "█";
144
+ if (fracCell)
145
+ out +=
146
+ (full / w < 0.6 ? C.green : full / w < 0.85 ? C.amber : C.red) + fracCell;
147
+ out +=
148
+ C.dim + "░".repeat(Math.max(0, w - full - (fracCell ? 1 : 0))) + C.reset;
149
+ return out;
150
+ }
151
+ /** Human "time since" string from a millisecond delta (or null → "never"). */
152
+ function sinceCompactStr(ms) {
153
+ if (ms == null)
154
+ return "never";
155
+ const s = Math.floor(ms / 1000);
156
+ if (s < 60)
157
+ return `${s}s ago`;
158
+ const m = Math.floor(s / 60);
159
+ if (m < 60)
160
+ return `${m}m ago`;
161
+ const h = Math.floor(m / 60);
162
+ if (h < 24)
163
+ return `${h}h ago`;
164
+ return `${Math.floor(h / 24)}d ago`;
165
+ }
166
+ // ── buildWidgetLines ───────────────────────────────────────────────────────
167
+ // Kept as a free function (not a MegaRuntime method) so state.ts stays
168
+ // focused on state management. It reads the WidgetData snapshot + the live
169
+ // activeAgents counter (passed in) and returns the panel lines.
170
+ /** Build the full-width panel lines from the latest snapshot. Cheap: reads
171
+ * only the WidgetData + a couple of live counters; no DB/IO. */
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;
178
+ if (!wd) {
179
+ return [
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),
205
+ ];
206
+ }
207
+ const pulse = wd.pulsing
208
+ ? `${C.cyan}${PULSE[Math.floor(Date.now() / 250) % PULSE.length]}${C.reset} `
209
+ : "";
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
+ : "";
220
+ // Build one long content line — let terminal wrap it naturally
221
+ const content = [
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}`,
223
+ wd.triggerLabel,
224
+ `${C.cyan}${wd.modelStr}${C.reset}`,
225
+ `${wd.chk} chk${wd.agentStr}${wd.turnStr}`,
226
+ `${C.magenta}dup ${wd.dedupStr}${C.reset}`,
227
+ `${C.gray}sess${C.reset} ${fmtTokens(wd.sessIn)}→${fmtTokens(wd.sessKept)} kept ${C.green}(${wd.sTxt}% freed)${C.reset}`,
228
+ `${C.gray}all-time${C.reset} ${fmtTokens(wd.repoIn)}→${fmtTokens(wd.repoKept)} kept ${C.blue}(${wd.rTxt}% freed)${C.reset}`,
229
+ `${wd.repoChk} chk/${wd.repoSess} sess`,
230
+ `${C.gray}mem${C.reset} ${wd.embedderName} · ${wd.chk} chunks · ${C.blue}comp ${wd.compStr}${C.reset}`,
231
+ `${C.gray}drift${C.reset} ${wd.driftStatus === "ok" ? C.green : C.amber}${wd.driftStatus}${C.reset}`,
232
+ `${C.gray}compact${C.reset} ${sinceCompactStr(wd.sinceCompact)}`,
233
+ ].join(sep);
234
+ // Wrap to terminal width and pad each line
235
+ const wrapped = wrapLine(content, width - 2, panelBg); // 2-char indent
236
+ const lines = [
237
+ panelBar(width, "─", panelBg),
238
+ ...wrapped.map((l) => panelLine(l, width, panelBg)),
239
+ ];
240
+ // L4 — agents block (S27, count + status; per-agent tokens gated on P0)
241
+ if (wd.agentsActive) {
242
+ lines.push(panelLine(` ${C.cyan}🤖 ${activeAgents} active${wd.turnStr}${C.reset}`, width, panelBg));
243
+ }
244
+ // L5 — live ticker / activity (♻ deduped … why, or tier trace, or pulsing)
245
+ if (wd.tierTrace && wd.fresh) {
246
+ lines.push(panelLine(` ${pulse}${wd.tierTrace}`, width, panelBg));
247
+ }
248
+ else if (wd.ticker.length > 0) {
249
+ const step = Math.floor(Date.now() / 250);
250
+ const idx = wd.ticker.length - 1 - (step % wd.ticker.length);
251
+ const head = wd.ticker[idx].text;
252
+ const why = wd.lastWhy ? ` ${C.gray}· ${wd.lastWhy}${C.reset}` : "";
253
+ const more = wd.ticker.length > 1
254
+ ? ` ${C.dim}(+${wd.ticker.length - 1} more)${C.reset}`
255
+ : "";
256
+ lines.push(panelLine(` ${wd.fresh ? C.teal : C.dim}${head}${why}${more}${C.reset}`, width, panelBg));
257
+ }
258
+ else if (wd.pulsing) {
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));
266
+ }
267
+ // bottom border
268
+ lines.push(panelBar(width, "─", panelBg));
269
+ return lines;
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
+ });