nox-mem 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (457) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -0
  3. package/dist/api/answer.d.ts +116 -0
  4. package/dist/api/answer.js +274 -0
  5. package/dist/api/answer.validate-patch.d.ts +72 -0
  6. package/dist/api/answer.validate-patch.js +52 -0
  7. package/dist/api/brief-diversity.d.ts +64 -0
  8. package/dist/api/brief-diversity.js +91 -0
  9. package/dist/api/brief.d.ts +114 -0
  10. package/dist/api/brief.js +524 -0
  11. package/dist/api/conflict.d.ts +33 -0
  12. package/dist/api/conflict.js +143 -0
  13. package/dist/api/cors.d.ts +73 -0
  14. package/dist/api/cors.js +124 -0
  15. package/dist/api/events-stream-limited.d.ts +133 -0
  16. package/dist/api/events-stream-limited.js +217 -0
  17. package/dist/api/events-stream.d.ts +53 -0
  18. package/dist/api/events-stream.js +125 -0
  19. package/dist/api/export.d.ts +42 -0
  20. package/dist/api/export.js +85 -0
  21. package/dist/api/health-confidence-adapter.d.ts +29 -0
  22. package/dist/api/health-confidence-adapter.js +73 -0
  23. package/dist/api/health-confidence.d.ts +36 -0
  24. package/dist/api/health-confidence.js +141 -0
  25. package/dist/api/hooks.d.ts +50 -0
  26. package/dist/api/hooks.js +115 -0
  27. package/dist/api/import.d.ts +38 -0
  28. package/dist/api/import.js +87 -0
  29. package/dist/api/ingest-event.d.ts +65 -0
  30. package/dist/api/ingest-event.js +153 -0
  31. package/dist/api/mark.d.ts +42 -0
  32. package/dist/api/mark.js +127 -0
  33. package/dist/api/server-deps-a2.d.ts +55 -0
  34. package/dist/api/server-deps-a2.js +138 -0
  35. package/dist/api/server-deps-l2-l3.d.ts +68 -0
  36. package/dist/api/server-deps-l2-l3.js +123 -0
  37. package/dist/api/server-deps-p1.d.ts +84 -0
  38. package/dist/api/server-deps-p1.js +156 -0
  39. package/dist/api/server-deps-p2.d.ts +32 -0
  40. package/dist/api/server-deps-p2.js +84 -0
  41. package/dist/api/server-deps-p5.d.ts +66 -0
  42. package/dist/api/server-deps-p5.js +139 -0
  43. package/dist/api/viewer-static.d.ts +30 -0
  44. package/dist/api/viewer-static.js +102 -0
  45. package/dist/api/wire-up.d.ts +54 -0
  46. package/dist/api/wire-up.js +521 -0
  47. package/dist/api-impact.d.ts +30 -0
  48. package/dist/api-impact.js +196 -0
  49. package/dist/api-server.d.ts +2 -0
  50. package/dist/api-server.js +614 -0
  51. package/dist/backfill-fts-anchor.d.ts +15 -0
  52. package/dist/backfill-fts-anchor.js +97 -0
  53. package/dist/backfill-source-type.d.ts +20 -0
  54. package/dist/backfill-source-type.js +182 -0
  55. package/dist/churn.d.ts +31 -0
  56. package/dist/churn.js +98 -0
  57. package/dist/cli/answer.d.ts +66 -0
  58. package/dist/cli/answer.js +287 -0
  59. package/dist/cli/conflict.d.ts +38 -0
  60. package/dist/cli/conflict.js +282 -0
  61. package/dist/cli/export.d.ts +51 -0
  62. package/dist/cli/export.js +280 -0
  63. package/dist/cli/hooks.d.ts +54 -0
  64. package/dist/cli/hooks.js +133 -0
  65. package/dist/cli/import.d.ts +52 -0
  66. package/dist/cli/import.js +274 -0
  67. package/dist/cli/mark.d.ts +33 -0
  68. package/dist/cli/mark.js +130 -0
  69. package/dist/cli/ocr-batch.d.ts +12 -0
  70. package/dist/cli/ocr-batch.js +411 -0
  71. package/dist/cli/snapshot-main.d.ts +30 -0
  72. package/dist/cli/snapshot-main.js +47 -0
  73. package/dist/cli/viewer.d.ts +35 -0
  74. package/dist/cli/viewer.js +71 -0
  75. package/dist/cli-telemetry.d.ts +36 -0
  76. package/dist/cli-telemetry.js +150 -0
  77. package/dist/compact.d.ts +7 -0
  78. package/dist/compact.js +147 -0
  79. package/dist/consolidate.d.ts +18 -0
  80. package/dist/consolidate.js +475 -0
  81. package/dist/consolidation.d.ts +32 -0
  82. package/dist/consolidation.js +212 -0
  83. package/dist/cross-agent-v2.d.ts +45 -0
  84. package/dist/cross-agent-v2.js +271 -0
  85. package/dist/cross-search.d.ts +11 -0
  86. package/dist/cross-search.js +119 -0
  87. package/dist/crystallize.d.ts +43 -0
  88. package/dist/crystallize.js +111 -0
  89. package/dist/db.d.ts +11 -0
  90. package/dist/db.js +388 -0
  91. package/dist/dedup.d.ts +1 -0
  92. package/dist/dedup.js +106 -0
  93. package/dist/detect-changes.d.ts +29 -0
  94. package/dist/detect-changes.js +236 -0
  95. package/dist/digest.d.ts +1 -0
  96. package/dist/digest.js +205 -0
  97. package/dist/doctor.d.ts +1 -0
  98. package/dist/doctor.js +71 -0
  99. package/dist/embed.d.ts +45 -0
  100. package/dist/embed.js +257 -0
  101. package/dist/evals.d.ts +176 -0
  102. package/dist/evals.js +351 -0
  103. package/dist/generate-user-profile.d.ts +18 -0
  104. package/dist/generate-user-profile.js +163 -0
  105. package/dist/graphify-ingest.d.ts +18 -0
  106. package/dist/graphify-ingest.js +158 -0
  107. package/dist/impact.d.ts +39 -0
  108. package/dist/impact.js +143 -0
  109. package/dist/index.d.ts +2 -0
  110. package/dist/index.js +689 -0
  111. package/dist/ingest-entity.d.ts +44 -0
  112. package/dist/ingest-entity.js +197 -0
  113. package/dist/ingest.d.ts +13 -0
  114. package/dist/ingest.js +210 -0
  115. package/dist/kg-llm.d.ts +39 -0
  116. package/dist/kg-llm.js +295 -0
  117. package/dist/knowledge-graph.d.ts +72 -0
  118. package/dist/knowledge-graph.js +507 -0
  119. package/dist/lib/answer/config.d.ts +41 -0
  120. package/dist/lib/answer/config.js +70 -0
  121. package/dist/lib/answer/index.d.ts +47 -0
  122. package/dist/lib/answer/index.js +221 -0
  123. package/dist/lib/answer/prompt.d.ts +37 -0
  124. package/dist/lib/answer/prompt.js +88 -0
  125. package/dist/lib/answer/provider.d.ts +47 -0
  126. package/dist/lib/answer/provider.js +101 -0
  127. package/dist/lib/answer/retrieval.d.ts +36 -0
  128. package/dist/lib/answer/retrieval.js +92 -0
  129. package/dist/lib/answer/telemetry.d.ts +99 -0
  130. package/dist/lib/answer/telemetry.js +154 -0
  131. package/dist/lib/answer/types.d.ts +108 -0
  132. package/dist/lib/answer/types.js +1 -0
  133. package/dist/lib/api/error-leak-fix.d.ts +54 -0
  134. package/dist/lib/api/error-leak-fix.js +55 -0
  135. package/dist/lib/api/safe-error-message.d.ts +70 -0
  136. package/dist/lib/api/safe-error-message.js +122 -0
  137. package/dist/lib/archive/common-passwords.d.ts +37 -0
  138. package/dist/lib/archive/common-passwords.js +753 -0
  139. package/dist/lib/archive/encryption.d.ts +81 -0
  140. package/dist/lib/archive/encryption.js +236 -0
  141. package/dist/lib/archive/enforce-strength.d.ts +54 -0
  142. package/dist/lib/archive/enforce-strength.js +70 -0
  143. package/dist/lib/archive/entropy.d.ts +34 -0
  144. package/dist/lib/archive/entropy.js +180 -0
  145. package/dist/lib/archive/export-locking.d.ts +102 -0
  146. package/dist/lib/archive/export-locking.js +202 -0
  147. package/dist/lib/archive/format.d.ts +20 -0
  148. package/dist/lib/archive/format.js +174 -0
  149. package/dist/lib/archive/index.d.ts +23 -0
  150. package/dist/lib/archive/index.js +17 -0
  151. package/dist/lib/archive/manifest.d.ts +53 -0
  152. package/dist/lib/archive/manifest.js +183 -0
  153. package/dist/lib/archive/migration.d.ts +36 -0
  154. package/dist/lib/archive/migration.js +100 -0
  155. package/dist/lib/archive/migrations/v18_to_v19.d.ts +16 -0
  156. package/dist/lib/archive/migrations/v18_to_v19.js +18 -0
  157. package/dist/lib/archive/orchestrator.d.ts +166 -0
  158. package/dist/lib/archive/orchestrator.js +428 -0
  159. package/dist/lib/archive/serializers/chunks.d.ts +30 -0
  160. package/dist/lib/archive/serializers/chunks.js +113 -0
  161. package/dist/lib/archive/serializers/embeddings.d.ts +36 -0
  162. package/dist/lib/archive/serializers/embeddings.js +115 -0
  163. package/dist/lib/archive/serializers/kg.d.ts +28 -0
  164. package/dist/lib/archive/serializers/kg.js +184 -0
  165. package/dist/lib/archive/serializers/ops_audit.d.ts +21 -0
  166. package/dist/lib/archive/serializers/ops_audit.js +97 -0
  167. package/dist/lib/archive/server-deps.d.ts +131 -0
  168. package/dist/lib/archive/server-deps.js +232 -0
  169. package/dist/lib/archive/strength.d.ts +50 -0
  170. package/dist/lib/archive/strength.js +77 -0
  171. package/dist/lib/archive/types.d.ts +159 -0
  172. package/dist/lib/archive/types.js +45 -0
  173. package/dist/lib/archive/unpack-streaming.d.ts +70 -0
  174. package/dist/lib/archive/unpack-streaming.js +255 -0
  175. package/dist/lib/auth/localhost-guard.d.ts +106 -0
  176. package/dist/lib/auth/localhost-guard.js +164 -0
  177. package/dist/lib/confidence/config.d.ts +37 -0
  178. package/dist/lib/confidence/config.js +107 -0
  179. package/dist/lib/confidence/db-shim-singleton.d.ts +20 -0
  180. package/dist/lib/confidence/db-shim-singleton.js +41 -0
  181. package/dist/lib/confidence/db-shim.d.ts +47 -0
  182. package/dist/lib/confidence/db-shim.js +141 -0
  183. package/dist/lib/confidence/mark.d.ts +58 -0
  184. package/dist/lib/confidence/mark.js +168 -0
  185. package/dist/lib/confidence/ranking.d.ts +69 -0
  186. package/dist/lib/confidence/ranking.js +101 -0
  187. package/dist/lib/confidence/search-filter.d.ts +44 -0
  188. package/dist/lib/confidence/search-filter.js +103 -0
  189. package/dist/lib/confidence/types.d.ts +146 -0
  190. package/dist/lib/confidence/types.js +20 -0
  191. package/dist/lib/confidence/write-hooks.d.ts +50 -0
  192. package/dist/lib/confidence/write-hooks.js +159 -0
  193. package/dist/lib/conflict/audit-fk-check.d.ts +72 -0
  194. package/dist/lib/conflict/audit-fk-check.js +131 -0
  195. package/dist/lib/conflict/audit-writer.d.ts +39 -0
  196. package/dist/lib/conflict/audit-writer.js +133 -0
  197. package/dist/lib/conflict/db-singleton.d.ts +28 -0
  198. package/dist/lib/conflict/db-singleton.js +61 -0
  199. package/dist/lib/conflict/db.d.ts +27 -0
  200. package/dist/lib/conflict/db.js +20 -0
  201. package/dist/lib/conflict/detector-direct.d.ts +21 -0
  202. package/dist/lib/conflict/detector-direct.js +105 -0
  203. package/dist/lib/conflict/evidence.d.ts +24 -0
  204. package/dist/lib/conflict/evidence.js +76 -0
  205. package/dist/lib/conflict/index.d.ts +14 -0
  206. package/dist/lib/conflict/index.js +12 -0
  207. package/dist/lib/conflict/scheduler.d.ts +78 -0
  208. package/dist/lib/conflict/scheduler.js +111 -0
  209. package/dist/lib/conflict/shadow.d.ts +75 -0
  210. package/dist/lib/conflict/shadow.js +161 -0
  211. package/dist/lib/conflict/types.d.ts +133 -0
  212. package/dist/lib/conflict/types.js +19 -0
  213. package/dist/lib/cost-cap.d.ts +94 -0
  214. package/dist/lib/cost-cap.js +129 -0
  215. package/dist/lib/deps/deps-registry.d.ts +111 -0
  216. package/dist/lib/deps/deps-registry.js +209 -0
  217. package/dist/lib/error-sanitizer/middleware.d.ts +43 -0
  218. package/dist/lib/error-sanitizer/middleware.js +100 -0
  219. package/dist/lib/error-sanitizer/sanitize.d.ts +78 -0
  220. package/dist/lib/error-sanitizer/sanitize.js +202 -0
  221. package/dist/lib/eval-batch.d.ts +34 -0
  222. package/dist/lib/eval-batch.js +103 -0
  223. package/dist/lib/eval-metrics.d.ts +36 -0
  224. package/dist/lib/eval-metrics.js +95 -0
  225. package/dist/lib/eval.d.ts +106 -0
  226. package/dist/lib/eval.js +343 -0
  227. package/dist/lib/events/bus.d.ts +135 -0
  228. package/dist/lib/events/bus.js +95 -0
  229. package/dist/lib/fts-anchor.d.ts +1 -0
  230. package/dist/lib/fts-anchor.js +131 -0
  231. package/dist/lib/hooks/classifier.d.ts +47 -0
  232. package/dist/lib/hooks/classifier.js +129 -0
  233. package/dist/lib/hooks/config.d.ts +49 -0
  234. package/dist/lib/hooks/config.js +106 -0
  235. package/dist/lib/hooks/decorators.d.ts +35 -0
  236. package/dist/lib/hooks/decorators.js +59 -0
  237. package/dist/lib/hooks/pipeline.d.ts +76 -0
  238. package/dist/lib/hooks/pipeline.js +213 -0
  239. package/dist/lib/hooks/privacy-filter-adapter.d.ts +55 -0
  240. package/dist/lib/hooks/privacy-filter-adapter.js +84 -0
  241. package/dist/lib/hooks/rate-limit-constant-time.d.ts +57 -0
  242. package/dist/lib/hooks/rate-limit-constant-time.js +69 -0
  243. package/dist/lib/hooks/rate-limit-dryrun-fix.d.ts +71 -0
  244. package/dist/lib/hooks/rate-limit-dryrun-fix.js +110 -0
  245. package/dist/lib/hooks/rate-limit.d.ts +54 -0
  246. package/dist/lib/hooks/rate-limit.js +122 -0
  247. package/dist/lib/hooks/server-deps.d.ts +61 -0
  248. package/dist/lib/hooks/server-deps.js +92 -0
  249. package/dist/lib/hooks/source-allowlist.d.ts +26 -0
  250. package/dist/lib/hooks/source-allowlist.js +53 -0
  251. package/dist/lib/hooks/types.d.ts +129 -0
  252. package/dist/lib/hooks/types.js +24 -0
  253. package/dist/lib/hooks/worker.d.ts +56 -0
  254. package/dist/lib/hooks/worker.js +150 -0
  255. package/dist/lib/ingest-router.d.ts +25 -0
  256. package/dist/lib/ingest-router.js +103 -0
  257. package/dist/lib/ocr-detector.d.ts +61 -0
  258. package/dist/lib/ocr-detector.js +138 -0
  259. package/dist/lib/ocr-engine-stub.d.ts +48 -0
  260. package/dist/lib/ocr-engine-stub.js +190 -0
  261. package/dist/lib/ocr-engines/google-doc-ai.d.ts +36 -0
  262. package/dist/lib/ocr-engines/google-doc-ai.js +164 -0
  263. package/dist/lib/ocr-jobs.d.ts +67 -0
  264. package/dist/lib/ocr-jobs.js +129 -0
  265. package/dist/lib/op-audit-extension/ran-at-guard.d.ts +86 -0
  266. package/dist/lib/op-audit-extension/ran-at-guard.js +110 -0
  267. package/dist/lib/op-audit.d.ts +71 -0
  268. package/dist/lib/op-audit.js +777 -0
  269. package/dist/lib/privacy-br/detector.d.ts +42 -0
  270. package/dist/lib/privacy-br/detector.js +130 -0
  271. package/dist/lib/privacy-br/index.d.ts +20 -0
  272. package/dist/lib/privacy-br/index.js +20 -0
  273. package/dist/lib/privacy-br/integration.d.ts +71 -0
  274. package/dist/lib/privacy-br/integration.js +74 -0
  275. package/dist/lib/privacy-br/patterns.d.ts +117 -0
  276. package/dist/lib/privacy-br/patterns.js +434 -0
  277. package/dist/lib/privacy-br/redact.d.ts +42 -0
  278. package/dist/lib/privacy-br/redact.js +103 -0
  279. package/dist/lib/privacy-br/types.d.ts +55 -0
  280. package/dist/lib/privacy-br/types.js +25 -0
  281. package/dist/lib/regex-extract/extractor.d.ts +30 -0
  282. package/dist/lib/regex-extract/extractor.js +91 -0
  283. package/dist/lib/regex-extract/frontmatter.d.ts +44 -0
  284. package/dist/lib/regex-extract/frontmatter.js +169 -0
  285. package/dist/lib/regex-extract/index.d.ts +14 -0
  286. package/dist/lib/regex-extract/index.js +14 -0
  287. package/dist/lib/regex-extract/ingest-router-l4.d.ts +76 -0
  288. package/dist/lib/regex-extract/ingest-router-l4.js +102 -0
  289. package/dist/lib/regex-extract/patterns.d.ts +61 -0
  290. package/dist/lib/regex-extract/patterns.js +91 -0
  291. package/dist/lib/regex-extract/production-wire.d.ts +128 -0
  292. package/dist/lib/regex-extract/production-wire.js +202 -0
  293. package/dist/lib/regex-extract/reconcile.d.ts +162 -0
  294. package/dist/lib/regex-extract/reconcile.js +210 -0
  295. package/dist/lib/regex-extract/strip-code.d.ts +24 -0
  296. package/dist/lib/regex-extract/strip-code.js +52 -0
  297. package/dist/lib/regex-extract/types.d.ts +48 -0
  298. package/dist/lib/regex-extract/types.js +25 -0
  299. package/dist/lib/reranker.d.ts +80 -0
  300. package/dist/lib/reranker.js +324 -0
  301. package/dist/lib/shadow-tracker.d.ts +191 -0
  302. package/dist/lib/shadow-tracker.js +384 -0
  303. package/dist/lib/spo-injection.d.ts +52 -0
  304. package/dist/lib/spo-injection.js +166 -0
  305. package/dist/lib/telemetry-collector.d.ts +158 -0
  306. package/dist/lib/telemetry-collector.js +249 -0
  307. package/dist/lib/temporal-detector.d.ts +27 -0
  308. package/dist/lib/temporal-detector.js +81 -0
  309. package/dist/lib/viewer/auth.d.ts +37 -0
  310. package/dist/lib/viewer/auth.js +70 -0
  311. package/dist/lib/viewer/backpressure.d.ts +59 -0
  312. package/dist/lib/viewer/backpressure.js +100 -0
  313. package/dist/lib/viewer/broadcast-singleton.d.ts +34 -0
  314. package/dist/lib/viewer/broadcast-singleton.js +49 -0
  315. package/dist/lib/viewer/broadcast.d.ts +66 -0
  316. package/dist/lib/viewer/broadcast.js +96 -0
  317. package/dist/lib/viewer/event-types.d.ts +132 -0
  318. package/dist/lib/viewer/event-types.js +74 -0
  319. package/dist/lib/viewer/instrumentation.d.ts +106 -0
  320. package/dist/lib/viewer/instrumentation.js +224 -0
  321. package/dist/lib/viewer/migration.d.ts +23 -0
  322. package/dist/lib/viewer/migration.js +56 -0
  323. package/dist/lib/viewer/redaction.d.ts +44 -0
  324. package/dist/lib/viewer/redaction.js +139 -0
  325. package/dist/lib/viewer/session.d.ts +51 -0
  326. package/dist/lib/viewer/session.js +87 -0
  327. package/dist/mcp/tools/answer.d.ts +94 -0
  328. package/dist/mcp/tools/answer.js +213 -0
  329. package/dist/mcp/tools/archive.d.ts +152 -0
  330. package/dist/mcp/tools/archive.js +170 -0
  331. package/dist/mcp/tools/conflict.d.ts +44 -0
  332. package/dist/mcp/tools/conflict.js +130 -0
  333. package/dist/mcp/tools/hooks.d.ts +29 -0
  334. package/dist/mcp/tools/hooks.js +78 -0
  335. package/dist/mcp/tools/mark.d.ts +38 -0
  336. package/dist/mcp/tools/mark.js +82 -0
  337. package/dist/mcp/tools/viewer.d.ts +58 -0
  338. package/dist/mcp/tools/viewer.js +64 -0
  339. package/dist/mcp-server.d.ts +2 -0
  340. package/dist/mcp-server.js +395 -0
  341. package/dist/metrics.d.ts +3 -0
  342. package/dist/metrics.js +59 -0
  343. package/dist/noise-filter.d.ts +18 -0
  344. package/dist/noise-filter.js +142 -0
  345. package/dist/notion-sync.d.ts +7 -0
  346. package/dist/notion-sync.js +97 -0
  347. package/dist/observability/adapters/a3-adapter.d.ts +63 -0
  348. package/dist/observability/adapters/a3-adapter.js +83 -0
  349. package/dist/observability/adapters/p1-adapter.d.ts +49 -0
  350. package/dist/observability/adapters/p1-adapter.js +63 -0
  351. package/dist/observability/adapters/p5-adapter.d.ts +36 -0
  352. package/dist/observability/adapters/p5-adapter.js +71 -0
  353. package/dist/observability/cardinality.d.ts +61 -0
  354. package/dist/observability/cardinality.js +300 -0
  355. package/dist/observability/collectors/db-stats.collector.d.ts +9 -0
  356. package/dist/observability/collectors/db-stats.collector.js +88 -0
  357. package/dist/observability/collectors/eventbus.collector.d.ts +6 -0
  358. package/dist/observability/collectors/eventbus.collector.js +50 -0
  359. package/dist/observability/collectors/process.collector.d.ts +7 -0
  360. package/dist/observability/collectors/process.collector.js +93 -0
  361. package/dist/observability/collectors/provider-telemetry.collector.d.ts +11 -0
  362. package/dist/observability/collectors/provider-telemetry.collector.js +112 -0
  363. package/dist/observability/collectors/search-telemetry.collector.d.ts +12 -0
  364. package/dist/observability/collectors/search-telemetry.collector.js +76 -0
  365. package/dist/observability/exporter.d.ts +30 -0
  366. package/dist/observability/exporter.js +182 -0
  367. package/dist/observability/index.d.ts +22 -0
  368. package/dist/observability/index.js +21 -0
  369. package/dist/observability/metrics.d.ts +53 -0
  370. package/dist/observability/metrics.js +213 -0
  371. package/dist/observability/privacy-guard.d.ts +32 -0
  372. package/dist/observability/privacy-guard.js +116 -0
  373. package/dist/observability/record.d.ts +83 -0
  374. package/dist/observability/record.js +217 -0
  375. package/dist/observability/registry.d.ts +60 -0
  376. package/dist/observability/registry.js +93 -0
  377. package/dist/observability/types.d.ts +115 -0
  378. package/dist/observability/types.js +235 -0
  379. package/dist/observability.d.ts +131 -0
  380. package/dist/observability.js +234 -0
  381. package/dist/plugins/nox-hooks/index.d.ts +61 -0
  382. package/dist/plugins/nox-hooks/index.js +99 -0
  383. package/dist/primer.d.ts +1 -0
  384. package/dist/primer.js +100 -0
  385. package/dist/privacy/filter.d.ts +27 -0
  386. package/dist/privacy/filter.js +74 -0
  387. package/dist/privacy/patterns.d.ts +29 -0
  388. package/dist/privacy/patterns.js +178 -0
  389. package/dist/privacy/tag-parser.d.ts +24 -0
  390. package/dist/privacy/tag-parser.js +29 -0
  391. package/dist/project-context-gen.d.ts +10 -0
  392. package/dist/project-context-gen.js +106 -0
  393. package/dist/providers/embedding/gemini.d.ts +73 -0
  394. package/dist/providers/embedding/gemini.js +118 -0
  395. package/dist/providers/embedding/openai.d.ts +76 -0
  396. package/dist/providers/embedding/openai.js +123 -0
  397. package/dist/providers/embedding/types.d.ts +39 -0
  398. package/dist/providers/embedding/types.js +1 -0
  399. package/dist/providers/embedding/voyage.d.ts +36 -0
  400. package/dist/providers/embedding/voyage.js +29 -0
  401. package/dist/providers/index.d.ts +116 -0
  402. package/dist/providers/index.js +158 -0
  403. package/dist/providers/llm/anthropic.d.ts +29 -0
  404. package/dist/providers/llm/anthropic.js +28 -0
  405. package/dist/providers/llm/chain.d.ts +99 -0
  406. package/dist/providers/llm/chain.js +213 -0
  407. package/dist/providers/llm/gemini.d.ts +48 -0
  408. package/dist/providers/llm/gemini.js +96 -0
  409. package/dist/providers/llm/openai.d.ts +64 -0
  410. package/dist/providers/llm/openai.js +109 -0
  411. package/dist/providers/llm/types.d.ts +47 -0
  412. package/dist/providers/llm/types.js +1 -0
  413. package/dist/providers/telemetry.d.ts +87 -0
  414. package/dist/providers/telemetry.js +156 -0
  415. package/dist/providers/types.d.ts +42 -0
  416. package/dist/providers/types.js +59 -0
  417. package/dist/query-entity-count.d.ts +54 -0
  418. package/dist/query-entity-count.js +171 -0
  419. package/dist/reflect.d.ts +26 -0
  420. package/dist/reflect.js +290 -0
  421. package/dist/reindex-errors.d.ts +7 -0
  422. package/dist/reindex-errors.js +21 -0
  423. package/dist/reindex.d.ts +16 -0
  424. package/dist/reindex.js +293 -0
  425. package/dist/retention.d.ts +40 -0
  426. package/dist/retention.js +86 -0
  427. package/dist/salience.d.ts +85 -0
  428. package/dist/salience.js +245 -0
  429. package/dist/scripts/migrate-v17-ops-audit.d.ts +17 -0
  430. package/dist/scripts/migrate-v17-ops-audit.js +70 -0
  431. package/dist/search-dedup.d.ts +44 -0
  432. package/dist/search-dedup.js +137 -0
  433. package/dist/search-expansion.d.ts +20 -0
  434. package/dist/search-expansion.js +99 -0
  435. package/dist/search.d.ts +62 -0
  436. package/dist/search.js +582 -0
  437. package/dist/seh-detector.d.ts +31 -0
  438. package/dist/seh-detector.js +201 -0
  439. package/dist/self-improve.d.ts +1 -0
  440. package/dist/self-improve.js +189 -0
  441. package/dist/session-distill.d.ts +29 -0
  442. package/dist/session-distill.js +325 -0
  443. package/dist/session-update.d.ts +1 -0
  444. package/dist/session-update.js +54 -0
  445. package/dist/shared-memory.d.ts +24 -0
  446. package/dist/shared-memory.js +104 -0
  447. package/dist/stats.d.ts +1 -0
  448. package/dist/stats.js +44 -0
  449. package/dist/temporal-retrieval.d.ts +132 -0
  450. package/dist/temporal-retrieval.js +495 -0
  451. package/dist/tier-manager.d.ts +69 -0
  452. package/dist/tier-manager.js +225 -0
  453. package/dist/vectorize.d.ts +16 -0
  454. package/dist/vectorize.js +91 -0
  455. package/dist/watch.d.ts +8 -0
  456. package/dist/watch.js +124 -0
  457. package/package.json +74 -0
@@ -0,0 +1,324 @@
1
+ // D01 — Cross-encoder Reranker (shadow)
2
+ // 2026-05-07 impl. Spec: specs/2026-05-07-D01-cross-encoder-reranker.md (memoria-nox)
3
+ //
4
+ // Adiciona camada de cross-encoder pós-RRF ao hybrid pipeline. BGE-reranker-base
5
+ // via @xenova/transformers (ONNX in Node, ~85MB on disk). Default off; shadow
6
+ // computa lift sem mutar resultados; active substitui ranking pelo reranker.
7
+ //
8
+ // Modes (env NOX_RERANKER_MODE):
9
+ // off — disabled (default), no compute, no apply
10
+ // shadow — rerank executa, telemetria, ranking final = original (não muta)
11
+ // active — rerank substitui ranking final
12
+ //
13
+ // Fail-open: model load falha, ONNX timeout, exception qualquer → log + retorna
14
+ // candidates originais (off-mode efetivo). Zero crash exposto ao caller.
15
+ //
16
+ // Telemetria computada mesmo em shadow:
17
+ // - position_changes: chunks que mudaram posição entre orig top-K e rerank top-K
18
+ // - lift_score: |sum(orig_pos − new_pos)| / K_OUT, normalizado [0,1]
19
+ //
20
+ // Cache do modelo: default em node_modules/@xenova/transformers/.cache/
21
+ // Override via env TRANSFORMERS_CACHE (recomendado prod: /var/cache/nox-mem-models/).
22
+ // ─── Defaults ────────────────────────────────────────────────────────────────
23
+ export const DEFAULT_TOP_K_IN = 50;
24
+ export const DEFAULT_TOP_K_OUT = 10;
25
+ export const DEFAULT_MODEL = "Xenova/bge-reranker-base";
26
+ export const DEFAULT_TIMEOUT_MS = 2000;
27
+ // ─── Env config ──────────────────────────────────────────────────────────────
28
+ export function getMode() {
29
+ const v = (process.env.NOX_RERANKER_MODE || "off").toLowerCase();
30
+ if (v === "off" || v === "shadow" || v === "active")
31
+ return v;
32
+ return "off";
33
+ }
34
+ export function getTopKIn() {
35
+ const raw = process.env.NOX_RERANKER_TOP_K_IN;
36
+ if (!raw)
37
+ return DEFAULT_TOP_K_IN;
38
+ const n = parseInt(raw, 10);
39
+ if (!Number.isFinite(n) || n <= 0)
40
+ return DEFAULT_TOP_K_IN;
41
+ return n;
42
+ }
43
+ export function getTopKOut() {
44
+ const raw = process.env.NOX_RERANKER_TOP_K_OUT;
45
+ if (!raw)
46
+ return DEFAULT_TOP_K_OUT;
47
+ const n = parseInt(raw, 10);
48
+ if (!Number.isFinite(n) || n <= 0)
49
+ return DEFAULT_TOP_K_OUT;
50
+ return n;
51
+ }
52
+ export function getModelName() {
53
+ return process.env.NOX_RERANKER_MODEL || DEFAULT_MODEL;
54
+ }
55
+ export function getTimeoutMs() {
56
+ const raw = process.env.NOX_RERANKER_TIMEOUT_MS;
57
+ if (!raw)
58
+ return DEFAULT_TIMEOUT_MS;
59
+ const n = parseInt(raw, 10);
60
+ if (!Number.isFinite(n) || n < 100)
61
+ return DEFAULT_TIMEOUT_MS;
62
+ return n;
63
+ }
64
+ let cachedFn = null;
65
+ let cachedModelName = null;
66
+ let cachedFactoryError = null;
67
+ /**
68
+ * Test hook: injetar uma fn mock pra evitar download do modelo.
69
+ * Em produção, NÃO chamar — `rerank()` carrega lazy via @xenova/transformers.
70
+ *
71
+ * Quando fn=null + reset=true (default), limpa singleton + cached error.
72
+ * Use reset=false só pra cenários onde você quer preservar erro cacheado.
73
+ */
74
+ export function __setRerankerFnForTesting(fn, reset = true) {
75
+ cachedFn = fn;
76
+ if (reset || fn !== null) {
77
+ cachedFactoryError = null;
78
+ }
79
+ cachedModelName = fn ? "__test__" : null;
80
+ }
81
+ /**
82
+ * Lazy-load do modelo. First call paga ~2-4s de cold start (ONNX bind).
83
+ * Subsequent calls reusam singleton. Fail-open: se carga falha, cacheia error
84
+ * pra evitar retry-storm.
85
+ */
86
+ async function getRerankerFn() {
87
+ const wantedModel = getModelName();
88
+ // Test injection bypass: __test__ marker overrides model match check.
89
+ if (cachedFn && (cachedModelName === "__test__" || cachedModelName === wantedModel))
90
+ return cachedFn;
91
+ if (cachedFactoryError)
92
+ throw cachedFactoryError;
93
+ try {
94
+ // Dynamic import: Node ESM, evita carga em paths off-mode.
95
+ const t = await import("@xenova/transformers");
96
+ // BGE-reranker-base é cross-encoder. xenova text-classification pipeline NÃO
97
+ // suporta text_pair (passa pares como string única → tokenizer ignora pair).
98
+ // Usar API low-level: AutoTokenizer + AutoModelForSequenceClassification com
99
+ // tokenize batch de pares (queries + docs) → logits.
100
+ // Quantized=true reduz disk de ~430MB → ~85MB sem perda significativa.
101
+ const tokenizer = await t.AutoTokenizer.from_pretrained(wantedModel);
102
+ const model = await t.AutoModelForSequenceClassification.from_pretrained(wantedModel, {
103
+ quantized: true,
104
+ });
105
+ const fn = async (pairs) => {
106
+ if (pairs.length === 0)
107
+ return [];
108
+ const queries = pairs.map((p) => p.text);
109
+ const docs = pairs.map((p) => p.text_pair);
110
+ const encoded = await tokenizer(queries, {
111
+ text_pair: docs,
112
+ padding: true,
113
+ truncation: true,
114
+ });
115
+ const out = await model(encoded);
116
+ // out.logits.dims = [batch, 1]; data = Float32Array
117
+ const data = Array.from(out.logits.data);
118
+ // Sigmoid-like normalize não obrigatório (sort desc por logit funciona).
119
+ // Mantemos raw logits — sort desc preserva ordem correta.
120
+ return data.map((s) => ({ score: s }));
121
+ };
122
+ cachedFn = fn;
123
+ cachedModelName = wantedModel;
124
+ return fn;
125
+ }
126
+ catch (e) {
127
+ cachedFactoryError = e instanceof Error ? e : new Error(String(e));
128
+ throw cachedFactoryError;
129
+ }
130
+ }
131
+ /**
132
+ * Pre-warm o singleton do modelo. Chamado pelo nox-mem-api boot quando
133
+ * NOX_RERANKER_MODE != off, pra evitar cold-start de ~12-90s no primeiro
134
+ * search request (D01 spec §risks §1). Idempotente: subsequent calls são no-op.
135
+ */
136
+ export async function preloadModel() {
137
+ await getRerankerFn();
138
+ }
139
+ // ─── Helpers: telemetry math (pure, testable) ────────────────────────────────
140
+ /**
141
+ * Conta chunks que mudaram posição entre os top-K original e o pós-rerank.
142
+ * Trabalha por id (campo opcional). Chunks sem id são ignorados (não rastreáveis).
143
+ */
144
+ export function computePositionChanges(origTopK, newTopK) {
145
+ const origPos = new Map();
146
+ const newPos = new Map();
147
+ origTopK.forEach((c, i) => {
148
+ if (typeof c.id === "number")
149
+ origPos.set(c.id, i);
150
+ });
151
+ newTopK.forEach((c, i) => {
152
+ if (typeof c.id === "number")
153
+ newPos.set(c.id, i);
154
+ });
155
+ const allIds = new Set([...origPos.keys(), ...newPos.keys()]);
156
+ let changes = 0;
157
+ for (const id of allIds) {
158
+ const a = origPos.get(id);
159
+ const b = newPos.get(id);
160
+ if (a === undefined || b === undefined) {
161
+ // chunk entrou ou saiu do top-K → mudança
162
+ changes++;
163
+ }
164
+ else if (a !== b) {
165
+ changes++;
166
+ }
167
+ }
168
+ return changes;
169
+ }
170
+ /**
171
+ * Lift score: mean displacement normalizado em [0, 1].
172
+ *
173
+ * Combina dois sinais:
174
+ * 1) displacement intra-intersection: |orig_pos − new_pos| pra ids em ambos
175
+ * 2) turnover (set churn): id que entrou OU saiu conta como displacement = K
176
+ *
177
+ * Total = sum(deltas) / (count * K), onde K = max(|orig|, |new|).
178
+ *
179
+ * Edge cases:
180
+ * - sets disjoint → todos turnover, score = 1
181
+ * - identical → 0
182
+ * - swap top-2 (K=5) → 2 ids movem 1 cada → 2/(5*4) = 0.1
183
+ */
184
+ export function computeLiftScore(origTopK, newTopK) {
185
+ if (origTopK.length === 0 || newTopK.length === 0)
186
+ return 0;
187
+ const k = Math.max(origTopK.length, newTopK.length);
188
+ if (k <= 1)
189
+ return 0;
190
+ const origPos = new Map();
191
+ const newPos = new Map();
192
+ origTopK.forEach((c, i) => {
193
+ if (typeof c.id === "number")
194
+ origPos.set(c.id, i);
195
+ });
196
+ newTopK.forEach((c, i) => {
197
+ if (typeof c.id === "number")
198
+ newPos.set(c.id, i);
199
+ });
200
+ const allIds = new Set([...origPos.keys(), ...newPos.keys()]);
201
+ if (allIds.size === 0)
202
+ return 0;
203
+ let sumDelta = 0;
204
+ for (const id of allIds) {
205
+ const a = origPos.get(id);
206
+ const b = newPos.get(id);
207
+ if (a === undefined || b === undefined) {
208
+ // turnover: id entrou ou saiu → trata como displacement máximo (k)
209
+ sumDelta += k;
210
+ }
211
+ else {
212
+ sumDelta += Math.abs(a - b);
213
+ }
214
+ }
215
+ // Normalize: max possible = allIds.size * k (all turned over)
216
+ const norm = sumDelta / (allIds.size * k);
217
+ return Math.min(1, Math.max(0, norm));
218
+ }
219
+ // ─── Core rerank function ────────────────────────────────────────────────────
220
+ /**
221
+ * Rerank candidates via cross-encoder. Comportamento per mode:
222
+ *
223
+ * - off: no-op, retorna candidates.slice(0, topK), summary mode='off'
224
+ * - shadow: roda reranker, calcula lift, retorna candidates ORIGINAIS top-K
225
+ * (não muta ranking — caller recebe ordem pre-rerank)
226
+ * - active: roda reranker, retorna pós-rerank top-K (muta ranking)
227
+ *
228
+ * Fail-open: qualquer erro (model load, timeout, ONNX crash) → retorna
229
+ * candidates.slice(0, topK) original com summary.failed=true. Não joga.
230
+ */
231
+ export async function rerank(query, candidates, topKOut) {
232
+ const mode = getMode();
233
+ const kIn = getTopKIn();
234
+ const kOut = topKOut ?? getTopKOut();
235
+ const t0 = Date.now();
236
+ const summaryBase = (overrides = {}) => ({
237
+ mode,
238
+ topKIn: 0,
239
+ topKOut: 0,
240
+ latencyMs: 0,
241
+ positionChanges: 0,
242
+ liftScore: 0,
243
+ failed: false,
244
+ ...overrides,
245
+ });
246
+ // off-mode: bypass total
247
+ if (mode === "off") {
248
+ return {
249
+ results: candidates.slice(0, kOut),
250
+ summary: summaryBase({ topKOut: Math.min(candidates.length, kOut) }),
251
+ };
252
+ }
253
+ // empty / single candidate: nothing to rerank
254
+ if (candidates.length <= 1 || !query || query.trim().length === 0) {
255
+ return {
256
+ results: candidates.slice(0, kOut),
257
+ summary: summaryBase({ topKOut: Math.min(candidates.length, kOut), latencyMs: Date.now() - t0 }),
258
+ };
259
+ }
260
+ const slice = candidates.slice(0, kIn);
261
+ const origTopK = candidates.slice(0, kOut);
262
+ let scored;
263
+ try {
264
+ const fn = await getRerankerFn();
265
+ const pairs = slice.map((c) => ({
266
+ text: query,
267
+ text_pair: (c.chunk_text || "").slice(0, 4000), // safety truncate (model max 512 tokens)
268
+ }));
269
+ const timeoutMs = getTimeoutMs();
270
+ // Race contra timeout
271
+ const rerankPromise = fn(pairs);
272
+ const timer = new Promise((_, reject) => setTimeout(() => reject(new Error(`reranker timeout after ${timeoutMs}ms`)), timeoutMs));
273
+ const scores = await Promise.race([rerankPromise, timer]);
274
+ if (!Array.isArray(scores) || scores.length !== slice.length) {
275
+ throw new Error(`reranker returned ${Array.isArray(scores) ? scores.length : "non-array"} scores for ${slice.length} pairs`);
276
+ }
277
+ scored = slice.map((c, i) => ({ candidate: c, score: scores[i].score }));
278
+ }
279
+ catch (e) {
280
+ const msg = e?.message || String(e);
281
+ if (process.env.NOX_RERANKER_LOG === "1") {
282
+ logRerank(query, mode, kIn, kOut, Date.now() - t0, 0, 0, true, msg);
283
+ }
284
+ return {
285
+ results: origTopK,
286
+ summary: summaryBase({
287
+ topKIn: slice.length,
288
+ topKOut: origTopK.length,
289
+ latencyMs: Date.now() - t0,
290
+ failed: true,
291
+ failureReason: msg.slice(0, 200),
292
+ }),
293
+ };
294
+ }
295
+ // Sort by reranker score desc
296
+ scored.sort((a, b) => b.score - a.score);
297
+ const newTopK = scored.slice(0, kOut).map((s) => s.candidate);
298
+ const positionChanges = computePositionChanges(origTopK, newTopK);
299
+ const liftScore = computeLiftScore(origTopK, newTopK);
300
+ const latencyMs = Date.now() - t0;
301
+ if (process.env.NOX_RERANKER_LOG === "1") {
302
+ logRerank(query, mode, kIn, kOut, latencyMs, positionChanges, liftScore, false);
303
+ }
304
+ const summary = summaryBase({
305
+ topKIn: slice.length,
306
+ topKOut: kOut,
307
+ latencyMs,
308
+ positionChanges,
309
+ liftScore,
310
+ failed: false,
311
+ });
312
+ // mode=shadow: NÃO muta resultado retornado (ranking original)
313
+ // mode=active: substitui pelo rerank
314
+ return {
315
+ results: mode === "active" ? newTopK : origTopK,
316
+ summary,
317
+ };
318
+ }
319
+ function logRerank(query, mode, kIn, kOut, latencyMs, positionChanges, liftScore, failed, failureReason) {
320
+ const safeQuery = (query || "").replace(/[\r\n"]/g, " ").slice(0, 80);
321
+ const tag = mode === "active" ? "rerank-active" : mode === "shadow" ? "rerank-shadow" : "rerank-off";
322
+ const status = failed ? `FAILED reason="${(failureReason || "").slice(0, 120)}"` : "ok";
323
+ console.error(`[${tag}] query="${safeQuery}" kIn=${kIn} kOut=${kOut} lat=${latencyMs}ms changes=${positionChanges} lift=${liftScore.toFixed(3)} ${status}`);
324
+ }
@@ -0,0 +1,191 @@
1
+ /**
2
+ * shadow-tracker.ts — F10 Phase D shadow tracker
3
+ *
4
+ * Records side-by-side comparisons between a baseline ranker and a shadow
5
+ * (candidate) ranker for the same query. Used to validate ranking changes
6
+ * BEFORE flipping the active path (per memory [[shadow-mode-for-ranking-changes]]).
7
+ *
8
+ * Data flow:
9
+ * 1. `recordShadowComparison(feature, query, baseline, shadow, metrics)` is
10
+ * called from the search hot-path (post-result, before response write).
11
+ * 2. The collector computes a delta_pct from the supplied scalar metric
12
+ * (or, when result-sets are passed without scalar metrics, from a
13
+ * rank-difference fallback).
14
+ * 3. The event is stored in BOTH:
15
+ * a) an in-memory 24h × 1h ring buffer keyed by feature, used by the
16
+ * dashboard endpoint for fast aggregation.
17
+ * b) the `shadow_runs` SQLite table for long-tail audit (append-only).
18
+ *
19
+ * Design principles:
20
+ * - Pattern mirrors `telemetry-collector.ts` from Phase C: synchronous, no
21
+ * external deps, ring-buffer eviction lazy on record().
22
+ * - Persistence is best-effort: a DB write failure logs to stderr but does
23
+ * NOT throw, so the search hot-path is never broken by observability.
24
+ * - SQLite handle is injected (not import-time singleton), so tests use
25
+ * in-memory DBs and prod uses the shared connection from db.ts.
26
+ *
27
+ * Spec: docs/ROADMAP.md F10 Phase D
28
+ * Cross-link: src/lib/shadow-tracker-schema.sql, api-server.shadow-wire-up.md
29
+ */
30
+ /** A single ranking result row. Shape is intentionally loose — the tracker only
31
+ * uses `id` (for rank-diff) and ignores the rest. */
32
+ export interface ResultRow {
33
+ id: string | number;
34
+ score?: number;
35
+ [k: string]: unknown;
36
+ }
37
+ export type ResultSet = ResultRow[];
38
+ export interface ShadowComparison {
39
+ /** Epoch ms when the comparison was recorded */
40
+ ts: number;
41
+ /** Feature name (e.g. "temporal-spike-v2", "salience-v2") */
42
+ feature: string;
43
+ /** Privacy-preserving hash of the query text */
44
+ query_hash: string;
45
+ /** Scalar metric for baseline (nullable: caller may only supply IDs) */
46
+ baseline_value: number | null;
47
+ /** Scalar metric for shadow */
48
+ shadow_value: number | null;
49
+ /** (shadow - baseline) / baseline * 100; null if baseline is 0 or null */
50
+ delta_pct: number | null;
51
+ /** Arbitrary per-feature payload (parsed JSON or raw object) */
52
+ metadata: Record<string, unknown>;
53
+ }
54
+ export interface ShadowFeatureBucket {
55
+ /** Start of this 1h bucket (epoch ms, floored to the hour) */
56
+ hour_ts: number;
57
+ label: string;
58
+ count: number;
59
+ sum_delta_pct: number;
60
+ sum_delta_sq: number;
61
+ win_count: number;
62
+ regression_count: number;
63
+ neutral_count: number;
64
+ }
65
+ export interface ShadowAggregate {
66
+ feature: string;
67
+ count: number;
68
+ win_count: number;
69
+ regression_count: number;
70
+ neutral_count: number;
71
+ mean_delta_pct: number | null;
72
+ std_dev: number | null;
73
+ buckets: ShadowFeatureBucket[];
74
+ }
75
+ export interface ShadowResponse {
76
+ window: {
77
+ hours: number;
78
+ bucket_size_hours: number;
79
+ from_ts: number;
80
+ to_ts: number;
81
+ };
82
+ /** When ?feature=<name> was passed, this is a single-element array. */
83
+ features: ShadowAggregate[];
84
+ /** Latest N comparisons for drill-down (only when ?feature=<name> is set) */
85
+ latest_runs: ShadowComparison[];
86
+ generated_at_ms: number;
87
+ }
88
+ /** Minimal SQLite handle shape (better-sqlite3-compatible). Kept loose for testability. */
89
+ export interface ShadowDB {
90
+ prepare(sql: string): {
91
+ run(...params: unknown[]): {
92
+ lastInsertRowid?: number | bigint;
93
+ };
94
+ all(...params: unknown[]): unknown[];
95
+ get(...params: unknown[]): unknown;
96
+ };
97
+ exec(sql: string): void;
98
+ }
99
+ /** Stable SHA-256 (truncated) of the query string. Privacy-preserving (no
100
+ * way to recover the query text from the hash). */
101
+ export declare function hashQuery(query: string): string;
102
+ declare function hourFloor(ts: number): number;
103
+ declare function hourLabel(ts: number): string;
104
+ declare function emptyBucket(hour_ts: number): ShadowFeatureBucket;
105
+ /** Compute (shadow - baseline) / baseline * 100. Returns null when baseline is
106
+ * zero, null, or undefined. */
107
+ export declare function computeDeltaPct(baseline: number | null | undefined, shadow: number | null | undefined): number | null;
108
+ /** Fallback delta when the caller did not supply a scalar metric: compute
109
+ * Kendall-style rank-difference normalised to [-100, +100] where positive
110
+ * means shadow promoted more of the baseline's top results. */
111
+ export declare function rankDifferenceDelta(baseline: ResultSet, shadow: ResultSet): number;
112
+ export declare class ShadowTracker {
113
+ /** Ring buffer: Map<feature, Map<hour_ts, ShadowFeatureBucket>> */
114
+ private buckets;
115
+ /** Per-feature ring of latest comparisons for drill-down. */
116
+ private latest;
117
+ /** Optional DB handle for append-only persistence. */
118
+ private db;
119
+ /** Cumulative count of skipped DB writes (failure or no-handle). Exposed for ops visibility. */
120
+ private skippedPersist;
121
+ constructor(db?: ShadowDB | null);
122
+ /** Inject or replace the DB handle (used by tests + lazy wire-up). */
123
+ setDB(db: ShadowDB | null): void;
124
+ /**
125
+ * Record a shadow comparison.
126
+ *
127
+ * @param feature Feature name. Required, non-empty.
128
+ * @param query Query text (will be hashed, not stored verbatim).
129
+ * @param baseline Baseline result-set (used for rank-diff fallback).
130
+ * @param shadow Shadow result-set (used for rank-diff fallback).
131
+ * @param metrics Optional scalar metrics. If `metric_name` is set, the
132
+ * corresponding `baseline`/`shadow` keys drive delta_pct.
133
+ * Otherwise delta_pct falls back to rank-difference.
134
+ * @param nowMs Override of `Date.now()` for tests.
135
+ */
136
+ recordShadowComparison(feature: string, query: string, baseline: ResultSet, shadow: ResultSet, metrics?: Record<string, number | string>, nowMs?: number): ShadowComparison;
137
+ /** Update the per-feature ring buffer + roll old buckets. */
138
+ private _updateRingBuffer;
139
+ private _updateLatestRing;
140
+ private _evict;
141
+ /** Best-effort SQLite persistence. Never throws — failures bump skippedPersist. */
142
+ private _persist;
143
+ /**
144
+ * Aggregate shadow stats for the dashboard endpoint.
145
+ *
146
+ * @param featureFilter When set, returns only that feature (+ latest_runs).
147
+ * @param windowHours 1..24
148
+ * @param nowMs Override "now" for tests.
149
+ */
150
+ query(featureFilter?: string | null, windowHours?: number, nowMs?: number): ShadowResponse;
151
+ /** Exposed for tests. */
152
+ _reset(): void;
153
+ /** Exposed for ops visibility. */
154
+ getSkippedPersistCount(): number;
155
+ /** Exposed for tests — number of features currently held. */
156
+ _featureCount(): number;
157
+ }
158
+ /** Module-scope singleton consumed by api-server.ts wire-up. Tests use
159
+ * fresh instances or call `_reset()` between cases. */
160
+ export declare const tracker: ShadowTracker;
161
+ /**
162
+ * Hot-path API: record one shadow comparison. Mirrors `recordRequest` shape
163
+ * from the Phase C telemetry collector.
164
+ *
165
+ * @param feature Feature name (required).
166
+ * @param query Query text (will be hashed).
167
+ * @param baseline Baseline result-set.
168
+ * @param shadow Shadow result-set.
169
+ * @param metrics Optional scalar metrics: pass `{ baseline, shadow }` to use
170
+ * scalar delta; omit to fall back to rank-diff.
171
+ */
172
+ export declare function recordShadowComparison(feature: string, query: string, baseline: ResultSet, shadow: ResultSet, metrics?: Record<string, number | string>): ShadowComparison;
173
+ /**
174
+ * Handler for GET /api/observability/shadow.
175
+ * Query params:
176
+ * feature (optional) Filter to a single feature name.
177
+ * window (default 24h) Hours to include (1..24).
178
+ * bucket (default 1h) Reserved for future sub-hour buckets.
179
+ */
180
+ export declare function handleObsShadow(params: Record<string, string>): ShadowResponse;
181
+ /** Parse "24h"/"6h"/"12" → integer hours clamped to [1, 24]. */
182
+ export declare function parseWindowParam(raw: string): number;
183
+ export declare const _internals: {
184
+ BUCKET_SIZE_MS: number;
185
+ MAX_BUCKETS: number;
186
+ MAX_LATEST_PER_FEATURE: number;
187
+ hourFloor: typeof hourFloor;
188
+ hourLabel: typeof hourLabel;
189
+ emptyBucket: typeof emptyBucket;
190
+ };
191
+ export {};