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,29 @@
1
+ export interface ChangedFile {
2
+ path: string;
3
+ status: string;
4
+ is_entity_file: boolean;
5
+ entity_type?: string;
6
+ entity_slug?: string;
7
+ }
8
+ export interface AffectedEntity {
9
+ name: string;
10
+ type: string;
11
+ mention_count: number;
12
+ source_files: string[];
13
+ via: 'entity_file' | 'chunk_reference';
14
+ }
15
+ export interface DetectChangesResult {
16
+ since: string;
17
+ head: string;
18
+ repo: string;
19
+ files_changed: number;
20
+ files: ChangedFile[];
21
+ affected_entities: AffectedEntity[];
22
+ scanned_chunks: number;
23
+ duration_ms: number;
24
+ }
25
+ export declare function detectChanges(opts: {
26
+ since: string;
27
+ repo: string;
28
+ }): DetectChangesResult;
29
+ export declare function formatDetectChanges(r: DetectChangesResult, mode?: 'json' | 'text'): string;
@@ -0,0 +1,236 @@
1
+ // E06 (2026-05-03): detect-changes — git diff --name-only <since> HEAD + identifica entidades KG afetadas.
2
+ // Read-only: zero mutation. Útil pra pré-commit hooks detectando entities que mudaram.
3
+ import { execFileSync } from "node:child_process";
4
+ import path from "node:path";
5
+ import fs from "node:fs";
6
+ import { getDb } from "./db.js";
7
+ // SEC-FIX 2026-05-03: repo allowlist (mesma idea do api-impact)
8
+ // NOX_DETECT_CHANGES_REPO_ALLOWLIST: comma-separated absolute paths that are
9
+ // permitted as `repo` arguments. Defaults to the canonical workspace root.
10
+ // Override to add additional trusted repos (e.g. /home/user/my-repo).
11
+ const REPO_ALLOWLIST = (process.env.NOX_DETECT_CHANGES_REPO_ALLOWLIST ?? "/root/.openclaw/workspace")
12
+ .split(",").map((s) => s.trim()).filter(Boolean);
13
+ function validateRepo(repo) {
14
+ const real = fs.realpathSync(repo);
15
+ const ok = REPO_ALLOWLIST.some((prefix) => {
16
+ try {
17
+ const realPrefix = fs.realpathSync(prefix);
18
+ return real === realPrefix || real.startsWith(realPrefix + path.sep);
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ });
24
+ if (!ok)
25
+ throw new Error(`Repo not in allowlist: ${real}. Set NOX_DETECT_CHANGES_REPO_ALLOWLIST or use a path under: ${REPO_ALLOWLIST.join(", ")}`);
26
+ return real;
27
+ }
28
+ // SEC-FIX HIGH #4: validate that resolved abs path is contained within repo (defends against ../../../etc/passwd in git history)
29
+ function safePathJoin(repo, relPath) {
30
+ const abs = path.resolve(repo, relPath);
31
+ const realRepo = fs.realpathSync(repo);
32
+ // Note: realpathSync would fail if abs doesn't exist (deleted file in diff). Use logical containment check.
33
+ const normalized = path.resolve(abs);
34
+ if (!normalized.startsWith(realRepo + path.sep) && normalized !== realRepo)
35
+ return null;
36
+ return normalized;
37
+ }
38
+ // SEC-FIX CRITICAL #2: execFileSync with array args (no shell expansion)
39
+ function gitCmd(repo, args) {
40
+ try {
41
+ return execFileSync("git", ["-C", repo, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 30_000 }).trim();
42
+ }
43
+ catch (e) {
44
+ throw new Error(`git ${args.join(" ")} failed in ${repo}: ${e.message?.split("\n")[0] || e}`);
45
+ }
46
+ }
47
+ function parseDiffNameStatus(out) {
48
+ if (!out)
49
+ return [];
50
+ return out.split("\n").map((line) => {
51
+ const parts = line.split("\t");
52
+ return { status: parts[0]?.[0] || "?", path: parts[parts.length - 1] || "" };
53
+ }).filter((f) => f.path);
54
+ }
55
+ const ENTITY_PATH_RE = /^memory\/entities\/([^/]+)\/([^/]+)\.md$/;
56
+ function detectEntityFile(filePath) {
57
+ const m = filePath.match(ENTITY_PATH_RE);
58
+ if (!m)
59
+ return null;
60
+ return { type: m[1], slug: m[2] };
61
+ }
62
+ function readFrontmatterName(absPath) {
63
+ try {
64
+ if (!fs.existsSync(absPath))
65
+ return null;
66
+ const head = fs.readFileSync(absPath, "utf8").substring(0, 2000);
67
+ const fm = head.match(/^---\s*\n([\s\S]*?)\n---/);
68
+ if (!fm)
69
+ return null;
70
+ const nameMatch = fm[1].match(/^name:\s*(.+)$/m);
71
+ return nameMatch ? nameMatch[1].trim() : null;
72
+ }
73
+ catch {
74
+ return null;
75
+ }
76
+ }
77
+ export function detectChanges(opts) {
78
+ const start = Date.now();
79
+ // SEC-FIX HIGH #4: confine repo path via realpath + allowlist
80
+ if (!fs.existsSync(opts.repo))
81
+ throw new Error(`Repo path does not exist: ${opts.repo}`);
82
+ const repo = validateRepo(opts.repo);
83
+ if (!fs.existsSync(path.join(repo, ".git"))) {
84
+ throw new Error(`Not a git repo: ${repo}`);
85
+ }
86
+ // SEC-FIX HIGH (since arg validation): defensive — allowed git ref chars only (alphanumeric + . / - _ ~ ^ : @ {})
87
+ if (!/^[a-zA-Z0-9._/~^:@{}-]+$/.test(opts.since)) {
88
+ throw new Error(`Invalid 'since' ref (allowed: alphanumeric + . / - _ ~ ^ : @ { }): ${opts.since}`);
89
+ }
90
+ const head = gitCmd(repo, ["rev-parse", "HEAD"]);
91
+ const sinceResolved = gitCmd(repo, ["rev-parse", opts.since]);
92
+ const diffOut = gitCmd(repo, ["diff", "--name-status", `${sinceResolved}...HEAD`]);
93
+ const rawFiles = parseDiffNameStatus(diffOut);
94
+ const files = rawFiles.map((f) => {
95
+ const ent = detectEntityFile(f.path);
96
+ return {
97
+ path: f.path,
98
+ status: f.status,
99
+ is_entity_file: !!ent,
100
+ entity_type: ent?.type,
101
+ entity_slug: ent?.slug,
102
+ };
103
+ });
104
+ const db = getDb();
105
+ const entityMap = new Map();
106
+ // Path 1: entity files diretos — resolve slug → name via frontmatter ou kg_entities lookup
107
+ for (const f of files) {
108
+ if (!f.is_entity_file || !f.entity_type || !f.entity_slug)
109
+ continue;
110
+ // SEC-FIX HIGH #4: bloqueia ../../../etc/passwd via path containment check
111
+ const absPath = safePathJoin(repo, f.path);
112
+ if (!absPath)
113
+ continue; // path escapes repo, skip
114
+ const fmName = readFrontmatterName(absPath);
115
+ const candidates = fmName ? [fmName] : [];
116
+ candidates.push(f.entity_slug.replace(/^\d{4}-\d{2}-\d{2}-/, "").replace(/-/g, " "));
117
+ let resolved;
118
+ for (const cand of candidates) {
119
+ const row = db.prepare("SELECT name, entity_type, mention_count FROM kg_entities WHERE LOWER(name) = LOWER(?) LIMIT 1").get(cand);
120
+ if (row) {
121
+ resolved = row;
122
+ break;
123
+ }
124
+ }
125
+ const key = resolved?.name || candidates[0];
126
+ if (!entityMap.has(key)) {
127
+ entityMap.set(key, {
128
+ name: key,
129
+ type: resolved?.entity_type || f.entity_type,
130
+ mention_count: resolved?.mention_count || 0,
131
+ source_files: [],
132
+ via: 'entity_file',
133
+ });
134
+ }
135
+ const e = entityMap.get(key);
136
+ if (!e.source_files.includes(f.path))
137
+ e.source_files.push(f.path);
138
+ }
139
+ // Path 2: chunks que vieram desses files → entidades mencionadas via evidence_chunk_id
140
+ // CODE-FIX HIGH: SQLite SQLITE_MAX_VARIABLE_NUMBER=999 default → batch em chunks de 500
141
+ let scannedChunks = 0;
142
+ const filePaths = files.map((f) => f.path);
143
+ const BATCH = 500;
144
+ function chunked(arr, n) {
145
+ const out = [];
146
+ for (let i = 0; i < arr.length; i += n)
147
+ out.push(arr.slice(i, i + n));
148
+ return out;
149
+ }
150
+ if (filePaths.length > 0) {
151
+ const allChunkIds = [];
152
+ for (const batch of chunked(filePaths, BATCH)) {
153
+ const placeholders = batch.map(() => "?").join(",");
154
+ const rows = db.prepare(`SELECT id FROM chunks WHERE source_file IN (${placeholders})`).all(...batch);
155
+ for (const r of rows)
156
+ allChunkIds.push(r.id);
157
+ }
158
+ scannedChunks = allChunkIds.length;
159
+ if (allChunkIds.length > 0) {
160
+ for (const batch of chunked(allChunkIds, BATCH)) {
161
+ const chPlace = batch.map(() => "?").join(",");
162
+ const refs = db.prepare(`SELECT DISTINCT e.name, e.entity_type, e.mention_count, c.source_file
163
+ FROM kg_entities e
164
+ JOIN kg_relations r ON r.source_entity_id = e.id OR r.target_entity_id = e.id
165
+ JOIN chunks c ON c.id = r.evidence_chunk_id
166
+ WHERE r.evidence_chunk_id IN (${chPlace})`).all(...batch);
167
+ for (const r of refs) {
168
+ if (!entityMap.has(r.name)) {
169
+ entityMap.set(r.name, {
170
+ name: r.name,
171
+ type: r.entity_type,
172
+ mention_count: r.mention_count,
173
+ source_files: [],
174
+ via: 'chunk_reference',
175
+ });
176
+ }
177
+ const e = entityMap.get(r.name);
178
+ if (!e.source_files.includes(r.source_file))
179
+ e.source_files.push(r.source_file);
180
+ }
181
+ }
182
+ }
183
+ }
184
+ const affected = Array.from(entityMap.values()).sort((a, b) => b.mention_count - a.mention_count);
185
+ return {
186
+ since: sinceResolved.substring(0, 8),
187
+ head: head.substring(0, 8),
188
+ repo,
189
+ files_changed: files.length,
190
+ files,
191
+ affected_entities: affected,
192
+ scanned_chunks: scannedChunks,
193
+ duration_ms: Date.now() - start,
194
+ };
195
+ }
196
+ export function formatDetectChanges(r, mode = 'text') {
197
+ if (mode === 'json')
198
+ return JSON.stringify(r, null, 2);
199
+ const lines = [];
200
+ lines.push(`## detect-changes (${r.since}...${r.head})`);
201
+ lines.push(`Repo: ${r.repo}`);
202
+ lines.push(`Files changed: ${r.files_changed} | Chunks scanned: ${r.scanned_chunks} | Duration: ${r.duration_ms}ms`);
203
+ lines.push(``);
204
+ if (r.files_changed === 0) {
205
+ lines.push(`(no changes)`);
206
+ return lines.join("\n");
207
+ }
208
+ const entityFiles = r.files.filter((f) => f.is_entity_file);
209
+ if (entityFiles.length > 0) {
210
+ lines.push(`### Entity files (${entityFiles.length})`);
211
+ for (const f of entityFiles)
212
+ lines.push(` ${f.status} ${f.path} → ${f.entity_type}/${f.entity_slug}`);
213
+ lines.push(``);
214
+ }
215
+ const otherFiles = r.files.filter((f) => !f.is_entity_file);
216
+ if (otherFiles.length > 0) {
217
+ lines.push(`### Other files (${otherFiles.length})`);
218
+ for (const f of otherFiles.slice(0, 20))
219
+ lines.push(` ${f.status} ${f.path}`);
220
+ if (otherFiles.length > 20)
221
+ lines.push(` ... +${otherFiles.length - 20} more`);
222
+ lines.push(``);
223
+ }
224
+ if (r.affected_entities.length > 0) {
225
+ lines.push(`### Affected entities (${r.affected_entities.length})`);
226
+ for (const e of r.affected_entities.slice(0, 20)) {
227
+ lines.push(` [${e.type}] ${e.name} (${e.mention_count} mentions, via=${e.via}, src=${e.source_files.length})`);
228
+ }
229
+ if (r.affected_entities.length > 20)
230
+ lines.push(` ... +${r.affected_entities.length - 20} more`);
231
+ }
232
+ else {
233
+ lines.push(`### Affected entities: 0 (changes don't touch indexed entities)`);
234
+ }
235
+ return lines.join("\n");
236
+ }
@@ -0,0 +1 @@
1
+ export declare function digest(): Promise<void>;
package/dist/digest.js ADDED
@@ -0,0 +1,205 @@
1
+ import { readFileSync, writeFileSync, mkdirSync } from "fs";
2
+ import { resolve, dirname } from "path";
3
+ import { fileURLToPath } from "url";
4
+ import { execFileSync } from "child_process";
5
+ import { getDb } from "./db.js";
6
+ const __dirname = dirname(fileURLToPath(import.meta.url));
7
+ const WORKSPACE = process.env.OPENCLAW_WORKSPACE || "/root/.openclaw/workspace";
8
+ // Primary: Gemini 2.5 Flash (large context, free tier, handles 50k+ tokens)
9
+ const GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent";
10
+ // Secondary: Groq (fast, but 12k TPM limit — fails on large digests)
11
+ const GROQ_URL = "https://api.groq.com/openai/v1/chat/completions";
12
+ const GROQ_MODEL = "llama-3.3-70b-versatile";
13
+ // Fallback: Ollama local (llama3.2:3b — limited ctx 4096 tokens, may fail with large prompts)
14
+ const OLLAMA_URL = "http://127.0.0.1:11434/api/generate";
15
+ const OLLAMA_MODEL = "llama3.2:3b";
16
+ const PROMPT_PATH = resolve(__dirname, "..", "prompts", "digest.txt");
17
+ function getISOWeek(date) {
18
+ const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
19
+ const dayNum = d.getUTCDay() || 7;
20
+ d.setUTCDate(d.getUTCDate() + 4 - dayNum);
21
+ const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
22
+ const weekNo = Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
23
+ return `${d.getUTCFullYear()}-W${String(weekNo).padStart(2, "0")}`;
24
+ }
25
+ /**
26
+ * Primary: Call Gemini 2.5 Flash via REST API. Large context, handles 50k+ tokens.
27
+ */
28
+ async function callGemini(prompt, retries = 2) {
29
+ const apiKey = process.env.GEMINI_API_KEY;
30
+ if (!apiKey) {
31
+ console.error("[WARN] GEMINI_API_KEY not set — skipping Gemini");
32
+ return null;
33
+ }
34
+ for (let attempt = 1; attempt <= retries; attempt++) {
35
+ try {
36
+ console.error(`[INFO] Calling Gemini (attempt ${attempt}/${retries})...`);
37
+ const response = await fetch(`${GEMINI_URL}?key=${apiKey}`, {
38
+ method: "POST",
39
+ headers: { "Content-Type": "application/json" },
40
+ body: JSON.stringify({
41
+ contents: [{ parts: [{ text: prompt }] }],
42
+ generationConfig: { temperature: 0.3, maxOutputTokens: 2048 },
43
+ }),
44
+ signal: AbortSignal.timeout(120_000),
45
+ });
46
+ if (!response.ok) {
47
+ const body = await response.text();
48
+ console.error(`[WARN] Gemini HTTP ${response.status} (attempt ${attempt}/${retries}): ${body.slice(0, 200)}`);
49
+ if (response.status === 401 || response.status === 403)
50
+ return null;
51
+ continue;
52
+ }
53
+ const data = (await response.json());
54
+ const text = data.candidates?.[0]?.content?.parts?.[0]?.text?.trim();
55
+ if (text && text.length > 10) {
56
+ console.error(`[INFO] Gemini response: ${text.length} chars`);
57
+ return text;
58
+ }
59
+ console.error(`[WARN] Empty Gemini response (attempt ${attempt}/${retries})`);
60
+ }
61
+ catch (err) {
62
+ const msg = err instanceof Error ? err.message : String(err);
63
+ console.error(`[WARN] Gemini error (attempt ${attempt}/${retries}): ${msg}`);
64
+ }
65
+ }
66
+ return null;
67
+ }
68
+ /**
69
+ * Call Groq API (OpenAI-compatible). Returns null if unavailable.
70
+ */
71
+ async function callGroq(prompt, retries = 2) {
72
+ const apiKey = process.env.GROQ_API_KEY;
73
+ if (!apiKey) {
74
+ console.error("[WARN] GROQ_API_KEY not set — skipping Groq");
75
+ return null;
76
+ }
77
+ for (let attempt = 1; attempt <= retries; attempt++) {
78
+ try {
79
+ console.error(`[INFO] Calling Groq (attempt ${attempt}/${retries})...`);
80
+ const response = await fetch(GROQ_URL, {
81
+ method: "POST",
82
+ headers: {
83
+ "Content-Type": "application/json",
84
+ "Authorization": `Bearer ${apiKey}`,
85
+ },
86
+ body: JSON.stringify({
87
+ model: GROQ_MODEL,
88
+ messages: [{ role: "user", content: prompt }],
89
+ temperature: 0.3,
90
+ max_tokens: 1024,
91
+ }),
92
+ signal: AbortSignal.timeout(60_000),
93
+ });
94
+ if (!response.ok) {
95
+ const body = await response.text();
96
+ console.error(`[WARN] Groq HTTP ${response.status} (attempt ${attempt}/${retries}): ${body.slice(0, 200)}`);
97
+ if (response.status === 401 || response.status === 403)
98
+ return null; // auth error, no retry
99
+ continue;
100
+ }
101
+ const data = (await response.json());
102
+ const text = data.choices?.[0]?.message?.content?.trim();
103
+ if (text && text.length > 10) {
104
+ console.error(`[INFO] Groq response: ${text.length} chars`);
105
+ return text;
106
+ }
107
+ console.error(`[WARN] Empty Groq response (attempt ${attempt}/${retries})`);
108
+ }
109
+ catch (err) {
110
+ const msg = err instanceof Error ? err.message : String(err);
111
+ console.error(`[WARN] Groq error (attempt ${attempt}/${retries}): ${msg}`);
112
+ }
113
+ }
114
+ return null;
115
+ }
116
+ /**
117
+ * Fallback: Call Ollama local. Note: llama3.2:3b has n_ctx=4096 tokens.
118
+ * With large prompts (>3k tokens) Ollama returns HTTP 500 — skip gracefully.
119
+ */
120
+ async function callOllama(prompt, retries = 2) {
121
+ // Rough token estimate: ~4 chars/token. Skip if prompt likely exceeds context.
122
+ const estimatedTokens = Math.ceil(prompt.length / 4);
123
+ if (estimatedTokens > 3000) {
124
+ console.error(`[WARN] Ollama skipped — prompt ~${estimatedTokens} tokens exceeds llama3.2:3b ctx limit (4096)`);
125
+ return null;
126
+ }
127
+ for (let attempt = 1; attempt <= retries; attempt++) {
128
+ try {
129
+ console.error(`[INFO] Calling Ollama fallback (attempt ${attempt}/${retries})...`);
130
+ const response = await fetch(OLLAMA_URL, {
131
+ method: "POST",
132
+ headers: { "Content-Type": "application/json" },
133
+ body: JSON.stringify({ model: OLLAMA_MODEL, prompt, stream: false, options: { temperature: 0.3 } }),
134
+ signal: AbortSignal.timeout(90_000),
135
+ });
136
+ if (!response.ok) {
137
+ console.error(`[WARN] Ollama HTTP ${response.status} (attempt ${attempt}/${retries})`);
138
+ continue;
139
+ }
140
+ const data = (await response.json());
141
+ if (data.response && data.response.trim().length > 10)
142
+ return data.response;
143
+ console.error(`[WARN] Empty Ollama response (attempt ${attempt}/${retries})`);
144
+ }
145
+ catch (err) {
146
+ const msg = err instanceof Error ? err.message : String(err);
147
+ if (msg.includes("ECONNREFUSED")) {
148
+ console.error("[WARN] Ollama offline");
149
+ return null;
150
+ }
151
+ console.error(`[WARN] Ollama error (attempt ${attempt}/${retries}): ${msg}`);
152
+ }
153
+ }
154
+ return null;
155
+ }
156
+ export async function digest() {
157
+ console.log("[INFO] nox-mem digest starting...");
158
+ const db = getDb();
159
+ let promptTemplate;
160
+ try {
161
+ promptTemplate = readFileSync(PROMPT_PATH, "utf-8");
162
+ }
163
+ catch (err) {
164
+ console.error(`[ERROR] Could not read prompt template: ${PROMPT_PATH}`);
165
+ return;
166
+ }
167
+ const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split("T")[0];
168
+ console.log(`[INFO] Querying chunks since ${sevenDaysAgo}...`);
169
+ const chunks = db.prepare("SELECT chunk_text, source_file, chunk_type FROM chunks WHERE source_date >= ? AND chunk_type IN ('decision','lesson','person','project','pending','daily') ORDER BY source_date ASC").all(sevenDaysAgo);
170
+ if (chunks.length === 0) {
171
+ console.log("[INFO] No data from last 7 days for digest");
172
+ return;
173
+ }
174
+ console.log(`[INFO] Found ${chunks.length} chunks`);
175
+ const fullText = chunks.map((c) => `[${c.chunk_type}] ${c.chunk_text}`).join("\n\n");
176
+ const prompt = promptTemplate + fullText;
177
+ console.log(`[INFO] Total prompt: ${prompt.length} chars (~${Math.ceil(prompt.length / 4)} tokens)`);
178
+ // Try Gemini first (primary — large context), then Groq, then Ollama
179
+ let result = await callGemini(prompt);
180
+ if (!result) {
181
+ console.error("[WARN] Gemini failed, trying Groq fallback...");
182
+ result = await callGroq(prompt);
183
+ }
184
+ if (!result) {
185
+ console.error("[WARN] Groq failed, trying Ollama fallback...");
186
+ result = await callOllama(prompt);
187
+ }
188
+ if (!result) {
189
+ console.error("[ERROR] Digest failed — Gemini, Groq and Ollama all unavailable");
190
+ return;
191
+ }
192
+ const weekId = getISOWeek(new Date());
193
+ const digestDir = resolve(WORKSPACE, "memory", "digests");
194
+ mkdirSync(digestDir, { recursive: true });
195
+ const digestPath = resolve(digestDir, `${weekId}.md`);
196
+ const content = `# Weekly Digest — ${weekId}\n\n*Gerado automaticamente em ${new Date().toISOString()}*\n\n${result}`;
197
+ writeFileSync(digestPath, content, "utf-8");
198
+ console.log(`[INFO] Digest saved to ${digestPath}`);
199
+ try {
200
+ execFileSync("git", ["-C", WORKSPACE, "add", `memory/digests/${weekId}.md`], { stdio: "pipe" });
201
+ execFileSync("git", ["-C", WORKSPACE, "commit", "-m", `chore(memory): weekly digest ${weekId}`], { stdio: "pipe" });
202
+ console.log(`[INFO] Git commit: weekly digest ${weekId}`);
203
+ }
204
+ catch { }
205
+ }
@@ -0,0 +1 @@
1
+ export declare function doctor(): Promise<void>;
package/dist/doctor.js ADDED
@@ -0,0 +1,71 @@
1
+ import { getDb, DB_PATH } from "./db.js";
2
+ import { statSync, existsSync } from "fs";
3
+ export async function doctor() {
4
+ const checks = [];
5
+ // 1. SQLite database
6
+ try {
7
+ const db = getDb();
8
+ const version = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
9
+ checks.push({ name: "SQLite DB", status: "✅", detail: `schema v${version?.value || "?"}, ${formatSize(DB_PATH)}` });
10
+ // 2. FTS5 index
11
+ const ftsCount = db.prepare("SELECT COUNT(*) as c FROM chunks_fts").get().c;
12
+ const chunkCount = db.prepare("SELECT COUNT(*) as c FROM chunks").get().c;
13
+ const ftsOk = ftsCount === chunkCount;
14
+ checks.push({ name: "FTS5 Index", status: ftsOk ? "✅" : "⚠️", detail: `${ftsCount} indexed / ${chunkCount} chunks${ftsOk ? "" : " — MISMATCH, run nox-mem reindex"}` });
15
+ // 3. Consolidated files
16
+ const consolidated = db.prepare("SELECT COUNT(*) as c FROM consolidated_files WHERE status = 1").get().c;
17
+ const failed = db.prepare("SELECT COUNT(*) as c FROM consolidated_files WHERE status = -1").get().c;
18
+ const pending = db.prepare("SELECT COUNT(DISTINCT source_file) as c FROM chunks WHERE chunk_type = 'daily' AND source_file NOT IN (SELECT source_file FROM consolidated_files)").get().c;
19
+ checks.push({ name: "Consolidation", status: failed > 0 ? "⚠️" : "✅", detail: `${consolidated} done, ${pending} pending, ${failed} failed` });
20
+ // 4. Last consolidation
21
+ const lastCon = db.prepare("SELECT value FROM meta WHERE key = 'last_consolidation'").get();
22
+ checks.push({ name: "Last consolidation", status: "ℹ️", detail: lastCon?.value ?? "never" });
23
+ }
24
+ catch (err) {
25
+ checks.push({ name: "SQLite DB", status: "❌", detail: `${err}` });
26
+ }
27
+ // 5. Ollama
28
+ try {
29
+ const response = await fetch("http://127.0.0.1:11434/api/tags", { signal: AbortSignal.timeout(5000) });
30
+ if (response.ok) {
31
+ const data = (await response.json());
32
+ const models = data.models.map((m) => m.name).join(", ");
33
+ checks.push({ name: "Ollama", status: "✅", detail: `running, models: ${models}` });
34
+ }
35
+ else {
36
+ checks.push({ name: "Ollama", status: "⚠️", detail: `HTTP ${response.status}` });
37
+ }
38
+ }
39
+ catch {
40
+ checks.push({ name: "Ollama", status: "❌", detail: "offline (ECONNREFUSED)" });
41
+ }
42
+ // 6. Notion token
43
+ const notionTokenPath = process.env.NOX_NOTION_TOKEN_PATH ?? "/root/.config/notion/api_key";
44
+ const notionTokenExists = existsSync(notionTokenPath);
45
+ checks.push({ name: "Notion token", status: notionTokenExists ? "✅" : "⚠️", detail: notionTokenExists ? `found at ${notionTokenPath}` : `missing (set NOX_NOTION_TOKEN_PATH or place key at ${notionTokenPath})` });
46
+ // 7. File watcher
47
+ try {
48
+ const { execFileSync } = await import("child_process");
49
+ const service = "nox-mem-watch.service";
50
+ const result = execFileSync("systemctl", ["is-active", service], { encoding: "utf-8" }).trim();
51
+ checks.push({ name: "File watcher", status: result === "active" ? "✅" : "⚠️", detail: result });
52
+ }
53
+ catch {
54
+ checks.push({ name: "File watcher", status: "❌", detail: "service not found or inactive" });
55
+ }
56
+ // Print report
57
+ console.log("\n🩺 nox-mem doctor\n");
58
+ for (const check of checks) {
59
+ console.log(` ${check.status} ${check.name}: ${check.detail}`);
60
+ }
61
+ console.log("");
62
+ }
63
+ function formatSize(path) {
64
+ try {
65
+ const bytes = statSync(path).size;
66
+ return bytes > 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : `${(bytes / 1024).toFixed(1)} KB`;
67
+ }
68
+ catch {
69
+ return "unknown";
70
+ }
71
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * embed.ts - Semantic embedding via Gemini API (gemini-embedding-001, 768-dim)
3
+ * Uses the same API key already configured in the OpenClaw gateway.
4
+ * Zero local model weight, zero sqlite-vec binding issues.
5
+ */
6
+ import Database from "better-sqlite3";
7
+ declare const EMBEDDING_DIM = 3072;
8
+ export declare function embedText(text: string): Promise<Float32Array>;
9
+ /**
10
+ * True batch embedding via Gemini batchEmbedContents API.
11
+ * Sends up to `batchSize` texts per HTTP call (default 50) — on gemini-embedding-001
12
+ * at 3072d we've measured ~13x throughput vs the per-text loop.
13
+ * Pauses `pauseMs` between batches to stay under 100 RPM on the free tier.
14
+ */
15
+ export declare function embedBatchAPI(texts: string[], options?: {
16
+ batchSize?: number;
17
+ pauseMs?: number;
18
+ onProgress?: (done: number, total: number) => void;
19
+ }): Promise<Float32Array[]>;
20
+ /**
21
+ * Legacy serial embedBatch kept for callers that still use it; now delegates
22
+ * to the batch API with batchSize=1 preserved only to keep error-per-item
23
+ * semantics where they exist. Prefer embedBatchAPI for new code.
24
+ */
25
+ export declare function embedBatch(texts: string[]): Promise<Float32Array[]>;
26
+ /**
27
+ * sqlite-vec v0.1.x compatibility note:
28
+ * - Does NOT support named INTEGER PRIMARY KEY columns
29
+ * - DOES support rowid-based inserts
30
+ * - We use a companion table (vec_chunk_map) to map rowid → chunk_id
31
+ * - Schema: vec_chunks has only `embedding` column, rowid = auto
32
+ * vec_chunk_map(vec_rowid, chunk_id) tracks the mapping
33
+ */
34
+ export declare function ensureVecTable(db: Database.Database): void;
35
+ export declare function upsertEmbedding(db: Database.Database, chunkId: number, embedding: Float32Array): void;
36
+ export declare function semanticSearch(db: Database.Database, queryEmbedding: Float32Array, limit?: number): Array<{
37
+ chunk_id: number;
38
+ distance: number;
39
+ source_file: string;
40
+ chunk_type: string;
41
+ chunk_text: string;
42
+ source_date: string | null;
43
+ }>;
44
+ export declare function countEmbedded(db: Database.Database): number;
45
+ export { EMBEDDING_DIM };