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,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
+ });
@@ -0,0 +1,324 @@
1
+ /**
2
+ * compact.ts — full compaction pipeline (Trident) + pi no-op prediction.
3
+ *
4
+ * `runCompact` runs the full Trident pipeline (fast-gate aside) and persists a
5
+ * checkpoint. `piCompactWouldNoop` predicts whether pi's `ctx.compact()` would
6
+ * throw a no-op error. Both mutate the shared MegaRuntime (token accounting,
7
+ * ticker, status, events) and are driven by the event + command handlers in
8
+ * mega-events.ts / mega-commands.ts.
9
+ */
10
+ import { sessionEntryToContextMessages } from "@earendil-works/pi-coding-agent";
11
+ import { compactSession } from "../../src/engine.js";
12
+ import { normalizeSessionId } from "../../src/store.js";
13
+ import { estimateBlockTokens } from "../../src/tokens.js";
14
+ import { touchSession, logDaily, incCompactCount, incCacheHitTokens } from "../../src/store/sqlite.js";
15
+ import { consolidateMemories } from "../../src/memory.js";
16
+ import { C, MARKER_TYPE, } from "../mega-runtime.js";
17
+ import { resolveRepoRoot, preserveRecentForPressure } from "../mega-config.js";
18
+ import { runRaptor } from "../../src/dedup/raptor/index.js";
19
+ import { loadDedupConfig } from "../../src/config/dedup.js";
20
+ import { upsertEmbedding as indexUpsertEmbedding } from "../../src/store/vectorIndex.js";
21
+ import { runMemoryReview } from "./memory-review.js";
22
+ /** Run the full compaction pipeline and persist a checkpoint. Returns the result. */
23
+ export function runCompact(pi, runtime, config, ctx, messages, opts = {}) {
24
+ runtime.bindRepo(ctx.cwd);
25
+ const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
26
+ runtime.resetRuntime(sid);
27
+ runtime.rt.sessionId = sid;
28
+ const view = runtime.engineView(messages);
29
+ // keepFrom deepens with context pressure (Fix E): under high pressure we
30
+ // compact more of the session, down to the preserveRecentMin floor.
31
+ const preserve = preserveRecentForPressure(opts.compressionPressure ?? 0, config.preserveRecent, config.preserveRecentMin);
32
+ const keepFrom = opts.keepFrom ?? Math.max(0, view.length - preserve);
33
+ // For very small sessions (fewer messages than preserveRecent), allow
34
+ // compacting everything except the last message — the user explicitly
35
+ // requested compaction, so don't refuse it just because the session is short.
36
+ if (keepFrom <= 0) {
37
+ if (view.length <= 1)
38
+ return { skipped: true };
39
+ // Use the fallback: compact everything except the last message
40
+ const fallbackKeepFrom = view.length - 1;
41
+ return doCompact(view, fallbackKeepFrom, opts, sid, config, pi, ctx, runtime);
42
+ }
43
+ return doCompact(view, keepFrom, opts, sid, config, pi, ctx, runtime);
44
+ }
45
+ function doCompact(view, keepFrom, opts, sid, config, pi, ctx, runtime) {
46
+ runtime.pulsing = true; // animate the status line while the (sync) pipeline runs
47
+ // S21.2: reset the per-compaction memory-op counter so the post-compact
48
+ // consolidate pass only fires when memory rows actually changed during the
49
+ // compaction window (turn_end → auto-review may have written some).
50
+ runtime.memoriesTouchedThisCompaction = 0;
51
+ const result = compactSession({
52
+ sessionId: sid,
53
+ messages: view,
54
+ keepFrom,
55
+ summary: opts.summary,
56
+ timestamp: Date.now(),
57
+ onTier: runtime.makeTierCallback(ctx),
58
+ compressionPressure: opts.compressionPressure,
59
+ }, runtime.store);
60
+ runtime.pulsing = false;
61
+ if (result.skipped)
62
+ return { skipped: true };
63
+ if (!result.deduped) {
64
+ runtime.rt.persistedThisSession = true;
65
+ runtime.rt.lastCheckpointId = result.checkpointId;
66
+ }
67
+ runtime.rt.lastCompactedFrom = result.compactedFrom;
68
+ runtime.rt.lastCompactedTokens = result.tokenEstimate;
69
+ runtime.rt.dedupAttempts++;
70
+ // Honest "tokens saved" for this session-instance only:
71
+ // new checkpoint → original − stored
72
+ // deduped onto existing → whole original region (nothing new stored)
73
+ // Resets to 0 on session_start (rt is rebuilt) — so a fresh session shows 0
74
+ // while the repo's cumulative saved (SQLite meta) keeps the running total.
75
+ const saved = result.deduped
76
+ ? result.originalTokenEstimate
77
+ : Math.max(0, result.originalTokenEstimate - result.tokenEstimate);
78
+ runtime.rt.tokensSaved += saved;
79
+ runtime.rt.compactCount += 1;
80
+ incCompactCount(runtime.currentStateDir);
81
+ if (result.deduped) {
82
+ runtime.rt.cacheHitTokens += saved;
83
+ incCacheHitTokens(saved, runtime.currentStateDir);
84
+ }
85
+ runtime.rt.lastCompactAt = Date.now();
86
+ if (result.deduped)
87
+ runtime.rt.dedupSkips++;
88
+ // Grow the rolling "saved" goal so the progress bar always has a fresh
89
+ // denominator (we don't want it pinned at 100% once we pass an old target).
90
+ if (runtime.rt.tokensSaved > runtime.savedGoal)
91
+ runtime.savedGoal = Math.ceil((runtime.rt.tokensSaved * 1.25) / 10_000) * 10_000;
92
+ // Live toolbar activity: what file/region just got compacted or deduped.
93
+ // Rendered via the rotating ticker line (see snapshot); the ring buffer is
94
+ // cycled one-per-repaint so the single line scrolls through recent files.
95
+ const files = result.filesModified ?? [];
96
+ const fileLabel = files.length
97
+ ? files.map((f) => f.split("/").pop() ?? f).slice(0, 2).join(", ")
98
+ : result.regionHash.slice(0, 8);
99
+ runtime.lastActivityAt = Date.now();
100
+ // Explain-why line: surfaced while fresh. Pulls the dedup reason (which for
101
+ // L2 includes the cosine sim) so the user sees WHY a region was kept/dropped.
102
+ runtime.lastWhy = result.deduped
103
+ ? `why: deduped@${result.dedupReason ?? "tier"}`
104
+ : `why: compacted → ${result.checkpointId}`;
105
+ // Recall/activity ticker: record this event in the ring buffer.
106
+ const savedK = (saved / 1000).toFixed(1);
107
+ runtime.pushTicker(result.deduped
108
+ ? `${C.green}♻${C.reset} deduped ${fileLabel} · ${savedK}k saved`
109
+ : `${C.cyan}🗜${C.reset} ${result.checkpointId} · +${savedK}k · ${fileLabel}`);
110
+ // The per-tier trace has settled into the final outcome — fold it back into
111
+ // the activity line and stop showing the live trace.
112
+ runtime.tierTrace = undefined;
113
+ // Record session activity + a daily-log entry in the per-repo SQLite store
114
+ // (foundation for resume-sessions / daily-log features). Best-effort — never
115
+ // block a compaction on bookkeeping.
116
+ try {
117
+ const root = resolveRepoRoot(ctx.cwd);
118
+ touchSession(sid, root, runtime.currentStateDir);
119
+ logDaily(sid, "compact", result.checkpointId, saved, runtime.currentStateDir);
120
+ }
121
+ catch {
122
+ /* non-fatal: stats bookkeeping only */
123
+ }
124
+ // S21.2: best-effort consolidation of near-duplicate memories for this repo.
125
+ // Runs after the per-repo stats touch so `consolidateMemories` can use the
126
+ // same stateDir. Non-fatal — a failed consolidate never blocks a compaction.
127
+ // Only runs when new memory ops landed in this pass (otherwise the prior
128
+ // compaction's consolidate already had its shot — re-running would just
129
+ // touch every row again with no merges).
130
+ if (!result.deduped && runtime.memoriesTouchedThisCompaction > 0) {
131
+ try {
132
+ const root = resolveRepoRoot(ctx.cwd);
133
+ void consolidateMemories(runtime.currentStateDir, root).then((n) => {
134
+ if (n > 0)
135
+ runtime.pushTicker(`${C.green}∫${C.reset} consolidated ${n} memory dup${n === 1 ? "" : "s"}`);
136
+ }, () => {
137
+ /* swallow: consolidate failures must never surface to the user */
138
+ });
139
+ }
140
+ catch {
141
+ /* non-fatal */
142
+ }
143
+ }
144
+ // S24 review-on-compact: when pressure is high, the just-compacted region is
145
+ // exactly the context worth remembering, so review it immediately rather than
146
+ // waiting for the next turn-cadence tick. Uses the shared runMemoryReview
147
+ // helper (fire-and-forget; doCompact is sync). Best-effort + non-fatal. Only
148
+ // fires above the `high` band so low-pressure compactions don't pay the cost.
149
+ if (!result.deduped && config.memoryAutoReview && runtime.pressureBand !== "low" && runtime.pressureBand !== "medium") {
150
+ void runMemoryReview(runtime, view, "pressure");
151
+ }
152
+ // Sentinel marker: a non-LLM bookkeeping entry so subsequent triggers can
153
+ // skip re-vectorizing an already-compacted region (zero token cost).
154
+ pi.appendEntry(MARKER_TYPE, {
155
+ checkpointId: result.checkpointId,
156
+ regionHash: result.regionHash,
157
+ tokenEstimate: result.tokenEstimate,
158
+ deduped: result.deduped,
159
+ });
160
+ // Fix D: refresh the RAPTOR tree for this session so live recall (search) can
161
+ // serve high-level summaries. Best-effort + non-fatal: never block compaction.
162
+ // Budget-guarded (RAPTOR_BUDGET_MS) so it can't hang a large session.
163
+ if (config.raptorEnabled && !result.deduped) {
164
+ try {
165
+ const dd = loadDedupConfig();
166
+ const all = runtime.store.list(sid);
167
+ const leaves = all.map((cp) => ({
168
+ id: cp.checkpointId,
169
+ messages: [],
170
+ sourceText: cp.normalizedText ?? cp.summary ?? cp.regionHash,
171
+ embedding: cp.embedding,
172
+ }));
173
+ if (leaves.length >= 2) {
174
+ // S25: stamp the tree with the newest checkpoint epoch so the
175
+ // freshness guard in raptorSearchHits can reject stale trees after a
176
+ // later compaction adds newer checkpoints.
177
+ const builtAt = all.length > 0 ? Math.max(...all.map((c) => c.timestamp)) : Date.now();
178
+ runRaptor(leaves, {
179
+ stateDir: runtime.currentStateDir,
180
+ sessionId: sid,
181
+ budgetMs: dd.RAPTOR_BUDGET_MS,
182
+ clustersPerLevel: dd.RAPTOR_CLUSTERS_PER_LEVEL,
183
+ consistencyThreshold: dd.RAPTOR_CONSISTENCY,
184
+ logger: runtime.logger,
185
+ builtAt: Number.isFinite(builtAt) ? builtAt : Date.now(),
186
+ });
187
+ }
188
+ }
189
+ catch {
190
+ /* non-fatal: tree refresh never blocks a compaction */
191
+ }
192
+ }
193
+ // Slice 2: best-effort mirror of the new checkpoint into the async global
194
+ // PGlite/HNSW vector index. Fires once per compaction (not per-add), so the
195
+ // shared global dir is never hammered by concurrent test workers.
196
+ // Non-fatal: a WASM init failure degrades to the sync scan silently.
197
+ if (!result.deduped) {
198
+ try {
199
+ const all = runtime.store.list(sid);
200
+ const latest = all.find((cp) => cp.checkpointId === result.checkpointId);
201
+ if (latest?.embedding) {
202
+ void indexUpsertEmbedding(runtime.currentStateDir, sid, latest.checkpointId, latest.embedding).catch(() => {
203
+ /* non-fatal: index refresh never blocks a compaction */
204
+ });
205
+ }
206
+ }
207
+ catch {
208
+ /* non-fatal: index refresh never blocks a compaction */
209
+ }
210
+ }
211
+ runtime.setStatus(ctx, runtime.rt.persistedThisSession
212
+ ? `mega-compact: ${result.checkpointId} · ${saved} tok saved`
213
+ : `mega-compact: ready`);
214
+ runtime.logger.info("compact", {
215
+ sessionId: sid,
216
+ checkpointId: result.checkpointId ?? "(deduped)",
217
+ deduped: result.deduped,
218
+ tokenEstimate: saved,
219
+ compactedFrom: result.compactedFrom,
220
+ });
221
+ runtime.dashboard.event("compact", {
222
+ sessionId: sid,
223
+ checkpointId: result.checkpointId ?? "(deduped)",
224
+ deduped: result.deduped,
225
+ tokenEstimate: saved,
226
+ compactedFrom: result.compactedFrom,
227
+ });
228
+ runtime.snapshot(ctx);
229
+ return { skipped: false, result, keepFrom, saved };
230
+ }
231
+ /**
232
+ * Predict whether pi's `ctx.compact()` would throw a no-op error — "Already
233
+ * compacted" or "Nothing to compact (session too small)" — so the auto-trigger
234
+ * can SKIP the call instead of surfacing a hard, user-facing error.
235
+ *
236
+ * Why we can't intercept or suppress it: pi's public `compact()` computes
237
+ * `prepareCompaction()` and throws *before* it emits `session_before_compact`,
238
+ * so our handler there never runs on the no-op path. And `ctx.compact()`'s
239
+ * `onError` callback fires only AFTER pi has already emitted a `compaction_end`
240
+ * event carrying the error message (which the interactive UI renders) — so
241
+ * `onError` cannot mute it either. The only robust fix is to not call
242
+ * `ctx.compact()` when pi would no-op. (pi's own `_runAutoCompaction` path is
243
+ * silent on this same condition; the public path we're forced through is the
244
+ * one that throws.)
245
+ *
246
+ * Skipping is correct, not a compromise: by the time this runs, `runCompact()`
247
+ * has already persisted the recall checkpoint (Path A). The durable on-disk
248
+ * trim is only useful when pi can actually summarize a region; a transcript
249
+ * under pi's `keepRecentTokens` budget is small enough that reloading it on
250
+ * resume isn't a token-growth problem, so the durable trim is unnecessary
251
+ * there anyway.
252
+ *
253
+ * Mirrors pi's `prepareCompaction()` return-undefined conditions (compaction.js):
254
+ * (1) last entry is a compaction → "Already compacted"
255
+ * (2) <2 cut-point messages since the last compaction → nothing to summarize
256
+ * (a cut point = any non-toolResult message — user/assistant/bash/custom/
257
+ * branchSummary/compactionSummary — matching pi's isCutPointMessage)
258
+ * (3) transcript tokens since the last compaction < keepRecentTokens → pi
259
+ * keeps everything → nothing to summarize
260
+ * `keepRecentTokens` isn't readable from the extension API, so (3) uses the pi
261
+ * default (20000) as a conservative floor; raise it via
262
+ * `MEGACOMPACT_DURABLE_TRIM_FLOOR` if you raise pi's `compact.keepRecentTokens`.
263
+ *
264
+ * Best-effort: on any read error returns true (skip) — skipping a durable trim
265
+ * is always safe; calling `ctx.compact()` on a no-op throws to the user.
266
+ */
267
+ export function piCompactWouldNoop(ctx) {
268
+ try {
269
+ const branch = ctx.sessionManager.getBranch();
270
+ if (branch.length === 0)
271
+ return true;
272
+ // (1) already compacted — pi throws "Already compacted"
273
+ if (branch[branch.length - 1].type === "compaction")
274
+ return true;
275
+ // boundaryStart = index just after the most recent compaction entry (or 0)
276
+ let boundaryStart = 0;
277
+ for (let i = branch.length - 1; i >= 0; i--) {
278
+ if (branch[i].type === "compaction") {
279
+ boundaryStart = i + 1;
280
+ break;
281
+ }
282
+ }
283
+ let cutPoints = 0;
284
+ let tokens = 0;
285
+ for (let i = boundaryStart; i < branch.length; i++) {
286
+ const e = branch[i];
287
+ if (e.type === "compaction")
288
+ continue;
289
+ let isCut = false;
290
+ for (const m of sessionEntryToContextMessages(e)) {
291
+ // pi's isCutPointMessage: every role except toolResult
292
+ if (m.role !== "toolResult")
293
+ isCut = true;
294
+ const c = m.content;
295
+ const text = typeof c === "string" ? c
296
+ : Array.isArray(c)
297
+ ? c.map((b) => b?.text ?? "").join(" ")
298
+ : "";
299
+ if (text)
300
+ tokens += estimateBlockTokens(text);
301
+ }
302
+ if (isCut)
303
+ cutPoints++;
304
+ }
305
+ // (2) need >=2 cut points so the kept cut isn't the first message
306
+ if (cutPoints < 2)
307
+ return true;
308
+ // (3) transcript under pi's keepRecentTokens budget → pi keeps everything
309
+ if (tokens < durableTrimFloorTokens())
310
+ return true;
311
+ return false;
312
+ }
313
+ catch {
314
+ return true; // safe: skip the durable trim rather than risk a user-facing throw
315
+ }
316
+ }
317
+ /** pi's default keepRecentTokens (compaction settings). Override with
318
+ * MEGACOMPACT_DURABLE_TRIM_FLOOR if you raise pi's compact.keepRecentTokens. */
319
+ function durableTrimFloorTokens() {
320
+ const raw = process.env.MEGACOMPACT_DURABLE_TRIM_FLOOR;
321
+ if (raw !== undefined && Number.isFinite(Number(raw)))
322
+ return Number(raw);
323
+ return 20_000;
324
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * memory-review.ts — review live conversation & persist durable memories.
3
+ *
4
+ * `runMemoryReview` is shared by the pressure-scaled turn-end cadence
5
+ * (mega-events.ts) AND review-on-compact (compact.ts) so both paths run the
6
+ * identical review body. Best-effort + non-fatal: a review failure is swallowed
7
+ * and never breaks the caller.
8
+ */
9
+ import { C, } from "../mega-runtime.js";
10
+ /**
11
+ * Review the live conversation and persist durable memories (S20+S24). Shared by
12
+ * the pressure-scaled turn-end cadence (mega-events.ts) AND review-on-compact
13
+ * (below) so both paths run the identical review body. Best-effort + non-fatal:
14
+ * a review failure is swallowed and never breaks the caller. On success, the
15
+ * number of applied ops is returned so callers can feed the consolidation gate.
16
+ *
17
+ * @param view the engine message view to review (caller builds it)
18
+ * @param label a short source tag for the ticker line (e.g. "pressure" / "turn")
19
+ */
20
+ export async function runMemoryReview(runtime, view, label) {
21
+ try {
22
+ const { reviewConversation } = await import("../../src/memory.js");
23
+ const { applyMemoryOps } = await import("../../src/memoryOps.js");
24
+ const ops = reviewConversation(view, []);
25
+ if (ops.length) {
26
+ await applyMemoryOps(ops, runtime.currentStateDir);
27
+ // S21.2: ops landed — the compaction path reads this counter and fires
28
+ // `consolidateMemories` only when > 0.
29
+ runtime.memoriesTouchedThisCompaction += ops.length;
30
+ runtime.pushTicker(`${C.green}🧠${C.reset} reviewed ${ops.length} memory op${ops.length === 1 ? "" : "s"} (${label})`);
31
+ }
32
+ return ops.length;
33
+ }
34
+ catch {
35
+ /* non-fatal — auto-review must never break the turn loop / compaction */
36
+ return 0;
37
+ }
38
+ }