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,158 @@
1
+ /**
2
+ * telemetry-collector.ts — F10 Phase C Phase 1: in-process telemetry collector
3
+ *
4
+ * Collects per-request metrics for /api/search and /api/answer.
5
+ * Stores data in a ring buffer (last 24h, 1h buckets).
6
+ * No external dependencies — pure in-memory with atomic writes.
7
+ *
8
+ * Design principles:
9
+ * - Ring buffer of 24 fixed 1h buckets; oldest bucket rolls when the hour
10
+ * changes. Rollover is done lazily on record() — no background timer needed.
11
+ * - All writes are synchronous (single-process Node.js event loop is naturally
12
+ * sequential); no mutex needed.
13
+ * - Exported as a singleton (module-scope instance) with _reset() for tests.
14
+ *
15
+ * Spec: specs/2026-05-01-F10-observability-dashboard.md §P2 (Phase C, Phase 1)
16
+ * Status: Phase C Phase 1 implementation
17
+ *
18
+ * Endpoint served by api-server.ts wire-up:
19
+ * GET /api/observability/telemetry?window=24h&bucket=1h
20
+ */
21
+ export type TelemetryPath = "search" | "answer";
22
+ export interface TelemetryEvent {
23
+ /** Epoch ms when the request completed */
24
+ ts: number;
25
+ /** Which API path triggered this record */
26
+ path: TelemetryPath;
27
+ /** Total request latency in ms */
28
+ latency_ms: number;
29
+ /** Number of results returned (chunks for search, 1 for answer) */
30
+ result_count: number;
31
+ /** Which internal path was used (e.g. "hybrid", "fts-only", "semantic", "answer-pipeline") */
32
+ path_used: string;
33
+ /** Whether semantic (vector) search was invoked */
34
+ semantic_used: boolean;
35
+ /** Optional: HTTP status code */
36
+ status_code?: number;
37
+ }
38
+ export interface TelemetryBucket {
39
+ /** Epoch ms of the start of this 1h bucket (floored to hour) */
40
+ hour_ts: number;
41
+ /** Human-readable label "YYYY-MM-DDTHH:00Z" */
42
+ label: string;
43
+ /** Total requests in this bucket */
44
+ count: number;
45
+ /** Sum of latencies (for computing avg) */
46
+ latency_sum_ms: number;
47
+ /** p50 latency estimate (median of sampled values, ms) */
48
+ p50_ms: number | null;
49
+ /** p95 latency estimate (95th percentile of sampled values, ms) */
50
+ p95_ms: number | null;
51
+ /** p99 latency estimate (99th percentile of sampled values, ms) */
52
+ p99_ms: number | null;
53
+ /** Per-path breakdown */
54
+ by_path: Record<TelemetryPath, number>;
55
+ /** Per path_used breakdown */
56
+ by_path_used: Record<string, number>;
57
+ /** Count of requests with semantic search */
58
+ semantic_count: number;
59
+ /** Total result_count across all requests */
60
+ result_count_sum: number;
61
+ /** Sorted latency samples (kept for percentile calc, capped at MAX_SAMPLES) */
62
+ _samples: number[];
63
+ }
64
+ export interface TelemetryResponse {
65
+ /** Window covered by the response */
66
+ window: {
67
+ hours: number;
68
+ bucket_size_hours: number;
69
+ from_ts: number;
70
+ to_ts: number;
71
+ };
72
+ /** Buckets ordered oldest → newest; empty buckets included */
73
+ buckets: Array<Omit<TelemetryBucket, "_samples">>;
74
+ /** Aggregate across the entire window */
75
+ aggregate: {
76
+ count: number;
77
+ avg_latency_ms: number | null;
78
+ p50_ms: number | null;
79
+ p95_ms: number | null;
80
+ p99_ms: number | null;
81
+ by_path: Record<TelemetryPath, number>;
82
+ semantic_ratio: number | null;
83
+ };
84
+ generated_at_ms: number;
85
+ }
86
+ declare function hourFloor(ts: number): number;
87
+ declare function hourLabel(ts: number): string;
88
+ declare function emptyBucket(hour_ts: number): TelemetryBucket;
89
+ /** Compute percentile from a sorted array. Returns null if empty. */
90
+ declare function percentile(sorted: number[], p: number): number | null;
91
+ export declare class TelemetryCollector {
92
+ /**
93
+ * Ring buffer: Map<hour_ts, TelemetryBucket>.
94
+ * We keep at most MAX_BUCKETS entries; evict oldest when rolling.
95
+ */
96
+ private buckets;
97
+ constructor();
98
+ /**
99
+ * Record a single telemetry event.
100
+ * Thread-safe within Node.js single-thread model (no async gap between read/write).
101
+ */
102
+ record(event: TelemetryEvent): void;
103
+ /**
104
+ * Evict buckets older than MAX_BUCKETS hours relative to the current hour.
105
+ * Called on every record() so no background timer is needed.
106
+ */
107
+ private _evict;
108
+ /**
109
+ * Query telemetry data.
110
+ * @param windowHours How many hours to include (1–24, default 24)
111
+ * @param bucketHours Bucket granularity (must be 1 for now)
112
+ * @param nowMs Override "now" for testing
113
+ */
114
+ query(windowHours?: number, bucketHours?: number, nowMs?: number): TelemetryResponse;
115
+ /** Exposed for tests — reset all collected data. */
116
+ _reset(): void;
117
+ /** Exposed for tests — inspect raw bucket map size. */
118
+ _bucketCount(): number;
119
+ }
120
+ /**
121
+ * Module-scope singleton used by api-server.ts hooks.
122
+ * Tests import this and call _reset() in before()/beforeEach().
123
+ */
124
+ export declare const collector: TelemetryCollector;
125
+ /**
126
+ * Middleware-style wrapper: records telemetry for a completed request.
127
+ * Call AFTER response has been computed, before writing to the client.
128
+ *
129
+ * @param path Which API path
130
+ * @param startMs Performance.now()-based start time in epoch ms (Date.now() at request start)
131
+ * @param endMs Date.now() at response ready (before write)
132
+ * @param resultCount Number of results in response
133
+ * @param pathUsed Which internal search path was invoked
134
+ * @param semanticUsed Whether semantic (vector) embedding was called
135
+ * @param statusCode HTTP response status
136
+ */
137
+ export declare function recordRequest(path: TelemetryPath, startMs: number, endMs: number, resultCount: number, pathUsed: string, semanticUsed: boolean, statusCode?: number): void;
138
+ /**
139
+ * Handler for GET /api/observability/telemetry endpoint.
140
+ * Parses ?window=Nh&bucket=1h query params (defaults: window=24h, bucket=1h).
141
+ * Returns TelemetryResponse JSON.
142
+ */
143
+ export declare function handleObsTelemetry(params: Record<string, string>): TelemetryResponse;
144
+ /**
145
+ * Parse window param: "24h" → 24, "6h" → 6, "1h" → 1.
146
+ * Clamps to [1, 24]. Falls back to 24 on invalid input.
147
+ */
148
+ export declare function parseWindowParam(raw: string): number;
149
+ export declare const _internals: {
150
+ BUCKET_SIZE_MS: number;
151
+ MAX_BUCKETS: number;
152
+ MAX_SAMPLES_PER_BUCKET: number;
153
+ hourFloor: typeof hourFloor;
154
+ hourLabel: typeof hourLabel;
155
+ emptyBucket: typeof emptyBucket;
156
+ percentile: typeof percentile;
157
+ };
158
+ export {};
@@ -0,0 +1,249 @@
1
+ /**
2
+ * telemetry-collector.ts — F10 Phase C Phase 1: in-process telemetry collector
3
+ *
4
+ * Collects per-request metrics for /api/search and /api/answer.
5
+ * Stores data in a ring buffer (last 24h, 1h buckets).
6
+ * No external dependencies — pure in-memory with atomic writes.
7
+ *
8
+ * Design principles:
9
+ * - Ring buffer of 24 fixed 1h buckets; oldest bucket rolls when the hour
10
+ * changes. Rollover is done lazily on record() — no background timer needed.
11
+ * - All writes are synchronous (single-process Node.js event loop is naturally
12
+ * sequential); no mutex needed.
13
+ * - Exported as a singleton (module-scope instance) with _reset() for tests.
14
+ *
15
+ * Spec: specs/2026-05-01-F10-observability-dashboard.md §P2 (Phase C, Phase 1)
16
+ * Status: Phase C Phase 1 implementation
17
+ *
18
+ * Endpoint served by api-server.ts wire-up:
19
+ * GET /api/observability/telemetry?window=24h&bucket=1h
20
+ */
21
+ // ── Constants ──────────────────────────────────────────────────────────────────
22
+ const BUCKET_SIZE_MS = 60 * 60 * 1000; // 1 hour
23
+ const MAX_BUCKETS = 24; // 24h ring buffer
24
+ /** Cap samples per bucket to avoid unbounded memory (≥1000 req/h = still accurate) */
25
+ const MAX_SAMPLES_PER_BUCKET = 1000;
26
+ // ── Bucket helpers ─────────────────────────────────────────────────────────────
27
+ function hourFloor(ts) {
28
+ return Math.floor(ts / BUCKET_SIZE_MS) * BUCKET_SIZE_MS;
29
+ }
30
+ function hourLabel(ts) {
31
+ return new Date(ts).toISOString().slice(0, 13) + ":00Z";
32
+ }
33
+ function emptyBucket(hour_ts) {
34
+ return {
35
+ hour_ts,
36
+ label: hourLabel(hour_ts),
37
+ count: 0,
38
+ latency_sum_ms: 0,
39
+ p50_ms: null,
40
+ p95_ms: null,
41
+ p99_ms: null,
42
+ by_path: { search: 0, answer: 0 },
43
+ by_path_used: {},
44
+ semantic_count: 0,
45
+ result_count_sum: 0,
46
+ _samples: [],
47
+ };
48
+ }
49
+ /** Compute percentile from a sorted array. Returns null if empty. */
50
+ function percentile(sorted, p) {
51
+ if (sorted.length === 0)
52
+ return null;
53
+ const idx = Math.ceil((p / 100) * sorted.length) - 1;
54
+ const clamped = Math.max(0, Math.min(sorted.length - 1, idx));
55
+ return sorted[clamped] ?? null;
56
+ }
57
+ function recomputePercentiles(bucket) {
58
+ const sorted = [...bucket._samples].sort((a, b) => a - b);
59
+ bucket.p50_ms = percentile(sorted, 50);
60
+ bucket.p95_ms = percentile(sorted, 95);
61
+ bucket.p99_ms = percentile(sorted, 99);
62
+ }
63
+ function stripSamples(bucket) {
64
+ const { _samples: _s, ...rest } = bucket;
65
+ void _s; // suppress unused var
66
+ return rest;
67
+ }
68
+ // ── TelemetryCollector class ───────────────────────────────────────────────────
69
+ export class TelemetryCollector {
70
+ /**
71
+ * Ring buffer: Map<hour_ts, TelemetryBucket>.
72
+ * We keep at most MAX_BUCKETS entries; evict oldest when rolling.
73
+ */
74
+ buckets = new Map();
75
+ constructor() { }
76
+ /**
77
+ * Record a single telemetry event.
78
+ * Thread-safe within Node.js single-thread model (no async gap between read/write).
79
+ */
80
+ record(event) {
81
+ const hour_ts = hourFloor(event.ts);
82
+ this._evict(hour_ts);
83
+ let bucket = this.buckets.get(hour_ts);
84
+ if (!bucket) {
85
+ bucket = emptyBucket(hour_ts);
86
+ this.buckets.set(hour_ts, bucket);
87
+ }
88
+ bucket.count++;
89
+ bucket.latency_sum_ms += event.latency_ms;
90
+ // Reservoir: only keep MAX_SAMPLES_PER_BUCKET samples
91
+ if (bucket._samples.length < MAX_SAMPLES_PER_BUCKET) {
92
+ bucket._samples.push(event.latency_ms);
93
+ }
94
+ else {
95
+ // Replace a random existing sample (reservoir sampling step)
96
+ const replaceIdx = Math.floor(Math.random() * MAX_SAMPLES_PER_BUCKET);
97
+ bucket._samples[replaceIdx] = event.latency_ms;
98
+ }
99
+ recomputePercentiles(bucket);
100
+ bucket.by_path[event.path]++;
101
+ const prevCount = bucket.by_path_used[event.path_used] ?? 0;
102
+ bucket.by_path_used[event.path_used] = prevCount + 1;
103
+ if (event.semantic_used)
104
+ bucket.semantic_count++;
105
+ bucket.result_count_sum += event.result_count;
106
+ }
107
+ /**
108
+ * Evict buckets older than MAX_BUCKETS hours relative to the current hour.
109
+ * Called on every record() so no background timer is needed.
110
+ */
111
+ _evict(currentHour) {
112
+ // Keep only the most recent MAX_BUCKETS hours.
113
+ // cutoff is the oldest hour we want to KEEP, so anything strictly older is evicted.
114
+ // currentHour is the most recent hour slot; oldest kept = currentHour - (MAX_BUCKETS-1)*BUCKET_SIZE_MS
115
+ const oldestKept = currentHour - (MAX_BUCKETS - 1) * BUCKET_SIZE_MS;
116
+ for (const [ts] of this.buckets) {
117
+ if (ts < oldestKept) {
118
+ this.buckets.delete(ts);
119
+ }
120
+ }
121
+ }
122
+ /**
123
+ * Query telemetry data.
124
+ * @param windowHours How many hours to include (1–24, default 24)
125
+ * @param bucketHours Bucket granularity (must be 1 for now)
126
+ * @param nowMs Override "now" for testing
127
+ */
128
+ query(windowHours = 24, bucketHours = 1, nowMs) {
129
+ const now = nowMs ?? Date.now();
130
+ const window_hours = Math.max(1, Math.min(MAX_BUCKETS, Math.floor(windowHours)));
131
+ void bucketHours; // reserved for future sub-hour buckets
132
+ const to_ts = hourFloor(now) + BUCKET_SIZE_MS; // inclusive of current partial hour
133
+ const from_ts = to_ts - window_hours * BUCKET_SIZE_MS;
134
+ // Build ordered bucket list (oldest → newest), filling gaps with empty buckets
135
+ const resultBuckets = [];
136
+ let agg_count = 0;
137
+ let agg_latency_sum = 0;
138
+ let agg_semantic = 0;
139
+ const agg_by_path = { search: 0, answer: 0 };
140
+ const allSamples = [];
141
+ for (let ts = from_ts; ts < to_ts; ts += BUCKET_SIZE_MS) {
142
+ const bucket = this.buckets.get(ts);
143
+ if (bucket) {
144
+ resultBuckets.push(stripSamples(bucket));
145
+ agg_count += bucket.count;
146
+ agg_latency_sum += bucket.latency_sum_ms;
147
+ agg_semantic += bucket.semantic_count;
148
+ agg_by_path.search += bucket.by_path.search;
149
+ agg_by_path.answer += bucket.by_path.answer;
150
+ allSamples.push(...bucket._samples);
151
+ }
152
+ else {
153
+ resultBuckets.push(stripSamples(emptyBucket(ts)));
154
+ }
155
+ }
156
+ // Aggregate percentiles from all samples
157
+ const sortedAll = [...allSamples].sort((a, b) => a - b);
158
+ return {
159
+ window: {
160
+ hours: window_hours,
161
+ bucket_size_hours: 1,
162
+ from_ts,
163
+ to_ts,
164
+ },
165
+ buckets: resultBuckets,
166
+ aggregate: {
167
+ count: agg_count,
168
+ avg_latency_ms: agg_count > 0 ? Math.round(agg_latency_sum / agg_count) : null,
169
+ p50_ms: percentile(sortedAll, 50),
170
+ p95_ms: percentile(sortedAll, 95),
171
+ p99_ms: percentile(sortedAll, 99),
172
+ by_path: agg_by_path,
173
+ semantic_ratio: agg_count > 0 ? Math.round((agg_semantic / agg_count) * 1000) / 1000 : null,
174
+ },
175
+ generated_at_ms: now,
176
+ };
177
+ }
178
+ /** Exposed for tests — reset all collected data. */
179
+ _reset() {
180
+ this.buckets.clear();
181
+ }
182
+ /** Exposed for tests — inspect raw bucket map size. */
183
+ _bucketCount() {
184
+ return this.buckets.size;
185
+ }
186
+ }
187
+ // ── Singleton ──────────────────────────────────────────────────────────────────
188
+ /**
189
+ * Module-scope singleton used by api-server.ts hooks.
190
+ * Tests import this and call _reset() in before()/beforeEach().
191
+ */
192
+ export const collector = new TelemetryCollector();
193
+ // ── Wire-up helpers (called from api-server.ts) ────────────────────────────────
194
+ /**
195
+ * Middleware-style wrapper: records telemetry for a completed request.
196
+ * Call AFTER response has been computed, before writing to the client.
197
+ *
198
+ * @param path Which API path
199
+ * @param startMs Performance.now()-based start time in epoch ms (Date.now() at request start)
200
+ * @param endMs Date.now() at response ready (before write)
201
+ * @param resultCount Number of results in response
202
+ * @param pathUsed Which internal search path was invoked
203
+ * @param semanticUsed Whether semantic (vector) embedding was called
204
+ * @param statusCode HTTP response status
205
+ */
206
+ export function recordRequest(path, startMs, endMs, resultCount, pathUsed, semanticUsed, statusCode = 200) {
207
+ collector.record({
208
+ ts: endMs,
209
+ path,
210
+ latency_ms: Math.max(0, endMs - startMs),
211
+ result_count: resultCount,
212
+ path_used: pathUsed,
213
+ semantic_used: semanticUsed,
214
+ status_code: statusCode,
215
+ });
216
+ }
217
+ /**
218
+ * Handler for GET /api/observability/telemetry endpoint.
219
+ * Parses ?window=Nh&bucket=1h query params (defaults: window=24h, bucket=1h).
220
+ * Returns TelemetryResponse JSON.
221
+ */
222
+ export function handleObsTelemetry(params) {
223
+ const windowParam = params["window"] ?? "24h";
224
+ const windowHours = parseWindowParam(windowParam);
225
+ return collector.query(windowHours, 1);
226
+ }
227
+ /**
228
+ * Parse window param: "24h" → 24, "6h" → 6, "1h" → 1.
229
+ * Clamps to [1, 24]. Falls back to 24 on invalid input.
230
+ */
231
+ export function parseWindowParam(raw) {
232
+ const m = /^(\d+)h?$/i.exec(raw.trim());
233
+ if (!m || !m[1])
234
+ return 24;
235
+ const n = parseInt(m[1], 10);
236
+ if (!Number.isFinite(n) || n < 1)
237
+ return 24;
238
+ return Math.min(24, n);
239
+ }
240
+ // ── Internals for tests ────────────────────────────────────────────────────────
241
+ export const _internals = {
242
+ BUCKET_SIZE_MS,
243
+ MAX_BUCKETS,
244
+ MAX_SAMPLES_PER_BUCKET,
245
+ hourFloor,
246
+ hourLabel,
247
+ emptyBucket,
248
+ percentile,
249
+ };
@@ -0,0 +1,27 @@
1
+ export type TemporalBoostMode = "off" | "shadow" | "active";
2
+ export declare function isTemporalQuery(query: string): boolean;
3
+ export declare const SECTION_BOOST_TEMPORAL: Record<string, number>;
4
+ export declare function getMode(): TemporalBoostMode;
5
+ /**
6
+ * Resolve effective section_boost given context.
7
+ * - mode=off → returns original sectionBoost (current behavior)
8
+ * - mode=shadow → returns original (active=false short-circuit) but caller logs alt via getOverride()
9
+ * - mode=active + temporal + section in lookup → returns override
10
+ * - else → returns original
11
+ */
12
+ export declare function effectiveSectionBoost(sectionBoost: number | null, section: string | null, isTemporal: boolean, mode?: TemporalBoostMode): number;
13
+ /**
14
+ * Pure lookup of override value (independent of mode). Used by shadow logger
15
+ * to compute "what would happen if active".
16
+ */
17
+ export declare function getOverride(section: string | null): number | null;
18
+ export interface TemporalShadowSignal {
19
+ isTemporal: boolean;
20
+ mode: TemporalBoostMode;
21
+ affectedChunks?: number;
22
+ }
23
+ /**
24
+ * Lightweight log helper — chamado 1× por query no pipeline.
25
+ * NOX_TEMPORAL_BOOST_LOG=1 pra emitir.
26
+ */
27
+ export declare function logTemporal(query: string, signal: TemporalShadowSignal): void;
@@ -0,0 +1,81 @@
1
+ // E13 — Temporal-aware Ranking
2
+ // 2026-05-06 impl. Spec: memoria-nox/specs/2026-05-06-E13-temporal-aware-ranking.md
3
+ //
4
+ // Detector de query temporal + override de section_boost. Hoje timeline=0.8
5
+ // (demote) penaliza 100% das queries temporais cured (gold em section=timeline).
6
+ // Pra elas, timeline IS truth. Override apenas quando isTemporalQuery(query).
7
+ //
8
+ // Aditivo single-pass (regra crítica #5): substitui lookup, não soma.
9
+ //
10
+ // Modes (env NOX_TEMPORAL_BOOST_MODE):
11
+ // off — disabled (default), no compute, no apply
12
+ // shadow — compute override + log delta, NO apply
13
+ // active — compute + log + apply override
14
+ // Padrões PT-BR + inglês curto. Cada um cobre family of triggers.
15
+ const TEMPORAL_PATTERNS = [
16
+ /\b(quando|que\s+dia|que\s+data|qual\s+(?:data|dia)|em\s+que\s+(?:dia|data))\b/iu,
17
+ /\b(primeir[ao]|últim[ao]|inicial)\b/iu,
18
+ /\b(deploy(?:ado|ed|amento)|ativad[ao]|subiu|lançad[ao]|started|aconteceu|inici(?:ou|ado))\b/iu,
19
+ /\b\d{4}-\d{2}-\d{2}\b/, // ISO date
20
+ ];
21
+ export function isTemporalQuery(query) {
22
+ if (!query || typeof query !== "string")
23
+ return false;
24
+ const q = query.trim();
25
+ if (q.length < 3)
26
+ return false;
27
+ return TEMPORAL_PATTERNS.some((re) => re.test(q));
28
+ }
29
+ // Override aplicado SOMENTE quando isTemporalQuery(query). Substitui lookup
30
+ // padrão (não soma). Valores escolhidos pra inverter timeline demote sem
31
+ // destruir compiled (que ainda pode ter info temporal relevante).
32
+ export const SECTION_BOOST_TEMPORAL = {
33
+ compiled: 1.0, // neutro — compiled é truth atual, mas não é a fonte primária pra "quando"
34
+ frontmatter: 0.9, // levemente demote — metadata raramente responde "quando"
35
+ timeline: 1.4, // PROMOVE — é onde events com data residem
36
+ // null/legacy = 1.0 (handled by caller)
37
+ };
38
+ export function getMode() {
39
+ const v = (process.env.NOX_TEMPORAL_BOOST_MODE || "off").toLowerCase();
40
+ if (v === "off" || v === "shadow" || v === "active")
41
+ return v;
42
+ return "off";
43
+ }
44
+ /**
45
+ * Resolve effective section_boost given context.
46
+ * - mode=off → returns original sectionBoost (current behavior)
47
+ * - mode=shadow → returns original (active=false short-circuit) but caller logs alt via getOverride()
48
+ * - mode=active + temporal + section in lookup → returns override
49
+ * - else → returns original
50
+ */
51
+ export function effectiveSectionBoost(sectionBoost, section, isTemporal, mode = getMode()) {
52
+ const baseline = typeof sectionBoost === "number" ? sectionBoost : 1.0;
53
+ if (mode !== "active")
54
+ return baseline;
55
+ if (!isTemporal || !section)
56
+ return baseline;
57
+ const override = SECTION_BOOST_TEMPORAL[section];
58
+ return override !== undefined ? override : baseline;
59
+ }
60
+ /**
61
+ * Pure lookup of override value (independent of mode). Used by shadow logger
62
+ * to compute "what would happen if active".
63
+ */
64
+ export function getOverride(section) {
65
+ if (!section)
66
+ return null;
67
+ const v = SECTION_BOOST_TEMPORAL[section];
68
+ return v !== undefined ? v : null;
69
+ }
70
+ /**
71
+ * Lightweight log helper — chamado 1× por query no pipeline.
72
+ * NOX_TEMPORAL_BOOST_LOG=1 pra emitir.
73
+ */
74
+ export function logTemporal(query, signal) {
75
+ if (process.env.NOX_TEMPORAL_BOOST_LOG !== "1")
76
+ return;
77
+ const safeQuery = (query || "").replace(/[\r\n"]/g, " ").slice(0, 80);
78
+ const tag = signal.mode === "active" ? "temporal-active" : "temporal-shadow";
79
+ console.error(`[${tag}] query="${safeQuery}" temporal=${signal.isTemporal} mode=${signal.mode}` +
80
+ (signal.affectedChunks !== undefined ? ` affected=${signal.affectedChunks}` : ""));
81
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * T11 — Optional auth gate
3
+ *
4
+ * Token-based, env-gated. Disabled by default (assumes 127.0.0.1 binding).
5
+ *
6
+ * Behavior:
7
+ * - If `NOX_VIEWER_AUTH_TOKEN` is unset → allow all (default).
8
+ * - If set → require either header `Authorization: Bearer <token>` OR
9
+ * query string `?token=<token>`.
10
+ * - Constant-time compare so timing leaks are not informative.
11
+ *
12
+ * The `?token=` path exists because the browser EventSource API cannot
13
+ * send custom headers; document this trade-off in VIEWER.md.
14
+ */
15
+ export interface AuthRequest {
16
+ /** Lower-cased headers map. */
17
+ headers: Record<string, string | string[] | undefined>;
18
+ /** Parsed query string. Values are first-occurrence. */
19
+ query: Record<string, string | undefined>;
20
+ }
21
+ export interface AuthResult {
22
+ ok: boolean;
23
+ reason?: "no_token_configured" | "matched" | "missing" | "mismatch";
24
+ }
25
+ /** Required-token policy active? */
26
+ export declare function authEnabled(env?: NodeJS.ProcessEnv): boolean;
27
+ /**
28
+ * Evaluate a request against the configured policy.
29
+ */
30
+ export declare function authorize(req: AuthRequest, env?: NodeJS.ProcessEnv): AuthResult;
31
+ /** Headers + status to send back when authorize() fails. */
32
+ export interface DenyResponse {
33
+ status: 401;
34
+ headers: Record<string, string>;
35
+ body: string;
36
+ }
37
+ export declare function denyResponse(reason: "missing" | "mismatch"): DenyResponse;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * T11 — Optional auth gate
3
+ *
4
+ * Token-based, env-gated. Disabled by default (assumes 127.0.0.1 binding).
5
+ *
6
+ * Behavior:
7
+ * - If `NOX_VIEWER_AUTH_TOKEN` is unset → allow all (default).
8
+ * - If set → require either header `Authorization: Bearer <token>` OR
9
+ * query string `?token=<token>`.
10
+ * - Constant-time compare so timing leaks are not informative.
11
+ *
12
+ * The `?token=` path exists because the browser EventSource API cannot
13
+ * send custom headers; document this trade-off in VIEWER.md.
14
+ */
15
+ import { timingSafeEqual } from "node:crypto";
16
+ function configuredToken(env = process.env) {
17
+ return env.NOX_VIEWER_AUTH_TOKEN ?? "";
18
+ }
19
+ /** Required-token policy active? */
20
+ export function authEnabled(env = process.env) {
21
+ return configuredToken(env).length > 0;
22
+ }
23
+ function extractToken(req) {
24
+ const authHeader = req.headers.authorization ?? req.headers["Authorization"];
25
+ if (typeof authHeader === "string") {
26
+ const m = /^Bearer\s+(\S+)/i.exec(authHeader);
27
+ if (m)
28
+ return m[1] ?? null;
29
+ }
30
+ const q = req.query.token;
31
+ if (typeof q === "string" && q.length > 0)
32
+ return q;
33
+ return null;
34
+ }
35
+ function safeEqual(a, b) {
36
+ if (a.length !== b.length) {
37
+ // Still run a comparison of same-length buffers to neutralize length leak.
38
+ const pad = Buffer.alloc(Math.max(a.length, b.length, 1));
39
+ timingSafeEqual(pad, pad);
40
+ return false;
41
+ }
42
+ return timingSafeEqual(Buffer.from(a), Buffer.from(b));
43
+ }
44
+ /**
45
+ * Evaluate a request against the configured policy.
46
+ */
47
+ export function authorize(req, env = process.env) {
48
+ const expected = configuredToken(env);
49
+ if (expected.length === 0) {
50
+ return { ok: true, reason: "no_token_configured" };
51
+ }
52
+ const presented = extractToken(req);
53
+ if (!presented) {
54
+ return { ok: false, reason: "missing" };
55
+ }
56
+ if (safeEqual(presented, expected)) {
57
+ return { ok: true, reason: "matched" };
58
+ }
59
+ return { ok: false, reason: "mismatch" };
60
+ }
61
+ export function denyResponse(reason) {
62
+ return {
63
+ status: 401,
64
+ headers: {
65
+ "Content-Type": "application/json",
66
+ "WWW-Authenticate": 'Bearer realm="nox-mem-viewer"',
67
+ },
68
+ body: JSON.stringify({ error: "unauthorized", reason }),
69
+ };
70
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * T9 — Backpressure ring buffer
3
+ *
4
+ * Bounded queue per SSE client. Producer pushes events; consumer drains.
5
+ * If consumer is slow and buffer hits capacity, OLDEST event is dropped
6
+ * (not the new one) so the recent stream stays current. Producer NEVER
7
+ * blocks — drop counter is incremented and exposed via `stats()`.
8
+ *
9
+ * Design:
10
+ * - O(1) push + drain via circular buffer (Array-backed deque)
11
+ * - No locks (single-threaded JS); concurrency safe wrt the event loop
12
+ * - Stats are read-only snapshots
13
+ */
14
+ export interface BackpressureStats {
15
+ /** Items currently buffered. */
16
+ size: number;
17
+ /** Total drop count since construction. */
18
+ dropped: number;
19
+ /** Total enqueued since construction. */
20
+ enqueued: number;
21
+ /** Capacity. */
22
+ capacity: number;
23
+ }
24
+ export declare class BackpressureQueue<T> {
25
+ readonly capacity: number;
26
+ private buf;
27
+ private head;
28
+ private tail;
29
+ private size_;
30
+ private dropped_;
31
+ private enqueued_;
32
+ constructor(capacity: number);
33
+ /**
34
+ * Push an item. Returns:
35
+ * - "ok" if buffered
36
+ * - "dropped_oldest" if buffer was full and oldest was evicted to make room
37
+ */
38
+ push(item: T): "ok" | "dropped_oldest";
39
+ /** Pop oldest item. Undefined if empty. */
40
+ shift(): T | undefined;
41
+ /** Drain up to `max` items into an array. */
42
+ drain(max?: number): T[];
43
+ get length(): number;
44
+ stats(): BackpressureStats;
45
+ /** Reset to empty. Counters preserved unless `hard=true`. */
46
+ clear(hard?: boolean): void;
47
+ }
48
+ /**
49
+ * Detect whether write to a Node.js Writable is hitting backpressure.
50
+ * Convenience wrapper for `res.write()` return value semantics.
51
+ */
52
+ export interface BackpressureSink {
53
+ /** Buffered amount in bytes (best-effort, may be undefined). */
54
+ writableLength?: number;
55
+ /** High-water mark (bytes). */
56
+ writableHighWaterMark?: number;
57
+ write?(chunk: string): boolean;
58
+ }
59
+ export declare function isSinkSaturated(sink: BackpressureSink): boolean;