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,116 @@
1
+ /**
2
+ * src/observability/privacy-guard.ts — PII / sensitive-text stripper (T9).
3
+ *
4
+ * RULES (non-negotiable):
5
+ * 1. No raw query text in label values — replace with "<redacted-query>".
6
+ * 2. No paths, file names, IPs, emails, phone numbers, BR personal IDs
7
+ * (CPF/CNPJ/CEP/RG), Pix keys, API keys / bearer tokens.
8
+ * 3. Anything not on a strict allowlist of "shapes" → "<redacted>".
9
+ *
10
+ * This module composes with `cardinality.ts` — privacy strips PII *contents*,
11
+ * cardinality enforces *shape* (allowlists) and *budget*.
12
+ *
13
+ * Patterns mirror A1 (privacy filter) and A1.1 (BR PII). Kept self-contained
14
+ * to avoid coupling — the observability layer must function even if the
15
+ * privacy package is later refactored.
16
+ */
17
+ // ─── PII / secret patterns ───────────────────────────────────────────────────
18
+ const PATTERNS = [
19
+ // Emails
20
+ { re: /[\w.+-]+@[\w-]+\.[\w.-]+/gi, label: "<redacted-email>" },
21
+ // Bearer tokens / Bearer + JWT-ish
22
+ { re: /Bearer\s+[A-Za-z0-9._-]{16,}/gi, label: "<redacted-bearer>" },
23
+ // OpenAI / Anthropic / Gemini-ish API keys
24
+ { re: /sk-[A-Za-z0-9_-]{20,}/g, label: "<redacted-key>" },
25
+ { re: /AIza[0-9A-Za-z_-]{20,}/g, label: "<redacted-key>" },
26
+ { re: /\bgsk_[A-Za-z0-9]{20,}/g, label: "<redacted-key>" },
27
+ // Generic high-entropy hex/uuid in the wild (32+ chars hex)
28
+ { re: /\b[A-Fa-f0-9]{32,}\b/g, label: "<redacted-hex>" },
29
+ // UUID
30
+ {
31
+ re: /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,
32
+ label: "<redacted-uuid>",
33
+ },
34
+ // IPv4
35
+ { re: /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g, label: "<redacted-ip>" },
36
+ // CPF (Brazilian personal ID) — 000.000.000-00 or 11 digits
37
+ { re: /\b\d{3}\.\d{3}\.\d{3}-\d{2}\b/g, label: "<redacted-cpf>" },
38
+ // CNPJ — 00.000.000/0000-00
39
+ {
40
+ re: /\b\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}\b/g,
41
+ label: "<redacted-cnpj>",
42
+ },
43
+ // CEP — 00000-000
44
+ { re: /\b\d{5}-\d{3}\b/g, label: "<redacted-cep>" },
45
+ // Phone — generic E.164 + BR
46
+ { re: /\+?\d{1,3}[\s-]?\(?\d{2,4}\)?[\s-]?\d{4,5}[\s-]?\d{4}/g, label: "<redacted-phone>" },
47
+ // Absolute path (Unix or Windows)
48
+ { re: /(?:[A-Za-z]:)?(?:\/[\w.\-+@]+){2,}/g, label: "<redacted-path>" },
49
+ // URL
50
+ { re: /https?:\/\/[\w.\-/?&=%#:]+/gi, label: "<redacted-url>" },
51
+ ];
52
+ /** Strip PII from a string. Returns the sanitized string. */
53
+ export function sanitizeString(s) {
54
+ if (!s)
55
+ return s;
56
+ let out = s;
57
+ for (const { re, label } of PATTERNS) {
58
+ out = out.replace(re, label);
59
+ }
60
+ return out;
61
+ }
62
+ /**
63
+ * Validate a label value: it must be either a known short shape (alphanum,
64
+ * snake_case, enum-style), or it gets coerced to "<redacted>".
65
+ *
66
+ * The intent is that *label values* are categorical (small set of low-entropy
67
+ * strings). Anything longer than 64 chars or containing PII patterns is
68
+ * automatically dropped.
69
+ */
70
+ const SAFE_VALUE_RE = /^[A-Za-z0-9_:\-.+]{1,64}$/;
71
+ const FORBIDDEN_NAME_HINTS = [
72
+ "query",
73
+ "prompt",
74
+ "response",
75
+ "user",
76
+ "email",
77
+ "ip",
78
+ "path",
79
+ "file",
80
+ ];
81
+ export function sanitizeLabelValue(name, value) {
82
+ // First, hard-strip PII patterns.
83
+ const stripped = sanitizeString(value);
84
+ // If the name itself looks like it carries content (query, prompt, …),
85
+ // collapse the value to a constant.
86
+ if (FORBIDDEN_NAME_HINTS.some((h) => name.toLowerCase().includes(h))) {
87
+ return "<redacted>";
88
+ }
89
+ // If after stripping it doesn't match safe shape, redact.
90
+ if (!SAFE_VALUE_RE.test(stripped)) {
91
+ return "<redacted>";
92
+ }
93
+ return stripped;
94
+ }
95
+ /** Sanitize an entire labels object — drop forbidden keys, coerce values. */
96
+ export function sanitizeLabels(labels) {
97
+ const out = {};
98
+ for (const [k, v] of Object.entries(labels)) {
99
+ if (typeof v !== "string")
100
+ continue;
101
+ out[k] = sanitizeLabelValue(k, v);
102
+ }
103
+ return out;
104
+ }
105
+ // ─── Composable guard: privacy → cardinality ────────────────────────────────
106
+ import { getDefaultGuard } from "./cardinality.js";
107
+ /**
108
+ * One-call guard for any metric: privacy first, then cardinality.
109
+ *
110
+ * This is the function the recording API uses. Caller should `null`-check.
111
+ */
112
+ export function guardLabels(metricName, rawLabels = {}, guard = getDefaultGuard()) {
113
+ const sanitized = sanitizeLabels(rawLabels);
114
+ const checked = guard.guard(metricName, sanitized);
115
+ return { labels: checked };
116
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * src/observability/record.ts — High-level recording API (T6).
3
+ *
4
+ * Convenience wrappers around the metric primitives. Callers in P1/A3/P5
5
+ * should use these — NOT `counter.inc()` directly — so that:
6
+ * 1. Cardinality + privacy guards are applied consistently.
7
+ * 2. Future schema changes only touch one file.
8
+ * 3. The recording is *fire-and-forget*: never throws, never blocks.
9
+ *
10
+ * All functions in this module catch + swallow errors. The hot path must
11
+ * not be affected by observability failures.
12
+ */
13
+ export type SearchMethod = "cli" | "api" | "mcp";
14
+ export type SearchOutcome = "success" | "empty" | "error";
15
+ export declare function recordSearch(opts: {
16
+ method: SearchMethod;
17
+ durationSeconds: number;
18
+ resultsCount: number;
19
+ outcome: SearchOutcome;
20
+ }): void;
21
+ export type AnswerOutcome = "success" | "no_chunks" | "llm_failed" | "hallucination" | "timeout" | "cost_cap";
22
+ export interface AnswerTiming {
23
+ total?: number;
24
+ retrieve?: number;
25
+ rerank?: number;
26
+ synthesize?: number;
27
+ verify?: number;
28
+ }
29
+ export declare function recordAnswer(opts: {
30
+ outcome: AnswerOutcome;
31
+ timing: AnswerTiming;
32
+ tokensIn?: number;
33
+ tokensOut?: number;
34
+ }): void;
35
+ export type ProviderOutcome = "success" | "rate_limit" | "error" | "fallback";
36
+ export type ProviderKind = "embedding" | "llm";
37
+ export declare function recordProviderCall(opts: {
38
+ provider: string;
39
+ model: string;
40
+ kind: ProviderKind;
41
+ durationSeconds: number;
42
+ outcome: ProviderOutcome;
43
+ costUsd?: number;
44
+ tokensIn?: number;
45
+ tokensOut?: number;
46
+ }): void;
47
+ export type ProvenanceKind = "fresh" | "stale" | "compiled" | "frontmatter" | "timeline";
48
+ export declare function recordChunkIngest(opts: {
49
+ provenanceKind: ProvenanceKind;
50
+ count?: number;
51
+ redactionsApplied?: number;
52
+ }): void;
53
+ export declare function recordEmbedding(opts: {
54
+ provider: string;
55
+ outcome: "success" | "error";
56
+ count?: number;
57
+ }): void;
58
+ export declare function recordKgEntity(opts: {
59
+ type: string;
60
+ count?: number;
61
+ }): void;
62
+ export declare function recordKgRelation(opts: {
63
+ predicate: string;
64
+ count?: number;
65
+ }): void;
66
+ export declare function recordHookEvent(opts: {
67
+ layer: string;
68
+ reason: "captured" | "filtered" | "redacted" | "error" | "dropped";
69
+ durationSeconds?: number;
70
+ }): void;
71
+ export declare function recordViewerConnect(): void;
72
+ export declare function recordViewerDisconnect(): void;
73
+ export declare function recordViewerEvent(type: string): void;
74
+ export declare function recordViewerDropped(reason: "slow_consumer" | "queue_full" | "client_gone"): void;
75
+ export declare function recordAuditWrite(table: string, count?: number): void;
76
+ /**
77
+ * Start a high-resolution timer that returns elapsed seconds when called.
78
+ * Use:
79
+ * const end = startTimer();
80
+ * // ... work
81
+ * recordSearch({ method: "api", durationSeconds: end(), … });
82
+ */
83
+ export declare function startTimer(): () => number;
@@ -0,0 +1,217 @@
1
+ /**
2
+ * src/observability/record.ts — High-level recording API (T6).
3
+ *
4
+ * Convenience wrappers around the metric primitives. Callers in P1/A3/P5
5
+ * should use these — NOT `counter.inc()` directly — so that:
6
+ * 1. Cardinality + privacy guards are applied consistently.
7
+ * 2. Future schema changes only touch one file.
8
+ * 3. The recording is *fire-and-forget*: never throws, never blocks.
9
+ *
10
+ * All functions in this module catch + swallow errors. The hot path must
11
+ * not be affected by observability failures.
12
+ */
13
+ import { chunksTotal, embeddingsTotal, kgEntitiesTotal, kgRelationsTotal, searchRequestsTotal, searchDurationSeconds, searchResultsReturned, answerRequestsTotal, answerDurationSeconds, answerTokensTotal, providerCallsTotal, providerDurationSeconds, providerCostUsdTotal, providerTokensTotal, hooksEventsTotal, hooksPipelineDurationSeconds, viewerConnections, viewerEventsTotal, viewerDroppedTotal, auditRowsTotal, } from "./metrics.js";
14
+ import { guardLabels } from "./privacy-guard.js";
15
+ // ─── helpers ─────────────────────────────────────────────────────────────────
16
+ function safe(fn) {
17
+ try {
18
+ return fn();
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ }
24
+ export function recordSearch(opts) {
25
+ safe(() => {
26
+ const reqLabels = guardLabels("nox_search_requests_total", {
27
+ method: opts.method,
28
+ outcome: opts.outcome,
29
+ }).labels;
30
+ if (reqLabels)
31
+ searchRequestsTotal.inc(reqLabels);
32
+ const durLabels = guardLabels("nox_search_duration_seconds", {
33
+ method: opts.method,
34
+ }).labels;
35
+ if (durLabels)
36
+ searchDurationSeconds.observe(durLabels, opts.durationSeconds);
37
+ const resLabels = guardLabels("nox_search_results_returned", {
38
+ method: opts.method,
39
+ }).labels;
40
+ if (resLabels)
41
+ searchResultsReturned.observe(resLabels, opts.resultsCount);
42
+ });
43
+ }
44
+ export function recordAnswer(opts) {
45
+ safe(() => {
46
+ const reqLabels = guardLabels("nox_answer_requests_total", {
47
+ failure_reason: opts.outcome,
48
+ }).labels;
49
+ if (reqLabels)
50
+ answerRequestsTotal.inc(reqLabels);
51
+ for (const phase of [
52
+ "total",
53
+ "retrieve",
54
+ "rerank",
55
+ "synthesize",
56
+ "verify",
57
+ ]) {
58
+ const v = opts.timing[phase];
59
+ if (typeof v === "number" && Number.isFinite(v)) {
60
+ const lbl = guardLabels("nox_answer_duration_seconds", { phase }).labels;
61
+ if (lbl)
62
+ answerDurationSeconds.observe(lbl, v);
63
+ }
64
+ }
65
+ if (typeof opts.tokensIn === "number" && opts.tokensIn > 0) {
66
+ const lbl = guardLabels("nox_answer_tokens_total", {
67
+ direction: "input",
68
+ }).labels;
69
+ if (lbl)
70
+ answerTokensTotal.inc(lbl, opts.tokensIn);
71
+ }
72
+ if (typeof opts.tokensOut === "number" && opts.tokensOut > 0) {
73
+ const lbl = guardLabels("nox_answer_tokens_total", {
74
+ direction: "output",
75
+ }).labels;
76
+ if (lbl)
77
+ answerTokensTotal.inc(lbl, opts.tokensOut);
78
+ }
79
+ });
80
+ }
81
+ export function recordProviderCall(opts) {
82
+ safe(() => {
83
+ const callLabels = guardLabels("nox_provider_calls_total", {
84
+ provider: opts.provider,
85
+ model: opts.model,
86
+ outcome: opts.outcome,
87
+ }).labels;
88
+ if (callLabels)
89
+ providerCallsTotal.inc(callLabels);
90
+ const durLabels = guardLabels("nox_provider_duration_seconds", {
91
+ provider: opts.provider,
92
+ kind: opts.kind,
93
+ }).labels;
94
+ if (durLabels)
95
+ providerDurationSeconds.observe(durLabels, opts.durationSeconds);
96
+ if (typeof opts.costUsd === "number" && opts.costUsd > 0) {
97
+ const lbl = guardLabels("nox_provider_cost_usd_total", {
98
+ provider: opts.provider,
99
+ model: opts.model,
100
+ }).labels;
101
+ if (lbl)
102
+ providerCostUsdTotal.inc(lbl, opts.costUsd);
103
+ }
104
+ if (typeof opts.tokensIn === "number" && opts.tokensIn > 0) {
105
+ const lbl = guardLabels("nox_provider_tokens_total", {
106
+ provider: opts.provider,
107
+ direction: "input",
108
+ }).labels;
109
+ if (lbl)
110
+ providerTokensTotal.inc(lbl, opts.tokensIn);
111
+ }
112
+ if (typeof opts.tokensOut === "number" && opts.tokensOut > 0) {
113
+ const lbl = guardLabels("nox_provider_tokens_total", {
114
+ provider: opts.provider,
115
+ direction: "output",
116
+ }).labels;
117
+ if (lbl)
118
+ providerTokensTotal.inc(lbl, opts.tokensOut);
119
+ }
120
+ });
121
+ }
122
+ export function recordChunkIngest(opts) {
123
+ safe(() => {
124
+ const lbl = guardLabels("nox_chunks_total", {
125
+ provenance_kind: opts.provenanceKind,
126
+ }).labels;
127
+ if (lbl)
128
+ chunksTotal.inc(lbl, opts.count ?? 1);
129
+ });
130
+ }
131
+ export function recordEmbedding(opts) {
132
+ safe(() => {
133
+ const lbl = guardLabels("nox_embeddings_total", {
134
+ provider: opts.provider,
135
+ outcome: opts.outcome,
136
+ }).labels;
137
+ if (lbl)
138
+ embeddingsTotal.inc(lbl, opts.count ?? 1);
139
+ });
140
+ }
141
+ export function recordKgEntity(opts) {
142
+ safe(() => {
143
+ const lbl = guardLabels("nox_kg_entities_total", {
144
+ type: opts.type,
145
+ }).labels;
146
+ if (lbl)
147
+ kgEntitiesTotal.inc(lbl, opts.count ?? 1);
148
+ });
149
+ }
150
+ export function recordKgRelation(opts) {
151
+ safe(() => {
152
+ const lbl = guardLabels("nox_kg_relations_total", {
153
+ predicate: opts.predicate,
154
+ }).labels;
155
+ if (lbl)
156
+ kgRelationsTotal.inc(lbl, opts.count ?? 1);
157
+ });
158
+ }
159
+ // ─── Hooks (P2) ──────────────────────────────────────────────────────────────
160
+ export function recordHookEvent(opts) {
161
+ safe(() => {
162
+ const evtLabels = guardLabels("nox_hooks_events_total", {
163
+ layer: opts.layer,
164
+ reason: opts.reason,
165
+ }).labels;
166
+ if (evtLabels)
167
+ hooksEventsTotal.inc(evtLabels);
168
+ if (typeof opts.durationSeconds === "number") {
169
+ const dur = guardLabels("nox_hooks_pipeline_duration_seconds", {
170
+ layer: opts.layer,
171
+ }).labels;
172
+ if (dur)
173
+ hooksPipelineDurationSeconds.observe(dur, opts.durationSeconds);
174
+ }
175
+ });
176
+ }
177
+ // ─── Viewer (P5) ─────────────────────────────────────────────────────────────
178
+ export function recordViewerConnect() {
179
+ safe(() => viewerConnections.inc());
180
+ }
181
+ export function recordViewerDisconnect() {
182
+ safe(() => viewerConnections.dec());
183
+ }
184
+ export function recordViewerEvent(type) {
185
+ safe(() => {
186
+ const lbl = guardLabels("nox_viewer_events_total", { type }).labels;
187
+ if (lbl)
188
+ viewerEventsTotal.inc(lbl);
189
+ });
190
+ }
191
+ export function recordViewerDropped(reason) {
192
+ safe(() => {
193
+ const lbl = guardLabels("nox_viewer_dropped_total", { reason }).labels;
194
+ if (lbl)
195
+ viewerDroppedTotal.inc(lbl);
196
+ });
197
+ }
198
+ // ─── Audit ───────────────────────────────────────────────────────────────────
199
+ export function recordAuditWrite(table, count = 1) {
200
+ safe(() => {
201
+ const lbl = guardLabels("nox_audit_rows_total", { table }).labels;
202
+ if (lbl)
203
+ auditRowsTotal.inc(lbl, count);
204
+ });
205
+ }
206
+ // ─── Timer helper ────────────────────────────────────────────────────────────
207
+ /**
208
+ * Start a high-resolution timer that returns elapsed seconds when called.
209
+ * Use:
210
+ * const end = startTimer();
211
+ * // ... work
212
+ * recordSearch({ method: "api", durationSeconds: end(), … });
213
+ */
214
+ export function startTimer() {
215
+ const start = process.hrtime.bigint();
216
+ return () => Number(process.hrtime.bigint() - start) / 1e9;
217
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * src/observability/registry.ts — MetricsRegistry singleton (T2).
3
+ *
4
+ * The Registry is the central index of all metrics. It is the only place
5
+ * exposed to the exporter (`/metrics`) and the recording API.
6
+ *
7
+ * INVARIANTS:
8
+ * - At most ONE metric per name across the whole process.
9
+ * - Re-registering the SAME object (idempotent) is allowed; re-registering
10
+ * a DIFFERENT object with the same name throws.
11
+ * - The registry is in-process (Node.js single-threaded); no external lock
12
+ * is required.
13
+ * - `collect()` returns an immutable snapshot — safe to render concurrently.
14
+ *
15
+ * SINGLETON PATTERN:
16
+ * `getDefaultRegistry()` returns a process-wide instance.
17
+ * Tests should construct a `new MetricsRegistry()` to stay isolated.
18
+ *
19
+ * THREAD-SAFETY:
20
+ * Node.js is single-threaded for JS; the only race is yielding between
21
+ * await points. The registry mutations (register/unregister) are
22
+ * synchronous so cannot interleave.
23
+ */
24
+ import { Counter, Gauge, Histogram, type MetricKind } from "./types.js";
25
+ export type AnyMetric = Counter | Gauge | Histogram;
26
+ export interface RegistrySnapshot {
27
+ /** Wall-clock ms when snapshot was taken. */
28
+ readonly takenAt: number;
29
+ readonly counters: readonly Counter[];
30
+ readonly gauges: readonly Gauge[];
31
+ readonly histograms: readonly Histogram[];
32
+ }
33
+ export declare class MetricsRegistry {
34
+ private readonly byName;
35
+ /**
36
+ * Register a metric. Idempotent if the same object is re-registered;
37
+ * throws if a DIFFERENT object claims the same name.
38
+ */
39
+ register<M extends AnyMetric>(metric: M): M;
40
+ /** Remove a metric by name. Returns true if it existed. */
41
+ unregister(name: string): boolean;
42
+ /** Look up a metric by name (typed by kind). */
43
+ get<K extends MetricKind>(name: string, kind?: K): AnyMetric | undefined;
44
+ /** Total number of distinct metric *names* (not series). */
45
+ get size(): number;
46
+ /** All metric names currently registered. */
47
+ names(): string[];
48
+ /**
49
+ * Take an immutable snapshot of all metrics.
50
+ * Returned arrays are sorted by metric name for stable exposition.
51
+ */
52
+ collect(): RegistrySnapshot;
53
+ /** Test-only — wipe all metrics. */
54
+ clear(): void;
55
+ /** Total series across all metrics (used for cardinality observability). */
56
+ totalSeries(): number;
57
+ }
58
+ export declare function getDefaultRegistry(): MetricsRegistry;
59
+ /** Reset the default registry — test-only. */
60
+ export declare function resetDefaultRegistry(): void;
@@ -0,0 +1,93 @@
1
+ export class MetricsRegistry {
2
+ byName = new Map();
3
+ /**
4
+ * Register a metric. Idempotent if the same object is re-registered;
5
+ * throws if a DIFFERENT object claims the same name.
6
+ */
7
+ register(metric) {
8
+ const existing = this.byName.get(metric.meta.name);
9
+ if (existing) {
10
+ if (existing === metric)
11
+ return metric; // idempotent
12
+ throw new Error(`metric ${JSON.stringify(metric.meta.name)} already registered with different instance`);
13
+ }
14
+ this.byName.set(metric.meta.name, metric);
15
+ return metric;
16
+ }
17
+ /** Remove a metric by name. Returns true if it existed. */
18
+ unregister(name) {
19
+ return this.byName.delete(name);
20
+ }
21
+ /** Look up a metric by name (typed by kind). */
22
+ get(name, kind) {
23
+ const m = this.byName.get(name);
24
+ if (!m)
25
+ return undefined;
26
+ if (kind && m.meta.kind !== kind)
27
+ return undefined;
28
+ return m;
29
+ }
30
+ /** Total number of distinct metric *names* (not series). */
31
+ get size() {
32
+ return this.byName.size;
33
+ }
34
+ /** All metric names currently registered. */
35
+ names() {
36
+ return [...this.byName.keys()].sort();
37
+ }
38
+ /**
39
+ * Take an immutable snapshot of all metrics.
40
+ * Returned arrays are sorted by metric name for stable exposition.
41
+ */
42
+ collect() {
43
+ const counters = [];
44
+ const gauges = [];
45
+ const histograms = [];
46
+ const sortedNames = this.names();
47
+ for (const name of sortedNames) {
48
+ const m = this.byName.get(name);
49
+ if (!m)
50
+ continue;
51
+ switch (m.meta.kind) {
52
+ case "counter":
53
+ counters.push(m);
54
+ break;
55
+ case "gauge":
56
+ gauges.push(m);
57
+ break;
58
+ case "histogram":
59
+ histograms.push(m);
60
+ break;
61
+ }
62
+ }
63
+ return Object.freeze({
64
+ takenAt: Date.now(),
65
+ counters: Object.freeze(counters),
66
+ gauges: Object.freeze(gauges),
67
+ histograms: Object.freeze(histograms),
68
+ });
69
+ }
70
+ /** Test-only — wipe all metrics. */
71
+ clear() {
72
+ this.byName.clear();
73
+ }
74
+ /** Total series across all metrics (used for cardinality observability). */
75
+ totalSeries() {
76
+ let n = 0;
77
+ for (const m of this.byName.values()) {
78
+ n += m.seriesCount;
79
+ }
80
+ return n;
81
+ }
82
+ }
83
+ // ─── Process-wide default ────────────────────────────────────────────────────
84
+ let _default;
85
+ export function getDefaultRegistry() {
86
+ if (!_default)
87
+ _default = new MetricsRegistry();
88
+ return _default;
89
+ }
90
+ /** Reset the default registry — test-only. */
91
+ export function resetDefaultRegistry() {
92
+ _default = new MetricsRegistry();
93
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * src/observability/types.ts — Prometheus / OpenMetrics metric primitives (T1).
3
+ *
4
+ * Provides three core types — Counter, Gauge, Histogram — implementing the
5
+ * OpenMetrics text exposition format used by Prometheus, VictoriaMetrics and
6
+ * Grafana Agent.
7
+ *
8
+ * DESIGN PROPERTIES (non-negotiable):
9
+ * - Labels are multi-dimensional but bounded: cardinality is enforced by the
10
+ * CardinalityGuard (see ./cardinality.ts). This module does NOT enforce
11
+ * limits — that is the responsibility of the Registry.
12
+ * - All recording APIs are synchronous and side-effect-free (no I/O).
13
+ * - Counter is monotonic: a `reset()` is provided only for tests.
14
+ * - Gauge supports `inc/dec/set`.
15
+ * - Histogram is bucketed with `le` semantics (less-or-equal upper bound)
16
+ * and accumulates `+Inf` bucket implicitly via `count`.
17
+ *
18
+ * The metric *name* is what is exported. Label *names* must match `[a-zA-Z_]
19
+ * [a-zA-Z0-9_]*` and label *values* are UTF-8 strings (escaped on render).
20
+ *
21
+ * Refs:
22
+ * - https://prometheus.io/docs/instrumenting/exposition_formats/
23
+ * - https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md
24
+ */
25
+ export type MetricKind = "counter" | "gauge" | "histogram";
26
+ export type Labels = Readonly<Record<string, string>>;
27
+ export interface MetricMeta {
28
+ /** Metric name (snake_case, prom convention). */
29
+ readonly name: string;
30
+ /** Help text shown on /metrics output (`# HELP` line). */
31
+ readonly help: string;
32
+ /** Type marker (`# TYPE` line). */
33
+ readonly kind: MetricKind;
34
+ /** Allowed label keys. If empty, the metric has no labels. */
35
+ readonly labelKeys: readonly string[];
36
+ /** Optional unit suffix per OpenMetrics (e.g. "seconds", "bytes"). */
37
+ readonly unit?: string;
38
+ }
39
+ export interface CounterSample {
40
+ labels: Labels;
41
+ value: number;
42
+ }
43
+ export interface GaugeSample {
44
+ labels: Labels;
45
+ value: number;
46
+ }
47
+ export interface HistogramSample {
48
+ labels: Labels;
49
+ /** Bucket boundaries (sorted ascending), excluding +Inf. */
50
+ buckets: readonly number[];
51
+ /** Cumulative counts per bucket (parallel to `buckets`). */
52
+ bucketCounts: number[];
53
+ /** Total observations (== count of +Inf bucket). */
54
+ count: number;
55
+ /** Sum of observed values. */
56
+ sum: number;
57
+ }
58
+ export declare function validateLabelName(name: string): void;
59
+ /** Stable string key for a label set (canonical form). */
60
+ export declare function labelsKey(labels: Labels): string;
61
+ /** Escape a label value per OpenMetrics spec (backslash, double-quote, newline). */
62
+ export declare function escapeLabelValue(v: string): string;
63
+ /** Filter a labels object to only the allowed keys; missing keys default to "". */
64
+ export declare function normalizeLabels(labels: Labels, allowed: readonly string[]): Labels;
65
+ /**
66
+ * Monotonic counter. Use for events that only go up (requests, errors, bytes).
67
+ */
68
+ export declare class Counter {
69
+ readonly meta: MetricMeta;
70
+ private readonly values;
71
+ constructor(meta: Omit<MetricMeta, "kind">);
72
+ inc(labels?: Labels, delta?: number): void;
73
+ /** Get the current value for a specific label set (0 if absent). */
74
+ get(labels?: Labels): number;
75
+ /** Test-only: clear all observations. */
76
+ reset(): void;
77
+ /** Snapshot — used by the exporter. */
78
+ collect(): CounterSample[];
79
+ /** Number of distinct label series tracked. */
80
+ get seriesCount(): number;
81
+ }
82
+ /**
83
+ * Gauge — value that goes up and down (queue length, memory, in-flight count).
84
+ */
85
+ export declare class Gauge {
86
+ readonly meta: MetricMeta;
87
+ private readonly values;
88
+ constructor(meta: Omit<MetricMeta, "kind">);
89
+ set(labels: Labels, value: number): void;
90
+ set(value: number): void;
91
+ inc(labels?: Labels, delta?: number): void;
92
+ dec(labels?: Labels, delta?: number): void;
93
+ get(labels?: Labels): number;
94
+ reset(): void;
95
+ collect(): GaugeSample[];
96
+ get seriesCount(): number;
97
+ }
98
+ /**
99
+ * Histogram — observations bucketed by upper bound. Used for latencies and
100
+ * sizes. Follows Prometheus `_bucket{le="..."}` conventions.
101
+ */
102
+ export declare class Histogram {
103
+ readonly meta: MetricMeta;
104
+ readonly buckets: readonly number[];
105
+ private readonly entries;
106
+ constructor(meta: Omit<MetricMeta, "kind">, buckets: readonly number[]);
107
+ observe(labels: Labels, value: number): void;
108
+ observe(value: number): void;
109
+ reset(): void;
110
+ collect(): HistogramSample[];
111
+ get seriesCount(): number;
112
+ }
113
+ export declare const DURATION_BUCKETS_SECONDS: readonly number[];
114
+ export declare const RESULT_COUNT_BUCKETS: readonly number[];
115
+ export declare const SIZE_BUCKETS_BYTES: readonly number[];