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,137 @@
1
+ /**
2
+ * mega-game-cmds.test.ts — /mega-game command parsing matrix (S30).
3
+ * Uses an isolated state dir + a fake pi harness (mirrors mega-compact.test.ts).
4
+ * Pi runtime is mocked; the src/ helpers under test are pi-agnostic.
5
+ */
6
+ import { describe, it, before, after } from "node:test";
7
+ import assert from "node:assert/strict";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { mkdtempSync, rmSync } from "node:fs";
11
+ import { createRequire } from "node:module";
12
+ import { closeStore, getGameState } from "../src/store/sqlite.js";
13
+ import { THEME_IDS } from "../src/config/themes.js";
14
+
15
+ // ESM bootstrap so `require()` works in this .test.ts (mirrors
16
+ // mega-compact.test.ts:20-24). Needed for the dynamic `require("./mega-game-cmds.js")`
17
+ // that wires the command against a fake pi without binding to the real pi
18
+ // module at load time.
19
+ const require = createRequire(import.meta.url);
20
+
21
+ type Cmd = { description?: string; handler: (args: string, ctx: any) => Promise<void> };
22
+
23
+ type Harness = {
24
+ commands: Record<string, Cmd>;
25
+ notifies: string[];
26
+ ctx: any;
27
+ };
28
+
29
+ function makeHarness(stateDir: string): Harness {
30
+ const commands: Record<string, Cmd> = {};
31
+ const notifies: string[] = [];
32
+ const runtime = { bindRepo: () => {}, currentStateDir: stateDir, bumpGameState: () => {} };
33
+ const ctx = {
34
+ cwd: stateDir,
35
+ ui: { notify: (s: string) => notifies.push(s) },
36
+ };
37
+ const fakePi = {
38
+ registerCommand: (name: string, opts: Cmd) => {
39
+ commands[name] = opts;
40
+ },
41
+ };
42
+ // Import after env is set so stateDir resolves. Dynamic import keeps the
43
+ // test from binding to the real pi module at load time.
44
+ const mod = require("./mega-game-cmds.js") as {
45
+ registerGameCommands: (pi: unknown, runtime: unknown) => void;
46
+ };
47
+ mod.registerGameCommands(fakePi, runtime);
48
+ return { commands, notifies, ctx };
49
+ }
50
+
51
+ describe("/mega-game (S30)", () => {
52
+ let dir: string;
53
+ before(() => {
54
+ dir = mkdtempSync(join(tmpdir(), "mc-megagame-"));
55
+ process.env.MEGACOMPACT_STATE_DIR = dir;
56
+ });
57
+ after(() => {
58
+ closeStore(dir);
59
+ delete process.env.MEGACOMPACT_STATE_DIR;
60
+ rmSync(dir, { recursive: true, force: true });
61
+ });
62
+
63
+ async function run(args: string): Promise<string[]> {
64
+ const h = makeHarness(dir);
65
+ h.notifies.length = 0;
66
+ await h.commands["mega-game"].handler(args, h.ctx);
67
+ return h.notifies;
68
+ }
69
+
70
+ it("bare command prints current (default) state", async () => {
71
+ const lines = await run("");
72
+ assert.ok(lines.some((l) => l.includes("game mode: off")));
73
+ assert.ok(lines.some((l) => l.includes("transparent")));
74
+ assert.ok(lines.some((l) => l.includes("tui:")));
75
+ });
76
+
77
+ it("on enables game mode and persists", async () => {
78
+ await run("on");
79
+ assert.equal(getGameState().game_mode_on, true);
80
+ });
81
+
82
+ it("off disables game mode and persists", async () => {
83
+ await run("on");
84
+ await run("off");
85
+ assert.equal(getGameState().game_mode_on, false);
86
+ });
87
+
88
+ it("theme <id> sets a valid theme and persists", async () => {
89
+ await run("theme retro");
90
+ assert.equal(getGameState().theme, "retro");
91
+ await run("theme cyan-neon");
92
+ assert.equal(getGameState().theme, "cyan-neon");
93
+ });
94
+
95
+ it("theme <unknown> is rejected with a usage line and does not mutate", async () => {
96
+ await run("theme retro");
97
+ const lines = await run("theme bogus");
98
+ assert.ok(lines.some((l) => l.includes("unknown theme")));
99
+ assert.equal(getGameState().theme, "retro");
100
+ });
101
+
102
+ it("theme next cycles to the next theme and wraps", async () => {
103
+ await run(`theme ${THEME_IDS[0]}`);
104
+ await run("theme next");
105
+ assert.equal(getGameState().theme, THEME_IDS[1]);
106
+ // cycle to the end then wrap
107
+ await run(`theme ${THEME_IDS[THEME_IDS.length - 1]!}`);
108
+ await run("theme next");
109
+ assert.equal(getGameState().theme, THEME_IDS[0]);
110
+ });
111
+
112
+ it("theme (bare) lists all themes", async () => {
113
+ const lines = await run("theme");
114
+ for (const id of THEME_IDS) {
115
+ assert.ok(lines.some((l) => l.includes(id)), `lists ${id}`);
116
+ }
117
+ });
118
+
119
+ it("tui full|minimal sets display mode and persists", async () => {
120
+ await run("tui minimal");
121
+ assert.equal(getGameState().tui_display_mode, "minimal");
122
+ await run("tui full");
123
+ assert.equal(getGameState().tui_display_mode, "full");
124
+ });
125
+
126
+ it("tui <bad> prints usage and does not mutate", async () => {
127
+ await run("tui minimal");
128
+ const lines = await run("tui huge");
129
+ assert.ok(lines.some((l) => l.includes("usage")));
130
+ assert.equal(getGameState().tui_display_mode, "minimal");
131
+ });
132
+
133
+ it("unknown subcommand prints usage", async () => {
134
+ const lines = await run("bogus");
135
+ assert.ok(lines.some((l) => l.includes("usage")));
136
+ });
137
+ });
@@ -0,0 +1,122 @@
1
+ /**
2
+ * mega-game-cmds.ts — /mega-game slash command (S30).
3
+ *
4
+ * Backs the game-mode toggle + theme picker + TUI display mode. All state is
5
+ * the global `game_state` SQLite row (src/store/sqlite/game-state.ts) — local
6
+ * only (PREVENT-PI-004: no network; no guardrails-allow needed because this
7
+ * command touches no fetch/http). All SQL is parameterized (PREVENT-002) and
8
+ * lives in the src/ submodule, not here.
9
+ *
10
+ * Usage:
11
+ * /mega-game print current state
12
+ * /mega-game on enable game mode (scoring + level-up + MEGA CACHE)
13
+ * /mega-game off disable game mode
14
+ * /mega-game theme list available themes
15
+ * /mega-game theme <id> set theme by id
16
+ * /mega-game theme next cycle to next theme
17
+ * /mega-game tui full full TUI widget (bars, stats, flair)
18
+ * /mega-game tui minimal one-line TUI widget (level + cache %)
19
+ * /mega-game achievements list unlocked achievements
20
+ */
21
+
22
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
23
+ import type { MegaRuntime } from "./mega-runtime.js";
24
+ import {
25
+ getGameState,
26
+ setGameState,
27
+ type GameState,
28
+ } from "../src/store/sqlite.js";
29
+ import { listAchievements } from "../src/store/sqlite/game-achievements.js";
30
+ import { THEMES, THEME_IDS, getTheme, isValidTheme, nextTheme, DEFAULT_THEME } from "../src/config/themes.js";
31
+
32
+ /** Format the current state as a human-readable status line set. */
33
+ function fmtState(s: GameState): string[] {
34
+ return [
35
+ `[mega-game] game mode: ${s.game_mode_on ? "ON" : "off"}`,
36
+ ` theme: ${s.theme}${s.theme === DEFAULT_THEME ? " (default)" : ""}`,
37
+ ` tui: ${s.tui_display_mode}`,
38
+ ];
39
+ }
40
+
41
+ /** Register the /mega-game command. */
42
+ export function registerGameCommands(pi: ExtensionAPI, runtime: MegaRuntime): void {
43
+ pi.registerCommand("mega-game", {
44
+ description:
45
+ "Game mode toggle + theme picker + TUI display mode. Usage: /mega-game [on|off|theme [id|next]|tui [full|minimal]|achievements]",
46
+ handler: async (args: string, ctx: ExtensionContext) => {
47
+ runtime.bindRepo(ctx.cwd);
48
+ const stateDir = runtime.currentStateDir;
49
+ const parts = args.trim().split(/\s+/).filter(Boolean);
50
+
51
+ // /mega-game → print current state.
52
+ if (parts.length === 0) {
53
+ const s = getGameState(stateDir);
54
+ for (const line of fmtState(s)) ctx.ui.notify(line);
55
+ return;
56
+ }
57
+
58
+ const sub = parts[0]!;
59
+
60
+ // /mega-game achievements — terse list of unlocked (hidden only once unlocked).
61
+ if (sub === "achievements") {
62
+ const rows = listAchievements(stateDir).filter((r) => r.unlocked_at != null);
63
+ ctx.ui.notify(`[mega-game] achievements unlocked (${rows.length}/9):`);
64
+ for (const r of rows) {
65
+ ctx.ui.notify(` ${r.icon ?? ""} ${r.title}`);
66
+ }
67
+ return;
68
+ }
69
+
70
+ // /mega-game on|off
71
+ if (sub === "on" || sub === "off") {
72
+ const s = setGameState({ game_mode_on: sub === "on" }, stateDir);
73
+ runtime.bumpGameState();
74
+ ctx.ui.notify(`[mega-game] game mode ${s.game_mode_on ? "ON" : "off"}`);
75
+ return;
76
+ }
77
+
78
+ // /mega-game theme [id|next]
79
+ if (sub === "theme") {
80
+ if (parts.length === 1) {
81
+ // list themes
82
+ ctx.ui.notify("[mega-game] themes:");
83
+ for (const t of THEMES) {
84
+ ctx.ui.notify(` ${t.id.padEnd(14)} ${t.label}`);
85
+ }
86
+ return;
87
+ }
88
+ const arg = parts[1]!;
89
+ let id: string;
90
+ if (arg === "next") {
91
+ id = nextTheme(getGameState(stateDir).theme);
92
+ } else if (isValidTheme(arg)) {
93
+ id = arg;
94
+ } else {
95
+ ctx.ui.notify(`[mega-game] unknown theme "${arg}". Valid: ${THEME_IDS.join(", ")}`);
96
+ return;
97
+ }
98
+ const s = setGameState({ theme: id }, stateDir);
99
+ runtime.bumpGameState();
100
+ ctx.ui.notify(`[mega-game] theme → ${s.theme} (${getTheme(s.theme)?.label ?? ""})`);
101
+ return;
102
+ }
103
+
104
+ // /mega-game tui full|minimal
105
+ if (sub === "tui") {
106
+ const arg = parts[1];
107
+ if (arg !== "full" && arg !== "minimal") {
108
+ ctx.ui.notify(`[mega-game] usage: /mega-game tui full|minimal`);
109
+ return;
110
+ }
111
+ const s = setGameState({ tui_display_mode: arg }, stateDir);
112
+ runtime.bumpGameState();
113
+ ctx.ui.notify(`[mega-game] tui → ${s.tui_display_mode}`);
114
+ return;
115
+ }
116
+
117
+ ctx.ui.notify(
118
+ `[mega-game] usage: /mega-game [on|off|theme [id|next]|tui [full|minimal]|achievements]`,
119
+ );
120
+ },
121
+ });
122
+ }
@@ -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
+
18
+ const require = createRequire(import.meta.url);
19
+ // Require the compiled JS (build output) so ESM import of pi-tui etc. resolves.
20
+ const { MegaRuntime } = require("./state.js") as {
21
+ MegaRuntime: new (config: any) => any;
22
+ };
23
+
24
+ /** Minimal MegaConfig — enough fields for the constructor; the snapshot path
25
+ * isn't exercised here, only getCachedGameState/bumpGameState. */
26
+ function minimalConfig(stateDir: string): any {
27
+ return {
28
+ tier: "custom",
29
+ tierPct: null,
30
+ thresholdTokens: 100_000,
31
+ stateDir,
32
+ fastGatePct: 70,
33
+ anchorUserMessages: 3,
34
+ preserveRecent: 4,
35
+ preserveRecentMin: 2,
36
+ auto: false,
37
+ autoInline: false,
38
+ autoContinueLengthStop: false,
39
+ autoPctTrigger: null,
40
+ dedupSim: 0.9,
41
+ raptorEnabled: false,
42
+ legacyDurableTrim: false,
43
+ dbMirror: false,
44
+ crossRepoEnabled: false,
45
+ crossRepoCosine: 0.9,
46
+ memoryAutoReview: false,
47
+ memoryReviewInterval: 10,
48
+ recallMaxTokens: 1500,
49
+ windowDedupe: false,
50
+ debug: false,
51
+ };
52
+ }
53
+
54
+ /** Fresh isolated state dir per test — the game_state row is global and
55
+ * persists across cases in a shared dir, so each case gets its own mkdtemp to
56
+ * avoid cross-test contamination. */
57
+ function freshDir(): string {
58
+ return mkdtempSync(join(tmpdir(), "mc-state-"));
59
+ }
60
+
61
+ describe("MegaRuntime game-state cache (S31)", () => {
62
+ const dirs: string[] = [];
63
+ after(() => {
64
+ for (const d of dirs) {
65
+ try { closeStore(d); } catch { /* */ }
66
+ }
67
+ delete process.env.MEGACOMPACT_STATE_DIR;
68
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
69
+ });
70
+
71
+ it("getCachedGameState returns defaults on a fresh install", () => {
72
+ const dir = freshDir(); dirs.push(dir);
73
+ process.env.MEGACOMPACT_STATE_DIR = dir;
74
+ const rt = new MegaRuntime(minimalConfig(dir));
75
+ const gs = rt.getCachedGameState();
76
+ assert.deepEqual(gs, { ...DEFAULT_GAME_STATE });
77
+ });
78
+
79
+ it("getCachedGameState memoizes (same ref across calls)", () => {
80
+ const dir = freshDir(); dirs.push(dir);
81
+ process.env.MEGACOMPACT_STATE_DIR = dir;
82
+ const rt = new MegaRuntime(minimalConfig(dir));
83
+ const a = rt.getCachedGameState();
84
+ const b = rt.getCachedGameState();
85
+ assert.equal(a, b, "memoized — same object ref");
86
+ });
87
+
88
+ it("bumpGameState evicts so the next read reflects a setGameState write", () => {
89
+ const dir = freshDir(); dirs.push(dir);
90
+ process.env.MEGACOMPACT_STATE_DIR = dir;
91
+ const rt = new MegaRuntime(minimalConfig(dir));
92
+ const before = rt.getCachedGameState();
93
+ assert.equal(before.game_mode_on, false);
94
+
95
+ // Write out-of-band (as /mega-game would).
96
+ setGameState({ game_mode_on: true, theme: "retro", tui_display_mode: "minimal" }, dir);
97
+
98
+ // Without bump, the stale memo is returned.
99
+ const stale = rt.getCachedGameState();
100
+ assert.equal(stale.game_mode_on, false, "stale cache before bump");
101
+
102
+ // After bump, the next read re-queries and reflects the write.
103
+ rt.bumpGameState();
104
+ const fresh = rt.getCachedGameState();
105
+ assert.equal(fresh.game_mode_on, true);
106
+ assert.equal(fresh.theme, "retro");
107
+ assert.equal(fresh.tui_display_mode, "minimal");
108
+ // And matches the authoritative getGameState read.
109
+ assert.deepEqual(fresh, getGameState(dir));
110
+ });
111
+
112
+ it("bumpGameState is idempotent (safe to call when cache is empty)", () => {
113
+ const dir = freshDir(); dirs.push(dir);
114
+ process.env.MEGACOMPACT_STATE_DIR = dir;
115
+ const rt = new MegaRuntime(minimalConfig(dir));
116
+ rt.bumpGameState(); // no cached state yet — must not throw
117
+ const gs = rt.getCachedGameState();
118
+ assert.deepEqual(gs, { ...DEFAULT_GAME_STATE });
119
+ });
120
+
121
+ it("bindRepo evicts cachedGameState so a repo switch reflects the new repo's game_state", () => {
122
+ // Two fresh git repos A and B simulate a real repo switch. Each holds its
123
+ // own per-repo state dir at <root>/.pi/mega-compact (what repoStateDir
124
+ // returns for a git cwd), and each holds its own game_state row, so a repo
125
+ // switch (bindRepo) must evict the cached memo or the widget shows A's
126
+ // theme/mode/toggle after moving to B. Uses MEGACOMPACT_STATE_DIR + mkdtemp
127
+ // + closeStore (G7); the global state dir stays separate.
128
+ const globalDir = freshDir(); dirs.push(globalDir);
129
+ const repoA = freshDir(); dirs.push(repoA);
130
+ const repoB = freshDir(); dirs.push(repoB);
131
+ const stateA = join(repoA, ".pi", "mega-compact");
132
+ const stateB = join(repoB, ".pi", "mega-compact");
133
+
134
+ // Make A and B real git roots so resolveRepoRoot(cwd) returns the root and
135
+ // repoStateDir produces <root>/.pi/mega-compact (the per-repo store).
136
+ execSync("git init -q", { cwd: repoA });
137
+ execSync("git init -q", { cwd: repoB });
138
+
139
+ // Seed A and B with distinct game_state rows in their per-repo dirs.
140
+ setGameState({ game_mode_on: true, theme: "retro", tui_display_mode: "minimal" }, stateA);
141
+ setGameState({ game_mode_on: false, theme: "cyan-neon", tui_display_mode: "full" }, stateB);
142
+
143
+ // Construct the runtime against the GLOBAL dir (the non-git fallback so a
144
+ // real bindRepo switch occurs once we point it at a git root).
145
+ process.env.MEGACOMPACT_STATE_DIR = globalDir;
146
+ const rt = new MegaRuntime(minimalConfig(globalDir));
147
+
148
+ // Point the runtime at repo A and prime the cache.
149
+ rt.bindRepo(repoA);
150
+ assert.equal(rt.currentStateDir, stateA, "bindRepo(A) switched to A's per-repo dir");
151
+ const a = rt.getCachedGameState();
152
+ assert.equal(a.game_mode_on, true, "A: game_mode_on primed");
153
+ assert.equal(a.theme, "retro", "A: theme primed");
154
+ assert.equal(a.tui_display_mode, "minimal", "A: tui_display_mode primed");
155
+
156
+ // Switch to repo B: bindRepo must evict cachedGameState so the next read
157
+ // re-queries B's row instead of returning A's stale memo.
158
+ rt.bindRepo(repoB);
159
+ assert.equal(rt.currentStateDir, stateB, "bindRepo(B) switched to B's per-repo dir");
160
+ const b = rt.getCachedGameState();
161
+ assert.equal(b.game_mode_on, false, "B: game_mode_on after switch (not A's stale true)");
162
+ assert.equal(b.theme, "cyan-neon", "B: theme after switch (not A's stale retro)");
163
+ assert.equal(b.tui_display_mode, "full", "B: tui_display_mode after switch (not A's stale minimal)");
164
+ assert.deepEqual(b, getGameState(stateB), "B matches authoritative getGameState read");
165
+
166
+ // Cleanup the per-repo DB handles.
167
+ try { closeStore(globalDir); } catch { /* */ }
168
+ try { closeStore(stateA); } catch { /* */ }
169
+ try { closeStore(stateB); } catch { /* */ }
170
+ });
171
+ });
@@ -27,7 +27,9 @@ import {
27
27
  getCompactCount,
28
28
  getRecallInjected,
29
29
  getCacheHitTokensSaved,
30
+ getGameState,
30
31
  type ModelSnapshot,
32
+ type GameState,
31
33
  } from "../../src/store/sqlite.js";
32
34
  import { detectCrossRepoDrift } from "../../src/driftDetection.js";
33
35
  import {
@@ -54,6 +56,9 @@ import {
54
56
  type TickerEntry,
55
57
  type WidgetData,
56
58
  } from "./widget.js";
59
+ import { getTheme } from "../../src/config/themes.js";
60
+ import { watch, type FSWatcher } from "node:fs";
61
+ import { turnLevel } from "../../src/game/scoring.js";
57
62
 
58
63
  export class MegaRuntime {
59
64
  config: MegaConfig;
@@ -88,6 +93,22 @@ export class MegaRuntime {
88
93
  // Agent tracking for real-time widget updates
89
94
  activeAgents = 0;
90
95
  currentTurn = 0;
96
+ // S33: transient MEGA CACHE flare flag (armed by the turn_end scoring hook
97
+ // when cachePct > 100). Copied into widgetData.megaCacheFlare on the next
98
+ // snapshot() so the widget renders the oopsie gag, then reset (one cycle).
99
+ megaCacheFlare = false;
100
+ megaCacheFlarePct = 0;
101
+ levelUpFlare = false;
102
+ lastLevel = 0;
103
+ // S35: transient achievement-unlock flare (armed by the scoring hooks after
104
+ // evaluateAndUnlockAchievements returns newly-unlocked titles). Copied into
105
+ // widgetData.achievementFlare on the next snapshot() so the widget renders the
106
+ // unlock toast, then reset (one cycle — mirrors megaCacheFlare/levelUpFlare).
107
+ achievementFlare = false;
108
+ achievementFlareTitles: string[] = [];
109
+ // S33: last cumulative dedup-collapsed count seen by the session_compact
110
+ // hook, so we only record the DELTA as the dedupe score (leaderboard sums).
111
+ lastDedupCollapsed = 0;
91
112
  // Recall block produced by auto-inline (resume/branch) that the next
92
113
  // before_agent_start should prepend to the system prompt. Unset after use.
93
114
  pendingRecallBlock: string | undefined;
@@ -134,6 +155,23 @@ export class MegaRuntime {
134
155
  // Cached cross-repo drift status (recomputed at most every 30s — it opens the
135
156
  // machine-wide registry DB, so we don't want to do it on every render frame).
136
157
  private driftCache: { at: number; status: "ok" | "warn" } | null = null;
158
+ // S31: cached game-mode state (game_mode_on/theme/tui_display_mode). Lazily
159
+ // read from the game_state SQLite row on the first widget render, then
160
+ // memoized until bumpGameState() evicts it (called by /mega-game after a
161
+ // write) so the widget picks up theme/mode/level changes live without
162
+ // re-querying the DB on every render frame.
163
+ private cachedGameState: GameState | undefined;
164
+ // S32: fs.watch on the current repo's sqlite.db so cross-process writes
165
+ // (e.g. the dashboard server's PUT /api/game-state, which runs as a detached
166
+ // child with no MegaRuntime ref) evict the cached game-state memo. Without
167
+ // this, /mega-game's in-process bumpGameState() is the only eviction trigger
168
+ // and the widget would keep showing stale theme/mode/toggle after a dashboard
169
+ // edit until a restart. The watcher tracks currentStateDir — closed + re-opened
170
+ // by ensureGameStateWatcher() on every bindRepo repo switch. Non-fatal: any
171
+ // fs.watch failure (missing file / platform issue) is swallowed; the next
172
+ // getCachedGameState() snapshot re-queries the DB anyway.
173
+ private gameStateWatcher?: FSWatcher;
174
+ private gameStateWatchDir?: string;
137
175
 
138
176
  /**
139
177
  * DIAG counters for the "team run doesn't relieve context" investigation.
@@ -235,6 +273,7 @@ export class MegaRuntime {
235
273
  });
236
274
  this.dashboard = new Dashboard(config.stateDir);
237
275
  this.currentStateDir = config.stateDir;
276
+ this.ensureGameStateWatcher();
238
277
  }
239
278
 
240
279
  // ---- per-repo binding -----------------------------------------------------
@@ -252,6 +291,15 @@ export class MegaRuntime {
252
291
  if (key === this.activeRepoRoot) return dir;
253
292
  this.activeRepoRoot = key;
254
293
  this.currentStateDir = dir;
294
+ // S31 audit P2: bindRepo switched currentStateDir but left cachedGameState
295
+ // memoized -> the widget kept showing the previous repo's theme/mode/toggle
296
+ // until /mega-game or a restart. The game_state row is per-repo (per
297
+ // stateDir), so evict the memo on every repo switch; the next widget render
298
+ // re-queries lazily via getCachedGameState().
299
+ this.cachedGameState = undefined;
300
+ // S32: re-target the fs.watch cache-eviction watcher at the NEW stateDir's
301
+ // sqlite.db so cross-process writes (dashboard server) still evict the memo.
302
+ this.ensureGameStateWatcher();
255
303
  this.store = new VectorStore({
256
304
  dedupSim: this.config.dedupSim,
257
305
  stateDir: dir,
@@ -520,6 +568,15 @@ export class MegaRuntime {
520
568
  const driftStatus = this.driftStatus();
521
569
  const agentsActive = this.activeAgents > 0;
522
570
 
571
+ // S31: game-mode state for the widget (theme/mode/level + MEGA CACHE).
572
+ // Pulled from the cached game_state row; cachePct is the REAL dedup hit
573
+ // rate (may exceed 100% — that's the MEGA CACHE trigger). megaCacheFlare
574
+ // is false for now (S33.4 scoring hook arms it when cachePct > 100).
575
+ const gs = this.getCachedGameState();
576
+ // S34: derive the level-up flare from the turn count each snapshot.
577
+ const curLevel = this.getTurnLevel();
578
+ if (curLevel > this.lastLevel) this.levelUpFlare = true;
579
+ const cachePct = st.dedupHitRate * 100;
523
580
  this.widgetData = {
524
581
  version: ownVersion(),
525
582
  tierLabel,
@@ -551,7 +608,31 @@ export class MegaRuntime {
551
608
  lastWhy: this.lastWhy,
552
609
  tierTrace: this.tierTrace,
553
610
  pulsing: this.pulsing,
611
+ // S31 game-mode fields:
612
+ gameMode: gs.game_mode_on,
613
+ theme: getTheme(gs.theme) ? gs.theme : "transparent",
614
+ tuiMode: gs.tui_display_mode,
615
+ level: this.getTurnLevel(),
616
+ cachePct,
617
+ megaCacheFlare: this.megaCacheFlare,
618
+ megaCacheFlarePct: this.megaCacheFlarePct,
619
+ levelUpFlare: this.levelUpFlare,
620
+ achievementFlare: this.achievementFlare,
621
+ achievementFlareTitles: this.achievementFlareTitles,
554
622
  };
623
+ // S33: consume the flare after copying it into widgetData so it fires
624
+ // for exactly one render cycle (the gag flares once, then clears).
625
+ this.megaCacheFlare = false;
626
+ this.megaCacheFlarePct = 0;
627
+
628
+ // S34: consume the level-up flare after one render cycle (mirrors the
629
+ // megaCacheFlare one-shot semantics), and advance lastLevel.
630
+ this.levelUpFlare = false;
631
+ this.lastLevel = curLevel;
632
+ // S35: consume the achievement-unlock flare after one render cycle
633
+ // (mirrors the megaCacheFlare/levelUpFlare one-shot semantics).
634
+ this.achievementFlare = false;
635
+ this.achievementFlareTitles = [];
555
636
  // Auto-fit: register a factory so pi re-renders the panel at the REAL
556
637
  // terminal width every frame (tui.columns), instead of guessing with
557
638
  // process.stdout.columns. buildWidgetLines reads this.widgetData live.
@@ -638,6 +719,10 @@ export class MegaRuntime {
638
719
  this.pulsing = false;
639
720
  this.savedGoal = 50_000;
640
721
  this.lastWhy = undefined;
722
+ // S31 audit P2: symmetry with bindRepo — a reset can coincide with a context
723
+ // that re-binds the repo, so drop the memo too. Cheap; the next
724
+ // getCachedGameState() re-queries lazily.
725
+ this.cachedGameState = undefined;
641
726
  }
642
727
 
643
728
  /**
@@ -745,6 +830,91 @@ export class MegaRuntime {
745
830
  return this.currentStateDir;
746
831
  }
747
832
 
833
+ /** S32: (re)target the fs.watch cache-eviction watcher at the current
834
+ * stateDir's sqlite.db. Called from the constructor + every bindRepo repo
835
+ * switch so the watcher always tracks the NEW repo's db file. If a watcher
836
+ * already exists for this dir, no-op; if the dir changed, close the old one
837
+ * first. fs.watch can throw on a missing file / platform issues — wrapped
838
+ * non-fatal; the next getCachedGameState() re-queries the DB anyway. */
839
+ private ensureGameStateWatcher(): void {
840
+ if (this.gameStateWatcher && this.gameStateWatchDir === this.currentStateDir) {
841
+ return;
842
+ }
843
+ if (this.gameStateWatcher) {
844
+ try { this.gameStateWatcher.close(); } catch { /* non-fatal */ }
845
+ this.gameStateWatcher = undefined;
846
+ this.gameStateWatchDir = undefined;
847
+ }
848
+ try {
849
+ this.gameStateWatcher = watch(
850
+ join(this.currentStateDir, "sqlite.db"),
851
+ () => { this.cachedGameState = undefined; },
852
+ );
853
+ this.gameStateWatchDir = this.currentStateDir;
854
+ } catch {
855
+ /* non-fatal: missing file / platform issue — next snapshot re-queries */
856
+ }
857
+ }
858
+
859
+ /** S32: release the fs.watch game-state watcher. Called when the runtime is
860
+ * torn down (no existing dispose path — the process exit reclaims the fd,
861
+ * but explicit close is correct for any in-process reload / test reuse). */
862
+ dispose(): void {
863
+ if (this.gameStateWatcher) {
864
+ try { this.gameStateWatcher.close(); } catch { /* non-fatal */ }
865
+ this.gameStateWatcher = undefined;
866
+ this.gameStateWatchDir = undefined;
867
+ }
868
+ }
869
+
870
+ /** S31: the cached game-mode state (game_mode_on/theme/tui_display_mode).
871
+ * Lazily read from the game_state SQLite row on the first call, then
872
+ * memoized until `bumpGameState()` evicts it. Reading is non-throwing
873
+ * (getGameState returns DEFAULT_GAME_STATE on any error), so the widget
874
+ * can call this on every render safely. */
875
+ getCachedGameState(): GameState {
876
+ if (!this.cachedGameState) {
877
+ try {
878
+ this.cachedGameState = getGameState(this.currentStateDir);
879
+ } catch {
880
+ this.cachedGameState = {
881
+ game_mode_on: false,
882
+ theme: "transparent",
883
+ tui_display_mode: "full",
884
+ };
885
+ }
886
+ }
887
+ return this.cachedGameState;
888
+ }
889
+
890
+ /** S31: evict the cached game-mode state so the next widget render re-reads
891
+ * the game_state row. Called by /mega-game after every setGameState() so
892
+ * the panel picks up theme/mode/toggle changes live. */
893
+ bumpGameState(): void {
894
+ this.cachedGameState = undefined;
895
+ }
896
+
897
+ /** S33: player level for game mode — floor(log2(turns+1))+1 (gentle).
898
+ * Defensive: non-finite/negative collapses to 1 (never NaN). */
899
+ private getTurnLevel(): number {
900
+ return turnLevel(this.currentTurn);
901
+ }
902
+
903
+ /** S33: arm the transient MEGA CACHE flare so the next snapshot() copies it
904
+ * into widgetData and the widget renders the oopsie gag for one cycle. */
905
+ armMegaCacheFlare(peakPct: number): void {
906
+ this.megaCacheFlare = true;
907
+ this.megaCacheFlarePct = peakPct;
908
+ }
909
+
910
+ /** S35: arm the transient achievement-unlock flare with the newly-unlocked
911
+ * titles so the next snapshot() copies them into widgetData and the widget
912
+ * renders the one-time unlock toast for one render cycle. */
913
+ armAchievementFlare(titles: string[]): void {
914
+ this.achievementFlare = true;
915
+ this.achievementFlareTitles = titles;
916
+ }
917
+
748
918
  /** Build the sync onTier callback that paints the live per-tier trace. */
749
919
  makeTierCallback(
750
920
  ctx: ExtensionContext,