pi-mega-compact 0.7.9 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/extensions/dashboard-server/html.js +333 -66
- package/dist/extensions/dashboard-server/html.test.js +41 -0
- package/dist/extensions/dashboard-server/server.js +161 -1
- package/dist/extensions/dashboard-server/server.test.js +120 -0
- package/dist/extensions/dashboard-server-s32.test.js +181 -0
- package/dist/extensions/mega-compact.js +3 -0
- package/dist/extensions/mega-events/agent-handlers.js +49 -0
- package/dist/extensions/mega-events/compact-handlers.js +29 -0
- package/dist/extensions/mega-game-cmds.js +106 -0
- package/dist/extensions/mega-game-cmds.test.js +113 -0
- package/dist/extensions/mega-runtime/state.js +167 -1
- package/dist/extensions/mega-runtime/state.test.js +171 -0
- package/dist/extensions/mega-runtime/widget.js +93 -20
- package/dist/extensions/mega-runtime/widget.test.js +160 -0
- package/dist/src/config/themes.js +84 -0
- package/dist/src/config/themes.test.js +94 -0
- package/dist/src/game/scoring.js +105 -0
- package/dist/src/game/scoring.test.js +98 -0
- package/dist/src/store/sqlite/game-achievements.js +111 -0
- package/dist/src/store/sqlite/game-achievements.test.js +67 -0
- package/dist/src/store/sqlite/game-scores.js +105 -0
- package/dist/src/store/sqlite/game-scores.test.js +106 -0
- package/dist/src/store/sqlite/game-state.js +54 -0
- package/dist/src/store/sqlite/game-state.test.js +76 -0
- package/dist/src/store/sqlite/schema.js +44 -0
- package/dist/src/store/sqlite.js +3 -0
- package/extensions/dashboard-server/html.test.ts +50 -0
- package/extensions/dashboard-server/html.ts +334 -66
- package/extensions/dashboard-server/server.test.ts +131 -0
- package/extensions/dashboard-server/server.ts +148 -1
- package/extensions/dashboard-server-s32.test.ts +195 -0
- package/extensions/mega-compact.ts +3 -0
- package/extensions/mega-events/agent-handlers.ts +48 -0
- package/extensions/mega-events/compact-handlers.ts +28 -0
- package/extensions/mega-game-cmds.test.ts +137 -0
- package/extensions/mega-game-cmds.ts +122 -0
- package/extensions/mega-runtime/state.test.ts +171 -0
- package/extensions/mega-runtime/state.ts +170 -0
- package/extensions/mega-runtime/widget.test.ts +185 -0
- package/extensions/mega-runtime/widget.ts +119 -18
- package/package.json +1 -1
- package/src/config/themes.test.ts +116 -0
- package/src/config/themes.ts +124 -0
- package/src/game/scoring.test.ts +103 -0
- package/src/game/scoring.ts +158 -0
- package/src/store/sqlite/game-achievements.test.ts +80 -0
- package/src/store/sqlite/game-achievements.ts +147 -0
- package/src/store/sqlite/game-scores.test.ts +132 -0
- package/src/store/sqlite/game-scores.ts +168 -0
- package/src/store/sqlite/game-state.test.ts +89 -0
- package/src/store/sqlite/game-state.ts +87 -0
- package/src/store/sqlite/schema.ts +47 -0
- package/src/store/sqlite.ts +3 -0
- package/dist/extensions/dashboard-server/helpers.js +0 -37
- package/dist/extensions/dashboard-server/html/all-repos-tab.js +0 -26
- package/dist/extensions/dashboard-server/html/body-open.js +0 -23
- package/dist/extensions/dashboard-server/html/current-repo-tab.js +0 -130
- package/dist/extensions/dashboard-server/html/head-open.js +0 -16
- package/dist/extensions/dashboard-server/html/high-score-tab.js +0 -25
- package/dist/extensions/dashboard-server/html/repo-detail-modal.js +0 -26
- package/dist/extensions/dashboard-server/html/script.js +0 -259
- package/dist/extensions/dashboard-server/html/styles.js +0 -103
- package/dist/extensions/dashboard-server/html/summary-tab.js +0 -19
- package/dist/extensions/dashboard-server/html-template.js +0 -41
- package/dist/src/store/sqlite/connection.js +0 -35
- package/dist/src/store/sqlite/index-store.js +0 -167
- package/dist/src/store/sqlite/memory.js +0 -54
- package/dist/src/store/sqlite/minhash-lsh.js +0 -47
- package/dist/src/store/sqlite/sessions.js +0 -39
- package/dist/src/store/sqlite/transaction.js +0 -19
- package/dist/src/vectorStore/add.js +0 -260
- package/dist/src/vectorStore/dedup.js +0 -52
- package/dist/src/vectorStore/index.js +0 -10
- package/dist/src/vectorStore/queries.js +0 -83
- package/dist/src/vectorStore/search.js +0 -95
- package/dist/src/vectorStore/session.js +0 -19
- package/dist/src/vectorStore/store.js +0 -105
- package/dist/src/vectorStore/types.js +0 -6
- package/dist/src/vectorStore/utils.js +0 -23
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mega-game-cmds.ts — /mega-game slash command (S30).
|
|
3
|
+
*
|
|
4
|
+
* Backs the game-mode toggle + theme picker + TUI display mode. All state is
|
|
5
|
+
* the global `game_state` SQLite row (src/store/sqlite/game-state.ts) — local
|
|
6
|
+
* only (PREVENT-PI-004: no network; no guardrails-allow needed because this
|
|
7
|
+
* command touches no fetch/http). All SQL is parameterized (PREVENT-002) and
|
|
8
|
+
* lives in the src/ submodule, not here.
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* /mega-game print current state
|
|
12
|
+
* /mega-game on enable game mode (scoring + level-up + MEGA CACHE)
|
|
13
|
+
* /mega-game off disable game mode
|
|
14
|
+
* /mega-game theme list available themes
|
|
15
|
+
* /mega-game theme <id> set theme by id
|
|
16
|
+
* /mega-game theme next cycle to next theme
|
|
17
|
+
* /mega-game tui full full TUI widget (bars, stats, flair)
|
|
18
|
+
* /mega-game tui minimal one-line TUI widget (level + cache %)
|
|
19
|
+
* /mega-game achievements list unlocked achievements
|
|
20
|
+
*/
|
|
21
|
+
import { getGameState, setGameState, } from "../src/store/sqlite.js";
|
|
22
|
+
import { listAchievements } from "../src/store/sqlite/game-achievements.js";
|
|
23
|
+
import { THEMES, THEME_IDS, getTheme, isValidTheme, nextTheme, DEFAULT_THEME } from "../src/config/themes.js";
|
|
24
|
+
/** Format the current state as a human-readable status line set. */
|
|
25
|
+
function fmtState(s) {
|
|
26
|
+
return [
|
|
27
|
+
`[mega-game] game mode: ${s.game_mode_on ? "ON" : "off"}`,
|
|
28
|
+
` theme: ${s.theme}${s.theme === DEFAULT_THEME ? " (default)" : ""}`,
|
|
29
|
+
` tui: ${s.tui_display_mode}`,
|
|
30
|
+
];
|
|
31
|
+
}
|
|
32
|
+
/** Register the /mega-game command. */
|
|
33
|
+
export function registerGameCommands(pi, runtime) {
|
|
34
|
+
pi.registerCommand("mega-game", {
|
|
35
|
+
description: "Game mode toggle + theme picker + TUI display mode. Usage: /mega-game [on|off|theme [id|next]|tui [full|minimal]|achievements]",
|
|
36
|
+
handler: async (args, ctx) => {
|
|
37
|
+
runtime.bindRepo(ctx.cwd);
|
|
38
|
+
const stateDir = runtime.currentStateDir;
|
|
39
|
+
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
40
|
+
// /mega-game → print current state.
|
|
41
|
+
if (parts.length === 0) {
|
|
42
|
+
const s = getGameState(stateDir);
|
|
43
|
+
for (const line of fmtState(s))
|
|
44
|
+
ctx.ui.notify(line);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const sub = parts[0];
|
|
48
|
+
// /mega-game achievements — terse list of unlocked (hidden only once unlocked).
|
|
49
|
+
if (sub === "achievements") {
|
|
50
|
+
const rows = listAchievements(stateDir).filter((r) => r.unlocked_at != null);
|
|
51
|
+
ctx.ui.notify(`[mega-game] achievements unlocked (${rows.length}/9):`);
|
|
52
|
+
for (const r of rows) {
|
|
53
|
+
ctx.ui.notify(` ${r.icon ?? ""} ${r.title}`);
|
|
54
|
+
}
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
// /mega-game on|off
|
|
58
|
+
if (sub === "on" || sub === "off") {
|
|
59
|
+
const s = setGameState({ game_mode_on: sub === "on" }, stateDir);
|
|
60
|
+
runtime.bumpGameState();
|
|
61
|
+
ctx.ui.notify(`[mega-game] game mode ${s.game_mode_on ? "ON" : "off"}`);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
// /mega-game theme [id|next]
|
|
65
|
+
if (sub === "theme") {
|
|
66
|
+
if (parts.length === 1) {
|
|
67
|
+
// list themes
|
|
68
|
+
ctx.ui.notify("[mega-game] themes:");
|
|
69
|
+
for (const t of THEMES) {
|
|
70
|
+
ctx.ui.notify(` ${t.id.padEnd(14)} ${t.label}`);
|
|
71
|
+
}
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const arg = parts[1];
|
|
75
|
+
let id;
|
|
76
|
+
if (arg === "next") {
|
|
77
|
+
id = nextTheme(getGameState(stateDir).theme);
|
|
78
|
+
}
|
|
79
|
+
else if (isValidTheme(arg)) {
|
|
80
|
+
id = arg;
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
ctx.ui.notify(`[mega-game] unknown theme "${arg}". Valid: ${THEME_IDS.join(", ")}`);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const s = setGameState({ theme: id }, stateDir);
|
|
87
|
+
runtime.bumpGameState();
|
|
88
|
+
ctx.ui.notify(`[mega-game] theme → ${s.theme} (${getTheme(s.theme)?.label ?? ""})`);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
// /mega-game tui full|minimal
|
|
92
|
+
if (sub === "tui") {
|
|
93
|
+
const arg = parts[1];
|
|
94
|
+
if (arg !== "full" && arg !== "minimal") {
|
|
95
|
+
ctx.ui.notify(`[mega-game] usage: /mega-game tui full|minimal`);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const s = setGameState({ tui_display_mode: arg }, stateDir);
|
|
99
|
+
runtime.bumpGameState();
|
|
100
|
+
ctx.ui.notify(`[mega-game] tui → ${s.tui_display_mode}`);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
ctx.ui.notify(`[mega-game] usage: /mega-game [on|off|theme [id|next]|tui [full|minimal]|achievements]`);
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
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
|
+
// ESM bootstrap so `require()` works in this .test.ts (mirrors
|
|
15
|
+
// mega-compact.test.ts:20-24). Needed for the dynamic `require("./mega-game-cmds.js")`
|
|
16
|
+
// that wires the command against a fake pi without binding to the real pi
|
|
17
|
+
// module at load time.
|
|
18
|
+
const require = createRequire(import.meta.url);
|
|
19
|
+
function makeHarness(stateDir) {
|
|
20
|
+
const commands = {};
|
|
21
|
+
const notifies = [];
|
|
22
|
+
const runtime = { bindRepo: () => { }, currentStateDir: stateDir, bumpGameState: () => { } };
|
|
23
|
+
const ctx = {
|
|
24
|
+
cwd: stateDir,
|
|
25
|
+
ui: { notify: (s) => notifies.push(s) },
|
|
26
|
+
};
|
|
27
|
+
const fakePi = {
|
|
28
|
+
registerCommand: (name, opts) => {
|
|
29
|
+
commands[name] = opts;
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
// Import after env is set so stateDir resolves. Dynamic import keeps the
|
|
33
|
+
// test from binding to the real pi module at load time.
|
|
34
|
+
const mod = require("./mega-game-cmds.js");
|
|
35
|
+
mod.registerGameCommands(fakePi, runtime);
|
|
36
|
+
return { commands, notifies, ctx };
|
|
37
|
+
}
|
|
38
|
+
describe("/mega-game (S30)", () => {
|
|
39
|
+
let dir;
|
|
40
|
+
before(() => {
|
|
41
|
+
dir = mkdtempSync(join(tmpdir(), "mc-megagame-"));
|
|
42
|
+
process.env.MEGACOMPACT_STATE_DIR = dir;
|
|
43
|
+
});
|
|
44
|
+
after(() => {
|
|
45
|
+
closeStore(dir);
|
|
46
|
+
delete process.env.MEGACOMPACT_STATE_DIR;
|
|
47
|
+
rmSync(dir, { recursive: true, force: true });
|
|
48
|
+
});
|
|
49
|
+
async function run(args) {
|
|
50
|
+
const h = makeHarness(dir);
|
|
51
|
+
h.notifies.length = 0;
|
|
52
|
+
await h.commands["mega-game"].handler(args, h.ctx);
|
|
53
|
+
return h.notifies;
|
|
54
|
+
}
|
|
55
|
+
it("bare command prints current (default) state", async () => {
|
|
56
|
+
const lines = await run("");
|
|
57
|
+
assert.ok(lines.some((l) => l.includes("game mode: off")));
|
|
58
|
+
assert.ok(lines.some((l) => l.includes("transparent")));
|
|
59
|
+
assert.ok(lines.some((l) => l.includes("tui:")));
|
|
60
|
+
});
|
|
61
|
+
it("on enables game mode and persists", async () => {
|
|
62
|
+
await run("on");
|
|
63
|
+
assert.equal(getGameState().game_mode_on, true);
|
|
64
|
+
});
|
|
65
|
+
it("off disables game mode and persists", async () => {
|
|
66
|
+
await run("on");
|
|
67
|
+
await run("off");
|
|
68
|
+
assert.equal(getGameState().game_mode_on, false);
|
|
69
|
+
});
|
|
70
|
+
it("theme <id> sets a valid theme and persists", async () => {
|
|
71
|
+
await run("theme retro");
|
|
72
|
+
assert.equal(getGameState().theme, "retro");
|
|
73
|
+
await run("theme cyan-neon");
|
|
74
|
+
assert.equal(getGameState().theme, "cyan-neon");
|
|
75
|
+
});
|
|
76
|
+
it("theme <unknown> is rejected with a usage line and does not mutate", async () => {
|
|
77
|
+
await run("theme retro");
|
|
78
|
+
const lines = await run("theme bogus");
|
|
79
|
+
assert.ok(lines.some((l) => l.includes("unknown theme")));
|
|
80
|
+
assert.equal(getGameState().theme, "retro");
|
|
81
|
+
});
|
|
82
|
+
it("theme next cycles to the next theme and wraps", async () => {
|
|
83
|
+
await run(`theme ${THEME_IDS[0]}`);
|
|
84
|
+
await run("theme next");
|
|
85
|
+
assert.equal(getGameState().theme, THEME_IDS[1]);
|
|
86
|
+
// cycle to the end then wrap
|
|
87
|
+
await run(`theme ${THEME_IDS[THEME_IDS.length - 1]}`);
|
|
88
|
+
await run("theme next");
|
|
89
|
+
assert.equal(getGameState().theme, THEME_IDS[0]);
|
|
90
|
+
});
|
|
91
|
+
it("theme (bare) lists all themes", async () => {
|
|
92
|
+
const lines = await run("theme");
|
|
93
|
+
for (const id of THEME_IDS) {
|
|
94
|
+
assert.ok(lines.some((l) => l.includes(id)), `lists ${id}`);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
it("tui full|minimal sets display mode and persists", async () => {
|
|
98
|
+
await run("tui minimal");
|
|
99
|
+
assert.equal(getGameState().tui_display_mode, "minimal");
|
|
100
|
+
await run("tui full");
|
|
101
|
+
assert.equal(getGameState().tui_display_mode, "full");
|
|
102
|
+
});
|
|
103
|
+
it("tui <bad> prints usage and does not mutate", async () => {
|
|
104
|
+
await run("tui minimal");
|
|
105
|
+
const lines = await run("tui huge");
|
|
106
|
+
assert.ok(lines.some((l) => l.includes("usage")));
|
|
107
|
+
assert.equal(getGameState().tui_display_mode, "minimal");
|
|
108
|
+
});
|
|
109
|
+
it("unknown subcommand prints usage", async () => {
|
|
110
|
+
const lines = await run("bogus");
|
|
111
|
+
assert.ok(lines.some((l) => l.includes("usage")));
|
|
112
|
+
});
|
|
113
|
+
});
|
|
@@ -15,12 +15,15 @@ import { VectorStore } from "../../src/vectorStore.js";
|
|
|
15
15
|
import { toEngineMessages } from "../../src/adapt.js";
|
|
16
16
|
import { normalizeSessionId } from "../../src/store.js";
|
|
17
17
|
import { Logger } from "../../src/log.js";
|
|
18
|
-
import { recordModelSnapshot, latestModelSnapshot, upsertRepoRegistry, recordRepoModel, getDedupStats, getCompactCount, getRecallInjected, getCacheHitTokensSaved, } from "../../src/store/sqlite.js";
|
|
18
|
+
import { recordModelSnapshot, latestModelSnapshot, upsertRepoRegistry, recordRepoModel, getDedupStats, getCompactCount, getRecallInjected, getCacheHitTokensSaved, getGameState, } from "../../src/store/sqlite.js";
|
|
19
19
|
import { detectCrossRepoDrift } from "../../src/driftDetection.js";
|
|
20
20
|
import { repoStateDir, resolveRepoRoot, pressureRatio, pressureFromPct, pressureBand, effectiveThresholdTokens, } from "../mega-config.js";
|
|
21
21
|
import { Dashboard } from "../mega-dashboard.js";
|
|
22
22
|
import { STATUS_KEY, WIDGET_KEY, TOKENS_PER_SEC_ESTIMATE, ownVersion, } from "./helpers.js";
|
|
23
23
|
import { C, buildWidgetLines, } from "./widget.js";
|
|
24
|
+
import { getTheme } from "../../src/config/themes.js";
|
|
25
|
+
import { watch } from "node:fs";
|
|
26
|
+
import { turnLevel } from "../../src/game/scoring.js";
|
|
24
27
|
export class MegaRuntime {
|
|
25
28
|
config;
|
|
26
29
|
// Store/dashboard/logger are rebound per-repo by bindRepo() so each git repo
|
|
@@ -53,6 +56,22 @@ export class MegaRuntime {
|
|
|
53
56
|
// Agent tracking for real-time widget updates
|
|
54
57
|
activeAgents = 0;
|
|
55
58
|
currentTurn = 0;
|
|
59
|
+
// S33: transient MEGA CACHE flare flag (armed by the turn_end scoring hook
|
|
60
|
+
// when cachePct > 100). Copied into widgetData.megaCacheFlare on the next
|
|
61
|
+
// snapshot() so the widget renders the oopsie gag, then reset (one cycle).
|
|
62
|
+
megaCacheFlare = false;
|
|
63
|
+
megaCacheFlarePct = 0;
|
|
64
|
+
levelUpFlare = false;
|
|
65
|
+
lastLevel = 0;
|
|
66
|
+
// S35: transient achievement-unlock flare (armed by the scoring hooks after
|
|
67
|
+
// evaluateAndUnlockAchievements returns newly-unlocked titles). Copied into
|
|
68
|
+
// widgetData.achievementFlare on the next snapshot() so the widget renders the
|
|
69
|
+
// unlock toast, then reset (one cycle — mirrors megaCacheFlare/levelUpFlare).
|
|
70
|
+
achievementFlare = false;
|
|
71
|
+
achievementFlareTitles = [];
|
|
72
|
+
// S33: last cumulative dedup-collapsed count seen by the session_compact
|
|
73
|
+
// hook, so we only record the DELTA as the dedupe score (leaderboard sums).
|
|
74
|
+
lastDedupCollapsed = 0;
|
|
56
75
|
// Recall block produced by auto-inline (resume/branch) that the next
|
|
57
76
|
// before_agent_start should prepend to the system prompt. Unset after use.
|
|
58
77
|
pendingRecallBlock;
|
|
@@ -97,6 +116,23 @@ export class MegaRuntime {
|
|
|
97
116
|
// Cached cross-repo drift status (recomputed at most every 30s — it opens the
|
|
98
117
|
// machine-wide registry DB, so we don't want to do it on every render frame).
|
|
99
118
|
driftCache = null;
|
|
119
|
+
// S31: cached game-mode state (game_mode_on/theme/tui_display_mode). Lazily
|
|
120
|
+
// read from the game_state SQLite row on the first widget render, then
|
|
121
|
+
// memoized until bumpGameState() evicts it (called by /mega-game after a
|
|
122
|
+
// write) so the widget picks up theme/mode/level changes live without
|
|
123
|
+
// re-querying the DB on every render frame.
|
|
124
|
+
cachedGameState;
|
|
125
|
+
// S32: fs.watch on the current repo's sqlite.db so cross-process writes
|
|
126
|
+
// (e.g. the dashboard server's PUT /api/game-state, which runs as a detached
|
|
127
|
+
// child with no MegaRuntime ref) evict the cached game-state memo. Without
|
|
128
|
+
// this, /mega-game's in-process bumpGameState() is the only eviction trigger
|
|
129
|
+
// and the widget would keep showing stale theme/mode/toggle after a dashboard
|
|
130
|
+
// edit until a restart. The watcher tracks currentStateDir — closed + re-opened
|
|
131
|
+
// by ensureGameStateWatcher() on every bindRepo repo switch. Non-fatal: any
|
|
132
|
+
// fs.watch failure (missing file / platform issue) is swallowed; the next
|
|
133
|
+
// getCachedGameState() snapshot re-queries the DB anyway.
|
|
134
|
+
gameStateWatcher;
|
|
135
|
+
gameStateWatchDir;
|
|
100
136
|
/**
|
|
101
137
|
* DIAG counters for the "team run doesn't relieve context" investigation.
|
|
102
138
|
* Plain integers, incremented at the three compaction decision points. They
|
|
@@ -188,6 +224,7 @@ export class MegaRuntime {
|
|
|
188
224
|
});
|
|
189
225
|
this.dashboard = new Dashboard(config.stateDir);
|
|
190
226
|
this.currentStateDir = config.stateDir;
|
|
227
|
+
this.ensureGameStateWatcher();
|
|
191
228
|
}
|
|
192
229
|
// ---- per-repo binding -----------------------------------------------------
|
|
193
230
|
/**
|
|
@@ -204,6 +241,15 @@ export class MegaRuntime {
|
|
|
204
241
|
return dir;
|
|
205
242
|
this.activeRepoRoot = key;
|
|
206
243
|
this.currentStateDir = dir;
|
|
244
|
+
// S31 audit P2: bindRepo switched currentStateDir but left cachedGameState
|
|
245
|
+
// memoized -> the widget kept showing the previous repo's theme/mode/toggle
|
|
246
|
+
// until /mega-game or a restart. The game_state row is per-repo (per
|
|
247
|
+
// stateDir), so evict the memo on every repo switch; the next widget render
|
|
248
|
+
// re-queries lazily via getCachedGameState().
|
|
249
|
+
this.cachedGameState = undefined;
|
|
250
|
+
// S32: re-target the fs.watch cache-eviction watcher at the NEW stateDir's
|
|
251
|
+
// sqlite.db so cross-process writes (dashboard server) still evict the memo.
|
|
252
|
+
this.ensureGameStateWatcher();
|
|
207
253
|
this.store = new VectorStore({
|
|
208
254
|
dedupSim: this.config.dedupSim,
|
|
209
255
|
stateDir: dir,
|
|
@@ -457,6 +503,16 @@ export class MegaRuntime {
|
|
|
457
503
|
// Cross-repo drift status (cached, read-only).
|
|
458
504
|
const driftStatus = this.driftStatus();
|
|
459
505
|
const agentsActive = this.activeAgents > 0;
|
|
506
|
+
// S31: game-mode state for the widget (theme/mode/level + MEGA CACHE).
|
|
507
|
+
// Pulled from the cached game_state row; cachePct is the REAL dedup hit
|
|
508
|
+
// rate (may exceed 100% — that's the MEGA CACHE trigger). megaCacheFlare
|
|
509
|
+
// is false for now (S33.4 scoring hook arms it when cachePct > 100).
|
|
510
|
+
const gs = this.getCachedGameState();
|
|
511
|
+
// S34: derive the level-up flare from the turn count each snapshot.
|
|
512
|
+
const curLevel = this.getTurnLevel();
|
|
513
|
+
if (curLevel > this.lastLevel)
|
|
514
|
+
this.levelUpFlare = true;
|
|
515
|
+
const cachePct = st.dedupHitRate * 100;
|
|
460
516
|
this.widgetData = {
|
|
461
517
|
version: ownVersion(),
|
|
462
518
|
tierLabel,
|
|
@@ -488,7 +544,30 @@ export class MegaRuntime {
|
|
|
488
544
|
lastWhy: this.lastWhy,
|
|
489
545
|
tierTrace: this.tierTrace,
|
|
490
546
|
pulsing: this.pulsing,
|
|
547
|
+
// S31 game-mode fields:
|
|
548
|
+
gameMode: gs.game_mode_on,
|
|
549
|
+
theme: getTheme(gs.theme) ? gs.theme : "transparent",
|
|
550
|
+
tuiMode: gs.tui_display_mode,
|
|
551
|
+
level: this.getTurnLevel(),
|
|
552
|
+
cachePct,
|
|
553
|
+
megaCacheFlare: this.megaCacheFlare,
|
|
554
|
+
megaCacheFlarePct: this.megaCacheFlarePct,
|
|
555
|
+
levelUpFlare: this.levelUpFlare,
|
|
556
|
+
achievementFlare: this.achievementFlare,
|
|
557
|
+
achievementFlareTitles: this.achievementFlareTitles,
|
|
491
558
|
};
|
|
559
|
+
// S33: consume the flare after copying it into widgetData so it fires
|
|
560
|
+
// for exactly one render cycle (the gag flares once, then clears).
|
|
561
|
+
this.megaCacheFlare = false;
|
|
562
|
+
this.megaCacheFlarePct = 0;
|
|
563
|
+
// S34: consume the level-up flare after one render cycle (mirrors the
|
|
564
|
+
// megaCacheFlare one-shot semantics), and advance lastLevel.
|
|
565
|
+
this.levelUpFlare = false;
|
|
566
|
+
this.lastLevel = curLevel;
|
|
567
|
+
// S35: consume the achievement-unlock flare after one render cycle
|
|
568
|
+
// (mirrors the megaCacheFlare/levelUpFlare one-shot semantics).
|
|
569
|
+
this.achievementFlare = false;
|
|
570
|
+
this.achievementFlareTitles = [];
|
|
492
571
|
// Auto-fit: register a factory so pi re-renders the panel at the REAL
|
|
493
572
|
// terminal width every frame (tui.columns), instead of guessing with
|
|
494
573
|
// process.stdout.columns. buildWidgetLines reads this.widgetData live.
|
|
@@ -563,6 +642,10 @@ export class MegaRuntime {
|
|
|
563
642
|
this.pulsing = false;
|
|
564
643
|
this.savedGoal = 50_000;
|
|
565
644
|
this.lastWhy = undefined;
|
|
645
|
+
// S31 audit P2: symmetry with bindRepo — a reset can coincide with a context
|
|
646
|
+
// that re-binds the repo, so drop the memo too. Cheap; the next
|
|
647
|
+
// getCachedGameState() re-queries lazily.
|
|
648
|
+
this.cachedGameState = undefined;
|
|
566
649
|
}
|
|
567
650
|
/**
|
|
568
651
|
* Capture the active model/provider from ctx.model and persist it so cost
|
|
@@ -665,6 +748,89 @@ export class MegaRuntime {
|
|
|
665
748
|
getStateDir() {
|
|
666
749
|
return this.currentStateDir;
|
|
667
750
|
}
|
|
751
|
+
/** S32: (re)target the fs.watch cache-eviction watcher at the current
|
|
752
|
+
* stateDir's sqlite.db. Called from the constructor + every bindRepo repo
|
|
753
|
+
* switch so the watcher always tracks the NEW repo's db file. If a watcher
|
|
754
|
+
* already exists for this dir, no-op; if the dir changed, close the old one
|
|
755
|
+
* first. fs.watch can throw on a missing file / platform issues — wrapped
|
|
756
|
+
* non-fatal; the next getCachedGameState() re-queries the DB anyway. */
|
|
757
|
+
ensureGameStateWatcher() {
|
|
758
|
+
if (this.gameStateWatcher && this.gameStateWatchDir === this.currentStateDir) {
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
if (this.gameStateWatcher) {
|
|
762
|
+
try {
|
|
763
|
+
this.gameStateWatcher.close();
|
|
764
|
+
}
|
|
765
|
+
catch { /* non-fatal */ }
|
|
766
|
+
this.gameStateWatcher = undefined;
|
|
767
|
+
this.gameStateWatchDir = undefined;
|
|
768
|
+
}
|
|
769
|
+
try {
|
|
770
|
+
this.gameStateWatcher = watch(join(this.currentStateDir, "sqlite.db"), () => { this.cachedGameState = undefined; });
|
|
771
|
+
this.gameStateWatchDir = this.currentStateDir;
|
|
772
|
+
}
|
|
773
|
+
catch {
|
|
774
|
+
/* non-fatal: missing file / platform issue — next snapshot re-queries */
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
/** S32: release the fs.watch game-state watcher. Called when the runtime is
|
|
778
|
+
* torn down (no existing dispose path — the process exit reclaims the fd,
|
|
779
|
+
* but explicit close is correct for any in-process reload / test reuse). */
|
|
780
|
+
dispose() {
|
|
781
|
+
if (this.gameStateWatcher) {
|
|
782
|
+
try {
|
|
783
|
+
this.gameStateWatcher.close();
|
|
784
|
+
}
|
|
785
|
+
catch { /* non-fatal */ }
|
|
786
|
+
this.gameStateWatcher = undefined;
|
|
787
|
+
this.gameStateWatchDir = undefined;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
/** S31: the cached game-mode state (game_mode_on/theme/tui_display_mode).
|
|
791
|
+
* Lazily read from the game_state SQLite row on the first call, then
|
|
792
|
+
* memoized until `bumpGameState()` evicts it. Reading is non-throwing
|
|
793
|
+
* (getGameState returns DEFAULT_GAME_STATE on any error), so the widget
|
|
794
|
+
* can call this on every render safely. */
|
|
795
|
+
getCachedGameState() {
|
|
796
|
+
if (!this.cachedGameState) {
|
|
797
|
+
try {
|
|
798
|
+
this.cachedGameState = getGameState(this.currentStateDir);
|
|
799
|
+
}
|
|
800
|
+
catch {
|
|
801
|
+
this.cachedGameState = {
|
|
802
|
+
game_mode_on: false,
|
|
803
|
+
theme: "transparent",
|
|
804
|
+
tui_display_mode: "full",
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
return this.cachedGameState;
|
|
809
|
+
}
|
|
810
|
+
/** S31: evict the cached game-mode state so the next widget render re-reads
|
|
811
|
+
* the game_state row. Called by /mega-game after every setGameState() so
|
|
812
|
+
* the panel picks up theme/mode/toggle changes live. */
|
|
813
|
+
bumpGameState() {
|
|
814
|
+
this.cachedGameState = undefined;
|
|
815
|
+
}
|
|
816
|
+
/** S33: player level for game mode — floor(log2(turns+1))+1 (gentle).
|
|
817
|
+
* Defensive: non-finite/negative collapses to 1 (never NaN). */
|
|
818
|
+
getTurnLevel() {
|
|
819
|
+
return turnLevel(this.currentTurn);
|
|
820
|
+
}
|
|
821
|
+
/** S33: arm the transient MEGA CACHE flare so the next snapshot() copies it
|
|
822
|
+
* into widgetData and the widget renders the oopsie gag for one cycle. */
|
|
823
|
+
armMegaCacheFlare(peakPct) {
|
|
824
|
+
this.megaCacheFlare = true;
|
|
825
|
+
this.megaCacheFlarePct = peakPct;
|
|
826
|
+
}
|
|
827
|
+
/** S35: arm the transient achievement-unlock flare with the newly-unlocked
|
|
828
|
+
* titles so the next snapshot() copies them into widgetData and the widget
|
|
829
|
+
* renders the one-time unlock toast for one render cycle. */
|
|
830
|
+
armAchievementFlare(titles) {
|
|
831
|
+
this.achievementFlare = true;
|
|
832
|
+
this.achievementFlareTitles = titles;
|
|
833
|
+
}
|
|
668
834
|
/** Build the sync onTier callback that paints the live per-tier trace. */
|
|
669
835
|
makeTierCallback(ctx) {
|
|
670
836
|
const order = ["L0", "L1", "L2", "new"];
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* state.test.ts — S31 MegaRuntime game-state cache round-trip.
|
|
3
|
+
*
|
|
4
|
+
* getCachedGameState() lazily reads the game_state row; bumpGameState()
|
|
5
|
+
* evicts so the next read re-queries. Uses MEGACOMPACT_STATE_DIR + mkdtemp
|
|
6
|
+
* (G7). A minimal MegaRuntime is constructed directly (no pi runtime).
|
|
7
|
+
*/
|
|
8
|
+
import { describe, it, after } from "node:test";
|
|
9
|
+
import assert from "node:assert/strict";
|
|
10
|
+
import { tmpdir } from "node:os";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
13
|
+
import { createRequire } from "node:module";
|
|
14
|
+
import { execSync } from "node:child_process";
|
|
15
|
+
import { closeStore, getGameState, setGameState } from "../../src/store/sqlite.js";
|
|
16
|
+
import { DEFAULT_GAME_STATE } from "../../src/store/sqlite/game-state.js";
|
|
17
|
+
const require = createRequire(import.meta.url);
|
|
18
|
+
// Require the compiled JS (build output) so ESM import of pi-tui etc. resolves.
|
|
19
|
+
const { MegaRuntime } = require("./state.js");
|
|
20
|
+
/** Minimal MegaConfig — enough fields for the constructor; the snapshot path
|
|
21
|
+
* isn't exercised here, only getCachedGameState/bumpGameState. */
|
|
22
|
+
function minimalConfig(stateDir) {
|
|
23
|
+
return {
|
|
24
|
+
tier: "custom",
|
|
25
|
+
tierPct: null,
|
|
26
|
+
thresholdTokens: 100_000,
|
|
27
|
+
stateDir,
|
|
28
|
+
fastGatePct: 70,
|
|
29
|
+
anchorUserMessages: 3,
|
|
30
|
+
preserveRecent: 4,
|
|
31
|
+
preserveRecentMin: 2,
|
|
32
|
+
auto: false,
|
|
33
|
+
autoInline: false,
|
|
34
|
+
autoContinueLengthStop: false,
|
|
35
|
+
autoPctTrigger: null,
|
|
36
|
+
dedupSim: 0.9,
|
|
37
|
+
raptorEnabled: false,
|
|
38
|
+
legacyDurableTrim: false,
|
|
39
|
+
dbMirror: false,
|
|
40
|
+
crossRepoEnabled: false,
|
|
41
|
+
crossRepoCosine: 0.9,
|
|
42
|
+
memoryAutoReview: false,
|
|
43
|
+
memoryReviewInterval: 10,
|
|
44
|
+
recallMaxTokens: 1500,
|
|
45
|
+
windowDedupe: false,
|
|
46
|
+
debug: false,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** Fresh isolated state dir per test — the game_state row is global and
|
|
50
|
+
* persists across cases in a shared dir, so each case gets its own mkdtemp to
|
|
51
|
+
* avoid cross-test contamination. */
|
|
52
|
+
function freshDir() {
|
|
53
|
+
return mkdtempSync(join(tmpdir(), "mc-state-"));
|
|
54
|
+
}
|
|
55
|
+
describe("MegaRuntime game-state cache (S31)", () => {
|
|
56
|
+
const dirs = [];
|
|
57
|
+
after(() => {
|
|
58
|
+
for (const d of dirs) {
|
|
59
|
+
try {
|
|
60
|
+
closeStore(d);
|
|
61
|
+
}
|
|
62
|
+
catch { /* */ }
|
|
63
|
+
}
|
|
64
|
+
delete process.env.MEGACOMPACT_STATE_DIR;
|
|
65
|
+
for (const d of dirs)
|
|
66
|
+
rmSync(d, { recursive: true, force: true });
|
|
67
|
+
});
|
|
68
|
+
it("getCachedGameState returns defaults on a fresh install", () => {
|
|
69
|
+
const dir = freshDir();
|
|
70
|
+
dirs.push(dir);
|
|
71
|
+
process.env.MEGACOMPACT_STATE_DIR = dir;
|
|
72
|
+
const rt = new MegaRuntime(minimalConfig(dir));
|
|
73
|
+
const gs = rt.getCachedGameState();
|
|
74
|
+
assert.deepEqual(gs, { ...DEFAULT_GAME_STATE });
|
|
75
|
+
});
|
|
76
|
+
it("getCachedGameState memoizes (same ref across calls)", () => {
|
|
77
|
+
const dir = freshDir();
|
|
78
|
+
dirs.push(dir);
|
|
79
|
+
process.env.MEGACOMPACT_STATE_DIR = dir;
|
|
80
|
+
const rt = new MegaRuntime(minimalConfig(dir));
|
|
81
|
+
const a = rt.getCachedGameState();
|
|
82
|
+
const b = rt.getCachedGameState();
|
|
83
|
+
assert.equal(a, b, "memoized — same object ref");
|
|
84
|
+
});
|
|
85
|
+
it("bumpGameState evicts so the next read reflects a setGameState write", () => {
|
|
86
|
+
const dir = freshDir();
|
|
87
|
+
dirs.push(dir);
|
|
88
|
+
process.env.MEGACOMPACT_STATE_DIR = dir;
|
|
89
|
+
const rt = new MegaRuntime(minimalConfig(dir));
|
|
90
|
+
const before = rt.getCachedGameState();
|
|
91
|
+
assert.equal(before.game_mode_on, false);
|
|
92
|
+
// Write out-of-band (as /mega-game would).
|
|
93
|
+
setGameState({ game_mode_on: true, theme: "retro", tui_display_mode: "minimal" }, dir);
|
|
94
|
+
// Without bump, the stale memo is returned.
|
|
95
|
+
const stale = rt.getCachedGameState();
|
|
96
|
+
assert.equal(stale.game_mode_on, false, "stale cache before bump");
|
|
97
|
+
// After bump, the next read re-queries and reflects the write.
|
|
98
|
+
rt.bumpGameState();
|
|
99
|
+
const fresh = rt.getCachedGameState();
|
|
100
|
+
assert.equal(fresh.game_mode_on, true);
|
|
101
|
+
assert.equal(fresh.theme, "retro");
|
|
102
|
+
assert.equal(fresh.tui_display_mode, "minimal");
|
|
103
|
+
// And matches the authoritative getGameState read.
|
|
104
|
+
assert.deepEqual(fresh, getGameState(dir));
|
|
105
|
+
});
|
|
106
|
+
it("bumpGameState is idempotent (safe to call when cache is empty)", () => {
|
|
107
|
+
const dir = freshDir();
|
|
108
|
+
dirs.push(dir);
|
|
109
|
+
process.env.MEGACOMPACT_STATE_DIR = dir;
|
|
110
|
+
const rt = new MegaRuntime(minimalConfig(dir));
|
|
111
|
+
rt.bumpGameState(); // no cached state yet — must not throw
|
|
112
|
+
const gs = rt.getCachedGameState();
|
|
113
|
+
assert.deepEqual(gs, { ...DEFAULT_GAME_STATE });
|
|
114
|
+
});
|
|
115
|
+
it("bindRepo evicts cachedGameState so a repo switch reflects the new repo's game_state", () => {
|
|
116
|
+
// Two fresh git repos A and B simulate a real repo switch. Each holds its
|
|
117
|
+
// own per-repo state dir at <root>/.pi/mega-compact (what repoStateDir
|
|
118
|
+
// returns for a git cwd), and each holds its own game_state row, so a repo
|
|
119
|
+
// switch (bindRepo) must evict the cached memo or the widget shows A's
|
|
120
|
+
// theme/mode/toggle after moving to B. Uses MEGACOMPACT_STATE_DIR + mkdtemp
|
|
121
|
+
// + closeStore (G7); the global state dir stays separate.
|
|
122
|
+
const globalDir = freshDir();
|
|
123
|
+
dirs.push(globalDir);
|
|
124
|
+
const repoA = freshDir();
|
|
125
|
+
dirs.push(repoA);
|
|
126
|
+
const repoB = freshDir();
|
|
127
|
+
dirs.push(repoB);
|
|
128
|
+
const stateA = join(repoA, ".pi", "mega-compact");
|
|
129
|
+
const stateB = join(repoB, ".pi", "mega-compact");
|
|
130
|
+
// Make A and B real git roots so resolveRepoRoot(cwd) returns the root and
|
|
131
|
+
// repoStateDir produces <root>/.pi/mega-compact (the per-repo store).
|
|
132
|
+
execSync("git init -q", { cwd: repoA });
|
|
133
|
+
execSync("git init -q", { cwd: repoB });
|
|
134
|
+
// Seed A and B with distinct game_state rows in their per-repo dirs.
|
|
135
|
+
setGameState({ game_mode_on: true, theme: "retro", tui_display_mode: "minimal" }, stateA);
|
|
136
|
+
setGameState({ game_mode_on: false, theme: "cyan-neon", tui_display_mode: "full" }, stateB);
|
|
137
|
+
// Construct the runtime against the GLOBAL dir (the non-git fallback so a
|
|
138
|
+
// real bindRepo switch occurs once we point it at a git root).
|
|
139
|
+
process.env.MEGACOMPACT_STATE_DIR = globalDir;
|
|
140
|
+
const rt = new MegaRuntime(minimalConfig(globalDir));
|
|
141
|
+
// Point the runtime at repo A and prime the cache.
|
|
142
|
+
rt.bindRepo(repoA);
|
|
143
|
+
assert.equal(rt.currentStateDir, stateA, "bindRepo(A) switched to A's per-repo dir");
|
|
144
|
+
const a = rt.getCachedGameState();
|
|
145
|
+
assert.equal(a.game_mode_on, true, "A: game_mode_on primed");
|
|
146
|
+
assert.equal(a.theme, "retro", "A: theme primed");
|
|
147
|
+
assert.equal(a.tui_display_mode, "minimal", "A: tui_display_mode primed");
|
|
148
|
+
// Switch to repo B: bindRepo must evict cachedGameState so the next read
|
|
149
|
+
// re-queries B's row instead of returning A's stale memo.
|
|
150
|
+
rt.bindRepo(repoB);
|
|
151
|
+
assert.equal(rt.currentStateDir, stateB, "bindRepo(B) switched to B's per-repo dir");
|
|
152
|
+
const b = rt.getCachedGameState();
|
|
153
|
+
assert.equal(b.game_mode_on, false, "B: game_mode_on after switch (not A's stale true)");
|
|
154
|
+
assert.equal(b.theme, "cyan-neon", "B: theme after switch (not A's stale retro)");
|
|
155
|
+
assert.equal(b.tui_display_mode, "full", "B: tui_display_mode after switch (not A's stale minimal)");
|
|
156
|
+
assert.deepEqual(b, getGameState(stateB), "B matches authoritative getGameState read");
|
|
157
|
+
// Cleanup the per-repo DB handles.
|
|
158
|
+
try {
|
|
159
|
+
closeStore(globalDir);
|
|
160
|
+
}
|
|
161
|
+
catch { /* */ }
|
|
162
|
+
try {
|
|
163
|
+
closeStore(stateA);
|
|
164
|
+
}
|
|
165
|
+
catch { /* */ }
|
|
166
|
+
try {
|
|
167
|
+
closeStore(stateB);
|
|
168
|
+
}
|
|
169
|
+
catch { /* */ }
|
|
170
|
+
});
|
|
171
|
+
});
|