pi-mega-compact 0.20.86 → 0.20.88

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 (34) hide show
  1. package/dist/config.js +9 -0
  2. package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +1 -0
  3. package/dist/extensions/mega-config.js +6 -0
  4. package/dist/extensions/mega-events/context-handler/injectionConfirm.fixture.js +63 -0
  5. package/dist/extensions/mega-events/context-handler/injectionConfirm.js +107 -0
  6. package/dist/extensions/mega-events/context-handler/triggerGuard.js +11 -17
  7. package/dist/extensions/mega-events/context-handler.js +17 -1
  8. package/dist/extensions/mega-pipeline/recall/impl.js +258 -0
  9. package/dist/extensions/mega-pipeline/recall.js +6 -253
  10. package/dist/src/config.js +9 -0
  11. package/dist/src/failback/floor.js +35 -0
  12. package/dist/src/recall/readonly.js +39 -0
  13. package/dist/src/recall/recall3wf.fixture.js +67 -0
  14. package/dist/src/recall/validator.js +99 -0
  15. package/dist/src/recall/vote.js +217 -0
  16. package/dist/src/store/sqlite/fts5-search.js +26 -0
  17. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +1 -0
  18. package/extensions/mega-config-types.ts +5 -0
  19. package/extensions/mega-config.ts +6 -0
  20. package/extensions/mega-events/context-handler/injectionConfirm.fixture.ts +90 -0
  21. package/extensions/mega-events/context-handler/injectionConfirm.ts +168 -0
  22. package/extensions/mega-events/context-handler/triggerGuard.ts +14 -22
  23. package/extensions/mega-events/context-handler.ts +16 -1
  24. package/extensions/mega-pipeline/recall/impl.ts +312 -0
  25. package/extensions/mega-pipeline/recall.ts +10 -306
  26. package/package.json +1 -1
  27. package/src/config.ts +12 -0
  28. package/src/failback/floor.ts +71 -0
  29. package/src/failback/types.ts +44 -0
  30. package/src/recall/readonly.ts +57 -0
  31. package/src/recall/recall3wf.fixture.ts +87 -0
  32. package/src/recall/validator.ts +137 -0
  33. package/src/recall/vote.ts +240 -0
  34. package/src/store/sqlite/fts5-search.ts +40 -0
@@ -1,256 +1,9 @@
1
1
  /**
2
- * recall.ts — unified Layer-5 recall pipeline.
2
+ * recall.ts — shell re-export for the unified Layer-5 recall pipeline (3WF-3 split).
3
3
  *
4
- * `doRecall` is the ONE path that injects (sync). `doRecallAsync` augments with
5
- * optional cross-repo HNSW on resume / /mega-recall --cross-repo. Both mutate
6
- * the shared MegaRuntime (token accounting, ticker, dashboard events).
4
+ * Delegate-shell pattern: the implementation lives in ./recall/impl.ts (kept
5
+ * under the 300-line soft cap). All public symbols are re-exported here so
6
+ * `export * from "./mega-pipeline/recall.js"` (mega-pipeline.ts) and any direct
7
+ * importers keep resolving with byte-identical names.
7
8
  */
8
- import { sessionEntryToContextMessages } from "@earendil-works/pi-coding-agent";
9
- import { recallAndInline, recallAndInlineAsync, formatRecallBlock, } from "../../src/recall.js";
10
- import { normalizeSessionId } from "../../src/store.js";
11
- import { incRecallInjected, incCacheHitTokens, getIndexDir, } from "../../src/store/sqlite.js";
12
- import { ensureConversationIdFor, recordTurnWrite, recordRecallWrite, } from "../mega-turn-store.js";
13
- import { C } from "../mega-runtime.js";
14
- import { recordRecallLatency } from "../mega-runtime/vc-observer.js";
15
- /**
16
- * Unified recall (Layer 5). The ONE path that injects. Returns the recall
17
- * result; callers decide whether to stage it for before_agent_start (resume)
18
- * or report it (command).
19
- */
20
- export function doRecall(runtime, config, ctx, query, source) {
21
- runtime.bindRepo(ctx.cwd);
22
- const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
23
- // Live window text for inline dedupe (Fix C): drop recalled checkpoints that
24
- // are already resident in the session, so recall never re-injects context the
25
- // model can already see. Best-effort — an empty window just skips dedupe.
26
- const liveWindow = config.windowDedupe ? extractLiveWindow(ctx) : undefined;
27
- const recallStartMs = Date.now();
28
- const result = recallAndInline({
29
- sessionId: sid,
30
- query,
31
- limit: config.autoInlineK,
32
- source,
33
- skipInjected: true,
34
- recallMaxTokens: config.recallMaxTokens,
35
- windowDedupe: config.windowDedupe,
36
- liveWindow,
37
- dedupSim: config.dedupSim,
38
- }, runtime.store);
39
- runtime.dashboard.event("recall", {
40
- source,
41
- query: query.slice(0, 120),
42
- injected: result.toInject.length,
43
- empty: result.empty,
44
- });
45
- if (config.ragRecallMetrics && result.hydeInfo) {
46
- runtime.dashboard.event("hyde_executed", {
47
- sessionId: sid,
48
- ran: result.hydeInfo.ran,
49
- skipped: result.hydeInfo.skipped,
50
- reason: result.hydeInfo.reason,
51
- hypotheticalDoc: result.hydeInfo.hypotheticalDoc.slice(0, 400),
52
- generationMs: result.hydeInfo.generationMs,
53
- rawHitCount: result.hydeInfo.rawHitCount,
54
- hydeHitCount: result.hydeInfo.hydeHitCount,
55
- fusedHitCount: result.hydeInfo.fusedHitCount,
56
- lift: result.hydeInfo.lift,
57
- });
58
- }
59
- if (config.ragRecallMetrics && result.recallMetrics) {
60
- runtime.dashboard.event("recall_metrics", {
61
- sessionId: sid,
62
- hitCount: result.recallMetrics.hitCount,
63
- score: result.recallMetrics.score,
64
- pass: result.recallMetrics.pass,
65
- relevance: result.recallMetrics.relevance,
66
- coverage: result.recallMetrics.coverage,
67
- diversity: result.recallMetrics.diversity,
68
- specificity: result.recallMetrics.specificity,
69
- });
70
- }
71
- if (!result.empty && result.toInject.length > 0) {
72
- const top = result.toInject[0];
73
- const scorePct = Math.round((top.score ?? 0) * 100);
74
- const files = top.checkpoint.filesModified ?? [];
75
- const label = files.length
76
- ? files
77
- .map((f) => f.split("/").pop() ?? f)
78
- .slice(0, 2)
79
- .join(", ")
80
- : top.checkpoint.checkpointId;
81
- runtime.pushTicker(`${C.amber}↩${C.reset} recalled ${top.checkpoint.checkpointId} · ${scorePct}% · ${label}`);
82
- runtime.lastWhy = `why: recalled@${scorePct}% (${result.toInject.length} chkpt)`;
83
- }
84
- let sumTokens = 0;
85
- for (const h of result.toInject)
86
- sumTokens += h.checkpoint.tokenEstimate;
87
- if (result.toInject.length > 0) {
88
- runtime.rt.recallInjections += result.toInject.length;
89
- runtime.rt.cacheHitTokens += sumTokens;
90
- incRecallInjected(result.toInject.length, runtime.currentStateDir);
91
- incCacheHitTokens(sumTokens, runtime.currentStateDir);
92
- }
93
- // S43: record recall provenance — which checkpoints/summaries served this
94
- // turn, their score + source path. Linked to the turn row written at
95
- // turn_end via the conversation+turnIndex. Best-effort + non-fatal.
96
- // Persists telemetry (HyDE + recall metrics) even when recall returned
97
- // no hits, so empty-recall HyDE invocations are still visible in the
98
- // dashboard Turns/Metrics tabs.
99
- const hasTelemetry = result.hydeInfo != null || result.recallMetrics != null;
100
- if (result.toInject.length > 0 || hasTelemetry) {
101
- try {
102
- const convId = ensureConversationIdFor(config, sid, runtime.currentStateDir);
103
- const turnId = recordTurnWrite(config, {
104
- conversationId: convId,
105
- sessionId: sid,
106
- turnIndex: runtime.currentTurn,
107
- role: "assistant",
108
- startedAt: Date.now(),
109
- hyde: result.hydeInfo ?? undefined,
110
- recallMetrics: result.recallMetrics ?? undefined,
111
- }, runtime.currentStateDir);
112
- if (result.toInject.length > 0) {
113
- recordRecallWrite(config, turnId, result.toInject.map((h) => ({
114
- checkpointId: h.checkpoint.checkpointId,
115
- score: h.score,
116
- source: h.raptorLevel !== undefined
117
- ? "raptor"
118
- : h.repoId
119
- ? "cross-repo"
120
- : "flat",
121
- raptorLevel: h.raptorLevel,
122
- })), runtime.currentStateDir);
123
- }
124
- }
125
- catch {
126
- /* non-fatal: recall provenance never breaks the recall path */
127
- }
128
- }
129
- // VC0A: record recall latency on the eval observer (mode A) so the dashboard
130
- // histogram reflects real data. No-op when the observer is absent (flag off /
131
- // construction failure).
132
- try {
133
- recordRecallLatency(runtime, Date.now() - recallStartMs, sid, 0);
134
- }
135
- catch {
136
- /* non-fatal: latency recording never breaks recall */
137
- }
138
- return result;
139
- }
140
- /**
141
- * S17: async recall with optional cross-repo augmentation. Used on resume
142
- * (session_start) and /mega-recall --cross-repo — NEVER from the mid-turn
143
- * context handler (that stays sync). Runs the sync same-repo scan first; if it
144
- * returns < config.autoInlineK hits AND crossRepo is enabled, awaits the PGlite
145
- * HNSW cross-repo path and merges (source-labeled, deduped by checkpointId). The
146
- * recallMaxTokens cap + windowDedupe apply to the merged set so cross-repo can
147
- * never net-inflate the window. Cross-repo uses a stricter cosine floor
148
- * (config.crossRepoCosine) than same-repo. Non-fatal: any async failure returns
149
- * the same-repo result unchanged.
150
- */
151
- export async function doRecallAsync(runtime, config, ctx, query, source, opts = {}) {
152
- runtime.bindRepo(ctx.cwd);
153
- const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
154
- const liveWindow = config.windowDedupe ? extractLiveWindow(ctx) : undefined;
155
- // Sync same-repo first (fast, never blocks).
156
- const sameRepo = recallAndInline({
157
- sessionId: sid,
158
- query,
159
- limit: config.autoInlineK,
160
- source,
161
- skipInjected: true,
162
- recallMaxTokens: config.recallMaxTokens,
163
- windowDedupe: config.windowDedupe,
164
- liveWindow,
165
- dedupSim: config.dedupSim,
166
- }, runtime.store);
167
- if (!config.crossRepoEnabled || !opts.crossRepo)
168
- return sameRepo;
169
- if (sameRepo.toInject.length >= config.autoInlineK)
170
- return sameRepo; // same-repo satisfied
171
- // Augment: cross-repo HNSW (async) with the stricter floor. Non-fatal.
172
- try {
173
- const x = await recallAndInlineAsync({
174
- sessionId: sid,
175
- query,
176
- limit: config.autoInlineK,
177
- source,
178
- skipInjected: true,
179
- recallMaxTokens: config.recallMaxTokens,
180
- windowDedupe: config.windowDedupe,
181
- liveWindow,
182
- dedupSim: config.crossRepoCosine,
183
- crossRepo: true,
184
- // F2: resolve the machine-wide index dir via the shared resolver so the
185
- // cross-repo injected-set dedup works even when MEGACOMPACT_INDEX_DIR is
186
- // unset. The env var still wins when set (getIndexDir checks it first);
187
- // the default (~/.mega-compact-index) is the same DB mega-commands and the
188
- // dashboard read, so injection counts stay consistent. Without this, a
189
- // bare `process.env` read returns undefined → cross-repo hits re-inject in
190
- // every new session (the global injected-set is never consulted).
191
- globalIndexDir: getIndexDir(),
192
- }, runtime.store);
193
- runtime.dashboard.event("recall-crossrepo", {
194
- source,
195
- query: query.slice(0, 120),
196
- injected: x.toInject.length,
197
- sourceRepos: x.toInject.map((h) => h.repoId).filter(Boolean),
198
- });
199
- // Merge, dedup by checkpointId, respect the same token cap by reformatting.
200
- const seen = new Set(sameRepo.toInject.map((h) => h.checkpoint.checkpointId));
201
- const merged = [...sameRepo.toInject];
202
- for (const h of x.toInject) {
203
- if (!seen.has(h.checkpoint.checkpointId)) {
204
- merged.push(h);
205
- seen.add(h.checkpoint.checkpointId);
206
- }
207
- }
208
- const block = merged.length ? formatRecallBlock(merged) : "";
209
- if (merged.length > 0) {
210
- let sumTokens = 0;
211
- for (const h of merged)
212
- sumTokens += h.checkpoint.tokenEstimate;
213
- runtime.rt.recallInjections += merged.length;
214
- runtime.rt.cacheHitTokens += sumTokens;
215
- incRecallInjected(merged.length, runtime.currentStateDir);
216
- incCacheHitTokens(sumTokens, runtime.currentStateDir);
217
- }
218
- return {
219
- toInject: merged,
220
- report: merged.map((h) => ` • ${h.checkpoint.checkpointId}${h.repoId ? ` (from ${h.repoId.split("/").filter(Boolean).pop()})` : ""}`),
221
- block,
222
- empty: merged.length === 0,
223
- // H1: merged cross-repo result reuses the same-repo pass's telemetry.
224
- hydeInfo: sameRepo.hydeInfo,
225
- recallMetrics: sameRepo.recallMetrics,
226
- };
227
- }
228
- catch {
229
- return sameRepo; // cross-repo failure → same-repo only (non-fatal)
230
- }
231
- }
232
- /**
233
- * Extract the live-window message texts from the session manager (Fix C),
234
- * for inline-dedupe of recalled checkpoints. Best-effort: returns [] on any
235
- * error so recall falls back to unbounded (still correct, just no dedupe).
236
- * Mirrors recentUserQuery's use of sessionEntryToContextMessages.
237
- */
238
- function extractLiveWindow(ctx) {
239
- try {
240
- const entries = ctx.sessionManager.getEntries();
241
- const texts = [];
242
- for (const e of entries) {
243
- for (const m of sessionEntryToContextMessages(e)) {
244
- const c = m.content;
245
- if (typeof c === "string")
246
- texts.push(c);
247
- else if (Array.isArray(c))
248
- texts.push(c.map((b) => b.text ?? "").join(" "));
249
- }
250
- }
251
- return texts;
252
- }
253
- catch {
254
- return [];
255
- }
256
- }
9
+ export { doRecall, doRecallAsync, extractLiveWindow, } from "./recall/impl.js";
@@ -110,6 +110,15 @@ export const RAG_HYDE_ENABLED = () => ragEnabled("MEGACOMPACT_HYDE");
110
110
  /** Spec 1: vbrainstorm visual design migration for the dashboard. */
111
111
  export const NEW_UI = () => ragEnabled("MEGACOMPACT_NEW_UI");
112
112
  // ---------------------------------------------------------------------------
113
+ // 3WF-3 same-repo recall cosine floor. SEPARATE from the S17 cross-repo floor
114
+ // (config.crossRepoCosine, default 0.90 — stricter, cross-repo only). This is
115
+ // the same-repo floor the 3-source validator applies to the top winner. A low
116
+ // default (0.12) keeps recall permissive within a repo while still rejecting
117
+ // effectively-unrelated hits. Call-time read so tests can set the env per-test.
118
+ // ---------------------------------------------------------------------------
119
+ /** Same-repo recall cosine floor: top winner must be >= this to be injected. */
120
+ export const RECALL_MIN_COSINE = () => Number(process.env.MEGACOMPACT_RECALL_MIN_COSINE ?? "0.12");
121
+ // ---------------------------------------------------------------------------
113
122
  // Vector-cortex flags + breaker constants (VC0A+). Positive sprint flags,
114
123
  // default ON, `=0`/`_DISABLED` off. Re-exported from src/config/vector-cortex.ts
115
124
  // so root consumers share one source of truth.
@@ -0,0 +1,35 @@
1
+ /** Floor text when the newest checkpoint summary is available (prefix). */
2
+ const WITH_SUMMARY_PREFIX = "The following compacted context is the most recent checkpoint from " +
3
+ "this session (recall found no query-relevant match):\n\n";
4
+ /** Floor text when checkpoints exist but no usable summary does. */
5
+ const NO_SUMMARY_TEXT = "This session has compacted context but recall could not surface a " +
6
+ "checkpoint relevant to the current request; the most recent checkpoint " +
7
+ "summary is unavailable.";
8
+ /** Floor text when the checkpoint read itself failed (hard last resort). */
9
+ export const FLOOR_UNAVAILABLE_TEXT = "This session has compacted context but recall could not surface a " +
10
+ "checkpoint relevant to the current request.";
11
+ /** The newest checkpoint by timestamp (first element wins ties, as before). */
12
+ export function newestCheckpoint(cps) {
13
+ let newest = cps[0];
14
+ for (const cp of cps) {
15
+ if (!newest || (cp.timestamp ?? 0) > (newest.timestamp ?? 0))
16
+ newest = cp;
17
+ }
18
+ return newest;
19
+ }
20
+ /**
21
+ * Build the provenance floor from an already-read checkpoint list. Pure: the
22
+ * caller owns the read (and any dedup-status filtering), so both legacy call
23
+ * sites keep byte-identical output.
24
+ */
25
+ export function buildFloorBlock(cps) {
26
+ const summary = newestCheckpoint(cps)?.summary?.trim();
27
+ if (summary) {
28
+ return { text: WITH_SUMMARY_PREFIX + summary, basis: "lastCheckpoint" };
29
+ }
30
+ return { text: NO_SUMMARY_TEXT, basis: "lastCheckpoint" };
31
+ }
32
+ /** The hard last-resort floor (checkpoint read unavailable or threw). */
33
+ export function unavailableFloorBlock() {
34
+ return { text: FLOOR_UNAVAILABLE_TEXT, basis: "none" };
35
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * recall/readonly.ts — read-only recall variant (3WF-3 Source A).
3
+ *
4
+ * A pure search+rank seam wrapping `engine.recall`'s RAW `hits` path. It is the
5
+ * canonical read-only entry point going forward (triggerGuard.ts still inlines
6
+ * `recall(...).hits` for its own need; this module is additive and does NOT
7
+ * refactor it).
8
+ *
9
+ * HARD contract (QA): this module MUST NOT call `vectorMarkInjected`, must NOT
10
+ * write any turn/recall rows, and must NOT emit S43 telemetry. It only searches
11
+ * and returns hits for the vote. RecallAndInline's inject loop is the ONLY place
12
+ * the injected-set is mutated; keying the vote on raw `hits` (skipInjected:false
13
+ * => hits === newHits) is deliberate — `newHits` is post-`skipInjected` filter,
14
+ * which would distort overlap appearance.
15
+ *
16
+ * Non-fatal: any failure returns [] so the caller degrades to other sources.
17
+ * Pi-agnostic: no pi runtime imports.
18
+ */
19
+ import { recall } from "../engine.js";
20
+ /**
21
+ * Raw, read-only recall hits for the 3-source vote. Returns `engine.recall`'s
22
+ * RAW `.hits` (skipInjected:false => equals the unfiltered vector result). No
23
+ * injected-set mutation, no turn writes, no telemetry. Returns [] on failure.
24
+ */
25
+ export function recallRawHits(opts, store) {
26
+ try {
27
+ const result = recall({
28
+ sessionId: opts.sessionId,
29
+ query: opts.query,
30
+ limit: opts.limit ?? 3,
31
+ skipInjected: false,
32
+ }, store);
33
+ return result.hits;
34
+ }
35
+ catch {
36
+ // Non-fatal: never break the agent loop. Degrade to other sources.
37
+ return [];
38
+ }
39
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * src/recall/recall3wf.fixture.ts — shared fixtures for the 3WF-3 recall tests.
3
+ *
4
+ * Split out of recall3wf.test.ts (which crossed the src 300 soft cap) so each
5
+ * test file stays under the limit. These are REAL fixtures, not mocks/stubs:
6
+ * a REAL VectorStore over a temp stateDir, REAL checkpoints persisted via
7
+ * compactSession, and readers that go through the SAME working path the
8
+ * extension uses (recallRawHits -> vectorSearch -> listCheckpoints, and
9
+ * vectorWasInjected), mirroring the proven triggerGuard test pattern.
10
+ */
11
+ import { mkdtempSync } from "node:fs";
12
+ import { tmpdir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { VectorStore } from "../vectorStore.js";
15
+ import { compactSession } from "../engine.js";
16
+ import { recallAndInline } from "../recall.js";
17
+ import { recallRawHits } from "./readonly.js";
18
+ import { openStore } from "../store/sqlite/utils.js";
19
+ import { initSchema } from "../store/sqlite/schema.js";
20
+ /** Real EngineMessage fixture. */
21
+ export function msg(role, text) {
22
+ return { role, text };
23
+ }
24
+ /** Fresh isolated state dir per VectorStore. */
25
+ export function freshStore() {
26
+ const dir = mkdtempSync(join(tmpdir(), "mc-3wf-"));
27
+ return { store: new VectorStore({ dedupSim: 0.9, stateDir: dir }), dir };
28
+ }
29
+ /** Persist N distinct checkpoints with distinct content + ascending timestamps. */
30
+ export function seed(store, topics, sid = "sess_3wf") {
31
+ topics.forEach((t, i) => {
32
+ compactSession({
33
+ sessionId: sid,
34
+ messages: [msg("user", t), msg("assistant", "ok")],
35
+ keepFrom: 2,
36
+ timestamp: i + 1,
37
+ }, store);
38
+ });
39
+ }
40
+ /** Checkpoint ids via the real search path (vectorSearch -> listCheckpoints). */
41
+ export function checkpointIds(store, sid, query) {
42
+ return recallRawHits({ sessionId: sid, query, limit: 10 }, store).map((h) => h.checkpoint.checkpointId);
43
+ }
44
+ /** Run the real recallAndInline path with skipInjected:false so nothing is
45
+ * marked and the block reflects the search result exactly (deterministic). */
46
+ export function recallAndInlineCapture(sid, query, store) {
47
+ const r = recallAndInline({ sessionId: sid, query, limit: 3, source: "command", skipInjected: false, windowDedupe: false }, store);
48
+ return { block: r.block, empty: r.empty, toInject: r.toInject };
49
+ }
50
+ /** Count recall-provenance rows (turn_recall) for a session via raw SQL reader. */
51
+ export function countTurnRecallRows(store, sid) {
52
+ try {
53
+ const reader = openStore(store.stateDir);
54
+ // Ensure the turns/turn_recall tables exist so a 0-count is meaningful
55
+ // (a write on the new path would be visible, not masked by a missing table).
56
+ initSchema(reader);
57
+ const row = reader
58
+ .prepare(`SELECT COUNT(*) AS n FROM turn_recall tr
59
+ JOIN turns t ON t.id = tr.turn_id
60
+ WHERE t.session_id = ?`)
61
+ .get(sid);
62
+ return row?.n ?? 0;
63
+ }
64
+ catch {
65
+ return 0;
66
+ }
67
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * recall/validator.ts — independent candidate validator (3WF-3).
3
+ *
4
+ * Judges candidates handed to it; it MUST NOT call any search itself. Given the
5
+ * ranked vote winners + the live-window text (already extracted by the caller,
6
+ * since src/ cannot import pi types), it walks the winners in order and returns
7
+ * the first that passes BOTH gates:
8
+ *
9
+ * 1. Cosine floor: the winner's score >= the same-repo floor (default 0.12,
10
+ * env MEGACOMPACT_RECALL_MIN_COSINE). The cross-repo 0.90 floor
11
+ * (config.crossRepoCosine) is SEPARATE and intentionally untouched.
12
+ * 2. Not already resident in the live window: reuse recall/sync.ts's exact
13
+ * comparison — embed each live message, embed the checkpoint summary, and
14
+ * treat the checkpoint as resident when cosineSimilarity >= dedupSim. We
15
+ * reuse that metric rather than inventing a new one.
16
+ *
17
+ * On a failing candidate it advances to the next-ranked winner. If ALL fail it
18
+ * returns the provenance floor (FloorBlock built from the newest checkpoint —
19
+ * pure over checkpoints, same semantics as triggerGuard's buildFloorBlock).
20
+ *
21
+ * Non-fatal throughout: any error degrades to the next candidate / the floor.
22
+ * Pi-agnostic: no pi runtime imports.
23
+ */
24
+ import { defaultEmbedder, cosineSimilarity } from "../embedder.js";
25
+ // SQLite store, NOT src/store.ts's legacy gzipped-JSON DR reader (that returns
26
+ // [] for live sessions). Mirrors vector-search.ts / tieredRouter.ts.
27
+ import { listCheckpoints } from "../store/sqlite.js";
28
+ import { RECALL_MIN_COSINE } from "../config.js";
29
+ import { buildFloorBlock as sharedFloorBlock, unavailableFloorBlock, } from "../failback/floor.js";
30
+ /**
31
+ * Build the provenance floor block from the session's newest checkpoint.
32
+ *
33
+ * 3WF-4: the text construction moved to the SHARED pure builder
34
+ * (src/failback/floor.ts). This wrapper keeps THIS call site's read semantics —
35
+ * `listCheckpoints` filtered to `dedupStatus !== "removed"` — so the output is
36
+ * byte-identical to the pre-refactor 3WF-3 version.
37
+ */
38
+ function buildFloorBlock(sessionId, store) {
39
+ try {
40
+ const cps = listCheckpoints(sessionId, store.stateDir).filter((c) => c.dedupStatus !== "removed");
41
+ return sharedFloorBlock(cps);
42
+ }
43
+ catch {
44
+ return unavailableFloorBlock();
45
+ }
46
+ }
47
+ /**
48
+ * Validate the ranked vote winners, returning the first that passes both gates,
49
+ * or the provenance floor if none do. Does NOT mutate the injected set, does NOT
50
+ * write turns, does NOT emit telemetry. Non-fatal.
51
+ */
52
+ export function validateRecall(winners, opts, store) {
53
+ const floor = RECALL_MIN_COSINE();
54
+ const dedupSim = opts.dedupSim ?? 0.9;
55
+ const embedder = defaultEmbedder();
56
+ const liveVecs = (opts.liveWindow ?? []).map((m) => embedder.embed(m));
57
+ // One checkpoint read for the whole pass (both gates share it).
58
+ const cps = listCheckpoints(opts.sessionId, store.stateDir);
59
+ const cpById = new Map(cps.map((c) => [c.checkpointId, c]));
60
+ const queryVec = opts.query ? embedder.embed(opts.query) : null;
61
+ for (const cand of winners) {
62
+ try {
63
+ const cp = cpById.get(cand.checkpointId);
64
+ // Gate 1: same-repo COSINE floor. `cand.score` is only a cosine for
65
+ // source "vector"; fts5 (BM25) and recency (freshness rank) live on
66
+ // other scales, so for those we re-derive the true cosine locally from
67
+ // the query + checkpoint embedding. No search call is made.
68
+ let cosine;
69
+ if (cand.source === "vector") {
70
+ cosine = cand.score;
71
+ }
72
+ else if (queryVec && cp) {
73
+ cosine = cosineSimilarity(queryVec, embedder.embed(cp.summary));
74
+ }
75
+ else {
76
+ // No comparable cosine available => cannot clear a cosine gate.
77
+ continue;
78
+ }
79
+ if (cosine < floor)
80
+ continue;
81
+ // Gate 2: not already resident in the live window.
82
+ if (liveVecs.length > 0) {
83
+ if (!cp)
84
+ continue; // cannot verify => skip rather than risk re-inject
85
+ const hitVec = embedder.embed(cp.summary);
86
+ const resident = liveVecs.some((v) => cosineSimilarity(v, hitVec) >= dedupSim);
87
+ if (resident)
88
+ continue;
89
+ }
90
+ return { kind: "candidate", candidate: cand };
91
+ }
92
+ catch {
93
+ // Non-fatal: skip this candidate, try the next.
94
+ continue;
95
+ }
96
+ }
97
+ // All candidates rejected -> provenance floor.
98
+ return { kind: "floor", floor: buildFloorBlock(opts.sessionId, store) };
99
+ }