nox-mem 3.1.1 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (398) hide show
  1. package/README.md +24 -16
  2. package/dist/__tests__/brief-diversity.test.js +266 -0
  3. package/dist/__tests__/brief.test.js +287 -0
  4. package/dist/__tests__/churn.test.js +66 -0
  5. package/dist/__tests__/edge-typing.test.js +99 -0
  6. package/dist/__tests__/ingest-event.test.js +151 -0
  7. package/dist/__tests__/op-audit-e2e.test.js +130 -0
  8. package/dist/__tests__/pragma-alignment.test.js +123 -0
  9. package/dist/__tests__/reranker.test.js +326 -0
  10. package/dist/__tests__/retention.test.js +99 -0
  11. package/dist/__tests__/search-track-access.test.js +49 -0
  12. package/dist/__tests__/spo-injection.test.js +172 -0
  13. package/dist/__tests__/temporal-detector.test.js +103 -0
  14. package/dist/api/wire-up.js +12 -381
  15. package/dist/api-server.js +6 -102
  16. package/dist/crystallize.js +3 -5
  17. package/dist/db.js +61 -2
  18. package/dist/embed.js +23 -2
  19. package/dist/index.js +1 -22
  20. package/dist/knowledge-graph.js +20 -0
  21. package/dist/lib/answer/__tests__/e2e-gemini.test.js +229 -0
  22. package/dist/lib/answer/__tests__/integration-sqlite.test.js +388 -0
  23. package/dist/lib/answer/__tests__/integration.test.js +347 -0
  24. package/dist/lib/answer/__tests__/prompt.test.js +117 -0
  25. package/dist/lib/answer/__tests__/t5-t10.test.js +501 -0
  26. package/dist/lib/answer/provider.js +29 -4
  27. package/dist/lib/api/__tests__/safe-error-message.test.js +155 -0
  28. package/dist/lib/auth/__tests__/localhost-guard.test.js +144 -0
  29. package/dist/lib/error-sanitizer/__tests__/sanitize.test.js +354 -0
  30. package/dist/lib/events/__tests__/bus.test.js +208 -0
  31. package/dist/lib/ingest-router.js +0 -43
  32. package/dist/lib/op-audit-extension/__tests__/ran-at-guard.test.js +109 -0
  33. package/dist/lib/regex-extract/__tests__/extractor.test.js +197 -0
  34. package/dist/lib/regex-extract/__tests__/frontmatter.test.js +75 -0
  35. package/dist/lib/regex-extract/__tests__/ingest-router-l4.test.js +139 -0
  36. package/dist/lib/regex-extract/__tests__/production-wire.test.js +177 -0
  37. package/dist/lib/regex-extract/__tests__/reconcile.test.js +170 -0
  38. package/dist/lib/regex-extract/__tests__/strip-code.test.js +36 -0
  39. package/dist/privacy/__tests__/filter.test.js +352 -0
  40. package/dist/providers/__tests__/conformance-extended.test.js +249 -0
  41. package/dist/providers/__tests__/conformance.test.js +98 -0
  42. package/dist/providers/__tests__/cost-cap.test.js +151 -0
  43. package/dist/providers/__tests__/e2e-real.test.js +79 -0
  44. package/dist/providers/__tests__/factory.test.js +80 -0
  45. package/dist/providers/__tests__/fallback.test.js +223 -0
  46. package/dist/providers/__tests__/gemini.test.js +191 -0
  47. package/dist/providers/__tests__/health.test.js +128 -0
  48. package/dist/providers/__tests__/telemetry.test.js +219 -0
  49. package/dist/reindex.js +2 -2
  50. package/package.json +3 -4
  51. package/dist/api/answer.d.ts +0 -116
  52. package/dist/api/answer.validate-patch.d.ts +0 -72
  53. package/dist/api/brief-diversity.d.ts +0 -64
  54. package/dist/api/brief.d.ts +0 -114
  55. package/dist/api/conflict.d.ts +0 -33
  56. package/dist/api/conflict.js +0 -143
  57. package/dist/api/cors.d.ts +0 -73
  58. package/dist/api/events-stream-limited.d.ts +0 -133
  59. package/dist/api/events-stream-limited.js +0 -217
  60. package/dist/api/events-stream.d.ts +0 -53
  61. package/dist/api/events-stream.js +0 -125
  62. package/dist/api/export.d.ts +0 -42
  63. package/dist/api/export.js +0 -85
  64. package/dist/api/health-confidence-adapter.d.ts +0 -29
  65. package/dist/api/health-confidence-adapter.js +0 -73
  66. package/dist/api/health-confidence.d.ts +0 -36
  67. package/dist/api/health-confidence.js +0 -141
  68. package/dist/api/hooks.d.ts +0 -50
  69. package/dist/api/hooks.js +0 -115
  70. package/dist/api/import.d.ts +0 -38
  71. package/dist/api/import.js +0 -87
  72. package/dist/api/ingest-event.d.ts +0 -65
  73. package/dist/api/mark.d.ts +0 -42
  74. package/dist/api/mark.js +0 -127
  75. package/dist/api/server-deps-a2.d.ts +0 -55
  76. package/dist/api/server-deps-a2.js +0 -138
  77. package/dist/api/server-deps-l2-l3.d.ts +0 -68
  78. package/dist/api/server-deps-l2-l3.js +0 -123
  79. package/dist/api/server-deps-p1.d.ts +0 -84
  80. package/dist/api/server-deps-p2.d.ts +0 -32
  81. package/dist/api/server-deps-p2.js +0 -84
  82. package/dist/api/server-deps-p5.d.ts +0 -66
  83. package/dist/api/server-deps-p5.js +0 -139
  84. package/dist/api/viewer-static.d.ts +0 -30
  85. package/dist/api/viewer-static.js +0 -102
  86. package/dist/api/wire-up.d.ts +0 -54
  87. package/dist/api-impact.d.ts +0 -30
  88. package/dist/api-server.d.ts +0 -2
  89. package/dist/backfill-fts-anchor.d.ts +0 -15
  90. package/dist/backfill-source-type.d.ts +0 -20
  91. package/dist/churn.d.ts +0 -31
  92. package/dist/cli/answer.d.ts +0 -66
  93. package/dist/cli/conflict.d.ts +0 -38
  94. package/dist/cli/conflict.js +0 -282
  95. package/dist/cli/export.d.ts +0 -51
  96. package/dist/cli/export.js +0 -280
  97. package/dist/cli/hooks.d.ts +0 -54
  98. package/dist/cli/hooks.js +0 -133
  99. package/dist/cli/import.d.ts +0 -52
  100. package/dist/cli/import.js +0 -274
  101. package/dist/cli/mark.d.ts +0 -33
  102. package/dist/cli/mark.js +0 -130
  103. package/dist/cli/ocr-batch.d.ts +0 -12
  104. package/dist/cli/ocr-batch.js +0 -411
  105. package/dist/cli/snapshot-main.d.ts +0 -30
  106. package/dist/cli/snapshot-main.js +0 -47
  107. package/dist/cli/viewer.d.ts +0 -35
  108. package/dist/cli/viewer.js +0 -71
  109. package/dist/cli-telemetry.d.ts +0 -36
  110. package/dist/cli-telemetry.js +0 -150
  111. package/dist/compact.d.ts +0 -7
  112. package/dist/consolidate.d.ts +0 -18
  113. package/dist/consolidation.d.ts +0 -32
  114. package/dist/cross-agent-v2.d.ts +0 -45
  115. package/dist/cross-search.d.ts +0 -11
  116. package/dist/crystallize.d.ts +0 -43
  117. package/dist/db.d.ts +0 -11
  118. package/dist/dedup.d.ts +0 -1
  119. package/dist/detect-changes.d.ts +0 -29
  120. package/dist/digest.d.ts +0 -1
  121. package/dist/doctor.d.ts +0 -1
  122. package/dist/embed.d.ts +0 -57
  123. package/dist/evals.d.ts +0 -176
  124. package/dist/evals.js +0 -351
  125. package/dist/generate-user-profile.d.ts +0 -18
  126. package/dist/graphify-ingest.d.ts +0 -18
  127. package/dist/impact.d.ts +0 -39
  128. package/dist/index.d.ts +0 -2
  129. package/dist/ingest-entity.d.ts +0 -44
  130. package/dist/ingest.d.ts +0 -13
  131. package/dist/kg-llm.d.ts +0 -39
  132. package/dist/knowledge-graph.d.ts +0 -72
  133. package/dist/lib/answer/config.d.ts +0 -41
  134. package/dist/lib/answer/index.d.ts +0 -47
  135. package/dist/lib/answer/prompt.d.ts +0 -37
  136. package/dist/lib/answer/provider.d.ts +0 -47
  137. package/dist/lib/answer/retrieval.d.ts +0 -36
  138. package/dist/lib/answer/telemetry.d.ts +0 -99
  139. package/dist/lib/answer/types.d.ts +0 -108
  140. package/dist/lib/api/error-leak-fix.d.ts +0 -54
  141. package/dist/lib/api/safe-error-message.d.ts +0 -70
  142. package/dist/lib/archive/common-passwords.d.ts +0 -37
  143. package/dist/lib/archive/common-passwords.js +0 -753
  144. package/dist/lib/archive/encryption.d.ts +0 -81
  145. package/dist/lib/archive/encryption.js +0 -236
  146. package/dist/lib/archive/enforce-strength.d.ts +0 -54
  147. package/dist/lib/archive/enforce-strength.js +0 -70
  148. package/dist/lib/archive/entropy.d.ts +0 -34
  149. package/dist/lib/archive/entropy.js +0 -180
  150. package/dist/lib/archive/export-locking.d.ts +0 -102
  151. package/dist/lib/archive/export-locking.js +0 -202
  152. package/dist/lib/archive/format.d.ts +0 -20
  153. package/dist/lib/archive/format.js +0 -174
  154. package/dist/lib/archive/index.d.ts +0 -23
  155. package/dist/lib/archive/index.js +0 -17
  156. package/dist/lib/archive/manifest.d.ts +0 -53
  157. package/dist/lib/archive/manifest.js +0 -183
  158. package/dist/lib/archive/migration.d.ts +0 -36
  159. package/dist/lib/archive/migration.js +0 -100
  160. package/dist/lib/archive/migrations/v18_to_v19.d.ts +0 -16
  161. package/dist/lib/archive/migrations/v18_to_v19.js +0 -18
  162. package/dist/lib/archive/orchestrator.d.ts +0 -166
  163. package/dist/lib/archive/orchestrator.js +0 -428
  164. package/dist/lib/archive/serializers/chunks.d.ts +0 -30
  165. package/dist/lib/archive/serializers/chunks.js +0 -113
  166. package/dist/lib/archive/serializers/embeddings.d.ts +0 -36
  167. package/dist/lib/archive/serializers/embeddings.js +0 -115
  168. package/dist/lib/archive/serializers/kg.d.ts +0 -28
  169. package/dist/lib/archive/serializers/kg.js +0 -184
  170. package/dist/lib/archive/serializers/ops_audit.d.ts +0 -21
  171. package/dist/lib/archive/serializers/ops_audit.js +0 -97
  172. package/dist/lib/archive/server-deps.d.ts +0 -131
  173. package/dist/lib/archive/server-deps.js +0 -232
  174. package/dist/lib/archive/strength.d.ts +0 -50
  175. package/dist/lib/archive/strength.js +0 -77
  176. package/dist/lib/archive/types.d.ts +0 -159
  177. package/dist/lib/archive/types.js +0 -45
  178. package/dist/lib/archive/unpack-streaming.d.ts +0 -70
  179. package/dist/lib/archive/unpack-streaming.js +0 -255
  180. package/dist/lib/auth/localhost-guard.d.ts +0 -106
  181. package/dist/lib/confidence/config.d.ts +0 -37
  182. package/dist/lib/confidence/config.js +0 -107
  183. package/dist/lib/confidence/db-shim-singleton.d.ts +0 -20
  184. package/dist/lib/confidence/db-shim-singleton.js +0 -41
  185. package/dist/lib/confidence/db-shim.d.ts +0 -47
  186. package/dist/lib/confidence/db-shim.js +0 -141
  187. package/dist/lib/confidence/mark.d.ts +0 -58
  188. package/dist/lib/confidence/mark.js +0 -168
  189. package/dist/lib/confidence/ranking.d.ts +0 -69
  190. package/dist/lib/confidence/ranking.js +0 -101
  191. package/dist/lib/confidence/search-filter.d.ts +0 -44
  192. package/dist/lib/confidence/search-filter.js +0 -103
  193. package/dist/lib/confidence/types.d.ts +0 -146
  194. package/dist/lib/confidence/types.js +0 -20
  195. package/dist/lib/confidence/write-hooks.d.ts +0 -50
  196. package/dist/lib/confidence/write-hooks.js +0 -159
  197. package/dist/lib/conflict/audit-fk-check.d.ts +0 -72
  198. package/dist/lib/conflict/audit-fk-check.js +0 -131
  199. package/dist/lib/conflict/audit-writer.d.ts +0 -39
  200. package/dist/lib/conflict/audit-writer.js +0 -133
  201. package/dist/lib/conflict/db-singleton.d.ts +0 -28
  202. package/dist/lib/conflict/db-singleton.js +0 -61
  203. package/dist/lib/conflict/db.d.ts +0 -27
  204. package/dist/lib/conflict/db.js +0 -20
  205. package/dist/lib/conflict/detector-direct.d.ts +0 -21
  206. package/dist/lib/conflict/detector-direct.js +0 -105
  207. package/dist/lib/conflict/evidence.d.ts +0 -24
  208. package/dist/lib/conflict/evidence.js +0 -76
  209. package/dist/lib/conflict/index.d.ts +0 -14
  210. package/dist/lib/conflict/index.js +0 -12
  211. package/dist/lib/conflict/scheduler.d.ts +0 -78
  212. package/dist/lib/conflict/scheduler.js +0 -111
  213. package/dist/lib/conflict/shadow.d.ts +0 -75
  214. package/dist/lib/conflict/shadow.js +0 -161
  215. package/dist/lib/conflict/types.d.ts +0 -133
  216. package/dist/lib/conflict/types.js +0 -19
  217. package/dist/lib/cost-cap.d.ts +0 -94
  218. package/dist/lib/deps/deps-registry.d.ts +0 -111
  219. package/dist/lib/error-sanitizer/middleware.d.ts +0 -43
  220. package/dist/lib/error-sanitizer/sanitize.d.ts +0 -78
  221. package/dist/lib/eval-batch.d.ts +0 -34
  222. package/dist/lib/eval-batch.js +0 -103
  223. package/dist/lib/eval-metrics.d.ts +0 -36
  224. package/dist/lib/eval-metrics.js +0 -95
  225. package/dist/lib/eval.d.ts +0 -106
  226. package/dist/lib/eval.js +0 -343
  227. package/dist/lib/events/bus.d.ts +0 -135
  228. package/dist/lib/fts-anchor.d.ts +0 -1
  229. package/dist/lib/hooks/classifier.d.ts +0 -47
  230. package/dist/lib/hooks/classifier.js +0 -129
  231. package/dist/lib/hooks/config.d.ts +0 -49
  232. package/dist/lib/hooks/config.js +0 -106
  233. package/dist/lib/hooks/decorators.d.ts +0 -35
  234. package/dist/lib/hooks/decorators.js +0 -59
  235. package/dist/lib/hooks/pipeline.d.ts +0 -76
  236. package/dist/lib/hooks/pipeline.js +0 -213
  237. package/dist/lib/hooks/privacy-filter-adapter.d.ts +0 -55
  238. package/dist/lib/hooks/privacy-filter-adapter.js +0 -84
  239. package/dist/lib/hooks/rate-limit-constant-time.d.ts +0 -57
  240. package/dist/lib/hooks/rate-limit-constant-time.js +0 -69
  241. package/dist/lib/hooks/rate-limit-dryrun-fix.d.ts +0 -71
  242. package/dist/lib/hooks/rate-limit-dryrun-fix.js +0 -110
  243. package/dist/lib/hooks/rate-limit.d.ts +0 -54
  244. package/dist/lib/hooks/rate-limit.js +0 -122
  245. package/dist/lib/hooks/server-deps.d.ts +0 -61
  246. package/dist/lib/hooks/server-deps.js +0 -92
  247. package/dist/lib/hooks/source-allowlist.d.ts +0 -26
  248. package/dist/lib/hooks/source-allowlist.js +0 -53
  249. package/dist/lib/hooks/types.d.ts +0 -129
  250. package/dist/lib/hooks/types.js +0 -24
  251. package/dist/lib/hooks/worker.d.ts +0 -56
  252. package/dist/lib/hooks/worker.js +0 -150
  253. package/dist/lib/ingest-router.d.ts +0 -25
  254. package/dist/lib/ocr-detector.d.ts +0 -61
  255. package/dist/lib/ocr-detector.js +0 -138
  256. package/dist/lib/ocr-engine-stub.d.ts +0 -48
  257. package/dist/lib/ocr-engine-stub.js +0 -190
  258. package/dist/lib/ocr-engines/google-doc-ai.d.ts +0 -36
  259. package/dist/lib/ocr-engines/google-doc-ai.js +0 -164
  260. package/dist/lib/ocr-jobs.d.ts +0 -67
  261. package/dist/lib/ocr-jobs.js +0 -129
  262. package/dist/lib/op-audit-extension/ran-at-guard.d.ts +0 -86
  263. package/dist/lib/op-audit.d.ts +0 -71
  264. package/dist/lib/privacy-br/detector.d.ts +0 -42
  265. package/dist/lib/privacy-br/detector.js +0 -130
  266. package/dist/lib/privacy-br/index.d.ts +0 -20
  267. package/dist/lib/privacy-br/index.js +0 -20
  268. package/dist/lib/privacy-br/integration.d.ts +0 -71
  269. package/dist/lib/privacy-br/integration.js +0 -74
  270. package/dist/lib/privacy-br/patterns.d.ts +0 -117
  271. package/dist/lib/privacy-br/patterns.js +0 -434
  272. package/dist/lib/privacy-br/redact.d.ts +0 -42
  273. package/dist/lib/privacy-br/redact.js +0 -103
  274. package/dist/lib/privacy-br/types.d.ts +0 -55
  275. package/dist/lib/privacy-br/types.js +0 -25
  276. package/dist/lib/regex-extract/extractor.d.ts +0 -30
  277. package/dist/lib/regex-extract/frontmatter.d.ts +0 -44
  278. package/dist/lib/regex-extract/index.d.ts +0 -14
  279. package/dist/lib/regex-extract/ingest-router-l4.d.ts +0 -76
  280. package/dist/lib/regex-extract/patterns.d.ts +0 -61
  281. package/dist/lib/regex-extract/production-wire.d.ts +0 -128
  282. package/dist/lib/regex-extract/reconcile.d.ts +0 -162
  283. package/dist/lib/regex-extract/strip-code.d.ts +0 -24
  284. package/dist/lib/regex-extract/types.d.ts +0 -48
  285. package/dist/lib/reranker.d.ts +0 -80
  286. package/dist/lib/shadow-tracker.d.ts +0 -191
  287. package/dist/lib/shadow-tracker.js +0 -384
  288. package/dist/lib/spo-injection.d.ts +0 -52
  289. package/dist/lib/telemetry-collector.d.ts +0 -158
  290. package/dist/lib/telemetry-collector.js +0 -249
  291. package/dist/lib/temporal-detector.d.ts +0 -27
  292. package/dist/lib/viewer/auth.d.ts +0 -37
  293. package/dist/lib/viewer/auth.js +0 -70
  294. package/dist/lib/viewer/backpressure.d.ts +0 -59
  295. package/dist/lib/viewer/backpressure.js +0 -100
  296. package/dist/lib/viewer/broadcast-singleton.d.ts +0 -34
  297. package/dist/lib/viewer/broadcast-singleton.js +0 -49
  298. package/dist/lib/viewer/broadcast.d.ts +0 -66
  299. package/dist/lib/viewer/broadcast.js +0 -96
  300. package/dist/lib/viewer/event-types.d.ts +0 -132
  301. package/dist/lib/viewer/event-types.js +0 -74
  302. package/dist/lib/viewer/instrumentation.d.ts +0 -106
  303. package/dist/lib/viewer/instrumentation.js +0 -224
  304. package/dist/lib/viewer/migration.d.ts +0 -23
  305. package/dist/lib/viewer/migration.js +0 -56
  306. package/dist/lib/viewer/redaction.d.ts +0 -44
  307. package/dist/lib/viewer/redaction.js +0 -139
  308. package/dist/lib/viewer/session.d.ts +0 -51
  309. package/dist/lib/viewer/session.js +0 -87
  310. package/dist/mcp/tools/answer.d.ts +0 -94
  311. package/dist/mcp/tools/archive.d.ts +0 -152
  312. package/dist/mcp/tools/archive.js +0 -170
  313. package/dist/mcp/tools/conflict.d.ts +0 -44
  314. package/dist/mcp/tools/conflict.js +0 -130
  315. package/dist/mcp/tools/hooks.d.ts +0 -29
  316. package/dist/mcp/tools/hooks.js +0 -78
  317. package/dist/mcp/tools/mark.d.ts +0 -38
  318. package/dist/mcp/tools/mark.js +0 -82
  319. package/dist/mcp/tools/viewer.d.ts +0 -58
  320. package/dist/mcp/tools/viewer.js +0 -64
  321. package/dist/mcp-server.d.ts +0 -2
  322. package/dist/metrics.d.ts +0 -3
  323. package/dist/noise-filter.d.ts +0 -18
  324. package/dist/notion-sync.d.ts +0 -7
  325. package/dist/notion-sync.js +0 -97
  326. package/dist/observability/adapters/a3-adapter.d.ts +0 -63
  327. package/dist/observability/adapters/a3-adapter.js +0 -83
  328. package/dist/observability/adapters/p1-adapter.d.ts +0 -49
  329. package/dist/observability/adapters/p1-adapter.js +0 -63
  330. package/dist/observability/adapters/p5-adapter.d.ts +0 -36
  331. package/dist/observability/adapters/p5-adapter.js +0 -71
  332. package/dist/observability/cardinality.d.ts +0 -61
  333. package/dist/observability/cardinality.js +0 -300
  334. package/dist/observability/collectors/db-stats.collector.d.ts +0 -9
  335. package/dist/observability/collectors/db-stats.collector.js +0 -88
  336. package/dist/observability/collectors/eventbus.collector.d.ts +0 -6
  337. package/dist/observability/collectors/eventbus.collector.js +0 -50
  338. package/dist/observability/collectors/process.collector.d.ts +0 -7
  339. package/dist/observability/collectors/process.collector.js +0 -93
  340. package/dist/observability/collectors/provider-telemetry.collector.d.ts +0 -11
  341. package/dist/observability/collectors/provider-telemetry.collector.js +0 -112
  342. package/dist/observability/collectors/search-telemetry.collector.d.ts +0 -12
  343. package/dist/observability/collectors/search-telemetry.collector.js +0 -76
  344. package/dist/observability/exporter.d.ts +0 -30
  345. package/dist/observability/exporter.js +0 -182
  346. package/dist/observability/index.d.ts +0 -22
  347. package/dist/observability/index.js +0 -21
  348. package/dist/observability/metrics.d.ts +0 -53
  349. package/dist/observability/metrics.js +0 -213
  350. package/dist/observability/privacy-guard.d.ts +0 -32
  351. package/dist/observability/privacy-guard.js +0 -116
  352. package/dist/observability/record.d.ts +0 -83
  353. package/dist/observability/record.js +0 -217
  354. package/dist/observability/registry.d.ts +0 -60
  355. package/dist/observability/registry.js +0 -93
  356. package/dist/observability/types.d.ts +0 -115
  357. package/dist/observability/types.js +0 -235
  358. package/dist/observability.d.ts +0 -131
  359. package/dist/plugins/nox-hooks/index.d.ts +0 -61
  360. package/dist/plugins/nox-hooks/index.js +0 -99
  361. package/dist/primer.d.ts +0 -1
  362. package/dist/privacy/filter.d.ts +0 -27
  363. package/dist/privacy/patterns.d.ts +0 -29
  364. package/dist/privacy/tag-parser.d.ts +0 -24
  365. package/dist/project-context-gen.d.ts +0 -10
  366. package/dist/providers/embedding/gemini.d.ts +0 -73
  367. package/dist/providers/embedding/openai.d.ts +0 -76
  368. package/dist/providers/embedding/types.d.ts +0 -39
  369. package/dist/providers/embedding/voyage.d.ts +0 -36
  370. package/dist/providers/index.d.ts +0 -116
  371. package/dist/providers/llm/anthropic.d.ts +0 -29
  372. package/dist/providers/llm/chain.d.ts +0 -99
  373. package/dist/providers/llm/gemini.d.ts +0 -48
  374. package/dist/providers/llm/openai.d.ts +0 -64
  375. package/dist/providers/llm/types.d.ts +0 -47
  376. package/dist/providers/telemetry.d.ts +0 -87
  377. package/dist/providers/types.d.ts +0 -42
  378. package/dist/query-entity-count.d.ts +0 -54
  379. package/dist/reflect.d.ts +0 -26
  380. package/dist/reindex-errors.d.ts +0 -7
  381. package/dist/reindex.d.ts +0 -16
  382. package/dist/retention.d.ts +0 -40
  383. package/dist/salience.d.ts +0 -85
  384. package/dist/scripts/migrate-v17-ops-audit.d.ts +0 -17
  385. package/dist/search-dedup.d.ts +0 -44
  386. package/dist/search-expansion.d.ts +0 -20
  387. package/dist/search.d.ts +0 -62
  388. package/dist/seh-detector.d.ts +0 -31
  389. package/dist/self-improve.d.ts +0 -1
  390. package/dist/session-distill.d.ts +0 -29
  391. package/dist/session-update.d.ts +0 -1
  392. package/dist/shared-memory.d.ts +0 -24
  393. package/dist/stats.d.ts +0 -1
  394. package/dist/temporal-retrieval.d.ts +0 -132
  395. package/dist/tier-manager.d.ts +0 -69
  396. package/dist/vectorize.d.ts +0 -16
  397. package/dist/version.d.ts +0 -1
  398. package/dist/watch.d.ts +0 -8
@@ -1,428 +0,0 @@
1
- /**
2
- * Orchestrator — T10/T11/T13/T14 backing module.
3
- *
4
- * Wires the T1-T9 primitives (format/manifest/serializers/encryption/migration)
5
- * into two top-level operations: `runExport` and `runImport`. Framework-agnostic
6
- * — CLI, HTTP and MCP layers all funnel through here.
7
- *
8
- * Design constraints (D41 #2 + spec §3 §6):
9
- * 1. Encrypt-by-default — `unencrypted: true` is opt-out (CLI / HTTP / MCP
10
- * surfaces enforce ACK separately).
11
- * 2. Passphrase never via argv — caller passes a string OR a `getPassphrase`
12
- * thunk; this module never inspects `process.argv`.
13
- * 3. Streaming-friendly outputs — `runExport` returns a Buffer for now
14
- * (T10/T11 pivot). The format module already exposes `packArchiveStream`
15
- * for callers that need to pipe directly to disk.
16
- * 4. Progress events — caller passes an optional `onProgress` callback. Tests
17
- * assert callback is invoked for each major phase.
18
- * 5. Cancellation — caller passes an optional `AbortSignal`. We abort
19
- * between phases (no partial DB writes possible because we build a single
20
- * tarball in memory before writing).
21
- * 6. ops_audit append-only — see T11 import path; merge/replace never DELETE
22
- * audit rows (enforced by `planOpsAuditImport`).
23
- * 7. Manifest AAD invariant — re-built via `manifestAADHash` after encryption
24
- * metadata is filled in, so decrypt side recomputes identically.
25
- */
26
- import { BadPassphraseError, TamperedArchiveError, } from "./types.js";
27
- import { listArchive, packArchive, unpackArchive } from "./format.js";
28
- import { buildManifest, manifestAADHash, parseManifest, writeManifest, } from "./manifest.js";
29
- import { serializeChunks, parseChunks, planChunkImport } from "./serializers/chunks.js";
30
- import { serializeKgEntities, parseKgEntities, serializeKgRelations, parseKgRelations, planKgMerge, } from "./serializers/kg.js";
31
- import { serializeOpsAudit, parseOpsAudit, planOpsAuditImport, } from "./serializers/ops_audit.js";
32
- import { serializeEmbeddings, parseEmbeddings, } from "./serializers/embeddings.js";
33
- import { buildEncryptionMetadata, decryptArchiveFile, deriveKey, encryptBuffer, } from "./encryption.js";
34
- import { canImport, migrateChunks } from "./migration.js";
35
- import { createHash, randomBytes } from "node:crypto";
36
- import { SALT_LEN } from "./encryption.js";
37
- // -- export -------------------------------------------------------------------
38
- const FILE_NAMES = {
39
- schema: "schema.sql",
40
- chunks: "chunks.jsonl",
41
- embeddings_bin: "embeddings.bin",
42
- embeddings_idx: "embeddings.idx",
43
- kg_entities: "kg_entities.jsonl",
44
- kg_relations: "kg_relations.jsonl",
45
- ops_audit: "ops_audit.jsonl",
46
- };
47
- /** Encrypted-suffix variant. */
48
- function encName(name) {
49
- return `${name}.enc`;
50
- }
51
- export async function runExport(req) {
52
- const started = Date.now();
53
- const emit = (ev) => req.onProgress?.(ev);
54
- const checkAbort = () => {
55
- if (req.signal?.aborted) {
56
- throw new Error("Export cancelled");
57
- }
58
- };
59
- emit({ phase: "export.start", total: req.chunks.length });
60
- // --- Serialize each table -------------------------------------------------
61
- checkAbort();
62
- const chunksBuf = serializeChunks(req.chunks);
63
- emit({
64
- phase: "export.chunks",
65
- emitted: req.chunks.length,
66
- total: req.chunks.length,
67
- });
68
- checkAbort();
69
- let embeddingsBundle = null;
70
- if (req.embeddings && req.embeddings.length > 0) {
71
- embeddingsBundle = serializeEmbeddings(req.embeddings);
72
- emit({
73
- phase: "export.embeddings",
74
- emitted: req.embeddings.length,
75
- total: req.embeddings.length,
76
- });
77
- }
78
- checkAbort();
79
- const kgEntitiesBuf = serializeKgEntities(req.kg_entities ?? []);
80
- const kgRelationsBuf = serializeKgRelations(req.kg_relations ?? []);
81
- emit({
82
- phase: "export.kg",
83
- emitted: (req.kg_entities?.length ?? 0) + (req.kg_relations?.length ?? 0),
84
- total: (req.kg_entities?.length ?? 0) + (req.kg_relations?.length ?? 0),
85
- });
86
- checkAbort();
87
- const opsAuditBuf = serializeOpsAudit(req.ops_audit ?? []);
88
- // --- Build counts + checksums ---------------------------------------------
89
- const counts = {
90
- chunks: req.chunks.length,
91
- embeddings: req.embeddings?.length ?? 0,
92
- kg_entities: req.kg_entities?.length ?? 0,
93
- kg_relations: req.kg_relations?.length ?? 0,
94
- ops_audit: req.ops_audit?.length ?? 0,
95
- };
96
- const checksums = {
97
- [FILE_NAMES.chunks]: sha256Hex(chunksBuf),
98
- [FILE_NAMES.kg_entities]: sha256Hex(kgEntitiesBuf),
99
- [FILE_NAMES.kg_relations]: sha256Hex(kgRelationsBuf),
100
- [FILE_NAMES.ops_audit]: sha256Hex(opsAuditBuf),
101
- };
102
- if (embeddingsBundle) {
103
- checksums[FILE_NAMES.embeddings_bin] = sha256Hex(embeddingsBundle.bin);
104
- checksums[FILE_NAMES.embeddings_idx] = sha256Hex(embeddingsBundle.idx);
105
- }
106
- const schemaSql = buildSchemaSql(req.schema_version);
107
- checksums[FILE_NAMES.schema] = sha256Hex(schemaSql);
108
- // --- Determine includes ---------------------------------------------------
109
- const includes = ["chunks"];
110
- if (embeddingsBundle)
111
- includes.push("embeddings");
112
- if ((req.kg_entities?.length ?? 0) + (req.kg_relations?.length ?? 0) > 0) {
113
- includes.push("kg");
114
- }
115
- if ((req.ops_audit?.length ?? 0) > 0)
116
- includes.push("audit");
117
- // --- Build manifest (no encryption yet) -----------------------------------
118
- let manifest = buildManifest({
119
- schema_version: req.schema_version,
120
- source_hostname: req.source_hostname,
121
- source_nox_mem_version: req.source_nox_mem_version,
122
- embedding_provider: req.embedding_provider,
123
- embedding_model: req.embedding_model,
124
- embedding_dim: req.embedding_dim,
125
- sqlite_vec_version: req.sqlite_vec_version ?? null,
126
- includes,
127
- filters: req.filters,
128
- counts,
129
- checksums,
130
- });
131
- const unencrypted = req.unencrypted === true;
132
- // --- Encryption (if requested) --------------------------------------------
133
- const archiveEntries = [];
134
- // Schema + manifest go in plain — manifest LAST so AAD is stable
135
- archiveEntries.push({ name: FILE_NAMES.schema, content: schemaSql });
136
- if (unencrypted) {
137
- archiveEntries.push({ name: FILE_NAMES.chunks, content: chunksBuf });
138
- if (embeddingsBundle) {
139
- archiveEntries.push({
140
- name: FILE_NAMES.embeddings_bin,
141
- content: embeddingsBundle.bin,
142
- });
143
- archiveEntries.push({
144
- name: FILE_NAMES.embeddings_idx,
145
- content: embeddingsBundle.idx,
146
- });
147
- }
148
- archiveEntries.push({ name: FILE_NAMES.kg_entities, content: kgEntitiesBuf });
149
- archiveEntries.push({
150
- name: FILE_NAMES.kg_relations,
151
- content: kgRelationsBuf,
152
- });
153
- archiveEntries.push({ name: FILE_NAMES.ops_audit, content: opsAuditBuf });
154
- }
155
- else {
156
- checkAbort();
157
- if (typeof req.passphrase !== "string" || req.passphrase.length === 0) {
158
- throw new Error("runExport: passphrase required (D41 #2 encrypt-by-default). " +
159
- "Pass `unencrypted: true` to opt out explicitly.");
160
- }
161
- // AAD source = canonical manifest plaintext WITHOUT encryption metadata,
162
- // computed via manifestAADHash (see manifest.ts).
163
- const aad = manifestAADHash(manifest);
164
- const salt = randomBytes(SALT_LEN);
165
- const key = deriveKey(req.passphrase, salt);
166
- const filesToEncrypt = [
167
- { name: FILE_NAMES.chunks, buf: chunksBuf },
168
- { name: FILE_NAMES.kg_entities, buf: kgEntitiesBuf },
169
- { name: FILE_NAMES.kg_relations, buf: kgRelationsBuf },
170
- { name: FILE_NAMES.ops_audit, buf: opsAuditBuf },
171
- ];
172
- if (embeddingsBundle) {
173
- filesToEncrypt.push({
174
- name: FILE_NAMES.embeddings_bin,
175
- buf: embeddingsBundle.bin,
176
- });
177
- filesToEncrypt.push({
178
- name: FILE_NAMES.embeddings_idx,
179
- buf: embeddingsBundle.idx,
180
- });
181
- }
182
- const encResults = {};
183
- for (const f of filesToEncrypt) {
184
- checkAbort();
185
- const res = encryptBuffer(f.buf, key, aad);
186
- encResults[encName(f.name)] = res;
187
- archiveEntries.push({ name: encName(f.name), content: res.ciphertext });
188
- }
189
- emit({ phase: "export.encrypt", files: filesToEncrypt.length });
190
- const encryptionMeta = buildEncryptionMetadata(salt.toString("base64"), encResults);
191
- // CRITICAL: preserve created_at from the AAD-source manifest. Re-running
192
- // buildManifest() with no created_at would default to Date.now(), which
193
- // would change the AAD bytes between export-time and import-time and
194
- // break GCM auth tag verification. Memory feedback: AAD stability is the
195
- // entire reason manifest canonicalization exists (manifest.ts §AAD).
196
- manifest = buildManifest({
197
- schema_version: req.schema_version,
198
- source_hostname: req.source_hostname,
199
- source_nox_mem_version: req.source_nox_mem_version,
200
- embedding_provider: req.embedding_provider,
201
- embedding_model: req.embedding_model,
202
- embedding_dim: req.embedding_dim,
203
- sqlite_vec_version: req.sqlite_vec_version ?? null,
204
- includes,
205
- filters: req.filters,
206
- counts,
207
- checksums,
208
- encryption: encryptionMeta,
209
- created_at: manifest.created_at, // freeze
210
- });
211
- }
212
- // Manifest is ALWAYS plaintext (D41 #2)
213
- const manifestBuf = writeManifest(manifest);
214
- archiveEntries.push({ name: "manifest.json", content: manifestBuf });
215
- checkAbort();
216
- emit({ phase: "export.pack", entries: archiveEntries.length });
217
- const archive = packArchive(archiveEntries);
218
- const duration_ms = Date.now() - started;
219
- emit({ phase: "export.done", size_bytes: archive.length, duration_ms });
220
- return { archive, manifest, size_bytes: archive.length, duration_ms };
221
- }
222
- // -- import -------------------------------------------------------------------
223
- export async function runImport(req) {
224
- const started = Date.now();
225
- const emit = (ev) => req.onProgress?.(ev);
226
- const checkAbort = () => {
227
- if (req.signal?.aborted) {
228
- throw new Error("Import cancelled");
229
- }
230
- };
231
- emit({ phase: "import.start" });
232
- const entries = unpackArchive(req.archive);
233
- emit({ phase: "import.unpack", entries: entries.length });
234
- const byName = new Map();
235
- for (const e of entries)
236
- byName.set(e.name, e.content);
237
- const manifestBuf = byName.get("manifest.json");
238
- if (!manifestBuf) {
239
- throw new Error("Import: manifest.json missing");
240
- }
241
- const manifest = parseManifest(manifestBuf);
242
- // Validate schema compatibility BEFORE any decryption / DB work.
243
- const importable = canImport(manifest.schema_version, req.current_schema_version);
244
- if (!importable.ok) {
245
- throw new Error(importable.reason);
246
- }
247
- // Decrypt (or pass through) per-table buffers.
248
- checkAbort();
249
- const encrypted = manifest.encryption.enabled === true;
250
- if (encrypted && (typeof req.passphrase !== "string" || req.passphrase.length === 0)) {
251
- throw new Error("Import: archive is encrypted; pass passphrase. (See `NOX_IMPORT_PASSPHRASE` env or `--passphrase-env`.)");
252
- }
253
- const aad = manifestAADHash(manifest);
254
- const pickBuf = (plainName) => {
255
- if (encrypted) {
256
- const ct = byName.get(encName(plainName));
257
- if (!ct)
258
- return undefined;
259
- return decryptArchiveFile({
260
- ciphertext: ct,
261
- fileName: encName(plainName),
262
- encryptionMetadata: manifest.encryption,
263
- passphrase: req.passphrase,
264
- aad,
265
- });
266
- }
267
- return byName.get(plainName);
268
- };
269
- let encryptedFiles = 0;
270
- if (encrypted) {
271
- encryptedFiles = Object.keys(manifest.encryption.files).length;
272
- emit({ phase: "import.decrypt", files: encryptedFiles });
273
- }
274
- // Pull every table buffer through decrypt + checksum validation.
275
- const chunksBuf = pickBuf(FILE_NAMES.chunks);
276
- if (!chunksBuf)
277
- throw new Error("Import: chunks payload missing");
278
- validatePlaintextChecksum(chunksBuf, FILE_NAMES.chunks, manifest, encrypted);
279
- const kgEntitiesBuf = pickBuf(FILE_NAMES.kg_entities);
280
- if (kgEntitiesBuf) {
281
- validatePlaintextChecksum(kgEntitiesBuf, FILE_NAMES.kg_entities, manifest, encrypted);
282
- }
283
- const kgRelationsBuf = pickBuf(FILE_NAMES.kg_relations);
284
- if (kgRelationsBuf) {
285
- validatePlaintextChecksum(kgRelationsBuf, FILE_NAMES.kg_relations, manifest, encrypted);
286
- }
287
- const opsAuditBuf = pickBuf(FILE_NAMES.ops_audit);
288
- if (opsAuditBuf) {
289
- validatePlaintextChecksum(opsAuditBuf, FILE_NAMES.ops_audit, manifest, encrypted);
290
- }
291
- const embBin = pickBuf(FILE_NAMES.embeddings_bin);
292
- const embIdx = pickBuf(FILE_NAMES.embeddings_idx);
293
- if (embBin && embIdx) {
294
- validatePlaintextChecksum(embBin, FILE_NAMES.embeddings_bin, manifest, encrypted);
295
- validatePlaintextChecksum(embIdx, FILE_NAMES.embeddings_idx, manifest, encrypted);
296
- }
297
- if (req.verify_only) {
298
- // Stop here: integrity passed, no resolution / writes.
299
- return assembleVerifyResult(manifest, started);
300
- }
301
- // Parse buffers into structured rows.
302
- let chunks = parseChunks(chunksBuf);
303
- if (manifest.schema_version !== req.current_schema_version) {
304
- emit({
305
- phase: "import.migrate",
306
- from: manifest.schema_version,
307
- to: req.current_schema_version,
308
- steps: req.current_schema_version - manifest.schema_version,
309
- });
310
- chunks = migrateChunks(chunks, manifest.schema_version, req.current_schema_version);
311
- }
312
- const kgEntities = kgEntitiesBuf ? parseKgEntities(kgEntitiesBuf) : [];
313
- const kgRelations = kgRelationsBuf ? parseKgRelations(kgRelationsBuf) : [];
314
- const opsAudit = opsAuditBuf ? parseOpsAudit(opsAuditBuf) : [];
315
- const embeddings = embBin && embIdx ? parseEmbeddings(embBin, embIdx) : new Map();
316
- // Plan merges.
317
- const mode = req.mode ?? "merge";
318
- const existing = req.existing ?? {};
319
- const chunkPlan = planChunkImport(chunks, existing.chunks ?? [], mode);
320
- emit({
321
- phase: "import.chunks",
322
- imported: chunkPlan.inserted,
323
- total: chunks.length,
324
- });
325
- const kgPlan = planKgMerge(kgEntities, existing.kg_entities ?? [], kgRelations, existing.kg_relations ?? []);
326
- emit({
327
- phase: "import.kg",
328
- imported: kgPlan.entities.inserted + kgPlan.relations.inserted,
329
- total: kgEntities.length + kgRelations.length,
330
- });
331
- const opsPlan = planOpsAuditImport(opsAudit, existing.ops_audit ?? []);
332
- const duration_ms = Date.now() - started;
333
- emit({ phase: "import.done", duration_ms });
334
- return {
335
- manifest,
336
- stats: {
337
- chunks: {
338
- inserted: chunkPlan.inserted,
339
- skipped: chunkPlan.skipped,
340
- merged: chunkPlan.merged,
341
- warnings: chunkPlan.warnings,
342
- },
343
- kg_entities: {
344
- inserted: kgPlan.entities.inserted,
345
- skipped: kgPlan.entities.skipped,
346
- merged: kgPlan.entities.merged,
347
- warnings: kgPlan.entities.warnings,
348
- },
349
- kg_relations: {
350
- inserted: kgPlan.relations.inserted,
351
- skipped: kgPlan.relations.skipped,
352
- merged: kgPlan.relations.merged,
353
- warnings: kgPlan.relations.warnings,
354
- },
355
- ops_audit: {
356
- inserted: opsPlan.inserted,
357
- skipped: opsPlan.skipped,
358
- merged: opsPlan.merged,
359
- warnings: opsPlan.warnings,
360
- },
361
- embeddings: { embedded: embeddings.size, skipped: 0 },
362
- },
363
- resolved: {
364
- chunks: chunkPlan.keep,
365
- kg_entities: kgPlan.entities.keep,
366
- kg_relations: kgPlan.relations.keep,
367
- ops_audit: opsPlan.keep,
368
- embeddings,
369
- },
370
- duration_ms,
371
- applied: req.dry_run !== true,
372
- };
373
- }
374
- /** Synchronous list of archive entries (open-toolchain DoD #4 hook). */
375
- export function listArchiveEntries(archive) {
376
- return listArchive(archive);
377
- }
378
- // -- internals ---------------------------------------------------------------
379
- function sha256Hex(buf) {
380
- return createHash("sha256").update(buf).digest("hex");
381
- }
382
- function buildSchemaSql(schemaVersion) {
383
- // Minimal canonical DDL pointer — full CREATE TABLE text is produced by the
384
- // caller (T11 import wires it to better-sqlite3 in production). For staged
385
- // module, we emit a version header so downstream consumers know what to
386
- // expect.
387
- const body = `-- nox-mem schema version ${schemaVersion}\n` +
388
- `-- This is a header stub; full DDL is reproduced by the importer side.\n`;
389
- return Buffer.from(body, "utf8");
390
- }
391
- function validatePlaintextChecksum(buf, name, manifest, encrypted) {
392
- const expected = manifest.checksums[name];
393
- if (!expected) {
394
- throw new Error(`Import: manifest missing checksum for ${name}`);
395
- }
396
- const got = sha256Hex(buf);
397
- if (got !== expected) {
398
- // For encrypted archives, this state is unreachable in practice — GCM
399
- // tag would have rejected first. But if it does happen, it's tamper.
400
- if (encrypted) {
401
- throw new TamperedArchiveError(`Plaintext checksum mismatch for ${name} after decrypt — archive tampered`);
402
- }
403
- throw new TamperedArchiveError(`Plaintext checksum mismatch for ${name}: expected ${expected}, got ${got}`);
404
- }
405
- }
406
- function assembleVerifyResult(manifest, started) {
407
- return {
408
- manifest,
409
- stats: {
410
- chunks: { inserted: 0, skipped: 0, merged: 0, warnings: [] },
411
- kg_entities: { inserted: 0, skipped: 0, merged: 0, warnings: [] },
412
- kg_relations: { inserted: 0, skipped: 0, merged: 0, warnings: [] },
413
- ops_audit: { inserted: 0, skipped: 0, merged: 0, warnings: [] },
414
- embeddings: { embedded: 0, skipped: 0 },
415
- },
416
- resolved: {
417
- chunks: [],
418
- kg_entities: [],
419
- kg_relations: [],
420
- ops_audit: [],
421
- embeddings: new Map(),
422
- },
423
- duration_ms: Date.now() - started,
424
- applied: false,
425
- };
426
- }
427
- // Re-exported convenience for callers that want the canonical error classes.
428
- export { BadPassphraseError, TamperedArchiveError };
@@ -1,30 +0,0 @@
1
- /**
2
- * T3 — Chunks serializer.
3
- *
4
- * JSONL one row per line. Preserves all schema v.29 columns:
5
- * id, content, content_hash, source_path, source_kind, project,
6
- * created_at, updated_at, retention_days, pain, section, section_boost,
7
- * metadata_json
8
- *
9
- * Schema v.29 columns retention_days/pain/section/section_boost are MANDATORY
10
- * (CLAUDE.md §regra #6 — A2 reindex incident). Missing any of them = test fail.
11
- */
12
- import { ChunkRow, ImportMode, ImportStats } from "../types.js";
13
- /** Serialize rows to a JSONL Buffer. */
14
- export declare function serializeChunks(rows: Iterable<ChunkRow>): Buffer;
15
- /** Parse a JSONL Buffer back into rows. */
16
- export declare function parseChunks(buf: Buffer): ChunkRow[];
17
- /** Single-row serializer. Stable key order matches SCHEMA_FIELDS. */
18
- export declare function serializeChunkRow(row: ChunkRow): string;
19
- export declare function parseChunkRow(line: string): ChunkRow;
20
- /**
21
- * In-memory import simulation. Used by tests + future DB-bound importer to
22
- * compute stats deterministically before hitting the DB.
23
- *
24
- * @param incoming new rows from archive
25
- * @param existing rows already in the DB (or empty for replace mode)
26
- * @param mode merge dedups by content_hash; replace wipes existing first
27
- */
28
- export declare function planChunkImport(incoming: ChunkRow[], existing: ChunkRow[], mode: ImportMode): ImportStats & {
29
- keep: ChunkRow[];
30
- };
@@ -1,113 +0,0 @@
1
- /**
2
- * T3 — Chunks serializer.
3
- *
4
- * JSONL one row per line. Preserves all schema v.29 columns:
5
- * id, content, content_hash, source_path, source_kind, project,
6
- * created_at, updated_at, retention_days, pain, section, section_boost,
7
- * metadata_json
8
- *
9
- * Schema v.29 columns retention_days/pain/section/section_boost are MANDATORY
10
- * (CLAUDE.md §regra #6 — A2 reindex incident). Missing any of them = test fail.
11
- */
12
- const SCHEMA_FIELDS = [
13
- "id",
14
- "content",
15
- "content_hash",
16
- "source_path",
17
- "source_kind",
18
- "project",
19
- "created_at",
20
- "updated_at",
21
- "retention_days",
22
- "pain",
23
- "section",
24
- "section_boost",
25
- "metadata_json",
26
- ];
27
- /** Serialize rows to a JSONL Buffer. */
28
- export function serializeChunks(rows) {
29
- const lines = [];
30
- for (const row of rows) {
31
- lines.push(serializeChunkRow(row));
32
- }
33
- return Buffer.from(lines.length > 0 ? lines.join("\n") + "\n" : "", "utf8");
34
- }
35
- /** Parse a JSONL Buffer back into rows. */
36
- export function parseChunks(buf) {
37
- const text = buf.toString("utf8");
38
- if (text.length === 0)
39
- return [];
40
- const rows = [];
41
- for (const line of text.split("\n")) {
42
- if (line.length === 0)
43
- continue;
44
- rows.push(parseChunkRow(line));
45
- }
46
- return rows;
47
- }
48
- /** Single-row serializer. Stable key order matches SCHEMA_FIELDS. */
49
- export function serializeChunkRow(row) {
50
- const obj = {};
51
- for (const k of SCHEMA_FIELDS)
52
- obj[k] = row[k];
53
- return JSON.stringify(obj);
54
- }
55
- export function parseChunkRow(line) {
56
- const raw = JSON.parse(line);
57
- for (const field of SCHEMA_FIELDS) {
58
- if (!(field in raw)) {
59
- throw new Error(`chunks.jsonl row missing required field: ${field}`);
60
- }
61
- }
62
- return {
63
- id: raw.id,
64
- content: raw.content,
65
- content_hash: raw.content_hash,
66
- source_path: raw.source_path,
67
- source_kind: raw.source_kind,
68
- project: raw.project,
69
- created_at: raw.created_at,
70
- updated_at: raw.updated_at,
71
- retention_days: raw.retention_days,
72
- pain: raw.pain,
73
- section: raw.section,
74
- section_boost: raw.section_boost,
75
- metadata_json: raw.metadata_json,
76
- };
77
- }
78
- /**
79
- * In-memory import simulation. Used by tests + future DB-bound importer to
80
- * compute stats deterministically before hitting the DB.
81
- *
82
- * @param incoming new rows from archive
83
- * @param existing rows already in the DB (or empty for replace mode)
84
- * @param mode merge dedups by content_hash; replace wipes existing first
85
- */
86
- export function planChunkImport(incoming, existing, mode) {
87
- const warnings = [];
88
- if (mode === "replace") {
89
- return {
90
- inserted: incoming.length,
91
- skipped: 0,
92
- merged: 0,
93
- warnings,
94
- keep: [...incoming],
95
- };
96
- }
97
- const existingByHash = new Map();
98
- for (const r of existing)
99
- existingByHash.set(r.content_hash, r);
100
- let inserted = 0;
101
- let skipped = 0;
102
- const keep = [...existing];
103
- for (const row of incoming) {
104
- if (existingByHash.has(row.content_hash)) {
105
- skipped++;
106
- continue;
107
- }
108
- keep.push(row);
109
- existingByHash.set(row.content_hash, row);
110
- inserted++;
111
- }
112
- return { inserted, skipped, merged: 0, warnings, keep };
113
- }
@@ -1,36 +0,0 @@
1
- /**
2
- * T4 — Embeddings serializer.
3
- *
4
- * Binary layout for embeddings.bin:
5
- *
6
- * bytes 0..7 magic "NOXEMBED" (ASCII)
7
- * bytes 8..11 format version (uint32 LE) = 1
8
- * bytes 12..15 embedding_dim (uint32 LE)
9
- * bytes 16+ raw concatenated Float32Array, little-endian
10
- *
11
- * embeddings.idx is JSONL: one EmbeddingIndexEntry per line, mapping chunk_id
12
- * to its (offset, length) inside embeddings.bin. length is in BYTES, not floats.
13
- *
14
- * CRITICAL — Buffer pool aliasing (memory feedback
15
- * `feedback_buffer_pool_aliasing_in_typed_arrays`): when reading floats back
16
- * out of the bin, we MUST copy through a Uint8Array intermediate. A direct
17
- * `new Float32Array(buf.buffer, byteOffset, dim)` would share Node's internal
18
- * Buffer pool memory and silently corrupt under GC. Tests assert byte-identity
19
- * after a full round-trip + a forced allocation.
20
- */
21
- export interface EmbeddingInput {
22
- chunk_id: number;
23
- vector: Float32Array;
24
- model_name: string;
25
- embedded_at: string;
26
- }
27
- export interface EmbeddingsBundle {
28
- bin: Buffer;
29
- idx: Buffer;
30
- dim: number;
31
- count: number;
32
- }
33
- /** Serialize embeddings to a packed bin + idx JSONL. */
34
- export declare function serializeEmbeddings(rows: EmbeddingInput[]): EmbeddingsBundle;
35
- /** Parse embeddings.bin back into a map keyed by chunk_id. */
36
- export declare function parseEmbeddings(bin: Buffer, idx: Buffer): Map<number, EmbeddingInput>;