pi-mega-compact 0.7.9 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/extensions/dashboard-server/html.js +333 -66
  2. package/dist/extensions/dashboard-server/html.test.js +41 -0
  3. package/dist/extensions/dashboard-server/server.js +170 -4
  4. package/dist/extensions/dashboard-server/server.test.js +120 -0
  5. package/dist/extensions/dashboard-server-s32.test.js +181 -0
  6. package/dist/extensions/mega-compact.js +3 -0
  7. package/dist/extensions/mega-events/agent-handlers.js +49 -0
  8. package/dist/extensions/mega-events/compact-handlers.js +29 -0
  9. package/dist/extensions/mega-events/context-handler.js +5 -3
  10. package/dist/extensions/mega-game-cmds.js +119 -0
  11. package/dist/extensions/mega-game-cmds.test.js +118 -0
  12. package/dist/extensions/mega-runtime/state.js +181 -1
  13. package/dist/extensions/mega-runtime/state.test.js +171 -0
  14. package/dist/extensions/mega-runtime/widget.js +93 -20
  15. package/dist/extensions/mega-runtime/widget.test.js +160 -0
  16. package/dist/src/config/themes.js +84 -0
  17. package/dist/src/config/themes.test.js +94 -0
  18. package/dist/src/game/scoring.js +105 -0
  19. package/dist/src/game/scoring.test.js +98 -0
  20. package/dist/src/store/sqlite/game-achievements.js +111 -0
  21. package/dist/src/store/sqlite/game-achievements.test.js +67 -0
  22. package/dist/src/store/sqlite/game-scores.js +105 -0
  23. package/dist/src/store/sqlite/game-scores.test.js +106 -0
  24. package/dist/src/store/sqlite/game-state.js +54 -0
  25. package/dist/src/store/sqlite/game-state.test.js +76 -0
  26. package/dist/src/store/sqlite/schema.js +44 -0
  27. package/dist/src/store/sqlite.js +3 -0
  28. package/extensions/dashboard-server/html.test.ts +50 -0
  29. package/extensions/dashboard-server/html.ts +334 -66
  30. package/extensions/dashboard-server/server.test.ts +131 -0
  31. package/extensions/dashboard-server/server.ts +157 -4
  32. package/extensions/dashboard-server-s32.test.ts +195 -0
  33. package/extensions/mega-compact.ts +3 -0
  34. package/extensions/mega-events/agent-handlers.ts +48 -0
  35. package/extensions/mega-events/compact-handlers.ts +28 -0
  36. package/extensions/mega-events/context-handler.ts +4 -2
  37. package/extensions/mega-game-cmds.test.ts +143 -0
  38. package/extensions/mega-game-cmds.ts +142 -0
  39. package/extensions/mega-runtime/state.test.ts +171 -0
  40. package/extensions/mega-runtime/state.ts +184 -0
  41. package/extensions/mega-runtime/widget.test.ts +185 -0
  42. package/extensions/mega-runtime/widget.ts +119 -18
  43. package/package.json +1 -1
  44. package/src/config/themes.test.ts +116 -0
  45. package/src/config/themes.ts +124 -0
  46. package/src/game/scoring.test.ts +103 -0
  47. package/src/game/scoring.ts +158 -0
  48. package/src/store/sqlite/game-achievements.test.ts +80 -0
  49. package/src/store/sqlite/game-achievements.ts +147 -0
  50. package/src/store/sqlite/game-scores.test.ts +132 -0
  51. package/src/store/sqlite/game-scores.ts +168 -0
  52. package/src/store/sqlite/game-state.test.ts +89 -0
  53. package/src/store/sqlite/game-state.ts +87 -0
  54. package/src/store/sqlite/schema.ts +47 -0
  55. package/src/store/sqlite.ts +3 -0
  56. package/dist/extensions/dashboard-server/helpers.js +0 -37
  57. package/dist/extensions/dashboard-server/html/all-repos-tab.js +0 -26
  58. package/dist/extensions/dashboard-server/html/body-open.js +0 -23
  59. package/dist/extensions/dashboard-server/html/current-repo-tab.js +0 -130
  60. package/dist/extensions/dashboard-server/html/head-open.js +0 -16
  61. package/dist/extensions/dashboard-server/html/high-score-tab.js +0 -25
  62. package/dist/extensions/dashboard-server/html/repo-detail-modal.js +0 -26
  63. package/dist/extensions/dashboard-server/html/script.js +0 -259
  64. package/dist/extensions/dashboard-server/html/styles.js +0 -103
  65. package/dist/extensions/dashboard-server/html/summary-tab.js +0 -19
  66. package/dist/extensions/dashboard-server/html-template.js +0 -41
  67. package/dist/src/store/sqlite/connection.js +0 -35
  68. package/dist/src/store/sqlite/index-store.js +0 -167
  69. package/dist/src/store/sqlite/memory.js +0 -54
  70. package/dist/src/store/sqlite/minhash-lsh.js +0 -47
  71. package/dist/src/store/sqlite/sessions.js +0 -39
  72. package/dist/src/store/sqlite/transaction.js +0 -19
  73. package/dist/src/vectorStore/add.js +0 -260
  74. package/dist/src/vectorStore/dedup.js +0 -52
  75. package/dist/src/vectorStore/index.js +0 -10
  76. package/dist/src/vectorStore/queries.js +0 -83
  77. package/dist/src/vectorStore/search.js +0 -95
  78. package/dist/src/vectorStore/session.js +0 -19
  79. package/dist/src/vectorStore/store.js +0 -105
  80. package/dist/src/vectorStore/types.js +0 -6
  81. package/dist/src/vectorStore/utils.js +0 -23
@@ -0,0 +1,143 @@
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-compact-settings (S30; /mega-game alias)", () => {
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("registers /mega-compact-settings as primary + /mega-game as alias", async () => {
71
+ const h = makeHarness(dir);
72
+ assert.ok(h.commands["mega-compact-settings"], "primary registered");
73
+ assert.ok(h.commands["mega-game"], "alias registered");
74
+ });
75
+
76
+ it("bare command prints current (default) state", async () => {
77
+ const lines = await run("");
78
+ assert.ok(lines.some((l) => l.includes("game mode: off")));
79
+ assert.ok(lines.some((l) => l.includes("transparent")));
80
+ assert.ok(lines.some((l) => l.includes("tui:")));
81
+ });
82
+
83
+ it("on enables game mode and persists", async () => {
84
+ await run("on");
85
+ assert.equal(getGameState().game_mode_on, true);
86
+ });
87
+
88
+ it("off disables game mode and persists", async () => {
89
+ await run("on");
90
+ await run("off");
91
+ assert.equal(getGameState().game_mode_on, false);
92
+ });
93
+
94
+ it("theme <id> sets a valid theme and persists", async () => {
95
+ await run("theme retro");
96
+ assert.equal(getGameState().theme, "retro");
97
+ await run("theme cyan-neon");
98
+ assert.equal(getGameState().theme, "cyan-neon");
99
+ });
100
+
101
+ it("theme <unknown> is rejected with a usage line and does not mutate", async () => {
102
+ await run("theme retro");
103
+ const lines = await run("theme bogus");
104
+ assert.ok(lines.some((l) => l.includes("unknown theme")));
105
+ assert.equal(getGameState().theme, "retro");
106
+ });
107
+
108
+ it("theme next cycles to the next theme and wraps", async () => {
109
+ await run(`theme ${THEME_IDS[0]}`);
110
+ await run("theme next");
111
+ assert.equal(getGameState().theme, THEME_IDS[1]);
112
+ // cycle to the end then wrap
113
+ await run(`theme ${THEME_IDS[THEME_IDS.length - 1]!}`);
114
+ await run("theme next");
115
+ assert.equal(getGameState().theme, THEME_IDS[0]);
116
+ });
117
+
118
+ it("theme (bare) lists all themes", async () => {
119
+ const lines = await run("theme");
120
+ for (const id of THEME_IDS) {
121
+ assert.ok(lines.some((l) => l.includes(id)), `lists ${id}`);
122
+ }
123
+ });
124
+
125
+ it("tui full|minimal sets display mode and persists", async () => {
126
+ await run("tui minimal");
127
+ assert.equal(getGameState().tui_display_mode, "minimal");
128
+ await run("tui full");
129
+ assert.equal(getGameState().tui_display_mode, "full");
130
+ });
131
+
132
+ it("tui <bad> prints usage and does not mutate", async () => {
133
+ await run("tui minimal");
134
+ const lines = await run("tui huge");
135
+ assert.ok(lines.some((l) => l.includes("usage")));
136
+ assert.equal(getGameState().tui_display_mode, "minimal");
137
+ });
138
+
139
+ it("unknown subcommand prints usage", async () => {
140
+ const lines = await run("bogus");
141
+ assert.ok(lines.some((l) => l.includes("usage")));
142
+ });
143
+ });
@@ -0,0 +1,142 @@
1
+ /**
2
+ * mega-game-cmds.ts — /mega-compact-settings slash command (S30; renamed in v0.8.x).
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
+ * The primary command is /mega-compact-settings. /mega-game is retained as a
11
+ * backward-compat alias (same handler) so existing muscle memory + docs keep
12
+ * working.
13
+ *
14
+ * Usage:
15
+ * /mega-compact-settings print current state
16
+ * /mega-compact-settings on enable game mode (scoring + level-up + MEGA CACHE)
17
+ * /mega-compact-settings off disable game mode
18
+ * /mega-compact-settings theme list available themes
19
+ * /mega-compact-settings theme <id> set theme by id
20
+ * /mega-compact-settings theme next cycle to next theme
21
+ * /mega-compact-settings tui full full TUI widget (bars, stats, flair)
22
+ * /mega-compact-settings tui minimal one-line TUI widget (level + cache %)
23
+ * /mega-compact-settings achievements list unlocked achievements
24
+ */
25
+
26
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
27
+ import type { MegaRuntime } from "./mega-runtime.js";
28
+ import {
29
+ getGameState,
30
+ setGameState,
31
+ type GameState,
32
+ } from "../src/store/sqlite.js";
33
+ import { listAchievements } from "../src/store/sqlite/game-achievements.js";
34
+ import { THEMES, THEME_IDS, getTheme, isValidTheme, nextTheme, DEFAULT_THEME } from "../src/config/themes.js";
35
+
36
+ /** Notify/usage tag + command name. Primary surface is /mega-compact-settings. */
37
+ const TAG = "mega-compact-settings";
38
+
39
+ /** Format the current state as a human-readable status line set. */
40
+ function fmtState(s: GameState): string[] {
41
+ return [
42
+ `[${TAG}] game mode: ${s.game_mode_on ? "ON" : "off"}`,
43
+ ` theme: ${s.theme}${s.theme === DEFAULT_THEME ? " (default)" : ""}`,
44
+ ` tui: ${s.tui_display_mode}`,
45
+ ];
46
+ }
47
+
48
+ /** Shared handler for /mega-compact-settings (primary) + /mega-game (alias). */
49
+ async function handleSettings(
50
+ args: string,
51
+ ctx: ExtensionContext,
52
+ runtime: MegaRuntime,
53
+ ): Promise<void> {
54
+ runtime.bindRepo(ctx.cwd);
55
+ const stateDir = runtime.currentStateDir;
56
+ const parts = args.trim().split(/\s+/).filter(Boolean);
57
+
58
+ // bare → print current state.
59
+ if (parts.length === 0) {
60
+ const s = getGameState(stateDir);
61
+ for (const line of fmtState(s)) ctx.ui.notify(line);
62
+ return;
63
+ }
64
+
65
+ const sub = parts[0]!;
66
+
67
+ // achievements — terse list of unlocked (hidden only once unlocked).
68
+ if (sub === "achievements") {
69
+ const rows = listAchievements(stateDir).filter((r) => r.unlocked_at != null);
70
+ ctx.ui.notify(`[${TAG}] achievements unlocked (${rows.length}/9):`);
71
+ for (const r of rows) {
72
+ ctx.ui.notify(` ${r.icon ?? ""} ${r.title}`);
73
+ }
74
+ return;
75
+ }
76
+
77
+ // on|off
78
+ if (sub === "on" || sub === "off") {
79
+ const s = setGameState({ game_mode_on: sub === "on" }, stateDir);
80
+ runtime.bumpGameState();
81
+ ctx.ui.notify(`[${TAG}] game mode ${s.game_mode_on ? "ON" : "off"}`);
82
+ return;
83
+ }
84
+
85
+ // theme [id|next]
86
+ if (sub === "theme") {
87
+ if (parts.length === 1) {
88
+ // list themes
89
+ ctx.ui.notify(`[${TAG}] themes:`);
90
+ for (const t of THEMES) {
91
+ ctx.ui.notify(` ${t.id.padEnd(14)} ${t.label}`);
92
+ }
93
+ return;
94
+ }
95
+ const arg = parts[1]!;
96
+ let id: string;
97
+ if (arg === "next") {
98
+ id = nextTheme(getGameState(stateDir).theme);
99
+ } else if (isValidTheme(arg)) {
100
+ id = arg;
101
+ } else {
102
+ ctx.ui.notify(`[${TAG}] unknown theme "${arg}". Valid: ${THEME_IDS.join(", ")}`);
103
+ return;
104
+ }
105
+ const s = setGameState({ theme: id }, stateDir);
106
+ runtime.bumpGameState();
107
+ ctx.ui.notify(`[${TAG}] theme → ${s.theme} (${getTheme(s.theme)?.label ?? ""})`);
108
+ return;
109
+ }
110
+
111
+ // tui full|minimal
112
+ if (sub === "tui") {
113
+ const arg = parts[1];
114
+ if (arg !== "full" && arg !== "minimal") {
115
+ ctx.ui.notify(`[${TAG}] usage: /${TAG} tui full|minimal`);
116
+ return;
117
+ }
118
+ const s = setGameState({ tui_display_mode: arg }, stateDir);
119
+ runtime.bumpGameState();
120
+ ctx.ui.notify(`[${TAG}] tui → ${s.tui_display_mode}`);
121
+ return;
122
+ }
123
+
124
+ ctx.ui.notify(
125
+ `[${TAG}] usage: /${TAG} [on|off|theme [id|next]|tui [full|minimal]|achievements]`,
126
+ );
127
+ }
128
+
129
+ /** Register /mega-compact-settings (primary) + /mega-game (backward-compat alias). */
130
+ export function registerGameCommands(pi: ExtensionAPI, runtime: MegaRuntime): void {
131
+ const description =
132
+ "Game mode toggle + theme picker + TUI display mode. Usage: /mega-compact-settings [on|off|theme [id|next]|tui [full|minimal]|achievements]";
133
+ const handler = (args: string, ctx: ExtensionContext) => handleSettings(args, ctx, runtime);
134
+
135
+ // Primary command (renamed in v0.8.x from /mega-game).
136
+ pi.registerCommand("mega-compact-settings", { description, handler });
137
+ // Backward-compat alias: /mega-game still resolves to the same settings UI.
138
+ pi.registerCommand("mega-game", {
139
+ description: "(alias for /mega-compact-settings) " + description,
140
+ handler,
141
+ });
142
+ }
@@ -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
+ });