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,190 +0,0 @@
1
- // ocr-engine-stub.ts — Interface OcrEngine + stub local Tesseract + factory.
2
- // Spec: memoria-nox/specs/2026-05-07-E12-tier3-ocr.md §3.1 + §4
3
- //
4
- // Engines:
5
- // - Interface canônica `OcrEngine` (estimateCostUsd + ocrFile)
6
- // - TesseractEngine: wrapper local (graceful failure se não instalado)
7
- // - GoogleDocAiEngine: cloud Document AI (impl em ./ocr-engines/google-doc-ai.ts)
8
- //
9
- // Cloud (2026-05-07): GCP creds em /root/.openclaw/.env (GOOGLE_APPLICATION_CREDENTIALS).
10
- import { execFileSync } from "node:child_process";
11
- import { existsSync } from "node:fs";
12
- import { resolve } from "node:path";
13
- import { createRequire } from "node:module";
14
- // ─────────────────────────────────────────────────────────────────────
15
- // TesseractEngine — local CPU OCR via tesseract-ocr + poppler-utils
16
- // ─────────────────────────────────────────────────────────────────────
17
- /**
18
- * Detecta se tesseract + pdftoppm estão instalados.
19
- * Retorna { available, missing[] } pra mensagens UX claras.
20
- */
21
- export function detectTesseractAvailability() {
22
- const missing = [];
23
- for (const bin of ["tesseract", "pdftoppm"]) {
24
- try {
25
- execFileSync("which", [bin], { stdio: "ignore", timeout: 5_000 });
26
- }
27
- catch {
28
- missing.push(bin);
29
- }
30
- }
31
- return { available: missing.length === 0, missing };
32
- }
33
- const TESSERACT_INSTALL_HINT = "Tesseract OCR not installed. Install with:\n" +
34
- " macOS: brew install tesseract tesseract-lang poppler\n" +
35
- " Debian: apt install tesseract-ocr tesseract-ocr-por poppler-utils\n" +
36
- "Then re-run ocr-batch.";
37
- export class TesseractEngine {
38
- name = "tesseract";
39
- lang;
40
- constructor(opts = {}) {
41
- this.lang = opts.lang ?? "por";
42
- }
43
- estimateCostUsd(_pageCount) {
44
- // Local CPU: zero opex marginal (VPS já provisionado).
45
- return 0;
46
- }
47
- async ocrFile(filePath) {
48
- if (!existsSync(filePath))
49
- throw new Error(`TesseractEngine: file not found: ${filePath}`);
50
- const avail = detectTesseractAvailability();
51
- if (!avail.available) {
52
- throw new Error(`${TESSERACT_INSTALL_HINT}\nMissing: ${avail.missing.join(", ")}`);
53
- }
54
- const abs = resolve(filePath);
55
- const ext = abs.split(".").pop()?.toLowerCase() ?? "";
56
- // Path 1: image inputs — tesseract handles natively.
57
- if (["jpg", "jpeg", "png", "tif", "tiff", "bmp", "gif"].includes(ext)) {
58
- return this.ocrImage(abs);
59
- }
60
- // Path 2: PDF — needs pdftoppm conversion first.
61
- // Tesseract NÃO suporta PDF nativamente (foundation impl bug 2026-05-08).
62
- if (ext === "pdf") {
63
- return this.ocrPdfViaConversion(abs);
64
- }
65
- throw new Error(`TesseractEngine: unsupported extension '${ext}' for file ${abs}`);
66
- }
67
- async ocrImage(abs) {
68
- const stdout = this.runTesseract(abs);
69
- return { markdown: stdout.trim(), pageCount: 1, costUsd: 0 };
70
- }
71
- async ocrPdfViaConversion(pdfPath) {
72
- // Workflow: pdftoppm → /tmp/ocr-<rand>-page-NN.png → tesseract per page → concat.
73
- // 200 DPI default (good balance recall vs runtime).
74
- const { mkdtempSync, rmSync, readdirSync } = await import("node:fs");
75
- const { tmpdir } = await import("node:os");
76
- const { join: pjoin } = await import("node:path");
77
- const tmpDir = mkdtempSync(pjoin(tmpdir(), "ocr-tess-"));
78
- try {
79
- const prefix = pjoin(tmpDir, "page");
80
- // pdftoppm: -png -r 200 = 200 DPI. -progress for progress info (ignored).
81
- execFileSync("pdftoppm", ["-png", "-r", "200", pdfPath, prefix], {
82
- timeout: 300_000, // 5min for conversion
83
- stdio: ["ignore", "ignore", "ignore"],
84
- });
85
- // Collect generated images, sort numerically (page-1, page-2, ..., page-10).
86
- const files = readdirSync(tmpDir)
87
- .filter((f) => f.startsWith("page") && f.endsWith(".png"))
88
- .sort((a, b) => {
89
- const na = parseInt(a.match(/page-?(\d+)/)?.[1] ?? "0", 10);
90
- const nb = parseInt(b.match(/page-?(\d+)/)?.[1] ?? "0", 10);
91
- return na - nb;
92
- });
93
- if (files.length === 0) {
94
- throw new Error(`TesseractEngine: pdftoppm produced 0 images from ${pdfPath}`);
95
- }
96
- // OCR pages with bounded concurrency (default 3 workers; tunable via env
97
- // NOX_TESSERACT_CONCURRENCY=N). Speedup: ~3-4× vs sequential on 4-core VPS.
98
- // Tesseract is CPU-bound C++; OS handles real parallelism via child processes.
99
- const concurrency = Math.max(1, Math.min(parseInt(process.env.NOX_TESSERACT_CONCURRENCY ?? "3", 10), 8));
100
- const texts = new Array(files.length);
101
- let nextIdx = 0;
102
- const workers = Array.from({ length: concurrency }, async () => {
103
- while (true) {
104
- const i = nextIdx++;
105
- if (i >= files.length)
106
- return;
107
- const text = this.runTesseract(pjoin(tmpDir, files[i]));
108
- texts[i] = text.trim();
109
- }
110
- });
111
- await Promise.all(workers);
112
- const markdown = texts.join("\n\n \n\n").trim();
113
- return { markdown, pageCount: files.length, costUsd: 0 };
114
- }
115
- finally {
116
- // Best-effort cleanup; ignore errors if tmpDir already gone.
117
- try {
118
- rmSync(tmpDir, { recursive: true, force: true });
119
- }
120
- catch {
121
- // intentionally ignored — cleanup is best-effort
122
- }
123
- }
124
- }
125
- runTesseract(imagePath) {
126
- try {
127
- return execFileSync("tesseract", [imagePath, "-", "-l", this.lang, "--psm", "1"], {
128
- encoding: "utf-8",
129
- timeout: 120_000, // 2min per page
130
- maxBuffer: 50 * 1024 * 1024,
131
- stdio: ["ignore", "pipe", "ignore"],
132
- });
133
- }
134
- catch (err) {
135
- throw new Error(`TesseractEngine: ocr failed on ${imagePath}: ${err?.message ?? err}`);
136
- }
137
- }
138
- async detectPageCount(filePath) {
139
- try {
140
- const out = execFileSync("pdfinfo", [filePath], {
141
- encoding: "utf-8",
142
- timeout: 15_000,
143
- stdio: ["ignore", "pipe", "ignore"],
144
- });
145
- const match = out.match(/^Pages:\s+(\d+)/m);
146
- return match ? parseInt(match[1], 10) : 0;
147
- }
148
- catch {
149
- return 0;
150
- }
151
- }
152
- }
153
- // ─────────────────────────────────────────────────────────────────────
154
- // Factory — dispatch por nome
155
- // ─────────────────────────────────────────────────────────────────────
156
- /**
157
- * Factory por nome. Cria engine apropriado.
158
- * - "tesseract" → TesseractEngine (CPU local, $0)
159
- * - "google_doc_ai" → GoogleDocAiEngine (cloud, $1.50/1k pages)
160
- */
161
- export function createEngine(name, opts = {}) {
162
- switch (name) {
163
- case "tesseract":
164
- return new TesseractEngine({ lang: opts.lang ?? "por" });
165
- case "google_doc_ai": {
166
- // Lazy require — evita custo de boot quando engine não usado.
167
- // Import síncrono via require() não funciona em ESM; usamos um helper
168
- // que exporta a classe pra inserir aqui em runtime.
169
- // eslint-disable-next-line @typescript-eslint/no-var-requires
170
- const { GoogleDocAiEngine } = loadGoogleDocAiSync();
171
- return new GoogleDocAiEngine({
172
- projectId: opts.projectId,
173
- location: opts.location,
174
- processorId: opts.processorId,
175
- });
176
- }
177
- default:
178
- throw new Error(`Unknown OCR engine: ${name}. Valid: tesseract, google_doc_ai.`);
179
- }
180
- }
181
- /** Alias: caller-friendly name esperado pela spec. */
182
- export function getEngine(name, opts = {}) {
183
- return createEngine(name, opts);
184
- }
185
- // Helper sync-loader pra GoogleDocAiEngine. ESM dynamic `import()` é async, mas
186
- // createEngine é sync — usamos createRequire (ESM-safe) pra resolver compiled JS.
187
- const _require = createRequire(import.meta.url);
188
- function loadGoogleDocAiSync() {
189
- return _require("./ocr-engines/google-doc-ai.js");
190
- }
@@ -1,36 +0,0 @@
1
- import type { OcrEngine, OcrResult } from "../ocr-engine-stub.js";
2
- type DocAiClient = {
3
- processDocument(req: {
4
- name: string;
5
- rawDocument: {
6
- content: Buffer | Uint8Array;
7
- mimeType: string;
8
- };
9
- skipHumanReview?: boolean;
10
- }): Promise<[DocAiResponse, unknown, unknown]>;
11
- };
12
- interface DocAiResponse {
13
- document?: {
14
- text?: string | null;
15
- pages?: unknown[] | null;
16
- } | null;
17
- }
18
- export interface GoogleDocAiEngineOpts {
19
- projectId?: string;
20
- location?: string;
21
- processorId?: string;
22
- /** Override pra testes — injeta um client mock. */
23
- client?: DocAiClient;
24
- }
25
- export declare class GoogleDocAiEngine implements OcrEngine {
26
- readonly name = "google_doc_ai";
27
- private clientPromise;
28
- private readonly processorName;
29
- private readonly injectedClient;
30
- constructor(opts?: GoogleDocAiEngineOpts);
31
- estimateCostUsd(pageCount: number): number;
32
- ocrFile(filePath: string): Promise<OcrResult>;
33
- private getClient;
34
- private callWithRetry;
35
- }
36
- export {};
@@ -1,164 +0,0 @@
1
- // google-doc-ai.ts — GoogleDocAiEngine (E12 Tier 3 cloud OCR).
2
- // Spec: memoria-nox/specs/2026-05-07-E12-tier3-ocr.md §3.5 + §4
3
- //
4
- // Implementa interface `OcrEngine` definida em ../ocr-engine-stub.ts.
5
- // SDK: @google-cloud/documentai (carrega creds via GOOGLE_APPLICATION_CREDENTIALS).
6
- //
7
- // MVP scope:
8
- // - sync API (processDocument) pra arquivos <5MB / single-shot
9
- // - retry 3× exponential backoff em RESOURCE_EXHAUSTED / UNAVAILABLE
10
- // - mimeType detection: pdf, png, jpeg, tiff
11
- // - cost estimate: $1.50 / 1k pages (OCR processor pricing 2026-05)
12
- // - fail-soft em arquivos >5MB (batchProcess deferido — requer GCS bucket)
13
- //
14
- // Renderização: usa `document.text` raw (preserva \n). Tabelas com layout
15
- // estruturado podem ser convertidas a markdown table em sessão futura — pra
16
- // MVP, raw text é suficiente pro pipeline routeIngest → ingestMarkdown.
17
- import { readFileSync, statSync } from "node:fs";
18
- import { extname } from "node:path";
19
- // Cost: $1.50 / 1k pages (Document AI OCR processor, 2026-05).
20
- // https://cloud.google.com/document-ai/pricing
21
- const PRICE_PER_PAGE_USD = 0.0015;
22
- // MVP: sync API limit. Doc AI sync `processDocument` aceita até ~20MB no wire,
23
- // mas Google recomenda batchProcess pra >5MB / multi-page. Fail-soft cutoff.
24
- const MAX_SYNC_BYTES = 5 * 1024 * 1024;
25
- // Retry config. Test override via NOX_OCR_BACKOFF_MS.
26
- const MAX_RETRIES = 3;
27
- const BASE_BACKOFF_MS = Number(process.env.NOX_OCR_BACKOFF_MS ?? 1_000);
28
- // Códigos retryable (gRPC + Doc AI semânticos).
29
- const RETRYABLE_CODES = new Set([
30
- "RESOURCE_EXHAUSTED",
31
- "UNAVAILABLE",
32
- "DEADLINE_EXCEEDED",
33
- 8, // RESOURCE_EXHAUSTED numeric
34
- 14, // UNAVAILABLE numeric
35
- 4, // DEADLINE_EXCEEDED numeric
36
- ]);
37
- export class GoogleDocAiEngine {
38
- name = "google_doc_ai";
39
- clientPromise = null;
40
- processorName;
41
- injectedClient;
42
- constructor(opts = {}) {
43
- const projectId = opts.projectId ?? process.env.GCP_PROJECT_ID;
44
- const location = opts.location ?? process.env.GCP_DOCAI_LOCATION ?? "us";
45
- const processorId = opts.processorId ?? process.env.GCP_DOCAI_PROCESSOR_ID;
46
- if (!projectId) {
47
- throw new Error("GoogleDocAiEngine: GCP_PROJECT_ID required (env or constructor opt). " +
48
- "Set in /root/.openclaw/.env on VPS or pass projectId.");
49
- }
50
- if (!processorId) {
51
- throw new Error("GoogleDocAiEngine: GCP_DOCAI_PROCESSOR_ID required (env or constructor opt).");
52
- }
53
- this.processorName = `projects/${projectId}/locations/${location}/processors/${processorId}`;
54
- this.injectedClient = opts.client;
55
- }
56
- estimateCostUsd(pageCount) {
57
- if (!Number.isFinite(pageCount) || pageCount <= 0)
58
- return 0;
59
- return pageCount * PRICE_PER_PAGE_USD;
60
- }
61
- async ocrFile(filePath) {
62
- const stat = statSync(filePath);
63
- if (stat.size > MAX_SYNC_BYTES) {
64
- throw new Error(`GoogleDocAiEngine: file too large for sync API (${stat.size} bytes > ${MAX_SYNC_BYTES}). ` +
65
- "MVP fail-soft: batchProcess (requires GCS bucket) deferred — split PDF or fallback to tesseract.");
66
- }
67
- const content = readFileSync(filePath);
68
- const mimeType = detectMimeType(filePath);
69
- const client = await this.getClient();
70
- // Imageless mode: bumps Doc AI sync page limit 15→30 (saves retry on 16-30 page docs).
71
- // Trade-off: response omits image data — we only consume `document.text` so this is free.
72
- const [response] = await this.callWithRetry(() => client.processDocument({
73
- name: this.processorName,
74
- rawDocument: { content, mimeType },
75
- skipHumanReview: true,
76
- imagelessMode: true,
77
- }));
78
- const doc = response.document ?? {};
79
- const markdown = (doc.text ?? "").toString();
80
- const pageCount = Array.isArray(doc.pages) ? doc.pages.length : 0;
81
- return {
82
- markdown,
83
- pageCount,
84
- costUsd: this.estimateCostUsd(pageCount),
85
- };
86
- }
87
- async getClient() {
88
- if (this.injectedClient)
89
- return this.injectedClient;
90
- if (!this.clientPromise) {
91
- this.clientPromise = (async () => {
92
- // Dynamic import — ESM path, evita require + permite engine carregar
93
- // mesmo se SDK não estiver instalado (lança erro só no primeiro uso).
94
- const mod = await import("@google-cloud/documentai");
95
- const Client = mod?.DocumentProcessorServiceClient ?? mod?.v1?.DocumentProcessorServiceClient;
96
- if (!Client) {
97
- throw new Error("GoogleDocAiEngine: @google-cloud/documentai SDK shape unexpected. " +
98
- "Re-run `npm install @google-cloud/documentai`.");
99
- }
100
- // Default credential resolution: GOOGLE_APPLICATION_CREDENTIALS env var
101
- // → service account JSON file. SDK handles auth.
102
- return new Client();
103
- })();
104
- }
105
- return this.clientPromise;
106
- }
107
- async callWithRetry(fn) {
108
- let lastErr;
109
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
110
- try {
111
- return await fn();
112
- }
113
- catch (err) {
114
- lastErr = err;
115
- const code = err?.code ?? err?.details?.code;
116
- const retryable = RETRYABLE_CODES.has(code) || RETRYABLE_CODES.has(String(code));
117
- if (!retryable || attempt === MAX_RETRIES) {
118
- throw enrichError(err);
119
- }
120
- const backoff = BASE_BACKOFF_MS * Math.pow(2, attempt);
121
- await sleep(backoff);
122
- }
123
- }
124
- throw enrichError(lastErr);
125
- }
126
- }
127
- // ─────────────────────────────────────────────────────────────────────
128
- // Helpers
129
- // ─────────────────────────────────────────────────────────────────────
130
- function detectMimeType(filePath) {
131
- const ext = extname(filePath).toLowerCase();
132
- switch (ext) {
133
- case ".pdf":
134
- return "application/pdf";
135
- case ".png":
136
- return "image/png";
137
- case ".jpg":
138
- case ".jpeg":
139
- return "image/jpeg";
140
- case ".tif":
141
- case ".tiff":
142
- return "image/tiff";
143
- case ".bmp":
144
- return "image/bmp";
145
- case ".gif":
146
- return "image/gif";
147
- case ".webp":
148
- return "image/webp";
149
- default:
150
- // Doc AI accepts pdf/image only — for unknown ext, default to pdf
151
- // (caller almost always passes PDFs in OCR pipeline).
152
- return "application/pdf";
153
- }
154
- }
155
- function enrichError(err) {
156
- const code = err?.code ?? err?.details?.code ?? "UNKNOWN";
157
- const msg = err?.message ?? String(err);
158
- const wrapped = new Error(`GoogleDocAiEngine: Doc AI request failed [code=${code}]: ${msg}`);
159
- wrapped.cause = err;
160
- return wrapped;
161
- }
162
- function sleep(ms) {
163
- return new Promise((resolve) => setTimeout(resolve, ms));
164
- }
@@ -1,67 +0,0 @@
1
- export type OcrJobStatus = "queued" | "running" | "success" | "failed" | "skipped";
2
- export interface EnqueueResult {
3
- jobId: number;
4
- alreadyExists: boolean;
5
- status: OcrJobStatus;
6
- }
7
- export interface OcrJobRow {
8
- id: number;
9
- source_path: string;
10
- engine: string;
11
- source_sha256: string;
12
- status: OcrJobStatus;
13
- }
14
- export interface JobStatusExtras {
15
- error?: string;
16
- charCount?: number;
17
- costUsd?: number;
18
- pageCount?: number;
19
- }
20
- export interface OcrJobStats {
21
- total: number;
22
- queued: number;
23
- running: number;
24
- success: number;
25
- failed: number;
26
- skipped: number;
27
- totalCostUsd: number;
28
- }
29
- /**
30
- * SHA256 do conteúdo do arquivo (não do path). Garante idempotência mesmo
31
- * se o mesmo PDF for movido/renomeado. Streaming-safe pra arquivos grandes
32
- * via createHash + readFileSync chunked.
33
- *
34
- * Para foundation simples: leitura inteira (PDFs típicos <50MB; se crescer
35
- * trocar pra fs.createReadStream + pipe).
36
- */
37
- export declare function sha256OfFile(filePath: string): string;
38
- /**
39
- * Enqueue um PDF pra OCR. Idempotente: se já existe job com mesmo source_sha256,
40
- * retorna jobId existente + alreadyExists=true (sem reset de status).
41
- *
42
- * @param filePath caminho absoluto do PDF
43
- * @param engine identificador do engine (ex: 'tesseract', 'google_doc_ai')
44
- */
45
- export declare function enqueueOcrJob(filePath: string, engine: string): Promise<EnqueueResult>;
46
- /**
47
- * Atualiza status de um job. Side effects:
48
- * - status='running' → seta started_at = now
49
- * - status terminal (success/failed/skipped) → seta completed_at = now
50
- * - error_message é truncado em 2000 chars
51
- */
52
- export declare function markJobStatus(jobId: number, status: OcrJobStatus, extras?: JobStatusExtras): void;
53
- /**
54
- * Lista jobs em status 'queued' (FIFO por created_at).
55
- * Usado pelo worker batch.
56
- */
57
- export declare function listPendingJobs(limit?: number): OcrJobRow[];
58
- /**
59
- * Stats agregados pra /api/health e CLI status.
60
- */
61
- export declare function getJobStats(): OcrJobStats;
62
- /**
63
- * Reset de jobs orphan ('running' há mais de N horas) pra 'queued'.
64
- * Útil em startup pra recuperar de crash mid-batch.
65
- * @param staleHours threshold em horas
66
- */
67
- export declare function resetOrphanJobs(staleHours?: number): number;
@@ -1,129 +0,0 @@
1
- // ocr-jobs.ts — Queue management para batch OCR (E12 Tier 3 foundation).
2
- // Spec: memoria-nox/specs/2026-05-07-E12-tier3-ocr.md §5.2 + §6
3
- //
4
- // DB-only: sem cloud calls, sem engine invocation. Apenas:
5
- // - enqueue (idempotente via source_sha256 UNIQUE)
6
- // - status transitions (queued → running → success/failed/skipped)
7
- // - listar pendentes
8
- // - stats agregados
9
- //
10
- // Idempotência: re-enqueue do mesmo PDF (mesmo SHA256) retorna o mesmo jobId,
11
- // alreadyExists=true. Cobertura do risk #7 (re-run não re-cobra cloud).
12
- import { createHash } from "node:crypto";
13
- import { readFileSync, statSync, existsSync } from "node:fs";
14
- import { getDb } from "../db.js";
15
- /**
16
- * SHA256 do conteúdo do arquivo (não do path). Garante idempotência mesmo
17
- * se o mesmo PDF for movido/renomeado. Streaming-safe pra arquivos grandes
18
- * via createHash + readFileSync chunked.
19
- *
20
- * Para foundation simples: leitura inteira (PDFs típicos <50MB; se crescer
21
- * trocar pra fs.createReadStream + pipe).
22
- */
23
- export function sha256OfFile(filePath) {
24
- if (!existsSync(filePath))
25
- throw new Error(`sha256OfFile: file not found: ${filePath}`);
26
- const buf = readFileSync(filePath);
27
- return createHash("sha256").update(buf).digest("hex");
28
- }
29
- /**
30
- * Enqueue um PDF pra OCR. Idempotente: se já existe job com mesmo source_sha256,
31
- * retorna jobId existente + alreadyExists=true (sem reset de status).
32
- *
33
- * @param filePath caminho absoluto do PDF
34
- * @param engine identificador do engine (ex: 'tesseract', 'google_doc_ai')
35
- */
36
- export async function enqueueOcrJob(filePath, engine) {
37
- if (!existsSync(filePath))
38
- throw new Error(`enqueueOcrJob: file not found: ${filePath}`);
39
- const db = getDb();
40
- const sha = sha256OfFile(filePath);
41
- const sizeBytes = statSync(filePath).size;
42
- // Try INSERT — UNIQUE(source_sha256) garante idempotência.
43
- const insertStmt = db.prepare("INSERT INTO ocr_jobs (source_path, source_sha256, source_size_bytes, engine, status) VALUES (?, ?, ?, ?, 'queued') ON CONFLICT(source_sha256) DO NOTHING");
44
- const r = insertStmt.run(filePath, sha, sizeBytes, engine);
45
- if (r.changes > 0) {
46
- return { jobId: Number(r.lastInsertRowid), alreadyExists: false, status: "queued" };
47
- }
48
- // Job já existe — fetch jobId e status atual.
49
- const existing = db
50
- .prepare("SELECT id, status FROM ocr_jobs WHERE source_sha256 = ?")
51
- .get(sha);
52
- if (!existing) {
53
- // Edge case: INSERT falhou + SELECT vazio = race ou DB corruption.
54
- throw new Error(`enqueueOcrJob: insert ON CONFLICT but row missing for sha=${sha}`);
55
- }
56
- return { jobId: existing.id, alreadyExists: true, status: existing.status };
57
- }
58
- /**
59
- * Atualiza status de um job. Side effects:
60
- * - status='running' → seta started_at = now
61
- * - status terminal (success/failed/skipped) → seta completed_at = now
62
- * - error_message é truncado em 2000 chars
63
- */
64
- export function markJobStatus(jobId, status, extras = {}) {
65
- const db = getDb();
66
- const errorMsg = extras.error
67
- ? extras.error.length > 2000
68
- ? extras.error.substring(0, 1980) + "…[truncated]"
69
- : extras.error
70
- : null;
71
- if (status === "running") {
72
- db.prepare("UPDATE ocr_jobs SET status = ?, started_at = COALESCE(started_at, datetime('now')) WHERE id = ?").run(status, jobId);
73
- return;
74
- }
75
- // Terminal status: seta completed_at + extras.
76
- db.prepare(`UPDATE ocr_jobs
77
- SET status = ?,
78
- completed_at = datetime('now'),
79
- error_message = COALESCE(?, error_message),
80
- char_count = COALESCE(?, char_count),
81
- cost_usd = COALESCE(?, cost_usd),
82
- page_count = COALESCE(?, page_count)
83
- WHERE id = ?`).run(status, errorMsg, extras.charCount ?? null, extras.costUsd ?? null, extras.pageCount ?? null, jobId);
84
- }
85
- /**
86
- * Lista jobs em status 'queued' (FIFO por created_at).
87
- * Usado pelo worker batch.
88
- */
89
- export function listPendingJobs(limit = 50) {
90
- const db = getDb();
91
- const rows = db
92
- .prepare("SELECT id, source_path, engine, source_sha256, status FROM ocr_jobs WHERE status = 'queued' ORDER BY created_at ASC LIMIT ?")
93
- .all(limit);
94
- return rows;
95
- }
96
- /**
97
- * Stats agregados pra /api/health e CLI status.
98
- */
99
- export function getJobStats() {
100
- const db = getDb();
101
- const row = db
102
- .prepare(`SELECT
103
- COUNT(*) AS total,
104
- COALESCE(SUM(CASE WHEN status='queued' THEN 1 ELSE 0 END), 0) AS queued,
105
- COALESCE(SUM(CASE WHEN status='running' THEN 1 ELSE 0 END), 0) AS running,
106
- COALESCE(SUM(CASE WHEN status='success' THEN 1 ELSE 0 END), 0) AS success,
107
- COALESCE(SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END), 0) AS failed,
108
- COALESCE(SUM(CASE WHEN status='skipped' THEN 1 ELSE 0 END), 0) AS skipped,
109
- COALESCE(SUM(cost_usd), 0) AS totalCostUsd
110
- FROM ocr_jobs`)
111
- .get();
112
- return row;
113
- }
114
- /**
115
- * Reset de jobs orphan ('running' há mais de N horas) pra 'queued'.
116
- * Útil em startup pra recuperar de crash mid-batch.
117
- * @param staleHours threshold em horas
118
- */
119
- export function resetOrphanJobs(staleHours = 6) {
120
- const db = getDb();
121
- const r = db
122
- .prepare(`UPDATE ocr_jobs
123
- SET status = 'queued', started_at = NULL
124
- WHERE status = 'running'
125
- AND started_at IS NOT NULL
126
- AND started_at < datetime('now', ?)`)
127
- .run(`-${staleHours} hours`);
128
- return r.changes;
129
- }
@@ -1,86 +0,0 @@
1
- /**
2
- * G10 — ran_at server-side enforcement for audit tables.
3
- *
4
- * Gap from THREAT-MODEL.md §3.4 / G10:
5
- * "ops_audit.ran_at field stored as user-supplied timestamp could be
6
- * backdated to hide actions."
7
- *
8
- * This module provides:
9
- * 1. Application-layer guard that overrides backdated timestamps before INSERT.
10
- * Defence-in-depth alongside the SQL trigger in v23-audit-ran-at-trigger.sql.
11
- *
12
- * 2. insertWithServerTimestamp() — wrapper around DB INSERT that forces
13
- * server-side time regardless of caller-supplied value.
14
- *
15
- * 3. validateAuditTimestamp() — utility to check whether a timestamp
16
- * is within acceptable skew (< 24h drift from now).
17
- *
18
- * The SQL trigger in v23 is the primary control. This module is secondary
19
- * (defence-in-depth) — handles cases where the trigger is not yet applied
20
- * or is on a different DB file.
21
- *
22
- * Ref: THREAT-MODEL.md G10 (medium priority).
23
- * staged-G10/edits/migrations/v23-audit-ran-at-trigger.sql.
24
- */
25
- /** Max allowable drift between caller-supplied timestamp and server time (ms). */
26
- export declare const MAX_TIMESTAMP_DRIFT_MS: number;
27
- /** Max allowable ISO 8601 drift for confidence_eval_log.ran_at. */
28
- export declare const MAX_ISO_DRIFT_MS: number;
29
- export interface AuditRow {
30
- ran_at?: number | string;
31
- started_at?: number;
32
- [key: string]: unknown;
33
- }
34
- export type AuditRowWithServerTime<T extends AuditRow> = Omit<T, "ran_at" | "started_at"> & {
35
- ran_at: number | string;
36
- started_at?: number;
37
- };
38
- /**
39
- * serverTimestampMs — current server time in Unix milliseconds.
40
- * Extracted for testability (mock in tests).
41
- */
42
- export declare function serverTimestampMs(): number;
43
- /**
44
- * serverTimestampIso — current server time in ISO 8601 UTC.
45
- */
46
- export declare function serverTimestampIso(): string;
47
- /**
48
- * validateAuditTimestamp — checks whether a numeric ms timestamp is within
49
- * MAX_TIMESTAMP_DRIFT_MS of server time.
50
- *
51
- * Returns { valid: true } or { valid: false, driftMs: number }.
52
- */
53
- export declare function validateAuditTimestamp(suppliedMs: number, nowMs?: number): {
54
- valid: true;
55
- } | {
56
- valid: false;
57
- driftMs: number;
58
- };
59
- /**
60
- * validateAuditTimestampIso — checks whether an ISO 8601 string is within
61
- * MAX_ISO_DRIFT_MS of server time.
62
- */
63
- export declare function validateAuditTimestampIso(suppliedIso: string, nowMs?: number): {
64
- valid: true;
65
- } | {
66
- valid: false;
67
- driftMs: number;
68
- };
69
- /**
70
- * overrideWithServerTime — returns row with started_at / ran_at forced to
71
- * server-side time, regardless of supplied values.
72
- *
73
- * For ops_audit: overrides started_at (INTEGER ms).
74
- * For confidence_eval_log: overrides ran_at (TEXT ISO 8601).
75
- *
76
- * @param row - input row (partial or full)
77
- * @param mode - "ops_audit" | "confidence_eval_log"
78
- */
79
- export declare function overrideWithServerTime<T extends AuditRow>(row: T, mode: "ops_audit" | "confidence_eval_log"): AuditRowWithServerTime<T>;
80
- /**
81
- * warnIfBackdated — logs a warning if the supplied timestamp is more than
82
- * MAX_TIMESTAMP_DRIFT_MS in the past. Does not throw — informational only.
83
- *
84
- * Used in development / testing to surface potential issues.
85
- */
86
- export declare function warnIfBackdated(field: string, suppliedMs: number, nowMs?: number): void;