@remnic/core 1.1.8 → 1.1.10

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 (267) hide show
  1. package/dist/access-cli.js +44 -41
  2. package/dist/access-cli.js.map +1 -1
  3. package/dist/access-http.d.ts +8 -7
  4. package/dist/access-http.js +20 -17
  5. package/dist/access-mcp.d.ts +8 -7
  6. package/dist/access-mcp.js +19 -16
  7. package/dist/{access-service-C0Rkioec.d.ts → access-service-BTTNyo1i.d.ts} +11 -9
  8. package/dist/access-service.d.ts +8 -7
  9. package/dist/access-service.js +18 -15
  10. package/dist/active-memory-bridge.d.ts +2 -1
  11. package/dist/active-recall.d.ts +3 -2
  12. package/dist/active-recall.js +2 -2
  13. package/dist/active-recall.js.map +1 -1
  14. package/dist/behavior-learner.d.ts +2 -1
  15. package/dist/behavior-signals.d.ts +2 -1
  16. package/dist/bootstrap.d.ts +7 -6
  17. package/dist/briefing.d.ts +3 -2
  18. package/dist/briefing.js +6 -6
  19. package/dist/buffer-surprise-report.d.ts +2 -1
  20. package/dist/buffer.d.ts +3 -2
  21. package/dist/calibration.d.ts +4 -1
  22. package/dist/calibration.js +10 -5
  23. package/dist/calibration.js.map +1 -1
  24. package/dist/causal-behavior.d.ts +2 -1
  25. package/dist/causal-consolidation.d.ts +5 -2
  26. package/dist/causal-consolidation.js +17 -11
  27. package/dist/causal-consolidation.js.map +1 -1
  28. package/dist/{chunk-AV2WSYZY.js → chunk-2YMTO4ZJ.js} +2 -2
  29. package/dist/{chunk-SYWJJTNL.js → chunk-363MWCD3.js} +42 -42
  30. package/dist/{chunk-65ZPH7QA.js → chunk-36CTNQY7.js} +7 -7
  31. package/dist/{chunk-GZCUW5IC.js → chunk-3IQ2TR4N.js} +5 -5
  32. package/dist/chunk-3IQ2TR4N.js.map +1 -0
  33. package/dist/{chunk-TUFG6VXY.js → chunk-4DWOBS2A.js} +2 -2
  34. package/dist/chunk-4DWOBS2A.js.map +1 -0
  35. package/dist/{chunk-SRIDOT64.js → chunk-4DXC6HQQ.js} +6 -4
  36. package/dist/chunk-4DXC6HQQ.js.map +1 -0
  37. package/dist/{chunk-L2IO2QPY.js → chunk-4IS4SXIQ.js} +17 -13
  38. package/dist/chunk-4IS4SXIQ.js.map +1 -0
  39. package/dist/{chunk-RJSVRPNU.js → chunk-57QNCUEZ.js} +19 -12
  40. package/dist/chunk-57QNCUEZ.js.map +1 -0
  41. package/dist/{chunk-GRDDGNYQ.js → chunk-5GCNE7CN.js} +105 -499
  42. package/dist/chunk-5GCNE7CN.js.map +1 -0
  43. package/dist/{chunk-LOBRX7VD.js → chunk-5UM2VJ6D.js} +12 -1
  44. package/dist/chunk-5UM2VJ6D.js.map +1 -0
  45. package/dist/{chunk-XVOIMCVW.js → chunk-6XA7UN4Z.js} +2 -2
  46. package/dist/{chunk-QJZ77K7F.js → chunk-6Z6UH6TK.js} +26 -12
  47. package/dist/chunk-6Z6UH6TK.js.map +1 -0
  48. package/dist/{chunk-ODWDQNRE.js → chunk-7SI52C65.js} +7 -3
  49. package/dist/chunk-7SI52C65.js.map +1 -0
  50. package/dist/{chunk-FIXIX6DE.js → chunk-C5HUWVH2.js} +33 -43
  51. package/dist/chunk-C5HUWVH2.js.map +1 -0
  52. package/dist/{chunk-NN3TS5BM.js → chunk-D54LZC5L.js} +4 -4
  53. package/dist/{chunk-KNQ5YJTO.js → chunk-ERUDW6DU.js} +209 -1
  54. package/dist/chunk-ERUDW6DU.js.map +1 -0
  55. package/dist/{chunk-E27HOXMX.js → chunk-EYNQTST2.js} +2 -2
  56. package/dist/chunk-FVQJYWH7.js +52 -0
  57. package/dist/chunk-FVQJYWH7.js.map +1 -0
  58. package/dist/{chunk-3FPTCC3Z.js → chunk-GVPWB7EY.js} +2 -2
  59. package/dist/chunk-HJYHRE4S.js +647 -0
  60. package/dist/chunk-HJYHRE4S.js.map +1 -0
  61. package/dist/{chunk-SWRJFKYW.js → chunk-I6BQZSML.js} +5 -5
  62. package/dist/chunk-IBX3VFOM.js +446 -0
  63. package/dist/chunk-IBX3VFOM.js.map +1 -0
  64. package/dist/{chunk-STB3GUYU.js → chunk-KBYWQWSB.js} +8 -8
  65. package/dist/chunk-KWBPHZUU.js +83 -0
  66. package/dist/chunk-KWBPHZUU.js.map +1 -0
  67. package/dist/{chunk-MYH2IBSP.js → chunk-LIO5X3CM.js} +3 -3
  68. package/dist/{chunk-XGX4TUF6.js → chunk-MCC6KDQF.js} +5 -5
  69. package/dist/{chunk-4KAN3GZ3.js → chunk-NN2DKE4T.js} +1 -1
  70. package/dist/chunk-NN2DKE4T.js.map +1 -0
  71. package/dist/{chunk-R2XRID2N.js → chunk-NN3LPQ5D.js} +5 -5
  72. package/dist/chunk-NN3LPQ5D.js.map +1 -0
  73. package/dist/{chunk-WXPPM426.js → chunk-O4XJUPSF.js} +2 -2
  74. package/dist/{chunk-WSZIHQBK.js → chunk-P77UEOU2.js} +4 -1
  75. package/dist/{chunk-WSZIHQBK.js.map → chunk-P77UEOU2.js.map} +1 -1
  76. package/dist/{chunk-RLV2F337.js → chunk-PB5KW5PL.js} +2 -2
  77. package/dist/{chunk-S5SQDIF5.js → chunk-PHNGXFQ6.js} +7 -5
  78. package/dist/chunk-PHNGXFQ6.js.map +1 -0
  79. package/dist/{chunk-FEMOX5AD.js → chunk-QR3C7BKQ.js} +7 -7
  80. package/dist/chunk-QR3C7BKQ.js.map +1 -0
  81. package/dist/{chunk-ETA2JXP5.js → chunk-RXTFCYQF.js} +2 -2
  82. package/dist/{chunk-Q7FJ5ZHM.js → chunk-S3IP6R6K.js} +8 -2
  83. package/dist/{chunk-Q7FJ5ZHM.js.map → chunk-S3IP6R6K.js.map} +1 -1
  84. package/dist/{chunk-3LCWFNVS.js → chunk-SKE7JYKA.js} +2 -2
  85. package/dist/{chunk-T65SHTJP.js → chunk-VQXK37XA.js} +1 -1
  86. package/dist/chunk-VQXK37XA.js.map +1 -0
  87. package/dist/{chunk-DWMXVUGO.js → chunk-VX2IUQFE.js} +98 -10
  88. package/dist/chunk-VX2IUQFE.js.map +1 -0
  89. package/dist/{chunk-KHJRMWO4.js → chunk-WGK4VHGP.js} +84 -22
  90. package/dist/chunk-WGK4VHGP.js.map +1 -0
  91. package/dist/{chunk-4IT6WL23.js → chunk-WTFWLUSX.js} +2 -2
  92. package/dist/{chunk-67YLUWLG.js → chunk-XJKFSSDW.js} +3 -3
  93. package/dist/chunk-XJKFSSDW.js.map +1 -0
  94. package/dist/{chunk-ASIQZXYO.js → chunk-XMVFHBHT.js} +2 -2
  95. package/dist/{chunk-Q5TJRAGE.js → chunk-Y5KDIOKF.js} +3 -3
  96. package/dist/{chunk-FCGWNWG4.js → chunk-Z5S5HNGY.js} +31 -29
  97. package/dist/chunk-Z5S5HNGY.js.map +1 -0
  98. package/dist/{chunk-OJMD2LIW.js → chunk-ZL4S7ARC.js} +3 -3
  99. package/dist/{cli-CIATRu8o.d.ts → cli-BrEwQTnW.d.ts} +4 -4
  100. package/dist/cli.d.ts +9 -8
  101. package/dist/cli.js +33 -31
  102. package/dist/codex-cli-fallback.d.ts +44 -0
  103. package/dist/codex-cli-fallback.js +12 -0
  104. package/dist/{codex-materialize-xVqbEmcm.d.ts → codex-materialize-CQlLTzke.d.ts} +1 -1
  105. package/dist/compression-optimizer.d.ts +2 -1
  106. package/dist/config.d.ts +2 -1
  107. package/dist/config.js +1 -1
  108. package/dist/consolidation-provenance-check.d.ts +3 -2
  109. package/dist/consolidation-undo.d.ts +3 -2
  110. package/dist/day-summary.d.ts +2 -1
  111. package/dist/day-summary.js +1 -1
  112. package/dist/delinearize.d.ts +2 -1
  113. package/dist/direct-answer-wiring.d.ts +2 -1
  114. package/dist/direct-answer.d.ts +2 -1
  115. package/dist/embedding-fallback.d.ts +2 -1
  116. package/dist/{engine-MEAYUA7A.js → engine-FOC3IJLA.js} +7 -7
  117. package/dist/entity-retrieval.d.ts +3 -2
  118. package/dist/entity-retrieval.js +6 -6
  119. package/dist/entity-schema.d.ts +2 -1
  120. package/dist/explicit-capture.d.ts +7 -6
  121. package/dist/explicit-capture.js +2 -2
  122. package/dist/explicit-cue-recall.js +1 -1
  123. package/dist/extraction-judge-telemetry.d.ts +2 -1
  124. package/dist/extraction-judge-training.d.ts +2 -1
  125. package/dist/extraction-judge.d.ts +2 -1
  126. package/dist/extraction.d.ts +2 -1
  127. package/dist/extraction.js +10 -8
  128. package/dist/fallback-llm.d.ts +8 -1
  129. package/dist/fallback-llm.js +5 -3
  130. package/dist/identity-continuity.d.ts +2 -1
  131. package/dist/importance.d.ts +2 -1
  132. package/dist/index-1qIcnbG1.d.ts +34 -0
  133. package/dist/index.d.ts +15 -13
  134. package/dist/index.js +175 -168
  135. package/dist/index.js.map +1 -1
  136. package/dist/intent.d.ts +2 -1
  137. package/dist/lifecycle.d.ts +2 -1
  138. package/dist/live-connectors-runner.d.ts +2 -1
  139. package/dist/live-connectors-runner.js +2 -2
  140. package/dist/local-llm.d.ts +2 -1
  141. package/dist/local-llm.js +1 -1
  142. package/dist/memory-action-policy.d.ts +2 -1
  143. package/dist/memory-cache.d.ts +2 -1
  144. package/dist/{memory-governance-G3XODEXW.js → memory-governance-F3QOJGEY.js} +7 -7
  145. package/dist/memory-lifecycle-ledger-utils.d.ts +2 -1
  146. package/dist/{memory-projection-store-lCzmu4JX.d.ts → memory-projection-store-CY8TU40w.d.ts} +1 -1
  147. package/dist/memory-projection-store.d.ts +3 -2
  148. package/dist/memory-projection-store.js +1 -1
  149. package/dist/memory-worth-outcomes.d.ts +3 -2
  150. package/dist/{migrate-from-identity-anchor-TTEDEJGX.js → migrate-from-identity-anchor-G27MCD6A.js} +2 -2
  151. package/dist/model-registry.js +1 -1
  152. package/dist/models-json.d.ts +2 -1
  153. package/dist/models-json.js +1 -1
  154. package/dist/native-knowledge.d.ts +2 -1
  155. package/dist/objective-state-writers.d.ts +23 -1
  156. package/dist/objective-state-writers.js +10 -306
  157. package/dist/objective-state-writers.js.map +1 -1
  158. package/dist/objective-state.d.ts +7 -1
  159. package/dist/objective-state.js +3 -1
  160. package/dist/operator-toolkit.d.ts +3 -2
  161. package/dist/operator-toolkit.js +11 -11
  162. package/dist/opik-exporter.js +2 -2
  163. package/dist/opik-exporter.js.map +1 -1
  164. package/dist/{orchestrator-CvUYwuaL.d.ts → orchestrator-6IvQ-Phj.d.ts} +6 -5
  165. package/dist/orchestrator.d.ts +7 -6
  166. package/dist/orchestrator.js +37 -35
  167. package/dist/patterns-cli.d.ts +2 -1
  168. package/dist/{peers-6OSQ3NK6.js → peers-HCVGHMAE.js} +3 -3
  169. package/dist/peers-HCVGHMAE.js.map +1 -0
  170. package/dist/policy-runtime.d.ts +2 -1
  171. package/dist/{port-BkWL7hqo.d.ts → port-B6VEDIkC.d.ts} +7 -1
  172. package/dist/qmd-recall-cache.d.ts +3 -2
  173. package/dist/qmd.d.ts +4 -2
  174. package/dist/qmd.js +1 -1
  175. package/dist/recall-disclosure-escalation.d.ts +2 -1
  176. package/dist/recall-explain-renderer.d.ts +2 -1
  177. package/dist/recall-explain-renderer.js +3 -3
  178. package/dist/recall-state.d.ts +2 -1
  179. package/dist/recall-tag-filter.d.ts +2 -1
  180. package/dist/recall-xray-cli.d.ts +2 -1
  181. package/dist/recall-xray-cli.js +4 -4
  182. package/dist/recall-xray-renderer.d.ts +2 -1
  183. package/dist/recall-xray-renderer.js +3 -3
  184. package/dist/recall-xray.d.ts +2 -1
  185. package/dist/recall-xray.js +2 -2
  186. package/dist/resolve-auth-token.d.ts +2 -1
  187. package/dist/resolve-provider-secret.d.ts +2 -1
  188. package/dist/resolve-provider-secret.js +3 -1
  189. package/dist/resume-bundles.js +4 -4
  190. package/dist/retrieval-agents.d.ts +3 -2
  191. package/dist/retrieval-tiers.d.ts +2 -1
  192. package/dist/sanitize.js +1 -1
  193. package/dist/schemas.d.ts +22 -22
  194. package/dist/{semantic-consolidation-CGiH52qa.d.ts → semantic-consolidation-ByBXb-sf.d.ts} +2 -2
  195. package/dist/semantic-consolidation.d.ts +4 -3
  196. package/dist/semantic-consolidation.js +6 -6
  197. package/dist/semantic-rule-promotion.js +6 -6
  198. package/dist/semantic-rule-verifier.d.ts +2 -1
  199. package/dist/semantic-rule-verifier.js +6 -6
  200. package/dist/session-observer-bands.d.ts +2 -1
  201. package/dist/session-observer-state.d.ts +2 -1
  202. package/dist/signal.d.ts +2 -1
  203. package/dist/source-attribution.d.ts +1 -1
  204. package/dist/source-attribution.js +1 -1
  205. package/dist/storage.d.ts +3 -2
  206. package/dist/storage.js +5 -5
  207. package/dist/summarizer.d.ts +2 -1
  208. package/dist/summarizer.js +8 -6
  209. package/dist/summary-snapshot.d.ts +2 -1
  210. package/dist/temporal-supersession.d.ts +3 -2
  211. package/dist/temporal-validity.d.ts +2 -1
  212. package/dist/threading.d.ts +2 -1
  213. package/dist/tier-migration.d.ts +4 -3
  214. package/dist/tier-routing.d.ts +2 -1
  215. package/dist/topics.d.ts +2 -1
  216. package/dist/transcript.d.ts +2 -1
  217. package/dist/types.d.ts +2693 -1
  218. package/dist/types.js +1 -1
  219. package/dist/utility-runtime.d.ts +2 -1
  220. package/dist/verified-recall.js +6 -6
  221. package/package.json +1 -1
  222. package/dist/chunk-4KAN3GZ3.js.map +0 -1
  223. package/dist/chunk-67YLUWLG.js.map +0 -1
  224. package/dist/chunk-DWMXVUGO.js.map +0 -1
  225. package/dist/chunk-FCGWNWG4.js.map +0 -1
  226. package/dist/chunk-FEMOX5AD.js.map +0 -1
  227. package/dist/chunk-FIXIX6DE.js.map +0 -1
  228. package/dist/chunk-GRDDGNYQ.js.map +0 -1
  229. package/dist/chunk-GZCUW5IC.js.map +0 -1
  230. package/dist/chunk-KHJRMWO4.js.map +0 -1
  231. package/dist/chunk-KNQ5YJTO.js.map +0 -1
  232. package/dist/chunk-L2IO2QPY.js.map +0 -1
  233. package/dist/chunk-LOBRX7VD.js.map +0 -1
  234. package/dist/chunk-M62O4P4T.js +0 -41
  235. package/dist/chunk-M62O4P4T.js.map +0 -1
  236. package/dist/chunk-ODWDQNRE.js.map +0 -1
  237. package/dist/chunk-QJZ77K7F.js.map +0 -1
  238. package/dist/chunk-R2XRID2N.js.map +0 -1
  239. package/dist/chunk-RJSVRPNU.js.map +0 -1
  240. package/dist/chunk-S5SQDIF5.js.map +0 -1
  241. package/dist/chunk-SRIDOT64.js.map +0 -1
  242. package/dist/chunk-T65SHTJP.js.map +0 -1
  243. package/dist/chunk-TUFG6VXY.js.map +0 -1
  244. package/dist/types-H85grL1f.d.ts +0 -2714
  245. /package/dist/{chunk-AV2WSYZY.js.map → chunk-2YMTO4ZJ.js.map} +0 -0
  246. /package/dist/{chunk-SYWJJTNL.js.map → chunk-363MWCD3.js.map} +0 -0
  247. /package/dist/{chunk-65ZPH7QA.js.map → chunk-36CTNQY7.js.map} +0 -0
  248. /package/dist/{chunk-XVOIMCVW.js.map → chunk-6XA7UN4Z.js.map} +0 -0
  249. /package/dist/{chunk-NN3TS5BM.js.map → chunk-D54LZC5L.js.map} +0 -0
  250. /package/dist/{chunk-E27HOXMX.js.map → chunk-EYNQTST2.js.map} +0 -0
  251. /package/dist/{chunk-3FPTCC3Z.js.map → chunk-GVPWB7EY.js.map} +0 -0
  252. /package/dist/{chunk-SWRJFKYW.js.map → chunk-I6BQZSML.js.map} +0 -0
  253. /package/dist/{chunk-STB3GUYU.js.map → chunk-KBYWQWSB.js.map} +0 -0
  254. /package/dist/{chunk-MYH2IBSP.js.map → chunk-LIO5X3CM.js.map} +0 -0
  255. /package/dist/{chunk-XGX4TUF6.js.map → chunk-MCC6KDQF.js.map} +0 -0
  256. /package/dist/{chunk-WXPPM426.js.map → chunk-O4XJUPSF.js.map} +0 -0
  257. /package/dist/{chunk-RLV2F337.js.map → chunk-PB5KW5PL.js.map} +0 -0
  258. /package/dist/{chunk-ETA2JXP5.js.map → chunk-RXTFCYQF.js.map} +0 -0
  259. /package/dist/{chunk-3LCWFNVS.js.map → chunk-SKE7JYKA.js.map} +0 -0
  260. /package/dist/{chunk-4IT6WL23.js.map → chunk-WTFWLUSX.js.map} +0 -0
  261. /package/dist/{chunk-ASIQZXYO.js.map → chunk-XMVFHBHT.js.map} +0 -0
  262. /package/dist/{chunk-Q5TJRAGE.js.map → chunk-Y5KDIOKF.js.map} +0 -0
  263. /package/dist/{chunk-OJMD2LIW.js.map → chunk-ZL4S7ARC.js.map} +0 -0
  264. /package/dist/{engine-MEAYUA7A.js.map → codex-cli-fallback.js.map} +0 -0
  265. /package/dist/{memory-governance-G3XODEXW.js.map → engine-FOC3IJLA.js.map} +0 -0
  266. /package/dist/{migrate-from-identity-anchor-TTEDEJGX.js.map → memory-governance-F3QOJGEY.js.map} +0 -0
  267. /package/dist/{peers-6OSQ3NK6.js.map → migrate-from-identity-anchor-G27MCD6A.js.map} +0 -0
@@ -3,24 +3,26 @@ import {
3
3
  EngramAccessInputError,
4
4
  EngramAccessService,
5
5
  shapeMemorySummary
6
- } from "./chunk-KHJRMWO4.js";
6
+ } from "./chunk-WGK4VHGP.js";
7
7
  import "./chunk-QIGOEM65.js";
8
8
  import "./chunk-BT7NVCML.js";
9
- import "./chunk-H7XKCNR6.js";
10
- import "./chunk-WXPPM426.js";
9
+ import "./chunk-O4XJUPSF.js";
11
10
  import "./chunk-SOBJ6NEY.js";
12
- import "./chunk-E27HOXMX.js";
13
- import "./chunk-NN3TS5BM.js";
11
+ import "./chunk-H7XKCNR6.js";
12
+ import "./chunk-EYNQTST2.js";
13
+ import "./chunk-D54LZC5L.js";
14
14
  import "./chunk-EQINRHYR.js";
15
- import "./chunk-AV2WSYZY.js";
15
+ import "./chunk-2YMTO4ZJ.js";
16
16
  import "./chunk-EIR5VLIH.js";
17
- import "./chunk-IXEJRKCZ.js";
17
+ import "./chunk-HJYHRE4S.js";
18
+ import "./chunk-IBX3VFOM.js";
19
+ import "./chunk-5UM2VJ6D.js";
18
20
  import "./chunk-PCUKNJAZ.js";
19
- import "./chunk-3FPTCC3Z.js";
20
- import "./chunk-2LGMW3DJ.js";
21
21
  import "./chunk-EEQLFRUM.js";
22
22
  import "./chunk-NBNN5GOB.js";
23
23
  import "./chunk-OR64ZGRZ.js";
24
+ import "./chunk-GVPWB7EY.js";
25
+ import "./chunk-2LGMW3DJ.js";
24
26
  import "./chunk-QDW3E4RD.js";
25
27
  import "./chunk-GDFS42HT.js";
26
28
  import "./chunk-RK2Y4XOM.js";
@@ -28,21 +30,22 @@ import "./chunk-2LSZVONP.js";
28
30
  import "./chunk-WIICJPET.js";
29
31
  import "./chunk-G2WADRQ3.js";
30
32
  import "./chunk-74EMIVE4.js";
33
+ import "./chunk-IXEJRKCZ.js";
31
34
  import "./chunk-DT5TVLJE.js";
32
35
  import "./chunk-N5AKDXAI.js";
33
36
  import "./chunk-TBBDFYXW.js";
34
- import "./chunk-4IT6WL23.js";
35
- import "./chunk-XGX4TUF6.js";
37
+ import "./chunk-WTFWLUSX.js";
38
+ import "./chunk-MCC6KDQF.js";
36
39
  import "./chunk-YNJHCGDT.js";
37
- import "./chunk-4KAN3GZ3.js";
38
- import "./chunk-T65SHTJP.js";
40
+ import "./chunk-NN2DKE4T.js";
41
+ import "./chunk-VQXK37XA.js";
39
42
  import "./chunk-PFV5C235.js";
40
43
  import "./chunk-RULE4VG5.js";
41
44
  import "./chunk-SCU65EZI.js";
42
- import "./chunk-67YLUWLG.js";
45
+ import "./chunk-XJKFSSDW.js";
43
46
  import "./chunk-DM2T26WE.js";
44
47
  import "./chunk-QSVPYQPG.js";
45
- import "./chunk-M62O4P4T.js";
48
+ import "./chunk-FVQJYWH7.js";
46
49
  import "./chunk-4DJQYKMN.js";
47
50
  import "./chunk-G7D6GZ5J.js";
48
51
  import "./chunk-FAAFWE4G.js";
@@ -1,4 +1,5 @@
1
- import { P as PluginConfig, f as MemoryFile } from './types-H85grL1f.js';
1
+ import { PluginConfig, MemoryFile } from './types.js';
2
+ import './index-1qIcnbG1.js';
2
3
 
3
4
  interface ActiveMemoryMetadata {
4
5
  type?: "fact" | "preference";
@@ -1,4 +1,5 @@
1
- import { A as ActiveRecallChatType, a as ActiveRecallQueryMode, b as ActiveRecallPromptStyle, c as ActiveRecallThinking, d as ActiveRecallModelFallbackPolicy } from './types-H85grL1f.js';
1
+ import { ActiveRecallChatType, ActiveRecallQueryMode, ActiveRecallPromptStyle, ActiveRecallThinking, ActiveRecallModelFallbackPolicy } from './types.js';
2
+ import './index-1qIcnbG1.js';
2
3
 
3
4
  interface ActiveRecallTurn {
4
5
  role: "user" | "assistant";
@@ -17,7 +18,7 @@ interface ActiveRecallConfig {
17
18
  allowedChatTypes: ActiveRecallChatType[];
18
19
  queryMode: ActiveRecallQueryMode;
19
20
  promptStyle: ActiveRecallPromptStyle;
20
- promptOverride: string | null;
21
+ customInstruction: string | null;
21
22
  promptAppend: string | null;
22
23
  maxSummaryChars: number;
23
24
  recentUserTurns: number;
@@ -40,7 +40,7 @@ function buildCacheKey(input, config, queryBundle) {
40
40
  agentId: input.agentId,
41
41
  queryMode: config.queryMode,
42
42
  promptStyle: config.promptStyle,
43
- promptOverride: config.promptOverride,
43
+ customInstruction: config.customInstruction,
44
44
  promptAppend: config.promptAppend,
45
45
  maxSummaryChars: config.maxSummaryChars,
46
46
  entityGraphDepth: config.entityGraphDepth,
@@ -129,7 +129,7 @@ function sanitizeTranscriptPathSegment(value) {
129
129
  }
130
130
  function buildActiveRecallPrompt(params) {
131
131
  const sections = [
132
- params.config.promptOverride?.trim() || STYLE_INSTRUCTIONS[params.config.promptStyle],
132
+ params.config.customInstruction?.trim() || STYLE_INSTRUCTIONS[params.config.promptStyle],
133
133
  `Query bundle:
134
134
  ${params.queryBundle}`,
135
135
  params.recallContext ? `Retrieved memory:
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/active-recall.ts"],"sourcesContent":["import { appendFile, mkdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { collapseWhitespace, truncateCodePointSafe } from \"./whitespace.js\";\nimport type {\n ActiveRecallChatType,\n ActiveRecallModelFallbackPolicy,\n ActiveRecallPromptStyle,\n ActiveRecallQueryMode,\n ActiveRecallThinking,\n} from \"./types.js\";\n\nexport interface ActiveRecallTurn {\n role: \"user\" | \"assistant\";\n content: string;\n}\n\nexport interface ActiveRecallInput {\n sessionKey: string;\n agentId: string;\n chatType: ActiveRecallChatType;\n recentTurns: ActiveRecallTurn[];\n currentMessage: string;\n}\n\nexport interface ActiveRecallConfig {\n enabled: boolean;\n agents: string[] | null;\n allowedChatTypes: ActiveRecallChatType[];\n queryMode: ActiveRecallQueryMode;\n promptStyle: ActiveRecallPromptStyle;\n promptOverride: string | null;\n promptAppend: string | null;\n maxSummaryChars: number;\n recentUserTurns: number;\n recentAssistantTurns: number;\n recentUserChars: number;\n recentAssistantChars: number;\n thinking: ActiveRecallThinking;\n timeoutMs: number;\n cacheTtlMs: number;\n persistTranscripts: boolean;\n transcriptDir: string;\n entityGraphDepth: number;\n includeCausalTrajectories: boolean;\n includeDaySummary: boolean;\n attachRecallExplain: boolean;\n modelOverride: string | null;\n modelFallbackPolicy: ActiveRecallModelFallbackPolicy;\n}\n\nexport interface ActiveRecallResult {\n summary: string | null;\n citations: Array<{ memoryId: string; relevance: number }>;\n latencyMs: number;\n cacheHit: boolean;\n modelUsed: string;\n transcriptPath: string | null;\n}\n\nexport interface ActiveRecallDependencies {\n recall(query: string, sessionKey: string): Promise<string | null>;\n getLastRecallSnapshot?(sessionKey: string): { memoryIds?: string[] } | null;\n walkEntityGraph?(params: {\n sessionKey: string;\n query: string;\n depth: number;\n }): Promise<string[]>;\n loadCausalTrajectories?(params: {\n sessionKey: string;\n query: string;\n }): Promise<string[]>;\n loadDaySummary?(sessionKey: string): Promise<string | null>;\n explainLastRecall?(sessionKey: string): Promise<string | null>;\n generateSummary?(params: {\n prompt: string;\n sessionKey: string;\n agentId: string;\n model: string;\n timeoutMs: number;\n thinking: ActiveRecallThinking;\n fallbackPolicy: ActiveRecallModelFallbackPolicy;\n }): Promise<{ text: string | null; modelUsed?: string; cacheHit?: boolean }>;\n now?: () => number;\n}\n\ninterface CachedRecallResult {\n expiresAt: number;\n value: ActiveRecallResult;\n}\n\ninterface ActiveRecallTurnWithIndex {\n index: number;\n role: ActiveRecallTurn[\"role\"];\n content: string;\n}\n\nconst ACTIVE_RECALL_CACHE_MAX_ENTRIES = 256;\n\nconst NONE_SET = new Set([\n \"\",\n \"none\",\n \"no_reply\",\n \"nothing useful\",\n \"no relevant memory\",\n \"timeout\",\n \"[]\",\n \"{}\",\n \"null\",\n \"n/a\",\n]);\n\nconst STYLE_INSTRUCTIONS: Record<ActiveRecallPromptStyle, string> = {\n balanced: \"Summarize the most relevant memory context in a compact, neutral way.\",\n strict: \"Only include memory that is directly supported by the retrieved context.\",\n contextual: \"Prefer concise context that helps the next reply stay grounded in recent work.\",\n \"recall-heavy\": \"Bias toward richer recall coverage when multiple retrieved items reinforce each other.\",\n \"precision-heavy\": \"Bias toward precision. Omit anything uncertain or weakly supported.\",\n \"preference-only\": \"Only surface user preference or operating-style memory when present.\",\n};\n\nfunction cloneRecallResult(value: ActiveRecallResult): ActiveRecallResult {\n return {\n ...value,\n citations: [...value.citations],\n };\n}\n\nfunction buildCacheKey(input: ActiveRecallInput, config: ActiveRecallConfig, queryBundle: string): string {\n return JSON.stringify({\n sessionKey: input.sessionKey,\n agentId: input.agentId,\n queryMode: config.queryMode,\n promptStyle: config.promptStyle,\n promptOverride: config.promptOverride,\n promptAppend: config.promptAppend,\n maxSummaryChars: config.maxSummaryChars,\n entityGraphDepth: config.entityGraphDepth,\n includeCausalTrajectories: config.includeCausalTrajectories,\n includeDaySummary: config.includeDaySummary,\n attachRecallExplain: config.attachRecallExplain,\n modelOverride: config.modelOverride,\n modelFallbackPolicy: config.modelFallbackPolicy,\n thinking: config.thinking,\n queryBundle,\n });\n}\n\nfunction pruneExpiredCache(\n cache: Map<string, CachedRecallResult>,\n currentTime: number,\n): void {\n for (const [key, entry] of cache.entries()) {\n if (entry.expiresAt <= currentTime) {\n cache.delete(key);\n }\n }\n}\n\nfunction enforceCacheLimit(cache: Map<string, CachedRecallResult>): void {\n while (cache.size > ACTIVE_RECALL_CACHE_MAX_ENTRIES) {\n const oldestKey = cache.keys().next().value;\n if (typeof oldestKey !== \"string\") {\n break;\n }\n cache.delete(oldestKey);\n }\n}\n\nfunction cropTurns(\n turns: ActiveRecallTurn[],\n role: \"user\" | \"assistant\",\n maxTurns: number,\n maxChars: number,\n): ActiveRecallTurnWithIndex[] {\n if (maxTurns <= 0) {\n return [];\n }\n\n const selected: ActiveRecallTurnWithIndex[] = [];\n for (let index = turns.length - 1; index >= 0 && selected.length < maxTurns; index -= 1) {\n const turn = turns[index];\n if (turn?.role === role) {\n selected.push({\n index,\n role: turn.role,\n content: collapseWhitespace(truncateCodePointSafe(turn.content, maxChars)),\n });\n }\n }\n\n return selected.reverse();\n}\n\nfunction mergeChronologicalTurns(\n userTurns: ActiveRecallTurnWithIndex[],\n assistantTurns: ActiveRecallTurnWithIndex[],\n): ActiveRecallTurnWithIndex[] {\n return [...userTurns, ...assistantTurns]\n .sort((left, right) => left.index - right.index)\n .filter((value) => value.content.length > 0);\n}\n\nexport function buildActiveRecallQueryBundle(\n input: ActiveRecallInput,\n config: ActiveRecallConfig,\n): string {\n if (config.queryMode === \"message\") {\n return collapseWhitespace(input.currentMessage);\n }\n\n const userTurns = cropTurns(\n input.recentTurns,\n \"user\",\n config.recentUserTurns,\n config.recentUserChars,\n );\n const assistantTurns = cropTurns(\n input.recentTurns,\n \"assistant\",\n config.recentAssistantTurns,\n config.recentAssistantChars,\n );\n const mergedTurns = mergeChronologicalTurns(userTurns, assistantTurns);\n\n const parts = [\n ...mergedTurns.map((turn) => `${turn.role}: ${turn.content}`),\n ];\n\n if (config.queryMode === \"full\") {\n return [...parts, `current: ${collapseWhitespace(input.currentMessage)}`]\n .filter((value) => value.trim().length > 0)\n .join(\"\\n\");\n }\n\n return [`current: ${collapseWhitespace(input.currentMessage)}`, ...parts]\n .filter((value) => value.trim().length > 0)\n .join(\"\\n\");\n}\n\nexport function normalizeActiveRecallSummary(value: string | null, maxChars: number): string | null {\n if (value == null) return null;\n const compact = collapseWhitespace(value);\n if (NONE_SET.has(compact.toLowerCase())) return null;\n return truncateCodePointSafe(compact, maxChars);\n}\n\nfunction sanitizeTranscriptPathSegment(value: string): string {\n const normalized = collapseWhitespace(value);\n return encodeURIComponent(normalized.length > 0 ? normalized : \"unknown\").replaceAll(\n \".\",\n \"%2E\",\n );\n}\n\nexport function buildActiveRecallPrompt(params: {\n config: ActiveRecallConfig;\n queryBundle: string;\n recallContext: string | null;\n graphContext: string[];\n causalContext: string[];\n daySummary: string | null;\n recallExplain: string | null;\n}): string {\n const sections = [\n params.config.promptOverride?.trim() || STYLE_INSTRUCTIONS[params.config.promptStyle],\n `Query bundle:\\n${params.queryBundle}`,\n params.recallContext ? `Retrieved memory:\\n${params.recallContext}` : null,\n params.graphContext.length > 0 ? `Entity graph:\\n${params.graphContext.join(\"\\n\")}` : null,\n params.causalContext.length > 0 ? `Causal trajectories:\\n${params.causalContext.join(\"\\n\")}` : null,\n params.daySummary ? `Day summary:\\n${params.daySummary}` : null,\n params.recallExplain ? `Recall explain:\\n${params.recallExplain}` : null,\n params.config.promptAppend?.trim() || null,\n \"Return either NONE or a compact summary grounded only in the supplied context.\",\n ];\n return sections.filter((value): value is string => !!value && value.trim().length > 0).join(\"\\n\\n\");\n}\n\nasync function appendActiveRecallTranscript(\n transcriptRoot: string,\n input: ActiveRecallInput,\n config: ActiveRecallConfig,\n result: ActiveRecallResult,\n queryBundle: string,\n): Promise<string> {\n const date = new Date().toISOString().slice(0, 10);\n const filePath = path.join(\n transcriptRoot,\n \"agents\",\n sanitizeTranscriptPathSegment(input.agentId),\n date,\n `${sanitizeTranscriptPathSegment(input.sessionKey)}.jsonl`,\n );\n await mkdir(path.dirname(filePath), { recursive: true });\n await appendFile(\n filePath,\n `${JSON.stringify({\n ts: new Date().toISOString(),\n sessionKey: input.sessionKey,\n agentId: input.agentId,\n queryMode: config.queryMode,\n promptStyle: config.promptStyle,\n queryBundle,\n summary: result.summary,\n citations: result.citations,\n latencyMs: result.latencyMs,\n cacheHit: result.cacheHit,\n modelUsed: result.modelUsed,\n })}\\n`,\n \"utf8\",\n );\n return filePath;\n}\n\nexport function createActiveRecallEngine(\n deps: ActiveRecallDependencies,\n config: ActiveRecallConfig,\n) {\n const cache = new Map<string, CachedRecallResult>();\n const now = deps.now ?? (() => Date.now());\n\n return {\n async run(input: ActiveRecallInput): Promise<ActiveRecallResult> {\n if (!config.enabled) {\n return {\n summary: null,\n citations: [],\n latencyMs: 0,\n cacheHit: false,\n modelUsed: config.modelOverride ?? \"disabled\",\n transcriptPath: null,\n };\n }\n if (config.agents && !config.agents.includes(input.agentId)) {\n return {\n summary: null,\n citations: [],\n latencyMs: 0,\n cacheHit: false,\n modelUsed: config.modelOverride ?? \"filtered\",\n transcriptPath: null,\n };\n }\n if (!config.allowedChatTypes.includes(input.chatType)) {\n return {\n summary: null,\n citations: [],\n latencyMs: 0,\n cacheHit: false,\n modelUsed: config.modelOverride ?? \"filtered\",\n transcriptPath: null,\n };\n }\n\n const queryBundle = buildActiveRecallQueryBundle(input, config);\n const cacheKey = buildCacheKey(input, config, queryBundle);\n const currentTime = now();\n const cacheEnabled = config.cacheTtlMs > 0;\n if (cacheEnabled) {\n pruneExpiredCache(cache, currentTime);\n }\n const cached = cache.get(cacheKey);\n if (cacheEnabled && cached) {\n return {\n ...cloneRecallResult(cached.value),\n latencyMs: Math.max(0, now() - currentTime),\n cacheHit: true,\n };\n }\n\n const start = currentTime;\n const recallContext = await deps.recall(queryBundle, input.sessionKey);\n const graphContext =\n config.entityGraphDepth > 0 && deps.walkEntityGraph\n ? await deps.walkEntityGraph({\n sessionKey: input.sessionKey,\n query: queryBundle,\n depth: config.entityGraphDepth,\n })\n : [];\n const causalContext =\n config.includeCausalTrajectories && deps.loadCausalTrajectories\n ? await deps.loadCausalTrajectories({\n sessionKey: input.sessionKey,\n query: queryBundle,\n })\n : [];\n const daySummary =\n config.includeDaySummary && deps.loadDaySummary\n ? await deps.loadDaySummary(input.sessionKey)\n : null;\n const recallExplain =\n config.attachRecallExplain && deps.explainLastRecall\n ? await deps.explainLastRecall(input.sessionKey)\n : null;\n const prompt = buildActiveRecallPrompt({\n config,\n queryBundle,\n recallContext,\n graphContext,\n causalContext,\n daySummary,\n recallExplain,\n });\n\n const generated = deps.generateSummary\n ? await deps.generateSummary({\n prompt,\n sessionKey: input.sessionKey,\n agentId: input.agentId,\n model: config.modelOverride ?? \"gpt-5.2\",\n timeoutMs: config.timeoutMs,\n thinking: config.thinking,\n fallbackPolicy: config.modelFallbackPolicy,\n })\n : {\n text: recallContext,\n modelUsed: config.modelOverride ?? \"gpt-5.2\",\n cacheHit: false,\n };\n const summary = normalizeActiveRecallSummary(\n generated.text,\n config.maxSummaryChars,\n );\n const snapshot = deps.getLastRecallSnapshot?.(input.sessionKey);\n const citations = (snapshot?.memoryIds ?? []).map((memoryId, index) => ({\n memoryId,\n relevance: Number((1 / (index + 1)).toFixed(3)),\n }));\n const result: ActiveRecallResult = {\n summary,\n citations,\n latencyMs: Math.max(0, now() - start),\n cacheHit: generated.cacheHit === true,\n modelUsed: generated.modelUsed ?? config.modelOverride ?? \"gpt-5.2\",\n transcriptPath: null,\n };\n if (config.persistTranscripts) {\n result.transcriptPath = await appendActiveRecallTranscript(\n config.transcriptDir,\n input,\n config,\n result,\n queryBundle,\n );\n }\n\n if (cacheEnabled) {\n const completedAt = now();\n cache.set(cacheKey, {\n expiresAt: completedAt + config.cacheTtlMs,\n value: cloneRecallResult(result),\n });\n enforceCacheLimit(cache);\n }\n return result;\n },\n };\n}\n"],"mappings":";;;;;;;AAAA,SAAS,YAAY,aAAa;AAClC,OAAO,UAAU;AA+FjB,IAAM,kCAAkC;AAExC,IAAM,WAAW,oBAAI,IAAI;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,qBAA8D;AAAA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f,OAAO,OAAO,iBAAiB;AAAA,QAC/B,WAAW,OAAO;AAAA,QAClB,UAAU,OAAO;AAAA,QACjB,gBAAgB,OAAO;AAAA,MACzB,CAAC,IACD;AAAA,QACE,MAAM;AAAA,QACN,WAAW,OAAO,iBAAiB;AAAA,QACnC,UAAU;AAAA,MACZ;AACJ,YAAM,UAAU;AAAA,QACd,UAAU;AAAA,QACV,OAAO;AAAA,MACT;AACA,YAAM,WAAW,KAAK,wBAAwB,MAAM,UAAU;AAC9D,YAAM,aAAa,UAAU,aAAa,CAAC,GAAG,IAAI,CAAC,UAAU,WAAW;AAAA,QACtE;AAAA,QACA,WAAW,QAAQ,KAAK,QAAQ,IAAI,QAAQ,CAAC,CAAC;AAAA,MAChD,EAAE;AACF,YAAM,SAA6B;AAAA,QACjC;AAAA,QACA;AAAA,QACA,WAAW,KAAK,IAAI,GAAG,IAAI,IAAI,KAAK;AAAA,QACpC,UAAU,UAAU,aAAa;AAAA,QACjC,WAAW,UAAU,aAAa,OAAO,iBAAiB;AAAA,QAC1D,gBAAgB;AAAA,MAClB;AACA,UAAI,OAAO,oBAAoB;AAC7B,eAAO,iBAAiB,MAAM;AAAA,UAC5B,OAAO;AAAA,UACP;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAEA,UAAI,cAAc;AAChB,cAAM,cAAc,IAAI;AACxB,cAAM,IAAI,UAAU;AAAA,UAClB,WAAW,cAAc,OAAO;AAAA,UAChC,OAAO,kBAAkB,MAAM;AAAA,QACjC,CAAC;AACD,0BAAkB,KAAK;AAAA,MACzB;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/active-recall.ts"],"sourcesContent":["import { appendFile, mkdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { collapseWhitespace, truncateCodePointSafe } from \"./whitespace.js\";\nimport type {\n ActiveRecallChatType,\n ActiveRecallModelFallbackPolicy,\n ActiveRecallPromptStyle,\n ActiveRecallQueryMode,\n ActiveRecallThinking,\n} from \"./types.js\";\n\nexport interface ActiveRecallTurn {\n role: \"user\" | \"assistant\";\n content: string;\n}\n\nexport interface ActiveRecallInput {\n sessionKey: string;\n agentId: string;\n chatType: ActiveRecallChatType;\n recentTurns: ActiveRecallTurn[];\n currentMessage: string;\n}\n\nexport interface ActiveRecallConfig {\n enabled: boolean;\n agents: string[] | null;\n allowedChatTypes: ActiveRecallChatType[];\n queryMode: ActiveRecallQueryMode;\n promptStyle: ActiveRecallPromptStyle;\n customInstruction: string | null;\n promptAppend: string | null;\n maxSummaryChars: number;\n recentUserTurns: number;\n recentAssistantTurns: number;\n recentUserChars: number;\n recentAssistantChars: number;\n thinking: ActiveRecallThinking;\n timeoutMs: number;\n cacheTtlMs: number;\n persistTranscripts: boolean;\n transcriptDir: string;\n entityGraphDepth: number;\n includeCausalTrajectories: boolean;\n includeDaySummary: boolean;\n attachRecallExplain: boolean;\n modelOverride: string | null;\n modelFallbackPolicy: ActiveRecallModelFallbackPolicy;\n}\n\nexport interface ActiveRecallResult {\n summary: string | null;\n citations: Array<{ memoryId: string; relevance: number }>;\n latencyMs: number;\n cacheHit: boolean;\n modelUsed: string;\n transcriptPath: string | null;\n}\n\nexport interface ActiveRecallDependencies {\n recall(query: string, sessionKey: string): Promise<string | null>;\n getLastRecallSnapshot?(sessionKey: string): { memoryIds?: string[] } | null;\n walkEntityGraph?(params: {\n sessionKey: string;\n query: string;\n depth: number;\n }): Promise<string[]>;\n loadCausalTrajectories?(params: {\n sessionKey: string;\n query: string;\n }): Promise<string[]>;\n loadDaySummary?(sessionKey: string): Promise<string | null>;\n explainLastRecall?(sessionKey: string): Promise<string | null>;\n generateSummary?(params: {\n prompt: string;\n sessionKey: string;\n agentId: string;\n model: string;\n timeoutMs: number;\n thinking: ActiveRecallThinking;\n fallbackPolicy: ActiveRecallModelFallbackPolicy;\n }): Promise<{ text: string | null; modelUsed?: string; cacheHit?: boolean }>;\n now?: () => number;\n}\n\ninterface CachedRecallResult {\n expiresAt: number;\n value: ActiveRecallResult;\n}\n\ninterface ActiveRecallTurnWithIndex {\n index: number;\n role: ActiveRecallTurn[\"role\"];\n content: string;\n}\n\nconst ACTIVE_RECALL_CACHE_MAX_ENTRIES = 256;\n\nconst NONE_SET = new Set([\n \"\",\n \"none\",\n \"no_reply\",\n \"nothing useful\",\n \"no relevant memory\",\n \"timeout\",\n \"[]\",\n \"{}\",\n \"null\",\n \"n/a\",\n]);\n\nconst STYLE_INSTRUCTIONS: Record<ActiveRecallPromptStyle, string> = {\n balanced: \"Summarize the most relevant memory context in a compact, neutral way.\",\n strict: \"Only include memory that is directly supported by the retrieved context.\",\n contextual: \"Prefer concise context that helps the next reply stay grounded in recent work.\",\n \"recall-heavy\": \"Bias toward richer recall coverage when multiple retrieved items reinforce each other.\",\n \"precision-heavy\": \"Bias toward precision. Omit anything uncertain or weakly supported.\",\n \"preference-only\": \"Only surface user preference or operating-style memory when present.\",\n};\n\nfunction cloneRecallResult(value: ActiveRecallResult): ActiveRecallResult {\n return {\n ...value,\n citations: [...value.citations],\n };\n}\n\nfunction buildCacheKey(input: ActiveRecallInput, config: ActiveRecallConfig, queryBundle: string): string {\n return JSON.stringify({\n sessionKey: input.sessionKey,\n agentId: input.agentId,\n queryMode: config.queryMode,\n promptStyle: config.promptStyle,\n customInstruction: config.customInstruction,\n promptAppend: config.promptAppend,\n maxSummaryChars: config.maxSummaryChars,\n entityGraphDepth: config.entityGraphDepth,\n includeCausalTrajectories: config.includeCausalTrajectories,\n includeDaySummary: config.includeDaySummary,\n attachRecallExplain: config.attachRecallExplain,\n modelOverride: config.modelOverride,\n modelFallbackPolicy: config.modelFallbackPolicy,\n thinking: config.thinking,\n queryBundle,\n });\n}\n\nfunction pruneExpiredCache(\n cache: Map<string, CachedRecallResult>,\n currentTime: number,\n): void {\n for (const [key, entry] of cache.entries()) {\n if (entry.expiresAt <= currentTime) {\n cache.delete(key);\n }\n }\n}\n\nfunction enforceCacheLimit(cache: Map<string, CachedRecallResult>): void {\n while (cache.size > ACTIVE_RECALL_CACHE_MAX_ENTRIES) {\n const oldestKey = cache.keys().next().value;\n if (typeof oldestKey !== \"string\") {\n break;\n }\n cache.delete(oldestKey);\n }\n}\n\nfunction cropTurns(\n turns: ActiveRecallTurn[],\n role: \"user\" | \"assistant\",\n maxTurns: number,\n maxChars: number,\n): ActiveRecallTurnWithIndex[] {\n if (maxTurns <= 0) {\n return [];\n }\n\n const selected: ActiveRecallTurnWithIndex[] = [];\n for (let index = turns.length - 1; index >= 0 && selected.length < maxTurns; index -= 1) {\n const turn = turns[index];\n if (turn?.role === role) {\n selected.push({\n index,\n role: turn.role,\n content: collapseWhitespace(truncateCodePointSafe(turn.content, maxChars)),\n });\n }\n }\n\n return selected.reverse();\n}\n\nfunction mergeChronologicalTurns(\n userTurns: ActiveRecallTurnWithIndex[],\n assistantTurns: ActiveRecallTurnWithIndex[],\n): ActiveRecallTurnWithIndex[] {\n return [...userTurns, ...assistantTurns]\n .sort((left, right) => left.index - right.index)\n .filter((value) => value.content.length > 0);\n}\n\nexport function buildActiveRecallQueryBundle(\n input: ActiveRecallInput,\n config: ActiveRecallConfig,\n): string {\n if (config.queryMode === \"message\") {\n return collapseWhitespace(input.currentMessage);\n }\n\n const userTurns = cropTurns(\n input.recentTurns,\n \"user\",\n config.recentUserTurns,\n config.recentUserChars,\n );\n const assistantTurns = cropTurns(\n input.recentTurns,\n \"assistant\",\n config.recentAssistantTurns,\n config.recentAssistantChars,\n );\n const mergedTurns = mergeChronologicalTurns(userTurns, assistantTurns);\n\n const parts = [\n ...mergedTurns.map((turn) => `${turn.role}: ${turn.content}`),\n ];\n\n if (config.queryMode === \"full\") {\n return [...parts, `current: ${collapseWhitespace(input.currentMessage)}`]\n .filter((value) => value.trim().length > 0)\n .join(\"\\n\");\n }\n\n return [`current: ${collapseWhitespace(input.currentMessage)}`, ...parts]\n .filter((value) => value.trim().length > 0)\n .join(\"\\n\");\n}\n\nexport function normalizeActiveRecallSummary(value: string | null, maxChars: number): string | null {\n if (value == null) return null;\n const compact = collapseWhitespace(value);\n if (NONE_SET.has(compact.toLowerCase())) return null;\n return truncateCodePointSafe(compact, maxChars);\n}\n\nfunction sanitizeTranscriptPathSegment(value: string): string {\n const normalized = collapseWhitespace(value);\n return encodeURIComponent(normalized.length > 0 ? normalized : \"unknown\").replaceAll(\n \".\",\n \"%2E\",\n );\n}\n\nexport function buildActiveRecallPrompt(params: {\n config: ActiveRecallConfig;\n queryBundle: string;\n recallContext: string | null;\n graphContext: string[];\n causalContext: string[];\n daySummary: string | null;\n recallExplain: string | null;\n}): string {\n const sections = [\n params.config.customInstruction?.trim() || STYLE_INSTRUCTIONS[params.config.promptStyle],\n `Query bundle:\\n${params.queryBundle}`,\n params.recallContext ? `Retrieved memory:\\n${params.recallContext}` : null,\n params.graphContext.length > 0 ? `Entity graph:\\n${params.graphContext.join(\"\\n\")}` : null,\n params.causalContext.length > 0 ? `Causal trajectories:\\n${params.causalContext.join(\"\\n\")}` : null,\n params.daySummary ? `Day summary:\\n${params.daySummary}` : null,\n params.recallExplain ? `Recall explain:\\n${params.recallExplain}` : null,\n params.config.promptAppend?.trim() || null,\n \"Return either NONE or a compact summary grounded only in the supplied context.\",\n ];\n return sections.filter((value): value is string => !!value && value.trim().length > 0).join(\"\\n\\n\");\n}\n\nasync function appendActiveRecallTranscript(\n transcriptRoot: string,\n input: ActiveRecallInput,\n config: ActiveRecallConfig,\n result: ActiveRecallResult,\n queryBundle: string,\n): Promise<string> {\n const date = new Date().toISOString().slice(0, 10);\n const filePath = path.join(\n transcriptRoot,\n \"agents\",\n sanitizeTranscriptPathSegment(input.agentId),\n date,\n `${sanitizeTranscriptPathSegment(input.sessionKey)}.jsonl`,\n );\n await mkdir(path.dirname(filePath), { recursive: true });\n await appendFile(\n filePath,\n `${JSON.stringify({\n ts: new Date().toISOString(),\n sessionKey: input.sessionKey,\n agentId: input.agentId,\n queryMode: config.queryMode,\n promptStyle: config.promptStyle,\n queryBundle,\n summary: result.summary,\n citations: result.citations,\n latencyMs: result.latencyMs,\n cacheHit: result.cacheHit,\n modelUsed: result.modelUsed,\n })}\\n`,\n \"utf8\",\n );\n return filePath;\n}\n\nexport function createActiveRecallEngine(\n deps: ActiveRecallDependencies,\n config: ActiveRecallConfig,\n) {\n const cache = new Map<string, CachedRecallResult>();\n const now = deps.now ?? (() => Date.now());\n\n return {\n async run(input: ActiveRecallInput): Promise<ActiveRecallResult> {\n if (!config.enabled) {\n return {\n summary: null,\n citations: [],\n latencyMs: 0,\n cacheHit: false,\n modelUsed: config.modelOverride ?? \"disabled\",\n transcriptPath: null,\n };\n }\n if (config.agents && !config.agents.includes(input.agentId)) {\n return {\n summary: null,\n citations: [],\n latencyMs: 0,\n cacheHit: false,\n modelUsed: config.modelOverride ?? \"filtered\",\n transcriptPath: null,\n };\n }\n if (!config.allowedChatTypes.includes(input.chatType)) {\n return {\n summary: null,\n citations: [],\n latencyMs: 0,\n cacheHit: false,\n modelUsed: config.modelOverride ?? \"filtered\",\n transcriptPath: null,\n };\n }\n\n const queryBundle = buildActiveRecallQueryBundle(input, config);\n const cacheKey = buildCacheKey(input, config, queryBundle);\n const currentTime = now();\n const cacheEnabled = config.cacheTtlMs > 0;\n if (cacheEnabled) {\n pruneExpiredCache(cache, currentTime);\n }\n const cached = cache.get(cacheKey);\n if (cacheEnabled && cached) {\n return {\n ...cloneRecallResult(cached.value),\n latencyMs: Math.max(0, now() - currentTime),\n cacheHit: true,\n };\n }\n\n const start = currentTime;\n const recallContext = await deps.recall(queryBundle, input.sessionKey);\n const graphContext =\n config.entityGraphDepth > 0 && deps.walkEntityGraph\n ? await deps.walkEntityGraph({\n sessionKey: input.sessionKey,\n query: queryBundle,\n depth: config.entityGraphDepth,\n })\n : [];\n const causalContext =\n config.includeCausalTrajectories && deps.loadCausalTrajectories\n ? await deps.loadCausalTrajectories({\n sessionKey: input.sessionKey,\n query: queryBundle,\n })\n : [];\n const daySummary =\n config.includeDaySummary && deps.loadDaySummary\n ? await deps.loadDaySummary(input.sessionKey)\n : null;\n const recallExplain =\n config.attachRecallExplain && deps.explainLastRecall\n ? await deps.explainLastRecall(input.sessionKey)\n : null;\n const prompt = buildActiveRecallPrompt({\n config,\n queryBundle,\n recallContext,\n graphContext,\n causalContext,\n daySummary,\n recallExplain,\n });\n\n const generated = deps.generateSummary\n ? await deps.generateSummary({\n prompt,\n sessionKey: input.sessionKey,\n agentId: input.agentId,\n model: config.modelOverride ?? \"gpt-5.2\",\n timeoutMs: config.timeoutMs,\n thinking: config.thinking,\n fallbackPolicy: config.modelFallbackPolicy,\n })\n : {\n text: recallContext,\n modelUsed: config.modelOverride ?? \"gpt-5.2\",\n cacheHit: false,\n };\n const summary = normalizeActiveRecallSummary(\n generated.text,\n config.maxSummaryChars,\n );\n const snapshot = deps.getLastRecallSnapshot?.(input.sessionKey);\n const citations = (snapshot?.memoryIds ?? []).map((memoryId, index) => ({\n memoryId,\n relevance: Number((1 / (index + 1)).toFixed(3)),\n }));\n const result: ActiveRecallResult = {\n summary,\n citations,\n latencyMs: Math.max(0, now() - start),\n cacheHit: generated.cacheHit === true,\n modelUsed: generated.modelUsed ?? config.modelOverride ?? \"gpt-5.2\",\n transcriptPath: null,\n };\n if (config.persistTranscripts) {\n result.transcriptPath = await appendActiveRecallTranscript(\n config.transcriptDir,\n input,\n config,\n result,\n queryBundle,\n );\n }\n\n if (cacheEnabled) {\n const completedAt = now();\n cache.set(cacheKey, {\n expiresAt: completedAt + config.cacheTtlMs,\n value: cloneRecallResult(result),\n });\n enforceCacheLimit(cache);\n }\n return result;\n },\n };\n}\n"],"mappings":";;;;;;;AAAA,SAAS,YAAY,aAAa;AAClC,OAAO,UAAU;AA+FjB,IAAM,kCAAkC;AAExC,IAAM,WAAW,oBAAI,IAAI;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AA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B,SAAS,MAAM;AAAA,QACf,OAAO,OAAO,iBAAiB;AAAA,QAC/B,WAAW,OAAO;AAAA,QAClB,UAAU,OAAO;AAAA,QACjB,gBAAgB,OAAO;AAAA,MACzB,CAAC,IACD;AAAA,QACE,MAAM;AAAA,QACN,WAAW,OAAO,iBAAiB;AAAA,QACnC,UAAU;AAAA,MACZ;AACJ,YAAM,UAAU;AAAA,QACd,UAAU;AAAA,QACV,OAAO;AAAA,MACT;AACA,YAAM,WAAW,KAAK,wBAAwB,MAAM,UAAU;AAC9D,YAAM,aAAa,UAAU,aAAa,CAAC,GAAG,IAAI,CAAC,UAAU,WAAW;AAAA,QACtE;AAAA,QACA,WAAW,QAAQ,KAAK,QAAQ,IAAI,QAAQ,CAAC,CAAC;AAAA,MAChD,EAAE;AACF,YAAM,SAA6B;AAAA,QACjC;AAAA,QACA;AAAA,QACA,WAAW,KAAK,IAAI,GAAG,IAAI,IAAI,KAAK;AAAA,QACpC,UAAU,UAAU,aAAa;AAAA,QACjC,WAAW,UAAU,aAAa,OAAO,iBAAiB;AAAA,QAC1D,gBAAgB;AAAA,MAClB;AACA,UAAI,OAAO,oBAAoB;AAC7B,eAAO,iBAAiB,MAAM;AAAA,UAC5B,OAAO;AAAA,UACP;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAEA,UAAI,cAAc;AAChB,cAAM,cAAc,IAAI;AACxB,cAAM,IAAI,UAAU;AAAA,UAClB,WAAW,cAAc,OAAO;AAAA,UAChC,OAAO,kBAAkB,MAAM;AAAA,QACjC,CAAC;AACD,0BAAkB,KAAK;AAAA,MACzB;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
@@ -1,4 +1,5 @@
1
- import { B as BehaviorSignalEvent, P as PluginConfig, e as BehaviorLoopPolicyState } from './types-H85grL1f.js';
1
+ import { BehaviorSignalEvent, PluginConfig, BehaviorLoopPolicyState } from './types.js';
2
+ import './index-1qIcnbG1.js';
2
3
 
3
4
  declare const TUNABLE_BEHAVIOR_PARAMETERS: readonly ["recencyWeight", "lifecyclePromoteHeatThreshold", "lifecycleStaleDecayThreshold", "cronRecallInstructionHeavyTokenCap"];
4
5
  type TunableBehaviorParameter = (typeof TUNABLE_BEHAVIOR_PARAMETERS)[number];
@@ -1,4 +1,5 @@
1
- import { M as MemoryCategory, B as BehaviorSignalEvent } from './types-H85grL1f.js';
1
+ import { MemoryCategory, BehaviorSignalEvent } from './types.js';
2
+ import './index-1qIcnbG1.js';
2
3
 
3
4
  declare function buildBehaviorSignalHash(category: MemoryCategory, content: string): string;
4
5
  declare function buildBehaviorSignalsForMemory(input: {
@@ -1,12 +1,13 @@
1
- import { P as PluginConfig } from './types-H85grL1f.js';
2
- import { O as Orchestrator } from './orchestrator-CvUYwuaL.js';
1
+ import { PluginConfig } from './types.js';
2
+ import { O as Orchestrator } from './orchestrator-6IvQ-Phj.js';
3
+ import './index-1qIcnbG1.js';
3
4
  import './buffer.js';
4
5
  import './storage.js';
5
6
  import './page-versioning.js';
6
7
  import './consolidation-operator.js';
7
- import './memory-projection-store-lCzmu4JX.js';
8
+ import './memory-projection-store-CY8TU40w.js';
8
9
  import 'better-sqlite3';
9
- import './port-BkWL7hqo.js';
10
+ import './port-B6VEDIkC.js';
10
11
  import './transcript.js';
11
12
  import './session-integrity.js';
12
13
  import './summarizer.js';
@@ -21,8 +22,8 @@ import './recall-state.js';
21
22
  import './recall-xray.js';
22
23
  import './session-observer-state.js';
23
24
  import './embedding-fallback.js';
24
- import './semantic-consolidation-CGiH52qa.js';
25
- import './codex-materialize-xVqbEmcm.js';
25
+ import './semantic-consolidation-ByBXb-sf.js';
26
+ import './codex-materialize-CQlLTzke.js';
26
27
  import './logger.js';
27
28
  import 'zod';
28
29
  import './policy-runtime.js';
@@ -1,9 +1,10 @@
1
1
  import { StorageManager } from './storage.js';
2
- import { a6 as BriefingSections, a7 as BriefingFollowup, a8 as BriefingFocus, a9 as CalendarSource, aa as CalendarEvent, f as MemoryFile, ab as BriefingActiveThread, ac as BriefingResult, E as EntityFile, ad as BriefingRecentEntity } from './types-H85grL1f.js';
2
+ import { BriefingSections, BriefingFollowup, BriefingFocus, CalendarSource, CalendarEvent, MemoryFile, BriefingActiveThread, BriefingResult, EntityFile, BriefingRecentEntity } from './types.js';
3
3
  import './page-versioning.js';
4
4
  import './consolidation-operator.js';
5
- import './memory-projection-store-lCzmu4JX.js';
5
+ import './memory-projection-store-CY8TU40w.js';
6
6
  import 'better-sqlite3';
7
+ import './index-1qIcnbG1.js';
7
8
 
8
9
  /**
9
10
  * Daily Context Briefing (Issue #370)
package/dist/briefing.js CHANGED
@@ -16,18 +16,18 @@ import {
16
16
  renderBriefingMarkdown,
17
17
  resolveBriefingSaveDir,
18
18
  validateBriefingFormat
19
- } from "./chunk-4IT6WL23.js";
20
- import "./chunk-XGX4TUF6.js";
19
+ } from "./chunk-WTFWLUSX.js";
20
+ import "./chunk-MCC6KDQF.js";
21
21
  import "./chunk-YNJHCGDT.js";
22
- import "./chunk-4KAN3GZ3.js";
23
- import "./chunk-T65SHTJP.js";
22
+ import "./chunk-NN2DKE4T.js";
23
+ import "./chunk-VQXK37XA.js";
24
24
  import "./chunk-PFV5C235.js";
25
25
  import "./chunk-RULE4VG5.js";
26
26
  import "./chunk-SCU65EZI.js";
27
- import "./chunk-67YLUWLG.js";
27
+ import "./chunk-XJKFSSDW.js";
28
28
  import "./chunk-DM2T26WE.js";
29
29
  import "./chunk-QSVPYQPG.js";
30
- import "./chunk-M62O4P4T.js";
30
+ import "./chunk-FVQJYWH7.js";
31
31
  import "./chunk-4DJQYKMN.js";
32
32
  import "./chunk-G7D6GZ5J.js";
33
33
  import "./chunk-FAAFWE4G.js";
@@ -1,4 +1,5 @@
1
- import { t as BufferSurpriseEvent } from './types-H85grL1f.js';
1
+ import { BufferSurpriseEvent } from './types.js';
2
+ import './index-1qIcnbG1.js';
2
3
 
3
4
  /**
4
5
  * Buffer-surprise telemetry report (issue #563 PR 3).
package/dist/buffer.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import { StorageManager } from './storage.js';
2
- import { P as PluginConfig, a1 as BufferTurn } from './types-H85grL1f.js';
2
+ import { PluginConfig, BufferTurn } from './types.js';
3
3
  import './page-versioning.js';
4
4
  import './consolidation-operator.js';
5
- import './memory-projection-store-lCzmu4JX.js';
5
+ import './memory-projection-store-CY8TU40w.js';
6
6
  import 'better-sqlite3';
7
+ import './index-1qIcnbG1.js';
7
8
 
8
9
  type TriggerDecision = "extract_now" | "extract_batch" | "keep_buffering";
9
10
  /**
@@ -1,5 +1,6 @@
1
1
  import { FallbackLlmClient } from './fallback-llm.js';
2
- import { G as GatewayConfig } from './types-H85grL1f.js';
2
+ import { GatewayConfig } from './types.js';
3
+ import './index-1qIcnbG1.js';
3
4
 
4
5
  /**
5
6
  * calibration.ts — Prediction-Error-Driven Model-User Calibration
@@ -66,6 +67,7 @@ declare function runCalibrationConsolidation(options: {
66
67
  memoryDir: string;
67
68
  gatewayConfig?: GatewayConfig;
68
69
  gatewayAgentId?: string;
70
+ workspaceDir?: string;
69
71
  }): Promise<CalibrationRule[]>;
70
72
  /**
71
73
  * Standalone entry point for calibration consolidation that can be called
@@ -78,6 +80,7 @@ declare function runCalibrationIfEnabled(options: {
78
80
  memoryDir: string;
79
81
  calibrationEnabled: boolean;
80
82
  gatewayConfig?: GatewayConfig;
83
+ workspaceDir?: string;
81
84
  }): Promise<CalibrationRule[]>;
82
85
  /**
83
86
  * Get calibration rules for recall injection.
@@ -1,10 +1,12 @@
1
1
  import {
2
2
  FallbackLlmClient
3
- } from "./chunk-DWMXVUGO.js";
4
- import "./chunk-Q7FJ5ZHM.js";
5
- import "./chunk-ODWDQNRE.js";
3
+ } from "./chunk-VX2IUQFE.js";
4
+ import "./chunk-S3IP6R6K.js";
6
5
  import "./chunk-L2EXJQJP.js";
6
+ import "./chunk-7SI52C65.js";
7
7
  import "./chunk-UZB5KHKX.js";
8
+ import "./chunk-KWBPHZUU.js";
9
+ import "./chunk-IXEJRKCZ.js";
8
10
  import "./chunk-MARWOCVP.js";
9
11
  import {
10
12
  log
@@ -183,7 +185,9 @@ function buildCalibrationRecallSection(rules, query, maxChars = 1200) {
183
185
  }
184
186
  async function runCalibrationConsolidation(options) {
185
187
  try {
186
- const llm = new FallbackLlmClient(options.gatewayConfig);
188
+ const llm = new FallbackLlmClient(options.gatewayConfig, {
189
+ workspaceDir: options.workspaceDir
190
+ });
187
191
  if (!llm.isAvailable(options.gatewayAgentId)) {
188
192
  log.debug("[calibration] no LLM available \u2014 skipping consolidation");
189
193
  return [];
@@ -229,7 +233,8 @@ async function runCalibrationIfEnabled(options) {
229
233
  }
230
234
  return runCalibrationConsolidation({
231
235
  memoryDir: options.memoryDir,
232
- gatewayConfig: options.gatewayConfig
236
+ gatewayConfig: options.gatewayConfig,
237
+ workspaceDir: options.workspaceDir
233
238
  });
234
239
  }
235
240
  async function getCalibrationRulesForRecall(memoryDir) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/calibration.ts"],"sourcesContent":["/**\n * calibration.ts — Prediction-Error-Driven Model-User Calibration\n *\n * Analyzes patterns in user corrections to identify systematic miscalibration\n * between the model's predictions and the user's actual expectations.\n * During consolidation, replays chains of similar corrections through an LLM\n * to synthesize CalibrationRules that adjust model behavior for this specific user.\n *\n * Inspired by:\n * - Cerebellar motor calibration (prediction errors drive lasting adjustments)\n * - Temporal difference learning (dopamine signals prediction error)\n * - Tesla FSD shadow mode (divergence between prediction and reality = training signal)\n */\n\nimport { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { FallbackLlmClient } from \"./fallback-llm.js\";\nimport type { GatewayConfig, MemoryFile } from \"./types.js\";\nimport { listJsonFiles, readJsonFile } from \"./json-store.js\";\nimport { isRecord } from \"./store-contract.js\";\nimport { log } from \"./logger.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface CalibrationRule {\n id: string;\n ruleType: \"model_tendency\" | \"user_expectation\" | \"scope_boundary\" | \"verification_required\";\n condition: string;\n modelTendency: string;\n userExpectation: string;\n calibration: string;\n confidence: number;\n evidenceCount: number;\n evidenceCorrectionIds: string[];\n createdAt: string;\n lastReinforcedAt: string;\n}\n\nexport interface CalibrationIndex {\n rules: CalibrationRule[];\n updatedAt: string;\n totalCorrectionsAnalyzed: number;\n}\n\n// ─── Storage ─────────────────────────────────────────────────────────────────\n\nfunction calibrationDir(memoryDir: string): string {\n return path.join(memoryDir, \"state\", \"calibration\");\n}\n\nfunction calibrationIndexPath(memoryDir: string): string {\n return path.join(calibrationDir(memoryDir), \"calibration-index.json\");\n}\n\nexport async function readCalibrationIndex(memoryDir: string): Promise<CalibrationIndex> {\n try {\n const raw = JSON.parse(await readFile(calibrationIndexPath(memoryDir), \"utf8\"));\n return {\n rules: Array.isArray(raw.rules) ? raw.rules : [],\n updatedAt: typeof raw.updatedAt === \"string\" ? raw.updatedAt : new Date().toISOString(),\n totalCorrectionsAnalyzed: typeof raw.totalCorrectionsAnalyzed === \"number\" ? raw.totalCorrectionsAnalyzed : 0,\n };\n } catch {\n return { rules: [], updatedAt: new Date().toISOString(), totalCorrectionsAnalyzed: 0 };\n }\n}\n\nasync function writeCalibrationIndex(memoryDir: string, index: CalibrationIndex): Promise<void> {\n const dir = calibrationDir(memoryDir);\n await mkdir(dir, { recursive: true });\n index.updatedAt = new Date().toISOString();\n await writeFile(calibrationIndexPath(memoryDir), JSON.stringify(index, null, 2), \"utf8\");\n}\n\n// ─── Correction Reading ──────────────────────────────────────────────────────\n\nexport interface CorrectionMemory {\n id: string;\n content: string;\n created: string;\n confidence: number;\n entityRefs: string[];\n tags: string[];\n}\n\n/**\n * Exported for entity-contamination R-11 regression coverage (#682\n * PR 2/3 — codex review). Tests can drive the real correction-reading\n * path instead of duplicating the regex inline, so calibration parser\n * regressions surface via the contamination suite.\n */\nexport async function readCalibrationCorrections(memoryDir: string): Promise<CorrectionMemory[]> {\n return readCorrectionsImpl(memoryDir);\n}\n\nasync function readCorrections(memoryDir: string): Promise<CorrectionMemory[]> {\n return readCorrectionsImpl(memoryDir);\n}\n\nasync function readCorrectionsImpl(memoryDir: string): Promise<CorrectionMemory[]> {\n const correctionsDir = path.join(memoryDir, \"corrections\");\n const files = await listJsonFiles(correctionsDir).catch(() => {\n // Corrections might be in facts/ directories too\n return [] as string[];\n });\n\n // Also scan facts directories for correction-category files\n const factsDir = path.join(memoryDir, \"facts\");\n try {\n const { readdir } = await import(\"node:fs/promises\");\n const dayDirs = (await readdir(factsDir)).filter((d: string) => /^\\d{4}-\\d{2}-\\d{2}$/.test(d));\n for (const day of dayDirs) {\n const dayPath = path.join(factsDir, day);\n const dayFiles = (await readdir(dayPath))\n .filter((f: string) => f.startsWith(\"correction-\") && f.endsWith(\".md\"))\n .map((f: string) => path.join(dayPath, f));\n files.push(...dayFiles);\n }\n } catch {\n // facts dir might not exist\n }\n\n // Also check the dedicated corrections directory\n try {\n const { readdir } = await import(\"node:fs/promises\");\n const corrFiles = (await readdir(correctionsDir))\n .filter((f: string) => f.endsWith(\".md\"))\n .map((f: string) => path.join(correctionsDir, f));\n files.push(...corrFiles);\n } catch {\n // corrections dir might not exist\n }\n\n const corrections: CorrectionMemory[] = [];\n const seen = new Set<string>();\n\n for (const filePath of files) {\n try {\n const raw = await readFile(filePath, \"utf8\");\n\n // Parse frontmatter\n const fmMatch = raw.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n if (!fmMatch) continue;\n\n const content = fmMatch[2].trim();\n if (!content || content.length < 10) continue;\n\n // Extract id from frontmatter\n const idMatch = fmMatch[1].match(/^id:\\s*(.+)$/m);\n const id = idMatch?.[1]?.trim() ?? path.basename(filePath, \".md\");\n\n if (seen.has(id)) continue;\n seen.add(id);\n\n const confMatch = fmMatch[1].match(/^confidence:\\s*(.+)$/m);\n const confidence = confMatch ? parseFloat(confMatch[1]) : 0.9;\n\n const entityMatch = fmMatch[1].match(/^entityRef:\\s*(.+)$/m);\n const entityRefs = entityMatch ? [entityMatch[1].trim()] : [];\n\n corrections.push({ id, content, created: \"\", confidence, entityRefs, tags: [] });\n } catch {\n // skip unparseable files\n }\n }\n\n return corrections;\n}\n\n// ─── LLM-Assisted Clustering and Replay ──────────────────────────────────────\n\nconst CLUSTER_PROMPT = `You are analyzing user corrections to an AI assistant. Each correction represents a moment where the assistant's prediction of what the user wanted was WRONG.\n\nYour job: Group these corrections into clusters where the SAME TYPE of misunderstanding is happening. Then for each cluster, synthesize a CalibrationRule.\n\nA CalibrationRule describes:\n- condition: When does this type of mistake happen?\n- modelTendency: What does the model tend to assume or do wrong?\n- userExpectation: What does the user actually want instead?\n- calibration: How should the model adjust its behavior?\n- ruleType: One of \"model_tendency\", \"user_expectation\", \"scope_boundary\", \"verification_required\"\n\nFocus on PATTERNS, not individual corrections. A cluster needs at least 2 corrections to be worth a rule.\n\nOutput valid JSON only:\n{\n \"rules\": [\n {\n \"ruleType\": \"model_tendency\",\n \"condition\": \"When discussing project scope or task boundaries\",\n \"modelTendency\": \"The model tends to assume broader scope than the user intends\",\n \"userExpectation\": \"The user prefers narrow, specific task definitions and wants to be asked before scope expansion\",\n \"calibration\": \"When uncertain about scope, ask for clarification rather than assuming. Default to the narrower interpretation.\",\n \"confidence\": 0.85,\n \"evidenceIds\": [\"correction-id-1\", \"correction-id-2\"]\n }\n ]\n}`;\n\nexport async function synthesizeCalibrationRules(\n corrections: CorrectionMemory[],\n llm: FallbackLlmClient,\n existingRules: CalibrationRule[],\n agentId?: string,\n): Promise<CalibrationRule[]> {\n if (corrections.length < 2) return [];\n\n // Format corrections for the LLM\n const correctionText = corrections\n .slice(0, 50) // limit to avoid huge prompts\n .map((c, i) => `[${c.id}] ${c.content}`)\n .join(\"\\n\\n\");\n\n const existingRulesText = existingRules.length > 0\n ? `\\n\\nExisting calibration rules (avoid duplicating these):\\n${existingRules.map((r) => `- ${r.condition}: ${r.calibration}`).join(\"\\n\")}`\n : \"\";\n\n const response = await llm.chatCompletion(\n [\n { role: \"system\", content: CLUSTER_PROMPT },\n { role: \"user\", content: `Here are ${corrections.length} corrections from this user:\\n\\n${correctionText}${existingRulesText}` },\n ],\n { temperature: 0.3, maxTokens: 3000, agentId },\n );\n\n if (!response?.content) return [];\n\n try {\n let jsonStr = response.content.trim();\n const fenceMatch = jsonStr.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?\\s*```/);\n if (fenceMatch) jsonStr = fenceMatch[1];\n\n const parsed = JSON.parse(jsonStr);\n if (!Array.isArray(parsed.rules)) return [];\n\n const now = new Date().toISOString();\n return parsed.rules\n .filter((r: any) => r.condition && r.calibration && r.modelTendency)\n .map((r: any) => ({\n id: `cal-${createHash(\"sha256\").update(r.condition + r.calibration).digest(\"hex\").slice(0, 12)}`,\n ruleType: r.ruleType ?? \"model_tendency\",\n condition: String(r.condition),\n modelTendency: String(r.modelTendency),\n userExpectation: String(r.userExpectation ?? \"\"),\n calibration: String(r.calibration),\n confidence: typeof r.confidence === \"number\" ? r.confidence : 0.7,\n evidenceCount: Array.isArray(r.evidenceIds) ? r.evidenceIds.length : 1,\n evidenceCorrectionIds: Array.isArray(r.evidenceIds) ? r.evidenceIds : [],\n createdAt: now,\n lastReinforcedAt: now,\n }));\n } catch {\n log.warn(\"[calibration] failed to parse LLM response\");\n return [];\n }\n}\n\n// ─── Recall Section ──────────────────────────────────────────────────────────\n\n/**\n * Build a recall section from calibration rules relevant to the current query.\n * Uses the LLM to select which rules apply to the current context.\n */\nexport function buildCalibrationRecallSection(\n rules: CalibrationRule[],\n query: string,\n maxChars: number = 1200,\n): string | null {\n if (rules.length === 0) return null;\n\n // Simple relevance: include all rules (they're already filtered to this user)\n // In production, could use embedding similarity to filter\n const lines: string[] = [\n \"## Model Calibration (learned from past corrections)\",\n \"\",\n \"Adjustments for this specific user, learned from patterns in their corrections:\",\n \"\",\n ];\n\n let totalChars = lines.join(\"\\n\").length;\n\n for (const rule of rules) {\n const line = `- **${rule.condition}**: ${rule.modelTendency} → Instead: ${rule.calibration}`;\n if (totalChars + line.length + 1 > maxChars) break;\n lines.push(line);\n totalChars += line.length + 1;\n }\n\n if (lines.length <= 4) return null;\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Run the full calibration pipeline:\n * 1. Read all corrections\n * 2. Send to LLM for clustering and rule synthesis\n * 3. Merge with existing rules\n * 4. Write updated index\n */\nexport async function runCalibrationConsolidation(options: {\n memoryDir: string;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n}): Promise<CalibrationRule[]> {\n try {\n const llm = new FallbackLlmClient(options.gatewayConfig);\n if (!llm.isAvailable(options.gatewayAgentId)) {\n log.debug(\"[calibration] no LLM available — skipping consolidation\");\n return [];\n }\n\n const corrections = await readCorrections(options.memoryDir);\n if (corrections.length < 3) {\n log.debug(`[calibration] only ${corrections.length} corrections — need at least 3`);\n return [];\n }\n\n const existingIndex = await readCalibrationIndex(options.memoryDir);\n\n const newRules = await synthesizeCalibrationRules(corrections, llm, existingIndex.rules, options.gatewayAgentId);\n if (newRules.length === 0) {\n log.debug(\"[calibration] no new calibration rules synthesized\");\n return existingIndex.rules;\n }\n\n // Merge: keep existing rules, add new ones (deduplicate by id)\n const ruleMap = new Map(existingIndex.rules.map((r) => [r.id, r]));\n for (const rule of newRules) {\n if (ruleMap.has(rule.id)) {\n // Reinforce existing rule\n const existing = ruleMap.get(rule.id)!;\n existing.lastReinforcedAt = new Date().toISOString();\n existing.evidenceCount += rule.evidenceCount;\n existing.confidence = Math.min(1, existing.confidence + 0.05);\n } else {\n ruleMap.set(rule.id, rule);\n }\n }\n\n const allRules = [...ruleMap.values()];\n await writeCalibrationIndex(options.memoryDir, {\n rules: allRules,\n updatedAt: new Date().toISOString(),\n totalCorrectionsAnalyzed: corrections.length,\n });\n\n log.debug(`[calibration] synthesized ${newRules.length} new rule(s), ${allRules.length} total`);\n return allRules;\n } catch (error) {\n log.warn(`[calibration] consolidation failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`);\n return [];\n }\n}\n\n/**\n * Standalone entry point for calibration consolidation that can be called\n * independently of weekly compounding. The compounding engine's\n * `synthesizeWeekly()` is one trigger, but orchestrators or periodic\n * maintenance jobs should call this directly so calibration is not gated\n * on weekly compounding being enabled.\n */\nexport async function runCalibrationIfEnabled(options: {\n memoryDir: string;\n calibrationEnabled: boolean;\n gatewayConfig?: GatewayConfig;\n}): Promise<CalibrationRule[]> {\n if (!options.calibrationEnabled) {\n return [];\n }\n return runCalibrationConsolidation({\n memoryDir: options.memoryDir,\n gatewayConfig: options.gatewayConfig,\n });\n}\n\n/**\n * Get calibration rules for recall injection.\n * Reads the pre-computed calibration index.\n */\nexport async function getCalibrationRulesForRecall(\n memoryDir: string,\n): Promise<CalibrationRule[]> {\n const index = await readCalibrationIndex(memoryDir);\n return index.rules;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAcA,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AACjB,SAAS,OAAO,UAAU,iBAAiB;AA+B3C,SAAS,eAAe,WAA2B;AACjD,SAAO,KAAK,KAAK,WAAW,SAAS,aAAa;AACpD;AAEA,SAAS,qBAAqB,WAA2B;AACvD,SAAO,KAAK,KAAK,eAAe,SAAS,GAAG,wBAAwB;AACtE;AAEA,eAAsB,qBAAqB,WAA8C;AACvF,MAAI;AACF,UAAM,MAAM,KAAK,MAAM,MAAM,SAAS,qBAAqB,SAAS,GAAG,MAAM,CAAC;AAC9E,WAAO;AAAA,MACL,OAAO,MAAM,QAAQ,IAAI,KAAK,IAAI,IAAI,QAAQ,CAAC;AAAA,MAC/C,WAAW,OAAO,IAAI,cAAc,WAAW,IAAI,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,MACtF,0BAA0B,OAAO,IAAI,6BAA6B,WAAW,IAAI,2BAA2B;AAAA,IAC9G;AAAA,EACF,QAAQ;AACN,WAAO,EAAE,OAAO,CAAC,GAAG,YAAW,oBAAI,KA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AAQ,MAAM,qBAAqB,SAAS;AAClD,SAAO,MAAM;AACf;","names":[]}
1
+ {"version":3,"sources":["../src/calibration.ts"],"sourcesContent":["/**\n * calibration.ts — Prediction-Error-Driven Model-User Calibration\n *\n * Analyzes patterns in user corrections to identify systematic miscalibration\n * between the model's predictions and the user's actual expectations.\n * During consolidation, replays chains of similar corrections through an LLM\n * to synthesize CalibrationRules that adjust model behavior for this specific user.\n *\n * Inspired by:\n * - Cerebellar motor calibration (prediction errors drive lasting adjustments)\n * - Temporal difference learning (dopamine signals prediction error)\n * - Tesla FSD shadow mode (divergence between prediction and reality = training signal)\n */\n\nimport { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { FallbackLlmClient } from \"./fallback-llm.js\";\nimport type { GatewayConfig, MemoryFile } from \"./types.js\";\nimport { listJsonFiles, readJsonFile } from \"./json-store.js\";\nimport { isRecord } from \"./store-contract.js\";\nimport { log } from \"./logger.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface CalibrationRule {\n id: string;\n ruleType: \"model_tendency\" | \"user_expectation\" | \"scope_boundary\" | \"verification_required\";\n condition: string;\n modelTendency: string;\n userExpectation: string;\n calibration: string;\n confidence: number;\n evidenceCount: number;\n evidenceCorrectionIds: string[];\n createdAt: string;\n lastReinforcedAt: string;\n}\n\nexport interface CalibrationIndex {\n rules: CalibrationRule[];\n updatedAt: string;\n totalCorrectionsAnalyzed: number;\n}\n\n// ─── Storage ─────────────────────────────────────────────────────────────────\n\nfunction calibrationDir(memoryDir: string): string {\n return path.join(memoryDir, \"state\", \"calibration\");\n}\n\nfunction calibrationIndexPath(memoryDir: string): string {\n return path.join(calibrationDir(memoryDir), \"calibration-index.json\");\n}\n\nexport async function readCalibrationIndex(memoryDir: string): Promise<CalibrationIndex> {\n try {\n const raw = JSON.parse(await readFile(calibrationIndexPath(memoryDir), \"utf8\"));\n return {\n rules: Array.isArray(raw.rules) ? raw.rules : [],\n updatedAt: typeof raw.updatedAt === \"string\" ? raw.updatedAt : new Date().toISOString(),\n totalCorrectionsAnalyzed: typeof raw.totalCorrectionsAnalyzed === \"number\" ? raw.totalCorrectionsAnalyzed : 0,\n };\n } catch {\n return { rules: [], updatedAt: new Date().toISOString(), totalCorrectionsAnalyzed: 0 };\n }\n}\n\nasync function writeCalibrationIndex(memoryDir: string, index: CalibrationIndex): Promise<void> {\n const dir = calibrationDir(memoryDir);\n await mkdir(dir, { recursive: true });\n index.updatedAt = new Date().toISOString();\n await writeFile(calibrationIndexPath(memoryDir), JSON.stringify(index, null, 2), \"utf8\");\n}\n\n// ─── Correction Reading ──────────────────────────────────────────────────────\n\nexport interface CorrectionMemory {\n id: string;\n content: string;\n created: string;\n confidence: number;\n entityRefs: string[];\n tags: string[];\n}\n\n/**\n * Exported for entity-contamination R-11 regression coverage (#682\n * PR 2/3 — codex review). Tests can drive the real correction-reading\n * path instead of duplicating the regex inline, so calibration parser\n * regressions surface via the contamination suite.\n */\nexport async function readCalibrationCorrections(memoryDir: string): Promise<CorrectionMemory[]> {\n return readCorrectionsImpl(memoryDir);\n}\n\nasync function readCorrections(memoryDir: string): Promise<CorrectionMemory[]> {\n return readCorrectionsImpl(memoryDir);\n}\n\nasync function readCorrectionsImpl(memoryDir: string): Promise<CorrectionMemory[]> {\n const correctionsDir = path.join(memoryDir, \"corrections\");\n const files = await listJsonFiles(correctionsDir).catch(() => {\n // Corrections might be in facts/ directories too\n return [] as string[];\n });\n\n // Also scan facts directories for correction-category files\n const factsDir = path.join(memoryDir, \"facts\");\n try {\n const { readdir } = await import(\"node:fs/promises\");\n const dayDirs = (await readdir(factsDir)).filter((d: string) => /^\\d{4}-\\d{2}-\\d{2}$/.test(d));\n for (const day of dayDirs) {\n const dayPath = path.join(factsDir, day);\n const dayFiles = (await readdir(dayPath))\n .filter((f: string) => f.startsWith(\"correction-\") && f.endsWith(\".md\"))\n .map((f: string) => path.join(dayPath, f));\n files.push(...dayFiles);\n }\n } catch {\n // facts dir might not exist\n }\n\n // Also check the dedicated corrections directory\n try {\n const { readdir } = await import(\"node:fs/promises\");\n const corrFiles = (await readdir(correctionsDir))\n .filter((f: string) => f.endsWith(\".md\"))\n .map((f: string) => path.join(correctionsDir, f));\n files.push(...corrFiles);\n } catch {\n // corrections dir might not exist\n }\n\n const corrections: CorrectionMemory[] = [];\n const seen = new Set<string>();\n\n for (const filePath of files) {\n try {\n const raw = await readFile(filePath, \"utf8\");\n\n // Parse frontmatter\n const fmMatch = raw.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n if (!fmMatch) continue;\n\n const content = fmMatch[2].trim();\n if (!content || content.length < 10) continue;\n\n // Extract id from frontmatter\n const idMatch = fmMatch[1].match(/^id:\\s*(.+)$/m);\n const id = idMatch?.[1]?.trim() ?? path.basename(filePath, \".md\");\n\n if (seen.has(id)) continue;\n seen.add(id);\n\n const confMatch = fmMatch[1].match(/^confidence:\\s*(.+)$/m);\n const confidence = confMatch ? parseFloat(confMatch[1]) : 0.9;\n\n const entityMatch = fmMatch[1].match(/^entityRef:\\s*(.+)$/m);\n const entityRefs = entityMatch ? [entityMatch[1].trim()] : [];\n\n corrections.push({ id, content, created: \"\", confidence, entityRefs, tags: [] });\n } catch {\n // skip unparseable files\n }\n }\n\n return corrections;\n}\n\n// ─── LLM-Assisted Clustering and Replay ──────────────────────────────────────\n\nconst CLUSTER_PROMPT = `You are analyzing user corrections to an AI assistant. Each correction represents a moment where the assistant's prediction of what the user wanted was WRONG.\n\nYour job: Group these corrections into clusters where the SAME TYPE of misunderstanding is happening. Then for each cluster, synthesize a CalibrationRule.\n\nA CalibrationRule describes:\n- condition: When does this type of mistake happen?\n- modelTendency: What does the model tend to assume or do wrong?\n- userExpectation: What does the user actually want instead?\n- calibration: How should the model adjust its behavior?\n- ruleType: One of \"model_tendency\", \"user_expectation\", \"scope_boundary\", \"verification_required\"\n\nFocus on PATTERNS, not individual corrections. A cluster needs at least 2 corrections to be worth a rule.\n\nOutput valid JSON only:\n{\n \"rules\": [\n {\n \"ruleType\": \"model_tendency\",\n \"condition\": \"When discussing project scope or task boundaries\",\n \"modelTendency\": \"The model tends to assume broader scope than the user intends\",\n \"userExpectation\": \"The user prefers narrow, specific task definitions and wants to be asked before scope expansion\",\n \"calibration\": \"When uncertain about scope, ask for clarification rather than assuming. Default to the narrower interpretation.\",\n \"confidence\": 0.85,\n \"evidenceIds\": [\"correction-id-1\", \"correction-id-2\"]\n }\n ]\n}`;\n\nexport async function synthesizeCalibrationRules(\n corrections: CorrectionMemory[],\n llm: FallbackLlmClient,\n existingRules: CalibrationRule[],\n agentId?: string,\n): Promise<CalibrationRule[]> {\n if (corrections.length < 2) return [];\n\n // Format corrections for the LLM\n const correctionText = corrections\n .slice(0, 50) // limit to avoid huge prompts\n .map((c, i) => `[${c.id}] ${c.content}`)\n .join(\"\\n\\n\");\n\n const existingRulesText = existingRules.length > 0\n ? `\\n\\nExisting calibration rules (avoid duplicating these):\\n${existingRules.map((r) => `- ${r.condition}: ${r.calibration}`).join(\"\\n\")}`\n : \"\";\n\n const response = await llm.chatCompletion(\n [\n { role: \"system\", content: CLUSTER_PROMPT },\n { role: \"user\", content: `Here are ${corrections.length} corrections from this user:\\n\\n${correctionText}${existingRulesText}` },\n ],\n { temperature: 0.3, maxTokens: 3000, agentId },\n );\n\n if (!response?.content) return [];\n\n try {\n let jsonStr = response.content.trim();\n const fenceMatch = jsonStr.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?\\s*```/);\n if (fenceMatch) jsonStr = fenceMatch[1];\n\n const parsed = JSON.parse(jsonStr);\n if (!Array.isArray(parsed.rules)) return [];\n\n const now = new Date().toISOString();\n return parsed.rules\n .filter((r: any) => r.condition && r.calibration && r.modelTendency)\n .map((r: any) => ({\n id: `cal-${createHash(\"sha256\").update(r.condition + r.calibration).digest(\"hex\").slice(0, 12)}`,\n ruleType: r.ruleType ?? \"model_tendency\",\n condition: String(r.condition),\n modelTendency: String(r.modelTendency),\n userExpectation: String(r.userExpectation ?? \"\"),\n calibration: String(r.calibration),\n confidence: typeof r.confidence === \"number\" ? r.confidence : 0.7,\n evidenceCount: Array.isArray(r.evidenceIds) ? r.evidenceIds.length : 1,\n evidenceCorrectionIds: Array.isArray(r.evidenceIds) ? r.evidenceIds : [],\n createdAt: now,\n lastReinforcedAt: now,\n }));\n } catch {\n log.warn(\"[calibration] failed to parse LLM response\");\n return [];\n }\n}\n\n// ─── Recall Section ──────────────────────────────────────────────────────────\n\n/**\n * Build a recall section from calibration rules relevant to the current query.\n * Uses the LLM to select which rules apply to the current context.\n */\nexport function buildCalibrationRecallSection(\n rules: CalibrationRule[],\n query: string,\n maxChars: number = 1200,\n): string | null {\n if (rules.length === 0) return null;\n\n // Simple relevance: include all rules (they're already filtered to this user)\n // In production, could use embedding similarity to filter\n const lines: string[] = [\n \"## Model Calibration (learned from past corrections)\",\n \"\",\n \"Adjustments for this specific user, learned from patterns in their corrections:\",\n \"\",\n ];\n\n let totalChars = lines.join(\"\\n\").length;\n\n for (const rule of rules) {\n const line = `- **${rule.condition}**: ${rule.modelTendency} → Instead: ${rule.calibration}`;\n if (totalChars + line.length + 1 > maxChars) break;\n lines.push(line);\n totalChars += line.length + 1;\n }\n\n if (lines.length <= 4) return null;\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Run the full calibration pipeline:\n * 1. Read all corrections\n * 2. Send to LLM for clustering and rule synthesis\n * 3. Merge with existing rules\n * 4. Write updated index\n */\nexport async function runCalibrationConsolidation(options: {\n memoryDir: string;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n workspaceDir?: string;\n}): Promise<CalibrationRule[]> {\n try {\n const llm = new FallbackLlmClient(options.gatewayConfig, {\n workspaceDir: options.workspaceDir,\n });\n if (!llm.isAvailable(options.gatewayAgentId)) {\n log.debug(\"[calibration] no LLM available — skipping consolidation\");\n return [];\n }\n\n const corrections = await readCorrections(options.memoryDir);\n if (corrections.length < 3) {\n log.debug(`[calibration] only ${corrections.length} corrections — need at least 3`);\n return [];\n }\n\n const existingIndex = await readCalibrationIndex(options.memoryDir);\n\n const newRules = await synthesizeCalibrationRules(corrections, llm, existingIndex.rules, options.gatewayAgentId);\n if (newRules.length === 0) {\n log.debug(\"[calibration] no new calibration rules synthesized\");\n return existingIndex.rules;\n }\n\n // Merge: keep existing rules, add new ones (deduplicate by id)\n const ruleMap = new Map(existingIndex.rules.map((r) => [r.id, r]));\n for (const rule of newRules) {\n if (ruleMap.has(rule.id)) {\n // Reinforce existing rule\n const existing = ruleMap.get(rule.id)!;\n existing.lastReinforcedAt = new Date().toISOString();\n existing.evidenceCount += rule.evidenceCount;\n existing.confidence = Math.min(1, existing.confidence + 0.05);\n } else {\n ruleMap.set(rule.id, rule);\n }\n }\n\n const allRules = [...ruleMap.values()];\n await writeCalibrationIndex(options.memoryDir, {\n rules: allRules,\n updatedAt: new Date().toISOString(),\n totalCorrectionsAnalyzed: corrections.length,\n });\n\n log.debug(`[calibration] synthesized ${newRules.length} new rule(s), ${allRules.length} total`);\n return allRules;\n } catch (error) {\n log.warn(`[calibration] consolidation failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`);\n return [];\n }\n}\n\n/**\n * Standalone entry point for calibration consolidation that can be called\n * independently of weekly compounding. The compounding engine's\n * `synthesizeWeekly()` is one trigger, but orchestrators or periodic\n * maintenance jobs should call this directly so calibration is not gated\n * on weekly compounding being enabled.\n */\nexport async function runCalibrationIfEnabled(options: {\n memoryDir: string;\n calibrationEnabled: boolean;\n gatewayConfig?: GatewayConfig;\n workspaceDir?: string;\n}): Promise<CalibrationRule[]> {\n if (!options.calibrationEnabled) {\n return [];\n }\n return runCalibrationConsolidation({\n memoryDir: options.memoryDir,\n gatewayConfig: options.gatewayConfig,\n workspaceDir: options.workspaceDir,\n });\n}\n\n/**\n * Get calibration rules for recall injection.\n * Reads the pre-computed calibration index.\n */\nexport async function getCalibrationRulesForRecall(\n memoryDir: string,\n): Promise<CalibrationRule[]> {\n const index = await readCalibrationIndex(memoryDir);\n return index.rules;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAcA,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AACjB,SAAS,OAAO,UAAU,iBAAiB;AA+B3C,SAAS,eAAe,WAA2B;AACjD,SAAO,KAAK,KAAK,WAAW,SAAS,aAAa;AACpD;AAEA,SAAS,qBAAqB,WAA2B;AACvD,SAAO,KAAK,KAAK,eAAe,SAAS,GAAG,wBAAwB;AACtE;AAEA,eAAsB,qBAAqB,WAA8C;AACvF,MAAI;AACF,UAAM,MAAM,KAAK,MAAM,MAAM,SAAS,qBAAqB,SAAS,GAAG,MAAM,CAAC;AAC9E,WAAO;AAAA,MACL,OAAO,MAAM,QAAQ,IAAI,KAAK,IAAI,IAAI,QAAQ,CAAC;AAAA,MAC/C,WAAW,OAAO,IAAI,cAAc,WAAW,IAAI,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,MACtF,0BAA0B,OAAO,IAAI,6BAA6B,WAAW,IAAI,2BAA2B;AAAA,IAC9G;AAAA,EACF,QAAQ;AACN,WAAO,EAAE,OAAO,CAAC,GAAG,YAAW,oBAAI,KAAK,GAAE,YAAY,GAAG,0BAA0B,EAAE;AAAA,EACvF;AACF;AAEA,eAAe,sBAAsB,WAAmB,OAAwC;AAC9F,QAAM,MAAM,eAAe,SAAS;AACpC,QAAM,MAAM,KAAK,EAAE,WAAW,KAAK,CAAC;AACpC,QAAM,aAAY,oBAAI,KAAK,GAAE,YAAY;AACzC,QAAM,UAAU,qBAAqB,SAAS,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,GAAG,MAAM;AACzF;AAmBA,eAAsB,2BAA2B,WAAgD;AAC/F,SAAO,oBAAoB,SAAS;AACtC;AAEA,eAAe,gBAAgB,WAAgD;AAC7E,SAAO,oBAAoB,SAAS;AACtC;AAEA,eAAe,oBAAoB,WAAgD;AACjF,QAAM,i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I,KAAK,GAAE,YAAY;AACnD,iBAAS,iBAAiB,KAAK;AAC/B,iBAAS,aAAa,KAAK,IAAI,GAAG,SAAS,aAAa,IAAI;AAAA,MAC9D,OAAO;AACL,gBAAQ,IAAI,KAAK,IAAI,IAAI;AAAA,MAC3B;AAAA,IACF;AAEA,UAAM,WAAW,CAAC,GAAG,QAAQ,OAAO,CAAC;AACrC,UAAM,sBAAsB,QAAQ,WAAW;AAAA,MAC7C,OAAO;AAAA,MACP,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MAClC,0BAA0B,YAAY;AAAA,IACxC,CAAC;AAED,QAAI,MAAM,6BAA6B,SAAS,MAAM,iBAAiB,SAAS,MAAM,QAAQ;AAC9F,WAAO;AAAA,EACT,SAAS,OAAO;AACd,QAAI,KAAK,mDAAmD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AACpH,WAAO,CAAC;AAAA,EACV;AACF;AASA,eAAsB,wBAAwB,SAKf;AAC7B,MAAI,CAAC,QAAQ,oBAAoB;AAC/B,WAAO,CAAC;AAAA,EACV;AACA,SAAO,4BAA4B;AAAA,IACjC,WAAW,QAAQ;AAAA,IACnB,eAAe,QAAQ;AAAA,IACvB,cAAc,QAAQ;AAAA,EACxB,CAAC;AACH;AAMA,eAAsB,6BACpB,WAC4B;AAC5B,QAAM,QAAQ,MAAM,qBAAqB,SAAS;AAClD,SAAO,MAAM;AACf;","names":[]}
@@ -1,7 +1,8 @@
1
1
  import { CausalChainIndex } from './causal-chain.js';
2
- import { M as MemoryCategory } from './types-H85grL1f.js';
2
+ import { MemoryCategory } from './types.js';
3
3
  import './causal-trajectory.js';
4
4
  import './objective-state.js';
5
+ import './index-1qIcnbG1.js';
5
6
 
6
7
  /**
7
8
  * preference-consolidator.ts — IRC Preference Consolidation for Engram
@@ -1,5 +1,6 @@
1
- import { G as GatewayConfig, P as PluginConfig, f as MemoryFile } from './types-H85grL1f.js';
2
- import { R as RolloutSummaryInput, M as MaterializeResult } from './codex-materialize-xVqbEmcm.js';
1
+ import { GatewayConfig, PluginConfig, MemoryFile } from './types.js';
2
+ import { R as RolloutSummaryInput, M as MaterializeResult } from './codex-materialize-CQlLTzke.js';
3
+ import './index-1qIcnbG1.js';
3
4
 
4
5
  /**
5
6
  * causal-consolidation.ts — CMC Phase 2: LLM-Assisted Causal Consolidation
@@ -56,6 +57,7 @@ declare function deriveCausalPromotionCandidates(options: {
56
57
  config: ConsolidationConfig;
57
58
  gatewayConfig?: GatewayConfig;
58
59
  gatewayAgentId?: string;
60
+ workspaceDir?: string;
59
61
  pluginConfig?: PluginConfig;
60
62
  }): Promise<CausalPatternCandidate[]>;
61
63
  /**
@@ -67,6 +69,7 @@ declare function synthesizeCausalPreferencesViaLlm(options: {
67
69
  causalTrajectoryStoreDir?: string;
68
70
  gatewayConfig?: GatewayConfig;
69
71
  gatewayAgentId?: string;
72
+ workspaceDir?: string;
70
73
  minTrajectories?: number;
71
74
  }): Promise<string | null>;
72
75
  /**
@@ -5,28 +5,30 @@ import {
5
5
  import {
6
6
  buildExtensionsBlockForConsolidation,
7
7
  runPostConsolidationMaterialize
8
- } from "./chunk-FIXIX6DE.js";
8
+ } from "./chunk-C5HUWVH2.js";
9
9
  import "./chunk-EJI5XIBB.js";
10
10
  import {
11
11
  FallbackLlmClient
12
- } from "./chunk-DWMXVUGO.js";
13
- import "./chunk-Q7FJ5ZHM.js";
14
- import "./chunk-ODWDQNRE.js";
12
+ } from "./chunk-VX2IUQFE.js";
13
+ import "./chunk-S3IP6R6K.js";
15
14
  import "./chunk-L2EXJQJP.js";
15
+ import "./chunk-7SI52C65.js";
16
16
  import "./chunk-UZB5KHKX.js";
17
+ import "./chunk-KWBPHZUU.js";
17
18
  import "./chunk-URB2WSKZ.js";
19
+ import "./chunk-IXEJRKCZ.js";
18
20
  import "./chunk-DT5TVLJE.js";
19
- import "./chunk-XGX4TUF6.js";
21
+ import "./chunk-MCC6KDQF.js";
20
22
  import "./chunk-YNJHCGDT.js";
21
- import "./chunk-4KAN3GZ3.js";
22
- import "./chunk-T65SHTJP.js";
23
+ import "./chunk-NN2DKE4T.js";
24
+ import "./chunk-VQXK37XA.js";
23
25
  import "./chunk-PFV5C235.js";
24
26
  import "./chunk-RULE4VG5.js";
25
27
  import "./chunk-SCU65EZI.js";
26
- import "./chunk-67YLUWLG.js";
28
+ import "./chunk-XJKFSSDW.js";
27
29
  import "./chunk-DM2T26WE.js";
28
30
  import "./chunk-QSVPYQPG.js";
29
- import "./chunk-M62O4P4T.js";
31
+ import "./chunk-FVQJYWH7.js";
30
32
  import "./chunk-4DJQYKMN.js";
31
33
  import "./chunk-G7D6GZ5J.js";
32
34
  import "./chunk-FAAFWE4G.js";
@@ -193,7 +195,9 @@ async function deriveCausalPromotionCandidates(options) {
193
195
  context += "\n\n" + extBlock;
194
196
  }
195
197
  }
196
- const llm = new FallbackLlmClient(options.gatewayConfig);
198
+ const llm = new FallbackLlmClient(options.gatewayConfig, {
199
+ workspaceDir: options.pluginConfig?.workspaceDir ?? options.workspaceDir
200
+ });
197
201
  if (!llm.isAvailable(options.gatewayAgentId)) {
198
202
  log.debug("[cmc] no LLM available for consolidation \u2014 skipping");
199
203
  return [];
@@ -214,7 +218,9 @@ async function synthesizeCausalPreferencesViaLlm(options) {
214
218
  const chainsDir = resolveChainsDir(options.memoryDir, options.causalTrajectoryStoreDir);
215
219
  const chainIndex = await readChainIndex(chainsDir);
216
220
  const context = formatCausalContext(trajectories, chainIndex);
217
- const llm = new FallbackLlmClient(options.gatewayConfig);
221
+ const llm = new FallbackLlmClient(options.gatewayConfig, {
222
+ workspaceDir: options.workspaceDir
223
+ });
218
224
  if (!llm.isAvailable(options.gatewayAgentId)) return null;
219
225
  const result = await consolidateWithLlm(context, llm, options.gatewayAgentId);
220
226
  if (result.preferences.length === 0 && result.rules.length === 0) return null;