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