nox-mem 3.0.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 (457) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -0
  3. package/dist/api/answer.d.ts +116 -0
  4. package/dist/api/answer.js +274 -0
  5. package/dist/api/answer.validate-patch.d.ts +72 -0
  6. package/dist/api/answer.validate-patch.js +52 -0
  7. package/dist/api/brief-diversity.d.ts +64 -0
  8. package/dist/api/brief-diversity.js +91 -0
  9. package/dist/api/brief.d.ts +114 -0
  10. package/dist/api/brief.js +524 -0
  11. package/dist/api/conflict.d.ts +33 -0
  12. package/dist/api/conflict.js +143 -0
  13. package/dist/api/cors.d.ts +73 -0
  14. package/dist/api/cors.js +124 -0
  15. package/dist/api/events-stream-limited.d.ts +133 -0
  16. package/dist/api/events-stream-limited.js +217 -0
  17. package/dist/api/events-stream.d.ts +53 -0
  18. package/dist/api/events-stream.js +125 -0
  19. package/dist/api/export.d.ts +42 -0
  20. package/dist/api/export.js +85 -0
  21. package/dist/api/health-confidence-adapter.d.ts +29 -0
  22. package/dist/api/health-confidence-adapter.js +73 -0
  23. package/dist/api/health-confidence.d.ts +36 -0
  24. package/dist/api/health-confidence.js +141 -0
  25. package/dist/api/hooks.d.ts +50 -0
  26. package/dist/api/hooks.js +115 -0
  27. package/dist/api/import.d.ts +38 -0
  28. package/dist/api/import.js +87 -0
  29. package/dist/api/ingest-event.d.ts +65 -0
  30. package/dist/api/ingest-event.js +153 -0
  31. package/dist/api/mark.d.ts +42 -0
  32. package/dist/api/mark.js +127 -0
  33. package/dist/api/server-deps-a2.d.ts +55 -0
  34. package/dist/api/server-deps-a2.js +138 -0
  35. package/dist/api/server-deps-l2-l3.d.ts +68 -0
  36. package/dist/api/server-deps-l2-l3.js +123 -0
  37. package/dist/api/server-deps-p1.d.ts +84 -0
  38. package/dist/api/server-deps-p1.js +156 -0
  39. package/dist/api/server-deps-p2.d.ts +32 -0
  40. package/dist/api/server-deps-p2.js +84 -0
  41. package/dist/api/server-deps-p5.d.ts +66 -0
  42. package/dist/api/server-deps-p5.js +139 -0
  43. package/dist/api/viewer-static.d.ts +30 -0
  44. package/dist/api/viewer-static.js +102 -0
  45. package/dist/api/wire-up.d.ts +54 -0
  46. package/dist/api/wire-up.js +521 -0
  47. package/dist/api-impact.d.ts +30 -0
  48. package/dist/api-impact.js +196 -0
  49. package/dist/api-server.d.ts +2 -0
  50. package/dist/api-server.js +614 -0
  51. package/dist/backfill-fts-anchor.d.ts +15 -0
  52. package/dist/backfill-fts-anchor.js +97 -0
  53. package/dist/backfill-source-type.d.ts +20 -0
  54. package/dist/backfill-source-type.js +182 -0
  55. package/dist/churn.d.ts +31 -0
  56. package/dist/churn.js +98 -0
  57. package/dist/cli/answer.d.ts +66 -0
  58. package/dist/cli/answer.js +287 -0
  59. package/dist/cli/conflict.d.ts +38 -0
  60. package/dist/cli/conflict.js +282 -0
  61. package/dist/cli/export.d.ts +51 -0
  62. package/dist/cli/export.js +280 -0
  63. package/dist/cli/hooks.d.ts +54 -0
  64. package/dist/cli/hooks.js +133 -0
  65. package/dist/cli/import.d.ts +52 -0
  66. package/dist/cli/import.js +274 -0
  67. package/dist/cli/mark.d.ts +33 -0
  68. package/dist/cli/mark.js +130 -0
  69. package/dist/cli/ocr-batch.d.ts +12 -0
  70. package/dist/cli/ocr-batch.js +411 -0
  71. package/dist/cli/snapshot-main.d.ts +30 -0
  72. package/dist/cli/snapshot-main.js +47 -0
  73. package/dist/cli/viewer.d.ts +35 -0
  74. package/dist/cli/viewer.js +71 -0
  75. package/dist/cli-telemetry.d.ts +36 -0
  76. package/dist/cli-telemetry.js +150 -0
  77. package/dist/compact.d.ts +7 -0
  78. package/dist/compact.js +147 -0
  79. package/dist/consolidate.d.ts +18 -0
  80. package/dist/consolidate.js +475 -0
  81. package/dist/consolidation.d.ts +32 -0
  82. package/dist/consolidation.js +212 -0
  83. package/dist/cross-agent-v2.d.ts +45 -0
  84. package/dist/cross-agent-v2.js +271 -0
  85. package/dist/cross-search.d.ts +11 -0
  86. package/dist/cross-search.js +119 -0
  87. package/dist/crystallize.d.ts +43 -0
  88. package/dist/crystallize.js +111 -0
  89. package/dist/db.d.ts +11 -0
  90. package/dist/db.js +388 -0
  91. package/dist/dedup.d.ts +1 -0
  92. package/dist/dedup.js +106 -0
  93. package/dist/detect-changes.d.ts +29 -0
  94. package/dist/detect-changes.js +236 -0
  95. package/dist/digest.d.ts +1 -0
  96. package/dist/digest.js +205 -0
  97. package/dist/doctor.d.ts +1 -0
  98. package/dist/doctor.js +71 -0
  99. package/dist/embed.d.ts +45 -0
  100. package/dist/embed.js +257 -0
  101. package/dist/evals.d.ts +176 -0
  102. package/dist/evals.js +351 -0
  103. package/dist/generate-user-profile.d.ts +18 -0
  104. package/dist/generate-user-profile.js +163 -0
  105. package/dist/graphify-ingest.d.ts +18 -0
  106. package/dist/graphify-ingest.js +158 -0
  107. package/dist/impact.d.ts +39 -0
  108. package/dist/impact.js +143 -0
  109. package/dist/index.d.ts +2 -0
  110. package/dist/index.js +689 -0
  111. package/dist/ingest-entity.d.ts +44 -0
  112. package/dist/ingest-entity.js +197 -0
  113. package/dist/ingest.d.ts +13 -0
  114. package/dist/ingest.js +210 -0
  115. package/dist/kg-llm.d.ts +39 -0
  116. package/dist/kg-llm.js +295 -0
  117. package/dist/knowledge-graph.d.ts +72 -0
  118. package/dist/knowledge-graph.js +507 -0
  119. package/dist/lib/answer/config.d.ts +41 -0
  120. package/dist/lib/answer/config.js +70 -0
  121. package/dist/lib/answer/index.d.ts +47 -0
  122. package/dist/lib/answer/index.js +221 -0
  123. package/dist/lib/answer/prompt.d.ts +37 -0
  124. package/dist/lib/answer/prompt.js +88 -0
  125. package/dist/lib/answer/provider.d.ts +47 -0
  126. package/dist/lib/answer/provider.js +101 -0
  127. package/dist/lib/answer/retrieval.d.ts +36 -0
  128. package/dist/lib/answer/retrieval.js +92 -0
  129. package/dist/lib/answer/telemetry.d.ts +99 -0
  130. package/dist/lib/answer/telemetry.js +154 -0
  131. package/dist/lib/answer/types.d.ts +108 -0
  132. package/dist/lib/answer/types.js +1 -0
  133. package/dist/lib/api/error-leak-fix.d.ts +54 -0
  134. package/dist/lib/api/error-leak-fix.js +55 -0
  135. package/dist/lib/api/safe-error-message.d.ts +70 -0
  136. package/dist/lib/api/safe-error-message.js +122 -0
  137. package/dist/lib/archive/common-passwords.d.ts +37 -0
  138. package/dist/lib/archive/common-passwords.js +753 -0
  139. package/dist/lib/archive/encryption.d.ts +81 -0
  140. package/dist/lib/archive/encryption.js +236 -0
  141. package/dist/lib/archive/enforce-strength.d.ts +54 -0
  142. package/dist/lib/archive/enforce-strength.js +70 -0
  143. package/dist/lib/archive/entropy.d.ts +34 -0
  144. package/dist/lib/archive/entropy.js +180 -0
  145. package/dist/lib/archive/export-locking.d.ts +102 -0
  146. package/dist/lib/archive/export-locking.js +202 -0
  147. package/dist/lib/archive/format.d.ts +20 -0
  148. package/dist/lib/archive/format.js +174 -0
  149. package/dist/lib/archive/index.d.ts +23 -0
  150. package/dist/lib/archive/index.js +17 -0
  151. package/dist/lib/archive/manifest.d.ts +53 -0
  152. package/dist/lib/archive/manifest.js +183 -0
  153. package/dist/lib/archive/migration.d.ts +36 -0
  154. package/dist/lib/archive/migration.js +100 -0
  155. package/dist/lib/archive/migrations/v18_to_v19.d.ts +16 -0
  156. package/dist/lib/archive/migrations/v18_to_v19.js +18 -0
  157. package/dist/lib/archive/orchestrator.d.ts +166 -0
  158. package/dist/lib/archive/orchestrator.js +428 -0
  159. package/dist/lib/archive/serializers/chunks.d.ts +30 -0
  160. package/dist/lib/archive/serializers/chunks.js +113 -0
  161. package/dist/lib/archive/serializers/embeddings.d.ts +36 -0
  162. package/dist/lib/archive/serializers/embeddings.js +115 -0
  163. package/dist/lib/archive/serializers/kg.d.ts +28 -0
  164. package/dist/lib/archive/serializers/kg.js +184 -0
  165. package/dist/lib/archive/serializers/ops_audit.d.ts +21 -0
  166. package/dist/lib/archive/serializers/ops_audit.js +97 -0
  167. package/dist/lib/archive/server-deps.d.ts +131 -0
  168. package/dist/lib/archive/server-deps.js +232 -0
  169. package/dist/lib/archive/strength.d.ts +50 -0
  170. package/dist/lib/archive/strength.js +77 -0
  171. package/dist/lib/archive/types.d.ts +159 -0
  172. package/dist/lib/archive/types.js +45 -0
  173. package/dist/lib/archive/unpack-streaming.d.ts +70 -0
  174. package/dist/lib/archive/unpack-streaming.js +255 -0
  175. package/dist/lib/auth/localhost-guard.d.ts +106 -0
  176. package/dist/lib/auth/localhost-guard.js +164 -0
  177. package/dist/lib/confidence/config.d.ts +37 -0
  178. package/dist/lib/confidence/config.js +107 -0
  179. package/dist/lib/confidence/db-shim-singleton.d.ts +20 -0
  180. package/dist/lib/confidence/db-shim-singleton.js +41 -0
  181. package/dist/lib/confidence/db-shim.d.ts +47 -0
  182. package/dist/lib/confidence/db-shim.js +141 -0
  183. package/dist/lib/confidence/mark.d.ts +58 -0
  184. package/dist/lib/confidence/mark.js +168 -0
  185. package/dist/lib/confidence/ranking.d.ts +69 -0
  186. package/dist/lib/confidence/ranking.js +101 -0
  187. package/dist/lib/confidence/search-filter.d.ts +44 -0
  188. package/dist/lib/confidence/search-filter.js +103 -0
  189. package/dist/lib/confidence/types.d.ts +146 -0
  190. package/dist/lib/confidence/types.js +20 -0
  191. package/dist/lib/confidence/write-hooks.d.ts +50 -0
  192. package/dist/lib/confidence/write-hooks.js +159 -0
  193. package/dist/lib/conflict/audit-fk-check.d.ts +72 -0
  194. package/dist/lib/conflict/audit-fk-check.js +131 -0
  195. package/dist/lib/conflict/audit-writer.d.ts +39 -0
  196. package/dist/lib/conflict/audit-writer.js +133 -0
  197. package/dist/lib/conflict/db-singleton.d.ts +28 -0
  198. package/dist/lib/conflict/db-singleton.js +61 -0
  199. package/dist/lib/conflict/db.d.ts +27 -0
  200. package/dist/lib/conflict/db.js +20 -0
  201. package/dist/lib/conflict/detector-direct.d.ts +21 -0
  202. package/dist/lib/conflict/detector-direct.js +105 -0
  203. package/dist/lib/conflict/evidence.d.ts +24 -0
  204. package/dist/lib/conflict/evidence.js +76 -0
  205. package/dist/lib/conflict/index.d.ts +14 -0
  206. package/dist/lib/conflict/index.js +12 -0
  207. package/dist/lib/conflict/scheduler.d.ts +78 -0
  208. package/dist/lib/conflict/scheduler.js +111 -0
  209. package/dist/lib/conflict/shadow.d.ts +75 -0
  210. package/dist/lib/conflict/shadow.js +161 -0
  211. package/dist/lib/conflict/types.d.ts +133 -0
  212. package/dist/lib/conflict/types.js +19 -0
  213. package/dist/lib/cost-cap.d.ts +94 -0
  214. package/dist/lib/cost-cap.js +129 -0
  215. package/dist/lib/deps/deps-registry.d.ts +111 -0
  216. package/dist/lib/deps/deps-registry.js +209 -0
  217. package/dist/lib/error-sanitizer/middleware.d.ts +43 -0
  218. package/dist/lib/error-sanitizer/middleware.js +100 -0
  219. package/dist/lib/error-sanitizer/sanitize.d.ts +78 -0
  220. package/dist/lib/error-sanitizer/sanitize.js +202 -0
  221. package/dist/lib/eval-batch.d.ts +34 -0
  222. package/dist/lib/eval-batch.js +103 -0
  223. package/dist/lib/eval-metrics.d.ts +36 -0
  224. package/dist/lib/eval-metrics.js +95 -0
  225. package/dist/lib/eval.d.ts +106 -0
  226. package/dist/lib/eval.js +343 -0
  227. package/dist/lib/events/bus.d.ts +135 -0
  228. package/dist/lib/events/bus.js +95 -0
  229. package/dist/lib/fts-anchor.d.ts +1 -0
  230. package/dist/lib/fts-anchor.js +131 -0
  231. package/dist/lib/hooks/classifier.d.ts +47 -0
  232. package/dist/lib/hooks/classifier.js +129 -0
  233. package/dist/lib/hooks/config.d.ts +49 -0
  234. package/dist/lib/hooks/config.js +106 -0
  235. package/dist/lib/hooks/decorators.d.ts +35 -0
  236. package/dist/lib/hooks/decorators.js +59 -0
  237. package/dist/lib/hooks/pipeline.d.ts +76 -0
  238. package/dist/lib/hooks/pipeline.js +213 -0
  239. package/dist/lib/hooks/privacy-filter-adapter.d.ts +55 -0
  240. package/dist/lib/hooks/privacy-filter-adapter.js +84 -0
  241. package/dist/lib/hooks/rate-limit-constant-time.d.ts +57 -0
  242. package/dist/lib/hooks/rate-limit-constant-time.js +69 -0
  243. package/dist/lib/hooks/rate-limit-dryrun-fix.d.ts +71 -0
  244. package/dist/lib/hooks/rate-limit-dryrun-fix.js +110 -0
  245. package/dist/lib/hooks/rate-limit.d.ts +54 -0
  246. package/dist/lib/hooks/rate-limit.js +122 -0
  247. package/dist/lib/hooks/server-deps.d.ts +61 -0
  248. package/dist/lib/hooks/server-deps.js +92 -0
  249. package/dist/lib/hooks/source-allowlist.d.ts +26 -0
  250. package/dist/lib/hooks/source-allowlist.js +53 -0
  251. package/dist/lib/hooks/types.d.ts +129 -0
  252. package/dist/lib/hooks/types.js +24 -0
  253. package/dist/lib/hooks/worker.d.ts +56 -0
  254. package/dist/lib/hooks/worker.js +150 -0
  255. package/dist/lib/ingest-router.d.ts +25 -0
  256. package/dist/lib/ingest-router.js +103 -0
  257. package/dist/lib/ocr-detector.d.ts +61 -0
  258. package/dist/lib/ocr-detector.js +138 -0
  259. package/dist/lib/ocr-engine-stub.d.ts +48 -0
  260. package/dist/lib/ocr-engine-stub.js +190 -0
  261. package/dist/lib/ocr-engines/google-doc-ai.d.ts +36 -0
  262. package/dist/lib/ocr-engines/google-doc-ai.js +164 -0
  263. package/dist/lib/ocr-jobs.d.ts +67 -0
  264. package/dist/lib/ocr-jobs.js +129 -0
  265. package/dist/lib/op-audit-extension/ran-at-guard.d.ts +86 -0
  266. package/dist/lib/op-audit-extension/ran-at-guard.js +110 -0
  267. package/dist/lib/op-audit.d.ts +71 -0
  268. package/dist/lib/op-audit.js +777 -0
  269. package/dist/lib/privacy-br/detector.d.ts +42 -0
  270. package/dist/lib/privacy-br/detector.js +130 -0
  271. package/dist/lib/privacy-br/index.d.ts +20 -0
  272. package/dist/lib/privacy-br/index.js +20 -0
  273. package/dist/lib/privacy-br/integration.d.ts +71 -0
  274. package/dist/lib/privacy-br/integration.js +74 -0
  275. package/dist/lib/privacy-br/patterns.d.ts +117 -0
  276. package/dist/lib/privacy-br/patterns.js +434 -0
  277. package/dist/lib/privacy-br/redact.d.ts +42 -0
  278. package/dist/lib/privacy-br/redact.js +103 -0
  279. package/dist/lib/privacy-br/types.d.ts +55 -0
  280. package/dist/lib/privacy-br/types.js +25 -0
  281. package/dist/lib/regex-extract/extractor.d.ts +30 -0
  282. package/dist/lib/regex-extract/extractor.js +91 -0
  283. package/dist/lib/regex-extract/frontmatter.d.ts +44 -0
  284. package/dist/lib/regex-extract/frontmatter.js +169 -0
  285. package/dist/lib/regex-extract/index.d.ts +14 -0
  286. package/dist/lib/regex-extract/index.js +14 -0
  287. package/dist/lib/regex-extract/ingest-router-l4.d.ts +76 -0
  288. package/dist/lib/regex-extract/ingest-router-l4.js +102 -0
  289. package/dist/lib/regex-extract/patterns.d.ts +61 -0
  290. package/dist/lib/regex-extract/patterns.js +91 -0
  291. package/dist/lib/regex-extract/production-wire.d.ts +128 -0
  292. package/dist/lib/regex-extract/production-wire.js +202 -0
  293. package/dist/lib/regex-extract/reconcile.d.ts +162 -0
  294. package/dist/lib/regex-extract/reconcile.js +210 -0
  295. package/dist/lib/regex-extract/strip-code.d.ts +24 -0
  296. package/dist/lib/regex-extract/strip-code.js +52 -0
  297. package/dist/lib/regex-extract/types.d.ts +48 -0
  298. package/dist/lib/regex-extract/types.js +25 -0
  299. package/dist/lib/reranker.d.ts +80 -0
  300. package/dist/lib/reranker.js +324 -0
  301. package/dist/lib/shadow-tracker.d.ts +191 -0
  302. package/dist/lib/shadow-tracker.js +384 -0
  303. package/dist/lib/spo-injection.d.ts +52 -0
  304. package/dist/lib/spo-injection.js +166 -0
  305. package/dist/lib/telemetry-collector.d.ts +158 -0
  306. package/dist/lib/telemetry-collector.js +249 -0
  307. package/dist/lib/temporal-detector.d.ts +27 -0
  308. package/dist/lib/temporal-detector.js +81 -0
  309. package/dist/lib/viewer/auth.d.ts +37 -0
  310. package/dist/lib/viewer/auth.js +70 -0
  311. package/dist/lib/viewer/backpressure.d.ts +59 -0
  312. package/dist/lib/viewer/backpressure.js +100 -0
  313. package/dist/lib/viewer/broadcast-singleton.d.ts +34 -0
  314. package/dist/lib/viewer/broadcast-singleton.js +49 -0
  315. package/dist/lib/viewer/broadcast.d.ts +66 -0
  316. package/dist/lib/viewer/broadcast.js +96 -0
  317. package/dist/lib/viewer/event-types.d.ts +132 -0
  318. package/dist/lib/viewer/event-types.js +74 -0
  319. package/dist/lib/viewer/instrumentation.d.ts +106 -0
  320. package/dist/lib/viewer/instrumentation.js +224 -0
  321. package/dist/lib/viewer/migration.d.ts +23 -0
  322. package/dist/lib/viewer/migration.js +56 -0
  323. package/dist/lib/viewer/redaction.d.ts +44 -0
  324. package/dist/lib/viewer/redaction.js +139 -0
  325. package/dist/lib/viewer/session.d.ts +51 -0
  326. package/dist/lib/viewer/session.js +87 -0
  327. package/dist/mcp/tools/answer.d.ts +94 -0
  328. package/dist/mcp/tools/answer.js +213 -0
  329. package/dist/mcp/tools/archive.d.ts +152 -0
  330. package/dist/mcp/tools/archive.js +170 -0
  331. package/dist/mcp/tools/conflict.d.ts +44 -0
  332. package/dist/mcp/tools/conflict.js +130 -0
  333. package/dist/mcp/tools/hooks.d.ts +29 -0
  334. package/dist/mcp/tools/hooks.js +78 -0
  335. package/dist/mcp/tools/mark.d.ts +38 -0
  336. package/dist/mcp/tools/mark.js +82 -0
  337. package/dist/mcp/tools/viewer.d.ts +58 -0
  338. package/dist/mcp/tools/viewer.js +64 -0
  339. package/dist/mcp-server.d.ts +2 -0
  340. package/dist/mcp-server.js +395 -0
  341. package/dist/metrics.d.ts +3 -0
  342. package/dist/metrics.js +59 -0
  343. package/dist/noise-filter.d.ts +18 -0
  344. package/dist/noise-filter.js +142 -0
  345. package/dist/notion-sync.d.ts +7 -0
  346. package/dist/notion-sync.js +97 -0
  347. package/dist/observability/adapters/a3-adapter.d.ts +63 -0
  348. package/dist/observability/adapters/a3-adapter.js +83 -0
  349. package/dist/observability/adapters/p1-adapter.d.ts +49 -0
  350. package/dist/observability/adapters/p1-adapter.js +63 -0
  351. package/dist/observability/adapters/p5-adapter.d.ts +36 -0
  352. package/dist/observability/adapters/p5-adapter.js +71 -0
  353. package/dist/observability/cardinality.d.ts +61 -0
  354. package/dist/observability/cardinality.js +300 -0
  355. package/dist/observability/collectors/db-stats.collector.d.ts +9 -0
  356. package/dist/observability/collectors/db-stats.collector.js +88 -0
  357. package/dist/observability/collectors/eventbus.collector.d.ts +6 -0
  358. package/dist/observability/collectors/eventbus.collector.js +50 -0
  359. package/dist/observability/collectors/process.collector.d.ts +7 -0
  360. package/dist/observability/collectors/process.collector.js +93 -0
  361. package/dist/observability/collectors/provider-telemetry.collector.d.ts +11 -0
  362. package/dist/observability/collectors/provider-telemetry.collector.js +112 -0
  363. package/dist/observability/collectors/search-telemetry.collector.d.ts +12 -0
  364. package/dist/observability/collectors/search-telemetry.collector.js +76 -0
  365. package/dist/observability/exporter.d.ts +30 -0
  366. package/dist/observability/exporter.js +182 -0
  367. package/dist/observability/index.d.ts +22 -0
  368. package/dist/observability/index.js +21 -0
  369. package/dist/observability/metrics.d.ts +53 -0
  370. package/dist/observability/metrics.js +213 -0
  371. package/dist/observability/privacy-guard.d.ts +32 -0
  372. package/dist/observability/privacy-guard.js +116 -0
  373. package/dist/observability/record.d.ts +83 -0
  374. package/dist/observability/record.js +217 -0
  375. package/dist/observability/registry.d.ts +60 -0
  376. package/dist/observability/registry.js +93 -0
  377. package/dist/observability/types.d.ts +115 -0
  378. package/dist/observability/types.js +235 -0
  379. package/dist/observability.d.ts +131 -0
  380. package/dist/observability.js +234 -0
  381. package/dist/plugins/nox-hooks/index.d.ts +61 -0
  382. package/dist/plugins/nox-hooks/index.js +99 -0
  383. package/dist/primer.d.ts +1 -0
  384. package/dist/primer.js +100 -0
  385. package/dist/privacy/filter.d.ts +27 -0
  386. package/dist/privacy/filter.js +74 -0
  387. package/dist/privacy/patterns.d.ts +29 -0
  388. package/dist/privacy/patterns.js +178 -0
  389. package/dist/privacy/tag-parser.d.ts +24 -0
  390. package/dist/privacy/tag-parser.js +29 -0
  391. package/dist/project-context-gen.d.ts +10 -0
  392. package/dist/project-context-gen.js +106 -0
  393. package/dist/providers/embedding/gemini.d.ts +73 -0
  394. package/dist/providers/embedding/gemini.js +118 -0
  395. package/dist/providers/embedding/openai.d.ts +76 -0
  396. package/dist/providers/embedding/openai.js +123 -0
  397. package/dist/providers/embedding/types.d.ts +39 -0
  398. package/dist/providers/embedding/types.js +1 -0
  399. package/dist/providers/embedding/voyage.d.ts +36 -0
  400. package/dist/providers/embedding/voyage.js +29 -0
  401. package/dist/providers/index.d.ts +116 -0
  402. package/dist/providers/index.js +158 -0
  403. package/dist/providers/llm/anthropic.d.ts +29 -0
  404. package/dist/providers/llm/anthropic.js +28 -0
  405. package/dist/providers/llm/chain.d.ts +99 -0
  406. package/dist/providers/llm/chain.js +213 -0
  407. package/dist/providers/llm/gemini.d.ts +48 -0
  408. package/dist/providers/llm/gemini.js +96 -0
  409. package/dist/providers/llm/openai.d.ts +64 -0
  410. package/dist/providers/llm/openai.js +109 -0
  411. package/dist/providers/llm/types.d.ts +47 -0
  412. package/dist/providers/llm/types.js +1 -0
  413. package/dist/providers/telemetry.d.ts +87 -0
  414. package/dist/providers/telemetry.js +156 -0
  415. package/dist/providers/types.d.ts +42 -0
  416. package/dist/providers/types.js +59 -0
  417. package/dist/query-entity-count.d.ts +54 -0
  418. package/dist/query-entity-count.js +171 -0
  419. package/dist/reflect.d.ts +26 -0
  420. package/dist/reflect.js +290 -0
  421. package/dist/reindex-errors.d.ts +7 -0
  422. package/dist/reindex-errors.js +21 -0
  423. package/dist/reindex.d.ts +16 -0
  424. package/dist/reindex.js +293 -0
  425. package/dist/retention.d.ts +40 -0
  426. package/dist/retention.js +86 -0
  427. package/dist/salience.d.ts +85 -0
  428. package/dist/salience.js +245 -0
  429. package/dist/scripts/migrate-v17-ops-audit.d.ts +17 -0
  430. package/dist/scripts/migrate-v17-ops-audit.js +70 -0
  431. package/dist/search-dedup.d.ts +44 -0
  432. package/dist/search-dedup.js +137 -0
  433. package/dist/search-expansion.d.ts +20 -0
  434. package/dist/search-expansion.js +99 -0
  435. package/dist/search.d.ts +62 -0
  436. package/dist/search.js +582 -0
  437. package/dist/seh-detector.d.ts +31 -0
  438. package/dist/seh-detector.js +201 -0
  439. package/dist/self-improve.d.ts +1 -0
  440. package/dist/self-improve.js +189 -0
  441. package/dist/session-distill.d.ts +29 -0
  442. package/dist/session-distill.js +325 -0
  443. package/dist/session-update.d.ts +1 -0
  444. package/dist/session-update.js +54 -0
  445. package/dist/shared-memory.d.ts +24 -0
  446. package/dist/shared-memory.js +104 -0
  447. package/dist/stats.d.ts +1 -0
  448. package/dist/stats.js +44 -0
  449. package/dist/temporal-retrieval.d.ts +132 -0
  450. package/dist/temporal-retrieval.js +495 -0
  451. package/dist/tier-manager.d.ts +69 -0
  452. package/dist/tier-manager.js +225 -0
  453. package/dist/vectorize.d.ts +16 -0
  454. package/dist/vectorize.js +91 -0
  455. package/dist/watch.d.ts +8 -0
  456. package/dist/watch.js +124 -0
  457. package/package.json +74 -0
@@ -0,0 +1,221 @@
1
+ /**
2
+ * src/lib/answer/index.ts — Public API for P1 (T1-T4 + minimal T5 partial).
3
+ *
4
+ * Exports:
5
+ * answer(opts) → AnswerResult
6
+ * Types: AnswerOpts, AnswerResult, Citation, RetrievedChunk, AnswerMetadata
7
+ * Helpers (re-export for adjacency modules): selectProvider, buildPrompt, retrieveContext
8
+ *
9
+ * Pipeline (T1-T4 scope + minimal T5/T6 anti-hallucination retry-once):
10
+ * 1. resolveConfig(opts) → ResolvedConfig
11
+ * 2. retrieveContext(question, topK) → RetrievedChunk[]
12
+ * 3. buildPrompt(question, chunks) → {system, user}
13
+ * 4. provider.complete(prompt + cfg) → LLMCallResult
14
+ * 5. parseCitations(text, chunks) → { citations, hallucinated[] }
15
+ * 6. If hallucinated.length > 0 → retry once with buildRetryPrompt()
16
+ * 7. If retry still hallucinates → throw AnswerError('hallucination_after_retry')
17
+ *
18
+ * Empty retrieval → returns canonical "no memory matches" answer WITHOUT
19
+ * calling the LLM (kickoff §6 retrieval_empty path).
20
+ */
21
+ import { resolveConfig } from "./config.js";
22
+ import { buildPrompt, buildRetryPrompt } from "./prompt.js";
23
+ import { retrieveContext } from "./retrieval.js";
24
+ import { selectProvider } from "./provider.js";
25
+ export { selectProvider, MockProvider } from "./provider.js";
26
+ export { buildPrompt, buildRetryPrompt } from "./prompt.js";
27
+ export { retrieveContext, __setRawSearchForTests } from "./retrieval.js";
28
+ export { resolveConfig } from "./config.js";
29
+ /** Thrown when the pipeline produces an unrecoverable failure. */
30
+ export class AnswerError extends Error {
31
+ reason;
32
+ metadata;
33
+ constructor(reason, message, metadata) {
34
+ super(message);
35
+ this.name = "AnswerError";
36
+ this.reason = reason;
37
+ this.metadata = metadata;
38
+ }
39
+ }
40
+ const CANONICAL_EMPTY_ANSWER = "I have no memory matches for this question.";
41
+ const CITATION_REGEX = /\[chunk_(\d+)\]/g;
42
+ const SNIPPET_MAX_CHARS = 200;
43
+ export async function answer(opts) {
44
+ const t0 = Date.now();
45
+ if (!opts || typeof opts.question !== "string" || opts.question.trim().length === 0) {
46
+ throw new AnswerError("invalid_input", "answer(): question is required", {
47
+ latency_ms: Date.now() - t0,
48
+ provider: "n/a",
49
+ model: "n/a",
50
+ retrieval_count: 0,
51
+ });
52
+ }
53
+ const cfg = resolveConfig(opts);
54
+ const provider = opts.providerOverride ?? selectProvider(cfg.provider);
55
+ const retrieve = opts.retrieveOverride ?? retrieveContext;
56
+ // ── Step 2: retrieval ──────────────────────────────────────────────────
57
+ const chunks = await retrieve(opts.question, cfg.topK);
58
+ if (chunks.length === 0) {
59
+ // Honour kickoff §6 retrieval_empty: short-circuit, no LLM spend.
60
+ return {
61
+ answer: CANONICAL_EMPTY_ANSWER,
62
+ citations: [],
63
+ metadata: {
64
+ latency_ms: Date.now() - t0,
65
+ tokens_in: 0,
66
+ tokens_out: 0,
67
+ provider: provider.name,
68
+ model: cfg.model,
69
+ retrieval_count: 0,
70
+ fallback_used: false,
71
+ failed_reason: "retrieval_empty",
72
+ retry_count: 0,
73
+ },
74
+ };
75
+ }
76
+ // ── Steps 3-4: prompt + first LLM call ─────────────────────────────────
77
+ const firstPrompt = buildPrompt(opts.question, chunks, cfg.maxTokens);
78
+ let llmRes;
79
+ try {
80
+ llmRes = await provider.complete({
81
+ system: firstPrompt.system,
82
+ user: firstPrompt.user,
83
+ maxTokens: cfg.maxTokens,
84
+ temperature: cfg.temperature,
85
+ model: cfg.model,
86
+ });
87
+ }
88
+ catch (err) {
89
+ throw new AnswerError("llm_error", `LLM call failed: ${err.message}`, {
90
+ latency_ms: Date.now() - t0,
91
+ provider: provider.name,
92
+ model: cfg.model,
93
+ retrieval_count: chunks.length,
94
+ failed_reason: "llm_error",
95
+ });
96
+ }
97
+ // ── Step 5: citation parse + validation ────────────────────────────────
98
+ const first = parseCitations(llmRes.text, chunks);
99
+ let finalText = llmRes.text;
100
+ let finalCitations = first.citations;
101
+ let tokensIn = llmRes.tokensIn;
102
+ let tokensOut = llmRes.tokensOut;
103
+ let retryCount = 0;
104
+ let fallbackUsed = false;
105
+ let failedReason;
106
+ if (first.hallucinated.length > 0) {
107
+ // ── Step 6: retry once with stricter prompt ─────────────────────────
108
+ fallbackUsed = true;
109
+ failedReason = "hallucinated_citation"; // tentative; cleared if retry succeeds
110
+ const retryPrompt = buildRetryPrompt(opts.question, chunks, cfg.maxTokens);
111
+ let retryRes;
112
+ try {
113
+ retryRes = await provider.complete({
114
+ system: retryPrompt.system,
115
+ user: retryPrompt.user,
116
+ maxTokens: cfg.maxTokens,
117
+ temperature: cfg.temperature,
118
+ model: cfg.model,
119
+ });
120
+ }
121
+ catch (err) {
122
+ throw new AnswerError("llm_error", `LLM retry call failed: ${err.message}`, {
123
+ latency_ms: Date.now() - t0,
124
+ provider: provider.name,
125
+ model: cfg.model,
126
+ retrieval_count: chunks.length,
127
+ fallback_used: true,
128
+ retry_count: 1,
129
+ failed_reason: "llm_error",
130
+ });
131
+ }
132
+ retryCount = 1;
133
+ tokensIn += retryRes.tokensIn;
134
+ tokensOut += retryRes.tokensOut;
135
+ const second = parseCitations(retryRes.text, chunks);
136
+ if (second.hallucinated.length > 0) {
137
+ // ── Step 7: hard fail per kickoff critical decision #3 ────────────
138
+ throw new AnswerError("hallucination_after_retry", `LLM cited unknown markers after retry: [${second.hallucinated.join(", ")}]`, {
139
+ latency_ms: Date.now() - t0,
140
+ tokens_in: tokensIn,
141
+ tokens_out: tokensOut,
142
+ provider: provider.name,
143
+ model: cfg.model,
144
+ retrieval_count: chunks.length,
145
+ fallback_used: true,
146
+ retry_count: 1,
147
+ failed_reason: "hallucination_after_retry",
148
+ });
149
+ }
150
+ finalText = retryRes.text;
151
+ finalCitations = second.citations;
152
+ failedReason = undefined; // retry succeeded
153
+ }
154
+ const metadata = {
155
+ latency_ms: Date.now() - t0,
156
+ tokens_in: tokensIn,
157
+ tokens_out: tokensOut,
158
+ provider: provider.name,
159
+ model: cfg.model,
160
+ retrieval_count: chunks.length,
161
+ fallback_used: fallbackUsed,
162
+ retry_count: retryCount,
163
+ };
164
+ if (failedReason !== undefined)
165
+ metadata.failed_reason = failedReason;
166
+ return {
167
+ answer: finalText,
168
+ citations: finalCitations,
169
+ metadata,
170
+ };
171
+ }
172
+ /**
173
+ * Extract `[chunk_N]` markers from LLM output, validate each against the
174
+ * retrieval set, and return Citation objects + the list of hallucinated
175
+ * markers (out-of-range N).
176
+ *
177
+ * Exported for testability.
178
+ */
179
+ export function parseCitations(text, chunks) {
180
+ // Build a lookup of marker_id → chunk for O(1) validation.
181
+ const byMarker = new Map();
182
+ for (const c of chunks)
183
+ byMarker.set(c.marker_id, c);
184
+ const seen = new Set();
185
+ const citations = [];
186
+ const hallucinated = [];
187
+ // Reset regex state defensively (it is /g so .exec advances lastIndex).
188
+ CITATION_REGEX.lastIndex = 0;
189
+ let m;
190
+ while ((m = CITATION_REGEX.exec(text)) !== null) {
191
+ const idxStr = m[1];
192
+ if (idxStr === undefined)
193
+ continue;
194
+ const marker = `chunk_${idxStr}`;
195
+ if (seen.has(marker))
196
+ continue;
197
+ seen.add(marker);
198
+ const chunk = byMarker.get(marker);
199
+ if (!chunk) {
200
+ hallucinated.push(marker);
201
+ continue;
202
+ }
203
+ const citation = {
204
+ chunk_id: chunk.chunk_id,
205
+ marker_id: chunk.marker_id,
206
+ file_path: chunk.file_path,
207
+ snippet: snippetOf(chunk.content),
208
+ };
209
+ if (chunk.line_range !== undefined) {
210
+ citation.line_range = chunk.line_range;
211
+ }
212
+ citations.push(citation);
213
+ }
214
+ return { citations, hallucinated };
215
+ }
216
+ function snippetOf(content) {
217
+ const trimmed = content.replace(/\s+/g, " ").trim();
218
+ if (trimmed.length <= SNIPPET_MAX_CHARS)
219
+ return trimmed;
220
+ return trimmed.slice(0, SNIPPET_MAX_CHARS - 1) + "…";
221
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * src/lib/answer/prompt.ts — Prompt assembly for P1 (T3 scope).
3
+ *
4
+ * Two builders:
5
+ * buildPrompt() — initial pass; standard anti-hallucination guard.
6
+ * buildRetryPrompt() — stricter variant when first pass cited a marker
7
+ * that did not exist in the retrieval set
8
+ * (anti-hallucination retry, partial T5/T6).
9
+ *
10
+ * Design (kickoff §T3 + critical decision #1):
11
+ * - LLM only ever sees marker_ids (`chunk_1`..`chunk_N`), never DB ids.
12
+ * - System prompt = anti-hallucination guard + citation rule.
13
+ * - User prompt = the question + the numbered context block.
14
+ * - Token-budget truncation drops LOWEST-SCORE chunks first
15
+ * (kickoff critical decision #2 — old chunks can be high-salience).
16
+ *
17
+ * Pure functions: no I/O, deterministic given inputs.
18
+ */
19
+ import type { RetrievedChunk } from "./types.js";
20
+ /**
21
+ * Assemble system + user prompt for the initial LLM call.
22
+ *
23
+ * @param question User question.
24
+ * @param chunks Retrieved chunks with marker_id already assigned.
25
+ * @param maxTokens Token budget for the full prompt (incl. completion reserve).
26
+ */
27
+ export declare function buildPrompt(question: string, chunks: RetrievedChunk[], maxTokens?: number): {
28
+ system: string;
29
+ user: string;
30
+ };
31
+ /**
32
+ * Stricter retry variant. Same shape as buildPrompt; different system prompt.
33
+ */
34
+ export declare function buildRetryPrompt(question: string, chunks: RetrievedChunk[], maxTokens?: number): {
35
+ system: string;
36
+ user: string;
37
+ };
@@ -0,0 +1,88 @@
1
+ /**
2
+ * src/lib/answer/prompt.ts — Prompt assembly for P1 (T3 scope).
3
+ *
4
+ * Two builders:
5
+ * buildPrompt() — initial pass; standard anti-hallucination guard.
6
+ * buildRetryPrompt() — stricter variant when first pass cited a marker
7
+ * that did not exist in the retrieval set
8
+ * (anti-hallucination retry, partial T5/T6).
9
+ *
10
+ * Design (kickoff §T3 + critical decision #1):
11
+ * - LLM only ever sees marker_ids (`chunk_1`..`chunk_N`), never DB ids.
12
+ * - System prompt = anti-hallucination guard + citation rule.
13
+ * - User prompt = the question + the numbered context block.
14
+ * - Token-budget truncation drops LOWEST-SCORE chunks first
15
+ * (kickoff critical decision #2 — old chunks can be high-salience).
16
+ *
17
+ * Pure functions: no I/O, deterministic given inputs.
18
+ */
19
+ /** Approximate chars-per-token; conservative for English+code. */
20
+ const APPROX_CHARS_PER_TOKEN = 4;
21
+ /** Reserve budget for system prompt + question + LLM completion + slack. */
22
+ const RESERVED_NON_CHUNK_TOKENS = 800;
23
+ const SYSTEM_BASE = "Answer ONLY from the numbered context blocks below. " +
24
+ "If the context does not contain the answer, reply exactly: " +
25
+ '"I have no memory matches for this question." ' +
26
+ "Cite EVERY factual claim with [chunk_N] using the marker shown next to each block. " +
27
+ "Never invent citations. Never cite a marker that is not in the context.";
28
+ const SYSTEM_RETRY = "STRICT MODE — your previous answer cited a marker that does not exist. " +
29
+ "You MUST only cite markers literally listed in the context below, e.g. [chunk_1], [chunk_2]. " +
30
+ "If you cannot answer using ONLY these markers, reply exactly: " +
31
+ '"I have no memory matches for this question." ' +
32
+ "Do NOT speculate. Do NOT invent marker numbers.";
33
+ /**
34
+ * Assemble system + user prompt for the initial LLM call.
35
+ *
36
+ * @param question User question.
37
+ * @param chunks Retrieved chunks with marker_id already assigned.
38
+ * @param maxTokens Token budget for the full prompt (incl. completion reserve).
39
+ */
40
+ export function buildPrompt(question, chunks, maxTokens = 4000) {
41
+ return {
42
+ system: SYSTEM_BASE,
43
+ user: assembleUserPrompt(question, chunks, maxTokens),
44
+ };
45
+ }
46
+ /**
47
+ * Stricter retry variant. Same shape as buildPrompt; different system prompt.
48
+ */
49
+ export function buildRetryPrompt(question, chunks, maxTokens = 4000) {
50
+ return {
51
+ system: SYSTEM_RETRY,
52
+ user: assembleUserPrompt(question, chunks, maxTokens),
53
+ };
54
+ }
55
+ /**
56
+ * Assemble the user-role message: question first, then numbered chunks.
57
+ * Drops lowest-score chunks until the rough char budget fits.
58
+ */
59
+ function assembleUserPrompt(question, chunks, maxTokens) {
60
+ if (chunks.length === 0) {
61
+ return `${question}\n\n(No context retrieved.)`;
62
+ }
63
+ const budgetChars = Math.max(256, (maxTokens - RESERVED_NON_CHUNK_TOKENS) * APPROX_CHARS_PER_TOKEN);
64
+ // Stable copy ordered by score desc — drop tail first if over budget.
65
+ const sortedDesc = [...chunks].sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
66
+ let used = question.length;
67
+ const kept = [];
68
+ for (const chunk of sortedDesc) {
69
+ const renderedLen = chunk.marker_id.length + chunk.content.length + 8; // brackets + newlines
70
+ if (used + renderedLen > budgetChars && kept.length > 0) {
71
+ break; // keep at least one chunk even if oversized
72
+ }
73
+ kept.push(chunk);
74
+ used += renderedLen;
75
+ }
76
+ // Render in original retrieval order (marker_id 1..N) so the LLM sees a
77
+ // monotonically numbered list, not score-sorted noise.
78
+ const inMarkerOrder = kept.sort((a, b) => markerNum(a) - markerNum(b));
79
+ const contextBlock = inMarkerOrder
80
+ .map((chunk) => `[${chunk.marker_id}] ${chunk.content}`)
81
+ .join("\n\n");
82
+ return `Question: ${question}\n\nContext:\n\n${contextBlock}`;
83
+ }
84
+ /** Helper — strip "chunk_" prefix to get the integer index for ordering. */
85
+ function markerNum(chunk) {
86
+ const match = chunk.marker_id.match(/chunk_(\d+)/);
87
+ return match && match[1] ? parseInt(match[1], 10) : Number.MAX_SAFE_INTEGER;
88
+ }
@@ -0,0 +1,47 @@
1
+ export interface LLMCallOpts {
2
+ system: string;
3
+ user: string;
4
+ maxTokens: number;
5
+ temperature: number;
6
+ model: string;
7
+ }
8
+ export interface LLMCallResult {
9
+ text: string;
10
+ tokensIn: number;
11
+ tokensOut: number;
12
+ latencyMs: number;
13
+ }
14
+ export interface LLMProvider {
15
+ readonly name: string;
16
+ complete(opts: LLMCallOpts): Promise<LLMCallResult>;
17
+ }
18
+ /**
19
+ * MockProvider — used by tests and by `--provider mock` CLI flag.
20
+ *
21
+ * Behaviour:
22
+ * - If `responses` queue non-empty, dequeue one per call (deterministic).
23
+ * - Else returns an echo of the question prefix + `[chunk_1]` citation,
24
+ * useful for happy-path smoke tests without scripting.
25
+ * - Token counts derived from text length / 4 (rough char-per-token).
26
+ */
27
+ export declare class MockProvider implements LLMProvider {
28
+ readonly name = "mock";
29
+ private readonly responses;
30
+ /** Per-call delay in ms; lets tests assert latency_ms is set. */
31
+ private readonly delayMs;
32
+ /** Optional canned error to throw on next call. */
33
+ private errorOnNextCall;
34
+ constructor(responses?: string[], delayMs?: number);
35
+ /** Test seam — force the next complete() to throw. */
36
+ throwNext(err: Error): void;
37
+ complete(opts: LLMCallOpts): Promise<LLMCallResult>;
38
+ }
39
+ /**
40
+ * Select a provider by name. Honours `NOX_ANSWER_PROVIDER` env when no
41
+ * explicit name is passed. Defaults to Gemini (D41 #1).
42
+ *
43
+ * Unknown name → falls back to Gemini default rather than throwing, so
44
+ * a typo in CLI flag never causes a hard crash; metadata.provider will
45
+ * surface the actual provider used.
46
+ */
47
+ export declare function selectProvider(name?: string): LLMProvider;
@@ -0,0 +1,101 @@
1
+ import { GeminiLLMProvider } from "../../providers/llm/gemini.js";
2
+ /**
3
+ * src/lib/answer/provider.ts — LLM provider abstraction for P1 (T4 scope).
4
+ *
5
+ * Goal: a minimal interface that ANTICIPATES the A3 module (PR #8) without
6
+ * creating a hard dependency. When A3 lands, the real Gemini provider in
7
+ * this file is replaced by a thin re-export of A3's `llm.call()`.
8
+ *
9
+ * Interface shape kept in sync with A3 spec §3:
10
+ * complete({system, user, maxTokens, temperature, model}) → {text, tokensIn, tokensOut, latencyMs}
11
+ *
12
+ * In this staged-P1 dir we ship:
13
+ * - MockProvider — deterministic, no network. Always available.
14
+ * - placeholderGemini — throws clear error; real impl bound on VPS apply.
15
+ * - selectProvider(name?) — name-based dispatch + env override.
16
+ *
17
+ * Per D41 #1: default model is `gemini-2.5-flash-lite`; never silently
18
+ * switch to `gemini-2.5-flash` (CLAUDE.md regra #3).
19
+ */
20
+ import { DEFAULT_PROVIDER } from "./config.js";
21
+ /**
22
+ * MockProvider — used by tests and by `--provider mock` CLI flag.
23
+ *
24
+ * Behaviour:
25
+ * - If `responses` queue non-empty, dequeue one per call (deterministic).
26
+ * - Else returns an echo of the question prefix + `[chunk_1]` citation,
27
+ * useful for happy-path smoke tests without scripting.
28
+ * - Token counts derived from text length / 4 (rough char-per-token).
29
+ */
30
+ export class MockProvider {
31
+ name = "mock";
32
+ responses;
33
+ /** Per-call delay in ms; lets tests assert latency_ms is set. */
34
+ delayMs;
35
+ /** Optional canned error to throw on next call. */
36
+ errorOnNextCall = null;
37
+ constructor(responses = [], delayMs = 1) {
38
+ this.responses = [...responses];
39
+ this.delayMs = delayMs;
40
+ }
41
+ /** Test seam — force the next complete() to throw. */
42
+ throwNext(err) {
43
+ this.errorOnNextCall = err;
44
+ }
45
+ async complete(opts) {
46
+ const t0 = Date.now();
47
+ if (this.delayMs > 0) {
48
+ await new Promise((res) => setTimeout(res, this.delayMs));
49
+ }
50
+ if (this.errorOnNextCall) {
51
+ const err = this.errorOnNextCall;
52
+ this.errorOnNextCall = null;
53
+ throw err;
54
+ }
55
+ const text = this.responses.shift() ?? defaultMockText(opts);
56
+ return {
57
+ text,
58
+ tokensIn: estimateTokens(opts.system) + estimateTokens(opts.user),
59
+ tokensOut: estimateTokens(text),
60
+ latencyMs: Date.now() - t0,
61
+ };
62
+ }
63
+ }
64
+ /**
65
+ * placeholderGemini — explicit failure surface; the VPS-side apply step
66
+ * replaces this with a real `@google/genai` client. Keeping it as an
67
+ * explicit throw prevents accidental real-network calls during tests.
68
+ */
69
+ const placeholderGemini = new GeminiLLMProvider({});
70
+ /**
71
+ * Select a provider by name. Honours `NOX_ANSWER_PROVIDER` env when no
72
+ * explicit name is passed. Defaults to Gemini (D41 #1).
73
+ *
74
+ * Unknown name → falls back to Gemini default rather than throwing, so
75
+ * a typo in CLI flag never causes a hard crash; metadata.provider will
76
+ * surface the actual provider used.
77
+ */
78
+ export function selectProvider(name) {
79
+ const resolved = name ?? process.env.NOX_ANSWER_PROVIDER ?? DEFAULT_PROVIDER;
80
+ switch (resolved) {
81
+ case "mock":
82
+ return new MockProvider();
83
+ case "gemini":
84
+ return placeholderGemini;
85
+ default:
86
+ // Unknown provider name — defensively fall back to Gemini.
87
+ return placeholderGemini;
88
+ }
89
+ }
90
+ // ─── Helpers ──────────────────────────────────────────────────────────────
91
+ function estimateTokens(text) {
92
+ if (!text)
93
+ return 0;
94
+ return Math.max(1, Math.ceil(text.length / 4));
95
+ }
96
+ function defaultMockText(opts) {
97
+ // Cheap echo response that includes a valid-looking citation so the
98
+ // happy-path test can assert citation parsing without scripting a queue.
99
+ const firstLine = (opts.user.split("\n")[0] ?? "").slice(0, 80);
100
+ return `Mock answer for: ${firstLine} [chunk_1]`;
101
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * src/lib/answer/retrieval.ts — Hybrid-search wrapper for P1 (T2 scope).
3
+ *
4
+ * T1-T4 MVP: this module exposes `retrieveContext()` which is a thin
5
+ * wrapper over the existing hybrid search (BM25 + sqlite-vec + RRF +
6
+ * salience). In production this calls `src/lib/search/hybrid.ts`; here
7
+ * (staged dir) we expose `defaultRawSearch` as a pluggable injection
8
+ * point so the unit tests can inject deterministic fixtures.
9
+ *
10
+ * Responsibilities (kickoff §T2 DoD):
11
+ * 1. Call hybrid search (or injected stub).
12
+ * 2. Dedupe near-duplicates by content_hash (keep highest score).
13
+ * 3. Cap to topK.
14
+ * 4. Assign marker_id = "chunk_1".."chunk_N" stable to retrieved order.
15
+ *
16
+ * Pure function: no DB writes, no LLM calls.
17
+ */
18
+ import type { RawChunk, RetrievedChunk } from "./types.js";
19
+ /**
20
+ * Signature for the underlying hybrid search call.
21
+ * In prod this is bound to `hybridSearch()` from existing search module.
22
+ */
23
+ export type RawSearchFn = (question: string, topK: number) => Promise<RawChunk[]>;
24
+ /**
25
+ * Test-only seam: replace the underlying raw search with a stub.
26
+ * Pass `null` to restore real-prod hybridSearch binding (set by VPS adapter).
27
+ */
28
+ export declare function __setRawSearchForTests(fn: RawSearchFn | null): void;
29
+ /**
30
+ * Retrieve context chunks for a question.
31
+ *
32
+ * @param question Natural-language input.
33
+ * @param topK Max chunks to return. Caller should pre-clamp via config.
34
+ * @returns Deduplicated, marker-assigned chunks ordered by score desc.
35
+ */
36
+ export declare function retrieveContext(question: string, topK: number): Promise<RetrievedChunk[]>;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * src/lib/answer/retrieval.ts — Hybrid-search wrapper for P1 (T2 scope).
3
+ *
4
+ * T1-T4 MVP: this module exposes `retrieveContext()` which is a thin
5
+ * wrapper over the existing hybrid search (BM25 + sqlite-vec + RRF +
6
+ * salience). In production this calls `src/lib/search/hybrid.ts`; here
7
+ * (staged dir) we expose `defaultRawSearch` as a pluggable injection
8
+ * point so the unit tests can inject deterministic fixtures.
9
+ *
10
+ * Responsibilities (kickoff §T2 DoD):
11
+ * 1. Call hybrid search (or injected stub).
12
+ * 2. Dedupe near-duplicates by content_hash (keep highest score).
13
+ * 3. Cap to topK.
14
+ * 4. Assign marker_id = "chunk_1".."chunk_N" stable to retrieved order.
15
+ *
16
+ * Pure function: no DB writes, no LLM calls.
17
+ */
18
+ import { searchHybrid } from "../../search.js";
19
+ let injectedSearch = null;
20
+ /**
21
+ * Test-only seam: replace the underlying raw search with a stub.
22
+ * Pass `null` to restore real-prod hybridSearch binding (set by VPS adapter).
23
+ */
24
+ export function __setRawSearchForTests(fn) {
25
+ injectedSearch = fn;
26
+ }
27
+ /**
28
+ * Default raw search — in this staged dir we do NOT bind to the real
29
+ * hybrid search (it lives in prod src/). The VPS-side apply step will
30
+ * patch this to import from `src/lib/search/hybrid.js`. For now we
31
+ * throw a clear error if called without injection — keeps tests honest
32
+ * (must always inject) and prevents accidental network calls.
33
+ */
34
+ async function defaultRawSearch(question, topK) {
35
+ const hits = await searchHybrid(question, topK);
36
+ return hits.map((h) => ({
37
+ chunk_id: h.id ?? 0,
38
+ file_path: h.source_file,
39
+ content: h.chunk_text,
40
+ score: h.score,
41
+ }));
42
+ }
43
+ /**
44
+ * Retrieve context chunks for a question.
45
+ *
46
+ * @param question Natural-language input.
47
+ * @param topK Max chunks to return. Caller should pre-clamp via config.
48
+ * @returns Deduplicated, marker-assigned chunks ordered by score desc.
49
+ */
50
+ export async function retrieveContext(question, topK) {
51
+ if (!question || question.trim().length === 0) {
52
+ return [];
53
+ }
54
+ if (topK <= 0)
55
+ return [];
56
+ const search = injectedSearch ?? defaultRawSearch;
57
+ const raw = await search(question, topK * 2); // overfetch to survive dedupe
58
+ // Sort by score desc (defensive — most hybrid impls already do this, but
59
+ // we cannot trust ordering of an injected/mocked search).
60
+ const sorted = [...raw].sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
61
+ // Dedupe by content_hash (keep highest-score = first hit in sorted list).
62
+ // If content_hash missing, dedupe by chunk_id as a fallback.
63
+ const seenHashes = new Set();
64
+ const seenIds = new Set();
65
+ const deduped = [];
66
+ for (const chunk of sorted) {
67
+ const key = chunk.content_hash ?? "";
68
+ if (key.length > 0) {
69
+ if (seenHashes.has(key))
70
+ continue;
71
+ seenHashes.add(key);
72
+ }
73
+ else {
74
+ if (seenIds.has(chunk.chunk_id))
75
+ continue;
76
+ seenIds.add(chunk.chunk_id);
77
+ }
78
+ deduped.push(chunk);
79
+ if (deduped.length >= topK)
80
+ break;
81
+ }
82
+ // Assign markers 1-indexed.
83
+ return deduped.map((chunk, idx) => ({
84
+ chunk_id: chunk.chunk_id,
85
+ marker_id: `chunk_${idx + 1}`,
86
+ file_path: chunk.file_path,
87
+ line_range: chunk.line_range,
88
+ content: chunk.content,
89
+ content_hash: chunk.content_hash,
90
+ score: chunk.score,
91
+ }));
92
+ }