nox-mem 3.1.0 → 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 (398) hide show
  1. package/README.md +24 -16
  2. package/dist/__tests__/brief-diversity.test.js +266 -0
  3. package/dist/__tests__/brief.test.js +287 -0
  4. package/dist/__tests__/churn.test.js +66 -0
  5. package/dist/__tests__/edge-typing.test.js +99 -0
  6. package/dist/__tests__/ingest-event.test.js +151 -0
  7. package/dist/__tests__/op-audit-e2e.test.js +130 -0
  8. package/dist/__tests__/pragma-alignment.test.js +123 -0
  9. package/dist/__tests__/reranker.test.js +326 -0
  10. package/dist/__tests__/retention.test.js +99 -0
  11. package/dist/__tests__/search-track-access.test.js +49 -0
  12. package/dist/__tests__/spo-injection.test.js +172 -0
  13. package/dist/__tests__/temporal-detector.test.js +103 -0
  14. package/dist/api/wire-up.js +12 -381
  15. package/dist/api-server.js +6 -102
  16. package/dist/db.js +61 -2
  17. package/dist/embed.js +23 -2
  18. package/dist/index.js +3 -23
  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/mcp-server.js +2 -1
  39. package/dist/privacy/__tests__/filter.test.js +352 -0
  40. package/dist/providers/__tests__/conformance-extended.test.js +249 -0
  41. package/dist/providers/__tests__/conformance.test.js +98 -0
  42. package/dist/providers/__tests__/cost-cap.test.js +151 -0
  43. package/dist/providers/__tests__/e2e-real.test.js +79 -0
  44. package/dist/providers/__tests__/factory.test.js +80 -0
  45. package/dist/providers/__tests__/fallback.test.js +223 -0
  46. package/dist/providers/__tests__/gemini.test.js +191 -0
  47. package/dist/providers/__tests__/health.test.js +128 -0
  48. package/dist/providers/__tests__/telemetry.test.js +219 -0
  49. package/dist/reindex.js +2 -2
  50. package/dist/version.js +22 -0
  51. package/package.json +3 -4
  52. package/dist/api/answer.d.ts +0 -116
  53. package/dist/api/answer.validate-patch.d.ts +0 -72
  54. package/dist/api/brief-diversity.d.ts +0 -64
  55. package/dist/api/brief.d.ts +0 -114
  56. package/dist/api/conflict.d.ts +0 -33
  57. package/dist/api/conflict.js +0 -143
  58. package/dist/api/cors.d.ts +0 -73
  59. package/dist/api/events-stream-limited.d.ts +0 -133
  60. package/dist/api/events-stream-limited.js +0 -217
  61. package/dist/api/events-stream.d.ts +0 -53
  62. package/dist/api/events-stream.js +0 -125
  63. package/dist/api/export.d.ts +0 -42
  64. package/dist/api/export.js +0 -85
  65. package/dist/api/health-confidence-adapter.d.ts +0 -29
  66. package/dist/api/health-confidence-adapter.js +0 -73
  67. package/dist/api/health-confidence.d.ts +0 -36
  68. package/dist/api/health-confidence.js +0 -141
  69. package/dist/api/hooks.d.ts +0 -50
  70. package/dist/api/hooks.js +0 -115
  71. package/dist/api/import.d.ts +0 -38
  72. package/dist/api/import.js +0 -87
  73. package/dist/api/ingest-event.d.ts +0 -65
  74. package/dist/api/mark.d.ts +0 -42
  75. package/dist/api/mark.js +0 -127
  76. package/dist/api/server-deps-a2.d.ts +0 -55
  77. package/dist/api/server-deps-a2.js +0 -138
  78. package/dist/api/server-deps-l2-l3.d.ts +0 -68
  79. package/dist/api/server-deps-l2-l3.js +0 -123
  80. package/dist/api/server-deps-p1.d.ts +0 -84
  81. package/dist/api/server-deps-p2.d.ts +0 -32
  82. package/dist/api/server-deps-p2.js +0 -84
  83. package/dist/api/server-deps-p5.d.ts +0 -66
  84. package/dist/api/server-deps-p5.js +0 -139
  85. package/dist/api/viewer-static.d.ts +0 -30
  86. package/dist/api/viewer-static.js +0 -102
  87. package/dist/api/wire-up.d.ts +0 -54
  88. package/dist/api-impact.d.ts +0 -30
  89. package/dist/api-server.d.ts +0 -2
  90. package/dist/backfill-fts-anchor.d.ts +0 -15
  91. package/dist/backfill-source-type.d.ts +0 -20
  92. package/dist/churn.d.ts +0 -31
  93. package/dist/cli/answer.d.ts +0 -66
  94. package/dist/cli/conflict.d.ts +0 -38
  95. package/dist/cli/conflict.js +0 -282
  96. package/dist/cli/export.d.ts +0 -51
  97. package/dist/cli/export.js +0 -280
  98. package/dist/cli/hooks.d.ts +0 -54
  99. package/dist/cli/hooks.js +0 -133
  100. package/dist/cli/import.d.ts +0 -52
  101. package/dist/cli/import.js +0 -274
  102. package/dist/cli/mark.d.ts +0 -33
  103. package/dist/cli/mark.js +0 -130
  104. package/dist/cli/ocr-batch.d.ts +0 -12
  105. package/dist/cli/ocr-batch.js +0 -411
  106. package/dist/cli/snapshot-main.d.ts +0 -30
  107. package/dist/cli/snapshot-main.js +0 -47
  108. package/dist/cli/viewer.d.ts +0 -35
  109. package/dist/cli/viewer.js +0 -71
  110. package/dist/cli-telemetry.d.ts +0 -36
  111. package/dist/cli-telemetry.js +0 -150
  112. package/dist/compact.d.ts +0 -7
  113. package/dist/consolidate.d.ts +0 -18
  114. package/dist/consolidation.d.ts +0 -32
  115. package/dist/cross-agent-v2.d.ts +0 -45
  116. package/dist/cross-search.d.ts +0 -11
  117. package/dist/crystallize.d.ts +0 -43
  118. package/dist/db.d.ts +0 -11
  119. package/dist/dedup.d.ts +0 -1
  120. package/dist/detect-changes.d.ts +0 -29
  121. package/dist/digest.d.ts +0 -1
  122. package/dist/doctor.d.ts +0 -1
  123. package/dist/embed.d.ts +0 -57
  124. package/dist/evals.d.ts +0 -176
  125. package/dist/evals.js +0 -351
  126. package/dist/generate-user-profile.d.ts +0 -18
  127. package/dist/graphify-ingest.d.ts +0 -18
  128. package/dist/impact.d.ts +0 -39
  129. package/dist/index.d.ts +0 -2
  130. package/dist/ingest-entity.d.ts +0 -44
  131. package/dist/ingest.d.ts +0 -13
  132. package/dist/kg-llm.d.ts +0 -39
  133. package/dist/knowledge-graph.d.ts +0 -72
  134. package/dist/lib/answer/config.d.ts +0 -41
  135. package/dist/lib/answer/index.d.ts +0 -47
  136. package/dist/lib/answer/prompt.d.ts +0 -37
  137. package/dist/lib/answer/provider.d.ts +0 -47
  138. package/dist/lib/answer/retrieval.d.ts +0 -36
  139. package/dist/lib/answer/telemetry.d.ts +0 -99
  140. package/dist/lib/answer/types.d.ts +0 -108
  141. package/dist/lib/api/error-leak-fix.d.ts +0 -54
  142. package/dist/lib/api/safe-error-message.d.ts +0 -70
  143. package/dist/lib/archive/common-passwords.d.ts +0 -37
  144. package/dist/lib/archive/common-passwords.js +0 -753
  145. package/dist/lib/archive/encryption.d.ts +0 -81
  146. package/dist/lib/archive/encryption.js +0 -236
  147. package/dist/lib/archive/enforce-strength.d.ts +0 -54
  148. package/dist/lib/archive/enforce-strength.js +0 -70
  149. package/dist/lib/archive/entropy.d.ts +0 -34
  150. package/dist/lib/archive/entropy.js +0 -180
  151. package/dist/lib/archive/export-locking.d.ts +0 -102
  152. package/dist/lib/archive/export-locking.js +0 -202
  153. package/dist/lib/archive/format.d.ts +0 -20
  154. package/dist/lib/archive/format.js +0 -174
  155. package/dist/lib/archive/index.d.ts +0 -23
  156. package/dist/lib/archive/index.js +0 -17
  157. package/dist/lib/archive/manifest.d.ts +0 -53
  158. package/dist/lib/archive/manifest.js +0 -183
  159. package/dist/lib/archive/migration.d.ts +0 -36
  160. package/dist/lib/archive/migration.js +0 -100
  161. package/dist/lib/archive/migrations/v18_to_v19.d.ts +0 -16
  162. package/dist/lib/archive/migrations/v18_to_v19.js +0 -18
  163. package/dist/lib/archive/orchestrator.d.ts +0 -166
  164. package/dist/lib/archive/orchestrator.js +0 -428
  165. package/dist/lib/archive/serializers/chunks.d.ts +0 -30
  166. package/dist/lib/archive/serializers/chunks.js +0 -113
  167. package/dist/lib/archive/serializers/embeddings.d.ts +0 -36
  168. package/dist/lib/archive/serializers/embeddings.js +0 -115
  169. package/dist/lib/archive/serializers/kg.d.ts +0 -28
  170. package/dist/lib/archive/serializers/kg.js +0 -184
  171. package/dist/lib/archive/serializers/ops_audit.d.ts +0 -21
  172. package/dist/lib/archive/serializers/ops_audit.js +0 -97
  173. package/dist/lib/archive/server-deps.d.ts +0 -131
  174. package/dist/lib/archive/server-deps.js +0 -232
  175. package/dist/lib/archive/strength.d.ts +0 -50
  176. package/dist/lib/archive/strength.js +0 -77
  177. package/dist/lib/archive/types.d.ts +0 -159
  178. package/dist/lib/archive/types.js +0 -45
  179. package/dist/lib/archive/unpack-streaming.d.ts +0 -70
  180. package/dist/lib/archive/unpack-streaming.js +0 -255
  181. package/dist/lib/auth/localhost-guard.d.ts +0 -106
  182. package/dist/lib/confidence/config.d.ts +0 -37
  183. package/dist/lib/confidence/config.js +0 -107
  184. package/dist/lib/confidence/db-shim-singleton.d.ts +0 -20
  185. package/dist/lib/confidence/db-shim-singleton.js +0 -41
  186. package/dist/lib/confidence/db-shim.d.ts +0 -47
  187. package/dist/lib/confidence/db-shim.js +0 -141
  188. package/dist/lib/confidence/mark.d.ts +0 -58
  189. package/dist/lib/confidence/mark.js +0 -168
  190. package/dist/lib/confidence/ranking.d.ts +0 -69
  191. package/dist/lib/confidence/ranking.js +0 -101
  192. package/dist/lib/confidence/search-filter.d.ts +0 -44
  193. package/dist/lib/confidence/search-filter.js +0 -103
  194. package/dist/lib/confidence/types.d.ts +0 -146
  195. package/dist/lib/confidence/types.js +0 -20
  196. package/dist/lib/confidence/write-hooks.d.ts +0 -50
  197. package/dist/lib/confidence/write-hooks.js +0 -159
  198. package/dist/lib/conflict/audit-fk-check.d.ts +0 -72
  199. package/dist/lib/conflict/audit-fk-check.js +0 -131
  200. package/dist/lib/conflict/audit-writer.d.ts +0 -39
  201. package/dist/lib/conflict/audit-writer.js +0 -133
  202. package/dist/lib/conflict/db-singleton.d.ts +0 -28
  203. package/dist/lib/conflict/db-singleton.js +0 -61
  204. package/dist/lib/conflict/db.d.ts +0 -27
  205. package/dist/lib/conflict/db.js +0 -20
  206. package/dist/lib/conflict/detector-direct.d.ts +0 -21
  207. package/dist/lib/conflict/detector-direct.js +0 -105
  208. package/dist/lib/conflict/evidence.d.ts +0 -24
  209. package/dist/lib/conflict/evidence.js +0 -76
  210. package/dist/lib/conflict/index.d.ts +0 -14
  211. package/dist/lib/conflict/index.js +0 -12
  212. package/dist/lib/conflict/scheduler.d.ts +0 -78
  213. package/dist/lib/conflict/scheduler.js +0 -111
  214. package/dist/lib/conflict/shadow.d.ts +0 -75
  215. package/dist/lib/conflict/shadow.js +0 -161
  216. package/dist/lib/conflict/types.d.ts +0 -133
  217. package/dist/lib/conflict/types.js +0 -19
  218. package/dist/lib/cost-cap.d.ts +0 -94
  219. package/dist/lib/deps/deps-registry.d.ts +0 -111
  220. package/dist/lib/error-sanitizer/middleware.d.ts +0 -43
  221. package/dist/lib/error-sanitizer/sanitize.d.ts +0 -78
  222. package/dist/lib/eval-batch.d.ts +0 -34
  223. package/dist/lib/eval-batch.js +0 -103
  224. package/dist/lib/eval-metrics.d.ts +0 -36
  225. package/dist/lib/eval-metrics.js +0 -95
  226. package/dist/lib/eval.d.ts +0 -106
  227. package/dist/lib/eval.js +0 -343
  228. package/dist/lib/events/bus.d.ts +0 -135
  229. package/dist/lib/fts-anchor.d.ts +0 -1
  230. package/dist/lib/hooks/classifier.d.ts +0 -47
  231. package/dist/lib/hooks/classifier.js +0 -129
  232. package/dist/lib/hooks/config.d.ts +0 -49
  233. package/dist/lib/hooks/config.js +0 -106
  234. package/dist/lib/hooks/decorators.d.ts +0 -35
  235. package/dist/lib/hooks/decorators.js +0 -59
  236. package/dist/lib/hooks/pipeline.d.ts +0 -76
  237. package/dist/lib/hooks/pipeline.js +0 -213
  238. package/dist/lib/hooks/privacy-filter-adapter.d.ts +0 -55
  239. package/dist/lib/hooks/privacy-filter-adapter.js +0 -84
  240. package/dist/lib/hooks/rate-limit-constant-time.d.ts +0 -57
  241. package/dist/lib/hooks/rate-limit-constant-time.js +0 -69
  242. package/dist/lib/hooks/rate-limit-dryrun-fix.d.ts +0 -71
  243. package/dist/lib/hooks/rate-limit-dryrun-fix.js +0 -110
  244. package/dist/lib/hooks/rate-limit.d.ts +0 -54
  245. package/dist/lib/hooks/rate-limit.js +0 -122
  246. package/dist/lib/hooks/server-deps.d.ts +0 -61
  247. package/dist/lib/hooks/server-deps.js +0 -92
  248. package/dist/lib/hooks/source-allowlist.d.ts +0 -26
  249. package/dist/lib/hooks/source-allowlist.js +0 -53
  250. package/dist/lib/hooks/types.d.ts +0 -129
  251. package/dist/lib/hooks/types.js +0 -24
  252. package/dist/lib/hooks/worker.d.ts +0 -56
  253. package/dist/lib/hooks/worker.js +0 -150
  254. package/dist/lib/ingest-router.d.ts +0 -25
  255. package/dist/lib/ocr-detector.d.ts +0 -61
  256. package/dist/lib/ocr-detector.js +0 -138
  257. package/dist/lib/ocr-engine-stub.d.ts +0 -48
  258. package/dist/lib/ocr-engine-stub.js +0 -190
  259. package/dist/lib/ocr-engines/google-doc-ai.d.ts +0 -36
  260. package/dist/lib/ocr-engines/google-doc-ai.js +0 -164
  261. package/dist/lib/ocr-jobs.d.ts +0 -67
  262. package/dist/lib/ocr-jobs.js +0 -129
  263. package/dist/lib/op-audit-extension/ran-at-guard.d.ts +0 -86
  264. package/dist/lib/op-audit.d.ts +0 -71
  265. package/dist/lib/privacy-br/detector.d.ts +0 -42
  266. package/dist/lib/privacy-br/detector.js +0 -130
  267. package/dist/lib/privacy-br/index.d.ts +0 -20
  268. package/dist/lib/privacy-br/index.js +0 -20
  269. package/dist/lib/privacy-br/integration.d.ts +0 -71
  270. package/dist/lib/privacy-br/integration.js +0 -74
  271. package/dist/lib/privacy-br/patterns.d.ts +0 -117
  272. package/dist/lib/privacy-br/patterns.js +0 -434
  273. package/dist/lib/privacy-br/redact.d.ts +0 -42
  274. package/dist/lib/privacy-br/redact.js +0 -103
  275. package/dist/lib/privacy-br/types.d.ts +0 -55
  276. package/dist/lib/privacy-br/types.js +0 -25
  277. package/dist/lib/regex-extract/extractor.d.ts +0 -30
  278. package/dist/lib/regex-extract/frontmatter.d.ts +0 -44
  279. package/dist/lib/regex-extract/index.d.ts +0 -14
  280. package/dist/lib/regex-extract/ingest-router-l4.d.ts +0 -76
  281. package/dist/lib/regex-extract/patterns.d.ts +0 -61
  282. package/dist/lib/regex-extract/production-wire.d.ts +0 -128
  283. package/dist/lib/regex-extract/reconcile.d.ts +0 -162
  284. package/dist/lib/regex-extract/strip-code.d.ts +0 -24
  285. package/dist/lib/regex-extract/types.d.ts +0 -48
  286. package/dist/lib/reranker.d.ts +0 -80
  287. package/dist/lib/shadow-tracker.d.ts +0 -191
  288. package/dist/lib/shadow-tracker.js +0 -384
  289. package/dist/lib/spo-injection.d.ts +0 -52
  290. package/dist/lib/telemetry-collector.d.ts +0 -158
  291. package/dist/lib/telemetry-collector.js +0 -249
  292. package/dist/lib/temporal-detector.d.ts +0 -27
  293. package/dist/lib/viewer/auth.d.ts +0 -37
  294. package/dist/lib/viewer/auth.js +0 -70
  295. package/dist/lib/viewer/backpressure.d.ts +0 -59
  296. package/dist/lib/viewer/backpressure.js +0 -100
  297. package/dist/lib/viewer/broadcast-singleton.d.ts +0 -34
  298. package/dist/lib/viewer/broadcast-singleton.js +0 -49
  299. package/dist/lib/viewer/broadcast.d.ts +0 -66
  300. package/dist/lib/viewer/broadcast.js +0 -96
  301. package/dist/lib/viewer/event-types.d.ts +0 -132
  302. package/dist/lib/viewer/event-types.js +0 -74
  303. package/dist/lib/viewer/instrumentation.d.ts +0 -106
  304. package/dist/lib/viewer/instrumentation.js +0 -224
  305. package/dist/lib/viewer/migration.d.ts +0 -23
  306. package/dist/lib/viewer/migration.js +0 -56
  307. package/dist/lib/viewer/redaction.d.ts +0 -44
  308. package/dist/lib/viewer/redaction.js +0 -139
  309. package/dist/lib/viewer/session.d.ts +0 -51
  310. package/dist/lib/viewer/session.js +0 -87
  311. package/dist/mcp/tools/answer.d.ts +0 -94
  312. package/dist/mcp/tools/archive.d.ts +0 -152
  313. package/dist/mcp/tools/archive.js +0 -170
  314. package/dist/mcp/tools/conflict.d.ts +0 -44
  315. package/dist/mcp/tools/conflict.js +0 -130
  316. package/dist/mcp/tools/hooks.d.ts +0 -29
  317. package/dist/mcp/tools/hooks.js +0 -78
  318. package/dist/mcp/tools/mark.d.ts +0 -38
  319. package/dist/mcp/tools/mark.js +0 -82
  320. package/dist/mcp/tools/viewer.d.ts +0 -58
  321. package/dist/mcp/tools/viewer.js +0 -64
  322. package/dist/mcp-server.d.ts +0 -2
  323. package/dist/metrics.d.ts +0 -3
  324. package/dist/noise-filter.d.ts +0 -18
  325. package/dist/notion-sync.d.ts +0 -7
  326. package/dist/notion-sync.js +0 -97
  327. package/dist/observability/adapters/a3-adapter.d.ts +0 -63
  328. package/dist/observability/adapters/a3-adapter.js +0 -83
  329. package/dist/observability/adapters/p1-adapter.d.ts +0 -49
  330. package/dist/observability/adapters/p1-adapter.js +0 -63
  331. package/dist/observability/adapters/p5-adapter.d.ts +0 -36
  332. package/dist/observability/adapters/p5-adapter.js +0 -71
  333. package/dist/observability/cardinality.d.ts +0 -61
  334. package/dist/observability/cardinality.js +0 -300
  335. package/dist/observability/collectors/db-stats.collector.d.ts +0 -9
  336. package/dist/observability/collectors/db-stats.collector.js +0 -88
  337. package/dist/observability/collectors/eventbus.collector.d.ts +0 -6
  338. package/dist/observability/collectors/eventbus.collector.js +0 -50
  339. package/dist/observability/collectors/process.collector.d.ts +0 -7
  340. package/dist/observability/collectors/process.collector.js +0 -93
  341. package/dist/observability/collectors/provider-telemetry.collector.d.ts +0 -11
  342. package/dist/observability/collectors/provider-telemetry.collector.js +0 -112
  343. package/dist/observability/collectors/search-telemetry.collector.d.ts +0 -12
  344. package/dist/observability/collectors/search-telemetry.collector.js +0 -76
  345. package/dist/observability/exporter.d.ts +0 -30
  346. package/dist/observability/exporter.js +0 -182
  347. package/dist/observability/index.d.ts +0 -22
  348. package/dist/observability/index.js +0 -21
  349. package/dist/observability/metrics.d.ts +0 -53
  350. package/dist/observability/metrics.js +0 -213
  351. package/dist/observability/privacy-guard.d.ts +0 -32
  352. package/dist/observability/privacy-guard.js +0 -116
  353. package/dist/observability/record.d.ts +0 -83
  354. package/dist/observability/record.js +0 -217
  355. package/dist/observability/registry.d.ts +0 -60
  356. package/dist/observability/registry.js +0 -93
  357. package/dist/observability/types.d.ts +0 -115
  358. package/dist/observability/types.js +0 -235
  359. package/dist/observability.d.ts +0 -131
  360. package/dist/plugins/nox-hooks/index.d.ts +0 -61
  361. package/dist/plugins/nox-hooks/index.js +0 -99
  362. package/dist/primer.d.ts +0 -1
  363. package/dist/privacy/filter.d.ts +0 -27
  364. package/dist/privacy/patterns.d.ts +0 -29
  365. package/dist/privacy/tag-parser.d.ts +0 -24
  366. package/dist/project-context-gen.d.ts +0 -10
  367. package/dist/providers/embedding/gemini.d.ts +0 -73
  368. package/dist/providers/embedding/openai.d.ts +0 -76
  369. package/dist/providers/embedding/types.d.ts +0 -39
  370. package/dist/providers/embedding/voyage.d.ts +0 -36
  371. package/dist/providers/index.d.ts +0 -116
  372. package/dist/providers/llm/anthropic.d.ts +0 -29
  373. package/dist/providers/llm/chain.d.ts +0 -99
  374. package/dist/providers/llm/gemini.d.ts +0 -48
  375. package/dist/providers/llm/openai.d.ts +0 -64
  376. package/dist/providers/llm/types.d.ts +0 -47
  377. package/dist/providers/telemetry.d.ts +0 -87
  378. package/dist/providers/types.d.ts +0 -42
  379. package/dist/query-entity-count.d.ts +0 -54
  380. package/dist/reflect.d.ts +0 -26
  381. package/dist/reindex-errors.d.ts +0 -7
  382. package/dist/reindex.d.ts +0 -16
  383. package/dist/retention.d.ts +0 -40
  384. package/dist/salience.d.ts +0 -85
  385. package/dist/scripts/migrate-v17-ops-audit.d.ts +0 -17
  386. package/dist/search-dedup.d.ts +0 -44
  387. package/dist/search-expansion.d.ts +0 -20
  388. package/dist/search.d.ts +0 -62
  389. package/dist/seh-detector.d.ts +0 -31
  390. package/dist/self-improve.d.ts +0 -1
  391. package/dist/session-distill.d.ts +0 -29
  392. package/dist/session-update.d.ts +0 -1
  393. package/dist/shared-memory.d.ts +0 -24
  394. package/dist/stats.d.ts +0 -1
  395. package/dist/temporal-retrieval.d.ts +0 -132
  396. package/dist/tier-manager.d.ts +0 -69
  397. package/dist/vectorize.d.ts +0 -16
  398. package/dist/watch.d.ts +0 -8
@@ -1,53 +0,0 @@
1
- /**
2
- * src/lib/hooks/source-allowlist.ts — T2: Layer 2 of the privacy pipeline.
3
- *
4
- * Filters HookEvent by `source` AND `role`. Only events with:
5
- * - source ∈ NOX_HOOK_SOURCES (default {openclaw})
6
- * - role ∈ {user, assistant} (system/tool/unknown rejected by default)
7
- *
8
- * pass through. "unknown" source is ALWAYS rejected (it indicates the
9
- * event was constructed without explicit channel attribution — risk vector).
10
- *
11
- * No content access. No telemetry write here — pipeline (T6) records the
12
- * decision via the trace mechanism.
13
- */
14
- /** Roles we accept as conversation content. */
15
- const ALLOWED_ROLES = new Set(["user", "assistant"]);
16
- /**
17
- * Evaluate Layer 2 against a HookEvent given the active config.
18
- * Pure function — safe to test in isolation.
19
- */
20
- export function evaluateSourceAllowlist(event, config, opts = {}) {
21
- const roles = opts.allowedRoles ?? ALLOWED_ROLES;
22
- // Reject unknown source unconditionally — explicit attribution required.
23
- if (event.source === "unknown") {
24
- return {
25
- capture: false,
26
- reason: "source=unknown is never allowed (explicit channel attribution required)",
27
- layer: "source-allowlist",
28
- };
29
- }
30
- if (!config.allowedSources.has(event.source)) {
31
- return {
32
- capture: false,
33
- reason: `source=${event.source} not in NOX_HOOK_SOURCES allowlist`,
34
- layer: "source-allowlist",
35
- };
36
- }
37
- if (!roles.has(event.role)) {
38
- return {
39
- capture: false,
40
- reason: `role=${event.role} not in {user,assistant}`,
41
- layer: "source-allowlist",
42
- };
43
- }
44
- return {
45
- capture: true,
46
- reason: `source=${event.source} role=${event.role} allowed`,
47
- layer: "source-allowlist",
48
- };
49
- }
50
- /** Returns true if a given source string is recognized at all. */
51
- export function isKnownSource(s) {
52
- return ["openclaw", "cli", "manual", "mcp", "api", "unknown"].includes(s);
53
- }
@@ -1,129 +0,0 @@
1
- /**
2
- * src/lib/hooks/types.ts — T1: Hook contract types.
3
- *
4
- * Public interfaces consumed by the 5-layer pipeline (T6) and all callers
5
- * (plugin T8, CLI T11, HTTP T12, MCP T13).
6
- *
7
- * Schema dependency: `agent_events` table (v11) already exists per spec §6.1
8
- * and is used by telemetry (T6 emits one row per rejection/capture).
9
- *
10
- * Privacy invariant: HookEvent.content is RAW until it leaves Layer 3.
11
- * After Layer 3, content has been passed through staged-A1 redact().
12
- * Telemetry rows NEVER include raw content — only layer name + reason + ts.
13
- */
14
- /**
15
- * Roles we recognize from the source agent's turn.
16
- * Layer 2 (source allowlist) constrains which roles get processed.
17
- */
18
- export type HookRole = "user" | "assistant" | "system" | "tool" | "unknown";
19
- /**
20
- * Origin channel of the event. Determines source allowlist (Layer 2).
21
- * - openclaw : afterTurn hook from the OpenClaw gateway
22
- * - cli : explicit `nox-mem hooks ingest` (manual or scripted)
23
- * - manual : in-process API client (tests, REPL, ad-hoc)
24
- * - mcp : MCP tool call
25
- * - api : HTTP endpoint
26
- * - unknown : default; ALWAYS rejected by Layer 2 unless explicitly allowed
27
- */
28
- export type HookSource = "openclaw" | "cli" | "manual" | "mcp" | "api" | "unknown";
29
- /**
30
- * Five-layer rejection reasons (one per layer + ok).
31
- * Stored in `agent_events.kind`-like telemetry column.
32
- */
33
- export type RejectionReason = "env_disabled" | "source_not_allowed" | "pii_detected_skip" | "classifier_low_signal" | "rate_limited" | "dedup_hit" | "queue_full" | "explicit_skip" | "dry_run" | "invalid_input";
34
- /** A capture decision returned by any layer. */
35
- export interface CaptureDecision {
36
- /** True → forward to next layer (or persist if last). */
37
- capture: boolean;
38
- /** Human-readable reason. Stored in telemetry. NEVER includes raw content. */
39
- reason: string;
40
- /** Optional layer-name; pipeline fills this if missing. */
41
- layer?: string;
42
- /** Optional score in [0,1] when classifier returned ambiguous. */
43
- score?: number;
44
- }
45
- /**
46
- * A normalized event before any layer touches it.
47
- * Source must populate role + content; rest is metadata.
48
- */
49
- export interface HookEvent {
50
- /** ULID assigned by caller or pipeline; used for dedup key + telemetry. */
51
- event_id: string;
52
- /** Where this event came from. */
53
- source: HookSource;
54
- /** Speaker. Layer 2 may filter by allowed roles. */
55
- role: HookRole;
56
- /** Raw text content (potentially containing PII). */
57
- content: string;
58
- /** Optional session_id (groups events from same convo). */
59
- session_id?: string;
60
- /** Optional project slug (cwd → slug mapping in plugin). */
61
- project_slug?: string;
62
- /** ISO 8601 timestamp. */
63
- ts: string;
64
- /** Optional decorator hints (T10 parses these). */
65
- decorators?: ReadonlyArray<"capture" | "skip">;
66
- /** Free-form metadata (model name, tool name, etc). NEVER content. */
67
- meta?: Readonly<Record<string, string | number | boolean>>;
68
- }
69
- /**
70
- * Mutable per-event state threaded through the pipeline.
71
- * Lets each layer attach side-data without mutating the original HookEvent.
72
- */
73
- export interface HookContext {
74
- event: HookEvent;
75
- /** Redacted text + redaction count after Layer 3. */
76
- redacted?: {
77
- text: string;
78
- redaction_count: number;
79
- kinds: string[];
80
- };
81
- /** Classifier output after Layer 4. */
82
- classification?: {
83
- score: number;
84
- reason: string;
85
- };
86
- /** Per-layer trace (debug + dryrun). */
87
- trace: Array<{
88
- layer: string;
89
- decision: CaptureDecision;
90
- t_ms: number;
91
- }>;
92
- /** Set once when pipeline short-circuits or persists. */
93
- outcome?: HookResult;
94
- }
95
- /** Final pipeline result. */
96
- export interface HookResult {
97
- captured: boolean;
98
- /** Reason for rejection, or "ok" when captured. */
99
- reason: RejectionReason | "ok";
100
- /** Layer that fired the rejection, or "persisted" on success. */
101
- layer: string;
102
- /** chunk_id when captured (set by ingestText). */
103
- chunk_id?: number;
104
- /** Total wall-clock time. */
105
- duration_ms: number;
106
- /** Whether dry-run mode was on (no persistence even if captured=true). */
107
- dry_run: boolean;
108
- }
109
- /**
110
- * Telemetry row written by pipeline for EVERY event (captured or rejected).
111
- * Maps onto `agent_events` columns; payload_json is a sanitized stub
112
- * (NEVER raw content).
113
- */
114
- export interface HookTelemetryRow {
115
- event_uuid: string;
116
- session_id: string;
117
- project_slug: string;
118
- kind: "tool_use" | "user_prompt" | "session_start" | "session_end" | "pre_compact";
119
- timestamp: string;
120
- payload_json: string;
121
- redaction_count: number;
122
- retention_days: number;
123
- }
124
- /** Standard error class for hook pipeline failures. */
125
- export declare class HookError extends Error {
126
- readonly code: RejectionReason | "internal";
127
- readonly layer?: string;
128
- constructor(code: RejectionReason | "internal", message: string, layer?: string);
129
- }
@@ -1,24 +0,0 @@
1
- /**
2
- * src/lib/hooks/types.ts — T1: Hook contract types.
3
- *
4
- * Public interfaces consumed by the 5-layer pipeline (T6) and all callers
5
- * (plugin T8, CLI T11, HTTP T12, MCP T13).
6
- *
7
- * Schema dependency: `agent_events` table (v11) already exists per spec §6.1
8
- * and is used by telemetry (T6 emits one row per rejection/capture).
9
- *
10
- * Privacy invariant: HookEvent.content is RAW until it leaves Layer 3.
11
- * After Layer 3, content has been passed through staged-A1 redact().
12
- * Telemetry rows NEVER include raw content — only layer name + reason + ts.
13
- */
14
- /** Standard error class for hook pipeline failures. */
15
- export class HookError extends Error {
16
- code;
17
- layer;
18
- constructor(code, message, layer) {
19
- super(message);
20
- this.name = "HookError";
21
- this.code = code;
22
- this.layer = layer;
23
- }
24
- }
@@ -1,56 +0,0 @@
1
- /**
2
- * src/lib/hooks/worker.ts — T9: Async worker queue.
3
- *
4
- * Backpressure-aware bounded queue:
5
- * - enqueue() returns synchronously (non-blocking for callers like
6
- * OpenClaw afterTurn hook). Returns {accepted, reason}.
7
- * - When full, oldest event is dropped + telemetry "queue_full" row
8
- * emitted. New event takes its slot (most-recent-wins).
9
- * - A drain loop runs every `tickMs` ms, processing batches of up to
10
- * `batchSize` events through the pipeline.
11
- *
12
- * The worker is the bridge between the synchronous hook trigger (an
13
- * OpenClaw turn ended) and the async pipeline (which may call out to
14
- * embed/ingest).
15
- *
16
- * Lifecycle:
17
- * const w = createWorker({ pipeline, ...opts });
18
- * w.start();
19
- * w.enqueue(event);
20
- * ...
21
- * await w.stop(); // drains remaining + shuts down
22
- */
23
- import type { PipelineHandle } from "./pipeline.js";
24
- import type { HookEvent, HookResult, HookTelemetryRow } from "./types.js";
25
- export interface WorkerOpts {
26
- pipeline: PipelineHandle;
27
- /** Max events held in queue. Default 10_000 (matches spec ring buffer). */
28
- maxSize?: number;
29
- /** Drain tick interval. Default 250ms (matches spec §3 T3). */
30
- tickMs?: number;
31
- /** Max events processed per tick. Default 100. */
32
- batchSize?: number;
33
- /** Optional sink for queue-overflow telemetry. */
34
- telemetry?: (row: HookTelemetryRow) => void | Promise<void>;
35
- }
36
- export interface WorkerStats {
37
- enqueued: number;
38
- processed: number;
39
- rejected: number;
40
- captured: number;
41
- dropped: number;
42
- errors: number;
43
- queueDepth: number;
44
- }
45
- export interface WorkerHandle {
46
- enqueue(event: HookEvent): {
47
- accepted: boolean;
48
- reason: string;
49
- depth: number;
50
- };
51
- start(): void;
52
- stop(): Promise<void>;
53
- drain(): Promise<HookResult[]>;
54
- stats(): WorkerStats;
55
- }
56
- export declare function createWorker(opts: WorkerOpts): WorkerHandle;
@@ -1,150 +0,0 @@
1
- /**
2
- * src/lib/hooks/worker.ts — T9: Async worker queue.
3
- *
4
- * Backpressure-aware bounded queue:
5
- * - enqueue() returns synchronously (non-blocking for callers like
6
- * OpenClaw afterTurn hook). Returns {accepted, reason}.
7
- * - When full, oldest event is dropped + telemetry "queue_full" row
8
- * emitted. New event takes its slot (most-recent-wins).
9
- * - A drain loop runs every `tickMs` ms, processing batches of up to
10
- * `batchSize` events through the pipeline.
11
- *
12
- * The worker is the bridge between the synchronous hook trigger (an
13
- * OpenClaw turn ended) and the async pipeline (which may call out to
14
- * embed/ingest).
15
- *
16
- * Lifecycle:
17
- * const w = createWorker({ pipeline, ...opts });
18
- * w.start();
19
- * w.enqueue(event);
20
- * ...
21
- * await w.stop(); // drains remaining + shuts down
22
- */
23
- export function createWorker(opts) {
24
- const pipeline = opts.pipeline;
25
- const maxSize = opts.maxSize ?? 10_000;
26
- const tickMs = opts.tickMs ?? 250;
27
- const batchSize = opts.batchSize ?? 100;
28
- const telemetry = opts.telemetry;
29
- const queue = [];
30
- let timer = null;
31
- let running = false;
32
- let inFlight = null;
33
- const counters = {
34
- enqueued: 0,
35
- processed: 0,
36
- rejected: 0,
37
- captured: 0,
38
- dropped: 0,
39
- errors: 0,
40
- queueDepth: 0,
41
- };
42
- function refreshDepth() {
43
- counters.queueDepth = queue.length;
44
- }
45
- function emitOverflow(droppedEvent) {
46
- if (!telemetry)
47
- return;
48
- try {
49
- void telemetry({
50
- event_uuid: droppedEvent.event_id,
51
- session_id: droppedEvent.session_id ?? "unknown",
52
- project_slug: droppedEvent.project_slug ?? "unknown",
53
- kind: "tool_use",
54
- timestamp: droppedEvent.ts,
55
- payload_json: JSON.stringify({ layer: "worker", reason: "queue_full_dropped_oldest" }),
56
- redaction_count: 0,
57
- retention_days: 30,
58
- });
59
- }
60
- catch {
61
- /* ignore */
62
- }
63
- }
64
- async function tick(force = false) {
65
- if ((!running && !force) || queue.length === 0)
66
- return;
67
- const batch = queue.splice(0, batchSize);
68
- refreshDepth();
69
- for (const ev of batch) {
70
- try {
71
- const result = await pipeline.run(ev);
72
- counters.processed += 1;
73
- if (result.captured)
74
- counters.captured += 1;
75
- else
76
- counters.rejected += 1;
77
- }
78
- catch {
79
- counters.errors += 1;
80
- }
81
- }
82
- }
83
- function scheduleTick() {
84
- inFlight = tick().finally(() => {
85
- inFlight = null;
86
- });
87
- }
88
- return {
89
- enqueue(event) {
90
- counters.enqueued += 1;
91
- if (queue.length >= maxSize) {
92
- // Drop oldest, append new
93
- const dropped = queue.shift();
94
- if (dropped) {
95
- counters.dropped += 1;
96
- emitOverflow(dropped);
97
- }
98
- queue.push(event);
99
- refreshDepth();
100
- return { accepted: true, reason: "queue_full_dropped_oldest", depth: queue.length };
101
- }
102
- queue.push(event);
103
- refreshDepth();
104
- return { accepted: true, reason: "enqueued", depth: queue.length };
105
- },
106
- start() {
107
- if (running)
108
- return;
109
- running = true;
110
- timer = setInterval(scheduleTick, tickMs);
111
- },
112
- async stop() {
113
- running = false;
114
- if (timer) {
115
- clearInterval(timer);
116
- timer = null;
117
- }
118
- // Drain remaining (force=true to bypass running check)
119
- if (inFlight)
120
- await inFlight;
121
- while (queue.length > 0) {
122
- await tick(true);
123
- }
124
- },
125
- async drain() {
126
- const out = [];
127
- while (queue.length > 0) {
128
- const ev = queue.shift();
129
- refreshDepth();
130
- try {
131
- const r = await pipeline.run(ev);
132
- counters.processed += 1;
133
- if (r.captured)
134
- counters.captured += 1;
135
- else
136
- counters.rejected += 1;
137
- out.push(r);
138
- }
139
- catch {
140
- counters.errors += 1;
141
- }
142
- }
143
- return out;
144
- },
145
- stats() {
146
- refreshDepth();
147
- return { ...counters };
148
- },
149
- };
150
- }
@@ -1,25 +0,0 @@
1
- import type Database from "better-sqlite3";
2
- export type IngestKind = "entity" | "markdown" | "graphify" | "pdf-scanned";
3
- export interface IngestRouteResult {
4
- chunks: number;
5
- kind: IngestKind;
6
- routedTo: string;
7
- /** Para 'pdf-scanned' kind: jobId enfileirado. */
8
- ocrJobId?: number;
9
- }
10
- export interface IngestOpts {
11
- externalDb?: Database.Database;
12
- skipDelete?: boolean;
13
- forceKind?: IngestKind;
14
- }
15
- /**
16
- * Detect ingest kind from path conventions. Centralizada aqui — mexer só nesse
17
- * arquivo quando adicionar novo tipo (ex: "pdf-text-layer", "fathom-transcript").
18
- */
19
- export declare function detectIngestKind(filePath: string): IngestKind;
20
- /**
21
- * Single dispatch entry point. Todos callers devem usar isso em vez de chamar
22
- * ingestFile()/ingestEntityFile() direto. Backward compat: kinds não-implementados
23
- * caem no markdown handler (ingestFile).
24
- */
25
- export declare function routeIngest(filePath: string, opts?: IngestOpts): Promise<IngestRouteResult>;
@@ -1,61 +0,0 @@
1
- /**
2
- * Threshold de char count abaixo do qual um PDF é considerado scaneado.
3
- * Markitdown sem OCR tipicamente retorna 2-50 chars em PDFs imagem.
4
- */
5
- export declare const SCANNED_PDF_CHAR_THRESHOLD = 100;
6
- /**
7
- * Threshold de tamanho/ratio: PDF >5MB com <0.001 chars/byte → provável scan
8
- * (densidade de texto extremamente baixa).
9
- */
10
- export declare const LARGE_PDF_BYTES_THRESHOLD = 5000000;
11
- export declare const LARGE_PDF_CHAR_RATIO = 0.001;
12
- /**
13
- * Threshold da pdftotext probe na primeira página.
14
- * <50 chars na 1ª página é forte indicador de scan.
15
- */
16
- export declare const PROBE_FIRST_PAGE_THRESHOLD = 50;
17
- /**
18
- * Heurística primária pós-markitdown.
19
- *
20
- * @param markitdownOutput texto extraído pelo markitdown (vazio ou ~2 chars = sinal forte)
21
- * @param fileSize tamanho do PDF em bytes
22
- * @returns true se PDF é provavelmente scaneado
23
- */
24
- export declare function isScannedPdf(markitdownOutput: string, fileSize: number): boolean;
25
- export interface PdftotextProbeResult {
26
- likelyScan: boolean;
27
- firstPageChars: number;
28
- /** -1 sentinela quando pdftotext não está disponível ou crash. */
29
- error?: string;
30
- }
31
- /**
32
- * Pre-flight zero-cost: extrai apenas a 1ª página via pdftotext e conta chars.
33
- * Usa execFileSync (regra security: argumento como array, sem shell).
34
- *
35
- * Graceful: se pdftotext não está instalado, retorna `{ likelyScan: false, firstPageChars: -1 }`
36
- * com warn em stderr — caller decide fallback (markitdown direto, OCR enqueue, etc).
37
- */
38
- export declare function pdftotextProbe(filePath: string): Promise<PdftotextProbeResult>;
39
- export interface OcrRouteHint {
40
- /** Override manual: força routing pra OCR mesmo se probe disser não. */
41
- force?: boolean;
42
- /** Path/folder prior (ex: PPR/, PESSOAL/) — força route=true sem probe. */
43
- folder?: string;
44
- }
45
- export interface OcrRouteDecision {
46
- route: boolean;
47
- reason: string;
48
- }
49
- /**
50
- * Combina file-size + pdftotext probe + hints (force, folder prior) pra decidir
51
- * se PDF deve ser roteado pra OCR pipeline.
52
- *
53
- * Ordem de precedência:
54
- * 1. opts.force=true → route=true ("forced")
55
- * 2. arquivo não existe → route=false ("file-not-found")
56
- * 3. arquivo está em SCAN_PRIOR_FOLDERS → route=true ("folder-prior")
57
- * 4. probe.firstPageChars < threshold → route=true ("probe-scan")
58
- * 5. probe.firstPageChars > threshold → route=false ("probe-text")
59
- * 6. probe error/unavailable → route=false ("probe-unavailable", caller usa heurística pós-markitdown)
60
- */
61
- export declare function shouldRouteToOcr(filePath: string, hint?: OcrRouteHint): Promise<OcrRouteDecision>;
@@ -1,138 +0,0 @@
1
- // ocr-detector.ts — Heurísticas de detecção de PDF scaneado (E12 Tier 3).
2
- // Spec: memoria-nox/specs/2026-05-07-E12-tier3-ocr.md §2
3
- //
4
- // Sem cloud calls. Apenas:
5
- // 1. char count pós-markitdown (heurística primária)
6
- // 2. pdftotext probe na primeira página (zero-cost pre-flight)
7
- // 3. routing decision combinando probe + hints (force, folder prior)
8
- //
9
- // Memória ref: feedback_scanned_pdf_heuristic (markitdown sem OCR retorna ~2 chars).
10
- // execFileSync (não execSync) — regra security feedback_execfilesync_over_execsync_for_user_input.
11
- import { execFileSync } from "node:child_process";
12
- import { existsSync, statSync } from "node:fs";
13
- import { resolve } from "node:path";
14
- /**
15
- * Threshold de char count abaixo do qual um PDF é considerado scaneado.
16
- * Markitdown sem OCR tipicamente retorna 2-50 chars em PDFs imagem.
17
- */
18
- export const SCANNED_PDF_CHAR_THRESHOLD = 100;
19
- /**
20
- * Threshold de tamanho/ratio: PDF >5MB com <0.001 chars/byte → provável scan
21
- * (densidade de texto extremamente baixa).
22
- */
23
- export const LARGE_PDF_BYTES_THRESHOLD = 5_000_000;
24
- export const LARGE_PDF_CHAR_RATIO = 0.001;
25
- /**
26
- * Threshold da pdftotext probe na primeira página.
27
- * <50 chars na 1ª página é forte indicador de scan.
28
- */
29
- export const PROBE_FIRST_PAGE_THRESHOLD = 50;
30
- /**
31
- * Folders com prior alto de PDF scaneado. Gera `route=true` mesmo sem probe.
32
- * Lista propositalmente conservadora — overrides via `--force-ocr` no CLI.
33
- */
34
- const SCAN_PRIOR_FOLDERS = ["/Documents/PPR/", "/Documents/PESSOAL/"];
35
- /**
36
- * Heurística primária pós-markitdown.
37
- *
38
- * @param markitdownOutput texto extraído pelo markitdown (vazio ou ~2 chars = sinal forte)
39
- * @param fileSize tamanho do PDF em bytes
40
- * @returns true se PDF é provavelmente scaneado
41
- */
42
- export function isScannedPdf(markitdownOutput, fileSize) {
43
- if (!markitdownOutput)
44
- return true;
45
- // Strip whitespace pra char count "real".
46
- const stripped = markitdownOutput.replace(/\s+/g, "").trim();
47
- if (stripped.length < SCANNED_PDF_CHAR_THRESHOLD)
48
- return true;
49
- // Sanity check: PDF grande com densidade text/byte muito baixa = scan.
50
- if (fileSize > LARGE_PDF_BYTES_THRESHOLD && stripped.length / fileSize < LARGE_PDF_CHAR_RATIO) {
51
- return true;
52
- }
53
- return false;
54
- }
55
- /**
56
- * Pre-flight zero-cost: extrai apenas a 1ª página via pdftotext e conta chars.
57
- * Usa execFileSync (regra security: argumento como array, sem shell).
58
- *
59
- * Graceful: se pdftotext não está instalado, retorna `{ likelyScan: false, firstPageChars: -1 }`
60
- * com warn em stderr — caller decide fallback (markitdown direto, OCR enqueue, etc).
61
- */
62
- export async function pdftotextProbe(filePath) {
63
- if (!existsSync(filePath)) {
64
- return { likelyScan: false, firstPageChars: -1, error: `file not found: ${filePath}` };
65
- }
66
- try {
67
- const out = execFileSync("pdftotext", ["-l", "1", filePath, "-"], {
68
- encoding: "utf-8",
69
- timeout: 30_000,
70
- maxBuffer: 5 * 1024 * 1024,
71
- stdio: ["ignore", "pipe", "ignore"],
72
- });
73
- const stripped = (out || "").replace(/\s+/g, "").trim();
74
- return {
75
- likelyScan: stripped.length < PROBE_FIRST_PAGE_THRESHOLD,
76
- firstPageChars: stripped.length,
77
- };
78
- }
79
- catch (err) {
80
- const code = err?.code || err?.errno;
81
- const msg = String(err?.message ?? err);
82
- // ENOENT = pdftotext não instalado (não-fatal: caller decide).
83
- if (code === "ENOENT") {
84
- console.warn("[ocr-detector] pdftotext not installed; skipping probe (apt install poppler-utils OR brew install poppler)");
85
- return { likelyScan: false, firstPageChars: -1, error: "pdftotext not installed" };
86
- }
87
- console.warn(`[ocr-detector] pdftotext probe failed: ${msg}`);
88
- return { likelyScan: false, firstPageChars: -1, error: msg };
89
- }
90
- }
91
- /**
92
- * Combina file-size + pdftotext probe + hints (force, folder prior) pra decidir
93
- * se PDF deve ser roteado pra OCR pipeline.
94
- *
95
- * Ordem de precedência:
96
- * 1. opts.force=true → route=true ("forced")
97
- * 2. arquivo não existe → route=false ("file-not-found")
98
- * 3. arquivo está em SCAN_PRIOR_FOLDERS → route=true ("folder-prior")
99
- * 4. probe.firstPageChars < threshold → route=true ("probe-scan")
100
- * 5. probe.firstPageChars > threshold → route=false ("probe-text")
101
- * 6. probe error/unavailable → route=false ("probe-unavailable", caller usa heurística pós-markitdown)
102
- */
103
- export async function shouldRouteToOcr(filePath, hint = {}) {
104
- if (hint.force)
105
- return { route: true, reason: "forced" };
106
- if (!existsSync(filePath))
107
- return { route: false, reason: "file-not-found" };
108
- const abs = resolve(filePath);
109
- // Normaliza separadores pra cobrir POSIX (Linux VPS) + Windows-likely-never.
110
- const folderHint = hint.folder ? resolve(hint.folder) : abs;
111
- for (const prior of SCAN_PRIOR_FOLDERS) {
112
- if (folderHint.includes(prior) || abs.includes(prior)) {
113
- return { route: true, reason: "folder-prior" };
114
- }
115
- }
116
- // Não é PDF? routing pra OCR não se aplica.
117
- if (!filePath.toLowerCase().endsWith(".pdf")) {
118
- return { route: false, reason: "not-pdf" };
119
- }
120
- const probe = await pdftotextProbe(filePath);
121
- if (probe.firstPageChars < 0) {
122
- return { route: false, reason: `probe-unavailable:${probe.error ?? "unknown"}` };
123
- }
124
- if (probe.likelyScan) {
125
- return { route: true, reason: `probe-scan:firstPageChars=${probe.firstPageChars}` };
126
- }
127
- // Sanity: file gigante com poucos chars na probe → também route.
128
- try {
129
- const sizeBytes = statSync(filePath).size;
130
- if (sizeBytes > LARGE_PDF_BYTES_THRESHOLD && probe.firstPageChars < SCANNED_PDF_CHAR_THRESHOLD) {
131
- return { route: true, reason: `large-file-low-text:${sizeBytes}b-${probe.firstPageChars}chars` };
132
- }
133
- }
134
- catch {
135
- /* stat failure non-fatal */
136
- }
137
- return { route: false, reason: `probe-text:firstPageChars=${probe.firstPageChars}` };
138
- }
@@ -1,48 +0,0 @@
1
- export interface OcrResult {
2
- /** Markdown rendered output. Tabelas Doc AI → markdown tables; preserva \n\n. */
3
- markdown: string;
4
- /** Page count detectado (Tesseract via pdfinfo, Doc AI via response). */
5
- pageCount: number;
6
- /** Cost real do engine (Tesseract = 0; cloud = chamada billable). */
7
- costUsd: number;
8
- }
9
- export interface OcrEngine {
10
- /** Identificador estável do engine (persistido em ocr_jobs.engine). */
11
- readonly name: string;
12
- /**
13
- * Custo estimado em USD pra processar `pageCount` páginas.
14
- * Tesseract: 0. Google Doc AI: ~$1.50/1k pages.
15
- */
16
- estimateCostUsd(pageCount: number): number;
17
- /** Roda OCR no arquivo e retorna markdown + metadata. */
18
- ocrFile(filePath: string): Promise<OcrResult>;
19
- }
20
- /**
21
- * Detecta se tesseract + pdftoppm estão instalados.
22
- * Retorna { available, missing[] } pra mensagens UX claras.
23
- */
24
- export declare function detectTesseractAvailability(): {
25
- available: boolean;
26
- missing: string[];
27
- };
28
- export declare class TesseractEngine implements OcrEngine {
29
- readonly name = "tesseract";
30
- private readonly lang;
31
- constructor(opts?: {
32
- lang?: string;
33
- });
34
- estimateCostUsd(_pageCount: number): number;
35
- ocrFile(filePath: string): Promise<OcrResult>;
36
- private ocrImage;
37
- private ocrPdfViaConversion;
38
- private runTesseract;
39
- private detectPageCount;
40
- }
41
- /**
42
- * Factory por nome. Cria engine apropriado.
43
- * - "tesseract" → TesseractEngine (CPU local, $0)
44
- * - "google_doc_ai" → GoogleDocAiEngine (cloud, $1.50/1k pages)
45
- */
46
- export declare function createEngine(name: string, opts?: Record<string, unknown>): OcrEngine;
47
- /** Alias: caller-friendly name esperado pela spec. */
48
- export declare function getEngine(name: string, opts?: Record<string, unknown>): OcrEngine;