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,524 @@
1
+ /**
2
+ * F1 — GET /api/brief (Session Priming Loop, fase 1)
3
+ *
4
+ * Pointer-pattern priming digest: top-N chunks por salience filtrados por
5
+ * escopo. Toda sessão (agente OpenClaw, Claude Code Mac, qualquer cliente
6
+ * MCP/HTTP) nasce contextualizada sem search cego.
7
+ *
8
+ * Specs (memoria-nox):
9
+ * - PRD: specs/2026-06-04-session-priming-loop.md (§6 contrato)
10
+ * - Impl: specs/2026-06-04-F1-api-brief-implementation.md (T0 findings)
11
+ *
12
+ * Invariantes:
13
+ * - Read-only sobre `chunks`. NÃO toca `chunks.access_count` — o sinal
14
+ * orgânico fica 100% puro pro audit mensal do Cipher (high-pain órfãos).
15
+ * Tracking de serving vai pra tabela própria `brief_log`.
16
+ * - NÃO altera scoring de search (regra #5 do repo) — consome
17
+ * `calculateSalience` canônica as-is, sem fork nem pesos próprios.
18
+ * - Framework-agnostic (mesmo padrão de src/api/conflict.ts): handler puro
19
+ * testável; api-server.ts faz o dispatch HTTP.
20
+ *
21
+ * Scope mapping (T0 2026-06-04, validado em prod 100.5k chunks):
22
+ * - agent → `sessions/<persona>/%` (cipher 7.6k, atlas 3.8k…)
23
+ * - scope → `memory/mac-docs/<scope>/%` (NUVIVI, PESSOAL, PPR…)
24
+ * | `shared/imports/Claude/Projetos/<scope>/%`
25
+ * | `shared/imports/<scope>/%`
26
+ * | `<scope>/%` (namespaces top-level)
27
+ * - global → sem filtro de path
28
+ *
29
+ * Changelog:
30
+ * - v1.1 (gate T7): age por source_date; dedup exato (title,one_liner);
31
+ * strip HTML no one_liner.
32
+ * - v1.2 (gate F3 real, Nox): (a) collapse de near-dups por Jaccard de
33
+ * tokens; (b) com `agent`, união garantida agente ∪ scope/global
34
+ * (~n/2 slots cada, backfill mútuo).
35
+ */
36
+ import { calculateSalience } from "../salience.js";
37
+ import { briefScore, diffBriefs, diversityConfigFromEnv, } from "./brief-diversity.js";
38
+ // ─── Constantes ──────────────────────────────────────────────────────────────
39
+ const DEFAULT_N = 10;
40
+ const MAX_N = 25;
41
+ /** Pool de candidatos pré-ranqueado em SQL antes do re-rank exato por salience.
42
+ * Proxy barato (importance + pain + access binário) aproxima a fórmula v2
43
+ * aditiva; 500 rows re-ranqueadas em JS mantém p50 < 100ms em corpus 100k+. */
44
+ const CANDIDATE_POOL = 500;
45
+ /** Budget do digest em tokens estimados (chars/4) — princípio 4.3 do PRD. */
46
+ const TOKEN_BUDGET = 1200;
47
+ const ONE_LINER_MAX = 140;
48
+ const SCOPE_RE = /^[\p{L}\p{N}][\p{L}\p{N}._-]{0,63}$/u;
49
+ const AGENT_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
50
+ const SINCE_RE = /^(\d{1,4})([hdw])$/;
51
+ export function parseBriefParams(q) {
52
+ const scope = (q.scope || "").trim();
53
+ if (!scope)
54
+ return { ok: false, error: "scope é obrigatório" };
55
+ if (!SCOPE_RE.test(scope)) {
56
+ return { ok: false, error: "scope inválido (alfanumérico + ._- , máx 64)" };
57
+ }
58
+ let agent;
59
+ if (q.agent !== undefined && q.agent !== "") {
60
+ if (!AGENT_RE.test(q.agent)) {
61
+ return { ok: false, error: "agent inválido (slug a-z0-9-, máx 32)" };
62
+ }
63
+ agent = q.agent;
64
+ }
65
+ let n = DEFAULT_N;
66
+ if (q.n !== undefined && q.n !== "") {
67
+ const parsed = parseInt(q.n, 10);
68
+ if (!Number.isFinite(parsed) || parsed < 1) {
69
+ return { ok: false, error: "n inválido (inteiro ≥ 1)" };
70
+ }
71
+ n = Math.min(parsed, MAX_N);
72
+ }
73
+ const format = q.format === "text" ? "text" : "json";
74
+ let sinceSql;
75
+ if (q.since !== undefined && q.since !== "") {
76
+ const m = SINCE_RE.exec(q.since);
77
+ if (!m)
78
+ return { ok: false, error: "since inválido (ex: 24h, 30d, 2w)" };
79
+ const unit = { h: "hours", d: "days", w: "days" }[m[2]];
80
+ const qty = m[2] === "w" ? parseInt(m[1], 10) * 7 : parseInt(m[1], 10);
81
+ sinceSql = `-${qty} ${unit}`;
82
+ }
83
+ return { ok: true, params: { scope, agent, n, format, sinceSql } };
84
+ }
85
+ // ─── Scope → LIKE patterns ───────────────────────────────────────────────────
86
+ /** Escapa metachars do LIKE (`%`, `_`, `\`) no trecho dinâmico — os wildcards
87
+ * `%` dos patterns são adicionados depois. Queries usam `ESCAPE '\'`. */
88
+ export function escapeLike(s) {
89
+ return s.replace(/[\\%_]/g, (c) => `\\${c}`);
90
+ }
91
+ export function scopePatterns(scope, agent) {
92
+ const patterns = [];
93
+ if (scope !== "global") {
94
+ const esc = escapeLike(scope);
95
+ patterns.push(`memory/mac-docs/${esc}/%`, `shared/imports/Claude/Projetos/${esc}/%`, `shared/imports/${esc}/%`, `${esc}/%`);
96
+ }
97
+ if (agent)
98
+ patterns.push(`sessions/${escapeLike(agent)}/%`);
99
+ return patterns;
100
+ }
101
+ // ─── Extração de digest ──────────────────────────────────────────────────────
102
+ /** v1.2a — assinatura de tokens pra collapse de near-duplicates.
103
+ * Gate F3 real (2026-06-04): 4/10 itens do brief do Nox eram variantes de
104
+ * "Ler/Usar/Seguir HEARTBEAT.md ... estritamente" — dedup exato não pega.
105
+ *
106
+ * Métrica: CONTAINMENT (interseção / menor assinatura), não Jaccard —
107
+ * variantes curtas vs longas do mesmo assunto diluem o Jaccard mas mantêm
108
+ * containment alto. Guarda: assinaturas < MIN_SIG tokens só dedupam por
109
+ * match exato (containment em sets minúsculos over-colapsa). Mantém sempre
110
+ * o candidato de maior salience. */
111
+ const NEAR_DUP_CONTAINMENT = 0.6;
112
+ const MIN_SIG_TOKENS = 3;
113
+ export function tokenSignature(title, oneLiner) {
114
+ const tokens = `${title} ${oneLiner}`
115
+ .toLowerCase()
116
+ .split(/[^\p{L}\p{N}.]+/u)
117
+ .filter((t) => t.length >= 4);
118
+ return new Set(tokens);
119
+ }
120
+ export function isNearDup(a, b) {
121
+ if (a.size < MIN_SIG_TOKENS || b.size < MIN_SIG_TOKENS)
122
+ return false;
123
+ let inter = 0;
124
+ for (const t of a)
125
+ if (b.has(t))
126
+ inter++;
127
+ return inter / Math.min(a.size, b.size) >= NEAR_DUP_CONTAINMENT;
128
+ }
129
+ /** Primeira linha "de conteúdo": pula vazias, fences de frontmatter (---) e
130
+ * marcação estrutural; strip de tags HTML (docs OCR/import vazam <u> etc.),
131
+ * heading/list markers; cap ONE_LINER_MAX. */
132
+ export function extractOneLiner(text) {
133
+ if (!text)
134
+ return "";
135
+ for (const raw of text.split("\n")) {
136
+ const line = raw.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
137
+ if (!line || line === "---" || line === "```")
138
+ continue;
139
+ const cleaned = line
140
+ .replace(/^#{1,6}\s+/, "")
141
+ .replace(/^[-*>]\s+/, "")
142
+ .replace(/\*\*/g, "")
143
+ .trim();
144
+ if (!cleaned)
145
+ continue;
146
+ return cleaned.length > ONE_LINER_MAX
147
+ ? cleaned.slice(0, ONE_LINER_MAX - 1) + "…"
148
+ : cleaned;
149
+ }
150
+ return "";
151
+ }
152
+ /** Datas do SQLite vêm "YYYY-MM-DD HH:MM:SS" (UTC) ou "YYYY-MM-DD" (source_date).
153
+ * Date.parse direto trata date-only como UTC; o formato com espaço precisa
154
+ * virar ISO + Z explícito pra não cair em timezone local. */
155
+ export function parseDbDateMs(ref) {
156
+ if (ref.includes(" "))
157
+ return Date.parse(ref.replace(" ", "T") + "Z");
158
+ return Date.parse(ref);
159
+ }
160
+ export function titleFromSourceFile(sourceFile) {
161
+ if (!sourceFile)
162
+ return "(sem origem)";
163
+ const base = sourceFile.split("/").pop() || sourceFile;
164
+ return base.replace(/\.(md|txt|json|jsonl)$/i, "");
165
+ }
166
+ // ─── brief_log (única escrita do endpoint — schema próprio, zero ALTER) ─────
167
+ let briefLogReady = false;
168
+ export function ensureBriefLog(db) {
169
+ if (briefLogReady)
170
+ return;
171
+ db.exec(`
172
+ CREATE TABLE IF NOT EXISTS brief_log (
173
+ id INTEGER PRIMARY KEY,
174
+ chunk_id INTEGER NOT NULL,
175
+ scope TEXT NOT NULL,
176
+ agent TEXT,
177
+ served_at TEXT NOT NULL DEFAULT (datetime('now'))
178
+ );
179
+ CREATE INDEX IF NOT EXISTS idx_brief_log_chunk ON brief_log(chunk_id, served_at);
180
+ `);
181
+ briefLogReady = true;
182
+ }
183
+ /** Test-only: reseta o memo de criação (cada DB de teste é novo). */
184
+ export function _resetBriefLogMemo() {
185
+ briefLogReady = false;
186
+ }
187
+ /** Pool de candidatos: pré-rank SQL barato (proxy da fórmula v2 aditiva)
188
+ * → LIMIT 500 → re-rank exato com calculateSalience. */
189
+ function fetchRankedPool(db, patterns, sinceSql, nowMs) {
190
+ const where = [];
191
+ const args = [];
192
+ if (patterns.length > 0) {
193
+ where.push(`(${patterns.map(() => "source_file LIKE ? ESCAPE '\\'").join(" OR ")})`);
194
+ args.push(...patterns);
195
+ }
196
+ if (sinceSql) {
197
+ where.push("updated_at >= datetime('now', ?)");
198
+ args.push(sinceSql);
199
+ }
200
+ const whereSql = where.length ? `WHERE ${where.join(" AND ")}` : "";
201
+ const rows = db
202
+ .prepare(`SELECT id, source_file, chunk_text, chunk_type, source_type, tier,
203
+ pain, importance, retention_days, source_date, created_at,
204
+ updated_at, last_accessed_at, access_count
205
+ FROM chunks
206
+ ${whereSql}
207
+ ORDER BY (0.55 * COALESCE(importance, 0.5)
208
+ + 0.10 * COALESCE(pain, 0.2)
209
+ + CASE WHEN COALESCE(access_count, 0) > 0 THEN 0.1 ELSE 0 END) DESC,
210
+ updated_at DESC
211
+ LIMIT ${CANDIDATE_POOL}`)
212
+ .all(...args);
213
+ return rows
214
+ .map((r) => ({
215
+ row: r,
216
+ salience: calculateSalience(r, nowMs),
217
+ }))
218
+ .sort((a, b) => b.salience - a.salience);
219
+ }
220
+ /** Score efetivo do re-rank: briefScore (D2) quando presente, senão salience. */
221
+ function effScore(c) {
222
+ return c.briefScore ?? c.salience;
223
+ }
224
+ /** Seleção com dedup global (exato por id + near-dup por assinatura de tokens,
225
+ * v1.2a) — mantém sempre o candidato de maior score. Parametrizado por
226
+ * `scoreOf` (off=salience, D2=briefScore) e por freshness slots (parte B):
227
+ * reserva `freshSlots` dos `n`, preenchidos com `freshPool` (recência) após
228
+ * os slots principais; backfill cobre fresh insuficiente. Com freshSlots=0 e
229
+ * scoreOf=salience reproduz exatamente o pick v1.2 (off bit-idêntico). */
230
+ function pickDedup(pools, quotas, n, scoreOf, freshPool = [], freshSlots = 0, pinnedIds = new Set()) {
231
+ const picked = [];
232
+ const seenIds = new Set();
233
+ const seenKeys = new Set();
234
+ const seenSigs = [];
235
+ const tryPick = (cand, asFresh = false) => {
236
+ if (seenIds.has(cand.row.id))
237
+ return false;
238
+ const title = titleFromSourceFile(cand.row.source_file);
239
+ const oneLiner = extractOneLiner(cand.row.chunk_text);
240
+ // Dedup exato (v1.1) — cinto de segurança pra assinaturas < MIN_SIG_TOKENS.
241
+ const key = `${title}|${oneLiner}`;
242
+ if (seenKeys.has(key))
243
+ return false;
244
+ const sig = tokenSignature(title, oneLiner);
245
+ for (const s of seenSigs)
246
+ if (isNearDup(s, sig))
247
+ return false;
248
+ seenIds.add(cand.row.id);
249
+ seenKeys.add(key);
250
+ seenSigs.push(sig);
251
+ picked.push({ ...cand, fresh: asFresh || cand.fresh, title, oneLiner });
252
+ return true;
253
+ };
254
+ const mainTarget = Math.max(0, n - freshSlots);
255
+ // Fase 0 (D2 floor — invariante #4): pinned = high-pain que JÁ estavam no
256
+ // brief atual. Entram primeiro e nunca são expulsos pelo freshness slot (que
257
+ // reserva slots e empurraria os últimos por salience pra fora). Sem isto, B
258
+ // podia esconder incident pain≥0.9. Pinned excedente come dos fresh slots.
259
+ if (pinnedIds.size > 0) {
260
+ const pinnedCands = pools
261
+ .flat()
262
+ .filter((c) => pinnedIds.has(c.row.id))
263
+ .sort((a, b) => scoreOf(b) - scoreOf(a));
264
+ for (const c of pinnedCands) {
265
+ if (picked.length >= n)
266
+ break;
267
+ tryPick(c);
268
+ }
269
+ }
270
+ // Fase 1: cotas por pool (ordem de score dentro de cada pool).
271
+ pools.forEach((pool, i) => {
272
+ let got = 0;
273
+ for (const cand of pool) {
274
+ if (got >= quotas[i] || picked.length >= mainTarget)
275
+ break;
276
+ if (tryPick(cand))
277
+ got++;
278
+ }
279
+ });
280
+ // Fase 2: backfill até mainTarget com as sobras de todos os pools (score global).
281
+ if (picked.length < mainTarget) {
282
+ const leftovers = pools.flat().sort((a, b) => scoreOf(b) - scoreOf(a));
283
+ for (const cand of leftovers) {
284
+ if (picked.length >= mainTarget)
285
+ break;
286
+ tryPick(cand);
287
+ }
288
+ }
289
+ // Fase 3 (D2 parte B): freshness slots — novidade recente relevante.
290
+ let freshGot = 0;
291
+ for (const cand of freshPool) {
292
+ if (freshGot >= freshSlots || picked.length >= n)
293
+ break;
294
+ if (tryPick(cand, true))
295
+ freshGot++;
296
+ }
297
+ // Fase 4: backfill restante até n (fresh insuficiente cai pros pools).
298
+ if (picked.length < n) {
299
+ const leftovers = pools.flat().sort((a, b) => scoreOf(b) - scoreOf(a));
300
+ for (const cand of leftovers) {
301
+ if (picked.length >= n)
302
+ break;
303
+ tryPick(cand);
304
+ }
305
+ }
306
+ picked.sort((a, b) => scoreOf(b) - scoreOf(a));
307
+ return picked;
308
+ }
309
+ function toItems(picked, nowMs) {
310
+ return picked.map(({ row, salience, title, oneLiner }) => {
311
+ // v1.1: idade do CONTEÚDO (source_date ?? created_at), não do último toque.
312
+ const ref = row.source_date ?? row.created_at ?? row.updated_at;
313
+ const refMs = ref ? parseDbDateMs(ref) : NaN;
314
+ const ageDays = Number.isFinite(refMs)
315
+ ? Math.max(0, Math.floor((nowMs - refMs) / 86_400_000))
316
+ : 0;
317
+ return {
318
+ id: row.id,
319
+ title,
320
+ one_liner: oneLiner,
321
+ type: row.chunk_type,
322
+ pain: row.pain ?? 0.2,
323
+ salience: Math.round(salience * 10_000) / 10_000,
324
+ age_days: ageDays,
325
+ };
326
+ });
327
+ }
328
+ function assembleResult(params, items, nowMs) {
329
+ const tokenEstimate = Math.ceil(items.reduce((acc, i) => acc + i.title.length + i.one_liner.length + 24, 0) / 4);
330
+ return {
331
+ scope: params.scope,
332
+ ...(params.agent ? { agent: params.agent } : {}),
333
+ generated_at: new Date(nowMs).toISOString(),
334
+ items,
335
+ token_estimate: tokenEstimate,
336
+ };
337
+ }
338
+ /** Monta os pools (união agente ∪ scope/global) + cotas — v1.2b. */
339
+ function buildPools(db, params, nowMs) {
340
+ const scopeOnly = scopePatterns(params.scope);
341
+ const pools = [];
342
+ const quotas = [];
343
+ if (params.agent) {
344
+ pools.push(fetchRankedPool(db, scopePatterns("global", params.agent), params.sinceSql, nowMs));
345
+ quotas.push(Math.ceil(params.n / 2));
346
+ pools.push(fetchRankedPool(db, scopeOnly, params.sinceSql, nowMs));
347
+ quotas.push(Math.floor(params.n / 2));
348
+ }
349
+ else {
350
+ pools.push(fetchRankedPool(db, scopeOnly, params.sinceSql, nowMs));
351
+ quotas.push(params.n);
352
+ }
353
+ return { pools, quotas };
354
+ }
355
+ export function buildBrief(db, params, nowMs = Date.now()) {
356
+ // v1.2b: com `agent`, o brief é UNIÃO GARANTIDA — ~metade dos slots pro
357
+ // pool do agente, ~metade pro scope/global, backfill mútuo se um vier magro.
358
+ const { pools, quotas } = buildPools(db, params, nowMs);
359
+ const picked = pickDedup(pools, quotas, params.n, (c) => c.salience);
360
+ return assembleResult(params, toItems(picked, nowMs), nowMs);
361
+ }
362
+ // ─── D2: serve-history + freshness (queries; lógica pura em brief-diversity) ──
363
+ /** Parte A — nº de serves por chunk na janela T (1 query agregada, índice
364
+ * idx_brief_log_chunk). Read-only sobre brief_log; tabela própria. */
365
+ export function serveCounts(db, ids, windowSql) {
366
+ const counts = new Map();
367
+ if (ids.length === 0)
368
+ return counts;
369
+ try {
370
+ const placeholders = ids.map(() => "?").join(",");
371
+ const rows = db
372
+ .prepare(`SELECT chunk_id, COUNT(*) AS n
373
+ FROM brief_log
374
+ WHERE chunk_id IN (${placeholders})
375
+ AND served_at > datetime('now', ?)
376
+ GROUP BY chunk_id`)
377
+ .all(...ids, windowSql);
378
+ for (const r of rows)
379
+ counts.set(r.chunk_id, r.n);
380
+ }
381
+ catch {
382
+ // fail-open (invariante #3): sem serve-history ⇒ penalty 0 pra todos.
383
+ }
384
+ return counts;
385
+ }
386
+ /** Parte B — candidatos de freshness: recentes, relevantes e NÃO servidos na
387
+ * janela. Query própria (o pool de 500 prioriza importance+access, barra
388
+ * recentes com access=0). Ordenado por recência do conteúdo. */
389
+ function fetchFreshCandidates(db, patterns, cfg, nowMs) {
390
+ const where = [];
391
+ const args = [];
392
+ if (patterns.length > 0) {
393
+ where.push(`(${patterns.map(() => "source_file LIKE ? ESCAPE '\\'").join(" OR ")})`);
394
+ args.push(...patterns);
395
+ }
396
+ where.push("(COALESCE(importance, 0) >= ? OR COALESCE(pain, 0) >= ?)");
397
+ args.push(cfg.freshMinImp, cfg.freshMinPain);
398
+ where.push("julianday('now') - julianday(COALESCE(source_date, created_at)) <= ?");
399
+ args.push(cfg.freshMaxAgeDays);
400
+ where.push("id NOT IN (SELECT chunk_id FROM brief_log WHERE served_at > datetime('now', ?))");
401
+ args.push(cfg.windowSql);
402
+ try {
403
+ const rows = db
404
+ .prepare(`SELECT id, source_file, chunk_text, chunk_type, source_type, tier,
405
+ pain, importance, retention_days, source_date, created_at,
406
+ updated_at, last_accessed_at, access_count
407
+ FROM chunks
408
+ WHERE ${where.join(" AND ")}
409
+ ORDER BY COALESCE(source_date, created_at) DESC
410
+ LIMIT ${Math.max(1, cfg.freshSlots * 4)}`)
411
+ .all(...args);
412
+ return rows.map((r) => {
413
+ const s = calculateSalience(r, nowMs);
414
+ return { row: r, salience: s, briefScore: s, fresh: true };
415
+ });
416
+ }
417
+ catch {
418
+ return []; // fail-open
419
+ }
420
+ }
421
+ /** D2 — buildBrief com diversidade (A novelty penalty + B freshness slot).
422
+ * Retorna o surface do `mode` + o brief atual + o diff (pra shadow log). */
423
+ export function buildBriefDiverse(db, params, cfg, nowMs = Date.now()) {
424
+ // Garante brief_log antes de lê-lo (1ª chamada em DB fresco vem antes do
425
+ // insert de handleBrief; em prod já existe). Idempotente (memo interno).
426
+ ensureBriefLog(db);
427
+ const { pools, quotas } = buildPools(db, params, nowMs);
428
+ // Brief atual (baseline, score = salience) — o que está em prod hoje.
429
+ const currentPicked = pickDedup(pools, quotas, params.n, (c) => c.salience);
430
+ const current = assembleResult(params, toItems(currentPicked, nowMs), nowMs);
431
+ // Parte A: novelty penalty sobre os candidatos dos pools.
432
+ const allIds = [...new Set(pools.flat().map((c) => c.row.id))];
433
+ const counts = serveCounts(db, allIds, cfg.windowSql);
434
+ for (const c of pools.flat()) {
435
+ c.briefScore = briefScore(c.salience, counts.get(c.row.id) ?? 0, c.row.pain ?? 0.2, cfg);
436
+ }
437
+ // Parte B: pool de freshness (recência relevante não-servida).
438
+ const freshPatterns = params.agent
439
+ ? scopePatterns(params.scope, params.agent)
440
+ : scopePatterns(params.scope);
441
+ const freshPool = cfg.freshSlots > 0
442
+ ? fetchFreshCandidates(db, freshPatterns, cfg, nowMs)
443
+ : [];
444
+ // Floor (invariante #4): high-pain que já estavam no brief atual viram
445
+ // pinned — nunca expulsos pelo freshness slot. Sem isto, B escondia incidents
446
+ // pain≥0.9 (detectado pelo gate report no 1º shadow: would_leave pain=1.0).
447
+ const pinnedIds = new Set(current.items.filter((i) => (i.pain ?? 0) >= cfg.painFloor).map((i) => i.id));
448
+ const altPicked = pickDedup(pools, quotas, params.n, effScore, freshPool, cfg.freshSlots, pinnedIds);
449
+ const alt = assembleResult(params, toItems(altPicked, nowMs), nowMs);
450
+ const freshIds = altPicked.filter((p) => p.fresh).map((p) => p.row.id);
451
+ const diff = diffBriefs(current.items.map((i) => i.id), alt.items.map((i) => i.id), freshIds);
452
+ return { current, alt, diff };
453
+ }
454
+ // ─── Render text (stdout-ready pra hooks SessionStart) ──────────────────────
455
+ export function renderBriefText(result) {
456
+ const head = `# nox-mem brief — scope=${result.scope}${result.agent ? ` agent=${result.agent}` : ""} — ${result.generated_at} — ${result.items.length} items`;
457
+ const lines = [head];
458
+ let budget = TOKEN_BUDGET - Math.ceil(head.length / 4);
459
+ for (const item of result.items) {
460
+ const line = `[${item.type ?? "?"}|pain ${item.pain.toFixed(1)}|${item.age_days}d] ${item.title} — ${item.one_liner} (chk ${item.id})`;
461
+ const cost = Math.ceil(line.length / 4);
462
+ if (cost > budget)
463
+ break;
464
+ lines.push(line);
465
+ budget -= cost;
466
+ }
467
+ return lines.join("\n") + "\n";
468
+ }
469
+ // ─── Handler HTTP-agnostic (api-server.ts despacha) ──────────────────────────
470
+ export function handleBrief(db, query) {
471
+ const parsed = parseBriefParams(query);
472
+ if (!parsed.ok)
473
+ return { status: 400, body: { error: parsed.error } };
474
+ // D2 — diversidade (NOX_BRIEF_DIVERSITY=off|shadow|active). off ⇒ caminho
475
+ // v1.2 intocado. shadow ⇒ computa o alt, loga o diff, serve o atual. active
476
+ // ⇒ serve o alt. Fail-open: qualquer erro cai no brief atual (invariante #3).
477
+ const cfg = diversityConfigFromEnv();
478
+ let result;
479
+ if (cfg.mode === "off") {
480
+ result = buildBrief(db, parsed.params);
481
+ }
482
+ else {
483
+ try {
484
+ const { current, alt, diff } = buildBriefDiverse(db, parsed.params, cfg);
485
+ if (cfg.mode === "shadow") {
486
+ if (diff.churn > 0) {
487
+ // stderr → journalctl. Gate D2 mede sobre estes ids × tabela chunks.
488
+ console.error(JSON.stringify({
489
+ tag: "brief_diversity_shadow",
490
+ scope: parsed.params.scope,
491
+ agent: parsed.params.agent ?? null,
492
+ n: parsed.params.n,
493
+ churn: diff.churn,
494
+ would_enter: diff.would_enter,
495
+ would_leave: diff.would_leave,
496
+ fresh_added: diff.fresh_added,
497
+ }));
498
+ }
499
+ result = current;
500
+ }
501
+ else {
502
+ result = alt;
503
+ }
504
+ }
505
+ catch {
506
+ result = buildBrief(db, parsed.params); // fail-open
507
+ }
508
+ }
509
+ // Tracking de serving — brief_log próprio; chunks.access_count INTOCADO.
510
+ try {
511
+ ensureBriefLog(db);
512
+ const ins = db.prepare("INSERT INTO brief_log (chunk_id, scope, agent) VALUES (?, ?, ?)");
513
+ for (const item of result.items) {
514
+ ins.run(item.id, parsed.params.scope, parsed.params.agent ?? null);
515
+ }
516
+ }
517
+ catch {
518
+ // fail-open: tracking nunca derruba o priming
519
+ }
520
+ if (parsed.params.format === "text") {
521
+ return { status: 200, text: renderBriefText(result) };
522
+ }
523
+ return { status: 200, body: result };
524
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * L2 T8 — HTTP API handlers.
3
+ *
4
+ * Endpoints (mounted on nox-mem-api at :18802):
5
+ * GET /api/conflict?status=open&limit=20 → list audit rows
6
+ * GET /api/conflict/:id → row + evidence
7
+ * POST /api/conflict/:id/resolve → write resolution
8
+ *
9
+ * Implementation is framework-agnostic: pure handlers operating on
10
+ * a `RequestInput` shape so they can be wired to Express, native http,
11
+ * or tested directly. No external HTTP library imported.
12
+ *
13
+ * All responses are JSON. Errors return {error: ...} with HTTP status.
14
+ */
15
+ import type { DBHandle } from "../lib/conflict/db.js";
16
+ export interface RequestInput {
17
+ method: "GET" | "POST";
18
+ path: string;
19
+ query?: Record<string, string | undefined>;
20
+ body?: unknown;
21
+ /** Caller actor id — populated from session/auth middleware in production. */
22
+ actor?: string;
23
+ }
24
+ export interface ApiResponse {
25
+ status: number;
26
+ body: unknown;
27
+ }
28
+ /**
29
+ * Dispatch incoming request to the appropriate handler. Returns 404 when
30
+ * the path does not match any conflict endpoint (caller can fall through
31
+ * to other routes).
32
+ */
33
+ export declare function dispatchConflictApi(db: DBHandle, req: RequestInput): ApiResponse;