pi-mega-compact 0.7.7 → 0.7.9

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 (114) hide show
  1. package/README.md +11 -12
  2. package/dist/extensions/dashboard-server/helpers.js +37 -0
  3. package/dist/extensions/dashboard-server/html/all-repos-tab.js +26 -0
  4. package/dist/extensions/dashboard-server/html/body-open.js +23 -0
  5. package/dist/extensions/dashboard-server/html/current-repo-tab.js +130 -0
  6. package/dist/extensions/dashboard-server/html/head-open.js +16 -0
  7. package/dist/extensions/dashboard-server/html/high-score-tab.js +25 -0
  8. package/dist/extensions/dashboard-server/html/repo-detail-modal.js +26 -0
  9. package/dist/extensions/dashboard-server/html/script.js +259 -0
  10. package/dist/extensions/dashboard-server/html/styles.js +103 -0
  11. package/dist/extensions/dashboard-server/html/summary-tab.js +19 -0
  12. package/dist/extensions/dashboard-server/html-template.js +41 -0
  13. package/dist/extensions/dashboard-server/html.js +756 -0
  14. package/dist/extensions/dashboard-server/index-reader.js +133 -0
  15. package/dist/extensions/dashboard-server/server.js +370 -0
  16. package/dist/extensions/dashboard-server/snapshot.js +43 -0
  17. package/dist/extensions/dashboard-server/state.js +30 -0
  18. package/dist/extensions/dashboard-server/types.js +5 -0
  19. package/dist/extensions/dashboard-server.js +7 -1315
  20. package/dist/extensions/mega-commands.js +162 -134
  21. package/dist/extensions/mega-compact.test.js +292 -24
  22. package/dist/extensions/mega-config.js +10 -0
  23. package/dist/extensions/mega-conflict-cmds.js +5 -1
  24. package/dist/extensions/mega-dashboard-cmds.js +29 -22
  25. package/dist/extensions/mega-db-cmds.js +11 -2
  26. package/dist/extensions/mega-events/agent-handlers.js +173 -0
  27. package/dist/extensions/mega-events/compact-handlers.js +133 -0
  28. package/dist/extensions/mega-events/context-handler.js +249 -0
  29. package/dist/extensions/mega-events/register.js +21 -0
  30. package/dist/extensions/mega-events/session-handlers.js +142 -0
  31. package/dist/extensions/mega-events.js +15 -652
  32. package/dist/extensions/mega-pipeline/compact.js +324 -0
  33. package/dist/extensions/mega-pipeline/memory-review.js +38 -0
  34. package/dist/extensions/mega-pipeline/recall.js +147 -0
  35. package/dist/extensions/mega-pipeline.js +9 -480
  36. package/dist/extensions/mega-runtime/helpers.js +40 -0
  37. package/dist/extensions/mega-runtime/query.js +29 -0
  38. package/dist/extensions/mega-runtime/state.js +711 -0
  39. package/dist/extensions/mega-runtime/widget.js +197 -0
  40. package/dist/extensions/mega-runtime.js +15 -932
  41. package/dist/src/store/sqlite/checkpoints.js +145 -0
  42. package/dist/src/store/sqlite/connection.js +35 -0
  43. package/dist/src/store/sqlite/dedup-mirror.js +64 -0
  44. package/dist/src/store/sqlite/foundation.js +38 -0
  45. package/dist/src/store/sqlite/global-index.js +224 -0
  46. package/dist/src/store/sqlite/index-store.js +167 -0
  47. package/dist/src/store/sqlite/maintenance.js +235 -0
  48. package/dist/src/store/sqlite/memories.js +164 -0
  49. package/dist/src/store/sqlite/memory.js +54 -0
  50. package/dist/src/store/sqlite/meta.js +82 -0
  51. package/dist/src/store/sqlite/minhash-lsh.js +47 -0
  52. package/dist/src/store/sqlite/model-snapshots.js +47 -0
  53. package/dist/src/store/sqlite/raptor.js +57 -0
  54. package/dist/src/store/sqlite/raw-transcript.js +134 -0
  55. package/dist/src/store/sqlite/schema.js +250 -0
  56. package/dist/src/store/sqlite/session-state.js +28 -0
  57. package/dist/src/store/sqlite/sessions.js +39 -0
  58. package/dist/src/store/sqlite/stats.js +66 -0
  59. package/dist/src/store/sqlite/transaction.js +19 -0
  60. package/dist/src/store/sqlite/utils.js +120 -0
  61. package/dist/src/store/sqlite.js +20 -1607
  62. package/dist/src/vectorStore/add.js +260 -0
  63. package/dist/src/vectorStore/dedup.js +52 -0
  64. package/dist/src/vectorStore/index.js +10 -0
  65. package/dist/src/vectorStore/queries.js +83 -0
  66. package/dist/src/vectorStore/search.js +95 -0
  67. package/dist/src/vectorStore/session.js +19 -0
  68. package/dist/src/vectorStore/store.js +105 -0
  69. package/dist/src/vectorStore/types.js +6 -0
  70. package/dist/src/vectorStore/utils.js +23 -0
  71. package/extensions/dashboard-server/html.ts +758 -0
  72. package/extensions/dashboard-server/index-reader.ts +130 -0
  73. package/extensions/dashboard-server/server.ts +358 -0
  74. package/extensions/dashboard-server/snapshot.ts +44 -0
  75. package/extensions/dashboard-server/state.ts +33 -0
  76. package/extensions/dashboard-server/types.ts +134 -0
  77. package/extensions/dashboard-server.ts +7 -1431
  78. package/extensions/mega-commands.ts +33 -10
  79. package/extensions/mega-compact.test.ts +453 -37
  80. package/extensions/mega-config.ts +22 -0
  81. package/extensions/mega-conflict-cmds.ts +6 -2
  82. package/extensions/mega-dashboard-cmds.ts +30 -23
  83. package/extensions/mega-db-cmds.ts +11 -3
  84. package/extensions/mega-events/agent-handlers.ts +214 -0
  85. package/extensions/mega-events/compact-handlers.ts +164 -0
  86. package/extensions/mega-events/context-handler.ts +290 -0
  87. package/extensions/mega-events/register.ts +37 -0
  88. package/extensions/mega-events/session-handlers.ts +165 -0
  89. package/extensions/mega-events.ts +15 -732
  90. package/extensions/mega-pipeline/compact.ts +366 -0
  91. package/extensions/mega-pipeline/memory-review.ts +46 -0
  92. package/extensions/mega-pipeline/recall.ts +165 -0
  93. package/extensions/mega-pipeline.ts +9 -537
  94. package/extensions/mega-runtime/helpers.ts +68 -0
  95. package/extensions/mega-runtime/query.ts +29 -0
  96. package/extensions/mega-runtime/state.ts +797 -0
  97. package/extensions/mega-runtime/widget.ts +258 -0
  98. package/extensions/mega-runtime.ts +15 -1076
  99. package/package.json +4 -3
  100. package/src/store/sqlite/checkpoints.ts +204 -0
  101. package/src/store/sqlite/dedup-mirror.ts +114 -0
  102. package/src/store/sqlite/foundation.ts +63 -0
  103. package/src/store/sqlite/global-index.ts +305 -0
  104. package/src/store/sqlite/maintenance.ts +294 -0
  105. package/src/store/sqlite/memories.ts +217 -0
  106. package/src/store/sqlite/meta.ts +108 -0
  107. package/src/store/sqlite/model-snapshots.ts +83 -0
  108. package/src/store/sqlite/raptor.ts +107 -0
  109. package/src/store/sqlite/raw-transcript.ts +221 -0
  110. package/src/store/sqlite/schema.ts +258 -0
  111. package/src/store/sqlite/session-state.ts +38 -0
  112. package/src/store/sqlite/stats.ts +127 -0
  113. package/src/store/sqlite/utils.ts +125 -0
  114. package/src/store/sqlite.ts +20 -2204
@@ -1,1080 +1,19 @@
1
1
  /**
2
- * mega-runtime.ts — the shared live state of the mega-compact extension.
2
+ * mega-runtime.ts — barrel file re-exporting the split submodules under
3
+ * extensions/mega-runtime/.
3
4
  *
4
- * The original mega-compact.ts was a single large closure over ~20 mutable
5
- * variables. This module lifts that state into a `MegaRuntime` class so the
6
- * event/command/pipeline modules can share it without re-declaring it. All
7
- * behavior (store/dashboard rebinding, dashboard snapshot shape, the
8
- * above-editor widget math, model capture) is preserved byte-for-byte from the
9
- * original closure.
5
+ * Originally a single ~1097-line monolith; split into focused submodules:
6
+ * - mega-runtime/widget.ts — above-editor widget helpers + WidgetData
7
+ * - mega-runtime/helpers.ts shared constants, SessionRuntime, ownVersion
8
+ * - mega-runtime/state.ts — the MegaRuntime class
9
+ * - mega-runtime/query.ts — recentUserQuery free function
10
+ *
11
+ * Every symbol previously exported from this file is re-exported here so
12
+ * consumers (mega-compact.ts, mega-commands.ts, mega-events.ts,
13
+ * mega-pipeline.ts, etc.) keep working with no import-path changes.
10
14
  */
11
15
 
12
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
13
- import { sessionEntryToContextMessages } from "@earendil-works/pi-coding-agent";
14
- import type { AgentMessage } from "@earendil-works/pi-agent-core";
15
- import { join, dirname } from "node:path";
16
- import { fileURLToPath } from "node:url";
17
- import { readFileSync, appendFileSync, mkdirSync } from "node:fs";
18
- import { VectorStore } from "../src/vectorStore.js";
19
- import { toEngineMessages } from "../src/adapt.js";
20
- import { normalizeSessionId } from "../src/store.js";
21
- import { Logger } from "../src/log.js";
22
- import {
23
- recordModelSnapshot,
24
- latestModelSnapshot,
25
- upsertRepoRegistry,
26
- recordRepoModel,
27
- getDedupStats,
28
- getCompactCount,
29
- getRecallInjected,
30
- getCacheHitTokensSaved,
31
- type ModelSnapshot,
32
- } from "../src/store/sqlite.js";
33
- import { detectCrossRepoDrift } from "../src/driftDetection.js";
34
- import {
35
- repoStateDir,
36
- resolveRepoRoot,
37
- pressureRatio,
38
- pressureFromPct,
39
- pressureBand,
40
- effectiveThresholdTokens,
41
- type MegaConfig,
42
- type PressureBand,
43
- } from "./mega-config.js";
44
- import { Dashboard, type DashboardSnapshot } from "./mega-dashboard.js";
45
-
46
- export const STATUS_KEY = "mega-compact";
47
- export const WIDGET_KEY = "mega-compact-stats";
48
- export const MARKER_TYPE = "mega-compact-marker";
49
-
50
- /** Cached npm version, read once from this extension's own package.json. */
51
- let CACHED_VERSION: string | null = null;
52
- function ownVersion(): string {
53
- if (CACHED_VERSION !== null) return CACHED_VERSION;
54
- let v = "?";
55
- try {
56
- const here = dirname(fileURLToPath(import.meta.url)); // .../extensions
57
- const pkg = JSON.parse(
58
- readFileSync(join(here, "..", "package.json"), "utf-8"),
59
- );
60
- v = pkg.version ?? "?";
61
- } catch {
62
- v = "?";
63
- }
64
- CACHED_VERSION = v;
65
- return v;
66
- }
67
-
68
- /** Per-session runtime state kept in the closure (mirrors neuralwatt-mcr). */
69
- interface SessionRuntime {
70
- sessionId: string;
71
- persistedThisSession: boolean;
72
- lastCheckpointId: string | undefined;
73
- lastCompactedFrom: number;
74
- lastCompactedTokens: number;
75
- dedupSkips: number; // compactions skipped because regionHash already stored
76
- dedupAttempts: number; // total compaction attempts (for hit-rate denominator)
77
- tokensSaved: number; // this session-instance only: reset on session_start
78
- lastCompactAt: number | null; // wall-clock ms of the last compaction this session
79
- lastNativeCompactAt: number | null; // COMPACT-DEDUP FIX: wall-clock ms of the last NATIVE pi compaction (session_compact event) — used by the agent_end/legacy race guard to skip a redundant ctx.compact() that would throw "Already compacted".
80
- // S25: live dashboard counters (reset on session_start, mirrored to SQLite).
81
- compactCount: number; // compactions performed this session-instance
82
- recallInjections: number; // recall blocks injected this session-instance
83
- cacheHitTokens: number; // tokens saved via cache hits (dedup + recall) this session
84
- }
85
-
86
- /** ANSI palette for the toolbar. The pi TUI's Text component preserves ANSI
87
- * escape codes (see wrapTextWithAnsi), so raw escapes render as colors. No
88
- * chalk dependency needed — these are just strings. */
89
- export const C = {
90
- reset: "\x1b[0m",
91
- dim: "\x1b[2m",
92
- bold: "\x1b[1m",
93
- amber: "\x1b[38;5;214m", // tier / ready
94
- green: "\x1b[38;5;120m", // saved
95
- cyan: "\x1b[38;5;51m", // used / live activity
96
- teal: "\x1b[38;5;37m", // processing (compress/dedup)
97
- magenta: "\x1b[38;5;201m", // dedup rate
98
- blue: "\x1b[38;5;75m", // repo totals
99
- gray: "\x1b[38;5;245m", // labels
100
- red: "\x1b[38;5;203m", // pressure / overflow
101
- };
102
-
103
- const PULSE = ["◐", "◓", "◑", "◒"];
104
-
105
- // Rough tokens-processed-per-second heuristic for the dashboard's "time saved"
106
- // estimate. Throughput varies by model/hardware; this is order-of-magnitude so
107
- // the dashboard can show a human-readable figure, not a precise measurement.
108
- const TOKENS_PER_SEC_ESTIMATE = 2000;
109
-
110
- // ── Full-width widget panel helpers ────────────────────────────────────────
111
- // pi's above-editor widget renderer (a Container of Text lines) does NOT pass
112
- // a terminal width to setWidget(), so lines render left-aligned by default. To
113
- // make the widget read as a full-width status panel we pad each line to the
114
- // real terminal width with a background fill. NOTE: C.reset is a FULL SGR
115
- // reset, so we re-apply the panel bg after every reset to keep the background
116
- // continuous under colored text (and under pi's own trailing reset).
117
- const PANEL_BG = "\x1b[48;5;236m"; // dark slate panel background
118
- const PANEL_RST = "\x1b[0m" + PANEL_BG; // reset fg but retain panel bg
119
-
120
- /** Visible cell width of a string, ignoring ANSI SGR/OSC escapes. */
121
- function visibleWidth(s: string): number {
122
- const stripped = s
123
- .replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "")
124
- .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "");
125
- let w = 0;
126
- for (const ch of stripped) {
127
- const cp = ch.codePointAt(0) ?? 0;
128
- const wide =
129
- cp >= 0x1100 &&
130
- (cp <= 0x115f ||
131
- (cp >= 0x2e80 && cp <= 0x303e) ||
132
- (cp >= 0x3041 && cp <= 0x33ff) ||
133
- (cp >= 0x3400 && cp <= 0x4dbf) ||
134
- (cp >= 0x4e00 && cp <= 0x9fff) ||
135
- (cp >= 0xa000 && cp <= 0xa4cf) ||
136
- (cp >= 0xac00 && cp <= 0xd7a3) ||
137
- (cp >= 0xf900 && cp <= 0xfaff) ||
138
- (cp >= 0xfe30 && cp <= 0xfe4f) ||
139
- (cp >= 0xff00 && cp <= 0xff60) ||
140
- (cp >= 0xffe0 && cp <= 0xffe6) ||
141
- (cp >= 0x1f300 && cp <= 0x1faff) ||
142
- (cp >= 0x20000 && cp <= 0x3fffd));
143
- w += wide ? 2 : 1;
144
- }
145
- return w;
146
- }
147
-
148
- /** Pad a content string (with ANSI colors) to `width` cells using panel bg. */
149
- /** Wrap a string (with ANSI codes) to fit within `maxWidth` visible chars.
150
- * Splits at │ separators or whitespace when possible. */
151
- function wrapLine(text: string, maxWidth: number): string[] {
152
- if (maxWidth <= 0) return [text];
153
- const result: string[] = [];
154
- let current = "";
155
- let currentW = 0;
156
- // Split at │ boundaries first
157
- const segments = text.split("│");
158
- for (let i = 0; i < segments.length; i++) {
159
- const seg = (i > 0 ? "│" : "") + segments[i];
160
- const segW = visibleWidth(PANEL_BG + seg.replace(/\x1b\[0m/g, PANEL_RST));
161
- if (currentW + segW <= maxWidth || currentW === 0) {
162
- current += seg;
163
- currentW += segW;
164
- } else {
165
- result.push(current);
166
- current = seg;
167
- currentW = segW;
168
- }
169
- }
170
- if (current) result.push(current);
171
- return result;
172
- }
173
-
174
- function panelLine(content: string, width: number): string {
175
- const withBg = PANEL_BG + content.replace(/\x1b\[0m/g, PANEL_RST);
176
- const pad = Math.max(0, width - visibleWidth(withBg));
177
- return withBg + " ".repeat(pad) + "\x1b[0m";
178
- }
179
-
180
- /** A full-width hairline bar (top/bottom border of the panel). */
181
- function panelBar(width: number, ch = "─"): string {
182
- return PANEL_BG + ch.repeat(Math.max(0, width)) + "\x1b[0m";
183
- }
184
-
185
- /** Token-count formatter: M at/above 1e6, k at/above 1e3, raw below.
186
- * 5,472,700 → "5.5mil", 24,100 → "24.1k", 142 → "142". */
187
- function fmtTokens(x: number): string {
188
- return x >= 1_000_000
189
- ? `${(x / 1_000_000).toFixed(1)}mil`
190
- : x >= 1000
191
- ? `${(x / 1000).toFixed(1)}k`
192
- : `${Math.round(x)}`;
193
- }
194
-
195
- /** Retro gradient bar — `w` cells shaded by fill position (green→amber→red).
196
- * Used for CONTEXT fill where low=green (room) and high=red (near the limit). */
197
- function ramp(pct: number, w = 12): string {
198
- const cells = ["▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"];
199
- const scaled = Math.max(0, Math.min(w, pct * w));
200
- const full = Math.floor(scaled);
201
- const frac = scaled - full;
202
- const fracCell = frac > 0 ? cells[Math.round(frac * (cells.length - 1))] : "";
203
- let out = "";
204
- for (let i = 0; i < full; i++)
205
- out += (i / w < 0.6 ? C.green : i / w < 0.85 ? C.amber : C.red) + "█";
206
- if (fracCell)
207
- out +=
208
- (full / w < 0.6 ? C.green : full / w < 0.85 ? C.amber : C.red) + fracCell;
209
- out +=
210
- C.dim + "░".repeat(Math.max(0, w - full - (fracCell ? 1 : 0))) + C.reset;
211
- return out;
212
- }
213
-
214
- /** Human "time since" string from a millisecond delta (or null → "never"). */
215
- function sinceCompactStr(ms: number | null): string {
216
- if (ms == null) return "never";
217
- const s = Math.floor(ms / 1000);
218
- if (s < 60) return `${s}s ago`;
219
- const m = Math.floor(s / 60);
220
- if (m < 60) return `${m}m ago`;
221
- const h = Math.floor(m / 60);
222
- if (h < 24) return `${h}h ago`;
223
- return `${Math.floor(h / 24)}d ago`;
224
- }
225
-
226
- interface TickerEntry {
227
- text: string;
228
- at: number;
229
- }
230
-
231
- /** Immutable snapshot of everything the above-editor widget needs to render.
232
- * Computed once per `snapshot()` (event-driven) and read by `buildWidgetLines`
233
- * on every TUI render frame, so frame rendering stays allocation-cheap and the
234
- * panel auto-fits whatever width pi passes to the setWidget factory. */
235
- interface WidgetData {
236
- version: string;
237
- tierLabel: string;
238
- triggerLabel: string;
239
- pctStr: string;
240
- tokStr: string;
241
- maxStr: string;
242
- ctxPct: number;
243
- chk: number;
244
- agentStr: string;
245
- turnStr: string;
246
- dedupStr: string;
247
- sessIn: number;
248
- sessKept: number;
249
- sTxt: string;
250
- repoIn: number;
251
- repoKept: number;
252
- rTxt: string;
253
- repoChk: number;
254
- repoSess: number;
255
- modelStr: string;
256
- sinceCompact: number | null;
257
- embedderName: string;
258
- compStr: string;
259
- driftStatus: "ok" | "warn";
260
- agentsActive: boolean;
261
- fresh: boolean;
262
- ticker: TickerEntry[];
263
- lastWhy: string | undefined;
264
- tierTrace: string | undefined;
265
- pulsing: boolean;
266
- }
267
-
268
- export class MegaRuntime {
269
- config: MegaConfig;
270
- // Store/dashboard/logger are rebound per-repo by bindRepo() so each git repo
271
- // gets its own isolated state dir. They start bound to the global default.
272
- store: VectorStore;
273
- logger: Logger;
274
- dashboard: Dashboard;
275
- activeRepoRoot: string | null = null;
276
- currentStateDir: string;
277
-
278
- // The only mutable per-session state. Reset on session_start / session_tree.
279
- rt: SessionRuntime = {
280
- sessionId: normalizeSessionId(undefined),
281
- persistedThisSession: false,
282
- lastCheckpointId: undefined,
283
- lastCompactedFrom: 0,
284
- lastCompactedTokens: 0,
285
- dedupSkips: 0,
286
- dedupAttempts: 0,
287
- tokensSaved: 0,
288
- lastCompactAt: null,
289
- lastNativeCompactAt: null,
290
- compactCount: 0,
291
- recallInjections: 0,
292
- cacheHitTokens: 0,
293
- };
294
- debounceUntil = 0;
295
- // S16: debounce for the agent_end resume nudge (avoid busy-loops).
296
- resumeNudgeUntil = 0;
297
- // Agent tracking for real-time widget updates
298
- activeAgents = 0;
299
- currentTurn = 0;
300
- // Recall block produced by auto-inline (resume/branch) that the next
301
- // before_agent_start should prepend to the system prompt. Unset after use.
302
- pendingRecallBlock: string | undefined;
303
- // S21: memory recall block, parallel to pendingRecallBlock. Same one-shot
304
- // semantics; composed with the checkpoint block in before_agent_start.
305
- pendingMemoryRecallBlock: string | undefined;
306
- statusKey: string | undefined; // current status text for dashboard
307
- // Active model/provider (for real cost estimation). Captured from ctx.model
308
- // on model_select + session_start; persisted to SQL so cost + the dashboard
309
- // can read it without a live ctx.
310
- currentModel: ModelSnapshot | undefined;
311
- // Live "what it's doing right now" timestamp, used for the fresh-window.
312
- lastActivityAt = 0;
313
- // Live per-tier dedup trace (Phase 1): e.g. "L0 ✓ → L1 ✓ → L2 0.91 → stored".
314
- // Built from the store's sync onTier callback during a compaction so the user
315
- // watches each tier evaluate in real time. Cleared once the outcome settles.
316
- tierTrace: string | undefined;
317
- // Phase 3 — standout toolbar state.
318
- // Recall/activity ticker: a small ring buffer (≤5) of recent compact/recall
319
- // events so the widget shows a live history instead of a single last action.
320
- ticker: TickerEntry[] = [];
321
- readonly TICKER_MAX = 5;
322
- // Pulsing status: set true while a compaction is in flight, cleared on result.
323
- pulsing = false;
324
- // S21.2: set by `applyMemoryOps` when a memory add/replace/remove lands in
325
- // the current compaction. The pipeline reads this after a successful compact
326
- // to decide whether to fire `consolidateMemories` (skip the work entirely
327
- // when no memory rows changed).
328
- memoriesTouchedThisCompaction = 0;
329
- // Rolling "saved" goal for the progress bar — grows as we save more, so the
330
- // bar always has a meaningful denominator (never sits at 100% forever).
331
- savedGoal = 50_000;
332
- // Last explain-why line (dedup reason / anchor-kept / superseded), surfaced
333
- // while fresh.
334
- lastWhy: string | undefined = undefined;
335
-
336
- // Context tracking for the dashboard (updated in the context handler).
337
- lastCtxTokens: number | null = null;
338
- lastCtxPercent: number | null = null;
339
- lastCtxWindow = 0;
340
-
341
- // Latest computed widget payload (recomputed per snapshot, rendered per frame).
342
- widgetData: WidgetData | null = null;
343
- // Cached cross-repo drift status (recomputed at most every 30s — it opens the
344
- // machine-wide registry DB, so we don't want to do it on every render frame).
345
- private driftCache: { at: number; status: "ok" | "warn" } | null = null;
346
-
347
- /**
348
- * DIAG counters for the "team run doesn't relieve context" investigation.
349
- * Plain integers, incremented at the three compaction decision points. They
350
- * let a headless test drive the real event handlers and assert the firing
351
- * cadence without scraping log files. Inert in production (the live-trim and
352
- * before-compact probes also emit logger.info, but these counters are always
353
- * updated and cost nothing).
354
- */
355
- diagLiveTrimFires = 0; // context handler returned a trimmed view
356
- diagBeforeCompactFires = 0; // session_before_compact handler entered
357
- diagBeforeCompactSupplied = 0; // session_before_compact supplied our trim
358
- diagAgentEndIdle = 0; // agent_end with activeAgents===0
359
- diagAgentEndDurable = 0; // agent_end fired ctx.compact() (mid-run durable trim)
360
- diagAgentEndDurableSkipRecent = 0; // agent_end skipped ctx.compact() — compaction in last 10s (race guard)
361
- // Per-skip-path counters for the team-run diagnosis.
362
- diagCtxFastGate = 0; // returned at token fast-gate (below threshold)
363
- diagCtxNoCompact = 0; // autoCompactCheck().shouldCompact === false
364
- diagCtxDebounce = 0; // debounceUntil not yet elapsed
365
- diagCtxRunSkipped = 0; // runCompact() returned skipped
366
- diagCtxCutNull = 0; // computeLiveTrimCut returned null (anchor/boundary)
367
- diagCtxThrown = 0; // live-trim try threw (caught)
368
-
369
- /**
370
- * S26 capture instrumentation: the "model_snapshots empty → $0.00 cost card"
371
- * bug was invisible because captureModel swallowed the DB write in a silent
372
- * `catch {}`. These always-updated counters (zero cost) let a headless test or
373
- * a live capture tell whether captureModel ran and whether the snapshot landed.
374
- */
375
- diagCaptureModelCalls = 0; // captureModel entered with a populated ctx.model
376
- diagCaptureModelFails = 0; // recordModelSnapshot threw → model_snapshots stays empty
377
-
378
- /**
379
- * Live 0–1 pressure — how full the context window is relative to the
380
- * compaction threshold.
381
- *
382
- * RECONCILE (BACKLOG dual-basis flicker): when the model context window is
383
- * known we base pressure consistently on the *percentage* basis
384
- * (`lastCtxPercent / (tierPct*100)`). This keeps the band stable whether the
385
- * latest context event carried a token count or only a percentage, so the
386
- * threshold comparison doesn't jump when a token-count event arrives vs a
387
- * percent-only event. We only fall back to the token-count basis
388
- * (`config.thresholdTokens`) when the window is unknown (e.g. before the first
389
- * context event, or a `custom` tier with no tierPct). Always finite + in [0,1].
390
- */
391
- get pressure(): number {
392
- if (
393
- this.lastCtxWindow > 0 &&
394
- this.config.tierPct != null &&
395
- this.lastCtxPercent != null
396
- ) {
397
- // pressureFromPct(x) = x/100, and x = lastCtxPercent/tierPct, so this is
398
- // exactly the intended lastCtxPercent/(tierPct*100) 0–1 ratio: at the
399
- // fire point (lastCtxPercent == tierPct*100) pressure == 1.0, matching the
400
- // token-based pressureRatio(currentTokens, effectiveThreshold) reading so
401
- // the band doesn't jump when a token-count vs percent-only event arrives.
402
- return pressureFromPct(this.lastCtxPercent / this.config.tierPct);
403
- }
404
- if (
405
- this.lastCtxTokens != null &&
406
- this.lastCtxTokens > 0 &&
407
- this.config.thresholdTokens > 0
408
- ) {
409
- return pressureRatio(this.lastCtxTokens, this.config.thresholdTokens);
410
- }
411
- return pressureFromPct(this.lastCtxPercent);
412
- }
413
-
414
- /**
415
- * The live compaction FIRE POINT in tokens: the effective threshold scaled by
416
- * the current model context window (`tierPct * window`) when known, else the
417
- * boot fallback `config.thresholdTokens`. This is what the FAST GATE /
418
- * `autoCompactCheck` / agent_end durable-trigger compare against, so
419
- * compaction fires at tier% of the window for ANY model size (200k or 1M),
420
- * always below pi's native auto-compaction (~80% of window).
421
- */
422
- get effectiveThreshold(): number {
423
- return effectiveThresholdTokens({
424
- tierPct: this.config.tierPct,
425
- fallbackThreshold: this.config.thresholdTokens,
426
- window: this.lastCtxWindow,
427
- });
428
- }
429
-
430
- /** Live discrete pressure band (low/medium/high/ultra/mega) over `pressure`. */
431
- get pressureBand(): PressureBand {
432
- return pressureBand(this.pressure);
433
- }
434
-
435
- constructor(config: MegaConfig) {
436
- this.config = config;
437
- this.store = new VectorStore({
438
- dedupSim: config.dedupSim,
439
- stateDir: config.stateDir,
440
- });
441
- this.logger = new Logger({
442
- enabled: config.debug,
443
- path: join(config.stateDir, "mega-compact.log"),
444
- });
445
- this.dashboard = new Dashboard(config.stateDir);
446
- this.currentStateDir = config.stateDir;
447
- }
448
-
449
- // ---- per-repo binding -----------------------------------------------------
450
-
451
- /**
452
- * Point store/dashboard/logger at the current repo's state dir. Rebuilds the
453
- * instances only when the repo root changes, so cross-repo dedup stats, db,
454
- * and events are fully isolated. Falls back to the global default outside git.
455
- */
456
- bindRepo(cwd: string | undefined): string {
457
- const dir = cwd
458
- ? repoStateDir(cwd, this.config.stateDir)
459
- : this.config.stateDir;
460
- const key = cwd ? (resolveRepoRoot(cwd) ?? dir) : dir;
461
- if (key === this.activeRepoRoot) return dir;
462
- this.activeRepoRoot = key;
463
- this.currentStateDir = dir;
464
- this.store = new VectorStore({
465
- dedupSim: this.config.dedupSim,
466
- stateDir: dir,
467
- });
468
- this.logger = new Logger({
469
- enabled: this.config.debug,
470
- path: join(dir, "mega-compact.log"),
471
- });
472
- this.dashboard = new Dashboard(dir);
473
- // Aggregate this repo into the machine-wide index so the multi-repo
474
- // dashboard (Summary / All-repos tabs) can show it alongside every other
475
- // repo. Best-effort + non-fatal: a read-only index dir or contention must
476
- // never break the per-repo compaction path. Runs only on repo-switch
477
- // (this branch), so it's infrequent — not per-context-event.
478
- try {
479
- const repo = this.store.repoStats();
480
- const di = this.store.dataInvariant();
481
- const root = key !== dir ? key : (resolveRepoRoot(cwd ?? dir) ?? dir);
482
- upsertRepoRegistry({
483
- repoRoot: root,
484
- displayName: root.split(/[\\/]/).filter(Boolean).pop() ?? root,
485
- stateDir: dir,
486
- checkpointCount: repo.checkpointCount,
487
- tokensSaved: repo.tokensSaved,
488
- compressedOriginalBytes: di.compressedOriginalBytes,
489
- });
490
- } catch {
491
- /* non-fatal: index aggregation must not block compaction */
492
- }
493
- return dir;
494
- }
495
-
496
- // ---- dashboard snapshot + widget ------------------------------------------
497
-
498
- /** Collect live state and write it to disk (+ paint the above-editor widget). */
499
- snapshot(ctx?: ExtensionContext): void {
500
- if (ctx) this.bindRepo(ctx.cwd);
501
- const st = this.store.stats(this.rt.sessionId);
502
- const repo = this.store.repoStats();
503
- const di = this.store.dataInvariant();
504
- // Live + store-wide cache-hit / compaction counters for the dashboard.
505
- const ds = getDedupStats(this.currentStateDir);
506
- const cacheHitsTotal = ds.deduped + getRecallInjected(this.currentStateDir);
507
- const cacheHitsTotalTokens = getCacheHitTokensSaved(this.currentStateDir);
508
- const cacheHitsSession = this.rt.dedupSkips + this.rt.recallInjections;
509
- const sec = (tok: number) => (tok || 0) / TOKENS_PER_SEC_ESTIMATE;
510
- // Active model/provider for the current-repo card + the multi-repo table.
511
- const modelSnap = latestModelSnapshot(this.currentStateDir);
512
- const model = modelSnap
513
- ? {
514
- name: modelSnap.modelName ?? modelSnap.modelId,
515
- provider: modelSnap.provider,
516
- providerName: modelSnap.providerName ?? "",
517
- inputRate: modelSnap.inputRate,
518
- outputRate: modelSnap.outputRate,
519
- }
520
- : undefined;
521
- // effectiveThresholdPct: the live fire point as a % of the window (null for
522
- // `custom`, which has no tierPct). Used by armed/ready + the dashboard.
523
- const effectiveThresholdPct =
524
- this.config.tierPct != null ? this.config.tierPct * 100 : null;
525
- // armed lights at/above the REAL fire point: max(effectiveThresholdPct,
526
- // fastGatePct). fastGatePct already equals tierPct*100 by default, but a
527
- // MEGACOMPACT_FAST_GATE_PCT override can raise it, so we take the max.
528
- const armed =
529
- this.lastCtxPercent != null &&
530
- this.lastCtxPercent >=
531
- Math.max(effectiveThresholdPct ?? 0, this.config.fastGatePct);
532
- const ready = armed && (this.lastCtxTokens ?? 0) >= this.effectiveThreshold;
533
- this.dashboard.snapshot({
534
- version: 1,
535
- updatedAt: new Date().toISOString(),
536
- // S24: the headline tier is the LIVE pressure band; the env preset is kept
537
- // alongside as presetTier so the dashboard can show both.
538
- tier: this.pressureBand,
539
- presetTier: this.config.tier,
540
- pressure: this.pressure,
541
- config: {
542
- fastGatePct: this.config.fastGatePct,
543
- thresholdTokens: this.effectiveThreshold,
544
- tierPct: this.config.tierPct,
545
- effectiveThresholdPct,
546
- anchorUserMessages: this.config.anchorUserMessages,
547
- preserveRecent: this.config.preserveRecent,
548
- auto: this.config.auto,
549
- autoInline: this.config.autoInline,
550
- },
551
- session: {
552
- id: this.rt.sessionId,
553
- state: this.statusKey ?? "idle",
554
- persistedThisSession: this.rt.persistedThisSession,
555
- lastCheckpointId: this.rt.lastCheckpointId ?? null,
556
- lastCompactedFrom: this.rt.lastCompactedFrom,
557
- lastCompactedTokens: this.rt.lastCompactedTokens,
558
- dedupSkips: this.rt.dedupSkips,
559
- dedupAttempts: this.rt.dedupAttempts,
560
- },
561
- context: {
562
- tokens: this.lastCtxTokens,
563
- percent: this.lastCtxPercent,
564
- contextWindow: this.lastCtxWindow,
565
- },
566
- trigger: {
567
- armed,
568
- ready,
569
- currentTokens: this.lastCtxTokens,
570
- thresholdTokens: this.effectiveThreshold,
571
- fastGatePct: this.config.fastGatePct,
572
- tierPct: this.config.tierPct,
573
- effectiveThresholdPct,
574
- },
575
- crew: { activeAgents: this.activeAgents, currentTurn: this.currentTurn },
576
- store: {
577
- checkpointCount: st.checkpointCount,
578
- totalTokenEstimate: st.totalTokenEstimate,
579
- originalTokens: st.originalTokens,
580
- tokensSaved: this.rt.tokensSaved,
581
- injectedCount: st.injectedCount,
582
- dedupHitRate: st.dedupHitRate,
583
- storageDedupRate: st.storageDedupRate,
584
- dedupAttempts: st.dedupAttempts,
585
- dedupCollapsed: st.dedupCollapsed,
586
- },
587
- // Reconciled token accounting (single canonical formula, session + repo).
588
- // Freed = In − Out; In = Freed + Out. session.Freed = rt.tokensSaved (incl.
589
- // deduped-away originals); repo.Freed = repo.tokensSaved meta counter.
590
- compression: {
591
- session: {
592
- tokensIn: this.rt.tokensSaved + st.totalTokenEstimate,
593
- tokensOut: st.totalTokenEstimate,
594
- tokensFreed: this.rt.tokensSaved,
595
- compressionPct:
596
- this.rt.tokensSaved + st.totalTokenEstimate > 0
597
- ? this.rt.tokensSaved /
598
- (this.rt.tokensSaved + st.totalTokenEstimate)
599
- : 0,
600
- dedupPct: st.storageDedupRate,
601
- },
602
- repo: {
603
- tokensIn: repo.tokensSaved + repo.totalTokenEstimate,
604
- tokensOut: repo.totalTokenEstimate,
605
- tokensFreed: repo.tokensSaved,
606
- compressionPct:
607
- repo.tokensSaved + repo.totalTokenEstimate > 0
608
- ? repo.tokensSaved / (repo.tokensSaved + repo.totalTokenEstimate)
609
- : 0,
610
- dedupPct: repo.storageDedupRate,
611
- },
612
- },
613
- repo: {
614
- checkpointCount: repo.checkpointCount,
615
- totalTokenEstimate: repo.totalTokenEstimate,
616
- originalTokens: repo.originalTokens,
617
- tokensSaved: repo.tokensSaved,
618
- sessionCount: repo.sessionCount,
619
- dedupAttempts: repo.dedupAttempts,
620
- dedupCollapsed: repo.dedupCollapsed,
621
- storageDedupRate: repo.storageDedupRate,
622
- },
623
- integrity: {
624
- regionsRetained: di.regionsRetained,
625
- compressedOriginalBytes: di.compressedOriginalBytes,
626
- duplicatesCollapsed: di.duplicatesCollapsed,
627
- bytesPermanentlyDeleted: di.bytesPermanentlyDeleted,
628
- },
629
- cacheHits: {
630
- session: cacheHitsSession,
631
- total: cacheHitsTotal,
632
- sessionTokensSaved: this.rt.cacheHitTokens,
633
- totalTokensSaved: cacheHitsTotalTokens,
634
- },
635
- compacts: {
636
- session: this.rt.compactCount,
637
- total: getCompactCount(this.currentStateDir),
638
- },
639
- timeSaved: {
640
- compact: { sessionSec: sec(this.rt.tokensSaved), totalSec: sec(this.store.repoStats().tokensSaved) },
641
- cacheHit: { sessionSec: sec(this.rt.cacheHitTokens), totalSec: sec(cacheHitsTotalTokens) },
642
- },
643
- model,
644
- } as DashboardSnapshot);
645
-
646
- // Live stats widget above the editor
647
- if (ctx) {
648
- // ── gather widget data (computed per snapshot, rendered per frame) ────
649
- const tokStr =
650
- this.lastCtxTokens != null
651
- ? `${Math.round(this.lastCtxTokens / 1000)}k`
652
- : "?";
653
- const maxStr =
654
- this.lastCtxWindow > 0
655
- ? `${Math.round(this.lastCtxWindow / 1000)}k`
656
- : "?";
657
- const pctStr =
658
- this.lastCtxPercent != null
659
- ? `${Math.round(this.lastCtxPercent * 10) / 10}%`
660
- : "?%";
661
- // S24: the tier label is the LIVE pressure band (low/medium/high/ultra/
662
- // mega), not the static env preset. It climbs as context fills.
663
- const liveBand = this.pressureBand;
664
- const tierLabel = `${C.bold}${liveBand}${C.reset}${C.gray}·${this.config.tier}${C.reset}`;
665
- const triggerLabel = ready
666
- ? `${C.green}● ready${C.reset}`
667
- : armed
668
- ? `${C.amber}◐ armed${C.reset}`
669
- : `${C.gray}○ idle${C.reset}`;
670
- // Storage dedup rate is cumulative (store-wide, per-repo) and survives
671
- // session resets. Always show a number (decimal for sub-10%).
672
- const storageRate = st.storageDedupRate; // 0..1
673
- const dedupStr =
674
- storageRate * 100 >= 10
675
- ? `${Math.round(storageRate * 100)}%`
676
- : `${(storageRate * 100).toFixed(1)}%`;
677
- // Agents view: count + status (S27 per-agent tokens are gated on P0).
678
- const agentLabel =
679
- this.activeAgents > 0
680
- ? `🤖 ${this.activeAgents} agent${this.activeAgents === 1 ? "" : "s"}`
681
- : `${C.dim}🤖 idle${C.reset}`;
682
- const agentStr = ` │ ${agentLabel}`;
683
- const turnStr = this.currentTurn > 0 ? ` │ turn ${this.currentTurn}` : "";
684
- // Reconciled in/out view (session + repo) — ONE canonical formula.
685
- const sessIn = this.rt.tokensSaved + st.totalTokenEstimate;
686
- const sessKept = st.totalTokenEstimate;
687
- const sessPct = sessIn > 0 ? this.rt.tokensSaved / sessIn : 0;
688
- const repoIn = repo.tokensSaved + repo.totalTokenEstimate;
689
- const repoKept = repo.totalTokenEstimate;
690
- const repoPct = repoIn > 0 ? repo.tokensSaved / repoIn : 0;
691
- const sTxt = (sessPct * 100).toFixed(sessPct * 100 >= 10 ? 0 : 1);
692
- const rTxt = (repoPct * 100).toFixed(repoPct * 100 >= 10 ? 0 : 1);
693
- const ctxPct =
694
- this.lastCtxPercent != null ? this.lastCtxPercent / 100 : 0;
695
- // Model + provider (S26 capture) for the header.
696
- const modelName = modelSnap?.modelName ?? modelSnap?.modelId ?? "?";
697
- const modelStr = modelSnap?.provider
698
- ? `${modelName}·${modelSnap.provider}`
699
- : modelName;
700
- // Since-last-compact (ms; null until first compaction this session).
701
- const sinceCompact =
702
- this.rt.lastCompactAt != null
703
- ? Date.now() - this.rt.lastCompactAt
704
- : null;
705
- // Memory store: embedder + compression ratio (original / stored).
706
- const embedderName = this.embedderName();
707
- const compRatio =
708
- st.originalTokens > 0 && st.totalTokenEstimate > 0
709
- ? st.originalTokens / st.totalTokenEstimate
710
- : st.originalTokens > 0
711
- ? 1
712
- : 0;
713
- const compStr = compRatio >= 1 ? `${compRatio.toFixed(1)}x` : "—";
714
- // Cross-repo drift status (cached, read-only).
715
- const driftStatus = this.driftStatus();
716
- const agentsActive = this.activeAgents > 0;
717
-
718
- this.widgetData = {
719
- version: ownVersion(),
720
- tierLabel,
721
- triggerLabel,
722
- pctStr,
723
- tokStr,
724
- maxStr,
725
- ctxPct,
726
- chk: st.checkpointCount,
727
- agentStr,
728
- turnStr,
729
- dedupStr,
730
- sessIn,
731
- sessKept,
732
- sTxt,
733
- repoIn,
734
- repoKept,
735
- rTxt,
736
- repoChk: repo.checkpointCount,
737
- repoSess: repo.sessionCount,
738
- modelStr,
739
- sinceCompact,
740
- embedderName,
741
- compStr,
742
- driftStatus,
743
- agentsActive,
744
- fresh: Date.now() - this.lastActivityAt < 4000,
745
- ticker: this.ticker,
746
- lastWhy: this.lastWhy,
747
- tierTrace: this.tierTrace,
748
- pulsing: this.pulsing,
749
- };
750
- // Auto-fit: register a factory so pi re-renders the panel at the REAL
751
- // terminal width every frame (tui.columns), instead of guessing with
752
- // process.stdout.columns. buildWidgetLines reads this.widgetData live.
753
- this.renderWidget(ctx);
754
- }
755
- }
756
-
757
- /** Register the above-editor widget as a width-aware factory so pi re-renders
758
- * it at the REAL terminal width every frame (auto-fit wide/narrow). The
759
- * factory returns a minimal Component whose render() reads this.widgetData.
760
- */
761
- private renderWidget(ctx: ExtensionContext): void {
762
- ctx.ui.setWidget(
763
- WIDGET_KEY,
764
- (_tui, _theme) => ({
765
- render: (width: number) =>
766
- this.buildWidgetLines(width > 0 ? width : 200),
767
- invalidate: () => {},
768
- }),
769
- { placement: "aboveEditor" },
770
- );
771
- }
772
-
773
- /** Build the full-width panel lines from the latest snapshot. Cheap: reads
774
- * only this.widgetData + a couple of live counters; no DB/IO. */
775
- private buildWidgetLines(width: number): string[] {
776
- const wd = this.widgetData;
777
- if (!wd) {
778
- return [
779
- panelBar(width, "─"),
780
- panelLine(" mega-compact: warming up…", width),
781
- panelBar(width, "─"),
782
- ];
783
- }
784
- const pulse = wd.pulsing
785
- ? `${C.cyan}${PULSE[Math.floor(Date.now() / 250) % PULSE.length]}${C.reset} `
786
- : "";
787
- const sep = ` ${C.dim}│${C.reset} `;
788
- // Build one long content line — let terminal wrap it naturally
789
- const content = [
790
- `${C.amber}⚡ ${wd.tierLabel}${C.reset} v${C.bold}${wd.version}${C.reset} ${ramp(wd.ctxPct, 20)} ${C.bold}${wd.pctStr}${C.reset} ${wd.tokStr}/${wd.maxStr}`,
791
- wd.triggerLabel,
792
- `${C.cyan}${wd.modelStr}${C.reset}`,
793
- `${wd.chk} chk${wd.agentStr}${wd.turnStr}`,
794
- `${C.magenta}dup ${wd.dedupStr}${C.reset}`,
795
- `${C.gray}sess${C.reset} ${fmtTokens(wd.sessIn)}→${fmtTokens(wd.sessKept)} kept ${C.green}(${wd.sTxt}% freed)${C.reset}`,
796
- `${C.gray}all-time${C.reset} ${fmtTokens(wd.repoIn)}→${fmtTokens(wd.repoKept)} kept ${C.blue}(${wd.rTxt}% freed)${C.reset}`,
797
- `${wd.repoChk} chk/${wd.repoSess} sess`,
798
- `${C.gray}mem${C.reset} ${wd.embedderName} · ${wd.chk} chunks · ${C.blue}comp ${wd.compStr}${C.reset}`,
799
- `${C.gray}drift${C.reset} ${wd.driftStatus === "ok" ? C.green : C.amber}${wd.driftStatus}${C.reset}`,
800
- `${C.gray}compact${C.reset} ${sinceCompactStr(wd.sinceCompact)}`,
801
- ].join(sep);
802
- // Wrap to terminal width and pad each line
803
- const wrapped = wrapLine(content, width - 2); // 2-char indent
804
- const lines: string[] = [
805
- panelBar(width, "─"),
806
- ...wrapped.map((l) => panelLine(l, width)),
807
- ];
808
- // L4 — agents block (S27, count + status; per-agent tokens gated on P0)
809
- if (wd.agentsActive) {
810
- lines.push(
811
- panelLine(
812
- ` ${C.cyan}🤖 ${this.activeAgents} active${wd.turnStr}${C.reset}`,
813
- width,
814
- ),
815
- );
816
- }
817
- // L5 — live ticker / activity (♻ deduped … why, or tier trace, or pulsing)
818
- if (wd.tierTrace && wd.fresh) {
819
- lines.push(panelLine(` ${pulse}${wd.tierTrace}`, width));
820
- } else if (wd.ticker.length > 0) {
821
- const step = Math.floor(Date.now() / 250);
822
- const idx = wd.ticker.length - 1 - (step % wd.ticker.length);
823
- const head = wd.ticker[idx].text;
824
- const why = wd.lastWhy ? ` ${C.gray}· ${wd.lastWhy}${C.reset}` : "";
825
- const more =
826
- wd.ticker.length > 1
827
- ? ` ${C.dim}(+${wd.ticker.length - 1} more)${C.reset}`
828
- : "";
829
- lines.push(
830
- panelLine(
831
- ` ${wd.fresh ? C.teal : C.dim}${head}${why}${more}${C.reset}`,
832
- width,
833
- ),
834
- );
835
- } else if (wd.pulsing) {
836
- lines.push(panelLine(` ${pulse}${C.teal}compacting…${C.reset}`, width));
837
- }
838
- // bottom border
839
- lines.push(panelBar(width, "─"));
840
- return lines;
841
- }
842
-
843
- /** Active embedder name for the memory-store line (Trigram default / MiniLM). */
844
- private embedderName(): string {
845
- // MINILM_EMBEDDER flag lives in src/config/dedup.ts; read the same env var
846
- // the embedder factory uses so the label matches what's actually running.
847
- return process.env.MEGACOMPACT_MINILM === "true" ||
848
- process.env.MEGACOMPACT_MINILM === "1"
849
- ? "MiniLM"
850
- : "Trigram";
851
- }
852
-
853
- /** Cross-repo drift status (ok | warn), cached for 30s (opens the registry DB). */
854
- private driftStatus(): "ok" | "warn" {
855
- const now = Date.now();
856
- if (this.driftCache && now - this.driftCache.at < 30_000)
857
- return this.driftCache.status;
858
- let status: "ok" | "warn" = "ok";
859
- try {
860
- const report = detectCrossRepoDrift();
861
- status = report.totals.warn > 0 ? "warn" : "ok";
862
- } catch {
863
- status = "ok";
864
- }
865
- this.driftCache = { at: now, status };
866
- return status;
867
- }
868
-
869
- setStatus(ctx: ExtensionContext, text: string | undefined): void {
870
- this.statusKey = text;
871
- ctx.ui.setStatus(STATUS_KEY, text);
872
- }
873
-
874
- resetRuntime(sessionId: string | undefined): void {
875
- const sid = normalizeSessionId(sessionId);
876
- if (this.rt.sessionId === sid && this.rt.persistedThisSession) return; // same session, keep checkpoint memory
877
- this.rt = {
878
- sessionId: sid,
879
- persistedThisSession: false,
880
- lastCheckpointId: undefined,
881
- lastCompactedFrom: 0,
882
- lastCompactedTokens: 0,
883
- dedupSkips: 0,
884
- dedupAttempts: 0,
885
- tokensSaved: 0,
886
- lastCompactAt: null,
887
- lastNativeCompactAt: null,
888
- compactCount: 0,
889
- recallInjections: 0,
890
- cacheHitTokens: 0,
891
- };
892
- this.statusKey = undefined;
893
- this.activeAgents = 0;
894
- this.currentTurn = 0;
895
- this.lastActivityAt = 0;
896
- this.tierTrace = undefined;
897
- this.ticker.length = 0;
898
- this.pulsing = false;
899
- this.savedGoal = 50_000;
900
- this.lastWhy = undefined;
901
- }
902
-
903
- /**
904
- * Capture the active model/provider from ctx.model and persist it so cost
905
- * estimation + the dashboard can read real pricing. Cheap + idempotent-ish:
906
- * only writes a new row when the model id changes (models change rarely).
907
- */
908
- captureModel(ctx: ExtensionContext): void {
909
- const m = ctx.model;
910
- if (!m) {
911
- this.appendEvent("captureModel:no-model", { cwd: ctx.cwd });
912
- return;
913
- }
914
- if (
915
- this.currentModel &&
916
- this.currentModel.modelId === m.id &&
917
- this.currentModel.provider === m.provider
918
- )
919
- return;
920
- let providerName: string | null = null;
921
- try {
922
- providerName =
923
- ctx.modelRegistry?.getProviderDisplayName(m.provider) ?? null;
924
- } catch {
925
- /* optional */
926
- }
927
- const snap: Omit<ModelSnapshot, "capturedAt"> = {
928
- provider: m.provider,
929
- providerName,
930
- modelId: m.id,
931
- modelName: m.name ?? null,
932
- inputRate: m.cost?.input ?? 0,
933
- outputRate: m.cost?.output ?? 0,
934
- contextWindow: m.contextWindow ?? 0,
935
- maxTokens: m.maxTokens ?? 0,
936
- reasoning: !!m.reasoning,
937
- };
938
- this.currentModel = { ...snap, capturedAt: Date.now() };
939
- this.diagCaptureModelCalls++;
940
- const repo = resolveRepoRoot(ctx.cwd) ?? this.currentStateDir;
941
- // S26: previously a single silent `catch {}` hid every capture failure, so
942
- // model_snapshots stayed empty and the cost card read $0.00 with zero signal.
943
- // Split per-write + append to events.log (always-on, dashboard live-streams
944
- // it) + bump a DIAG counter so a live capture surfaces the root cause.
945
- try {
946
- recordModelSnapshot(repo, snap, this.currentStateDir);
947
- this.appendEvent("captureModel:recorded", {
948
- repo,
949
- modelId: snap.modelId,
950
- provider: snap.provider,
951
- inputRate: snap.inputRate,
952
- outputRate: snap.outputRate,
953
- });
954
- } catch (e) {
955
- this.diagCaptureModelFails++;
956
- this.appendEvent("captureModel:record-failed", {
957
- repo,
958
- modelId: snap.modelId,
959
- error: e instanceof Error ? e.message : String(e),
960
- stack: e instanceof Error ? e.stack : undefined,
961
- });
962
- }
963
- try {
964
- // Denormalize the active model into the machine-wide index so the
965
- // All-repos dashboard table can show provider/model per repo without
966
- // opening every repo's DB. Best-effort + non-fatal.
967
- recordRepoModel(repo, {
968
- provider: snap.provider,
969
- providerName: snap.providerName,
970
- modelName: snap.modelName,
971
- inputRate: snap.inputRate,
972
- outputRate: snap.outputRate,
973
- stateDir: this.currentStateDir,
974
- displayName: repo.split(/[\\/]/).filter(Boolean).pop() ?? repo,
975
- });
976
- } catch (e) {
977
- this.appendEvent("captureModel:index-record-failed", {
978
- repo,
979
- modelId: snap.modelId,
980
- error: e instanceof Error ? e.message : String(e),
981
- });
982
- }
983
- }
984
-
985
- /**
986
- * Append a structured line to the repo's events.log — the always-on
987
- * diagnostics sink the dashboard live-streams. Unlike this.logger (gated by
988
- * config.debug), this fires in production, so capture failures surface during
989
- * a real capture even with debugging off. Best-effort + non-fatal.
990
- */
991
- private appendEvent(event: string, fields: Record<string, unknown>): void {
992
- try {
993
- mkdirSync(this.currentStateDir, { recursive: true });
994
- appendFileSync(
995
- join(this.currentStateDir, "events.log"),
996
- JSON.stringify({ ts: Date.now(), event, ...fields }) + "\n",
997
- );
998
- } catch {
999
- /* non-fatal */
1000
- }
1001
- }
1002
-
1003
- /** S21: state dir of the currently bound repo (where memories live). */
1004
- getStateDir(): string {
1005
- return this.currentStateDir;
1006
- }
1007
-
1008
- /** Build the sync onTier callback that paints the live per-tier trace. */
1009
- makeTierCallback(
1010
- ctx: ExtensionContext,
1011
- ): (ev: {
1012
- tier: "L0" | "L1" | "L2" | "new";
1013
- status: "scanning" | "deduped" | "passed" | "stored";
1014
- detail?: string;
1015
- }) => void {
1016
- const order: Array<"L0" | "L1" | "L2" | "new"> = ["L0", "L1", "L2", "new"];
1017
- const seen = new Map<string, string>();
1018
- const glyph = (status: string) =>
1019
- status === "deduped"
1020
- ? `${C.green}✓${C.reset}`
1021
- : status === "passed"
1022
- ? `${C.dim}○${C.reset}`
1023
- : status === "scanning"
1024
- ? `${C.amber}…${C.reset}`
1025
- : `${C.cyan}●${C.reset}`;
1026
- return (ev) => {
1027
- const label =
1028
- ev.tier === "new"
1029
- ? `${C.cyan}stored${C.reset}`
1030
- : `${ev.tier} ${glyph(ev.status)}` +
1031
- (ev.detail ? ` ${C.gray}(${ev.detail})${C.reset}` : "");
1032
- // Show the most recent outcome per tier (collapses re-fires).
1033
- seen.set(ev.tier, label);
1034
- const show: string[] = [];
1035
- for (const t of order) if (seen.has(t)) show.push(seen.get(t)!);
1036
- this.tierTrace = `${C.teal}⚙${C.reset} ${show.join(` ${C.gray}→${C.reset} `)}`;
1037
- this.lastActivityAt = Date.now();
1038
- try {
1039
- this.snapshot(ctx);
1040
- } catch {
1041
- /* non-fatal */
1042
- }
1043
- };
1044
- }
1045
-
1046
- // Phase 3 — recall/activity ticker ring buffer.
1047
- pushTicker(text: string): void {
1048
- this.ticker.push({ text, at: Date.now() });
1049
- while (this.ticker.length > this.TICKER_MAX) this.ticker.shift();
1050
- this.lastActivityAt = Date.now();
1051
- }
1052
-
1053
- /** Convert the messages pi hands us in the `context` event into the engine view. */
1054
- engineView(messages: AgentMessage[]): ReturnType<typeof toEngineMessages> {
1055
- return toEngineMessages(messages);
1056
- }
1057
- }
1058
-
1059
- /**
1060
- * Latest user message text — used as the auto-inline recall query.
1061
- * Kept as a free function (not instance state) since it only reads ctx.
1062
- */
1063
- export function recentUserQuery(ctx: ExtensionContext): string {
1064
- try {
1065
- const entries = ctx.sessionManager.getEntries();
1066
- for (let i = entries.length - 1; i >= 0; i--) {
1067
- const msgs = sessionEntryToContextMessages(entries[i]);
1068
- for (let j = msgs.length - 1; j >= 0; j--) {
1069
- if (msgs[j].role === "user") {
1070
- const c = (msgs[j] as { content: unknown }).content;
1071
- if (typeof c === "string") return c;
1072
- if (Array.isArray(c)) return c.map((b: any) => b.text).join(" ");
1073
- }
1074
- }
1075
- }
1076
- } catch {
1077
- /* best-effort */
1078
- }
1079
- return "";
1080
- }
16
+ export * from "./mega-runtime/widget.js";
17
+ export * from "./mega-runtime/helpers.js";
18
+ export * from "./mega-runtime/state.js";
19
+ export * from "./mega-runtime/query.js";