pi-mega-compact 0.7.8 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +11 -12
  2. package/dist/extensions/dashboard-server/html.js +1023 -0
  3. package/dist/extensions/dashboard-server/html.test.js +41 -0
  4. package/dist/extensions/dashboard-server/index-reader.js +133 -0
  5. package/dist/extensions/dashboard-server/server.js +530 -0
  6. package/dist/extensions/dashboard-server/server.test.js +120 -0
  7. package/dist/extensions/dashboard-server/snapshot.js +43 -0
  8. package/dist/extensions/dashboard-server/state.js +30 -0
  9. package/dist/extensions/dashboard-server/types.js +5 -0
  10. package/dist/extensions/dashboard-server-s32.test.js +181 -0
  11. package/dist/extensions/dashboard-server.js +7 -1315
  12. package/dist/extensions/mega-commands.js +162 -134
  13. package/dist/extensions/mega-compact.js +3 -0
  14. package/dist/extensions/mega-compact.test.js +90 -21
  15. package/dist/extensions/mega-conflict-cmds.js +5 -1
  16. package/dist/extensions/mega-dashboard-cmds.js +29 -22
  17. package/dist/extensions/mega-db-cmds.js +11 -2
  18. package/dist/extensions/mega-events/agent-handlers.js +222 -0
  19. package/dist/extensions/mega-events/compact-handlers.js +162 -0
  20. package/dist/extensions/mega-events/context-handler.js +249 -0
  21. package/dist/extensions/mega-events/register.js +21 -0
  22. package/dist/extensions/mega-events/session-handlers.js +142 -0
  23. package/dist/extensions/mega-events.js +15 -699
  24. package/dist/extensions/mega-game-cmds.js +106 -0
  25. package/dist/extensions/mega-game-cmds.test.js +113 -0
  26. package/dist/extensions/mega-pipeline/compact.js +324 -0
  27. package/dist/extensions/mega-pipeline/memory-review.js +38 -0
  28. package/dist/extensions/mega-pipeline/recall.js +147 -0
  29. package/dist/extensions/mega-pipeline.js +9 -480
  30. package/dist/extensions/mega-runtime/helpers.js +40 -0
  31. package/dist/extensions/mega-runtime/query.js +29 -0
  32. package/dist/extensions/mega-runtime/state.js +877 -0
  33. package/dist/extensions/mega-runtime/state.test.js +171 -0
  34. package/dist/extensions/mega-runtime/widget.js +270 -0
  35. package/dist/extensions/mega-runtime/widget.test.js +160 -0
  36. package/dist/extensions/mega-runtime.js +15 -947
  37. package/dist/src/config/themes.js +84 -0
  38. package/dist/src/config/themes.test.js +94 -0
  39. package/dist/src/game/scoring.js +105 -0
  40. package/dist/src/game/scoring.test.js +98 -0
  41. package/dist/src/store/sqlite/checkpoints.js +145 -0
  42. package/dist/src/store/sqlite/dedup-mirror.js +64 -0
  43. package/dist/src/store/sqlite/foundation.js +38 -0
  44. package/dist/src/store/sqlite/game-achievements.js +111 -0
  45. package/dist/src/store/sqlite/game-achievements.test.js +67 -0
  46. package/dist/src/store/sqlite/game-scores.js +105 -0
  47. package/dist/src/store/sqlite/game-scores.test.js +106 -0
  48. package/dist/src/store/sqlite/game-state.js +54 -0
  49. package/dist/src/store/sqlite/game-state.test.js +76 -0
  50. package/dist/src/store/sqlite/global-index.js +224 -0
  51. package/dist/src/store/sqlite/maintenance.js +235 -0
  52. package/dist/src/store/sqlite/memories.js +164 -0
  53. package/dist/src/store/sqlite/meta.js +82 -0
  54. package/dist/src/store/sqlite/model-snapshots.js +47 -0
  55. package/dist/src/store/sqlite/raptor.js +57 -0
  56. package/dist/src/store/sqlite/raw-transcript.js +134 -0
  57. package/dist/src/store/sqlite/schema.js +294 -0
  58. package/dist/src/store/sqlite/session-state.js +28 -0
  59. package/dist/src/store/sqlite/stats.js +66 -0
  60. package/dist/src/store/sqlite/utils.js +120 -0
  61. package/dist/src/store/sqlite.js +23 -1607
  62. package/extensions/dashboard-server/html.test.ts +50 -0
  63. package/extensions/dashboard-server/html.ts +1026 -0
  64. package/extensions/dashboard-server/index-reader.ts +130 -0
  65. package/extensions/dashboard-server/server.test.ts +131 -0
  66. package/extensions/dashboard-server/server.ts +505 -0
  67. package/extensions/dashboard-server/snapshot.ts +44 -0
  68. package/extensions/dashboard-server/state.ts +33 -0
  69. package/extensions/dashboard-server/types.ts +134 -0
  70. package/extensions/dashboard-server-s32.test.ts +195 -0
  71. package/extensions/dashboard-server.ts +7 -1431
  72. package/extensions/mega-commands.ts +33 -10
  73. package/extensions/mega-compact.test.ts +198 -43
  74. package/extensions/mega-compact.ts +3 -0
  75. package/extensions/mega-conflict-cmds.ts +6 -2
  76. package/extensions/mega-dashboard-cmds.ts +30 -23
  77. package/extensions/mega-db-cmds.ts +11 -3
  78. package/extensions/mega-events/agent-handlers.ts +262 -0
  79. package/extensions/mega-events/compact-handlers.ts +192 -0
  80. package/extensions/mega-events/context-handler.ts +290 -0
  81. package/extensions/mega-events/register.ts +37 -0
  82. package/extensions/mega-events/session-handlers.ts +165 -0
  83. package/extensions/mega-events.ts +15 -780
  84. package/extensions/mega-game-cmds.test.ts +137 -0
  85. package/extensions/mega-game-cmds.ts +122 -0
  86. package/extensions/mega-pipeline/compact.ts +366 -0
  87. package/extensions/mega-pipeline/memory-review.ts +46 -0
  88. package/extensions/mega-pipeline/recall.ts +165 -0
  89. package/extensions/mega-pipeline.ts +9 -537
  90. package/extensions/mega-runtime/helpers.ts +68 -0
  91. package/extensions/mega-runtime/query.ts +29 -0
  92. package/extensions/mega-runtime/state.test.ts +171 -0
  93. package/extensions/mega-runtime/state.ts +967 -0
  94. package/extensions/mega-runtime/widget.test.ts +185 -0
  95. package/extensions/mega-runtime/widget.ts +359 -0
  96. package/extensions/mega-runtime.ts +15 -1093
  97. package/package.json +4 -3
  98. package/src/config/themes.test.ts +116 -0
  99. package/src/config/themes.ts +124 -0
  100. package/src/game/scoring.test.ts +103 -0
  101. package/src/game/scoring.ts +158 -0
  102. package/src/store/sqlite/checkpoints.ts +204 -0
  103. package/src/store/sqlite/dedup-mirror.ts +114 -0
  104. package/src/store/sqlite/foundation.ts +63 -0
  105. package/src/store/sqlite/game-achievements.test.ts +80 -0
  106. package/src/store/sqlite/game-achievements.ts +147 -0
  107. package/src/store/sqlite/game-scores.test.ts +132 -0
  108. package/src/store/sqlite/game-scores.ts +168 -0
  109. package/src/store/sqlite/game-state.test.ts +89 -0
  110. package/src/store/sqlite/game-state.ts +87 -0
  111. package/src/store/sqlite/global-index.ts +305 -0
  112. package/src/store/sqlite/maintenance.ts +294 -0
  113. package/src/store/sqlite/memories.ts +217 -0
  114. package/src/store/sqlite/meta.ts +108 -0
  115. package/src/store/sqlite/model-snapshots.ts +83 -0
  116. package/src/store/sqlite/raptor.ts +107 -0
  117. package/src/store/sqlite/raw-transcript.ts +221 -0
  118. package/src/store/sqlite/schema.ts +305 -0
  119. package/src/store/sqlite/session-state.ts +38 -0
  120. package/src/store/sqlite/stats.ts +127 -0
  121. package/src/store/sqlite/utils.ts +125 -0
  122. package/src/store/sqlite.ts +23 -2204
@@ -0,0 +1,505 @@
1
+ /**
2
+ * dashboard-server/server.ts — HTTP server creation + launch + CLI entry point.
3
+ */
4
+
5
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
6
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, watch, writeFileSync } from "node:fs";
7
+ import { join, dirname } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { createRequire } from "node:module";
10
+
11
+ import { log, setLogPath, setDashboardServerVersion } from "./state.js";
12
+ import { readIndex, getIndexDir } from "./index-reader.js";
13
+ import { readSnapshot, readFrom } from "./snapshot.js";
14
+ import { dashboardHtml } from "./html.js";
15
+ import { ACTIVE_WINDOW_SEC } from "./types.js";
16
+ import type { IndexIndex, Snapshot, LiveSnapshot } from "./types.js";
17
+ import type { GameMetric } from "../../src/game/scoring.js";
18
+
19
+ export async function launchDashboardServer(stateDir: string): Promise<{ port: number; url: string }> {
20
+ // Our own package version — exposed at /api/version so the launcher can
21
+ // detect a stale server (started by an older build) and replace it on
22
+ // upgrade instead of reuse it.
23
+ let SERVER_VERSION = "0.0.0";
24
+ try {
25
+ // dashboard-server.js lives at <pkg>/dist/extensions/, so package.json is
26
+ // two levels up. Guard each candidate so a dev-checkout layout still works.
27
+ const here = dirname(fileURLToPath(import.meta.url));
28
+ const candidates = [join(here, "..", "..", "package.json"), join(here, "..", "package.json")];
29
+ for (const p of candidates) {
30
+ if (!existsSync(p)) continue;
31
+ const pkg = JSON.parse(readFileSync(p, "utf-8"));
32
+ if (pkg.version) { SERVER_VERSION = pkg.version; setDashboardServerVersion(pkg.version); break; }
33
+ }
34
+ } catch { /* non-fatal */ }
35
+
36
+ // Lazy-loaded via require so the dashboard stays cheap to boot and we don't
37
+ // need a top-level await in the handler.
38
+ const driftReq = createRequire(import.meta.url);
39
+ const detectCrossRepoDrift = (idxDir: string) =>
40
+ (driftReq("../../src/driftDetection.js") as typeof import("../../src/driftDetection.js"))
41
+ .detectCrossRepoDrift(idxDir);
42
+ const portFile = join(stateDir, "port.pid");
43
+ const snapshotPath = join(stateDir, "dashboard.json");
44
+ const eventsPath = join(stateDir, "events.log");
45
+ setLogPath(join(stateDir, "dashboard.log"));
46
+ log("launch invoked", { stateDir });
47
+
48
+ // ── Existing server? ───────────────────────────────────────────────────────
49
+ // A stale port.pid pointing at a dead/competing process is the classic cause
50
+ // of "dashboard failed to start" — we return a port that is NOT actually
51
+ // serving. Probe for a live server on that port first; only reuse the marker
52
+ // when something real answers /api/version. Otherwise drop it and start fresh.
53
+ if (existsSync(portFile)) {
54
+ try {
55
+ const info = JSON.parse(readFileSync(portFile, "utf-8"));
56
+ if (info && info.port) {
57
+ let live = false;
58
+ try {
59
+ const probe = await fetch(`http://localhost:${info.port}/api/version`, { signal: AbortSignal.timeout(800) }); // guardrails-allow PREVENT-PI-004: optional localhost dashboard server probe (loopback-only)
60
+ live = probe.ok;
61
+ } catch {
62
+ live = false;
63
+ }
64
+ if (live) {
65
+ log("reusing live server from port.pid", { port: info.port });
66
+ return { port: info.port, url: `http://localhost:${info.port}` }; // guardrails-allow PREVENT-PI-004: localhost dashboard URL (loopback-only)
67
+ }
68
+ log("port.pid present but no live server — treating as stale", { port: info.port });
69
+ }
70
+ } catch {
71
+ log("port.pid unparseable — treating as stale");
72
+ }
73
+ // stale file, remove so the fresh bind does not collide with a lingering
74
+ // process that still holds the port
75
+ try { unlinkSync(portFile); } catch { /* ignore */ }
76
+ }
77
+
78
+ // ── New server ────────────────────────────────────────────────────────────
79
+ mkdirSync(stateDir, { recursive: true });
80
+
81
+ let eventOffset = 0;
82
+
83
+ // Overlay the live current-repo snapshot (snapshot.json, rewritten every
84
+ // context event) onto its registry row so the All-repos / Summary views stay
85
+ // in sync with the live menu bar + Current-repo card in real time. The
86
+ // registry (index.sqlite) is only written on repo-switch (bindRepo), so
87
+ // without this the current repo's row freezes between switches. Read-only —
88
+ // no extra writes to index.sqlite. Matched by stateDir, which equals the
89
+ // value this server was launched with (runtime.currentStateDir).
90
+ function overlayCurrentRepo(idx: IndexIndex | null): void {
91
+ if (!idx || !idx.repos.length) return;
92
+ let snap: Snapshot | null = null;
93
+ try { snap = readSnapshot(snapshotPath); } catch { return; }
94
+ if (!snap || !snap.repo) return;
95
+ const cur = idx.repos.find((r) => r.stateDir === stateDir);
96
+ if (!cur) return;
97
+ const prevSaved = cur.tokensSaved;
98
+ const prevCp = cur.checkpointCount;
99
+ const prevBytes = cur.compressedOriginalBytes;
100
+ const comp = snap.compression?.repo;
101
+ const liveSaved = comp ? comp.tokensFreed : (snap.repo.tokensSaved ?? prevSaved);
102
+ const liveCp = snap.repo.checkpointCount ?? prevCp;
103
+ const liveBytes = snap.integrity?.compressedOriginalBytes ?? prevBytes;
104
+ cur.tokensSaved = liveSaved;
105
+ cur.checkpointCount = liveCp;
106
+ cur.compressedOriginalBytes = liveBytes;
107
+ if (idx.summary) {
108
+ idx.summary.totalTokensSaved += liveSaved - prevSaved;
109
+ idx.summary.totalCheckpoints += liveCp - prevCp;
110
+ idx.summary.totalCompressedOriginalBytes += liveBytes - prevBytes;
111
+ }
112
+ idx.updatedAt = snap.updatedAt ?? idx.updatedAt;
113
+ }
114
+
115
+ const server = createServer((req: IncomingMessage, res: ServerResponse) => {
116
+ // guardrails-allow PREVENT-PI-004: optional, user-triggered /dashboard localhost server (loopback-only) — CORS open for local browser access
117
+ // CORS for local access
118
+ res.setHeader("Access-Control-Allow-Origin", "*");
119
+ res.setHeader("Access-Control-Allow-Methods", "GET, PUT, OPTIONS");
120
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
121
+
122
+ if (req.method === "OPTIONS") {
123
+ res.writeHead(204);
124
+ res.end();
125
+ return;
126
+ }
127
+
128
+ if (req.url === "/" || req.url === "/index.html") {
129
+ const tier = readSnapshot(snapshotPath).tier;
130
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
131
+ res.end(dashboardHtml(tier));
132
+ return;
133
+ }
134
+
135
+ if (req.url === "/api/snapshot") {
136
+ const snap = readSnapshot(snapshotPath);
137
+ res.writeHead(200, { "Content-Type": "application/json" });
138
+ res.end(JSON.stringify(snap));
139
+ return;
140
+ }
141
+
142
+ // Server version — lets the /dashboard launcher detect a stale server from
143
+ // an older build and replace it on upgrade rather than reuse it.
144
+ if (req.url === "/api/version") {
145
+ res.writeHead(200, { "Content-Type": "application/json" });
146
+ res.end(JSON.stringify({ version: SERVER_VERSION }));
147
+ return;
148
+ }
149
+
150
+ // Multi-repo aggregate (Phase 5b): the machine-wide repo registry read
151
+ // directly from SQLite (index.sqlite). Lets one dashboard show every repo's
152
+ // checkpoints, tokens saved, and active model. Read-only.
153
+ if (req.url === "/api/index") {
154
+ const idx = readIndex();
155
+ if (idx) overlayCurrentRepo(idx);
156
+ res.writeHead(200, { "Content-Type": "application/json" });
157
+ res.end(JSON.stringify(idx ?? { updatedAt: null, summary: null, repos: [] }));
158
+ return;
159
+ }
160
+
161
+ // /api/repos — registry list. Optional `?active=24h` filters to repos
162
+ // seen within the last N hours (default: all). The dashboard uses this to
163
+ // drive its "active vs archived" badge without refetching /api/index.
164
+ if (req.url?.startsWith("/api/repos")) {
165
+ const url = new URL(req.url, "http://x"); // guardrails-allow PREVENT-PI-004: localhost dashboard URL base (loopback-only)
166
+ const activeParam = url.searchParams.get("active");
167
+ const idx = readIndex();
168
+ if (idx) overlayCurrentRepo(idx);
169
+ let repos = idx?.repos ?? [];
170
+ if (activeParam) {
171
+ const m = /^(\d+)h$/.exec(activeParam);
172
+ if (m) {
173
+ const cutoffSec = Math.floor(Date.now() / 1000) - Number(m[1]) * 3600;
174
+ repos = repos.filter((r) => (r.lastSeen ?? 0) >= cutoffSec);
175
+ }
176
+ }
177
+ res.writeHead(200, { "Content-Type": "application/json" });
178
+ res.end(JSON.stringify({ updatedAt: idx?.updatedAt ?? null, repos, count: repos.length }));
179
+ return;
180
+ }
181
+
182
+ // /api/summary — header tiles without the full repo list (keeps payload
183
+ // small for embed scenarios). activeRepos mirrors the /api/repos?active=24h
184
+ // count so the dashboard can render the active badge alongside totals.
185
+ if (req.url?.startsWith("/api/summary")) {
186
+ const idx = readIndex();
187
+ if (idx) overlayCurrentRepo(idx);
188
+ const repos = idx?.repos ?? [];
189
+ const cutoffSec = Math.floor(Date.now() / 1000) - 24 * 3600;
190
+ const activeRepos = repos.filter((r) => (r.lastSeen ?? 0) >= cutoffSec).length;
191
+ res.writeHead(200, { "Content-Type": "application/json" });
192
+ res.end(JSON.stringify({
193
+ updatedAt: idx?.updatedAt ?? null,
194
+ summary: idx?.summary ?? null,
195
+ activeRepos,
196
+ totalRepos: repos.length,
197
+ }));
198
+ return;
199
+ }
200
+
201
+ // /api/drift — R4: cross-repo drift report over repo_registry. Flags stale
202
+ // repos (>30d idle), compaction lag (active but >24h since last
203
+ // compaction), and recent model churn. Read-only.
204
+ if (req.url?.startsWith("/api/drift")) {
205
+ const report = detectCrossRepoDrift(getIndexDir());
206
+ res.writeHead(200, { "Content-Type": "application/json" });
207
+ res.end(JSON.stringify(report));
208
+ return;
209
+ }
210
+
211
+ if (req.url === "/api/servers") {
212
+ try {
213
+ const idx = readIndex();
214
+ const nowSec = Math.floor(Date.now() / 1000);
215
+ const servers = (idx?.repos ?? []).filter((r) => (r.lastSeen ?? 0) >= nowSec - ACTIVE_WINDOW_SEC).map((r) => {
216
+ const out: Record<string, unknown> = { repoRoot: r.repoRoot, displayName: r.displayName, model: r.modelName, provider: r.providerName, lastSeen: r.lastSeen, lastCompactedAt: r.lastCompactedAt };
217
+ try { const p = join(r.stateDir, "dashboard.json"); if (existsSync(p)) { const snap = JSON.parse(readFileSync(p, "utf-8")) as LiveSnapshot; out.tier = snap.tier ?? null; out.contextPct = (snap.context && snap.context.percent != null) ? snap.context.percent : null; out.state = (snap.session && snap.session.state) || null; out.cacheHits = snap.cacheHits ?? null; out.compacts = snap.compacts ?? null; out.timeSaved = snap.timeSaved ?? null; out.updatedAt = snap.updatedAt ?? null; } } catch { /* best-effort */ }
218
+ return out;
219
+ }).sort((a, b) => (b.lastSeen as number) - (a.lastSeen as number));
220
+ res.writeHead(200, { "Content-Type": "application/json" });
221
+ res.end(JSON.stringify({ updatedAt: new Date().toISOString(), servers }));
222
+ } catch {
223
+ res.writeHead(500, { "Content-Type": "application/json" });
224
+ res.end(JSON.stringify({ error: "servers_unavailable" }));
225
+ }
226
+ return;
227
+ }
228
+
229
+ if (req.url === "/api/events") {
230
+ res.writeHead(200, {
231
+ "Content-Type": "text/event-stream",
232
+ "Cache-Control": "no-cache",
233
+ "Connection": "keep-alive",
234
+ });
235
+
236
+ // Drain existing events so the client starts with history
237
+ const { data: existing, offset: initialOffset } = readFrom(eventsPath, 0);
238
+ eventOffset = initialOffset;
239
+ const lines = existing.split("\n").filter((l: string) => l.trim());
240
+ for (const line of lines) {
241
+ res.write(`data: ${line}\n\n`);
242
+ }
243
+
244
+ // Tail new events via fs.watch (coalesced with 100ms debounce)
245
+ let watchTimer: ReturnType<typeof setTimeout> | null = null;
246
+ const onWatch = () => {
247
+ if (watchTimer) return;
248
+ watchTimer = setTimeout(() => {
249
+ watchTimer = null;
250
+ const { data, offset } = readFrom(eventsPath, eventOffset);
251
+ eventOffset = offset;
252
+ const newLines = data.split("\n").filter((l: string) => l.trim());
253
+ for (const line of newLines) {
254
+ res.write(`data: ${line}\n\n`);
255
+ }
256
+ }, 100);
257
+ };
258
+
259
+ // Set up file watching: if file exists, watch it directly;
260
+ // otherwise poll for creation every 1s then switch to fs.watch.
261
+ let watcher: ReturnType<typeof watch> | null = null;
262
+ let pollInterval: ReturnType<typeof setInterval> | null = null;
263
+
264
+ function startFileWatch(): void {
265
+ try {
266
+ watcher = watch(eventsPath, onWatch);
267
+ } catch { /* give up */ }
268
+ }
269
+
270
+ if (existsSync(eventsPath)) {
271
+ startFileWatch();
272
+ } else {
273
+ pollInterval = setInterval(() => {
274
+ if (existsSync(eventsPath)) {
275
+ if (pollInterval) { clearInterval(pollInterval); pollInterval = null; }
276
+ startFileWatch();
277
+ }
278
+ }, 1000);
279
+ }
280
+
281
+ req.on("close", () => {
282
+ if (watchTimer) clearTimeout(watchTimer);
283
+ if (pollInterval) clearInterval(pollInterval);
284
+ watcher?.close();
285
+ });
286
+ return;
287
+ }
288
+
289
+ // /api/game-state — S32 game-mode settings (game_mode_on / theme /
290
+ // tui_display_mode). GET returns the current row; PUT applies a partial
291
+ // patch (validated) and returns the post-write row. The dashboard server is
292
+ // a detached child with no MegaRuntime ref, so it reads/writes the
293
+ // game_state SQLite row directly; the in-process MegaRuntime picks up the
294
+ // change via its fs.watch cache-eviction watcher. PREVENT-PI-004: loopback.
295
+ if (req.url?.startsWith("/api/game-state")) {
296
+ const gsReq = createRequire(import.meta.url);
297
+ const { getGameState, setGameState } = gsReq("../../src/store/sqlite.js") as typeof import("../../src/store/sqlite.js");
298
+ const { isValidTheme } = gsReq("../../src/config/themes.js") as typeof import("../../src/config/themes.js");
299
+ if (req.method === "GET") {
300
+ try {
301
+ const gs = getGameState(stateDir); // guardrails-allow PREVENT-PI-004: local SQLite read (loopback dashboard)
302
+ res.writeHead(200, { "Content-Type": "application/json" });
303
+ res.end(JSON.stringify(gs));
304
+ } catch (e) {
305
+ res.writeHead(500, { "Content-Type": "application/json" });
306
+ res.end(JSON.stringify({ error: "game_state_unavailable", detail: String(e) }));
307
+ }
308
+ return;
309
+ }
310
+ if (req.method === "PUT") {
311
+ // Read + parse the JSON body (capped — the patch is tiny). The handler
312
+ // is sync, so drain the stream via data/end listeners then continue.
313
+ let body = "";
314
+ let tooBig = false;
315
+ req.on("data", (chunk: Buffer) => { // guardrails-allow PREVENT-PI-004: loopback dashboard request body (local)
316
+ if (body.length > 65536) { tooBig = true; return; }
317
+ body += chunk.toString();
318
+ });
319
+ req.on("end", () => {
320
+ if (tooBig) {
321
+ res.writeHead(413, { "Content-Type": "application/json" });
322
+ res.end(JSON.stringify({ error: "body_too_large" }));
323
+ return;
324
+ }
325
+ let patch: Record<string, unknown> = {};
326
+ try { patch = body ? JSON.parse(body) : {}; } catch {
327
+ res.writeHead(400, { "Content-Type": "application/json" });
328
+ res.end(JSON.stringify({ error: "invalid_json" }));
329
+ return;
330
+ }
331
+ // Reject valid-but-non-object JSON (null/[]/42) — dereferencing
332
+ // patch.game_mode_on would throw an unhandled TypeError inside this
333
+ // 'end' listener and crash the detached server (audit P1: loopback DoS).
334
+ if (typeof patch !== "object" || patch === null || Array.isArray(patch)) {
335
+ res.writeHead(400, { "Content-Type": "application/json" });
336
+ res.end(JSON.stringify({ error: "invalid_patch_object" }));
337
+ return;
338
+ }
339
+ // Validate the patch fields (unknown keys ignored; invalid values -> 400).
340
+ const clean: { game_mode_on?: boolean; theme?: string; tui_display_mode?: "full" | "minimal" } = {};
341
+ let bad = false;
342
+ if (patch.game_mode_on != null) {
343
+ if (typeof patch.game_mode_on !== "boolean") bad = true;
344
+ else clean.game_mode_on = patch.game_mode_on;
345
+ }
346
+ if (patch.theme != null) {
347
+ if (typeof patch.theme !== "string" || !isValidTheme(patch.theme)) bad = true;
348
+ else clean.theme = patch.theme;
349
+ }
350
+ if (patch.tui_display_mode != null) {
351
+ if (patch.tui_display_mode !== "full" && patch.tui_display_mode !== "minimal") bad = true;
352
+ else clean.tui_display_mode = patch.tui_display_mode;
353
+ }
354
+ if (bad) {
355
+ res.writeHead(400, { "Content-Type": "application/json" });
356
+ res.end(JSON.stringify({ error: "invalid_patch" }));
357
+ return;
358
+ }
359
+ try {
360
+ const gs = setGameState(clean, stateDir); // guardrails-allow PREVENT-PI-004: local SQLite write (loopback dashboard)
361
+ res.writeHead(200, { "Content-Type": "application/json" });
362
+ res.end(JSON.stringify(gs));
363
+ } catch (e) {
364
+ res.writeHead(500, { "Content-Type": "application/json" });
365
+ res.end(JSON.stringify({ error: "game_state_write_failed", detail: String(e) }));
366
+ }
367
+ });
368
+ return;
369
+ }
370
+ // Any other method on /api/game-state → 405.
371
+ res.writeHead(405, { "Content-Type": "application/json" }); // guardrails-allow PREVENT-PI-004: loopback dashboard response (local)
372
+ res.end(JSON.stringify({ error: "method_not_allowed" }));
373
+ return;
374
+ }
375
+
376
+ // /api/game-scores — S34 high-score leaderboards. GET returns the leaderboard
377
+ // for a metric (?metric=<m>&limit=<n>). `metric` is validated against the
378
+ // METRICS allow-list from src/game/scoring (re-exported via the sqlite barrel);
379
+ // default limit 10, clamped to [1,100]. The dashboard server is a detached
380
+ // child with no MegaRuntime ref, so it reads the game_scores SQLite table
381
+ // directly. Unknown metric -> 400, non-GET -> 405. PREVENT-PI-004: loopback.
382
+ if (req.url?.startsWith("/api/game-scores")) {
383
+ const gsReq = createRequire(import.meta.url);
384
+ const { leaderboard, METRICS } = gsReq("../../src/store/sqlite.js") as typeof import("../../src/store/sqlite.js");
385
+ if (req.method !== "GET") {
386
+ res.writeHead(405, { "Content-Type": "application/json" }); // guardrails-allow PREVENT-PI-004: loopback dashboard response (local)
387
+ res.end(JSON.stringify({ error: "method_not_allowed" }));
388
+ return;
389
+ }
390
+ try {
391
+ const url = new URL(req.url, "http://x"); // guardrails-allow PREVENT-PI-004: localhost dashboard URL base (loopback-only)
392
+ const metricParam = url.searchParams.get("metric") ?? "cache";
393
+ if (!(METRICS as readonly string[]).includes(metricParam)) {
394
+ res.writeHead(400, { "Content-Type": "application/json" }); // guardrails-allow PREVENT-PI-004: loopback dashboard response (local)
395
+ res.end(JSON.stringify({ error: "unknown_metric", metric: metricParam }));
396
+ return;
397
+ }
398
+ const metric = metricParam as GameMetric; // validated against METRICS above
399
+ let limit = Number(url.searchParams.get("limit") ?? "10");
400
+ if (!Number.isFinite(limit) || limit <= 0) limit = 10;
401
+ limit = Math.min(Math.max(limit, 1), 100); // clamp to [1,100]
402
+ const rows = leaderboard(stateDir, metric, { limit }); // guardrails-allow PREVENT-PI-004: local SQLite read (loopback dashboard)
403
+ res.writeHead(200, { "Content-Type": "application/json" });
404
+ res.end(JSON.stringify(rows));
405
+ } catch (e) {
406
+ res.writeHead(500, { "Content-Type": "application/json" });
407
+ res.end(JSON.stringify({ error: "game_scores_unavailable", detail: String(e) }));
408
+ }
409
+ return;
410
+ }
411
+
412
+ // /api/achievements — S35 achievement tiles. GET returns the 9 seeded rows
413
+ // {id,title,description,icon,hidden,unlocked_at}. The dashboard server is a
414
+ // detached child with no MegaRuntime ref, so it reads game_achievements via
415
+ // listAchievements(stateDir) directly. Non-GET -> 405. PREVENT-PI-004: loopback.
416
+ if (req.url?.startsWith("/api/achievements")) {
417
+ const achReq = createRequire(import.meta.url);
418
+ const { listAchievements } = achReq("../../src/store/sqlite.js") as typeof import("../../src/store/sqlite.js");
419
+ if (req.method !== "GET") {
420
+ res.writeHead(405, { "Content-Type": "application/json" }); // guardrails-allow PREVENT-PI-004: loopback dashboard response (local)
421
+ res.end(JSON.stringify({ error: "method_not_allowed" }));
422
+ return;
423
+ }
424
+ try {
425
+ const rows = listAchievements(stateDir); // guardrails-allow PREVENT-PI-004: local SQLite read (loopback dashboard)
426
+ res.writeHead(200, { "Content-Type": "application/json" });
427
+ res.end(JSON.stringify(rows));
428
+ } catch (e) {
429
+ res.writeHead(500, { "Content-Type": "application/json" });
430
+ res.end(JSON.stringify({ error: "achievements_unavailable", detail: String(e) }));
431
+ }
432
+ return;
433
+ }
434
+
435
+ // Fallback — serve the dashboard
436
+ const tier = readSnapshot(snapshotPath).tier;
437
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
438
+ res.end(dashboardHtml(tier));
439
+ });
440
+
441
+ // Bind base + range are env-configurable so tests can use a private,
442
+ // non-colliding range (parallel runs / leftover servers from killed runs
443
+ // would otherwise EADDRINUSE on the machine-global 9320 range). Default
444
+ // MEGACOMPACT_DASHBOARD_PORT=9320 (10-port range 9320–9329) preserves the
445
+ // production behavior.
446
+ const TARGET_PORT = Number(process.env.MEGACOMPACT_DASHBOARD_PORT ?? "9320");
447
+ const PORT_RANGE = 10; // TARGET_PORT..TARGET_PORT+9
448
+
449
+ return new Promise((resolve, reject) => {
450
+ function tryPort(port: number) {
451
+ server.once("error", (err: NodeJS.ErrnoException) => {
452
+ if (err.code === "EADDRINUSE" && port < TARGET_PORT + PORT_RANGE - 1) {
453
+ log("port in use, trying next", { port });
454
+ tryPort(port + 1);
455
+ } else {
456
+ log("listen failed", { port, code: err.code, message: err.message });
457
+ reject(err);
458
+ }
459
+ });
460
+
461
+ server.listen(port, "127.0.0.1", () => {
462
+ const url = `http://localhost:${port}`; // guardrails-allow PREVENT-PI-004: localhost dashboard URL (loopback-only)
463
+ log("server running", { url });
464
+ // eslint-disable-next-line no-console
465
+ console.log(`[mega-compact] dashboard server running: ${url}`);
466
+
467
+ // Write port.pid
468
+ try {
469
+ writeFileSync(portFile, JSON.stringify({ port, pid: process.pid }));
470
+ } catch (e) {
471
+ log("could not write port.pid", { error: String(e) });
472
+ }
473
+
474
+ // Graceful cleanup
475
+ const cleanup = () => {
476
+ try { unlinkSync(portFile); } catch { /* already gone */ }
477
+ server.close();
478
+ process.exit(0);
479
+ };
480
+ process.on("SIGTERM", cleanup);
481
+ process.on("SIGINT", cleanup);
482
+
483
+ resolve({ port, url });
484
+ });
485
+ }
486
+
487
+ tryPort(TARGET_PORT);
488
+ });
489
+ }
490
+
491
+ // ---------------------------------------------------------------------------
492
+ // CLI entry point — when run directly as `node dashboard-server.js <stateDir>`
493
+ // ---------------------------------------------------------------------------
494
+
495
+ if (process.argv[1] && process.argv[1].includes("dashboard-server")) {
496
+ const stateDir = process.argv[2];
497
+ if (!stateDir) {
498
+ console.error("Usage: node dashboard-server.js <stateDir>");
499
+ process.exit(1);
500
+ }
501
+ launchDashboardServer(stateDir).catch((err) => {
502
+ console.error("[mega-compact] dashboard server failed:", err);
503
+ process.exit(1);
504
+ });
505
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * dashboard-server/snapshot.ts — snapshot + events.log file readers.
3
+ */
4
+
5
+ import { readFileSync } from "node:fs";
6
+ import type { Snapshot } from "./types.js";
7
+
8
+ export function readSnapshot(snapshotPath: string) {
9
+ try {
10
+ const raw = readFileSync(snapshotPath, "utf-8");
11
+ return JSON.parse(raw) as Snapshot;
12
+ } catch {
13
+ return {
14
+ version: 1,
15
+ updatedAt: null,
16
+ tier: "unknown",
17
+ presetTier: "unknown",
18
+ pressure: 0,
19
+ config: { fastGatePct: 80, thresholdTokens: 100_000, tierPct: null, effectiveThresholdPct: null, anchorUserMessages: 1, preserveRecent: 2, auto: true, autoInlineK: 3 },
20
+ session: { id: null, state: null, persistedThisSession: false, lastCheckpointId: null, lastCompactedFrom: 0 },
21
+ context: { tokens: null, percent: null, contextWindow: 0 },
22
+ trigger: { armed: false, ready: false, currentTokens: null, thresholdTokens: 100_000, fastGatePct: 80, tierPct: null, effectiveThresholdPct: null },
23
+ store: { checkpointCount: 0, totalTokenEstimate: 0, originalTokens: 0, tokensSaved: 0, injectedCount: 0, dedupHitRate: 0, storageDedupRate: 0, dedupCollapsed: 0 },
24
+ crew: { activeAgents: 0, currentTurn: 0 },
25
+ repo: { checkpointCount: 0, totalTokenEstimate: 0, originalTokens: 0, tokensSaved: 0, sessionCount: 0, dedupAttempts: 0, dedupCollapsed: 0, storageDedupRate: 0 },
26
+ integrity: { regionsRetained: 0, compressedOriginalBytes: 0, duplicatesCollapsed: 0, bytesPermanentlyDeleted: 0 },
27
+ cacheHits: { session: 0, total: 0, sessionTokensSaved: 0, totalTokensSaved: 0 },
28
+ compacts: { session: 0, total: 0 },
29
+ timeSaved: { compact: { sessionSec: 0, totalSec: 0 }, cacheHit: { sessionSec: 0, totalSec: 0 } },
30
+ compression: { session: { tokensIn: 0, tokensOut: 0, tokensFreed: 0, compressionPct: 0, dedupPct: 0 }, repo: { tokensIn: 0, tokensOut: 0, tokensFreed: 0, compressionPct: 0, dedupPct: 0 } },
31
+ model: undefined,
32
+ } as Snapshot;
33
+ }
34
+ }
35
+
36
+ export function readFrom(path: string, charOffset: number): { data: string; offset: number } {
37
+ try {
38
+ const content = readFileSync(path, "utf-8");
39
+ if (content.length <= charOffset) return { data: "", offset: charOffset };
40
+ return { data: content.slice(charOffset), offset: content.length };
41
+ } catch {
42
+ return { data: "", offset: charOffset };
43
+ }
44
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * dashboard-server/state.ts — local runtime log + version state.
3
+ *
4
+ * The dashboard server is spawned as a DETACHED child. When it is launched with
5
+ * `stdio: "ignore"` (the old default) any crash before the first console.log is
6
+ * invisible — there is no log to "check". We therefore mirror every lifecycle
7
+ * line to a file in the state dir so a failed start is always diagnosable. The
8
+ * launcher also captures stderr, so this doubles as defense-in-depth.
9
+ */
10
+
11
+ import { appendFileSync } from "node:fs";
12
+
13
+ let LOG_PATH: string | null = null;
14
+
15
+ export function setLogPath(path: string | null): void {
16
+ LOG_PATH = path;
17
+ }
18
+
19
+ export function log(...parts: unknown[]): void {
20
+ const line = `[mega-compact][dashboard] ${parts.map((p) => (typeof p === "string" ? p : JSON.stringify(p))).join(" ")}`;
21
+ // eslint-disable-next-line no-console
22
+ console.error(line); // stderr — captured by the launcher pipe
23
+ if (LOG_PATH) {
24
+ try { appendFileSync(LOG_PATH, new Date().toISOString() + " " + line + "\n"); } catch { /* non-fatal */ }
25
+ }
26
+ }
27
+
28
+ /** Package version of this extension, surfaced in the dashboard header. */
29
+ export let dashboardServerVersion = "0.0.0";
30
+
31
+ export function setDashboardServerVersion(v: string): void {
32
+ dashboardServerVersion = v;
33
+ }