pi-mega-compact 0.11.5 → 0.11.7

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 (147) hide show
  1. package/dist/extensions/dashboard-server/api-contracts/cache-stripes.js +8 -0
  2. package/dist/extensions/dashboard-server/api-contracts/endpoints.js +13 -0
  3. package/dist/extensions/dashboard-server/api-contracts/memory-map.js +1 -0
  4. package/dist/extensions/dashboard-server/routes-cache.js +28 -0
  5. package/dist/extensions/dashboard-server/routes-game.js +3 -0
  6. package/dist/extensions/dashboard-server/routes-memory-map.js +50 -0
  7. package/dist/extensions/dashboard-server/routes-setup.js +105 -0
  8. package/dist/extensions/dashboard-server/routes.js +3 -1
  9. package/dist/extensions/dashboard-server/server.js +7 -1
  10. package/dist/extensions/mega-compact.js +5 -0
  11. package/dist/extensions/mega-config.js +5 -0
  12. package/dist/extensions/mega-events/context-handler.js +10 -2
  13. package/dist/extensions/mega-events/perf-handler.js +83 -1
  14. package/dist/extensions/mega-events/separated-prompt.js +248 -0
  15. package/dist/extensions/mega-runtime/env-loader.js +56 -0
  16. package/dist/extensions/mega-runtime/reset-runtime.js +1 -0
  17. package/dist/extensions/mega-runtime/runtime-snapshot.js +1 -0
  18. package/dist/extensions/mega-runtime/runtime.js +1 -0
  19. package/dist/extensions/mega-runtime/snapshot.js +1 -0
  20. package/dist/extensions/mega-runtime/widget.js +5 -0
  21. package/dist/src/cache-stripe-impl.js +288 -0
  22. package/dist/src/cache-stripe.js +11 -0
  23. package/dist/src/config/stopwords.js +24 -0
  24. package/dist/src/config.js +17 -0
  25. package/dist/src/memoryGraph.js +299 -0
  26. package/dist/src/monitoring.js +13 -0
  27. package/dist/src/queryExpansion.js +163 -0
  28. package/dist/src/queryReformulation/cache.js +123 -0
  29. package/dist/src/queryReformulation/rrf.js +29 -0
  30. package/dist/src/queryReformulation/tfidf.js +61 -0
  31. package/dist/src/queryReformulation/vagueness.js +33 -0
  32. package/dist/src/queryReformulation.js +225 -0
  33. package/dist/src/recall.js +136 -1
  34. package/dist/src/recallMetrics.js +258 -0
  35. package/dist/src/store/sqlite/cache-stripes.js +133 -0
  36. package/dist/src/store/sqlite/fts5-search.js +68 -0
  37. package/dist/src/store/sqlite/perf-samples.js +1 -0
  38. package/dist/src/store/sqlite/schema.js +60 -1
  39. package/dist/src/store/sqlite.js +1 -0
  40. package/dist/src/store/vectorIndex.js +29 -5
  41. package/dist/src/tiered-router/types.js +18 -0
  42. package/dist/src/tieredRouter.js +421 -0
  43. package/dist/src/vectorStore.js +8 -6
  44. package/extensions/dashboard-client/dist/assets/{AchievementTiles-BoL7qBOJ.js → AchievementTiles-DR9cLGDL.js} +2 -2
  45. package/extensions/dashboard-client/dist/assets/{AchievementTiles-BoL7qBOJ.js.map → AchievementTiles-DR9cLGDL.js.map} +1 -1
  46. package/extensions/dashboard-client/dist/assets/{AchievementsTab-BFDE3HYc.js → AchievementsTab-svNUgJ1e.js} +2 -2
  47. package/extensions/dashboard-client/dist/assets/{AchievementsTab-BFDE3HYc.js.map → AchievementsTab-svNUgJ1e.js.map} +1 -1
  48. package/extensions/dashboard-client/dist/assets/CacheTab-ASwhOMjR.js +2 -0
  49. package/extensions/dashboard-client/dist/assets/CacheTab-ASwhOMjR.js.map +1 -0
  50. package/extensions/dashboard-client/dist/assets/{ConfigTab-DDFE-ckA.js → ConfigTab-CmmWheuW.js} +2 -2
  51. package/extensions/dashboard-client/dist/assets/{ConfigTab-DDFE-ckA.js.map → ConfigTab-CmmWheuW.js.map} +1 -1
  52. package/extensions/dashboard-client/dist/assets/{EventsTab-B6UxZ7PM.js → EventsTab-CFE7jLsa.js} +2 -2
  53. package/extensions/dashboard-client/dist/assets/{EventsTab-B6UxZ7PM.js.map → EventsTab-CFE7jLsa.js.map} +1 -1
  54. package/extensions/dashboard-client/dist/assets/GameTab-CJAX_th_.js +2 -0
  55. package/extensions/dashboard-client/dist/assets/{GameTab-DehUX-KE.js.map → GameTab-CJAX_th_.js.map} +1 -1
  56. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-0GWRt4wn.js → MaintenanceTab-P4SUsvMf.js} +2 -2
  57. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-0GWRt4wn.js.map → MaintenanceTab-P4SUsvMf.js.map} +1 -1
  58. package/extensions/dashboard-client/dist/assets/MemoryMapTab-BBiH76eF.js +2 -0
  59. package/extensions/dashboard-client/dist/assets/MemoryMapTab-BBiH76eF.js.map +1 -0
  60. package/extensions/dashboard-client/dist/assets/{MetricsTab-C3rwMVsN.js → MetricsTab-CHQscixy.js} +2 -2
  61. package/extensions/dashboard-client/dist/assets/{MetricsTab-C3rwMVsN.js.map → MetricsTab-CHQscixy.js.map} +1 -1
  62. package/extensions/dashboard-client/dist/assets/{OverviewTab-39O9_x5j.js → OverviewTab-DBs4DJdd.js} +2 -2
  63. package/extensions/dashboard-client/dist/assets/{OverviewTab-39O9_x5j.js.map → OverviewTab-DBs4DJdd.js.map} +1 -1
  64. package/extensions/dashboard-client/dist/assets/{ReposTab-Cfj6Q5sH.js → ReposTab-DeFz76L5.js} +2 -2
  65. package/extensions/dashboard-client/dist/assets/{ReposTab-Cfj6Q5sH.js.map → ReposTab-DeFz76L5.js.map} +1 -1
  66. package/extensions/dashboard-client/dist/assets/{SessionsTab-DXDTCi3r.js → SessionsTab-BWNsj1OB.js} +2 -2
  67. package/extensions/dashboard-client/dist/assets/{SessionsTab-DXDTCi3r.js.map → SessionsTab-BWNsj1OB.js.map} +1 -1
  68. package/extensions/dashboard-client/dist/assets/SetupTab-uS6A0xmw.js +2 -0
  69. package/extensions/dashboard-client/dist/assets/SetupTab-uS6A0xmw.js.map +1 -0
  70. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-Cw1dJ4e9.js → TimeSavedCard-CiqCOQuL.js} +2 -2
  71. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-Cw1dJ4e9.js.map → TimeSavedCard-CiqCOQuL.js.map} +1 -1
  72. package/extensions/dashboard-client/dist/assets/{TopicsTab-BAw972BV.js → TopicsTab-BWWQxltv.js} +2 -2
  73. package/extensions/dashboard-client/dist/assets/{TopicsTab-BAw972BV.js.map → TopicsTab-BWWQxltv.js.map} +1 -1
  74. package/extensions/dashboard-client/dist/assets/{TurnsTab-Cf5mGIdl.js → TurnsTab-CVz4f4-o.js} +2 -2
  75. package/extensions/dashboard-client/dist/assets/{TurnsTab-Cf5mGIdl.js.map → TurnsTab-CVz4f4-o.js.map} +1 -1
  76. package/extensions/dashboard-client/dist/assets/index-CUNn22iV.css +1 -0
  77. package/extensions/dashboard-client/dist/assets/{index-4gQ7auad.js → index-DrktNOoT.js} +11 -11
  78. package/extensions/dashboard-client/dist/assets/index-DrktNOoT.js.map +1 -0
  79. package/extensions/dashboard-client/dist/assets/{useSSE-DNgMuyP6.js → useSSE-Bf5LOLSi.js} +2 -2
  80. package/extensions/dashboard-client/dist/assets/{useSSE-DNgMuyP6.js.map → useSSE-Bf5LOLSi.js.map} +1 -1
  81. package/extensions/dashboard-client/dist/index.html +2 -2
  82. package/extensions/dashboard-client/src/App.tsx +24 -8
  83. package/extensions/dashboard-client/src/api/client.ts +15 -0
  84. package/extensions/dashboard-client/src/components/CacheHitRateTrendCard.tsx +100 -0
  85. package/extensions/dashboard-client/src/components/StripeDistributionCard.tsx +110 -0
  86. package/extensions/dashboard-client/src/components/TabBar.tsx +49 -4
  87. package/extensions/dashboard-client/src/main.tsx +1 -0
  88. package/extensions/dashboard-client/src/styles/base.css +30 -0
  89. package/extensions/dashboard-client/src/styles/cache.css +167 -0
  90. package/extensions/dashboard-client/src/tabs/CacheTab.tsx +75 -13
  91. package/extensions/dashboard-client/src/tabs/MemoryMapTab.tsx +440 -0
  92. package/extensions/dashboard-client/src/tabs/SetupTab.tsx +65 -2
  93. package/extensions/dashboard-server/api-contracts/cache-stripes.ts +49 -0
  94. package/extensions/dashboard-server/api-contracts/endpoints.ts +31 -1
  95. package/extensions/dashboard-server/api-contracts/index.ts +16 -1
  96. package/extensions/dashboard-server/api-contracts/memory-map.ts +50 -0
  97. package/extensions/dashboard-server/api-contracts/setup.ts +22 -0
  98. package/extensions/dashboard-server/routes-cache.ts +36 -1
  99. package/extensions/dashboard-server/routes-game.ts +3 -0
  100. package/extensions/dashboard-server/routes-memory-map.ts +105 -0
  101. package/extensions/dashboard-server/routes-setup.ts +112 -0
  102. package/extensions/dashboard-server/routes.ts +3 -1
  103. package/extensions/dashboard-server/server.ts +6 -0
  104. package/extensions/mega-compact.ts +5 -0
  105. package/extensions/mega-config.ts +17 -0
  106. package/extensions/mega-events/context-handler.ts +10 -2
  107. package/extensions/mega-events/perf-handler.ts +111 -1
  108. package/extensions/mega-events/separated-prompt.ts +329 -0
  109. package/extensions/mega-runtime/env-loader.ts +55 -0
  110. package/extensions/mega-runtime/helpers.ts +2 -0
  111. package/extensions/mega-runtime/reset-runtime.ts +1 -0
  112. package/extensions/mega-runtime/runtime-snapshot.ts +1 -0
  113. package/extensions/mega-runtime/runtime.ts +1 -0
  114. package/extensions/mega-runtime/snapshot.ts +6 -0
  115. package/extensions/mega-runtime/widget-types.ts +3 -0
  116. package/extensions/mega-runtime/widget.ts +5 -0
  117. package/package.json +1 -1
  118. package/src/cache-stripe-impl.ts +385 -0
  119. package/src/cache-stripe.ts +18 -0
  120. package/src/config/stopwords.ts +25 -0
  121. package/src/config.ts +26 -0
  122. package/src/memoryGraph.ts +438 -0
  123. package/src/monitoring.ts +35 -0
  124. package/src/queryExpansion.ts +206 -0
  125. package/src/queryReformulation/cache.ts +169 -0
  126. package/src/queryReformulation/rrf.ts +51 -0
  127. package/src/queryReformulation/tfidf.ts +79 -0
  128. package/src/queryReformulation/vagueness.ts +38 -0
  129. package/src/queryReformulation.ts +355 -0
  130. package/src/recall.ts +168 -4
  131. package/src/recallMetrics.ts +388 -0
  132. package/src/store/sqlite/cache-stripes.ts +196 -0
  133. package/src/store/sqlite/fts5-search.ts +90 -0
  134. package/src/store/sqlite/perf-samples.ts +3 -1
  135. package/src/store/sqlite/schema.ts +60 -1
  136. package/src/store/sqlite.ts +1 -0
  137. package/src/store/vectorIndex.ts +38 -7
  138. package/src/tiered-router/types.ts +64 -0
  139. package/src/tieredRouter.ts +489 -0
  140. package/src/vectorStore.ts +9 -5
  141. package/extensions/dashboard-client/dist/assets/CacheTab-eKVc-NV1.js +0 -2
  142. package/extensions/dashboard-client/dist/assets/CacheTab-eKVc-NV1.js.map +0 -1
  143. package/extensions/dashboard-client/dist/assets/GameTab-DehUX-KE.js +0 -2
  144. package/extensions/dashboard-client/dist/assets/SetupTab-mMlfunJa.js +0 -2
  145. package/extensions/dashboard-client/dist/assets/SetupTab-mMlfunJa.js.map +0 -1
  146. package/extensions/dashboard-client/dist/assets/index-4gQ7auad.js.map +0 -1
  147. package/extensions/dashboard-client/dist/assets/index-BEdKlpAB.css +0 -1
@@ -0,0 +1,61 @@
1
+ /**
2
+ * tfidf.ts — TF-IDF term extraction from neighbor documents (S43A-6).
3
+ *
4
+ * Extracts the highest-IDF-weighted terms from a set of neighbor documents
5
+ * for query expansion.
6
+ *
7
+ * Term frequency = raw count of the term in the neighbor document (normalized
8
+ * by document length for cross-doc comparability).
9
+ * Inverse document frequency = log(N / df) where N = total docs in corpus.
10
+ *
11
+ * This is NOT a stopword list: frequent terms like "the" naturally get a low
12
+ * IDF and rank below rare terms like "jwt" even when both have similar TF.
13
+ */
14
+ /**
15
+ * Extract the top-N terms by TF-IDF weight from the given neighbor documents.
16
+ *
17
+ * Returns an empty array when:
18
+ * - neighbors list is empty
19
+ * - totalDocs <= 0
20
+ * - no terms survive filtering (all numeric, all single-char, etc.)
21
+ */
22
+ export function extractExpansionTerms(neighbors, corpus, topTerms) {
23
+ if (neighbors.length === 0)
24
+ return [];
25
+ const { totalDocs, docFreq } = corpus;
26
+ if (totalDocs <= 0)
27
+ return [];
28
+ // Aggregate term frequency across all neighbor documents
29
+ const termTf = new Map();
30
+ for (const neighbor of neighbors) {
31
+ const words = neighbor.text.toLowerCase().split(/\W+/).filter(Boolean);
32
+ if (words.length === 0)
33
+ continue;
34
+ // Normalize TF by document length so longer docs don't dominate
35
+ const lenNorm = words.length;
36
+ for (const word of words) {
37
+ // Skip pure number tokens (short numbers)
38
+ if (/^\d+$/.test(word) && word.length <= 4)
39
+ continue;
40
+ // Skip single characters
41
+ if (word.length < 2)
42
+ continue;
43
+ // Accumulate across neighbors (multiple docs amplify a term's importance)
44
+ termTf.set(word, (termTf.get(word) ?? 0) + (1 / lenNorm));
45
+ }
46
+ }
47
+ // Compute TF-IDF for each term
48
+ const scored = [];
49
+ for (const [term, tf] of termTf) {
50
+ const df = docFreq(term);
51
+ // IDF = ln(1 + (N - df + 0.5) / (df + 0.5)) — smooth version
52
+ const idf = Math.log(1 + (totalDocs - df + 0.5) / (df + 0.5));
53
+ const tfIdf = tf * idf;
54
+ if (tfIdf > 0) {
55
+ scored.push({ term, tfIdf, df });
56
+ }
57
+ }
58
+ // Sort by TF-IDF descending, take top N
59
+ scored.sort((a, b) => b.tfIdf - a.tfIdf);
60
+ return scored.slice(0, topTerms);
61
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * vagueness.ts — heuristic vagueness detection for S43 query reformulation.
3
+ *
4
+ * Detects whether a query is "vague" enough to benefit from reformulation.
5
+ */
6
+ /**
7
+ * Heuristic: is this query "vague" enough to benefit from reformulation?
8
+ * Returns true if the query is short, question-like, or lacks specific terms.
9
+ *
10
+ * ANY match -> vague:
11
+ * a) Total words <= `vagueMinWords` (e.g. "what about auth")
12
+ * b) Contains a question word AND total words <= `vagueVeryShortWords`
13
+ *
14
+ * NOTE: Misclassification is low-cost: a specific query that's wrongly expanded
15
+ * just gets a slightly broader search; a vague query that's wrongly skipped
16
+ * just gets the raw-query search (today's behavior).
17
+ */
18
+ export function isVagueQuery(query, opts) {
19
+ const cleaned = query.replace(/[^\w\s]/g, "").trim();
20
+ if (!cleaned)
21
+ return true; // empty or punctuation-only query is vague
22
+ const words = cleaned.split(/\s+/).filter(Boolean);
23
+ const wordCount = words.length;
24
+ // Rule a: very short query
25
+ if (wordCount <= opts.vagueMinWords)
26
+ return true;
27
+ // Rule b: contains a question word AND is short-ish
28
+ const questionWords = /^(what|why|how|when|where|who|which|does|did|is|are|was|were|can|could|would|should)\b/i;
29
+ const hasQuestionWord = words.some((w) => questionWords.test(w));
30
+ if (hasQuestionWord && wordCount <= opts.vagueVeryShortWords)
31
+ return true;
32
+ return false;
33
+ }
@@ -0,0 +1,225 @@
1
+ /**
2
+ * queryReformulation.ts — fully local, zero-LLM query reformulation for vague
3
+ * recall queries (S43).
4
+ *
5
+ * Shell: delegates TF-IDF extraction to queryReformulation/tfidf.ts and
6
+ * vagueness detection to queryReformulation/vagueness.ts. Orchestrates the
7
+ * pipeline here.
8
+ *
9
+ * Pipeline:
10
+ * 1. Embed the raw query via the project's default TrigramEmbedder.
11
+ * 2. Linear-scan the real `context_chunks` store for top-N cosine neighbors.
12
+ * 3. Extract high-IDF terms from those neighbors (real TF-IDF, no stopword
13
+ * list — high-frequency terms naturally get low IDF).
14
+ * 4. Expand the query with the top-IDF terms.
15
+ * 5. Re-embed the expanded query and fuse both ranked lists via RRF.
16
+ *
17
+ * Pi-agnostic: no pi runtime types. Pure src/ module.
18
+ */
19
+ import { isVagueQuery } from "./queryReformulation/vagueness.js";
20
+ import { extractExpansionTerms } from "./queryReformulation/tfidf.js";
21
+ import { reciprocalRankFusion } from "./queryReformulation/rrf.js";
22
+ import { cacheGet, cacheSet, maybeLogCacheStats, computeUncalibrated, QUERY_REFORM_CACHE_TTL_SECONDS, EXPANSION_NEIGHBOR_COUNT, EXPANSION_TOP_TERMS, VAGUE_MIN_WORDS, VAGUE_VERY_SHORT_WORDS, RRF_K, } from "./queryReformulation/cache.js";
23
+ export { isVagueQuery } from "./queryReformulation/vagueness.js";
24
+ export { extractExpansionTerms } from "./queryReformulation/tfidf.js";
25
+ export { reciprocalRankFusion } from "./queryReformulation/rrf.js";
26
+ export { readCacheStats } from "./queryReformulation/cache.js";
27
+ // ---------------------------------------------------------------------------
28
+ // Embedding Neighbor Finder (S43A-5)
29
+ // ---------------------------------------------------------------------------
30
+ /**
31
+ * Find the top-N nearest neighbor chunks by real cosine similarity over the
32
+ * real `context_chunks` store. Uses the provided embedder + scan function.
33
+ */
34
+ export function findExpansionNeighbors(query, embedder, scan, neighborCount) {
35
+ const embedding = embedder.embed(query);
36
+ if (embedding.length === 0)
37
+ return [];
38
+ return scan(embedding, neighborCount);
39
+ }
40
+ // ---------------------------------------------------------------------------
41
+ // Build Expanded Query
42
+ // ---------------------------------------------------------------------------
43
+ /**
44
+ * Build an expanded query by appending the top IDF-weighted terms from the
45
+ * expansion neighbors to the original query. Simple concatenation: the
46
+ * expanded string is `"originalQuery topTerm1 topTerm2 ..."`.
47
+ */
48
+ export function buildExpandedQuery(original, terms, maxTerms = EXPANSION_TOP_TERMS) {
49
+ if (terms.length === 0)
50
+ return original;
51
+ const extra = terms.slice(0, maxTerms).map((t) => t.term).join(" ");
52
+ return `${original} ${extra}`;
53
+ }
54
+ // ---------------------------------------------------------------------------
55
+ // Public API: reformulateQuery (S43A-9)
56
+ // ---------------------------------------------------------------------------
57
+ /**
58
+ * Reformulate a query using the fully local pipeline:
59
+ * 1. Check cache (TTL-gated)
60
+ * 2. Check vagueness — skip if not vague
61
+ * 3. Find embedding neighbors
62
+ * 4. Extract TF-IDF terms from neighbor texts
63
+ * 5. Build expanded query
64
+ * 6. Optionally re-embed and search (caller handles RRF fusion)
65
+ *
66
+ * Error contract:
67
+ * - If the embedder throws OR the scan fails: the error propagates to the
68
+ * caller (NOT caught here). The caller is responsible for the
69
+ * `query_reformulation_failed` event + fallback to raw query.
70
+ * - If the corpus is empty: returns raw query with rrfApplied: false and
71
+ * skipReason: "empty_corpus".
72
+ * - If the corpus is too thin (< 2 neighbors): returns raw query with
73
+ * rrfApplied: false and skipReason: "thin_corpus".
74
+ * - If the query is not vague: returns raw query with rrfApplied: false and
75
+ * skipReason: "not_vague".
76
+ */
77
+ export function reformulateQuery(query, embedder, scan, corpus, neighborTexts, opts = {}, log) {
78
+ const config = {
79
+ neighborCount: opts.neighborCount ?? EXPANSION_NEIGHBOR_COUNT,
80
+ topTerms: opts.topTerms ?? EXPANSION_TOP_TERMS,
81
+ vagueMinWords: opts.vagueMinWords ?? VAGUE_MIN_WORDS,
82
+ vagueVeryShortWords: opts.vagueVeryShortWords ?? VAGUE_VERY_SHORT_WORDS,
83
+ cacheTtlSeconds: opts.cacheTtlSeconds ?? QUERY_REFORM_CACHE_TTL_SECONDS,
84
+ rrfK: opts.rrfK ?? RRF_K,
85
+ searchLimit: opts.searchLimit ?? 5,
86
+ };
87
+ const ttlMs = config.cacheTtlSeconds * 1000;
88
+ // 0. Check cache
89
+ const cached = cacheGet(query, ttlMs);
90
+ if (cached) {
91
+ maybeLogCacheStats(log);
92
+ return {
93
+ result: cached,
94
+ rawNeighbors: cached.neighbors,
95
+ rawTerms: cached.neighbors.map((n) => ({ id: n.id, text: "" })),
96
+ };
97
+ }
98
+ // 1. Vagueness check
99
+ if (!isVagueQuery(query, { vagueMinWords: config.vagueMinWords, vagueVeryShortWords: config.vagueVeryShortWords })) {
100
+ const result = {
101
+ expanded: query,
102
+ original: query,
103
+ neighbors: [],
104
+ terms: [],
105
+ rrfApplied: false,
106
+ fromCache: false,
107
+ uncalibrated: computeUncalibrated(config),
108
+ skipReason: "not_vague",
109
+ };
110
+ cacheSet(query, result);
111
+ maybeLogCacheStats(log);
112
+ log?.info("query_reformulation_skipped", { query: query.slice(0, 80), reason: "not_vague" });
113
+ return { result, rawNeighbors: [], rawTerms: [] };
114
+ }
115
+ // 2. Corpus check
116
+ if (corpus.totalDocs <= 0) {
117
+ const result = {
118
+ expanded: query,
119
+ original: query,
120
+ neighbors: [],
121
+ terms: [],
122
+ rrfApplied: false,
123
+ fromCache: false,
124
+ uncalibrated: computeUncalibrated(config),
125
+ skipReason: "empty_corpus",
126
+ };
127
+ cacheSet(query, result);
128
+ maybeLogCacheStats(log);
129
+ log?.info("query_reformulation_skipped", { query: query.slice(0, 80), reason: "empty_corpus" });
130
+ return { result, rawNeighbors: [], rawTerms: [] };
131
+ }
132
+ // 3. Find embedding neighbors
133
+ const neighbors = findExpansionNeighbors(query, embedder, scan, config.neighborCount);
134
+ if (neighbors.length < 2) {
135
+ const result = {
136
+ expanded: query,
137
+ original: query,
138
+ neighbors,
139
+ terms: [],
140
+ rrfApplied: false,
141
+ fromCache: false,
142
+ uncalibrated: computeUncalibrated(config),
143
+ skipReason: "thin_corpus",
144
+ };
145
+ cacheSet(query, result);
146
+ maybeLogCacheStats(log);
147
+ log?.info("query_reformulation_skipped", { query: query.slice(0, 80), reason: "thin_corpus" });
148
+ return { result, rawNeighbors: neighbors, rawTerms: [] };
149
+ }
150
+ // 4. Fetch neighbor texts for TF-IDF
151
+ const neighborIds = neighbors.map((n) => n.id);
152
+ const rawTerms = neighborTexts(neighborIds);
153
+ // 5. Extract expansion terms via TF-IDF
154
+ const expansionTerms = extractExpansionTerms(rawTerms, corpus, config.topTerms);
155
+ if (expansionTerms.length === 0) {
156
+ const result = {
157
+ expanded: query,
158
+ original: query,
159
+ neighbors,
160
+ terms: [],
161
+ rrfApplied: false,
162
+ fromCache: false,
163
+ uncalibrated: computeUncalibrated(config),
164
+ skipReason: "thin_corpus",
165
+ };
166
+ cacheSet(query, result);
167
+ maybeLogCacheStats(log);
168
+ log?.info("query_reformulation_skipped", { query: query.slice(0, 80), reason: "thin_corpus" });
169
+ return { result, rawNeighbors: neighbors, rawTerms };
170
+ }
171
+ // 6. Build expanded query
172
+ const expanded = buildExpandedQuery(query, expansionTerms, config.topTerms);
173
+ const uncalibrated = computeUncalibrated(config);
174
+ const result = {
175
+ expanded,
176
+ original: query,
177
+ neighbors: neighbors.map((n) => ({ id: n.id, score: n.score })),
178
+ terms: expansionTerms,
179
+ rrfApplied: true,
180
+ fromCache: false,
181
+ uncalibrated,
182
+ };
183
+ cacheSet(query, result);
184
+ maybeLogCacheStats(log);
185
+ log?.info("query_reformulation", {
186
+ query: query.slice(0, 80),
187
+ expanded: expanded.slice(0, 120),
188
+ neighborCount: neighbors.length,
189
+ topTerms: expansionTerms.slice(0, 5).map((t) => t.term),
190
+ rrfApplied: true,
191
+ fromCache: false,
192
+ uncalibrated,
193
+ });
194
+ return { result, rawNeighbors: neighbors, rawTerms };
195
+ }
196
+ /**
197
+ * Full reformulation search pipeline:
198
+ * 1. Reformulate the query (embedding neighbors -> TF-IDF -> expansion).
199
+ * 2. If RRF was applied: run BOTH raw + expanded queries and fuse via RRF.
200
+ * 3. If no RRF: return raw-query results only.
201
+ */
202
+ export function reformulationSearch(query, embedder, scan, corpus, neighborTexts, search, opts = {}, log) {
203
+ const config = {
204
+ neighborCount: opts.neighborCount ?? EXPANSION_NEIGHBOR_COUNT,
205
+ topTerms: opts.topTerms ?? EXPANSION_TOP_TERMS,
206
+ vagueMinWords: opts.vagueMinWords ?? VAGUE_MIN_WORDS,
207
+ vagueVeryShortWords: opts.vagueVeryShortWords ?? VAGUE_VERY_SHORT_WORDS,
208
+ cacheTtlSeconds: opts.cacheTtlSeconds ?? QUERY_REFORM_CACHE_TTL_SECONDS,
209
+ rrfK: opts.rrfK ?? RRF_K,
210
+ searchLimit: opts.searchLimit ?? 5,
211
+ };
212
+ const { result: reformulation } = reformulateQuery(query, embedder, scan, corpus, neighborTexts, opts, log);
213
+ // Always run the raw query search (needed for the S41 quality gate and as
214
+ // a fallback when RRF is not applied).
215
+ const rawSearchResults = search(query, config.searchLimit);
216
+ if (!reformulation.rrfApplied) {
217
+ return { fused: rawSearchResults, reformulation, rawSearchResults };
218
+ }
219
+ // RRF path: run expanded query search and fuse
220
+ const expandedResults = search(reformulation.expanded, config.searchLimit);
221
+ const rawRanked = rawSearchResults.map((r, i) => ({ id: r.id, rank: i + 1 }));
222
+ const expandedRanked = expandedResults.map((r, i) => ({ id: r.id, rank: i + 1 }));
223
+ const fused = reciprocalRankFusion([rawRanked, expandedRanked], config.rrfK);
224
+ return { fused, reformulation, rawSearchResults };
225
+ }
@@ -20,6 +20,19 @@ import { defaultEmbedder, cosineSimilarity } from "./embedder.js";
20
20
  import { rehydrateRaptorTree, isShadowMode } from "./dedup/raptor/index.js";
21
21
  import { maxCheckpointTimestamp } from "./store/sqlite.js";
22
22
  import { normalizeSessionId } from "./store.js";
23
+ // ---------------------------------------------------------------------------
24
+ // S57 RAG suite feature flags + module imports. Each flag defaults OFF — the
25
+ // flag-OFF path below is byte-identical to the pre-S57 recall path (recallQuery
26
+ // === opts.query, the single searchRecall call), so the helpers are only reached
27
+ // when their flag is ON. Wiring is additive; the proven v0.11.5 behavior is the
28
+ // default.
29
+ // ---------------------------------------------------------------------------
30
+ import { RAG_QUERY_REFORMULATION, RAG_TIERED_ROUTER, RAG_RECALL_METRICS } from "./config.js";
31
+ import { reformulateQuery, isVagueQuery } from "./queryReformulation.js";
32
+ import { VAGUE_MIN_WORDS, VAGUE_VERY_SHORT_WORDS } from "./queryReformulation/cache.js";
33
+ import { getTieredRouter } from "./tieredRouter.js";
34
+ import { computeRecallMetrics } from "./recallMetrics.js";
35
+ import { Logger } from "./log.js";
23
36
  /** Wrap a recall block so the model reads it as restored compacted context. */
24
37
  export function formatRecallBlock(hits) {
25
38
  if (hits.length === 0)
@@ -72,6 +85,107 @@ export function formatRaptorBlock(nodes) {
72
85
  "session so far. Use it as a map of what has been covered:\n\n" +
73
86
  parts.join("\n"));
74
87
  }
88
+ // ---------------------------------------------------------------------------
89
+ // S57 RAG suite helpers (B1/B2/B3). Each is only called when its feature flag
90
+ // is ON; flag-OFF never reaches them. All degrade non-fatally to the standard
91
+ // path on any error.
92
+ // ---------------------------------------------------------------------------
93
+ /**
94
+ * B1: If the query is vague, reformulate it via embedding-neighbor TF-IDF
95
+ * expansion. Returns the original query when reformulation is not supported
96
+ * or the query is already specific. Non-fatal: any error → original query.
97
+ */
98
+ function reformulateRecallQuery(query, store, sessionId) {
99
+ try {
100
+ if (!isVagueQuery(query, {
101
+ vagueMinWords: VAGUE_MIN_WORDS,
102
+ vagueVeryShortWords: VAGUE_VERY_SHORT_WORDS,
103
+ }))
104
+ return query;
105
+ // Pre-compute neighbor candidates once. reformulateQuery embeds the query
106
+ // and calls `scan` internally; we return these pre-computed neighbors (same
107
+ // query) so the store needs no by-embedding lookup.
108
+ const { hits } = searchRecall({ sessionId, query, limit: 10, skipInjected: false }, store);
109
+ if (hits.length < 2)
110
+ return query; // too few neighbors for TF-IDF
111
+ const neighbors = hits.map((h) => ({
112
+ id: h.checkpoint.checkpointId,
113
+ score: h.score,
114
+ }));
115
+ const textById = new Map();
116
+ for (const h of hits)
117
+ textById.set(h.checkpoint.checkpointId, h.checkpoint.summary);
118
+ const scan = () => neighbors;
119
+ const corpus = {
120
+ totalDocs: neighbors.length,
121
+ docFreq: (term) => {
122
+ let df = 0;
123
+ for (const text of textById.values()) {
124
+ if (text.toLowerCase().includes(term.toLowerCase()))
125
+ df++;
126
+ }
127
+ return Math.max(df, 1);
128
+ },
129
+ };
130
+ const neighborTexts = (ids) => ids.map((id) => ({ id, text: textById.get(id) ?? "" }));
131
+ const { result } = reformulateQuery(query, defaultEmbedder(), scan, corpus, neighborTexts);
132
+ return result.expanded.length > query.length ? result.expanded : query;
133
+ }
134
+ catch {
135
+ return query; // non-fatal: fall back to original query
136
+ }
137
+ }
138
+ /**
139
+ * B2: Synchronous tiered recall. The TieredRouter.route() is async, so the
140
+ * sync path can only peek the L0 in-memory cache; on miss it falls through to
141
+ * the standard sync vector scan. The router's L1/L2 value is realized on the
142
+ * async path (recallAndInlineAsync). Non-fatal.
143
+ */
144
+ function runTieredRecall(query, sessionId, limit, skip, store) {
145
+ try {
146
+ const router = getTieredRouter();
147
+ if (!router) {
148
+ const result = searchRecall({ sessionId, query, limit, skipInjected: skip }, store);
149
+ return { newHits: result.newHits, tier: "off" };
150
+ }
151
+ // Peek the L0 in-memory cache synchronously; fall through on miss.
152
+ const cached = router.peekCache(sessionId, query, limit);
153
+ if (cached && cached.length > 0)
154
+ return { newHits: cached, tier: "L0-cache" };
155
+ const result = searchRecall({ sessionId, query, limit, skipInjected: skip }, store);
156
+ return { newHits: result.newHits, tier: "sync-fallback" };
157
+ }
158
+ catch {
159
+ const result = searchRecall({ sessionId, query, limit, skipInjected: skip }, store);
160
+ return { newHits: result.newHits, tier: "fallback-error" };
161
+ }
162
+ }
163
+ /**
164
+ * B3: Compute recall-quality metrics on the injected hits and log them.
165
+ * Only called when RAG_RECALL_METRICS() is ON. Non-fatal.
166
+ */
167
+ function scoreAndLogRecallMetrics(query, toInject) {
168
+ try {
169
+ const logger = new Logger();
170
+ const metrics = computeRecallMetrics(query, toInject);
171
+ logger.info("recall_metrics", {
172
+ hitCount: toInject.length,
173
+ score: metrics.score,
174
+ pass: metrics.pass,
175
+ });
176
+ if (!metrics.pass && toInject.length > 0) {
177
+ logger.info("recall_metrics_low_quality", {
178
+ score: metrics.score,
179
+ relevance: metrics.breakdown.relevance,
180
+ coverage: metrics.breakdown.coverage,
181
+ diversity: metrics.breakdown.diversity,
182
+ });
183
+ }
184
+ }
185
+ catch {
186
+ /* non-fatal: metrics never break recall */
187
+ }
188
+ }
75
189
  /**
76
190
  * Run the unified recall+dudupe+prepare-inject pipeline. Does NOT touch pi;
77
191
  * it records injections via `markInjected` so the next call dedupes. The
@@ -123,7 +237,22 @@ export function recallAndInline(opts, store) {
123
237
  // F4: thread skipInjected through to searchRecall instead of hardcoding false
124
238
  // and re-implementing the filter here. newHits is already deduped when skip
125
239
  // is true (default); equals hits when skip is false (openclaw command path).
126
- const { newHits } = searchRecall({ sessionId: opts.sessionId, query: opts.query, limit, skipInjected: skip }, store);
240
+ //
241
+ // S57 B1: optionally expand a vague query via TF-IDF neighbor terms.
242
+ // S57 B2: optionally route via the TieredRouter's sync L0 cache peek.
243
+ // Both flags default OFF — recallQuery === opts.query and the single
244
+ // searchRecall call reproduce the pre-S57 byte-identical path.
245
+ const recallQuery = RAG_QUERY_REFORMULATION()
246
+ ? reformulateRecallQuery(opts.query, store, opts.sessionId)
247
+ : opts.query;
248
+ let newHits;
249
+ if (RAG_TIERED_ROUTER()) {
250
+ newHits = runTieredRecall(recallQuery, opts.sessionId, limit, skip, store).newHits;
251
+ }
252
+ else {
253
+ const result = searchRecall({ sessionId: opts.sessionId, query: recallQuery, limit, skipInjected: skip }, store);
254
+ newHits = result.newHits;
255
+ }
127
256
  // F1: hoist one embedder instance for inline dedupe (matches the async path).
128
257
  // defaultEmbedder() is deterministic but creating it per hit wastes allocations.
129
258
  const embedder = defaultEmbedder();
@@ -154,6 +283,12 @@ export function recallAndInline(opts, store) {
154
283
  blockTokens += partTokens;
155
284
  vectorMarkInjected(store, opts.sessionId, h.checkpoint.checkpointId);
156
285
  }
286
+ // S57 B3: optionally score + log recall quality metrics (flag-OFF: skipped,
287
+ // byte-identical). Scores the injected hits against the ORIGINAL query so the
288
+ // metric measures whether the (possibly expanded) search results stay
289
+ // relevant to what the user actually asked.
290
+ if (RAG_RECALL_METRICS())
291
+ scoreAndLogRecallMetrics(opts.query, toInject);
157
292
  // F3: format once — one preamble, correct [1..n] numbering.
158
293
  const recallBlock = toInject.length > 0 ? formatRecallBlock(toInject) : "";
159
294
  const report = toInject.map((h) => ` • ${h.checkpoint.checkpointId} (${h.checkpoint.summary.slice(0, 60).replace(/\n/g, " ")}…)`);