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,54 @@
1
+ /**
2
+ * src/lib/hooks/rate-limit.ts — T5: Layer 5 of pipeline.
3
+ *
4
+ * Two protections combined:
5
+ * 1. Token-bucket rate limit (default 30 captures/min, configurable via
6
+ * NOX_HOOK_RATE_LIMIT). Refills 1 token every (60/N) seconds.
7
+ * 2. Near-duplicate dedup via cosine similarity on a lightweight
8
+ * character-shingle vector (no embeddings required — keeps Layer 5
9
+ * independent of embedding provider availability).
10
+ *
11
+ * Dedup keeps a ring buffer of the last 10 redacted texts; if cosine
12
+ * (new vs any in ring) > NOX_HOOK_DEDUP_THRESHOLD (default 0.95), reject.
13
+ *
14
+ * Note on cosine choice: full Gemini embedding cosine would be ideal but
15
+ * Layer 5 must NOT depend on network/embedding latency (it's the last
16
+ * gate before persistence). Char-shingle cosine is fast + decent for
17
+ * near-identical detection (e.g., "rerun the same command" duplicates).
18
+ * Upstream callers can swap the similarity fn via DI if a real embedder
19
+ * is desired (e.g., from cached chunks).
20
+ */
21
+ import type { CaptureDecision, HookContext } from "./types.js";
22
+ /** Pluggable similarity. Default = char-shingle cosine. */
23
+ export type SimilarityFn = (a: string, b: string) => number;
24
+ export interface RateLimitState {
25
+ /** Tokens available (float). */
26
+ tokens: number;
27
+ /** Last refill timestamp (ms epoch). */
28
+ lastRefillMs: number;
29
+ /** Ring buffer of recent redacted texts. */
30
+ recent: string[];
31
+ }
32
+ export interface RateLimitOpts {
33
+ /** Captures-per-minute capacity. Default 30. */
34
+ capacityPerMin?: number;
35
+ /** Cosine threshold for dedup (rejects if >threshold). Default 0.95. */
36
+ dedupThreshold?: number;
37
+ /** Ring buffer size. Default 10. */
38
+ ringSize?: number;
39
+ /** Pluggable similarity. Default charShingleCosine. */
40
+ similarity?: SimilarityFn;
41
+ /** Inject clock for tests. */
42
+ now?: () => number;
43
+ }
44
+ /**
45
+ * Build a fresh empty state with full bucket.
46
+ */
47
+ export declare function createState(capacity: number, now?: () => number): RateLimitState;
48
+ /** Default: character 3-shingle cosine. */
49
+ export declare function charShingleCosine(a: string, b: string): number;
50
+ /**
51
+ * Evaluate Layer 5 against a HookContext, updating the passed-in state.
52
+ * State must be threaded by the pipeline (singleton per worker).
53
+ */
54
+ export declare function applyRateLimit(ctx: HookContext, state: RateLimitState, opts?: RateLimitOpts): CaptureDecision;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * src/lib/hooks/rate-limit.ts — T5: Layer 5 of pipeline.
3
+ *
4
+ * Two protections combined:
5
+ * 1. Token-bucket rate limit (default 30 captures/min, configurable via
6
+ * NOX_HOOK_RATE_LIMIT). Refills 1 token every (60/N) seconds.
7
+ * 2. Near-duplicate dedup via cosine similarity on a lightweight
8
+ * character-shingle vector (no embeddings required — keeps Layer 5
9
+ * independent of embedding provider availability).
10
+ *
11
+ * Dedup keeps a ring buffer of the last 10 redacted texts; if cosine
12
+ * (new vs any in ring) > NOX_HOOK_DEDUP_THRESHOLD (default 0.95), reject.
13
+ *
14
+ * Note on cosine choice: full Gemini embedding cosine would be ideal but
15
+ * Layer 5 must NOT depend on network/embedding latency (it's the last
16
+ * gate before persistence). Char-shingle cosine is fast + decent for
17
+ * near-identical detection (e.g., "rerun the same command" duplicates).
18
+ * Upstream callers can swap the similarity fn via DI if a real embedder
19
+ * is desired (e.g., from cached chunks).
20
+ */
21
+ /**
22
+ * Build a fresh empty state with full bucket.
23
+ */
24
+ export function createState(capacity, now = Date.now) {
25
+ return {
26
+ tokens: capacity,
27
+ lastRefillMs: now(),
28
+ recent: [],
29
+ };
30
+ }
31
+ /** Default: character 3-shingle cosine. */
32
+ export function charShingleCosine(a, b) {
33
+ if (a.length === 0 || b.length === 0)
34
+ return 0;
35
+ if (a === b)
36
+ return 1;
37
+ const shA = shingle(a, 3);
38
+ const shB = shingle(b, 3);
39
+ let dot = 0;
40
+ let magA = 0;
41
+ let magB = 0;
42
+ for (const [k, va] of shA) {
43
+ magA += va * va;
44
+ const vb = shB.get(k) ?? 0;
45
+ if (vb !== 0)
46
+ dot += va * vb;
47
+ }
48
+ for (const vb of shB.values())
49
+ magB += vb * vb;
50
+ if (magA === 0 || magB === 0)
51
+ return 0;
52
+ return dot / (Math.sqrt(magA) * Math.sqrt(magB));
53
+ }
54
+ function shingle(s, n) {
55
+ const m = new Map();
56
+ if (s.length < n) {
57
+ m.set(s, 1);
58
+ return m;
59
+ }
60
+ for (let i = 0; i <= s.length - n; i++) {
61
+ const k = s.slice(i, i + n);
62
+ m.set(k, (m.get(k) ?? 0) + 1);
63
+ }
64
+ return m;
65
+ }
66
+ /**
67
+ * Refill token bucket based on elapsed wall-clock since last refill.
68
+ */
69
+ function refill(state, capacityPerMin, now) {
70
+ const t = now();
71
+ const elapsedMs = t - state.lastRefillMs;
72
+ if (elapsedMs <= 0)
73
+ return;
74
+ const refillRatePerMs = capacityPerMin / 60_000;
75
+ const add = elapsedMs * refillRatePerMs;
76
+ state.tokens = Math.min(capacityPerMin, state.tokens + add);
77
+ state.lastRefillMs = t;
78
+ }
79
+ /**
80
+ * Evaluate Layer 5 against a HookContext, updating the passed-in state.
81
+ * State must be threaded by the pipeline (singleton per worker).
82
+ */
83
+ export function applyRateLimit(ctx, state, opts = {}) {
84
+ const capacity = opts.capacityPerMin ?? 30;
85
+ const threshold = opts.dedupThreshold ?? 0.95;
86
+ const ringSize = opts.ringSize ?? 10;
87
+ const sim = opts.similarity ?? charShingleCosine;
88
+ const now = opts.now ?? Date.now;
89
+ refill(state, capacity, now);
90
+ // Dedup check (cosine) before consuming a token — dedup hits should NOT
91
+ // count against rate-limit.
92
+ const text = ctx.redacted?.text ?? ctx.event.content;
93
+ for (const prev of state.recent) {
94
+ const c = sim(text, prev);
95
+ if (c > threshold) {
96
+ return {
97
+ capture: false,
98
+ reason: `dedup_hit cosine=${c.toFixed(3)} threshold=${threshold}`,
99
+ layer: "rate-limit",
100
+ score: c,
101
+ };
102
+ }
103
+ }
104
+ // Rate-limit
105
+ if (state.tokens < 1) {
106
+ return {
107
+ capture: false,
108
+ reason: `rate_limited tokens=${state.tokens.toFixed(2)} capacity=${capacity}/min`,
109
+ layer: "rate-limit",
110
+ };
111
+ }
112
+ // Consume + push to ring
113
+ state.tokens -= 1;
114
+ state.recent.push(text);
115
+ if (state.recent.length > ringSize)
116
+ state.recent.shift();
117
+ return {
118
+ capture: true,
119
+ reason: `ok tokens_remaining=${state.tokens.toFixed(2)}`,
120
+ layer: "rate-limit",
121
+ };
122
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * src/lib/hooks/server-deps.ts — Wave O T5: P2 (hooks) runtime adapter.
3
+ *
4
+ * Wire-up.ts lazy-imports this module:
5
+ *
6
+ * const depsMod = await tryImport("../lib/hooks/server-deps.js");
7
+ * if (!depsMod?.buildHooksDeps) writeJson(res, ..., 503);
8
+ * const out = await handleHooksRequest(req, await depsMod.buildHooksDeps());
9
+ *
10
+ * The staged-P2 `handleHooksRequest` expects `HooksApiDeps`:
11
+ *
12
+ * interface HooksApiDeps {
13
+ * readRecent(limit): Promise<row[]>;
14
+ * config?: HookConfig;
15
+ * telemetry?: TelemetrySink;
16
+ * inspectQueue?(): { queueDepth; rateLimitTokens? };
17
+ * }
18
+ *
19
+ * `readRecent` queries `agent_events` (schema v11) for the most recent N
20
+ * captured events. Each row is sanitized to METADATA ONLY — no `payload_json`,
21
+ * no raw content (P2 privacy invariant; see staged-P2 source comment).
22
+ */
23
+ export interface HookRecentRow {
24
+ event_uuid: string;
25
+ session_id: string;
26
+ project_slug: string;
27
+ kind: string;
28
+ timestamp: string;
29
+ redaction_count: number;
30
+ }
31
+ export interface HookTelemetryRow {
32
+ event_uuid: string;
33
+ layer: string;
34
+ reason: string;
35
+ kind: string;
36
+ redaction_count: number;
37
+ payload_json: string;
38
+ ts: string;
39
+ }
40
+ export interface HooksApiDeps {
41
+ readRecent: (limit: number) => Promise<HookRecentRow[]>;
42
+ /** Optional. When absent, handler defaults to `loadConfig()` from env. */
43
+ config?: unknown;
44
+ /** Sink for dryrun telemetry. No-op default. */
45
+ telemetry?: (row: HookTelemetryRow) => void;
46
+ inspectQueue?: () => {
47
+ queueDepth: number;
48
+ rateLimitTokens?: number;
49
+ };
50
+ }
51
+ /**
52
+ * Build the HooksApiDeps the staged-P2 `handleHooksRequest` expects.
53
+ * Idempotent — safe to call once per request.
54
+ */
55
+ export declare function buildHooksDeps(overrides?: Partial<HooksApiDeps>): Promise<HooksApiDeps>;
56
+ /** Swap the queue probe for tests. */
57
+ export declare function __setQueueProbeForTests(probe: (() => {
58
+ queueDepth: number;
59
+ rateLimitTokens?: number;
60
+ }) | null): void;
61
+ export declare function __resetHooksDepsForTests(): void;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * src/lib/hooks/server-deps.ts — Wave O T5: P2 (hooks) runtime adapter.
3
+ *
4
+ * Wire-up.ts lazy-imports this module:
5
+ *
6
+ * const depsMod = await tryImport("../lib/hooks/server-deps.js");
7
+ * if (!depsMod?.buildHooksDeps) writeJson(res, ..., 503);
8
+ * const out = await handleHooksRequest(req, await depsMod.buildHooksDeps());
9
+ *
10
+ * The staged-P2 `handleHooksRequest` expects `HooksApiDeps`:
11
+ *
12
+ * interface HooksApiDeps {
13
+ * readRecent(limit): Promise<row[]>;
14
+ * config?: HookConfig;
15
+ * telemetry?: TelemetrySink;
16
+ * inspectQueue?(): { queueDepth; rateLimitTokens? };
17
+ * }
18
+ *
19
+ * `readRecent` queries `agent_events` (schema v11) for the most recent N
20
+ * captured events. Each row is sanitized to METADATA ONLY — no `payload_json`,
21
+ * no raw content (P2 privacy invariant; see staged-P2 source comment).
22
+ */
23
+ import { getDb } from "../deps/deps-registry.js";
24
+ // ─── Default implementations ─────────────────────────────────────────────────
25
+ async function defaultReadRecent(limit) {
26
+ const db = await getDb();
27
+ if (!db)
28
+ return [];
29
+ // Cap limit defensively even though handler already validates.
30
+ const safeLimit = Math.max(1, Math.min(500, Math.floor(limit)));
31
+ try {
32
+ const rows = db
33
+ .prepare(`SELECT event_uuid, session_id, project_slug, kind, timestamp, redaction_count
34
+ FROM agent_events
35
+ WHERE captured = 1
36
+ ORDER BY timestamp DESC
37
+ LIMIT ?`)
38
+ .all(safeLimit);
39
+ return rows;
40
+ }
41
+ catch {
42
+ // Table missing (pre-v11) → return empty.
43
+ return [];
44
+ }
45
+ }
46
+ function defaultInspectQueue() {
47
+ // The actual worker singleton lives in `lib/hooks/worker.ts`. We try to
48
+ // probe it dynamically; when unavailable (CLI-only deploy), return zero.
49
+ return { queueDepth: 0 };
50
+ }
51
+ let _queueProbe = null;
52
+ async function tryLoadWorkerProbe() {
53
+ if (_queueProbe)
54
+ return;
55
+ try {
56
+ // String indirection — `./worker.js` is staged-P2's worker module,
57
+ // co-located only after rsync.
58
+ const WORKER_SPEC = "./worker.js";
59
+ const mod = await import(WORKER_SPEC);
60
+ if (typeof mod.inspectQueue === "function") {
61
+ _queueProbe = mod.inspectQueue.bind(mod);
62
+ }
63
+ else if (typeof mod.default?.inspectQueue === "function") {
64
+ _queueProbe = mod.default.inspectQueue.bind(mod.default);
65
+ }
66
+ }
67
+ catch {
68
+ // Worker module not deployed — silent fallback.
69
+ }
70
+ }
71
+ // ─── Public builder ──────────────────────────────────────────────────────────
72
+ /**
73
+ * Build the HooksApiDeps the staged-P2 `handleHooksRequest` expects.
74
+ * Idempotent — safe to call once per request.
75
+ */
76
+ export async function buildHooksDeps(overrides) {
77
+ await tryLoadWorkerProbe();
78
+ return {
79
+ readRecent: overrides?.readRecent ?? defaultReadRecent,
80
+ config: overrides?.config,
81
+ telemetry: overrides?.telemetry,
82
+ inspectQueue: overrides?.inspectQueue ?? _queueProbe ?? defaultInspectQueue,
83
+ };
84
+ }
85
+ // ─── Test seam ───────────────────────────────────────────────────────────────
86
+ /** Swap the queue probe for tests. */
87
+ export function __setQueueProbeForTests(probe) {
88
+ _queueProbe = probe;
89
+ }
90
+ export function __resetHooksDepsForTests() {
91
+ _queueProbe = null;
92
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * src/lib/hooks/source-allowlist.ts — T2: Layer 2 of the privacy pipeline.
3
+ *
4
+ * Filters HookEvent by `source` AND `role`. Only events with:
5
+ * - source ∈ NOX_HOOK_SOURCES (default {openclaw})
6
+ * - role ∈ {user, assistant} (system/tool/unknown rejected by default)
7
+ *
8
+ * pass through. "unknown" source is ALWAYS rejected (it indicates the
9
+ * event was constructed without explicit channel attribution — risk vector).
10
+ *
11
+ * No content access. No telemetry write here — pipeline (T6) records the
12
+ * decision via the trace mechanism.
13
+ */
14
+ import type { HookConfig } from "./config.js";
15
+ import type { CaptureDecision, HookEvent, HookRole } from "./types.js";
16
+ export interface SourceAllowlistOpts {
17
+ /** Override allowed roles (tests only). */
18
+ allowedRoles?: ReadonlySet<HookRole>;
19
+ }
20
+ /**
21
+ * Evaluate Layer 2 against a HookEvent given the active config.
22
+ * Pure function — safe to test in isolation.
23
+ */
24
+ export declare function evaluateSourceAllowlist(event: HookEvent, config: HookConfig, opts?: SourceAllowlistOpts): CaptureDecision;
25
+ /** Returns true if a given source string is recognized at all. */
26
+ export declare function isKnownSource(s: string): boolean;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * src/lib/hooks/source-allowlist.ts — T2: Layer 2 of the privacy pipeline.
3
+ *
4
+ * Filters HookEvent by `source` AND `role`. Only events with:
5
+ * - source ∈ NOX_HOOK_SOURCES (default {openclaw})
6
+ * - role ∈ {user, assistant} (system/tool/unknown rejected by default)
7
+ *
8
+ * pass through. "unknown" source is ALWAYS rejected (it indicates the
9
+ * event was constructed without explicit channel attribution — risk vector).
10
+ *
11
+ * No content access. No telemetry write here — pipeline (T6) records the
12
+ * decision via the trace mechanism.
13
+ */
14
+ /** Roles we accept as conversation content. */
15
+ const ALLOWED_ROLES = new Set(["user", "assistant"]);
16
+ /**
17
+ * Evaluate Layer 2 against a HookEvent given the active config.
18
+ * Pure function — safe to test in isolation.
19
+ */
20
+ export function evaluateSourceAllowlist(event, config, opts = {}) {
21
+ const roles = opts.allowedRoles ?? ALLOWED_ROLES;
22
+ // Reject unknown source unconditionally — explicit attribution required.
23
+ if (event.source === "unknown") {
24
+ return {
25
+ capture: false,
26
+ reason: "source=unknown is never allowed (explicit channel attribution required)",
27
+ layer: "source-allowlist",
28
+ };
29
+ }
30
+ if (!config.allowedSources.has(event.source)) {
31
+ return {
32
+ capture: false,
33
+ reason: `source=${event.source} not in NOX_HOOK_SOURCES allowlist`,
34
+ layer: "source-allowlist",
35
+ };
36
+ }
37
+ if (!roles.has(event.role)) {
38
+ return {
39
+ capture: false,
40
+ reason: `role=${event.role} not in {user,assistant}`,
41
+ layer: "source-allowlist",
42
+ };
43
+ }
44
+ return {
45
+ capture: true,
46
+ reason: `source=${event.source} role=${event.role} allowed`,
47
+ layer: "source-allowlist",
48
+ };
49
+ }
50
+ /** Returns true if a given source string is recognized at all. */
51
+ export function isKnownSource(s) {
52
+ return ["openclaw", "cli", "manual", "mcp", "api", "unknown"].includes(s);
53
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * src/lib/hooks/types.ts — T1: Hook contract types.
3
+ *
4
+ * Public interfaces consumed by the 5-layer pipeline (T6) and all callers
5
+ * (plugin T8, CLI T11, HTTP T12, MCP T13).
6
+ *
7
+ * Schema dependency: `agent_events` table (v11) already exists per spec §6.1
8
+ * and is used by telemetry (T6 emits one row per rejection/capture).
9
+ *
10
+ * Privacy invariant: HookEvent.content is RAW until it leaves Layer 3.
11
+ * After Layer 3, content has been passed through staged-A1 redact().
12
+ * Telemetry rows NEVER include raw content — only layer name + reason + ts.
13
+ */
14
+ /**
15
+ * Roles we recognize from the source agent's turn.
16
+ * Layer 2 (source allowlist) constrains which roles get processed.
17
+ */
18
+ export type HookRole = "user" | "assistant" | "system" | "tool" | "unknown";
19
+ /**
20
+ * Origin channel of the event. Determines source allowlist (Layer 2).
21
+ * - openclaw : afterTurn hook from the OpenClaw gateway
22
+ * - cli : explicit `nox-mem hooks ingest` (manual or scripted)
23
+ * - manual : in-process API client (tests, REPL, ad-hoc)
24
+ * - mcp : MCP tool call
25
+ * - api : HTTP endpoint
26
+ * - unknown : default; ALWAYS rejected by Layer 2 unless explicitly allowed
27
+ */
28
+ export type HookSource = "openclaw" | "cli" | "manual" | "mcp" | "api" | "unknown";
29
+ /**
30
+ * Five-layer rejection reasons (one per layer + ok).
31
+ * Stored in `agent_events.kind`-like telemetry column.
32
+ */
33
+ export type RejectionReason = "env_disabled" | "source_not_allowed" | "pii_detected_skip" | "classifier_low_signal" | "rate_limited" | "dedup_hit" | "queue_full" | "explicit_skip" | "dry_run" | "invalid_input";
34
+ /** A capture decision returned by any layer. */
35
+ export interface CaptureDecision {
36
+ /** True → forward to next layer (or persist if last). */
37
+ capture: boolean;
38
+ /** Human-readable reason. Stored in telemetry. NEVER includes raw content. */
39
+ reason: string;
40
+ /** Optional layer-name; pipeline fills this if missing. */
41
+ layer?: string;
42
+ /** Optional score in [0,1] when classifier returned ambiguous. */
43
+ score?: number;
44
+ }
45
+ /**
46
+ * A normalized event before any layer touches it.
47
+ * Source must populate role + content; rest is metadata.
48
+ */
49
+ export interface HookEvent {
50
+ /** ULID assigned by caller or pipeline; used for dedup key + telemetry. */
51
+ event_id: string;
52
+ /** Where this event came from. */
53
+ source: HookSource;
54
+ /** Speaker. Layer 2 may filter by allowed roles. */
55
+ role: HookRole;
56
+ /** Raw text content (potentially containing PII). */
57
+ content: string;
58
+ /** Optional session_id (groups events from same convo). */
59
+ session_id?: string;
60
+ /** Optional project slug (cwd → slug mapping in plugin). */
61
+ project_slug?: string;
62
+ /** ISO 8601 timestamp. */
63
+ ts: string;
64
+ /** Optional decorator hints (T10 parses these). */
65
+ decorators?: ReadonlyArray<"capture" | "skip">;
66
+ /** Free-form metadata (model name, tool name, etc). NEVER content. */
67
+ meta?: Readonly<Record<string, string | number | boolean>>;
68
+ }
69
+ /**
70
+ * Mutable per-event state threaded through the pipeline.
71
+ * Lets each layer attach side-data without mutating the original HookEvent.
72
+ */
73
+ export interface HookContext {
74
+ event: HookEvent;
75
+ /** Redacted text + redaction count after Layer 3. */
76
+ redacted?: {
77
+ text: string;
78
+ redaction_count: number;
79
+ kinds: string[];
80
+ };
81
+ /** Classifier output after Layer 4. */
82
+ classification?: {
83
+ score: number;
84
+ reason: string;
85
+ };
86
+ /** Per-layer trace (debug + dryrun). */
87
+ trace: Array<{
88
+ layer: string;
89
+ decision: CaptureDecision;
90
+ t_ms: number;
91
+ }>;
92
+ /** Set once when pipeline short-circuits or persists. */
93
+ outcome?: HookResult;
94
+ }
95
+ /** Final pipeline result. */
96
+ export interface HookResult {
97
+ captured: boolean;
98
+ /** Reason for rejection, or "ok" when captured. */
99
+ reason: RejectionReason | "ok";
100
+ /** Layer that fired the rejection, or "persisted" on success. */
101
+ layer: string;
102
+ /** chunk_id when captured (set by ingestText). */
103
+ chunk_id?: number;
104
+ /** Total wall-clock time. */
105
+ duration_ms: number;
106
+ /** Whether dry-run mode was on (no persistence even if captured=true). */
107
+ dry_run: boolean;
108
+ }
109
+ /**
110
+ * Telemetry row written by pipeline for EVERY event (captured or rejected).
111
+ * Maps onto `agent_events` columns; payload_json is a sanitized stub
112
+ * (NEVER raw content).
113
+ */
114
+ export interface HookTelemetryRow {
115
+ event_uuid: string;
116
+ session_id: string;
117
+ project_slug: string;
118
+ kind: "tool_use" | "user_prompt" | "session_start" | "session_end" | "pre_compact";
119
+ timestamp: string;
120
+ payload_json: string;
121
+ redaction_count: number;
122
+ retention_days: number;
123
+ }
124
+ /** Standard error class for hook pipeline failures. */
125
+ export declare class HookError extends Error {
126
+ readonly code: RejectionReason | "internal";
127
+ readonly layer?: string;
128
+ constructor(code: RejectionReason | "internal", message: string, layer?: string);
129
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * src/lib/hooks/types.ts — T1: Hook contract types.
3
+ *
4
+ * Public interfaces consumed by the 5-layer pipeline (T6) and all callers
5
+ * (plugin T8, CLI T11, HTTP T12, MCP T13).
6
+ *
7
+ * Schema dependency: `agent_events` table (v11) already exists per spec §6.1
8
+ * and is used by telemetry (T6 emits one row per rejection/capture).
9
+ *
10
+ * Privacy invariant: HookEvent.content is RAW until it leaves Layer 3.
11
+ * After Layer 3, content has been passed through staged-A1 redact().
12
+ * Telemetry rows NEVER include raw content — only layer name + reason + ts.
13
+ */
14
+ /** Standard error class for hook pipeline failures. */
15
+ export class HookError extends Error {
16
+ code;
17
+ layer;
18
+ constructor(code, message, layer) {
19
+ super(message);
20
+ this.name = "HookError";
21
+ this.code = code;
22
+ this.layer = layer;
23
+ }
24
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * src/lib/hooks/worker.ts — T9: Async worker queue.
3
+ *
4
+ * Backpressure-aware bounded queue:
5
+ * - enqueue() returns synchronously (non-blocking for callers like
6
+ * OpenClaw afterTurn hook). Returns {accepted, reason}.
7
+ * - When full, oldest event is dropped + telemetry "queue_full" row
8
+ * emitted. New event takes its slot (most-recent-wins).
9
+ * - A drain loop runs every `tickMs` ms, processing batches of up to
10
+ * `batchSize` events through the pipeline.
11
+ *
12
+ * The worker is the bridge between the synchronous hook trigger (an
13
+ * OpenClaw turn ended) and the async pipeline (which may call out to
14
+ * embed/ingest).
15
+ *
16
+ * Lifecycle:
17
+ * const w = createWorker({ pipeline, ...opts });
18
+ * w.start();
19
+ * w.enqueue(event);
20
+ * ...
21
+ * await w.stop(); // drains remaining + shuts down
22
+ */
23
+ import type { PipelineHandle } from "./pipeline.js";
24
+ import type { HookEvent, HookResult, HookTelemetryRow } from "./types.js";
25
+ export interface WorkerOpts {
26
+ pipeline: PipelineHandle;
27
+ /** Max events held in queue. Default 10_000 (matches spec ring buffer). */
28
+ maxSize?: number;
29
+ /** Drain tick interval. Default 250ms (matches spec §3 T3). */
30
+ tickMs?: number;
31
+ /** Max events processed per tick. Default 100. */
32
+ batchSize?: number;
33
+ /** Optional sink for queue-overflow telemetry. */
34
+ telemetry?: (row: HookTelemetryRow) => void | Promise<void>;
35
+ }
36
+ export interface WorkerStats {
37
+ enqueued: number;
38
+ processed: number;
39
+ rejected: number;
40
+ captured: number;
41
+ dropped: number;
42
+ errors: number;
43
+ queueDepth: number;
44
+ }
45
+ export interface WorkerHandle {
46
+ enqueue(event: HookEvent): {
47
+ accepted: boolean;
48
+ reason: string;
49
+ depth: number;
50
+ };
51
+ start(): void;
52
+ stop(): Promise<void>;
53
+ drain(): Promise<HookResult[]>;
54
+ stats(): WorkerStats;
55
+ }
56
+ export declare function createWorker(opts: WorkerOpts): WorkerHandle;