neuralbrain 0.0.1 → 0.1.0

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 (226) hide show
  1. package/.env.example +2 -2
  2. package/README.md +19 -4
  3. package/dist/ai/chat.d.ts +1 -2
  4. package/dist/ai/chat.d.ts.map +1 -1
  5. package/dist/ai/chat.js +1 -2
  6. package/dist/ai/chat.js.map +1 -1
  7. package/dist/ai/config.d.ts +1 -1
  8. package/dist/ai/config.js +2 -2
  9. package/dist/ai/config.js.map +1 -1
  10. package/dist/app.d.ts +1 -0
  11. package/dist/app.d.ts.map +1 -1
  12. package/dist/app.js +417 -50
  13. package/dist/app.js.map +1 -1
  14. package/dist/cli.d.ts +53 -2
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +437 -37
  17. package/dist/cli.js.map +1 -1
  18. package/dist/consolidation/candidates.d.ts.map +1 -1
  19. package/dist/consolidation/candidates.js +19 -4
  20. package/dist/consolidation/candidates.js.map +1 -1
  21. package/dist/consolidation/fixtures.js +1 -1
  22. package/dist/consolidation/fixtures.js.map +1 -1
  23. package/dist/consolidation/gate.d.ts.map +1 -1
  24. package/dist/consolidation/gate.js +145 -109
  25. package/dist/consolidation/gate.js.map +1 -1
  26. package/dist/consolidation/runner.d.ts +6 -0
  27. package/dist/consolidation/runner.d.ts.map +1 -1
  28. package/dist/consolidation/runner.js +22 -2
  29. package/dist/consolidation/runner.js.map +1 -1
  30. package/dist/dashboard/clientScript.d.ts +1 -1
  31. package/dist/dashboard/clientScript.d.ts.map +1 -1
  32. package/dist/dashboard/clientScript.js +3774 -905
  33. package/dist/dashboard/clientScript.js.map +1 -1
  34. package/dist/dashboard/html.d.ts.map +1 -1
  35. package/dist/dashboard/html.js +605 -101
  36. package/dist/dashboard/html.js.map +1 -1
  37. package/dist/dashboard/styles.d.ts +1 -1
  38. package/dist/dashboard/styles.d.ts.map +1 -1
  39. package/dist/dashboard/styles.js +1591 -359
  40. package/dist/dashboard/styles.js.map +1 -1
  41. package/dist/learning/embedWorker.d.ts +13 -0
  42. package/dist/learning/embedWorker.d.ts.map +1 -1
  43. package/dist/learning/embedWorker.js +329 -59
  44. package/dist/learning/embedWorker.js.map +1 -1
  45. package/dist/learning/embedding.d.ts +1 -0
  46. package/dist/learning/embedding.d.ts.map +1 -1
  47. package/dist/learning/embedding.js +101 -26
  48. package/dist/learning/embedding.js.map +1 -1
  49. package/dist/learning/engine.js +1 -1
  50. package/dist/learning/engine.js.map +1 -1
  51. package/dist/learning/search.d.ts +17 -1
  52. package/dist/learning/search.d.ts.map +1 -1
  53. package/dist/learning/search.js +2094 -354
  54. package/dist/learning/search.js.map +1 -1
  55. package/dist/learning/storeMeta.d.ts +9 -0
  56. package/dist/learning/storeMeta.d.ts.map +1 -1
  57. package/dist/learning/storeMeta.js +30 -24
  58. package/dist/learning/storeMeta.js.map +1 -1
  59. package/dist/learning/types.d.ts +57 -8
  60. package/dist/learning/types.d.ts.map +1 -1
  61. package/dist/lib/condenser.d.ts +112 -0
  62. package/dist/lib/condenser.d.ts.map +1 -0
  63. package/dist/lib/condenser.js +1337 -0
  64. package/dist/lib/condenser.js.map +1 -0
  65. package/dist/lib/db.d.ts +10 -0
  66. package/dist/lib/db.d.ts.map +1 -1
  67. package/dist/lib/db.js +654 -167
  68. package/dist/lib/db.js.map +1 -1
  69. package/dist/lib/logger.d.ts.map +1 -1
  70. package/dist/lib/logger.js +3 -2
  71. package/dist/lib/logger.js.map +1 -1
  72. package/dist/lib/projectSlug.d.ts +12 -5
  73. package/dist/lib/projectSlug.d.ts.map +1 -1
  74. package/dist/lib/projectSlug.js +62 -23
  75. package/dist/lib/projectSlug.js.map +1 -1
  76. package/dist/lib/recurrence.d.ts +16 -0
  77. package/dist/lib/recurrence.d.ts.map +1 -0
  78. package/dist/lib/recurrence.js +293 -0
  79. package/dist/lib/recurrence.js.map +1 -0
  80. package/dist/lib/scope.d.ts +36 -1
  81. package/dist/lib/scope.d.ts.map +1 -1
  82. package/dist/lib/scope.js +183 -19
  83. package/dist/lib/scope.js.map +1 -1
  84. package/dist/lib/signalTags.d.ts +39 -0
  85. package/dist/lib/signalTags.d.ts.map +1 -0
  86. package/dist/lib/signalTags.js +203 -0
  87. package/dist/lib/signalTags.js.map +1 -0
  88. package/dist/lib/spool.d.ts +2 -0
  89. package/dist/lib/spool.d.ts.map +1 -1
  90. package/dist/lib/spool.js +176 -65
  91. package/dist/lib/spool.js.map +1 -1
  92. package/dist/lib/storeDiagnostics.d.ts +41 -0
  93. package/dist/lib/storeDiagnostics.d.ts.map +1 -0
  94. package/dist/lib/storeDiagnostics.js +148 -0
  95. package/dist/lib/storeDiagnostics.js.map +1 -0
  96. package/dist/lib/temporal.d.ts +44 -0
  97. package/dist/lib/temporal.d.ts.map +1 -0
  98. package/dist/lib/temporal.js +1063 -0
  99. package/dist/lib/temporal.js.map +1 -0
  100. package/dist/mcp/server.d.ts +93 -3
  101. package/dist/mcp/server.d.ts.map +1 -1
  102. package/dist/mcp/server.js +499 -68
  103. package/dist/mcp/server.js.map +1 -1
  104. package/dist/memory/actionStore.d.ts +94 -3
  105. package/dist/memory/actionStore.d.ts.map +1 -1
  106. package/dist/memory/actionStore.js +412 -124
  107. package/dist/memory/actionStore.js.map +1 -1
  108. package/dist/memory/deadLetterStore.d.ts.map +1 -1
  109. package/dist/memory/deadLetterStore.js +4 -2
  110. package/dist/memory/deadLetterStore.js.map +1 -1
  111. package/dist/memory/embedQueueStore.d.ts +19 -8
  112. package/dist/memory/embedQueueStore.d.ts.map +1 -1
  113. package/dist/memory/embedQueueStore.js +55 -25
  114. package/dist/memory/embedQueueStore.js.map +1 -1
  115. package/dist/memory/failurePatternStore.d.ts +17 -1
  116. package/dist/memory/failurePatternStore.d.ts.map +1 -1
  117. package/dist/memory/failurePatternStore.js +54 -31
  118. package/dist/memory/failurePatternStore.js.map +1 -1
  119. package/dist/memory/graphStore.d.ts +133 -3
  120. package/dist/memory/graphStore.d.ts.map +1 -1
  121. package/dist/memory/graphStore.js +980 -155
  122. package/dist/memory/graphStore.js.map +1 -1
  123. package/dist/memory/noteStore.d.ts +27 -2
  124. package/dist/memory/noteStore.d.ts.map +1 -1
  125. package/dist/memory/noteStore.js +89 -26
  126. package/dist/memory/noteStore.js.map +1 -1
  127. package/dist/memory/observationStore.d.ts +11 -1
  128. package/dist/memory/observationStore.d.ts.map +1 -1
  129. package/dist/memory/observationStore.js +90 -15
  130. package/dist/memory/observationStore.js.map +1 -1
  131. package/dist/memory/projectRename.d.ts.map +1 -1
  132. package/dist/memory/projectRename.js +5 -1
  133. package/dist/memory/projectRename.js.map +1 -1
  134. package/dist/memory/rollupSweeper.d.ts.map +1 -1
  135. package/dist/memory/rollupSweeper.js +43 -23
  136. package/dist/memory/rollupSweeper.js.map +1 -1
  137. package/dist/memory/sessionStore.d.ts +25 -7
  138. package/dist/memory/sessionStore.d.ts.map +1 -1
  139. package/dist/memory/sessionStore.js +145 -33
  140. package/dist/memory/sessionStore.js.map +1 -1
  141. package/dist/memory/trajectoryStore.d.ts +8 -0
  142. package/dist/memory/trajectoryStore.d.ts.map +1 -1
  143. package/dist/memory/trajectoryStore.js +196 -130
  144. package/dist/memory/trajectoryStore.js.map +1 -1
  145. package/dist/middleware/rateLimiter.d.ts.map +1 -1
  146. package/dist/middleware/rateLimiter.js +24 -1
  147. package/dist/middleware/rateLimiter.js.map +1 -1
  148. package/dist/routes/dashboard.d.ts.map +1 -1
  149. package/dist/routes/dashboard.js +181 -8
  150. package/dist/routes/dashboard.js.map +1 -1
  151. package/dist/routes/mcp.d.ts.map +1 -1
  152. package/dist/routes/mcp.js +173 -21
  153. package/dist/routes/mcp.js.map +1 -1
  154. package/dist/routes/memories.js +9 -1
  155. package/dist/routes/memories.js.map +1 -1
  156. package/dist/scripts/doctor.d.ts +26 -2
  157. package/dist/scripts/doctor.d.ts.map +1 -1
  158. package/dist/scripts/doctor.js +371 -259
  159. package/dist/scripts/doctor.js.map +1 -1
  160. package/dist/scripts/installAgent.d.ts.map +1 -1
  161. package/dist/scripts/installAgent.js +101 -19
  162. package/dist/scripts/installAgent.js.map +1 -1
  163. package/dist/scripts/migrateAgentMemory.js +2 -2
  164. package/dist/scripts/smokeTest.js +1 -1
  165. package/dist/scripts/smokeTest.js.map +1 -1
  166. package/docker-compose.yml +1 -1
  167. package/npm-shrinkwrap.json +2 -2
  168. package/package.json +3 -2
  169. package/plugin/hooks/postToolUse.js +155 -50
  170. package/plugin/hooks/sessionStart.js +179 -27
  171. package/plugin/hooks/sessionStop.js +152 -37
  172. package/plugin/plugin.json +1 -1
  173. package/plugin/rules/AGENTS.md +10 -8
  174. package/plugin/skills/brain-memory/REFERENCE.md +15 -14
  175. package/plugin/skills/brain-memory/SKILL.md +2 -2
  176. package/plugin/skills/digest/SKILL.md +1 -1
  177. package/plugin/skills/handoff/SKILL.md +1 -1
  178. package/plugin/skills/save/SKILL.md +2 -2
  179. package/plugin/skills/search/SKILL.md +2 -2
  180. package/src/ai/chat.ts +1 -2
  181. package/src/ai/config.ts +2 -2
  182. package/src/app.ts +475 -54
  183. package/src/cli.ts +500 -38
  184. package/src/consolidation/candidates.ts +22 -4
  185. package/src/consolidation/fixtures.ts +1 -1
  186. package/src/consolidation/gate.ts +177 -140
  187. package/src/consolidation/runner.ts +26 -2
  188. package/src/dashboard/clientScript.ts +3774 -905
  189. package/src/dashboard/html.ts +605 -101
  190. package/src/dashboard/styles.ts +1591 -359
  191. package/src/learning/embedWorker.ts +350 -70
  192. package/src/learning/embedding.ts +141 -28
  193. package/src/learning/engine.ts +1 -1
  194. package/src/learning/search.ts +2533 -397
  195. package/src/learning/storeMeta.ts +36 -29
  196. package/src/learning/types.ts +66 -8
  197. package/src/lib/condenser.ts +1515 -0
  198. package/src/lib/db.ts +690 -171
  199. package/src/lib/logger.ts +4 -2
  200. package/src/lib/projectSlug.ts +77 -23
  201. package/src/lib/recurrence.ts +382 -0
  202. package/src/lib/scope.ts +220 -22
  203. package/src/lib/signalTags.ts +257 -0
  204. package/src/lib/spool.ts +181 -71
  205. package/src/lib/storeDiagnostics.ts +181 -0
  206. package/src/lib/temporal.ts +1250 -0
  207. package/src/mcp/server.ts +559 -88
  208. package/src/memory/actionStore.ts +642 -171
  209. package/src/memory/deadLetterStore.ts +4 -2
  210. package/src/memory/embedQueueStore.ts +63 -27
  211. package/src/memory/failurePatternStore.ts +84 -31
  212. package/src/memory/graphStore.ts +1396 -215
  213. package/src/memory/noteStore.ts +151 -30
  214. package/src/memory/observationStore.ts +117 -17
  215. package/src/memory/projectRename.ts +6 -2
  216. package/src/memory/rollupSweeper.ts +46 -23
  217. package/src/memory/sessionStore.ts +197 -38
  218. package/src/memory/trajectoryStore.ts +260 -140
  219. package/src/middleware/rateLimiter.ts +24 -1
  220. package/src/routes/dashboard.ts +194 -9
  221. package/src/routes/mcp.ts +185 -26
  222. package/src/routes/memories.ts +8 -1
  223. package/src/scripts/doctor.ts +461 -262
  224. package/src/scripts/installAgent.ts +106 -19
  225. package/src/scripts/migrateAgentMemory.ts +2 -2
  226. package/src/scripts/smokeTest.ts +1 -1
@@ -1,14 +1,399 @@
1
1
  import { getDb } from '../lib/db';
2
+ import {
3
+ computeInformationDensity,
4
+ condenseObservation,
5
+ condenseText,
6
+ extractQueryFocusedSnippet,
7
+ parseQuerySignals,
8
+ safeUtf16Slice,
9
+ type ParsedQuerySignals,
10
+ } from '../lib/condenser';
2
11
  import { logger } from '../lib/logger';
12
+ import { normalizeUtcIso } from '../lib/recurrence';
13
+ import { detectQuerySignalIntent } from '../lib/signalTags';
14
+ import {
15
+ parseTemporalQueryWindow,
16
+ resolveRelativeDates,
17
+ type ParsedTemporalWindow,
18
+ type ResolvedDateAnnotation,
19
+ } from '../lib/temporal';
20
+ import {
21
+ buildHierarchicalScopeSql,
22
+ classifyMatchTier,
23
+ getProjectAncestors,
24
+ getProjectChildRange,
25
+ normalizeProjectId,
26
+ type MatchTier,
27
+ } from '../lib/scope';
3
28
  import { deserializeEmbedding, embedQuery, resolveEmbedderRecipe } from './embedding';
4
29
  import { verifyOrCreateStoreMeta } from './storeMeta';
5
30
  import { getQdrantClient } from './embedWorker';
6
- import type { SearchRequest, SearchResponse, SearchResultItem } from './types';
31
+ import type {
32
+ MemoryRecordType,
33
+ ObservationSearchKind,
34
+ SearchRequest,
35
+ SearchResponse,
36
+ SearchResultItem,
37
+ SearchSummarySource,
38
+ SnippetMode,
39
+ } from './types';
7
40
 
8
- function tokenize(text: string): string[] {
9
- if (!text) return [];
10
- const matches = text.toLowerCase().match(/[a-z0-9_./-]+/g);
11
- return matches ? matches : [];
41
+ const DEFAULT_RAW_SAFETY_CAP_CHARS = 32_000;
42
+ const MAX_SOURCE_PREVIEW_CHARS = 160;
43
+ const MAX_ENTITY_SEEDS = 15;
44
+ const MIN_ENTITY_DENSE_SIM = 0.55;
45
+ const RRF_K = 60;
46
+
47
+ export type QueryKindIntent = 'assistant' | 'tool' | 'general';
48
+
49
+ const OBSERVATION_KINDS: readonly ObservationSearchKind[] = ['prompt', 'response', 'tool_call'];
50
+
51
+ const ASSISTANT_INTENT_RE =
52
+ /\b(?:did\s{1,3}you|what\s{1,3}did\s{1,3}you|have\s{1,3}you\s{1,3}(?:suggest\w{0,10}|recommend\w{0,10}|said|mention\w{0,10}|told|given|advis\w{0,10}|explain\w{0,10}|list\w{0,10}|provid\w{0,10}|written|share\w{0,10}|shown)|you\s{1,3}(?:suggested|recommended|said|mentioned|told|gave|advised|explained|listed|provided|wrote|shared|showed)|your\s{1,3}(?:recipe|advice|recommendation\w{0,10}|suggestion\w{0,10}|list|explanation|answer|response|plan|outline|summary))\b/i;
53
+
54
+ const TOOL_FILE_OR_SYMBOL_RE =
55
+ /(?:(?:^|[\s"'`(])(?:\.{0,2}\/)?[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_./-]+|\b[a-zA-Z0-9_-]+\.(?:ts|tsx|js|jsx|mjs|cjs|json|py|rs|go|java|rb|php|sh|bash|zsh|yml|yaml|toml|sql|md|css|scss|html|lock|env|conf|ini|xml|c|cpp|h|hpp)\b|\b[a-z0-9]+_[a-z0-9_]+\b|\b[a-z]+[A-Z][a-zA-Z0-9]*\b)/;
56
+
57
+ const TOOL_ERROR_OR_CLI_RE =
58
+ /\b(?:error|errors|failed|failure|exception|traceback|stack\s*trace|stderr|stdout|exit\s*code|command|enoent|econnrefused|eaddrinuse|eacces|etimedout|typeerror|referenceerror|syntaxerror|sqliteerror|npm|npx|jest|tsc|git|docker|kubectl|curl|grep|bash)\b/i;
59
+
60
+ const INTENT_DEFAULT_KIND_WEIGHTS: Record<
61
+ QueryKindIntent,
62
+ Record<ObservationSearchKind, number>
63
+ > = {
64
+ assistant: { response: 1.20, prompt: 1.0, tool_call: 0.95 },
65
+ tool: { tool_call: 1.18, prompt: 1.08, response: 0.95 },
66
+ general: { prompt: 1.15, tool_call: 1.05, response: 0.90 },
67
+ };
68
+
69
+ export function detectQueryKindIntent(q: string, hasFileFilter = false): QueryKindIntent {
70
+ const sample = typeof q === 'string' ? (q.length > 4_000 ? safeUtf16Slice(q, 0, 4_000) : q) : '';
71
+ if (sample && ASSISTANT_INTENT_RE.test(sample)) {
72
+ return 'assistant';
73
+ }
74
+ if (
75
+ hasFileFilter ||
76
+ (sample && (TOOL_FILE_OR_SYMBOL_RE.test(sample) || TOOL_ERROR_OR_CLI_RE.test(sample)))
77
+ ) {
78
+ return 'tool';
79
+ }
80
+ return 'general';
81
+ }
82
+
83
+ function resolveKindWeights(
84
+ intent: QueryKindIntent,
85
+ callerWeights?: Partial<Record<ObservationSearchKind, number>>
86
+ ): Record<ObservationSearchKind, number> {
87
+ const weights: Record<ObservationSearchKind, number> = {
88
+ ...INTENT_DEFAULT_KIND_WEIGHTS[intent],
89
+ };
90
+ if (callerWeights && typeof callerWeights === 'object') {
91
+ for (const k of OBSERVATION_KINDS) {
92
+ if (Object.prototype.hasOwnProperty.call(callerWeights, k)) {
93
+ const raw = callerWeights[k];
94
+ if (typeof raw === 'number' && Number.isFinite(raw)) {
95
+ weights[k] = Math.min(5.0, Math.max(0.1, raw));
96
+ }
97
+ }
98
+ }
99
+ }
100
+ return weights;
101
+ }
102
+
103
+ function cleanOptionalString(v: unknown): string | null {
104
+ return typeof v === 'string' && v.trim() !== '' ? v.trim() : null;
105
+ }
106
+
107
+ function resolveMaxKindShare(
108
+ params: SearchRequest,
109
+ recordTypes: MemoryRecordType[],
110
+ intent: QueryKindIntent,
111
+ limit: number
112
+ ): Partial<Record<ObservationSearchKind, number>> | null {
113
+ if (params.max_kind_share !== undefined && params.max_kind_share !== null) {
114
+ if (typeof params.max_kind_share === 'object' && !Array.isArray(params.max_kind_share)) {
115
+ const ownKeys = Object.keys(params.max_kind_share);
116
+ if (ownKeys.length === 0) {
117
+ return null;
118
+ }
119
+ const explicit: Partial<Record<ObservationSearchKind, number>> = {};
120
+ let hasAny = false;
121
+ for (const k of OBSERVATION_KINDS) {
122
+ if (Object.prototype.hasOwnProperty.call(params.max_kind_share, k)) {
123
+ const raw = params.max_kind_share[k];
124
+ if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) {
125
+ explicit[k] = Math.min(1, raw);
126
+ hasAny = true;
127
+ }
128
+ }
129
+ }
130
+ if (hasAny) {
131
+ return explicit;
132
+ }
133
+ }
134
+ }
135
+
136
+ if (
137
+ recordTypes.includes('observation') &&
138
+ !cleanOptionalString(params.filters?.kind) &&
139
+ intent !== 'assistant' &&
140
+ limit >= 5
141
+ ) {
142
+ return { response: 0.6 };
143
+ }
144
+ return null;
145
+ }
146
+
147
+ function computeObservationDensityMultiplier(
148
+ record: Record<string, any>,
149
+ querySignals: ParsedQuerySignals
150
+ ): number {
151
+ const rawBody = [record.input, record.output].filter(Boolean).join('\n');
152
+ if (rawBody.length <= 800) {
153
+ return 1.0;
154
+ }
155
+
156
+ const lowerBody = rawBody.toLowerCase();
157
+ let matchedTerms = 0;
158
+ for (const tok of querySignals.contentTokens) {
159
+ if (lowerBody.includes(tok)) {
160
+ matchedTerms++;
161
+ }
162
+ }
163
+ const coverage =
164
+ querySignals.contentTokens.length > 0
165
+ ? matchedTerms / querySignals.contentTokens.length
166
+ : 0;
167
+
168
+ if (coverage >= 0.5) {
169
+ return 1.0;
170
+ }
171
+
172
+ const info = computeInformationDensity(rawBody);
173
+ const lowUnique = Math.max(0, (0.45 - info.uniqueContentRatio) / 0.45);
174
+ const highBoilerplate = Math.min(1, info.boilerplateListRatio / 0.55);
175
+ const lowDensity = Math.max(0, (0.38 - info.density) / 0.38);
176
+ const bloatSignal = Math.min(1, 0.45 * lowUnique + 0.35 * highBoilerplate + 0.20 * lowDensity);
177
+
178
+ if (bloatSignal <= 0.05) {
179
+ return 1.0;
180
+ }
181
+
182
+ const lenScale = 0.5 + 0.5 * Math.min(1, (rawBody.length - 800) / 3200);
183
+ const covScale = 1 - coverage;
184
+ const severity = Math.min(1, bloatSignal * lenScale * covScale * 1.25);
185
+ return Math.max(0.82, Math.min(0.95, 0.95 - 0.13 * severity));
186
+ }
187
+
188
+ function hasAnyQueryTerm(text: string | null | undefined, signals: ParsedQuerySignals): boolean {
189
+ if (!text) return false;
190
+ const lower = text.toLowerCase();
191
+ for (const phrase of signals.phrases) {
192
+ if (lower.includes(phrase)) return true;
193
+ }
194
+ for (const tok of signals.contentTokens) {
195
+ if (lower.includes(tok)) return true;
196
+ }
197
+ return false;
198
+ }
199
+
200
+ function allocateFieldBudgets(
201
+ inLen: number,
202
+ outLen: number,
203
+ inMatches: boolean,
204
+ outMatches: boolean,
205
+ totalCap: number
206
+ ): [number, number] {
207
+ if (inLen === 0) return [0, totalCap];
208
+ if (outLen === 0) return [totalCap, 0];
209
+ if (inLen + outLen <= totalCap) return [inLen, outLen];
210
+
211
+ const quarter = Math.max(32, Math.floor(totalCap * 0.25));
212
+ if (inLen <= quarter) {
213
+ return [inLen, Math.max(32, totalCap - inLen)];
214
+ }
215
+ if (outLen <= quarter) {
216
+ return [Math.max(32, totalCap - outLen), outLen];
217
+ }
218
+
219
+ if (outMatches && !inMatches) {
220
+ const inShare = Math.max(36, Math.floor(totalCap * 0.22));
221
+ return [inShare, Math.max(36, totalCap - inShare)];
222
+ }
223
+ if (inMatches && !outMatches) {
224
+ const outShare = Math.max(36, Math.floor(totalCap * 0.22));
225
+ return [Math.max(36, totalCap - outShare), outShare];
226
+ }
227
+
228
+ const inShare = Math.max(36, Math.floor(totalCap * 0.45));
229
+ return [inShare, Math.max(36, totalCap - inShare)];
230
+ }
231
+
232
+ function capRawField(value: string | null | undefined, cap: number): string | null {
233
+ if (value === null || value === undefined) return null;
234
+ if (value.length <= cap) return value;
235
+ if (cap <= 3) return safeUtf16Slice(value, 0, Math.max(0, cap));
236
+ return `${safeUtf16Slice(value, 0, cap - 3)}...`;
237
+ }
238
+
239
+ function formatObservationResult(
240
+ rawRecord: Record<string, any>,
241
+ q: string,
242
+ signals: ParsedQuerySignals,
243
+ snippetMode: SnippetMode,
244
+ explicitMaxChars?: number,
245
+ parsedWindow?: ParsedTemporalWindow | null
246
+ ): { record: Record<string, any>; snippet: string } {
247
+ const obsKind = (rawRecord.kind as ObservationSearchKind) || 'tool_call';
248
+ const rawInput: string | null = typeof rawRecord.input === 'string' ? rawRecord.input : null;
249
+ const rawOutput: string | null = typeof rawRecord.output === 'string' ? rawRecord.output : null;
250
+
251
+ const obsAnchor: string | number | null =
252
+ typeof rawRecord.event_at === 'string' && rawRecord.event_at.trim() !== ''
253
+ ? rawRecord.event_at
254
+ : typeof rawRecord.created_at === 'number' && Number.isFinite(rawRecord.created_at)
255
+ ? rawRecord.created_at
256
+ : null;
257
+
258
+ const annotatedInput =
259
+ rawInput !== null && obsAnchor !== null
260
+ ? resolveRelativeDates(rawInput, obsAnchor).annotatedText
261
+ : rawInput;
262
+ const annotatedOutput =
263
+ rawOutput !== null && obsAnchor !== null
264
+ ? resolveRelativeDates(rawOutput, obsAnchor).annotatedText
265
+ : rawOutput;
266
+
267
+ const toolPrefix = [rawRecord.tool_name, rawRecord.file_path].filter(Boolean).join(' ');
268
+ const combinedAnnotated = [
269
+ toolPrefix ? `[${toolPrefix}]` : '',
270
+ annotatedInput || '',
271
+ annotatedOutput || '',
272
+ ]
273
+ .filter(Boolean)
274
+ .join('\n');
275
+
276
+ const snippetQuery = parsedWindow
277
+ ? `${q} ${new Date(parsedWindow.centerMs).toISOString().slice(0, 10)}`
278
+ : q;
279
+
280
+ const previewCap = explicitMaxChars ?? (obsKind === 'prompt' ? 1000 : 600);
281
+
282
+ if (snippetMode === 'raw') {
283
+ const rawCap = explicitMaxChars ?? DEFAULT_RAW_SAFETY_CAP_CHARS;
284
+ const snippet = combinedAnnotated
285
+ ? extractQueryFocusedSnippet(combinedAnnotated, snippetQuery, { maxChars: previewCap })
286
+ : '';
287
+ return {
288
+ record: {
289
+ ...rawRecord,
290
+ input: capRawField(rawInput, rawCap),
291
+ output: capRawField(rawOutput, rawCap),
292
+ },
293
+ snippet,
294
+ };
295
+ }
296
+
297
+ if (snippetMode === 'condensed') {
298
+ const maxChars = explicitMaxChars ?? 600;
299
+ const storedOrComputed =
300
+ (typeof rawRecord.condensed_text === 'string' && rawRecord.condensed_text.trim() !== ''
301
+ ? rawRecord.condensed_text
302
+ : condenseObservation({
303
+ kind: obsKind,
304
+ toolName: rawRecord.tool_name,
305
+ filePath: rawRecord.file_path,
306
+ input: annotatedInput,
307
+ output: annotatedOutput,
308
+ maxChars,
309
+ })) || '';
310
+ const snippet =
311
+ storedOrComputed.length <= maxChars
312
+ ? storedOrComputed
313
+ : condenseText(storedOrComputed, { kind: obsKind, maxChars });
314
+
315
+ const [inBudget, outBudget] = allocateFieldBudgets(
316
+ annotatedInput?.length ?? 0,
317
+ annotatedOutput?.length ?? 0,
318
+ hasAnyQueryTerm(annotatedInput, signals),
319
+ hasAnyQueryTerm(annotatedOutput, signals),
320
+ maxChars
321
+ );
322
+
323
+ const formattedInput =
324
+ annotatedInput === null
325
+ ? null
326
+ : annotatedInput.length <= inBudget && obsKind === 'prompt' && annotatedInput.length <= 500
327
+ ? annotatedInput
328
+ : condenseText(annotatedInput, { kind: obsKind, maxChars: Math.max(40, inBudget) });
329
+ const formattedOutput =
330
+ annotatedOutput === null
331
+ ? null
332
+ : annotatedOutput.length <= outBudget && obsKind === 'prompt' && annotatedOutput.length <= 500
333
+ ? annotatedOutput
334
+ : condenseText(annotatedOutput, { kind: obsKind, maxChars: Math.max(40, outBudget) });
335
+
336
+ return {
337
+ record: {
338
+ ...rawRecord,
339
+ input: formattedInput !== null ? capRawField(formattedInput, inBudget) : null,
340
+ output: formattedOutput !== null ? capRawField(formattedOutput, outBudget) : null,
341
+ },
342
+ snippet: capRawField(snippet, maxChars) || '',
343
+ };
344
+ }
345
+
346
+ // Default: 'query_focused'
347
+ const maxChars = previewCap;
348
+ const effectiveSignals = parsedWindow ? parseQuerySignals(snippetQuery) : signals;
349
+ const [inBudget, outBudget] = allocateFieldBudgets(
350
+ annotatedInput?.length ?? 0,
351
+ annotatedOutput?.length ?? 0,
352
+ hasAnyQueryTerm(annotatedInput, effectiveSignals),
353
+ hasAnyQueryTerm(annotatedOutput, effectiveSignals),
354
+ maxChars
355
+ );
356
+
357
+ const formattedInput =
358
+ annotatedInput === null
359
+ ? null
360
+ : extractQueryFocusedSnippet(annotatedInput, snippetQuery, {
361
+ maxChars: Math.max(32, inBudget),
362
+ });
363
+ const formattedOutput =
364
+ annotatedOutput === null
365
+ ? null
366
+ : extractQueryFocusedSnippet(annotatedOutput, snippetQuery, {
367
+ maxChars: Math.max(32, outBudget),
368
+ });
369
+
370
+ const snippet = combinedAnnotated
371
+ ? extractQueryFocusedSnippet(combinedAnnotated, snippetQuery, { maxChars })
372
+ : '';
373
+
374
+ return {
375
+ record: {
376
+ ...rawRecord,
377
+ input: formattedInput,
378
+ output: formattedOutput,
379
+ },
380
+ snippet,
381
+ };
382
+ }
383
+
384
+ const SEMANTIC_NOTE_TYPES = ['fact', 'architecture', 'preference'] as const;
385
+ const PROCEDURAL_NOTE_TYPES = ['workflow', 'pattern', 'lesson', 'bug'] as const;
386
+ const VALID_RECORD_TYPES = new Set<MemoryRecordType>([
387
+ 'note',
388
+ 'trajectory',
389
+ 'observation',
390
+ 'summary',
391
+ 'entity',
392
+ 'action',
393
+ ]);
394
+
395
+ function docKey(recordType: string, id: string): string {
396
+ return `${recordType}:${id}`;
12
397
  }
13
398
 
14
399
  function cosineSimilarity(a: number[], b: number[]): number {
@@ -25,424 +410,1647 @@ function cosineSimilarity(a: number[], b: number[]): number {
25
410
  return denom === 0 ? 0 : dot / denom;
26
411
  }
27
412
 
28
- interface CandidateDoc {
29
- id: string;
30
- grain: 'note' | 'trajectory' | 'observation' | 'summary';
31
- record: Record<string, any>;
32
- text: string;
33
- embedding: Buffer | null;
34
- bm25Score?: number;
35
- denseScore?: number;
36
- rrfScore?: number;
413
+ function parseTimestampMs(raw: unknown): number | null {
414
+ if (typeof raw === 'number' && Number.isFinite(raw)) {
415
+ return raw * 1000;
416
+ }
417
+ if (typeof raw === 'string') {
418
+ const trimmed = raw.trim();
419
+ if (!trimmed) return null;
420
+ const iso = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(trimmed)
421
+ ? `${trimmed.replace(' ', 'T')}Z`
422
+ : trimmed;
423
+ const ms = Date.parse(iso);
424
+ return Number.isFinite(ms) ? ms : null;
425
+ }
426
+ return null;
427
+ }
428
+
429
+ const MAX_FTS_QUERY_CHARS = 4_000;
430
+ const MAX_FTS_TOKENS = 48;
431
+ const FTS_TOKEN_RE = /[\p{L}\p{N}_]+/gu;
432
+ const FTS_HAS_ALNUM_RE = /[\p{L}\p{N}]/u;
433
+ const FTS_DIGIT_OR_UNDERSCORE_RE = /[0-9_]/;
434
+ const FTS_INTERNAL_UPPER_RE = /\p{Ll}\p{Lu}|\p{Lu}{2,}/u;
435
+ const FTS_INITIAL_UPPER_RE = /^\p{Lu}/u;
436
+ const FTS_TRAILING_LETTER_RE = /\p{L}$/u;
437
+ const FTS_PURE_CJK_RE =
438
+ /^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u30fc\u3005]{2,}$/u;
439
+ const FTS_DOUBLE_QUOTED_RE = /"([^"\r\n]*)"/g;
440
+ const FTS_SINGLE_QUOTED_RE = /(?:^|[^\p{L}\p{N}_])'([^'\r\n]*)'(?=$|[^\p{L}\p{N}_])/gu;
441
+ const FTS_APOSTROPHE_CLITICS = new Set(['s', 't', 'm', 'd', 're', 've', 'll']);
442
+
443
+ const FTS_STOPWORDS = new Set([
444
+ 'i',
445
+ 'me',
446
+ 'my',
447
+ 'you',
448
+ 'your',
449
+ 'we',
450
+ 'our',
451
+ 'he',
452
+ 'him',
453
+ 'his',
454
+ 'she',
455
+ 'her',
456
+ 'hers',
457
+ 'they',
458
+ 'them',
459
+ 'their',
460
+ 'theirs',
461
+ 'the',
462
+ 'a',
463
+ 'an',
464
+ 'to',
465
+ 'of',
466
+ 'in',
467
+ 'on',
468
+ 'at',
469
+ 'for',
470
+ 'with',
471
+ 'from',
472
+ 'by',
473
+ 'about',
474
+ 'as',
475
+ 'into',
476
+ 'is',
477
+ 'am',
478
+ 'are',
479
+ 'was',
480
+ 'were',
481
+ 'be',
482
+ 'been',
483
+ 'being',
484
+ 'do',
485
+ 'does',
486
+ 'did',
487
+ 'have',
488
+ 'has',
489
+ 'had',
490
+ 'can',
491
+ 'could',
492
+ 'will',
493
+ 'would',
494
+ 'should',
495
+ 'may',
496
+ 'might',
497
+ 'don',
498
+ 'doesn',
499
+ 'didn',
500
+ 'isn',
501
+ 'aren',
502
+ 'wasn',
503
+ 'weren',
504
+ 'hasn',
505
+ 'haven',
506
+ 'hadn',
507
+ 'won',
508
+ 'wouldn',
509
+ 'couldn',
510
+ 'shouldn',
511
+ 'mustn',
512
+ 'ain',
513
+ 'how',
514
+ 'what',
515
+ 'when',
516
+ 'where',
517
+ 'who',
518
+ 'which',
519
+ 'why',
520
+ 'many',
521
+ 'much',
522
+ 'some',
523
+ 'any',
524
+ 'this',
525
+ 'that',
526
+ 'these',
527
+ 'those',
528
+ 'it',
529
+ 'its',
530
+ 'and',
531
+ 'or',
532
+ 'not',
533
+ 'but',
534
+ 'if',
535
+ 'so',
536
+ 'than',
537
+ 'then',
538
+ 'there',
539
+ 'here',
540
+ ]);
541
+
542
+ const STRICT_QUERY_META_VERBS = new Set([
543
+ 'mention',
544
+ 'mentioned',
545
+ 'mentions',
546
+ 'say',
547
+ 'said',
548
+ 'tell',
549
+ 'told',
550
+ 'talk',
551
+ 'talked',
552
+ 'discuss',
553
+ 'discussed',
554
+ 'remember',
555
+ 'recall',
556
+ 'happen',
557
+ 'happened',
558
+ 'recommend',
559
+ 'recommended',
560
+ 'recommends',
561
+ 'suggest',
562
+ 'suggested',
563
+ 'suggestions',
564
+ ]);
565
+
566
+ interface ScannedFtsToken {
567
+ tok: string;
568
+ firstIndex: number;
569
+ hasDigitOrUnderscore: boolean;
570
+ hasInternalUpper: boolean;
571
+ isMidSentenceCap: boolean;
572
+ isInitialCap: boolean;
573
+ }
574
+
575
+ function quoteFtsToken(tok: string): string {
576
+ return `"${tok.replace(/"/g, '""')}"`;
577
+ }
578
+
579
+ function scoreFtsTokenSpecificity(info: ScannedFtsToken): number {
580
+ let score = 0;
581
+ if (info.hasDigitOrUnderscore) score += 5.0;
582
+ if (info.hasInternalUpper) score += 4.0;
583
+ else if (info.isMidSentenceCap) score += 3.5;
584
+ else if (info.isInitialCap) score += 1.5;
585
+
586
+ if (info.tok.length >= 4) {
587
+ score += Math.min(info.tok.length, 16) * 0.35;
588
+ } else if (info.tok.length === 3) {
589
+ score += 0.3;
590
+ } else {
591
+ score -= 1.0;
592
+ }
593
+ return score;
594
+ }
595
+
596
+ function isApostropheClitic(text: string, matchIndex: number, lowerTok: string): boolean {
597
+ if (!FTS_APOSTROPHE_CLITICS.has(lowerTok) || matchIndex < 2) return false;
598
+ const quoteChar = text[matchIndex - 1];
599
+ if (quoteChar !== "'" && quoteChar !== '\u2019' && quoteChar !== '\u2018') return false;
600
+ const beforeQuote = text.slice(Math.max(0, matchIndex - 3), matchIndex - 1);
601
+ return FTS_TRAILING_LETTER_RE.test(beforeQuote);
602
+ }
603
+
604
+ function scanBoundedFtsTokens(q: string): {
605
+ sample: string;
606
+ allTokens: ScannedFtsToken[];
607
+ contentTokens: ScannedFtsToken[];
608
+ } {
609
+ const sample = q.length > MAX_FTS_QUERY_CHARS ? safeUtf16Slice(q, 0, MAX_FTS_QUERY_CHARS) : q;
610
+ const byTok = new Map<string, ScannedFtsToken>();
611
+ const tokenRe = new RegExp(FTS_TOKEN_RE.source, 'gu');
612
+ let match: RegExpExecArray | null;
613
+ let ordinal = 0;
614
+
615
+ while ((match = tokenRe.exec(sample)) !== null) {
616
+ const surface = match[0];
617
+ if (!FTS_HAS_ALNUM_RE.test(surface)) continue;
618
+ const lower = surface.toLowerCase();
619
+ if (isApostropheClitic(sample, match.index, lower)) continue;
620
+ const isUpperStart = FTS_INITIAL_UPPER_RE.test(surface);
621
+ const hasInternalUpper = FTS_INTERNAL_UPPER_RE.test(surface);
622
+ const existing = byTok.get(lower);
623
+ if (!existing) {
624
+ byTok.set(lower, {
625
+ tok: lower,
626
+ firstIndex: ordinal,
627
+ hasDigitOrUnderscore: FTS_DIGIT_OR_UNDERSCORE_RE.test(lower),
628
+ hasInternalUpper,
629
+ isMidSentenceCap: ordinal > 0 && isUpperStart,
630
+ isInitialCap: ordinal === 0 && isUpperStart,
631
+ });
632
+ } else {
633
+ if (hasInternalUpper) existing.hasInternalUpper = true;
634
+ if (ordinal > 0 && isUpperStart) existing.isMidSentenceCap = true;
635
+ }
636
+ ordinal++;
637
+ }
638
+
639
+ const allTokens = Array.from(byTok.values());
640
+ const contentTokens = allTokens.filter((t) => !FTS_STOPWORDS.has(t.tok));
641
+ return { sample, allTokens, contentTokens };
642
+ }
643
+
644
+ /**
645
+ * Safely convert an arbitrary user query string into a stopword-filtered FTS5 OR
646
+ * expression. Bounds scan length to 4,000 chars and token count to <= 48 so huge
647
+ * pasted stack traces run in linear O(N) time and never approach SQLite's
648
+ * SQLITE_MAX_EXPR_DEPTH limit. Falls back to unfiltered tokens on pure-stopword queries.
649
+ */
650
+ export function buildSafeFtsQuery(q: string): string | null {
651
+ if (typeof q !== 'string') return null;
652
+ const { allTokens, contentTokens } = scanBoundedFtsTokens(q);
653
+ if (allTokens.length === 0) return null;
654
+
655
+ const active = contentTokens.length > 0 ? contentTokens : allTokens;
656
+ let selected: ScannedFtsToken[];
657
+ if (active.length <= MAX_FTS_TOKENS) {
658
+ selected = active;
659
+ } else {
660
+ selected = [...active]
661
+ .sort((a, b) => {
662
+ const diff = scoreFtsTokenSpecificity(b) - scoreFtsTokenSpecificity(a);
663
+ return Math.abs(diff) > 1e-6 ? diff : a.firstIndex - b.firstIndex;
664
+ })
665
+ .slice(0, MAX_FTS_TOKENS)
666
+ .sort((a, b) => a.firstIndex - b.firstIndex);
667
+ }
668
+
669
+ return selected
670
+ .map((t) =>
671
+ FTS_PURE_CJK_RE.test(t.tok) ? `${quoteFtsToken(t.tok)}*` : quoteFtsToken(t.tok)
672
+ )
673
+ .join(' OR ');
674
+ }
675
+
676
+ function extractQuotedPhraseClauses(
677
+ sample: string
678
+ ): { clauses: string[]; coveredTokens: Set<string> } {
679
+ const clauses: string[] = [];
680
+ const coveredTokens = new Set<string>();
681
+ const seenClause = new Set<string>();
682
+
683
+ const collectFromRegex = (re: RegExp) => {
684
+ re.lastIndex = 0;
685
+ let m: RegExpExecArray | null;
686
+ while ((m = re.exec(sample)) !== null && clauses.length < 2) {
687
+ const inner = m[1];
688
+ if (inner.length < 3 || inner.length > 120) continue;
689
+ const innerTokenRe = new RegExp(FTS_TOKEN_RE.source, 'gu');
690
+ const phraseToks: string[] = [];
691
+ const seenInPhrase = new Set<string>();
692
+ let rawTokenCount = 0;
693
+ let tokMatch: RegExpExecArray | null;
694
+ while ((tokMatch = innerTokenRe.exec(inner)) !== null) {
695
+ const raw = tokMatch[0];
696
+ if (!FTS_HAS_ALNUM_RE.test(raw)) continue;
697
+ const lower = raw.toLowerCase();
698
+ if (isApostropheClitic(inner, tokMatch.index, lower)) continue;
699
+ rawTokenCount++;
700
+ if (FTS_STOPWORDS.has(lower) || seenInPhrase.has(lower)) continue;
701
+ seenInPhrase.add(lower);
702
+ phraseToks.push(lower);
703
+ if (phraseToks.length > 4) break;
704
+ }
705
+ if (rawTokenCount < 2) continue;
706
+ if (phraseToks.length >= 2 && phraseToks.length <= 4) {
707
+ const clause = `NEAR(${phraseToks.map(quoteFtsToken).join(' ')}, 6)`;
708
+ if (!seenClause.has(clause)) {
709
+ seenClause.add(clause);
710
+ clauses.push(clause);
711
+ for (const pt of phraseToks) {
712
+ coveredTokens.add(pt);
713
+ }
714
+ }
715
+ }
716
+ }
717
+ };
718
+
719
+ collectFromRegex(FTS_DOUBLE_QUOTED_RE);
720
+ if (clauses.length < 2) {
721
+ collectFromRegex(FTS_SINGLE_QUOTED_RE);
722
+ }
723
+
724
+ return { clauses, coveredTokens };
725
+ }
726
+
727
+ /**
728
+ * Build a Tier-1 strict FTS5 query (`AND` over top specific content terms plus
729
+ * `NEAR(..., 6)` on explicit quoted multi-word titles/phrases) when >= 2 content
730
+ * tokens exist. Returns null for empty, pure-stopword, or single-token queries.
731
+ */
732
+ export function buildStrictFtsQuery(q: string): string | null {
733
+ if (typeof q !== 'string') return null;
734
+ const { sample, contentTokens } = scanBoundedFtsTokens(q);
735
+ if (contentTokens.length < 2) return null;
736
+
737
+ const { clauses: nearClauses, coveredTokens } = extractQuotedPhraseClauses(sample);
738
+ const remaining = contentTokens.filter((t) => !coveredTokens.has(t.tok));
739
+
740
+ const withoutMeta = remaining.filter((t) => !STRICT_QUERY_META_VERBS.has(t.tok));
741
+ const pool =
742
+ coveredTokens.size + withoutMeta.length >= 2 ? withoutMeta : remaining;
743
+
744
+ const maxTotalClauses = contentTokens.length > 5 && nearClauses.length === 0 ? 3 : 4;
745
+ const slotsLeft = Math.max(0, maxTotalClauses - nearClauses.length);
746
+
747
+ let chosenTerms: ScannedFtsToken[] = [];
748
+ if (slotsLeft > 0 && pool.length > 0) {
749
+ if (pool.length <= slotsLeft) {
750
+ chosenTerms = pool;
751
+ } else {
752
+ chosenTerms = [...pool]
753
+ .sort((a, b) => {
754
+ const diff = scoreFtsTokenSpecificity(b) - scoreFtsTokenSpecificity(a);
755
+ return Math.abs(diff) > 1e-6 ? diff : a.firstIndex - b.firstIndex;
756
+ })
757
+ .slice(0, slotsLeft)
758
+ .sort((a, b) => a.firstIndex - b.firstIndex);
759
+ }
760
+ }
761
+
762
+ const allClauses = [
763
+ ...nearClauses,
764
+ ...chosenTerms.map((t) => quoteFtsToken(t.tok)),
765
+ ];
766
+ if (allClauses.length === 0) return null;
767
+ if (nearClauses.length === 0 && chosenTerms.length < 2) return null;
768
+
769
+ return allClauses.join(' AND ');
770
+ }
771
+
772
+ function resolveEffectiveNoteTypes(params: SearchRequest): string[] | null {
773
+ const layer = params.filters?.memory_layer;
774
+ const rawTypeParam = params.filters?.type;
775
+ const rawTypes = Array.isArray(rawTypeParam)
776
+ ? rawTypeParam.map(cleanOptionalString).filter((t): t is string => t !== null)
777
+ : undefined;
778
+
779
+ let layerSet: Set<string> | null = null;
780
+ if (layer === 'semantic') {
781
+ layerSet = new Set(SEMANTIC_NOTE_TYPES);
782
+ } else if (layer === 'procedural') {
783
+ layerSet = new Set(PROCEDURAL_NOTE_TYPES);
784
+ }
785
+
786
+ if (layerSet && rawTypes && rawTypes.length > 0) {
787
+ return rawTypes.filter((t) => layerSet!.has(t));
788
+ }
789
+ if (layerSet) {
790
+ return Array.from(layerSet);
791
+ }
792
+ if (rawTypes && rawTypes.length > 0) {
793
+ return rawTypes;
794
+ }
795
+ return null;
37
796
  }
38
797
 
39
798
  export function buildQdrantFilter(
40
799
  params: SearchRequest,
41
- grains: string[],
42
- includeGlobal: boolean
800
+ recordTypes: string[],
801
+ includeGlobal: boolean,
802
+ childProjectIds?: string[]
43
803
  ): Record<string, any> | undefined {
44
804
  const must: any[] = [];
45
805
 
46
- // Grains filter
47
- if (grains.length === 1) {
48
- must.push({ key: 'grain', match: { value: grains[0] } });
49
- } else if (grains.length > 1) {
50
- must.push({ key: 'grain', match: { any: grains } });
806
+ if (recordTypes.length === 1) {
807
+ must.push({ key: 'record_type', match: { value: recordTypes[0] } });
808
+ } else if (recordTypes.length > 1) {
809
+ must.push({ key: 'record_type', match: { any: recordTypes } });
51
810
  }
52
811
 
53
- // Scope filter
812
+ const cleanProjectId = cleanOptionalString(params.project_id) ?? '';
813
+
54
814
  if (params.scope === 'unknown') {
55
815
  must.push({ key: 'scope', match: { value: 'unknown' } });
56
- } else if (params.scope === 'global' || !params.project_id) {
816
+ } else if (params.scope === 'global' || !cleanProjectId) {
57
817
  must.push({ key: 'scope', match: { value: 'global' } });
58
- } else if (params.project_id) {
818
+ } else {
819
+ const normRes = normalizeProjectId(cleanProjectId);
820
+ const norm = normRes.ok ? normRes.projectId : cleanProjectId;
821
+ const includeAncestors = params.include_ancestors !== false;
822
+ const includeChildren = params.include_children === true;
823
+ const targetIds = includeAncestors ? getProjectAncestors(norm) : [norm];
824
+
825
+ const ancestorMatch =
826
+ targetIds.length === 1
827
+ ? { key: 'project_id', match: { value: targetIds[0] } }
828
+ : { key: 'project_id', match: { any: targetIds } };
829
+
830
+ const projectMust: any[] = [{ key: 'scope', match: { value: 'project' } }];
831
+ if (includeChildren) {
832
+ const childShould: any[] = [
833
+ ancestorMatch,
834
+ { key: 'project_ancestors', match: { value: norm } },
835
+ ];
836
+ if (childProjectIds && childProjectIds.length > 0) {
837
+ childShould.push(
838
+ childProjectIds.length === 1
839
+ ? { key: 'project_id', match: { value: childProjectIds[0] } }
840
+ : { key: 'project_id', match: { any: childProjectIds } }
841
+ );
842
+ }
843
+ projectMust.push({ should: childShould });
844
+ } else {
845
+ projectMust.push(ancestorMatch);
846
+ }
847
+
59
848
  if (includeGlobal) {
60
849
  must.push({
61
850
  should: [
62
- {
63
- must: [
64
- { key: 'scope', match: { value: 'project' } },
65
- { key: 'project_id', match: { value: params.project_id } },
66
- ],
67
- },
851
+ { must: projectMust },
68
852
  { key: 'scope', match: { value: 'global' } },
69
853
  ],
70
854
  });
71
855
  } else {
72
- must.push({ key: 'scope', match: { value: 'project' } });
73
- must.push({ key: 'project_id', match: { value: params.project_id } });
856
+ must.push(...projectMust);
857
+ }
858
+ }
859
+
860
+ const userId = cleanOptionalString(params.user_id) ?? cleanOptionalString(params.filters?.user_id);
861
+ if (userId) {
862
+ must.push({ key: 'user_id', match: { value: userId } });
863
+ }
864
+
865
+ const entityType = cleanOptionalString(params.filters?.entity_type);
866
+ if (entityType) {
867
+ must.push({ key: 'entity_type', match: { value: entityType } });
868
+ }
869
+
870
+ const cleanFilterTypes = Array.isArray(params.filters?.type)
871
+ ? params.filters.type.map(cleanOptionalString).filter((t): t is string => t !== null)
872
+ : [];
873
+ const effectiveNoteTypes = resolveEffectiveNoteTypes(params);
874
+ if (cleanFilterTypes.length > 0) {
875
+ const typesToFilter =
876
+ params.filters?.memory_layer && effectiveNoteTypes ? effectiveNoteTypes : cleanFilterTypes;
877
+ if (typesToFilter.length === 0) {
878
+ must.push({ key: 'type', match: { value: '__none__' } });
879
+ } else {
880
+ must.push(
881
+ typesToFilter.length === 1
882
+ ? { key: 'type', match: { value: typesToFilter[0] } }
883
+ : { key: 'type', match: { any: typesToFilter } }
884
+ );
885
+ }
886
+ } else if (params.filters?.memory_layer && effectiveNoteTypes && recordTypes.length === 1 && recordTypes[0] === 'note') {
887
+ must.push(
888
+ effectiveNoteTypes.length === 1
889
+ ? { key: 'type', match: { value: effectiveNoteTypes[0] } }
890
+ : { key: 'type', match: { any: effectiveNoteTypes } }
891
+ );
892
+ }
893
+
894
+ const kind = cleanOptionalString(params.filters?.kind);
895
+ if (kind) {
896
+ must.push({ key: 'kind', match: { value: kind } });
897
+ }
898
+ const taskType = cleanOptionalString(params.filters?.task_type);
899
+ if (taskType) {
900
+ must.push({ key: 'task_type', match: { value: taskType } });
901
+ }
902
+ const filePath = cleanOptionalString(params.filters?.file_path);
903
+ if (filePath) {
904
+ must.push({ key: 'file_path', match: { value: filePath } });
905
+ }
906
+ const agent = cleanOptionalString(params.filters?.agent);
907
+ if (agent) {
908
+ must.push({ key: 'agent', match: { value: agent } });
909
+ }
910
+ if (params.filters?.success !== undefined) {
911
+ must.push({ key: 'success', match: { value: !!params.filters.success } });
912
+ }
913
+ const noteRef = cleanOptionalString(params.filters?.note_ref);
914
+ if (noteRef) {
915
+ must.push({ key: 'note_ref', match: { value: noteRef } });
916
+ }
917
+ const taskRef = cleanOptionalString(params.filters?.task_ref);
918
+ if (taskRef) {
919
+ must.push({ key: 'task_ref', match: { value: taskRef } });
920
+ }
921
+ const sessionId = cleanOptionalString((params.filters as any)?.session_id);
922
+ if (sessionId) {
923
+ must.push({ key: 'session_id', match: { value: sessionId } });
924
+ }
925
+
926
+ if (must.length === 0) return undefined;
927
+ return { must };
928
+ }
929
+
930
+ interface CandidateDoc {
931
+ id: string;
932
+ record_type: MemoryRecordType;
933
+ record: Record<string, any>;
934
+ text: string;
935
+ embedding: Buffer | null;
936
+ claims?: Array<{ id: string; summary_id: string; text: string; ordinal: number }>;
937
+ bm25Score?: number;
938
+ denseScore?: number;
939
+ entityLinkScore?: number;
940
+ temporalRecallScore?: number;
941
+ matchedEntities?: string[];
942
+ matchTier?: MatchTier;
943
+ rrfScore?: number;
944
+ }
945
+
946
+ interface FilterContext {
947
+ params: SearchRequest;
948
+ queryIntent: QueryKindIntent;
949
+ includeGlobal: boolean;
950
+ includeAncestors: boolean;
951
+ includeChildren: boolean;
952
+ userId: string | null;
953
+ afterIso: string | null;
954
+ beforeIso: string | null;
955
+ asOfIso: string | null;
956
+ }
957
+
958
+ interface SqlConditionsResult {
959
+ impossible?: boolean;
960
+ conditions: string[];
961
+ queryParams: unknown[];
962
+ }
963
+
964
+ interface RecordTypeSpec {
965
+ table: string;
966
+ alias: string;
967
+ ftsTable: string;
968
+ hasEmbedding: boolean;
969
+ scanOrderCol: string;
970
+ temporalExpr: (alias: string) => string;
971
+ buildExtraConditions: (ctx: FilterContext) => SqlConditionsResult;
972
+ hydrate: (db: ReturnType<typeof getDb>, rows: any[]) => CandidateDoc[];
973
+ }
974
+
975
+ function hydrateNotes(db: ReturnType<typeof getDb>, rows: any[]): CandidateDoc[] {
976
+ if (rows.length === 0) return [];
977
+ const noteIds = rows.map((r) => r.id);
978
+ const placeholders = noteIds.map(() => '?').join(',');
979
+
980
+ const allConcepts = db
981
+ .prepare(`SELECT note_id, concept FROM note_concepts WHERE note_id IN (${placeholders})`)
982
+ .all(...noteIds) as Array<{ note_id: string; concept: string }>;
983
+ const conceptsByNoteId = new Map<string, string[]>();
984
+ for (const row of allConcepts) {
985
+ let list = conceptsByNoteId.get(row.note_id);
986
+ if (!list) {
987
+ list = [];
988
+ conceptsByNoteId.set(row.note_id, list);
989
+ }
990
+ list.push(row.concept);
991
+ }
992
+
993
+ const allFiles = db
994
+ .prepare(`SELECT note_id, file_path FROM note_files WHERE note_id IN (${placeholders})`)
995
+ .all(...noteIds) as Array<{ note_id: string; file_path: string }>;
996
+ const filesByNoteId = new Map<string, string[]>();
997
+ for (const row of allFiles) {
998
+ let list = filesByNoteId.get(row.note_id);
999
+ if (!list) {
1000
+ list = [];
1001
+ filesByNoteId.set(row.note_id, list);
1002
+ }
1003
+ list.push(row.file_path);
1004
+ }
1005
+
1006
+ return rows.map((row) => {
1007
+ const concepts = conceptsByNoteId.get(row.id) || [];
1008
+ const files = filesByNoteId.get(row.id) || [];
1009
+ const { embedding, fts_bm25, ...rowWithoutEmbedding } = row;
1010
+ const record = { ...rowWithoutEmbedding, concepts, files };
1011
+ const text = `${row.title}\n\n${row.content}\n${concepts.join(' ')}\n${files.join(' ')}`;
1012
+ return {
1013
+ id: row.id,
1014
+ record_type: 'note' as const,
1015
+ record,
1016
+ text,
1017
+ embedding: embedding ?? null,
1018
+ ...(typeof fts_bm25 === 'number' ? { bm25Score: Math.max(fts_bm25, 1e-6) } : {}),
1019
+ };
1020
+ });
1021
+ }
1022
+
1023
+ function hydrateSummaries(db: ReturnType<typeof getDb>, rows: any[]): CandidateDoc[] {
1024
+ if (rows.length === 0) return [];
1025
+ const summaryIds = rows.map((r) => r.id);
1026
+ const placeholders = summaryIds.map(() => '?').join(',');
1027
+
1028
+ const allClaims = db
1029
+ .prepare(
1030
+ `SELECT id, summary_id, text, ordinal FROM summary_claims WHERE summary_id IN (${placeholders}) ORDER BY ordinal ASC`
1031
+ )
1032
+ .all(...summaryIds) as Array<{ id: string; summary_id: string; text: string; ordinal: number }>;
1033
+ const claimsBySummaryId = new Map<string, typeof allClaims>();
1034
+ for (const c of allClaims) {
1035
+ let list = claimsBySummaryId.get(c.summary_id);
1036
+ if (!list) {
1037
+ list = [];
1038
+ claimsBySummaryId.set(c.summary_id, list);
1039
+ }
1040
+ list.push(c);
1041
+ }
1042
+
1043
+ return rows.map((row) => {
1044
+ const claims = claimsBySummaryId.get(row.id) || [];
1045
+ const { embedding, fts_bm25, ...rowWithoutEmbedding } = row;
1046
+ const text = claims.map((c) => c.text).join('\n');
1047
+ return {
1048
+ id: row.id,
1049
+ record_type: 'summary' as const,
1050
+ record: rowWithoutEmbedding,
1051
+ text,
1052
+ embedding: embedding ?? null,
1053
+ claims,
1054
+ ...(typeof fts_bm25 === 'number' ? { bm25Score: Math.max(fts_bm25, 1e-6) } : {}),
1055
+ };
1056
+ });
1057
+ }
1058
+
1059
+ const RECORD_SPECS: Record<MemoryRecordType, RecordTypeSpec> = {
1060
+ note: {
1061
+ table: 'notes',
1062
+ alias: 'n',
1063
+ ftsTable: 'fts_notes',
1064
+ hasEmbedding: true,
1065
+ scanOrderCol: 'n.updated_at',
1066
+ temporalExpr: (a) => `COALESCE(${a}.event_at, strftime('%Y-%m-%dT%H:%M:%fZ', ${a}.created_at, 'unixepoch'))`,
1067
+ buildExtraConditions: ({ params, asOfIso }) => {
1068
+ const conditions: string[] = [];
1069
+ const queryParams: unknown[] = [];
1070
+ if (params.include_history !== true) {
1071
+ conditions.push('n.is_latest = 1');
1072
+ }
1073
+ if (asOfIso) {
1074
+ conditions.push('(n.valid_from IS NULL OR n.valid_from <= ?) AND (n.valid_until IS NULL OR n.valid_until >= ?)');
1075
+ queryParams.push(asOfIso, asOfIso);
1076
+ }
1077
+ const effectiveTypes = resolveEffectiveNoteTypes(params);
1078
+ if (effectiveTypes !== null) {
1079
+ if (effectiveTypes.length === 0) {
1080
+ return { impossible: true, conditions, queryParams };
1081
+ }
1082
+ conditions.push(`n.type IN (${effectiveTypes.map(() => '?').join(',')})`);
1083
+ queryParams.push(...effectiveTypes);
1084
+ }
1085
+ const filePath = cleanOptionalString(params.filters?.file_path);
1086
+ if (filePath) {
1087
+ conditions.push('EXISTS (SELECT 1 FROM note_files nf WHERE nf.note_id = n.id AND nf.file_path = ?)');
1088
+ queryParams.push(filePath);
1089
+ }
1090
+ const agent = cleanOptionalString(params.filters?.agent);
1091
+ if (agent) {
1092
+ conditions.push('n.author = ?');
1093
+ queryParams.push(agent);
1094
+ }
1095
+ return { conditions, queryParams };
1096
+ },
1097
+ hydrate: hydrateNotes,
1098
+ },
1099
+
1100
+ trajectory: {
1101
+ table: 'trajectories',
1102
+ alias: 't',
1103
+ ftsTable: 'fts_trajectories',
1104
+ hasEmbedding: true,
1105
+ scanOrderCol: 't.created_at',
1106
+ temporalExpr: (a) => `strftime('%Y-%m-%dT%H:%M:%fZ', ${a}.created_at, 'unixepoch')`,
1107
+ buildExtraConditions: ({ params }) => {
1108
+ const conditions: string[] = [];
1109
+ const queryParams: unknown[] = [];
1110
+ const taskType = cleanOptionalString(params.filters?.task_type);
1111
+ if (taskType) {
1112
+ conditions.push('t.task_type = ?');
1113
+ queryParams.push(taskType);
1114
+ }
1115
+ const agent = cleanOptionalString(params.filters?.agent);
1116
+ if (agent) {
1117
+ conditions.push('t.agent = ?');
1118
+ queryParams.push(agent);
1119
+ }
1120
+ if (params.filters?.success !== undefined) {
1121
+ conditions.push('t.success = ?');
1122
+ queryParams.push(params.filters.success ? 1 : 0);
1123
+ }
1124
+ const noteRef = cleanOptionalString(params.filters?.note_ref);
1125
+ if (noteRef) {
1126
+ conditions.push('t.note_ref = ?');
1127
+ queryParams.push(noteRef);
1128
+ }
1129
+ const taskRef = cleanOptionalString(params.filters?.task_ref);
1130
+ if (taskRef) {
1131
+ conditions.push('t.task_ref = ?');
1132
+ queryParams.push(taskRef);
1133
+ }
1134
+ const sessionId = cleanOptionalString((params.filters as any)?.session_id);
1135
+ if (sessionId) {
1136
+ conditions.push('t.session_id = ?');
1137
+ queryParams.push(sessionId);
1138
+ }
1139
+ return { conditions, queryParams };
1140
+ },
1141
+ hydrate: (_db, rows) =>
1142
+ rows.map((row) => {
1143
+ const { embedding, fts_bm25, ...record } = row;
1144
+ const text = `${row.description || ''}\n${row.result || ''}\n${row.task_type || ''}`;
1145
+ return {
1146
+ id: row.id,
1147
+ record_type: 'trajectory' as const,
1148
+ record,
1149
+ text,
1150
+ embedding: embedding ?? null,
1151
+ ...(typeof fts_bm25 === 'number' ? { bm25Score: Math.max(fts_bm25, 1e-6) } : {}),
1152
+ };
1153
+ }),
1154
+ },
1155
+
1156
+ observation: {
1157
+ table: 'observations',
1158
+ alias: 'o',
1159
+ ftsTable: 'fts_observations',
1160
+ hasEmbedding: false,
1161
+ scanOrderCol: 'o.created_at',
1162
+ temporalExpr: (a) => `COALESCE(${a}.event_at, strftime('%Y-%m-%dT%H:%M:%fZ', ${a}.created_at, 'unixepoch'))`,
1163
+ buildExtraConditions: ({ params }) => {
1164
+ const conditions: string[] = [];
1165
+ const queryParams: unknown[] = [];
1166
+ const kind = cleanOptionalString(params.filters?.kind);
1167
+ if (kind) {
1168
+ conditions.push('o.kind = ?');
1169
+ queryParams.push(kind);
1170
+ }
1171
+ const filePath = cleanOptionalString(params.filters?.file_path);
1172
+ if (filePath) {
1173
+ conditions.push('o.file_path = ?');
1174
+ queryParams.push(filePath);
1175
+ }
1176
+ const agent = cleanOptionalString(params.filters?.agent);
1177
+ if (agent) {
1178
+ conditions.push('o.agent = ?');
1179
+ queryParams.push(agent);
1180
+ }
1181
+ if (params.filters?.success !== undefined) {
1182
+ conditions.push('o.failed = ?');
1183
+ queryParams.push(params.filters.success ? 0 : 1);
1184
+ }
1185
+ const noteRef = cleanOptionalString(params.filters?.note_ref);
1186
+ if (noteRef) {
1187
+ conditions.push('o.note_ref = ?');
1188
+ queryParams.push(noteRef);
1189
+ }
1190
+ const taskRef = cleanOptionalString(params.filters?.task_ref);
1191
+ if (taskRef) {
1192
+ conditions.push('o.task_ref = ?');
1193
+ queryParams.push(taskRef);
1194
+ }
1195
+ const sessionId = cleanOptionalString((params.filters as any)?.session_id);
1196
+ if (sessionId) {
1197
+ conditions.push('o.session_id = ?');
1198
+ queryParams.push(sessionId);
1199
+ }
1200
+ const signalTag = cleanOptionalString(params.filters?.signal_tag);
1201
+ if (signalTag) {
1202
+ conditions.push(
1203
+ "o.signal_tags IS NOT NULL AND json_valid(o.signal_tags) = 1 AND json_type(o.signal_tags) = 'array' AND EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(o.signal_tags) = 1 AND json_type(o.signal_tags) = 'array' THEN o.signal_tags ELSE '[]' END) je WHERE je.type = 'text' AND je.value = ?)"
1204
+ );
1205
+ queryParams.push(signalTag);
1206
+ }
1207
+ return { conditions, queryParams };
1208
+ },
1209
+ hydrate: (_db, rows) =>
1210
+ rows.map((row) => {
1211
+ const { fts_bm25, ...record } = row;
1212
+ const text = `${row.tool_name || ''}\n${row.file_path || ''}\n${row.input || ''}\n${row.output || ''}\n${row.condensed_text || ''}`;
1213
+ return {
1214
+ id: row.id,
1215
+ record_type: 'observation' as const,
1216
+ record,
1217
+ text,
1218
+ embedding: null,
1219
+ ...(typeof fts_bm25 === 'number' ? { bm25Score: Math.max(fts_bm25, 1e-6) } : {}),
1220
+ };
1221
+ }),
1222
+ },
1223
+
1224
+ summary: {
1225
+ table: 'summaries',
1226
+ alias: 's',
1227
+ ftsTable: 'fts_summaries',
1228
+ hasEmbedding: true,
1229
+ scanOrderCol: 's.created_at',
1230
+ temporalExpr: (a) => `strftime('%Y-%m-%dT%H:%M:%fZ', ${a}.created_at, 'unixepoch')`,
1231
+ buildExtraConditions: ({ params }) => {
1232
+ const conditions: string[] = [];
1233
+ const queryParams: unknown[] = [];
1234
+ if (params.include_history !== true) {
1235
+ conditions.push('s.is_latest = 1');
1236
+ }
1237
+ const kind = cleanOptionalString(params.filters?.kind);
1238
+ if (kind) {
1239
+ conditions.push('s.kind = ?');
1240
+ queryParams.push(kind);
1241
+ }
1242
+ const agent = cleanOptionalString(params.filters?.agent);
1243
+ if (agent) {
1244
+ conditions.push('(s.producer_model = ? OR s.producer_tier = ?)');
1245
+ queryParams.push(agent, agent);
1246
+ }
1247
+ if (params.filters?.success !== undefined) {
1248
+ conditions.push('s.outcome = ?');
1249
+ queryParams.push(params.filters.success ? 'success' : 'failure');
1250
+ }
1251
+ return { conditions, queryParams };
1252
+ },
1253
+ hydrate: hydrateSummaries,
1254
+ },
1255
+
1256
+ entity: {
1257
+ table: 'entities',
1258
+ alias: 'e',
1259
+ ftsTable: 'fts_entities',
1260
+ hasEmbedding: true,
1261
+ scanOrderCol: 'e.updated_at',
1262
+ temporalExpr: (a) => `strftime('%Y-%m-%dT%H:%M:%fZ', ${a}.created_at, 'unixepoch')`,
1263
+ buildExtraConditions: ({ params }) => {
1264
+ const conditions: string[] = [];
1265
+ const queryParams: unknown[] = [];
1266
+ const entityType = cleanOptionalString(params.filters?.entity_type);
1267
+ if (entityType) {
1268
+ conditions.push('e.entity_type = ?');
1269
+ queryParams.push(entityType);
1270
+ }
1271
+ return { conditions, queryParams };
1272
+ },
1273
+ hydrate: (_db, rows) =>
1274
+ rows.map((row) => {
1275
+ const { embedding, fts_bm25, ...record } = row;
1276
+ const text = [row.entity_type, row.name, row.description, row.external_ref]
1277
+ .filter(Boolean)
1278
+ .join('\n');
1279
+ return {
1280
+ id: row.id,
1281
+ record_type: 'entity' as const,
1282
+ record,
1283
+ text,
1284
+ embedding: embedding ?? null,
1285
+ ...(typeof fts_bm25 === 'number' ? { bm25Score: Math.max(fts_bm25, 1e-6) } : {}),
1286
+ };
1287
+ }),
1288
+ },
1289
+
1290
+ action: {
1291
+ table: 'actions',
1292
+ alias: 'a',
1293
+ ftsTable: 'fts_actions',
1294
+ hasEmbedding: true,
1295
+ scanOrderCol: 'a.created_at',
1296
+ temporalExpr: (al) => `COALESCE(${al}.due_at, strftime('%Y-%m-%dT%H:%M:%fZ', ${al}.created_at))`,
1297
+ buildExtraConditions: ({ params }) => {
1298
+ const conditions: string[] = [];
1299
+ const queryParams: unknown[] = [];
1300
+ const kind = cleanOptionalString(params.filters?.kind);
1301
+ if (kind) {
1302
+ conditions.push('a.status = ?');
1303
+ queryParams.push(kind);
1304
+ }
1305
+ const cleanPriorities = Array.isArray(params.filters?.type)
1306
+ ? params.filters.type.map(cleanOptionalString).filter((t): t is string => t !== null)
1307
+ : [];
1308
+ if (cleanPriorities.length > 0) {
1309
+ conditions.push(`a.priority IN (${cleanPriorities.map(() => '?').join(',')})`);
1310
+ queryParams.push(...cleanPriorities);
1311
+ }
1312
+ const sessionId = cleanOptionalString((params.filters as any)?.session_id);
1313
+ if (sessionId) {
1314
+ conditions.push('a.session_id = ?');
1315
+ queryParams.push(sessionId);
1316
+ }
1317
+ return { conditions, queryParams };
1318
+ },
1319
+ hydrate: (_db, rows) =>
1320
+ rows.map((row) => {
1321
+ const { embedding, fts_bm25, ...record } = row;
1322
+ const text = [row.title, row.description, row.blocked_reason].filter(Boolean).join('\n');
1323
+ return {
1324
+ id: row.id,
1325
+ record_type: 'action' as const,
1326
+ record,
1327
+ text,
1328
+ embedding: embedding ?? null,
1329
+ ...(typeof fts_bm25 === 'number' ? { bm25Score: Math.max(fts_bm25, 1e-6) } : {}),
1330
+ };
1331
+ }),
1332
+ },
1333
+ };
1334
+
1335
+ function buildWhereForType(
1336
+ spec: RecordTypeSpec,
1337
+ ctx: FilterContext
1338
+ ): SqlConditionsResult {
1339
+ const scopeSql = buildHierarchicalScopeSql({
1340
+ tableAlias: spec.alias,
1341
+ scope: ctx.params.scope,
1342
+ projectId: cleanOptionalString(ctx.params.project_id),
1343
+ includeAncestors: ctx.includeAncestors,
1344
+ includeChildren: ctx.includeChildren,
1345
+ includeGlobal: ctx.includeGlobal,
1346
+ userId: ctx.userId,
1347
+ });
1348
+
1349
+ const conditions: string[] = [scopeSql.clause];
1350
+ const queryParams: unknown[] = [...scopeSql.params];
1351
+
1352
+ if (ctx.afterIso) {
1353
+ conditions.push(`${spec.temporalExpr(spec.alias)} >= ?`);
1354
+ queryParams.push(ctx.afterIso);
1355
+ }
1356
+ if (ctx.beforeIso) {
1357
+ conditions.push(`${spec.temporalExpr(spec.alias)} <= ?`);
1358
+ queryParams.push(ctx.beforeIso);
1359
+ }
1360
+
1361
+ const extra = spec.buildExtraConditions(ctx);
1362
+ if (extra.impossible) {
1363
+ return { impossible: true, conditions, queryParams };
1364
+ }
1365
+ conditions.push(...extra.conditions);
1366
+ queryParams.push(...extra.queryParams);
1367
+
1368
+ return { conditions, queryParams };
1369
+ }
1370
+
1371
+ function getBm25Expr(recordType: MemoryRecordType, queryIntent: QueryKindIntent): string {
1372
+ switch (recordType) {
1373
+ case 'observation':
1374
+ if (queryIntent === 'assistant') {
1375
+ return '-bm25(fts_observations, 0.0, 1.2, 1.2, 1.0, 1.4, 1.6)';
1376
+ }
1377
+ if (queryIntent === 'tool') {
1378
+ return '-bm25(fts_observations, 0.0, 2.0, 2.2, 1.4, 1.0, 1.5)';
1379
+ }
1380
+ return '-bm25(fts_observations, 0.0, 1.5, 1.6, 1.6, 0.75, 1.8)';
1381
+ case 'note':
1382
+ return '-bm25(fts_notes, 0.0, 2.2, 1.0, 1.6)';
1383
+ case 'trajectory':
1384
+ return '-bm25(fts_trajectories, 0.0, 1.6, 1.0, 1.4)';
1385
+ case 'summary':
1386
+ return '-bm25(fts_summaries, 0.0, 1.0)';
1387
+ case 'entity':
1388
+ return '-bm25(fts_entities, 0.0, 2.5, 1.4, 1.0, 1.8)';
1389
+ case 'action':
1390
+ return '-bm25(fts_actions, 0.0, 2.0, 1.0, 1.2)';
1391
+ }
1392
+ }
1393
+
1394
+ function queryTypeFts(
1395
+ db: ReturnType<typeof getDb>,
1396
+ recordType: MemoryRecordType,
1397
+ ctx: FilterContext,
1398
+ safeFtsQuery: string,
1399
+ strictFtsQuery: string | null,
1400
+ ftsLimit: number
1401
+ ): CandidateDoc[] {
1402
+ const spec = RECORD_SPECS[recordType];
1403
+ if (!spec) return [];
1404
+ const built = buildWhereForType(spec, ctx);
1405
+ if (built.impossible) return [];
1406
+
1407
+ const bm25Expr = getBm25Expr(recordType, ctx.queryIntent);
1408
+ const sql = `
1409
+ SELECT ${spec.alias}.*, ${bm25Expr} AS fts_bm25
1410
+ FROM ${spec.ftsTable}
1411
+ JOIN ${spec.table} ${spec.alias} ON ${spec.alias}.id = ${spec.ftsTable}.record_id
1412
+ WHERE ${spec.ftsTable} MATCH ? AND ${built.conditions.join(' AND ')}
1413
+ ORDER BY fts_bm25 DESC
1414
+ LIMIT ?
1415
+ `;
1416
+ const stmt = db.prepare(sql);
1417
+ const relaxedRows = stmt.all(safeFtsQuery, ...built.queryParams, ftsLimit) as any[];
1418
+
1419
+ if (!strictFtsQuery) {
1420
+ return spec.hydrate(db, relaxedRows);
1421
+ }
1422
+
1423
+ const strictLimit = Math.min(ftsLimit, 100);
1424
+ const strictRows = stmt.all(strictFtsQuery, ...built.queryParams, strictLimit) as any[];
1425
+ if (strictRows.length === 0) {
1426
+ return spec.hydrate(db, relaxedRows);
1427
+ }
1428
+
1429
+ const mergedById = new Map<string, any>();
1430
+ for (const r of relaxedRows) {
1431
+ mergedById.set(r.id, r);
1432
+ }
1433
+
1434
+ for (const sRow of strictRows) {
1435
+ const strictBm25 = Math.max(Number(sRow.fts_bm25) || 0, 1e-6);
1436
+ const existing = mergedById.get(sRow.id);
1437
+ if (existing) {
1438
+ const relaxedBm25 = Math.max(Number(existing.fts_bm25) || 0, 1e-6);
1439
+ existing.fts_bm25 = Math.max(strictBm25 * 1.6, relaxedBm25 * 1.35);
1440
+ } else {
1441
+ mergedById.set(sRow.id, {
1442
+ ...sRow,
1443
+ fts_bm25: strictBm25 * 1.6,
1444
+ });
74
1445
  }
75
1446
  }
76
1447
 
77
- // Metadata filters
78
- if (params.filters?.type && params.filters.type.length > 0) {
79
- must.push(
80
- params.filters.type.length === 1
81
- ? { key: 'type', match: { value: params.filters.type[0] } }
82
- : { key: 'type', match: { any: params.filters.type } }
1448
+ const mergedRows = Array.from(mergedById.values())
1449
+ .sort((a, b) => (Number(b.fts_bm25) || 0) - (Number(a.fts_bm25) || 0))
1450
+ .slice(0, ftsLimit);
1451
+
1452
+ return spec.hydrate(db, mergedRows);
1453
+ }
1454
+
1455
+ function queryTypeEmbeddedScan(
1456
+ db: ReturnType<typeof getDb>,
1457
+ recordType: MemoryRecordType,
1458
+ ctx: FilterContext,
1459
+ scanLimit = 500
1460
+ ): CandidateDoc[] {
1461
+ const spec = RECORD_SPECS[recordType];
1462
+ if (!spec || !spec.hasEmbedding) return [];
1463
+ const built = buildWhereForType(spec, ctx);
1464
+ if (built.impossible) return [];
1465
+
1466
+ const sql = `
1467
+ SELECT ${spec.alias}.*
1468
+ FROM ${spec.table} ${spec.alias}
1469
+ WHERE ${spec.alias}.embedding IS NOT NULL AND ${built.conditions.join(' AND ')}
1470
+ ORDER BY ${spec.scanOrderCol} DESC
1471
+ LIMIT ?
1472
+ `;
1473
+ const rows = db.prepare(sql).all(...built.queryParams, scanLimit) as any[];
1474
+ return spec.hydrate(db, rows);
1475
+ }
1476
+
1477
+ function queryTypeByIds(
1478
+ db: ReturnType<typeof getDb>,
1479
+ recordType: MemoryRecordType,
1480
+ ctx: FilterContext,
1481
+ ids: string[]
1482
+ ): CandidateDoc[] {
1483
+ if (ids.length === 0) return [];
1484
+ const spec = RECORD_SPECS[recordType];
1485
+ if (!spec) return [];
1486
+ const built = buildWhereForType(spec, ctx);
1487
+ if (built.impossible) return [];
1488
+
1489
+ const placeholders = ids.map(() => '?').join(',');
1490
+ const sql = `
1491
+ SELECT ${spec.alias}.*
1492
+ FROM ${spec.table} ${spec.alias}
1493
+ WHERE ${built.conditions.join(' AND ')} AND ${spec.alias}.id IN (${placeholders})
1494
+ `;
1495
+ const rows = db.prepare(sql).all(...built.queryParams, ...ids) as any[];
1496
+ return spec.hydrate(db, rows);
1497
+ }
1498
+
1499
+ function assignCompetitionRanks<T>(
1500
+ items: T[],
1501
+ getKey: (item: T) => string,
1502
+ getScore: (item: T) => number
1503
+ ): Map<string, number> {
1504
+ const sorted = [...items].sort((a, b) => getScore(b) - getScore(a));
1505
+ const rankMap = new Map<string, number>();
1506
+ let prevScore: number | null = null;
1507
+ let prevRank = 1;
1508
+ for (let i = 0; i < sorted.length; i++) {
1509
+ const score = getScore(sorted[i]);
1510
+ const rank = prevScore !== null && Math.abs(score - prevScore) <= 1e-9 ? prevRank : i + 1;
1511
+ rankMap.set(getKey(sorted[i]), rank);
1512
+ prevScore = score;
1513
+ prevRank = rank;
1514
+ }
1515
+ return rankMap;
1516
+ }
1517
+
1518
+ interface EntitySeed {
1519
+ entityName: string;
1520
+ entityScore: number;
1521
+ }
1522
+
1523
+ function findEntitySeeds(
1524
+ db: ReturnType<typeof getDb>,
1525
+ ctx: FilterContext,
1526
+ safeFtsQuery: string | null,
1527
+ strictFtsQuery: string | null,
1528
+ mode: 'hybrid' | 'bm25',
1529
+ queryVec: number[],
1530
+ denseScoresMap: Map<string, number>
1531
+ ): Map<string, EntitySeed> {
1532
+ const scopeSql = buildHierarchicalScopeSql({
1533
+ tableAlias: 'e',
1534
+ scope: ctx.params.scope,
1535
+ projectId: cleanOptionalString(ctx.params.project_id),
1536
+ includeAncestors: ctx.includeAncestors,
1537
+ includeChildren: ctx.includeChildren,
1538
+ includeGlobal: ctx.includeGlobal,
1539
+ userId: ctx.userId,
1540
+ });
1541
+
1542
+ const conditions: string[] = [scopeSql.clause];
1543
+ const queryParams: unknown[] = [...scopeSql.params];
1544
+ const entityType = cleanOptionalString(ctx.params.filters?.entity_type);
1545
+ if (entityType) {
1546
+ conditions.push('e.entity_type = ?');
1547
+ queryParams.push(entityType);
1548
+ }
1549
+
1550
+ const nameById = new Map<string, string>();
1551
+ const ftsScoreById = new Map<string, number>();
1552
+ if (safeFtsQuery) {
1553
+ const entFtsStmt = db.prepare(
1554
+ `
1555
+ SELECT e.id, e.name, -bm25(fts_entities, 0.0, 2.5, 1.4, 1.0, 1.8) AS fts_bm25
1556
+ FROM fts_entities
1557
+ JOIN entities e ON e.id = fts_entities.record_id
1558
+ WHERE fts_entities MATCH ? AND ${conditions.join(' AND ')}
1559
+ ORDER BY fts_bm25 DESC
1560
+ LIMIT 30
1561
+ `
83
1562
  );
1563
+ const ftsRows = entFtsStmt.all(safeFtsQuery, ...queryParams) as Array<{
1564
+ id: string;
1565
+ name: string;
1566
+ fts_bm25: number;
1567
+ }>;
1568
+
1569
+ for (const r of ftsRows) {
1570
+ nameById.set(r.id, r.name);
1571
+ ftsScoreById.set(r.id, Math.max(Number(r.fts_bm25) || 0, 1e-6));
1572
+ }
1573
+
1574
+ if (strictFtsQuery) {
1575
+ const strictEntRows = entFtsStmt.all(strictFtsQuery, ...queryParams) as Array<{
1576
+ id: string;
1577
+ name: string;
1578
+ fts_bm25: number;
1579
+ }>;
1580
+ for (const r of strictEntRows) {
1581
+ nameById.set(r.id, r.name);
1582
+ const strictBm25 = Math.max(Number(r.fts_bm25) || 0, 1e-6);
1583
+ const relaxedBm25 = ftsScoreById.get(r.id) ?? 0;
1584
+ ftsScoreById.set(r.id, Math.max(strictBm25 * 1.6, relaxedBm25 * 1.35));
1585
+ }
1586
+ }
84
1587
  }
85
- if (params.filters?.kind) {
86
- must.push({ key: 'kind', match: { value: params.filters.kind.trim() } });
87
- }
88
- if (params.filters?.task_type) {
89
- must.push({ key: 'task_type', match: { value: params.filters.task_type.trim() } });
90
- }
91
- if (params.filters?.file_path) {
92
- must.push({ key: 'file_path', match: { value: params.filters.file_path.trim() } });
93
- }
94
- if (params.filters?.agent) {
95
- must.push({ key: 'agent', match: { value: params.filters.agent.trim() } });
96
- }
97
- if (params.filters?.success !== undefined) {
98
- must.push({ key: 'success', match: { value: !!params.filters.success } });
99
- }
100
- if (params.filters?.note_ref) {
101
- must.push({ key: 'note_ref', match: { value: params.filters.note_ref.trim() } });
1588
+ const ftsHits: Array<{ id: string; score: number }> = Array.from(ftsScoreById.entries()).map(
1589
+ ([id, score]) => ({ id, score })
1590
+ );
1591
+
1592
+ const denseHitsMap = new Map<string, number>();
1593
+ if (mode === 'hybrid' && queryVec.length > 0) {
1594
+ const embRows = db
1595
+ .prepare(
1596
+ `
1597
+ SELECT e.id, e.name, e.embedding
1598
+ FROM entities e
1599
+ WHERE e.embedding IS NOT NULL AND ${conditions.join(' AND ')}
1600
+ ORDER BY e.updated_at DESC
1601
+ LIMIT 500
1602
+ `
1603
+ )
1604
+ .all(...queryParams) as Array<{ id: string; name: string; embedding: Buffer }>;
1605
+
1606
+ for (const r of embRows) {
1607
+ const qdrantScore = denseScoresMap.get(docKey('entity', r.id));
1608
+ const sim = qdrantScore !== undefined
1609
+ ? qdrantScore
1610
+ : cosineSimilarity(queryVec, deserializeEmbedding(r.embedding));
1611
+ if (sim >= MIN_ENTITY_DENSE_SIM) {
1612
+ nameById.set(r.id, r.name);
1613
+ denseHitsMap.set(r.id, sim);
1614
+ }
1615
+ }
102
1616
  }
103
- if (params.filters?.task_ref) {
104
- must.push({ key: 'task_ref', match: { value: params.filters.task_ref.trim() } });
1617
+
1618
+ if (ftsHits.length === 0 && denseHitsMap.size === 0) {
1619
+ return new Map();
105
1620
  }
106
- if ((params.filters as any)?.session_id) {
107
- must.push({ key: 'session_id', match: { value: (params.filters as any).session_id.trim() } });
1621
+
1622
+ const ftsRankMap = assignCompetitionRanks(ftsHits, (x) => x.id, (x) => x.score);
1623
+ const denseHits = Array.from(denseHitsMap.entries()).map(([id, score]) => ({ id, score }));
1624
+ const denseRankMap = assignCompetitionRanks(denseHits, (x) => x.id, (x) => x.score);
1625
+
1626
+ const scored: Array<{ id: string; entityName: string; entityScore: number }> = [];
1627
+ for (const [id, entityName] of nameById.entries()) {
1628
+ const rFts = ftsRankMap.get(id);
1629
+ const rDense = denseRankMap.get(id);
1630
+ const entityScore =
1631
+ (rFts !== undefined ? 1 / (RRF_K + rFts) : 0) +
1632
+ (rDense !== undefined ? 1 / (RRF_K + rDense) : 0);
1633
+ if (entityScore > 0) {
1634
+ scored.push({ id, entityName, entityScore });
1635
+ }
108
1636
  }
109
1637
 
110
- if (must.length === 0) return undefined;
111
- return { must };
1638
+ scored.sort((a, b) => b.entityScore - a.entityScore);
1639
+ const seeds = new Map<string, EntitySeed>();
1640
+ for (const item of scored.slice(0, MAX_ENTITY_SEEDS)) {
1641
+ seeds.set(item.id, { entityName: item.entityName, entityScore: item.entityScore });
1642
+ }
1643
+ return seeds;
112
1644
  }
113
1645
 
114
- export async function hybridSearch(params: SearchRequest): Promise<SearchResponse> {
115
- const q = params.q?.trim() || '';
116
- const requestedTypes =
117
- params.record_types && params.record_types.length > 0
118
- ? params.record_types
119
- : params.grains;
120
- const grains =
121
- requestedTypes && requestedTypes.length > 0 ? requestedTypes : ['note', 'trajectory'];
122
- const limit = Math.min(Math.max(params.limit ?? 10, 1), 100);
123
- const includeGlobal = params.include_global !== false;
124
- const db = getDb();
125
-
126
- // Scope filter helper
127
- const buildScopeClause = (tablePrefix: string): { clause: string; params: unknown[] } => {
128
- const colScope = tablePrefix ? `${tablePrefix}.scope` : 'scope';
129
- const colProject = tablePrefix ? `${tablePrefix}.project_id` : 'project_id';
1646
+ function normalizeEdgeRecordType(edgeNodeType: string): MemoryRecordType | null {
1647
+ if (edgeNodeType === 'lesson') return 'note';
1648
+ return VALID_RECORD_TYPES.has(edgeNodeType as MemoryRecordType)
1649
+ ? (edgeNodeType as MemoryRecordType)
1650
+ : null;
1651
+ }
130
1652
 
131
- if (params.scope === 'unknown') {
132
- return { clause: `${colScope} = 'unknown'`, params: [] };
1653
+ function collectChildProjectIds(db: ReturnType<typeof getDb>, normalizedProjectId: string): string[] {
1654
+ const range = getProjectChildRange(normalizedProjectId);
1655
+ const tables = ['notes', 'trajectories', 'observations', 'summaries', 'entities', 'actions'];
1656
+ const ids = new Set<string>();
1657
+ for (const table of tables) {
1658
+ const rows = db
1659
+ .prepare(
1660
+ `SELECT DISTINCT project_id FROM ${table} WHERE scope = 'project' AND project_id >= ? AND project_id < ?`
1661
+ )
1662
+ .all(range.gte, range.lt) as Array<{ project_id: string }>;
1663
+ for (const r of rows) {
1664
+ if (r.project_id) ids.add(r.project_id);
133
1665
  }
1666
+ }
1667
+ return Array.from(ids);
1668
+ }
134
1669
 
135
- if (params.scope === 'global' || !params.project_id) {
136
- return { clause: `${colScope} = 'global'`, params: [] };
137
- }
1670
+ function computeTierMultiplier(
1671
+ matchTier: MatchTier,
1672
+ ancestorDistance: number | undefined,
1673
+ hasQueryProject: boolean
1674
+ ): number {
1675
+ if (!hasQueryProject) return 1.0;
1676
+ switch (matchTier) {
1677
+ case 'exact':
1678
+ return 1.15;
1679
+ case 'ancestor':
1680
+ return 1.0 + 0.1 / Math.max(1, ancestorDistance ?? 1);
1681
+ case 'global':
1682
+ return 1.02;
1683
+ case 'child':
1684
+ return 0.98;
1685
+ default:
1686
+ return 1.0;
1687
+ }
1688
+ }
138
1689
 
139
- if (params.project_id) {
140
- if (includeGlobal) {
141
- return {
142
- clause: `((${colScope} = 'project' AND ${colProject} = ?) OR ${colScope} = 'global')`,
143
- params: [params.project_id],
144
- };
145
- } else {
146
- return {
147
- clause: `(${colScope} = 'project' AND ${colProject} = ?)`,
148
- params: [params.project_id],
149
- };
150
- }
151
- }
1690
+ function getCandidateCreatedMs(c: CandidateDoc): number | null {
1691
+ if ((c.record_type === 'note' || c.record_type === 'observation') && c.record.event_at) {
1692
+ const eventMs = parseTimestampMs(c.record.event_at);
1693
+ if (eventMs !== null) return eventMs;
1694
+ }
1695
+ return parseTimestampMs(c.record.created_at);
1696
+ }
152
1697
 
153
- return { clause: `${colScope} != 'unknown'`, params: [] };
154
- };
1698
+ const YMD_STRICT_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
155
1699
 
156
- const candidates: CandidateDoc[] = [];
1700
+ function parseYmdUtcMs(ymd: unknown, hour: number, min: number, sec: number, ms: number): number | null {
1701
+ if (typeof ymd !== 'string') return null;
1702
+ const m = YMD_STRICT_RE.exec(ymd.trim());
1703
+ if (!m) return null;
1704
+ const year = parseInt(m[1], 10);
1705
+ const month = parseInt(m[2], 10);
1706
+ const day = parseInt(m[3], 10);
1707
+ if (month < 1 || month > 12 || day < 1 || day > 31) return null;
1708
+ return Date.UTC(year, month - 1, day, hour, min, sec, ms);
1709
+ }
157
1710
 
158
- // 1. Fetch candidate records from SQLite
159
- if (grains.includes('note')) {
160
- const scopeFilter = buildScopeClause('n');
161
- const conditions: string[] = ['n.is_latest = 1', scopeFilter.clause];
162
- const queryParams: unknown[] = [...scopeFilter.params];
1711
+ function parseResolvedDateAnnotations(rawJson: unknown): ResolvedDateAnnotation[] {
1712
+ if (typeof rawJson !== 'string' || rawJson.trim() === '') return [];
1713
+ try {
1714
+ const parsed = JSON.parse(rawJson);
1715
+ if (!Array.isArray(parsed)) return [];
1716
+ return parsed.filter(
1717
+ (el): el is ResolvedDateAnnotation =>
1718
+ Boolean(el) &&
1719
+ typeof el === 'object' &&
1720
+ !Array.isArray(el) &&
1721
+ typeof (el as Record<string, unknown>).resolved_date === 'string'
1722
+ );
1723
+ } catch {
1724
+ return [];
1725
+ }
1726
+ }
163
1727
 
164
- if (params.filters?.type && params.filters.type.length > 0) {
165
- const placeholders = params.filters.type.map(() => '?').join(',');
166
- conditions.push(`n.type IN (${placeholders})`);
167
- queryParams.push(...params.filters.type);
168
- }
169
- if (params.filters?.file_path) {
170
- conditions.push(
171
- `EXISTS (SELECT 1 FROM note_files nf WHERE nf.note_id = n.id AND nf.file_path = ?)`
172
- );
173
- queryParams.push(params.filters.file_path.trim());
174
- }
175
- if (params.filters?.agent) {
176
- conditions.push(`n.author = ?`);
177
- queryParams.push(params.filters.agent.trim());
178
- }
1728
+ export function parseSignalTags(raw: unknown): string[] {
1729
+ if (Array.isArray(raw)) {
1730
+ return raw.filter((el): el is string => typeof el === 'string' && el.length > 0);
1731
+ }
1732
+ if (typeof raw !== 'string' || raw.trim() === '') return [];
1733
+ try {
1734
+ const parsed = JSON.parse(raw);
1735
+ if (!Array.isArray(parsed)) return [];
1736
+ return parsed.filter((el): el is string => typeof el === 'string' && el.length > 0);
1737
+ } catch {
1738
+ return [];
1739
+ }
1740
+ }
179
1741
 
180
- const rows = db
181
- .prepare(`SELECT * FROM notes n WHERE ${conditions.join(' AND ')} ORDER BY n.created_at DESC LIMIT 500`)
182
- .all(...queryParams) as any[];
183
-
184
- if (rows.length > 0) {
185
- const noteIds = rows.map((r) => r.id);
186
- const placeholders = noteIds.map(() => '?').join(',');
187
-
188
- const allConcepts = db
189
- .prepare(`SELECT note_id, concept FROM note_concepts WHERE note_id IN (${placeholders})`)
190
- .all(...noteIds) as Array<{ note_id: string; concept: string }>;
191
- const conceptsByNoteId = new Map<string, string[]>();
192
- for (const row of allConcepts) {
193
- let list = conceptsByNoteId.get(row.note_id);
194
- if (!list) {
195
- list = [];
196
- conceptsByNoteId.set(row.note_id, list);
1742
+ function getBestTemporalWindowDistanceMs(
1743
+ c: CandidateDoc,
1744
+ parsedWindow: ParsedTemporalWindow
1745
+ ): number | null {
1746
+ const createdMs = getCandidateCreatedMs(c);
1747
+ let bestDist: number | null =
1748
+ createdMs !== null ? Math.abs(createdMs - parsedWindow.centerMs) : null;
1749
+
1750
+ if (c.record_type === 'observation' && c.record.resolved_dates_json) {
1751
+ const annotations = parseResolvedDateAnnotations(c.record.resolved_dates_json);
1752
+ for (const ann of annotations) {
1753
+ let dist: number | null = null;
1754
+ if (ann.granularity !== 'day' && ann.window_start && ann.window_end) {
1755
+ const sMs = parseYmdUtcMs(ann.window_start, 0, 0, 0, 0);
1756
+ const eMs = parseYmdUtcMs(ann.window_end, 23, 59, 59, 999);
1757
+ if (sMs !== null && eMs !== null) {
1758
+ if (parsedWindow.centerMs >= sMs && parsedWindow.centerMs <= eMs) {
1759
+ dist = Math.min(parsedWindow.halfWidthMs * 0.25, (eMs - sMs) * 0.1);
1760
+ } else {
1761
+ dist =
1762
+ parsedWindow.centerMs < sMs
1763
+ ? sMs - parsedWindow.centerMs
1764
+ : parsedWindow.centerMs - eMs;
1765
+ }
197
1766
  }
198
- list.push(row.concept);
199
- }
200
-
201
- const allFiles = db
202
- .prepare(`SELECT note_id, file_path FROM note_files WHERE note_id IN (${placeholders})`)
203
- .all(...noteIds) as Array<{ note_id: string; file_path: string }>;
204
- const filesByNoteId = new Map<string, string[]>();
205
- for (const row of allFiles) {
206
- let list = filesByNoteId.get(row.note_id);
207
- if (!list) {
208
- list = [];
209
- filesByNoteId.set(row.note_id, list);
1767
+ } else if (ann.resolved_date) {
1768
+ const midMs = parseYmdUtcMs(ann.resolved_date, 12, 0, 0, 0);
1769
+ if (midMs !== null) {
1770
+ dist = Math.abs(midMs - parsedWindow.centerMs);
210
1771
  }
211
- list.push(row.file_path);
212
1772
  }
213
1773
 
214
- for (const row of rows) {
215
- const concepts = conceptsByNoteId.get(row.id) || [];
216
- const files = filesByNoteId.get(row.id) || [];
217
- const record = { ...row, concepts, files };
218
- const text = `${row.title}\n\n${row.content}\n${concepts.join(' ')}\n${files.join(' ')}`;
219
- candidates.push({
220
- id: row.id,
221
- grain: 'note',
222
- record,
223
- text,
224
- embedding: row.embedding,
225
- });
1774
+ if (dist !== null) {
1775
+ bestDist = bestDist === null ? dist : Math.min(bestDist, dist);
226
1776
  }
227
1777
  }
228
1778
  }
229
1779
 
230
- if (grains.includes('trajectory')) {
231
- const scopeFilter = buildScopeClause('t');
232
- const conditions: string[] = [scopeFilter.clause];
233
- const queryParams: unknown[] = [...scopeFilter.params];
1780
+ return bestDist;
1781
+ }
234
1782
 
235
- if (params.filters?.task_type) {
236
- conditions.push(`t.task_type = ?`);
237
- queryParams.push(params.filters.task_type.trim());
238
- }
239
- if (params.filters?.agent) {
240
- conditions.push(`t.agent = ?`);
241
- queryParams.push(params.filters.agent.trim());
242
- }
243
- if (params.filters?.success !== undefined) {
244
- conditions.push(`t.success = ?`);
245
- queryParams.push(params.filters.success ? 1 : 0);
246
- }
247
- if (params.filters?.note_ref) {
248
- conditions.push(`t.note_ref = ?`);
249
- queryParams.push(params.filters.note_ref.trim());
250
- }
251
- if (params.filters?.task_ref) {
252
- conditions.push(`t.task_ref = ?`);
253
- queryParams.push(params.filters.task_ref.trim());
254
- }
1783
+ function queryTemporalWindowCandidates(
1784
+ db: ReturnType<typeof getDb>,
1785
+ recordTypes: MemoryRecordType[],
1786
+ ctx: FilterContext,
1787
+ parsedWindow: ParsedTemporalWindow
1788
+ ): CandidateDoc[] {
1789
+ const out: CandidateDoc[] = [];
1790
+ const centerIso = new Date(parsedWindow.centerMs).toISOString();
1791
+ const windowStartDate = parsedWindow.windowStartIso.slice(0, 10);
1792
+ const windowEndDate = parsedWindow.windowEndIso.slice(0, 10);
255
1793
 
256
- const rows = db
257
- .prepare(`SELECT * FROM trajectories t WHERE ${conditions.join(' AND ')} ORDER BY t.created_at DESC LIMIT 500`)
258
- .all(...queryParams) as any[];
259
-
260
- for (const row of rows) {
261
- const text = `${row.description || ''}\n${row.result || ''}\n${row.task_type || ''}`;
262
- candidates.push({
263
- id: row.id,
264
- grain: 'trajectory',
265
- record: row,
266
- text,
267
- embedding: row.embedding,
268
- });
1794
+ const targetTypes: Array<'observation' | 'note'> = ['observation', 'note'];
1795
+ for (const rType of targetTypes) {
1796
+ if (!recordTypes.includes(rType)) continue;
1797
+ const spec = RECORD_SPECS[rType];
1798
+ const built = buildWhereForType(spec, ctx);
1799
+ if (built.impossible) continue;
1800
+
1801
+ const tExpr = spec.temporalExpr(spec.alias);
1802
+ const windowSql = `
1803
+ SELECT ${spec.alias}.*
1804
+ FROM ${spec.table} ${spec.alias}
1805
+ WHERE ${built.conditions.join(' AND ')}
1806
+ AND ${tExpr} >= ?
1807
+ AND ${tExpr} <= ?
1808
+ ORDER BY ABS(julianday(${tExpr}) - julianday(?)) ASC, ${spec.scanOrderCol} DESC
1809
+ LIMIT 150
1810
+ `;
1811
+ const windowRows = db
1812
+ .prepare(windowSql)
1813
+ .all(
1814
+ ...built.queryParams,
1815
+ parsedWindow.windowStartIso,
1816
+ parsedWindow.windowEndIso,
1817
+ centerIso
1818
+ ) as any[];
1819
+ out.push(...spec.hydrate(db, windowRows));
1820
+
1821
+ if (rType === 'observation') {
1822
+ const resolvedOverlapSql = `
1823
+ SELECT o.*
1824
+ FROM observations o
1825
+ WHERE ${built.conditions.join(' AND ')}
1826
+ AND o.resolved_dates_json IS NOT NULL
1827
+ AND json_valid(o.resolved_dates_json) = 1
1828
+ AND json_type(o.resolved_dates_json) = 'array'
1829
+ AND EXISTS (
1830
+ SELECT 1
1831
+ FROM json_each(
1832
+ CASE
1833
+ WHEN json_valid(o.resolved_dates_json) = 1 AND json_type(o.resolved_dates_json) = 'array'
1834
+ THEN o.resolved_dates_json
1835
+ ELSE '[]'
1836
+ END
1837
+ ) je
1838
+ WHERE je.type = 'object'
1839
+ AND COALESCE(
1840
+ CASE WHEN je.type = 'object' THEN json_extract(je.value, '$.window_start') END,
1841
+ CASE WHEN je.type = 'object' THEN json_extract(je.value, '$.resolved_date') END
1842
+ ) <= ?
1843
+ AND COALESCE(
1844
+ CASE WHEN je.type = 'object' THEN json_extract(je.value, '$.window_end') END,
1845
+ CASE WHEN je.type = 'object' THEN json_extract(je.value, '$.resolved_date') END
1846
+ ) >= ?
1847
+ )
1848
+ ORDER BY o.created_at DESC
1849
+ LIMIT 100
1850
+ `;
1851
+ const resolvedRows = db
1852
+ .prepare(resolvedOverlapSql)
1853
+ .all(...built.queryParams, windowEndDate, windowStartDate) as any[];
1854
+ out.push(...spec.hydrate(db, resolvedRows));
269
1855
  }
270
1856
  }
271
1857
 
272
- if (grains.includes('observation')) {
273
- const scopeFilter = buildScopeClause('o');
274
- const conditions: string[] = [scopeFilter.clause];
275
- const queryParams: unknown[] = [...scopeFilter.params];
1858
+ return out;
1859
+ }
276
1860
 
277
- if (params.filters?.kind) {
278
- conditions.push(`o.kind = ?`);
279
- queryParams.push(params.filters.kind.trim());
280
- }
281
- if (params.filters?.file_path) {
282
- conditions.push(`o.file_path = ?`);
283
- queryParams.push(params.filters.file_path.trim());
284
- }
285
- if (params.filters?.agent) {
286
- conditions.push(`o.agent = ?`);
287
- queryParams.push(params.filters.agent.trim());
288
- }
289
- if (params.filters?.success !== undefined) {
290
- conditions.push(`o.failed = ?`);
291
- queryParams.push(params.filters.success ? 0 : 1);
292
- }
293
- if (params.filters?.note_ref) {
294
- conditions.push(`o.note_ref = ?`);
295
- queryParams.push(params.filters.note_ref.trim());
296
- }
297
- if (params.filters?.task_ref) {
298
- conditions.push(`o.task_ref = ?`);
299
- queryParams.push(params.filters.task_ref.trim());
300
- }
1861
+ const TEMPORAL_RECALL_META_VERBS = new Set([
1862
+ 'mention',
1863
+ 'mentioned',
1864
+ 'mentions',
1865
+ 'say',
1866
+ 'said',
1867
+ 'tell',
1868
+ 'told',
1869
+ 'happen',
1870
+ 'happened',
1871
+ 'happening',
1872
+ 'talk',
1873
+ 'talked',
1874
+ 'discuss',
1875
+ 'discussed',
1876
+ 'remember',
1877
+ 'recall',
1878
+ 'log',
1879
+ 'logged',
1880
+ 'record',
1881
+ 'recorded',
1882
+ 'occur',
1883
+ 'occurred',
1884
+ ]);
301
1885
 
302
- const rows = db
303
- .prepare(`SELECT * FROM observations o WHERE ${conditions.join(' AND ')} ORDER BY o.created_at DESC LIMIT 500`)
304
- .all(...queryParams) as any[];
305
-
306
- for (const row of rows) {
307
- const text = `${row.tool_name || ''}\n${row.file_path || ''}\n${row.input || ''}\n${row.output || ''}`;
308
- candidates.push({
309
- id: row.id,
310
- grain: 'observation',
311
- record: row,
312
- text,
313
- embedding: null,
314
- });
315
- }
316
- }
1886
+ const EXPLICIT_CALENDAR_TOKEN_RE =
1887
+ /^(?:\d{4}|\d{1,2}|jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:t|tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?|q[1-4])$/i;
317
1888
 
318
- if (grains.includes('summary')) {
319
- const scopeFilter = buildScopeClause('s');
320
- const conditions: string[] = ['s.is_latest = 1', scopeFilter.clause];
321
- const queryParams: unknown[] = [...scopeFilter.params];
1889
+ function computeTemporalMultiplier(
1890
+ c: CandidateDoc,
1891
+ params: SearchRequest,
1892
+ nowMs: number,
1893
+ parsedWindow: ParsedTemporalWindow | null
1894
+ ): number {
1895
+ let mult = 1.0;
322
1896
 
323
- if (params.filters?.kind) {
324
- conditions.push(`s.kind = ?`);
325
- queryParams.push(params.filters.kind.trim());
326
- }
327
- if (params.filters?.agent) {
328
- conditions.push(`(s.producer_model = ? OR s.producer_tier = ?)`);
329
- queryParams.push(params.filters.agent.trim(), params.filters.agent.trim());
330
- }
331
- if (params.filters?.success !== undefined) {
332
- conditions.push(`s.outcome = ?`);
333
- queryParams.push(params.filters.success ? 'success' : 'failure');
1897
+ if (!params.as_of && !params.include_history && c.record_type === 'note' && c.record.valid_until) {
1898
+ const validUntilMs = parseTimestampMs(c.record.valid_until);
1899
+ if (validUntilMs !== null && validUntilMs < nowMs) {
1900
+ mult *= 0.75;
334
1901
  }
1902
+ }
335
1903
 
336
- const rows = db
337
- .prepare(`SELECT * FROM summaries s WHERE ${conditions.join(' AND ')} ORDER BY s.created_at DESC LIMIT 500`)
338
- .all(...queryParams) as any[];
339
-
340
- if (rows.length > 0) {
341
- const summaryIds = rows.map((r) => r.id);
342
- const placeholders = summaryIds.map(() => '?').join(',');
343
-
344
- const allClaims = db
345
- .prepare(`SELECT id, summary_id, text, ordinal FROM summary_claims WHERE summary_id IN (${placeholders}) ORDER BY ordinal ASC`)
346
- .all(...summaryIds) as Array<{ id: string; summary_id: string; text: string; ordinal: number }>;
347
- const claimsBySummaryId = new Map<string, Array<{ id: string; summary_id: string; text: string; ordinal: number }>>();
348
- for (const c of allClaims) {
349
- let list = claimsBySummaryId.get(c.summary_id);
350
- if (!list) {
351
- list = [];
352
- claimsBySummaryId.set(c.summary_id, list);
353
- }
354
- list.push(c);
355
- }
356
-
357
- const allSources = db
358
- .prepare(`SELECT summary_id, claim_id, record_id, grain FROM summary_sources WHERE summary_id IN (${placeholders})`)
359
- .all(...summaryIds) as Array<{ summary_id: string; claim_id: string; record_id: string; grain: string }>;
360
- const sourcesBySummaryId = new Map<string, Array<{ summary_id: string; claim_id: string; record_id: string; grain: string }>>();
361
- for (const s of allSources) {
362
- let list = sourcesBySummaryId.get(s.summary_id);
363
- if (!list) {
364
- list = [];
365
- sourcesBySummaryId.set(s.summary_id, list);
366
- }
367
- list.push(s);
1904
+ if (parsedWindow) {
1905
+ const distMs = getBestTemporalWindowDistanceMs(c, parsedWindow);
1906
+ if (distMs !== null) {
1907
+ const hw = Math.max(parsedWindow.halfWidthMs, 1);
1908
+ if (distMs <= hw) {
1909
+ // Inside [windowStart, windowEnd]: 1.40x at window center down to 1.22x at window edge
1910
+ mult *= 1.22 + 0.18 * Math.cos((Math.PI / 2) * (distMs / hw));
1911
+ } else if (distMs <= 2 * hw) {
1912
+ // 1x halfWidthMs grace zone: smooth cosine taper from 1.22x down to 1.0x
1913
+ const t = (distMs - hw) / hw;
1914
+ mult *= 1.0 + 0.22 * Math.cos((Math.PI / 2) * t);
368
1915
  }
1916
+ }
1917
+ }
369
1918
 
370
- for (const row of rows) {
371
- const claims = claimsBySummaryId.get(row.id) || [];
372
- const sources = sourcesBySummaryId.get(row.id) || [];
373
- const record = { ...row, claims, sources };
374
- const text = claims.map((c) => c.text).join('\n');
375
- candidates.push({
376
- id: row.id,
377
- grain: 'summary',
378
- record,
379
- text,
380
- embedding: row.embedding,
381
- });
1919
+ if (params.temporal_bias === 'recent') {
1920
+ const createdMs = getCandidateCreatedMs(c);
1921
+ if (createdMs !== null) {
1922
+ const ageDays = Math.max(0, (nowMs - createdMs) / 86_400_000);
1923
+ mult *= 1.0 + 0.08 / (1 + ageDays / 30);
1924
+ }
1925
+ } else if (params.temporal_bias === 'upcoming') {
1926
+ if (c.record_type === 'action' && c.record.due_at) {
1927
+ const dueMs = parseTimestampMs(c.record.due_at);
1928
+ if (dueMs !== null && dueMs >= nowMs) {
1929
+ mult *= 1.12;
1930
+ }
1931
+ } else if ((c.record_type === 'note' || c.record_type === 'observation') && c.record.event_at) {
1932
+ const eventMs = parseTimestampMs(c.record.event_at);
1933
+ if (eventMs !== null && eventMs >= nowMs) {
1934
+ mult *= 1.08;
382
1935
  }
383
1936
  }
384
1937
  }
385
1938
 
386
- if (candidates.length === 0) {
387
- const verification = verifyOrCreateStoreMeta();
388
- const recipe = resolveEmbedderRecipe();
389
- const isDegraded = !verification.match && recipe.embed_tier !== 'none';
390
- const mode = recipe.embed_tier === 'none' || isDegraded ? 'bm25' : 'hybrid';
1939
+ return mult;
1940
+ }
1941
+
1942
+ export async function hybridSearch(params: SearchRequest): Promise<SearchResponse> {
1943
+ const q = typeof params.q === 'string' ? params.q.trim() : '';
1944
+ const requestedTypesRaw =
1945
+ Array.isArray(params.record_types) && params.record_types.length > 0
1946
+ ? params.record_types
1947
+ : Array.isArray(params.grains) && params.grains.length > 0
1948
+ ? params.grains
1949
+ : typeof (params.record_types as unknown) === 'string' &&
1950
+ (params.record_types as unknown as string).trim() !== ''
1951
+ ? [(params.record_types as unknown as string).trim()]
1952
+ : typeof (params.grains as unknown) === 'string' &&
1953
+ (params.grains as unknown as string).trim() !== ''
1954
+ ? [(params.grains as unknown as string).trim()]
1955
+ : null;
1956
+ const recordTypes: MemoryRecordType[] = (requestedTypesRaw ?? ['note', 'trajectory']).filter(
1957
+ (t): t is MemoryRecordType =>
1958
+ typeof t === 'string' && VALID_RECORD_TYPES.has(t as MemoryRecordType)
1959
+ );
1960
+
1961
+ const parsedLimit =
1962
+ typeof params.limit === 'number'
1963
+ ? params.limit
1964
+ : typeof (params.limit as unknown) === 'string' &&
1965
+ (params.limit as unknown as string).trim() !== ''
1966
+ ? Number(params.limit)
1967
+ : Number.NaN;
1968
+ const limit = Number.isFinite(parsedLimit)
1969
+ ? Math.min(Math.max(Math.trunc(parsedLimit), 1), 100)
1970
+ : 10;
1971
+ const includeGlobal = params.include_global !== false;
1972
+ const includeAncestors = params.include_ancestors !== false;
1973
+ const includeChildren = params.include_children === true;
1974
+ const userId = cleanOptionalString(params.user_id) ?? cleanOptionalString(params.filters?.user_id);
1975
+
1976
+ const afterIso = normalizeUtcIso(params.after, 'after');
1977
+ const beforeIso = normalizeUtcIso(params.before, 'before');
1978
+ const asOfIso = normalizeUtcIso(params.as_of, 'as_of');
1979
+ const referenceIso = normalizeUtcIso(params.reference_date, 'reference_date');
1980
+ const nowMs = referenceIso ? Date.parse(referenceIso) : Date.now();
1981
+ const parsedWindow = parseTemporalQueryWindow(q, referenceIso ?? new Date(nowMs).toISOString());
1982
+ const temporalWindowMeta = parsedWindow
1983
+ ? {
1984
+ start: parsedWindow.windowStartIso,
1985
+ end: parsedWindow.windowEndIso,
1986
+ expressions: parsedWindow.expressions,
1987
+ }
1988
+ : undefined;
1989
+
1990
+ const db = getDb();
1991
+
1992
+ if (recordTypes.length === 0) {
391
1993
  return {
392
1994
  results: [],
393
- mode,
394
- degraded: isDegraded ? verification.mismatchReason : undefined,
1995
+ mode: 'bm25',
1996
+ ...(temporalWindowMeta ? { temporal_window: temporalWindowMeta } : {}),
395
1997
  };
396
1998
  }
397
1999
 
398
- // 2. BM25 scoring over candidates
399
- const queryTokens = tokenize(q);
400
- const docTokensMap = new Map<string, string[]>();
401
- const docLengths: number[] = [];
2000
+ const hasFileFilter = cleanOptionalString(params.filters?.file_path) !== null;
2001
+ const intent = detectQueryKindIntent(q, hasFileFilter);
402
2002
 
403
- for (const c of candidates) {
404
- const tokens = tokenize(c.text);
405
- docTokensMap.set(c.id, tokens);
406
- docLengths.push(tokens.length);
407
- }
2003
+ const ctx: FilterContext = {
2004
+ params,
2005
+ queryIntent: intent,
2006
+ includeGlobal,
2007
+ includeAncestors,
2008
+ includeChildren,
2009
+ userId,
2010
+ afterIso,
2011
+ beforeIso,
2012
+ asOfIso,
2013
+ };
408
2014
 
409
- const N = candidates.length;
410
- const avgdl = docLengths.reduce((a, b) => a + b, 0) / (N || 1);
411
- const k1 = 1.2;
412
- const b = 0.75;
2015
+ const candidateMap = new Map<string, CandidateDoc>();
2016
+ const addCandidate = (doc: CandidateDoc) => {
2017
+ const key = docKey(doc.record_type, doc.id);
2018
+ const existing = candidateMap.get(key);
2019
+ if (!existing) {
2020
+ candidateMap.set(key, doc);
2021
+ } else {
2022
+ if (doc.bm25Score !== undefined && (existing.bm25Score ?? 0) < doc.bm25Score) {
2023
+ existing.bm25Score = doc.bm25Score;
2024
+ }
2025
+ if (
2026
+ doc.temporalRecallScore !== undefined &&
2027
+ (existing.temporalRecallScore ?? 0) < doc.temporalRecallScore
2028
+ ) {
2029
+ existing.temporalRecallScore = doc.temporalRecallScore;
2030
+ }
2031
+ }
2032
+ };
413
2033
 
414
- // Compute document frequency for each query token
415
- const idfMap = new Map<string, number>();
416
- for (const token of queryTokens) {
417
- let df = 0;
418
- for (const c of candidates) {
419
- const tokens = docTokensMap.get(c.id)!;
420
- if (tokens.includes(token)) df++;
2034
+ // 1. Signal 1: Two-tier SQLite FTS5 BM25 retrieval across all requested record types
2035
+ const safeFtsQuery = buildSafeFtsQuery(q);
2036
+ const strictFtsQuery = buildStrictFtsQuery(q);
2037
+ const ftsLimit = Math.max(limit * 10, 200);
2038
+ if (safeFtsQuery) {
2039
+ for (const recordType of recordTypes) {
2040
+ for (const doc of queryTypeFts(db, recordType, ctx, safeFtsQuery, strictFtsQuery, ftsLimit)) {
2041
+ addCandidate(doc);
2042
+ }
421
2043
  }
422
- const idf = Math.log(1 + (N - df + 0.5) / (df + 0.5));
423
- idfMap.set(token, idf);
424
2044
  }
425
2045
 
426
- for (const c of candidates) {
427
- const tokens = docTokensMap.get(c.id)!;
428
- const tfMap = new Map<string, number>();
429
- for (const t of tokens) {
430
- tfMap.set(t, (tfMap.get(t) || 0) + 1);
431
- }
432
- let score = 0;
433
- const len = tokens.length;
434
- for (const qToken of queryTokens) {
435
- const tf = tfMap.get(qToken) || 0;
436
- if (tf > 0) {
437
- const idf = idfMap.get(qToken) || 0;
438
- const termScore = idf * ((tf * (k1 + 1)) / (tf + k1 * (1 - b + b * (len / (avgdl || 1)))));
439
- score += termScore;
440
- }
2046
+ // 1b. Auxiliary Temporal Window Recall (when query expresses a temporal window)
2047
+ if (parsedWindow) {
2048
+ for (const doc of queryTemporalWindowCandidates(db, recordTypes, ctx, parsedWindow)) {
2049
+ addCandidate(doc);
441
2050
  }
442
- c.bm25Score = score;
443
2051
  }
444
2052
 
445
- // 3. Dense scoring
2053
+ // 2. Signal 2: Dense vector retrieval (Qdrant + bounded SQLite scan fallback)
446
2054
  const recipe = resolveEmbedderRecipe();
447
2055
  const verification = verifyOrCreateStoreMeta();
448
2056
  const isMismatch = !verification.match && recipe.embed_tier !== 'none';
@@ -458,111 +2066,639 @@ export async function hybridSearch(params: SearchRequest): Promise<SearchRespons
458
2066
  }
459
2067
 
460
2068
  const denseScoresMap = new Map<string, number>();
2069
+ let queryVec: number[] = [];
461
2070
 
462
2071
  if (mode === 'hybrid') {
463
2072
  try {
464
- const queryVec = await embedQuery(q);
2073
+ queryVec = await embedQuery(q);
2074
+ let qdrantReturnedHits = false;
2075
+
465
2076
  if (queryVec && queryVec.length > 0) {
466
- // Try Qdrant top points if connected
467
2077
  const qdrant = getQdrantClient();
468
2078
  if (qdrant) {
469
2079
  const alias = verification.meta?.qdrant_alias || 'brain';
470
2080
  try {
471
- const filter = buildQdrantFilter(params, grains, includeGlobal);
2081
+ let childProjectIds: string[] | undefined;
2082
+ const rawChildProject = cleanOptionalString(params.project_id);
2083
+ if (includeChildren && rawChildProject) {
2084
+ const normRes = normalizeProjectId(rawChildProject);
2085
+ const norm = normRes.ok ? normRes.projectId : rawChildProject;
2086
+ childProjectIds = collectChildProjectIds(db, norm);
2087
+ }
2088
+ const filter = buildQdrantFilter(params, recordTypes, includeGlobal, childProjectIds);
472
2089
  const searchRes = await qdrant.search(alias, {
473
2090
  vector: queryVec,
474
2091
  limit: Math.max(limit * 2, 50),
475
2092
  with_payload: true,
476
2093
  ...(filter ? { filter } : {}),
477
2094
  });
478
- for (const pt of searchRes) {
479
- denseScoresMap.set(String(pt.id), pt.score);
2095
+
2096
+ if (searchRes.length > 0) {
2097
+ qdrantReturnedHits = true;
2098
+ const missingByType = new Map<MemoryRecordType, string[]>();
2099
+
2100
+ for (const pt of searchRes) {
2101
+ const ptId =
2102
+ typeof pt.payload?.record_id === 'string' ? pt.payload.record_id : String(pt.id);
2103
+ const ptType =
2104
+ typeof pt.payload?.record_type === 'string'
2105
+ ? pt.payload.record_type
2106
+ : typeof pt.payload?.grain === 'string'
2107
+ ? pt.payload.grain
2108
+ : undefined;
2109
+
2110
+ const typesForPt: MemoryRecordType[] =
2111
+ ptType && VALID_RECORD_TYPES.has(ptType as MemoryRecordType)
2112
+ ? [ptType as MemoryRecordType]
2113
+ : recordTypes;
2114
+
2115
+ for (const rType of typesForPt) {
2116
+ const key = docKey(rType, ptId);
2117
+ denseScoresMap.set(key, pt.score);
2118
+ if (recordTypes.includes(rType) && !candidateMap.has(key)) {
2119
+ let list = missingByType.get(rType);
2120
+ if (!list) {
2121
+ list = [];
2122
+ missingByType.set(rType, list);
2123
+ }
2124
+ list.push(ptId);
2125
+ }
2126
+ }
2127
+ }
2128
+
2129
+ for (const [rType, ids] of missingByType.entries()) {
2130
+ for (const doc of queryTypeByIds(db, rType, ctx, ids)) {
2131
+ addCandidate(doc);
2132
+ }
2133
+ }
480
2134
  }
481
- } catch (qErr) {
482
- // Fallback to SQLite embedding blobs
2135
+ } catch {
2136
+ // Fallback to bounded SQLite embedding scan below
483
2137
  }
484
2138
  }
485
2139
 
486
- // For any candidate not scored by Qdrant or if Qdrant was unavailable
487
- for (const c of candidates) {
488
- if (!denseScoresMap.has(c.id) && c.embedding) {
489
- const vec = deserializeEmbedding(c.embedding);
490
- if (vec.length === queryVec.length) {
491
- const sim = cosineSimilarity(queryVec, vec);
492
- denseScoresMap.set(c.id, sim);
2140
+ if (!qdrantReturnedHits) {
2141
+ for (const recordType of recordTypes) {
2142
+ for (const doc of queryTypeEmbeddedScan(db, recordType, ctx, 500)) {
2143
+ addCandidate(doc);
493
2144
  }
494
2145
  }
495
2146
  }
496
2147
  }
497
2148
  } catch (err) {
498
- logger.warn({ error: err instanceof Error ? err.message : String(err) }, 'dense query embedding failed, falling back to BM25');
2149
+ logger.warn(
2150
+ { error: err instanceof Error ? err.message : String(err) },
2151
+ 'dense query embedding failed, falling back to BM25'
2152
+ );
499
2153
  mode = 'bm25';
500
2154
  }
501
2155
  }
502
2156
 
503
- // 4. Rank candidates and compute RRF
504
- // Rank BM25
505
- const bm25Sorted = candidates
506
- .filter((c) => (c.bm25Score ?? 0) > 0)
507
- .sort((a, b) => (b.bm25Score ?? 0) - (a.bm25Score ?? 0));
508
- const bm25RankMap = new Map<string, number>();
509
- bm25Sorted.forEach((c, idx) => {
510
- bm25RankMap.set(c.id, idx + 1);
511
- });
2157
+ // 3. Signal 3: Entity-Graph 1-hop discovery & boosting
2158
+ const entitySeeds = findEntitySeeds(
2159
+ db,
2160
+ ctx,
2161
+ safeFtsQuery,
2162
+ strictFtsQuery,
2163
+ mode,
2164
+ queryVec,
2165
+ denseScoresMap
2166
+ );
2167
+ if (entitySeeds.size > 0) {
2168
+ const seedIds = Array.from(entitySeeds.keys());
2169
+ const seedPlaceholders = seedIds.map(() => '?').join(',');
2170
+ const edges = db
2171
+ .prepare(
2172
+ `
2173
+ SELECT source_type, source_id, target_type, target_id
2174
+ FROM entity_edges
2175
+ WHERE source_id IN (${seedPlaceholders}) OR target_id IN (${seedPlaceholders})
2176
+ `
2177
+ )
2178
+ .all(...seedIds, ...seedIds) as Array<{
2179
+ source_type: string;
2180
+ source_id: string;
2181
+ target_type: string;
2182
+ target_id: string;
2183
+ }>;
512
2184
 
513
- // Rank Dense
514
- const denseRankMap = new Map<string, number>();
515
- if (mode === 'hybrid') {
516
- const denseSorted = candidates
517
- .filter((c) => denseScoresMap.has(c.id) && (denseScoresMap.get(c.id) ?? 0) > 0)
518
- .sort((a, b) => (denseScoresMap.get(b.id) ?? 0) - (denseScoresMap.get(a.id) ?? 0));
519
- denseSorted.forEach((c, idx) => {
520
- denseRankMap.set(c.id, idx + 1);
521
- });
2185
+ const recordTypeSet = new Set<MemoryRecordType>(recordTypes);
2186
+ const linksByDocKey = new Map<string, Map<string, EntitySeed>>();
2187
+ const missingByType = new Map<MemoryRecordType, Set<string>>();
2188
+
2189
+ const recordLink = (targetTypeRaw: string, targetId: string, seedId: string, seed: EntitySeed) => {
2190
+ if (targetId === seedId) return;
2191
+ const targetType = normalizeEdgeRecordType(targetTypeRaw);
2192
+ if (!targetType || !recordTypeSet.has(targetType)) return;
2193
+ const key = docKey(targetType, targetId);
2194
+ let linkedSeeds = linksByDocKey.get(key);
2195
+ if (!linkedSeeds) {
2196
+ linkedSeeds = new Map();
2197
+ linksByDocKey.set(key, linkedSeeds);
2198
+ }
2199
+ linkedSeeds.set(seedId, seed);
2200
+
2201
+ if (!candidateMap.has(key)) {
2202
+ let missing = missingByType.get(targetType);
2203
+ if (!missing) {
2204
+ missing = new Set();
2205
+ missingByType.set(targetType, missing);
2206
+ }
2207
+ missing.add(targetId);
2208
+ }
2209
+ };
2210
+
2211
+ for (const edge of edges) {
2212
+ const srcSeed = entitySeeds.get(edge.source_id);
2213
+ if (srcSeed) {
2214
+ recordLink(edge.target_type, edge.target_id, edge.source_id, srcSeed);
2215
+ }
2216
+ const tgtSeed = entitySeeds.get(edge.target_id);
2217
+ if (tgtSeed) {
2218
+ recordLink(edge.source_type, edge.source_id, edge.target_id, tgtSeed);
2219
+ }
2220
+ }
2221
+
2222
+ for (const [rType, idSet] of missingByType.entries()) {
2223
+ for (const doc of queryTypeByIds(db, rType, ctx, Array.from(idSet))) {
2224
+ addCandidate(doc);
2225
+ }
2226
+ }
2227
+
2228
+ for (const [key, linkedSeeds] of linksByDocKey.entries()) {
2229
+ const cand = candidateMap.get(key);
2230
+ if (!cand) continue;
2231
+ const ordered = Array.from(linkedSeeds.values()).sort(
2232
+ (a, b) => b.entityScore - a.entityScore
2233
+ );
2234
+ cand.entityLinkScore = ordered[0]?.entityScore;
2235
+ cand.matchedEntities = Array.from(new Set(ordered.map((s) => s.entityName)));
2236
+ }
2237
+ }
2238
+
2239
+ const candidates = Array.from(candidateMap.values());
2240
+ if (candidates.length === 0) {
2241
+ return {
2242
+ results: [],
2243
+ mode,
2244
+ degraded: degradedMessage,
2245
+ ...(temporalWindowMeta ? { temporal_window: temporalWindowMeta } : {}),
2246
+ };
2247
+ }
2248
+
2249
+ // Compute SQLite cosine similarity for any candidate not scored by Qdrant
2250
+ if (mode === 'hybrid' && queryVec.length > 0) {
2251
+ for (const c of candidates) {
2252
+ const key = docKey(c.record_type, c.id);
2253
+ if (!denseScoresMap.has(key) && c.embedding) {
2254
+ const vec = deserializeEmbedding(c.embedding);
2255
+ if (vec.length === queryVec.length) {
2256
+ denseScoresMap.set(key, cosineSimilarity(queryVec, vec));
2257
+ }
2258
+ }
2259
+ }
2260
+ }
2261
+
2262
+ // Score auxiliary temporal recall for candidates inside [windowStart, windowEnd]
2263
+ let residualTopicalTokens: string[] = [];
2264
+ let residualPhrases: string[] = [];
2265
+ let explicitCalendarTokens: string[] = [];
2266
+ if (parsedWindow) {
2267
+ const residualSignals = parseQuerySignals(parsedWindow.residualQuery);
2268
+ residualPhrases = residualSignals.phrases;
2269
+ residualTopicalTokens = residualSignals.contentTokens.filter(
2270
+ (tok) => !TEMPORAL_RECALL_META_VERBS.has(tok)
2271
+ );
2272
+ const exprWords = parsedWindow.expressions.join(' ').toLowerCase().match(/[a-z0-9]+/g) ?? [];
2273
+ explicitCalendarTokens = Array.from(
2274
+ new Set(exprWords.filter((w) => EXPLICIT_CALENDAR_TOKEN_RE.test(w)))
2275
+ );
2276
+
2277
+ const hw = Math.max(parsedWindow.halfWidthMs, 1);
2278
+ for (const c of candidates) {
2279
+ const distMs = getBestTemporalWindowDistanceMs(c, parsedWindow);
2280
+ if (distMs !== null && distMs <= hw) {
2281
+ const proximity = 0.35 + 0.65 * Math.cos((Math.PI / 2) * (distMs / hw));
2282
+ let residualOverlap = 0;
2283
+ if (residualTopicalTokens.length > 0) {
2284
+ const lower = c.text.toLowerCase();
2285
+ let matched = 0;
2286
+ for (const tok of residualTopicalTokens) {
2287
+ if (lower.includes(tok)) matched++;
2288
+ }
2289
+ residualOverlap = matched / residualTopicalTokens.length;
2290
+ }
2291
+ c.temporalRecallScore = proximity + 1.5 * residualOverlap;
2292
+ }
2293
+ }
2294
+ }
2295
+
2296
+ const hasSubstantiveTemporalQueryLexicalMatch = (c: CandidateDoc): boolean => {
2297
+ if (!parsedWindow) return true;
2298
+ const lower = c.text.toLowerCase();
2299
+ for (const phrase of residualPhrases) {
2300
+ if (lower.includes(phrase)) return true;
2301
+ }
2302
+ for (const tok of residualTopicalTokens) {
2303
+ if (lower.includes(tok)) return true;
2304
+ }
2305
+ if (explicitCalendarTokens.length >= 2) {
2306
+ let calMatches = 0;
2307
+ for (const calTok of explicitCalendarTokens) {
2308
+ if (lower.includes(calTok)) calMatches++;
2309
+ }
2310
+ if (calMatches >= 2) return true;
2311
+ }
2312
+ return false;
2313
+ };
2314
+
2315
+ // 4. Rank each signal independently (competition ranking prevents arbitrary tie skew)
2316
+ const bm25Matched = candidates.filter((c) => (c.bm25Score ?? 0) > 0);
2317
+ const bm25RankMap = assignCompetitionRanks(
2318
+ bm25Matched,
2319
+ (c) => docKey(c.record_type, c.id),
2320
+ (c) => c.bm25Score ?? 0
2321
+ );
2322
+
2323
+ const denseRankMap =
2324
+ mode === 'hybrid'
2325
+ ? assignCompetitionRanks(
2326
+ candidates.filter((c) => (denseScoresMap.get(docKey(c.record_type, c.id)) ?? 0) > 0),
2327
+ (c) => docKey(c.record_type, c.id),
2328
+ (c) => denseScoresMap.get(docKey(c.record_type, c.id)) ?? 0
2329
+ )
2330
+ : new Map<string, number>();
2331
+
2332
+ const entityRankMap = assignCompetitionRanks(
2333
+ candidates.filter((c) => (c.entityLinkScore ?? 0) > 0),
2334
+ (c) => docKey(c.record_type, c.id),
2335
+ (c) => c.entityLinkScore ?? 0
2336
+ );
2337
+
2338
+ const temporalRankMap = parsedWindow
2339
+ ? assignCompetitionRanks(
2340
+ candidates.filter((c) => (c.temporalRecallScore ?? 0) > 0),
2341
+ (c) => docKey(c.record_type, c.id),
2342
+ (c) => c.temporalRecallScore ?? 0
2343
+ )
2344
+ : new Map<string, number>();
2345
+
2346
+ const maxBm25 = bm25Matched.reduce((m, c) => Math.max(m, c.bm25Score ?? 0), 0);
2347
+
2348
+ const queryProjectRaw = cleanOptionalString(params.project_id);
2349
+ let queryProjectNorm: string | null = null;
2350
+ if (queryProjectRaw && params.scope !== 'global' && params.scope !== 'unknown') {
2351
+ const res = normalizeProjectId(queryProjectRaw);
2352
+ queryProjectNorm = res.ok ? res.projectId : queryProjectRaw;
522
2353
  }
523
2354
 
524
- const k_rrf = 60;
2355
+ const kindWeights = resolveKindWeights(intent, params.kind_weights);
2356
+ const querySignals = parseQuerySignals(q);
2357
+ const signalIntent = detectQuerySignalIntent(q);
2358
+ const snippetMode: SnippetMode =
2359
+ params.snippet_mode === 'condensed' || params.snippet_mode === 'raw'
2360
+ ? params.snippet_mode
2361
+ : 'query_focused';
2362
+ const explicitMaxChars =
2363
+ typeof params.max_record_chars === 'number' &&
2364
+ Number.isFinite(params.max_record_chars) &&
2365
+ params.max_record_chars > 0
2366
+ ? Math.max(32, Math.trunc(params.max_record_chars))
2367
+ : undefined;
2368
+
525
2369
  for (const c of candidates) {
2370
+ const key = docKey(c.record_type, c.id);
2371
+ const rankDense = denseRankMap.get(key);
2372
+ const rankBm25 = bm25RankMap.get(key);
2373
+ const rankEntity = entityRankMap.get(key);
2374
+ const rankTemporal = temporalRankMap.get(key);
2375
+ const bm25LexicalScale =
2376
+ rankBm25 !== undefined && parsedWindow && !hasSubstantiveTemporalQueryLexicalMatch(c)
2377
+ ? 0.2
2378
+ : 1.0;
2379
+
2380
+ let baseScore = 0;
526
2381
  if (mode === 'hybrid') {
527
- const rankDense = denseRankMap.get(c.id);
528
- const rankBm25 = bm25RankMap.get(c.id);
529
- let rrf = 0;
530
- if (rankDense !== undefined) {
531
- rrf += 1 / (k_rrf + rankDense);
532
- }
533
- if (rankBm25 !== undefined) {
534
- rrf += 1 / (k_rrf + rankBm25);
2382
+ if (rankDense !== undefined) baseScore += 1 / (RRF_K + rankDense);
2383
+ if (rankBm25 !== undefined) baseScore += bm25LexicalScale / (RRF_K + rankBm25);
2384
+ if (rankEntity !== undefined) baseScore += 1 / (RRF_K + rankEntity);
2385
+ if (rankTemporal !== undefined) baseScore += 0.75 / (RRF_K + rankTemporal);
2386
+ } else {
2387
+ const bm25Norm =
2388
+ maxBm25 > 0 && (c.bm25Score ?? 0) > 0 ? (c.bm25Score! / maxBm25) * bm25LexicalScale : 0;
2389
+ const entityBoost =
2390
+ rankEntity !== undefined ? 0.25 * ((RRF_K + 1) / (RRF_K + rankEntity)) : 0;
2391
+ const temporalBoost =
2392
+ rankTemporal !== undefined ? 0.35 * ((RRF_K + 1) / (RRF_K + rankTemporal)) : 0;
2393
+ baseScore = bm25Norm + entityBoost + temporalBoost;
2394
+ }
2395
+
2396
+ const tierInfo = classifyMatchTier(c.record.scope, c.record.project_id, queryProjectNorm);
2397
+ c.matchTier = tierInfo.match_tier;
2398
+
2399
+ if (baseScore > 0) {
2400
+ const tierMult = computeTierMultiplier(
2401
+ tierInfo.match_tier,
2402
+ tierInfo.ancestor_distance,
2403
+ queryProjectNorm !== null
2404
+ );
2405
+ const temporalMult = computeTemporalMultiplier(c, params, nowMs, parsedWindow);
2406
+ let obsMult = 1.0;
2407
+ if (c.record_type === 'observation') {
2408
+ const obsKind = c.record.kind as ObservationSearchKind;
2409
+ const kindMult =
2410
+ obsKind === 'prompt' || obsKind === 'response' || obsKind === 'tool_call'
2411
+ ? kindWeights[obsKind]
2412
+ : 1.0;
2413
+ const densityMult = computeObservationDensityMultiplier(c.record, querySignals);
2414
+ let signalMult = 1.0;
2415
+ if (signalIntent.wantsPreference || signalIntent.wantsStateUpdate) {
2416
+ const tags = parseSignalTags(c.record.signal_tags);
2417
+ if (tags.length > 0) {
2418
+ if (
2419
+ intent !== 'assistant' &&
2420
+ signalIntent.wantsPreference &&
2421
+ tags.includes('preference')
2422
+ ) {
2423
+ signalMult *= 1.22;
2424
+ }
2425
+ if (signalIntent.wantsStateUpdate && tags.includes('state_update')) {
2426
+ signalMult *= 1.18;
2427
+ const createdMs = getCandidateCreatedMs(c);
2428
+ if (createdMs !== null) {
2429
+ const ageDays = Math.max(0, (nowMs - createdMs) / 86_400_000);
2430
+ signalMult *= 1.0 + 0.06 / (1 + ageDays / 60);
2431
+ }
2432
+ }
2433
+ }
2434
+ }
2435
+ obsMult = kindMult * densityMult * signalMult;
535
2436
  }
536
- c.rrfScore = rrf;
2437
+ c.rrfScore = baseScore * tierMult * temporalMult * obsMult;
537
2438
  } else {
538
- // In BM25 mode, score is the BM25 score
539
- c.rrfScore = c.bm25Score ?? 0;
2439
+ c.rrfScore = 0;
540
2440
  }
541
2441
  }
542
2442
 
543
- // Filter candidates with non-zero score
544
2443
  const matched = candidates.filter((c) => (c.rrfScore ?? 0) > 0);
545
2444
  matched.sort((a, b) => (b.rrfScore ?? 0) - (a.rrfScore ?? 0));
546
2445
 
547
- const sliced = matched.slice(0, limit);
2446
+ const maxKindShare = resolveMaxKindShare(params, recordTypes, intent, limit);
2447
+ let sliced: CandidateDoc[];
2448
+ if (!maxKindShare) {
2449
+ sliced = matched.slice(0, limit);
2450
+ } else {
2451
+ const selected: CandidateDoc[] = [];
2452
+ const deferred: CandidateDoc[] = [];
2453
+ const countsByKind: Record<ObservationSearchKind, number> = {
2454
+ prompt: 0,
2455
+ response: 0,
2456
+ tool_call: 0,
2457
+ };
2458
+
2459
+ for (const c of matched) {
2460
+ if (selected.length >= limit) break;
2461
+ if (c.record_type === 'observation') {
2462
+ const obsKind = c.record.kind as ObservationSearchKind;
2463
+ const shareCap =
2464
+ obsKind === 'prompt' || obsKind === 'response' || obsKind === 'tool_call'
2465
+ ? maxKindShare[obsKind]
2466
+ : undefined;
2467
+ if (shareCap !== undefined) {
2468
+ const maxForKind = Math.max(1, Math.floor(limit * shareCap));
2469
+ if (countsByKind[obsKind] >= maxForKind) {
2470
+ deferred.push(c);
2471
+ continue;
2472
+ }
2473
+ countsByKind[obsKind]++;
2474
+ }
2475
+ }
2476
+ selected.push(c);
2477
+ }
2478
+
2479
+ if (selected.length < limit && deferred.length > 0) {
2480
+ selected.push(...deferred.slice(0, limit - selected.length));
2481
+ selected.sort((a, b) => (b.rrfScore ?? 0) - (a.rrfScore ?? 0));
2482
+ }
2483
+
2484
+ sliced = selected;
2485
+ }
548
2486
 
549
2487
  const results: SearchResultItem[] = sliced.map((c) => {
2488
+ let recordOut = c.record;
2489
+ let snippetOut: string | undefined;
2490
+ if (c.record_type === 'observation') {
2491
+ const formatted = formatObservationResult(
2492
+ c.record,
2493
+ q,
2494
+ querySignals,
2495
+ snippetMode,
2496
+ explicitMaxChars,
2497
+ parsedWindow
2498
+ );
2499
+ recordOut = formatted.record;
2500
+ snippetOut = formatted.snippet;
2501
+ }
2502
+
550
2503
  const item: SearchResultItem = {
551
2504
  id: c.id,
552
- grain: c.grain,
2505
+ record_type: c.record_type,
553
2506
  score: c.rrfScore ?? 0,
554
- record: c.record,
2507
+ project_id: recordOut.project_id ?? null,
2508
+ match_tier: c.matchTier,
2509
+ ...(c.matchedEntities && c.matchedEntities.length > 0
2510
+ ? { matched_entities: c.matchedEntities }
2511
+ : {}),
2512
+ ...(snippetOut !== undefined ? { snippet: snippetOut } : {}),
2513
+ record: recordOut,
555
2514
  };
556
- if (c.grain === 'summary') {
557
- item.claims = c.record.claims;
558
- item.sources = c.record.sources;
2515
+ if (c.record_type === 'summary') {
2516
+ item.claims = c.claims;
559
2517
  }
560
2518
  return item;
561
2519
  });
562
2520
 
2521
+ if (params.include_sources === true) {
2522
+ const rawLimit = params.sources_limit;
2523
+ const sourcesLimit =
2524
+ typeof rawLimit === 'number' && Number.isFinite(rawLimit)
2525
+ ? Math.max(1, Math.min(Math.trunc(rawLimit), 100))
2526
+ : 20;
2527
+ const rawOffset = params.sources_offset;
2528
+ const sourcesOffset =
2529
+ typeof rawOffset === 'number' && Number.isFinite(rawOffset)
2530
+ ? Math.max(0, Math.trunc(rawOffset))
2531
+ : 0;
2532
+ attachPaginatedSummarySources(db, results, sourcesLimit, sourcesOffset);
2533
+ }
2534
+
563
2535
  return {
564
2536
  results,
565
2537
  mode,
566
2538
  degraded: degradedMessage,
2539
+ ...(temporalWindowMeta ? { temporal_window: temporalWindowMeta } : {}),
567
2540
  };
568
2541
  }
2542
+
2543
+ function truncateSourcePreview(value: string | null | undefined, maxChars = MAX_SOURCE_PREVIEW_CHARS): string | null {
2544
+ if (!value) return null;
2545
+ const compact = value.replace(/\s+/g, ' ').trim();
2546
+ if (!compact) return null;
2547
+ return compact.length <= maxChars ? compact : `${compact.slice(0, maxChars)}...`;
2548
+ }
2549
+
2550
+ function attachPaginatedSummarySources(
2551
+ db: ReturnType<typeof getDb>,
2552
+ results: SearchResultItem[],
2553
+ sourcesLimit: number,
2554
+ sourcesOffset: number
2555
+ ): void {
2556
+ const summaryItems = results.filter((r) => r.record_type === 'summary');
2557
+ if (summaryItems.length === 0) return;
2558
+
2559
+ const summaryIds = summaryItems.map((r) => r.id);
2560
+ const placeholders = summaryIds.map(() => '?').join(',');
2561
+ const allSources = db
2562
+ .prepare(
2563
+ `SELECT summary_id, claim_id, record_id, record_type FROM summary_sources WHERE summary_id IN (${placeholders}) ORDER BY rowid ASC`
2564
+ )
2565
+ .all(...summaryIds) as Array<{ summary_id: string; claim_id: string | null; record_id: string; record_type: string }>;
2566
+
2567
+ const sourcesBySummaryId = new Map<string, typeof allSources>();
2568
+ for (const s of allSources) {
2569
+ let list = sourcesBySummaryId.get(s.summary_id);
2570
+ if (!list) {
2571
+ list = [];
2572
+ sourcesBySummaryId.set(s.summary_id, list);
2573
+ }
2574
+ list.push(s);
2575
+ }
2576
+
2577
+ const pagedBySummaryId = new Map<string, { page: typeof allSources; total: number }>();
2578
+ const idsByType = new Map<string, Set<string>>();
2579
+
2580
+ for (const item of summaryItems) {
2581
+ const all = sourcesBySummaryId.get(item.id) || [];
2582
+ const page = all.slice(sourcesOffset, sourcesOffset + sourcesLimit);
2583
+ pagedBySummaryId.set(item.id, { page, total: all.length });
2584
+ for (const s of page) {
2585
+ let set = idsByType.get(s.record_type);
2586
+ if (!set) {
2587
+ set = new Set<string>();
2588
+ idsByType.set(s.record_type, set);
2589
+ }
2590
+ set.add(s.record_id);
2591
+ }
2592
+ }
2593
+
2594
+ const metaByKey = new Map<string, Partial<SearchSummarySource>>();
2595
+
2596
+ const obsIds = Array.from(idsByType.get('observation') ?? []);
2597
+ if (obsIds.length > 0) {
2598
+ const obsPlaceholders = obsIds.map(() => '?').join(',');
2599
+ const obsRows = db
2600
+ .prepare(
2601
+ `SELECT id, kind, tool_name, file_path, input, output, failed FROM observations WHERE id IN (${obsPlaceholders})`
2602
+ )
2603
+ .all(...obsIds) as Array<{
2604
+ id: string;
2605
+ kind: string;
2606
+ tool_name: string | null;
2607
+ file_path: string | null;
2608
+ input: string | null;
2609
+ output: string | null;
2610
+ failed: number;
2611
+ }>;
2612
+
2613
+ const foundObsIds = new Set<string>();
2614
+ const mapObsRow = (row: (typeof obsRows)[number]) => {
2615
+ const title =
2616
+ row.kind === 'prompt'
2617
+ ? 'prompt'
2618
+ : row.tool_name
2619
+ ? row.file_path
2620
+ ? `${row.tool_name}: ${row.file_path}`
2621
+ : row.tool_name
2622
+ : row.kind || 'observation';
2623
+ metaByKey.set(docKey('observation', row.id), {
2624
+ title,
2625
+ kind: row.kind,
2626
+ tool_name: row.tool_name,
2627
+ file_path: row.file_path,
2628
+ failed: Boolean(row.failed),
2629
+ preview: truncateSourcePreview(row.input) ?? truncateSourcePreview(row.output),
2630
+ });
2631
+ };
2632
+
2633
+ for (const row of obsRows) {
2634
+ foundObsIds.add(row.id);
2635
+ mapObsRow(row);
2636
+ }
2637
+
2638
+ const missingObsIds = obsIds.filter((id) => !foundObsIds.has(id));
2639
+ if (missingObsIds.length > 0) {
2640
+ const arcPlaceholders = missingObsIds.map(() => '?').join(',');
2641
+ const arcRows = db
2642
+ .prepare(
2643
+ `SELECT original_observation_id as id, kind, tool_name, file_path, input, output, failed FROM observations_archive WHERE original_observation_id IN (${arcPlaceholders})`
2644
+ )
2645
+ .all(...missingObsIds) as typeof obsRows;
2646
+ for (const row of arcRows) {
2647
+ mapObsRow(row);
2648
+ }
2649
+ }
2650
+ }
2651
+
2652
+ const noteIds = Array.from(idsByType.get('note') ?? []);
2653
+ if (noteIds.length > 0) {
2654
+ const notePlaceholders = noteIds.map(() => '?').join(',');
2655
+ const noteRows = db
2656
+ .prepare(`SELECT id, title, type FROM notes WHERE id IN (${notePlaceholders})`)
2657
+ .all(...noteIds) as Array<{ id: string; title: string; type: string }>;
2658
+ for (const row of noteRows) {
2659
+ metaByKey.set(docKey('note', row.id), { title: row.title, kind: row.type });
2660
+ }
2661
+ }
2662
+
2663
+ const trajIds = Array.from(idsByType.get('trajectory') ?? []);
2664
+ if (trajIds.length > 0) {
2665
+ const trajPlaceholders = trajIds.map(() => '?').join(',');
2666
+ const trajRows = db
2667
+ .prepare(`SELECT id, task_type, description FROM trajectories WHERE id IN (${trajPlaceholders})`)
2668
+ .all(...trajIds) as Array<{ id: string; task_type: string | null; description: string }>;
2669
+ for (const row of trajRows) {
2670
+ metaByKey.set(docKey('trajectory', row.id), {
2671
+ title: truncateSourcePreview(row.description) ?? row.task_type ?? 'trajectory',
2672
+ ...(row.task_type ? { kind: row.task_type } : {}),
2673
+ });
2674
+ }
2675
+ }
2676
+
2677
+ const sumIds = Array.from(idsByType.get('summary') ?? []);
2678
+ if (sumIds.length > 0) {
2679
+ const sumPlaceholders = sumIds.map(() => '?').join(',');
2680
+ const sumRows = db
2681
+ .prepare(
2682
+ `SELECT s.id, s.kind, (SELECT c.text FROM summary_claims c WHERE c.summary_id = s.id ORDER BY c.ordinal ASC LIMIT 1) as first_claim
2683
+ FROM summaries s WHERE s.id IN (${sumPlaceholders})`
2684
+ )
2685
+ .all(...sumIds) as Array<{ id: string; kind: string; first_claim: string | null }>;
2686
+ for (const row of sumRows) {
2687
+ metaByKey.set(docKey('summary', row.id), {
2688
+ title: truncateSourcePreview(row.first_claim) ?? row.kind,
2689
+ kind: row.kind,
2690
+ });
2691
+ }
2692
+ }
2693
+
2694
+ for (const item of summaryItems) {
2695
+ const paged = pagedBySummaryId.get(item.id);
2696
+ if (!paged) continue;
2697
+ item.sources = paged.page.map((s) => ({
2698
+ ...s,
2699
+ ...metaByKey.get(docKey(s.record_type, s.record_id)),
2700
+ }));
2701
+ item.sources_total = paged.total;
2702
+ item.sources_has_more = sourcesOffset + paged.page.length < paged.total;
2703
+ }
2704
+ }