nox-mem 3.1.1 → 3.2.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 (397) 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/db.js +61 -2
  17. package/dist/embed.js +23 -2
  18. package/dist/index.js +1 -22
  19. package/dist/knowledge-graph.js +20 -0
  20. package/dist/lib/answer/__tests__/e2e-gemini.test.js +229 -0
  21. package/dist/lib/answer/__tests__/integration-sqlite.test.js +388 -0
  22. package/dist/lib/answer/__tests__/integration.test.js +347 -0
  23. package/dist/lib/answer/__tests__/prompt.test.js +117 -0
  24. package/dist/lib/answer/__tests__/t5-t10.test.js +501 -0
  25. package/dist/lib/answer/provider.js +29 -4
  26. package/dist/lib/api/__tests__/safe-error-message.test.js +155 -0
  27. package/dist/lib/auth/__tests__/localhost-guard.test.js +144 -0
  28. package/dist/lib/error-sanitizer/__tests__/sanitize.test.js +354 -0
  29. package/dist/lib/events/__tests__/bus.test.js +208 -0
  30. package/dist/lib/ingest-router.js +0 -43
  31. package/dist/lib/op-audit-extension/__tests__/ran-at-guard.test.js +109 -0
  32. package/dist/lib/regex-extract/__tests__/extractor.test.js +197 -0
  33. package/dist/lib/regex-extract/__tests__/frontmatter.test.js +75 -0
  34. package/dist/lib/regex-extract/__tests__/ingest-router-l4.test.js +139 -0
  35. package/dist/lib/regex-extract/__tests__/production-wire.test.js +177 -0
  36. package/dist/lib/regex-extract/__tests__/reconcile.test.js +170 -0
  37. package/dist/lib/regex-extract/__tests__/strip-code.test.js +36 -0
  38. package/dist/privacy/__tests__/filter.test.js +352 -0
  39. package/dist/providers/__tests__/conformance-extended.test.js +249 -0
  40. package/dist/providers/__tests__/conformance.test.js +98 -0
  41. package/dist/providers/__tests__/cost-cap.test.js +151 -0
  42. package/dist/providers/__tests__/e2e-real.test.js +79 -0
  43. package/dist/providers/__tests__/factory.test.js +80 -0
  44. package/dist/providers/__tests__/fallback.test.js +223 -0
  45. package/dist/providers/__tests__/gemini.test.js +191 -0
  46. package/dist/providers/__tests__/health.test.js +128 -0
  47. package/dist/providers/__tests__/telemetry.test.js +219 -0
  48. package/dist/reindex.js +2 -2
  49. package/package.json +3 -4
  50. package/dist/api/answer.d.ts +0 -116
  51. package/dist/api/answer.validate-patch.d.ts +0 -72
  52. package/dist/api/brief-diversity.d.ts +0 -64
  53. package/dist/api/brief.d.ts +0 -114
  54. package/dist/api/conflict.d.ts +0 -33
  55. package/dist/api/conflict.js +0 -143
  56. package/dist/api/cors.d.ts +0 -73
  57. package/dist/api/events-stream-limited.d.ts +0 -133
  58. package/dist/api/events-stream-limited.js +0 -217
  59. package/dist/api/events-stream.d.ts +0 -53
  60. package/dist/api/events-stream.js +0 -125
  61. package/dist/api/export.d.ts +0 -42
  62. package/dist/api/export.js +0 -85
  63. package/dist/api/health-confidence-adapter.d.ts +0 -29
  64. package/dist/api/health-confidence-adapter.js +0 -73
  65. package/dist/api/health-confidence.d.ts +0 -36
  66. package/dist/api/health-confidence.js +0 -141
  67. package/dist/api/hooks.d.ts +0 -50
  68. package/dist/api/hooks.js +0 -115
  69. package/dist/api/import.d.ts +0 -38
  70. package/dist/api/import.js +0 -87
  71. package/dist/api/ingest-event.d.ts +0 -65
  72. package/dist/api/mark.d.ts +0 -42
  73. package/dist/api/mark.js +0 -127
  74. package/dist/api/server-deps-a2.d.ts +0 -55
  75. package/dist/api/server-deps-a2.js +0 -138
  76. package/dist/api/server-deps-l2-l3.d.ts +0 -68
  77. package/dist/api/server-deps-l2-l3.js +0 -123
  78. package/dist/api/server-deps-p1.d.ts +0 -84
  79. package/dist/api/server-deps-p2.d.ts +0 -32
  80. package/dist/api/server-deps-p2.js +0 -84
  81. package/dist/api/server-deps-p5.d.ts +0 -66
  82. package/dist/api/server-deps-p5.js +0 -139
  83. package/dist/api/viewer-static.d.ts +0 -30
  84. package/dist/api/viewer-static.js +0 -102
  85. package/dist/api/wire-up.d.ts +0 -54
  86. package/dist/api-impact.d.ts +0 -30
  87. package/dist/api-server.d.ts +0 -2
  88. package/dist/backfill-fts-anchor.d.ts +0 -15
  89. package/dist/backfill-source-type.d.ts +0 -20
  90. package/dist/churn.d.ts +0 -31
  91. package/dist/cli/answer.d.ts +0 -66
  92. package/dist/cli/conflict.d.ts +0 -38
  93. package/dist/cli/conflict.js +0 -282
  94. package/dist/cli/export.d.ts +0 -51
  95. package/dist/cli/export.js +0 -280
  96. package/dist/cli/hooks.d.ts +0 -54
  97. package/dist/cli/hooks.js +0 -133
  98. package/dist/cli/import.d.ts +0 -52
  99. package/dist/cli/import.js +0 -274
  100. package/dist/cli/mark.d.ts +0 -33
  101. package/dist/cli/mark.js +0 -130
  102. package/dist/cli/ocr-batch.d.ts +0 -12
  103. package/dist/cli/ocr-batch.js +0 -411
  104. package/dist/cli/snapshot-main.d.ts +0 -30
  105. package/dist/cli/snapshot-main.js +0 -47
  106. package/dist/cli/viewer.d.ts +0 -35
  107. package/dist/cli/viewer.js +0 -71
  108. package/dist/cli-telemetry.d.ts +0 -36
  109. package/dist/cli-telemetry.js +0 -150
  110. package/dist/compact.d.ts +0 -7
  111. package/dist/consolidate.d.ts +0 -18
  112. package/dist/consolidation.d.ts +0 -32
  113. package/dist/cross-agent-v2.d.ts +0 -45
  114. package/dist/cross-search.d.ts +0 -11
  115. package/dist/crystallize.d.ts +0 -43
  116. package/dist/db.d.ts +0 -11
  117. package/dist/dedup.d.ts +0 -1
  118. package/dist/detect-changes.d.ts +0 -29
  119. package/dist/digest.d.ts +0 -1
  120. package/dist/doctor.d.ts +0 -1
  121. package/dist/embed.d.ts +0 -57
  122. package/dist/evals.d.ts +0 -176
  123. package/dist/evals.js +0 -351
  124. package/dist/generate-user-profile.d.ts +0 -18
  125. package/dist/graphify-ingest.d.ts +0 -18
  126. package/dist/impact.d.ts +0 -39
  127. package/dist/index.d.ts +0 -2
  128. package/dist/ingest-entity.d.ts +0 -44
  129. package/dist/ingest.d.ts +0 -13
  130. package/dist/kg-llm.d.ts +0 -39
  131. package/dist/knowledge-graph.d.ts +0 -72
  132. package/dist/lib/answer/config.d.ts +0 -41
  133. package/dist/lib/answer/index.d.ts +0 -47
  134. package/dist/lib/answer/prompt.d.ts +0 -37
  135. package/dist/lib/answer/provider.d.ts +0 -47
  136. package/dist/lib/answer/retrieval.d.ts +0 -36
  137. package/dist/lib/answer/telemetry.d.ts +0 -99
  138. package/dist/lib/answer/types.d.ts +0 -108
  139. package/dist/lib/api/error-leak-fix.d.ts +0 -54
  140. package/dist/lib/api/safe-error-message.d.ts +0 -70
  141. package/dist/lib/archive/common-passwords.d.ts +0 -37
  142. package/dist/lib/archive/common-passwords.js +0 -753
  143. package/dist/lib/archive/encryption.d.ts +0 -81
  144. package/dist/lib/archive/encryption.js +0 -236
  145. package/dist/lib/archive/enforce-strength.d.ts +0 -54
  146. package/dist/lib/archive/enforce-strength.js +0 -70
  147. package/dist/lib/archive/entropy.d.ts +0 -34
  148. package/dist/lib/archive/entropy.js +0 -180
  149. package/dist/lib/archive/export-locking.d.ts +0 -102
  150. package/dist/lib/archive/export-locking.js +0 -202
  151. package/dist/lib/archive/format.d.ts +0 -20
  152. package/dist/lib/archive/format.js +0 -174
  153. package/dist/lib/archive/index.d.ts +0 -23
  154. package/dist/lib/archive/index.js +0 -17
  155. package/dist/lib/archive/manifest.d.ts +0 -53
  156. package/dist/lib/archive/manifest.js +0 -183
  157. package/dist/lib/archive/migration.d.ts +0 -36
  158. package/dist/lib/archive/migration.js +0 -100
  159. package/dist/lib/archive/migrations/v18_to_v19.d.ts +0 -16
  160. package/dist/lib/archive/migrations/v18_to_v19.js +0 -18
  161. package/dist/lib/archive/orchestrator.d.ts +0 -166
  162. package/dist/lib/archive/orchestrator.js +0 -428
  163. package/dist/lib/archive/serializers/chunks.d.ts +0 -30
  164. package/dist/lib/archive/serializers/chunks.js +0 -113
  165. package/dist/lib/archive/serializers/embeddings.d.ts +0 -36
  166. package/dist/lib/archive/serializers/embeddings.js +0 -115
  167. package/dist/lib/archive/serializers/kg.d.ts +0 -28
  168. package/dist/lib/archive/serializers/kg.js +0 -184
  169. package/dist/lib/archive/serializers/ops_audit.d.ts +0 -21
  170. package/dist/lib/archive/serializers/ops_audit.js +0 -97
  171. package/dist/lib/archive/server-deps.d.ts +0 -131
  172. package/dist/lib/archive/server-deps.js +0 -232
  173. package/dist/lib/archive/strength.d.ts +0 -50
  174. package/dist/lib/archive/strength.js +0 -77
  175. package/dist/lib/archive/types.d.ts +0 -159
  176. package/dist/lib/archive/types.js +0 -45
  177. package/dist/lib/archive/unpack-streaming.d.ts +0 -70
  178. package/dist/lib/archive/unpack-streaming.js +0 -255
  179. package/dist/lib/auth/localhost-guard.d.ts +0 -106
  180. package/dist/lib/confidence/config.d.ts +0 -37
  181. package/dist/lib/confidence/config.js +0 -107
  182. package/dist/lib/confidence/db-shim-singleton.d.ts +0 -20
  183. package/dist/lib/confidence/db-shim-singleton.js +0 -41
  184. package/dist/lib/confidence/db-shim.d.ts +0 -47
  185. package/dist/lib/confidence/db-shim.js +0 -141
  186. package/dist/lib/confidence/mark.d.ts +0 -58
  187. package/dist/lib/confidence/mark.js +0 -168
  188. package/dist/lib/confidence/ranking.d.ts +0 -69
  189. package/dist/lib/confidence/ranking.js +0 -101
  190. package/dist/lib/confidence/search-filter.d.ts +0 -44
  191. package/dist/lib/confidence/search-filter.js +0 -103
  192. package/dist/lib/confidence/types.d.ts +0 -146
  193. package/dist/lib/confidence/types.js +0 -20
  194. package/dist/lib/confidence/write-hooks.d.ts +0 -50
  195. package/dist/lib/confidence/write-hooks.js +0 -159
  196. package/dist/lib/conflict/audit-fk-check.d.ts +0 -72
  197. package/dist/lib/conflict/audit-fk-check.js +0 -131
  198. package/dist/lib/conflict/audit-writer.d.ts +0 -39
  199. package/dist/lib/conflict/audit-writer.js +0 -133
  200. package/dist/lib/conflict/db-singleton.d.ts +0 -28
  201. package/dist/lib/conflict/db-singleton.js +0 -61
  202. package/dist/lib/conflict/db.d.ts +0 -27
  203. package/dist/lib/conflict/db.js +0 -20
  204. package/dist/lib/conflict/detector-direct.d.ts +0 -21
  205. package/dist/lib/conflict/detector-direct.js +0 -105
  206. package/dist/lib/conflict/evidence.d.ts +0 -24
  207. package/dist/lib/conflict/evidence.js +0 -76
  208. package/dist/lib/conflict/index.d.ts +0 -14
  209. package/dist/lib/conflict/index.js +0 -12
  210. package/dist/lib/conflict/scheduler.d.ts +0 -78
  211. package/dist/lib/conflict/scheduler.js +0 -111
  212. package/dist/lib/conflict/shadow.d.ts +0 -75
  213. package/dist/lib/conflict/shadow.js +0 -161
  214. package/dist/lib/conflict/types.d.ts +0 -133
  215. package/dist/lib/conflict/types.js +0 -19
  216. package/dist/lib/cost-cap.d.ts +0 -94
  217. package/dist/lib/deps/deps-registry.d.ts +0 -111
  218. package/dist/lib/error-sanitizer/middleware.d.ts +0 -43
  219. package/dist/lib/error-sanitizer/sanitize.d.ts +0 -78
  220. package/dist/lib/eval-batch.d.ts +0 -34
  221. package/dist/lib/eval-batch.js +0 -103
  222. package/dist/lib/eval-metrics.d.ts +0 -36
  223. package/dist/lib/eval-metrics.js +0 -95
  224. package/dist/lib/eval.d.ts +0 -106
  225. package/dist/lib/eval.js +0 -343
  226. package/dist/lib/events/bus.d.ts +0 -135
  227. package/dist/lib/fts-anchor.d.ts +0 -1
  228. package/dist/lib/hooks/classifier.d.ts +0 -47
  229. package/dist/lib/hooks/classifier.js +0 -129
  230. package/dist/lib/hooks/config.d.ts +0 -49
  231. package/dist/lib/hooks/config.js +0 -106
  232. package/dist/lib/hooks/decorators.d.ts +0 -35
  233. package/dist/lib/hooks/decorators.js +0 -59
  234. package/dist/lib/hooks/pipeline.d.ts +0 -76
  235. package/dist/lib/hooks/pipeline.js +0 -213
  236. package/dist/lib/hooks/privacy-filter-adapter.d.ts +0 -55
  237. package/dist/lib/hooks/privacy-filter-adapter.js +0 -84
  238. package/dist/lib/hooks/rate-limit-constant-time.d.ts +0 -57
  239. package/dist/lib/hooks/rate-limit-constant-time.js +0 -69
  240. package/dist/lib/hooks/rate-limit-dryrun-fix.d.ts +0 -71
  241. package/dist/lib/hooks/rate-limit-dryrun-fix.js +0 -110
  242. package/dist/lib/hooks/rate-limit.d.ts +0 -54
  243. package/dist/lib/hooks/rate-limit.js +0 -122
  244. package/dist/lib/hooks/server-deps.d.ts +0 -61
  245. package/dist/lib/hooks/server-deps.js +0 -92
  246. package/dist/lib/hooks/source-allowlist.d.ts +0 -26
  247. package/dist/lib/hooks/source-allowlist.js +0 -53
  248. package/dist/lib/hooks/types.d.ts +0 -129
  249. package/dist/lib/hooks/types.js +0 -24
  250. package/dist/lib/hooks/worker.d.ts +0 -56
  251. package/dist/lib/hooks/worker.js +0 -150
  252. package/dist/lib/ingest-router.d.ts +0 -25
  253. package/dist/lib/ocr-detector.d.ts +0 -61
  254. package/dist/lib/ocr-detector.js +0 -138
  255. package/dist/lib/ocr-engine-stub.d.ts +0 -48
  256. package/dist/lib/ocr-engine-stub.js +0 -190
  257. package/dist/lib/ocr-engines/google-doc-ai.d.ts +0 -36
  258. package/dist/lib/ocr-engines/google-doc-ai.js +0 -164
  259. package/dist/lib/ocr-jobs.d.ts +0 -67
  260. package/dist/lib/ocr-jobs.js +0 -129
  261. package/dist/lib/op-audit-extension/ran-at-guard.d.ts +0 -86
  262. package/dist/lib/op-audit.d.ts +0 -71
  263. package/dist/lib/privacy-br/detector.d.ts +0 -42
  264. package/dist/lib/privacy-br/detector.js +0 -130
  265. package/dist/lib/privacy-br/index.d.ts +0 -20
  266. package/dist/lib/privacy-br/index.js +0 -20
  267. package/dist/lib/privacy-br/integration.d.ts +0 -71
  268. package/dist/lib/privacy-br/integration.js +0 -74
  269. package/dist/lib/privacy-br/patterns.d.ts +0 -117
  270. package/dist/lib/privacy-br/patterns.js +0 -434
  271. package/dist/lib/privacy-br/redact.d.ts +0 -42
  272. package/dist/lib/privacy-br/redact.js +0 -103
  273. package/dist/lib/privacy-br/types.d.ts +0 -55
  274. package/dist/lib/privacy-br/types.js +0 -25
  275. package/dist/lib/regex-extract/extractor.d.ts +0 -30
  276. package/dist/lib/regex-extract/frontmatter.d.ts +0 -44
  277. package/dist/lib/regex-extract/index.d.ts +0 -14
  278. package/dist/lib/regex-extract/ingest-router-l4.d.ts +0 -76
  279. package/dist/lib/regex-extract/patterns.d.ts +0 -61
  280. package/dist/lib/regex-extract/production-wire.d.ts +0 -128
  281. package/dist/lib/regex-extract/reconcile.d.ts +0 -162
  282. package/dist/lib/regex-extract/strip-code.d.ts +0 -24
  283. package/dist/lib/regex-extract/types.d.ts +0 -48
  284. package/dist/lib/reranker.d.ts +0 -80
  285. package/dist/lib/shadow-tracker.d.ts +0 -191
  286. package/dist/lib/shadow-tracker.js +0 -384
  287. package/dist/lib/spo-injection.d.ts +0 -52
  288. package/dist/lib/telemetry-collector.d.ts +0 -158
  289. package/dist/lib/telemetry-collector.js +0 -249
  290. package/dist/lib/temporal-detector.d.ts +0 -27
  291. package/dist/lib/viewer/auth.d.ts +0 -37
  292. package/dist/lib/viewer/auth.js +0 -70
  293. package/dist/lib/viewer/backpressure.d.ts +0 -59
  294. package/dist/lib/viewer/backpressure.js +0 -100
  295. package/dist/lib/viewer/broadcast-singleton.d.ts +0 -34
  296. package/dist/lib/viewer/broadcast-singleton.js +0 -49
  297. package/dist/lib/viewer/broadcast.d.ts +0 -66
  298. package/dist/lib/viewer/broadcast.js +0 -96
  299. package/dist/lib/viewer/event-types.d.ts +0 -132
  300. package/dist/lib/viewer/event-types.js +0 -74
  301. package/dist/lib/viewer/instrumentation.d.ts +0 -106
  302. package/dist/lib/viewer/instrumentation.js +0 -224
  303. package/dist/lib/viewer/migration.d.ts +0 -23
  304. package/dist/lib/viewer/migration.js +0 -56
  305. package/dist/lib/viewer/redaction.d.ts +0 -44
  306. package/dist/lib/viewer/redaction.js +0 -139
  307. package/dist/lib/viewer/session.d.ts +0 -51
  308. package/dist/lib/viewer/session.js +0 -87
  309. package/dist/mcp/tools/answer.d.ts +0 -94
  310. package/dist/mcp/tools/archive.d.ts +0 -152
  311. package/dist/mcp/tools/archive.js +0 -170
  312. package/dist/mcp/tools/conflict.d.ts +0 -44
  313. package/dist/mcp/tools/conflict.js +0 -130
  314. package/dist/mcp/tools/hooks.d.ts +0 -29
  315. package/dist/mcp/tools/hooks.js +0 -78
  316. package/dist/mcp/tools/mark.d.ts +0 -38
  317. package/dist/mcp/tools/mark.js +0 -82
  318. package/dist/mcp/tools/viewer.d.ts +0 -58
  319. package/dist/mcp/tools/viewer.js +0 -64
  320. package/dist/mcp-server.d.ts +0 -2
  321. package/dist/metrics.d.ts +0 -3
  322. package/dist/noise-filter.d.ts +0 -18
  323. package/dist/notion-sync.d.ts +0 -7
  324. package/dist/notion-sync.js +0 -97
  325. package/dist/observability/adapters/a3-adapter.d.ts +0 -63
  326. package/dist/observability/adapters/a3-adapter.js +0 -83
  327. package/dist/observability/adapters/p1-adapter.d.ts +0 -49
  328. package/dist/observability/adapters/p1-adapter.js +0 -63
  329. package/dist/observability/adapters/p5-adapter.d.ts +0 -36
  330. package/dist/observability/adapters/p5-adapter.js +0 -71
  331. package/dist/observability/cardinality.d.ts +0 -61
  332. package/dist/observability/cardinality.js +0 -300
  333. package/dist/observability/collectors/db-stats.collector.d.ts +0 -9
  334. package/dist/observability/collectors/db-stats.collector.js +0 -88
  335. package/dist/observability/collectors/eventbus.collector.d.ts +0 -6
  336. package/dist/observability/collectors/eventbus.collector.js +0 -50
  337. package/dist/observability/collectors/process.collector.d.ts +0 -7
  338. package/dist/observability/collectors/process.collector.js +0 -93
  339. package/dist/observability/collectors/provider-telemetry.collector.d.ts +0 -11
  340. package/dist/observability/collectors/provider-telemetry.collector.js +0 -112
  341. package/dist/observability/collectors/search-telemetry.collector.d.ts +0 -12
  342. package/dist/observability/collectors/search-telemetry.collector.js +0 -76
  343. package/dist/observability/exporter.d.ts +0 -30
  344. package/dist/observability/exporter.js +0 -182
  345. package/dist/observability/index.d.ts +0 -22
  346. package/dist/observability/index.js +0 -21
  347. package/dist/observability/metrics.d.ts +0 -53
  348. package/dist/observability/metrics.js +0 -213
  349. package/dist/observability/privacy-guard.d.ts +0 -32
  350. package/dist/observability/privacy-guard.js +0 -116
  351. package/dist/observability/record.d.ts +0 -83
  352. package/dist/observability/record.js +0 -217
  353. package/dist/observability/registry.d.ts +0 -60
  354. package/dist/observability/registry.js +0 -93
  355. package/dist/observability/types.d.ts +0 -115
  356. package/dist/observability/types.js +0 -235
  357. package/dist/observability.d.ts +0 -131
  358. package/dist/plugins/nox-hooks/index.d.ts +0 -61
  359. package/dist/plugins/nox-hooks/index.js +0 -99
  360. package/dist/primer.d.ts +0 -1
  361. package/dist/privacy/filter.d.ts +0 -27
  362. package/dist/privacy/patterns.d.ts +0 -29
  363. package/dist/privacy/tag-parser.d.ts +0 -24
  364. package/dist/project-context-gen.d.ts +0 -10
  365. package/dist/providers/embedding/gemini.d.ts +0 -73
  366. package/dist/providers/embedding/openai.d.ts +0 -76
  367. package/dist/providers/embedding/types.d.ts +0 -39
  368. package/dist/providers/embedding/voyage.d.ts +0 -36
  369. package/dist/providers/index.d.ts +0 -116
  370. package/dist/providers/llm/anthropic.d.ts +0 -29
  371. package/dist/providers/llm/chain.d.ts +0 -99
  372. package/dist/providers/llm/gemini.d.ts +0 -48
  373. package/dist/providers/llm/openai.d.ts +0 -64
  374. package/dist/providers/llm/types.d.ts +0 -47
  375. package/dist/providers/telemetry.d.ts +0 -87
  376. package/dist/providers/types.d.ts +0 -42
  377. package/dist/query-entity-count.d.ts +0 -54
  378. package/dist/reflect.d.ts +0 -26
  379. package/dist/reindex-errors.d.ts +0 -7
  380. package/dist/reindex.d.ts +0 -16
  381. package/dist/retention.d.ts +0 -40
  382. package/dist/salience.d.ts +0 -85
  383. package/dist/scripts/migrate-v17-ops-audit.d.ts +0 -17
  384. package/dist/search-dedup.d.ts +0 -44
  385. package/dist/search-expansion.d.ts +0 -20
  386. package/dist/search.d.ts +0 -62
  387. package/dist/seh-detector.d.ts +0 -31
  388. package/dist/self-improve.d.ts +0 -1
  389. package/dist/session-distill.d.ts +0 -29
  390. package/dist/session-update.d.ts +0 -1
  391. package/dist/shared-memory.d.ts +0 -24
  392. package/dist/stats.d.ts +0 -1
  393. package/dist/temporal-retrieval.d.ts +0 -132
  394. package/dist/tier-manager.d.ts +0 -69
  395. package/dist/vectorize.d.ts +0 -16
  396. package/dist/version.d.ts +0 -1
  397. package/dist/watch.d.ts +0 -8
@@ -0,0 +1,352 @@
1
+ /**
2
+ * privacy/__tests__/filter.test.ts
3
+ *
4
+ * Test suite for the privacy redaction pipeline.
5
+ * Runner: node:test (node --test)
6
+ *
7
+ * All secret values here are SYNTHETIC / official test vectors.
8
+ * No real credentials are present.
9
+ *
10
+ * gitleaks:allow — test fixtures only; all values are synthetic or official test vectors.
11
+ */
12
+ import { describe, it } from "node:test";
13
+ import assert from "node:assert/strict";
14
+ import { redact } from "../filter.js";
15
+ import { stripPrivateTags } from "../tag-parser.js";
16
+ import { luhn } from "../patterns.js";
17
+ // ─── Helper ─────────────────────────────────────────────────────────────────
18
+ function assertRedacted(text, expectedKind, desc) {
19
+ const result = redact(text);
20
+ assert.ok(result.redactionCount > 0, `${desc ?? expectedKind}: expected redaction, got none. text="${text}"`);
21
+ assert.ok(result.kinds.includes(expectedKind), `${desc ?? expectedKind}: expected kind "${expectedKind}", got [${result.kinds.join(", ")}]`);
22
+ assert.ok(!result.text.includes(text.substring(0, 12)) || result.text.includes("[REDACTED"), `${desc ?? expectedKind}: raw secret still visible in output`);
23
+ }
24
+ function assertNotRedacted(text, desc) {
25
+ const result = redact(text);
26
+ assert.strictEqual(result.redactionCount, 0, `${desc ?? "negative case"}: expected no redaction, got ${result.redactionCount} for text="${text}"`);
27
+ }
28
+ // ─── Positive cases — one per pattern ────────────────────────────────────────
29
+ describe("AWS access key id", () => {
30
+ it("matches canonical AKIA format", () => {
31
+ assertRedacted("key_id=AKIAIOSFODNN7EXAMPLE", "aws-access-key-id");
32
+ });
33
+ it("matches embedded in sentence", () => {
34
+ assertRedacted("Access key: AKIAI44QH8DHBEXAMPLE was rotated.", "aws-access-key-id");
35
+ });
36
+ it("replaces with correct placeholder", () => {
37
+ const { text } = redact("AKIAIOSFODNN7EXAMPLE");
38
+ assert.ok(text.includes("[REDACTED:aws-access-key-id]"));
39
+ });
40
+ });
41
+ describe("AWS secret access key", () => {
42
+ it("matches env-var style assignment", () => {
43
+ assertRedacted("aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "aws-secret-key");
44
+ });
45
+ it("matches uppercase env name", () => {
46
+ assertRedacted("AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "aws-secret-key");
47
+ });
48
+ });
49
+ describe("Anthropic API key", () => {
50
+ it("matches sk-ant prefix", () => {
51
+ assertRedacted("sk-ant-test-EXAMPLEKEY1234567890abcdefghij", "anthropic-key");
52
+ });
53
+ it("matches api03 variant", () => {
54
+ assertRedacted("sk-ant-api03-EXAMPLEKEY1234567890abcdefghijklmnopqr", "anthropic-key");
55
+ });
56
+ it("matches in config line", () => {
57
+ assertRedacted('ANTHROPIC_API_KEY="sk-ant-test-EXAMPLEKEY1234567890abcdefghij"', "env-secret");
58
+ });
59
+ });
60
+ describe("OpenAI API key", () => {
61
+ it("matches sk- prefix", () => {
62
+ assertRedacted("sk-EXAMPLEKEY1234567890abcdefghij", "openai-key");
63
+ });
64
+ it("matches sk-proj variant", () => {
65
+ assertRedacted("sk-proj-EXAMPLEKEY1234567890abcde", "openai-key");
66
+ });
67
+ it("does NOT match sk-ant- as OpenAI key", () => {
68
+ const { kinds } = redact("sk-ant-test-EXAMPLEKEY1234567890abcdefghij");
69
+ assert.ok(!kinds.includes("openai-key"), "sk-ant- should not fire openai-key pattern");
70
+ });
71
+ });
72
+ describe("Gemini API key", () => {
73
+ it("matches AIza prefix with 35 trailing chars", () => {
74
+ assertRedacted("AIzaSyEXAMPLEKEY1234567890abcdefghij123", "gemini-key"); // gitleaks:allow
75
+ });
76
+ it("matches inline in code comment", () => {
77
+ assertRedacted("// key = AIzaSyEXAMPLEKEY1234567890abcdefghij123 (test)", // gitleaks:allow
78
+ "gemini-key");
79
+ });
80
+ });
81
+ describe("GitHub tokens", () => {
82
+ it("matches ghp_ prefix", () => {
83
+ assertRedacted("ghp_EXAMPLETOKEN1234567890abcdefghij", "github-token");
84
+ });
85
+ it("matches gho_ prefix", () => {
86
+ assertRedacted("gho_EXAMPLETOKEN1234567890abcdefghij", "github-token");
87
+ });
88
+ it("matches ghs_ prefix", () => {
89
+ assertRedacted("ghs_EXAMPLETOKEN1234567890abcdefghij", "github-token");
90
+ });
91
+ it("matches ghu_ prefix", () => {
92
+ assertRedacted("ghu_EXAMPLETOKEN1234567890abcdefghij", "github-token");
93
+ });
94
+ it("matches github_pat_ prefix", () => {
95
+ assertRedacted("github_pat_EXAMPLETOKEN1234567890abcdef", "github-token");
96
+ });
97
+ });
98
+ describe("Slack tokens", () => {
99
+ it("matches xoxb- (bot token)", () => {
100
+ assertRedacted("xoxb-EXAMPLE-TOKEN-1234567890", "slack-token");
101
+ });
102
+ it("matches xoxp- (user token)", () => {
103
+ assertRedacted("xoxp-EXAMPLE-TOKEN-1234567890abcdef", "slack-token");
104
+ });
105
+ it("matches xoxa- prefix", () => {
106
+ assertRedacted("xoxa-EXAMPLE-TOKEN-1234567890", "slack-token");
107
+ });
108
+ });
109
+ describe("Discord bot token", () => {
110
+ it("matches M + 23 chars . 6 chars . 27 chars format", () => {
111
+ // Exact structure: M + 23 word chars (24 total) . 6 chars . 27 chars
112
+ // Synthetic safe token (all repeat chars — not a real bot token)
113
+ assertRedacted("Mkkkkkkkkkkkkkkkkkkkkkkk.AAAAAA.BBBBBBBBBBBBBBBBBBBBBBBBBBB", "discord-token");
114
+ });
115
+ });
116
+ describe("JWT", () => {
117
+ it("matches standard three-part eyJ... token", () => {
118
+ const jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" +
119
+ ".eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ" +
120
+ ".SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
121
+ assertRedacted(jwt, "jwt");
122
+ });
123
+ it("replaces JWT in Authorization header (both kinds fire)", () => {
124
+ const jwt = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyMTIzIn0.SIGNATURE_EXAMPLE_123456"; // gitleaks:allow
125
+ const text = `Authorization: Bearer ${jwt}`;
126
+ const { redactionCount } = redact(text);
127
+ assert.ok(redactionCount > 0, "auth header or JWT must fire");
128
+ });
129
+ });
130
+ describe("PEM private key", () => {
131
+ it("matches RSA private key block", () => {
132
+ const pem = [
133
+ "-----BEGIN RSA PRIVATE KEY-----",
134
+ "MIIEpAIBAAKCAQEAEXAMPLEKEY1234567890abcdefghijklmnopqrstuvwxyz==",
135
+ "-----END RSA PRIVATE KEY-----",
136
+ ].join("\n");
137
+ assertRedacted(pem, "pem-private-key");
138
+ });
139
+ it("matches generic PRIVATE KEY block", () => {
140
+ const pem = [
141
+ "-----BEGIN PRIVATE KEY-----", // gitleaks:allow
142
+ "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcEXAMPLE==",
143
+ "-----END PRIVATE KEY-----",
144
+ ].join("\n");
145
+ assertRedacted(pem, "pem-private-key");
146
+ });
147
+ it("matches EC PRIVATE KEY block", () => {
148
+ const pem = "-----BEGIN EC PRIVATE KEY-----\nMHQCAQEEIEXAMPLE==\n-----END EC PRIVATE KEY-----";
149
+ assertRedacted(pem, "pem-private-key");
150
+ });
151
+ });
152
+ describe("Bearer/Basic auth header", () => {
153
+ it("matches Bearer token", () => {
154
+ assertRedacted("Authorization: Bearer mysecrettoken1234567890ab", "auth-header");
155
+ });
156
+ it("matches Basic base64", () => {
157
+ assertRedacted("Authorization: Basic dXNlcjpFWEFNUExFUEFTU1dPUkQ=", "auth-header");
158
+ });
159
+ it("matches Token form", () => {
160
+ assertRedacted("Authorization: Token EXAMPLETOKEN1234567890abcdef", "auth-header");
161
+ });
162
+ it("is case-insensitive for authorization keyword", () => {
163
+ assertRedacted("authorization: Bearer mysecrettoken1234567890ab", "auth-header");
164
+ });
165
+ });
166
+ describe(".env-style secrets", () => {
167
+ it("matches PASSWORD=", () => {
168
+ assertRedacted("PASSWORD=s3cr3tP@ssw0rd!", "env-secret");
169
+ });
170
+ it("matches SECRET=", () => {
171
+ assertRedacted("MY_SECRET=supersecretvalue123", "env-secret");
172
+ });
173
+ it("matches TOKEN=", () => {
174
+ assertRedacted("GITHUB_TOKEN=ghp_EXAMPLETOKEN1234567890abcdefghij", "env-secret");
175
+ });
176
+ it("matches API_KEY=", () => {
177
+ assertRedacted("GEMINI_API_KEY=AIzaSyEXAMPLEKEY1234567890abcdefghij123", "env-secret"); // gitleaks:allow
178
+ });
179
+ it("matches with export prefix", () => {
180
+ assertRedacted("export SECRET=mysecretvalue123", "env-secret");
181
+ });
182
+ it("matches quoted value", () => {
183
+ assertRedacted('DB_PASSWORD="my-secret-db-pass"', "env-secret");
184
+ });
185
+ });
186
+ describe("Credit card (Luhn-validated)", () => {
187
+ it("matches Visa test number (Luhn-valid)", () => {
188
+ assertRedacted("4532015112830366", "credit-card");
189
+ });
190
+ it("matches formatted CC with spaces", () => {
191
+ assertRedacted("4532 0151 1283 0366", "credit-card");
192
+ });
193
+ it("matches Mastercard test number", () => {
194
+ assertRedacted("5425233430109903", "credit-card");
195
+ });
196
+ it("does NOT redact Luhn-invalid 16-digit strings (e.g., hashes)", () => {
197
+ // This is a random 16-digit string that fails Luhn
198
+ const notACard = "1234567890123456"; // fails Luhn
199
+ const { kinds } = redact(notACard);
200
+ assert.ok(!kinds.includes("credit-card"), "Luhn-invalid string should not be redacted as CC");
201
+ });
202
+ });
203
+ // ─── <private> tag handling ───────────────────────────────────────────────────
204
+ describe("<private> tag stripping", () => {
205
+ it("strips basic private tag", () => {
206
+ const result = redact("before <private>secret content here</private> after");
207
+ assert.ok(result.text.includes("[REDACTED:user-marked]"), "user-marked replacement missing");
208
+ assert.ok(!result.text.includes("secret content here"), "tag content still visible");
209
+ assert.ok(result.kinds.includes("user-marked"));
210
+ assert.strictEqual(result.redactionCount, 1);
211
+ });
212
+ it("strips multiline private tag", () => {
213
+ const text = "Header\n<private>\nline1\nline2\nline3\n</private>\nFooter";
214
+ const { text: out, redactionCount } = redact(text);
215
+ assert.strictEqual(redactionCount, 1);
216
+ assert.ok(out.includes("[REDACTED:user-marked]"));
217
+ assert.ok(!out.includes("line1"));
218
+ });
219
+ it("strips multiple private tags", () => {
220
+ const text = "a<private>x</private>b<private>y</private>c";
221
+ const { redactionCount, kinds } = redact(text);
222
+ assert.strictEqual(redactionCount, 2);
223
+ assert.ok(kinds.includes("user-marked"));
224
+ });
225
+ it("strips regex secrets inside private tags (tag wins, runs first)", () => {
226
+ const secret = "AKIAIOSFODNN7EXAMPLE";
227
+ const text = `<private>${secret}</private>`;
228
+ const { text: out, kinds } = redact(text);
229
+ // Should be user-marked, not aws-access-key-id (tag stripped it first)
230
+ assert.ok(out.includes("[REDACTED:user-marked]"));
231
+ assert.ok(!out.includes(secret));
232
+ assert.ok(kinds.includes("user-marked"));
233
+ });
234
+ it("handles private tags with surrounding regex secrets", () => {
235
+ const text = `key=sk-EXAMPLEKEY1234567890abcdefghij <private>my personal note</private>`;
236
+ const { redactionCount, kinds } = redact(text);
237
+ assert.ok(redactionCount >= 2, "both OpenAI key and user-marked should fire");
238
+ assert.ok(kinds.includes("user-marked"));
239
+ assert.ok(kinds.includes("openai-key"));
240
+ });
241
+ it("case-insensitive tag matching", () => {
242
+ const { redactionCount } = redact("<PRIVATE>secret</PRIVATE>");
243
+ assert.strictEqual(redactionCount, 1);
244
+ });
245
+ });
246
+ // ─── Negative cases — should NOT be redacted ─────────────────────────────────
247
+ describe("Negative cases (no false positives)", () => {
248
+ it("UUID is not flagged as credit card", () => {
249
+ // UUID has 32 hex chars, not 16 decimal digits
250
+ assertNotRedacted("550e8400-e29b-41d4-a716-446655440000", "UUID");
251
+ });
252
+ it("SHA256 hash is not flagged", () => {
253
+ assertNotRedacted("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "SHA256 hash");
254
+ });
255
+ it("innocent base64 of JSON is not flagged", () => {
256
+ // base64 of {"hello":"world"} — looks like base64 but is not a secret
257
+ const b64 = Buffer.from('{"hello":"world","count":42}').toString("base64");
258
+ assertNotRedacted(b64, "innocent base64 JSON");
259
+ });
260
+ it("code variable named 'mySecret' is not flagged (no = assignment)", () => {
261
+ assertNotRedacted("const mySecret = computeHash(data);", "code variable");
262
+ });
263
+ it("short token-looking string under threshold is not flagged", () => {
264
+ // sk- with only 5 chars after — too short for OpenAI pattern (requires 20+)
265
+ assertNotRedacted("sk-abc12", "short sk- string");
266
+ });
267
+ it("code identifier 'AKTION_KEY' is not flagged as AWS key (wrong prefix)", () => {
268
+ assertNotRedacted("AKTION_KEY=production", "AKTION_KEY env var");
269
+ });
270
+ it("UUID-like 32 hex string without separators is not flagged as CC", () => {
271
+ // 32 chars hex, not 16 decimal digits
272
+ assertNotRedacted("a3f5c8d2e1b4a9f6c3d7e2b5a8f1c4d7", "32-char hex without separators");
273
+ });
274
+ it("ordinary sentence with word 'secret' in prose is not flagged", () => {
275
+ assertNotRedacted("The secret to great coffee is the grind size.", "prose with 'secret' word");
276
+ });
277
+ it("Luhn-invalid 16-digit number (random phone-like) is not redacted", () => {
278
+ // 5500000000000001 — fails Luhn (chosen to be plausible but invalid)
279
+ const { kinds } = redact("5500000000000001");
280
+ assert.ok(!kinds.includes("credit-card"), "Luhn-invalid not redacted as CC");
281
+ });
282
+ });
283
+ // ─── Telemetry shape ──────────────────────────────────────────────────────────
284
+ describe("Telemetry shape", () => {
285
+ it("returns correct redactionCount for single pattern", () => {
286
+ const { redactionCount, kinds } = redact("AKIAIOSFODNN7EXAMPLE");
287
+ assert.strictEqual(redactionCount, 1);
288
+ assert.deepStrictEqual(kinds, ["aws-access-key-id"]);
289
+ });
290
+ it("returns deduplicated kinds for repeated pattern", () => {
291
+ const text = "AKIAIOSFODNN7EXAMPLE and AKIAI44QH8DHBEXAMPLE";
292
+ const { redactionCount, kinds } = redact(text);
293
+ assert.strictEqual(redactionCount, 2);
294
+ // kinds should be deduplicated (only one entry for aws-access-key-id)
295
+ assert.strictEqual(kinds.filter(k => k === "aws-access-key-id").length, 1);
296
+ });
297
+ it("accumulates multiple kinds", () => {
298
+ const text = [
299
+ "AKIAIOSFODNN7EXAMPLE",
300
+ "ghp_EXAMPLETOKEN1234567890abcdefghij",
301
+ "<private>hidden</private>",
302
+ ].join(" ");
303
+ const { redactionCount, kinds } = redact(text);
304
+ assert.ok(redactionCount >= 3, `expected ≥3 redactions, got ${redactionCount}`);
305
+ assert.ok(kinds.includes("aws-access-key-id"));
306
+ assert.ok(kinds.includes("github-token"));
307
+ assert.ok(kinds.includes("user-marked"));
308
+ });
309
+ it("returns empty kinds and zero count for clean text", () => {
310
+ const { redactionCount, kinds, text } = redact("This is a normal chunk of text.");
311
+ assert.strictEqual(redactionCount, 0);
312
+ assert.deepStrictEqual(kinds, []);
313
+ assert.strictEqual(text, "This is a normal chunk of text.");
314
+ });
315
+ it("text field is returned unchanged when nothing redacted", () => {
316
+ const input = "Hello world — no secrets here.";
317
+ const { text } = redact(input);
318
+ assert.strictEqual(text, input);
319
+ });
320
+ });
321
+ // ─── Luhn standalone tests ────────────────────────────────────────────────────
322
+ describe("Luhn algorithm", () => {
323
+ it("validates Visa test number", () => {
324
+ assert.ok(luhn("4532015112830366"));
325
+ });
326
+ it("validates Mastercard test number", () => {
327
+ assert.ok(luhn("5425233430109903"));
328
+ });
329
+ it("rejects invalid CC (digit sum not divisible by 10)", () => {
330
+ // 1111111111111111 — fails Luhn (sum = 8+1+8+1+8+1+8+1+8+1+8+1+8+1+8+1 = not %10)
331
+ assert.ok(!luhn("1111111111111111"));
332
+ });
333
+ it("rejects sequential digits", () => {
334
+ assert.ok(!luhn("1234567890123456"));
335
+ });
336
+ });
337
+ // ─── tag-parser standalone tests ──────────────────────────────────────────────
338
+ describe("stripPrivateTags standalone", () => {
339
+ it("returns tagCount=0 for text without tags", () => {
340
+ const { tagCount, text } = stripPrivateTags("no tags here");
341
+ assert.strictEqual(tagCount, 0);
342
+ assert.strictEqual(text, "no tags here");
343
+ });
344
+ it("handles adjacent tags", () => {
345
+ const { tagCount } = stripPrivateTags("<private>a</private><private>b</private>");
346
+ assert.strictEqual(tagCount, 2);
347
+ });
348
+ it("handles whitespace inside tags", () => {
349
+ const { text } = stripPrivateTags("<private> \n </private>");
350
+ assert.ok(text.includes("[REDACTED:user-marked]"));
351
+ });
352
+ });
@@ -0,0 +1,249 @@
1
+ /**
2
+ * conformance-extended.test.ts — Extended conformance suite across all providers (T13).
3
+ *
4
+ * Verifies that the abstraction is actually abstract: identical input → same shape
5
+ * output, modulo content. Callers must not depend on provider-specific quirks.
6
+ *
7
+ * Cases (14):
8
+ * Embedding conformance (5):
9
+ * 1. gemini: embed empty array → [] (no network call shape)
10
+ * 2. all embedding providers: embed() returns Float32Array[] or throws NotImplementedError
11
+ * 3. all embedding providers: healthCheck() returns HealthStatus shape (ok + optional error + optional latencyMs)
12
+ * 4. all embedding providers: dimensions and maxTokens are positive integers
13
+ * 5. all embedding providers: costPerMillionTokens is a non-negative number
14
+ *
15
+ * LLM conformance (5):
16
+ * 6. all LLM providers: complete() returns CompleteResult shape or throws NotImplementedError
17
+ * 7. all LLM providers: healthCheck() returns HealthStatus shape
18
+ * 8. all LLM providers: name, model, contextWindow are non-empty strings/positive numbers
19
+ * 9. gemini: complete() result has all required fields (text, tokensIn, tokensOut, latencyMs)
20
+ * 10. stub providers: NotImplementedError from complete() names the provider
21
+ *
22
+ * Chain conformance (2):
23
+ * 11. LLMFallbackChain exposes LLMProvider interface (name, model, contextWindow, complete, healthCheck)
24
+ * 12. CostCappedProvider exposes LLMProvider interface
25
+ *
26
+ * Secret hygiene (2):
27
+ * 13. stub errors do NOT contain API key patterns
28
+ * 14. telemetry row shapes conform to ProviderTelemetryRow (all required fields present)
29
+ */
30
+ import { test, describe } from "node:test";
31
+ import { strict as assert } from "node:assert";
32
+ import { GeminiEmbeddingProvider } from "../embedding/gemini.js";
33
+ import { OpenAIEmbeddingProvider } from "../embedding/openai.js";
34
+ import { VoyageEmbeddingProvider } from "../embedding/voyage.js";
35
+ import { GeminiLLMProvider } from "../llm/gemini.js";
36
+ import { OpenAILLMProvider } from "../llm/openai.js";
37
+ import { AnthropicLLMProvider } from "../llm/anthropic.js";
38
+ import { NotImplementedError, MissingKeyError } from "../types.js";
39
+ import { LLMFallbackChain } from "../llm/chain.js";
40
+ import { CostCappedProvider } from "../../lib/cost-cap.js";
41
+ const FAKE_KEY = "AIzaTESTtestTESTtestTESTtestTESTtest";
42
+ /** Mock fetch that always returns a fixed embed response. */
43
+ function mockEmbedFetch(dim) {
44
+ const values = Array.from({ length: dim }, (_, i) => i / dim);
45
+ return async () => ({
46
+ ok: true, status: 200, statusText: "OK",
47
+ text: async () => "{}",
48
+ json: async () => ({ embeddings: [{ values }] }),
49
+ });
50
+ }
51
+ /** Mock fetch for Gemini LLM. */
52
+ function mockLLMFetch() {
53
+ return async () => ({
54
+ ok: true, status: 200, statusText: "OK",
55
+ text: async () => "{}",
56
+ json: async () => ({
57
+ candidates: [{ content: { parts: [{ text: "response" }] } }],
58
+ usageMetadata: { promptTokenCount: 10, candidatesTokenCount: 5 },
59
+ }),
60
+ });
61
+ }
62
+ // OpenAI is a live provider: apiKey:"" forces the deterministic no-credentials
63
+ // path (MissingKeyError) so the conformance loops never consult the ambient
64
+ // OPENAI_API_KEY env var nor make a network call.
65
+ const ALL_EMBEDDING_PROVIDERS = [
66
+ new GeminiEmbeddingProvider({ apiKey: FAKE_KEY, fetchFn: mockEmbedFetch(3072) }),
67
+ new OpenAIEmbeddingProvider({ apiKey: "" }),
68
+ new VoyageEmbeddingProvider(),
69
+ ];
70
+ const ALL_LLM_PROVIDERS = [
71
+ new GeminiLLMProvider({ apiKey: FAKE_KEY, fetchFn: mockLLMFetch() }),
72
+ new OpenAILLMProvider({ apiKey: "" }),
73
+ new AnthropicLLMProvider(),
74
+ ];
75
+ // ─── Embedding conformance ────────────────────────────────────────────────────
76
+ describe("EmbeddingProvider conformance — all providers", () => {
77
+ test("gemini: embed([]) returns empty array without network call", async () => {
78
+ const p = new GeminiEmbeddingProvider({ apiKey: FAKE_KEY, fetchFn: mockEmbedFetch(3072) });
79
+ const result = await p.embed([]);
80
+ assert.deepEqual(result, []);
81
+ });
82
+ test("all providers: embed() returns Float32Array[] or NotImplementedError/MissingKeyError", async () => {
83
+ for (const p of ALL_EMBEDDING_PROVIDERS) {
84
+ try {
85
+ const result = await p.embed(["test input"]);
86
+ assert.ok(Array.isArray(result), `${p.name}: embed() should return array`);
87
+ if (result.length > 0) {
88
+ assert.ok(result[0] instanceof Float32Array, `${p.name}: each element should be Float32Array`);
89
+ }
90
+ }
91
+ catch (err) {
92
+ // Stubs throw NotImplementedError; live providers (OpenAI) without a key
93
+ // surface MissingKeyError. Both are acceptable conformance outcomes.
94
+ assert.ok(err instanceof NotImplementedError || err instanceof MissingKeyError, `${p.name}: only NotImplementedError/MissingKeyError allowed, got: ${err}`);
95
+ }
96
+ }
97
+ });
98
+ test("all providers: healthCheck() returns HealthStatus shape", async () => {
99
+ for (const p of ALL_EMBEDDING_PROVIDERS) {
100
+ const status = await p.healthCheck();
101
+ assert.equal(typeof status.ok, "boolean", `${p.name}: ok must be boolean`);
102
+ if (status.latencyMs !== undefined) {
103
+ assert.equal(typeof status.latencyMs, "number", `${p.name}: latencyMs must be number`);
104
+ }
105
+ if (!status.ok) {
106
+ assert.ok(status.error && status.error.length > 0, `${p.name}: ok=false must have non-empty error`);
107
+ }
108
+ }
109
+ });
110
+ test("all providers: dimensions and maxTokens are positive integers", () => {
111
+ for (const p of ALL_EMBEDDING_PROVIDERS) {
112
+ assert.ok(Number.isInteger(p.dimensions) && p.dimensions > 0, `${p.name}: dimensions=${p.dimensions} must be positive integer`);
113
+ assert.ok(Number.isInteger(p.maxTokens) && p.maxTokens > 0, `${p.name}: maxTokens=${p.maxTokens} must be positive integer`);
114
+ }
115
+ });
116
+ test("all providers: costPerMillionTokens is non-negative number", () => {
117
+ for (const p of ALL_EMBEDDING_PROVIDERS) {
118
+ assert.equal(typeof p.costPerMillionTokens, "number", `${p.name}: costPerMillionTokens must be number`);
119
+ assert.ok(p.costPerMillionTokens >= 0, `${p.name}: costPerMillionTokens=${p.costPerMillionTokens} must be >= 0`);
120
+ }
121
+ });
122
+ });
123
+ // ─── LLM conformance ─────────────────────────────────────────────────────────
124
+ describe("LLMProvider conformance — all providers", () => {
125
+ test("all providers: complete() returns CompleteResult shape or NotImplementedError/MissingKeyError", async () => {
126
+ for (const p of ALL_LLM_PROVIDERS) {
127
+ try {
128
+ const result = await p.complete({ user: "hello" });
129
+ assert.equal(typeof result.text, "string", `${p.name}: text must be string`);
130
+ assert.equal(typeof result.tokensIn, "number", `${p.name}: tokensIn must be number`);
131
+ assert.equal(typeof result.tokensOut, "number", `${p.name}: tokensOut must be number`);
132
+ assert.equal(typeof result.latencyMs, "number", `${p.name}: latencyMs must be number`);
133
+ }
134
+ catch (err) {
135
+ // Stubs throw NotImplementedError; live providers (OpenAI) without a key
136
+ // surface MissingKeyError. Both are acceptable conformance outcomes.
137
+ assert.ok(err instanceof NotImplementedError || err instanceof MissingKeyError, `${p.name}: only NotImplementedError/MissingKeyError allowed from complete(), got: ${err}`);
138
+ }
139
+ }
140
+ });
141
+ test("all providers: healthCheck() returns HealthStatus shape", async () => {
142
+ for (const p of ALL_LLM_PROVIDERS) {
143
+ const status = await p.healthCheck();
144
+ assert.equal(typeof status.ok, "boolean", `${p.name}: ok must be boolean`);
145
+ if (!status.ok) {
146
+ assert.ok(status.error && status.error.length > 0, `${p.name}: ok=false must have non-empty error`);
147
+ }
148
+ }
149
+ });
150
+ test("all providers: name, model, contextWindow have correct types", () => {
151
+ for (const p of ALL_LLM_PROVIDERS) {
152
+ assert.equal(typeof p.name, "string", `name must be string`);
153
+ assert.ok(p.name.length > 0, `${p.name}: name must be non-empty`);
154
+ assert.equal(typeof p.model, "string");
155
+ assert.ok(p.model.length > 0, `${p.name}: model must be non-empty`);
156
+ assert.ok(typeof p.contextWindow === "number" && p.contextWindow > 0, `${p.name}: contextWindow must be positive number`);
157
+ }
158
+ });
159
+ test("gemini: complete() result has all required fields", async () => {
160
+ const p = new GeminiLLMProvider({ apiKey: FAKE_KEY, fetchFn: mockLLMFetch() });
161
+ const result = await p.complete({ user: "ping", system: "be brief", maxTokens: 10 });
162
+ assert.equal(result.text, "response");
163
+ assert.equal(result.tokensIn, 10);
164
+ assert.equal(result.tokensOut, 5);
165
+ assert.ok(result.latencyMs >= 0);
166
+ });
167
+ test("stub providers: NotImplementedError names the provider", async () => {
168
+ // OpenAI is a live provider now (throws MissingKeyError, not
169
+ // NotImplementedError) — only Anthropic remains a NotImplementedError stub.
170
+ const stubs = [new AnthropicLLMProvider()];
171
+ for (const p of stubs) {
172
+ let err;
173
+ try {
174
+ await p.complete({ user: "hi" });
175
+ }
176
+ catch (e) {
177
+ err = e;
178
+ }
179
+ assert.ok(err instanceof NotImplementedError, `${p.name}: should throw NotImplementedError`);
180
+ // Error message should name the provider.
181
+ assert.ok(err?.message.includes(p.name), `NotImplementedError message should include "${p.name}": got "${err?.message}"`);
182
+ }
183
+ });
184
+ });
185
+ // ─── Chain / wrapper conformance ─────────────────────────────────────────────
186
+ describe("Chain/wrapper LLMProvider conformance", () => {
187
+ test("LLMFallbackChain exposes LLMProvider interface", () => {
188
+ const primary = new GeminiLLMProvider({ apiKey: FAKE_KEY, fetchFn: mockLLMFetch() });
189
+ const chain = new LLMFallbackChain({ primary, fallbacks: [] });
190
+ assert.equal(typeof chain.name, "string");
191
+ assert.equal(typeof chain.model, "string");
192
+ assert.ok(chain.contextWindow > 0);
193
+ assert.equal(typeof chain.complete, "function");
194
+ assert.equal(typeof chain.healthCheck, "function");
195
+ });
196
+ test("CostCappedProvider exposes LLMProvider interface", () => {
197
+ const primary = new GeminiLLMProvider({ apiKey: FAKE_KEY, fetchFn: mockLLMFetch() });
198
+ const capped = new CostCappedProvider({ provider: primary, capUsd: 50 });
199
+ assert.equal(typeof capped.name, "string");
200
+ assert.equal(typeof capped.model, "string");
201
+ assert.ok(capped.contextWindow > 0);
202
+ assert.equal(typeof capped.complete, "function");
203
+ assert.equal(typeof capped.healthCheck, "function");
204
+ });
205
+ });
206
+ // ─── Secret hygiene ───────────────────────────────────────────────────────────
207
+ describe("Secret hygiene conformance", () => {
208
+ test("stub errors do NOT contain API key patterns", async () => {
209
+ const stubs = [
210
+ new OpenAIEmbeddingProvider({ apiKey: "" }),
211
+ new VoyageEmbeddingProvider(),
212
+ new OpenAILLMProvider({ apiKey: "" }),
213
+ new AnthropicLLMProvider(),
214
+ ];
215
+ const keyPattern = /AIza[A-Za-z0-9_-]{20,}|sk-[A-Za-z0-9_-]{20,}|Bearer\s+[A-Za-z0-9._-]{20,}/;
216
+ for (const p of stubs) {
217
+ const status = await p.healthCheck();
218
+ if (status.error) {
219
+ assert.ok(!keyPattern.test(status.error), `${p.name}: healthCheck error should not contain key pattern`);
220
+ }
221
+ }
222
+ });
223
+ test("ProviderTelemetryRow shape: all required fields present", () => {
224
+ // Verify the type contract by constructing a valid row and checking fields.
225
+ const row = {
226
+ ts: Date.now(),
227
+ provider_id: "gemini",
228
+ model: "gemini-2.5-flash-lite",
229
+ kind: "llm",
230
+ tokens_in: 10,
231
+ tokens_out: 5,
232
+ cost_usd: 0.001,
233
+ latency_ms: 50,
234
+ ok: 1,
235
+ caller: "kg-extract",
236
+ session_id: "s1",
237
+ };
238
+ // All required fields present.
239
+ assert.equal(typeof row.ts, "number");
240
+ assert.equal(typeof row.provider_id, "string");
241
+ assert.equal(typeof row.model, "string");
242
+ assert.ok(row.kind === "embedding" || row.kind === "llm");
243
+ assert.equal(typeof row.tokens_in, "number");
244
+ assert.equal(typeof row.tokens_out, "number");
245
+ assert.equal(typeof row.cost_usd, "number");
246
+ assert.equal(typeof row.latency_ms, "number");
247
+ assert.ok(row.ok === 0 || row.ok === 1);
248
+ });
249
+ });