pi-mega-compact 0.7.8 → 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 (112) 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 +90 -21
  22. package/dist/extensions/mega-conflict-cmds.js +5 -1
  23. package/dist/extensions/mega-dashboard-cmds.js +29 -22
  24. package/dist/extensions/mega-db-cmds.js +11 -2
  25. package/dist/extensions/mega-events/agent-handlers.js +173 -0
  26. package/dist/extensions/mega-events/compact-handlers.js +133 -0
  27. package/dist/extensions/mega-events/context-handler.js +249 -0
  28. package/dist/extensions/mega-events/register.js +21 -0
  29. package/dist/extensions/mega-events/session-handlers.js +142 -0
  30. package/dist/extensions/mega-events.js +15 -699
  31. package/dist/extensions/mega-pipeline/compact.js +324 -0
  32. package/dist/extensions/mega-pipeline/memory-review.js +38 -0
  33. package/dist/extensions/mega-pipeline/recall.js +147 -0
  34. package/dist/extensions/mega-pipeline.js +9 -480
  35. package/dist/extensions/mega-runtime/helpers.js +40 -0
  36. package/dist/extensions/mega-runtime/query.js +29 -0
  37. package/dist/extensions/mega-runtime/state.js +711 -0
  38. package/dist/extensions/mega-runtime/widget.js +197 -0
  39. package/dist/extensions/mega-runtime.js +15 -947
  40. package/dist/src/store/sqlite/checkpoints.js +145 -0
  41. package/dist/src/store/sqlite/connection.js +35 -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/global-index.js +224 -0
  45. package/dist/src/store/sqlite/index-store.js +167 -0
  46. package/dist/src/store/sqlite/maintenance.js +235 -0
  47. package/dist/src/store/sqlite/memories.js +164 -0
  48. package/dist/src/store/sqlite/memory.js +54 -0
  49. package/dist/src/store/sqlite/meta.js +82 -0
  50. package/dist/src/store/sqlite/minhash-lsh.js +47 -0
  51. package/dist/src/store/sqlite/model-snapshots.js +47 -0
  52. package/dist/src/store/sqlite/raptor.js +57 -0
  53. package/dist/src/store/sqlite/raw-transcript.js +134 -0
  54. package/dist/src/store/sqlite/schema.js +250 -0
  55. package/dist/src/store/sqlite/session-state.js +28 -0
  56. package/dist/src/store/sqlite/sessions.js +39 -0
  57. package/dist/src/store/sqlite/stats.js +66 -0
  58. package/dist/src/store/sqlite/transaction.js +19 -0
  59. package/dist/src/store/sqlite/utils.js +120 -0
  60. package/dist/src/store/sqlite.js +20 -1607
  61. package/dist/src/vectorStore/add.js +260 -0
  62. package/dist/src/vectorStore/dedup.js +52 -0
  63. package/dist/src/vectorStore/index.js +10 -0
  64. package/dist/src/vectorStore/queries.js +83 -0
  65. package/dist/src/vectorStore/search.js +95 -0
  66. package/dist/src/vectorStore/session.js +19 -0
  67. package/dist/src/vectorStore/store.js +105 -0
  68. package/dist/src/vectorStore/types.js +6 -0
  69. package/dist/src/vectorStore/utils.js +23 -0
  70. package/extensions/dashboard-server/html.ts +758 -0
  71. package/extensions/dashboard-server/index-reader.ts +130 -0
  72. package/extensions/dashboard-server/server.ts +358 -0
  73. package/extensions/dashboard-server/snapshot.ts +44 -0
  74. package/extensions/dashboard-server/state.ts +33 -0
  75. package/extensions/dashboard-server/types.ts +134 -0
  76. package/extensions/dashboard-server.ts +7 -1431
  77. package/extensions/mega-commands.ts +33 -10
  78. package/extensions/mega-compact.test.ts +198 -43
  79. package/extensions/mega-conflict-cmds.ts +6 -2
  80. package/extensions/mega-dashboard-cmds.ts +30 -23
  81. package/extensions/mega-db-cmds.ts +11 -3
  82. package/extensions/mega-events/agent-handlers.ts +214 -0
  83. package/extensions/mega-events/compact-handlers.ts +164 -0
  84. package/extensions/mega-events/context-handler.ts +290 -0
  85. package/extensions/mega-events/register.ts +37 -0
  86. package/extensions/mega-events/session-handlers.ts +165 -0
  87. package/extensions/mega-events.ts +15 -780
  88. package/extensions/mega-pipeline/compact.ts +366 -0
  89. package/extensions/mega-pipeline/memory-review.ts +46 -0
  90. package/extensions/mega-pipeline/recall.ts +165 -0
  91. package/extensions/mega-pipeline.ts +9 -537
  92. package/extensions/mega-runtime/helpers.ts +68 -0
  93. package/extensions/mega-runtime/query.ts +29 -0
  94. package/extensions/mega-runtime/state.ts +797 -0
  95. package/extensions/mega-runtime/widget.ts +258 -0
  96. package/extensions/mega-runtime.ts +15 -1093
  97. package/package.json +4 -3
  98. package/src/store/sqlite/checkpoints.ts +204 -0
  99. package/src/store/sqlite/dedup-mirror.ts +114 -0
  100. package/src/store/sqlite/foundation.ts +63 -0
  101. package/src/store/sqlite/global-index.ts +305 -0
  102. package/src/store/sqlite/maintenance.ts +294 -0
  103. package/src/store/sqlite/memories.ts +217 -0
  104. package/src/store/sqlite/meta.ts +108 -0
  105. package/src/store/sqlite/model-snapshots.ts +83 -0
  106. package/src/store/sqlite/raptor.ts +107 -0
  107. package/src/store/sqlite/raw-transcript.ts +221 -0
  108. package/src/store/sqlite/schema.ts +258 -0
  109. package/src/store/sqlite/session-state.ts +38 -0
  110. package/src/store/sqlite/stats.ts +127 -0
  111. package/src/store/sqlite/utils.ts +125 -0
  112. package/src/store/sqlite.ts +20 -2204
@@ -0,0 +1,797 @@
1
+ /**
2
+ * state.ts — the `MegaRuntime` class: shared live state of the mega-compact
3
+ * extension.
4
+ *
5
+ * The original mega-compact.ts was a single large closure over ~20 mutable
6
+ * variables. This module lifts that state into a `MegaRuntime` class so the
7
+ * event/command/pipeline modules can share it without re-declaring it. All
8
+ * behavior (store/dashboard rebinding, dashboard snapshot shape, the
9
+ * above-editor widget math, model capture) is preserved byte-for-byte from the
10
+ * original closure.
11
+ */
12
+
13
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
14
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
15
+ import { join } from "node:path";
16
+ import { appendFileSync, mkdirSync } from "node:fs";
17
+ import { VectorStore } from "../../src/vectorStore.js";
18
+ import { toEngineMessages } from "../../src/adapt.js";
19
+ import { normalizeSessionId } from "../../src/store.js";
20
+ import { Logger } from "../../src/log.js";
21
+ import {
22
+ recordModelSnapshot,
23
+ latestModelSnapshot,
24
+ upsertRepoRegistry,
25
+ recordRepoModel,
26
+ getDedupStats,
27
+ getCompactCount,
28
+ getRecallInjected,
29
+ getCacheHitTokensSaved,
30
+ type ModelSnapshot,
31
+ } from "../../src/store/sqlite.js";
32
+ import { detectCrossRepoDrift } from "../../src/driftDetection.js";
33
+ import {
34
+ repoStateDir,
35
+ resolveRepoRoot,
36
+ pressureRatio,
37
+ pressureFromPct,
38
+ pressureBand,
39
+ effectiveThresholdTokens,
40
+ type MegaConfig,
41
+ type PressureBand,
42
+ } from "../mega-config.js";
43
+ import { Dashboard, type DashboardSnapshot } from "../mega-dashboard.js";
44
+ import {
45
+ STATUS_KEY,
46
+ WIDGET_KEY,
47
+ TOKENS_PER_SEC_ESTIMATE,
48
+ ownVersion,
49
+ type SessionRuntime,
50
+ } from "./helpers.js";
51
+ import {
52
+ C,
53
+ buildWidgetLines,
54
+ type TickerEntry,
55
+ type WidgetData,
56
+ } from "./widget.js";
57
+
58
+ export class MegaRuntime {
59
+ config: MegaConfig;
60
+ // Store/dashboard/logger are rebound per-repo by bindRepo() so each git repo
61
+ // gets its own isolated state dir. They start bound to the global default.
62
+ store: VectorStore;
63
+ logger: Logger;
64
+ dashboard: Dashboard;
65
+ activeRepoRoot: string | null = null;
66
+ currentStateDir: string;
67
+
68
+ // The only mutable per-session state. Reset on session_start / session_tree.
69
+ rt: SessionRuntime = {
70
+ sessionId: normalizeSessionId(undefined),
71
+ persistedThisSession: false,
72
+ lastCheckpointId: undefined,
73
+ lastCompactedFrom: 0,
74
+ lastCompactedTokens: 0,
75
+ dedupSkips: 0,
76
+ dedupAttempts: 0,
77
+ tokensSaved: 0,
78
+ lastCompactAt: null,
79
+ lastNativeCompactAt: null,
80
+ compactCount: 0,
81
+ recallInjections: 0,
82
+ cacheHitTokens: 0,
83
+ lengthStopPending: false,
84
+ };
85
+ debounceUntil = 0;
86
+ // S16: debounce for the agent_end resume nudge (avoid busy-loops).
87
+ resumeNudgeUntil = 0;
88
+ // Agent tracking for real-time widget updates
89
+ activeAgents = 0;
90
+ currentTurn = 0;
91
+ // Recall block produced by auto-inline (resume/branch) that the next
92
+ // before_agent_start should prepend to the system prompt. Unset after use.
93
+ pendingRecallBlock: string | undefined;
94
+ // S21: memory recall block, parallel to pendingRecallBlock. Same one-shot
95
+ // semantics; composed with the checkpoint block in before_agent_start.
96
+ pendingMemoryRecallBlock: string | undefined;
97
+ statusKey: string | undefined; // current status text for dashboard
98
+ // Active model/provider (for real cost estimation). Captured from ctx.model
99
+ // on model_select + session_start; persisted to SQL so cost + the dashboard
100
+ // can read it without a live ctx.
101
+ currentModel: ModelSnapshot | undefined;
102
+ // Live "what it's doing right now" timestamp, used for the fresh-window.
103
+ lastActivityAt = 0;
104
+ // Live per-tier dedup trace (Phase 1): e.g. "L0 ✓ → L1 ✓ → L2 0.91 → stored".
105
+ // Built from the store's sync onTier callback during a compaction so the user
106
+ // watches each tier evaluate in real time. Cleared once the outcome settles.
107
+ tierTrace: string | undefined;
108
+ // Phase 3 — standout toolbar state.
109
+ // Recall/activity ticker: a small ring buffer (≤5) of recent compact/recall
110
+ // events so the widget shows a live history instead of a single last action.
111
+ ticker: TickerEntry[] = [];
112
+ readonly TICKER_MAX = 5;
113
+ // Pulsing status: set true while a compaction is in flight, cleared on result.
114
+ pulsing = false;
115
+ // S21.2: set by `applyMemoryOps` when a memory add/replace/remove lands in
116
+ // the current compaction. The pipeline reads this after a successful compact
117
+ // to decide whether to fire `consolidateMemories` (skip the work entirely
118
+ // when no memory rows changed).
119
+ memoriesTouchedThisCompaction = 0;
120
+ // Rolling "saved" goal for the progress bar — grows as we save more, so the
121
+ // bar always has a meaningful denominator (never sits at 100% forever).
122
+ savedGoal = 50_000;
123
+ // Last explain-why line (dedup reason / anchor-kept / superseded), surfaced
124
+ // while fresh.
125
+ lastWhy: string | undefined = undefined;
126
+
127
+ // Context tracking for the dashboard (updated in the context handler).
128
+ lastCtxTokens: number | null = null;
129
+ lastCtxPercent: number | null = null;
130
+ lastCtxWindow = 0;
131
+
132
+ // Latest computed widget payload (recomputed per snapshot, rendered per frame).
133
+ widgetData: WidgetData | null = null;
134
+ // Cached cross-repo drift status (recomputed at most every 30s — it opens the
135
+ // machine-wide registry DB, so we don't want to do it on every render frame).
136
+ private driftCache: { at: number; status: "ok" | "warn" } | null = null;
137
+
138
+ /**
139
+ * DIAG counters for the "team run doesn't relieve context" investigation.
140
+ * Plain integers, incremented at the three compaction decision points. They
141
+ * let a headless test drive the real event handlers and assert the firing
142
+ * cadence without scraping log files. Inert in production (the live-trim and
143
+ * before-compact probes also emit logger.info, but these counters are always
144
+ * updated and cost nothing).
145
+ */
146
+ diagLiveTrimFires = 0; // context handler returned a trimmed view
147
+ diagBeforeCompactFires = 0; // session_before_compact handler entered
148
+ diagBeforeCompactSupplied = 0; // session_before_compact supplied our trim
149
+ diagAgentEndIdle = 0; // agent_end with activeAgents===0
150
+ diagAgentEndDurable = 0; // agent_end fired ctx.compact() (mid-run durable trim)
151
+ diagAgentEndDurableSkipRecent = 0; // agent_end skipped ctx.compact() — compaction in last 10s (race guard)
152
+ // Per-skip-path counters for the team-run diagnosis.
153
+ diagCtxFastGate = 0; // returned at token fast-gate (below threshold)
154
+ diagCtxNoCompact = 0; // autoCompactCheck().shouldCompact === false
155
+ diagCtxDebounce = 0; // debounceUntil not yet elapsed
156
+ diagCtxRunSkipped = 0; // runCompact() returned skipped
157
+ diagCtxCutNull = 0; // computeLiveTrimCut returned null (anchor/boundary)
158
+ diagCtxThrown = 0; // live-trim try threw (caught)
159
+
160
+ /**
161
+ * S26 capture instrumentation: the "model_snapshots empty → $0.00 cost card"
162
+ * bug was invisible because captureModel swallowed the DB write in a silent
163
+ * `catch {}`. These always-updated counters (zero cost) let a headless test or
164
+ * a live capture tell whether captureModel ran and whether the snapshot landed.
165
+ */
166
+ diagCaptureModelCalls = 0; // captureModel entered with a populated ctx.model
167
+ diagCaptureModelFails = 0; // recordModelSnapshot threw → model_snapshots stays empty
168
+
169
+ /**
170
+ * Live 0–1 pressure — how full the context window is relative to the
171
+ * compaction threshold.
172
+ *
173
+ * RECONCILE (BACKLOG dual-basis flicker): when the model context window is
174
+ * known we base pressure consistently on the *percentage* basis
175
+ * (`lastCtxPercent / (tierPct*100)`). This keeps the band stable whether the
176
+ * latest context event carried a token count or only a percentage, so the
177
+ * threshold comparison doesn't jump when a token-count event arrives vs a
178
+ * percent-only event. We only fall back to the token-count basis
179
+ * (`config.thresholdTokens`) when the window is unknown (e.g. before the first
180
+ * context event, or a `custom` tier with no tierPct). Always finite + in [0,1].
181
+ */
182
+ get pressure(): number {
183
+ if (
184
+ this.lastCtxWindow > 0 &&
185
+ this.config.tierPct != null &&
186
+ this.lastCtxPercent != null
187
+ ) {
188
+ // pressureFromPct(x) = x/100, and x = lastCtxPercent/tierPct, so this is
189
+ // exactly the intended lastCtxPercent/(tierPct*100) 0–1 ratio: at the
190
+ // fire point (lastCtxPercent == tierPct*100) pressure == 1.0, matching the
191
+ // token-based pressureRatio(currentTokens, effectiveThreshold) reading so
192
+ // the band doesn't jump when a token-count vs percent-only event arrives.
193
+ return pressureFromPct(this.lastCtxPercent / this.config.tierPct);
194
+ }
195
+ if (
196
+ this.lastCtxTokens != null &&
197
+ this.lastCtxTokens > 0 &&
198
+ this.config.thresholdTokens > 0
199
+ ) {
200
+ return pressureRatio(this.lastCtxTokens, this.config.thresholdTokens);
201
+ }
202
+ return pressureFromPct(this.lastCtxPercent);
203
+ }
204
+
205
+ /**
206
+ * The live compaction FIRE POINT in tokens: the effective threshold scaled by
207
+ * the current model context window (`tierPct * window`) when known, else the
208
+ * boot fallback `config.thresholdTokens`. This is what the FAST GATE /
209
+ * `autoCompactCheck` / agent_end durable-trigger compare against, so
210
+ * compaction fires at tier% of the window for ANY model size (200k or 1M),
211
+ * always below pi's native auto-compaction (~80% of window).
212
+ */
213
+ get effectiveThreshold(): number {
214
+ return effectiveThresholdTokens({
215
+ tierPct: this.config.tierPct,
216
+ fallbackThreshold: this.config.thresholdTokens,
217
+ window: this.lastCtxWindow,
218
+ });
219
+ }
220
+
221
+ /** Live discrete pressure band (low/medium/high/ultra/mega) over `pressure`. */
222
+ get pressureBand(): PressureBand {
223
+ return pressureBand(this.pressure);
224
+ }
225
+
226
+ constructor(config: MegaConfig) {
227
+ this.config = config;
228
+ this.store = new VectorStore({
229
+ dedupSim: config.dedupSim,
230
+ stateDir: config.stateDir,
231
+ });
232
+ this.logger = new Logger({
233
+ enabled: config.debug,
234
+ path: join(config.stateDir, "mega-compact.log"),
235
+ });
236
+ this.dashboard = new Dashboard(config.stateDir);
237
+ this.currentStateDir = config.stateDir;
238
+ }
239
+
240
+ // ---- per-repo binding -----------------------------------------------------
241
+
242
+ /**
243
+ * Point store/dashboard/logger at the current repo's state dir. Rebuilds the
244
+ * instances only when the repo root changes, so cross-repo dedup stats, db,
245
+ * and events are fully isolated. Falls back to the global default outside git.
246
+ */
247
+ bindRepo(cwd: string | undefined): string {
248
+ const dir = cwd
249
+ ? repoStateDir(cwd, this.config.stateDir)
250
+ : this.config.stateDir;
251
+ const key = cwd ? (resolveRepoRoot(cwd) ?? dir) : dir;
252
+ if (key === this.activeRepoRoot) return dir;
253
+ this.activeRepoRoot = key;
254
+ this.currentStateDir = dir;
255
+ this.store = new VectorStore({
256
+ dedupSim: this.config.dedupSim,
257
+ stateDir: dir,
258
+ });
259
+ this.logger = new Logger({
260
+ enabled: this.config.debug,
261
+ path: join(dir, "mega-compact.log"),
262
+ });
263
+ this.dashboard = new Dashboard(dir);
264
+ // Aggregate this repo into the machine-wide index so the multi-repo
265
+ // dashboard (Summary / All-repos tabs) can show it alongside every other
266
+ // repo. Best-effort + non-fatal: a read-only index dir or contention must
267
+ // never break the per-repo compaction path. Runs only on repo-switch
268
+ // (this branch), so it's infrequent — not per-context-event.
269
+ try {
270
+ const repo = this.store.repoStats();
271
+ const di = this.store.dataInvariant();
272
+ const root = key !== dir ? key : (resolveRepoRoot(cwd ?? dir) ?? dir);
273
+ upsertRepoRegistry({
274
+ repoRoot: root,
275
+ displayName: root.split(/[\\/]/).filter(Boolean).pop() ?? root,
276
+ stateDir: dir,
277
+ checkpointCount: repo.checkpointCount,
278
+ tokensSaved: repo.tokensSaved,
279
+ compressedOriginalBytes: di.compressedOriginalBytes,
280
+ });
281
+ } catch {
282
+ /* non-fatal: index aggregation must not block compaction */
283
+ }
284
+ return dir;
285
+ }
286
+
287
+ // ---- dashboard snapshot + widget ------------------------------------------
288
+
289
+ /** Collect live state and write it to disk (+ paint the above-editor widget). */
290
+ snapshot(ctx?: ExtensionContext): void {
291
+ if (ctx) this.bindRepo(ctx.cwd);
292
+ const st = this.store.stats(this.rt.sessionId);
293
+ const repo = this.store.repoStats();
294
+ const di = this.store.dataInvariant();
295
+ // Live + store-wide cache-hit / compaction counters for the dashboard.
296
+ const ds = getDedupStats(this.currentStateDir);
297
+ const cacheHitsTotal = ds.deduped + getRecallInjected(this.currentStateDir);
298
+ const cacheHitsTotalTokens = getCacheHitTokensSaved(this.currentStateDir);
299
+ const cacheHitsSession = this.rt.dedupSkips + this.rt.recallInjections;
300
+ const sec = (tok: number) => (tok || 0) / TOKENS_PER_SEC_ESTIMATE;
301
+ // Active model/provider for the current-repo card + the multi-repo table.
302
+ const modelSnap = latestModelSnapshot(this.currentStateDir);
303
+ const model = modelSnap
304
+ ? {
305
+ name: modelSnap.modelName ?? modelSnap.modelId,
306
+ provider: modelSnap.provider,
307
+ providerName: modelSnap.providerName ?? "",
308
+ inputRate: modelSnap.inputRate,
309
+ outputRate: modelSnap.outputRate,
310
+ }
311
+ : undefined;
312
+ // effectiveThresholdPct: the live fire point as a % of the window (null for
313
+ // `custom`, which has no tierPct). S29: honors MEGACOMPACT_AUTO_PCT_TRIGGER
314
+ // override so the dashboard's armed/ready match the context-handler gate
315
+ // (which fires on this same %). Used by armed/ready + the dashboard.
316
+ const effectiveThresholdPct =
317
+ this.config.tierPct != null
318
+ ? (this.config.autoPctTrigger ?? this.config.tierPct) * 100
319
+ : null;
320
+ // armed lights at/above the REAL fire point: max(effectiveThresholdPct,
321
+ // fastGatePct). fastGatePct already equals tierPct*100 by default, but a
322
+ // MEGACOMPACT_FAST_GATE_PCT override can raise it, so we take the max.
323
+ const armed =
324
+ this.lastCtxPercent != null &&
325
+ this.lastCtxPercent >=
326
+ Math.max(effectiveThresholdPct ?? 0, this.config.fastGatePct);
327
+ // S29: ready mirrors the context-handler gate's basis — percent for tiered
328
+ // (the gate fires on pct), tokens for custom (the gate fires on tokens).
329
+ // Previously this always required tokens, so the dashboard could show
330
+ // "armed" (percent high) but never "ready" when tokens were under-reported
331
+ // — the same inconsistency the S29 gate fix removes.
332
+ const ready =
333
+ this.config.tierPct != null
334
+ ? armed && (this.lastCtxPercent ?? 0) >= (effectiveThresholdPct ?? 0)
335
+ : armed && (this.lastCtxTokens ?? 0) >= this.effectiveThreshold;
336
+ this.dashboard.snapshot({
337
+ version: 1,
338
+ updatedAt: new Date().toISOString(),
339
+ // S24: the headline tier is the LIVE pressure band; the env preset is kept
340
+ // alongside as presetTier so the dashboard can show both.
341
+ tier: this.pressureBand,
342
+ presetTier: this.config.tier,
343
+ pressure: this.pressure,
344
+ config: {
345
+ fastGatePct: this.config.fastGatePct,
346
+ thresholdTokens: this.effectiveThreshold,
347
+ tierPct: this.config.tierPct,
348
+ effectiveThresholdPct,
349
+ anchorUserMessages: this.config.anchorUserMessages,
350
+ preserveRecent: this.config.preserveRecent,
351
+ auto: this.config.auto,
352
+ autoInline: this.config.autoInline,
353
+ },
354
+ session: {
355
+ id: this.rt.sessionId,
356
+ state: this.statusKey ?? "idle",
357
+ persistedThisSession: this.rt.persistedThisSession,
358
+ lastCheckpointId: this.rt.lastCheckpointId ?? null,
359
+ lastCompactedFrom: this.rt.lastCompactedFrom,
360
+ lastCompactedTokens: this.rt.lastCompactedTokens,
361
+ dedupSkips: this.rt.dedupSkips,
362
+ dedupAttempts: this.rt.dedupAttempts,
363
+ },
364
+ context: {
365
+ tokens: this.lastCtxTokens,
366
+ percent: this.lastCtxPercent,
367
+ contextWindow: this.lastCtxWindow,
368
+ },
369
+ trigger: {
370
+ armed,
371
+ ready,
372
+ currentTokens: this.lastCtxTokens,
373
+ thresholdTokens: this.effectiveThreshold,
374
+ fastGatePct: this.config.fastGatePct,
375
+ tierPct: this.config.tierPct,
376
+ effectiveThresholdPct,
377
+ },
378
+ crew: { activeAgents: this.activeAgents, currentTurn: this.currentTurn },
379
+ store: {
380
+ checkpointCount: st.checkpointCount,
381
+ totalTokenEstimate: st.totalTokenEstimate,
382
+ originalTokens: st.originalTokens,
383
+ tokensSaved: this.rt.tokensSaved,
384
+ injectedCount: st.injectedCount,
385
+ dedupHitRate: st.dedupHitRate,
386
+ storageDedupRate: st.storageDedupRate,
387
+ dedupAttempts: st.dedupAttempts,
388
+ dedupCollapsed: st.dedupCollapsed,
389
+ },
390
+ // Reconciled token accounting (single canonical formula, session + repo).
391
+ // Freed = In − Out; In = Freed + Out. session.Freed = rt.tokensSaved (incl.
392
+ // deduped-away originals); repo.Freed = repo.tokensSaved meta counter.
393
+ compression: {
394
+ session: {
395
+ tokensIn: this.rt.tokensSaved + st.totalTokenEstimate,
396
+ tokensOut: st.totalTokenEstimate,
397
+ tokensFreed: this.rt.tokensSaved,
398
+ compressionPct:
399
+ this.rt.tokensSaved + st.totalTokenEstimate > 0
400
+ ? this.rt.tokensSaved /
401
+ (this.rt.tokensSaved + st.totalTokenEstimate)
402
+ : 0,
403
+ dedupPct: st.storageDedupRate,
404
+ },
405
+ repo: {
406
+ tokensIn: repo.tokensSaved + repo.totalTokenEstimate,
407
+ tokensOut: repo.totalTokenEstimate,
408
+ tokensFreed: repo.tokensSaved,
409
+ compressionPct:
410
+ repo.tokensSaved + repo.totalTokenEstimate > 0
411
+ ? repo.tokensSaved / (repo.tokensSaved + repo.totalTokenEstimate)
412
+ : 0,
413
+ dedupPct: repo.storageDedupRate,
414
+ },
415
+ },
416
+ repo: {
417
+ checkpointCount: repo.checkpointCount,
418
+ totalTokenEstimate: repo.totalTokenEstimate,
419
+ originalTokens: repo.originalTokens,
420
+ tokensSaved: repo.tokensSaved,
421
+ sessionCount: repo.sessionCount,
422
+ dedupAttempts: repo.dedupAttempts,
423
+ dedupCollapsed: repo.dedupCollapsed,
424
+ storageDedupRate: repo.storageDedupRate,
425
+ },
426
+ integrity: {
427
+ regionsRetained: di.regionsRetained,
428
+ compressedOriginalBytes: di.compressedOriginalBytes,
429
+ duplicatesCollapsed: di.duplicatesCollapsed,
430
+ bytesPermanentlyDeleted: di.bytesPermanentlyDeleted,
431
+ },
432
+ cacheHits: {
433
+ session: cacheHitsSession,
434
+ total: cacheHitsTotal,
435
+ sessionTokensSaved: this.rt.cacheHitTokens,
436
+ totalTokensSaved: cacheHitsTotalTokens,
437
+ },
438
+ compacts: {
439
+ session: this.rt.compactCount,
440
+ total: getCompactCount(this.currentStateDir),
441
+ },
442
+ timeSaved: {
443
+ compact: { sessionSec: sec(this.rt.tokensSaved), totalSec: sec(this.store.repoStats().tokensSaved) },
444
+ cacheHit: { sessionSec: sec(this.rt.cacheHitTokens), totalSec: sec(cacheHitsTotalTokens) },
445
+ },
446
+ model,
447
+ } as DashboardSnapshot);
448
+
449
+ // Live stats widget above the editor
450
+ if (ctx) {
451
+ // ── gather widget data (computed per snapshot, rendered per frame) ────
452
+ const tokStr =
453
+ this.lastCtxTokens != null
454
+ ? `${Math.round(this.lastCtxTokens / 1000)}k`
455
+ : "?";
456
+ const maxStr =
457
+ this.lastCtxWindow > 0
458
+ ? `${Math.round(this.lastCtxWindow / 1000)}k`
459
+ : "?";
460
+ const pctStr =
461
+ this.lastCtxPercent != null
462
+ ? this.lastCtxPercent > 100
463
+ ? `>100%` // S29: overshoot warning, not a raw "250%" — the percent trigger now compacts before 100%, so this is the residual case where it can't keep up.
464
+ : `${Math.round(this.lastCtxPercent * 10) / 10}%`
465
+ : "?%";
466
+ // S24: the tier label is the LIVE pressure band (low/medium/high/ultra/
467
+ // mega), not the static env preset. It climbs as context fills.
468
+ const liveBand = this.pressureBand;
469
+ const tierLabel = `${C.bold}${liveBand}${C.reset}${C.gray}·${this.config.tier}${C.reset}`;
470
+ const triggerLabel = ready
471
+ ? `${C.green}● ready${C.reset}`
472
+ : armed
473
+ ? `${C.amber}◐ armed${C.reset}`
474
+ : `${C.gray}○ idle${C.reset}`;
475
+ // Storage dedup rate is cumulative (store-wide, per-repo) and survives
476
+ // session resets. Always show a number (decimal for sub-10%).
477
+ const storageRate = st.storageDedupRate; // 0..1
478
+ const dedupStr =
479
+ storageRate * 100 >= 10
480
+ ? `${Math.round(storageRate * 100)}%`
481
+ : `${(storageRate * 100).toFixed(1)}%`;
482
+ // Agents view: count + status (S27 per-agent tokens are gated on P0).
483
+ const agentLabel =
484
+ this.activeAgents > 0
485
+ ? `🤖 ${this.activeAgents} agent${this.activeAgents === 1 ? "" : "s"}`
486
+ : `${C.dim}🤖 idle${C.reset}`;
487
+ const agentStr = ` │ ${agentLabel}`;
488
+ const turnStr = this.currentTurn > 0 ? ` │ turn ${this.currentTurn}` : "";
489
+ // Reconciled in/out view (session + repo) — ONE canonical formula.
490
+ const sessIn = this.rt.tokensSaved + st.totalTokenEstimate;
491
+ const sessKept = st.totalTokenEstimate;
492
+ const sessPct = sessIn > 0 ? this.rt.tokensSaved / sessIn : 0;
493
+ const repoIn = repo.tokensSaved + repo.totalTokenEstimate;
494
+ const repoKept = repo.totalTokenEstimate;
495
+ const repoPct = repoIn > 0 ? repo.tokensSaved / repoIn : 0;
496
+ const sTxt = (sessPct * 100).toFixed(sessPct * 100 >= 10 ? 0 : 1);
497
+ const rTxt = (repoPct * 100).toFixed(repoPct * 100 >= 10 ? 0 : 1);
498
+ const ctxPct =
499
+ this.lastCtxPercent != null ? this.lastCtxPercent / 100 : 0;
500
+ // Model + provider (S26 capture) for the header.
501
+ const modelName = modelSnap?.modelName ?? modelSnap?.modelId ?? "?";
502
+ const modelStr = modelSnap?.provider
503
+ ? `${modelName}·${modelSnap.provider}`
504
+ : modelName;
505
+ // Since-last-compact (ms; null until first compaction this session).
506
+ const sinceCompact =
507
+ this.rt.lastCompactAt != null
508
+ ? Date.now() - this.rt.lastCompactAt
509
+ : null;
510
+ // Memory store: embedder + compression ratio (original / stored).
511
+ const embedderName = this.embedderName();
512
+ const compRatio =
513
+ st.originalTokens > 0 && st.totalTokenEstimate > 0
514
+ ? st.originalTokens / st.totalTokenEstimate
515
+ : st.originalTokens > 0
516
+ ? 1
517
+ : 0;
518
+ const compStr = compRatio >= 1 ? `${compRatio.toFixed(1)}x` : "—";
519
+ // Cross-repo drift status (cached, read-only).
520
+ const driftStatus = this.driftStatus();
521
+ const agentsActive = this.activeAgents > 0;
522
+
523
+ this.widgetData = {
524
+ version: ownVersion(),
525
+ tierLabel,
526
+ triggerLabel,
527
+ pctStr,
528
+ tokStr,
529
+ maxStr,
530
+ ctxPct,
531
+ chk: st.checkpointCount,
532
+ agentStr,
533
+ turnStr,
534
+ dedupStr,
535
+ sessIn,
536
+ sessKept,
537
+ sTxt,
538
+ repoIn,
539
+ repoKept,
540
+ rTxt,
541
+ repoChk: repo.checkpointCount,
542
+ repoSess: repo.sessionCount,
543
+ modelStr,
544
+ sinceCompact,
545
+ embedderName,
546
+ compStr,
547
+ driftStatus,
548
+ agentsActive,
549
+ fresh: Date.now() - this.lastActivityAt < 4000,
550
+ ticker: this.ticker,
551
+ lastWhy: this.lastWhy,
552
+ tierTrace: this.tierTrace,
553
+ pulsing: this.pulsing,
554
+ };
555
+ // Auto-fit: register a factory so pi re-renders the panel at the REAL
556
+ // terminal width every frame (tui.columns), instead of guessing with
557
+ // process.stdout.columns. buildWidgetLines reads this.widgetData live.
558
+ this.renderWidget(ctx);
559
+ }
560
+ }
561
+
562
+ /** Register the above-editor widget as a width-aware factory so pi re-renders
563
+ * it at the REAL terminal width every frame (auto-fit wide/narrow). The
564
+ * factory returns a minimal Component whose render() reads this.widgetData.
565
+ */
566
+ private renderWidget(ctx: ExtensionContext): void {
567
+ ctx.ui.setWidget(
568
+ WIDGET_KEY,
569
+ (_tui, _theme) => ({
570
+ render: (width: number) =>
571
+ buildWidgetLines(
572
+ this.widgetData,
573
+ width > 0 ? width : 200,
574
+ this.activeAgents,
575
+ ),
576
+ invalidate: () => {},
577
+ }),
578
+ { placement: "aboveEditor" },
579
+ );
580
+ }
581
+
582
+ /** Active embedder name for the memory-store line (Trigram default / MiniLM). */
583
+ private embedderName(): string {
584
+ // MINILM_EMBEDDER flag lives in src/config/dedup.ts; read the same env var
585
+ // the embedder factory uses so the label matches what's actually running.
586
+ return process.env.MEGACOMPACT_MINILM === "true" ||
587
+ process.env.MEGACOMPACT_MINILM === "1"
588
+ ? "MiniLM"
589
+ : "Trigram";
590
+ }
591
+
592
+ /** Cross-repo drift status (ok | warn), cached for 30s (opens the registry DB). */
593
+ private driftStatus(): "ok" | "warn" {
594
+ const now = Date.now();
595
+ if (this.driftCache && now - this.driftCache.at < 30_000)
596
+ return this.driftCache.status;
597
+ let status: "ok" | "warn" = "ok";
598
+ try {
599
+ const report = detectCrossRepoDrift();
600
+ status = report.totals.warn > 0 ? "warn" : "ok";
601
+ } catch {
602
+ status = "ok";
603
+ }
604
+ this.driftCache = { at: now, status };
605
+ return status;
606
+ }
607
+
608
+ setStatus(ctx: ExtensionContext, text: string | undefined): void {
609
+ this.statusKey = text;
610
+ ctx.ui.setStatus(STATUS_KEY, text);
611
+ }
612
+
613
+ resetRuntime(sessionId: string | undefined): void {
614
+ const sid = normalizeSessionId(sessionId);
615
+ if (this.rt.sessionId === sid && this.rt.persistedThisSession) return; // same session, keep checkpoint memory
616
+ this.rt = {
617
+ sessionId: sid,
618
+ persistedThisSession: false,
619
+ lastCheckpointId: undefined,
620
+ lastCompactedFrom: 0,
621
+ lastCompactedTokens: 0,
622
+ dedupSkips: 0,
623
+ dedupAttempts: 0,
624
+ tokensSaved: 0,
625
+ lastCompactAt: null,
626
+ lastNativeCompactAt: null,
627
+ compactCount: 0,
628
+ recallInjections: 0,
629
+ cacheHitTokens: 0,
630
+ lengthStopPending: false,
631
+ };
632
+ this.statusKey = undefined;
633
+ this.activeAgents = 0;
634
+ this.currentTurn = 0;
635
+ this.lastActivityAt = 0;
636
+ this.tierTrace = undefined;
637
+ this.ticker.length = 0;
638
+ this.pulsing = false;
639
+ this.savedGoal = 50_000;
640
+ this.lastWhy = undefined;
641
+ }
642
+
643
+ /**
644
+ * Capture the active model/provider from ctx.model and persist it so cost
645
+ * estimation + the dashboard can read real pricing. Cheap + idempotent-ish:
646
+ * only writes a new row when the model id changes (models change rarely).
647
+ */
648
+ captureModel(ctx: ExtensionContext): void {
649
+ const m = ctx.model;
650
+ if (!m) {
651
+ this.appendEvent("captureModel:no-model", { cwd: ctx.cwd });
652
+ return;
653
+ }
654
+ if (
655
+ this.currentModel &&
656
+ this.currentModel.modelId === m.id &&
657
+ this.currentModel.provider === m.provider
658
+ )
659
+ return;
660
+ let providerName: string | null = null;
661
+ try {
662
+ providerName =
663
+ ctx.modelRegistry?.getProviderDisplayName(m.provider) ?? null;
664
+ } catch {
665
+ /* optional */
666
+ }
667
+ const snap: Omit<ModelSnapshot, "capturedAt"> = {
668
+ provider: m.provider,
669
+ providerName,
670
+ modelId: m.id,
671
+ modelName: m.name ?? null,
672
+ inputRate: m.cost?.input ?? 0,
673
+ outputRate: m.cost?.output ?? 0,
674
+ contextWindow: m.contextWindow ?? 0,
675
+ maxTokens: m.maxTokens ?? 0,
676
+ reasoning: !!m.reasoning,
677
+ };
678
+ this.currentModel = { ...snap, capturedAt: Date.now() };
679
+ this.diagCaptureModelCalls++;
680
+ const repo = resolveRepoRoot(ctx.cwd) ?? this.currentStateDir;
681
+ // S26: previously a single silent `catch {}` hid every capture failure, so
682
+ // model_snapshots stayed empty and the cost card read $0.00 with zero signal.
683
+ // Split per-write + append to events.log (always-on, dashboard live-streams
684
+ // it) + bump a DIAG counter so a live capture surfaces the root cause.
685
+ try {
686
+ recordModelSnapshot(repo, snap, this.currentStateDir);
687
+ this.appendEvent("captureModel:recorded", {
688
+ repo,
689
+ modelId: snap.modelId,
690
+ provider: snap.provider,
691
+ inputRate: snap.inputRate,
692
+ outputRate: snap.outputRate,
693
+ });
694
+ } catch (e) {
695
+ this.diagCaptureModelFails++;
696
+ this.appendEvent("captureModel:record-failed", {
697
+ repo,
698
+ modelId: snap.modelId,
699
+ error: e instanceof Error ? e.message : String(e),
700
+ stack: e instanceof Error ? e.stack : undefined,
701
+ });
702
+ }
703
+ try {
704
+ // Denormalize the active model into the machine-wide index so the
705
+ // All-repos dashboard table can show provider/model per repo without
706
+ // opening every repo's DB. Best-effort + non-fatal.
707
+ recordRepoModel(repo, {
708
+ provider: snap.provider,
709
+ providerName: snap.providerName,
710
+ modelName: snap.modelName,
711
+ inputRate: snap.inputRate,
712
+ outputRate: snap.outputRate,
713
+ stateDir: this.currentStateDir,
714
+ displayName: repo.split(/[\\/]/).filter(Boolean).pop() ?? repo,
715
+ });
716
+ } catch (e) {
717
+ this.appendEvent("captureModel:index-record-failed", {
718
+ repo,
719
+ modelId: snap.modelId,
720
+ error: e instanceof Error ? e.message : String(e),
721
+ });
722
+ }
723
+ }
724
+
725
+ /**
726
+ * Append a structured line to the repo's events.log — the always-on
727
+ * diagnostics sink the dashboard live-streams. Unlike this.logger (gated by
728
+ * config.debug), this fires in production, so capture failures surface during
729
+ * a real capture even with debugging off. Best-effort + non-fatal.
730
+ */
731
+ private appendEvent(event: string, fields: Record<string, unknown>): void {
732
+ try {
733
+ mkdirSync(this.currentStateDir, { recursive: true });
734
+ appendFileSync(
735
+ join(this.currentStateDir, "events.log"),
736
+ JSON.stringify({ ts: Date.now(), event, ...fields }) + "\n",
737
+ );
738
+ } catch {
739
+ /* non-fatal */
740
+ }
741
+ }
742
+
743
+ /** S21: state dir of the currently bound repo (where memories live). */
744
+ getStateDir(): string {
745
+ return this.currentStateDir;
746
+ }
747
+
748
+ /** Build the sync onTier callback that paints the live per-tier trace. */
749
+ makeTierCallback(
750
+ ctx: ExtensionContext,
751
+ ): (ev: {
752
+ tier: "L0" | "L1" | "L2" | "new";
753
+ status: "scanning" | "deduped" | "passed" | "stored";
754
+ detail?: string;
755
+ }) => void {
756
+ const order: Array<"L0" | "L1" | "L2" | "new"> = ["L0", "L1", "L2", "new"];
757
+ const seen = new Map<string, string>();
758
+ const glyph = (status: string) =>
759
+ status === "deduped"
760
+ ? `${C.green}✓${C.reset}`
761
+ : status === "passed"
762
+ ? `${C.dim}○${C.reset}`
763
+ : status === "scanning"
764
+ ? `${C.amber}…${C.reset}`
765
+ : `${C.cyan}●${C.reset}`;
766
+ return (ev) => {
767
+ const label =
768
+ ev.tier === "new"
769
+ ? `${C.cyan}stored${C.reset}`
770
+ : `${ev.tier} ${glyph(ev.status)}` +
771
+ (ev.detail ? ` ${C.gray}(${ev.detail})${C.reset}` : "");
772
+ // Show the most recent outcome per tier (collapses re-fires).
773
+ seen.set(ev.tier, label);
774
+ const show: string[] = [];
775
+ for (const t of order) if (seen.has(t)) show.push(seen.get(t)!);
776
+ this.tierTrace = `${C.teal}⚙${C.reset} ${show.join(` ${C.gray}→${C.reset} `)}`;
777
+ this.lastActivityAt = Date.now();
778
+ try {
779
+ this.snapshot(ctx);
780
+ } catch {
781
+ /* non-fatal */
782
+ }
783
+ };
784
+ }
785
+
786
+ // Phase 3 — recall/activity ticker ring buffer.
787
+ pushTicker(text: string): void {
788
+ this.ticker.push({ text, at: Date.now() });
789
+ while (this.ticker.length > this.TICKER_MAX) this.ticker.shift();
790
+ this.lastActivityAt = Date.now();
791
+ }
792
+
793
+ /** Convert the messages pi hands us in the `context` event into the engine view. */
794
+ engineView(messages: AgentMessage[]): ReturnType<typeof toEngineMessages> {
795
+ return toEngineMessages(messages);
796
+ }
797
+ }