@remnic/core 9.3.613 → 9.3.615

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 (386) hide show
  1. package/dist/access-cli.js +59 -58
  2. package/dist/access-cli.js.map +1 -1
  3. package/dist/access-http.d.ts +4 -2
  4. package/dist/access-http.js +23 -23
  5. package/dist/access-mcp.d.ts +9 -2
  6. package/dist/access-mcp.js +20 -20
  7. package/dist/access-schema.d.ts +26 -14
  8. package/dist/access-schema.js +3 -3
  9. package/dist/{access-service-D2J9dh_9.d.ts → access-service-CBNEKjzN.d.ts} +71 -6
  10. package/dist/access-service.d.ts +2 -2
  11. package/dist/access-service.js +17 -17
  12. package/dist/active-recall.js +20 -3
  13. package/dist/active-recall.js.map +1 -1
  14. package/dist/adapters/index.js +4 -4
  15. package/dist/adapters/registry.js +2 -2
  16. package/dist/behavior-learner.js +2 -3
  17. package/dist/behavior-learner.js.map +1 -1
  18. package/dist/bootstrap.d.ts +1 -1
  19. package/dist/briefing.js +3 -3
  20. package/dist/buffer.d.ts +1 -1
  21. package/dist/buffer.js +1 -1
  22. package/dist/calibration.d.ts +5 -2
  23. package/dist/calibration.js +7 -5
  24. package/dist/calibration.js.map +1 -1
  25. package/dist/{capsule-crypto-7FJQINUR.js → capsule-crypto-YO5QJ6L3.js} +2 -2
  26. package/dist/causal-consolidation.d.ts +8 -2
  27. package/dist/causal-consolidation.js +13 -11
  28. package/dist/causal-consolidation.js.map +1 -1
  29. package/dist/{chunk-3BP57I6J.js → chunk-2F6NP3NT.js} +2 -1
  30. package/dist/{chunk-3BP57I6J.js.map → chunk-2F6NP3NT.js.map} +1 -1
  31. package/dist/{chunk-AU7Q3LSC.js → chunk-2QSZNTDO.js} +4 -4
  32. package/dist/{chunk-HSVJGWYS.js → chunk-2ROPI5OE.js} +2 -2
  33. package/dist/{chunk-C4SQJZAF.js → chunk-2SGJY2UY.js} +6 -3
  34. package/dist/chunk-2SGJY2UY.js.map +1 -0
  35. package/dist/{chunk-ZDTVJXIP.js → chunk-3MAONBX3.js} +13 -5
  36. package/dist/chunk-3MAONBX3.js.map +1 -0
  37. package/dist/{chunk-G3Z3QEF5.js → chunk-3PY7VHV7.js} +2 -2
  38. package/dist/chunk-3PY7VHV7.js.map +1 -0
  39. package/dist/{chunk-CF3ZF2YU.js → chunk-3QSU4NFF.js} +3 -3
  40. package/dist/{chunk-AJA46VX5.js → chunk-3T74IZB3.js} +11 -2
  41. package/dist/chunk-3T74IZB3.js.map +1 -0
  42. package/dist/{chunk-KVEVLBKC.js → chunk-4HFJQCJZ.js} +13 -8
  43. package/dist/chunk-4HFJQCJZ.js.map +1 -0
  44. package/dist/{chunk-KGK2QKWL.js → chunk-4R4KTDIE.js} +1 -1
  45. package/dist/chunk-4R4KTDIE.js.map +1 -0
  46. package/dist/{chunk-OI27U2HT.js → chunk-5BTCT236.js} +2 -2
  47. package/dist/{chunk-TH67Q46T.js → chunk-5OHHEORR.js} +64 -21
  48. package/dist/chunk-5OHHEORR.js.map +1 -0
  49. package/dist/{chunk-CO7ZO4TU.js → chunk-5VDJMYTF.js} +2 -2
  50. package/dist/{chunk-BFBF3XEF.js → chunk-6BDVBBBY.js} +33 -25
  51. package/dist/{chunk-BFBF3XEF.js.map → chunk-6BDVBBBY.js.map} +1 -1
  52. package/dist/{chunk-EAZGEEG2.js → chunk-6L46YAEZ.js} +45 -9
  53. package/dist/chunk-6L46YAEZ.js.map +1 -0
  54. package/dist/{chunk-YFS5OEKO.js → chunk-7MLB4NCL.js} +2 -2
  55. package/dist/{chunk-LZ3VEOU5.js → chunk-AL4RAJL5.js} +22 -5
  56. package/dist/chunk-AL4RAJL5.js.map +1 -0
  57. package/dist/{chunk-557IAFPD.js → chunk-APRRL26Q.js} +2 -2
  58. package/dist/{chunk-QDDHYAKV.js → chunk-AZDOWD2L.js} +2 -2
  59. package/dist/{chunk-MLT75J5S.js → chunk-B6SU7YSE.js} +3 -3
  60. package/dist/{chunk-FXKPZ3H6.js → chunk-BPSGLMQ4.js} +2 -2
  61. package/dist/{chunk-2NLLXCJG.js → chunk-BXLOS5AJ.js} +2 -2
  62. package/dist/{chunk-NOMEVTUD.js → chunk-C6C7XVKG.js} +5 -4
  63. package/dist/chunk-C6C7XVKG.js.map +1 -0
  64. package/dist/{chunk-XKIQZXUB.js → chunk-CI7RKSRE.js} +7 -1
  65. package/dist/chunk-CI7RKSRE.js.map +1 -0
  66. package/dist/{chunk-IK34DVAC.js → chunk-CIOMS6DI.js} +2 -2
  67. package/dist/{chunk-2I5JGH3M.js → chunk-CYEPCZN5.js} +2 -2
  68. package/dist/{chunk-2I5JGH3M.js.map → chunk-CYEPCZN5.js.map} +1 -1
  69. package/dist/{chunk-JHMFYY7L.js → chunk-DCGT4FPP.js} +13 -5
  70. package/dist/chunk-DCGT4FPP.js.map +1 -0
  71. package/dist/{chunk-7DZRO2DC.js → chunk-DEPRLVLK.js} +2 -2
  72. package/dist/{chunk-CSKLPDN6.js → chunk-DEVUWMME.js} +52 -19
  73. package/dist/chunk-DEVUWMME.js.map +1 -0
  74. package/dist/{chunk-DHGSZ3UD.js → chunk-DGNQRNLL.js} +2 -2
  75. package/dist/{chunk-X7Y7WX73.js → chunk-DQEMWVMT.js} +1 -1
  76. package/dist/{chunk-HJNQQICM.js → chunk-EXUAP5LH.js} +108 -51
  77. package/dist/chunk-EXUAP5LH.js.map +1 -0
  78. package/dist/chunk-FAV25DUZ.js +12 -0
  79. package/dist/chunk-FAV25DUZ.js.map +1 -0
  80. package/dist/{chunk-ETUPBUHB.js → chunk-GDASG7NC.js} +2 -2
  81. package/dist/{chunk-L227SKTB.js → chunk-GDB4J2H3.js} +17 -1
  82. package/dist/chunk-GDB4J2H3.js.map +1 -0
  83. package/dist/{chunk-IP73YCZP.js → chunk-GLPBYIXN.js} +4 -2
  84. package/dist/chunk-GLPBYIXN.js.map +1 -0
  85. package/dist/{chunk-4HP7HIE3.js → chunk-HP5FMB6L.js} +2 -2
  86. package/dist/{chunk-EVZFIAPG.js → chunk-IBTZEBUD.js} +23 -10
  87. package/dist/chunk-IBTZEBUD.js.map +1 -0
  88. package/dist/{chunk-DOX2CG6Y.js → chunk-IEUU7O4F.js} +2 -2
  89. package/dist/{chunk-EUML3N6B.js → chunk-IMA6GU4Y.js} +3 -3
  90. package/dist/chunk-IMA6GU4Y.js.map +1 -0
  91. package/dist/{chunk-JNANKJLN.js → chunk-JOASJWQR.js} +2 -2
  92. package/dist/chunk-JOASJWQR.js.map +1 -0
  93. package/dist/{chunk-WSGF57U2.js → chunk-JQDZQ4TB.js} +2 -2
  94. package/dist/{chunk-HINSGUA7.js → chunk-KBL3JJR6.js} +9 -13
  95. package/dist/chunk-KBL3JJR6.js.map +1 -0
  96. package/dist/{chunk-IOTENEVL.js → chunk-KGLPJROV.js} +57 -50
  97. package/dist/chunk-KGLPJROV.js.map +1 -0
  98. package/dist/{chunk-W7L6HXUC.js → chunk-LXOM6IQU.js} +2 -2
  99. package/dist/{chunk-G6R5UD3Q.js → chunk-MGN7VHWQ.js} +42 -1
  100. package/dist/{chunk-G6R5UD3Q.js.map → chunk-MGN7VHWQ.js.map} +1 -1
  101. package/dist/{chunk-DLJ4IR6M.js → chunk-MHQC2WU2.js} +2 -2
  102. package/dist/chunk-MHQC2WU2.js.map +1 -0
  103. package/dist/{chunk-5RPTH6AU.js → chunk-NM5NQYJE.js} +20 -19
  104. package/dist/chunk-NM5NQYJE.js.map +1 -0
  105. package/dist/{chunk-6JGNHWCI.js → chunk-OBIRVF36.js} +3 -3
  106. package/dist/{chunk-CHCA44C3.js → chunk-ODPLEWB6.js} +3 -3
  107. package/dist/chunk-ODPLEWB6.js.map +1 -0
  108. package/dist/{chunk-HENLZHIT.js → chunk-OIF36KGD.js} +7 -4
  109. package/dist/chunk-OIF36KGD.js.map +1 -0
  110. package/dist/{chunk-GUPISBV2.js → chunk-PP2JH3GP.js} +2 -2
  111. package/dist/{chunk-OXJBNGBK.js → chunk-PSUB67YB.js} +2 -2
  112. package/dist/{chunk-UWY7GIVS.js → chunk-PYIFUBRK.js} +45 -13
  113. package/dist/chunk-PYIFUBRK.js.map +1 -0
  114. package/dist/{chunk-KIB7SDIJ.js → chunk-Q6YIJGXJ.js} +2 -2
  115. package/dist/{chunk-ZT3EGNLR.js → chunk-QPD426WT.js} +2 -2
  116. package/dist/{chunk-RLV3PQGH.js → chunk-QVO4YOB7.js} +6 -6
  117. package/dist/{chunk-GMAG2HS4.js → chunk-RG3LBSGH.js} +46 -9
  118. package/dist/chunk-RG3LBSGH.js.map +1 -0
  119. package/dist/{chunk-XSWKORGM.js → chunk-S53OYO3F.js} +3 -1
  120. package/dist/chunk-S53OYO3F.js.map +1 -0
  121. package/dist/{chunk-YCN4BVDK.js → chunk-SCPFRKIT.js} +4 -2
  122. package/dist/chunk-SCPFRKIT.js.map +1 -0
  123. package/dist/{chunk-NZPF2SYV.js → chunk-T7N6KQGS.js} +138 -5
  124. package/dist/chunk-T7N6KQGS.js.map +1 -0
  125. package/dist/{chunk-VJXSUAO7.js → chunk-TNOWU6RP.js} +13 -10
  126. package/dist/chunk-TNOWU6RP.js.map +1 -0
  127. package/dist/{chunk-PCI747N2.js → chunk-TZVQQTG4.js} +48 -19
  128. package/dist/chunk-TZVQQTG4.js.map +1 -0
  129. package/dist/{chunk-KQAFEZQX.js → chunk-VDX2J7OX.js} +2 -2
  130. package/dist/{chunk-IK7DCC5H.js → chunk-VMGLYN42.js} +2 -2
  131. package/dist/{chunk-KM2A35EO.js → chunk-WB3LYXC5.js} +11 -7
  132. package/dist/chunk-WB3LYXC5.js.map +1 -0
  133. package/dist/{chunk-PPPZY2EU.js → chunk-WD2W4234.js} +9 -3
  134. package/dist/chunk-WD2W4234.js.map +1 -0
  135. package/dist/{chunk-NSKYFGDL.js → chunk-X4QQB7O6.js} +2 -2
  136. package/dist/{chunk-HPWVAEET.js → chunk-X6IRLNOO.js} +3 -7
  137. package/dist/chunk-X6IRLNOO.js.map +1 -0
  138. package/dist/{chunk-46GJIW5M.js → chunk-XAZOWLW4.js} +5 -5
  139. package/dist/{chunk-46GJIW5M.js.map → chunk-XAZOWLW4.js.map} +1 -1
  140. package/dist/{chunk-XPSVGJYA.js → chunk-YRMKDTKF.js} +12 -9
  141. package/dist/chunk-YRMKDTKF.js.map +1 -0
  142. package/dist/{chunk-6ZZP4EJF.js → chunk-ZJR7VG5L.js} +3 -3
  143. package/dist/{chunk-6ZZP4EJF.js.map → chunk-ZJR7VG5L.js.map} +1 -1
  144. package/dist/{chunk-2QANQKSQ.js → chunk-ZK32E74R.js} +156 -45
  145. package/dist/chunk-ZK32E74R.js.map +1 -0
  146. package/dist/{cli-OrfKXNU4.d.ts → cli-Cw729yLf.d.ts} +6 -2
  147. package/dist/cli.d.ts +3 -3
  148. package/dist/cli.js +61 -60
  149. package/dist/compounding/engine.js +3 -3
  150. package/dist/compounding/preference-consolidator.js +39 -11
  151. package/dist/compounding/preference-consolidator.js.map +1 -1
  152. package/dist/config.js +1 -1
  153. package/dist/connectors/codex-materialize-runner.js +3 -3
  154. package/dist/connectors/index.js +3 -3
  155. package/dist/consolidation-provenance-check.js +1 -1
  156. package/dist/contradiction/index.js +4 -4
  157. package/dist/conversation-index/backend.js +2 -2
  158. package/dist/conversation-index/indexer.js +1 -1
  159. package/dist/cross-namespace-budget.js +1 -1
  160. package/dist/enrichment/index.js +1 -1
  161. package/dist/entity-retrieval.js +3 -3
  162. package/dist/evals.js +1 -1
  163. package/dist/explicit-capture.d.ts +11 -1
  164. package/dist/explicit-capture.js +1 -1
  165. package/dist/extraction-judge.js +8 -1
  166. package/dist/extraction.js +2 -2
  167. package/dist/fallback-llm.d.ts +23 -6
  168. package/dist/fallback-llm.js +5 -3
  169. package/dist/{first-start-migration-GYJWIH36.js → first-start-migration-FF7YFGRP.js} +6 -6
  170. package/dist/index.d.ts +3 -3
  171. package/dist/index.js +95 -94
  172. package/dist/index.js.map +1 -1
  173. package/dist/lcm/archive.js +2 -2
  174. package/dist/lcm/engine.js +5 -5
  175. package/dist/lcm/index.js +7 -7
  176. package/dist/lcm/summarizer.js +3 -3
  177. package/dist/maintenance/memory-governance-cron.d.ts +6 -4
  178. package/dist/maintenance/memory-governance-cron.js +1 -1
  179. package/dist/maintenance/memory-governance.js +3 -3
  180. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +3 -3
  181. package/dist/maintenance/rebuild-memory-projection.js +4 -4
  182. package/dist/mcp-memory-inspector-app.d.ts +2 -2
  183. package/dist/mcp-memory-inspector-app.js +1 -1
  184. package/dist/migrate/from-engram.js +1 -1
  185. package/dist/namespaces/migrate.js +16 -15
  186. package/dist/namespaces/search.js +12 -11
  187. package/dist/namespaces/storage.js +3 -3
  188. package/dist/network/webdav.d.ts +2 -0
  189. package/dist/network/webdav.js +1 -1
  190. package/dist/objective-state-writers.js +2 -2
  191. package/dist/operator-toolkit.d.ts +3 -1
  192. package/dist/operator-toolkit.js +21 -20
  193. package/dist/{orchestrator-DTRQG75J.d.ts → orchestrator-CqWOjfgl.d.ts} +46 -3
  194. package/dist/orchestrator.d.ts +1 -1
  195. package/dist/orchestrator.js +48 -45
  196. package/dist/patterns-cli.js +1 -1
  197. package/dist/qmd-recall-cache.d.ts +2 -0
  198. package/dist/qmd-recall-cache.js +1 -1
  199. package/dist/qmd.d.ts +37 -2
  200. package/dist/qmd.js +4 -1
  201. package/dist/recall-explain-renderer.js +3 -3
  202. package/dist/recall-planner-llm.d.ts +57 -0
  203. package/dist/recall-planner-llm.js +167 -0
  204. package/dist/recall-planner-llm.js.map +1 -0
  205. package/dist/recall-xray-cli.js +4 -4
  206. package/dist/recall-xray-renderer.js +3 -3
  207. package/dist/recall-xray.js +2 -2
  208. package/dist/resume-bundles.js +2 -2
  209. package/dist/retrieval-agents.js +2 -2
  210. package/dist/routing/store.js +1 -1
  211. package/dist/schemas.d.ts +22 -22
  212. package/dist/search/factory.js +11 -10
  213. package/dist/search/index.js +11 -10
  214. package/dist/search/lancedb-backend.d.ts +1 -1
  215. package/dist/search/lancedb-backend.js +3 -2
  216. package/dist/search/meilisearch-backend.d.ts +1 -1
  217. package/dist/search/meilisearch-backend.js +3 -2
  218. package/dist/search/noop-backend.d.ts +1 -1
  219. package/dist/search/noop-backend.js +1 -1
  220. package/dist/search/orama-backend.d.ts +1 -1
  221. package/dist/search/orama-backend.js +3 -2
  222. package/dist/search/port.d.ts +6 -1
  223. package/dist/search/port.js +7 -0
  224. package/dist/search/remote-backend.d.ts +1 -1
  225. package/dist/search/remote-backend.js +1 -1
  226. package/dist/semantic-consolidation.js +4 -4
  227. package/dist/semantic-rule-promotion.js +3 -3
  228. package/dist/semantic-rule-verifier.js +3 -3
  229. package/dist/session-observer-state.js +1 -1
  230. package/dist/storage.js +2 -2
  231. package/dist/summarizer.js +2 -2
  232. package/dist/temporal-index.js +1 -1
  233. package/dist/{tier-stats-SKML2OSF.js → tier-stats-3LYQ3VV5.js} +3 -3
  234. package/dist/transfer/backup.js +2 -2
  235. package/dist/transfer/capsule-export.js +2 -2
  236. package/dist/transfer/capsule-import.js +2 -2
  237. package/dist/transfer/export-sqlite.js +1 -1
  238. package/dist/transfer/types.d.ts +12 -12
  239. package/dist/types.d.ts +32 -0
  240. package/dist/types.js +1 -1
  241. package/dist/utility-learner.js +1 -1
  242. package/dist/utility-runtime.js +2 -2
  243. package/dist/verified-recall.js +3 -3
  244. package/dist/work/board.js +2 -2
  245. package/dist/work/storage.d.ts +2 -0
  246. package/dist/work/storage.js +1 -1
  247. package/package.json +1 -1
  248. package/src/access-http.ts +24 -10
  249. package/src/access-mcp.test.ts +160 -0
  250. package/src/access-mcp.ts +72 -7
  251. package/src/access-schema.ts +11 -0
  252. package/src/access-service-coding-write.test.ts +478 -0
  253. package/src/access-service.ts +237 -32
  254. package/src/active-recall.test.ts +40 -0
  255. package/src/active-recall.ts +19 -2
  256. package/src/behavior-learner.ts +5 -3
  257. package/src/buffer-session.test.ts +58 -0
  258. package/src/buffer-surprise-trigger.test.ts +4 -18
  259. package/src/buffer.ts +39 -11
  260. package/src/calibration.ts +10 -4
  261. package/src/causal-consolidation.test.ts +47 -2
  262. package/src/causal-consolidation.ts +13 -9
  263. package/src/cli.ts +19 -4
  264. package/src/compounding/engine.ts +2 -0
  265. package/src/compounding/preference-consolidator.test.ts +292 -0
  266. package/src/compounding/preference-consolidator.ts +55 -19
  267. package/src/config.test.ts +213 -0
  268. package/src/config.ts +175 -4
  269. package/src/connectors/codex-materialize-runner.ts +7 -4
  270. package/src/consolidation-provenance-check.ts +24 -5
  271. package/src/conversation-index/indexer.test.ts +22 -0
  272. package/src/conversation-index/indexer.ts +7 -3
  273. package/src/cross-namespace-budget.test.ts +44 -21
  274. package/src/cross-namespace-budget.ts +2 -2
  275. package/src/enrichment/pipeline.ts +11 -16
  276. package/src/evals.ts +1 -1
  277. package/src/explicit-capture.ts +19 -2
  278. package/src/extraction-judge-chain.test.ts +55 -0
  279. package/src/extraction-judge.ts +7 -9
  280. package/src/extraction.ts +16 -5
  281. package/src/fallback-llm.test.ts +600 -1
  282. package/src/fallback-llm.ts +91 -22
  283. package/src/maintenance/memory-governance-cron.ts +39 -29
  284. package/src/mcp-memory-inspector-app.ts +54 -12
  285. package/src/message-parts/index.ts +6 -0
  286. package/src/message-parts/message-parts.test.ts +30 -0
  287. package/src/migrate/from-engram.ts +19 -5
  288. package/src/namespaces/search.test.ts +15 -2
  289. package/src/namespaces/search.ts +1 -1
  290. package/src/network/webdav.ts +61 -21
  291. package/src/operator-toolkit.ts +6 -2
  292. package/src/orchestrator.ts +173 -20
  293. package/src/qmd-client.test.ts +85 -0
  294. package/src/qmd-recall-cache.test.ts +16 -0
  295. package/src/qmd-recall-cache.ts +7 -0
  296. package/src/qmd.test.ts +54 -0
  297. package/src/qmd.ts +119 -19
  298. package/src/recall-planner-llm.test.ts +224 -0
  299. package/src/recall-planner-llm.ts +289 -0
  300. package/src/routing/store.ts +4 -8
  301. package/src/search/factory.ts +3 -0
  302. package/src/search/lancedb-backend.ts +15 -3
  303. package/src/search/meilisearch-backend.ts +70 -7
  304. package/src/search/noop-backend.ts +5 -1
  305. package/src/search/orama-backend.ts +15 -3
  306. package/src/search/port.ts +15 -0
  307. package/src/search/remote-backend.ts +5 -1
  308. package/src/session-observer-state.ts +1 -1
  309. package/src/summarizer.ts +3 -3
  310. package/src/temporal-index.test.ts +18 -0
  311. package/src/temporal-index.ts +45 -0
  312. package/src/training-export/cli-date-validation.test.ts +36 -0
  313. package/src/training-export/date-parse.ts +21 -2
  314. package/src/transfer/export-sqlite.ts +3 -0
  315. package/src/types.ts +35 -0
  316. package/src/utility-learner.ts +1 -0
  317. package/src/work/storage.ts +23 -0
  318. package/dist/chunk-2QANQKSQ.js.map +0 -1
  319. package/dist/chunk-5RPTH6AU.js.map +0 -1
  320. package/dist/chunk-AJA46VX5.js.map +0 -1
  321. package/dist/chunk-C4SQJZAF.js.map +0 -1
  322. package/dist/chunk-CHCA44C3.js.map +0 -1
  323. package/dist/chunk-CSKLPDN6.js.map +0 -1
  324. package/dist/chunk-DLJ4IR6M.js.map +0 -1
  325. package/dist/chunk-EAZGEEG2.js.map +0 -1
  326. package/dist/chunk-EUML3N6B.js.map +0 -1
  327. package/dist/chunk-EVZFIAPG.js.map +0 -1
  328. package/dist/chunk-G3Z3QEF5.js.map +0 -1
  329. package/dist/chunk-GMAG2HS4.js.map +0 -1
  330. package/dist/chunk-HENLZHIT.js.map +0 -1
  331. package/dist/chunk-HINSGUA7.js.map +0 -1
  332. package/dist/chunk-HJNQQICM.js.map +0 -1
  333. package/dist/chunk-HPWVAEET.js.map +0 -1
  334. package/dist/chunk-IOTENEVL.js.map +0 -1
  335. package/dist/chunk-IP73YCZP.js.map +0 -1
  336. package/dist/chunk-JHMFYY7L.js.map +0 -1
  337. package/dist/chunk-JNANKJLN.js.map +0 -1
  338. package/dist/chunk-KGK2QKWL.js.map +0 -1
  339. package/dist/chunk-KM2A35EO.js.map +0 -1
  340. package/dist/chunk-KVEVLBKC.js.map +0 -1
  341. package/dist/chunk-L227SKTB.js.map +0 -1
  342. package/dist/chunk-LZ3VEOU5.js.map +0 -1
  343. package/dist/chunk-NOMEVTUD.js.map +0 -1
  344. package/dist/chunk-NZPF2SYV.js.map +0 -1
  345. package/dist/chunk-PCI747N2.js.map +0 -1
  346. package/dist/chunk-PPPZY2EU.js.map +0 -1
  347. package/dist/chunk-TH67Q46T.js.map +0 -1
  348. package/dist/chunk-UWY7GIVS.js.map +0 -1
  349. package/dist/chunk-VJXSUAO7.js.map +0 -1
  350. package/dist/chunk-XKIQZXUB.js.map +0 -1
  351. package/dist/chunk-XPSVGJYA.js.map +0 -1
  352. package/dist/chunk-XSWKORGM.js.map +0 -1
  353. package/dist/chunk-YCN4BVDK.js.map +0 -1
  354. package/dist/chunk-ZDTVJXIP.js.map +0 -1
  355. /package/dist/{capsule-crypto-7FJQINUR.js.map → capsule-crypto-YO5QJ6L3.js.map} +0 -0
  356. /package/dist/{chunk-AU7Q3LSC.js.map → chunk-2QSZNTDO.js.map} +0 -0
  357. /package/dist/{chunk-HSVJGWYS.js.map → chunk-2ROPI5OE.js.map} +0 -0
  358. /package/dist/{chunk-CF3ZF2YU.js.map → chunk-3QSU4NFF.js.map} +0 -0
  359. /package/dist/{chunk-OI27U2HT.js.map → chunk-5BTCT236.js.map} +0 -0
  360. /package/dist/{chunk-CO7ZO4TU.js.map → chunk-5VDJMYTF.js.map} +0 -0
  361. /package/dist/{chunk-YFS5OEKO.js.map → chunk-7MLB4NCL.js.map} +0 -0
  362. /package/dist/{chunk-557IAFPD.js.map → chunk-APRRL26Q.js.map} +0 -0
  363. /package/dist/{chunk-QDDHYAKV.js.map → chunk-AZDOWD2L.js.map} +0 -0
  364. /package/dist/{chunk-MLT75J5S.js.map → chunk-B6SU7YSE.js.map} +0 -0
  365. /package/dist/{chunk-FXKPZ3H6.js.map → chunk-BPSGLMQ4.js.map} +0 -0
  366. /package/dist/{chunk-2NLLXCJG.js.map → chunk-BXLOS5AJ.js.map} +0 -0
  367. /package/dist/{chunk-IK34DVAC.js.map → chunk-CIOMS6DI.js.map} +0 -0
  368. /package/dist/{chunk-7DZRO2DC.js.map → chunk-DEPRLVLK.js.map} +0 -0
  369. /package/dist/{chunk-DHGSZ3UD.js.map → chunk-DGNQRNLL.js.map} +0 -0
  370. /package/dist/{chunk-X7Y7WX73.js.map → chunk-DQEMWVMT.js.map} +0 -0
  371. /package/dist/{chunk-ETUPBUHB.js.map → chunk-GDASG7NC.js.map} +0 -0
  372. /package/dist/{chunk-4HP7HIE3.js.map → chunk-HP5FMB6L.js.map} +0 -0
  373. /package/dist/{chunk-DOX2CG6Y.js.map → chunk-IEUU7O4F.js.map} +0 -0
  374. /package/dist/{chunk-WSGF57U2.js.map → chunk-JQDZQ4TB.js.map} +0 -0
  375. /package/dist/{chunk-W7L6HXUC.js.map → chunk-LXOM6IQU.js.map} +0 -0
  376. /package/dist/{chunk-6JGNHWCI.js.map → chunk-OBIRVF36.js.map} +0 -0
  377. /package/dist/{chunk-GUPISBV2.js.map → chunk-PP2JH3GP.js.map} +0 -0
  378. /package/dist/{chunk-OXJBNGBK.js.map → chunk-PSUB67YB.js.map} +0 -0
  379. /package/dist/{chunk-KIB7SDIJ.js.map → chunk-Q6YIJGXJ.js.map} +0 -0
  380. /package/dist/{chunk-ZT3EGNLR.js.map → chunk-QPD426WT.js.map} +0 -0
  381. /package/dist/{chunk-RLV3PQGH.js.map → chunk-QVO4YOB7.js.map} +0 -0
  382. /package/dist/{chunk-KQAFEZQX.js.map → chunk-VDX2J7OX.js.map} +0 -0
  383. /package/dist/{chunk-IK7DCC5H.js.map → chunk-VMGLYN42.js.map} +0 -0
  384. /package/dist/{chunk-NSKYFGDL.js.map → chunk-X4QQB7O6.js.map} +0 -0
  385. /package/dist/{first-start-migration-GYJWIH36.js.map → first-start-migration-FF7YFGRP.js.map} +0 -0
  386. /package/dist/{tier-stats-SKML2OSF.js.map → tier-stats-3LYQ3VV5.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/extraction.ts"],"sourcesContent":["import OpenAI from \"openai\";\nimport { log } from \"./logger.js\";\nimport { delinearize } from \"./delinearize.js\";\nimport { LocalLlmClient } from \"./local-llm.js\";\nimport { FallbackLlmClient, fallbackLlmRuntimeContextFromConfig } from \"./fallback-llm.js\";\nimport {\n ExtractionResultSchema,\n ConsolidationResultSchema,\n IdentityConsolidationResultSchema,\n buildProfileConsolidationResultSchema,\n ProactiveExtractionResultSchema,\n ProactiveQuestionsResultSchema,\n type ContradictionVerificationResult,\n type SuggestedLinks,\n type MemorySummaryResult,\n type ProactiveQuestionsResultParsed,\n DaySummaryResultSchema,\n} from \"./schemas.js\";\nimport type {\n BufferTurn,\n ExtractionResult,\n ConsolidationResult,\n MemoryFile,\n PluginConfig,\n LlmTraceEvent,\n GatewayConfig,\n MemoryCategory,\n DaySummaryResult as DaySummaryResultShape,\n} from \"./types.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { extractJsonCandidates } from \"./json-extract.js\";\nimport { sanitizeMemoryContent } from \"./sanitize.js\";\nimport { applyWorkExtractionBoundary } from \"./work/boundary.js\";\nimport { buildChatCompletionTokenLimit, shouldAssumeOpenAiChatCompletions } from \"./openai-chat-compat.js\";\nimport { formatDaySummaryMemories, loadDaySummaryPrompt, buildExtensionsFooterForSummary } from \"./day-summary.js\";\nimport { ProfilingCollector } from \"./profiling.js\";\nimport { normalizeProcedureSteps } from \"./procedural/procedure-types.js\";\nimport { normalizeReasoningTrace } from \"./reasoning-trace-types.js\";\nimport { looksLikeMechanicalTelemetryTranscript } from \"./telemetry-transcript.js\";\n\ntype ExtractionQuestion = ExtractionResult[\"questions\"][number];\ntype ExtractedFactResult = ExtractionResult[\"facts\"][number];\ntype ExtractedEntityResult = ExtractionResult[\"entities\"][number];\ntype ExtractedRelationshipResult = NonNullable<ExtractionResult[\"relationships\"]>[number];\nconst PROACTIVE_MIN_CONFIDENCE = 0.8;\nconst CONSOLIDATION_RESPONSE_SCHEMA = `{\n \"items\": [\n {\n \"existingId\": \"id\",\n \"action\": \"ADD\",\n \"mergeWith\": \"optional-existing-id\",\n \"updatedContent\": \"optional replacement content\",\n \"reason\": \"brief reason for this action\"\n }\n ],\n \"profileUpdates\": [\"optional profile update\"],\n \"entityUpdates\": [{\"name\": \"person-jane-doe\", \"type\": \"person\", \"facts\": [\"Now leads the backend team\", \"Recently migrated the user service to TypeScript\"]}]\n}`;\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction normalizeQuestion(question: ExtractionQuestion): ExtractionQuestion {\n const priority = Number.isFinite(question.priority)\n ? Math.max(0, Math.min(1, question.priority))\n : 0.5;\n return {\n question: typeof question.question === \"string\" ? question.question.trim() : \"\",\n context: typeof question.context === \"string\" ? question.context.trim() : \"\",\n priority,\n };\n}\n\nfunction normalizeFactKey(fact: Pick<ExtractedFactResult, \"category\" | \"content\">): string {\n return `${fact.category}:${fact.content.trim().toLowerCase()}`;\n}\n\nfunction normalizeEntityKey(entity: Pick<ExtractedEntityResult, \"name\" | \"type\">): string {\n return `${entity.type}:${entity.name.trim().toLowerCase()}`;\n}\n\nfunction normalizeRelationshipKey(\n relationship: Pick<ExtractedRelationshipResult, \"source\" | \"target\" | \"label\">,\n): string {\n return `${relationship.source.trim().toLowerCase()}=>${relationship.target.trim().toLowerCase()}:${relationship.label.trim().toLowerCase()}`;\n}\n\nfunction normalizeProfileUpdateKey(update: string): string {\n return update.trim().toLowerCase();\n}\n\nexport class ExtractionEngine {\n private client: OpenAI | null;\n private localLlm: LocalLlmClient;\n private fallbackLlm: FallbackLlmClient;\n private modelRegistry: ModelRegistry;\n private profiler: ProfilingCollector;\n\n constructor(\n private readonly config: PluginConfig,\n profilerArg?: ProfilingCollector,\n localLlm?: LocalLlmClient,\n gatewayConfig?: GatewayConfig,\n modelRegistry?: ModelRegistry,\n ) {\n this.profiler = profilerArg ?? new ProfilingCollector({ enabled: false, storageDir: \"/tmp/engram-profiler-disabled\", maxTraces: 0 });\n if (config.openaiApiKey) {\n this.client = new OpenAI({\n apiKey: config.openaiApiKey,\n ...(config.openaiBaseUrl ? { baseURL: config.openaiBaseUrl } : {}),\n });\n } else {\n this.client = null;\n log.warn(\"no OpenAI API key — direct OpenAI client disabled; local and gateway fallback paths remain available\");\n }\n this.localLlm = localLlm ?? new LocalLlmClient(config, modelRegistry);\n this.fallbackLlm = new FallbackLlmClient(\n gatewayConfig,\n fallbackLlmRuntimeContextFromConfig(config),\n );\n this.modelRegistry = modelRegistry ?? new ModelRegistry(config.memoryDir);\n if (config.modelSource === \"gateway\") {\n log.debug(\n `extraction engine: gateway model source active; extraction uses the gateway chain as its primary path` +\n (config.gatewayAgentId ? ` (agent: ${config.gatewayAgentId})` : \" (defaults)\"),\n );\n }\n }\n\n /**\n * Whether LLM calls should be routed through the gateway model chain\n * instead of the plugin's own local/OpenAI clients.\n */\n private get useGatewayModelSource(): boolean {\n return this.config.modelSource === \"gateway\";\n }\n\n /**\n * Whether the local LLM path should be attempted.\n * Disabled when gateway model source is active (gateway chain replaces local).\n */\n private get shouldUseLocalLlm(): boolean {\n return this.config.localLlmEnabled && !this.useGatewayModelSource;\n }\n\n /**\n * Whether the direct OpenAI client should be used.\n * Disabled when gateway model source is active.\n */\n private get shouldUseDirectClient(): boolean {\n return !this.useGatewayModelSource && this.client !== null;\n }\n\n /**\n * Build FallbackLlmOptions with the configured gateway agent ID injected.\n */\n private withGatewayAgent(options: import(\"./fallback-llm.js\").FallbackLlmOptions): import(\"./fallback-llm.js\").FallbackLlmOptions {\n if (!this.useGatewayModelSource) return options;\n const agentId = this.config.gatewayAgentId || undefined;\n return agentId ? { ...options, agentId } : options;\n }\n\n private emit(event: LlmTraceEvent): void {\n try {\n const cb = (globalThis as any).__openclawEngramTrace;\n if (typeof cb === \"function\") cb(event);\n } catch {\n // Never throw — broken subscriber must not crash extraction\n }\n }\n\n private directClientUsesOpenAiTokenSemantics(): boolean {\n return shouldAssumeOpenAiChatCompletions(this.config.openaiBaseUrl);\n }\n\n private sanitizeExtractionResult(result: ExtractionResult, messageTimestamp?: Date): ExtractionResult {\n const proceduralOn = this.config.procedural?.enabled === true;\n const ts = messageTimestamp ?? new Date();\n const facts = result.facts\n .filter((fact) => proceduralOn || fact.category !== \"procedure\")\n .map((fact) => {\n const sanitized = sanitizeMemoryContent(fact.content);\n if (!sanitized.clean) {\n log.warn(`extraction fact sanitized; violations=${sanitized.violations.join(\", \")}`);\n }\n let content = sanitized.text;\n // De-linearize: resolve coreferences + anchor temporal expressions\n if (this.config.delinearizeEnabled) {\n content = delinearize(content, result.entities, ts);\n }\n return { ...fact, content };\n });\n return { ...result, facts };\n }\n\n private hasExtractionOutputs(result: ExtractionResult): boolean {\n return result.facts.length > 0\n || result.entities.length > 0\n || result.questions.length > 0\n || result.profileUpdates.length > 0\n || (result.relationships?.length ?? 0) > 0;\n }\n\n private looksLikeExtractionResultPayload(parsed: any): boolean {\n return !!parsed &&\n typeof parsed === \"object\" &&\n !Array.isArray(parsed) &&\n (\n \"facts\" in parsed ||\n \"entities\" in parsed ||\n \"profileUpdates\" in parsed ||\n \"questions\" in parsed ||\n \"relationships\" in parsed ||\n \"identityReflection\" in parsed\n );\n }\n\n private normalizeExtractionResultPayload(parsed: any): ExtractionResult {\n const entities = Array.isArray(parsed?.entities)\n ? parsed.entities\n .map((e: any) => this.normalizeEntityUpdate(e))\n .filter((e: any) => e.name.length > 0)\n : [];\n\n const facts = Array.isArray(parsed?.facts)\n ? parsed.facts\n .map((f: any) => ({\n category: typeof f?.category === \"string\" ? f.category : \"fact\",\n content: typeof f?.content === \"string\" ? f.content : typeof f?.text === \"string\" ? f.text : \"\",\n confidence: typeof f?.confidence === \"number\" ? f.confidence : 0.7,\n tags: Array.isArray(f?.tags) ? f.tags.filter((t: any) => typeof t === \"string\") : [],\n entityRef: typeof f?.entityRef === \"string\" ? f.entityRef : undefined,\n promptedByQuestion:\n typeof f?.promptedByQuestion === \"string\" ? f.promptedByQuestion : undefined,\n scope:\n f?.scope === \"global\" || f?.scope === \"project\" ? f.scope : undefined,\n structuredAttributes:\n f?.structuredAttributes && typeof f.structuredAttributes === \"object\" && !Array.isArray(f.structuredAttributes)\n ? Object.fromEntries(\n Object.entries(f.structuredAttributes)\n .filter(([k, v]) => typeof k === \"string\" && typeof v === \"string\")\n ) as Record<string, string>\n : undefined,\n procedureSteps: Array.isArray(f?.procedureSteps)\n ? normalizeProcedureSteps(f.procedureSteps)\n : undefined,\n reasoningTrace: (() => {\n // Accept both camelCase and snake_case payload keys. The\n // category itself is snake_case and we already tolerate\n // snake_case nested fields in normalizeReasoningTrace, so a\n // loose local/direct LLM that outputs `reasoning_trace` on the\n // fact should not silently drop the structured chain.\n const candidate =\n f?.reasoningTrace && typeof f.reasoningTrace === \"object\" && !Array.isArray(f.reasoningTrace)\n ? f.reasoningTrace\n : f?.reasoning_trace && typeof f.reasoning_trace === \"object\" && !Array.isArray(f.reasoning_trace)\n ? f.reasoning_trace\n : null;\n return candidate ? normalizeReasoningTrace(candidate) ?? undefined : undefined;\n })(),\n }))\n .filter((f: any) => f.content.length > 0)\n : [];\n\n const questions = Array.isArray(parsed?.questions)\n ? parsed.questions\n .map((q: any) => {\n if (typeof q === \"string\") return { question: q, context: \"\", priority: 0.5 };\n return {\n question: typeof q?.question === \"string\" ? q.question : typeof q?.text === \"string\" ? q.text : \"\",\n context: typeof q?.context === \"string\" ? q.context : \"\",\n priority: typeof q?.priority === \"number\" ? q.priority : 0.5,\n };\n })\n .filter((q: any) => q.question.length > 0)\n : [];\n\n return {\n facts,\n entities,\n profileUpdates: Array.isArray(parsed?.profileUpdates)\n ? parsed.profileUpdates.filter((u: any) => typeof u === \"string\" && u.trim().length > 0)\n : [],\n questions,\n identityReflection: parsed?.identityReflection ?? undefined,\n relationships: Array.isArray(parsed?.relationships)\n ? parsed.relationships.filter(\n (r: any) =>\n typeof r?.source === \"string\" &&\n typeof r?.target === \"string\" &&\n typeof r?.label === \"string\",\n )\n .map((r: any) => ({\n source: r.source,\n target: r.target,\n label: r.label,\n promptedByQuestion:\n typeof r?.promptedByQuestion === \"string\" ? r.promptedByQuestion : undefined,\n }))\n : undefined,\n };\n }\n\n private normalizeEntityUpdate(entity: any): ExtractedEntityResult {\n const rawUpdates = isPlainRecord(entity?.updates) ? entity.updates : null;\n const directFacts = Array.isArray(entity?.facts)\n ? entity.facts\n .filter((fact: any) => typeof fact === \"string\")\n .map((fact: string) => fact.trim())\n .filter((fact: string) => fact.length > 0)\n : [];\n const updateFacts = rawUpdates && Array.isArray(rawUpdates.facts)\n ? rawUpdates.facts\n .filter((fact: unknown) => typeof fact === \"string\")\n .map((fact: string) => fact.trim())\n .filter((fact: string) => fact.length > 0)\n : [];\n const scalarUpdateFacts = rawUpdates\n ? Object.keys(rawUpdates)\n .sort((a, b) => a.localeCompare(b))\n .filter((key) => ![\"facts\", \"name\", \"promptedByQuestion\", \"structuredSections\", \"type\"].includes(key))\n .flatMap((key) => {\n const value = rawUpdates[key];\n if (typeof value === \"string\" && value.trim().length > 0) {\n return [`${key}: ${value.trim()}`];\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return [`${key}: ${String(value)}`];\n }\n return [];\n })\n : [];\n const structuredSectionsSource = Array.isArray(entity?.structuredSections)\n ? entity.structuredSections\n : Array.isArray(rawUpdates?.structuredSections)\n ? rawUpdates.structuredSections\n : [];\n const name =\n typeof entity?.name === \"string\"\n ? entity.name.trim()\n : typeof entity?.entityId === \"string\"\n ? entity.entityId.trim()\n : typeof rawUpdates?.name === \"string\"\n ? rawUpdates.name.trim()\n : \"\";\n const type =\n typeof entity?.type === \"string\" && entity.type.trim().length > 0\n ? entity.type.trim()\n : typeof rawUpdates?.type === \"string\" && rawUpdates.type.trim().length > 0\n ? rawUpdates.type.trim()\n : \"other\";\n\n return {\n name,\n type,\n facts: [...directFacts, ...updateFacts, ...scalarUpdateFacts],\n structuredSections: structuredSectionsSource.length > 0\n ? structuredSectionsSource\n .map((section: any) => ({\n key: typeof section?.key === \"string\" ? section.key.trim() : \"\",\n title: typeof section?.title === \"string\" ? section.title.trim() : \"\",\n facts: Array.isArray(section?.facts)\n ? section.facts.filter((fact: any) => typeof fact === \"string\")\n .map((fact: string) => fact.trim())\n .filter((fact: string) => fact.length > 0)\n : [],\n }))\n .filter((section: any) => (\n section.key.length > 0 &&\n section.title.length > 0 &&\n section.facts.length > 0\n ))\n : undefined,\n promptedByQuestion:\n typeof entity?.promptedByQuestion === \"string\"\n ? entity.promptedByQuestion\n : typeof rawUpdates?.promptedByQuestion === \"string\"\n ? rawUpdates.promptedByQuestion\n : undefined,\n };\n }\n\n private parseJsonObject(content?: string | null): any | null {\n const trimmed = content?.trim();\n if (!trimmed) return null;\n\n for (const candidate of extractJsonCandidates(trimmed)) {\n try {\n return JSON.parse(candidate);\n } catch {\n // keep trying candidates\n }\n }\n\n return null;\n }\n\n private normalizeContradictionVerificationResult(parsed: any): ContradictionVerificationResult | null {\n if (!parsed || typeof parsed.isContradiction !== \"boolean\") return null;\n\n const rawWhich = parsed.whichIsNewer ?? parsed.winner;\n const normalizedWhich =\n rawWhich === \"first\" || rawWhich === \"existing\"\n ? \"first\"\n : rawWhich === \"second\" || rawWhich === \"new\"\n ? \"second\"\n : \"unclear\";\n\n return {\n isContradiction: Boolean(parsed.isContradiction),\n confidence: typeof parsed.confidence === \"number\" ? parsed.confidence : 0.5,\n reasoning:\n typeof parsed.reasoning === \"string\"\n ? parsed.reasoning\n : typeof parsed.explanation === \"string\"\n ? parsed.explanation\n : \"\",\n whichIsNewer: normalizedWhich,\n };\n }\n\n private normalizeSuggestedLinksResult(parsed: any): SuggestedLinks | null {\n if (!parsed || !Array.isArray(parsed.links)) {\n return null;\n }\n\n const normalizedLinks = parsed.links\n .map((link: any) => {\n const rawLinkType = link?.linkType ?? link?.type;\n return {\n targetId: typeof link?.targetId === \"string\" ? link.targetId : \"\",\n linkType:\n rawLinkType === \"follows\" ||\n rawLinkType === \"references\" ||\n rawLinkType === \"contradicts\" ||\n rawLinkType === \"supports\" ||\n rawLinkType === \"related\"\n ? rawLinkType\n : \"related\",\n strength: typeof link?.strength === \"number\" ? Math.max(0, Math.min(1, link.strength)) : 0.5,\n reason: typeof link?.reason === \"string\" ? link.reason : undefined,\n };\n })\n .filter((link: any) => link.targetId.length > 0);\n\n return { links: normalizedLinks };\n }\n\n private normalizeMemorySummaryResult(parsed: any): MemorySummaryResult | null {\n if (!parsed) return null;\n\n const normalized: MemorySummaryResult = {\n summaryText:\n typeof parsed.summaryText === \"string\"\n ? parsed.summaryText\n : typeof parsed.summary === \"string\"\n ? parsed.summary\n : \"\",\n keyFacts: Array.isArray(parsed.keyFacts) ? parsed.keyFacts.filter((f: unknown) => typeof f === \"string\") : [],\n keyEntities: Array.isArray(parsed.keyEntities)\n ? parsed.keyEntities.filter((e: unknown) => typeof e === \"string\")\n : Array.isArray(parsed.entities)\n ? parsed.entities.filter((e: unknown) => typeof e === \"string\")\n : [],\n };\n\n return normalized.summaryText.length > 0 ? normalized : null;\n }\n\n private normalizeDaySummaryResult(parsed: any): DaySummaryResultShape | null {\n if (!parsed) return null;\n\n const normalized: DaySummaryResultShape = {\n summary: typeof parsed.summary === \"string\" ? parsed.summary.trim() : \"\",\n bullets: Array.isArray(parsed.bullets)\n ? parsed.bullets.filter((item: unknown) => typeof item === \"string\").map((item: string) => item.trim()).filter(Boolean)\n : [],\n next_actions: Array.isArray(parsed.next_actions)\n ? parsed.next_actions.filter((item: unknown) => typeof item === \"string\").map((item: string) => item.trim()).filter(Boolean)\n : [],\n risks_or_open_loops: Array.isArray(parsed.risks_or_open_loops)\n ? parsed.risks_or_open_loops.filter((item: unknown) => typeof item === \"string\").map((item: string) => item.trim()).filter(Boolean)\n : [],\n };\n\n return normalized.summary.length > 0 ? normalized : null;\n }\n\n private sanitizeConsolidationResult(result: {\n items?: unknown[];\n profileUpdates?: unknown[];\n entityUpdates?: unknown[];\n }): ConsolidationResult {\n const items: ConsolidationResult[\"items\"] = [];\n for (const item of Array.isArray(result.items) ? result.items : []) {\n const rawAction = typeof (item as any)?.action === \"string\" ? (item as any).action.toUpperCase() : \"SKIP\";\n const action =\n rawAction === \"ADD\" ||\n rawAction === \"MERGE\" ||\n rawAction === \"UPDATE\" ||\n rawAction === \"INVALIDATE\" ||\n rawAction === \"SKIP\"\n ? rawAction\n : \"SKIP\";\n const existingId =\n typeof (item as any)?.existingId === \"string\"\n ? (item as any).existingId.trim()\n : typeof (item as any)?.newMemoryId === \"string\"\n ? (item as any).newMemoryId.trim()\n : typeof (item as any)?.memoryId === \"string\"\n ? (item as any).memoryId.trim()\n : \"\";\n if (!existingId) continue;\n const mergeWith = typeof (item as any)?.mergeWith === \"string\" ? (item as any).mergeWith : undefined;\n const reason = typeof (item as any)?.reason === \"string\" ? (item as any).reason : \"\";\n const rawUpdatedContent = typeof (item as any)?.updatedContent === \"string\" ? (item as any).updatedContent : undefined;\n if (!rawUpdatedContent) {\n items.push({ existingId, action, mergeWith, updatedContent: undefined, reason });\n continue;\n }\n const sanitized = sanitizeMemoryContent(rawUpdatedContent);\n if (!sanitized.clean) {\n log.warn(`consolidation item sanitized (${existingId}); violations=${sanitized.violations.join(\", \")}`);\n }\n items.push({\n existingId,\n action,\n mergeWith,\n updatedContent: sanitized.text,\n reason,\n });\n }\n const profileUpdates = (Array.isArray(result.profileUpdates) ? result.profileUpdates : [])\n .map((update: any) =>\n typeof update === \"string\"\n ? update.trim()\n : typeof update?.content === \"string\"\n ? update.content.trim()\n : \"\",\n )\n .filter((update) => update.length > 0);\n const entityUpdates = (Array.isArray(result.entityUpdates) ? result.entityUpdates : [])\n .map((entity: any) => this.normalizeEntityUpdate(entity))\n .filter((entity: ExtractedEntityResult) => entity.name.length > 0);\n return { items, profileUpdates, entityUpdates };\n }\n\n private async applyProactiveQuestionPass(\n conversation: string,\n base: ExtractionResult,\n ): Promise<ExtractionResult> {\n if (!this.config.proactiveExtractionEnabled) return base;\n const maxAdditional = Math.max(0, Math.floor(this.config.maxProactiveQuestionsPerExtraction));\n if (maxAdditional === 0) return base;\n if (this.config.proactiveExtractionTimeoutMs === 0) return base;\n if (this.config.proactiveExtractionMaxTokens === 0) return base;\n\n try {\n const proactive = await this.generateProactiveQuestions(conversation, base, maxAdditional);\n if (proactive.length === 0) return base;\n const proactiveAdditions = await this.answerProactiveQuestions(\n conversation,\n base,\n proactive,\n maxAdditional,\n );\n if (!this.hasExtractionOutputs(proactiveAdditions)) return base;\n return this.mergeProactiveExtractionPass(base, proactiveAdditions, maxAdditional);\n } catch (err) {\n log.debug(`proactive extraction question pass failed (ignored): ${err}`);\n return base;\n }\n }\n\n private parseProactiveQuestionsFromText(\n content: string,\n existingQuestionKeys: Set<string>,\n ): ExtractionQuestion[] {\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate) as Partial<ProactiveQuestionsResultParsed>;\n if (!Array.isArray(parsed.questions)) continue;\n return parsed.questions\n .map((q) => normalizeQuestion(q as ExtractionQuestion))\n .filter((q) => q.question.length > 0)\n .filter((q) => !existingQuestionKeys.has(q.question.toLowerCase()));\n } catch {\n // Continue to next candidate.\n }\n }\n return [];\n }\n\n private parseProactiveExtractionResultFromText(content: string): ExtractionResult | null {\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = ProactiveExtractionResultSchema.parse(JSON.parse(candidate));\n return this.normalizeExtractionResultPayload({\n ...parsed,\n questions: [],\n });\n } catch {\n // Continue to next candidate.\n }\n }\n return null;\n }\n\n private async generateProactiveQuestions(\n conversation: string,\n base: ExtractionResult,\n maxAdditional: number,\n ): Promise<ExtractionQuestion[]> {\n const existingQuestionKeys = new Set(\n (base.questions ?? [])\n .map((q) => q.question.trim().toLowerCase())\n .filter((q) => q.length > 0),\n );\n const factsPreview = base.facts\n .slice(0, 8)\n .map((f) => `- (${f.category}) ${f.content}`)\n .join(\"\\n\");\n const existingQuestionsPreview = (base.questions ?? [])\n .slice(0, 8)\n .map((q) => `- ${q.question}`)\n .join(\"\\n\");\n\n const prompt = [\n \"You are doing a proactive second-pass memory extraction.\",\n `Generate up to ${maxAdditional} additional high-value follow-up questions not already covered.`,\n \"Return only valid JSON with this shape:\",\n '{\"questions\":[{\"question\":\"...\",\"context\":\"...\",\"priority\":0.0}]}',\n \"\",\n \"Current extracted facts:\",\n factsPreview || \"(none)\",\n \"\",\n \"Questions already extracted (do not repeat):\",\n existingQuestionsPreview || \"(none)\",\n \"\",\n \"Conversation:\",\n conversation,\n ].join(\"\\n\");\n\n if (this.shouldUseLocalLlm) {\n try {\n const localResponse = await this.localLlm.chatCompletion(\n [\n {\n role: \"system\",\n content: \"You are a proactive memory extraction assistant. Output valid JSON only.\",\n },\n { role: \"user\", content: prompt },\n ],\n {\n temperature: 0.2,\n maxTokens: this.config.proactiveExtractionMaxTokens,\n timeoutMs: this.config.proactiveExtractionTimeoutMs,\n operation: \"proactive_extraction\",\n priority: \"background\",\n },\n );\n if (localResponse?.content) {\n const localParsed = this.parseProactiveQuestionsFromText(\n localResponse.content.trim(),\n existingQuestionKeys,\n );\n if (localParsed.length > 0) {\n return localParsed.slice(0, maxAdditional);\n }\n }\n if (!this.config.localLlmFallback) {\n return [];\n }\n } catch (err) {\n if (!this.config.localLlmFallback) {\n throw err;\n }\n }\n }\n\n const fallbackResult = await this.fallbackLlm.parseWithSchema(\n [\n {\n role: \"system\",\n content: \"Generate additional proactive memory follow-up questions. Return valid JSON only.\",\n },\n { role: \"user\", content: prompt },\n ],\n ProactiveQuestionsResultSchema,\n this.withGatewayAgent({\n temperature: 0.2,\n maxTokens: this.config.proactiveExtractionMaxTokens,\n timeoutMs: this.config.proactiveExtractionTimeoutMs,\n }),\n );\n if (!fallbackResult?.questions) return [];\n return fallbackResult.questions\n .map((q) => normalizeQuestion(q as ExtractionQuestion))\n .filter((q) => q.question.length > 0)\n .filter((q) => !existingQuestionKeys.has(q.question.toLowerCase()))\n .slice(0, maxAdditional);\n }\n\n private async answerProactiveQuestions(\n conversation: string,\n base: ExtractionResult,\n proactiveQuestions: ExtractionQuestion[],\n maxAdditional: number,\n ): Promise<ExtractionResult> {\n const factsPreview = base.facts\n .slice(0, 8)\n .map((f) => `- (${f.category}) ${f.content}`)\n .join(\"\\n\");\n const entitiesPreview = base.entities\n .slice(0, 8)\n .map((entity) => `- (${entity.type}) ${entity.name}: ${entity.facts.join(\"; \") || \"(no facts)\"}`)\n .join(\"\\n\");\n const proactivePreview = proactiveQuestions\n .slice(0, maxAdditional)\n .map((question, index) => `${index + 1}. ${question.question}${question.context ? `\\n context: ${question.context}` : \"\"}`)\n .join(\"\\n\");\n\n const prompt = [\n \"You are answering proactive memory follow-up questions using only the provided buffered conversation.\",\n `Return at most ${maxAdditional} additional high-confidence memory candidates that were omitted from the base extraction.`,\n \"Only include information directly supported by the conversation. Do not speculate. Do not repeat the base extraction.\",\n \"Return only valid JSON with this shape:\",\n '{\"facts\":[{\"category\":\"fact\",\"content\":\"...\",\"confidence\":0.0,\"tags\":[\"...\"],\"entityRef\":\"optional\",\"promptedByQuestion\":\"optional\"}],\"profileUpdates\":[\"...\"],\"entities\":[{\"name\":\"...\",\"type\":\"person\",\"facts\":[\"...\"],\"structuredSections\":[{\"key\":\"beliefs\",\"title\":\"Beliefs\",\"facts\":[\"...\"]}],\"promptedByQuestion\":\"optional\"}],\"relationships\":[{\"source\":\"...\",\"target\":\"...\",\"label\":\"...\",\"promptedByQuestion\":\"optional\"}]}',\n \"\",\n \"Base extracted facts (do not repeat):\",\n factsPreview || \"(none)\",\n \"\",\n \"Base extracted entities (do not repeat):\",\n entitiesPreview || \"(none)\",\n \"\",\n \"Answer these follow-up questions from the same conversation only:\",\n proactivePreview || \"(none)\",\n \"\",\n \"Conversation:\",\n conversation,\n ].join(\"\\n\");\n\n if (this.shouldUseLocalLlm) {\n try {\n const localResponse = await this.localLlm.chatCompletion(\n [\n {\n role: \"system\",\n content: \"You are a proactive memory extraction assistant. Output valid JSON only.\",\n },\n { role: \"user\", content: prompt },\n ],\n {\n temperature: 0.2,\n maxTokens: this.config.proactiveExtractionMaxTokens,\n timeoutMs: this.config.proactiveExtractionTimeoutMs,\n operation: \"proactive_extraction\",\n priority: \"background\",\n },\n );\n if (localResponse?.content) {\n const parsed = this.parseProactiveExtractionResultFromText(localResponse.content.trim());\n if (parsed) {\n return this.sanitizeExtractionResult(parsed);\n }\n }\n if (!this.config.localLlmFallback) {\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n } catch (err) {\n if (!this.config.localLlmFallback) {\n throw err;\n }\n }\n }\n\n const fallbackResult = await this.fallbackLlm.parseWithSchema(\n [\n {\n role: \"system\",\n content: \"Answer proactive memory follow-up questions from the provided conversation only. Return valid JSON only.\",\n },\n { role: \"user\", content: prompt },\n ],\n ProactiveExtractionResultSchema,\n this.withGatewayAgent({\n temperature: 0.2,\n maxTokens: this.config.proactiveExtractionMaxTokens,\n timeoutMs: this.config.proactiveExtractionTimeoutMs,\n }),\n );\n if (!fallbackResult) {\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n return this.sanitizeExtractionResult(\n this.normalizeExtractionResultPayload({\n ...fallbackResult,\n questions: [],\n }),\n );\n }\n\n private mergeProactiveExtractionPass(\n base: ExtractionResult,\n proactive: ExtractionResult,\n maxAdditional: number,\n ): ExtractionResult {\n const allowlist = this.config.proactiveExtractionCategoryAllowlist;\n let remainingBudget = Math.max(0, Math.floor(maxAdditional));\n const mergedFacts = [...base.facts];\n const seenFacts = new Set(base.facts.map((fact) => normalizeFactKey(fact)));\n for (const fact of proactive.facts) {\n if (remainingBudget <= 0) break;\n if (fact.confidence < PROACTIVE_MIN_CONFIDENCE) continue;\n if (allowlist && !allowlist.includes(fact.category as MemoryCategory)) continue;\n const key = normalizeFactKey(fact);\n if (seenFacts.has(key)) continue;\n seenFacts.add(key);\n mergedFacts.push({ ...fact, source: \"proactive\" });\n remainingBudget -= 1;\n }\n\n const mergedEntities = base.entities.map((entity) => ({\n ...entity,\n facts: [...entity.facts],\n structuredSections: entity.structuredSections\n ? entity.structuredSections.map((section) => ({\n ...section,\n facts: [...section.facts],\n }))\n : undefined,\n }));\n const entityIndex = new Map(mergedEntities.map((entity, index) => [normalizeEntityKey(entity), index]));\n for (const entity of proactive.entities) {\n if (remainingBudget <= 0) break;\n const key = normalizeEntityKey(entity);\n const existingIndex = entityIndex.get(key);\n if (typeof existingIndex === \"number\") {\n const existing = mergedEntities[existingIndex]!;\n const nextFacts = new Set(existing.facts.map((fact) => fact.trim()));\n const nextSections = new Map(\n (existing.structuredSections ?? []).map((section) => [section.key, {\n ...section,\n facts: [...section.facts],\n }]),\n );\n let changed = false;\n for (const fact of entity.facts) {\n const trimmed = fact.trim();\n if (!trimmed || nextFacts.has(trimmed)) continue;\n nextFacts.add(trimmed);\n changed = true;\n }\n for (const section of entity.structuredSections ?? []) {\n const existingSection = nextSections.get(section.key);\n if (!existingSection) {\n nextSections.set(section.key, {\n key: section.key,\n title: section.title,\n facts: [...section.facts],\n });\n changed = true;\n continue;\n }\n const nextSectionFacts = new Set(existingSection.facts.map((fact) => fact.trim()));\n for (const fact of section.facts) {\n const trimmed = fact.trim();\n if (!trimmed || nextSectionFacts.has(trimmed)) continue;\n nextSectionFacts.add(trimmed);\n changed = true;\n }\n existingSection.facts = Array.from(nextSectionFacts);\n }\n if (changed) {\n mergedEntities[existingIndex] = {\n ...existing,\n facts: Array.from(nextFacts),\n structuredSections: Array.from(nextSections.values()),\n source: \"proactive\",\n promptedByQuestion: existing.promptedByQuestion ?? entity.promptedByQuestion,\n };\n remainingBudget -= 1;\n }\n continue;\n }\n mergedEntities.push({\n ...entity,\n source: \"proactive\",\n structuredSections: entity.structuredSections\n ? entity.structuredSections.map((section) => ({\n ...section,\n facts: [...section.facts],\n }))\n : undefined,\n });\n entityIndex.set(key, mergedEntities.length - 1);\n remainingBudget -= 1;\n }\n\n const mergedProfileUpdates = [...base.profileUpdates];\n const seenProfileUpdates = new Set(base.profileUpdates.map((update) => normalizeProfileUpdateKey(update)));\n for (const update of proactive.profileUpdates) {\n if (remainingBudget <= 0) break;\n const key = normalizeProfileUpdateKey(update);\n if (!key || seenProfileUpdates.has(key)) continue;\n seenProfileUpdates.add(key);\n mergedProfileUpdates.push(update.trim());\n remainingBudget -= 1;\n }\n\n const mergedRelationships = [...(base.relationships ?? [])];\n const seenRelationships = new Set(mergedRelationships.map((relationship) => normalizeRelationshipKey(relationship)));\n for (const relationship of proactive.relationships ?? []) {\n if (remainingBudget <= 0) break;\n const key = normalizeRelationshipKey(relationship);\n if (seenRelationships.has(key)) continue;\n seenRelationships.add(key);\n mergedRelationships.push({ ...relationship, extractionSource: \"proactive\" });\n remainingBudget -= 1;\n }\n\n return {\n ...base,\n facts: mergedFacts,\n entities: mergedEntities,\n profileUpdates: mergedProfileUpdates,\n relationships: mergedRelationships,\n };\n }\n\n private async parseWithGatewayFallback<T>(\n traceId: string,\n operation: LlmTraceEvent[\"operation\"],\n startedAtMs: number,\n schema: { parse: (data: unknown) => T },\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options: { temperature?: number; maxTokens?: number } = {},\n ): Promise<T | null> {\n const detailed = await this.fallbackLlm.parseWithSchemaDetailed(messages, schema, this.withGatewayAgent(options));\n if (detailed?.result) {\n const durationMs = Date.now() - startedAtMs;\n this.emit({\n kind: \"llm_end\",\n traceId,\n model: detailed.modelUsed,\n operation,\n durationMs,\n output: JSON.stringify(detailed.result).slice(0, 2000),\n });\n return detailed.result;\n }\n return null;\n }\n\n async extract(turns: BufferTurn[], existingEntities?: string[]): Promise<ExtractionResult> {\n\n // Guard: skip if buffer is empty or all turns are whitespace-only\n const substantiveTurns = turns.filter((t) => t.content.trim().length > 0);\n if (substantiveTurns.length === 0) {\n log.debug(\"extraction skipped — no substantive turns in buffer\");\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n\n const boundedTurns = substantiveTurns\n .map((turn) => ({\n ...turn,\n content: turn.role === \"assistant\"\n ? applyWorkExtractionBoundary(turn.content)\n : turn.content,\n }))\n .filter((turn) => turn.content.trim().length > 0);\n const conversation = boundedTurns\n .map((t) => {\n const roleLabel =\n t.extractionContextOnly === true ? `context ${t.role}` : t.role;\n return `[${roleLabel}] ${t.content}`;\n })\n .join(\"\\n\\n\");\n if (conversation.trim().length === 0) {\n log.debug(\"extraction skipped — conversation only contained non-memory work-layer context\");\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n if (\n this.config.extractionTelemetryPrefilterEnabled &&\n looksLikeMechanicalTelemetryTranscript(conversation)\n ) {\n log.debug(\"extraction skipped — mechanical action/state telemetry without durable-memory cues\");\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n\n // Use the last turn's timestamp for temporal anchoring (more accurate than wall-clock)\n const lastTurnTs = boundedTurns.length > 0 ? new Date(boundedTurns[boundedTurns.length - 1].timestamp) : undefined;\n const messageTimestamp = lastTurnTs && !isNaN(lastTurnTs.getTime()) ? lastTurnTs : undefined;\n\n const traceId = crypto.randomUUID();\n // Only emit llm_start for the direct path when a client or local LLM is configured.\n // Fallback-only deployments skip this to avoid fake spans in Opik.\n const emittedDirectStart = !!(this.shouldUseDirectClient || this.shouldUseLocalLlm);\n if (emittedDirectStart) {\n this.emit({ kind: \"llm_start\", traceId, model: this.config.model, operation: \"extraction\", input: conversation });\n }\n let closedDirectTrace = false;\n const startTime = Date.now();\n\n // --- profiling instrumentation ---\n const extractionTraceId = this.profiler.startTrace(\"extraction\", undefined, {\n model: this.config.model,\n localLlm: this.config.localLlmEnabled,\n });\n this.profiler.startSpan(\"total\", extractionTraceId);\n\n try {\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n this.profiler.startSpan(\"local-llm\", extractionTraceId);\n try {\n const localResult = await this.extractWithLocalLlm(conversation, existingEntities);\n if (localResult) {\n const durationMs = Date.now() - startTime;\n this.profiler.endSpan(\"local-llm\", extractionTraceId);\n this.emit({ kind: \"llm_end\", traceId, model: this.config.localLlmModel, operation: \"extraction\", durationMs });\n log.debug(`extraction: used local LLM — ${localResult.facts.length} facts, ${localResult.entities.length} entities`);\n const sanitized = this.sanitizeExtractionResult(localResult, messageTimestamp);\n return await this.applyProactiveQuestionPass(conversation, sanitized);\n }\n // Local failed, fall back if allowed\n if (!this.config.localLlmFallback) {\n log.warn(\"extraction: local LLM failed and fallback disabled\");\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n log.info(\"extraction: local LLM unavailable, falling back to gateway default AI\");\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(\"extraction: local LLM error and fallback disabled:\", err);\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n }\n log.info(\"extraction: local LLM error, falling back to gateway default AI:\", err);\n } finally {\n // End local-llm span if it wasn't ended on the success path\n try { this.profiler.endSpan(\"local-llm\", extractionTraceId); } catch { /* span may already be closed */ }\n }\n }\n\n // Try direct OpenAI-compatible client (Scryr, OpenRouter, etc.)\n if (this.shouldUseDirectClient) {\n this.profiler.startSpan(\"direct-client\", extractionTraceId);\n try {\n const directResult = await this.extractWithDirectClient(conversation, existingEntities);\n if (directResult) {\n const durationMs = Date.now() - startTime;\n this.profiler.endSpan(\"direct-client\", extractionTraceId);\n this.emit({ kind: \"llm_end\", traceId, model: this.config.model, operation: \"extraction\", durationMs });\n log.debug(`extraction: used direct client (${this.config.model}) — ${directResult.facts.length} facts, ${directResult.entities.length} entities`);\n const sanitized = this.sanitizeExtractionResult(directResult, messageTimestamp);\n return await this.applyProactiveQuestionPass(conversation, sanitized);\n }\n // Emit error event so Opik sees the direct client failure before fallback.\n // Wrapped in try/catch so a subscriber error doesn't break the fallback path.\n try {\n this.emit({\n kind: \"llm_error\", traceId, model: this.config.model, operation: \"extraction\",\n durationMs: Date.now() - startTime, error: \"direct client returned no result\",\n });\n } catch { /* trace emit must not block fallback */ }\n closedDirectTrace = true;\n log.info(\"extraction: direct client returned no result, falling back to gateway AI\");\n } catch (err) {\n try {\n this.emit({\n kind: \"llm_error\", traceId, model: this.config.model, operation: \"extraction\",\n durationMs: Date.now() - startTime, error: String(err),\n });\n } catch { /* trace emit must not block fallback */ }\n closedDirectTrace = true;\n log.info(\"extraction: direct client failed, falling back to gateway AI:\", err);\n } finally {\n try { this.profiler.endSpan(\"direct-client\", extractionTraceId); } catch { /* span may already be closed */ }\n }\n }\n\n // Close any orphaned direct-path llm_start (e.g., local LLM failed, no direct client)\n if (emittedDirectStart && !closedDirectTrace) {\n try {\n this.emit({\n kind: \"llm_error\", traceId, model: this.config.model, operation: \"extraction\",\n durationMs: Date.now() - startTime, error: \"local LLM failed, handing off to gateway fallback\",\n });\n } catch { /* trace emit must not block fallback */ }\n }\n\n // In gateway mode this is the primary extraction path. In plugin mode it is the\n // final fallback after local/direct attempts fail. Emit a fresh llm_start so the\n // gateway-backed call gets its own trace rather than being orphaned under the\n // direct-client traceId.\n const fallbackTraceId = crypto.randomUUID();\n const fallbackStartTime = Date.now();\n if (this.useGatewayModelSource) {\n log.debug(\n `extraction: using gateway model chain as primary path` +\n (this.config.gatewayAgentId ? ` (agent: ${this.config.gatewayAgentId})` : \" (defaults)\"),\n );\n } else {\n log.info(\"extraction: falling back to gateway default AI\");\n }\n\n this.profiler.startSpan(\"gateway-fallback\", extractionTraceId);\n try {\n const messages = [\n { role: \"system\" as const, content: this.buildExtractionInstructions(existingEntities) },\n { role: \"user\" as const, content: conversation },\n ];\n\n this.emit({ kind: \"llm_start\", traceId: fallbackTraceId, model: \"fallback\", operation: \"extraction\", input: conversation });\n\n const detailed = await this.fallbackLlm.parseWithSchemaDetailed(\n messages,\n ExtractionResultSchema,\n this.withGatewayAgent({\n temperature: 0.3,\n maxTokens: this.config.extractionMaxOutputTokens,\n timeoutMs: this.config.localLlmTimeoutMs,\n }),\n );\n\n const fallbackDurationMs = Date.now() - fallbackStartTime;\n\n if (detailed?.result && Array.isArray(detailed.result.facts)) {\n const result = detailed.result;\n this.emit({\n kind: \"llm_end\", traceId: fallbackTraceId, model: detailed.modelUsed, operation: \"extraction\",\n durationMs: fallbackDurationMs, output: JSON.stringify(result).slice(0, 2000),\n });\n log.debug(\n `extracted ${result.facts.length} facts, ${result.entities.length} entities, ${(result.questions ?? []).length} questions via fallback (${detailed.modelUsed})`,\n );\n // Zod schema accepts snake_case aliases (final_answer / observed_outcome)\n // alongside camelCase for gateway-tolerance, but the downstream\n // ExtractedFact contract only exposes camelCase. Collapse each fact's\n // reasoningTrace through normalizeReasoningTrace before passing it on so\n // gateway output matches the shape local/direct-client paths produce.\n const normalizedFacts = result.facts.map((f: any) => {\n if (!f?.reasoningTrace) return f;\n return {\n ...f,\n reasoningTrace: normalizeReasoningTrace(f.reasoningTrace) ?? undefined,\n };\n });\n const sanitized = this.sanitizeExtractionResult({\n ...result,\n facts: normalizedFacts,\n questions: result.questions ?? [],\n identityReflection: result.identityReflection ?? undefined,\n } as ExtractionResult, messageTimestamp);\n return await this.applyProactiveQuestionPass(conversation, sanitized);\n }\n\n this.emit({\n kind: \"llm_error\", traceId: fallbackTraceId, model: \"fallback\", operation: \"extraction\",\n durationMs: fallbackDurationMs, error: \"fallback returned no parsed output\",\n });\n log.warn(\"extraction fallback returned no parsed output\");\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n } catch (err) {\n this.emit({\n kind: \"llm_error\", traceId: fallbackTraceId, model: \"fallback\", operation: \"extraction\",\n durationMs: Date.now() - fallbackStartTime, error: String(err),\n });\n log.error(\"extraction fallback failed\", err);\n return { facts: [], profileUpdates: [], entities: [], questions: [] };\n } finally {\n try { this.profiler.endSpan(\"gateway-fallback\", extractionTraceId); } catch { /* span may already be closed */ }\n }\n\n } finally {\n // --- profiling: close the total span and trace ---\n this.profiler.endSpan(\"total\", extractionTraceId);\n this.profiler.endTrace(extractionTraceId); // persists to JSONL file\n }\n }\n\n /**\n * Extract memories using local LLM with JSON mode.\n * Uses a minimal prompt to fit within local model context limits (typically 4k-8k).\n */\n private async extractWithLocalLlm(conversation: string, existingEntities?: string[]): Promise<ExtractionResult | null> {\n log.debug(\n `extractWithLocalLlm: starting extraction, localLlmEnabled=${this.shouldUseLocalLlm}, model=${this.config.localLlmModel}`,\n );\n\n // Get dynamic context sizes based on model capabilities (with optional user override)\n const contextSizes = this.modelRegistry.calculateContextSizes(\n this.config.localLlmModel,\n this.config.localLlmMaxContext\n );\n log.debug(`Model context: ${contextSizes.description}`);\n\n const maxConversationChars = contextSizes.maxInputChars;\n const truncatedConversation = conversation.length > maxConversationChars\n ? conversation.slice(0, maxConversationChars) + \"\\n\\n[truncated]\"\n : conversation;\n\n const localPrompt = `You are a memory extraction system. Extract durable, reusable memories from this conversation.\n\nMemory categories — use the MOST SPECIFIC category that fits:\n- fact: Objective information about the world\n- preference: User likes, dislikes, or stylistic choices\n- correction: User correcting a mistake (highest priority)\n- entity: People, projects, tools, companies (use canonical hyphenated names like \"my-project\")\n- decision: Choices made with rationale\n- relationship: How entities relate (e.g., \"Alice manages Bob\")\n- principle: Durable rules or operating beliefs (e.g., \"never use X API\")\n- commitment: Promises, obligations, deadlines\n- moment: Emotionally significant events\n- skill: Demonstrated capabilities\n- rule: Explicit operational rules or constraints\n- procedure: Repeatable workflows — use when the user describes a multi-step play (≥2 ordered steps). Put the human-readable trigger/context in \"content\" (e.g. \"When you deploy…\") and list steps in \"procedureSteps\" as [{\"order\":1,\"intent\":\"…\"}, …] mirroring the gateway extraction schema.\n- reasoning_trace: Stored solution chains — use when the user narrates HOW they solved a specific problem step-by-step (\"here's how I figured out…\", \"the debugging went like this…\"). Put a short title in \"content\" (e.g. \"How I debugged the staging latency spike\") and the chain in \"reasoningTrace\": {\"steps\":[{\"order\":1,\"description\":\"…\"}, …], \"finalAnswer\":\"…\", \"observedOutcome\":\"…\" (optional)}. Require ≥2 ordered steps and a finalAnswer. Do NOT use for ordinary decisions (prefer \"decision\") or reusable workflows (prefer \"procedure\").\n\nIMPORTANT: Do NOT label everything as \"fact\". Use \"decision\" for architectural choices, \"commitment\" for deadlines/promises, \"principle\" for reusable rules, \"correction\" for when the user rejects a suggestion, etc.\n\n=== DO NOT EXTRACT (negative examples) ===\nThese are operational noise - skip them:\n- \"The user has a cron job that runs every 30 minutes\" (scheduled task descriptions)\n- \"The user encountered error XYZ at 3:45 PM\" (temporary error states)\n- \"The file is located at /path/to/project/file\" (transient file paths)\n- \"The system is using 4GB of memory\" (current resource usage)\n- \"The user ran the 'git status' command\" (individual command executions)\n- \"The conversation took place on Tuesday\" (session metadata)\n- \"The agent read the file at /path/to/file.txt\" (agent's own actions)\n- \"The user's OpenClaw automation posts to #channel on failures\" (automation behavior descriptions)\n- \"The user stores state in /path/to/state.json\" (implementation details)\n- \"The X-watch automation has been stalled for 58 hours\" (system status updates)\n- \"The user processed 5 batch files and extracted insights\" (processing summaries)\n- \"The user has a cron job that runs a Checkpoint Loop every 2 hours\" (automation schedules)\n- \"The user runs a Morning Surprise cron job daily at 7:30 AM\" (automation schedules)\n- \"The user runs an X Bookmarks → Insights pipeline hourly at :13\" (automation schedules)\n- \"The user's system mines X/Twitter mentions for ideas every 10a/2p/6p\" (automation schedules)\n- \"The user runs a Health Insights cron job weekday mornings\" (automation schedules)\n- \"The system monitors the showcase page every 12 hours\" (system monitoring configurations)\n\n=== DO EXTRACT (positive examples) ===\nThese are durable insights - capture them:\n- \"The user prefers dark mode interfaces and finds light mode uncomfortable\" (preference)\n- \"The user works primarily with TypeScript and avoids Python for frontend code\" (long-term fact)\n- \"The user's side project 'alpha-trader' uses a custom algorithm for arbitrage\" (entity + detail)\n- \"The user corrected that PostgreSQL 15 is required, not version 14\" (correction)\n- \"The user never commits code without running tests first\" (principle)\n- \"The user has a meeting with the design team every Friday at 2pm\" (commitment)\n\n=== Rules ===\n- Extract only NEW information worth remembering across sessions\n- Skip transient details (file paths, current errors, temporary states, agent actions)\n- Confidence: Explicit (0.95-1.0), Implied (0.70-0.94), Inferred (0.40-0.69), Speculative (0.00-0.39)\n- Corrections get highest confidence (0.95+)\n- Each fact should be standalone and self-contained\n- Lines labelled [context user] or [context assistant] are reference context only. Use them to resolve pronouns and adjacent question/answer pairs, but do not extract a memory stated only in context lines unless a normal [user] or [assistant] line confirms or completes it.\n- CRITICAL: Use canonical hyphenated entity names (e.g., \"jane-doe\" not \"janedoe\")\n- CRITICAL: NEVER extract the same fact twice - check for duplicates before adding to facts array\n- CRITICAL: NEVER extract cron job schedules, automation configurations, or system monitoring details (these are operational noise)\n- If uncertain about relevance, prefer NOT extracting${this.config.extractionScopeClassificationEnabled ? `\n- For each fact, set \"scope\" to \"global\" (cross-project knowledge: framework bugs, library behavior, user preferences, tool configs, general patterns) or \"project\" (codebase-specific: file paths, env configs, deployment details, project workarounds). When in doubt, prefer \"project\".` : \"\"}\n\n=== Structured Attributes ===\nWhen a fact contains measurable, categorical, or precisely valued data, add a \"structuredAttributes\" object with key-value string pairs. This captures exact values for precise retrieval later.\nExamples of when to add structuredAttributes:\n- Product details: {\"price\": \"29.99\", \"brand\": \"Sony\", \"color\": \"black\", \"rating\": \"4.5\"}\n- Person details: {\"age\": \"32\", \"occupation\": \"engineer\", \"city\": \"Austin\"}\n- Events with dates: {\"date\": \"2024-03-15\", \"location\": \"San Francisco\"}\n- Decisions: {\"chosen\": \"PostgreSQL\", \"rejected\": \"MongoDB\", \"reason\": \"ACID compliance\"}\n- Quantities/measurements: {\"budget\": \"50000\", \"team_size\": \"5\", \"deadline\": \"2024-06-01\"}\nOnly add structuredAttributes when there are concrete values. Skip for abstract or narrative facts.\n\nAlso generate:\n1. 1-3 genuine questions you're curious about from this conversation\n2. Profile updates about user patterns/behaviors (if any)\n3. Relationships between entities (max 5). Use normalized names like \"person-jane-doe\", \"company-acme-corp\".\n4. For entity facts that fit a durable named heading, include entity.structuredSections with {key, title, facts}.\n\nOutput JSON:\n{\n \"facts\": [{\"category\": \"decision\", \"content\": \"Chose PostgreSQL over MongoDB for the user service\", \"importance\": 8, \"confidence\": 0.9, \"scope\": \"project\", \"structuredAttributes\": {\"chosen\": \"PostgreSQL\", \"rejected\": \"MongoDB\"}}, {\"category\": \"procedure\", \"content\": \"When you cut a hotfix release, follow the checklist\", \"importance\": 8, \"confidence\": 0.9, \"scope\": \"project\", \"procedureSteps\": [{\"order\": 1, \"intent\": \"Branch from main and cherry-pick the fix\"}, {\"order\": 2, \"intent\": \"Run CI and tag the release\"}]}, {\"category\": \"reasoning_trace\", \"content\": \"How I debugged the staging latency spike\", \"importance\": 7, \"confidence\": 0.9, \"scope\": \"project\", \"reasoningTrace\": {\"steps\": [{\"order\": 1, \"description\": \"Checked CPU/memory dashboards — both were flat\"}, {\"order\": 2, \"description\": \"Ran a traceroute and saw retries against the cache tier\"}, {\"order\": 3, \"description\": \"Tailed cache-tier logs and spotted eviction storms\"}], \"finalAnswer\": \"Root cause was an undersized eviction policy on the session cache\", \"observedOutcome\": \"Increased cache size, p95 returned to baseline within 10 minutes\"}}, {\"category\": \"commitment\", \"content\": \"Must ship v2.0 API by end of March\", \"importance\": 10, \"confidence\": 1.0, \"scope\": \"project\", \"structuredAttributes\": {\"deadline\": \"end of March\", \"deliverable\": \"v2.0 API\"}}, {\"category\": \"fact\", \"content\": \"The store backend uses Redis for session caching\", \"importance\": 6, \"confidence\": 0.95, \"scope\": \"project\", \"entityRef\": \"project-acme-store\"}, {\"category\": \"principle\", \"content\": \"Always run migrations in a transaction to avoid partial schema updates\", \"importance\": 8, \"confidence\": 0.9, \"scope\": \"global\"}],\n \"entities\": [{\"name\": \"person-jane-doe\", \"type\": \"person\", \"facts\": [\"Works at Acme Corp\", \"Prefers Python over JavaScript\"], \"structuredSections\": [{\"key\": \"beliefs\", \"title\": \"Beliefs\", \"facts\": [\"Python is a better fit than JavaScript for backend work.\"]}]}, {\"name\": \"project-acme-store\", \"type\": \"project\", \"facts\": [\"Built with Next.js\", \"Deployed on Vercel\"]}],\n \"profileUpdates\": [\"User prefers dark mode in all editors\"],\n \"questions\": [{\"question\": \"Which cloud provider hosts the staging environment?\", \"context\": \"Came up during deployment discussion\", \"priority\": 0.5}],\n \"relationships\": [{\"source\": \"person-jane-doe\", \"target\": \"company-acme-corp\", \"label\": \"works at\"}]\n}\n\nConversation:\n${truncatedConversation}`;\n\n log.debug(\n `extractWithLocalLlm: calling localLlm.chatCompletion with prompt length ${localPrompt.length}...`,\n );\n const response = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: \"You are a memory extraction system. Output valid JSON only.\" },\n { role: \"user\", content: localPrompt },\n ],\n {\n temperature: 0.1,\n maxTokens: contextSizes.maxOutputTokens,\n operation: \"extraction\",\n priority: \"background\",\n },\n );\n\n if (!response?.content) {\n log.debug(\"extractWithLocalLlm: chatCompletion returned null or empty content\");\n return null;\n }\n\n const content = response.content.trim();\n // Avoid logging model output content by default (may contain user data).\n log.debug(`extractWithLocalLlm: got response content, length=${content.length}`);\n\n for (const candidate of extractJsonCandidates(content)) {\n try {\n log.debug(`extractWithLocalLlm: attempting JSON parse, candidate length=${candidate.length}`);\n const parsed = JSON.parse(candidate);\n if (!this.looksLikeExtractionResultPayload(parsed)) {\n continue;\n }\n\n const result: ExtractionResult = this.normalizeExtractionResultPayload(parsed);\n\n log.debug(\n `extractWithLocalLlm: successfully parsed response, facts=${result.facts.length}, entities=${result.entities.length}, profileUpdates=${result.profileUpdates.length}, questions=${result.questions.length}`,\n );\n return result;\n } catch {\n // keep trying candidates\n }\n }\n\n // Try to extract partial facts from truncated JSON after all complete JSON\n // candidates fail to parse.\n log.debug(\"extractWithLocalLlm: JSON parse failed, attempting partial extraction...\");\n const partial = this.extractPartialFacts(content);\n if (partial.facts.length > 0 || partial.entities.length > 0) {\n log.debug(\n `extractWithLocalLlm: extracted ${partial.facts.length} partial facts from truncated JSON`,\n );\n return partial;\n }\n return null;\n }\n\n /**\n * Extract memories using direct OpenAI-compatible client (Chat Completions API).\n * Works with Scryr, OpenRouter, and other OpenAI-compatible endpoints.\n */\n private async extractWithDirectClient(\n conversation: string,\n existingEntities?: string[],\n ): Promise<ExtractionResult | null> {\n if (!this.client) return null;\n\n const tokenParams = buildChatCompletionTokenLimit(this.config.model, this.config.extractionMaxOutputTokens, {\n assumeOpenAI: this.directClientUsesOpenAiTokenSemantics(),\n });\n log.debug(`extractWithDirectClient: calling model=${this.config.model} tokenParams=${JSON.stringify(tokenParams)}`);\n\n const response = await this.client.chat.completions.create({\n model: this.config.model,\n messages: [\n {\n role: \"system\",\n content:\n this.buildExtractionInstructions(existingEntities) +\n `\\n\\nRespond with valid JSON matching this schema:\n{\n \"facts\": [{\"category\": \"decision\", \"content\": \"Chose React over Vue for the dashboard rewrite\", \"importance\": 8, \"confidence\": 0.9, \"tags\": [\"frontend\"], \"scope\": \"project\", \"structuredAttributes\": {\"chosen\": \"React\", \"rejected\": \"Vue\"}}, {\"category\": \"fact\", \"content\": \"The API gateway uses rate limiting at 1000 req/min\", \"importance\": 6, \"confidence\": 0.95, \"tags\": [\"infra\"], \"scope\": \"project\", \"entityRef\": \"project-dashboard\", \"structuredAttributes\": {\"rate_limit\": \"1000 req/min\"}}, {\"category\": \"reasoning_trace\", \"content\": \"How I chose the dashboard rewrite framework\", \"confidence\": 0.9, \"tags\": [\"frontend\"], \"scope\": \"project\", \"reasoningTrace\": {\"steps\": [{\"order\": 1, \"description\": \"Listed constraints: SSR needed, team mostly JS\"}, {\"order\": 2, \"description\": \"Ran a spike in Vue 3 — worked, but ecosystem felt thin for our needs\"}, {\"order\": 3, \"description\": \"Ran the same spike in React — integrated faster with Next.js\"}], \"finalAnswer\": \"Picked React with Next.js for SSR + ecosystem fit\"}}],\n \"entities\": [{\"name\": \"person-sarah-chen\", \"type\": \"person\", \"facts\": [\"Leads the backend team\", \"Joined from Google in 2024\"], \"structuredSections\": [{\"key\": \"beliefs\", \"title\": \"Beliefs\", \"facts\": [\"Small teams should own whole systems.\"]}]}, {\"name\": \"project-dashboard\", \"type\": \"project\", \"facts\": [\"React-based admin panel\", \"Deployed on AWS ECS\"]}],\n \"profileUpdates\": [\"User prefers TypeScript over plain JavaScript\"],\n \"questions\": [{\"question\": \"What database does the analytics service use?\", \"context\": \"Came up during discussion of migration plan\", \"priority\": 0.5}],\n \"relationships\": [{\"source\": \"person-sarah-chen\", \"target\": \"project-dashboard\", \"label\": \"leads development of\"}]\n}`,\n },\n { role: \"user\", content: conversation },\n ],\n ...tokenParams,\n });\n\n const content = response.choices?.[0]?.message?.content?.trim();\n if (!content) {\n log.info(`extractWithDirectClient: empty response — choices=${JSON.stringify(response.choices?.length ?? 0)} finishReason=${response.choices?.[0]?.finish_reason ?? \"n/a\"}`);\n return null;\n }\n\n log.info(\n `extractWithDirectClient: got response, length=${content.length}`,\n );\n\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate);\n\n return this.normalizeExtractionResultPayload(parsed);\n } catch {\n // keep trying candidates\n }\n }\n\n log.info(`extractWithDirectClient: failed to parse JSON from response (first 200 chars: ${content.slice(0, 200)})`);\n return null;\n }\n\n /**\n * Extract partial facts from truncated JSON responses.\n * Local LLMs sometimes hit token limits mid-JSON. This tries to salvage valid facts.\n */\n private extractPartialFacts(jsonStr: string): ExtractionResult {\n const allowedCategories = new Set([\n \"fact\",\n \"preference\",\n \"correction\",\n \"entity\",\n \"decision\",\n \"relationship\",\n \"principle\",\n \"commitment\",\n \"moment\",\n \"skill\",\n \"rule\",\n \"procedure\",\n \"reasoning_trace\",\n ]);\n const allowedEntityTypes = new Set([\n \"person\",\n \"project\",\n \"tool\",\n \"company\",\n \"place\",\n \"other\",\n ]);\n\n const facts: ExtractionResult[\"facts\"] = [];\n const entities: ExtractionResult[\"entities\"] = [];\n\n try {\n // Find all complete fact objects (ones with all required fields)\n const factRegex = /\\{\\s*\"category\"\\s*:\\s*\"([^\"]+)\"\\s*,\\s*\"content\"\\s*:\\s*\"([^\"]+)\"\\s*,\\s*\"confidence\"\\s*:\\s*([0-9.]+)/g;\n let match;\n while ((match = factRegex.exec(jsonStr)) !== null) {\n const rawCat = match[1];\n const category = allowedCategories.has(rawCat) ? (rawCat as ExtractionResult[\"facts\"][number][\"category\"]) : \"fact\";\n facts.push({\n category,\n content: match[2].replace(/\\\\n/g, '\\n').replace(/\\\\\"/g, '\"'),\n confidence: parseFloat(match[3]),\n tags: [],\n });\n }\n\n // Find all complete entity objects\n const entityRegex = /\\{\\s*\"name\"\\s*:\\s*\"([^\"]+)\"\\s*,\\s*\"type\"\\s*:\\s*\"([^\"]+)\"/g;\n while ((match = entityRegex.exec(jsonStr)) !== null) {\n const rawType = match[2];\n const type = allowedEntityTypes.has(rawType) ? (rawType as ExtractionResult[\"entities\"][number][\"type\"]) : \"other\";\n entities.push({\n name: match[1],\n type,\n facts: [],\n });\n }\n } catch {\n // Ignore regex errors\n }\n\n return { facts, entities, profileUpdates: [], questions: [] };\n }\n\n /**\n * Build extraction instructions shared between local and cloud LLM.\n */\n private buildExtractionInstructions(existingEntities?: string[]): string {\n return `You are a memory extraction system. Analyze the following conversation and extract durable, reusable memories.\n\nMemory categories:\n- fact: Objective information about the world\n- preference: User likes, dislikes, or stylistic choices\n- correction: User correcting a mistake or misconception (highest priority)\n- entity: Information about a specific person, project, tool, or company\n- decision: A choice that was made with rationale\n- relationship: How two entities relate to each other (e.g., \"Alice is Bob's manager\", \"Acme Corp uses Shopify\")\n- principle: Durable rules, values, or operating beliefs (e.g., \"never use Chat Completions API\")\n- commitment: Promises, obligations, or deadlines (e.g., \"deploy by Friday\", \"call accountant Monday\")\n- moment: Emotionally significant events or milestones (e.g., \"first successful deployment of engram\")\n- skill: Capabilities the user or agent has demonstrated (e.g., \"user is proficient with Kubernetes\")${this.config.causalRuleExtractionEnabled ? `\n- rule: Causal rules discovered through experience (format: \"IF <condition> THEN <action/outcome>\", e.g., \"IF Shopify API returns 401 THEN the admin token is missing read_products scope\")` : \"\"}\n- procedure: A reusable workflow the user wants remembered the same way across sessions. Set category to \"procedure\". Use \"content\" for a short title that includes explicit trigger phrasing (e.g. \"When you deploy to production…\", \"Whenever you ship a release…\"). Add \"procedureSteps\": an array of at least two objects {\"order\": number, \"intent\": \"concrete step description\"} in execution order. Optional per-step \"toolCall\": {\"kind\": \"…\", \"signature\": \"…\"}, \"expectedOutcome\", \"optional\": true.\n- reasoning_trace: A stored solution chain / chain-of-thought the user walked through to solve a problem (e.g. \"Here's how I debugged the latency spike: first I checked…, then I…, finally I…\"). Set category to \"reasoning_trace\". Use \"content\" for a short title summarising the problem (e.g. \"How I debugged the staging latency spike\"). Add \"reasoningTrace\": {\"steps\": [{\"order\": number, \"description\": \"what happened at this step\"}, …], \"finalAnswer\": \"the conclusion or answer\", \"observedOutcome\": \"optional confirmation of how it played out\"}. Require at least two ordered steps AND a finalAnswer. Use this category only when the user explicitly narrates their reasoning — not for ordinary decisions (use \"decision\") or reusable workflows (use \"procedure\").\n\nRules:\n- Only extract genuinely NEW information worth remembering across sessions\n- Skip transient task details (file paths being edited, current errors, etc.)\n- Priority: corrections > principles${this.config.causalRuleExtractionEnabled ? \" > rules\" : \"\"} > preferences > commitments > decisions > relationships > entities > moments > skills > facts\n- Corrections (user saying \"actually, don't do X\" or \"I prefer Y\") get highest confidence\n- Each fact should be a standalone, self-contained statement\n- Lines labelled [context user] or [context assistant] are reference context only. Use them to resolve pronouns and adjacent question/answer pairs, but do not extract a memory stated only in context lines unless a normal [user] or [assistant] line confirms or completes it.\n- Entity references should use normalized names (lowercase, hyphenated: \"jane-doe\", \"acme-corp\")\n- CRITICAL: Entity names must be CANONICAL. Always use the hyphenated multi-word form: \"acme-corp\" NOT \"acmecorp\" or \"acme\". \"jane-doe\" NOT \"janedoe\" or \"jane\". If unsure, prefer the most specific full name.\n- Avoid creating entities typed as \"other\" when a more specific type fits (company, project, tool, person, place)\n- When entity facts clearly belong under a durable named heading, add them to entity.structuredSections as {key, title, facts}. Example person headings: \"Beliefs\", \"Communication Style\", \"Building / Working On\". Leave structuredSections empty when no stable heading fits.\n- Tags should be concise and reusable (e.g., \"coding-style\", \"personal\", \"tools\")\n- When a fact contains measurable, categorical, or precisely valued data, include a \"structuredAttributes\" field with key-value string pairs (e.g., {\"price\": \"29.99\", \"brand\": \"Sony\"}, {\"date\": \"2024-03-15\", \"location\": \"SF\"}, {\"chosen\": \"PostgreSQL\", \"rejected\": \"MongoDB\"}). Only for concrete values, not narrative content.\n- Set confidence using these tiers:\n * Explicit (0.95-1.0): Direct user statements — \"I prefer X\", \"my name is Y\"\n * Implied (0.70-0.94): Strong contextual inference — user consistently does X, clear from conversation flow\n * Inferred (0.40-0.69): Pattern recognition — reasonable guess from limited evidence\n * Speculative (0.00-0.39): Tentative hypothesis — weak signal, needs future confirmation. Speculative memories auto-expire after 30 days if not confirmed.\n- For commitments: include any deadline or timeframe mentioned${this.config.extractionScopeClassificationEnabled ? `\n\nScope classification:\nFor each fact, set \"scope\" to one of:\n- \"global\" — knowledge that applies across projects: core framework/library bugs, API behavior patterns, user preferences (editor, language, style), tool configurations, general coding patterns, infrastructure knowledge, technology facts not tied to one codebase\n- \"project\" — knowledge specific to one codebase: file paths, environment configs, deployment details, project-specific workarounds, team/stakeholder info tied to one project, repo-specific conventions\nWhen in doubt, prefer \"project\" — it is safer to keep knowledge scoped narrowly.\nExamples:\n \"Magento 2.4.8 has a race condition in checkout\" → \"global\"\n \"User prefers dark mode in all editors\" → \"global\"\n \"The staging server is at staging.acme.com\" → \"project\"\n \"The deploy script lives at scripts/deploy.sh\" → \"project\"\n \"PostgreSQL 15 requires the uuid-ossp extension for gen_random_uuid()\" → \"global\"\n \"The acme-store repo uses a custom Webpack config for SSR\" → \"project\"` : \"\"}\n\nEntity creation rules (STRICT):\n- Only create entities for DURABLE things: real people, companies, products, tools, ongoing projects\n- NEVER create entities for transient items: individual PRs, branches, Jira tickets, meetings, agent task IDs, log files, database tables, cron job runs, sessions\n- When you learn something about a transient item (e.g., PR #58 fixed a bug), store it as a FACT with an entityRef to the parent project — do NOT create an entity for the PR itself\n- Prefer attaching facts to broad parent entities rather than creating sub-entities. E.g., \"acme-store uses Algolia for search\" is a fact on entity \"acme-store\", NOT a new entity \"acme-store-algolia-connector\"\n- The entity list should be SHORT — think \"things that would have their own Wikipedia page\" not \"things mentioned in passing\"\n\n${existingEntities && existingEntities.length > 0 ? `\nKNOWN ENTITIES (use these exact names when referencing existing things):\n${existingEntities.join(\", \")}\n\nWhen you see something that matches a known entity, use THAT name exactly. Only create a NEW entity if nothing in this list represents it.\n` : \"\"}\nAlso extract relationships between entities mentioned in the conversation.\n- Format: {source: \"entity-name\", target: \"entity-name\", label: \"relationship description\"}\n- Max 5 relationships per extraction\n- Only include clear, durable relationships (e.g., \"works at\", \"created\", \"manages\", \"uses\")\n- Use normalized entity names (e.g., \"person-jane-doe\", \"company-acme-corp\")\n\nAlso generate 1-3 genuine questions you're curious about based on this conversation. These should be things you'd actually want answers to in future sessions — not prompts, but real curiosity.\n\nFinally, write a brief identity reflection about the AGENT who had this conversation (not about you, the extraction system). Based on what the agent said and did in the conversation:\n- What communication patterns did the agent show? (e.g., proactive vs reactive, verbose vs concise)\n- Did the agent handle the user's needs well or miss something?\n- What behavioral tendencies are visible? (e.g., cautious, creative, thorough, impatient)\n- What could the agent improve next time?\nDo NOT write about the extraction process itself. Do NOT say things like \"I extracted durable facts\" — that's about YOUR job, not the agent's behavior.`;\n }\n\n async consolidate(\n newMemories: MemoryFile[],\n existingMemories: MemoryFile[],\n currentProfile: string,\n ): Promise<ConsolidationResult> {\n const newList = newMemories\n .map(\n (m) =>\n `[${m.frontmatter.id}] (${m.frontmatter.category}) ${m.content}`,\n )\n .join(\"\\n\");\n\n const existingList = existingMemories\n .slice(-50) // Only consolidate against recent memories\n .map(\n (m) =>\n `[${m.frontmatter.id}] (${m.frontmatter.category}) ${m.content}`,\n )\n .join(\"\\n\");\n\n const cTraceId = crypto.randomUUID();\n this.emit({ kind: \"llm_start\", traceId: cTraceId, model: this.config.model, operation: \"consolidation\", input: newList });\n const cStartTime = Date.now();\n\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n try {\n const localResult = await this.consolidateWithLocalLlm(newList, existingList, currentProfile);\n if (localResult) {\n const durationMs = Date.now() - cStartTime;\n this.emit({ kind: \"llm_end\", traceId: cTraceId, model: this.config.localLlmModel, operation: \"consolidation\", durationMs });\n log.debug(`consolidation: used local LLM — ${localResult.items.length} decisions`);\n return this.sanitizeConsolidationResult(localResult);\n }\n if (!this.config.localLlmFallback) {\n log.warn(\"consolidation: local LLM failed and fallback disabled\");\n return { items: [], profileUpdates: [], entityUpdates: [] };\n }\n log.info(\"consolidation: local LLM unavailable, falling back to gateway AI\");\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(\"consolidation: local LLM error and fallback disabled:\", err);\n return { items: [], profileUpdates: [], entityUpdates: [] };\n }\n log.info(\"consolidation: local LLM error, falling back to gateway AI:\", err);\n }\n }\n\n const fallbackResult = await this.parseWithGatewayFallback(\n cTraceId,\n \"consolidation\",\n cStartTime,\n ConsolidationResultSchema,\n [\n {\n role: \"system\",\n content: `You are a memory consolidation system. Compare new memories against existing ones and decide what to do with each.\n\nActions:\n- ADD: Keep the new memory as-is (no duplicate exists)\n- MERGE: Combine with an existing memory (provide mergeWith ID and updated content)\n- UPDATE: Replace existing memory content (provide updated content)\n- INVALIDATE: Remove existing memory (it's been superseded or is wrong)\n- SKIP: This new memory is redundant (exact duplicate or subset of existing)\n\nAlso:\n- Suggest profile updates based on patterns across memories\n- Identify entity updates for entity tracking${this.config.causalRuleExtractionEnabled ? `\n- When merging or updating memories, look for IF→THEN causal patterns. If a memory describes \"X failed/succeeded because Y\" or \"doing X led to Y\", rewrite its content to make the causal rule explicit in the form \"IF <condition> THEN <action/outcome>\".` : \"\"}`,\n },\n {\n role: \"user\",\n content: `Current behavioral profile:\n${currentProfile || \"(empty)\"}\n\nExisting memories:\n${existingList || \"(none)\"}\n\nNew memories to consolidate:\n${newList}\n\nConsolidate the new memories against existing ones.`,\n },\n ],\n { temperature: 0.3, maxTokens: 4096 },\n );\n if (fallbackResult) {\n log.debug(`consolidation: ${fallbackResult.items.length} decisions via fallback`);\n return this.sanitizeConsolidationResult({\n items: fallbackResult.items,\n profileUpdates: fallbackResult.profileUpdates,\n entityUpdates: fallbackResult.entityUpdates,\n });\n }\n\n // Fall back to OpenAI API\n if (!this.client) {\n log.warn(\"consolidation skipped — no OpenAI API key and local LLM failed/disabled\");\n return { items: [], profileUpdates: [], entityUpdates: [] };\n }\n\n try {\n const instructionText = `You are a memory consolidation system. Compare new memories against existing ones and decide what to do with each.\n\nActions:\n- ADD: Keep the new memory as-is (no duplicate exists)\n- MERGE: Combine with an existing memory (provide mergeWith ID and updated content)\n- UPDATE: Replace existing memory content (provide updated content)\n- INVALIDATE: Remove existing memory (it's been superseded or is wrong)\n- SKIP: This new memory is redundant (exact duplicate or subset of existing)\n\nAlso:\n- Suggest profile updates based on patterns across memories\n- Identify entity updates for entity tracking${this.config.causalRuleExtractionEnabled ? `\n- When merging or updating memories, look for IF→THEN causal patterns. If a memory describes \"X failed/succeeded because Y\" or \"doing X led to Y\", rewrite its content to make the causal rule explicit in the form \"IF <condition> THEN <action/outcome>\".` : \"\"}\n\nCurrent behavioral profile:\n${currentProfile || \"(empty)\"}\n\nExisting memories:\n${existingList || \"(none)\"}\n\nNew memories to consolidate:\n${newList}\n\nRespond with valid JSON only, matching this schema:\n${CONSOLIDATION_RESPONSE_SCHEMA}`;\n\n const response = await this.client.chat.completions.create({\n model: this.config.model,\n messages: [\n { role: \"system\", content: instructionText },\n { role: \"user\", content: \"Consolidate the new memories against existing ones.\" },\n ],\n ...(this.config.reasoningEffort !== \"none\" ? { reasoning_effort: this.config.reasoningEffort } : {}),\n ...buildChatCompletionTokenLimit(this.config.model, 4096, {\n assumeOpenAI: this.directClientUsesOpenAiTokenSemantics(),\n }),\n });\n\n const rawContent = response.choices?.[0]?.message?.content?.trim();\n const cDurationMs = Date.now() - cStartTime;\n const cUsage = (response as any).usage;\n\n let parsed: any = null;\n if (rawContent) {\n for (const candidate of extractJsonCandidates(rawContent)) {\n try {\n parsed = JSON.parse(candidate);\n break;\n } catch {\n // keep trying candidates\n }\n }\n }\n\n this.emit({\n kind: \"llm_end\", traceId: cTraceId, model: this.config.model, operation: \"consolidation\", durationMs: cDurationMs,\n output: parsed ? JSON.stringify(parsed).slice(0, 2000) : undefined,\n tokenUsage: cUsage ? { input: cUsage.prompt_tokens, output: cUsage.completion_tokens, total: cUsage.total_tokens } : undefined,\n });\n\n if (parsed && Array.isArray(parsed.items)) {\n log.debug(\n `consolidation: ${parsed.items.length} decisions`,\n );\n return this.sanitizeConsolidationResult({\n items: parsed.items,\n profileUpdates: Array.isArray(parsed.profileUpdates) ? parsed.profileUpdates : [],\n entityUpdates: Array.isArray(parsed.entityUpdates) ? parsed.entityUpdates : [],\n });\n }\n\n log.warn(\"consolidation returned no parsed output\");\n return { items: [], profileUpdates: [], entityUpdates: [] };\n } catch (err) {\n this.emit({\n kind: \"llm_error\", traceId: cTraceId, model: this.config.model, operation: \"consolidation\",\n durationMs: Date.now() - cStartTime, error: String(err),\n });\n log.error(\"consolidation failed\", err);\n return { items: [], profileUpdates: [], entityUpdates: [] };\n }\n }\n\n /**\n * Consolidate memories using local LLM.\n */\n private async consolidateWithLocalLlm(\n newList: string,\n existingList: string,\n currentProfile: string,\n ): Promise<ConsolidationResult | null> {\n // Get dynamic context sizes\n const contextSizes = this.modelRegistry.calculateContextSizes(\n this.config.localLlmModel,\n this.config.localLlmMaxContext\n );\n log.debug(`Consolidation model context: ${contextSizes.description}`);\n\n const prompt = `You are a memory consolidation system. Compare new memories against existing ones and decide what to do with each.\n\nActions:\n- ADD: Keep the new memory as-is (no duplicate exists)\n- MERGE: Combine with an existing memory (provide mergeWith ID and updated content)\n- UPDATE: Replace existing memory content (provide updated content)\n- INVALIDATE: Remove existing memory (it's been superseded or is wrong)\n- SKIP: This new memory is redundant (exact duplicate or subset of existing)\n\nAlso:\n- Suggest profile updates based on patterns across memories\n- Identify entity updates for entity tracking${this.config.causalRuleExtractionEnabled ? `\n- When merging or updating memories, look for IF→THEN causal patterns. If a memory describes \"X failed/succeeded because Y\" or \"doing X led to Y\", rewrite its content to make the causal rule explicit in the form \"IF <condition> THEN <action/outcome>\".` : \"\"}\n\nCurrent behavioral profile:\n${currentProfile || \"(empty)\"}\n\nExisting memories:\n${existingList || \"(none)\"}\n\nNew memories to consolidate:\n${newList}\n\nRespond with valid JSON matching this schema:\n${CONSOLIDATION_RESPONSE_SCHEMA}`;\n\n const response = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: \"You are a memory consolidation system. Output valid JSON only.\" },\n { role: \"user\", content: prompt },\n ],\n {\n temperature: 0.3,\n maxTokens: contextSizes.maxOutputTokens,\n operation: \"consolidation\",\n priority: \"background\",\n },\n );\n\n if (!response?.content) {\n return null;\n }\n\n try {\n const content = response.content.trim();\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate);\n return {\n items: Array.isArray((parsed as any).items) ? (parsed as any).items : [],\n profileUpdates: Array.isArray((parsed as any).profileUpdates)\n ? (parsed as any).profileUpdates\n : [],\n entityUpdates: Array.isArray((parsed as any).entityUpdates)\n ? (parsed as any).entityUpdates\n : [],\n } as ConsolidationResult;\n } catch {\n // keep trying candidates\n }\n }\n return null;\n } catch (err) {\n log.warn(\"local LLM consolidation: failed to parse JSON response:\", err);\n return null;\n }\n }\n\n /**\n * Consolidate a bloated profile.md into a compact version.\n * The LLM merges duplicates, removes stale info, and preserves section structure.\n * Returns the consolidated markdown or null on failure.\n */\n async consolidateProfile(\n fullProfileContent: string,\n targetLines: number = 50,\n ): Promise<{ consolidatedProfile: string; removedCount: number; summary: string } | null> {\n const pTraceId = crypto.randomUUID();\n this.emit({ kind: \"llm_start\", traceId: pTraceId, model: this.config.model, operation: \"profile_consolidation\", input: fullProfileContent.slice(0, 2000) });\n const pStartTime = Date.now();\n\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n try {\n const localResult = await this.consolidateProfileWithLocalLlm(fullProfileContent, targetLines);\n if (localResult) {\n const durationMs = Date.now() - pStartTime;\n this.emit({ kind: \"llm_end\", traceId: pTraceId, model: this.config.localLlmModel, operation: \"profile_consolidation\", durationMs });\n log.debug(`profile consolidation: used local LLM — removed ${localResult.removedCount} items`);\n return localResult;\n }\n if (!this.config.localLlmFallback) {\n log.warn(\"profile consolidation: local LLM failed and fallback disabled\");\n return null;\n }\n log.info(\"profile consolidation: local LLM unavailable, falling back to gateway AI\");\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(\"profile consolidation: local LLM error and fallback disabled:\", err);\n return null;\n }\n log.info(\"profile consolidation: local LLM error, falling back to gateway AI:\", err);\n }\n }\n\n const profileFallback = await this.parseWithGatewayFallback(\n pTraceId,\n \"profile_consolidation\",\n pStartTime,\n buildProfileConsolidationResultSchema(targetLines),\n [\n {\n role: \"system\",\n content: `You are a profile consolidation system. You are given a behavioral profile (markdown) that has grown too large. Your job is to produce a CONSOLIDATED version that:\n\n1. PRESERVES all ## section headers and their structure\n2. MERGES duplicate or near-duplicate bullet points into single, clear statements\n3. REMOVES stale information that has been superseded by newer bullets\n4. REMOVES trivial or overly specific operational details that won't be useful across sessions\n5. KEEPS the most important, durable observations about the user's preferences, habits, identity, and working style\n6. Target roughly ${targetLines} lines — this is a soft target, prioritize quality over length\n7. Write in the same style as the existing profile — concise bullets, no fluff\n\nThe output should be the COMPLETE consolidated profile as valid markdown, starting with \"# Behavioral Profile\".`,\n },\n { role: \"user\", content: fullProfileContent },\n ],\n { temperature: 0.3, maxTokens: 4096 },\n );\n if (profileFallback) {\n log.debug(\n `profile consolidation: removed ${profileFallback.removedCount} items — ${profileFallback.summary} (fallback)`,\n );\n return profileFallback;\n }\n\n // Fall back to OpenAI API\n if (!this.client) {\n log.warn(\"profile consolidation skipped — no OpenAI API key and local LLM failed/disabled\");\n return null;\n }\n\n try {\n const instructionText = `You are a profile consolidation system. You are given a behavioral profile (markdown) that has grown too large. Your job is to produce a CONSOLIDATED version that:\n\n1. PRESERVES all ## section headers and their structure\n2. MERGES duplicate or near-duplicate bullet points into single, clear statements\n3. REMOVES stale information that has been superseded by newer bullets\n4. REMOVES trivial or overly specific operational details that won't be useful across sessions\n5. KEEPS the most important, durable observations about the user's preferences, habits, identity, and working style\n6. Target roughly ${targetLines} lines — this is a soft target, prioritize quality over length\n7. Write in the same style as the existing profile — concise bullets, no fluff\n\nThe output should be the COMPLETE consolidated profile as valid markdown, starting with \"# Behavioral Profile\".\n\nRespond with valid JSON matching this schema:\n{\n \"consolidatedProfile\": \"# Behavioral Profile\\\\n\\\\n... (complete markdown)\",\n \"removedCount\": 42,\n \"summary\": \"brief summary of what was consolidated\"\n}`;\n\n const response = await this.client.chat.completions.create({\n model: this.config.model,\n messages: [\n { role: \"system\", content: instructionText },\n { role: \"user\", content: fullProfileContent },\n ],\n ...(this.config.reasoningEffort !== \"none\" ? { reasoning_effort: this.config.reasoningEffort } : {}),\n ...buildChatCompletionTokenLimit(this.config.model, 4096, {\n assumeOpenAI: this.directClientUsesOpenAiTokenSemantics(),\n }),\n });\n\n const rawContent = response.choices?.[0]?.message?.content?.trim();\n const pDurationMs = Date.now() - pStartTime;\n const pUsage = (response as any).usage;\n\n let parsed: any = null;\n if (rawContent) {\n for (const candidate of extractJsonCandidates(rawContent)) {\n try {\n parsed = JSON.parse(candidate);\n break;\n } catch {\n // keep trying candidates\n }\n }\n }\n\n this.emit({\n kind: \"llm_end\", traceId: pTraceId, model: this.config.model, operation: \"profile_consolidation\", durationMs: pDurationMs,\n output: parsed ? parsed.summary : undefined,\n tokenUsage: pUsage ? { input: pUsage.prompt_tokens, output: pUsage.completion_tokens, total: pUsage.total_tokens } : undefined,\n });\n\n if (parsed && typeof parsed.consolidatedProfile === \"string\") {\n log.debug(\n `profile consolidation: removed ${parsed.removedCount ?? 0} items — ${parsed.summary ?? \"\"}`,\n );\n return {\n consolidatedProfile: parsed.consolidatedProfile,\n removedCount: Number(parsed.removedCount || 0),\n summary: String(parsed.summary || \"\"),\n };\n }\n\n log.warn(\"profile consolidation returned no parsed output\");\n return null;\n } catch (err) {\n this.emit({\n kind: \"llm_error\", traceId: pTraceId, model: this.config.model, operation: \"profile_consolidation\",\n durationMs: Date.now() - pStartTime, error: String(err),\n });\n log.error(\"profile consolidation failed\", err);\n return null;\n }\n }\n\n /**\n * Consolidate profile using local LLM.\n */\n private async consolidateProfileWithLocalLlm(\n fullProfileContent: string,\n targetLines: number = 50,\n ): Promise<{ consolidatedProfile: string; removedCount: number; summary: string } | null> {\n // Get dynamic context sizes\n const contextSizes = this.modelRegistry.calculateContextSizes(\n this.config.localLlmModel,\n this.config.localLlmMaxContext\n );\n log.debug(`Profile consolidation model context: ${contextSizes.description}`);\n\n const prompt = `You are a profile consolidation system. You are given a behavioral profile (markdown) that has grown too large. Your job is to produce a CONSOLIDATED version that:\n\n1. PRESERVES all ## section headers and their structure\n2. MERGES duplicate or near-duplicate bullet points into single, clear statements\n3. REMOVES stale information that has been superseded by newer bullets\n4. REMOVES trivial or overly specific operational details that won't be useful across sessions\n5. KEEPS the most important, durable observations about the user's preferences, habits, identity, and working style\n6. Target roughly ${targetLines} lines — this is a soft target, prioritize quality over length\n7. Write in the same style as the existing profile — concise bullets, no fluff\n\nProfile to consolidate:\n${fullProfileContent}\n\nRespond with valid JSON matching this schema:\n{\n \"consolidatedProfile\": \"# Behavioral Profile\\\\n\\\\n... (complete markdown)\",\n \"removedCount\": 42,\n \"summary\": \"brief summary of what was consolidated\"\n}`;\n\n const response = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: \"You are a profile consolidation system. Output valid JSON only.\" },\n { role: \"user\", content: prompt },\n ],\n {\n temperature: 0.3,\n maxTokens: contextSizes.maxOutputTokens,\n operation: \"profile_consolidation\",\n priority: \"background\",\n },\n );\n\n if (!response?.content) {\n return null;\n }\n\n try {\n const content = response.content.trim();\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate);\n return {\n consolidatedProfile: String((parsed as any).consolidatedProfile || \"\"),\n removedCount: Number((parsed as any).removedCount || 0),\n summary: String((parsed as any).summary || \"\"),\n };\n } catch {\n // keep trying candidates\n }\n }\n return null;\n } catch (err) {\n log.warn(\"local LLM profile consolidation: failed to parse JSON response:\", err);\n return null;\n }\n }\n\n /**\n * Consolidate IDENTITY.md reflections into a concise \"Learned Patterns\" section.\n * Returns the new content for the IDENTITY.md file (everything below the static header).\n */\n async consolidateIdentity(\n fullIdentityContent: string,\n staticHeaderEndMarker: string,\n ): Promise<{ learnedPatterns: string[]; summary: string } | null> {\n const iTraceId = crypto.randomUUID();\n this.emit({ kind: \"llm_start\", traceId: iTraceId, model: this.config.model, operation: \"identity_consolidation\", input: fullIdentityContent.slice(0, 2000) });\n const iStartTime = Date.now();\n\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n try {\n const localResult = await this.consolidateIdentityWithLocalLlm(fullIdentityContent);\n if (localResult) {\n const durationMs = Date.now() - iStartTime;\n this.emit({ kind: \"llm_end\", traceId: iTraceId, model: this.config.localLlmModel, operation: \"identity_consolidation\", durationMs });\n log.debug(`identity consolidation: used local LLM — ${localResult.learnedPatterns.length} patterns`);\n return localResult;\n }\n if (!this.config.localLlmFallback) {\n log.warn(\"identity consolidation: local LLM failed and fallback disabled\");\n return null;\n }\n log.info(\"identity consolidation: local LLM unavailable, falling back to gateway AI\");\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(\"identity consolidation: local LLM error and fallback disabled:\", err);\n return null;\n }\n log.info(\"identity consolidation: local LLM error, falling back to gateway AI:\", err);\n }\n }\n\n const identityFallback = await this.parseWithGatewayFallback(\n iTraceId,\n \"identity_consolidation\",\n iStartTime,\n IdentityConsolidationResultSchema,\n [\n {\n role: \"system\",\n content: `You are an identity consolidation system. You are given the full contents of an IDENTITY.md file that contains many individual reflection entries. Your job is to:\n\n1. Read all the reflection entries (sections starting with \"## Reflection\")\n2. Extract the most important, durable behavioral patterns and lessons learned\n3. Consolidate them into concise, standalone statements (aim for 10-25 key patterns)\n4. Remove redundancy — if multiple reflections say the same thing, merge into one clear statement\n5. Prioritize patterns that are actionable and recurring over one-off observations\n6. Write a brief summary paragraph\n\nThe goal is to reduce a bloated file to a compact, high-signal set of learned patterns while preserving all genuinely useful self-knowledge.`,\n },\n { role: \"user\", content: fullIdentityContent },\n ],\n { temperature: 0.3, maxTokens: 4096 },\n );\n if (identityFallback) {\n log.debug(\n `identity consolidation: ${identityFallback.learnedPatterns.length} patterns (fallback)`,\n );\n return identityFallback;\n }\n\n // Fall back to OpenAI API\n if (!this.client) {\n log.warn(\"identity consolidation skipped — no OpenAI API key and local LLM failed/disabled\");\n return null;\n }\n\n try {\n const instructionText = `You are an identity consolidation system. You are given the full contents of an IDENTITY.md file that contains many individual reflection entries. Your job is to:\n\n1. Read all the reflection entries (sections starting with \"## Reflection\")\n2. Extract the most important, durable behavioral patterns and lessons learned\n3. Consolidate them into concise, standalone statements (aim for 10-25 key patterns)\n4. Remove redundancy — if multiple reflections say the same thing, merge into one clear statement\n5. Prioritize patterns that are actionable and recurring over one-off observations\n6. Write a brief summary paragraph\n\nThe goal is to reduce a bloated file to a compact, high-signal set of learned patterns while preserving all genuinely useful self-knowledge.\n\nRespond with valid JSON matching this schema:\n{\n \"learnedPatterns\": [\"pattern 1\", \"pattern 2\", \"pattern 3\"],\n \"summary\": \"brief summary of consolidation\"\n}`;\n\n const response = await this.client.chat.completions.create({\n model: this.config.model,\n messages: [\n { role: \"system\", content: instructionText },\n { role: \"user\", content: fullIdentityContent },\n ],\n ...(this.config.reasoningEffort !== \"none\" ? { reasoning_effort: this.config.reasoningEffort } : {}),\n ...buildChatCompletionTokenLimit(this.config.model, 4096, {\n assumeOpenAI: this.directClientUsesOpenAiTokenSemantics(),\n }),\n });\n\n const rawContent = response.choices?.[0]?.message?.content?.trim();\n const iDurationMs = Date.now() - iStartTime;\n const iUsage = (response as any).usage;\n\n let parsed: any = null;\n if (rawContent) {\n for (const candidate of extractJsonCandidates(rawContent)) {\n try {\n parsed = JSON.parse(candidate);\n break;\n } catch {\n // keep trying candidates\n }\n }\n }\n\n this.emit({\n kind: \"llm_end\", traceId: iTraceId, model: this.config.model, operation: \"identity_consolidation\", durationMs: iDurationMs,\n output: parsed ? parsed.summary : undefined,\n tokenUsage: iUsage ? { input: iUsage.prompt_tokens, output: iUsage.completion_tokens, total: iUsage.total_tokens } : undefined,\n });\n\n if (parsed && Array.isArray(parsed.learnedPatterns)) {\n const learnedPatterns = parsed.learnedPatterns\n .filter((pattern: unknown) => typeof pattern === \"string\")\n .map((pattern: string) => pattern.trim())\n .filter((pattern: string) => pattern.length > 0);\n log.debug(\n `identity consolidation: ${learnedPatterns.length} patterns`,\n );\n return {\n learnedPatterns,\n summary: String(parsed.summary || \"\"),\n };\n }\n\n log.warn(\"identity consolidation returned no parsed output\");\n return null;\n } catch (err) {\n this.emit({\n kind: \"llm_error\", traceId: iTraceId, model: this.config.model, operation: \"identity_consolidation\",\n durationMs: Date.now() - iStartTime, error: String(err),\n });\n log.error(\"identity consolidation failed\", err);\n return null;\n }\n }\n\n /**\n * Consolidate identity using local LLM.\n */\n private async consolidateIdentityWithLocalLlm(\n fullIdentityContent: string,\n ): Promise<{ learnedPatterns: string[]; summary: string } | null> {\n // Get dynamic context sizes\n const contextSizes = this.modelRegistry.calculateContextSizes(\n this.config.localLlmModel,\n this.config.localLlmMaxContext\n );\n log.debug(`Identity consolidation model context: ${contextSizes.description}`);\n\n const prompt = `You are an identity consolidation system. You are given the full contents of an IDENTITY.md file that contains many individual reflection entries. Your job is to:\n\n1. Read all the reflection entries (sections starting with \"## Reflection\")\n2. Extract the most important, durable behavioral patterns and lessons learned\n3. Consolidate them into concise, standalone statements (aim for 10-25 key patterns)\n4. Remove redundancy — if multiple reflections say the same thing, merge into one clear statement\n5. Prioritize patterns that are actionable and recurring over one-off observations\n6. Write a brief summary paragraph\n\nThe goal is to reduce a bloated file to a compact, high-signal set of learned patterns while preserving all genuinely useful self-knowledge.\n\nIDENTITY.md content:\n${fullIdentityContent}\n\nRespond with valid JSON matching this schema:\n{\n \"learnedPatterns\": [\"pattern 1\", \"pattern 2\", \"pattern 3\"],\n \"summary\": \"brief summary of consolidation\"\n}`;\n\n const response = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: \"You are an identity consolidation system. Output valid JSON only.\" },\n { role: \"user\", content: prompt },\n ],\n {\n temperature: 0.3,\n maxTokens: contextSizes.maxOutputTokens,\n operation: \"identity_consolidation\",\n priority: \"background\",\n },\n );\n\n if (!response?.content) {\n return null;\n }\n\n try {\n const content = response.content.trim();\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate);\n return {\n learnedPatterns: Array.isArray((parsed as any).learnedPatterns)\n ? (parsed as any).learnedPatterns\n : [],\n summary: String((parsed as any).summary || \"\"),\n };\n } catch {\n // keep trying candidates\n }\n }\n return null;\n } catch (err) {\n log.warn(\"local LLM identity consolidation: failed to parse JSON response:\", err);\n return null;\n }\n }\n\n /**\n * Verify if two memories contradict each other using LLM.\n * Called when QMD finds semantically similar memories (Phase 2B).\n */\n async verifyContradiction(\n newMemory: { content: string; category: string },\n existingMemory: { id: string; content: string; category: string; created: string },\n ): Promise<ContradictionVerificationResult | null> {\n const input = `Memory 1 (existing, created ${existingMemory.created}):\nCategory: ${existingMemory.category}\nContent: ${existingMemory.content}\n\nMemory 2 (new):\nCategory: ${newMemory.category}\nContent: ${newMemory.content}`;\n\n try {\n const instructionText = `You are a contradiction detection system. Analyze whether two memories contradict each other.\n\nIMPORTANT: Not all similar memories are contradictions!\n- \"User likes TypeScript\" and \"User likes Python\" are NOT contradictions (preferences can coexist)\n- \"User prefers dark mode\" and \"User prefers light mode\" ARE contradictions (mutually exclusive)\n- \"User's email is a@b.com\" and \"User's email is c@d.com\" ARE contradictions (only one email)\n- \"User works at Acme\" and \"User used to work at Acme\" might be a contradiction (temporal change)\n\nOnly mark as contradiction if the two statements CANNOT both be true at the same time.\n\nIf they ARE contradictory, determine which represents the more recent/current state based on:\n- Explicit time references (\"now\", \"currently\", \"used to\", \"no longer\")\n- The fact that newer corrections often start with \"actually\" or \"correction\"\n- Context clues about change over time\n\nRespond with valid JSON matching this schema:\n{\n \"isContradiction\": true,\n \"confidence\": 0.95,\n \"reasoning\": \"why they contradict or don't\",\n \"whichIsNewer\": \"first\"\n}`;\n\n if (this.shouldUseLocalLlm) {\n try {\n const localResponse = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: instructionText },\n { role: \"user\", content: input },\n ],\n {\n temperature: 0.3,\n maxTokens: 2048,\n operation: \"contradiction_verification\",\n priority: \"background\",\n },\n );\n const normalized = this.normalizeContradictionVerificationResult(\n this.parseJsonObject(localResponse?.content),\n );\n if (normalized) {\n log.debug(\n `contradiction check via local LLM: ${normalized.isContradiction ? \"YES\" : \"NO\"} (confidence: ${normalized.confidence})`,\n );\n return normalized;\n }\n if (!this.config.localLlmFallback) {\n log.warn(\"contradiction verification skipped — local LLM returned invalid JSON and cloud fallback is disabled\");\n return null;\n }\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(`contradiction verification skipped — local LLM failed and cloud fallback is disabled: ${err}`);\n return null;\n }\n }\n }\n\n if (!this.shouldUseDirectClient) {\n const fallbackResponse = await this.fallbackLlm.chatCompletion(\n [\n { role: \"system\", content: instructionText },\n { role: \"user\", content: input },\n ],\n this.withGatewayAgent({ temperature: 0.3, maxTokens: 2048 }),\n );\n const normalized = this.normalizeContradictionVerificationResult(\n this.parseJsonObject(fallbackResponse?.content),\n );\n if (normalized) {\n log.debug(\n `contradiction check via fallback: ${normalized.isContradiction ? \"YES\" : \"NO\"} (confidence: ${normalized.confidence})`,\n );\n return normalized;\n }\n log.warn(\"contradiction verification skipped — no OpenAI API key and fallback unavailable\");\n return null;\n }\n\n const response = await this.client!.chat.completions.create({\n model: this.config.model,\n messages: [\n { role: \"system\", content: instructionText },\n { role: \"user\", content: input },\n ],\n ...buildChatCompletionTokenLimit(this.config.model, 2048, {\n assumeOpenAI: this.directClientUsesOpenAiTokenSemantics(),\n }),\n });\n\n const normalized = this.normalizeContradictionVerificationResult(\n this.parseJsonObject(response.choices?.[0]?.message?.content),\n );\n if (normalized) {\n log.debug(\n `contradiction check: ${normalized.isContradiction ? \"YES\" : \"NO\"} (confidence: ${normalized.confidence})`,\n );\n return normalized;\n }\n\n return null;\n } catch (err) {\n log.error(\"contradiction verification failed\", err);\n return null;\n }\n }\n\n /**\n * Suggest links between a new memory and existing memories (Phase 3A).\n * Called during extraction to build the knowledge graph.\n */\n async suggestLinks(\n newMemory: { content: string; category: string },\n candidateMemories: Array<{ id: string; content: string; category: string }>,\n ): Promise<SuggestedLinks | null> {\n if (candidateMemories.length === 0) {\n return { links: [] };\n }\n\n const candidateList = candidateMemories\n .map((m, i) => `[${i + 1}] ID: ${m.id}\\nCategory: ${m.category}\\nContent: ${m.content}`)\n .join(\"\\n\\n\");\n\n const input = `New memory:\nCategory: ${newMemory.category}\nContent: ${newMemory.content}\n\nCandidate memories to link to:\n${candidateList}`;\n\n try {\n const instructionText = `You are a memory linking system. Analyze the new memory and suggest relationships to existing memories.\n\nLink types:\n- follows: This memory is a continuation or next step (e.g., decision follows discussion)\n- references: This memory mentions or refers to the other (e.g., fact references entity)\n- contradicts: This memory conflicts with the other (use sparingly, only for true contradictions)\n- supports: This memory provides evidence or reinforcement (e.g., example supports principle)\n- related: General topical relationship\n\nRules:\n- Only suggest links with strength > 0.5\n- Quality over quantity — 0-3 links is typical\n- Prefer specific link types over generic \"related\"\n- Consider entity references, topics, and causal relationships\n\nRespond with valid JSON matching this schema:\n{\n \"links\": [{\"targetId\": \"memory-id\", \"linkType\": \"follows|references|contradicts|supports|related\", \"strength\": 0.8, \"reason\": \"why\"}]\n}`;\n\n if (this.shouldUseLocalLlm) {\n try {\n const localResponse = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: instructionText },\n { role: \"user\", content: input },\n ],\n {\n temperature: 0.3,\n maxTokens: 2048,\n operation: \"link_suggestion\",\n priority: \"background\",\n },\n );\n const normalized = this.normalizeSuggestedLinksResult(this.parseJsonObject(localResponse?.content));\n if (normalized) {\n log.debug(`suggested ${normalized.links.length} links via local LLM`);\n return normalized;\n }\n if (!this.config.localLlmFallback) {\n log.warn(\"link suggestion skipped — local LLM returned invalid JSON and cloud fallback is disabled\");\n return null;\n }\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(`link suggestion skipped — local LLM failed and cloud fallback is disabled: ${err}`);\n return null;\n }\n }\n }\n\n if (!this.shouldUseDirectClient) {\n const fallbackResponse = await this.fallbackLlm.chatCompletion(\n [\n { role: \"system\", content: instructionText },\n { role: \"user\", content: input },\n ],\n this.withGatewayAgent({ temperature: 0.3, maxTokens: 2048 }),\n );\n const normalized = this.normalizeSuggestedLinksResult(this.parseJsonObject(fallbackResponse?.content));\n if (normalized) {\n log.debug(`suggested ${normalized.links.length} links via fallback`);\n return normalized;\n }\n log.warn(\"link suggestion skipped — no OpenAI API key and fallback unavailable\");\n return null;\n }\n\n const response = await this.client!.chat.completions.create({\n model: this.config.model,\n messages: [\n { role: \"system\", content: instructionText },\n { role: \"user\", content: input },\n ],\n ...buildChatCompletionTokenLimit(this.config.model, 2048, {\n assumeOpenAI: this.directClientUsesOpenAiTokenSemantics(),\n }),\n });\n\n const normalized = this.normalizeSuggestedLinksResult(\n this.parseJsonObject(response.choices?.[0]?.message?.content),\n );\n if (normalized) {\n log.debug(`suggested ${normalized.links.length} links`);\n return normalized;\n }\n\n return null;\n } catch (err) {\n log.error(\"link suggestion failed\", err);\n return null;\n }\n }\n\n async generateDaySummary(memories: string | MemoryFile[]): Promise<DaySummaryResultShape | null> {\n if (!this.config.daySummaryEnabled) {\n log.warn(\"day summary skipped — disabled by config\");\n return null;\n }\n\n const memoryContext = formatDaySummaryMemories(memories);\n if (memoryContext.length === 0) return null;\n\n const instructionText = await loadDaySummaryPrompt();\n\n // Append extension footer when extensions are active (#382)\n let extensionsFooter = \"\";\n try {\n extensionsFooter = await buildExtensionsFooterForSummary(this.config);\n } catch {\n // Non-fatal: skip extension footer if discovery fails\n }\n\n const userPrompt = `Generate an end-of-day summary from this Remnic memory context:\n\n${memoryContext}${extensionsFooter.length > 0 ? `\\n\\n${extensionsFooter}` : \"\"}`;\n const traceId = crypto.randomUUID();\n const startedAt = Date.now();\n this.emit({ kind: \"llm_start\", traceId, model: this.config.model, operation: \"day_summary\", input: memoryContext.slice(0, 4000) });\n\n if (this.shouldUseLocalLlm) {\n try {\n const localResponse = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: `${instructionText}\n\nReturn valid JSON only.` },\n { role: \"user\", content: userPrompt },\n ],\n {\n temperature: 0.2,\n maxTokens: 2048,\n operation: \"day_summary\",\n priority: \"background\",\n },\n );\n const normalized = this.normalizeDaySummaryResult(this.parseJsonObject(localResponse?.content));\n if (normalized) {\n this.emit({ kind: \"llm_end\", traceId, model: this.config.localLlmModel, operation: \"day_summary\", durationMs: Date.now() - startedAt, output: JSON.stringify(normalized).slice(0, 2000) });\n log.debug(`generated day summary via local LLM (${normalized.bullets.length} bullets)`);\n return normalized;\n }\n if (!this.config.localLlmFallback) {\n this.emit({ kind: \"llm_error\", traceId, model: this.config.localLlmModel, operation: \"day_summary\", durationMs: Date.now() - startedAt, error: \"local LLM returned invalid JSON and fallback disabled\" });\n log.warn(\"day summary skipped — local LLM returned invalid JSON and fallback disabled\");\n return null;\n }\n } catch (err) {\n if (!this.config.localLlmFallback) {\n this.emit({ kind: \"llm_error\", traceId, model: this.config.localLlmModel, operation: \"day_summary\", durationMs: Date.now() - startedAt, error: String(err) });\n log.warn(`day summary skipped — local LLM failed and fallback disabled: ${err}`);\n return null;\n }\n }\n }\n\n const fallbackResult = await this.parseWithGatewayFallback(\n traceId,\n \"day_summary\",\n startedAt,\n DaySummaryResultSchema,\n [\n { role: \"system\", content: `${instructionText}\n\nReturn valid JSON only.` },\n { role: \"user\", content: userPrompt },\n ],\n { temperature: 0.2, maxTokens: 2048 },\n );\n if (fallbackResult) {\n const normalized = this.normalizeDaySummaryResult(fallbackResult);\n if (normalized) {\n log.debug(`generated day summary via fallback (${normalized.bullets.length} bullets)`);\n return normalized;\n }\n }\n\n // Direct Responses API fallback (AGENTS.md-compliant: never Chat Completions)\n if (this.shouldUseDirectClient) {\n try {\n const response = await (this.client as any).responses.create({\n model: this.config.model,\n instructions: `${instructionText}\\n\\nReturn valid JSON only.`,\n input: userPrompt,\n max_output_tokens: 2048,\n });\n const rawText = typeof response.output_text === \"string\" ? response.output_text : JSON.stringify(response.output_text ?? \"\");\n const normalized = this.normalizeDaySummaryResult(this.parseJsonObject(rawText));\n if (normalized) {\n this.emit({ kind: \"llm_end\", traceId, model: this.config.model, operation: \"day_summary\", durationMs: Date.now() - startedAt, output: JSON.stringify(normalized).slice(0, 2000) });\n log.debug(`generated day summary via Responses API (${normalized.bullets.length} bullets)`);\n return normalized;\n }\n this.emit({ kind: \"llm_error\", traceId, model: this.config.model, operation: \"day_summary\", durationMs: Date.now() - startedAt, error: \"Responses API returned unparseable output\" });\n } catch (err) {\n this.emit({ kind: \"llm_error\", traceId, model: this.config.model, operation: \"day_summary\", durationMs: Date.now() - startedAt, error: `Responses API failed: ${err}` });\n }\n }\n\n this.emit({ kind: \"llm_error\", traceId, model: this.config.model, operation: \"day_summary\", durationMs: Date.now() - startedAt, error: \"all generation paths exhausted (local LLM + gateway + Responses API)\" });\n log.warn(\"day summary skipped — all generation paths exhausted\");\n return null;\n }\n\n\n /**\n * Summarize a batch of old memories into a compact summary (Phase 4A).\n */\n async summarizeMemories(\n memories: Array<{ id: string; content: string; category: string; created: string }>,\n ): Promise<MemorySummaryResult | null> {\n if (memories.length === 0) return null;\n\n const memoryList = memories\n .map((m) => `[${m.id}] (${m.category}, ${m.created.slice(0, 10)})\\n${m.content}`)\n .join(\"\\n\\n\");\n\n try {\n const instructionText = `You are a memory summarization system. You are given a batch of old memories that need to be compressed into a summary.\n\nYour task:\n1. Write a concise summary paragraph (2-4 sentences) capturing the essence of these memories\n2. Extract the 5-10 most important facts that should be preserved\n3. List the key entities mentioned\n\nGuidelines:\n- Preserve specific, actionable information\n- Merge redundant details into single statements\n- Focus on durable insights, not transient details\n- Maintain any preferences, decisions, or corrections as key facts\n\nRespond with valid JSON matching this schema:\n{\n \"summaryText\": \"concise summary paragraph\",\n \"keyFacts\": [\"fact 1\", \"fact 2\"],\n \"keyEntities\": [\"entity-1\", \"entity-2\"]\n}`;\n\n if (this.shouldUseLocalLlm) {\n try {\n const localResponse = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: instructionText },\n { role: \"user\", content: `Summarize these ${memories.length} memories:\\n\\n${memoryList}` },\n ],\n {\n temperature: 0.3,\n maxTokens: 4096,\n operation: \"memory_summarization\",\n priority: \"background\",\n },\n );\n const normalized = this.normalizeMemorySummaryResult(this.parseJsonObject(localResponse?.content));\n if (normalized) {\n log.debug(\n `summarized ${memories.length} memories into ${normalized.keyFacts.length} key facts via local LLM`,\n );\n return normalized;\n }\n if (!this.config.localLlmFallback) {\n log.warn(\"summarization skipped — local LLM returned invalid JSON and cloud fallback is disabled\");\n return null;\n }\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(`summarization skipped — local LLM failed and cloud fallback is disabled: ${err}`);\n return null;\n }\n }\n }\n\n if (!this.shouldUseDirectClient) {\n const fallbackResponse = await this.fallbackLlm.chatCompletion(\n [\n { role: \"system\", content: instructionText },\n { role: \"user\", content: `Summarize these ${memories.length} memories:\\n\\n${memoryList}` },\n ],\n this.withGatewayAgent({ temperature: 0.3, maxTokens: 4096 }),\n );\n const normalized = this.normalizeMemorySummaryResult(this.parseJsonObject(fallbackResponse?.content));\n if (normalized) {\n log.debug(`summarized ${memories.length} memories into ${normalized.keyFacts.length} key facts via fallback`);\n return normalized;\n }\n log.warn(\"summarization skipped — no OpenAI API key and fallback unavailable\");\n return null;\n }\n\n const response = await this.client!.chat.completions.create({\n model: this.config.model,\n messages: [\n { role: \"system\", content: instructionText },\n { role: \"user\", content: `Summarize these ${memories.length} memories:\\n\\n${memoryList}` },\n ],\n ...buildChatCompletionTokenLimit(this.config.model, 4096, {\n assumeOpenAI: this.directClientUsesOpenAiTokenSemantics(),\n }),\n });\n\n const normalized = this.normalizeMemorySummaryResult(\n this.parseJsonObject(response.choices?.[0]?.message?.content),\n );\n if (normalized) {\n log.debug(`summarized ${memories.length} memories into ${normalized.keyFacts.length} key facts`);\n return normalized;\n }\n\n return null;\n } catch (err) {\n log.error(\"memory summarization failed\", err);\n return null;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,YAAY;AA4CnB,IAAM,2BAA2B;AACjC,IAAM,gCAAgC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AActC,SAAS,cAAc,OAAkD;AACvE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,kBAAkB,UAAkD;AAC3E,QAAM,WAAW,OAAO,SAAS,SAAS,QAAQ,IAC9C,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,SAAS,QAAQ,CAAC,IAC1C;AACJ,SAAO;AAAA,IACL,UAAU,OAAO,SAAS,aAAa,WAAW,SAAS,SAAS,KAAK,IAAI;AAAA,IAC7E,SAAS,OAAO,SAAS,YAAY,WAAW,SAAS,QAAQ,KAAK,IAAI;AAAA,IAC1E;AAAA,EACF;AACF;AAEA,SAAS,iBAAiB,MAAiE;AACzF,SAAO,GAAG,KAAK,QAAQ,IAAI,KAAK,QAAQ,KAAK,EAAE,YAAY,CAAC;AAC9D;AAEA,SAAS,mBAAmB,QAA8D;AACxF,SAAO,GAAG,OAAO,IAAI,IAAI,OAAO,KAAK,KAAK,EAAE,YAAY,CAAC;AAC3D;AAEA,SAAS,yBACP,cACQ;AACR,SAAO,GAAG,aAAa,OAAO,KAAK,EAAE,YAAY,CAAC,KAAK,aAAa,OAAO,KAAK,EAAE,YAAY,CAAC,IAAI,aAAa,MAAM,KAAK,EAAE,YAAY,CAAC;AAC5I;AAEA,SAAS,0BAA0B,QAAwB;AACzD,SAAO,OAAO,KAAK,EAAE,YAAY;AACnC;AAEO,IAAM,mBAA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AG,SAAS,OAAO;AAAA,MAC9D;AACA,UAAI,YAAY;AACd,YAAI,MAAM,cAAc,SAAS,MAAM,kBAAkB,WAAW,SAAS,MAAM,YAAY;AAC/F,eAAO;AAAA,MACT;AAEA,aAAO;AAAA,IACT,SAAS,KAAK;AACZ,UAAI,MAAM,+BAA+B,GAAG;AAC5C,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["normalized"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/migrate/from-engram.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport {\n chmod,\n copyFile,\n lstat,\n mkdir,\n open,\n readFile,\n readdir,\n rm,\n stat,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { resolveHomeDir } from \"../runtime/env.js\";\nimport { launchProcessSync } from \"../runtime/child-process.js\";\n\nexport interface MigrationResult {\n status: \"fresh-install\" | \"already-migrated\" | \"migrated\";\n copied: string[];\n tokensRegenerated: number;\n servicesReinstalled: string[];\n rollbackCommand: string;\n}\n\ninterface RollbackManifestEntry {\n targetPath: string;\n backupPath?: string;\n createdByMigration?: boolean;\n contentHash?: string;\n}\n\ninterface RollbackManifest {\n version: 1;\n createdAt: string;\n entries: RollbackManifestEntry[];\n}\n\ninterface ValidatedRollbackManifestEntry extends RollbackManifestEntry {\n targetPath: string;\n backupPath?: string;\n contentHash?: string;\n}\n\nexport interface MigrationOptions {\n connectorConfigPaths?: string[];\n cwd?: string;\n execCommand?: (command: string, args: string[]) => void;\n homeDir?: string;\n logger?: (message: string) => void;\n platform?: NodeJS.Platform;\n quiet?: boolean;\n}\n\nexport interface RollbackResult {\n removed: string[];\n restored: string[];\n}\n\ninterface TokenEntry {\n connector: string;\n createdAt: string;\n token: string;\n}\n\ntype PersistRollbackManifest = () => Promise<void>;\n\nconst MARKER_FILE = \".migrated-from-engram\";\nconst LOCK_FILE = \".migration.lock\";\nconst ROLLBACK_MANIFEST = \".rollback.json\";\nconst BACKUP_DIR = \".backup\";\nconst LOCK_RETRY_MS = 100;\nconst LOCK_TIMEOUT_MS = 5_000;\nconst TOKEN_STORE_MODE = 0o600;\n\nfunction resolvePlatform(options?: MigrationOptions): NodeJS.Platform {\n return options?.platform ?? process.platform;\n}\n\nfunction resolveMigrationHome(options?: MigrationOptions): string {\n return options?.homeDir ?? resolveHomeDir();\n}\n\nfunction resolveLogger(options?: MigrationOptions): (message: string) => void {\n const sink = options?.logger ?? ((message: string) => console.log(message));\n return (message: string) => {\n if (!options?.quiet) sink(`[remnic] ${message}`);\n };\n}\n\nfunction resolveExec(options?: MigrationOptions): (command: string, args: string[]) => void {\n return options?.execCommand ?? ((command: string, args: string[]) => {\n const result = launchProcessSync(command, args, { stdio: \"ignore\" });\n if (result.error) {\n throw result.error;\n }\n if (result.status !== 0) {\n const reason = result.status === null\n ? `signal ${result.signal ?? \"unknown\"}`\n : `exit code ${result.status}`;\n throw new Error(`migration command failed: ${command} ${args.join(\" \")} (${reason})`);\n }\n });\n}\n\nfunction remnicRoot(homeDir: string): string {\n return path.join(homeDir, \".remnic\");\n}\n\nfunction legacyRoot(homeDir: string): string {\n return path.join(homeDir, \".engram\");\n}\n\nfunction legacyConfigPath(homeDir: string): string {\n return path.join(homeDir, \".config\", \"engram\", \"config.json\");\n}\n\nfunction remnicConfigPath(homeDir: string): string {\n return path.join(homeDir, \".config\", \"remnic\", \"config.json\");\n}\n\nfunction markerPath(homeDir: string): string {\n return path.join(remnicRoot(homeDir), MARKER_FILE);\n}\n\nfunction lockPath(homeDir: string): string {\n return path.join(remnicRoot(homeDir), LOCK_FILE);\n}\n\nfunction rollbackManifestPath(homeDir: string): string {\n return path.join(remnicRoot(homeDir), ROLLBACK_MANIFEST);\n}\n\nfunction backupRoot(homeDir: string): string {\n return path.join(remnicRoot(homeDir), BACKUP_DIR);\n}\n\nfunction defaultRollbackCommand(): string {\n return \"remnic migrate --rollback\";\n}\n\nfunction resolveMigrationCwd(options?: MigrationOptions): string {\n return path.resolve(options?.cwd ?? process.cwd());\n}\n\nfunction resolveConnectorConfigPath(candidate: string, cwd: string): string {\n return path.isAbsolute(candidate) ? path.resolve(candidate) : path.resolve(cwd, candidate);\n}\n\nasync function ensureParent(filePath: string): Promise<void> {\n await mkdir(path.dirname(filePath), { recursive: true });\n}\n\nasync function secureTokenFilePermissions(filePath: string): Promise<void> {\n await chmod(filePath, TOKEN_STORE_MODE);\n}\n\nasync function writeOwnerOnlyFile(filePath: string, content: string): Promise<void> {\n await writeFile(filePath, content, { encoding: \"utf8\", mode: TOKEN_STORE_MODE });\n await chmod(filePath, TOKEN_STORE_MODE);\n}\n\nasync function fileContentHash(filePath: string): Promise<string> {\n return createHash(\"sha256\").update(await readFile(filePath)).digest(\"hex\");\n}\n\nasync function writeTokenStoreFile(filePath: string, content: string): Promise<void> {\n await writeOwnerOnlyFile(filePath, content);\n}\n\nfunction isRemnicTokenStorePath(filePath: string, homeDir: string): boolean {\n return path.resolve(filePath) === path.resolve(path.join(remnicRoot(homeDir), \"tokens.json\"));\n}\n\nasync function pathExistsNoFollow(filePath: string): Promise<boolean> {\n try {\n await lstat(filePath);\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n throw error;\n }\n}\n\nasync function assertExistingRegularFileNoFollow(filePath: string, label: string): Promise<void> {\n const fileStat = await lstat(filePath);\n if (fileStat.isSymbolicLink()) {\n throw new Error(`${label} must not be a symlink: ${filePath}`);\n }\n if (!fileStat.isFile()) {\n throw new Error(`${label} must be a regular file: ${filePath}`);\n }\n}\n\nasync function isExistingRegularFileNoFollow(filePath: string): Promise<boolean> {\n try {\n const fileStat = await lstat(filePath);\n return fileStat.isFile() && !fileStat.isSymbolicLink();\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n throw error;\n }\n}\n\nasync function copyTreeMissing(\n source: string,\n destination: string,\n copied: string[],\n manifest: RollbackManifest,\n persistManifest?: PersistRollbackManifest,\n isRoot = true,\n): Promise<void> {\n if (!existsSync(source)) return;\n const sourceStat = await lstat(source);\n if (sourceStat.isSymbolicLink()) {\n if (isRoot) {\n throw new Error(`legacy migration root must not be a symlink: ${source}`);\n }\n return;\n }\n if (sourceStat.isDirectory()) {\n await mkdir(destination, { recursive: true });\n const entries = await readdir(source, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.name === MARKER_FILE || entry.name === LOCK_FILE || entry.name === ROLLBACK_MANIFEST) {\n continue;\n }\n await copyTreeMissing(\n path.join(source, entry.name),\n path.join(destination, entry.name),\n copied,\n manifest,\n persistManifest,\n false,\n );\n }\n return;\n }\n\n if (await pathExistsNoFollow(destination)) return;\n await ensureParent(destination);\n await copyFile(source, destination);\n await recordCreatedPath(destination, manifest, persistManifest);\n copied.push(destination);\n}\n\nfunction rewriteRemnicText(content: string): string {\n return content\n .replaceAll(\".engram/\", \".remnic/\")\n .replaceAll(\".engram\\\\\", \".remnic\\\\\")\n .replaceAll(\"ENGRAM_\", \"REMNIC_\")\n .replaceAll(\"{{ENGRAM_TOKEN}}\", \"{{REMNIC_TOKEN}}\")\n .replaceAll(\"${ENGRAM_AUTH_TOKEN}\", \"${REMNIC_AUTH_TOKEN}\")\n .replaceAll(\"ai.engram.daemon\", \"ai.remnic.daemon\")\n .replaceAll(\"engram.service\", \"remnic.service\");\n}\n\nfunction rewriteTokenValue(token: string): string {\n return token.startsWith(\"engram_\") ? `remnic_${token.slice(\"engram_\".length)}` : token;\n}\n\nfunction parseTokenEntries(raw: unknown): TokenEntry[] {\n if (typeof raw !== \"object\" || raw === null) return [];\n\n if (Array.isArray((raw as { tokens?: unknown }).tokens)) {\n return ((raw as { tokens: unknown[] }).tokens)\n .filter((entry): entry is TokenEntry => {\n if (typeof entry !== \"object\" || entry === null) return false;\n const candidate = entry as Partial<TokenEntry>;\n return typeof candidate.connector === \"string\" &&\n candidate.connector.length > 0 &&\n typeof candidate.token === \"string\" &&\n candidate.token.length > 0 &&\n typeof candidate.createdAt === \"string\" &&\n candidate.createdAt.length > 0;\n })\n .map((entry) => ({ ...entry }));\n }\n\n return Object.entries(raw)\n .filter(([key, value]) => key !== \"tokens\" && typeof value === \"string\" && value.length > 0)\n .map(([connector, token]) => ({\n connector,\n createdAt: new Date().toISOString(),\n token,\n }));\n}\n\nfunction isPlainJsonObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseRollbackManifestEntry(raw: unknown, index: number): RollbackManifestEntry {\n if (!isPlainJsonObject(raw)) {\n throw new Error(`rollback manifest entry ${index} must be an object`);\n }\n if (typeof raw.targetPath !== \"string\" || raw.targetPath.length === 0 || !path.isAbsolute(raw.targetPath)) {\n throw new Error(`rollback manifest entry ${index} has an invalid targetPath`);\n }\n if (raw.backupPath !== undefined && (typeof raw.backupPath !== \"string\" || raw.backupPath.length === 0 || !path.isAbsolute(raw.backupPath))) {\n throw new Error(`rollback manifest entry ${index} has an invalid backupPath`);\n }\n if (raw.createdByMigration !== undefined && typeof raw.createdByMigration !== \"boolean\") {\n throw new Error(`rollback manifest entry ${index} has an invalid createdByMigration flag`);\n }\n if (raw.contentHash !== undefined && (typeof raw.contentHash !== \"string\" || !/^[a-f0-9]{64}$/u.test(raw.contentHash))) {\n throw new Error(`rollback manifest entry ${index} has an invalid contentHash`);\n }\n return {\n targetPath: raw.targetPath,\n ...(raw.backupPath === undefined ? {} : { backupPath: raw.backupPath }),\n ...(raw.createdByMigration === undefined ? {} : { createdByMigration: raw.createdByMigration }),\n ...(raw.contentHash === undefined ? {} : { contentHash: raw.contentHash }),\n };\n}\n\nfunction parseRollbackManifest(raw: unknown, manifestPath: string): RollbackManifest {\n if (!isPlainJsonObject(raw)) {\n throw new Error(`rollback manifest must be an object: ${manifestPath}`);\n }\n if (raw.version !== 1) {\n throw new Error(`rollback manifest has unsupported version: ${manifestPath}`);\n }\n if (typeof raw.createdAt !== \"string\") {\n throw new Error(`rollback manifest has an invalid createdAt: ${manifestPath}`);\n }\n if (!Array.isArray(raw.entries)) {\n throw new Error(`rollback manifest entries must be an array: ${manifestPath}`);\n }\n return {\n version: 1,\n createdAt: raw.createdAt,\n entries: raw.entries.map(parseRollbackManifestEntry),\n };\n}\n\nfunction isPathInside(parentPath: string, candidatePath: string): boolean {\n const relative = path.relative(path.resolve(parentPath), path.resolve(candidatePath));\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\nfunction isPathDescendant(parentPath: string, candidatePath: string): boolean {\n const relative = path.relative(path.resolve(parentPath), path.resolve(candidatePath));\n return relative !== \"\" && !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n}\n\nfunction hasConnectorConfigShape(targetPath: string, homeDir: string): boolean {\n const relative = path.relative(path.resolve(homeDir), path.resolve(targetPath));\n if (relative === \".claude.json\" || relative === path.join(\".claude\", \".mcp.json\")) {\n return true;\n }\n\n return hasRepoConnectorConfigShape(relative);\n}\n\nfunction hasRepoConnectorConfigShape(relativePath: string): boolean {\n const parts = relativePath.split(path.sep);\n const last = parts.at(-1);\n const packageName = parts.at(-2);\n const packagesDir = parts.at(-3);\n return last === \".mcp.json\" &&\n packagesDir === \"packages\" &&\n (packageName === \"plugin-claude-code\" || packageName === \"plugin-codex\");\n}\n\nfunction connectorBackupPathForTarget(targetPath: string, homeDir: string): string {\n const digest = createHash(\"sha256\").update(targetPath).digest(\"hex\").slice(0, 12);\n return path.join(backupRoot(homeDir), \"mcp\", `${digest}.json`);\n}\n\nfunction isRollbackTargetAllowed(\n entry: RollbackManifestEntry,\n targetPath: string,\n homeDir: string,\n options?: MigrationOptions,\n): boolean {\n const resolvedTarget = path.resolve(targetPath);\n if (isPathDescendant(remnicRoot(homeDir), resolvedTarget)) {\n if (entry.createdByMigration && !entry.backupPath) return true;\n return Boolean(entry.backupPath) && isRemnicTokenStorePath(resolvedTarget, homeDir);\n }\n if (isPathDescendant(path.join(homeDir, \".config\", \"remnic\"), resolvedTarget)) {\n return entry.createdByMigration === true && !entry.backupPath;\n }\n\n const serviceTargets = new Set([\n path.resolve(path.join(homeDir, \"Library\", \"LaunchAgents\", \"ai.remnic.daemon.plist\")),\n path.resolve(path.join(homeDir, \".config\", \"systemd\", \"user\", \"remnic.service\")),\n ]);\n if (serviceTargets.has(resolvedTarget)) return true;\n\n const cwd = resolveMigrationCwd(options);\n const allowedConnectorPaths = new Set(\n [\n ...defaultConnectorConfigPaths(homeDir, cwd),\n ...(options?.connectorConfigPaths ?? []),\n ].map((candidate) => resolveConnectorConfigPath(candidate, cwd)),\n );\n if (allowedConnectorPaths.has(resolvedTarget)) return true;\n\n return isPathInside(homeDir, resolvedTarget) && hasConnectorConfigShape(resolvedTarget, homeDir);\n}\n\nfunction isRollbackBackupAllowed(backupPath: string, homeDir: string): boolean {\n return isPathInside(backupRoot(homeDir), backupPath);\n}\n\nasync function assertNoSymlinkPathSegments(filePath: string, trustedRoot: string, label: string): Promise<void> {\n const resolvedPath = path.resolve(filePath);\n const resolvedRoot = path.resolve(trustedRoot);\n if (!isPathInside(resolvedRoot, resolvedPath)) {\n throw new Error(`${label} is outside the trusted rollback root: ${filePath}`);\n }\n const segments = path.relative(resolvedRoot, resolvedPath).split(path.sep).filter(Boolean);\n let current = resolvedRoot;\n\n for (const [index, segment] of segments.entries()) {\n current = path.join(current, segment);\n try {\n const currentStat = await lstat(current);\n if (currentStat.isSymbolicLink()) {\n throw new Error(`${label} must not contain symlink segments: ${filePath}`);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\" && index === segments.length - 1) return;\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new Error(`${label} must not contain missing parent segments: ${filePath}`);\n }\n throw error;\n }\n }\n}\n\nfunction rollbackTargetSymlinkRoot(targetPath: string, homeDir: string, options?: MigrationOptions): string {\n if (isPathInside(homeDir, targetPath)) return homeDir;\n\n const cwd = resolveMigrationCwd(options);\n if (isPathInside(cwd, targetPath)) return cwd;\n\n return path.parse(targetPath).root;\n}\n\nasync function validateRollbackManifestEntries(\n manifest: RollbackManifest,\n homeDir: string,\n options?: MigrationOptions,\n): Promise<ValidatedRollbackManifestEntry[]> {\n const validated: ValidatedRollbackManifestEntry[] = [];\n\n for (const entry of manifest.entries) {\n const targetPath = path.resolve(entry.targetPath);\n if (!isRollbackTargetAllowed(entry, targetPath, homeDir, options)) {\n throw new Error(`rollback manifest target is outside migration-owned paths: ${entry.targetPath}`);\n }\n if (entry.backupPath && entry.createdByMigration) {\n throw new Error(`rollback manifest entry cannot restore and remove the same target: ${entry.targetPath}`);\n }\n const targetExists = await pathExistsNoFollow(targetPath);\n if (!entry.createdByMigration || targetExists) {\n const targetSymlinkRoot = rollbackTargetSymlinkRoot(targetPath, homeDir, options);\n await assertNoSymlinkPathSegments(targetPath, targetSymlinkRoot, \"rollback manifest target\");\n }\n if (entry.createdByMigration && targetExists) {\n await assertCreatedRollbackTargetMatchesRecord(entry, targetPath);\n }\n\n let backupPath: string | undefined;\n if (entry.backupPath) {\n backupPath = path.resolve(entry.backupPath);\n if (!isRollbackBackupAllowed(backupPath, homeDir)) {\n throw new Error(`rollback manifest backup is outside migration backup storage: ${entry.backupPath}`);\n }\n if (await pathExistsNoFollow(backupPath)) {\n await assertNoSymlinkPathSegments(backupPath, homeDir, \"rollback manifest backup\");\n await assertExistingRegularFileNoFollow(backupPath, \"rollback manifest backup\");\n }\n if (backupPath !== connectorBackupPathForTarget(targetPath, homeDir)) {\n throw new Error(`rollback manifest backup does not match target: ${entry.targetPath}`);\n }\n }\n\n validated.push({\n targetPath,\n ...(backupPath === undefined ? {} : { backupPath }),\n ...(entry.createdByMigration === undefined ? {} : { createdByMigration: entry.createdByMigration }),\n ...(entry.contentHash === undefined ? {} : { contentHash: entry.contentHash }),\n });\n }\n\n return validated;\n}\n\nasync function assertCreatedRollbackTargetMatchesRecord(\n entry: RollbackManifestEntry,\n targetPath: string,\n): Promise<boolean> {\n const targetStat = await lstat(targetPath);\n if (targetStat.isDirectory()) {\n throw new Error(`rollback manifest created target must be a file path: ${entry.targetPath}`);\n }\n if (!targetStat.isFile() || !entry.contentHash) return false;\n if (await fileContentHash(targetPath) !== entry.contentHash) {\n throw new Error(`rollback manifest created target content does not match migration record: ${entry.targetPath}`);\n }\n return true;\n}\n\nasync function rewriteTokensIfPresent(filePath: string): Promise<number> {\n if (!existsSync(filePath)) return 0;\n await assertExistingRegularFileNoFollow(filePath, \"Remnic token store\");\n await secureTokenFilePermissions(filePath);\n let raw: Record<string, unknown>;\n try {\n raw = JSON.parse(await readFile(filePath, \"utf8\")) as Record<string, unknown>;\n } catch {\n return 0;\n }\n let rewritten = 0;\n\n if (Array.isArray(raw.tokens)) {\n for (const entry of raw.tokens as Array<Record<string, unknown>>) {\n if (typeof entry.token === \"string\") {\n const next = rewriteTokenValue(entry.token);\n if (next !== entry.token) {\n entry.token = next;\n rewritten += 1;\n }\n }\n }\n } else {\n for (const [key, value] of Object.entries(raw)) {\n if (typeof value === \"string\") {\n const next = rewriteTokenValue(value);\n if (next !== value) {\n raw[key] = next;\n rewritten += 1;\n }\n }\n }\n }\n\n if (rewritten > 0) {\n await writeTokenStoreFile(filePath, `${JSON.stringify(raw, null, 2)}\\n`);\n }\n return rewritten;\n}\n\nasync function mergeLegacyTokens(\n legacyTokensPath: string,\n remnicTokensPath: string,\n homeDir: string,\n manifest: RollbackManifest,\n backupExisting: boolean,\n persistManifest?: PersistRollbackManifest,\n): Promise<number> {\n if (existsSync(legacyTokensPath)) {\n await assertExistingRegularFileNoFollow(legacyTokensPath, \"legacy Engram token store\");\n }\n if (!existsSync(remnicTokensPath)) return 0;\n await assertExistingRegularFileNoFollow(remnicTokensPath, \"Remnic token store\");\n await secureTokenFilePermissions(remnicTokensPath);\n if (!existsSync(legacyTokensPath)) return rewriteTokensIfPresent(remnicTokensPath);\n\n let remnicRaw: unknown;\n let legacyRaw: unknown;\n const originalRemnic = await readFile(remnicTokensPath, \"utf8\");\n\n try {\n remnicRaw = JSON.parse(originalRemnic) as unknown;\n legacyRaw = JSON.parse(await readFile(legacyTokensPath, \"utf8\")) as unknown;\n } catch {\n try {\n legacyRaw = JSON.parse(await readFile(legacyTokensPath, \"utf8\")) as unknown;\n } catch {\n return rewriteTokensIfPresent(remnicTokensPath);\n }\n\n const legacyEntries = parseTokenEntries(legacyRaw);\n let rewritten = 0;\n const recoveredEntries = legacyEntries.map((entry) => {\n const nextToken = rewriteTokenValue(entry.token);\n if (nextToken !== entry.token) rewritten += 1;\n return {\n ...entry,\n token: nextToken,\n };\n });\n\n if (backupExisting) {\n await backupFile(remnicTokensPath, originalRemnic, homeDir, manifest, persistManifest);\n }\n\n await writeTokenStoreFile(\n remnicTokensPath,\n `${JSON.stringify({ tokens: recoveredEntries }, null, 2)}\\n`,\n );\n return rewritten;\n }\n\n const mergedEntries = parseTokenEntries(remnicRaw);\n const legacyEntries = parseTokenEntries(legacyRaw);\n const existingConnectors = new Set(mergedEntries.map((entry) => entry.connector));\n let rewritten = 0;\n let changed = false;\n\n for (const entry of mergedEntries) {\n const nextToken = rewriteTokenValue(entry.token);\n if (nextToken !== entry.token) {\n entry.token = nextToken;\n rewritten += 1;\n changed = true;\n }\n }\n\n for (const entry of legacyEntries) {\n const nextToken = rewriteTokenValue(entry.token);\n if (nextToken !== entry.token) {\n rewritten += 1;\n }\n if (existingConnectors.has(entry.connector)) continue;\n mergedEntries.push({ ...entry, token: nextToken });\n existingConnectors.add(entry.connector);\n changed = true;\n }\n\n if (!changed) return rewritten;\n\n if (backupExisting) {\n await backupFile(remnicTokensPath, originalRemnic, homeDir, manifest, persistManifest);\n }\n\n await writeTokenStoreFile(\n remnicTokensPath,\n `${JSON.stringify({ tokens: mergedEntries }, null, 2)}\\n`,\n );\n return rewritten;\n}\n\nasync function rewriteJsonFile(\n targetPath: string,\n homeDir: string,\n manifest: RollbackManifest,\n persistManifest?: PersistRollbackManifest,\n): Promise<boolean> {\n if (!existsSync(targetPath)) return false;\n const targetStat = await lstat(targetPath);\n if (targetStat.isSymbolicLink()) return false;\n if (!targetStat.isFile()) {\n const error = new Error(`connector config must be a regular file: ${targetPath}`) as NodeJS.ErrnoException;\n error.code = targetStat.isDirectory() ? \"EISDIR\" : \"EINVAL\";\n throw error;\n }\n\n const original = await readFile(targetPath, \"utf8\");\n let parsed: unknown;\n try {\n parsed = JSON.parse(original) as unknown;\n } catch {\n return false;\n }\n if (!isPlainJsonObject(parsed)) return false;\n\n let changed = false;\n if (\n parsed.mcpServers &&\n typeof parsed.mcpServers === \"object\" &&\n !Array.isArray(parsed.mcpServers)\n ) {\n const servers = parsed.mcpServers as Record<string, unknown>;\n if (servers.engram && !servers.remnic) {\n servers.remnic = servers.engram;\n delete servers.engram;\n changed = true;\n }\n }\n\n const rewritten = rewriteRemnicText(JSON.stringify(parsed, null, 2));\n const next = `${rewritten}\\n`;\n if (!changed && next === original) return false;\n\n await backupFile(targetPath, original, homeDir, manifest, persistManifest);\n await writeFile(targetPath, next, \"utf8\");\n return true;\n}\n\nasync function backupFile(\n targetPath: string,\n originalContent: string,\n homeDir: string,\n manifest: RollbackManifest,\n persistManifest?: PersistRollbackManifest,\n): Promise<void> {\n if (manifest.entries.some((entry) => entry.targetPath === targetPath && entry.backupPath)) {\n return;\n }\n const backupPath = connectorBackupPathForTarget(targetPath, homeDir);\n await ensureParent(backupPath);\n if (isRemnicTokenStorePath(targetPath, homeDir)) {\n await writeOwnerOnlyFile(backupPath, originalContent);\n } else {\n const originalMode = (await stat(targetPath)).mode & 0o777;\n await writeFile(backupPath, originalContent, { encoding: \"utf8\", mode: originalMode });\n await chmod(backupPath, originalMode);\n }\n manifest.entries.push({ targetPath, backupPath });\n await persistManifest?.();\n}\n\nasync function recordCreatedPath(\n filePath: string,\n manifest: RollbackManifest,\n persistManifest?: PersistRollbackManifest,\n): Promise<void> {\n if (manifest.entries.some((entry) => entry.targetPath === filePath)) return;\n manifest.entries.push({\n targetPath: filePath,\n createdByMigration: true,\n contentHash: await fileContentHash(filePath),\n });\n await persistManifest?.();\n}\n\nasync function refreshCreatedPathHash(\n filePath: string,\n manifest: RollbackManifest,\n persistManifest?: PersistRollbackManifest,\n): Promise<void> {\n const entry = manifest.entries.find((candidate) =>\n candidate.targetPath === filePath && candidate.createdByMigration\n );\n if (!entry) return;\n entry.contentHash = await fileContentHash(filePath);\n await persistManifest?.();\n}\n\nfunction defaultConnectorConfigPaths(homeDir: string, cwd: string): string[] {\n return [\n path.join(homeDir, \".claude.json\"),\n path.join(homeDir, \".claude\", \".mcp.json\"),\n path.join(cwd, \"packages\", \"plugin-claude-code\", \".mcp.json\"),\n path.join(cwd, \"packages\", \"plugin-codex\", \".mcp.json\"),\n ];\n}\n\nasync function updateConnectorConfigs(\n homeDir: string,\n cwd: string,\n options: MigrationOptions | undefined,\n manifest: RollbackManifest,\n persistManifest?: PersistRollbackManifest,\n): Promise<string[]> {\n const updated: string[] = [];\n const candidates = options?.connectorConfigPaths ?? defaultConnectorConfigPaths(homeDir, cwd);\n for (const targetPath of candidates) {\n const resolvedTarget = resolveConnectorConfigPath(targetPath, cwd);\n if (await rewriteJsonFile(resolvedTarget, homeDir, manifest, persistManifest)) {\n updated.push(resolvedTarget);\n }\n }\n return updated;\n}\n\nasync function copyLegacyConfig(\n homeDir: string,\n copied: string[],\n manifest: RollbackManifest,\n persistManifest?: PersistRollbackManifest,\n): Promise<void> {\n const source = legacyConfigPath(homeDir);\n const destination = remnicConfigPath(homeDir);\n if (!existsSync(source) || existsSync(destination)) return;\n if (!(await isExistingRegularFileNoFollow(source))) return;\n await ensureParent(destination);\n const original = await readFile(source, \"utf8\");\n let next = rewriteRemnicText(original);\n try {\n const parsed = JSON.parse(next) as unknown;\n if (isPlainJsonObject(parsed) && parsed.engram && !parsed.remnic) {\n parsed.remnic = parsed.engram;\n delete parsed.engram;\n next = JSON.stringify(parsed, null, 2);\n }\n } catch {\n // Keep rewritten text when config is not JSON.\n }\n await writeFile(destination, `${next.trimEnd()}\\n`, \"utf8\");\n await recordCreatedPath(destination, manifest, persistManifest);\n copied.push(destination);\n}\n\nfunction rewriteServiceText(content: string): string {\n return rewriteRemnicText(content);\n}\n\nasync function migrateServices(\n homeDir: string,\n options: MigrationOptions | undefined,\n manifest: RollbackManifest,\n persistManifest?: PersistRollbackManifest,\n): Promise<string[]> {\n const logger = resolveLogger(options);\n const exec = resolveExec(options);\n const servicesReinstalled: string[] = [];\n const platform = resolvePlatform(options);\n\n if (platform === \"darwin\") {\n const legacyPlist = path.join(homeDir, \"Library\", \"LaunchAgents\", \"ai.engram.daemon.plist\");\n const remnicPlist = path.join(homeDir, \"Library\", \"LaunchAgents\", \"ai.remnic.daemon.plist\");\n if (existsSync(legacyPlist) && !existsSync(remnicPlist)) {\n if (!(await isExistingRegularFileNoFollow(legacyPlist))) return servicesReinstalled;\n const next = rewriteServiceText(await readFile(legacyPlist, \"utf8\"));\n await ensureParent(remnicPlist);\n await writeFile(remnicPlist, next, \"utf8\");\n await recordCreatedPath(remnicPlist, manifest, persistManifest);\n try {\n exec(\"launchctl\", [\"unload\", legacyPlist]);\n } catch {\n // Keep migration fail-open when launchd rejects unload.\n }\n try {\n exec(\"launchctl\", [\"load\", \"-w\", remnicPlist]);\n } catch {\n // Keep migration fail-open when launchd rejects load.\n }\n servicesReinstalled.push(\"ai.remnic.daemon\");\n logger(\"launchd: ai.engram.daemon unloaded, ai.remnic.daemon installed\");\n }\n return servicesReinstalled;\n }\n\n if (platform === \"linux\") {\n const legacyUnit = path.join(homeDir, \".config\", \"systemd\", \"user\", \"engram.service\");\n const remnicUnit = path.join(homeDir, \".config\", \"systemd\", \"user\", \"remnic.service\");\n if (existsSync(legacyUnit) && !existsSync(remnicUnit)) {\n if (!(await isExistingRegularFileNoFollow(legacyUnit))) return servicesReinstalled;\n const next = rewriteServiceText(await readFile(legacyUnit, \"utf8\"));\n await ensureParent(remnicUnit);\n await writeFile(remnicUnit, next, \"utf8\");\n await recordCreatedPath(remnicUnit, manifest, persistManifest);\n try {\n exec(\"systemctl\", [\"--user\", \"stop\", \"engram.service\"]);\n exec(\"systemctl\", [\"--user\", \"disable\", \"engram.service\"]);\n exec(\"systemctl\", [\"--user\", \"daemon-reload\"]);\n exec(\"systemctl\", [\"--user\", \"enable\", \"remnic.service\"]);\n exec(\"systemctl\", [\"--user\", \"start\", \"remnic.service\"]);\n } catch {\n // Keep migration fail-open when systemd is unavailable.\n }\n servicesReinstalled.push(\"remnic.service\");\n logger(\"systemd: engram.service disabled, remnic.service installed\");\n }\n }\n\n return servicesReinstalled;\n}\n\nasync function writeRollbackManifest(homeDir: string, manifest: RollbackManifest): Promise<void> {\n await ensureParent(rollbackManifestPath(homeDir));\n await writeFile(\n rollbackManifestPath(homeDir),\n `${JSON.stringify(manifest, null, 2)}\\n`,\n \"utf8\",\n );\n}\n\nasync function readRollbackManifest(homeDir: string): Promise<RollbackManifest | null> {\n const target = rollbackManifestPath(homeDir);\n let targetStat: Awaited<ReturnType<typeof lstat>>;\n try {\n targetStat = await lstat(target);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n }\n if (targetStat.isSymbolicLink()) {\n throw new Error(`rollback manifest must not be a symlink: ${target}`);\n }\n if (!targetStat.isFile()) {\n throw new Error(`rollback manifest must be a regular file: ${target}`);\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(await readFile(target, \"utf8\")) as unknown;\n } catch {\n return null;\n }\n return parseRollbackManifest(parsed, target);\n}\n\nasync function acquireLock(homeDir: string): Promise<() => Promise<void>> {\n const target = lockPath(homeDir);\n await mkdir(remnicRoot(homeDir), { recursive: true });\n const started = Date.now();\n\n while (true) {\n try {\n const handle = await open(target, \"wx\");\n await handle.writeFile(`${process.pid}\\n${Date.now()}\\n`, \"utf8\");\n return async () => {\n try {\n await handle.close();\n } finally {\n await unlink(target).catch(() => undefined);\n }\n };\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== \"EEXIST\") throw error;\n\n const details = await readFile(target, \"utf8\").catch(() => null);\n if (details === null) {\n if (await removeLock(target)) continue;\n } else {\n const lines = details.split(\"\\n\");\n const pid = Number.parseInt(lines[0] ?? \"\", 10);\n const createdAt = Number.parseInt(lines[1] ?? \"\", 10);\n const malformed = !Number.isSafeInteger(pid) || pid <= 0 || !Number.isFinite(createdAt);\n const deadPid = !malformed && !processIsAlive(pid);\n if (malformed || deadPid) {\n if (await removeLockIfUnchanged(target, details)) continue;\n }\n }\n if (Date.now() - started > LOCK_TIMEOUT_MS) {\n throw new Error(`timed out waiting for migration lock: ${target}`);\n }\n await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));\n }\n }\n}\n\nasync function removeLockIfUnchanged(target: string, expectedContent: string): Promise<boolean> {\n const current = await readFile(target, \"utf8\").catch(() => null);\n if (current !== expectedContent) return false;\n return removeLock(target);\n}\n\nasync function removeLock(target: string): Promise<boolean> {\n try {\n await rm(target, { force: true });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction processIsAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EPERM\") return true;\n return false;\n }\n}\n\nexport async function rollbackFromEngramMigration(options?: MigrationOptions): Promise<RollbackResult> {\n const homeDir = resolveMigrationHome(options);\n const manifest = await readRollbackManifest(homeDir);\n const exec = resolveExec(options);\n const platform = resolvePlatform(options);\n const restored: string[] = [];\n const removed: string[] = [];\n\n if (!manifest) return { restored, removed };\n const entries = await validateRollbackManifestEntries(manifest, homeDir, options);\n\n if (platform === \"darwin\") {\n const remnicPlist = path.join(homeDir, \"Library\", \"LaunchAgents\", \"ai.remnic.daemon.plist\");\n if (existsSync(remnicPlist)) {\n try {\n exec(\"launchctl\", [\"unload\", remnicPlist]);\n } catch {\n // Ignore launchctl rollback failures.\n }\n }\n } else if (platform === \"linux\") {\n try {\n exec(\"systemctl\", [\"--user\", \"stop\", \"remnic.service\"]);\n exec(\"systemctl\", [\"--user\", \"disable\", \"remnic.service\"]);\n } catch {\n // Ignore systemd rollback failures.\n }\n }\n\n for (const entry of [...entries].reverse()) {\n if (entry.backupPath && await pathExistsNoFollow(entry.backupPath)) {\n await assertNoSymlinkPathSegments(entry.backupPath, homeDir, \"rollback manifest backup\");\n await assertExistingRegularFileNoFollow(entry.backupPath, \"rollback manifest backup\");\n await ensureParent(entry.targetPath);\n await copyFile(entry.backupPath, entry.targetPath);\n if (isRemnicTokenStorePath(entry.targetPath, homeDir)) {\n await secureTokenFilePermissions(entry.targetPath);\n }\n restored.push(entry.targetPath);\n continue;\n }\n if (entry.createdByMigration && existsSync(entry.targetPath)) {\n const targetSymlinkRoot = rollbackTargetSymlinkRoot(entry.targetPath, homeDir, options);\n await assertNoSymlinkPathSegments(entry.targetPath, targetSymlinkRoot, \"rollback manifest target\");\n if (!await assertCreatedRollbackTargetMatchesRecord(entry, entry.targetPath)) continue;\n await rm(entry.targetPath, { recursive: true, force: true });\n removed.push(entry.targetPath);\n }\n }\n\n if (platform === \"linux\") {\n try {\n exec(\"systemctl\", [\"--user\", \"daemon-reload\"]);\n } catch {\n // Ignore systemd rollback failures after removing unit files.\n }\n }\n\n await rm(markerPath(homeDir), { force: true }).catch(() => undefined);\n await rm(rollbackManifestPath(homeDir), { force: true }).catch(() => undefined);\n return { restored, removed };\n}\n\nexport async function migrateFromEngram(options?: MigrationOptions): Promise<MigrationResult> {\n const homeDir = resolveMigrationHome(options);\n const cwd = resolveMigrationCwd(options);\n const logger = resolveLogger(options);\n const copied: string[] = [];\n let tokensRegenerated = 0;\n let servicesReinstalled: string[] = [];\n\n if (existsSync(markerPath(homeDir))) {\n return {\n status: \"already-migrated\",\n copied,\n tokensRegenerated,\n servicesReinstalled,\n rollbackCommand: defaultRollbackCommand(),\n };\n }\n\n const hasLegacyRoot = existsSync(legacyRoot(homeDir));\n const hasLegacyConfig = existsSync(legacyConfigPath(homeDir));\n if (!hasLegacyRoot && !hasLegacyConfig) {\n return {\n status: \"fresh-install\",\n copied,\n tokensRegenerated,\n servicesReinstalled,\n rollbackCommand: defaultRollbackCommand(),\n };\n }\n\n const releaseLock = await acquireLock(homeDir);\n try {\n if (existsSync(markerPath(homeDir))) {\n return {\n status: \"already-migrated\",\n copied,\n tokensRegenerated,\n servicesReinstalled,\n rollbackCommand: defaultRollbackCommand(),\n };\n }\n\n const manifest: RollbackManifest = await readRollbackManifest(homeDir) ?? {\n version: 1,\n createdAt: new Date().toISOString(),\n entries: [],\n };\n const persistManifest = () => writeRollbackManifest(homeDir, manifest);\n\n logger(\"First run after Engram -> Remnic rename. Migrating...\");\n await mkdir(remnicRoot(homeDir), { recursive: true });\n await persistManifest();\n await copyTreeMissing(legacyRoot(homeDir), remnicRoot(homeDir), copied, manifest, persistManifest);\n await copyLegacyConfig(homeDir, copied, manifest, persistManifest);\n\n const legacyTokens = path.join(legacyRoot(homeDir), \"tokens.json\");\n const remnicTokens = path.join(remnicRoot(homeDir), \"tokens.json\");\n if (copied.includes(remnicTokens)) {\n tokensRegenerated += await rewriteTokensIfPresent(remnicTokens);\n await refreshCreatedPathHash(remnicTokens, manifest, persistManifest);\n } else {\n tokensRegenerated += await mergeLegacyTokens(\n legacyTokens,\n remnicTokens,\n homeDir,\n manifest,\n true,\n persistManifest,\n );\n }\n if (existsSync(remnicTokens)) {\n logger(\"tokens copied to ~/.remnic/tokens.json (legacy prefixes rewritten)\");\n }\n\n const updatedConfigs = await updateConnectorConfigs(homeDir, cwd, options, manifest, persistManifest);\n for (const updated of updatedConfigs) {\n logger(`Updated connector config: ${updated}`);\n }\n\n servicesReinstalled = await migrateServices(homeDir, options, manifest, persistManifest);\n await writeRollbackManifest(homeDir, manifest);\n await writeFile(markerPath(homeDir), `${new Date().toISOString()}\\n`, \"utf8\");\n logger(\"Migration complete. Welcome to Remnic.\");\n\n return {\n status: \"migrated\",\n copied,\n tokensRegenerated,\n servicesReinstalled,\n rollbackCommand: defaultRollbackCommand(),\n };\n } finally {\n await releaseLock();\n }\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AACjB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