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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Luiz Antonio Busnello (Toto)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,179 @@
1
+ # nox-mem
2
+
3
+ Pain-weighted hybrid memory engine for AI agents. Self-hosted, zero vendor lock-in.
4
+
5
+ **Stack:** TypeScript · Node 20+ · SQLite (FTS5 + sqlite-vec) · Gemini embeddings (default) · OpenAI-compat optional
6
+
7
+ ---
8
+
9
+ ## Prerequisites
10
+
11
+ ### System packages (Linux)
12
+
13
+ ```bash
14
+ apt-get update
15
+ apt-get install -y build-essential python3 python3-pip inotify-tools
16
+ ```
17
+
18
+ `build-essential` and `python3` are required by `better-sqlite3` (compiles a native addon) and `@xenova/transformers` (optional local embeddings).
19
+
20
+ ### Node.js 20+
21
+
22
+ ```bash
23
+ # Via NodeSource (Ubuntu/Debian)
24
+ curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
25
+ apt-get install -y nodejs
26
+ node --version # expect v20.x or higher
27
+ ```
28
+
29
+ ---
30
+
31
+ ## Install
32
+
33
+ ### From tarball (recommended for production)
34
+
35
+ ```bash
36
+ # Unpack and install globally from the directory
37
+ npm install -g .
38
+ ```
39
+
40
+ ### From source (build yourself)
41
+
42
+ ```bash
43
+ npm ci
44
+ npm run build
45
+ npm install -g .
46
+ ```
47
+
48
+ After either method, the `nox-mem` command is available globally.
49
+
50
+ ---
51
+
52
+ ## Environment variables
53
+
54
+ Copy `.env.example` to `.env` in your install directory and fill in the required values, then source it before running:
55
+
56
+ ```bash
57
+ set -a; source /path/to/.env; set +a
58
+ nox-mem stats
59
+ ```
60
+
61
+ ### Required
62
+
63
+ | Var | Default | Purpose |
64
+ |---|---|---|
65
+ | `GEMINI_API_KEY` | — | Google AI Studio key (default LLM + embedding provider). |
66
+ | `NOX_DB_PATH` | `<cwd>/nox-mem.db` | SQLite database path. Its directory is auto-added to the op-audit allowlist. |
67
+ | `NOX_MEM_DIR` | — | Directory of markdown memory files to ingest/watch. |
68
+
69
+ ### API server
70
+
71
+ | Var | Default | Purpose |
72
+ |---|---|---|
73
+ | `NOX_API_PORT` | `18802` | HTTP API port. |
74
+ | `NOX_API_HOST` | `127.0.0.1` | HTTP API bind host. |
75
+ | `NOX_API_TOKEN` | — | If set, requires `Authorization: Bearer <token>` on the API. |
76
+
77
+ ### Multi-provider (optional — default is Gemini / AI Studio)
78
+
79
+ | Var | Default | Purpose |
80
+ |---|---|---|
81
+ | `NOX_LLM_PROVIDER` | `gemini` | `gemini` or `openai` (any OpenAI-compatible endpoint). |
82
+ | `NOX_LLM_MODEL` | `gemini-2.5-flash-lite` / `gpt-4o-mini` | LLM model id. |
83
+ | `NOX_LLM_BASE_URL` | provider default | OpenAI-compat endpoint — DeepSeek/OpenRouter/Together/local. |
84
+ | `NOX_LLM_API_KEY` | falls back to `GEMINI_API_KEY` / `OPENAI_API_KEY` | LLM key. |
85
+ | `NOX_LLM_FALLBACK` | — | Fallback chain, e.g. `openai:gpt-4o-mini`. |
86
+ | `NOX_EMBEDDING_PROVIDER` | `gemini` | `gemini` or `openai`. Alias: `NOX_EMBED_PROVIDER`. |
87
+ | `NOX_EMBEDDING_MODEL` | `gemini-embedding-001` / `text-embedding-3-small` | Embedding model. Alias: `NOX_EMBED_MODEL`. |
88
+ | `NOX_EMBEDDING_BASE_URL` | provider default | Embedding endpoint. Alias: `NOX_EMBED_BASE_URL`. |
89
+ | `NOX_EMBEDDING_API_KEY` | falls back to provider key | Embedding key. Alias: `NOX_EMBED_API_KEY`. |
90
+ | `NOX_EMBEDDING_DIM` | `3072` | Vector dim. **MUST equal the vec0 table dim** — changing it requires re-embedding the whole corpus. Alias: `NOX_EMBED_DIM`. |
91
+
92
+ > ⚠️ Embeddings from different models/dims are not comparable. Pick one embedding model up front; mixing silently corrupts semantic search. `text-embedding-3-large` supports `dimensions=3072` for parity with the default table.
93
+
94
+ ### Advanced (safe to leave unset — defaults are standalone-neutral)
95
+
96
+ | Var | Default | Purpose |
97
+ |---|---|---|
98
+ | `OPENCLAW_WORKSPACE` | `/root/.openclaw/workspace` | Origin platform workspace root (origin/legacy only). |
99
+ | `NOX_OP_AUDIT_ALLOWED_PREFIXES` | derived from `NOX_DB_PATH`/`NOX_MEM_DIR` + origin defaults | Comma-sep path prefixes the DB/snapshots may live under. |
100
+ | `NOX_PRE_OP_SNAPSHOT_DIR` | `<NOX_MEM_DIR>/.nox-snapshots` (standalone) | Pre-op snapshot directory. |
101
+ | `NOX_PROTECTED_NAMES` | empty | Comma-sep names never auto-merged in the KG. |
102
+ | `NOX_NAME_ALIASES` | empty | `from:To` name-normalization pairs for the KG. |
103
+ | `NOX_ENTITY_PATTERNS` / `NOX_PROJECT_PATTERNS` | empty | Terms for the legacy regex entity extractor. |
104
+ | `NOX_KNOWN_PROJECTS` | empty | Project slugs for `project-context-gen`. |
105
+ | `NOX_AGENTS` / `NOX_AGENTS_DIR` | `nox,atlas,boris,cipher,forge,lex` / `/root/.openclaw/agents` | Multi-agent cross-search layout (no-op standalone). |
106
+ | `NOX_WATCH_DIRS` | origin layout | Comma-sep dirs for the file watcher. |
107
+ | `NOX_SPEAKER_FILTER` | empty | One-time V7 migration speaker classification. |
108
+ | `NOX_NOTION_TOKEN` / `NOX_NOTION_TOKEN_PATH` | — / `/root/.config/notion/api_key` | Optional Notion sync token (value or file path). |
109
+
110
+ ---
111
+
112
+ ## Multi-provider support
113
+
114
+ By default nox-mem uses **Gemini via AI Studio** (`gemini/gemini-2.5-flash-lite` model, key = `GEMINI_API_KEY`).
115
+
116
+ To switch to any OpenAI-compatible provider (DeepSeek, OpenRouter, local Ollama, etc.):
117
+
118
+ ```bash
119
+ NOX_LLM_PROVIDER=openai
120
+ NOX_LLM_BASE_URL=https://openrouter.ai/api/v1
121
+ NOX_LLM_MODEL=deepseek/deepseek-chat
122
+ NOX_LLM_API_KEY=sk-...
123
+
124
+ NOX_EMBED_PROVIDER=openai
125
+ NOX_EMBED_BASE_URL=https://openrouter.ai/api/v1
126
+ NOX_EMBED_MODEL=text-embedding-3-small
127
+ NOX_EMBED_API_KEY=sk-...
128
+ ```
129
+
130
+ Provider-switching works at runtime — no rebuild required.
131
+
132
+ ---
133
+
134
+ ## Operation audit snapshots
135
+
136
+ All destructive operations (reindex, consolidate, compact, crystallize, kg-prune) create an atomic SQLite snapshot before mutating data. Snapshots land in `$NOX_PRE_OP_SNAPSHOT_DIR` (default: `/var/backups/nox-mem/pre-op/`). Retention: 7 days. Do NOT restore with raw `cp` — use the `safeRestore()` path or the `--restore` flag which handles WAL/SHM cleanup correctly.
137
+
138
+ ---
139
+
140
+ ## Sanity check
141
+
142
+ After install, verify the engine is healthy:
143
+
144
+ ```bash
145
+ # Start the API server (no `serve` subcommand — run the server entry directly)
146
+ node "$(npm root -g)/nox-mem/dist/api-server.js" &
147
+
148
+ # Check vector coverage (should be close to 1.0). Code default port is 18800.
149
+ curl -s "http://127.0.0.1:${NOX_API_PORT:-18800}/api/health" | jq .vectorCoverage
150
+ ```
151
+
152
+ A `vectorCoverage` value below 0.99 means some chunks are not yet embedded — run `nox-mem vectorize` to catch up.
153
+
154
+ ---
155
+
156
+ ## Key commands
157
+
158
+ ```
159
+ nox-mem search "query" — hybrid search (FTS5 + semantic + RRF)
160
+ nox-mem ingest <file> — ingest a markdown or entity file
161
+ nox-mem reindex — rebuild FTS5 index
162
+ nox-mem vectorize — embed any unembedded chunks
163
+ nox-mem stats — chunk/entity/vector counts
164
+ nox-mem kg-build — extract knowledge graph entities
165
+ nox-mem reflect — surface high-salience insights
166
+ node dist/api-server.js — start HTTP API on $NOX_API_PORT (code default 18800)
167
+ node dist/mcp-server.js — start MCP server (20 tools, for agents)
168
+ nox-mem --help — full command reference
169
+ ```
170
+
171
+ ---
172
+
173
+ ## sqlite-vec and platform binaries
174
+
175
+ `sqlite-vec` ships native `.so`/`.dylib`/`.dll` files as platform-specific optional npm packages (`sqlite-vec-linux-x64`, `sqlite-vec-darwin-arm64`, etc.). A plain `npm install` on a supported platform automatically resolves and downloads the correct binary — no `postinstall` script required. The nox-mem `package.json` explicitly lists all platform variants under `optionalDependencies` so package managers that strip optional deps by default still see them declared.
176
+
177
+ ---
178
+
179
+ *MIT License — Copyright (c) 2026 Luiz Antonio Busnello (Toto)*
@@ -0,0 +1,116 @@
1
+ /**
2
+ * src/api/answer.ts — P1 T9: POST /api/answer.
3
+ *
4
+ * Framework-agnostic handler. Production `src/api/server.ts` mounts it via
5
+ * a 5-line Fastify (or Express) adapter:
6
+ *
7
+ * fastify.post('/api/answer', async (req, reply) => {
8
+ * const out = await handleAnswerRequest({
9
+ * body: req.body,
10
+ * headers: req.headers as Record<string, string | undefined>,
11
+ * answer: realAnswer,
12
+ * telemetryStore: getTelemetryStore(),
13
+ * });
14
+ * reply.code(out.status);
15
+ * for (const [k, v] of Object.entries(out.headers)) reply.header(k, v);
16
+ * return out.body;
17
+ * });
18
+ *
19
+ * Same shape — kickoff §6 status codes:
20
+ * 200 ok / 400 invalid body / 422 hallucination after retry /
21
+ * 502 LLM unreachable / 503 retrieval empty / 504 timeout
22
+ *
23
+ * Response also sets X-Trace-Id, X-Model-Used, X-Retry-Count.
24
+ *
25
+ * Auth: this handler does NOT enforce auth — `src/api/server.ts` chains the
26
+ * existing `requireApiToken()` middleware in front of it (same mechanism
27
+ * as the other 7 routes). Documented as a precondition.
28
+ */
29
+ import type { AnswerOpts, AnswerResult } from "../lib/answer/index.js";
30
+ import { type TelemetryStore } from "../lib/answer/telemetry.js";
31
+ export interface AnswerHttpRequest {
32
+ question: string;
33
+ top_k?: number;
34
+ max_tokens?: number;
35
+ provider?: string;
36
+ model?: string;
37
+ temperature?: number;
38
+ no_citations?: boolean;
39
+ trace_id?: string;
40
+ }
41
+ export interface AnswerHttpResponseSuccess {
42
+ answer: string;
43
+ citations: AnswerResult["citations"];
44
+ metadata: AnswerResult["metadata"];
45
+ trace_id: string;
46
+ }
47
+ export interface AnswerHttpResponseError {
48
+ error: true;
49
+ reason: string;
50
+ message: string;
51
+ trace_id: string;
52
+ }
53
+ export type AnswerHttpResponse = AnswerHttpResponseSuccess | AnswerHttpResponseError;
54
+ export interface HandleAnswerArgs {
55
+ /** Parsed JSON body (or raw string we coerce). */
56
+ body: unknown;
57
+ /** Headers (case-insensitive lookups expected by caller). */
58
+ headers?: Record<string, string | string[] | undefined>;
59
+ /** Auth check seam: when present, must return true to allow. Default: allow. */
60
+ authCheck?: (headers: Record<string, string | string[] | undefined>) => boolean;
61
+ /** Test seam — replace answer() under test. */
62
+ answer?: (opts: AnswerOpts) => Promise<AnswerResult>;
63
+ /** Optional telemetry sink. */
64
+ telemetryStore?: TelemetryStore;
65
+ /** Session correlation passthrough (from middleware). */
66
+ sessionId?: string | null;
67
+ }
68
+ export interface HandlerOutput {
69
+ status: number;
70
+ headers: Record<string, string>;
71
+ body: AnswerHttpResponse;
72
+ }
73
+ export declare function validateBody(body: unknown): AnswerHttpRequest;
74
+ export declare function statusFromReason(reason: string): number;
75
+ export declare function handleAnswerRequest(args: HandleAnswerArgs): Promise<HandlerOutput>;
76
+ export declare const REQUEST_SCHEMA: {
77
+ readonly $schema: "http://json-schema.org/draft-07/schema#";
78
+ readonly type: "object";
79
+ readonly required: readonly ["question"];
80
+ readonly additionalProperties: false;
81
+ readonly properties: {
82
+ readonly question: {
83
+ readonly type: "string";
84
+ readonly minLength: 1;
85
+ readonly maxLength: 2000;
86
+ };
87
+ readonly top_k: {
88
+ readonly type: "integer";
89
+ readonly minimum: 1;
90
+ readonly maximum: 20;
91
+ };
92
+ readonly max_tokens: {
93
+ readonly type: "integer";
94
+ readonly minimum: 64;
95
+ readonly maximum: 8192;
96
+ };
97
+ readonly provider: {
98
+ readonly type: "string";
99
+ };
100
+ readonly model: {
101
+ readonly type: "string";
102
+ };
103
+ readonly temperature: {
104
+ readonly type: "number";
105
+ readonly minimum: 0;
106
+ readonly maximum: 1;
107
+ };
108
+ readonly no_citations: {
109
+ readonly type: "boolean";
110
+ };
111
+ readonly trace_id: {
112
+ readonly type: "string";
113
+ readonly maxLength: 64;
114
+ };
115
+ };
116
+ };
@@ -0,0 +1,274 @@
1
+ /**
2
+ * src/api/answer.ts — P1 T9: POST /api/answer.
3
+ *
4
+ * Framework-agnostic handler. Production `src/api/server.ts` mounts it via
5
+ * a 5-line Fastify (or Express) adapter:
6
+ *
7
+ * fastify.post('/api/answer', async (req, reply) => {
8
+ * const out = await handleAnswerRequest({
9
+ * body: req.body,
10
+ * headers: req.headers as Record<string, string | undefined>,
11
+ * answer: realAnswer,
12
+ * telemetryStore: getTelemetryStore(),
13
+ * });
14
+ * reply.code(out.status);
15
+ * for (const [k, v] of Object.entries(out.headers)) reply.header(k, v);
16
+ * return out.body;
17
+ * });
18
+ *
19
+ * Same shape — kickoff §6 status codes:
20
+ * 200 ok / 400 invalid body / 422 hallucination after retry /
21
+ * 502 LLM unreachable / 503 retrieval empty / 504 timeout
22
+ *
23
+ * Response also sets X-Trace-Id, X-Model-Used, X-Retry-Count.
24
+ *
25
+ * Auth: this handler does NOT enforce auth — `src/api/server.ts` chains the
26
+ * existing `requireApiToken()` middleware in front of it (same mechanism
27
+ * as the other 7 routes). Documented as a precondition.
28
+ */
29
+ import { randomUUID } from "node:crypto";
30
+ import { answer as defaultAnswer, AnswerError } from "../lib/answer/index.js";
31
+ import { recordAnswer, } from "../lib/answer/telemetry.js";
32
+ const MARKER_RE = /\s?\[chunk_\d+\]/g;
33
+ // ─── Body validation ──────────────────────────────────────────────────────
34
+ function getHeader(headers, name) {
35
+ if (!headers)
36
+ return undefined;
37
+ const lower = name.toLowerCase();
38
+ for (const k of Object.keys(headers)) {
39
+ if (k.toLowerCase() === lower) {
40
+ const v = headers[k];
41
+ if (Array.isArray(v))
42
+ return v[0];
43
+ return v;
44
+ }
45
+ }
46
+ return undefined;
47
+ }
48
+ class HttpError extends Error {
49
+ status;
50
+ reason;
51
+ constructor(status, reason, message) {
52
+ super(message);
53
+ this.status = status;
54
+ this.reason = reason;
55
+ }
56
+ }
57
+ export function validateBody(body) {
58
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
59
+ throw new HttpError(400, "invalid_body", "body must be a JSON object");
60
+ }
61
+ const b = body;
62
+ if (typeof b.question !== "string" || b.question.trim().length === 0) {
63
+ throw new HttpError(400, "invalid_body", "question is required (non-empty string)");
64
+ }
65
+ if (b.question.length > 2000) {
66
+ throw new HttpError(400, "invalid_body", "question exceeds 2000 chars");
67
+ }
68
+ const req = { question: b.question };
69
+ if (b.top_k !== undefined) {
70
+ if (typeof b.top_k !== "number" || !Number.isFinite(b.top_k)) {
71
+ throw new HttpError(400, "invalid_body", "top_k must be a number");
72
+ }
73
+ req.top_k = b.top_k;
74
+ }
75
+ if (b.max_tokens !== undefined) {
76
+ if (typeof b.max_tokens !== "number" || !Number.isFinite(b.max_tokens)) {
77
+ throw new HttpError(400, "invalid_body", "max_tokens must be a number");
78
+ }
79
+ req.max_tokens = b.max_tokens;
80
+ }
81
+ if (b.temperature !== undefined) {
82
+ if (typeof b.temperature !== "number" || !Number.isFinite(b.temperature)) {
83
+ throw new HttpError(400, "invalid_body", "temperature must be a number");
84
+ }
85
+ req.temperature = b.temperature;
86
+ }
87
+ if (b.provider !== undefined) {
88
+ if (typeof b.provider !== "string") {
89
+ throw new HttpError(400, "invalid_body", "provider must be a string");
90
+ }
91
+ req.provider = b.provider;
92
+ }
93
+ if (b.model !== undefined) {
94
+ if (typeof b.model !== "string") {
95
+ throw new HttpError(400, "invalid_body", "model must be a string");
96
+ }
97
+ req.model = b.model;
98
+ }
99
+ if (b.no_citations !== undefined) {
100
+ if (typeof b.no_citations !== "boolean") {
101
+ throw new HttpError(400, "invalid_body", "no_citations must be a boolean");
102
+ }
103
+ req.no_citations = b.no_citations;
104
+ }
105
+ if (b.trace_id !== undefined) {
106
+ if (typeof b.trace_id !== "string" || b.trace_id.length > 64) {
107
+ throw new HttpError(400, "invalid_body", "trace_id must be string ≤64 chars");
108
+ }
109
+ req.trace_id = b.trace_id;
110
+ }
111
+ return req;
112
+ }
113
+ // ─── Status-code mapper ───────────────────────────────────────────────────
114
+ export function statusFromReason(reason) {
115
+ switch (reason) {
116
+ case "retrieval_empty":
117
+ return 503;
118
+ case "hallucination_after_retry":
119
+ case "hallucinated_citation":
120
+ return 422;
121
+ case "llm_timeout":
122
+ return 504;
123
+ case "llm_error":
124
+ return 502;
125
+ case "invalid_input":
126
+ case "invalid_body":
127
+ return 400;
128
+ case "unauthorized":
129
+ return 401;
130
+ default:
131
+ return 500;
132
+ }
133
+ }
134
+ // ─── Handler ──────────────────────────────────────────────────────────────
135
+ export async function handleAnswerRequest(args) {
136
+ const traceIdHeader = getHeader(args.headers, "x-trace-id");
137
+ const traceId = traceIdHeader ?? randomUUID();
138
+ const baseHeaders = { "X-Trace-Id": traceId };
139
+ // Auth (optional; default-allow when no check provided).
140
+ if (args.authCheck && !args.authCheck(args.headers ?? {})) {
141
+ return {
142
+ status: 401,
143
+ headers: baseHeaders,
144
+ body: {
145
+ error: true,
146
+ reason: "unauthorized",
147
+ message: "missing or invalid API token",
148
+ trace_id: traceId,
149
+ },
150
+ };
151
+ }
152
+ // Body validation.
153
+ let req;
154
+ try {
155
+ req = validateBody(args.body);
156
+ }
157
+ catch (err) {
158
+ const httpErr = err;
159
+ return {
160
+ status: httpErr.status ?? 400,
161
+ headers: baseHeaders,
162
+ body: {
163
+ error: true,
164
+ reason: httpErr.reason ?? "invalid_body",
165
+ message: httpErr.message,
166
+ trace_id: traceId,
167
+ },
168
+ };
169
+ }
170
+ // Build AnswerOpts.
171
+ const opts = { question: req.question };
172
+ if (req.top_k !== undefined)
173
+ opts.topK = req.top_k;
174
+ if (req.max_tokens !== undefined)
175
+ opts.maxTokens = req.max_tokens;
176
+ if (req.temperature !== undefined)
177
+ opts.temperature = req.temperature;
178
+ if (req.provider !== undefined)
179
+ opts.provider = req.provider;
180
+ if (req.model !== undefined)
181
+ opts.model = req.model;
182
+ const run = args.answer ?? defaultAnswer;
183
+ try {
184
+ const res = await run(opts);
185
+ if (args.telemetryStore) {
186
+ recordAnswer(args.telemetryStore, {
187
+ question: req.question,
188
+ citationCount: res.citations.length,
189
+ metadata: res.metadata,
190
+ sessionId: args.sessionId ?? null,
191
+ });
192
+ }
193
+ const finalAnswer = req.no_citations
194
+ ? res.answer.replace(MARKER_RE, "")
195
+ : res.answer;
196
+ const headers = {
197
+ ...baseHeaders,
198
+ "X-Model-Used": res.metadata.model,
199
+ "X-Retry-Count": String(res.metadata.retry_count ?? 0),
200
+ "Content-Type": "application/json",
201
+ };
202
+ // retrieval_empty is a "success" path (lib returns canonical message)
203
+ // but kickoff §6 maps to 503. Surface accordingly.
204
+ const status = res.metadata.failed_reason === "retrieval_empty" ? 503 : 200;
205
+ return {
206
+ status,
207
+ headers,
208
+ body: {
209
+ answer: finalAnswer,
210
+ citations: res.citations,
211
+ metadata: res.metadata,
212
+ trace_id: traceId,
213
+ },
214
+ };
215
+ }
216
+ catch (err) {
217
+ if (err instanceof AnswerError) {
218
+ if (args.telemetryStore) {
219
+ recordAnswer(args.telemetryStore, {
220
+ question: req.question,
221
+ citationCount: 0,
222
+ metadata: {
223
+ latency_ms: err.metadata.latency_ms ?? 0,
224
+ tokens_in: err.metadata.tokens_in ?? 0,
225
+ tokens_out: err.metadata.tokens_out ?? 0,
226
+ provider: err.metadata.provider ?? "n/a",
227
+ model: err.metadata.model ?? "n/a",
228
+ retrieval_count: err.metadata.retrieval_count ?? 0,
229
+ fallback_used: err.metadata.fallback_used ?? false,
230
+ failed_reason: err.reason,
231
+ },
232
+ sessionId: args.sessionId ?? null,
233
+ });
234
+ }
235
+ return {
236
+ status: statusFromReason(err.reason),
237
+ headers: baseHeaders,
238
+ body: {
239
+ error: true,
240
+ reason: err.reason,
241
+ message: err.message,
242
+ trace_id: traceId,
243
+ },
244
+ };
245
+ }
246
+ return {
247
+ status: 500,
248
+ headers: baseHeaders,
249
+ body: {
250
+ error: true,
251
+ reason: "internal_error",
252
+ message: err.message,
253
+ trace_id: traceId,
254
+ },
255
+ };
256
+ }
257
+ }
258
+ // ─── JSON Schema (for runtime validators + OpenAPI gen) ───────────────────
259
+ export const REQUEST_SCHEMA = {
260
+ $schema: "http://json-schema.org/draft-07/schema#",
261
+ type: "object",
262
+ required: ["question"],
263
+ additionalProperties: false,
264
+ properties: {
265
+ question: { type: "string", minLength: 1, maxLength: 2000 },
266
+ top_k: { type: "integer", minimum: 1, maximum: 20 },
267
+ max_tokens: { type: "integer", minimum: 64, maximum: 8192 },
268
+ provider: { type: "string" },
269
+ model: { type: "string" },
270
+ temperature: { type: "number", minimum: 0, maximum: 1 },
271
+ no_citations: { type: "boolean" },
272
+ trace_id: { type: "string", maxLength: 64 },
273
+ },
274
+ };
@@ -0,0 +1,72 @@
1
+ /**
2
+ * G4 — Validator/schema drift patch for /api/answer
3
+ *
4
+ * Gap identified in THREAT-MODEL.md §3.1 (DoS / validator drift):
5
+ * "top_k schema declares max=20 but validateBody() doesn't enforce it.
6
+ * User could request top_k=10000 and crash service."
7
+ *
8
+ * This file documents the exact patch to apply to staged-P1/edits/src/api/answer.ts.
9
+ * The validateBody() function must enforce ALL OpenAPI schema constraints at runtime,
10
+ * not just type checks.
11
+ *
12
+ * Ref: THREAT-MODEL.md G4 (medium priority).
13
+ */
14
+ /**
15
+ * ValidationError shape for 422 responses:
16
+ *
17
+ * { error: "Validation failed", details: { field: string, got: unknown, max?: number, min?: number } }
18
+ */
19
+ export interface ValidationDetails {
20
+ field: string;
21
+ got: unknown;
22
+ max?: number;
23
+ min?: number;
24
+ reason?: string;
25
+ }
26
+ export declare class ValidationError extends Error {
27
+ readonly status = 422;
28
+ readonly reason = "validation_failed";
29
+ readonly details: ValidationDetails;
30
+ constructor(details: ValidationDetails);
31
+ }
32
+ /**
33
+ * Schema constraints aligned with OpenAPI JSON schema in answer.ts.
34
+ * Single source of truth — change here only, no duplication.
35
+ */
36
+ export declare const ANSWER_CONSTRAINTS: {
37
+ readonly question: {
38
+ readonly minLength: 1;
39
+ readonly maxLength: 2000;
40
+ };
41
+ readonly top_k: {
42
+ readonly min: 1;
43
+ readonly max: 20;
44
+ };
45
+ readonly max_tokens: {
46
+ readonly min: 64;
47
+ readonly max: 8192;
48
+ };
49
+ readonly temperature: {
50
+ readonly min: 0;
51
+ readonly max: 1;
52
+ };
53
+ readonly trace_id: {
54
+ readonly maxLength: 64;
55
+ };
56
+ };
57
+ /**
58
+ * validateBodyStrict — drop-in replacement for validateBody() in answer.ts.
59
+ *
60
+ * Differences from original:
61
+ * 1. top_k: enforces min=1, max=20 (rejects 10000 → 422)
62
+ * 2. max_tokens: enforces min=64, max=8192
63
+ * 3. temperature: enforces min=0, max=1
64
+ * 4. All violations return 422 with structured ValidationError (not 400 HttpError)
65
+ *
66
+ * Backward compatibility: callers that catch HttpError(400) should also handle
67
+ * ValidationError(422). Existing smoke tests remain green since valid payloads
68
+ * pass all checks.
69
+ */
70
+ export declare function validateAnswerConstraints(field: "top_k", value: number): void;
71
+ export declare function validateAnswerConstraints(field: "max_tokens", value: number): void;
72
+ export declare function validateAnswerConstraints(field: "temperature", value: number): void;