pi-mega-compact 0.20.85 → 0.20.87

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 (42) hide show
  1. package/dist/config.js +9 -0
  2. package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +2 -0
  3. package/dist/extensions/mega-config.js +12 -0
  4. package/dist/extensions/mega-events/context-handler/gateCheck.js +27 -0
  5. package/dist/extensions/mega-events/context-handler/thrashGuard.js +186 -0
  6. package/dist/extensions/mega-events/context-handler.js +33 -1
  7. package/dist/extensions/mega-pipeline/compact/noop.js +104 -0
  8. package/dist/extensions/mega-pipeline/compact/run.js +268 -0
  9. package/dist/extensions/mega-pipeline/compact/vote.js +72 -0
  10. package/dist/extensions/mega-pipeline/compact.js +12 -343
  11. package/dist/extensions/mega-pipeline/recall/impl.js +258 -0
  12. package/dist/extensions/mega-pipeline/recall.js +6 -253
  13. package/dist/src/config.js +9 -0
  14. package/dist/src/failback/compact.js +109 -0
  15. package/dist/src/recall/readonly.js +39 -0
  16. package/dist/src/recall/recall3wf.fixture.js +67 -0
  17. package/dist/src/recall/validator.js +113 -0
  18. package/dist/src/recall/vote.js +217 -0
  19. package/dist/src/store/sqlite/fts5-search.js +26 -0
  20. package/dist/src/store/sqlite/meta.js +32 -0
  21. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +9 -0
  22. package/extensions/mega-config-types.ts +13 -0
  23. package/extensions/mega-config.ts +12 -0
  24. package/extensions/mega-events/context-handler/gateCheck.ts +30 -0
  25. package/extensions/mega-events/context-handler/thrashGuard.ts +228 -0
  26. package/extensions/mega-events/context-handler.ts +36 -1
  27. package/extensions/mega-pipeline/compact/noop.ts +96 -0
  28. package/extensions/mega-pipeline/compact/run.ts +322 -0
  29. package/extensions/mega-pipeline/compact/vote.ts +85 -0
  30. package/extensions/mega-pipeline/compact.ts +12 -385
  31. package/extensions/mega-pipeline/recall/impl.ts +312 -0
  32. package/extensions/mega-pipeline/recall.ts +10 -306
  33. package/package.json +1 -1
  34. package/src/config.ts +12 -0
  35. package/src/failback/compact.ts +122 -0
  36. package/src/failback/types.ts +72 -0
  37. package/src/recall/readonly.ts +57 -0
  38. package/src/recall/recall3wf.fixture.ts +87 -0
  39. package/src/recall/validator.ts +150 -0
  40. package/src/recall/vote.ts +240 -0
  41. package/src/store/sqlite/fts5-search.ts +40 -0
  42. package/src/store/sqlite/meta.ts +36 -0
@@ -1,345 +1,14 @@
1
1
  /**
2
- * compact.ts — full compaction pipeline (Trident) + pi no-op prediction.
3
- *
4
- * `runCompact` runs the full Trident pipeline (fast-gate aside) and persists a
5
- * checkpoint. `piCompactWouldNoop` predicts whether pi's `ctx.compact()` would
6
- * throw a no-op error. Both mutate the shared MegaRuntime (token accounting,
7
- * ticker, status, events) and are driven by the event + command handlers in
8
- * mega-events.ts / mega-commands.ts.
9
- */
10
- import { sessionEntryToContextMessages } from "@earendil-works/pi-coding-agent";
11
- import { compactSession } from "../../src/engine.js";
12
- import { normalizeSessionId } from "../../src/store.js";
13
- import { repoKey } from "../../src/store/repoKey.js";
14
- import { estimateBlockTokens } from "../../src/tokens.js";
15
- import { touchSession, logDaily, incCompactCount, incCacheHitTokens } from "../../src/store/sqlite.js";
16
- import { consolidateMemories } from "../../src/memory.js";
17
- import { C, MARKER_TYPE, } from "../mega-runtime.js";
18
- import { resolveRepoRoot, preserveRecentForPressure } from "../mega-config.js";
19
- import { runRaptor } from "../../src/dedup/raptor/index.js";
20
- import { isRaptorTreeFresh } from "../../src/dedup/raptor/buildHistory.js";
21
- import { loadDedupConfig } from "../../src/config/dedup.js";
22
- import { upsertEmbedding as indexUpsertEmbedding } from "../../src/store/vectorIndex.js";
23
- import { runMemoryReview } from "./memory-review.js";
24
- import { vectorList } from "../../src/vectorStore.js";
25
- /** Run the full compaction pipeline and persist a checkpoint. Returns the result. */
26
- export function runCompact(pi, runtime, config, ctx, messages, opts = {}) {
27
- runtime.bindRepo(ctx.cwd);
28
- const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
29
- runtime.resetRuntime(sid);
30
- runtime.rt.sessionId = sid;
31
- const view = runtime.engineView(messages);
32
- // keepFrom deepens with context pressure (Fix E): under high pressure we
33
- // compact more of the session, down to the preserveRecentMin floor.
34
- const preserve = preserveRecentForPressure(opts.compressionPressure ?? 0, config.preserveRecent, config.preserveRecentMin);
35
- const keepFrom = opts.keepFrom ?? Math.max(0, view.length - preserve);
36
- // For very small sessions (fewer messages than preserveRecent), allow
37
- // compacting everything except the last message — the user explicitly
38
- // requested compaction, so don't refuse it just because the session is short.
39
- if (keepFrom <= 0) {
40
- if (view.length <= 1)
41
- return { skipped: true };
42
- // Use the fallback: compact everything except the last message
43
- const fallbackKeepFrom = view.length - 1;
44
- return doCompact(view, fallbackKeepFrom, opts, sid, config, pi, ctx, runtime);
45
- }
46
- return doCompact(view, keepFrom, opts, sid, config, pi, ctx, runtime);
47
- }
48
- function doCompact(view, keepFrom, opts, sid, config, pi, ctx, runtime) {
49
- runtime.pulsing = true; // animate the status line while the (sync) pipeline runs
50
- runtime.setEffect?.("pulse", "accent", 1500); // v0.8.3: ambient border pulse during compaction
51
- // S21.2: reset the per-compaction memory-op counter so the post-compact
52
- // consolidate pass only fires when memory rows actually changed during the
53
- // compaction window (turn_end → auto-review may have written some).
54
- runtime.memoriesTouchedThisCompaction = 0;
55
- const result = compactSession({
56
- sessionId: sid,
57
- messages: view,
58
- keepFrom,
59
- summary: opts.summary,
60
- timestamp: Date.now(),
61
- onTier: runtime.makeTierCallback(ctx),
62
- compressionPressure: opts.compressionPressure,
63
- }, runtime.store);
64
- runtime.pulsing = false;
65
- if (result.skipped)
66
- return { skipped: true };
67
- if (!result.deduped) {
68
- runtime.rt.persistedThisSession = true;
69
- runtime.rt.lastCheckpointId = result.checkpointId;
70
- }
71
- runtime.rt.lastCompactedFrom = result.compactedFrom;
72
- runtime.rt.lastCompactedTokens = result.tokenEstimate;
73
- runtime.rt.dedupAttempts++;
74
- // Honest "tokens saved" for this session-instance only:
75
- // new checkpoint → original − stored
76
- // deduped onto existing → whole original region (nothing new stored)
77
- // Resets to 0 on session_start (rt is rebuilt) — so a fresh session shows 0
78
- // while the repo's cumulative saved (SQLite meta) keeps the running total.
79
- const saved = result.deduped
80
- ? result.originalTokenEstimate
81
- : Math.max(0, result.originalTokenEstimate - result.tokenEstimate);
82
- runtime.rt.tokensSaved += saved;
83
- runtime.rt.compactCount += 1;
84
- incCompactCount(runtime.currentStateDir);
85
- if (result.deduped) {
86
- runtime.rt.cacheHitTokens += saved;
87
- incCacheHitTokens(saved, runtime.currentStateDir);
88
- }
89
- runtime.rt.lastCompactAt = Date.now();
90
- if (result.deduped)
91
- runtime.rt.dedupSkips++;
92
- // Grow the rolling "saved" goal so the progress bar always has a fresh
93
- // denominator (we don't want it pinned at 100% once we pass an old target).
94
- if (runtime.rt.tokensSaved > runtime.savedGoal)
95
- runtime.savedGoal = Math.ceil((runtime.rt.tokensSaved * 1.25) / 10_000) * 10_000;
96
- // Live toolbar activity: what file/region just got compacted or deduped.
97
- // Rendered via the rotating ticker line (see snapshot); the ring buffer is
98
- // cycled one-per-repaint so the single line scrolls through recent files.
99
- const files = result.filesModified ?? [];
100
- const fileLabel = files.length
101
- ? files.map((f) => f.split("/").pop() ?? f).slice(0, 2).join(", ")
102
- : result.regionHash.slice(0, 8);
103
- runtime.lastActivityAt = Date.now();
104
- // Explain-why line: surfaced while fresh. Pulls the dedup reason (which for
105
- // L2 includes the cosine sim) so the user sees WHY a region was kept/dropped.
106
- runtime.lastWhy = result.deduped
107
- ? `why: deduped@${result.dedupReason ?? "tier"}`
108
- : `why: compacted → ${result.checkpointId}`;
109
- // Recall/activity ticker: record this event in the ring buffer.
110
- const savedK = (saved / 1000).toFixed(1);
111
- runtime.pushTicker(result.deduped
112
- ? `${C.green}♻${C.reset} deduped ${fileLabel} · ${savedK}k saved`
113
- : `${C.cyan}🗜${C.reset} ${result.checkpointId} · +${savedK}k · ${fileLabel}`);
114
- // The per-tier trace has settled into the final outcome — fold it back into
115
- // the activity line and stop showing the live trace.
116
- runtime.tierTrace = undefined;
117
- // Record session activity + a daily-log entry in the per-repo SQLite store
118
- // (foundation for resume-sessions / daily-log features). Best-effort — never
119
- // block a compaction on bookkeeping.
120
- try {
121
- const root = resolveRepoRoot(ctx.cwd);
122
- touchSession(sid, root, runtime.currentStateDir);
123
- logDaily(sid, "compact", result.checkpointId, saved, runtime.currentStateDir);
124
- }
125
- catch {
126
- /* non-fatal: stats bookkeeping only */
127
- }
128
- // S21.2: best-effort consolidation of near-duplicate memories for this repo.
129
- // Runs after the per-repo stats touch so `consolidateMemories` can use the
130
- // same stateDir. Non-fatal — a failed consolidate never blocks a compaction.
131
- // Only runs when new memory ops landed in this pass (otherwise the prior
132
- // compaction's consolidate already had its shot — re-running would just
133
- // touch every row again with no merges).
134
- if (!result.deduped && runtime.memoriesTouchedThisCompaction > 0) {
135
- try {
136
- const root = resolveRepoRoot(ctx.cwd);
137
- void consolidateMemories(runtime.currentStateDir, root).then((n) => {
138
- if (n > 0)
139
- runtime.pushTicker(`${C.green}∫${C.reset} consolidated ${n} memory dup${n === 1 ? "" : "s"}`);
140
- }, () => {
141
- /* swallow: consolidate failures must never surface to the user */
142
- });
143
- }
144
- catch {
145
- /* non-fatal */
146
- }
147
- }
148
- // S24 review-on-compact: when pressure is high, the just-compacted region is
149
- // exactly the context worth remembering, so review it immediately rather than
150
- // waiting for the next turn-cadence tick. Uses the shared runMemoryReview
151
- // helper (fire-and-forget; doCompact is sync). Best-effort + non-fatal. Only
152
- // fires above the `high` band so low-pressure compactions don't pay the cost.
153
- if (!result.deduped && config.memoryAutoReview && runtime.pressureBand !== "low" && runtime.pressureBand !== "medium") {
154
- void runMemoryReview(runtime, view, "pressure");
155
- }
156
- // Sentinel marker: a non-LLM bookkeeping entry so subsequent triggers can
157
- // skip re-vectorizing an already-compacted region (zero token cost).
158
- // v0.8.6: gate on !result.deduped so the marker ONLY lands when a genuinely
159
- // new checkpoint was created. Without this, every dedup re-fire appended a
160
- // fresh sentinel to the real transcript, bloating it and perturbing the
161
- // provider KV-cache prefix (the alternating cache-miss regression). Matches
162
- // the RAPTOR + vector-index blocks above, which are already !deduped-gated.
163
- if (!result.deduped) {
164
- pi.appendEntry(MARKER_TYPE, {
165
- checkpointId: result.checkpointId,
166
- regionHash: result.regionHash,
167
- tokenEstimate: result.tokenEstimate,
168
- deduped: result.deduped,
169
- });
170
- }
171
- // Fix D: refresh the RAPTOR tree for this session so live recall (search) can
172
- // serve high-level summaries. Best-effort + non-fatal: never block compaction.
173
- // Budget-guarded (RAPTOR_BUDGET_MS) so it can't hang a large session.
174
- if (config.raptorEnabled && !result.deduped) {
175
- try {
176
- const dd = loadDedupConfig();
177
- const all = vectorList(runtime.store, sid);
178
- const leaves = all.map((cp) => ({
179
- id: cp.checkpointId,
180
- messages: [],
181
- sourceText: cp.normalizedText ?? cp.summary ?? cp.regionHash,
182
- embedding: cp.embedding,
183
- }));
184
- if (leaves.length >= 2) {
185
- // S42D: skip the rebuild when the last build is fresh (within
186
- // RAPTOR_FRESHNESS_HOURS) and the checkpoint count hasn't drifted by
187
- // more than 20%. avoids re-clustering on every compaction when the
188
- // tree is still representative. 0 disables (always rebuild).
189
- if (dd.RAPTOR_FRESHNESS_HOURS > 0 &&
190
- isRaptorTreeFresh(sid, runtime.currentStateDir, dd.RAPTOR_FRESHNESS_HOURS, all.length)) {
191
- runtime.logger?.info("raptor_skip_fresh", { sessionId: sid });
192
- }
193
- else {
194
- // S25: stamp the tree with the newest checkpoint epoch so the
195
- // freshness guard in raptorSearchHits can reject stale trees after a
196
- // later compaction adds newer checkpoints.
197
- const builtAt = all.length > 0 ? Math.max(...all.map((c) => c.timestamp)) : Date.now();
198
- runRaptor(leaves, {
199
- stateDir: runtime.currentStateDir,
200
- sessionId: sid,
201
- budgetMs: dd.RAPTOR_BUDGET_MS,
202
- clustersPerLevel: dd.RAPTOR_CLUSTERS_PER_LEVEL,
203
- consistencyThreshold: dd.RAPTOR_CONSISTENCY,
204
- logger: runtime.logger,
205
- builtAt: Number.isFinite(builtAt) ? builtAt : Date.now(),
206
- });
207
- }
208
- }
209
- }
210
- catch {
211
- /* non-fatal: tree refresh never blocks a compaction */
212
- }
213
- }
214
- // Slice 2: best-effort mirror of the new checkpoint into the async global
215
- // PGlite/HNSW vector index. Fires once per compaction (not per-add), so the
216
- // shared global dir is never hammered by concurrent test workers.
217
- // Non-fatal: a WASM init failure degrades to the sync scan silently.
218
- if (!result.deduped) {
219
- try {
220
- const all = vectorList(runtime.store, sid);
221
- const latest = all.find((cp) => cp.checkpointId === result.checkpointId);
222
- if (latest?.embedding) {
223
- void indexUpsertEmbedding(repoKey(runtime.currentStateDir), sid, latest.checkpointId, latest.embedding).catch(() => {
224
- /* non-fatal: index refresh never blocks a compaction */
225
- });
226
- }
227
- }
228
- catch {
229
- /* non-fatal: index refresh never blocks a compaction */
230
- }
231
- }
232
- runtime.setStatus(ctx, runtime.rt.persistedThisSession
233
- ? `mega-compact: ${result.checkpointId} · ${saved} tok saved`
234
- : `mega-compact: ready`);
235
- runtime.logger.info("compact", {
236
- sessionId: sid,
237
- checkpointId: result.checkpointId ?? "(deduped)",
238
- deduped: result.deduped,
239
- tokenEstimate: saved,
240
- compactedFrom: result.compactedFrom,
241
- });
242
- runtime.dashboard.event("compact", {
243
- sessionId: sid,
244
- checkpointId: result.checkpointId ?? "(deduped)",
245
- deduped: result.deduped,
246
- tokenEstimate: saved,
247
- compactedFrom: result.compactedFrom,
248
- });
249
- runtime.snapshot(ctx);
250
- return { skipped: false, result, keepFrom, saved };
251
- }
252
- /**
253
- * Predict whether pi's `ctx.compact()` would throw a no-op error — "Already
254
- * compacted" or "Nothing to compact (session too small)" — so the auto-trigger
255
- * can SKIP the call instead of surfacing a hard, user-facing error.
256
- *
257
- * Why we can't intercept or suppress it: pi's public `compact()` computes
258
- * `prepareCompaction()` and throws *before* it emits `session_before_compact`,
259
- * so our handler there never runs on the no-op path. And `ctx.compact()`'s
260
- * `onError` callback fires only AFTER pi has already emitted a `compaction_end`
261
- * event carrying the error message (which the interactive UI renders) — so
262
- * `onError` cannot mute it either. The only robust fix is to not call
263
- * `ctx.compact()` when pi would no-op. (pi's own `_runAutoCompaction` path is
264
- * silent on this same condition; the public path we're forced through is the
265
- * one that throws.)
266
- *
267
- * Skipping is correct, not a compromise: by the time this runs, `runCompact()`
268
- * has already persisted the recall checkpoint (Path A). The durable on-disk
269
- * trim is only useful when pi can actually summarize a region; a transcript
270
- * under pi's `keepRecentTokens` budget is small enough that reloading it on
271
- * resume isn't a token-growth problem, so the durable trim is unnecessary
272
- * there anyway.
273
- *
274
- * Mirrors pi's `prepareCompaction()` return-undefined conditions (compaction.js):
275
- * (1) last entry is a compaction → "Already compacted"
276
- * (2) <2 cut-point messages since the last compaction → nothing to summarize
277
- * (a cut point = any non-toolResult message — user/assistant/bash/custom/
278
- * branchSummary/compactionSummary — matching pi's isCutPointMessage)
279
- * (3) transcript tokens since the last compaction < keepRecentTokens → pi
280
- * keeps everything → nothing to summarize
281
- * `keepRecentTokens` isn't readable from the extension API, so (3) uses the pi
282
- * default (20000) as a conservative floor; raise it via
283
- * `MEGACOMPACT_DURABLE_TRIM_FLOOR` if you raise pi's `compact.keepRecentTokens`.
284
- *
285
- * Best-effort: on any read error returns true (skip) — skipping a durable trim
286
- * is always safe; calling `ctx.compact()` on a no-op throws to the user.
2
+ * compact.ts — delegate-shell for the compaction pipeline (3WF-2 split).
3
+ *
4
+ * This file is now a thin barrel: the real bodies live in `./compact/` so the
5
+ * module stays well under the extensions/ 400-line soft cap. The public API is
6
+ * UNCHANGED every existing importer (via `../mega-pipeline.js`, which does
7
+ * `export * from "./mega-pipeline/compact.js"`) keeps working with ZERO changes
8
+ * at their call sites. Exports preserved exactly:
9
+ * - `RunCompactResult` (type)
10
+ * - `runCompact`
11
+ * - `piCompactWouldNoop`
287
12
  */
288
- export function piCompactWouldNoop(ctx) {
289
- try {
290
- const branch = ctx.sessionManager.getBranch();
291
- if (branch.length === 0)
292
- return true;
293
- // (1) already compacted — pi throws "Already compacted"
294
- if (branch[branch.length - 1].type === "compaction")
295
- return true;
296
- // boundaryStart = index just after the most recent compaction entry (or 0)
297
- let boundaryStart = 0;
298
- for (let i = branch.length - 1; i >= 0; i--) {
299
- if (branch[i].type === "compaction") {
300
- boundaryStart = i + 1;
301
- break;
302
- }
303
- }
304
- let cutPoints = 0;
305
- let tokens = 0;
306
- for (let i = boundaryStart; i < branch.length; i++) {
307
- const e = branch[i];
308
- if (e.type === "compaction")
309
- continue;
310
- let isCut = false;
311
- for (const m of sessionEntryToContextMessages(e)) {
312
- // pi's isCutPointMessage: every role except toolResult
313
- if (m.role !== "toolResult")
314
- isCut = true;
315
- const c = m.content;
316
- const text = typeof c === "string" ? c
317
- : Array.isArray(c)
318
- ? c.map((b) => b?.text ?? "").join(" ")
319
- : "";
320
- if (text)
321
- tokens += estimateBlockTokens(text);
322
- }
323
- if (isCut)
324
- cutPoints++;
325
- }
326
- // (2) need >=2 cut points so the kept cut isn't the first message
327
- if (cutPoints < 2)
328
- return true;
329
- // (3) transcript under pi's keepRecentTokens budget → pi keeps everything
330
- if (tokens < durableTrimFloorTokens())
331
- return true;
332
- return false;
333
- }
334
- catch {
335
- return true; // safe: skip the durable trim rather than risk a user-facing throw
336
- }
337
- }
338
- /** pi's default keepRecentTokens (compaction settings). Override with
339
- * MEGACOMPACT_DURABLE_TRIM_FLOOR if you raise pi's compact.keepRecentTokens. */
340
- function durableTrimFloorTokens() {
341
- const raw = process.env.MEGACOMPACT_DURABLE_TRIM_FLOOR;
342
- if (raw !== undefined && Number.isFinite(Number(raw)))
343
- return Number(raw);
344
- return 20_000;
345
- }
13
+ export { runCompact } from "./compact/run.js";
14
+ export { piCompactWouldNoop } from "./compact/noop.js";
@@ -0,0 +1,258 @@
1
+ /**
2
+ * recall/impl.ts — unified Layer-5 recall pipeline implementation (3WF-3 split).
3
+ *
4
+ * Behavior is UNCHANGED from the pre-split recall.ts. `doRecall` is the ONE path
5
+ * that injects (sync). `doRecallAsync` augments with optional cross-repo HNSW
6
+ * on resume / /mega-recall --cross-repo. Both mutate the shared MegaRuntime
7
+ * (token accounting, ticker, dashboard events). The shell recall.ts re-exports
8
+ * these names so `export * from "./mega-pipeline/recall.js"` stays byte-stable.
9
+ */
10
+ import { sessionEntryToContextMessages } from "@earendil-works/pi-coding-agent";
11
+ import { recallAndInline, recallAndInlineAsync, formatRecallBlock, } from "../../../src/recall.js";
12
+ import { normalizeSessionId } from "../../../src/store.js";
13
+ import { incRecallInjected, incCacheHitTokens, getIndexDir, } from "../../../src/store/sqlite.js";
14
+ import { ensureConversationIdFor, recordTurnWrite, recordRecallWrite, } from "../../mega-turn-store.js";
15
+ import { C } from "../../mega-runtime.js";
16
+ import { recordRecallLatency } from "../../mega-runtime/vc-observer.js";
17
+ /**
18
+ * Unified recall (Layer 5). The ONE path that injects. Returns the recall
19
+ * result; callers decide whether to stage it for before_agent_start (resume)
20
+ * or report it (command).
21
+ */
22
+ export function doRecall(runtime, config, ctx, query, source) {
23
+ runtime.bindRepo(ctx.cwd);
24
+ const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
25
+ // Live window text for inline dedupe (Fix C): drop recalled checkpoints that
26
+ // are already resident in the session, so recall never re-injects context the
27
+ // model can already see. Best-effort — an empty window just skips dedupe.
28
+ const liveWindow = config.windowDedupe ? extractLiveWindow(ctx) : undefined;
29
+ const recallStartMs = Date.now();
30
+ const result = recallAndInline({
31
+ sessionId: sid,
32
+ query,
33
+ limit: config.autoInlineK,
34
+ source,
35
+ skipInjected: true,
36
+ recallMaxTokens: config.recallMaxTokens,
37
+ windowDedupe: config.windowDedupe,
38
+ liveWindow,
39
+ dedupSim: config.dedupSim,
40
+ }, runtime.store);
41
+ runtime.dashboard.event("recall", {
42
+ source,
43
+ query: query.slice(0, 120),
44
+ injected: result.toInject.length,
45
+ empty: result.empty,
46
+ });
47
+ if (config.ragRecallMetrics && result.hydeInfo) {
48
+ runtime.dashboard.event("hyde_executed", {
49
+ sessionId: sid,
50
+ ran: result.hydeInfo.ran,
51
+ skipped: result.hydeInfo.skipped,
52
+ reason: result.hydeInfo.reason,
53
+ hypotheticalDoc: result.hydeInfo.hypotheticalDoc.slice(0, 400),
54
+ generationMs: result.hydeInfo.generationMs,
55
+ rawHitCount: result.hydeInfo.rawHitCount,
56
+ hydeHitCount: result.hydeInfo.hydeHitCount,
57
+ fusedHitCount: result.hydeInfo.fusedHitCount,
58
+ lift: result.hydeInfo.lift,
59
+ });
60
+ }
61
+ if (config.ragRecallMetrics && result.recallMetrics) {
62
+ runtime.dashboard.event("recall_metrics", {
63
+ sessionId: sid,
64
+ hitCount: result.recallMetrics.hitCount,
65
+ score: result.recallMetrics.score,
66
+ pass: result.recallMetrics.pass,
67
+ relevance: result.recallMetrics.relevance,
68
+ coverage: result.recallMetrics.coverage,
69
+ diversity: result.recallMetrics.diversity,
70
+ specificity: result.recallMetrics.specificity,
71
+ });
72
+ }
73
+ if (!result.empty && result.toInject.length > 0) {
74
+ const top = result.toInject[0];
75
+ const scorePct = Math.round((top.score ?? 0) * 100);
76
+ const files = top.checkpoint.filesModified ?? [];
77
+ const label = files.length
78
+ ? files
79
+ .map((f) => f.split("/").pop() ?? f)
80
+ .slice(0, 2)
81
+ .join(", ")
82
+ : top.checkpoint.checkpointId;
83
+ runtime.pushTicker(`${C.amber}↩${C.reset} recalled ${top.checkpoint.checkpointId} · ${scorePct}% · ${label}`);
84
+ runtime.lastWhy = `why: recalled@${scorePct}% (${result.toInject.length} chkpt)`;
85
+ }
86
+ let sumTokens = 0;
87
+ for (const h of result.toInject)
88
+ sumTokens += h.checkpoint.tokenEstimate;
89
+ if (result.toInject.length > 0) {
90
+ runtime.rt.recallInjections += result.toInject.length;
91
+ runtime.rt.cacheHitTokens += sumTokens;
92
+ incRecallInjected(result.toInject.length, runtime.currentStateDir);
93
+ incCacheHitTokens(sumTokens, runtime.currentStateDir);
94
+ }
95
+ // S43: record recall provenance — which checkpoints/summaries served this
96
+ // turn, their score + source path. Linked to the turn row written at
97
+ // turn_end via the conversation+turnIndex. Best-effort + non-fatal.
98
+ // Persists telemetry (HyDE + recall metrics) even when recall returned
99
+ // no hits, so empty-recall HyDE invocations are still visible in the
100
+ // dashboard Turns/Metrics tabs.
101
+ const hasTelemetry = result.hydeInfo != null || result.recallMetrics != null;
102
+ if (result.toInject.length > 0 || hasTelemetry) {
103
+ try {
104
+ const convId = ensureConversationIdFor(config, sid, runtime.currentStateDir);
105
+ const turnId = recordTurnWrite(config, {
106
+ conversationId: convId,
107
+ sessionId: sid,
108
+ turnIndex: runtime.currentTurn,
109
+ role: "assistant",
110
+ startedAt: Date.now(),
111
+ hyde: result.hydeInfo ?? undefined,
112
+ recallMetrics: result.recallMetrics ?? undefined,
113
+ }, runtime.currentStateDir);
114
+ if (result.toInject.length > 0) {
115
+ recordRecallWrite(config, turnId, result.toInject.map((h) => ({
116
+ checkpointId: h.checkpoint.checkpointId,
117
+ score: h.score,
118
+ source: h.raptorLevel !== undefined
119
+ ? "raptor"
120
+ : h.repoId
121
+ ? "cross-repo"
122
+ : "flat",
123
+ raptorLevel: h.raptorLevel,
124
+ })), runtime.currentStateDir);
125
+ }
126
+ }
127
+ catch {
128
+ /* non-fatal: recall provenance never breaks the recall path */
129
+ }
130
+ }
131
+ // VC0A: record recall latency on the eval observer (mode A) so the dashboard
132
+ // histogram reflects real data. No-op when the observer is absent (flag off /
133
+ // construction failure).
134
+ try {
135
+ recordRecallLatency(runtime, Date.now() - recallStartMs, sid, 0);
136
+ }
137
+ catch {
138
+ /* non-fatal: latency recording never breaks recall */
139
+ }
140
+ return result;
141
+ }
142
+ /**
143
+ * S17: async recall with optional cross-repo augmentation. Used on resume
144
+ * (session_start) and /mega-recall --cross-repo — NEVER from the mid-turn
145
+ * context handler (that stays sync). Runs the sync same-repo scan first; if it
146
+ * returns < config.autoInlineK hits AND crossRepo is enabled, awaits the PGlite
147
+ * HNSW cross-repo path and merges (source-labeled, deduped by checkpointId). The
148
+ * recallMaxTokens cap + windowDedupe apply to the merged set so cross-repo can
149
+ * never net-inflate the window. Cross-repo uses a stricter cosine floor
150
+ * (config.crossRepoCosine) than same-repo. Non-fatal: any async failure returns
151
+ * the same-repo result unchanged.
152
+ */
153
+ export async function doRecallAsync(runtime, config, ctx, query, source, opts = {}) {
154
+ runtime.bindRepo(ctx.cwd);
155
+ const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
156
+ const liveWindow = config.windowDedupe ? extractLiveWindow(ctx) : undefined;
157
+ // Sync same-repo first (fast, never blocks).
158
+ const sameRepo = recallAndInline({
159
+ sessionId: sid,
160
+ query,
161
+ limit: config.autoInlineK,
162
+ source,
163
+ skipInjected: true,
164
+ recallMaxTokens: config.recallMaxTokens,
165
+ windowDedupe: config.windowDedupe,
166
+ liveWindow,
167
+ dedupSim: config.dedupSim,
168
+ }, runtime.store);
169
+ if (!config.crossRepoEnabled || !opts.crossRepo)
170
+ return sameRepo;
171
+ if (sameRepo.toInject.length >= config.autoInlineK)
172
+ return sameRepo; // same-repo satisfied
173
+ // Augment: cross-repo HNSW (async) with the stricter floor. Non-fatal.
174
+ try {
175
+ const x = await recallAndInlineAsync({
176
+ sessionId: sid,
177
+ query,
178
+ limit: config.autoInlineK,
179
+ source,
180
+ skipInjected: true,
181
+ recallMaxTokens: config.recallMaxTokens,
182
+ windowDedupe: config.windowDedupe,
183
+ liveWindow,
184
+ dedupSim: config.crossRepoCosine,
185
+ crossRepo: true,
186
+ // F2: resolve the machine-wide index dir via the shared resolver so the
187
+ // cross-repo injected-set dedup works even when MEGACOMPACT_INDEX_DIR is
188
+ // unset. The env var still wins when set (getIndexDir checks it first);
189
+ // the default (~/.mega-compact-index) is the same DB mega-commands and the
190
+ // dashboard read, so injection counts stay consistent. Without this, a
191
+ // bare `process.env` read returns undefined → cross-repo hits re-inject in
192
+ // every new session (the global injected-set is never consulted).
193
+ globalIndexDir: getIndexDir(),
194
+ }, runtime.store);
195
+ runtime.dashboard.event("recall-crossrepo", {
196
+ source,
197
+ query: query.slice(0, 120),
198
+ injected: x.toInject.length,
199
+ sourceRepos: x.toInject.map((h) => h.repoId).filter(Boolean),
200
+ });
201
+ // Merge, dedup by checkpointId, respect the same token cap by reformatting.
202
+ const seen = new Set(sameRepo.toInject.map((h) => h.checkpoint.checkpointId));
203
+ const merged = [...sameRepo.toInject];
204
+ for (const h of x.toInject) {
205
+ if (!seen.has(h.checkpoint.checkpointId)) {
206
+ merged.push(h);
207
+ seen.add(h.checkpoint.checkpointId);
208
+ }
209
+ }
210
+ const block = merged.length ? formatRecallBlock(merged) : "";
211
+ if (merged.length > 0) {
212
+ let sumTokens = 0;
213
+ for (const h of merged)
214
+ sumTokens += h.checkpoint.tokenEstimate;
215
+ runtime.rt.recallInjections += merged.length;
216
+ runtime.rt.cacheHitTokens += sumTokens;
217
+ incRecallInjected(merged.length, runtime.currentStateDir);
218
+ incCacheHitTokens(sumTokens, runtime.currentStateDir);
219
+ }
220
+ return {
221
+ toInject: merged,
222
+ report: merged.map((h) => ` • ${h.checkpoint.checkpointId}${h.repoId ? ` (from ${h.repoId.split("/").filter(Boolean).pop()})` : ""}`),
223
+ block,
224
+ empty: merged.length === 0,
225
+ // H1: merged cross-repo result reuses the same-repo pass's telemetry.
226
+ hydeInfo: sameRepo.hydeInfo,
227
+ recallMetrics: sameRepo.recallMetrics,
228
+ };
229
+ }
230
+ catch {
231
+ return sameRepo; // cross-repo failure → same-repo only (non-fatal)
232
+ }
233
+ }
234
+ /**
235
+ * Extract the live-window message texts from the session manager (Fix C),
236
+ * for inline-dedupe of recalled checkpoints. Best-effort: returns [] on any
237
+ * error so recall falls back to unbounded (still correct, just no dedupe).
238
+ * Mirrors recentUserQuery's use of sessionEntryToContextMessages.
239
+ */
240
+ export function extractLiveWindow(ctx) {
241
+ try {
242
+ const entries = ctx.sessionManager.getEntries();
243
+ const texts = [];
244
+ for (const e of entries) {
245
+ for (const m of sessionEntryToContextMessages(e)) {
246
+ const c = m.content;
247
+ if (typeof c === "string")
248
+ texts.push(c);
249
+ else if (Array.isArray(c))
250
+ texts.push(c.map((b) => b.text ?? "").join(" "));
251
+ }
252
+ }
253
+ return texts;
254
+ }
255
+ catch {
256
+ return [];
257
+ }
258
+ }