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