neuralbrain 0.0.0-stage → 0.0.1

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 (293) hide show
  1. package/.dockerignore +11 -0
  2. package/.env.example +245 -0
  3. package/Dockerfile +65 -0
  4. package/LICENSE +44 -0
  5. package/README.md +312 -2
  6. package/dist/ai/chat.d.ts +45 -0
  7. package/dist/ai/chat.d.ts.map +1 -0
  8. package/dist/ai/chat.js +153 -0
  9. package/dist/ai/chat.js.map +1 -0
  10. package/dist/ai/circuitBreaker.d.ts +35 -0
  11. package/dist/ai/circuitBreaker.d.ts.map +1 -0
  12. package/dist/ai/circuitBreaker.js +95 -0
  13. package/dist/ai/circuitBreaker.js.map +1 -0
  14. package/dist/ai/config.d.ts +88 -0
  15. package/dist/ai/config.d.ts.map +1 -0
  16. package/dist/ai/config.js +255 -0
  17. package/dist/ai/config.js.map +1 -0
  18. package/dist/ai/vendors.d.ts +58 -0
  19. package/dist/ai/vendors.d.ts.map +1 -0
  20. package/dist/ai/vendors.js +223 -0
  21. package/dist/ai/vendors.js.map +1 -0
  22. package/dist/app.d.ts +4 -0
  23. package/dist/app.d.ts.map +1 -0
  24. package/dist/app.js +1013 -0
  25. package/dist/app.js.map +1 -0
  26. package/dist/cli.d.ts +133 -0
  27. package/dist/cli.d.ts.map +1 -0
  28. package/dist/cli.js +912 -0
  29. package/dist/cli.js.map +1 -0
  30. package/dist/consolidation/candidates.d.ts +34 -0
  31. package/dist/consolidation/candidates.d.ts.map +1 -0
  32. package/dist/consolidation/candidates.js +150 -0
  33. package/dist/consolidation/candidates.js.map +1 -0
  34. package/dist/consolidation/fixtures.d.ts +25 -0
  35. package/dist/consolidation/fixtures.d.ts.map +1 -0
  36. package/dist/consolidation/fixtures.js +400 -0
  37. package/dist/consolidation/fixtures.js.map +1 -0
  38. package/dist/consolidation/gate.d.ts +39 -0
  39. package/dist/consolidation/gate.d.ts.map +1 -0
  40. package/dist/consolidation/gate.js +286 -0
  41. package/dist/consolidation/gate.js.map +1 -0
  42. package/dist/consolidation/runner.d.ts +63 -0
  43. package/dist/consolidation/runner.d.ts.map +1 -0
  44. package/dist/consolidation/runner.js +171 -0
  45. package/dist/consolidation/runner.js.map +1 -0
  46. package/dist/dashboard/clientScript.d.ts +2 -0
  47. package/dist/dashboard/clientScript.d.ts.map +1 -0
  48. package/dist/dashboard/clientScript.js +4212 -0
  49. package/dist/dashboard/clientScript.js.map +1 -0
  50. package/dist/dashboard/html.d.ts +2 -0
  51. package/dist/dashboard/html.d.ts.map +1 -0
  52. package/dist/dashboard/html.js +554 -0
  53. package/dist/dashboard/html.js.map +1 -0
  54. package/dist/dashboard/styles.d.ts +2 -0
  55. package/dist/dashboard/styles.d.ts.map +1 -0
  56. package/dist/dashboard/styles.js +1283 -0
  57. package/dist/dashboard/styles.js.map +1 -0
  58. package/dist/index.d.ts +3 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +124 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/learning/embedWorker.d.ts +58 -0
  63. package/dist/learning/embedWorker.d.ts.map +1 -0
  64. package/dist/learning/embedWorker.js +552 -0
  65. package/dist/learning/embedWorker.js.map +1 -0
  66. package/dist/learning/embedding.d.ts +52 -0
  67. package/dist/learning/embedding.d.ts.map +1 -0
  68. package/dist/learning/embedding.js +511 -0
  69. package/dist/learning/embedding.js.map +1 -0
  70. package/dist/learning/engine.d.ts +20 -0
  71. package/dist/learning/engine.d.ts.map +1 -0
  72. package/dist/learning/engine.js +69 -0
  73. package/dist/learning/engine.js.map +1 -0
  74. package/dist/learning/search.d.ts +4 -0
  75. package/dist/learning/search.d.ts.map +1 -0
  76. package/dist/learning/search.js +509 -0
  77. package/dist/learning/search.js.map +1 -0
  78. package/dist/learning/storeMeta.d.ts +11 -0
  79. package/dist/learning/storeMeta.d.ts.map +1 -0
  80. package/dist/learning/storeMeta.js +100 -0
  81. package/dist/learning/storeMeta.js.map +1 -0
  82. package/dist/learning/types.d.ts +101 -0
  83. package/dist/learning/types.d.ts.map +1 -0
  84. package/dist/learning/types.js +3 -0
  85. package/dist/learning/types.js.map +1 -0
  86. package/dist/lib/brainHome.d.ts +28 -0
  87. package/dist/lib/brainHome.d.ts.map +1 -0
  88. package/dist/lib/brainHome.js +104 -0
  89. package/dist/lib/brainHome.js.map +1 -0
  90. package/dist/lib/db.d.ts +10 -0
  91. package/dist/lib/db.d.ts.map +1 -0
  92. package/dist/lib/db.js +589 -0
  93. package/dist/lib/db.js.map +1 -0
  94. package/dist/lib/logger.d.ts +3 -0
  95. package/dist/lib/logger.d.ts.map +1 -0
  96. package/dist/lib/logger.js +11 -0
  97. package/dist/lib/logger.js.map +1 -0
  98. package/dist/lib/projectSlug.d.ts +61 -0
  99. package/dist/lib/projectSlug.d.ts.map +1 -0
  100. package/dist/lib/projectSlug.js +273 -0
  101. package/dist/lib/projectSlug.js.map +1 -0
  102. package/dist/lib/redactSecrets.d.ts +7 -0
  103. package/dist/lib/redactSecrets.d.ts.map +1 -0
  104. package/dist/lib/redactSecrets.js +90 -0
  105. package/dist/lib/redactSecrets.js.map +1 -0
  106. package/dist/lib/scope.d.ts +54 -0
  107. package/dist/lib/scope.d.ts.map +1 -0
  108. package/dist/lib/scope.js +103 -0
  109. package/dist/lib/scope.js.map +1 -0
  110. package/dist/lib/spool.d.ts +23 -0
  111. package/dist/lib/spool.d.ts.map +1 -0
  112. package/dist/lib/spool.js +317 -0
  113. package/dist/lib/spool.js.map +1 -0
  114. package/dist/lib/sqlite.d.ts +50 -0
  115. package/dist/lib/sqlite.d.ts.map +1 -0
  116. package/dist/lib/sqlite.js +130 -0
  117. package/dist/lib/sqlite.js.map +1 -0
  118. package/dist/lib/tls.d.ts +34 -0
  119. package/dist/lib/tls.d.ts.map +1 -0
  120. package/dist/lib/tls.js +212 -0
  121. package/dist/lib/tls.js.map +1 -0
  122. package/dist/mcp/server.d.ts +231 -0
  123. package/dist/mcp/server.d.ts.map +1 -0
  124. package/dist/mcp/server.js +615 -0
  125. package/dist/mcp/server.js.map +1 -0
  126. package/dist/memory/actionStore.d.ts +75 -0
  127. package/dist/memory/actionStore.d.ts.map +1 -0
  128. package/dist/memory/actionStore.js +239 -0
  129. package/dist/memory/actionStore.js.map +1 -0
  130. package/dist/memory/deadLetterStore.d.ts +30 -0
  131. package/dist/memory/deadLetterStore.d.ts.map +1 -0
  132. package/dist/memory/deadLetterStore.js +91 -0
  133. package/dist/memory/deadLetterStore.js.map +1 -0
  134. package/dist/memory/embedQueueStore.d.ts +32 -0
  135. package/dist/memory/embedQueueStore.d.ts.map +1 -0
  136. package/dist/memory/embedQueueStore.js +143 -0
  137. package/dist/memory/embedQueueStore.js.map +1 -0
  138. package/dist/memory/failurePatternStore.d.ts +37 -0
  139. package/dist/memory/failurePatternStore.d.ts.map +1 -0
  140. package/dist/memory/failurePatternStore.js +179 -0
  141. package/dist/memory/failurePatternStore.js.map +1 -0
  142. package/dist/memory/graphStore.d.ts +38 -0
  143. package/dist/memory/graphStore.d.ts.map +1 -0
  144. package/dist/memory/graphStore.js +229 -0
  145. package/dist/memory/graphStore.js.map +1 -0
  146. package/dist/memory/noteStore.d.ts +58 -0
  147. package/dist/memory/noteStore.d.ts.map +1 -0
  148. package/dist/memory/noteStore.js +280 -0
  149. package/dist/memory/noteStore.js.map +1 -0
  150. package/dist/memory/observationStore.d.ts +40 -0
  151. package/dist/memory/observationStore.d.ts.map +1 -0
  152. package/dist/memory/observationStore.js +213 -0
  153. package/dist/memory/observationStore.js.map +1 -0
  154. package/dist/memory/projectRename.d.ts +14 -0
  155. package/dist/memory/projectRename.d.ts.map +1 -0
  156. package/dist/memory/projectRename.js +105 -0
  157. package/dist/memory/projectRename.js.map +1 -0
  158. package/dist/memory/rollupSweeper.d.ts +36 -0
  159. package/dist/memory/rollupSweeper.d.ts.map +1 -0
  160. package/dist/memory/rollupSweeper.js +235 -0
  161. package/dist/memory/rollupSweeper.js.map +1 -0
  162. package/dist/memory/sessionStore.d.ts +81 -0
  163. package/dist/memory/sessionStore.d.ts.map +1 -0
  164. package/dist/memory/sessionStore.js +285 -0
  165. package/dist/memory/sessionStore.js.map +1 -0
  166. package/dist/memory/trajectoryStore.d.ts +86 -0
  167. package/dist/memory/trajectoryStore.d.ts.map +1 -0
  168. package/dist/memory/trajectoryStore.js +528 -0
  169. package/dist/memory/trajectoryStore.js.map +1 -0
  170. package/dist/middleware/auth.d.ts +30 -0
  171. package/dist/middleware/auth.d.ts.map +1 -0
  172. package/dist/middleware/auth.js +387 -0
  173. package/dist/middleware/auth.js.map +1 -0
  174. package/dist/middleware/rateLimiter.d.ts +13 -0
  175. package/dist/middleware/rateLimiter.d.ts.map +1 -0
  176. package/dist/middleware/rateLimiter.js +153 -0
  177. package/dist/middleware/rateLimiter.js.map +1 -0
  178. package/dist/middleware/tracing.d.ts +15 -0
  179. package/dist/middleware/tracing.d.ts.map +1 -0
  180. package/dist/middleware/tracing.js +53 -0
  181. package/dist/middleware/tracing.js.map +1 -0
  182. package/dist/routes/dashboard.d.ts +2 -0
  183. package/dist/routes/dashboard.d.ts.map +1 -0
  184. package/dist/routes/dashboard.js +443 -0
  185. package/dist/routes/dashboard.js.map +1 -0
  186. package/dist/routes/learning.d.ts +2 -0
  187. package/dist/routes/learning.d.ts.map +1 -0
  188. package/dist/routes/learning.js +46 -0
  189. package/dist/routes/learning.js.map +1 -0
  190. package/dist/routes/mcp.d.ts +8 -0
  191. package/dist/routes/mcp.d.ts.map +1 -0
  192. package/dist/routes/mcp.js +316 -0
  193. package/dist/routes/mcp.js.map +1 -0
  194. package/dist/routes/memories.d.ts +2 -0
  195. package/dist/routes/memories.d.ts.map +1 -0
  196. package/dist/routes/memories.js +33 -0
  197. package/dist/routes/memories.js.map +1 -0
  198. package/dist/scripts/createApiKey.d.ts +2 -0
  199. package/dist/scripts/createApiKey.d.ts.map +1 -0
  200. package/dist/scripts/createApiKey.js +78 -0
  201. package/dist/scripts/createApiKey.js.map +1 -0
  202. package/dist/scripts/doctor.d.ts +24 -0
  203. package/dist/scripts/doctor.d.ts.map +1 -0
  204. package/dist/scripts/doctor.js +332 -0
  205. package/dist/scripts/doctor.js.map +1 -0
  206. package/dist/scripts/installAgent.d.ts +80 -0
  207. package/dist/scripts/installAgent.d.ts.map +1 -0
  208. package/dist/scripts/installAgent.js +1046 -0
  209. package/dist/scripts/installAgent.js.map +1 -0
  210. package/dist/scripts/migrateAgentMemory.d.ts +16 -0
  211. package/dist/scripts/migrateAgentMemory.d.ts.map +1 -0
  212. package/dist/scripts/migrateAgentMemory.js +209 -0
  213. package/dist/scripts/migrateAgentMemory.js.map +1 -0
  214. package/dist/scripts/smokeTest.d.ts +16 -0
  215. package/dist/scripts/smokeTest.d.ts.map +1 -0
  216. package/dist/scripts/smokeTest.js +150 -0
  217. package/dist/scripts/smokeTest.js.map +1 -0
  218. package/docker-compose.qdrant-port.yml +7 -0
  219. package/docker-compose.yml +107 -0
  220. package/npm-shrinkwrap.json +7635 -0
  221. package/package.json +106 -4
  222. package/plugin/hooks/postToolUse.js +513 -0
  223. package/plugin/hooks/sessionStart.js +416 -0
  224. package/plugin/hooks/sessionStop.js +346 -0
  225. package/plugin/hooks.json +30 -0
  226. package/plugin/mcp_config.json +13 -0
  227. package/plugin/plugin.json +15 -0
  228. package/plugin/rules/AGENTS.md +66 -0
  229. package/plugin/skills/brain-memory/REFERENCE.md +64 -0
  230. package/plugin/skills/brain-memory/SKILL.md +68 -0
  231. package/plugin/skills/brain-memory/TROUBLESHOOTING.md +24 -0
  232. package/plugin/skills/digest/SKILL.md +54 -0
  233. package/plugin/skills/digest/TROUBLESHOOTING.md +24 -0
  234. package/plugin/skills/handoff/SKILL.md +59 -0
  235. package/plugin/skills/handoff/TROUBLESHOOTING.md +24 -0
  236. package/plugin/skills/save/SKILL.md +76 -0
  237. package/plugin/skills/save/TROUBLESHOOTING.md +24 -0
  238. package/plugin/skills/search/SKILL.md +60 -0
  239. package/plugin/skills/search/TROUBLESHOOTING.md +24 -0
  240. package/src/ai/chat.ts +214 -0
  241. package/src/ai/circuitBreaker.ts +120 -0
  242. package/src/ai/config.ts +311 -0
  243. package/src/ai/vendors.ts +292 -0
  244. package/src/app.ts +1150 -0
  245. package/src/cli.ts +1080 -0
  246. package/src/consolidation/candidates.ts +219 -0
  247. package/src/consolidation/fixtures.ts +461 -0
  248. package/src/consolidation/gate.ts +408 -0
  249. package/src/consolidation/runner.ts +220 -0
  250. package/src/dashboard/clientScript.ts +4208 -0
  251. package/src/dashboard/html.ts +550 -0
  252. package/src/dashboard/styles.ts +1279 -0
  253. package/src/index.ts +139 -0
  254. package/src/learning/embedWorker.ts +651 -0
  255. package/src/learning/embedding.ts +522 -0
  256. package/src/learning/engine.ts +86 -0
  257. package/src/learning/search.ts +568 -0
  258. package/src/learning/storeMeta.ts +147 -0
  259. package/src/learning/types.ts +111 -0
  260. package/src/lib/brainHome.ts +101 -0
  261. package/src/lib/db.ts +627 -0
  262. package/src/lib/logger.ts +7 -0
  263. package/src/lib/projectSlug.ts +286 -0
  264. package/src/lib/redactSecrets.ts +87 -0
  265. package/src/lib/scope.ts +121 -0
  266. package/src/lib/spool.ts +372 -0
  267. package/src/lib/sqlite.ts +158 -0
  268. package/src/lib/tls.ts +252 -0
  269. package/src/mcp/server.ts +793 -0
  270. package/src/memory/actionStore.ts +378 -0
  271. package/src/memory/deadLetterStore.ts +141 -0
  272. package/src/memory/embedQueueStore.ts +176 -0
  273. package/src/memory/failurePatternStore.ts +221 -0
  274. package/src/memory/graphStore.ts +352 -0
  275. package/src/memory/noteStore.ts +403 -0
  276. package/src/memory/observationStore.ts +303 -0
  277. package/src/memory/projectRename.ts +147 -0
  278. package/src/memory/rollupSweeper.ts +309 -0
  279. package/src/memory/sessionStore.ts +410 -0
  280. package/src/memory/trajectoryStore.ts +775 -0
  281. package/src/middleware/auth.ts +450 -0
  282. package/src/middleware/rateLimiter.ts +186 -0
  283. package/src/middleware/tracing.ts +70 -0
  284. package/src/routes/dashboard.ts +496 -0
  285. package/src/routes/learning.ts +51 -0
  286. package/src/routes/mcp.ts +349 -0
  287. package/src/routes/memories.ts +33 -0
  288. package/src/scripts/createApiKey.ts +109 -0
  289. package/src/scripts/doctor.ts +359 -0
  290. package/src/scripts/installAgent.ts +1278 -0
  291. package/src/scripts/migrateAgentMemory.ts +263 -0
  292. package/src/scripts/smokeTest.ts +189 -0
  293. package/tsconfig.json +21 -0
@@ -0,0 +1,568 @@
1
+ import { getDb } from '../lib/db';
2
+ import { logger } from '../lib/logger';
3
+ import { deserializeEmbedding, embedQuery, resolveEmbedderRecipe } from './embedding';
4
+ import { verifyOrCreateStoreMeta } from './storeMeta';
5
+ import { getQdrantClient } from './embedWorker';
6
+ import type { SearchRequest, SearchResponse, SearchResultItem } from './types';
7
+
8
+ function tokenize(text: string): string[] {
9
+ if (!text) return [];
10
+ const matches = text.toLowerCase().match(/[a-z0-9_./-]+/g);
11
+ return matches ? matches : [];
12
+ }
13
+
14
+ function cosineSimilarity(a: number[], b: number[]): number {
15
+ if (!a || !b || a.length === 0 || b.length === 0 || a.length !== b.length) return 0;
16
+ let dot = 0;
17
+ let normA = 0;
18
+ let normB = 0;
19
+ for (let i = 0; i < a.length; i++) {
20
+ dot += a[i] * b[i];
21
+ normA += a[i] * a[i];
22
+ normB += b[i] * b[i];
23
+ }
24
+ const denom = Math.sqrt(normA) * Math.sqrt(normB);
25
+ return denom === 0 ? 0 : dot / denom;
26
+ }
27
+
28
+ interface CandidateDoc {
29
+ id: string;
30
+ grain: 'note' | 'trajectory' | 'observation' | 'summary';
31
+ record: Record<string, any>;
32
+ text: string;
33
+ embedding: Buffer | null;
34
+ bm25Score?: number;
35
+ denseScore?: number;
36
+ rrfScore?: number;
37
+ }
38
+
39
+ export function buildQdrantFilter(
40
+ params: SearchRequest,
41
+ grains: string[],
42
+ includeGlobal: boolean
43
+ ): Record<string, any> | undefined {
44
+ const must: any[] = [];
45
+
46
+ // Grains filter
47
+ if (grains.length === 1) {
48
+ must.push({ key: 'grain', match: { value: grains[0] } });
49
+ } else if (grains.length > 1) {
50
+ must.push({ key: 'grain', match: { any: grains } });
51
+ }
52
+
53
+ // Scope filter
54
+ if (params.scope === 'unknown') {
55
+ must.push({ key: 'scope', match: { value: 'unknown' } });
56
+ } else if (params.scope === 'global' || !params.project_id) {
57
+ must.push({ key: 'scope', match: { value: 'global' } });
58
+ } else if (params.project_id) {
59
+ if (includeGlobal) {
60
+ must.push({
61
+ should: [
62
+ {
63
+ must: [
64
+ { key: 'scope', match: { value: 'project' } },
65
+ { key: 'project_id', match: { value: params.project_id } },
66
+ ],
67
+ },
68
+ { key: 'scope', match: { value: 'global' } },
69
+ ],
70
+ });
71
+ } else {
72
+ must.push({ key: 'scope', match: { value: 'project' } });
73
+ must.push({ key: 'project_id', match: { value: params.project_id } });
74
+ }
75
+ }
76
+
77
+ // Metadata filters
78
+ if (params.filters?.type && params.filters.type.length > 0) {
79
+ must.push(
80
+ params.filters.type.length === 1
81
+ ? { key: 'type', match: { value: params.filters.type[0] } }
82
+ : { key: 'type', match: { any: params.filters.type } }
83
+ );
84
+ }
85
+ if (params.filters?.kind) {
86
+ must.push({ key: 'kind', match: { value: params.filters.kind.trim() } });
87
+ }
88
+ if (params.filters?.task_type) {
89
+ must.push({ key: 'task_type', match: { value: params.filters.task_type.trim() } });
90
+ }
91
+ if (params.filters?.file_path) {
92
+ must.push({ key: 'file_path', match: { value: params.filters.file_path.trim() } });
93
+ }
94
+ if (params.filters?.agent) {
95
+ must.push({ key: 'agent', match: { value: params.filters.agent.trim() } });
96
+ }
97
+ if (params.filters?.success !== undefined) {
98
+ must.push({ key: 'success', match: { value: !!params.filters.success } });
99
+ }
100
+ if (params.filters?.note_ref) {
101
+ must.push({ key: 'note_ref', match: { value: params.filters.note_ref.trim() } });
102
+ }
103
+ if (params.filters?.task_ref) {
104
+ must.push({ key: 'task_ref', match: { value: params.filters.task_ref.trim() } });
105
+ }
106
+ if ((params.filters as any)?.session_id) {
107
+ must.push({ key: 'session_id', match: { value: (params.filters as any).session_id.trim() } });
108
+ }
109
+
110
+ if (must.length === 0) return undefined;
111
+ return { must };
112
+ }
113
+
114
+ export async function hybridSearch(params: SearchRequest): Promise<SearchResponse> {
115
+ const q = params.q?.trim() || '';
116
+ const requestedTypes =
117
+ params.record_types && params.record_types.length > 0
118
+ ? params.record_types
119
+ : params.grains;
120
+ const grains =
121
+ requestedTypes && requestedTypes.length > 0 ? requestedTypes : ['note', 'trajectory'];
122
+ const limit = Math.min(Math.max(params.limit ?? 10, 1), 100);
123
+ const includeGlobal = params.include_global !== false;
124
+ const db = getDb();
125
+
126
+ // Scope filter helper
127
+ const buildScopeClause = (tablePrefix: string): { clause: string; params: unknown[] } => {
128
+ const colScope = tablePrefix ? `${tablePrefix}.scope` : 'scope';
129
+ const colProject = tablePrefix ? `${tablePrefix}.project_id` : 'project_id';
130
+
131
+ if (params.scope === 'unknown') {
132
+ return { clause: `${colScope} = 'unknown'`, params: [] };
133
+ }
134
+
135
+ if (params.scope === 'global' || !params.project_id) {
136
+ return { clause: `${colScope} = 'global'`, params: [] };
137
+ }
138
+
139
+ if (params.project_id) {
140
+ if (includeGlobal) {
141
+ return {
142
+ clause: `((${colScope} = 'project' AND ${colProject} = ?) OR ${colScope} = 'global')`,
143
+ params: [params.project_id],
144
+ };
145
+ } else {
146
+ return {
147
+ clause: `(${colScope} = 'project' AND ${colProject} = ?)`,
148
+ params: [params.project_id],
149
+ };
150
+ }
151
+ }
152
+
153
+ return { clause: `${colScope} != 'unknown'`, params: [] };
154
+ };
155
+
156
+ const candidates: CandidateDoc[] = [];
157
+
158
+ // 1. Fetch candidate records from SQLite
159
+ if (grains.includes('note')) {
160
+ const scopeFilter = buildScopeClause('n');
161
+ const conditions: string[] = ['n.is_latest = 1', scopeFilter.clause];
162
+ const queryParams: unknown[] = [...scopeFilter.params];
163
+
164
+ if (params.filters?.type && params.filters.type.length > 0) {
165
+ const placeholders = params.filters.type.map(() => '?').join(',');
166
+ conditions.push(`n.type IN (${placeholders})`);
167
+ queryParams.push(...params.filters.type);
168
+ }
169
+ if (params.filters?.file_path) {
170
+ conditions.push(
171
+ `EXISTS (SELECT 1 FROM note_files nf WHERE nf.note_id = n.id AND nf.file_path = ?)`
172
+ );
173
+ queryParams.push(params.filters.file_path.trim());
174
+ }
175
+ if (params.filters?.agent) {
176
+ conditions.push(`n.author = ?`);
177
+ queryParams.push(params.filters.agent.trim());
178
+ }
179
+
180
+ const rows = db
181
+ .prepare(`SELECT * FROM notes n WHERE ${conditions.join(' AND ')} ORDER BY n.created_at DESC LIMIT 500`)
182
+ .all(...queryParams) as any[];
183
+
184
+ if (rows.length > 0) {
185
+ const noteIds = rows.map((r) => r.id);
186
+ const placeholders = noteIds.map(() => '?').join(',');
187
+
188
+ const allConcepts = db
189
+ .prepare(`SELECT note_id, concept FROM note_concepts WHERE note_id IN (${placeholders})`)
190
+ .all(...noteIds) as Array<{ note_id: string; concept: string }>;
191
+ const conceptsByNoteId = new Map<string, string[]>();
192
+ for (const row of allConcepts) {
193
+ let list = conceptsByNoteId.get(row.note_id);
194
+ if (!list) {
195
+ list = [];
196
+ conceptsByNoteId.set(row.note_id, list);
197
+ }
198
+ list.push(row.concept);
199
+ }
200
+
201
+ const allFiles = db
202
+ .prepare(`SELECT note_id, file_path FROM note_files WHERE note_id IN (${placeholders})`)
203
+ .all(...noteIds) as Array<{ note_id: string; file_path: string }>;
204
+ const filesByNoteId = new Map<string, string[]>();
205
+ for (const row of allFiles) {
206
+ let list = filesByNoteId.get(row.note_id);
207
+ if (!list) {
208
+ list = [];
209
+ filesByNoteId.set(row.note_id, list);
210
+ }
211
+ list.push(row.file_path);
212
+ }
213
+
214
+ for (const row of rows) {
215
+ const concepts = conceptsByNoteId.get(row.id) || [];
216
+ const files = filesByNoteId.get(row.id) || [];
217
+ const record = { ...row, concepts, files };
218
+ const text = `${row.title}\n\n${row.content}\n${concepts.join(' ')}\n${files.join(' ')}`;
219
+ candidates.push({
220
+ id: row.id,
221
+ grain: 'note',
222
+ record,
223
+ text,
224
+ embedding: row.embedding,
225
+ });
226
+ }
227
+ }
228
+ }
229
+
230
+ if (grains.includes('trajectory')) {
231
+ const scopeFilter = buildScopeClause('t');
232
+ const conditions: string[] = [scopeFilter.clause];
233
+ const queryParams: unknown[] = [...scopeFilter.params];
234
+
235
+ if (params.filters?.task_type) {
236
+ conditions.push(`t.task_type = ?`);
237
+ queryParams.push(params.filters.task_type.trim());
238
+ }
239
+ if (params.filters?.agent) {
240
+ conditions.push(`t.agent = ?`);
241
+ queryParams.push(params.filters.agent.trim());
242
+ }
243
+ if (params.filters?.success !== undefined) {
244
+ conditions.push(`t.success = ?`);
245
+ queryParams.push(params.filters.success ? 1 : 0);
246
+ }
247
+ if (params.filters?.note_ref) {
248
+ conditions.push(`t.note_ref = ?`);
249
+ queryParams.push(params.filters.note_ref.trim());
250
+ }
251
+ if (params.filters?.task_ref) {
252
+ conditions.push(`t.task_ref = ?`);
253
+ queryParams.push(params.filters.task_ref.trim());
254
+ }
255
+
256
+ const rows = db
257
+ .prepare(`SELECT * FROM trajectories t WHERE ${conditions.join(' AND ')} ORDER BY t.created_at DESC LIMIT 500`)
258
+ .all(...queryParams) as any[];
259
+
260
+ for (const row of rows) {
261
+ const text = `${row.description || ''}\n${row.result || ''}\n${row.task_type || ''}`;
262
+ candidates.push({
263
+ id: row.id,
264
+ grain: 'trajectory',
265
+ record: row,
266
+ text,
267
+ embedding: row.embedding,
268
+ });
269
+ }
270
+ }
271
+
272
+ if (grains.includes('observation')) {
273
+ const scopeFilter = buildScopeClause('o');
274
+ const conditions: string[] = [scopeFilter.clause];
275
+ const queryParams: unknown[] = [...scopeFilter.params];
276
+
277
+ if (params.filters?.kind) {
278
+ conditions.push(`o.kind = ?`);
279
+ queryParams.push(params.filters.kind.trim());
280
+ }
281
+ if (params.filters?.file_path) {
282
+ conditions.push(`o.file_path = ?`);
283
+ queryParams.push(params.filters.file_path.trim());
284
+ }
285
+ if (params.filters?.agent) {
286
+ conditions.push(`o.agent = ?`);
287
+ queryParams.push(params.filters.agent.trim());
288
+ }
289
+ if (params.filters?.success !== undefined) {
290
+ conditions.push(`o.failed = ?`);
291
+ queryParams.push(params.filters.success ? 0 : 1);
292
+ }
293
+ if (params.filters?.note_ref) {
294
+ conditions.push(`o.note_ref = ?`);
295
+ queryParams.push(params.filters.note_ref.trim());
296
+ }
297
+ if (params.filters?.task_ref) {
298
+ conditions.push(`o.task_ref = ?`);
299
+ queryParams.push(params.filters.task_ref.trim());
300
+ }
301
+
302
+ const rows = db
303
+ .prepare(`SELECT * FROM observations o WHERE ${conditions.join(' AND ')} ORDER BY o.created_at DESC LIMIT 500`)
304
+ .all(...queryParams) as any[];
305
+
306
+ for (const row of rows) {
307
+ const text = `${row.tool_name || ''}\n${row.file_path || ''}\n${row.input || ''}\n${row.output || ''}`;
308
+ candidates.push({
309
+ id: row.id,
310
+ grain: 'observation',
311
+ record: row,
312
+ text,
313
+ embedding: null,
314
+ });
315
+ }
316
+ }
317
+
318
+ if (grains.includes('summary')) {
319
+ const scopeFilter = buildScopeClause('s');
320
+ const conditions: string[] = ['s.is_latest = 1', scopeFilter.clause];
321
+ const queryParams: unknown[] = [...scopeFilter.params];
322
+
323
+ if (params.filters?.kind) {
324
+ conditions.push(`s.kind = ?`);
325
+ queryParams.push(params.filters.kind.trim());
326
+ }
327
+ if (params.filters?.agent) {
328
+ conditions.push(`(s.producer_model = ? OR s.producer_tier = ?)`);
329
+ queryParams.push(params.filters.agent.trim(), params.filters.agent.trim());
330
+ }
331
+ if (params.filters?.success !== undefined) {
332
+ conditions.push(`s.outcome = ?`);
333
+ queryParams.push(params.filters.success ? 'success' : 'failure');
334
+ }
335
+
336
+ const rows = db
337
+ .prepare(`SELECT * FROM summaries s WHERE ${conditions.join(' AND ')} ORDER BY s.created_at DESC LIMIT 500`)
338
+ .all(...queryParams) as any[];
339
+
340
+ if (rows.length > 0) {
341
+ const summaryIds = rows.map((r) => r.id);
342
+ const placeholders = summaryIds.map(() => '?').join(',');
343
+
344
+ const allClaims = db
345
+ .prepare(`SELECT id, summary_id, text, ordinal FROM summary_claims WHERE summary_id IN (${placeholders}) ORDER BY ordinal ASC`)
346
+ .all(...summaryIds) as Array<{ id: string; summary_id: string; text: string; ordinal: number }>;
347
+ const claimsBySummaryId = new Map<string, Array<{ id: string; summary_id: string; text: string; ordinal: number }>>();
348
+ for (const c of allClaims) {
349
+ let list = claimsBySummaryId.get(c.summary_id);
350
+ if (!list) {
351
+ list = [];
352
+ claimsBySummaryId.set(c.summary_id, list);
353
+ }
354
+ list.push(c);
355
+ }
356
+
357
+ const allSources = db
358
+ .prepare(`SELECT summary_id, claim_id, record_id, grain FROM summary_sources WHERE summary_id IN (${placeholders})`)
359
+ .all(...summaryIds) as Array<{ summary_id: string; claim_id: string; record_id: string; grain: string }>;
360
+ const sourcesBySummaryId = new Map<string, Array<{ summary_id: string; claim_id: string; record_id: string; grain: string }>>();
361
+ for (const s of allSources) {
362
+ let list = sourcesBySummaryId.get(s.summary_id);
363
+ if (!list) {
364
+ list = [];
365
+ sourcesBySummaryId.set(s.summary_id, list);
366
+ }
367
+ list.push(s);
368
+ }
369
+
370
+ for (const row of rows) {
371
+ const claims = claimsBySummaryId.get(row.id) || [];
372
+ const sources = sourcesBySummaryId.get(row.id) || [];
373
+ const record = { ...row, claims, sources };
374
+ const text = claims.map((c) => c.text).join('\n');
375
+ candidates.push({
376
+ id: row.id,
377
+ grain: 'summary',
378
+ record,
379
+ text,
380
+ embedding: row.embedding,
381
+ });
382
+ }
383
+ }
384
+ }
385
+
386
+ if (candidates.length === 0) {
387
+ const verification = verifyOrCreateStoreMeta();
388
+ const recipe = resolveEmbedderRecipe();
389
+ const isDegraded = !verification.match && recipe.embed_tier !== 'none';
390
+ const mode = recipe.embed_tier === 'none' || isDegraded ? 'bm25' : 'hybrid';
391
+ return {
392
+ results: [],
393
+ mode,
394
+ degraded: isDegraded ? verification.mismatchReason : undefined,
395
+ };
396
+ }
397
+
398
+ // 2. BM25 scoring over candidates
399
+ const queryTokens = tokenize(q);
400
+ const docTokensMap = new Map<string, string[]>();
401
+ const docLengths: number[] = [];
402
+
403
+ for (const c of candidates) {
404
+ const tokens = tokenize(c.text);
405
+ docTokensMap.set(c.id, tokens);
406
+ docLengths.push(tokens.length);
407
+ }
408
+
409
+ const N = candidates.length;
410
+ const avgdl = docLengths.reduce((a, b) => a + b, 0) / (N || 1);
411
+ const k1 = 1.2;
412
+ const b = 0.75;
413
+
414
+ // Compute document frequency for each query token
415
+ const idfMap = new Map<string, number>();
416
+ for (const token of queryTokens) {
417
+ let df = 0;
418
+ for (const c of candidates) {
419
+ const tokens = docTokensMap.get(c.id)!;
420
+ if (tokens.includes(token)) df++;
421
+ }
422
+ const idf = Math.log(1 + (N - df + 0.5) / (df + 0.5));
423
+ idfMap.set(token, idf);
424
+ }
425
+
426
+ for (const c of candidates) {
427
+ const tokens = docTokensMap.get(c.id)!;
428
+ const tfMap = new Map<string, number>();
429
+ for (const t of tokens) {
430
+ tfMap.set(t, (tfMap.get(t) || 0) + 1);
431
+ }
432
+ let score = 0;
433
+ const len = tokens.length;
434
+ for (const qToken of queryTokens) {
435
+ const tf = tfMap.get(qToken) || 0;
436
+ if (tf > 0) {
437
+ const idf = idfMap.get(qToken) || 0;
438
+ const termScore = idf * ((tf * (k1 + 1)) / (tf + k1 * (1 - b + b * (len / (avgdl || 1)))));
439
+ score += termScore;
440
+ }
441
+ }
442
+ c.bm25Score = score;
443
+ }
444
+
445
+ // 3. Dense scoring
446
+ const recipe = resolveEmbedderRecipe();
447
+ const verification = verifyOrCreateStoreMeta();
448
+ const isMismatch = !verification.match && recipe.embed_tier !== 'none';
449
+
450
+ let mode: 'hybrid' | 'bm25' = 'hybrid';
451
+ let degradedMessage: string | undefined;
452
+
453
+ if (recipe.embed_tier === 'none') {
454
+ mode = 'bm25';
455
+ } else if (isMismatch) {
456
+ mode = 'bm25';
457
+ degradedMessage = verification.mismatchReason;
458
+ }
459
+
460
+ const denseScoresMap = new Map<string, number>();
461
+
462
+ if (mode === 'hybrid') {
463
+ try {
464
+ const queryVec = await embedQuery(q);
465
+ if (queryVec && queryVec.length > 0) {
466
+ // Try Qdrant top points if connected
467
+ const qdrant = getQdrantClient();
468
+ if (qdrant) {
469
+ const alias = verification.meta?.qdrant_alias || 'brain';
470
+ try {
471
+ const filter = buildQdrantFilter(params, grains, includeGlobal);
472
+ const searchRes = await qdrant.search(alias, {
473
+ vector: queryVec,
474
+ limit: Math.max(limit * 2, 50),
475
+ with_payload: true,
476
+ ...(filter ? { filter } : {}),
477
+ });
478
+ for (const pt of searchRes) {
479
+ denseScoresMap.set(String(pt.id), pt.score);
480
+ }
481
+ } catch (qErr) {
482
+ // Fallback to SQLite embedding blobs
483
+ }
484
+ }
485
+
486
+ // For any candidate not scored by Qdrant or if Qdrant was unavailable
487
+ for (const c of candidates) {
488
+ if (!denseScoresMap.has(c.id) && c.embedding) {
489
+ const vec = deserializeEmbedding(c.embedding);
490
+ if (vec.length === queryVec.length) {
491
+ const sim = cosineSimilarity(queryVec, vec);
492
+ denseScoresMap.set(c.id, sim);
493
+ }
494
+ }
495
+ }
496
+ }
497
+ } catch (err) {
498
+ logger.warn({ error: err instanceof Error ? err.message : String(err) }, 'dense query embedding failed, falling back to BM25');
499
+ mode = 'bm25';
500
+ }
501
+ }
502
+
503
+ // 4. Rank candidates and compute RRF
504
+ // Rank BM25
505
+ const bm25Sorted = candidates
506
+ .filter((c) => (c.bm25Score ?? 0) > 0)
507
+ .sort((a, b) => (b.bm25Score ?? 0) - (a.bm25Score ?? 0));
508
+ const bm25RankMap = new Map<string, number>();
509
+ bm25Sorted.forEach((c, idx) => {
510
+ bm25RankMap.set(c.id, idx + 1);
511
+ });
512
+
513
+ // Rank Dense
514
+ const denseRankMap = new Map<string, number>();
515
+ if (mode === 'hybrid') {
516
+ const denseSorted = candidates
517
+ .filter((c) => denseScoresMap.has(c.id) && (denseScoresMap.get(c.id) ?? 0) > 0)
518
+ .sort((a, b) => (denseScoresMap.get(b.id) ?? 0) - (denseScoresMap.get(a.id) ?? 0));
519
+ denseSorted.forEach((c, idx) => {
520
+ denseRankMap.set(c.id, idx + 1);
521
+ });
522
+ }
523
+
524
+ const k_rrf = 60;
525
+ for (const c of candidates) {
526
+ if (mode === 'hybrid') {
527
+ const rankDense = denseRankMap.get(c.id);
528
+ const rankBm25 = bm25RankMap.get(c.id);
529
+ let rrf = 0;
530
+ if (rankDense !== undefined) {
531
+ rrf += 1 / (k_rrf + rankDense);
532
+ }
533
+ if (rankBm25 !== undefined) {
534
+ rrf += 1 / (k_rrf + rankBm25);
535
+ }
536
+ c.rrfScore = rrf;
537
+ } else {
538
+ // In BM25 mode, score is the BM25 score
539
+ c.rrfScore = c.bm25Score ?? 0;
540
+ }
541
+ }
542
+
543
+ // Filter candidates with non-zero score
544
+ const matched = candidates.filter((c) => (c.rrfScore ?? 0) > 0);
545
+ matched.sort((a, b) => (b.rrfScore ?? 0) - (a.rrfScore ?? 0));
546
+
547
+ const sliced = matched.slice(0, limit);
548
+
549
+ const results: SearchResultItem[] = sliced.map((c) => {
550
+ const item: SearchResultItem = {
551
+ id: c.id,
552
+ grain: c.grain,
553
+ score: c.rrfScore ?? 0,
554
+ record: c.record,
555
+ };
556
+ if (c.grain === 'summary') {
557
+ item.claims = c.record.claims;
558
+ item.sources = c.record.sources;
559
+ }
560
+ return item;
561
+ });
562
+
563
+ return {
564
+ results,
565
+ mode,
566
+ degraded: degradedMessage,
567
+ };
568
+ }
@@ -0,0 +1,147 @@
1
+ import { getDb } from '../lib/db';
2
+ import { logger } from '../lib/logger';
3
+ import { resolveEmbedderRecipe } from './embedding';
4
+ import type { ResolvedEmbedderRecipe, StoreMetaRecord } from './types';
5
+
6
+ export interface StoreMetaVerificationResult {
7
+ match: boolean;
8
+ meta: StoreMetaRecord;
9
+ recipe: ResolvedEmbedderRecipe;
10
+ mismatchReason?: string;
11
+ }
12
+
13
+ export function getStoreMeta(): StoreMetaRecord | undefined {
14
+ const db = getDb();
15
+ return db.prepare('SELECT * FROM store_meta WHERE id = 1').get() as StoreMetaRecord | undefined;
16
+ }
17
+
18
+ export function verifyOrCreateStoreMeta(
19
+ customRecipe?: ResolvedEmbedderRecipe
20
+ ): StoreMetaVerificationResult {
21
+ const recipe = customRecipe || resolveEmbedderRecipe();
22
+ const db = getDb();
23
+
24
+ let existing = getStoreMeta();
25
+
26
+ if (!existing) {
27
+ db.prepare(`
28
+ INSERT INTO store_meta (
29
+ id, schema_version, embed_tier, embed_model, embed_model_id,
30
+ embed_dim, doc_prefix, query_prefix, pooling, normalize, qdrant_alias, set_at
31
+ ) VALUES (1, 1, ?, ?, ?, ?, ?, ?, ?, ?, 'brain', unixepoch())
32
+ `).run(
33
+ recipe.embed_tier,
34
+ recipe.embed_model,
35
+ recipe.embed_model_id,
36
+ recipe.embed_dim,
37
+ recipe.doc_prefix,
38
+ recipe.query_prefix,
39
+ recipe.pooling,
40
+ recipe.normalize
41
+ );
42
+
43
+ existing = getStoreMeta()!;
44
+ logger.info(
45
+ {
46
+ embed_tier: recipe.embed_tier,
47
+ embed_model_id: recipe.embed_model_id,
48
+ embed_dim: recipe.embed_dim,
49
+ },
50
+ 'store_meta initialized'
51
+ );
52
+
53
+ return {
54
+ match: true,
55
+ meta: existing,
56
+ recipe,
57
+ };
58
+ }
59
+
60
+ // If configured as 'none', we are deliberately running in bm25-only mode without error
61
+ if (recipe.embed_tier === 'none') {
62
+ return {
63
+ match: true,
64
+ meta: existing,
65
+ recipe,
66
+ };
67
+ }
68
+
69
+ // Compare both embed_model_id and embed_dim, as well as tier and prefixes
70
+ const isMatch =
71
+ existing.embed_tier === recipe.embed_tier &&
72
+ existing.embed_model_id === recipe.embed_model_id &&
73
+ existing.embed_dim === recipe.embed_dim &&
74
+ existing.doc_prefix === recipe.doc_prefix &&
75
+ existing.query_prefix === recipe.query_prefix;
76
+
77
+ if (!isMatch) {
78
+ const mismatchReason = `vector search unavailable: store_meta expects embed_model_id=${existing.embed_model_id} (dim=${existing.embed_dim}, tier=${existing.embed_tier}), but config resolved embed_model_id=${recipe.embed_model_id} (dim=${recipe.embed_dim}, tier=${recipe.embed_tier}). Run POST /maintenance/reembed to rebuild the index.`;
79
+
80
+ logger.error(
81
+ {
82
+ expected: {
83
+ embed_tier: existing.embed_tier,
84
+ embed_model_id: existing.embed_model_id,
85
+ embed_dim: existing.embed_dim,
86
+ },
87
+ resolved: {
88
+ embed_tier: recipe.embed_tier,
89
+ embed_model_id: recipe.embed_model_id,
90
+ embed_dim: recipe.embed_dim,
91
+ },
92
+ reason: mismatchReason,
93
+ },
94
+ 'store_meta mismatch detected'
95
+ );
96
+
97
+ return {
98
+ match: false,
99
+ meta: existing,
100
+ recipe,
101
+ mismatchReason,
102
+ };
103
+ }
104
+
105
+ return {
106
+ match: true,
107
+ meta: existing,
108
+ recipe,
109
+ };
110
+ }
111
+
112
+ export function commitStoreMeta(
113
+ recipe: ResolvedEmbedderRecipe,
114
+ qdrantAlias = 'brain'
115
+ ): StoreMetaRecord {
116
+ const db = getDb();
117
+ db.prepare(`
118
+ INSERT INTO store_meta (
119
+ id, schema_version, embed_tier, embed_model, embed_model_id,
120
+ embed_dim, doc_prefix, query_prefix, pooling, normalize, qdrant_alias, set_at
121
+ ) VALUES (1, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, unixepoch())
122
+ ON CONFLICT(id) DO UPDATE SET
123
+ schema_version = 1,
124
+ embed_tier = excluded.embed_tier,
125
+ embed_model = excluded.embed_model,
126
+ embed_model_id = excluded.embed_model_id,
127
+ embed_dim = excluded.embed_dim,
128
+ doc_prefix = excluded.doc_prefix,
129
+ query_prefix = excluded.query_prefix,
130
+ pooling = excluded.pooling,
131
+ normalize = excluded.normalize,
132
+ qdrant_alias = excluded.qdrant_alias,
133
+ set_at = unixepoch()
134
+ `).run(
135
+ recipe.embed_tier,
136
+ recipe.embed_model,
137
+ recipe.embed_model_id,
138
+ recipe.embed_dim,
139
+ recipe.doc_prefix,
140
+ recipe.query_prefix,
141
+ recipe.pooling,
142
+ recipe.normalize,
143
+ qdrantAlias
144
+ );
145
+
146
+ return getStoreMeta()!;
147
+ }