nox-mem 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (457) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -0
  3. package/dist/api/answer.d.ts +116 -0
  4. package/dist/api/answer.js +274 -0
  5. package/dist/api/answer.validate-patch.d.ts +72 -0
  6. package/dist/api/answer.validate-patch.js +52 -0
  7. package/dist/api/brief-diversity.d.ts +64 -0
  8. package/dist/api/brief-diversity.js +91 -0
  9. package/dist/api/brief.d.ts +114 -0
  10. package/dist/api/brief.js +524 -0
  11. package/dist/api/conflict.d.ts +33 -0
  12. package/dist/api/conflict.js +143 -0
  13. package/dist/api/cors.d.ts +73 -0
  14. package/dist/api/cors.js +124 -0
  15. package/dist/api/events-stream-limited.d.ts +133 -0
  16. package/dist/api/events-stream-limited.js +217 -0
  17. package/dist/api/events-stream.d.ts +53 -0
  18. package/dist/api/events-stream.js +125 -0
  19. package/dist/api/export.d.ts +42 -0
  20. package/dist/api/export.js +85 -0
  21. package/dist/api/health-confidence-adapter.d.ts +29 -0
  22. package/dist/api/health-confidence-adapter.js +73 -0
  23. package/dist/api/health-confidence.d.ts +36 -0
  24. package/dist/api/health-confidence.js +141 -0
  25. package/dist/api/hooks.d.ts +50 -0
  26. package/dist/api/hooks.js +115 -0
  27. package/dist/api/import.d.ts +38 -0
  28. package/dist/api/import.js +87 -0
  29. package/dist/api/ingest-event.d.ts +65 -0
  30. package/dist/api/ingest-event.js +153 -0
  31. package/dist/api/mark.d.ts +42 -0
  32. package/dist/api/mark.js +127 -0
  33. package/dist/api/server-deps-a2.d.ts +55 -0
  34. package/dist/api/server-deps-a2.js +138 -0
  35. package/dist/api/server-deps-l2-l3.d.ts +68 -0
  36. package/dist/api/server-deps-l2-l3.js +123 -0
  37. package/dist/api/server-deps-p1.d.ts +84 -0
  38. package/dist/api/server-deps-p1.js +156 -0
  39. package/dist/api/server-deps-p2.d.ts +32 -0
  40. package/dist/api/server-deps-p2.js +84 -0
  41. package/dist/api/server-deps-p5.d.ts +66 -0
  42. package/dist/api/server-deps-p5.js +139 -0
  43. package/dist/api/viewer-static.d.ts +30 -0
  44. package/dist/api/viewer-static.js +102 -0
  45. package/dist/api/wire-up.d.ts +54 -0
  46. package/dist/api/wire-up.js +521 -0
  47. package/dist/api-impact.d.ts +30 -0
  48. package/dist/api-impact.js +196 -0
  49. package/dist/api-server.d.ts +2 -0
  50. package/dist/api-server.js +614 -0
  51. package/dist/backfill-fts-anchor.d.ts +15 -0
  52. package/dist/backfill-fts-anchor.js +97 -0
  53. package/dist/backfill-source-type.d.ts +20 -0
  54. package/dist/backfill-source-type.js +182 -0
  55. package/dist/churn.d.ts +31 -0
  56. package/dist/churn.js +98 -0
  57. package/dist/cli/answer.d.ts +66 -0
  58. package/dist/cli/answer.js +287 -0
  59. package/dist/cli/conflict.d.ts +38 -0
  60. package/dist/cli/conflict.js +282 -0
  61. package/dist/cli/export.d.ts +51 -0
  62. package/dist/cli/export.js +280 -0
  63. package/dist/cli/hooks.d.ts +54 -0
  64. package/dist/cli/hooks.js +133 -0
  65. package/dist/cli/import.d.ts +52 -0
  66. package/dist/cli/import.js +274 -0
  67. package/dist/cli/mark.d.ts +33 -0
  68. package/dist/cli/mark.js +130 -0
  69. package/dist/cli/ocr-batch.d.ts +12 -0
  70. package/dist/cli/ocr-batch.js +411 -0
  71. package/dist/cli/snapshot-main.d.ts +30 -0
  72. package/dist/cli/snapshot-main.js +47 -0
  73. package/dist/cli/viewer.d.ts +35 -0
  74. package/dist/cli/viewer.js +71 -0
  75. package/dist/cli-telemetry.d.ts +36 -0
  76. package/dist/cli-telemetry.js +150 -0
  77. package/dist/compact.d.ts +7 -0
  78. package/dist/compact.js +147 -0
  79. package/dist/consolidate.d.ts +18 -0
  80. package/dist/consolidate.js +475 -0
  81. package/dist/consolidation.d.ts +32 -0
  82. package/dist/consolidation.js +212 -0
  83. package/dist/cross-agent-v2.d.ts +45 -0
  84. package/dist/cross-agent-v2.js +271 -0
  85. package/dist/cross-search.d.ts +11 -0
  86. package/dist/cross-search.js +119 -0
  87. package/dist/crystallize.d.ts +43 -0
  88. package/dist/crystallize.js +111 -0
  89. package/dist/db.d.ts +11 -0
  90. package/dist/db.js +388 -0
  91. package/dist/dedup.d.ts +1 -0
  92. package/dist/dedup.js +106 -0
  93. package/dist/detect-changes.d.ts +29 -0
  94. package/dist/detect-changes.js +236 -0
  95. package/dist/digest.d.ts +1 -0
  96. package/dist/digest.js +205 -0
  97. package/dist/doctor.d.ts +1 -0
  98. package/dist/doctor.js +71 -0
  99. package/dist/embed.d.ts +45 -0
  100. package/dist/embed.js +257 -0
  101. package/dist/evals.d.ts +176 -0
  102. package/dist/evals.js +351 -0
  103. package/dist/generate-user-profile.d.ts +18 -0
  104. package/dist/generate-user-profile.js +163 -0
  105. package/dist/graphify-ingest.d.ts +18 -0
  106. package/dist/graphify-ingest.js +158 -0
  107. package/dist/impact.d.ts +39 -0
  108. package/dist/impact.js +143 -0
  109. package/dist/index.d.ts +2 -0
  110. package/dist/index.js +689 -0
  111. package/dist/ingest-entity.d.ts +44 -0
  112. package/dist/ingest-entity.js +197 -0
  113. package/dist/ingest.d.ts +13 -0
  114. package/dist/ingest.js +210 -0
  115. package/dist/kg-llm.d.ts +39 -0
  116. package/dist/kg-llm.js +295 -0
  117. package/dist/knowledge-graph.d.ts +72 -0
  118. package/dist/knowledge-graph.js +507 -0
  119. package/dist/lib/answer/config.d.ts +41 -0
  120. package/dist/lib/answer/config.js +70 -0
  121. package/dist/lib/answer/index.d.ts +47 -0
  122. package/dist/lib/answer/index.js +221 -0
  123. package/dist/lib/answer/prompt.d.ts +37 -0
  124. package/dist/lib/answer/prompt.js +88 -0
  125. package/dist/lib/answer/provider.d.ts +47 -0
  126. package/dist/lib/answer/provider.js +101 -0
  127. package/dist/lib/answer/retrieval.d.ts +36 -0
  128. package/dist/lib/answer/retrieval.js +92 -0
  129. package/dist/lib/answer/telemetry.d.ts +99 -0
  130. package/dist/lib/answer/telemetry.js +154 -0
  131. package/dist/lib/answer/types.d.ts +108 -0
  132. package/dist/lib/answer/types.js +1 -0
  133. package/dist/lib/api/error-leak-fix.d.ts +54 -0
  134. package/dist/lib/api/error-leak-fix.js +55 -0
  135. package/dist/lib/api/safe-error-message.d.ts +70 -0
  136. package/dist/lib/api/safe-error-message.js +122 -0
  137. package/dist/lib/archive/common-passwords.d.ts +37 -0
  138. package/dist/lib/archive/common-passwords.js +753 -0
  139. package/dist/lib/archive/encryption.d.ts +81 -0
  140. package/dist/lib/archive/encryption.js +236 -0
  141. package/dist/lib/archive/enforce-strength.d.ts +54 -0
  142. package/dist/lib/archive/enforce-strength.js +70 -0
  143. package/dist/lib/archive/entropy.d.ts +34 -0
  144. package/dist/lib/archive/entropy.js +180 -0
  145. package/dist/lib/archive/export-locking.d.ts +102 -0
  146. package/dist/lib/archive/export-locking.js +202 -0
  147. package/dist/lib/archive/format.d.ts +20 -0
  148. package/dist/lib/archive/format.js +174 -0
  149. package/dist/lib/archive/index.d.ts +23 -0
  150. package/dist/lib/archive/index.js +17 -0
  151. package/dist/lib/archive/manifest.d.ts +53 -0
  152. package/dist/lib/archive/manifest.js +183 -0
  153. package/dist/lib/archive/migration.d.ts +36 -0
  154. package/dist/lib/archive/migration.js +100 -0
  155. package/dist/lib/archive/migrations/v18_to_v19.d.ts +16 -0
  156. package/dist/lib/archive/migrations/v18_to_v19.js +18 -0
  157. package/dist/lib/archive/orchestrator.d.ts +166 -0
  158. package/dist/lib/archive/orchestrator.js +428 -0
  159. package/dist/lib/archive/serializers/chunks.d.ts +30 -0
  160. package/dist/lib/archive/serializers/chunks.js +113 -0
  161. package/dist/lib/archive/serializers/embeddings.d.ts +36 -0
  162. package/dist/lib/archive/serializers/embeddings.js +115 -0
  163. package/dist/lib/archive/serializers/kg.d.ts +28 -0
  164. package/dist/lib/archive/serializers/kg.js +184 -0
  165. package/dist/lib/archive/serializers/ops_audit.d.ts +21 -0
  166. package/dist/lib/archive/serializers/ops_audit.js +97 -0
  167. package/dist/lib/archive/server-deps.d.ts +131 -0
  168. package/dist/lib/archive/server-deps.js +232 -0
  169. package/dist/lib/archive/strength.d.ts +50 -0
  170. package/dist/lib/archive/strength.js +77 -0
  171. package/dist/lib/archive/types.d.ts +159 -0
  172. package/dist/lib/archive/types.js +45 -0
  173. package/dist/lib/archive/unpack-streaming.d.ts +70 -0
  174. package/dist/lib/archive/unpack-streaming.js +255 -0
  175. package/dist/lib/auth/localhost-guard.d.ts +106 -0
  176. package/dist/lib/auth/localhost-guard.js +164 -0
  177. package/dist/lib/confidence/config.d.ts +37 -0
  178. package/dist/lib/confidence/config.js +107 -0
  179. package/dist/lib/confidence/db-shim-singleton.d.ts +20 -0
  180. package/dist/lib/confidence/db-shim-singleton.js +41 -0
  181. package/dist/lib/confidence/db-shim.d.ts +47 -0
  182. package/dist/lib/confidence/db-shim.js +141 -0
  183. package/dist/lib/confidence/mark.d.ts +58 -0
  184. package/dist/lib/confidence/mark.js +168 -0
  185. package/dist/lib/confidence/ranking.d.ts +69 -0
  186. package/dist/lib/confidence/ranking.js +101 -0
  187. package/dist/lib/confidence/search-filter.d.ts +44 -0
  188. package/dist/lib/confidence/search-filter.js +103 -0
  189. package/dist/lib/confidence/types.d.ts +146 -0
  190. package/dist/lib/confidence/types.js +20 -0
  191. package/dist/lib/confidence/write-hooks.d.ts +50 -0
  192. package/dist/lib/confidence/write-hooks.js +159 -0
  193. package/dist/lib/conflict/audit-fk-check.d.ts +72 -0
  194. package/dist/lib/conflict/audit-fk-check.js +131 -0
  195. package/dist/lib/conflict/audit-writer.d.ts +39 -0
  196. package/dist/lib/conflict/audit-writer.js +133 -0
  197. package/dist/lib/conflict/db-singleton.d.ts +28 -0
  198. package/dist/lib/conflict/db-singleton.js +61 -0
  199. package/dist/lib/conflict/db.d.ts +27 -0
  200. package/dist/lib/conflict/db.js +20 -0
  201. package/dist/lib/conflict/detector-direct.d.ts +21 -0
  202. package/dist/lib/conflict/detector-direct.js +105 -0
  203. package/dist/lib/conflict/evidence.d.ts +24 -0
  204. package/dist/lib/conflict/evidence.js +76 -0
  205. package/dist/lib/conflict/index.d.ts +14 -0
  206. package/dist/lib/conflict/index.js +12 -0
  207. package/dist/lib/conflict/scheduler.d.ts +78 -0
  208. package/dist/lib/conflict/scheduler.js +111 -0
  209. package/dist/lib/conflict/shadow.d.ts +75 -0
  210. package/dist/lib/conflict/shadow.js +161 -0
  211. package/dist/lib/conflict/types.d.ts +133 -0
  212. package/dist/lib/conflict/types.js +19 -0
  213. package/dist/lib/cost-cap.d.ts +94 -0
  214. package/dist/lib/cost-cap.js +129 -0
  215. package/dist/lib/deps/deps-registry.d.ts +111 -0
  216. package/dist/lib/deps/deps-registry.js +209 -0
  217. package/dist/lib/error-sanitizer/middleware.d.ts +43 -0
  218. package/dist/lib/error-sanitizer/middleware.js +100 -0
  219. package/dist/lib/error-sanitizer/sanitize.d.ts +78 -0
  220. package/dist/lib/error-sanitizer/sanitize.js +202 -0
  221. package/dist/lib/eval-batch.d.ts +34 -0
  222. package/dist/lib/eval-batch.js +103 -0
  223. package/dist/lib/eval-metrics.d.ts +36 -0
  224. package/dist/lib/eval-metrics.js +95 -0
  225. package/dist/lib/eval.d.ts +106 -0
  226. package/dist/lib/eval.js +343 -0
  227. package/dist/lib/events/bus.d.ts +135 -0
  228. package/dist/lib/events/bus.js +95 -0
  229. package/dist/lib/fts-anchor.d.ts +1 -0
  230. package/dist/lib/fts-anchor.js +131 -0
  231. package/dist/lib/hooks/classifier.d.ts +47 -0
  232. package/dist/lib/hooks/classifier.js +129 -0
  233. package/dist/lib/hooks/config.d.ts +49 -0
  234. package/dist/lib/hooks/config.js +106 -0
  235. package/dist/lib/hooks/decorators.d.ts +35 -0
  236. package/dist/lib/hooks/decorators.js +59 -0
  237. package/dist/lib/hooks/pipeline.d.ts +76 -0
  238. package/dist/lib/hooks/pipeline.js +213 -0
  239. package/dist/lib/hooks/privacy-filter-adapter.d.ts +55 -0
  240. package/dist/lib/hooks/privacy-filter-adapter.js +84 -0
  241. package/dist/lib/hooks/rate-limit-constant-time.d.ts +57 -0
  242. package/dist/lib/hooks/rate-limit-constant-time.js +69 -0
  243. package/dist/lib/hooks/rate-limit-dryrun-fix.d.ts +71 -0
  244. package/dist/lib/hooks/rate-limit-dryrun-fix.js +110 -0
  245. package/dist/lib/hooks/rate-limit.d.ts +54 -0
  246. package/dist/lib/hooks/rate-limit.js +122 -0
  247. package/dist/lib/hooks/server-deps.d.ts +61 -0
  248. package/dist/lib/hooks/server-deps.js +92 -0
  249. package/dist/lib/hooks/source-allowlist.d.ts +26 -0
  250. package/dist/lib/hooks/source-allowlist.js +53 -0
  251. package/dist/lib/hooks/types.d.ts +129 -0
  252. package/dist/lib/hooks/types.js +24 -0
  253. package/dist/lib/hooks/worker.d.ts +56 -0
  254. package/dist/lib/hooks/worker.js +150 -0
  255. package/dist/lib/ingest-router.d.ts +25 -0
  256. package/dist/lib/ingest-router.js +103 -0
  257. package/dist/lib/ocr-detector.d.ts +61 -0
  258. package/dist/lib/ocr-detector.js +138 -0
  259. package/dist/lib/ocr-engine-stub.d.ts +48 -0
  260. package/dist/lib/ocr-engine-stub.js +190 -0
  261. package/dist/lib/ocr-engines/google-doc-ai.d.ts +36 -0
  262. package/dist/lib/ocr-engines/google-doc-ai.js +164 -0
  263. package/dist/lib/ocr-jobs.d.ts +67 -0
  264. package/dist/lib/ocr-jobs.js +129 -0
  265. package/dist/lib/op-audit-extension/ran-at-guard.d.ts +86 -0
  266. package/dist/lib/op-audit-extension/ran-at-guard.js +110 -0
  267. package/dist/lib/op-audit.d.ts +71 -0
  268. package/dist/lib/op-audit.js +777 -0
  269. package/dist/lib/privacy-br/detector.d.ts +42 -0
  270. package/dist/lib/privacy-br/detector.js +130 -0
  271. package/dist/lib/privacy-br/index.d.ts +20 -0
  272. package/dist/lib/privacy-br/index.js +20 -0
  273. package/dist/lib/privacy-br/integration.d.ts +71 -0
  274. package/dist/lib/privacy-br/integration.js +74 -0
  275. package/dist/lib/privacy-br/patterns.d.ts +117 -0
  276. package/dist/lib/privacy-br/patterns.js +434 -0
  277. package/dist/lib/privacy-br/redact.d.ts +42 -0
  278. package/dist/lib/privacy-br/redact.js +103 -0
  279. package/dist/lib/privacy-br/types.d.ts +55 -0
  280. package/dist/lib/privacy-br/types.js +25 -0
  281. package/dist/lib/regex-extract/extractor.d.ts +30 -0
  282. package/dist/lib/regex-extract/extractor.js +91 -0
  283. package/dist/lib/regex-extract/frontmatter.d.ts +44 -0
  284. package/dist/lib/regex-extract/frontmatter.js +169 -0
  285. package/dist/lib/regex-extract/index.d.ts +14 -0
  286. package/dist/lib/regex-extract/index.js +14 -0
  287. package/dist/lib/regex-extract/ingest-router-l4.d.ts +76 -0
  288. package/dist/lib/regex-extract/ingest-router-l4.js +102 -0
  289. package/dist/lib/regex-extract/patterns.d.ts +61 -0
  290. package/dist/lib/regex-extract/patterns.js +91 -0
  291. package/dist/lib/regex-extract/production-wire.d.ts +128 -0
  292. package/dist/lib/regex-extract/production-wire.js +202 -0
  293. package/dist/lib/regex-extract/reconcile.d.ts +162 -0
  294. package/dist/lib/regex-extract/reconcile.js +210 -0
  295. package/dist/lib/regex-extract/strip-code.d.ts +24 -0
  296. package/dist/lib/regex-extract/strip-code.js +52 -0
  297. package/dist/lib/regex-extract/types.d.ts +48 -0
  298. package/dist/lib/regex-extract/types.js +25 -0
  299. package/dist/lib/reranker.d.ts +80 -0
  300. package/dist/lib/reranker.js +324 -0
  301. package/dist/lib/shadow-tracker.d.ts +191 -0
  302. package/dist/lib/shadow-tracker.js +384 -0
  303. package/dist/lib/spo-injection.d.ts +52 -0
  304. package/dist/lib/spo-injection.js +166 -0
  305. package/dist/lib/telemetry-collector.d.ts +158 -0
  306. package/dist/lib/telemetry-collector.js +249 -0
  307. package/dist/lib/temporal-detector.d.ts +27 -0
  308. package/dist/lib/temporal-detector.js +81 -0
  309. package/dist/lib/viewer/auth.d.ts +37 -0
  310. package/dist/lib/viewer/auth.js +70 -0
  311. package/dist/lib/viewer/backpressure.d.ts +59 -0
  312. package/dist/lib/viewer/backpressure.js +100 -0
  313. package/dist/lib/viewer/broadcast-singleton.d.ts +34 -0
  314. package/dist/lib/viewer/broadcast-singleton.js +49 -0
  315. package/dist/lib/viewer/broadcast.d.ts +66 -0
  316. package/dist/lib/viewer/broadcast.js +96 -0
  317. package/dist/lib/viewer/event-types.d.ts +132 -0
  318. package/dist/lib/viewer/event-types.js +74 -0
  319. package/dist/lib/viewer/instrumentation.d.ts +106 -0
  320. package/dist/lib/viewer/instrumentation.js +224 -0
  321. package/dist/lib/viewer/migration.d.ts +23 -0
  322. package/dist/lib/viewer/migration.js +56 -0
  323. package/dist/lib/viewer/redaction.d.ts +44 -0
  324. package/dist/lib/viewer/redaction.js +139 -0
  325. package/dist/lib/viewer/session.d.ts +51 -0
  326. package/dist/lib/viewer/session.js +87 -0
  327. package/dist/mcp/tools/answer.d.ts +94 -0
  328. package/dist/mcp/tools/answer.js +213 -0
  329. package/dist/mcp/tools/archive.d.ts +152 -0
  330. package/dist/mcp/tools/archive.js +170 -0
  331. package/dist/mcp/tools/conflict.d.ts +44 -0
  332. package/dist/mcp/tools/conflict.js +130 -0
  333. package/dist/mcp/tools/hooks.d.ts +29 -0
  334. package/dist/mcp/tools/hooks.js +78 -0
  335. package/dist/mcp/tools/mark.d.ts +38 -0
  336. package/dist/mcp/tools/mark.js +82 -0
  337. package/dist/mcp/tools/viewer.d.ts +58 -0
  338. package/dist/mcp/tools/viewer.js +64 -0
  339. package/dist/mcp-server.d.ts +2 -0
  340. package/dist/mcp-server.js +395 -0
  341. package/dist/metrics.d.ts +3 -0
  342. package/dist/metrics.js +59 -0
  343. package/dist/noise-filter.d.ts +18 -0
  344. package/dist/noise-filter.js +142 -0
  345. package/dist/notion-sync.d.ts +7 -0
  346. package/dist/notion-sync.js +97 -0
  347. package/dist/observability/adapters/a3-adapter.d.ts +63 -0
  348. package/dist/observability/adapters/a3-adapter.js +83 -0
  349. package/dist/observability/adapters/p1-adapter.d.ts +49 -0
  350. package/dist/observability/adapters/p1-adapter.js +63 -0
  351. package/dist/observability/adapters/p5-adapter.d.ts +36 -0
  352. package/dist/observability/adapters/p5-adapter.js +71 -0
  353. package/dist/observability/cardinality.d.ts +61 -0
  354. package/dist/observability/cardinality.js +300 -0
  355. package/dist/observability/collectors/db-stats.collector.d.ts +9 -0
  356. package/dist/observability/collectors/db-stats.collector.js +88 -0
  357. package/dist/observability/collectors/eventbus.collector.d.ts +6 -0
  358. package/dist/observability/collectors/eventbus.collector.js +50 -0
  359. package/dist/observability/collectors/process.collector.d.ts +7 -0
  360. package/dist/observability/collectors/process.collector.js +93 -0
  361. package/dist/observability/collectors/provider-telemetry.collector.d.ts +11 -0
  362. package/dist/observability/collectors/provider-telemetry.collector.js +112 -0
  363. package/dist/observability/collectors/search-telemetry.collector.d.ts +12 -0
  364. package/dist/observability/collectors/search-telemetry.collector.js +76 -0
  365. package/dist/observability/exporter.d.ts +30 -0
  366. package/dist/observability/exporter.js +182 -0
  367. package/dist/observability/index.d.ts +22 -0
  368. package/dist/observability/index.js +21 -0
  369. package/dist/observability/metrics.d.ts +53 -0
  370. package/dist/observability/metrics.js +213 -0
  371. package/dist/observability/privacy-guard.d.ts +32 -0
  372. package/dist/observability/privacy-guard.js +116 -0
  373. package/dist/observability/record.d.ts +83 -0
  374. package/dist/observability/record.js +217 -0
  375. package/dist/observability/registry.d.ts +60 -0
  376. package/dist/observability/registry.js +93 -0
  377. package/dist/observability/types.d.ts +115 -0
  378. package/dist/observability/types.js +235 -0
  379. package/dist/observability.d.ts +131 -0
  380. package/dist/observability.js +234 -0
  381. package/dist/plugins/nox-hooks/index.d.ts +61 -0
  382. package/dist/plugins/nox-hooks/index.js +99 -0
  383. package/dist/primer.d.ts +1 -0
  384. package/dist/primer.js +100 -0
  385. package/dist/privacy/filter.d.ts +27 -0
  386. package/dist/privacy/filter.js +74 -0
  387. package/dist/privacy/patterns.d.ts +29 -0
  388. package/dist/privacy/patterns.js +178 -0
  389. package/dist/privacy/tag-parser.d.ts +24 -0
  390. package/dist/privacy/tag-parser.js +29 -0
  391. package/dist/project-context-gen.d.ts +10 -0
  392. package/dist/project-context-gen.js +106 -0
  393. package/dist/providers/embedding/gemini.d.ts +73 -0
  394. package/dist/providers/embedding/gemini.js +118 -0
  395. package/dist/providers/embedding/openai.d.ts +76 -0
  396. package/dist/providers/embedding/openai.js +123 -0
  397. package/dist/providers/embedding/types.d.ts +39 -0
  398. package/dist/providers/embedding/types.js +1 -0
  399. package/dist/providers/embedding/voyage.d.ts +36 -0
  400. package/dist/providers/embedding/voyage.js +29 -0
  401. package/dist/providers/index.d.ts +116 -0
  402. package/dist/providers/index.js +158 -0
  403. package/dist/providers/llm/anthropic.d.ts +29 -0
  404. package/dist/providers/llm/anthropic.js +28 -0
  405. package/dist/providers/llm/chain.d.ts +99 -0
  406. package/dist/providers/llm/chain.js +213 -0
  407. package/dist/providers/llm/gemini.d.ts +48 -0
  408. package/dist/providers/llm/gemini.js +96 -0
  409. package/dist/providers/llm/openai.d.ts +64 -0
  410. package/dist/providers/llm/openai.js +109 -0
  411. package/dist/providers/llm/types.d.ts +47 -0
  412. package/dist/providers/llm/types.js +1 -0
  413. package/dist/providers/telemetry.d.ts +87 -0
  414. package/dist/providers/telemetry.js +156 -0
  415. package/dist/providers/types.d.ts +42 -0
  416. package/dist/providers/types.js +59 -0
  417. package/dist/query-entity-count.d.ts +54 -0
  418. package/dist/query-entity-count.js +171 -0
  419. package/dist/reflect.d.ts +26 -0
  420. package/dist/reflect.js +290 -0
  421. package/dist/reindex-errors.d.ts +7 -0
  422. package/dist/reindex-errors.js +21 -0
  423. package/dist/reindex.d.ts +16 -0
  424. package/dist/reindex.js +293 -0
  425. package/dist/retention.d.ts +40 -0
  426. package/dist/retention.js +86 -0
  427. package/dist/salience.d.ts +85 -0
  428. package/dist/salience.js +245 -0
  429. package/dist/scripts/migrate-v17-ops-audit.d.ts +17 -0
  430. package/dist/scripts/migrate-v17-ops-audit.js +70 -0
  431. package/dist/search-dedup.d.ts +44 -0
  432. package/dist/search-dedup.js +137 -0
  433. package/dist/search-expansion.d.ts +20 -0
  434. package/dist/search-expansion.js +99 -0
  435. package/dist/search.d.ts +62 -0
  436. package/dist/search.js +582 -0
  437. package/dist/seh-detector.d.ts +31 -0
  438. package/dist/seh-detector.js +201 -0
  439. package/dist/self-improve.d.ts +1 -0
  440. package/dist/self-improve.js +189 -0
  441. package/dist/session-distill.d.ts +29 -0
  442. package/dist/session-distill.js +325 -0
  443. package/dist/session-update.d.ts +1 -0
  444. package/dist/session-update.js +54 -0
  445. package/dist/shared-memory.d.ts +24 -0
  446. package/dist/shared-memory.js +104 -0
  447. package/dist/stats.d.ts +1 -0
  448. package/dist/stats.js +44 -0
  449. package/dist/temporal-retrieval.d.ts +132 -0
  450. package/dist/temporal-retrieval.js +495 -0
  451. package/dist/tier-manager.d.ts +69 -0
  452. package/dist/tier-manager.js +225 -0
  453. package/dist/vectorize.d.ts +16 -0
  454. package/dist/vectorize.js +91 -0
  455. package/dist/watch.d.ts +8 -0
  456. package/dist/watch.js +124 -0
  457. package/package.json +74 -0
@@ -0,0 +1,99 @@
1
+ /**
2
+ * src/lib/answer/telemetry.ts — P1 T7 scope: persist per-call answer metadata.
3
+ *
4
+ * Writes one row to `answer_telemetry` (schema v11) per answer() invocation,
5
+ * INCLUDING failures (LLM error, hallucination_after_retry, retrieval_empty).
6
+ *
7
+ * Privacy rule (kickoff §critical decision):
8
+ * - NEVER log raw question or answer text.
9
+ * - Store `question_hash = sha256(question)[:16]` instead.
10
+ *
11
+ * Storage abstraction:
12
+ * - `TelemetryStore` interface decouples lib from better-sqlite3.
13
+ * - `InMemoryTelemetryStore` for tests (push to array, query helpers).
14
+ * - VPS apply step binds a `Sqlite3TelemetryStore` that targets
15
+ * `nox-mem.db` opened by the rest of the codebase. We avoid hard-
16
+ * coding `better-sqlite3` here to keep the staged dir installable
17
+ * with zero runtime deps (tests use the in-memory store).
18
+ *
19
+ * Cost estimation:
20
+ * - We accept `cost_estimate_usd` as input from caller (provider knows the
21
+ * per-model unit price). When absent we derive a 0-USD estimate so the
22
+ * column stays NOT NULL per v11 schema.
23
+ *
24
+ * Failure-reason mapping:
25
+ * The v11 schema CHECK constrains `failed_reason IN ('hallucinated_citation',
26
+ * 'provider_down', 'token_budget')` OR NULL. The lib's AnswerFailureReason
27
+ * enum is broader (includes 'hallucination_after_retry', 'llm_timeout',
28
+ * 'retrieval_empty', 'llm_error', 'invalid_input'). We map to the schema
29
+ * alphabet in `mapFailureReason()` so the INSERT never violates CHECK.
30
+ */
31
+ import type { AnswerFailureReason, AnswerMetadata } from "./types.js";
32
+ /** Subset of v11 schema column names — keeps the lib decoupled from SQL. */
33
+ export interface AnswerTelemetryRow {
34
+ question_hash: string;
35
+ session_id: string | null;
36
+ timestamp_ms: number;
37
+ provider: string;
38
+ model: string;
39
+ retrieval_count: number;
40
+ citation_count: number;
41
+ tokens_in: number | null;
42
+ tokens_out: number | null;
43
+ latency_ms: number;
44
+ fallback_used: 0 | 1;
45
+ failed_reason: SchemaFailureReason | null;
46
+ cost_estimate_usd: number;
47
+ }
48
+ /** Subset allowed by the v11 schema CHECK. */
49
+ export type SchemaFailureReason = "hallucinated_citation" | "provider_down" | "token_budget";
50
+ /** Storage seam: prod implementation wraps better-sqlite3 prepared insert. */
51
+ export interface TelemetryStore {
52
+ insert(row: AnswerTelemetryRow): void;
53
+ }
54
+ /** In-memory store for tests + dev. Keeps every row in `rows`. */
55
+ export declare class InMemoryTelemetryStore implements TelemetryStore {
56
+ readonly rows: AnswerTelemetryRow[];
57
+ insert(row: AnswerTelemetryRow): void;
58
+ /** Convenience: filter by `failed_reason` (or NULL for success rows). */
59
+ byFailure(reason: SchemaFailureReason | null): AnswerTelemetryRow[];
60
+ }
61
+ /** sha256(question)[:16] — never store raw question text. */
62
+ export declare function hashQuestion(question: string): string;
63
+ /**
64
+ * Map the lib's broader AnswerFailureReason → the narrow v11 schema alphabet.
65
+ * Returns NULL for happy-path success (no failure reason on metadata).
66
+ *
67
+ * Mapping:
68
+ * hallucinated_citation → hallucinated_citation
69
+ * hallucination_after_retry → hallucinated_citation (root cause is same)
70
+ * llm_error → provider_down
71
+ * llm_timeout → provider_down
72
+ * retrieval_empty → NULL (not a failure — surfaces via citations.length=0)
73
+ * invalid_input → NULL (caller bug; we still record the row but no SQL-side failure tag)
74
+ */
75
+ export declare function mapFailureReason(reason: AnswerFailureReason | undefined): SchemaFailureReason | null;
76
+ export declare function estimateCost(model: string, tokensIn: number, tokensOut: number): number;
77
+ export interface RecordAnswerInput {
78
+ question: string;
79
+ citationCount: number;
80
+ metadata: AnswerMetadata;
81
+ /** Optional session correlation; pass-through from caller (CLI/HTTP/MCP). */
82
+ sessionId?: string | null;
83
+ /** Optional override; if absent we estimate from model + tokens. */
84
+ costEstimateUsd?: number;
85
+ /** Override clock — test seam; defaults to Date.now(). */
86
+ now?: () => number;
87
+ }
88
+ /**
89
+ * Persist one telemetry row. Returns the row written (useful in tests).
90
+ * Never throws — telemetry failures must NOT break the user-facing answer call.
91
+ * Errors are swallowed and surfaced via process.stderr in non-test mode.
92
+ */
93
+ export declare function recordAnswer(store: TelemetryStore, input: RecordAnswerInput): AnswerTelemetryRow;
94
+ /**
95
+ * Prepared INSERT string the VPS adapter should use. Exported so the apply
96
+ * step can `const STMT = db.prepare(INSERT_SQL)` without re-deriving column
97
+ * order from scratch.
98
+ */
99
+ export declare const INSERT_SQL: string;
@@ -0,0 +1,154 @@
1
+ /**
2
+ * src/lib/answer/telemetry.ts — P1 T7 scope: persist per-call answer metadata.
3
+ *
4
+ * Writes one row to `answer_telemetry` (schema v11) per answer() invocation,
5
+ * INCLUDING failures (LLM error, hallucination_after_retry, retrieval_empty).
6
+ *
7
+ * Privacy rule (kickoff §critical decision):
8
+ * - NEVER log raw question or answer text.
9
+ * - Store `question_hash = sha256(question)[:16]` instead.
10
+ *
11
+ * Storage abstraction:
12
+ * - `TelemetryStore` interface decouples lib from better-sqlite3.
13
+ * - `InMemoryTelemetryStore` for tests (push to array, query helpers).
14
+ * - VPS apply step binds a `Sqlite3TelemetryStore` that targets
15
+ * `nox-mem.db` opened by the rest of the codebase. We avoid hard-
16
+ * coding `better-sqlite3` here to keep the staged dir installable
17
+ * with zero runtime deps (tests use the in-memory store).
18
+ *
19
+ * Cost estimation:
20
+ * - We accept `cost_estimate_usd` as input from caller (provider knows the
21
+ * per-model unit price). When absent we derive a 0-USD estimate so the
22
+ * column stays NOT NULL per v11 schema.
23
+ *
24
+ * Failure-reason mapping:
25
+ * The v11 schema CHECK constrains `failed_reason IN ('hallucinated_citation',
26
+ * 'provider_down', 'token_budget')` OR NULL. The lib's AnswerFailureReason
27
+ * enum is broader (includes 'hallucination_after_retry', 'llm_timeout',
28
+ * 'retrieval_empty', 'llm_error', 'invalid_input'). We map to the schema
29
+ * alphabet in `mapFailureReason()` so the INSERT never violates CHECK.
30
+ */
31
+ import { createHash } from "node:crypto";
32
+ /** In-memory store for tests + dev. Keeps every row in `rows`. */
33
+ export class InMemoryTelemetryStore {
34
+ rows = [];
35
+ insert(row) {
36
+ this.rows.push(row);
37
+ }
38
+ /** Convenience: filter by `failed_reason` (or NULL for success rows). */
39
+ byFailure(reason) {
40
+ return this.rows.filter((r) => r.failed_reason === reason);
41
+ }
42
+ }
43
+ // ─── Privacy helpers ──────────────────────────────────────────────────────
44
+ /** sha256(question)[:16] — never store raw question text. */
45
+ export function hashQuestion(question) {
46
+ return createHash("sha256").update(question, "utf8").digest("hex").slice(0, 16);
47
+ }
48
+ // ─── Failure-reason mapping ───────────────────────────────────────────────
49
+ /**
50
+ * Map the lib's broader AnswerFailureReason → the narrow v11 schema alphabet.
51
+ * Returns NULL for happy-path success (no failure reason on metadata).
52
+ *
53
+ * Mapping:
54
+ * hallucinated_citation → hallucinated_citation
55
+ * hallucination_after_retry → hallucinated_citation (root cause is same)
56
+ * llm_error → provider_down
57
+ * llm_timeout → provider_down
58
+ * retrieval_empty → NULL (not a failure — surfaces via citations.length=0)
59
+ * invalid_input → NULL (caller bug; we still record the row but no SQL-side failure tag)
60
+ */
61
+ export function mapFailureReason(reason) {
62
+ switch (reason) {
63
+ case "hallucinated_citation":
64
+ case "hallucination_after_retry":
65
+ return "hallucinated_citation";
66
+ case "llm_error":
67
+ case "llm_timeout":
68
+ return "provider_down";
69
+ case "retrieval_empty":
70
+ case "invalid_input":
71
+ case undefined:
72
+ return null;
73
+ default:
74
+ return null;
75
+ }
76
+ }
77
+ // ─── Cost estimation ──────────────────────────────────────────────────────
78
+ /**
79
+ * Conservative USD cost estimator. Numbers from D41 #1 baseline; revise via
80
+ * spec, not silently. Returns 0 for unknown models so we never overstate
81
+ * spend in dashboards.
82
+ *
83
+ * Prices in USD per 1M tokens (input / output):
84
+ * gemini-2.5-flash-lite → 0.10 / 0.40
85
+ * gemini-2.5-flash → 0.30 / 2.50
86
+ * mock → 0 (test)
87
+ */
88
+ const PRICE_TABLE = {
89
+ "gemini-2.5-flash-lite": { in: 0.1, out: 0.4 },
90
+ "gemini-2.5-flash": { in: 0.3, out: 2.5 },
91
+ };
92
+ export function estimateCost(model, tokensIn, tokensOut) {
93
+ const price = PRICE_TABLE[model];
94
+ if (!price)
95
+ return 0;
96
+ const usd = (tokensIn * price.in + tokensOut * price.out) / 1_000_000;
97
+ // round to 6 decimals — single call almost always sub-cent
98
+ return Math.round(usd * 1_000_000) / 1_000_000;
99
+ }
100
+ /**
101
+ * Persist one telemetry row. Returns the row written (useful in tests).
102
+ * Never throws — telemetry failures must NOT break the user-facing answer call.
103
+ * Errors are swallowed and surfaced via process.stderr in non-test mode.
104
+ */
105
+ export function recordAnswer(store, input) {
106
+ const m = input.metadata;
107
+ const tokensIn = m.tokens_in ?? 0;
108
+ const tokensOut = m.tokens_out ?? 0;
109
+ const cost = input.costEstimateUsd !== undefined
110
+ ? input.costEstimateUsd
111
+ : estimateCost(m.model, tokensIn, tokensOut);
112
+ const row = {
113
+ question_hash: hashQuestion(input.question),
114
+ session_id: input.sessionId ?? null,
115
+ timestamp_ms: (input.now ?? Date.now)(),
116
+ provider: m.provider,
117
+ model: m.model,
118
+ retrieval_count: m.retrieval_count,
119
+ citation_count: input.citationCount,
120
+ tokens_in: m.tokens_in ?? null,
121
+ tokens_out: m.tokens_out ?? null,
122
+ latency_ms: m.latency_ms,
123
+ fallback_used: m.fallback_used ? 1 : 0,
124
+ failed_reason: mapFailureReason(m.failed_reason),
125
+ cost_estimate_usd: cost,
126
+ };
127
+ try {
128
+ store.insert(row);
129
+ }
130
+ catch (err) {
131
+ // Telemetry MUST NOT break the call. Log to stderr (best-effort) and
132
+ // swallow so the caller still receives the answer.
133
+ if (process.env.NODE_ENV !== "test") {
134
+ process.stderr.write(`[answer/telemetry] insert failed: ${err.message}\n`);
135
+ }
136
+ }
137
+ return row;
138
+ }
139
+ // ─── SQL hints (for VPS-side adapter, kept here as a runbook) ─────────────
140
+ /**
141
+ * Prepared INSERT string the VPS adapter should use. Exported so the apply
142
+ * step can `const STMT = db.prepare(INSERT_SQL)` without re-deriving column
143
+ * order from scratch.
144
+ */
145
+ export const INSERT_SQL = `
146
+ INSERT INTO answer_telemetry (
147
+ question_hash, session_id, timestamp_ms, provider, model,
148
+ retrieval_count, citation_count, tokens_in, tokens_out,
149
+ latency_ms, fallback_used, failed_reason, cost_estimate_usd
150
+ ) VALUES (
151
+ @question_hash, @session_id, @timestamp_ms, @provider, @model,
152
+ @retrieval_count, @citation_count, @tokens_in, @tokens_out,
153
+ @latency_ms, @fallback_used, @failed_reason, @cost_estimate_usd
154
+ )`.trim();
@@ -0,0 +1,108 @@
1
+ /**
2
+ * src/lib/answer/types.ts — Public interfaces for P1 answer primitive.
3
+ *
4
+ * Per kickoff doc PR #18 §3:
5
+ * - AnswerOpts: request shape (kickoff §6 contract simplified for T1-T4 MVP)
6
+ * - AnswerResult: response shape with citations + metadata
7
+ * - Citation: chunk_id + marker_id bridge (LLM never sees real ids)
8
+ * - RetrievedChunk: shape returned by retrieval.ts wrapper
9
+ *
10
+ * Naming convention: kickoff doc uses AnswerRequest/AnswerResponse; T1-T4
11
+ * spec from operator uses AnswerOpts/AnswerResult. We export BOTH aliases
12
+ * so downstream T8 (CLI) and T9 (HTTP) can pick either without churn.
13
+ */
14
+ import type { LLMProvider } from "./provider.js";
15
+ /** Request to answer(): {question, topK, maxTokens, provider, model, temperature}. */
16
+ export interface AnswerOpts {
17
+ /** Natural-language question. Required. */
18
+ question: string;
19
+ /** Top-K chunks from retrieval. Default 8. Range 1-20. */
20
+ topK?: number;
21
+ /** Max output tokens from LLM. Default 1500. */
22
+ maxTokens?: number;
23
+ /** Provider name: 'gemini' | 'mock' | future 'openai'/'anthropic'. Default 'gemini'. */
24
+ provider?: string;
25
+ /** Model id. Default 'gemini-2.5-flash-lite' (D41 #1 locked). */
26
+ model?: string;
27
+ /** LLM temperature. Default 0.2. */
28
+ temperature?: number;
29
+ /**
30
+ * Optional injection point for testing. If set, used INSTEAD of selectProvider().
31
+ * Production code should leave undefined and let config defaults flow.
32
+ */
33
+ providerOverride?: LLMProvider;
34
+ /**
35
+ * Optional retrieval injection point for testing/mocking.
36
+ * If set, used INSTEAD of the real hybrid search wrapper.
37
+ */
38
+ retrieveOverride?: (question: string, topK: number) => Promise<RetrievedChunk[]>;
39
+ }
40
+ /** Alias kept for kickoff-doc consistency. */
41
+ export type AnswerRequest = AnswerOpts;
42
+ /** A chunk surfaced by retrieval, with marker_id assigned for LLM-side citation. */
43
+ export interface RetrievedChunk {
44
+ /** Real DB chunk id — server-side only, NEVER shown to LLM. */
45
+ chunk_id: number;
46
+ /** Display marker for LLM: "chunk_1", "chunk_2", ..., "chunk_N". */
47
+ marker_id: string;
48
+ /** Source file path (absolute or workspace-relative). */
49
+ file_path: string;
50
+ /** Optional "L42-L58" hint when chunk maps to specific lines. */
51
+ line_range?: string;
52
+ /** Chunk body text. */
53
+ content: string;
54
+ /** Optional content hash (sha256 hex) used by dedupe. */
55
+ content_hash?: string;
56
+ /** Optional fused score from hybrid search (RRF or similar). */
57
+ score?: number;
58
+ }
59
+ /** A citation as returned to the caller — marker_id + real chunk pointer. */
60
+ export interface Citation {
61
+ chunk_id: number;
62
+ marker_id: string;
63
+ file_path: string;
64
+ line_range?: string;
65
+ /** Short excerpt (≤200 chars) for inline preview. */
66
+ snippet: string;
67
+ }
68
+ /** Top-level answer() return shape. */
69
+ export interface AnswerResult {
70
+ /** Final answer text from LLM. May contain `[chunk_N]` markers inline. */
71
+ answer: string;
72
+ /** Citations parsed + validated against the retrieval set. */
73
+ citations: Citation[];
74
+ /** Telemetry/observability metadata. */
75
+ metadata: AnswerMetadata;
76
+ }
77
+ export type AnswerResponse = AnswerResult;
78
+ export interface AnswerMetadata {
79
+ /** Wall-clock latency in milliseconds, end-to-end. */
80
+ latency_ms: number;
81
+ /** Input tokens billed to the LLM call. */
82
+ tokens_in: number;
83
+ /** Output tokens billed to the LLM call. */
84
+ tokens_out: number;
85
+ /** Provider name as actually selected. */
86
+ provider: string;
87
+ /** Model id as actually called. */
88
+ model: string;
89
+ /** Chunks returned by retrieval (post-dedupe, pre-prompt). */
90
+ retrieval_count: number;
91
+ /** Whether fallback retry path was exercised (e.g., hallucinated citation). */
92
+ fallback_used?: boolean;
93
+ /** If non-success path, machine-readable reason. */
94
+ failed_reason?: AnswerFailureReason;
95
+ /** Number of retries attempted (0 or 1 in T1-T4 MVP). */
96
+ retry_count?: number;
97
+ }
98
+ /** Failure-reason enum, aligned with kickoff §6 contract + T5/T6 partial. */
99
+ export type AnswerFailureReason = "hallucinated_citation" | "hallucination_after_retry" | "retrieval_empty" | "llm_error" | "llm_timeout" | "invalid_input";
100
+ /** Internal: chunk before marker_id is assigned (raw from search). */
101
+ export interface RawChunk {
102
+ chunk_id: number;
103
+ file_path: string;
104
+ line_range?: string;
105
+ content: string;
106
+ content_hash?: string;
107
+ score?: number;
108
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,54 @@
1
+ /**
2
+ * G12 — Adoption helpers for safeErrorMessage across staged-* handlers.
3
+ *
4
+ * This file ships drop-in replacements for the leaky `return { status: 500,
5
+ * body: { error: (e as Error).message } }` pattern found in:
6
+ *
7
+ * - staged-P2/edits/src/api/hooks.ts:99 (G12 root)
8
+ * - staged-L2/edits/src/api/conflict.ts:181 (resolution_failed message)
9
+ * - staged-L3/edits/src/api/mark.ts (R-L3-3) (SQL fragment leak)
10
+ *
11
+ * Use the patch helpers below from each handler. Example (P2 hooks.ts L99):
12
+ *
13
+ * - return { status: 500, body: { error: (e as Error).message } };
14
+ * + return { status: 500, body: safeError500(e, { context: "hooks.recent" }) };
15
+ *
16
+ * Logging: caller can pass an `onLog` callback to forward the raw error to
17
+ * stderr / structured logger. The sanitized correlation_id is the link.
18
+ */
19
+ import { type SanitizeOptions } from "./safe-error-message.js";
20
+ export interface SafeError500Options extends SanitizeOptions {
21
+ /** Short context tag for log correlation (e.g. "hooks.recent", "conflict.resolve"). */
22
+ context?: string;
23
+ /** Logger override. Defaults to console.error. */
24
+ onLog?: (info: {
25
+ correlationId: string;
26
+ raw: unknown;
27
+ context?: string;
28
+ }) => void;
29
+ }
30
+ /**
31
+ * Build a sanitized 5xx response body. Always returns `{ error, correlation_id }`.
32
+ * Side-effect: logs raw error to onLog (or console.error) with the correlation_id.
33
+ */
34
+ export declare function safeError500(e: unknown, opts?: SafeError500Options): {
35
+ error: string;
36
+ correlation_id: string;
37
+ };
38
+ /**
39
+ * Convenience for the L2 conflict resolve path (`409 resolution_failed`).
40
+ * Shape differs slightly — keeps the `error` discriminator for backward
41
+ * compat while still sanitizing the inner message.
42
+ */
43
+ export declare function safeConflict409(e: unknown, opts?: SafeError500Options): {
44
+ error: "resolution_failed";
45
+ message: string;
46
+ correlation_id: string;
47
+ };
48
+ /**
49
+ * Convenience for the L3 mark path 500 leak. Same shape as `safeError500`.
50
+ */
51
+ export declare function safeMark500(e: unknown, opts?: SafeError500Options): {
52
+ error: string;
53
+ correlation_id: string;
54
+ };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * G12 — Adoption helpers for safeErrorMessage across staged-* handlers.
3
+ *
4
+ * This file ships drop-in replacements for the leaky `return { status: 500,
5
+ * body: { error: (e as Error).message } }` pattern found in:
6
+ *
7
+ * - staged-P2/edits/src/api/hooks.ts:99 (G12 root)
8
+ * - staged-L2/edits/src/api/conflict.ts:181 (resolution_failed message)
9
+ * - staged-L3/edits/src/api/mark.ts (R-L3-3) (SQL fragment leak)
10
+ *
11
+ * Use the patch helpers below from each handler. Example (P2 hooks.ts L99):
12
+ *
13
+ * - return { status: 500, body: { error: (e as Error).message } };
14
+ * + return { status: 500, body: safeError500(e, { context: "hooks.recent" }) };
15
+ *
16
+ * Logging: caller can pass an `onLog` callback to forward the raw error to
17
+ * stderr / structured logger. The sanitized correlation_id is the link.
18
+ */
19
+ import { buildSafeErrorBody } from "./safe-error-message.js";
20
+ /**
21
+ * Build a sanitized 5xx response body. Always returns `{ error, correlation_id }`.
22
+ * Side-effect: logs raw error to onLog (or console.error) with the correlation_id.
23
+ */
24
+ export function safeError500(e, opts = {}) {
25
+ const log = opts.onLog
26
+ ? opts.onLog
27
+ : (info) => {
28
+ const ctx = info.context ? `[${info.context}] ` : "";
29
+ // eslint-disable-next-line no-console
30
+ console.error(`${ctx}correlation_id=${info.correlationId} error=`, info.raw);
31
+ };
32
+ return buildSafeErrorBody(e, {
33
+ ...opts,
34
+ onLog: ({ correlationId, raw }) => log({ correlationId, raw, context: opts.context }),
35
+ });
36
+ }
37
+ /**
38
+ * Convenience for the L2 conflict resolve path (`409 resolution_failed`).
39
+ * Shape differs slightly — keeps the `error` discriminator for backward
40
+ * compat while still sanitizing the inner message.
41
+ */
42
+ export function safeConflict409(e, opts = {}) {
43
+ const body = safeError500(e, { ...opts, context: opts.context ?? "conflict.resolve" });
44
+ return {
45
+ error: "resolution_failed",
46
+ message: body.error,
47
+ correlation_id: body.correlation_id,
48
+ };
49
+ }
50
+ /**
51
+ * Convenience for the L3 mark path 500 leak. Same shape as `safeError500`.
52
+ */
53
+ export function safeMark500(e, opts = {}) {
54
+ return safeError500(e, { ...opts, context: opts.context ?? "mark" });
55
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * G12 — Safe error message helper (Wave G)
3
+ *
4
+ * Sanitize `(e as Error).message` before exposing it in 5xx responses across
5
+ * `/api/hooks/recent` (P2), `/api/conflict/:id/resolve` (L2), `/api/mark` (L3),
6
+ * and any future endpoint that may surface backend errors to clients.
7
+ *
8
+ * Complements G5 (Wave F) which strips `error.stack`. Even with stack gone,
9
+ * `error.message` itself often contains:
10
+ * - Absolute file paths (`/Users/.../db.ts:42:15`, `/root/.openclaw/...`)
11
+ * - SQLite connection strings (`SQLITE_ERROR: ... /var/lib/nox-mem.db ...`)
12
+ * - Env var values dumped by stricter ORMs (`ENV NOX_API_TOKEN=xyz ...`)
13
+ * - Stack frame fragments embedded in long `Error.toString()` outputs
14
+ *
15
+ * Strategy:
16
+ * 1. Walk through a small set of regex strippers (paths, DB strings, env).
17
+ * 2. Generate a stable correlation ID (UUID-v4) to map sanitized error
18
+ * → original (logged server-side via `onLog`).
19
+ * 3. Return generic message + correlationId. Caller logs full error.
20
+ *
21
+ * Threats addressed (refs PR #58 §14):
22
+ * - G12 (High) — `/api/hooks/recent` 500 leaks DB path.
23
+ * - R-L3-3 — `/mark` 500 leaks SQL fragments.
24
+ * - Cross-cutting hardening across staged-* edit dirs.
25
+ *
26
+ * Backward compat:
27
+ * - Pure function. No deps on Express / Fastify / http. Caller wires it
28
+ * into existing handlers.
29
+ * - Env-opt-in for full passthrough during local dev:
30
+ * NOX_ERROR_PASSTHROUGH=1 → returns raw message (NEVER set in prod).
31
+ * A boot-time WARN should be emitted by the caller when active.
32
+ */
33
+ export interface SanitizeOptions {
34
+ /** Cap on returned message length. Default 200. */
35
+ maxLength?: number;
36
+ /** Generic fallback when stripping leaves empty/garbage. Default 'internal_error'. */
37
+ fallback?: string;
38
+ /** Allow raw passthrough (DEV ONLY). Default false. */
39
+ passthrough?: boolean;
40
+ }
41
+ export interface SafeErrorResult {
42
+ /** Sanitized, length-capped message safe to expose in 5xx responses. */
43
+ message: string;
44
+ /** UUID-v4 correlation ID. Log server-side with the raw error for triage. */
45
+ correlationId: string;
46
+ }
47
+ /**
48
+ * Sanitize an arbitrary error/string for client exposure.
49
+ */
50
+ export declare function safeErrorMessage(e: unknown, opts?: SanitizeOptions): SafeErrorResult;
51
+ /**
52
+ * Build a complete `{ error, correlation_id }` body for HTTP 500 responses.
53
+ * Optionally invoke a logging hook with the full original error.
54
+ */
55
+ export declare function buildSafeErrorBody(e: unknown, opts?: SanitizeOptions & {
56
+ onLog?: (info: {
57
+ correlationId: string;
58
+ raw: unknown;
59
+ }) => void;
60
+ }): {
61
+ error: string;
62
+ correlation_id: string;
63
+ };
64
+ /**
65
+ * Boot-time check — caller should invoke once on startup to emit a WARN
66
+ * when passthrough is enabled.
67
+ */
68
+ export declare function checkErrorPassthroughAtBoot(logger?: {
69
+ warn: (msg: string) => void;
70
+ }, env?: NodeJS.ProcessEnv): boolean;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * G12 — Safe error message helper (Wave G)
3
+ *
4
+ * Sanitize `(e as Error).message` before exposing it in 5xx responses across
5
+ * `/api/hooks/recent` (P2), `/api/conflict/:id/resolve` (L2), `/api/mark` (L3),
6
+ * and any future endpoint that may surface backend errors to clients.
7
+ *
8
+ * Complements G5 (Wave F) which strips `error.stack`. Even with stack gone,
9
+ * `error.message` itself often contains:
10
+ * - Absolute file paths (`/Users/.../db.ts:42:15`, `/root/.openclaw/...`)
11
+ * - SQLite connection strings (`SQLITE_ERROR: ... /var/lib/nox-mem.db ...`)
12
+ * - Env var values dumped by stricter ORMs (`ENV NOX_API_TOKEN=xyz ...`)
13
+ * - Stack frame fragments embedded in long `Error.toString()` outputs
14
+ *
15
+ * Strategy:
16
+ * 1. Walk through a small set of regex strippers (paths, DB strings, env).
17
+ * 2. Generate a stable correlation ID (UUID-v4) to map sanitized error
18
+ * → original (logged server-side via `onLog`).
19
+ * 3. Return generic message + correlationId. Caller logs full error.
20
+ *
21
+ * Threats addressed (refs PR #58 §14):
22
+ * - G12 (High) — `/api/hooks/recent` 500 leaks DB path.
23
+ * - R-L3-3 — `/mark` 500 leaks SQL fragments.
24
+ * - Cross-cutting hardening across staged-* edit dirs.
25
+ *
26
+ * Backward compat:
27
+ * - Pure function. No deps on Express / Fastify / http. Caller wires it
28
+ * into existing handlers.
29
+ * - Env-opt-in for full passthrough during local dev:
30
+ * NOX_ERROR_PASSTHROUGH=1 → returns raw message (NEVER set in prod).
31
+ * A boot-time WARN should be emitted by the caller when active.
32
+ */
33
+ import { randomUUID } from "node:crypto";
34
+ // ── strippers ───────────────────────────────────────────────────────────────
35
+ /**
36
+ * Each stripper takes a string and returns a (possibly redacted) string.
37
+ * Order matters — paths first, then DB strings, then env values, then
38
+ * generic stack-line patterns.
39
+ */
40
+ const STRIPPERS = [
41
+ // Absolute POSIX paths with optional :line:col suffix (mac dev + linux prod).
42
+ { name: "users-path", re: /\/Users\/[^\s'"`)]+(?::\d+(?::\d+)?)?/g, replacement: "<path>" },
43
+ { name: "root-path", re: /\/root\/[^\s'"`)]+(?::\d+(?::\d+)?)?/g, replacement: "<path>" },
44
+ { name: "var-path", re: /\/var\/[^\s'"`)]+(?::\d+(?::\d+)?)?/g, replacement: "<path>" },
45
+ { name: "opt-path", re: /\/opt\/[^\s'"`)]+(?::\d+(?::\d+)?)?/g, replacement: "<path>" },
46
+ { name: "tmp-path", re: /\/tmp\/[^\s'"`)]+(?::\d+(?::\d+)?)?/g, replacement: "<path>" },
47
+ { name: "home-path", re: /\/home\/[^\s'"`)]+(?::\d+(?::\d+)?)?/g, replacement: "<path>" },
48
+ // SQLite errors often embed the DB file path. We catch the path with the
49
+ // earlier rules; this catches the connection-string-style fragment.
50
+ { name: "sqlite-conn", re: /(?:sqlite:|file:)[^\s'"`)]+/gi, replacement: "<dburl>" },
51
+ // ENV=value patterns (e.g. NOX_API_TOKEN=abc123).
52
+ { name: "env-assign", re: /\b([A-Z][A-Z0-9_]{2,})=([A-Za-z0-9_\-\.+/=]{4,})/g, replacement: "$1=<redacted>" },
53
+ // Bearer tokens / API keys embedded inline.
54
+ { name: "bearer", re: /\bBearer\s+[A-Za-z0-9_\-\.]+/gi, replacement: "Bearer <redacted>" },
55
+ // Long opaque tokens (32+ chars). Avoid greedy match on natural language.
56
+ { name: "long-token", re: /\b[A-Za-z0-9_\-]{32,}\b/g, replacement: "<token>" },
57
+ // Stack frame fragments that survive `Error.toString()` flattening.
58
+ { name: "stack-frame", re: /\bat\s+[^\s()]+\s+\([^\s)]+\)/g, replacement: "<frame>" },
59
+ ];
60
+ /**
61
+ * Sanitize an arbitrary error/string for client exposure.
62
+ */
63
+ export function safeErrorMessage(e, opts = {}) {
64
+ const correlationId = randomUUID();
65
+ const passthrough = opts.passthrough ?? process.env.NOX_ERROR_PASSTHROUGH === "1";
66
+ const raw = extractMessage(e);
67
+ if (passthrough) {
68
+ return { message: raw, correlationId };
69
+ }
70
+ let cleaned = raw;
71
+ for (const s of STRIPPERS) {
72
+ cleaned = cleaned.replace(s.re, s.replacement);
73
+ }
74
+ // Collapse whitespace; remove repeated <path>/<frame>/<token> placeholders.
75
+ cleaned = cleaned
76
+ .replace(/\s+/g, " ")
77
+ .replace(/(<path>(?:\s+<path>)+)/g, "<path>")
78
+ .replace(/(<frame>(?:\s+<frame>)+)/g, "<frame>")
79
+ .replace(/(<token>(?:\s+<token>)+)/g, "<token>")
80
+ .trim();
81
+ if (!cleaned || cleaned === "<path>" || cleaned === "<frame>") {
82
+ cleaned = opts.fallback ?? "internal_error";
83
+ }
84
+ const maxLength = opts.maxLength ?? 200;
85
+ if (cleaned.length > maxLength) {
86
+ cleaned = cleaned.slice(0, maxLength - 3) + "...";
87
+ }
88
+ return { message: cleaned, correlationId };
89
+ }
90
+ function extractMessage(e) {
91
+ if (typeof e === "string")
92
+ return e;
93
+ if (e instanceof Error)
94
+ return e.message ?? String(e);
95
+ if (e && typeof e === "object" && "message" in e) {
96
+ const m = e.message;
97
+ return typeof m === "string" ? m : String(m);
98
+ }
99
+ return String(e);
100
+ }
101
+ // ── helpers for caller-side adoption ────────────────────────────────────────
102
+ /**
103
+ * Build a complete `{ error, correlation_id }` body for HTTP 500 responses.
104
+ * Optionally invoke a logging hook with the full original error.
105
+ */
106
+ export function buildSafeErrorBody(e, opts = {}) {
107
+ const { message, correlationId } = safeErrorMessage(e, opts);
108
+ opts.onLog?.({ correlationId, raw: e });
109
+ return { error: message, correlation_id: correlationId };
110
+ }
111
+ /**
112
+ * Boot-time check — caller should invoke once on startup to emit a WARN
113
+ * when passthrough is enabled.
114
+ */
115
+ export function checkErrorPassthroughAtBoot(logger = console, env = process.env) {
116
+ if (env.NOX_ERROR_PASSTHROUGH === "1") {
117
+ logger.warn("[security] NOX_ERROR_PASSTHROUGH=1 — 5xx responses will leak raw error messages. " +
118
+ "DISABLE in production.");
119
+ return true;
120
+ }
121
+ return false;
122
+ }