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,131 @@
1
+ /**
2
+ * server.test.ts — S34 /api/game-scores endpoint (GET leaderboard, metric
3
+ * validation, method + limit handling). Mirrors the S32 /api/game-state
4
+ * spawn-and-fetch harness.
5
+ */
6
+ import { test, describe } from "node:test";
7
+ import assert from "node:assert/strict";
8
+ import { mkdtempSync, rmSync, readFileSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+ import { spawn } from "node:child_process";
12
+ import { recordScore } from "../../src/store/sqlite.js";
13
+
14
+ const SERVER_ENTRY = new URL("./server.js", import.meta.url).pathname;
15
+
16
+ function waitFor(cond: () => boolean | Promise<boolean>, timeoutMs = 6000): Promise<void> {
17
+ const start = Date.now();
18
+ return new Promise((resolve, reject) => {
19
+ const tick = async () => {
20
+ if (await cond()) return resolve();
21
+ if (Date.now() - start > timeoutMs) return reject(new Error("timeout"));
22
+ setTimeout(tick, 50);
23
+ };
24
+ tick();
25
+ });
26
+ }
27
+
28
+ function freshDir(prefix: string): string {
29
+ return mkdtempSync(join(tmpdir(), prefix));
30
+ }
31
+
32
+ async function withServer<T>(
33
+ port: string,
34
+ dir: string,
35
+ fn: (port: number) => Promise<T>,
36
+ ): Promise<T> {
37
+ process.env.MEGACOMPACT_DASHBOARD_PORT = port;
38
+ const child = spawn(process.execPath, [SERVER_ENTRY, dir], { stdio: "ignore" });
39
+ try {
40
+ await waitFor(async () => {
41
+ try {
42
+ const raw = JSON.parse(readFileSync(join(dir, "port.pid"), "utf-8"));
43
+ const res = await fetch(`http://localhost:${raw.port}/api/version`);
44
+ return res.ok;
45
+ } catch {
46
+ return false;
47
+ }
48
+ });
49
+ const raw = JSON.parse(readFileSync(join(dir, "port.pid"), "utf-8"));
50
+ return await fn(raw.port);
51
+ } finally {
52
+ child.kill("SIGTERM");
53
+ delete process.env.MEGACOMPACT_DASHBOARD_PORT;
54
+ rmSync(dir, { recursive: true, force: true });
55
+ }
56
+ }
57
+
58
+ describe("S34 /api/game-scores", () => {
59
+ test("GET ?metric=cache returns recorded rows as JSON array", async () => {
60
+ const dir = freshDir("dash-gs-cache-");
61
+ recordScore(dir, { repo_root: "/repo/a", metric: "cache", value: 42 });
62
+ await withServer("19430", dir, async (port) => {
63
+ const res = await fetch(`http://localhost:${port}/api/game-scores?metric=cache`);
64
+ assert.equal(res.status, 200);
65
+ const rows = (await res.json()) as Array<{ repo_root: string; value: number; ts: number }>;
66
+ assert.ok(Array.isArray(rows));
67
+ assert.equal(rows.length, 1);
68
+ assert.equal(rows[0].repo_root, "/repo/a");
69
+ assert.equal(rows[0].value, 42);
70
+ assert.ok(typeof rows[0].ts === "number");
71
+ });
72
+ });
73
+
74
+ test("unknown metric -> 400", async () => {
75
+ const dir = freshDir("dash-gs-bad-");
76
+ await withServer("19431", dir, async (port) => {
77
+ const res = await fetch(`http://localhost:${port}/api/game-scores?metric=bogus`);
78
+ assert.equal(res.status, 400);
79
+ });
80
+ });
81
+
82
+ test("non-GET (POST) -> 405", async () => {
83
+ const dir = freshDir("dash-gs-meth-");
84
+ await withServer("19432", dir, async (port) => {
85
+ const res = await fetch(`http://localhost:${port}/api/game-scores`, { method: "POST" });
86
+ assert.equal(res.status, 405);
87
+ });
88
+ });
89
+
90
+ test("limit clamp: 3 rows -> default 10 returns 3, limit=2 caps to 2, limit<=0 clamps to >=1", async () => {
91
+ const dir = freshDir("dash-gs-lim-");
92
+ recordScore(dir, { repo_root: "/repo/a", metric: "cache", value: 1 });
93
+ recordScore(dir, { repo_root: "/repo/b", metric: "cache", value: 2 });
94
+ recordScore(dir, { repo_root: "/repo/c", metric: "cache", value: 3 });
95
+ await withServer("19433", dir, async (port) => {
96
+ const all = (await fetch(`http://localhost:${port}/api/game-scores?metric=cache`).then((r) => r.json())) as unknown[];
97
+ assert.equal(all.length, 3);
98
+ const capped = (await fetch(`http://localhost:${port}/api/game-scores?metric=cache&limit=2`).then((r) => r.json())) as unknown[];
99
+ assert.equal(capped.length, 2);
100
+ const zero = (await fetch(`http://localhost:${port}/api/game-scores?metric=cache&limit=0`).then((r) => r.json())) as unknown[];
101
+ assert.ok(zero.length >= 1, "limit<=0 clamps to >=1 row");
102
+ });
103
+ });
104
+ });
105
+
106
+
107
+ describe("S35 /api/achievements", () => {
108
+ test("GET returns the 9 seeded achievement rows", async () => {
109
+ const dir = freshDir("dash-ach-");
110
+ await withServer("19434", dir, async (port) => {
111
+ const res = await fetch(`http://localhost:${port}/api/achievements`);
112
+ assert.equal(res.status, 200);
113
+ const rows = (await res.json()) as Array<{ id: string; title: string; hidden: number; unlocked_at: number | null }>;
114
+ assert.ok(Array.isArray(rows));
115
+ assert.equal(rows.length, 9);
116
+ const opie = rows.find((r) => r.id === "opie_wild_ride");
117
+ assert.ok(opie, "opie_wild_ride seeded");
118
+ assert.equal(opie!.hidden, 1);
119
+ assert.equal(opie!.unlocked_at, null);
120
+ assert.equal(rows.find((r) => r.id === "first_compact")!.title, "First Compact");
121
+ });
122
+ });
123
+
124
+ test("non-GET (POST) -> 405", async () => {
125
+ const dir = freshDir("dash-ach-meth-");
126
+ await withServer("19435", dir, async (port) => {
127
+ const res = await fetch(`http://localhost:${port}/api/achievements`, { method: "POST" });
128
+ assert.equal(res.status, 405);
129
+ });
130
+ });
131
+ });
@@ -14,6 +14,7 @@ import { readSnapshot, readFrom } from "./snapshot.js";
14
14
  import { dashboardHtml } from "./html.js";
15
15
  import { ACTIVE_WINDOW_SEC } from "./types.js";
16
16
  import type { IndexIndex, Snapshot, LiveSnapshot } from "./types.js";
17
+ import type { GameMetric } from "../../src/game/scoring.js";
17
18
 
18
19
  export async function launchDashboardServer(stateDir: string): Promise<{ port: number; url: string }> {
19
20
  // Our own package version — exposed at /api/version so the launcher can
@@ -21,10 +22,16 @@ export async function launchDashboardServer(stateDir: string): Promise<{ port: n
21
22
  // upgrade instead of reuse it.
22
23
  let SERVER_VERSION = "0.0.0";
23
24
  try {
24
- // dashboard-server.js lives at <pkg>/dist/extensions/, so package.json is
25
- // two levels up. Guard each candidate so a dev-checkout layout still works.
25
+ // Since v0.7.9 (8821ef3) dashboard-server.js lives at
26
+ // <pkg>/dist/extensions/dashboard-server/, so package.json is THREE levels
27
+ // up. Keep the two- and one-level-up candidates as fallbacks for flatter
28
+ // dev-checkout layouts. Guard each candidate so a missing file is skipped.
26
29
  const here = dirname(fileURLToPath(import.meta.url));
27
- const candidates = [join(here, "..", "..", "package.json"), join(here, "..", "package.json")];
30
+ const candidates = [
31
+ join(here, "..", "..", "..", "package.json"),
32
+ join(here, "..", "..", "package.json"),
33
+ join(here, "..", "package.json"),
34
+ ];
28
35
  for (const p of candidates) {
29
36
  if (!existsSync(p)) continue;
30
37
  const pkg = JSON.parse(readFileSync(p, "utf-8"));
@@ -115,7 +122,7 @@ export async function launchDashboardServer(stateDir: string): Promise<{ port: n
115
122
  // guardrails-allow PREVENT-PI-004: optional, user-triggered /dashboard localhost server (loopback-only) — CORS open for local browser access
116
123
  // CORS for local access
117
124
  res.setHeader("Access-Control-Allow-Origin", "*");
118
- res.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
125
+ res.setHeader("Access-Control-Allow-Methods", "GET, PUT, OPTIONS");
119
126
  res.setHeader("Access-Control-Allow-Headers", "Content-Type");
120
127
 
121
128
  if (req.method === "OPTIONS") {
@@ -285,6 +292,152 @@ export async function launchDashboardServer(stateDir: string): Promise<{ port: n
285
292
  return;
286
293
  }
287
294
 
295
+ // /api/game-state — S32 game-mode settings (game_mode_on / theme /
296
+ // tui_display_mode). GET returns the current row; PUT applies a partial
297
+ // patch (validated) and returns the post-write row. The dashboard server is
298
+ // a detached child with no MegaRuntime ref, so it reads/writes the
299
+ // game_state SQLite row directly; the in-process MegaRuntime picks up the
300
+ // change via its fs.watch cache-eviction watcher. PREVENT-PI-004: loopback.
301
+ if (req.url?.startsWith("/api/game-state")) {
302
+ const gsReq = createRequire(import.meta.url);
303
+ const { getGameState, setGameState } = gsReq("../../src/store/sqlite.js") as typeof import("../../src/store/sqlite.js");
304
+ const { isValidTheme } = gsReq("../../src/config/themes.js") as typeof import("../../src/config/themes.js");
305
+ if (req.method === "GET") {
306
+ try {
307
+ const gs = getGameState(stateDir); // guardrails-allow PREVENT-PI-004: local SQLite read (loopback dashboard)
308
+ res.writeHead(200, { "Content-Type": "application/json" });
309
+ res.end(JSON.stringify(gs));
310
+ } catch (e) {
311
+ res.writeHead(500, { "Content-Type": "application/json" });
312
+ res.end(JSON.stringify({ error: "game_state_unavailable", detail: String(e) }));
313
+ }
314
+ return;
315
+ }
316
+ if (req.method === "PUT") {
317
+ // Read + parse the JSON body (capped — the patch is tiny). The handler
318
+ // is sync, so drain the stream via data/end listeners then continue.
319
+ let body = "";
320
+ let tooBig = false;
321
+ req.on("data", (chunk: Buffer) => { // guardrails-allow PREVENT-PI-004: loopback dashboard request body (local)
322
+ if (body.length > 65536) { tooBig = true; return; }
323
+ body += chunk.toString();
324
+ });
325
+ req.on("end", () => {
326
+ if (tooBig) {
327
+ res.writeHead(413, { "Content-Type": "application/json" });
328
+ res.end(JSON.stringify({ error: "body_too_large" }));
329
+ return;
330
+ }
331
+ let patch: Record<string, unknown> = {};
332
+ try { patch = body ? JSON.parse(body) : {}; } catch {
333
+ res.writeHead(400, { "Content-Type": "application/json" });
334
+ res.end(JSON.stringify({ error: "invalid_json" }));
335
+ return;
336
+ }
337
+ // Reject valid-but-non-object JSON (null/[]/42) — dereferencing
338
+ // patch.game_mode_on would throw an unhandled TypeError inside this
339
+ // 'end' listener and crash the detached server (audit P1: loopback DoS).
340
+ if (typeof patch !== "object" || patch === null || Array.isArray(patch)) {
341
+ res.writeHead(400, { "Content-Type": "application/json" });
342
+ res.end(JSON.stringify({ error: "invalid_patch_object" }));
343
+ return;
344
+ }
345
+ // Validate the patch fields (unknown keys ignored; invalid values -> 400).
346
+ const clean: { game_mode_on?: boolean; theme?: string; tui_display_mode?: "full" | "minimal" } = {};
347
+ let bad = false;
348
+ if (patch.game_mode_on != null) {
349
+ if (typeof patch.game_mode_on !== "boolean") bad = true;
350
+ else clean.game_mode_on = patch.game_mode_on;
351
+ }
352
+ if (patch.theme != null) {
353
+ if (typeof patch.theme !== "string" || !isValidTheme(patch.theme)) bad = true;
354
+ else clean.theme = patch.theme;
355
+ }
356
+ if (patch.tui_display_mode != null) {
357
+ if (patch.tui_display_mode !== "full" && patch.tui_display_mode !== "minimal") bad = true;
358
+ else clean.tui_display_mode = patch.tui_display_mode;
359
+ }
360
+ if (bad) {
361
+ res.writeHead(400, { "Content-Type": "application/json" });
362
+ res.end(JSON.stringify({ error: "invalid_patch" }));
363
+ return;
364
+ }
365
+ try {
366
+ const gs = setGameState(clean, stateDir); // guardrails-allow PREVENT-PI-004: local SQLite write (loopback dashboard)
367
+ res.writeHead(200, { "Content-Type": "application/json" });
368
+ res.end(JSON.stringify(gs));
369
+ } catch (e) {
370
+ res.writeHead(500, { "Content-Type": "application/json" });
371
+ res.end(JSON.stringify({ error: "game_state_write_failed", detail: String(e) }));
372
+ }
373
+ });
374
+ return;
375
+ }
376
+ // Any other method on /api/game-state → 405.
377
+ res.writeHead(405, { "Content-Type": "application/json" }); // guardrails-allow PREVENT-PI-004: loopback dashboard response (local)
378
+ res.end(JSON.stringify({ error: "method_not_allowed" }));
379
+ return;
380
+ }
381
+
382
+ // /api/game-scores — S34 high-score leaderboards. GET returns the leaderboard
383
+ // for a metric (?metric=<m>&limit=<n>). `metric` is validated against the
384
+ // METRICS allow-list from src/game/scoring (re-exported via the sqlite barrel);
385
+ // default limit 10, clamped to [1,100]. The dashboard server is a detached
386
+ // child with no MegaRuntime ref, so it reads the game_scores SQLite table
387
+ // directly. Unknown metric -> 400, non-GET -> 405. PREVENT-PI-004: loopback.
388
+ if (req.url?.startsWith("/api/game-scores")) {
389
+ const gsReq = createRequire(import.meta.url);
390
+ const { leaderboard, METRICS } = gsReq("../../src/store/sqlite.js") as typeof import("../../src/store/sqlite.js");
391
+ if (req.method !== "GET") {
392
+ res.writeHead(405, { "Content-Type": "application/json" }); // guardrails-allow PREVENT-PI-004: loopback dashboard response (local)
393
+ res.end(JSON.stringify({ error: "method_not_allowed" }));
394
+ return;
395
+ }
396
+ try {
397
+ const url = new URL(req.url, "http://x"); // guardrails-allow PREVENT-PI-004: localhost dashboard URL base (loopback-only)
398
+ const metricParam = url.searchParams.get("metric") ?? "cache";
399
+ if (!(METRICS as readonly string[]).includes(metricParam)) {
400
+ res.writeHead(400, { "Content-Type": "application/json" }); // guardrails-allow PREVENT-PI-004: loopback dashboard response (local)
401
+ res.end(JSON.stringify({ error: "unknown_metric", metric: metricParam }));
402
+ return;
403
+ }
404
+ const metric = metricParam as GameMetric; // validated against METRICS above
405
+ let limit = Number(url.searchParams.get("limit") ?? "10");
406
+ if (!Number.isFinite(limit) || limit <= 0) limit = 10;
407
+ limit = Math.min(Math.max(limit, 1), 100); // clamp to [1,100]
408
+ const rows = leaderboard(stateDir, metric, { limit }); // guardrails-allow PREVENT-PI-004: local SQLite read (loopback dashboard)
409
+ res.writeHead(200, { "Content-Type": "application/json" });
410
+ res.end(JSON.stringify(rows));
411
+ } catch (e) {
412
+ res.writeHead(500, { "Content-Type": "application/json" });
413
+ res.end(JSON.stringify({ error: "game_scores_unavailable", detail: String(e) }));
414
+ }
415
+ return;
416
+ }
417
+
418
+ // /api/achievements — S35 achievement tiles. GET returns the 9 seeded rows
419
+ // {id,title,description,icon,hidden,unlocked_at}. The dashboard server is a
420
+ // detached child with no MegaRuntime ref, so it reads game_achievements via
421
+ // listAchievements(stateDir) directly. Non-GET -> 405. PREVENT-PI-004: loopback.
422
+ if (req.url?.startsWith("/api/achievements")) {
423
+ const achReq = createRequire(import.meta.url);
424
+ const { listAchievements } = achReq("../../src/store/sqlite.js") as typeof import("../../src/store/sqlite.js");
425
+ if (req.method !== "GET") {
426
+ res.writeHead(405, { "Content-Type": "application/json" }); // guardrails-allow PREVENT-PI-004: loopback dashboard response (local)
427
+ res.end(JSON.stringify({ error: "method_not_allowed" }));
428
+ return;
429
+ }
430
+ try {
431
+ const rows = listAchievements(stateDir); // guardrails-allow PREVENT-PI-004: local SQLite read (loopback dashboard)
432
+ res.writeHead(200, { "Content-Type": "application/json" });
433
+ res.end(JSON.stringify(rows));
434
+ } catch (e) {
435
+ res.writeHead(500, { "Content-Type": "application/json" });
436
+ res.end(JSON.stringify({ error: "achievements_unavailable", detail: String(e) }));
437
+ }
438
+ return;
439
+ }
440
+
288
441
  // Fallback — serve the dashboard
289
442
  const tier = readSnapshot(snapshotPath).tier;
290
443
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
@@ -0,0 +1,195 @@
1
+ /**
2
+ * dashboard-server.test.ts — S32 game-state API + settings strip tests.
3
+ *
4
+ * GET/PUT /api/game-state round-trips the game_state SQLite row through the
5
+ * real server subprocess (spawn + waitFor + fetch), and the HTML template
6
+ * carries the data-theme attribute + settings strip + theme CSS-var blocks.
7
+ */
8
+ import { test, describe } from "node:test";
9
+ import assert from "node:assert/strict";
10
+ import { mkdtempSync, rmSync, readFileSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { spawn } from "node:child_process";
14
+ import { dashboardHtml } from "./dashboard-server/html.js";
15
+ import { setGameState, getGameState } from "../src/store/sqlite.js";
16
+
17
+ const SERVER_ENTRY = new URL("./dashboard-server.js", import.meta.url).pathname;
18
+
19
+ function waitFor(cond: () => boolean | Promise<boolean>, timeoutMs = 6000): Promise<void> {
20
+ const start = Date.now();
21
+ return new Promise((resolve, reject) => {
22
+ const tick = async () => {
23
+ if (await cond()) return resolve();
24
+ if (Date.now() - start > timeoutMs) return reject(new Error("timeout"));
25
+ setTimeout(tick, 50);
26
+ };
27
+ tick();
28
+ });
29
+ }
30
+
31
+ function freshDir(prefix: string): string {
32
+ return mkdtempSync(join(tmpdir(), prefix));
33
+ }
34
+
35
+ async function withServer<T>(
36
+ port: string,
37
+ dir: string,
38
+ fn: (port: number) => Promise<T>,
39
+ ): Promise<T> {
40
+ process.env.MEGACOMPACT_DASHBOARD_PORT = port;
41
+ const child = spawn(process.execPath, [SERVER_ENTRY, dir], { stdio: "ignore" });
42
+ try {
43
+ await waitFor(async () => {
44
+ try {
45
+ const raw = JSON.parse(readFileSync(join(dir, "port.pid"), "utf-8"));
46
+ const res = await fetch(`http://localhost:${raw.port}/api/version`);
47
+ return res.ok;
48
+ } catch {
49
+ return false;
50
+ }
51
+ });
52
+ const raw = JSON.parse(readFileSync(join(dir, "port.pid"), "utf-8"));
53
+ return await fn(raw.port);
54
+ } finally {
55
+ child.kill("SIGTERM");
56
+ delete process.env.MEGACOMPACT_DASHBOARD_PORT;
57
+ rmSync(dir, { recursive: true, force: true });
58
+ }
59
+ }
60
+
61
+ describe("S32 /api/game-state", () => {
62
+ test("GET returns the current game_state row (seeded via setGameState)", async () => {
63
+ const dir = freshDir("dash-gs-get-");
64
+ setGameState({ game_mode_on: true, theme: "retro", tui_display_mode: "minimal" }, dir);
65
+ await withServer("19330", dir, async (port) => {
66
+ const gs = (await fetch(`http://localhost:${port}/api/game-state`).then((r) => r.json())) as {
67
+ game_mode_on: boolean; theme: string; tui_display_mode: string;
68
+ };
69
+ assert.equal(gs.game_mode_on, true);
70
+ assert.equal(gs.theme, "retro");
71
+ assert.equal(gs.tui_display_mode, "minimal");
72
+ });
73
+ });
74
+
75
+ test("PUT {theme:'retro'} -> 200 and getGameState(dir).theme === 'retro'", async () => {
76
+ const dir = freshDir("dash-gs-theme-");
77
+ await withServer("19331", dir, async (port) => {
78
+ const res = await fetch(`http://localhost:${port}/api/game-state`, {
79
+ method: "PUT",
80
+ headers: { "Content-Type": "application/json" },
81
+ body: JSON.stringify({ theme: "retro" }),
82
+ });
83
+ assert.equal(res.status, 200);
84
+ const body = (await res.json()) as { theme: string };
85
+ assert.equal(body.theme, "retro");
86
+ // And the authoritative DB read reflects the write.
87
+ assert.equal(getGameState(dir).theme, "retro");
88
+ });
89
+ });
90
+
91
+ test("PUT invalid theme 'bogus' -> 400 and row unchanged", async () => {
92
+ const dir = freshDir("dash-gs-invalid-");
93
+ setGameState({ theme: "orange-bold" }, dir);
94
+ const before = getGameState(dir).theme;
95
+ await withServer("19332", dir, async (port) => {
96
+ const res = await fetch(`http://localhost:${port}/api/game-state`, {
97
+ method: "PUT",
98
+ headers: { "Content-Type": "application/json" },
99
+ body: JSON.stringify({ theme: "bogus" }),
100
+ });
101
+ assert.equal(res.status, 400);
102
+ });
103
+ assert.equal(getGameState(dir).theme, before, "row unchanged after invalid PUT");
104
+ });
105
+
106
+ test("PUT body 'null' (valid-but-non-object JSON) -> 400, server stays up (audit P1)", async () => {
107
+ const dir = freshDir("dash-gs-nullobj-");
108
+ setGameState({ theme: "amber-mono" }, dir);
109
+ const before = getGameState(dir).theme;
110
+ await withServer("19335", dir, async (port) => {
111
+ // A valid-JSON-but-non-object body must NOT crash the detached server
112
+ // (audit P1: unhandled TypeError on patch.game_mode_on deref).
113
+ const res = await fetch(`http://localhost:${port}/api/game-state`, {
114
+ method: "PUT",
115
+ headers: { "Content-Type": "application/json" },
116
+ body: JSON.stringify(null),
117
+ });
118
+ assert.equal(res.status, 400, "non-object JSON -> 400, not a crash");
119
+ const body = (await res.json()) as { error: string };
120
+ assert.equal(body.error, "invalid_patch_object");
121
+ // Server must still be up — a follow-up GET must succeed.
122
+ const follow = await fetch(`http://localhost:${port}/api/game-state`);
123
+ assert.equal(follow.status, 200, "server survived the non-object PUT");
124
+ });
125
+ assert.equal(getGameState(dir).theme, before, "row unchanged after non-object PUT");
126
+ });
127
+
128
+ test("PUT body '[]' (array) -> 400, server stays up", async () => {
129
+ const dir = freshDir("dash-gs-arr-");
130
+ await withServer("19336", dir, async (port) => {
131
+ const res = await fetch(`http://localhost:${port}/api/game-state`, {
132
+ method: "PUT",
133
+ headers: { "Content-Type": "application/json" },
134
+ body: JSON.stringify([]),
135
+ });
136
+ assert.equal(res.status, 400);
137
+ const follow = await fetch(`http://localhost:${port}/api/game-state`);
138
+ assert.equal(follow.status, 200, "server survived the array PUT");
139
+ });
140
+ });
141
+
142
+ test("PUT {tui_display_mode:'minimal'} round-trips", async () => {
143
+ const dir = freshDir("dash-gs-tui-");
144
+ await withServer("19333", dir, async (port) => {
145
+ const res = await fetch(`http://localhost:${port}/api/game-state`, {
146
+ method: "PUT",
147
+ headers: { "Content-Type": "application/json" },
148
+ body: JSON.stringify({ tui_display_mode: "minimal" }),
149
+ });
150
+ assert.equal(res.status, 200);
151
+ const body = (await res.json()) as { tui_display_mode: string };
152
+ assert.equal(body.tui_display_mode, "minimal");
153
+ assert.equal(getGameState(dir).tui_display_mode, "minimal");
154
+ });
155
+ });
156
+
157
+ test("PUT {game_mode_on:true} round-trips", async () => {
158
+ const dir = freshDir("dash-gs-mode-");
159
+ await withServer("19334", dir, async (port) => {
160
+ const res = await fetch(`http://localhost:${port}/api/game-state`, {
161
+ method: "PUT",
162
+ headers: { "Content-Type": "application/json" },
163
+ body: JSON.stringify({ game_mode_on: true }),
164
+ });
165
+ assert.equal(res.status, 200);
166
+ const body = (await res.json()) as { game_mode_on: boolean };
167
+ assert.equal(body.game_mode_on, true);
168
+ assert.equal(getGameState(dir).game_mode_on, true);
169
+ });
170
+ });
171
+ });
172
+
173
+ describe("S32 dashboard HTML skin", () => {
174
+ test("carries data-theme on <html> + settings strip + theme CSS-var blocks", () => {
175
+ const html = dashboardHtml("custom");
176
+ // default transparent theme attribute on <html>
177
+ assert.match(html, /<html lang="en" data-theme="transparent">/);
178
+ // settings strip with the three controls
179
+ assert.match(html, /<div class="settings-strip">/);
180
+ assert.match(html, /id="set-game-mode"/);
181
+ assert.match(html, /id="set-theme"/);
182
+ assert.match(html, /id="set-tui-mode"/);
183
+ // all 6 theme ids appear as :root[data-theme="<id>"] override blocks
184
+ for (const id of ["transparent", "retro", "orange-bold", "cyan-neon", "amber-mono", "grayscale"]) {
185
+ assert.ok(html.includes(`:root[data-theme="${id}"]{`), `${id} data-theme block present`);
186
+ }
187
+ // core CSS vars defined in the base :root
188
+ assert.match(html, /--bg: #0d1117;/);
189
+ assert.match(html, /--fg: #c9d1d9;/);
190
+ assert.match(html, /--accent: #3fb950;/);
191
+ assert.match(html, /--mega: #f0883e;/);
192
+ // body uses the themed var (not a hardcoded hex)
193
+ assert.match(html, /body\s*\{[^}]*background: var\(--bg\)/);
194
+ });
195
+ });
@@ -18,6 +18,7 @@
18
18
  * - mega-runtime.ts shared live state (MegaRuntime) + widget + model capture
19
19
  * - mega-pipeline.ts runCompact (Trident+persist) + doRecall (Layer 5)
20
20
  * - mega-commands.ts data/inspection slash commands
21
+ * - mega-game-cmds.ts /mega-compact-settings (+ /mega-game alias) toggle + theme + TUI display mode
21
22
  * - mega-dashboard-cmds.ts localhost dashboard server lifecycle commands
22
23
  * - mega-events.ts pi lifecycle event handlers
23
24
  *
@@ -33,6 +34,7 @@ import { registerCommands } from "./mega-commands.js";
33
34
  import { registerDashboardCommands } from "./mega-dashboard-cmds.js";
34
35
  import { registerConflictCommands } from "./mega-conflict-cmds.js";
35
36
  import { registerDbCommands } from "./mega-db-cmds.js";
37
+ import { registerGameCommands } from "./mega-game-cmds.js";
36
38
 
37
39
  export default function (pi: ExtensionAPI) {
38
40
  const config = loadConfig();
@@ -42,4 +44,5 @@ export default function (pi: ExtensionAPI) {
42
44
  registerDashboardCommands(pi, runtime);
43
45
  registerConflictCommands(pi, runtime);
44
46
  registerDbCommands(pi, runtime);
47
+ registerGameCommands(pi, runtime);
45
48
  }
@@ -14,6 +14,10 @@ import {
14
14
  memoryReviewCadence,
15
15
  type MegaConfig,
16
16
  } from "../mega-config.js";
17
+ import { recordScore } from "../../src/store/sqlite.js";
18
+ import { evaluateAndUnlockAchievements } from "../../src/store/sqlite/game-achievements.js";
19
+ import { isMegaCache } from "../../src/game/scoring.js";
20
+ import { resolveRepoRoot } from "../mega-config.js";
17
21
 
18
22
  /** Register agent/turn tracking event handlers. */
19
23
  export function registerAgentHandlers(
@@ -176,6 +180,50 @@ export function registerAgentHandlers(
176
180
  runtime.dashboard.event("turn_end", { turnIndex: event.turnIndex });
177
181
  runtime.snapshot(ctx);
178
182
 
183
+ // S33: game-mode scoring — record turns + cache metrics per repo, and arm
184
+ // the MEGA CACHE flare (oopsie gag) when the real dedup hit rate exceeds
185
+ // 100%. Gated behind game_mode_on (no scoring when off). Best-effort +
186
+ // non-fatal: a scoring failure must never break the agent loop (G6).
187
+ try {
188
+ if (runtime.getCachedGameState().game_mode_on) {
189
+ const repo = resolveRepoRoot(ctx.cwd) ?? runtime.currentStateDir;
190
+ const st = runtime.store.stats(runtime.rt.sessionId);
191
+ const cachePct = st.dedupHitRate * 100;
192
+ const modelId = runtime.currentModel?.modelId ?? "unknown";
193
+ recordScore(runtime.currentStateDir, {
194
+ repo_root: repo,
195
+ metric: "turns",
196
+ value: runtime.currentTurn,
197
+ meta: { modelId, turnIndex: event.turnIndex },
198
+ });
199
+ recordScore(runtime.currentStateDir, {
200
+ repo_root: repo,
201
+ metric: "cache",
202
+ value: cachePct,
203
+ meta: {
204
+ hits: st.dedupCollapsed + runtime.rt.recallInjections,
205
+ lookups: st.checkpointCount,
206
+ },
207
+ });
208
+ // MEGA CACHE: the real ratio >1 (dedupHitRate>1) → trophy row + flare.
209
+ if (isMegaCache(cachePct)) {
210
+ recordScore(runtime.currentStateDir, {
211
+ repo_root: repo,
212
+ metric: "mega_cache",
213
+ value: cachePct,
214
+ meta: { peakPct: cachePct, firstSeenTs: Date.now() },
215
+ });
216
+ runtime.armMegaCacheFlare(cachePct);
217
+ }
218
+ // S35: evaluate achievements after scoring; arm a one-time flare for
219
+ // the newly-unlocked ones (consumed by snapshot() → widget toast).
220
+ const newTitles = evaluateAndUnlockAchievements(runtime.currentStateDir);
221
+ if (newTitles.length) runtime.armAchievementFlare(newTitles);
222
+ }
223
+ } catch {
224
+ /* non-fatal: scoring must never break the agent loop */
225
+ }
226
+
179
227
  // S20+S24: auto-review the conversation and persist durable memories. The
180
228
  // review cadence scales with pressure (memoryReviewCadence): as context
181
229
  // fills, the conversation is reviewed more often so memories keep pace with
@@ -19,6 +19,9 @@ import {
19
19
  import { estimateBlockTokens } from "../../src/tokens.js";
20
20
  import { type MegaRuntime } from "../mega-runtime.js";
21
21
  import type { MegaConfig } from "../mega-config.js";
22
+ import { recordScore, getDedupStats } from "../../src/store/sqlite.js";
23
+ import { evaluateAndUnlockAchievements } from "../../src/store/sqlite/game-achievements.js";
24
+ import { resolveRepoRoot } from "../mega-config.js";
22
25
 
23
26
  /**
24
27
  * Build a minimal fallback compaction so pi never runs its throwing compact().
@@ -160,5 +163,30 @@ export function registerCompactHandlers(
160
163
  sessionId: runtime.rt.sessionId,
161
164
  at: runtime.rt.lastCompactAt,
162
165
  });
166
+
167
+ // S33: game-mode dedupe scoring — record the DELTA of cumulative dedup
168
+ // collapses since the last compact (leaderboard SUMs the deltas). Gated
169
+ // behind game_mode_on (no scoring when off). Best-effort + non-fatal (G6).
170
+ try {
171
+ if (runtime.getCachedGameState().game_mode_on) {
172
+ const ds = getDedupStats(runtime.currentStateDir);
173
+ const delta = ds.deduped - runtime.lastDedupCollapsed;
174
+ runtime.lastDedupCollapsed = ds.deduped;
175
+ if (delta > 0) {
176
+ const repo = resolveRepoRoot(_ctx.cwd) ?? runtime.currentStateDir;
177
+ recordScore(runtime.currentStateDir, {
178
+ repo_root: repo,
179
+ metric: "dedupe",
180
+ value: delta,
181
+ meta: { compactCount: runtime.rt.compactCount },
182
+ });
183
+ }
184
+ }
185
+ // S35: evaluate achievements after scoring; arm the one-time flare.
186
+ const newTitles = evaluateAndUnlockAchievements(runtime.currentStateDir);
187
+ if (newTitles.length) runtime.armAchievementFlare(newTitles);
188
+ } catch {
189
+ /* non-fatal: scoring must never break compaction */
190
+ }
163
191
  });
164
192
  }
@@ -83,14 +83,16 @@ export function registerContextHandler(
83
83
  // Legacy: MEGACOMPACT_LEGACY_DURABLE_TRIM=true restores the v0.4.28 ctx.compact
84
84
  // path (kept one release as rollback).
85
85
  pi.on("context", async (event: ContextEvent, ctx: ExtensionContext) => {
86
- if (!config.auto) return;
87
86
  const usage = ctx.getContextUsage();
88
87
  const pct = usage?.percent;
89
- // Always track context for the dashboard, even if we return early below.
88
+ // Always track context for the dashboard/widget, even when auto is off.
89
+ // (v0.8 regression: !config.auto gate sat above this, leaving ctx stats
90
+ // null -> widget '?% / ?/?' when auto disabled. Track first, THEN gate.)
90
91
  runtime.lastCtxTokens = usage?.tokens ?? null;
91
92
  runtime.lastCtxPercent = pct ?? null;
92
93
  runtime.lastCtxWindow = usage?.contextWindow ?? 0;
93
94
  runtime.snapshot(ctx);
95
+ if (!config.auto) return;
94
96
 
95
97
  const messages = event.messages;
96
98
  const view = runtime.engineView(messages);