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
package/dist/lib/eval.js DELETED
@@ -1,343 +0,0 @@
1
- // R01a — Eval Harness orchestration.
2
- // Spec: specs/2026-04-27-R01a-eval-harness.md
3
- //
4
- // init: ensures schema (delegated to ensureSchema in db.ts)
5
- // importGolden: read JSONL, INSERT OR IGNORE
6
- // runEval: execute search() per query, compute metrics, persist run + results
7
- // compareRuns: diff two runs side-by-side
8
- // listRuns: tail recent runs
9
- import { readFileSync, mkdirSync, existsSync, writeFileSync } from "node:fs";
10
- import { join } from "node:path";
11
- import { execSync } from "node:child_process";
12
- import { getDb } from "../db.js";
13
- import { searchHybrid, search as ftsSearch, searchSemantic } from "../search.js";
14
- import { computePerQuery, mean } from "./eval-metrics.js";
15
- const REPORTS_DIR = process.env.NOX_EVAL_REPORTS_DIR ||
16
- join(process.env.OPENCLAW_WORKSPACE || "/root/.openclaw/workspace", "tools/nox-mem/reports/eval");
17
- export function getGitSha() {
18
- try {
19
- return execSync("git rev-parse --short HEAD", { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
20
- }
21
- catch {
22
- return null;
23
- }
24
- }
25
- export function getSchemaVersion(db) {
26
- const row = db.prepare("SELECT value FROM meta WHERE key='schema_version'").get();
27
- return row ? parseInt(row.value, 10) : 0;
28
- }
29
- /**
30
- * Import golden queries from JSONL file. INSERT OR IGNORE on UNIQUE(query).
31
- * Returns { imported, skipped, total_in_db }.
32
- */
33
- export function importGolden(file, addedBy = "human") {
34
- const db = getDb();
35
- const raw = readFileSync(file, "utf8");
36
- const lines = raw.split(/\r?\n/).filter((l) => l.trim().length > 0);
37
- const stmt = db.prepare(`
38
- INSERT OR IGNORE INTO eval_queries
39
- (query, expected_chunk_ids, difficulty, category, added_by, notes)
40
- VALUES (?, ?, ?, ?, ?, ?)
41
- `);
42
- let imported = 0;
43
- let skipped = 0;
44
- for (const line of lines) {
45
- let obj;
46
- try {
47
- obj = JSON.parse(line);
48
- }
49
- catch (e) {
50
- console.error(`[eval] skip malformed line: ${e.message}`);
51
- skipped++;
52
- continue;
53
- }
54
- if (!obj.query || !Array.isArray(obj.expected_chunk_ids)) {
55
- console.error(`[eval] skip invalid shape: ${JSON.stringify(obj).slice(0, 80)}`);
56
- skipped++;
57
- continue;
58
- }
59
- const result = stmt.run(obj.query, JSON.stringify(obj.expected_chunk_ids), obj.difficulty || "medium", obj.category || null, obj.added_by || addedBy, obj.notes || null);
60
- if (result.changes === 1)
61
- imported++;
62
- else
63
- skipped++;
64
- }
65
- const total = db.prepare("SELECT COUNT(*) AS c FROM eval_queries").get().c;
66
- return { imported, skipped, total };
67
- }
68
- /**
69
- * List all golden queries in DB.
70
- */
71
- export function listGolden() {
72
- const db = getDb();
73
- const rows = db.prepare("SELECT id, query, expected_chunk_ids, difficulty, category, notes FROM eval_queries ORDER BY id").all();
74
- return rows.map((r) => ({
75
- id: r.id,
76
- query: r.query,
77
- expected_chunk_ids: JSON.parse(r.expected_chunk_ids),
78
- difficulty: r.difficulty,
79
- category: r.category,
80
- notes: r.notes,
81
- }));
82
- }
83
- /**
84
- * Execute search variant for a query, returning ordered chunk IDs + scores.
85
- * Truncates to top 10 (eval cutoff).
86
- */
87
- async function runVariant(query, variant) {
88
- const limit = 10;
89
- switch (variant) {
90
- case "hybrid":
91
- case "rrf-only":
92
- case "custom": {
93
- const results = await searchHybrid(query, limit);
94
- return {
95
- ids: results.map((r) => r.id ?? -1).filter((x) => x >= 0),
96
- scores: results.map((r) => r.score),
97
- };
98
- }
99
- case "rerank": {
100
- // D01 (2026-05-07): força reranker active TEMPORARIAMENTE pra esta run.
101
- // Permite comparação 3-run hybrid vs hybrid+rerank na mesma corrida sem
102
- // mudar env permanente. Restaura mode anterior pós-call.
103
- const prev = process.env.NOX_RERANKER_MODE;
104
- process.env.NOX_RERANKER_MODE = "active";
105
- try {
106
- const results = await searchHybrid(query, limit);
107
- return {
108
- ids: results.map((r) => r.id ?? -1).filter((x) => x >= 0),
109
- scores: results.map((r) => r.score),
110
- };
111
- }
112
- finally {
113
- if (prev === undefined)
114
- delete process.env.NOX_RERANKER_MODE;
115
- else
116
- process.env.NOX_RERANKER_MODE = prev;
117
- }
118
- }
119
- case "fts": {
120
- const results = ftsSearch(query, limit);
121
- return {
122
- ids: results.map((r) => r.id ?? -1).filter((x) => x >= 0),
123
- scores: results.map((r) => r.score),
124
- };
125
- }
126
- case "vector": {
127
- const results = await searchSemantic(query, limit);
128
- return {
129
- ids: results.map((r) => r.id ?? -1).filter((x) => x >= 0),
130
- scores: results.map((r) => r.score),
131
- };
132
- }
133
- default:
134
- throw new Error(`unknown variant: ${variant}`);
135
- }
136
- }
137
- /**
138
- * Run eval over all golden queries with given variant.
139
- * Persists eval_runs + eval_results, exports JSONL, returns summary.
140
- */
141
- export async function runEval(opts = {}) {
142
- const variant = opts.variant || "hybrid";
143
- const db = getDb();
144
- const golden = listGolden();
145
- if (golden.length === 0) {
146
- throw new Error("no golden queries — run `eval golden import <file>` first");
147
- }
148
- const t0 = Date.now();
149
- const perQuery = [];
150
- for (const q of golden) {
151
- const tq = Date.now();
152
- const { ids, scores } = await runVariant(q.query, variant);
153
- const m = computePerQuery(ids, new Set(q.expected_chunk_ids));
154
- perQuery.push({ q, m, ids, scores, duration_ms: Date.now() - tq });
155
- }
156
- const totalDurationMs = Date.now() - t0;
157
- const aggregate = {
158
- ndcg_at_10: mean(perQuery.map((p) => p.m.ndcg_at_10)),
159
- mrr: mean(perQuery.map((p) => p.m.mrr)),
160
- recall_at_10: mean(perQuery.map((p) => p.m.recall_at_10)),
161
- precision_at_5: mean(perQuery.map((p) => p.m.precision_at_5)),
162
- };
163
- // INSERT eval_run + eval_results (transaction)
164
- const gitSha = opts.gitSha || getGitSha();
165
- const schemaV = getSchemaVersion(db);
166
- const insertRun = db.prepare(`
167
- INSERT INTO eval_runs (variant, git_sha, schema_version, query_count, total_duration_ms, notes)
168
- VALUES (?, ?, ?, ?, ?, ?)
169
- `);
170
- const insertResult = db.prepare(`
171
- INSERT INTO eval_results
172
- (run_id, query_id, retrieved_chunk_ids, retrieved_scores, ndcg_at_10, mrr, recall_at_10, precision_at_5, duration_ms)
173
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
174
- `);
175
- const tx = db.transaction(() => {
176
- const r = insertRun.run(variant, gitSha, schemaV, golden.length, totalDurationMs, opts.notes || null);
177
- const runId = Number(r.lastInsertRowid);
178
- for (const p of perQuery) {
179
- insertResult.run(runId, p.q.id, JSON.stringify(p.ids), JSON.stringify(p.scores), p.m.ndcg_at_10, p.m.mrr, p.m.recall_at_10, p.m.precision_at_5, p.duration_ms);
180
- }
181
- return runId;
182
- });
183
- const runId = tx();
184
- const ranAt = db.prepare("SELECT ran_at FROM eval_runs WHERE id=?").get(runId).ran_at;
185
- // By difficulty / category aggregates
186
- const byDifficulty = {};
187
- const byCategory = {};
188
- for (const p of perQuery) {
189
- const d = p.q.difficulty || "medium";
190
- if (!byDifficulty[d])
191
- byDifficulty[d] = { ndcgs: [], mrrs: [], recalls: [], precs: [] };
192
- byDifficulty[d].ndcgs.push(p.m.ndcg_at_10);
193
- byDifficulty[d].mrrs.push(p.m.mrr);
194
- byDifficulty[d].recalls.push(p.m.recall_at_10);
195
- byDifficulty[d].precs.push(p.m.precision_at_5);
196
- const c = p.q.category || "uncategorized";
197
- if (!byCategory[c])
198
- byCategory[c] = { ndcgs: [], mrrs: [], recalls: [], precs: [] };
199
- byCategory[c].ndcgs.push(p.m.ndcg_at_10);
200
- byCategory[c].mrrs.push(p.m.mrr);
201
- byCategory[c].recalls.push(p.m.recall_at_10);
202
- byCategory[c].precs.push(p.m.precision_at_5);
203
- }
204
- const collapseAgg = (raw) => ({
205
- ndcg_at_10: mean(raw.ndcgs),
206
- mrr: mean(raw.mrrs),
207
- recall_at_10: mean(raw.recalls),
208
- precision_at_5: mean(raw.precs),
209
- n: raw.ndcgs.length,
210
- });
211
- const byDifficultyOut = {};
212
- for (const k of Object.keys(byDifficulty))
213
- byDifficultyOut[k] = collapseAgg(byDifficulty[k]);
214
- const byCategoryOut = {};
215
- for (const k of Object.keys(byCategory))
216
- byCategoryOut[k] = collapseAgg(byCategory[k]);
217
- // Delta vs previous run of SAME variant
218
- const prev = db.prepare(`
219
- SELECT id FROM eval_runs WHERE variant=? AND id < ? ORDER BY id DESC LIMIT 1
220
- `).get(variant, runId);
221
- let delta = null;
222
- if (prev) {
223
- const prevAgg = aggregateForRun(prev.id);
224
- if (prevAgg) {
225
- delta = {
226
- ndcg_at_10: aggregate.ndcg_at_10 - prevAgg.ndcg_at_10,
227
- mrr: aggregate.mrr - prevAgg.mrr,
228
- recall_at_10: aggregate.recall_at_10 - prevAgg.recall_at_10,
229
- precision_at_5: aggregate.precision_at_5 - prevAgg.precision_at_5,
230
- };
231
- }
232
- }
233
- // JSONL export
234
- const reportsDir = opts.reportsDir || REPORTS_DIR;
235
- if (!existsSync(reportsDir))
236
- mkdirSync(reportsDir, { recursive: true, mode: 0o755 });
237
- const jsonlPath = join(reportsDir, `${runId}-${variant}-${ranAt.replace(/[:.]/g, "-")}.jsonl`);
238
- const jsonlLines = [];
239
- jsonlLines.push(JSON.stringify({
240
- type: "run_meta", run_id: runId, variant, ran_at: ranAt, git_sha: gitSha,
241
- schema_version: schemaV, query_count: golden.length, total_duration_ms: totalDurationMs,
242
- notes: opts.notes || null, aggregate,
243
- }));
244
- for (const p of perQuery) {
245
- jsonlLines.push(JSON.stringify({
246
- type: "result", run_id: runId, query_id: p.q.id, query: p.q.query,
247
- difficulty: p.q.difficulty, category: p.q.category,
248
- retrieved_chunk_ids: p.ids, retrieved_scores: p.scores,
249
- expected_chunk_ids: p.q.expected_chunk_ids,
250
- metrics: p.m, duration_ms: p.duration_ms,
251
- }));
252
- }
253
- writeFileSync(jsonlPath, jsonlLines.join("\n") + "\n", { mode: 0o644 });
254
- return {
255
- run_id: runId,
256
- variant,
257
- ran_at: ranAt,
258
- git_sha: gitSha,
259
- query_count: golden.length,
260
- total_duration_ms: totalDurationMs,
261
- aggregate,
262
- byDifficulty: byDifficultyOut,
263
- byCategory: byCategoryOut,
264
- jsonlPath,
265
- prevRunId: prev?.id ?? null,
266
- delta,
267
- };
268
- }
269
- /**
270
- * Compute aggregate for a given run from eval_results table.
271
- */
272
- export function aggregateForRun(runId) {
273
- const db = getDb();
274
- const rows = db.prepare(`
275
- SELECT ndcg_at_10, mrr, recall_at_10, precision_at_5 FROM eval_results WHERE run_id=?
276
- `).all(runId);
277
- if (rows.length === 0)
278
- return null;
279
- return {
280
- ndcg_at_10: mean(rows.map((r) => r.ndcg_at_10)),
281
- mrr: mean(rows.map((r) => r.mrr)),
282
- recall_at_10: mean(rows.map((r) => r.recall_at_10)),
283
- precision_at_5: mean(rows.map((r) => r.precision_at_5)),
284
- };
285
- }
286
- /**
287
- * List recent runs, optionally filtered by variant.
288
- */
289
- export function listRuns(variant, limit = 10) {
290
- const db = getDb();
291
- const sql = variant
292
- ? "SELECT * FROM eval_runs WHERE variant=? ORDER BY id DESC LIMIT ?"
293
- : "SELECT * FROM eval_runs ORDER BY id DESC LIMIT ?";
294
- return (variant ? db.prepare(sql).all(variant, limit) : db.prepare(sql).all(limit));
295
- }
296
- /**
297
- * Compare two runs query-by-query. Returns sorted by delta (regressions first).
298
- */
299
- export function compareRuns(runIdA, runIdB) {
300
- const db = getDb();
301
- const rows = db.prepare(`
302
- SELECT
303
- q.id AS query_id, q.query AS query,
304
- a.ndcg_at_10 AS a_ndcg, b.ndcg_at_10 AS b_ndcg
305
- FROM eval_queries q
306
- JOIN eval_results a ON a.query_id = q.id AND a.run_id = ?
307
- JOIN eval_results b ON b.query_id = q.id AND b.run_id = ?
308
- `).all(runIdA, runIdB);
309
- const all = rows.map((r) => ({ ...r, delta: r.b_ndcg - r.a_ndcg }));
310
- const regressions = all.filter((r) => r.delta < -0.01).sort((x, y) => x.delta - y.delta);
311
- const improvements = all.filter((r) => r.delta > 0.01).sort((x, y) => y.delta - x.delta);
312
- return {
313
- regressions,
314
- improvements,
315
- aggregate_a: aggregateForRun(runIdA),
316
- aggregate_b: aggregateForRun(runIdB),
317
- };
318
- }
319
- /**
320
- * Get latest run per variant for /api/health.evalMetrics surface.
321
- */
322
- export function getEvalMetricsSnapshot() {
323
- const db = getDb();
324
- const lastRow = db.prepare("SELECT * FROM eval_runs ORDER BY id DESC LIMIT 1").get();
325
- let lastRun = null;
326
- if (lastRow) {
327
- const agg = aggregateForRun(lastRow.id);
328
- if (agg)
329
- lastRun = { ...lastRow, ...agg };
330
- }
331
- const variants = db.prepare("SELECT DISTINCT variant FROM eval_runs").all();
332
- const byVariant = {};
333
- for (const { variant } of variants) {
334
- const row = db.prepare("SELECT id, ran_at FROM eval_runs WHERE variant=? ORDER BY id DESC LIMIT 1").get(variant);
335
- if (!row)
336
- continue;
337
- const agg = aggregateForRun(row.id);
338
- if (!agg)
339
- continue;
340
- byVariant[variant] = { ndcg_at_10: agg.ndcg_at_10, ran_at: row.ran_at, run_id: row.id };
341
- }
342
- return { lastRun, byVariant };
343
- }
@@ -1,135 +0,0 @@
1
- /**
2
- * P5a — Internal Event Bus
3
- * Singleton EventEmitter for nox-mem-api internal observability.
4
- * Used as SSE feed prerequisite for P5 viewer.
5
- *
6
- * Design constraints:
7
- * - Never blocks caller — all emits are fire-forget via setImmediate
8
- * - No external dependencies — Node native events.EventEmitter only
9
- * - Max listeners: 50 (SSE clients + internal subscribers)
10
- * - Sub-millisecond overhead per emit (benchmarked in tests)
11
- */
12
- import { EventEmitter } from "events";
13
- export declare const EventKind: {
14
- readonly CHUNK_CREATED: "chunk.created";
15
- readonly CHUNK_DELETED: "chunk.deleted";
16
- readonly KG_ENTITY_CREATED: "kg.entity.created";
17
- readonly KG_RELATION_CREATED: "kg.relation.created";
18
- readonly SEARCH_EXECUTED: "search.executed";
19
- readonly PROVIDER_CALL: "provider.call";
20
- readonly OP_AUDIT_STARTED: "op_audit.started";
21
- readonly OP_AUDIT_COMPLETED: "op_audit.completed";
22
- readonly HEALTH_WARNING: "health.warning";
23
- };
24
- export type EventKindValue = (typeof EventKind)[keyof typeof EventKind];
25
- export interface ChunkCreatedPayload {
26
- chunk_id: number;
27
- source_file?: string;
28
- type?: string;
29
- section?: string;
30
- token_count?: number;
31
- ts: number;
32
- }
33
- export interface ChunkDeletedPayload {
34
- chunk_id: number;
35
- ts: number;
36
- }
37
- export interface KgEntityCreatedPayload {
38
- entity_id: number;
39
- name: string;
40
- entity_type: string;
41
- ts: number;
42
- }
43
- export interface KgRelationCreatedPayload {
44
- relation_id: number;
45
- source_entity_id: number;
46
- target_entity_id: number;
47
- relation_type: string;
48
- ts: number;
49
- }
50
- export interface SearchExecutedPayload {
51
- query_hash: string;
52
- latency_ms: number;
53
- top_k: number;
54
- result_count: number;
55
- mode?: "hybrid" | "fts" | "vector";
56
- ts: number;
57
- }
58
- export interface ProviderCallPayload {
59
- provider: string;
60
- op_type: "embed" | "complete" | "extract";
61
- latency_ms: number;
62
- cost_usd?: number;
63
- model?: string;
64
- token_count?: number;
65
- ts: number;
66
- }
67
- export interface OpAuditStartedPayload {
68
- op_id: number;
69
- op_type: string;
70
- ts: number;
71
- }
72
- export interface OpAuditCompletedPayload {
73
- op_id: number;
74
- op_type: string;
75
- status: "success" | "failed" | "crashed";
76
- duration_ms: number;
77
- ts: number;
78
- }
79
- export interface HealthWarningPayload {
80
- code: string;
81
- message: string;
82
- severity: "warn" | "critical";
83
- context?: Record<string, unknown>;
84
- ts: number;
85
- }
86
- export type EventPayloadMap = {
87
- [EventKind.CHUNK_CREATED]: ChunkCreatedPayload;
88
- [EventKind.CHUNK_DELETED]: ChunkDeletedPayload;
89
- [EventKind.KG_ENTITY_CREATED]: KgEntityCreatedPayload;
90
- [EventKind.KG_RELATION_CREATED]: KgRelationCreatedPayload;
91
- [EventKind.SEARCH_EXECUTED]: SearchExecutedPayload;
92
- [EventKind.PROVIDER_CALL]: ProviderCallPayload;
93
- [EventKind.OP_AUDIT_STARTED]: OpAuditStartedPayload;
94
- [EventKind.OP_AUDIT_COMPLETED]: OpAuditCompletedPayload;
95
- [EventKind.HEALTH_WARNING]: HealthWarningPayload;
96
- };
97
- declare class NoxEventBus extends EventEmitter {
98
- constructor();
99
- /**
100
- * Fire-forget emit — schedules listener dispatch via setImmediate.
101
- * NEVER blocks caller. Caller returns before any listener runs.
102
- * Overhead: <1ms per call (just setImmediate scheduling).
103
- */
104
- emitAsync<K extends EventKindValue>(kind: K, data: EventPayloadMap[K]): void;
105
- /**
106
- * Subscribe to a typed event kind.
107
- * Returns unsubscribe function for clean teardown.
108
- */
109
- on<K extends EventKindValue>(kind: K, listener: (data: EventPayloadMap[K]) => void): this;
110
- once<K extends EventKindValue>(kind: K, listener: (data: EventPayloadMap[K]) => void): this;
111
- off<K extends EventKindValue>(kind: K, listener: (data: EventPayloadMap[K]) => void): this;
112
- /**
113
- * Subscribe and return explicit unsubscribe. Preferred for SSE/cleanup paths.
114
- */
115
- subscribe<K extends EventKindValue>(kind: K, listener: (data: EventPayloadMap[K]) => void): () => void;
116
- /**
117
- * Current listener count per kind — for health checks and leak detection.
118
- */
119
- listenerCount(kind: EventKindValue): number;
120
- /**
121
- * Stats for /api/health.eventBus endpoint.
122
- */
123
- stats(): Record<string, number>;
124
- }
125
- export declare const bus: NoxEventBus;
126
- /**
127
- * Convenience wrapper. Prefer `bus.emitAsync()` for explicit intent.
128
- * This alias exists so integration sites can import just `emit`.
129
- *
130
- * Usage:
131
- * import { emit, EventKind } from '../lib/events/bus';
132
- * emit(EventKind.CHUNK_CREATED, { chunk_id: 42, ts: Date.now() });
133
- */
134
- export declare function emit<K extends EventKindValue>(kind: K, data: EventPayloadMap[K]): void;
135
- export {};
@@ -1 +0,0 @@
1
- export declare function extractAnchors(text: string): string;
@@ -1,47 +0,0 @@
1
- /**
2
- * src/lib/hooks/classifier.ts — T4: Layer 4 of pipeline.
3
- *
4
- * Heuristics-first content classifier. Decides if a redacted text chunk
5
- * is "worth capturing" or noise. Cheap regex/length checks before any LLM.
6
- *
7
- * Heuristics (each contributes a small signal):
8
- * - length > NOX_HOOK_MIN_LENGTH (default 20) → +0.25
9
- * - not pure code (no ratio ≥0.8 of /[{};=<>]/) → +0.15
10
- * - not pure URLs (≥50% chars in URL tokens drops to 0)
11
- * - contains noun-phrase markers (capitalized words, common conjunctions) → +0.20
12
- * - contains sentence terminator (. ! ?) → +0.15
13
- * - has lowercase + uppercase mix → +0.10
14
- * - not just whitespace/punctuation → +0.15
15
- *
16
- * Final score in [0, 1]. Decision:
17
- * score < 0.4 → reject (low signal)
18
- * score > 0.6 → accept
19
- * 0.4..0.6 → ambiguous; LLM fallback if NOX_HOOK_LLM_CLASSIFY=1, else
20
- * accept (lean towards capture in ambiguous-mid range)
21
- *
22
- * No content escapes this module; only score + reason.
23
- */
24
- import type { CaptureDecision, HookContext } from "./types.js";
25
- export interface ClassifierOpts {
26
- /** Min chars to even consider capturing. Mirrors config.minLength. */
27
- minLength?: number;
28
- /** Allow LLM fallback for ambiguous (score 0.4..0.6). Default false. */
29
- llmFallback?: boolean;
30
- /**
31
- * Pluggable LLM-classify hook. Called only when score ambiguous AND
32
- * llmFallback=true. Returns {capture, reason}. The pipeline can wire
33
- * this to flash-lite per D41 if desired.
34
- */
35
- llmClassify?: (text: string) => {
36
- capture: boolean;
37
- reason: string;
38
- };
39
- }
40
- /**
41
- * Score a text in isolation. Pure, deterministic, no LLM.
42
- */
43
- export declare function scoreText(text: string, minLength: number): number;
44
- /**
45
- * Apply Layer 4 to a HookContext (uses ctx.redacted.text if present, else event.content).
46
- */
47
- export declare function applyClassifier(ctx: HookContext, opts?: ClassifierOpts): CaptureDecision;
@@ -1,129 +0,0 @@
1
- /**
2
- * src/lib/hooks/classifier.ts — T4: Layer 4 of pipeline.
3
- *
4
- * Heuristics-first content classifier. Decides if a redacted text chunk
5
- * is "worth capturing" or noise. Cheap regex/length checks before any LLM.
6
- *
7
- * Heuristics (each contributes a small signal):
8
- * - length > NOX_HOOK_MIN_LENGTH (default 20) → +0.25
9
- * - not pure code (no ratio ≥0.8 of /[{};=<>]/) → +0.15
10
- * - not pure URLs (≥50% chars in URL tokens drops to 0)
11
- * - contains noun-phrase markers (capitalized words, common conjunctions) → +0.20
12
- * - contains sentence terminator (. ! ?) → +0.15
13
- * - has lowercase + uppercase mix → +0.10
14
- * - not just whitespace/punctuation → +0.15
15
- *
16
- * Final score in [0, 1]. Decision:
17
- * score < 0.4 → reject (low signal)
18
- * score > 0.6 → accept
19
- * 0.4..0.6 → ambiguous; LLM fallback if NOX_HOOK_LLM_CLASSIFY=1, else
20
- * accept (lean towards capture in ambiguous-mid range)
21
- *
22
- * No content escapes this module; only score + reason.
23
- */
24
- const URL_RE = /\bhttps?:\/\/\S+/gi;
25
- const CODE_TOKENS_RE = /[{};=<>()[\]]/g;
26
- const SENTENCE_TERM_RE = /[.!?](\s|$)/;
27
- const NOUN_HINT_RE = /\b[A-Z][a-z]{2,}\b|\b(the|a|an|and|or|but|because|when|if|while|that|this)\b/i;
28
- const WHITESPACE_OR_PUNCT_RE = /^[\s\p{P}]+$/u;
29
- /**
30
- * Score a text in isolation. Pure, deterministic, no LLM.
31
- */
32
- export function scoreText(text, minLength) {
33
- if (text.length < minLength)
34
- return 0;
35
- if (WHITESPACE_OR_PUNCT_RE.test(text))
36
- return 0;
37
- let score = 0;
38
- // Length bonus
39
- score += 0.25;
40
- // URL ratio kills the score
41
- const urlMatches = text.match(URL_RE) ?? [];
42
- const urlChars = urlMatches.reduce((sum, m) => sum + m.length, 0);
43
- if (urlChars / text.length >= 0.5)
44
- return Math.min(score, 0.1);
45
- // Code ratio
46
- const codeChars = (text.match(CODE_TOKENS_RE) ?? []).length;
47
- const codeRatio = codeChars / Math.max(1, text.length);
48
- if (codeRatio >= 0.08) {
49
- // looks like code — heavy penalty
50
- score -= 0.15;
51
- }
52
- else {
53
- score += 0.15;
54
- }
55
- // Noun-phrase / conjunction hint
56
- if (NOUN_HINT_RE.test(text))
57
- score += 0.2;
58
- // Sentence terminator
59
- if (SENTENCE_TERM_RE.test(text))
60
- score += 0.15;
61
- // Mixed case (proxy for natural prose)
62
- if (/[a-z]/.test(text) && /[A-Z]/.test(text))
63
- score += 0.1;
64
- // Has non-whitespace, non-punct chars
65
- if (/\w/.test(text))
66
- score += 0.15;
67
- if (score < 0)
68
- score = 0;
69
- if (score > 1)
70
- score = 1;
71
- return score;
72
- }
73
- /**
74
- * Apply Layer 4 to a HookContext (uses ctx.redacted.text if present, else event.content).
75
- */
76
- export function applyClassifier(ctx, opts = {}) {
77
- const minLength = opts.minLength ?? 20;
78
- const llmFallback = opts.llmFallback ?? false;
79
- const text = ctx.redacted?.text ?? ctx.event.content;
80
- const score = scoreText(text, minLength);
81
- ctx.classification = { score, reason: `heuristic_score=${score.toFixed(2)}` };
82
- if (score < 0.4) {
83
- return {
84
- capture: false,
85
- reason: `low_signal score=${score.toFixed(2)} len=${text.length}`,
86
- layer: "classifier",
87
- score,
88
- };
89
- }
90
- if (score > 0.6) {
91
- return {
92
- capture: true,
93
- reason: `high_signal score=${score.toFixed(2)}`,
94
- layer: "classifier",
95
- score,
96
- };
97
- }
98
- // Ambiguous range 0.4..0.6
99
- if (llmFallback && opts.llmClassify) {
100
- try {
101
- const llm = opts.llmClassify(text);
102
- ctx.classification = {
103
- score,
104
- reason: `llm_fallback decision=${llm.capture ? "yes" : "no"} reason=${llm.reason}`,
105
- };
106
- return {
107
- capture: llm.capture,
108
- reason: `llm_fallback ${llm.reason} (heuristic=${score.toFixed(2)})`,
109
- layer: "classifier",
110
- score,
111
- };
112
- }
113
- catch (e) {
114
- return {
115
- capture: true,
116
- reason: `llm_fallback_failed lean_capture err=${e.message}`,
117
- layer: "classifier",
118
- score,
119
- };
120
- }
121
- }
122
- // Default: ambiguous → lean towards capture (Toto's bias = better recall over precision here)
123
- return {
124
- capture: true,
125
- reason: `ambiguous_lean_capture score=${score.toFixed(2)}`,
126
- layer: "classifier",
127
- score,
128
- };
129
- }