@remnic/core 1.0.3 → 1.1.1

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 (323) hide show
  1. package/dist/abort-error.d.ts +32 -0
  2. package/dist/abort-error.js +11 -0
  3. package/dist/access-audit.d.ts +56 -0
  4. package/dist/access-audit.js +9 -0
  5. package/dist/access-audit.js.map +1 -0
  6. package/dist/access-cli.js +72 -54
  7. package/dist/access-cli.js.map +1 -1
  8. package/dist/access-http.d.ts +16 -8
  9. package/dist/access-http.js +25 -17
  10. package/dist/access-mcp.d.ts +16 -8
  11. package/dist/access-mcp.js +28 -6
  12. package/dist/access-schema.d.ts +130 -39
  13. package/dist/access-schema.js +5 -1
  14. package/dist/access-service-Br8ZydTK.d.ts +827 -0
  15. package/dist/access-service.d.ts +20 -660
  16. package/dist/access-service.js +22 -14
  17. package/dist/bootstrap.d.ts +6 -3
  18. package/dist/briefing.d.ts +1 -0
  19. package/dist/briefing.js +6 -5
  20. package/dist/buffer-surprise-report.d.ts +70 -0
  21. package/dist/buffer-surprise-report.js +7 -0
  22. package/dist/buffer-surprise-report.js.map +1 -0
  23. package/dist/buffer-surprise.d.ts +98 -0
  24. package/dist/buffer-surprise.js +11 -0
  25. package/dist/buffer-surprise.js.map +1 -0
  26. package/dist/buffer.d.ts +100 -2
  27. package/dist/buffer.js +1 -1
  28. package/dist/calibration.js +5 -5
  29. package/dist/causal-behavior.js +4 -4
  30. package/dist/causal-chain.js +2 -2
  31. package/dist/causal-consolidation.js +17 -16
  32. package/dist/causal-consolidation.js.map +1 -1
  33. package/dist/causal-retrieval.js +4 -4
  34. package/dist/causal-trajectory.js +1 -1
  35. package/dist/{chunk-QNJMBKFK.js → chunk-2LGMW3DJ.js} +3 -2
  36. package/dist/chunk-2LGMW3DJ.js.map +1 -0
  37. package/dist/{chunk-QDYXG4CS.js → chunk-3FPTCC3Z.js} +4 -3
  38. package/dist/chunk-3FPTCC3Z.js.map +1 -0
  39. package/dist/chunk-3GPTTA4J.js +57 -0
  40. package/dist/chunk-3GPTTA4J.js.map +1 -0
  41. package/dist/{chunk-QKAH5B6E.js → chunk-3GXCSUXR.js} +94 -6
  42. package/dist/chunk-3GXCSUXR.js.map +1 -0
  43. package/dist/{chunk-POBPGDWI.js → chunk-3OGMS3PE.js} +2 -2
  44. package/dist/chunk-54V4BZWP.js +139 -0
  45. package/dist/chunk-54V4BZWP.js.map +1 -0
  46. package/dist/chunk-5JRF2PZA.js +67 -0
  47. package/dist/chunk-5JRF2PZA.js.map +1 -0
  48. package/dist/chunk-64NJRYU2.js +332 -0
  49. package/dist/chunk-64NJRYU2.js.map +1 -0
  50. package/dist/chunk-6AUUAZEX.js +150 -0
  51. package/dist/chunk-6AUUAZEX.js.map +1 -0
  52. package/dist/{chunk-HITJFT7E.js → chunk-7I7FKFZH.js} +28 -21
  53. package/dist/chunk-7I7FKFZH.js.map +1 -0
  54. package/dist/chunk-AJU4PJGY.js +126 -0
  55. package/dist/chunk-AJU4PJGY.js.map +1 -0
  56. package/dist/chunk-ASAITVLA.js +64 -0
  57. package/dist/chunk-ASAITVLA.js.map +1 -0
  58. package/dist/{chunk-X4WESCKA.js → chunk-B5WXLVDY.js} +187 -6
  59. package/dist/chunk-B5WXLVDY.js.map +1 -0
  60. package/dist/{chunk-RCICHSHL.js → chunk-BGJGXLZ7.js} +111 -2
  61. package/dist/{chunk-RCICHSHL.js.map → chunk-BGJGXLZ7.js.map} +1 -1
  62. package/dist/{chunk-OJFGVJS6.js → chunk-BK2EFTE2.js} +319 -18
  63. package/dist/chunk-BK2EFTE2.js.map +1 -0
  64. package/dist/chunk-C4SQJZAF.js +486 -0
  65. package/dist/chunk-C4SQJZAF.js.map +1 -0
  66. package/dist/{chunk-GJQPH5G3.js → chunk-CUPFXL3J.js} +2 -2
  67. package/dist/chunk-DF3RVK3X.js +119 -0
  68. package/dist/chunk-DF3RVK3X.js.map +1 -0
  69. package/dist/{chunk-PMB3WGDL.js → chunk-DFTTJYSO.js} +167 -7
  70. package/dist/chunk-DFTTJYSO.js.map +1 -0
  71. package/dist/chunk-DGVM5SFL.js +69 -0
  72. package/dist/chunk-DGVM5SFL.js.map +1 -0
  73. package/dist/chunk-EIR5VLIH.js +90 -0
  74. package/dist/chunk-EIR5VLIH.js.map +1 -0
  75. package/dist/{chunk-PAORGQRI.js → chunk-EPQJM2GC.js} +37 -23
  76. package/dist/chunk-EPQJM2GC.js.map +1 -0
  77. package/dist/{chunk-POMSFKTB.js → chunk-F5VP6YCB.js} +368 -10
  78. package/dist/chunk-F5VP6YCB.js.map +1 -0
  79. package/dist/{chunk-6ZH4TU6I.js → chunk-FAAFWE4G.js} +2 -1
  80. package/dist/chunk-FAAFWE4G.js.map +1 -0
  81. package/dist/{chunk-74JR4N5J.js → chunk-FVA6TGI3.js} +2 -2
  82. package/dist/chunk-GDFS42HT.js +206 -0
  83. package/dist/chunk-GDFS42HT.js.map +1 -0
  84. package/dist/{chunk-BKQJBXXX.js → chunk-GGD5W7TB.js} +2 -2
  85. package/dist/chunk-GGD5W7TB.js.map +1 -0
  86. package/dist/{chunk-V7XCAHIB.js → chunk-GKFXUTJ2.js} +508 -26
  87. package/dist/chunk-GKFXUTJ2.js.map +1 -0
  88. package/dist/{chunk-NSB3WSYS.js → chunk-HK3FGIEW.js} +278 -3
  89. package/dist/chunk-HK3FGIEW.js.map +1 -0
  90. package/dist/{chunk-AAI7JARD.js → chunk-HMDCOMYU.js} +8 -11
  91. package/dist/chunk-HMDCOMYU.js.map +1 -0
  92. package/dist/chunk-IISBCCWR.js +52 -0
  93. package/dist/chunk-IISBCCWR.js.map +1 -0
  94. package/dist/{chunk-YFYL2SIJ.js → chunk-INXV5JBT.js} +290 -46
  95. package/dist/chunk-INXV5JBT.js.map +1 -0
  96. package/dist/chunk-JBMSGZEQ.js +441 -0
  97. package/dist/chunk-JBMSGZEQ.js.map +1 -0
  98. package/dist/{chunk-UPMD5XND.js → chunk-JL2PU6AI.js} +16 -5
  99. package/dist/chunk-JL2PU6AI.js.map +1 -0
  100. package/dist/{chunk-J4IYOZZ5.js → chunk-JXS5PDQ7.js} +3 -1
  101. package/dist/chunk-JXS5PDQ7.js.map +1 -0
  102. package/dist/{chunk-AYPYCLR7.js → chunk-KUB6JU6H.js} +4 -4
  103. package/dist/chunk-KVBLZUKV.js +173 -0
  104. package/dist/chunk-KVBLZUKV.js.map +1 -0
  105. package/dist/chunk-LBLXEFWK.js +51 -0
  106. package/dist/chunk-LBLXEFWK.js.map +1 -0
  107. package/dist/{chunk-U2IQTSBY.js → chunk-LTCGGW2D.js} +1 -1
  108. package/dist/chunk-LTCGGW2D.js.map +1 -0
  109. package/dist/{chunk-UEYA6UC7.js → chunk-NZLQTHS5.js} +25 -2
  110. package/dist/chunk-NZLQTHS5.js.map +1 -0
  111. package/dist/chunk-PVGDJXVK.js +21 -0
  112. package/dist/chunk-PVGDJXVK.js.map +1 -0
  113. package/dist/chunk-PVPWZSSI.js +37 -0
  114. package/dist/chunk-PVPWZSSI.js.map +1 -0
  115. package/dist/{chunk-4NRAJUDS.js → chunk-RBBWYEFJ.js} +1 -1
  116. package/dist/chunk-RFYAYKTD.js +146 -0
  117. package/dist/chunk-RFYAYKTD.js.map +1 -0
  118. package/dist/{chunk-JROGC36Y.js → chunk-RGLL5SPU.js} +2 -2
  119. package/dist/{chunk-2VFW5K5U.js → chunk-S3EEFKNY.js} +103 -65
  120. package/dist/chunk-S3EEFKNY.js.map +1 -0
  121. package/dist/chunk-SOBJ6NEY.js +18 -0
  122. package/dist/chunk-SOBJ6NEY.js.map +1 -0
  123. package/dist/{chunk-MYQWXITD.js → chunk-SPI27QT6.js} +2 -2
  124. package/dist/chunk-TVVEYCNW.js +65 -0
  125. package/dist/chunk-TVVEYCNW.js.map +1 -0
  126. package/dist/chunk-ULYOGL6R.js +322 -0
  127. package/dist/chunk-ULYOGL6R.js.map +1 -0
  128. package/dist/{chunk-S4LX5EBI.js → chunk-VBVG2M5G.js} +64 -10
  129. package/dist/chunk-VBVG2M5G.js.map +1 -0
  130. package/dist/{chunk-KWP7T3DP.js → chunk-VDX363PS.js} +2 -2
  131. package/dist/{chunk-XMGSSBFX.js → chunk-VYM3VWOF.js} +1560 -244
  132. package/dist/chunk-VYM3VWOF.js.map +1 -0
  133. package/dist/{chunk-MTLYEMJB.js → chunk-WCLICCGB.js} +18 -3
  134. package/dist/chunk-WCLICCGB.js.map +1 -0
  135. package/dist/{chunk-ECKDIK5F.js → chunk-WVVA7F5A.js} +2 -2
  136. package/dist/chunk-X6GF3FX2.js +26 -0
  137. package/dist/chunk-X6GF3FX2.js.map +1 -0
  138. package/dist/{chunk-3QFQGRHO.js → chunk-XMHBH5H6.js} +4 -4
  139. package/dist/{chunk-KEG4GNGI.js → chunk-XZ2TIKGC.js} +38 -8
  140. package/dist/chunk-XZ2TIKGC.js.map +1 -0
  141. package/dist/chunk-Y4FHOFJ2.js +140 -0
  142. package/dist/chunk-Y4FHOFJ2.js.map +1 -0
  143. package/dist/chunk-YNB73F22.js +137 -0
  144. package/dist/chunk-YNB73F22.js.map +1 -0
  145. package/dist/{chunk-7PA4OZEU.js → chunk-YNQKWQT4.js} +55 -30
  146. package/dist/chunk-YNQKWQT4.js.map +1 -0
  147. package/dist/chunk-ZAIM4TUE.js +488 -0
  148. package/dist/chunk-ZAIM4TUE.js.map +1 -0
  149. package/dist/{chunk-BTY5RRRF.js → chunk-ZEM3OK2K.js} +5 -5
  150. package/dist/chunk-ZZTOURJI.js +91 -0
  151. package/dist/chunk-ZZTOURJI.js.map +1 -0
  152. package/dist/{cli-DwIBnp2g.d.ts → cli-BkeRaYfk.d.ts} +2 -2
  153. package/dist/cli.d.ts +13 -5
  154. package/dist/cli.js +45 -33
  155. package/dist/config.js +1 -1
  156. package/dist/consolidation-operator.d.ts +41 -0
  157. package/dist/consolidation-operator.js +11 -0
  158. package/dist/consolidation-operator.js.map +1 -0
  159. package/dist/consolidation-provenance-check.d.ts +68 -0
  160. package/dist/consolidation-provenance-check.js +9 -0
  161. package/dist/consolidation-provenance-check.js.map +1 -0
  162. package/dist/consolidation-undo.d.ts +123 -0
  163. package/dist/consolidation-undo.js +426 -0
  164. package/dist/consolidation-undo.js.map +1 -0
  165. package/dist/contradiction-review-WIUBAR52.js +21 -0
  166. package/dist/contradiction-review-WIUBAR52.js.map +1 -0
  167. package/dist/contradiction-scan-E3GJTI4F.js +412 -0
  168. package/dist/contradiction-scan-E3GJTI4F.js.map +1 -0
  169. package/dist/cross-namespace-budget.d.ts +133 -0
  170. package/dist/cross-namespace-budget.js +9 -0
  171. package/dist/cross-namespace-budget.js.map +1 -0
  172. package/dist/direct-answer-wiring.d.ts +77 -0
  173. package/dist/direct-answer-wiring.js +10 -0
  174. package/dist/direct-answer-wiring.js.map +1 -0
  175. package/dist/direct-answer.d.ts +106 -0
  176. package/dist/direct-answer.js +10 -0
  177. package/dist/direct-answer.js.map +1 -0
  178. package/dist/{engine-X7X3AAG3.js → engine-F3GOXGE5.js} +7 -6
  179. package/dist/engine-F3GOXGE5.js.map +1 -0
  180. package/dist/entity-retrieval.d.ts +1 -0
  181. package/dist/entity-retrieval.js +6 -5
  182. package/dist/explicit-capture.d.ts +6 -3
  183. package/dist/explicit-capture.js +2 -2
  184. package/dist/extraction-judge-telemetry.d.ts +113 -0
  185. package/dist/extraction-judge-telemetry.js +14 -0
  186. package/dist/extraction-judge-telemetry.js.map +1 -0
  187. package/dist/extraction-judge-training.d.ts +85 -0
  188. package/dist/extraction-judge-training.js +16 -0
  189. package/dist/extraction-judge-training.js.map +1 -0
  190. package/dist/extraction-judge.d.ts +124 -2
  191. package/dist/extraction-judge.js +11 -1
  192. package/dist/extraction.js +7 -6
  193. package/dist/fallback-llm.d.ts +11 -2
  194. package/dist/fallback-llm.js +2 -2
  195. package/dist/graph-recall.d.ts +100 -0
  196. package/dist/graph-recall.js +8 -0
  197. package/dist/graph-recall.js.map +1 -0
  198. package/dist/graph-retrieval.d.ts +271 -0
  199. package/dist/graph-retrieval.js +21 -0
  200. package/dist/graph-retrieval.js.map +1 -0
  201. package/dist/harmonic-retrieval.js +2 -1
  202. package/dist/importance.js +1 -1
  203. package/dist/index.d.ts +589 -138
  204. package/dist/index.js +531 -403
  205. package/dist/index.js.map +1 -1
  206. package/dist/intent.js +1 -1
  207. package/dist/local-llm.d.ts +10 -3
  208. package/dist/local-llm.js +1 -1
  209. package/dist/memory-worth-bench.d.ts +51 -0
  210. package/dist/memory-worth-bench.js +131 -0
  211. package/dist/memory-worth-bench.js.map +1 -0
  212. package/dist/memory-worth-filter.d.ts +128 -0
  213. package/dist/memory-worth-filter.js +10 -0
  214. package/dist/memory-worth-filter.js.map +1 -0
  215. package/dist/memory-worth-outcomes.d.ts +118 -0
  216. package/dist/memory-worth-outcomes.js +9 -0
  217. package/dist/memory-worth-outcomes.js.map +1 -0
  218. package/dist/memory-worth.d.ts +102 -0
  219. package/dist/memory-worth.js +7 -0
  220. package/dist/memory-worth.js.map +1 -0
  221. package/dist/operator-toolkit.d.ts +40 -1
  222. package/dist/operator-toolkit.js +24 -14
  223. package/dist/{orchestrator-B9kwlCep.d.ts → orchestrator-CmJ-NTdJ.d.ts} +254 -10
  224. package/dist/orchestrator.d.ts +6 -3
  225. package/dist/orchestrator.js +59 -48
  226. package/dist/page-versioning.d.ts +12 -1
  227. package/dist/page-versioning.js +5 -3
  228. package/dist/{port-C1GZFv8h.d.ts → port-BADbLZU5.d.ts} +2 -2
  229. package/dist/qmd-recall-cache.d.ts +1 -1
  230. package/dist/qmd.d.ts +5 -3
  231. package/dist/qmd.js +2 -1
  232. package/dist/reasoning-trace-recall.d.ts +90 -0
  233. package/dist/reasoning-trace-recall.js +13 -0
  234. package/dist/reasoning-trace-recall.js.map +1 -0
  235. package/dist/reasoning-trace-types.d.ts +54 -0
  236. package/dist/reasoning-trace-types.js +17 -0
  237. package/dist/reasoning-trace-types.js.map +1 -0
  238. package/dist/recall-audit-anomaly.d.ts +112 -0
  239. package/dist/recall-audit-anomaly.js +11 -0
  240. package/dist/recall-audit-anomaly.js.map +1 -0
  241. package/dist/recall-audit.js +5 -44
  242. package/dist/recall-audit.js.map +1 -1
  243. package/dist/recall-explain-renderer.d.ts +49 -0
  244. package/dist/recall-explain-renderer.js +18 -0
  245. package/dist/recall-explain-renderer.js.map +1 -0
  246. package/dist/recall-state.d.ts +39 -1
  247. package/dist/recall-state.js +1 -1
  248. package/dist/recall-xray-cli.d.ts +40 -0
  249. package/dist/recall-xray-cli.js +11 -0
  250. package/dist/recall-xray-cli.js.map +1 -0
  251. package/dist/recall-xray-renderer.d.ts +44 -0
  252. package/dist/recall-xray-renderer.js +18 -0
  253. package/dist/recall-xray-renderer.js.map +1 -0
  254. package/dist/recall-xray.d.ts +179 -0
  255. package/dist/recall-xray.js +13 -0
  256. package/dist/recall-xray.js.map +1 -0
  257. package/dist/resolution-QBTDHTG7.js +100 -0
  258. package/dist/resolution-QBTDHTG7.js.map +1 -0
  259. package/dist/resolve-provider-secret.d.ts +24 -1
  260. package/dist/resolve-provider-secret.js +3 -1
  261. package/dist/resume-bundles.js +6 -6
  262. package/dist/retrieval-agents.d.ts +1 -1
  263. package/dist/retrieval-tiers.d.ts +17 -0
  264. package/dist/retrieval-tiers.js +9 -0
  265. package/dist/retrieval-tiers.js.map +1 -0
  266. package/dist/schemas.d.ts +301 -45
  267. package/dist/schemas.js +1 -1
  268. package/dist/{semantic-consolidation-DrvSYRdB.d.ts → semantic-consolidation-CxJU6MJk.d.ts} +62 -1
  269. package/dist/semantic-consolidation.d.ts +2 -1
  270. package/dist/semantic-consolidation.js +20 -6
  271. package/dist/semantic-rule-promotion.js +6 -5
  272. package/dist/semantic-rule-verifier.js +6 -5
  273. package/dist/storage.d.ts +82 -1
  274. package/dist/storage.js +5 -4
  275. package/dist/summarizer.js +4 -4
  276. package/dist/temporal-supersession.d.ts +1 -0
  277. package/dist/tier-migration.d.ts +2 -1
  278. package/dist/types-DJhqDJUV.d.ts +50 -0
  279. package/dist/types.d.ts +309 -3
  280. package/dist/types.js +1 -1
  281. package/dist/verified-recall.js +6 -5
  282. package/package.json +1 -1
  283. package/dist/chunk-2VFW5K5U.js.map +0 -1
  284. package/dist/chunk-6ZH4TU6I.js.map +0 -1
  285. package/dist/chunk-7PA4OZEU.js.map +0 -1
  286. package/dist/chunk-AAI7JARD.js.map +0 -1
  287. package/dist/chunk-BKQJBXXX.js.map +0 -1
  288. package/dist/chunk-HITJFT7E.js.map +0 -1
  289. package/dist/chunk-J4IYOZZ5.js.map +0 -1
  290. package/dist/chunk-KEG4GNGI.js.map +0 -1
  291. package/dist/chunk-LAYN4LDC.js +0 -267
  292. package/dist/chunk-LAYN4LDC.js.map +0 -1
  293. package/dist/chunk-MTLYEMJB.js.map +0 -1
  294. package/dist/chunk-NSB3WSYS.js.map +0 -1
  295. package/dist/chunk-OJFGVJS6.js.map +0 -1
  296. package/dist/chunk-PAORGQRI.js.map +0 -1
  297. package/dist/chunk-PMB3WGDL.js.map +0 -1
  298. package/dist/chunk-POMSFKTB.js.map +0 -1
  299. package/dist/chunk-QDYXG4CS.js.map +0 -1
  300. package/dist/chunk-QKAH5B6E.js.map +0 -1
  301. package/dist/chunk-QNJMBKFK.js.map +0 -1
  302. package/dist/chunk-S4LX5EBI.js.map +0 -1
  303. package/dist/chunk-U2IQTSBY.js.map +0 -1
  304. package/dist/chunk-UEYA6UC7.js.map +0 -1
  305. package/dist/chunk-UPMD5XND.js.map +0 -1
  306. package/dist/chunk-UVJFDP7P.js +0 -202
  307. package/dist/chunk-UVJFDP7P.js.map +0 -1
  308. package/dist/chunk-V7XCAHIB.js.map +0 -1
  309. package/dist/chunk-X4WESCKA.js.map +0 -1
  310. package/dist/chunk-XMGSSBFX.js.map +0 -1
  311. package/dist/chunk-YFYL2SIJ.js.map +0 -1
  312. /package/dist/{engine-X7X3AAG3.js.map → abort-error.js.map} +0 -0
  313. /package/dist/{chunk-POBPGDWI.js.map → chunk-3OGMS3PE.js.map} +0 -0
  314. /package/dist/{chunk-GJQPH5G3.js.map → chunk-CUPFXL3J.js.map} +0 -0
  315. /package/dist/{chunk-74JR4N5J.js.map → chunk-FVA6TGI3.js.map} +0 -0
  316. /package/dist/{chunk-AYPYCLR7.js.map → chunk-KUB6JU6H.js.map} +0 -0
  317. /package/dist/{chunk-4NRAJUDS.js.map → chunk-RBBWYEFJ.js.map} +0 -0
  318. /package/dist/{chunk-JROGC36Y.js.map → chunk-RGLL5SPU.js.map} +0 -0
  319. /package/dist/{chunk-MYQWXITD.js.map → chunk-SPI27QT6.js.map} +0 -0
  320. /package/dist/{chunk-KWP7T3DP.js.map → chunk-VDX363PS.js.map} +0 -0
  321. /package/dist/{chunk-ECKDIK5F.js.map → chunk-WVVA7F5A.js.map} +0 -0
  322. /package/dist/{chunk-3QFQGRHO.js.map → chunk-XMHBH5H6.js.map} +0 -0
  323. /package/dist/{chunk-BTY5RRRF.js.map → chunk-ZEM3OK2K.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/local-llm.ts"],"sourcesContent":["import { log } from \"./logger.js\";\nimport type { PluginConfig } from \"./types.js\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport os from \"node:os\";\nimport type { ModelRegistry } from \"./model-registry.js\";\nimport { launchProcessSync } from \"./runtime/child-process.js\";\nimport { mergeEnv, readEnvVar } from \"./runtime/env.js\";\n\n/** Trim trailing slash characters without backtracking regex. */\nfunction trimTrailingSlashes(s: string): string {\n let end = s.length;\n while (end > 0 && s[end - 1] === \"/\") end--;\n return s.substring(0, end);\n}\n\n/**\n * Local LLM client for OpenAI-compatible endpoints (LM Studio, Ollama, MLX, etc.)\n *\n * Based on openclaw-tactician's provider detection patterns for consistency.\n * Provides privacy-preserving, cost-effective LLM operations with\n * graceful fallback to cloud providers when local LLM is unavailable.\n */\nexport type LocalLlmType = \"lmstudio\" | \"ollama\" | \"mlx\" | \"vllm\" | \"generic\";\n\n/**\n * Backends known to honor `chat_template_kwargs: { enable_thinking: false }`\n * on OpenAI-compatible `/v1/chat/completions`. LM Studio and vLLM both\n * forward this field to the jinja chat template, where thinking-capable\n * models (Qwen 3.5, Gemma 4, DeepSeek) suppress reasoning tokens.\n *\n * Strict OpenAI-compatible backends (standard OpenAI, Azure OpenAI, some\n * proxies) reject unknown request fields with 400 — which trips the\n * `localLlm400*` cooldown path. `LocalLlmClient` therefore only injects\n * the kwarg when the detected backend is in this set; unknown / `generic`\n * / `ollama` / `mlx` fail open (no injection, no 400 risk). Issue #548.\n */\nconst THINKING_COMPATIBLE_BACKENDS: ReadonlySet<LocalLlmType> = new Set([\n \"lmstudio\",\n \"vllm\",\n]);\n\ninterface LocalServerConfig {\n type: LocalLlmType;\n defaultPort: number;\n healthEndpoint: string;\n modelsEndpoint: string;\n detectFn: (response: unknown) => boolean;\n}\n\nconst LOCAL_SERVERS: LocalServerConfig[] = [\n {\n type: \"ollama\",\n defaultPort: 11434,\n healthEndpoint: \"/\",\n modelsEndpoint: \"/api/tags\",\n detectFn: (resp) => typeof resp === \"string\" && resp.includes(\"Ollama\"),\n },\n {\n type: \"mlx\",\n defaultPort: 8080,\n healthEndpoint: \"/v1/models\",\n modelsEndpoint: \"/v1/models\",\n detectFn: (resp) =>\n typeof resp === \"object\" &&\n resp !== null &&\n \"data\" in resp &&\n Array.isArray((resp as { data: unknown[] }).data),\n },\n {\n type: \"lmstudio\",\n defaultPort: 1234,\n healthEndpoint: \"/v1/models\",\n modelsEndpoint: \"/v1/models\",\n detectFn: (resp) =>\n typeof resp === \"object\" &&\n resp !== null &&\n \"data\" in resp &&\n Array.isArray((resp as { data: unknown[] }).data),\n },\n {\n type: \"vllm\",\n defaultPort: 8000,\n healthEndpoint: \"/health\",\n modelsEndpoint: \"/v1/models\",\n detectFn: (resp) => resp === \"\" || (typeof resp === \"object\" && resp !== null),\n },\n];\n\nexport interface LocalModelInfo {\n id: string;\n contextWindow?: number;\n maxTokens?: number;\n}\n\nexport type LocalLlmRequestPriority = \"recall-critical\" | \"background\";\n\ninterface LocalLlmChatCompletionOptions {\n temperature?: number;\n maxTokens?: number;\n responseFormat?: { type: string };\n timeoutMs?: number;\n operation?: string;\n priority?: LocalLlmRequestPriority;\n}\n\ninterface LocalLlmQueuedRequest {\n messages: Array<{ role: string; content: string }>;\n options: LocalLlmChatCompletionOptions;\n priority: LocalLlmRequestPriority;\n enqueuedAtMs: number;\n resolve: (value: LocalLlmChatCompletionResult | null) => void;\n}\n\ninterface LocalLlmChatCompletionResult {\n content: string;\n usage?: { promptTokens: number; completionTokens: number; totalTokens: number };\n}\n\nconst LOCAL_LLM_GLOBAL_BACKEND_STATE = \"__openclawEngramLocalLlmBackendState\";\n\ntype LocalLlmBackendState = {\n untilMs: number;\n reason: string;\n};\nexport class LocalLlmClient {\n private config: PluginConfig;\n private isAvailable: boolean | null = null;\n private lastHealthCheck: number = 0;\n private detectedType: LocalLlmType | null = null;\n private cachedModelInfo: LocalModelInfo | null = null;\n private cachedLmsContext: number | null = null;\n private lastLmsCheck: number = 0;\n private consecutive400s: number = 0;\n private cooldownUntilMs: number = 0;\n private modelRegistry?: ModelRegistry;\n private _disableThinking: boolean = false;\n private readonly requestQueues: Record<LocalLlmRequestPriority, LocalLlmQueuedRequest[]> = {\n \"recall-critical\": [],\n background: [],\n };\n private readonly queueProcessing = new Set<LocalLlmRequestPriority>();\n private queueDrainScheduled: boolean = false;\n private static readonly HEALTH_CHECK_INTERVAL_MS = 60000; // 1 minute\n private static readonly LMS_CACHE_INTERVAL_MS = 30000; // 30 seconds\n\n constructor(config: PluginConfig, modelRegistry?: ModelRegistry) {\n this.config = config;\n this.modelRegistry = modelRegistry;\n }\n\n /**\n * Request thinking/reasoning suppression on the next chat completion.\n *\n * When `true`, the client will inject\n * `chat_template_kwargs: { enable_thinking: false }` into the request\n * body — **but only when the detected backend is known to support it**\n * (LM Studio, vLLM; see `THINKING_COMPATIBLE_BACKENDS`). Strict\n * OpenAI-compat backends reject unknown fields with 400; on those the\n * client fails open (thinking runs normally). This is the safe\n * default for Remnic extraction / consolidation: measurable latency\n * win on thinking-capable backends, zero risk on others. Issue #548.\n */\n set disableThinking(value: boolean) {\n this._disableThinking = value;\n }\n\n private resolveHomeDir(): string {\n return this.config.localLlmHomeDir || readEnvVar(\"HOME\") || os.homedir();\n }\n\n private buildRequestHeaders(base: Record<string, string> = {}): Record<string, string> {\n const headers: Record<string, string> = {\n ...base,\n ...(this.config.localLlmHeaders ?? {}),\n };\n if (this.config.localLlmApiKey && this.config.localLlmAuthHeader !== false) {\n headers.Authorization = `Bearer ${this.config.localLlmApiKey}`;\n }\n return headers;\n }\n\n private isAbortError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const maybe = err as { name?: string; message?: string };\n return (\n maybe.name === \"AbortError\" ||\n maybe.message === \"This operation was aborted\" ||\n maybe.message === \"The operation was aborted\"\n );\n }\n\n /**\n * Set the ModelRegistry for caching detected capabilities\n */\n setModelRegistry(registry: ModelRegistry): void {\n this.modelRegistry = registry;\n }\n\n /**\n * Get the detected server type (null if not detected)\n */\n getDetectedType(): LocalLlmType | null {\n return this.detectedType;\n }\n\n private getBackendKey(): string {\n return trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n ).replace(/\\/v1$/, \"\");\n }\n\n private getGlobalBackendState(): Map<string, LocalLlmBackendState> {\n const globalAny = globalThis as typeof globalThis & {\n [LOCAL_LLM_GLOBAL_BACKEND_STATE]?: Map<string, LocalLlmBackendState>;\n };\n if (!globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE]) {\n globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE] = new Map();\n }\n return globalAny[LOCAL_LLM_GLOBAL_BACKEND_STATE];\n }\n\n private getTrippedBackendState(now: number): LocalLlmBackendState | null {\n const state = this.getGlobalBackendState().get(this.getBackendKey()) ?? null;\n if (!state) return null;\n if (state.untilMs <= now) {\n this.getGlobalBackendState().delete(this.getBackendKey());\n this.lastHealthCheck = 0;\n return null;\n }\n return state;\n }\n\n private markBackendUnavailable(reason: string, durationMs: number): void {\n const normalizedReason = this.normalizeBackendTripReason(reason);\n if (durationMs > 0) {\n const untilMs = Date.now() + durationMs;\n this.getGlobalBackendState().set(this.getBackendKey(), { untilMs, reason: normalizedReason });\n } else {\n this.getGlobalBackendState().delete(this.getBackendKey());\n }\n this.isAvailable = false;\n this.lastHealthCheck = 0;\n log.warn(\n `local LLM backend unavailable for ${durationMs}ms: model=${this.config.localLlmModel} reason=${normalizedReason}`,\n );\n }\n\n private extractNonRecoverableBackendReason(reason: string): string | null {\n const match = reason.match(\n /Failed to load model|Library not loaded|different Team IDs|code signature|llm_engine_mlx_amphibian/i,\n );\n return match?.[0] ?? null;\n }\n\n private extractNonRecoverableBackendReasonFromErrorText(errorText: string): string | null {\n const directReason = this.extractNonRecoverableBackendReason(errorText);\n if (directReason) return directReason;\n try {\n const parsed = JSON.parse(errorText) as { error?: { message?: string } };\n return this.extractNonRecoverableBackendReason(parsed?.error?.message ?? \"\");\n } catch {\n return null;\n }\n }\n\n private normalizeBackendTripReason(reason: string): string {\n const cleaned = reason.replace(/\\s+/g, \" \").replace(/^[-:–—\\s]+/, \"\").trim();\n if (!cleaned) return \"unknown local backend failure\";\n return cleaned.length > 160 ? `${cleaned.slice(0, 157)}...` : cleaned;\n }\n\n /**\n * Fetch with timeout for health checks\n */\n private async fetchWithTimeout(\n url: string,\n timeoutMs: number = 2000,\n headers?: Record<string, string>,\n ): Promise<{ ok: boolean; data: unknown; status: number | null }> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await fetch(url, {\n signal: controller.signal,\n headers: this.buildRequestHeaders({ Accept: \"application/json\", ...(headers ?? {}) }),\n });\n clearTimeout(timeout);\n\n if (!response.ok) {\n return { ok: false, data: null, status: response.status };\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return { ok: true, data: await response.json(), status: response.status };\n } else {\n return { ok: true, data: await response.text(), status: response.status };\n }\n } catch (err) {\n clearTimeout(timeout);\n return { ok: false, data: null, status: null };\n }\n }\n\n /**\n * Check if local LLM is available\n * Uses 127.0.0.1 instead of localhost to avoid DNS issues (consistent with tactician)\n */\n async checkAvailability(): Promise<boolean> {\n // Cache health check results for 1 minute\n const now = Date.now();\n const trippedState = this.getTrippedBackendState(now);\n if (trippedState) {\n this.isAvailable = false;\n this.lastHealthCheck = 0;\n log.info(\n `local LLM availability: backend circuit open for ${Math.max(0, trippedState.untilMs - now)}ms (${trippedState.reason})`,\n );\n return false;\n }\n if (this.isAvailable !== null && now - this.lastHealthCheck < LocalLlmClient.HEALTH_CHECK_INTERVAL_MS) {\n return this.isAvailable;\n }\n\n // Normalize URL - replace localhost with 127.0.0.1, remove trailing slashes\n const baseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n let sawUnauthorizedProbe = false;\n\n // Try to detect which server type is running\n for (const serverConfig of LOCAL_SERVERS) {\n const healthUrl = `${baseUrl}${serverConfig.healthEndpoint}`;\n log.debug(`checking ${serverConfig.type} at ${healthUrl}`);\n\n const result = await this.fetchWithTimeout(healthUrl);\n if (result.ok && serverConfig.detectFn(result.data)) {\n this.isAvailable = true;\n this.detectedType = serverConfig.type;\n this.lastHealthCheck = now;\n log.info(`detected ${serverConfig.type} at ${baseUrl}`);\n return true;\n }\n if (result.status === 401 || result.status === 403) {\n sawUnauthorizedProbe = true;\n }\n }\n\n // Generic check if specific detection failed\n try {\n const modelsUrl = `${baseUrl}/v1/models`;\n const result = await this.fetchWithTimeout(modelsUrl);\n if (result.ok) {\n this.isAvailable = true;\n this.detectedType = \"generic\";\n this.lastHealthCheck = now;\n log.info(`detected generic OpenAI-compatible server at ${baseUrl}`);\n return true;\n }\n if (result.status === 401 || result.status === 403) {\n sawUnauthorizedProbe = true;\n }\n } catch {\n // Fall through to unavailable\n }\n\n this.isAvailable = false;\n this.detectedType = null;\n this.lastHealthCheck = now;\n if (sawUnauthorizedProbe) {\n log.warn(\n `local LLM availability probe was unauthorized at ${baseUrl}; verify localLlmApiKey and localLlmAuthHeader settings`,\n );\n }\n log.debug(\"local LLM not available at\", baseUrl);\n return false;\n }\n\n /**\n * Try to get context window from LM Studio settings.json as fallback.\n * This reads the defaultContextLength setting which is what LM Studio uses\n * when loading models without explicit context configuration.\n */\n private getContextFromLmStudioSettings(): number | null {\n try {\n const homeDir = this.resolveHomeDir();\n const settingsPath = `${homeDir}/.cache/lm-studio/settings.json`;\n\n if (!existsSync(settingsPath)) {\n log.debug(`LM Studio settings: file not found at ${settingsPath}`);\n return null;\n }\n\n const content = readFileSync(settingsPath, \"utf-8\");\n const settings = JSON.parse(content) as {\n defaultContextLength?: {\n type?: string;\n value?: number;\n };\n };\n\n if (settings.defaultContextLength?.value) {\n const contextWindow = settings.defaultContextLength.value;\n log.debug(`LM Studio settings: found default context length: ${contextWindow}`);\n return contextWindow;\n }\n\n return null;\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n log.debug(`LM Studio settings: failed to read - ${errorMsg}`);\n return null;\n }\n }\n\n /**\n * Try to get context window from LMS CLI (LM Studio specific).\n * Uses --json flag for reliable parsing.\n * Returns null if LMS CLI is not available or model not found.\n */\n private getContextFromLmsCli(modelId: string): number | null {\n try {\n // Check if lms CLI exists in common locations.\n // HOME may be absent in launchd environments, so prefer the resolved helper.\n const homeDir = this.resolveHomeDir();\n const lmsPaths = [\n this.config.localLmsCliPath || \"\",\n `${homeDir}/.cache/lm-studio/bin/lms`,\n \"/usr/local/bin/lms\",\n \"/opt/homebrew/bin/lms\",\n ];\n\n const lmsPath = lmsPaths.find((p) => p.length > 0 && existsSync(p));\n if (!lmsPath) {\n log.debug(`LMS CLI: not found in standard locations (checked: ${lmsPaths.join(\", \")})`);\n return null;\n }\n\n // Run lms ps --json to get loaded models with context\n // Use spawnSync with shell and explicit PATH to ensure lms can find its dependencies\n log.debug(`LMS CLI: running: ${lmsPath} ps --json`);\n const existingPath = readEnvVar(\"PATH\") || \"\";\n const result = launchProcessSync(lmsPath, [\"ps\", \"--json\"], {\n encoding: \"utf-8\",\n timeout: 5000,\n shell: false, // Don't use shell for JSON output - more reliable\n env: mergeEnv({\n PATH: `${this.config.localLmsBinDir || `${homeDir}/.cache/lm-studio/bin`}:/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:${existingPath}`,\n HOME: homeDir,\n }),\n });\n\n if (result.error) {\n log.debug(`LMS CLI: spawn error - ${result.error.message}`);\n return null;\n }\n\n if (result.stderr && result.stderr.trim()) {\n log.debug(`LMS CLI: stderr - ${result.stderr.slice(0, 200)}`);\n }\n\n const output = result.stdout || \"\";\n if (!output.trim()) {\n log.debug(\"LMS CLI: empty output - LM Studio may not be running or no models loaded\");\n return null;\n }\n\n // Parse JSON output\n let models: Array<{\n identifier?: string;\n modelKey?: string;\n contextLength?: number;\n maxContextLength?: number;\n }>;\n\n try {\n models = JSON.parse(output) as typeof models;\n } catch (parseErr) {\n log.debug(`LMS CLI: JSON parse error - ${parseErr}`);\n return null;\n }\n\n if (!Array.isArray(models) || models.length === 0) {\n log.debug(\"LMS CLI: no models loaded\");\n return null;\n }\n\n // Find the model matching our configured model ID\n const model = models.find((m) =>\n m.identifier === modelId ||\n m.modelKey === modelId ||\n (m.identifier?.includes(modelId.replace(/@\\d+bit$/, \"\")))\n );\n\n if (!model) {\n log.debug(`LMS CLI: model \"${modelId}\" not found in loaded models: ${models.map(m => m.identifier).join(\", \")}`);\n return null;\n }\n\n // Use contextLength (actual configured) or fall back to maxContextLength (model max)\n const contextWindow = model.contextLength || model.maxContextLength;\n\n if (contextWindow) {\n log.info(`LMS CLI detected context window: ${contextWindow} for ${modelId} (max: ${model.maxContextLength})`);\n return contextWindow;\n }\n\n return null;\n } catch (err) {\n // LMS CLI not available or failed\n const errorMsg = err instanceof Error ? err.message : String(err);\n log.debug(`LMS CLI: failed - ${errorMsg}`);\n return null;\n }\n }\n\n /**\n * Get full model info from LMS CLI including context length and max context length.\n * Returns null if LMS CLI is unavailable or model not found.\n */\n private getLmsModelInfo(modelId: string): { contextLength: number; maxContextLength: number; identifier: string } | null {\n try {\n const result = launchProcessSync(\"lms\", [\"ps\", \"--json\"], {\n encoding: \"utf-8\",\n timeout: 5000,\n shell: false,\n });\n\n if (result.error) {\n return null;\n }\n\n const output = result.stdout || \"\";\n if (!output.trim()) {\n return null;\n }\n\n let models: Array<{\n identifier?: string;\n modelKey?: string;\n contextLength?: number;\n maxContextLength?: number;\n }>;\n\n try {\n models = JSON.parse(output) as typeof models;\n } catch {\n return null;\n }\n\n if (!Array.isArray(models) || models.length === 0) {\n return null;\n }\n\n const model = models.find((m) =>\n m.identifier === modelId ||\n m.modelKey === modelId ||\n (m.identifier?.includes(modelId.replace(/@\\d+bit$/, \"\")))\n );\n\n if (!model || !model.contextLength) {\n return null;\n }\n\n return {\n contextLength: model.contextLength,\n maxContextLength: model.maxContextLength || model.contextLength,\n identifier: model.identifier || modelId,\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Get context window for the configured model, using cache if available.\n * This method caches the result to avoid repeated LMS CLI calls.\n * Order: ModelRegistry (persistent) -> memory cache -> LMS CLI -> settings.json\n */\n getCachedContextWindow(modelId: string): number | null {\n const now = Date.now();\n\n // 1. Check ModelRegistry for persisted context window\n if (this.modelRegistry) {\n const caps = this.modelRegistry.getCapabilities(modelId);\n if (caps.source === \"lmstudio\" && caps.contextWindow) {\n log.debug(`ModelRegistry: using persisted LM Studio context: ${caps.contextWindow}`);\n // Also update memory cache\n this.cachedLmsContext = caps.contextWindow;\n this.lastLmsCheck = now;\n return caps.contextWindow;\n }\n }\n\n // 2. Return in-memory cached value if still valid\n if (this.cachedLmsContext && now - this.lastLmsCheck < LocalLlmClient.LMS_CACHE_INTERVAL_MS) {\n log.debug(`LMS CLI: returning in-memory cached context: ${this.cachedLmsContext}`);\n return this.cachedLmsContext;\n }\n\n // 3. Try LMS CLI (authoritative source)\n const lmsInfo = this.getLmsModelInfo(modelId);\n if (lmsInfo?.contextLength) {\n this.cachedLmsContext = lmsInfo.contextLength;\n this.lastLmsCheck = now;\n // Calculate appropriate output tokens based on context size\n // Use 12.5% of context window, capped at 16K (generous but safe)\n const calculatedOutputTokens = Math.min(Math.floor(lmsInfo.contextLength / 8), 16384);\n const outputTokens = Math.max(calculatedOutputTokens, 4096); // Minimum 4K\n // Persist to ModelRegistry with detected capabilities\n if (this.modelRegistry) {\n this.modelRegistry.setCapabilities(modelId, {\n maxPositionEmbeddings: lmsInfo.maxContextLength || lmsInfo.contextLength,\n contextWindow: lmsInfo.contextLength,\n supportsExtendedContext: (lmsInfo.maxContextLength || lmsInfo.contextLength) > 65536,\n typicalOutputTokens: outputTokens,\n source: \"lmstudio\",\n });\n log.info(`LMS CLI: Stored capabilities for ${modelId}: ${lmsInfo.contextLength} context, ${outputTokens} output tokens`);\n }\n return lmsInfo.contextLength;\n }\n\n // Legacy: Try LMS CLI context only (fallback)\n const legacyContext = this.getContextFromLmsCli(modelId);\n if (legacyContext) {\n this.cachedLmsContext = legacyContext;\n this.lastLmsCheck = now;\n // Persist to ModelRegistry with calculated output tokens\n if (this.modelRegistry) {\n const calculatedOutputTokens = Math.min(Math.floor(legacyContext / 8), 16384);\n const outputTokens = Math.max(calculatedOutputTokens, 4096);\n this.modelRegistry.setCapabilities(modelId, {\n maxPositionEmbeddings: legacyContext,\n contextWindow: legacyContext,\n supportsExtendedContext: false,\n typicalOutputTokens: outputTokens,\n source: \"lmstudio\",\n });\n }\n return legacyContext;\n }\n\n // 4. Fall back to LM Studio settings.json\n const settingsContext = this.getContextFromLmStudioSettings();\n if (settingsContext) {\n log.info(`LM Studio settings: using default context: ${settingsContext}`);\n this.cachedLmsContext = settingsContext;\n this.lastLmsCheck = now;\n return settingsContext;\n }\n\n return null;\n }\n\n /**\n * Clear the LMS context cache. Call this when the model changes.\n */\n clearContextCache(): void {\n this.cachedLmsContext = null;\n this.lastLmsCheck = 0;\n log.debug(\"LMS CLI: context cache cleared\");\n }\n\n private remainingCooldownMs(now: number = Date.now()): number {\n return Math.max(0, this.cooldownUntilMs - now);\n }\n\n private scheduleQueueDrain(): void {\n if (this.queueDrainScheduled) return;\n this.queueDrainScheduled = true;\n\n queueMicrotask(() => {\n this.queueDrainScheduled = false;\n this.startAvailableQueuedRequests();\n });\n }\n\n private hasQueuedRequests(): boolean {\n return (\n this.requestQueues[\"recall-critical\"].length > 0 ||\n this.requestQueues.background.length > 0\n );\n }\n\n private dequeueQueuedRequest(priority: LocalLlmRequestPriority): LocalLlmQueuedRequest | null {\n const next = this.requestQueues[priority].shift();\n return next ?? null;\n }\n\n private failOpenQueuedRequestsForCooldown(): number {\n let dropped = 0;\n for (const priority of [\"recall-critical\", \"background\"] as const) {\n while (this.requestQueues[priority].length > 0) {\n const queued = this.requestQueues[priority].shift();\n queued?.resolve(null);\n dropped += 1;\n }\n }\n return dropped;\n }\n\n private startAvailableQueuedRequests(): void {\n if (!this.queueProcessing.has(\"recall-critical\")) {\n const nextCritical = this.dequeueQueuedRequest(\"recall-critical\");\n if (nextCritical) {\n this.queueProcessing.add(\"recall-critical\");\n void this.runQueuedRequest(nextCritical);\n }\n }\n\n if (!this.queueProcessing.has(\"background\")) {\n const nextBackground = this.dequeueQueuedRequest(\"background\");\n if (nextBackground) {\n this.queueProcessing.add(\"background\");\n void this.runQueuedRequest(nextBackground);\n }\n }\n }\n\n private async runQueuedRequest(next: LocalLlmQueuedRequest): Promise<void> {\n try {\n const remainingCooldownMs = this.remainingCooldownMs();\n if (remainingCooldownMs > 0) {\n const additionalDropped = this.failOpenQueuedRequestsForCooldown();\n log.warn(\n `local LLM: cooldown active (${remainingCooldownMs}ms remaining), dropping ${additionalDropped + 1} queued request(s) fail-open`,\n );\n next.resolve(null);\n return;\n }\n\n let result: LocalLlmChatCompletionResult | null = null;\n try {\n result = await this.runChatCompletionRequest(next.messages, next.options, {\n priority: next.priority,\n enqueuedAtMs: next.enqueuedAtMs,\n });\n } catch (err) {\n log.warn(`local LLM queue drain failed open: ${err instanceof Error ? err.message : String(err)}`);\n }\n next.resolve(result);\n } finally {\n this.queueProcessing.delete(next.priority);\n if (this.hasQueuedRequests()) {\n this.scheduleQueueDrain();\n }\n }\n }\n\n private async runChatCompletionRequest(\n messages: Array<{ role: string; content: string }>,\n options: LocalLlmChatCompletionOptions,\n queueMeta?: { priority: LocalLlmRequestPriority; enqueuedAtMs: number },\n ): Promise<LocalLlmChatCompletionResult | null> {\n log.debug(\n `local LLM chatCompletion: localLlmEnabled=${this.config.localLlmEnabled}, model=${this.config.localLlmModel}`,\n );\n\n const operation = options.operation ?? \"unspecified\";\n const startedAtMs = Date.now();\n if (queueMeta) {\n log.debug(\n `local LLM queue start: priority=${queueMeta.priority} waitMs=${startedAtMs - queueMeta.enqueuedAtMs} op=${operation}`,\n );\n }\n\n try {\n const isAvailable = await this.checkAvailability();\n if (!isAvailable) {\n log.debug(\n `local LLM: checkAvailability returned false for ${this.config.localLlmUrl}`,\n );\n return null;\n }\n\n const promptChars = messages.reduce((sum, m) => sum + (m.content?.length ?? 0), 0);\n const requestBody: Record<string, unknown> = {\n model: this.config.localLlmModel,\n messages,\n temperature: options.temperature ?? 0.7,\n // Use max_tokens consistent with cloud models\n max_tokens: options.maxTokens ?? 4096,\n };\n\n // Skip response_format for local LLMs - they don't support json_object type\n // The prompts already instruct the model to output JSON\n // Only send if it's json_schema type which some local LLMs support\n if (options.responseFormat?.type === \"json_schema\") {\n requestBody.response_format = options.responseFormat;\n }\n\n // Suppress thinking/reasoning for thinking-capable models\n // (Qwen 3.5, Gemma 4, DeepSeek). These models default to\n // thinking-on via their chat template; sending\n // `chat_template_kwargs: { enable_thinking: false }` tells the\n // template to skip reasoning tokens.\n //\n // Gate the injection on detected backend support (issue #548,\n // Codex P1 on PR #550): `chat_template_kwargs` is an LM Studio /\n // vLLM / llama.cpp extension, not part of standard OpenAI chat\n // completions. Strict OpenAI-compatible backends reject\n // unknown fields with 400, which trips the 400-cooldown path and\n // can effectively disable local extraction. Fail open when the\n // backend hasn't been positively identified as thinking-capable.\n if (\n this._disableThinking &&\n this.detectedType !== null &&\n THINKING_COMPATIBLE_BACKENDS.has(this.detectedType)\n ) {\n requestBody.chat_template_kwargs = { enable_thinking: false };\n }\n\n // Normalize URL (use 127.0.0.1 instead of localhost)\n const baseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n const chatUrl = baseUrl.endsWith(\"/v1\")\n ? `${baseUrl}/chat/completions`\n : `${baseUrl}/v1/chat/completions`;\n\n const requestBodyJson = JSON.stringify(requestBody);\n log.debug(\n `local LLM: sending request to ${chatUrl} with model ${this.config.localLlmModel}`,\n );\n // Avoid logging request bodies by default (can contain sensitive user content).\n log.debug(`local LLM: request body length=${requestBodyJson.length}`);\n\n // Write request body to file for debugging\n if (this.config.debug) {\n try {\n const { writeFileSync } = await import(\"node:fs\");\n writeFileSync(\"/tmp/engram-last-request.json\", requestBodyJson);\n } catch {\n /* ignore */\n }\n }\n\n const effectiveTimeoutMs =\n typeof options.timeoutMs === \"number\"\n ? Math.min(this.config.localLlmTimeoutMs, options.timeoutMs)\n : this.config.localLlmTimeoutMs;\n const maxAttempts = 1 + Math.max(0, this.config.localLlmRetry5xxCount);\n let response: Response | null = null;\n let lastAbortError: Error | null = null;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const attemptAbort = new AbortController();\n const attemptTimeout = setTimeout(() => attemptAbort.abort(), effectiveTimeoutMs);\n try {\n response = await fetch(chatUrl, {\n method: \"POST\",\n headers: this.buildRequestHeaders({\n \"Content-Type\": \"application/json\",\n }),\n body: JSON.stringify(requestBody),\n signal: attemptAbort.signal,\n });\n } catch (err) {\n if (!this.isAbortError(err)) throw err;\n lastAbortError = err instanceof Error ? err : new Error(String(err));\n if (attempt < maxAttempts) {\n const backoffMs = this.config.localLlmRetryBackoffMs * attempt;\n log.warn(\n `local LLM request aborted: op=${operation} attempt=${attempt}/${maxAttempts} timeoutMs=${effectiveTimeoutMs} model=${this.config.localLlmModel}; retrying after ${backoffMs}ms`,\n );\n await new Promise((resolve) => setTimeout(resolve, backoffMs));\n continue;\n }\n break;\n } finally {\n clearTimeout(attemptTimeout);\n }\n\n if (response.ok) break;\n if (response.status >= 500 && attempt < maxAttempts) {\n try {\n const errorText = await response.clone().text();\n const nonRecoverableReason =\n this.extractNonRecoverableBackendReasonFromErrorText(errorText);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n );\n this.consecutive400s = 0;\n return null;\n }\n } catch (e) {\n log.debug(`local LLM failed to inspect retryable error body: ${e}`);\n }\n }\n if (response.status < 500 || attempt >= maxAttempts) break;\n\n const backoffMs = this.config.localLlmRetryBackoffMs * attempt;\n log.warn(\n `local LLM request got ${response.status}; retrying (attempt ${attempt + 1}/${maxAttempts}) after ${backoffMs}ms`,\n );\n await new Promise((resolve) => setTimeout(resolve, backoffMs));\n }\n log.debug(\n `local LLM: received response, status=${response?.status}, ok=${response?.ok}`,\n );\n\n if (!response) {\n if (lastAbortError) {\n log.warn(\n `local LLM request aborted after ${maxAttempts} attempt(s): op=${operation} timeoutMs=${effectiveTimeoutMs} model=${this.config.localLlmModel} promptChars=${promptChars} durationMs=${Date.now() - startedAtMs}`,\n );\n } else {\n log.warn(\n `local LLM request failed: no response object (op=${operation} model=${this.config.localLlmModel} durationMs=${Date.now() - startedAtMs})`,\n );\n }\n return null;\n }\n\n if (!response.ok) {\n let reason = \"\";\n let errorText = \"\";\n try {\n errorText = await response.text();\n // Try to extract a stable error message without logging content.\n try {\n const parsed = JSON.parse(errorText) as { error?: { message?: string } };\n reason = parsed?.error?.message ? ` — ${parsed.error.message}` : \"\";\n } catch {\n // Keep a short preview in debug only.\n log.debug(`local LLM error body: ${errorText.slice(0, 500)}`);\n }\n } catch (e) {\n log.debug(`local LLM failed to read error body: ${e}`);\n }\n log.warn(\n `local LLM request failed: ${response.status} ${response.statusText}${reason} ` +\n `(op=${operation}, model=${this.config.localLlmModel}, url=${chatUrl}, promptChars=${promptChars}, maxTokens=${requestBody.max_tokens as number})`,\n );\n const nonRecoverableReason =\n this.extractNonRecoverableBackendReason(reason) ??\n this.extractNonRecoverableBackendReasonFromErrorText(errorText);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n );\n this.consecutive400s = 0;\n return null;\n }\n if (response.status === 400) {\n this.consecutive400s += 1;\n if (this.consecutive400s >= this.config.localLlm400TripThreshold) {\n this.cooldownUntilMs = Date.now() + this.config.localLlm400CooldownMs;\n log.warn(\n `local LLM: entering cooldown for ${this.config.localLlm400CooldownMs}ms ` +\n `after ${this.consecutive400s} consecutive 400 responses`,\n );\n this.consecutive400s = 0;\n }\n } else {\n this.consecutive400s = 0;\n }\n return null;\n }\n this.consecutive400s = 0;\n\n const data = (await response.json()) as {\n choices?: Array<{\n message?: { content?: string; reasoning_content?: string };\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n };\n };\n\n log.debug(\n `local LLM response: choices=${data.choices?.length}, usage=${JSON.stringify(data.usage)}`,\n );\n\n // Thinking models (e.g. Qwen 3.5) may put their response in\n // `reasoning_content` and leave `content` empty. Fall back to\n // reasoning_content so engram still gets a usable result.\n const msg = data.choices?.[0]?.message;\n const content = msg?.content || msg?.reasoning_content || \"\";\n if (!content) {\n log.warn(`local LLM returned empty content. choices=${JSON.stringify(data.choices)?.slice(0, 200)}`);\n return null;\n }\n\n // Estimate tokens if not provided by local LLM\n const usage = data.usage\n ? {\n promptTokens: data.usage.prompt_tokens ?? 0,\n completionTokens: data.usage.completion_tokens ?? 0,\n totalTokens: data.usage.total_tokens ?? 0,\n }\n : this.estimateTokens(messages, content);\n\n const durationMs = Date.now() - startedAtMs;\n if (this.config.slowLogEnabled && durationMs >= this.config.slowLogThresholdMs) {\n const promptChars = messages.reduce((sum, m) => sum + (m.content?.length ?? 0), 0);\n const op = options.operation ? ` op=${options.operation}` : \"\";\n log.warn(\n `SLOW local LLM:${op} durationMs=${durationMs} model=${this.config.localLlmModel} url=${chatUrl} promptChars=${promptChars} outputTokens=${usage.completionTokens} totalTokens=${usage.totalTokens}`,\n );\n }\n\n log.debug(\"local LLM: request succeeded, tokens:\", usage.totalTokens);\n return { content, usage };\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n const durationMs = Date.now() - startedAtMs;\n if (this.isAbortError(err)) {\n log.warn(\n `local LLM request aborted: op=${operation} timeoutMs=${options.timeoutMs ?? this.config.localLlmTimeoutMs} model=${this.config.localLlmModel} durationMs=${durationMs} error=${errMsg}`,\n );\n return null;\n }\n log.warn(`local LLM request error: op=${operation} error=${errMsg}`);\n this.isAvailable = false; // Mark as unavailable on non-abort errors\n const nonRecoverableReason = this.extractNonRecoverableBackendReason(errMsg);\n if (nonRecoverableReason) {\n this.markBackendUnavailable(\n nonRecoverableReason,\n this.config.localLlm400CooldownMs,\n );\n }\n return null;\n } finally {\n if (queueMeta) {\n const finishedAtMs = Date.now();\n const waitMs = startedAtMs - queueMeta.enqueuedAtMs;\n log.debug(\n `local LLM queue finish: priority=${queueMeta.priority} waitMs=${waitMs} runMs=${finishedAtMs - startedAtMs} totalMs=${finishedAtMs - queueMeta.enqueuedAtMs} op=${operation}`,\n );\n }\n }\n }\n\n /**\n * Query the local LLM server for loaded model information.\n * Returns null if unavailable or if the model is not found.\n */\n async getLoadedModelInfo(): Promise<LocalModelInfo | null> {\n const baseUrl = trimTrailingSlashes(\n this.config.localLlmUrl.replace(\"localhost\", \"127.0.0.1\"),\n );\n\n // Handle URL construction - localLlmUrl may already include /v1\n const modelsUrl = baseUrl.endsWith(\"/v1\")\n ? `${baseUrl}/models`\n : `${baseUrl}/v1/models`;\n log.debug(`Fetching model info from ${modelsUrl}`);\n\n try {\n const result = await this.fetchWithTimeout(modelsUrl, 3000);\n if (!result.ok) {\n if (result.status === 401 || result.status === 403) {\n log.warn(\n `Local LLM: unauthorized while fetching models from ${modelsUrl}; verify localLlmApiKey and localLlmAuthHeader settings`,\n );\n }\n log.warn(`Local LLM: Failed to fetch models from ${modelsUrl} - server returned error`);\n return null;\n }\n if (!result.data) {\n log.warn(`Local LLM: No data returned from ${modelsUrl}`);\n return null;\n }\n\n const data = result.data as {\n data?: Array<{\n id?: string;\n object?: string;\n owned_by?: string;\n // LM Studio specific fields\n max_context_length?: number;\n max_tokens?: number;\n // Ollama specific\n name?: string;\n details?: {\n parameter_size?: string;\n family?: string;\n };\n }>;\n };\n\n if (!Array.isArray(data.data) || data.data.length === 0) {\n log.warn(\"Local LLM returned no models\");\n return null;\n }\n\n // Verbose model listings are noisy on every gateway restart. Keep it debug-only.\n const modelIds = data.data.map((m) => m.id).filter(Boolean);\n log.debug(\n `Local LLM: Found ${modelIds.length} model(s). First 10: ${modelIds.slice(0, 10).join(\", \")}`,\n );\n\n // Find the model matching our configured model ID\n const configuredModel = this.config.localLlmModel;\n let model = data.data.find((m) => m.id === configuredModel);\n\n // If not found by exact match, try partial match (handle suffixes like @4bit)\n if (!model) {\n model = data.data.find((m) =>\n configuredModel.includes(m.id || \"\") ||\n (m.id || \"\").includes(configuredModel.replace(/@\\d+bit$/, \"\"))\n );\n }\n\n // If still not found, use the first loaded model and warn\n if (!model) {\n model = data.data[0];\n const availablePreview = data.data\n .map((m) => m.id)\n .filter(Boolean)\n .slice(0, 10)\n .join(\", \");\n log.warn(\n `Configured model \"${configuredModel}\" not found in local LLM. ` +\n `Using \"${model.id}\" instead. Available (first 10): ${availablePreview}`\n );\n }\n\n // Extract context window - try multiple field names\n let contextWindow = model.max_context_length || model.max_tokens;\n\n // If API doesn't report context window, try LMS CLI (LM Studio specific)\n if (!contextWindow) {\n log.info(\"Local LLM: API did not report context window, trying LMS CLI...\");\n const lmsContext = this.getCachedContextWindow(model.id || \"\");\n if (lmsContext) {\n contextWindow = lmsContext;\n }\n }\n\n this.cachedModelInfo = {\n id: model.id || \"unknown\",\n contextWindow: contextWindow,\n maxTokens: model.max_tokens,\n };\n\n log.info(\n `Local LLM model detected: ${this.cachedModelInfo.id}, ` +\n `context window: ${contextWindow?.toLocaleString() || \"unknown (may use default)\"}`\n );\n\n return this.cachedModelInfo;\n } catch (err) {\n log.warn(`Failed to fetch model info: ${err}`);\n return null;\n }\n }\n\n /**\n * Check if the configured model is available and get its actual context window.\n * Warns if there's a mismatch between expected and actual context.\n */\n async validateModelConfig(expectedContextWindow?: number): Promise<{\n available: boolean;\n actualContextWindow?: number;\n warnings: string[];\n }> {\n const warnings: string[] = [];\n\n const modelInfo = await this.getLoadedModelInfo();\n if (!modelInfo) {\n return { available: false, warnings: [\"Could not query local LLM for model info\"] };\n }\n\n // If we have expected context and the server reports one, check for mismatch\n if (expectedContextWindow && modelInfo.contextWindow) {\n if (modelInfo.contextWindow < expectedContextWindow) {\n warnings.push(\n `Context window mismatch: Model ${modelInfo.id} supports ${modelInfo.contextWindow.toLocaleString()} tokens, ` +\n `but engram is configured for ${expectedContextWindow.toLocaleString()}. ` +\n `Set localLlmMaxContext: ${modelInfo.contextWindow} in config to avoid errors.`\n );\n }\n }\n\n // Warn if server doesn't report context window (common with some local LLM setups)\n if (!modelInfo.contextWindow) {\n warnings.push(\n `Local LLM server did not report context window for ${modelInfo.id}. ` +\n `If you get \"context length exceeded\" errors, set localLlmMaxContext in config.`\n );\n }\n\n return {\n available: true,\n actualContextWindow: modelInfo.contextWindow,\n warnings,\n };\n }\n\n /**\n * Make a chat completion request to local LLM\n */\n async chatCompletion(\n messages: Array<{ role: string; content: string }>,\n options: LocalLlmChatCompletionOptions = {},\n ): Promise<LocalLlmChatCompletionResult | null> {\n if (!this.config.localLlmEnabled) {\n log.debug(\"local LLM: disabled, returning null\");\n return null;\n }\n\n const remainingMs = this.remainingCooldownMs();\n if (remainingMs > 0) {\n log.debug(`local LLM: cooldown active (${remainingMs}ms remaining), skipping request`);\n return null;\n }\n if (options.priority) {\n const priority = options.priority;\n return await new Promise<LocalLlmChatCompletionResult | null>((resolve) => {\n this.requestQueues[priority].push({\n messages,\n options,\n priority,\n enqueuedAtMs: Date.now(),\n resolve,\n });\n this.scheduleQueueDrain();\n });\n }\n\n return await this.runChatCompletionRequest(messages, options);\n }\n\n /**\n * Estimate tokens when local LLM doesn't return usage stats\n * Rough estimate: 1 token ≈ 4 characters\n */\n private estimateTokens(\n messages: Array<{ role: string; content: string }>,\n response: string\n ): { promptTokens: number; completionTokens: number; totalTokens: number } {\n const promptChars = messages.reduce((sum, m) => sum + m.content.length, 0);\n const promptTokens = Math.ceil(promptChars / 4);\n const completionTokens = Math.ceil(response.length / 4);\n\n return {\n promptTokens,\n completionTokens,\n totalTokens: promptTokens + completionTokens,\n };\n }\n\n /**\n * Try local LLM first, fallback to cloud provider if configured\n */\n async withFallback<T>(\n localOperation: () => Promise<T | null>,\n fallbackOperation: () => Promise<T>,\n operationName: string\n ): Promise<T> {\n // Try local LLM first if enabled\n if (this.config.localLlmEnabled) {\n const localResult = await localOperation();\n if (localResult !== null) {\n log.debug(`${operationName}: used local LLM`);\n return localResult;\n }\n\n // Local failed or unavailable\n if (this.config.localLlmFallback) {\n log.info(`${operationName}: local LLM unavailable, falling back to cloud`);\n } else {\n throw new Error(`${operationName}: local LLM unavailable and fallback disabled`);\n }\n }\n\n // Use fallback (cloud provider)\n return fallbackOperation();\n }\n}\n"],"mappings":";;;;;;;;;;;;AAEA,SAAS,YAAY,oBAAoB;AACzC,OAAO,QAAQ;AAMf,SAAS,oBAAoB,GAAmB;AAC9C,MAAI,MAAM,EAAE;AACZ,SAAO,MAAM,KAAK,EAAE,MAAM,CAAC,MAAM,IAAK;AACtC,SAAO,EAAE,UAAU,GAAG,GAAG;AAC3B;AAuBA,IAAM,+BAA0D,oBAAI,IAAI;AAAA,EACtE;AAAA,EACA;AACF,CAAC;AAUD,IAAM,gBAAqC;AAAA,EACzC;AAAA,IACE,MAAM;AAAA,IACN,aAAa;AAAA,IACb,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,UAAU,CAAC,SAAS,OAAO,SA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Promises/obligations
68
+ reasoning_trace: 0.09,
69
+ // Stored reasoning chains (issue #564)
68
70
  decision: 0.08,
69
71
  // Decisions with rationale
70
72
  relationship: 0.05,
@@ -328,4 +330,4 @@ export {
328
330
  importanceLevel,
329
331
  isAboveImportanceThreshold
330
332
  };
331
- //# sourceMappingURL=chunk-J4IYOZZ5.js.map
333
+ //# sourceMappingURL=chunk-JXS5PDQ7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/importance.ts"],"sourcesContent":["/**\n * Local Importance Scoring (Phase 1B)\n *\n * Zero-LLM heuristic system that evaluates each memory's significance.\n * Analyzes content for markers like explicit importance statements,\n * personal information, instructions, emotional content, and factual density.\n */\n\nimport type { ImportanceLevel, ImportanceScore, MemoryCategory, MemoryFile } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Marker patterns for each tier\n// ---------------------------------------------------------------------------\n\n/** Critical importance markers (0.9-1.0) */\nconst CRITICAL_PATTERNS = [\n // Explicit importance\n /\\b(critical|crucial|essential|must|always|never)\\b/i,\n /\\b(important|remember this|don't forget)\\b/i,\n // Personal identity\n /\\b(my name is|i am|i'm called)\\b/i,\n /\\b(my (birthday|phone|email|address|ssn|password))\\b/i,\n // Strong preferences\n /\\b(i (hate|love|despise|adore))\\b/i,\n /\\b(absolutely|definitely|certainly) (not|must|should)\\b/i,\n // Corrections (high weight)\n /\\b(actually|no,? that's wrong|correction:?|let me correct)\\b/i,\n /\\b(i said|i meant|i was wrong)\\b/i,\n];\n\n/** High importance markers (0.7-0.9) */\nconst HIGH_PATTERNS = [\n // Decisions\n /\\b(decided|decision|chose|choosing|picked|selected)\\b/i,\n /\\b(we('ll| will) (go with|use|implement))\\b/i,\n // Instructions\n /\\b(make sure|ensure|always|don't|do not|never|avoid)\\b/i,\n /\\b(you (should|must|need to))\\b/i,\n // Temporal references (deadlines, schedules)\n /\\b(by (monday|tuesday|wednesday|thursday|friday|saturday|sunday))\\b/i,\n /\\b(deadline|due (date|by)|by (end of|next))\\b/i,\n /\\b(tomorrow|next week|this week|today)\\b/i,\n // Preferences\n /\\b(i (prefer|like|want|need|dislike))\\b/i,\n /\\b(my (preference|style|approach|way))\\b/i,\n // Commitments\n /\\b(i('ll| will)|promise|commit|guarantee)\\b/i,\n /\\b(scheduled|appointment|meeting|call)\\b/i,\n];\n\n/** Normal importance markers (0.4-0.7) */\nconst NORMAL_PATTERNS = [\n // Factual content\n /\\b(is|are|was|were|has|have|does|do)\\b/i,\n /\\b(because|since|therefore|thus|so)\\b/i,\n // Emotional content\n /\\b(happy|sad|frustrated|excited|worried|anxious)\\b/i,\n /\\b(feel|feeling|felt)\\b/i,\n // Technical details\n /\\b(version|api|endpoint|database|server|config)\\b/i,\n /\\b(function|class|method|variable|parameter)\\b/i,\n];\n\n/** Low importance markers (0.2-0.4) */\nconst LOW_PATTERNS = [\n // Uncertainty\n /\\b(maybe|perhaps|possibly|might|could be)\\b/i,\n /\\b(i think|i guess|not sure|uncertain)\\b/i,\n /\\b(probably|likely|seems like)\\b/i,\n // Hedging\n /\\b(kind of|sort of|somewhat|a bit)\\b/i,\n /\\b(in a way|to some extent)\\b/i,\n];\n\n/** Trivial content markers (0.0-0.2) */\nconst TRIVIAL_PATTERNS = [\n // Greetings and filler\n /^(hi|hello|hey|yo|sup|greetings)[.!,]?\\s*$/i,\n /^(ok|okay|k|sure|yes|no|yep|nope|yeah|nah)[.!]?\\s*$/i,\n /^(thanks|thank you|thx|ty|cheers)[.!]?\\s*$/i,\n /^(got it|understood|roger|copy|noted)[.!]?\\s*$/i,\n /^(bye|goodbye|later|see ya|ttyl)[.!]?\\s*$/i,\n /^(lol|haha|hehe|lmao|rofl)[.!]?\\s*$/i,\n /^(hmm+|uhh*|ahh*|err*|umm*)[.!]?\\s*$/i,\n // Very short content\n /^.{1,10}$/,\n];\n\n// ---------------------------------------------------------------------------\n// Category-based importance boosts\n// ---------------------------------------------------------------------------\n\nconst CATEGORY_BOOSTS: Record<MemoryCategory, number> = {\n correction: 0.15, // Corrections are always important\n principle: 0.12, // Durable rules/values\n rule: 0.11, // Causal IF→THEN rules\n procedure: 0.10, // Repeatable workflows (issue #519)\n preference: 0.10, // User preferences matter\n commitment: 0.10, // Promises/obligations\n reasoning_trace: 0.09, // Stored reasoning chains (issue #564)\n decision: 0.08, // Decisions with rationale\n relationship: 0.05, // Entity relationships\n skill: 0.05, // Capabilities\n moment: 0.03, // Emotional milestones\n entity: 0.02, // Entity facts\n fact: 0.00, // Base facts, no boost\n};\n\n// ---------------------------------------------------------------------------\n// Keyword extraction\n// ---------------------------------------------------------------------------\n\n/** Common stop words to filter out */\nconst STOP_WORDS = new Set([\n \"a\", \"an\", \"the\", \"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\",\n \"have\", \"has\", \"had\", \"do\", \"does\", \"did\", \"will\", \"would\", \"could\",\n \"should\", \"may\", \"might\", \"must\", \"shall\", \"can\", \"need\", \"dare\",\n \"ought\", \"used\", \"to\", \"of\", \"in\", \"for\", \"on\", \"with\", \"at\", \"by\",\n \"from\", \"as\", \"into\", \"through\", \"during\", \"before\", \"after\", \"above\",\n \"below\", \"between\", \"under\", \"again\", \"further\", \"then\", \"once\",\n \"here\", \"there\", \"when\", \"where\", \"why\", \"how\", \"all\", \"each\", \"few\",\n \"more\", \"most\", \"other\", \"some\", \"such\", \"no\", \"nor\", \"not\", \"only\",\n \"own\", \"same\", \"so\", \"than\", \"too\", \"very\", \"just\", \"and\", \"but\",\n \"or\", \"if\", \"because\", \"until\", \"while\", \"this\", \"that\", \"these\",\n \"those\", \"i\", \"me\", \"my\", \"myself\", \"we\", \"our\", \"ours\", \"ourselves\",\n \"you\", \"your\", \"yours\", \"yourself\", \"yourselves\", \"he\", \"him\", \"his\",\n \"himself\", \"she\", \"her\", \"hers\", \"herself\", \"it\", \"its\", \"itself\",\n \"they\", \"them\", \"their\", \"theirs\", \"themselves\", \"what\", \"which\",\n \"who\", \"whom\", \"whose\", \"am\", \"been\", \"being\", \"about\", \"against\",\n]);\n\n/**\n * Extract salient keywords from content.\n * Returns top N keywords sorted by relevance.\n */\nfunction extractKeywords(content: string, maxKeywords: number = 5): string[] {\n // Tokenize and normalize\n const words = content\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, \" \")\n .split(/\\s+/)\n .filter((w) => w.length >= 3 && !STOP_WORDS.has(w));\n\n // Count frequencies\n const freq = new Map<string, number>();\n for (const word of words) {\n freq.set(word, (freq.get(word) ?? 0) + 1);\n }\n\n // Sort by frequency, take top N\n return [...freq.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, maxKeywords)\n .map(([word]) => word);\n}\n\n// ---------------------------------------------------------------------------\n// Main scoring function\n// ---------------------------------------------------------------------------\n\n/**\n * Calculate importance score for a memory.\n * Pure local heuristics, zero LLM calls.\n */\nexport function scoreImportance(\n content: string,\n category: MemoryCategory,\n tags: string[] = [],\n): ImportanceScore {\n const reasons: string[] = [];\n let score = 0.5; // Start at normal baseline\n\n const lowerContent = content.toLowerCase();\n const contentLength = content.length;\n\n // Check for trivial content first (short-circuit)\n for (const pattern of TRIVIAL_PATTERNS) {\n if (pattern.test(content)) {\n return {\n score: 0.1,\n level: \"trivial\",\n reasons: [\"Trivial content (greeting, filler, or very short)\"],\n keywords: [],\n };\n }\n }\n\n // Check critical patterns\n for (const pattern of CRITICAL_PATTERNS) {\n if (pattern.test(content)) {\n score += 0.20;\n reasons.push(`Critical marker: ${pattern.source.slice(0, 30)}`);\n break; // Only count once per tier\n }\n }\n\n // Check high patterns\n for (const pattern of HIGH_PATTERNS) {\n if (pattern.test(content)) {\n score += 0.12;\n reasons.push(`High importance marker detected`);\n break;\n }\n }\n\n // Check low patterns (reduces score)\n for (const pattern of LOW_PATTERNS) {\n if (pattern.test(content)) {\n score -= 0.15;\n reasons.push(`Uncertainty/hedging detected`);\n break;\n }\n }\n\n // Category boost\n const categoryBoost = CATEGORY_BOOSTS[category] ?? 0;\n if (categoryBoost > 0) {\n score += categoryBoost;\n reasons.push(`Category boost: ${category}`);\n }\n\n // Length bonus (longer = more substance, capped)\n if (contentLength > 200) {\n const lengthBonus = Math.min((contentLength - 200) / 1000, 0.1);\n score += lengthBonus;\n if (lengthBonus > 0.05) {\n reasons.push(\"Substantial content length\");\n }\n }\n\n // Check for personal pronouns (signals personal relevance)\n if (/\\b(my|mine|i|i'm|i've|i'd|i'll)\\b/i.test(content)) {\n score += 0.05;\n reasons.push(\"Personal reference\");\n }\n\n // Check for numbers/specifics (concrete details)\n if (/\\b\\d{2,}\\b/.test(content) || /\\b(version|v\\d|api|config)\\b/i.test(content)) {\n score += 0.03;\n reasons.push(\"Contains specific details\");\n }\n\n // Tag-based boosts\n const importantTags = tags.filter((t) =>\n [\"important\", \"critical\", \"preference\", \"decision\", \"rule\", \"principle\"].includes(t.toLowerCase())\n );\n if (importantTags.length > 0) {\n score += 0.05 * importantTags.length;\n reasons.push(`Important tags: ${importantTags.join(\", \")}`);\n }\n\n // Clamp score to 0-1 range\n score = Math.max(0, Math.min(1, score));\n\n // Determine level from score\n let level: ImportanceLevel;\n if (score >= 0.9) {\n level = \"critical\";\n } else if (score >= 0.7) {\n level = \"high\";\n } else if (score >= 0.4) {\n level = \"normal\";\n } else if (score >= 0.2) {\n level = \"low\";\n } else {\n level = \"trivial\";\n }\n\n // Extract keywords\n const keywords = extractKeywords(content);\n\n return {\n score: Math.round(score * 100) / 100, // Round to 2 decimal places\n level,\n reasons: reasons.slice(0, 5), // Cap at 5 reasons\n keywords,\n };\n}\n\n/**\n * Recompute importance for an existing memory file using current local heuristics.\n */\nexport function rescoreMemoryImportance(memory: MemoryFile): ImportanceScore {\n return scoreImportance(memory.content, memory.frontmatter.category, memory.frontmatter.tags ?? []);\n}\n\n/**\n * Get importance level from numeric score.\n */\nexport function importanceLevel(score: number): ImportanceLevel {\n if (score >= 0.9) return \"critical\";\n if (score >= 0.7) return \"high\";\n if (score >= 0.4) return \"normal\";\n if (score >= 0.2) return \"low\";\n return \"trivial\";\n}\n\n// ---------------------------------------------------------------------------\n// Importance threshold helper (issue #372)\n// ---------------------------------------------------------------------------\n\n/**\n * Ordering for importance levels used by the extraction write gate.\n * Higher indices mean more important.\n */\nconst IMPORTANCE_LEVEL_RANK: Record<ImportanceLevel, number> = {\n trivial: 0,\n low: 1,\n normal: 2,\n high: 3,\n critical: 4,\n};\n\n/**\n * Return true if `candidate` meets or exceeds `threshold`. Used by the\n * extraction write gate in orchestrator.persistExtraction() to drop trivial\n * content before it is written to the memory store.\n *\n * Note: callers should pass the ALREADY-BOOSTED level returned by\n * scoreImportance(), because category boosts (e.g. corrections) are applied\n * inside scoreImportance() before the level is derived.\n */\nexport function isAboveImportanceThreshold(\n candidate: ImportanceLevel,\n threshold: ImportanceLevel,\n): boolean {\n return IMPORTANCE_LEVEL_RANK[candidate] >= IMPORTANCE_LEVEL_RANK[threshold];\n}\n"],"mappings":";AAeA,IAAM,oBAAoB;AAAA;AAAA,EAExB;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AACF;AAGA,IAAM,gBAAgB;AAAA;AAAA,EAEpB;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AACF;AAgBA,IAAM,eAAe;AAAA;AAAA,EAEnB;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AACF;AAGA,IAAM,mBAAmB;AAAA;AAAA,EAEvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AACF;AAMA,IAAM,kBAAkD;AAAA,EACtD,YAAY;AAAA;AAAA,EACZ,WAAW;AAAA;AAAA,EACX,MAAM;AAAA;AAAA,EACN,WAAW;AAAA;AAAA,EACX,YAAY;AAAA;AAAA,EACZ,YAAY;AAAA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fig
14
+ } from "./chunk-BK2EFTE2.js";
12
15
  import {
13
16
  resolveCommitmentLedgerDir,
14
17
  validateCommitmentLedgerEntry
15
18
  } from "./chunk-FYIYMQ5N.js";
16
- import {
17
- parseConfig
18
- } from "./chunk-OJFGVJS6.js";
19
19
  import {
20
20
  assertIsoRecordedAt,
21
21
  assertSafePathSegment,
@@ -268,4 +268,4 @@ export {
268
268
  recordResumeBundle,
269
269
  getResumeBundleStatus
270
270
  };
271
- //# sourceMappingURL=chunk-AYPYCLR7.js.map
271
+ //# sourceMappingURL=chunk-KUB6JU6H.js.map
@@ -0,0 +1,173 @@
1
+ // src/recall-xray.ts
2
+ import { randomUUID } from "crypto";
3
+ var RECALL_XRAY_SERVED_BY_VALUES = [
4
+ "direct-answer",
5
+ "hybrid",
6
+ "graph",
7
+ "recent-scan",
8
+ "procedural",
9
+ "review-context"
10
+ ];
11
+ function isRecallXrayServedBy(value) {
12
+ return typeof value === "string" && RECALL_XRAY_SERVED_BY_VALUES.includes(value);
13
+ }
14
+ function buildXraySnapshot(input) {
15
+ const now = input.now ?? Date.now;
16
+ const snapshotIdGenerator = input.snapshotIdGenerator ?? randomUUID;
17
+ const results = Array.isArray(input.results) ? input.results.map(cloneResult) : [];
18
+ const filters = Array.isArray(input.filters) ? input.filters.map(cloneFilter) : [];
19
+ const budgetChars = nonNegativeInt(input.budget?.chars);
20
+ const budgetUsed = nonNegativeInt(input.budget?.used);
21
+ const tierExplain = input.tierExplain && typeof input.tierExplain === "object" ? cloneTierExplain(input.tierExplain) : null;
22
+ return {
23
+ schemaVersion: "1",
24
+ query: typeof input.query === "string" ? input.query : "",
25
+ snapshotId: snapshotIdGenerator(),
26
+ capturedAt: now(),
27
+ tierExplain,
28
+ results,
29
+ filters,
30
+ budget: { chars: budgetChars, used: budgetUsed },
31
+ sessionKey: nonEmptyString(input.sessionKey),
32
+ namespace: nonEmptyString(input.namespace),
33
+ traceId: nonEmptyString(input.traceId)
34
+ };
35
+ }
36
+ var RecallXrayBuilder = class {
37
+ query;
38
+ sessionKey;
39
+ namespace;
40
+ traceId;
41
+ tierExplain = null;
42
+ results = [];
43
+ filters = [];
44
+ budgetChars = 0;
45
+ budgetUsed = 0;
46
+ constructor(opts) {
47
+ this.query = typeof opts.query === "string" ? opts.query : "";
48
+ this.sessionKey = nonEmptyString(opts.sessionKey);
49
+ this.namespace = nonEmptyString(opts.namespace);
50
+ this.traceId = nonEmptyString(opts.traceId);
51
+ }
52
+ setNamespace(namespace) {
53
+ this.namespace = nonEmptyString(namespace);
54
+ }
55
+ setTraceId(traceId) {
56
+ this.traceId = nonEmptyString(traceId);
57
+ }
58
+ setTierExplain(tierExplain) {
59
+ this.tierExplain = tierExplain && typeof tierExplain === "object" ? cloneTierExplain(tierExplain) : null;
60
+ }
61
+ setBudget(budget) {
62
+ this.budgetChars = nonNegativeInt(budget.chars);
63
+ this.budgetUsed = nonNegativeInt(budget.used);
64
+ }
65
+ recordResult(result) {
66
+ this.results.push(cloneResult(result));
67
+ }
68
+ recordFilter(filter) {
69
+ this.filters.push(cloneFilter(filter));
70
+ }
71
+ build(opts = {}) {
72
+ return buildXraySnapshot({
73
+ query: this.query,
74
+ tierExplain: this.tierExplain,
75
+ results: this.results,
76
+ filters: this.filters,
77
+ budget: { chars: this.budgetChars, used: this.budgetUsed },
78
+ sessionKey: this.sessionKey,
79
+ namespace: this.namespace,
80
+ traceId: this.traceId,
81
+ now: opts.now,
82
+ snapshotIdGenerator: opts.snapshotIdGenerator
83
+ });
84
+ }
85
+ };
86
+ function cloneResult(result) {
87
+ if (!result || typeof result !== "object") {
88
+ throw new TypeError("RecallXrayResult must be an object");
89
+ }
90
+ if (!isRecallXrayServedBy(result.servedBy)) {
91
+ throw new TypeError(
92
+ `RecallXrayResult.servedBy must be one of ${RECALL_XRAY_SERVED_BY_VALUES.join(
93
+ ", "
94
+ )}; got ${JSON.stringify(result.servedBy)}`
95
+ );
96
+ }
97
+ const memoryId = typeof result.memoryId === "string" ? result.memoryId : "";
98
+ const path = typeof result.path === "string" ? result.path : "";
99
+ const admittedBy = Array.isArray(result.admittedBy) ? result.admittedBy.filter((x) => typeof x === "string") : [];
100
+ const graphPath = Array.isArray(result.graphPath) ? result.graphPath.filter((x) => typeof x === "string") : void 0;
101
+ const auditEntryId = nonEmptyString(result.auditEntryId);
102
+ const rejectedBy = nonEmptyString(result.rejectedBy);
103
+ const scoreDecomposition = cloneScoreDecomposition(result.scoreDecomposition);
104
+ const out = {
105
+ memoryId,
106
+ path,
107
+ servedBy: result.servedBy,
108
+ scoreDecomposition,
109
+ admittedBy
110
+ };
111
+ if (graphPath !== void 0) out.graphPath = graphPath;
112
+ if (auditEntryId !== void 0) out.auditEntryId = auditEntryId;
113
+ if (rejectedBy !== void 0) out.rejectedBy = rejectedBy;
114
+ return out;
115
+ }
116
+ function cloneFilter(filter) {
117
+ if (!filter || typeof filter !== "object") {
118
+ throw new TypeError("RecallFilterTrace must be an object");
119
+ }
120
+ const out = {
121
+ name: typeof filter.name === "string" ? filter.name : "",
122
+ considered: nonNegativeInt(filter.considered),
123
+ admitted: nonNegativeInt(filter.admitted)
124
+ };
125
+ const reason = nonEmptyString(filter.reason);
126
+ if (reason !== void 0) out.reason = reason;
127
+ return out;
128
+ }
129
+ function cloneScoreDecomposition(value) {
130
+ if (!value || typeof value !== "object") {
131
+ return { final: 0 };
132
+ }
133
+ const out = {
134
+ final: finiteNumber(value.final) ?? 0
135
+ };
136
+ const vector = finiteNumber(value.vector);
137
+ if (vector !== void 0) out.vector = vector;
138
+ const bm25 = finiteNumber(value.bm25);
139
+ if (bm25 !== void 0) out.bm25 = bm25;
140
+ const importance = finiteNumber(value.importance);
141
+ if (importance !== void 0) out.importance = importance;
142
+ const mmrPenalty = finiteNumber(value.mmrPenalty);
143
+ if (mmrPenalty !== void 0) out.mmrPenalty = mmrPenalty;
144
+ const tierPrior = finiteNumber(value.tierPrior);
145
+ if (tierPrior !== void 0) out.tierPrior = tierPrior;
146
+ return out;
147
+ }
148
+ function cloneTierExplain(tierExplain) {
149
+ return structuredClone(tierExplain);
150
+ }
151
+ function nonNegativeInt(value) {
152
+ if (typeof value !== "number" || !Number.isFinite(value)) return 0;
153
+ if (value <= 0) return 0;
154
+ return Math.floor(value);
155
+ }
156
+ function finiteNumber(value) {
157
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
158
+ return value;
159
+ }
160
+ function nonEmptyString(value) {
161
+ if (typeof value !== "string") return void 0;
162
+ const trimmed = value.trim();
163
+ if (trimmed.length === 0) return void 0;
164
+ return trimmed;
165
+ }
166
+
167
+ export {
168
+ RECALL_XRAY_SERVED_BY_VALUES,
169
+ isRecallXrayServedBy,
170
+ buildXraySnapshot,
171
+ RecallXrayBuilder
172
+ };
173
+ //# sourceMappingURL=chunk-KVBLZUKV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/recall-xray.ts"],"sourcesContent":["/**\n * Recall X-ray snapshot schema (issue #570, PR 1).\n *\n * The X-ray surface is the unified, per-result attribution document that\n * merges the tier that served each memory, its score decomposition, any\n * graph path, an audit entry id, and the exact filter/eligibility ladder\n * that either admitted or rejected each candidate. This file defines the\n * schema and an in-memory builder + builder-state helper.\n *\n * Scope for PR 1 (this slice):\n * - Types only + pure builder functions (no IO, no rendering).\n * - Orchestrator plumbing captures a snapshot when the caller passes\n * `xrayCapture: true`. No behavior change when the flag is absent.\n * - NO new public surfaces here — CLI/HTTP/MCP land in later slices.\n *\n * The shared renderer lands in PR 2 at `recall-xray-renderer.ts`. Do not\n * fork formatting logic into other surfaces; extend the renderer.\n */\n\nimport { randomUUID } from \"node:crypto\";\n\nimport type { RecallTierExplain } from \"./types.js\";\n\n/**\n * Which retrieval source produced a given result. This is the X-ray\n * tier ladder called out in issue #570 and is *distinct* from the\n * `RetrievalTier` enum (which describes issue #518's tier-explain\n * block). Keeping the sets separate lets the two observability\n * surfaces evolve without conflating their vocabularies:\n *\n * - `RetrievalTier` — direct-answer eligibility ladder.\n * - `RecallXrayServedBy` — which source materialized each result.\n */\nexport type RecallXrayServedBy =\n | \"direct-answer\"\n | \"hybrid\"\n | \"graph\"\n | \"recent-scan\"\n | \"procedural\"\n | \"review-context\";\n\nexport const RECALL_XRAY_SERVED_BY_VALUES: readonly RecallXrayServedBy[] = [\n \"direct-answer\",\n \"hybrid\",\n \"graph\",\n \"recent-scan\",\n \"procedural\",\n \"review-context\",\n] as const;\n\nexport function isRecallXrayServedBy(\n value: unknown,\n): value is RecallXrayServedBy {\n return (\n typeof value === \"string\" &&\n (RECALL_XRAY_SERVED_BY_VALUES as readonly string[]).includes(value)\n );\n}\n\n/**\n * Score decomposition for a single X-ray result.\n *\n * All fields are optional because different tiers populate different\n * terms: `hybrid` reports vector + bm25 + mmr penalty, `direct-answer`\n * reports importance + tier prior, etc. The only guaranteed field is\n * `final`, which is the post-combination score used for ordering.\n */\nexport interface RecallXrayScoreDecomposition {\n vector?: number;\n bm25?: number;\n importance?: number;\n mmrPenalty?: number;\n tierPrior?: number;\n final: number;\n}\n\n/**\n * Per-result breakdown inside an X-ray snapshot.\n */\nexport interface RecallXrayResult {\n memoryId: string;\n path: string;\n servedBy: RecallXrayServedBy;\n scoreDecomposition: RecallXrayScoreDecomposition;\n graphPath?: string[];\n auditEntryId?: string;\n /** Human-readable list of filters the candidate *passed*. */\n admittedBy: string[];\n /**\n * First filter that *would have* rejected the candidate, or undefined\n * when the candidate was admitted without a rejection trace. When\n * present, `admittedBy` may still contain filters the candidate passed\n * before the rejecting gate; consumers should render both.\n */\n rejectedBy?: string;\n}\n\n/**\n * Trace entry for a filter the orchestrator evaluated during recall.\n * Captures the name of the filter, how many candidates it saw, and how\n * many it let through. Used by X-ray consumers to render the filter\n * ladder above the per-result breakdown.\n */\nexport interface RecallFilterTrace {\n name: string;\n considered: number;\n admitted: number;\n /** Optional human-readable reason for any rejections. */\n reason?: string;\n}\n\n/**\n * The unified X-ray snapshot. CLI, HTTP, and MCP surfaces all render\n * this same shape through the shared renderer (CLAUDE.md rule 22).\n */\nexport interface RecallXraySnapshot {\n /** Stable v1 tag so downstream consumers can version-gate their parsers. */\n schemaVersion: \"1\";\n query: string;\n /** UUID minted per capture; unique across snapshots within a process. */\n snapshotId: string;\n /** Epoch milliseconds the snapshot was captured. */\n capturedAt: number;\n /**\n * Tier-explain block from issue #518, carried verbatim when present.\n * `null` means direct-answer tier did not run (disabled, or another\n * tier served the query).\n */\n tierExplain: RecallTierExplain | null;\n results: RecallXrayResult[];\n filters: RecallFilterTrace[];\n /**\n * Character budget accounting for the final assembled recall payload.\n * `used` is the rendered-context length; `chars` is the cap. Both are\n * non-negative integers in `[0, 2**31)`.\n */\n budget: { chars: number; used: number };\n /** Optional session-scope fields carried for downstream filtering. */\n sessionKey?: string;\n namespace?: string;\n traceId?: string;\n}\n\n// ─── Builder ──────────────────────────────────────────────────────────────\n\nexport interface BuildXraySnapshotInput {\n query: string;\n tierExplain?: RecallTierExplain | null;\n results?: RecallXrayResult[];\n filters?: RecallFilterTrace[];\n budget?: { chars?: number; used?: number };\n sessionKey?: string;\n namespace?: string;\n traceId?: string;\n /** Optional injected timestamp for deterministic tests. */\n now?: () => number;\n /** Optional injected id generator for deterministic tests. */\n snapshotIdGenerator?: () => string;\n}\n\n/**\n * Build a `RecallXraySnapshot` from explicit input fields. Pure\n * function; safe to call from anywhere. All array/object inputs are\n * shallow-copied so caller mutation after build cannot tear the\n * returned snapshot.\n */\nexport function buildXraySnapshot(\n input: BuildXraySnapshotInput,\n): RecallXraySnapshot {\n const now = input.now ?? Date.now;\n const snapshotIdGenerator = input.snapshotIdGenerator ?? randomUUID;\n\n const results = Array.isArray(input.results)\n ? input.results.map(cloneResult)\n : [];\n const filters = Array.isArray(input.filters)\n ? input.filters.map(cloneFilter)\n : [];\n\n const budgetChars = nonNegativeInt(input.budget?.chars);\n const budgetUsed = nonNegativeInt(input.budget?.used);\n\n const tierExplain =\n input.tierExplain && typeof input.tierExplain === \"object\"\n ? cloneTierExplain(input.tierExplain)\n : null;\n\n return {\n schemaVersion: \"1\",\n query: typeof input.query === \"string\" ? input.query : \"\",\n snapshotId: snapshotIdGenerator(),\n capturedAt: now(),\n tierExplain,\n results,\n filters,\n budget: { chars: budgetChars, used: budgetUsed },\n sessionKey: nonEmptyString(input.sessionKey),\n namespace: nonEmptyString(input.namespace),\n traceId: nonEmptyString(input.traceId),\n };\n}\n\n/**\n * Mutable builder used by the orchestrator to accumulate X-ray fields\n * as recall progresses. Call `build()` to get the finalized\n * immutable-ish snapshot. All inputs are validated at insert time so\n * a malformed entry cannot poison the snapshot later.\n */\nexport class RecallXrayBuilder {\n private readonly query: string;\n private readonly sessionKey: string | undefined;\n private namespace: string | undefined;\n private traceId: string | undefined;\n private tierExplain: RecallTierExplain | null = null;\n private readonly results: RecallXrayResult[] = [];\n private readonly filters: RecallFilterTrace[] = [];\n private budgetChars = 0;\n private budgetUsed = 0;\n\n constructor(opts: {\n query: string;\n sessionKey?: string;\n namespace?: string;\n traceId?: string;\n }) {\n this.query = typeof opts.query === \"string\" ? opts.query : \"\";\n this.sessionKey = nonEmptyString(opts.sessionKey);\n this.namespace = nonEmptyString(opts.namespace);\n this.traceId = nonEmptyString(opts.traceId);\n }\n\n setNamespace(namespace: string | undefined): void {\n this.namespace = nonEmptyString(namespace);\n }\n\n setTraceId(traceId: string | undefined): void {\n this.traceId = nonEmptyString(traceId);\n }\n\n setTierExplain(tierExplain: RecallTierExplain | null | undefined): void {\n this.tierExplain =\n tierExplain && typeof tierExplain === \"object\"\n ? cloneTierExplain(tierExplain)\n : null;\n }\n\n setBudget(budget: { chars?: number; used?: number }): void {\n this.budgetChars = nonNegativeInt(budget.chars);\n this.budgetUsed = nonNegativeInt(budget.used);\n }\n\n recordResult(result: RecallXrayResult): void {\n this.results.push(cloneResult(result));\n }\n\n recordFilter(filter: RecallFilterTrace): void {\n this.filters.push(cloneFilter(filter));\n }\n\n build(opts: {\n now?: () => number;\n snapshotIdGenerator?: () => string;\n } = {}): RecallXraySnapshot {\n return buildXraySnapshot({\n query: this.query,\n tierExplain: this.tierExplain,\n results: this.results,\n filters: this.filters,\n budget: { chars: this.budgetChars, used: this.budgetUsed },\n sessionKey: this.sessionKey,\n namespace: this.namespace,\n traceId: this.traceId,\n now: opts.now,\n snapshotIdGenerator: opts.snapshotIdGenerator,\n });\n }\n}\n\n// ─── Internals ────────────────────────────────────────────────────────────\n\nfunction cloneResult(result: RecallXrayResult): RecallXrayResult {\n if (!result || typeof result !== \"object\") {\n throw new TypeError(\"RecallXrayResult must be an object\");\n }\n if (!isRecallXrayServedBy(result.servedBy)) {\n throw new TypeError(\n `RecallXrayResult.servedBy must be one of ${RECALL_XRAY_SERVED_BY_VALUES.join(\n \", \",\n )}; got ${JSON.stringify(result.servedBy)}`,\n );\n }\n const memoryId = typeof result.memoryId === \"string\" ? result.memoryId : \"\";\n const path = typeof result.path === \"string\" ? result.path : \"\";\n const admittedBy = Array.isArray(result.admittedBy)\n ? result.admittedBy.filter((x): x is string => typeof x === \"string\")\n : [];\n const graphPath = Array.isArray(result.graphPath)\n ? result.graphPath.filter((x): x is string => typeof x === \"string\")\n : undefined;\n const auditEntryId = nonEmptyString(result.auditEntryId);\n const rejectedBy = nonEmptyString(result.rejectedBy);\n const scoreDecomposition = cloneScoreDecomposition(result.scoreDecomposition);\n const out: RecallXrayResult = {\n memoryId,\n path,\n servedBy: result.servedBy,\n scoreDecomposition,\n admittedBy,\n };\n if (graphPath !== undefined) out.graphPath = graphPath;\n if (auditEntryId !== undefined) out.auditEntryId = auditEntryId;\n if (rejectedBy !== undefined) out.rejectedBy = rejectedBy;\n return out;\n}\n\nfunction cloneFilter(filter: RecallFilterTrace): RecallFilterTrace {\n if (!filter || typeof filter !== \"object\") {\n throw new TypeError(\"RecallFilterTrace must be an object\");\n }\n const out: RecallFilterTrace = {\n name: typeof filter.name === \"string\" ? filter.name : \"\",\n considered: nonNegativeInt(filter.considered),\n admitted: nonNegativeInt(filter.admitted),\n };\n const reason = nonEmptyString(filter.reason);\n if (reason !== undefined) out.reason = reason;\n return out;\n}\n\nfunction cloneScoreDecomposition(\n value: RecallXrayScoreDecomposition | undefined,\n): RecallXrayScoreDecomposition {\n if (!value || typeof value !== \"object\") {\n return { final: 0 };\n }\n const out: RecallXrayScoreDecomposition = {\n final: finiteNumber(value.final) ?? 0,\n };\n const vector = finiteNumber(value.vector);\n if (vector !== undefined) out.vector = vector;\n const bm25 = finiteNumber(value.bm25);\n if (bm25 !== undefined) out.bm25 = bm25;\n const importance = finiteNumber(value.importance);\n if (importance !== undefined) out.importance = importance;\n const mmrPenalty = finiteNumber(value.mmrPenalty);\n if (mmrPenalty !== undefined) out.mmrPenalty = mmrPenalty;\n const tierPrior = finiteNumber(value.tierPrior);\n if (tierPrior !== undefined) out.tierPrior = tierPrior;\n return out;\n}\n\nfunction cloneTierExplain(tierExplain: RecallTierExplain): RecallTierExplain {\n // Use structuredClone so future RecallTierExplain additions do not\n // silently share references through hand-enumerated fields. The\n // payload is JSON-shaped.\n return structuredClone(tierExplain);\n}\n\nfunction nonNegativeInt(value: unknown): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return 0;\n if (value <= 0) return 0;\n return Math.floor(value);\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return undefined;\n return value;\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (trimmed.length === 0) return undefined;\n return trimmed;\n}\n"],"mappings":";AAmBA,SAAS,kBAAkB;AAsBpB,IAAM,+BAA8D;AAAA,EACzE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,qBACd,OAC6B;AAC7B,SACE,OAAO,UAAU,YAChB,6BAAmD,SAAS,KAAK;AAEtE;AA6GO,SAAS,kBACd,OACoB;AACpB,QAAM,MAAM,MAAM,OAAO,KAAK;AAC9B,QAAM,sBAAsB,MAAM,uBAAuB;AAEzD,QAAM,UAAU,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UAAU;AAChD,MAAI,eAAe,OAAW,KAAI,aAAa;AAC/C,QAAM,YAAY,aAAa,MAAM,SAAS;AAC9C,MAAI,cAAc,OAAW,KAAI,YAAY;AAC7C,SAAO;AACT;AAEA,SAAS,iBAAiB,aAAmD;AAI3E,SAAO,gBAAgB,WAAW;AACpC;AAEA,SAAS,eAAe,OAAwB;AAC9C,MAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACjE,MAAI,SAAS,EAAG,QAAO;AACvB,SAAO,KAAK,MAAM,KAAK;AACzB;AAEA,SAAS,aAAa,OAAoC;AACxD,MAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACjE,SAAO;AACT;AAEA,SAAS,eAAe,OAAoC;AAC1D,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,SAAO;AACT;","names":[]}
@@ -0,0 +1,51 @@
1
+ // src/recall-audit.ts
2
+ import { appendFile, mkdir, readdir, rm } from "fs/promises";
3
+ import path from "path";
4
+ function formatIsoDate(ts) {
5
+ const normalized = new Date(ts);
6
+ if (Number.isNaN(normalized.getTime())) {
7
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
8
+ }
9
+ return normalized.toISOString().slice(0, 10);
10
+ }
11
+ function buildRecallAuditPath(rootDir, ts, sessionKey) {
12
+ const safeSessionKey = encodeURIComponent(sessionKey);
13
+ return path.join(rootDir, "transcripts", formatIsoDate(ts), `${safeSessionKey}.jsonl`);
14
+ }
15
+ async function appendRecallAuditEntry(rootDir, entry) {
16
+ const filePath = buildRecallAuditPath(rootDir, entry.ts, entry.sessionKey);
17
+ await mkdir(path.dirname(filePath), { recursive: true });
18
+ await appendFile(filePath, `${JSON.stringify(entry)}
19
+ `, "utf8");
20
+ return filePath;
21
+ }
22
+ async function pruneRecallAuditEntries(rootDir, retentionDays, now = /* @__PURE__ */ new Date()) {
23
+ const transcriptsDir = path.join(rootDir, "transcripts");
24
+ const removed = [];
25
+ const cutoff = new Date(now);
26
+ cutoff.setUTCHours(0, 0, 0, 0);
27
+ cutoff.setUTCDate(cutoff.getUTCDate() - Math.max(1, Math.floor(retentionDays)));
28
+ let entries;
29
+ try {
30
+ entries = await readdir(transcriptsDir, { withFileTypes: true });
31
+ } catch {
32
+ return removed;
33
+ }
34
+ for (const entry of entries) {
35
+ if (!entry.isDirectory()) continue;
36
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(entry.name)) continue;
37
+ const day = /* @__PURE__ */ new Date(`${entry.name}T00:00:00.000Z`);
38
+ if (Number.isNaN(day.getTime()) || day >= cutoff) continue;
39
+ const dirPath = path.join(transcriptsDir, entry.name);
40
+ await rm(dirPath, { recursive: true, force: true });
41
+ removed.push(dirPath);
42
+ }
43
+ return removed;
44
+ }
45
+
46
+ export {
47
+ buildRecallAuditPath,
48
+ appendRecallAuditEntry,
49
+ pruneRecallAuditEntries
50
+ };
51
+ //# sourceMappingURL=chunk-LBLXEFWK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/recall-audit.ts"],"sourcesContent":["import type { Dirent } from \"node:fs\";\nimport { appendFile, mkdir, readdir, rm } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport interface RecallAuditEntry {\n ts: string;\n sessionKey: string;\n agentId: string;\n trigger: string;\n queryText: string;\n candidateMemoryIds: string[];\n summary: string | null;\n injectedChars: number;\n toggleState: \"enabled\" | \"disabled-primary\" | \"disabled-secondary\";\n latencyMs?: number;\n plannerMode?: string;\n requestedMode?: string;\n fallbackUsed?: boolean;\n}\n\nfunction formatIsoDate(ts: string): string {\n const normalized = new Date(ts);\n if (Number.isNaN(normalized.getTime())) {\n return new Date().toISOString().slice(0, 10);\n }\n return normalized.toISOString().slice(0, 10);\n}\n\nexport function buildRecallAuditPath(rootDir: string, ts: string, sessionKey: string): string {\n const safeSessionKey = encodeURIComponent(sessionKey);\n return path.join(rootDir, \"transcripts\", formatIsoDate(ts), `${safeSessionKey}.jsonl`);\n}\n\nexport async function appendRecallAuditEntry(\n rootDir: string,\n entry: RecallAuditEntry,\n): Promise<string> {\n const filePath = buildRecallAuditPath(rootDir, entry.ts, entry.sessionKey);\n await mkdir(path.dirname(filePath), { recursive: true });\n await appendFile(filePath, `${JSON.stringify(entry)}\\n`, \"utf8\");\n return filePath;\n}\n\nexport async function pruneRecallAuditEntries(\n rootDir: string,\n retentionDays: number,\n now: Date = new Date(),\n): Promise<string[]> {\n const transcriptsDir = path.join(rootDir, \"transcripts\");\n const removed: string[] = [];\n const cutoff = new Date(now);\n cutoff.setUTCHours(0, 0, 0, 0);\n cutoff.setUTCDate(cutoff.getUTCDate() - Math.max(1, Math.floor(retentionDays)));\n let entries: Dirent[];\n try {\n entries = await readdir(transcriptsDir, { withFileTypes: true });\n } catch {\n return removed;\n }\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(entry.name)) continue;\n const day = new Date(`${entry.name}T00:00:00.000Z`);\n if (Number.isNaN(day.getTime()) || day >= cutoff) continue;\n const dirPath = path.join(transcriptsDir, entry.name);\n await rm(dirPath, { recursive: true, force: true });\n removed.push(dirPath);\n }\n\n return removed;\n}\n"],"mappings":";AACA,SAAS,YAAY,OAAO,SAAS,UAAU;AAC/C,OAAO,UAAU;AAkBjB,SAAS,cAAc,IAAoB;AACzC,QAAM,aAAa,IAAI,KAAK,EAAE;AAC9B,MAAI,OAAO,MAAM,WAAW,QAAQ,CAAC,GAAG;AACtC,YAAO,oBAAI,KAAK,GAAE,YAAY,EAAE,MAAM,GAAG,EAAE;AAAA,EAC7C;AACA,SAAO,WAAW,YAAY,EAAE,MAAM,GAAG,EAAE;AAC7C;AAEO,SAAS,qBAAqB,SAAiB,IAAY,YAA4B;AAC5F,QAAM,iBAAiB,mBAAmB,UAAU;AACpD,SAAO,KAAK,KAAK,SAAS,eA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