@remnic/core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (551) hide show
  1. package/dist/abstraction-nodes.d.ts +52 -0
  2. package/dist/abstraction-nodes.js +15 -0
  3. package/dist/abstraction-nodes.js.map +1 -0
  4. package/dist/access-cli.d.ts +5 -0
  5. package/dist/access-cli.js +308 -0
  6. package/dist/access-cli.js.map +1 -0
  7. package/dist/access-http.d.ts +158 -0
  8. package/dist/access-http.js +32 -0
  9. package/dist/access-http.js.map +1 -0
  10. package/dist/access-idempotency.d.ts +31 -0
  11. package/dist/access-idempotency.js +11 -0
  12. package/dist/access-idempotency.js.map +1 -0
  13. package/dist/access-mcp.d.ts +76 -0
  14. package/dist/access-mcp.js +8 -0
  15. package/dist/access-mcp.js.map +1 -0
  16. package/dist/access-schema.d.ts +266 -0
  17. package/dist/access-schema.js +29 -0
  18. package/dist/access-schema.js.map +1 -0
  19. package/dist/access-service.d.ts +614 -0
  20. package/dist/access-service.js +32 -0
  21. package/dist/access-service.js.map +1 -0
  22. package/dist/behavior-learner.d.ts +16 -0
  23. package/dist/behavior-learner.js +124 -0
  24. package/dist/behavior-learner.js.map +1 -0
  25. package/dist/behavior-signals.d.ts +15 -0
  26. package/dist/behavior-signals.js +11 -0
  27. package/dist/behavior-signals.js.map +1 -0
  28. package/dist/bootstrap.d.ts +46 -0
  29. package/dist/bootstrap.js +9 -0
  30. package/dist/bootstrap.js.map +1 -0
  31. package/dist/boxes.d.ts +93 -0
  32. package/dist/boxes.js +14 -0
  33. package/dist/boxes.js.map +1 -0
  34. package/dist/buffer.d.ts +22 -0
  35. package/dist/buffer.js +9 -0
  36. package/dist/buffer.js.map +1 -0
  37. package/dist/calibration.d.ts +81 -0
  38. package/dist/calibration.js +239 -0
  39. package/dist/calibration.js.map +1 -0
  40. package/dist/causal-behavior.d.ts +79 -0
  41. package/dist/causal-behavior.js +190 -0
  42. package/dist/causal-behavior.js.map +1 -0
  43. package/dist/causal-chain.d.ts +61 -0
  44. package/dist/causal-chain.js +24 -0
  45. package/dist/causal-chain.js.map +1 -0
  46. package/dist/causal-consolidation.d.ts +71 -0
  47. package/dist/causal-consolidation.js +211 -0
  48. package/dist/causal-consolidation.js.map +1 -0
  49. package/dist/causal-retrieval.d.ts +44 -0
  50. package/dist/causal-retrieval.js +184 -0
  51. package/dist/causal-retrieval.js.map +1 -0
  52. package/dist/causal-trajectory-graph.d.ts +13 -0
  53. package/dist/causal-trajectory-graph.js +59 -0
  54. package/dist/causal-trajectory-graph.js.map +1 -0
  55. package/dist/causal-trajectory.d.ts +68 -0
  56. package/dist/causal-trajectory.js +18 -0
  57. package/dist/causal-trajectory.js.map +1 -0
  58. package/dist/chunk-2CJCWDMR.js +87 -0
  59. package/dist/chunk-2CJCWDMR.js.map +1 -0
  60. package/dist/chunk-2NMMFZ5T.js +216 -0
  61. package/dist/chunk-2NMMFZ5T.js.map +1 -0
  62. package/dist/chunk-2PO5ZRKV.js +103 -0
  63. package/dist/chunk-2PO5ZRKV.js.map +1 -0
  64. package/dist/chunk-3QKK7QOS.js +154 -0
  65. package/dist/chunk-3QKK7QOS.js.map +1 -0
  66. package/dist/chunk-3SLRNYNG.js +26 -0
  67. package/dist/chunk-3SLRNYNG.js.map +1 -0
  68. package/dist/chunk-4A24LIM2.js +68 -0
  69. package/dist/chunk-4A24LIM2.js.map +1 -0
  70. package/dist/chunk-6HZ6AO2P.js +164 -0
  71. package/dist/chunk-6HZ6AO2P.js.map +1 -0
  72. package/dist/chunk-763GUIOU.js +302 -0
  73. package/dist/chunk-763GUIOU.js.map +1 -0
  74. package/dist/chunk-AAI7JARD.js +173 -0
  75. package/dist/chunk-AAI7JARD.js.map +1 -0
  76. package/dist/chunk-B7LOFDVE.js +112 -0
  77. package/dist/chunk-B7LOFDVE.js.map +1 -0
  78. package/dist/chunk-BDFZXRSO.js +318 -0
  79. package/dist/chunk-BDFZXRSO.js.map +1 -0
  80. package/dist/chunk-BOUYNNYD.js +707 -0
  81. package/dist/chunk-BOUYNNYD.js.map +1 -0
  82. package/dist/chunk-BRK4ODMI.js +60 -0
  83. package/dist/chunk-BRK4ODMI.js.map +1 -0
  84. package/dist/chunk-C6QPK5GG.js +111 -0
  85. package/dist/chunk-C6QPK5GG.js.map +1 -0
  86. package/dist/chunk-C7VW7C3F.js +117 -0
  87. package/dist/chunk-C7VW7C3F.js.map +1 -0
  88. package/dist/chunk-CDW777AI.js +621 -0
  89. package/dist/chunk-CDW777AI.js.map +1 -0
  90. package/dist/chunk-CULXMQJH.js +185 -0
  91. package/dist/chunk-CULXMQJH.js.map +1 -0
  92. package/dist/chunk-CXWFUJR2.js +1203 -0
  93. package/dist/chunk-CXWFUJR2.js.map +1 -0
  94. package/dist/chunk-DGXUHMOV.js +61 -0
  95. package/dist/chunk-DGXUHMOV.js.map +1 -0
  96. package/dist/chunk-DM2T26WE.js +61 -0
  97. package/dist/chunk-DM2T26WE.js.map +1 -0
  98. package/dist/chunk-DORBM6OB.js +81 -0
  99. package/dist/chunk-DORBM6OB.js.map +1 -0
  100. package/dist/chunk-DT5TVLJE.js +32 -0
  101. package/dist/chunk-DT5TVLJE.js.map +1 -0
  102. package/dist/chunk-EEQLFRUM.js +89 -0
  103. package/dist/chunk-EEQLFRUM.js.map +1 -0
  104. package/dist/chunk-EQINRHYR.js +672 -0
  105. package/dist/chunk-EQINRHYR.js.map +1 -0
  106. package/dist/chunk-ESSMF2FR.js +146 -0
  107. package/dist/chunk-ESSMF2FR.js.map +1 -0
  108. package/dist/chunk-ETOW6ACV.js +158 -0
  109. package/dist/chunk-ETOW6ACV.js.map +1 -0
  110. package/dist/chunk-FYIYMQ5N.js +221 -0
  111. package/dist/chunk-FYIYMQ5N.js.map +1 -0
  112. package/dist/chunk-G3AG3KZN.js +78 -0
  113. package/dist/chunk-G3AG3KZN.js.map +1 -0
  114. package/dist/chunk-GJR6D6KC.js +61 -0
  115. package/dist/chunk-GJR6D6KC.js.map +1 -0
  116. package/dist/chunk-GPGBSNKM.js +380 -0
  117. package/dist/chunk-GPGBSNKM.js.map +1 -0
  118. package/dist/chunk-H63EDPFJ.js +57 -0
  119. package/dist/chunk-H63EDPFJ.js.map +1 -0
  120. package/dist/chunk-HG2NKWR2.js +185 -0
  121. package/dist/chunk-HG2NKWR2.js.map +1 -0
  122. package/dist/chunk-HL4DB7TO.js +13 -0
  123. package/dist/chunk-HL4DB7TO.js.map +1 -0
  124. package/dist/chunk-HLBYLYRD.js +346 -0
  125. package/dist/chunk-HLBYLYRD.js.map +1 -0
  126. package/dist/chunk-HLXVTBF3.js +109 -0
  127. package/dist/chunk-HLXVTBF3.js.map +1 -0
  128. package/dist/chunk-IFFFR3MR.js +68 -0
  129. package/dist/chunk-IFFFR3MR.js.map +1 -0
  130. package/dist/chunk-ISY75RLM.js +1027 -0
  131. package/dist/chunk-ISY75RLM.js.map +1 -0
  132. package/dist/chunk-IZME7KW2.js +1886 -0
  133. package/dist/chunk-IZME7KW2.js.map +1 -0
  134. package/dist/chunk-J3BT33K7.js +720 -0
  135. package/dist/chunk-J3BT33K7.js.map +1 -0
  136. package/dist/chunk-J47FNDR7.js +113 -0
  137. package/dist/chunk-J47FNDR7.js.map +1 -0
  138. package/dist/chunk-JWPLJLDU.js +63 -0
  139. package/dist/chunk-JWPLJLDU.js.map +1 -0
  140. package/dist/chunk-K6WK37A6.js +865 -0
  141. package/dist/chunk-K6WK37A6.js.map +1 -0
  142. package/dist/chunk-KL4CP4SB.js +130 -0
  143. package/dist/chunk-KL4CP4SB.js.map +1 -0
  144. package/dist/chunk-KT4NEUNF.js +315 -0
  145. package/dist/chunk-KT4NEUNF.js.map +1 -0
  146. package/dist/chunk-KWBU5S5U.js +42 -0
  147. package/dist/chunk-KWBU5S5U.js.map +1 -0
  148. package/dist/chunk-L5RPWGFK.js +59 -0
  149. package/dist/chunk-L5RPWGFK.js.map +1 -0
  150. package/dist/chunk-L7WO3MZ4.js +128 -0
  151. package/dist/chunk-L7WO3MZ4.js.map +1 -0
  152. package/dist/chunk-LIRZNNUP.js +74 -0
  153. package/dist/chunk-LIRZNNUP.js.map +1 -0
  154. package/dist/chunk-LK6SGL53.js +22 -0
  155. package/dist/chunk-LK6SGL53.js.map +1 -0
  156. package/dist/chunk-LOBRX7VD.js +200 -0
  157. package/dist/chunk-LOBRX7VD.js.map +1 -0
  158. package/dist/chunk-LPSF4OQH.js +47 -0
  159. package/dist/chunk-LPSF4OQH.js.map +1 -0
  160. package/dist/chunk-LU3GQNDQ.js +152 -0
  161. package/dist/chunk-LU3GQNDQ.js.map +1 -0
  162. package/dist/chunk-M5KEYE5E.js +350 -0
  163. package/dist/chunk-M5KEYE5E.js.map +1 -0
  164. package/dist/chunk-M62O4P4T.js +41 -0
  165. package/dist/chunk-M62O4P4T.js.map +1 -0
  166. package/dist/chunk-MARWOCVP.js +48 -0
  167. package/dist/chunk-MARWOCVP.js.map +1 -0
  168. package/dist/chunk-MDDAA2AO.js +925 -0
  169. package/dist/chunk-MDDAA2AO.js.map +1 -0
  170. package/dist/chunk-MWGVGUIS.js +198 -0
  171. package/dist/chunk-MWGVGUIS.js.map +1 -0
  172. package/dist/chunk-N5AKDXAI.js +74 -0
  173. package/dist/chunk-N5AKDXAI.js.map +1 -0
  174. package/dist/chunk-NGAVDO7E.js +115 -0
  175. package/dist/chunk-NGAVDO7E.js.map +1 -0
  176. package/dist/chunk-NTTLPF7F.js +283 -0
  177. package/dist/chunk-NTTLPF7F.js.map +1 -0
  178. package/dist/chunk-ONRU4L2N.js +240 -0
  179. package/dist/chunk-ONRU4L2N.js.map +1 -0
  180. package/dist/chunk-ORZMT74A.js +209 -0
  181. package/dist/chunk-ORZMT74A.js.map +1 -0
  182. package/dist/chunk-OTAVQCSF.js +268 -0
  183. package/dist/chunk-OTAVQCSF.js.map +1 -0
  184. package/dist/chunk-PGK3VUHN.js +160 -0
  185. package/dist/chunk-PGK3VUHN.js.map +1 -0
  186. package/dist/chunk-Q6FETXJA.js +1362 -0
  187. package/dist/chunk-Q6FETXJA.js.map +1 -0
  188. package/dist/chunk-QANCTXQF.js +271 -0
  189. package/dist/chunk-QANCTXQF.js.map +1 -0
  190. package/dist/chunk-QCCCQT3O.js +189 -0
  191. package/dist/chunk-QCCCQT3O.js.map +1 -0
  192. package/dist/chunk-QDOSNLB4.js +1048 -0
  193. package/dist/chunk-QDOSNLB4.js.map +1 -0
  194. package/dist/chunk-QFQVZOGA.js +2168 -0
  195. package/dist/chunk-QFQVZOGA.js.map +1 -0
  196. package/dist/chunk-QPKFPHOO.js +178 -0
  197. package/dist/chunk-QPKFPHOO.js.map +1 -0
  198. package/dist/chunk-QSVPYQPG.js +268 -0
  199. package/dist/chunk-QSVPYQPG.js.map +1 -0
  200. package/dist/chunk-QWUUMMIK.js +3045 -0
  201. package/dist/chunk-QWUUMMIK.js.map +1 -0
  202. package/dist/chunk-QY2BHY5O.js +2378 -0
  203. package/dist/chunk-QY2BHY5O.js.map +1 -0
  204. package/dist/chunk-SCHEKPYH.js +349 -0
  205. package/dist/chunk-SCHEKPYH.js.map +1 -0
  206. package/dist/chunk-SCU65EZI.js +15 -0
  207. package/dist/chunk-SCU65EZI.js.map +1 -0
  208. package/dist/chunk-T4WRIV2C.js +170 -0
  209. package/dist/chunk-T4WRIV2C.js.map +1 -0
  210. package/dist/chunk-TKO4HZCK.js +1852 -0
  211. package/dist/chunk-TKO4HZCK.js.map +1 -0
  212. package/dist/chunk-TP4FZJIZ.js +93 -0
  213. package/dist/chunk-TP4FZJIZ.js.map +1 -0
  214. package/dist/chunk-TPB3I2AC.js +403 -0
  215. package/dist/chunk-TPB3I2AC.js.map +1 -0
  216. package/dist/chunk-TVVVQQAK.js +1431 -0
  217. package/dist/chunk-TVVVQQAK.js.map +1 -0
  218. package/dist/chunk-U4PV25RD.js +14 -0
  219. package/dist/chunk-U4PV25RD.js.map +1 -0
  220. package/dist/chunk-UCYSTFZR.js +284 -0
  221. package/dist/chunk-UCYSTFZR.js.map +1 -0
  222. package/dist/chunk-UHGBNIOS.js +205 -0
  223. package/dist/chunk-UHGBNIOS.js.map +1 -0
  224. package/dist/chunk-UIYZ5T3I.js +108 -0
  225. package/dist/chunk-UIYZ5T3I.js.map +1 -0
  226. package/dist/chunk-UV2FO7J4.js +747 -0
  227. package/dist/chunk-UV2FO7J4.js.map +1 -0
  228. package/dist/chunk-UZB5KHKX.js +63 -0
  229. package/dist/chunk-UZB5KHKX.js.map +1 -0
  230. package/dist/chunk-V3RXWQIE.js +626 -0
  231. package/dist/chunk-V3RXWQIE.js.map +1 -0
  232. package/dist/chunk-V4YC4LUK.js +444 -0
  233. package/dist/chunk-V4YC4LUK.js.map +1 -0
  234. package/dist/chunk-VEWZZM3H.js +133 -0
  235. package/dist/chunk-VEWZZM3H.js.map +1 -0
  236. package/dist/chunk-WWIQTB2Y.js +98 -0
  237. package/dist/chunk-WWIQTB2Y.js.map +1 -0
  238. package/dist/chunk-X7XN6YU4.js +24 -0
  239. package/dist/chunk-X7XN6YU4.js.map +1 -0
  240. package/dist/chunk-XKECPATV.js +202 -0
  241. package/dist/chunk-XKECPATV.js.map +1 -0
  242. package/dist/chunk-XYIK4LF6.js +75 -0
  243. package/dist/chunk-XYIK4LF6.js.map +1 -0
  244. package/dist/chunk-Y27UJK6V.js +39 -0
  245. package/dist/chunk-Y27UJK6V.js.map +1 -0
  246. package/dist/chunk-Y4Z4I6WK.js +9 -0
  247. package/dist/chunk-Y4Z4I6WK.js.map +1 -0
  248. package/dist/chunk-YAPUAHAY.js +10761 -0
  249. package/dist/chunk-YAPUAHAY.js.map +1 -0
  250. package/dist/chunk-YAZNBMNF.js +92 -0
  251. package/dist/chunk-YAZNBMNF.js.map +1 -0
  252. package/dist/chunk-YCN4BVDK.js +66 -0
  253. package/dist/chunk-YCN4BVDK.js.map +1 -0
  254. package/dist/chunk-YNCQ7E4M.js +388 -0
  255. package/dist/chunk-YNCQ7E4M.js.map +1 -0
  256. package/dist/chunk-YNI4S5WT.js +143 -0
  257. package/dist/chunk-YNI4S5WT.js.map +1 -0
  258. package/dist/chunk-YRMVARQP.js +406 -0
  259. package/dist/chunk-YRMVARQP.js.map +1 -0
  260. package/dist/chunk-Z5AAYHUC.js +79 -0
  261. package/dist/chunk-Z5AAYHUC.js.map +1 -0
  262. package/dist/chunk-Z5LAYHGJ.js +15 -0
  263. package/dist/chunk-Z5LAYHGJ.js.map +1 -0
  264. package/dist/chunk-ZJLY4QSU.js +823 -0
  265. package/dist/chunk-ZJLY4QSU.js.map +1 -0
  266. package/dist/chunk-ZKYI7UVO.js +276 -0
  267. package/dist/chunk-ZKYI7UVO.js.map +1 -0
  268. package/dist/chunk-ZPKBYX2F.js +297 -0
  269. package/dist/chunk-ZPKBYX2F.js.map +1 -0
  270. package/dist/chunking.d.ts +48 -0
  271. package/dist/chunking.js +11 -0
  272. package/dist/chunking.js.map +1 -0
  273. package/dist/cli.d.ts +1162 -0
  274. package/dist/cli.js +7187 -0
  275. package/dist/cli.js.map +1 -0
  276. package/dist/commitment-ledger.d.ts +83 -0
  277. package/dist/commitment-ledger.js +19 -0
  278. package/dist/commitment-ledger.js.map +1 -0
  279. package/dist/compression-optimizer.d.ts +37 -0
  280. package/dist/compression-optimizer.js +13 -0
  281. package/dist/compression-optimizer.js.map +1 -0
  282. package/dist/config.d.ts +6 -0
  283. package/dist/config.js +12 -0
  284. package/dist/config.js.map +1 -0
  285. package/dist/cue-anchors.d.ts +50 -0
  286. package/dist/cue-anchors.js +15 -0
  287. package/dist/cue-anchors.js.map +1 -0
  288. package/dist/dashboard-runtime.d.ts +46 -0
  289. package/dist/dashboard-runtime.js +10 -0
  290. package/dist/dashboard-runtime.js.map +1 -0
  291. package/dist/day-summary.d.ts +6 -0
  292. package/dist/day-summary.js +10 -0
  293. package/dist/day-summary.js.map +1 -0
  294. package/dist/delinearize.d.ts +34 -0
  295. package/dist/delinearize.js +11 -0
  296. package/dist/delinearize.js.map +1 -0
  297. package/dist/embedding-fallback.d.ts +22 -0
  298. package/dist/embedding-fallback.js +8 -0
  299. package/dist/embedding-fallback.js.map +1 -0
  300. package/dist/engine-P26JFSVY.js +19 -0
  301. package/dist/engine-P26JFSVY.js.map +1 -0
  302. package/dist/entity-retrieval.d.ts +23 -0
  303. package/dist/entity-retrieval.js +24 -0
  304. package/dist/entity-retrieval.js.map +1 -0
  305. package/dist/evals.d.ts +282 -0
  306. package/dist/evals.js +32 -0
  307. package/dist/evals.js.map +1 -0
  308. package/dist/explicit-capture.d.ts +60 -0
  309. package/dist/explicit-capture.js +23 -0
  310. package/dist/explicit-capture.js.map +1 -0
  311. package/dist/extraction.d.ts +141 -0
  312. package/dist/extraction.js +22 -0
  313. package/dist/extraction.js.map +1 -0
  314. package/dist/fallback-llm.d.ts +95 -0
  315. package/dist/fallback-llm.js +12 -0
  316. package/dist/fallback-llm.js.map +1 -0
  317. package/dist/graph-dashboard-diff.d.ts +12 -0
  318. package/dist/graph-dashboard-diff.js +8 -0
  319. package/dist/graph-dashboard-diff.js.map +1 -0
  320. package/dist/graph-dashboard-key.d.ts +5 -0
  321. package/dist/graph-dashboard-key.js +7 -0
  322. package/dist/graph-dashboard-key.js.map +1 -0
  323. package/dist/graph-dashboard-parser.d.ts +20 -0
  324. package/dist/graph-dashboard-parser.js +8 -0
  325. package/dist/graph-dashboard-parser.js.map +1 -0
  326. package/dist/graph.d.ts +157 -0
  327. package/dist/graph.js +27 -0
  328. package/dist/graph.js.map +1 -0
  329. package/dist/harmonic-retrieval.d.ts +27 -0
  330. package/dist/harmonic-retrieval.js +12 -0
  331. package/dist/harmonic-retrieval.js.map +1 -0
  332. package/dist/himem.d.ts +23 -0
  333. package/dist/himem.js +7 -0
  334. package/dist/himem.js.map +1 -0
  335. package/dist/hygiene.d.ts +24 -0
  336. package/dist/hygiene.js +9 -0
  337. package/dist/hygiene.js.map +1 -0
  338. package/dist/identity-continuity.d.ts +17 -0
  339. package/dist/identity-continuity.js +19 -0
  340. package/dist/identity-continuity.js.map +1 -0
  341. package/dist/importance.d.ts +25 -0
  342. package/dist/importance.js +11 -0
  343. package/dist/importance.js.map +1 -0
  344. package/dist/index.d.ts +923 -0
  345. package/dist/index.js +2512 -0
  346. package/dist/index.js.map +1 -0
  347. package/dist/intent.d.ts +8 -0
  348. package/dist/intent.js +13 -0
  349. package/dist/intent.js.map +1 -0
  350. package/dist/json-extract.d.ts +14 -0
  351. package/dist/json-extract.js +9 -0
  352. package/dist/json-extract.js.map +1 -0
  353. package/dist/json-store.d.ts +5 -0
  354. package/dist/json-store.js +11 -0
  355. package/dist/json-store.js.map +1 -0
  356. package/dist/legacy-hook-compat.d.ts +3 -0
  357. package/dist/legacy-hook-compat.js +35 -0
  358. package/dist/legacy-hook-compat.js.map +1 -0
  359. package/dist/lifecycle.d.ts +52 -0
  360. package/dist/lifecycle.js +21 -0
  361. package/dist/lifecycle.js.map +1 -0
  362. package/dist/local-llm.d.ts +154 -0
  363. package/dist/local-llm.js +10 -0
  364. package/dist/local-llm.js.map +1 -0
  365. package/dist/logger.d.ts +15 -0
  366. package/dist/logger.js +9 -0
  367. package/dist/logger.js.map +1 -0
  368. package/dist/memory-action-policy.d.ts +13 -0
  369. package/dist/memory-action-policy.js +7 -0
  370. package/dist/memory-action-policy.js.map +1 -0
  371. package/dist/memory-cache.d.ts +35 -0
  372. package/dist/memory-cache.js +37 -0
  373. package/dist/memory-cache.js.map +1 -0
  374. package/dist/memory-lifecycle-ledger-utils.d.ts +13 -0
  375. package/dist/memory-lifecycle-ledger-utils.js +23 -0
  376. package/dist/memory-lifecycle-ledger-utils.js.map +1 -0
  377. package/dist/memory-projection-format.d.ts +4 -0
  378. package/dist/memory-projection-format.js +9 -0
  379. package/dist/memory-projection-format.js.map +1 -0
  380. package/dist/memory-projection-store-NxMkbocT.d.ts +221 -0
  381. package/dist/memory-projection-store.d.ts +3 -0
  382. package/dist/memory-projection-store.js +31 -0
  383. package/dist/memory-projection-store.js.map +1 -0
  384. package/dist/model-registry.d.ts +60 -0
  385. package/dist/model-registry.js +8 -0
  386. package/dist/model-registry.js.map +1 -0
  387. package/dist/native-knowledge.d.ts +94 -0
  388. package/dist/native-knowledge.js +26 -0
  389. package/dist/native-knowledge.js.map +1 -0
  390. package/dist/negative.d.ts +26 -0
  391. package/dist/negative.js +8 -0
  392. package/dist/negative.js.map +1 -0
  393. package/dist/objective-state-writers.d.ts +22 -0
  394. package/dist/objective-state-writers.js +313 -0
  395. package/dist/objective-state-writers.js.map +1 -0
  396. package/dist/objective-state.d.ts +75 -0
  397. package/dist/objective-state.js +17 -0
  398. package/dist/objective-state.js.map +1 -0
  399. package/dist/openai-chat-compat.d.ts +13 -0
  400. package/dist/openai-chat-compat.js +11 -0
  401. package/dist/openai-chat-compat.js.map +1 -0
  402. package/dist/operator-toolkit.d.ts +304 -0
  403. package/dist/operator-toolkit.js +41 -0
  404. package/dist/operator-toolkit.js.map +1 -0
  405. package/dist/opik-exporter.d.ts +72 -0
  406. package/dist/opik-exporter.js +361 -0
  407. package/dist/opik-exporter.js.map +1 -0
  408. package/dist/orchestrator-zTa-Qo-1.d.ts +1104 -0
  409. package/dist/orchestrator.d.ts +21 -0
  410. package/dist/orchestrator.js +145 -0
  411. package/dist/orchestrator.js.map +1 -0
  412. package/dist/policy-runtime.d.ts +37 -0
  413. package/dist/policy-runtime.js +13 -0
  414. package/dist/policy-runtime.js.map +1 -0
  415. package/dist/port-C1GZFv8h.d.ts +41 -0
  416. package/dist/profiling.d.ts +80 -0
  417. package/dist/profiling.js +10 -0
  418. package/dist/profiling.js.map +1 -0
  419. package/dist/qmd-recall-cache.d.ts +29 -0
  420. package/dist/qmd-recall-cache.js +13 -0
  421. package/dist/qmd-recall-cache.js.map +1 -0
  422. package/dist/qmd.d.ts +105 -0
  423. package/dist/qmd.js +13 -0
  424. package/dist/qmd.js.map +1 -0
  425. package/dist/recall-qos.d.ts +33 -0
  426. package/dist/recall-qos.js +10 -0
  427. package/dist/recall-qos.js.map +1 -0
  428. package/dist/recall-query-policy.d.ts +20 -0
  429. package/dist/recall-query-policy.js +11 -0
  430. package/dist/recall-query-policy.js.map +1 -0
  431. package/dist/recall-state.d.ts +113 -0
  432. package/dist/recall-state.js +12 -0
  433. package/dist/recall-state.js.map +1 -0
  434. package/dist/recall-tokenization.d.ts +4 -0
  435. package/dist/recall-tokenization.js +9 -0
  436. package/dist/recall-tokenization.js.map +1 -0
  437. package/dist/reconstruct.d.ts +16 -0
  438. package/dist/reconstruct.js +7 -0
  439. package/dist/reconstruct.js.map +1 -0
  440. package/dist/release-changelog.d.ts +7 -0
  441. package/dist/release-changelog.js +30 -0
  442. package/dist/release-changelog.js.map +1 -0
  443. package/dist/relevance.d.ts +18 -0
  444. package/dist/relevance.js +8 -0
  445. package/dist/relevance.js.map +1 -0
  446. package/dist/rerank.d.ts +57 -0
  447. package/dist/rerank.js +11 -0
  448. package/dist/rerank.js.map +1 -0
  449. package/dist/resolve-provider-secret.d.ts +16 -0
  450. package/dist/resolve-provider-secret.js +11 -0
  451. package/dist/resolve-provider-secret.js.map +1 -0
  452. package/dist/resume-bundles.d.ts +66 -0
  453. package/dist/resume-bundles.js +27 -0
  454. package/dist/resume-bundles.js.map +1 -0
  455. package/dist/retrieval-agents.d.ts +129 -0
  456. package/dist/retrieval-agents.js +23 -0
  457. package/dist/retrieval-agents.js.map +1 -0
  458. package/dist/retrieval.d.ts +19 -0
  459. package/dist/retrieval.js +10 -0
  460. package/dist/retrieval.js.map +1 -0
  461. package/dist/sanitize.d.ts +9 -0
  462. package/dist/sanitize.js +9 -0
  463. package/dist/sanitize.js.map +1 -0
  464. package/dist/schemas.d.ts +688 -0
  465. package/dist/schemas.js +51 -0
  466. package/dist/schemas.js.map +1 -0
  467. package/dist/sdk-compat.d.ts +21 -0
  468. package/dist/sdk-compat.js +28 -0
  469. package/dist/sdk-compat.js.map +1 -0
  470. package/dist/semantic-consolidation.d.ts +42 -0
  471. package/dist/semantic-consolidation.js +12 -0
  472. package/dist/semantic-consolidation.js.map +1 -0
  473. package/dist/semantic-rule-promotion.d.ts +28 -0
  474. package/dist/semantic-rule-promotion.js +17 -0
  475. package/dist/semantic-rule-promotion.js.map +1 -0
  476. package/dist/semantic-rule-verifier.d.ts +19 -0
  477. package/dist/semantic-rule-verifier.js +18 -0
  478. package/dist/semantic-rule-verifier.js.map +1 -0
  479. package/dist/session-integrity.d.ts +67 -0
  480. package/dist/session-integrity.js +11 -0
  481. package/dist/session-integrity.js.map +1 -0
  482. package/dist/session-observer-bands.d.ts +6 -0
  483. package/dist/session-observer-bands.js +9 -0
  484. package/dist/session-observer-bands.js.map +1 -0
  485. package/dist/session-observer-state.d.ts +40 -0
  486. package/dist/session-observer-state.js +11 -0
  487. package/dist/session-observer-state.js.map +1 -0
  488. package/dist/signal.d.ts +6 -0
  489. package/dist/signal.js +9 -0
  490. package/dist/signal.js.map +1 -0
  491. package/dist/storage.d.ts +453 -0
  492. package/dist/storage.js +24 -0
  493. package/dist/storage.js.map +1 -0
  494. package/dist/store-contract.d.ts +10 -0
  495. package/dist/store-contract.js +21 -0
  496. package/dist/store-contract.js.map +1 -0
  497. package/dist/summarizer.d.ts +35 -0
  498. package/dist/summarizer.js +17 -0
  499. package/dist/summarizer.js.map +1 -0
  500. package/dist/summary-snapshot.d.ts +8 -0
  501. package/dist/summary-snapshot.js +13 -0
  502. package/dist/summary-snapshot.js.map +1 -0
  503. package/dist/temporal-index.d.ts +139 -0
  504. package/dist/temporal-index.js +29 -0
  505. package/dist/temporal-index.js.map +1 -0
  506. package/dist/threading.d.ts +62 -0
  507. package/dist/threading.js +8 -0
  508. package/dist/threading.js.map +1 -0
  509. package/dist/tier-migration.d.ts +44 -0
  510. package/dist/tier-migration.js +7 -0
  511. package/dist/tier-migration.js.map +1 -0
  512. package/dist/tier-routing.d.ts +21 -0
  513. package/dist/tier-routing.js +10 -0
  514. package/dist/tier-routing.js.map +1 -0
  515. package/dist/tmt.d.ts +79 -0
  516. package/dist/tmt.js +29 -0
  517. package/dist/tmt.js.map +1 -0
  518. package/dist/tokens.d.ts +24 -0
  519. package/dist/tokens.js +21 -0
  520. package/dist/tokens.js.map +1 -0
  521. package/dist/topics.d.ts +29 -0
  522. package/dist/topics.js +9 -0
  523. package/dist/topics.js.map +1 -0
  524. package/dist/transcript.d.ts +171 -0
  525. package/dist/transcript.js +9 -0
  526. package/dist/transcript.js.map +1 -0
  527. package/dist/trust-zones.d.ts +170 -0
  528. package/dist/trust-zones.js +32 -0
  529. package/dist/trust-zones.js.map +1 -0
  530. package/dist/types.d.ts +1243 -0
  531. package/dist/types.js +9 -0
  532. package/dist/types.js.map +1 -0
  533. package/dist/utility-learner.d.ts +59 -0
  534. package/dist/utility-learner.js +17 -0
  535. package/dist/utility-learner.js.map +1 -0
  536. package/dist/utility-runtime.d.ts +21 -0
  537. package/dist/utility-runtime.js +16 -0
  538. package/dist/utility-runtime.js.map +1 -0
  539. package/dist/utility-telemetry.d.ts +68 -0
  540. package/dist/utility-telemetry.js +17 -0
  541. package/dist/utility-telemetry.js.map +1 -0
  542. package/dist/verified-recall.d.ts +17 -0
  543. package/dist/verified-recall.js +19 -0
  544. package/dist/verified-recall.js.map +1 -0
  545. package/dist/version-utils.d.ts +4 -0
  546. package/dist/version-utils.js +7 -0
  547. package/dist/version-utils.js.map +1 -0
  548. package/dist/work-product-ledger.d.ts +65 -0
  549. package/dist/work-product-ledger.js +18 -0
  550. package/dist/work-product-ledger.js.map +1 -0
  551. package/package.json +58 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts","../src/transfer/export-json.ts","../src/transfer/constants.ts","../src/transfer/fs-utils.ts","../src/transfer/export-md.ts","../src/transfer/backup.ts","../src/transfer/export-sqlite.ts","../src/transfer/sqlite-schema.ts","../src/transfer/import-json.ts","../src/transfer/types.ts","../src/transfer/import-sqlite.ts","../src/transfer/import-md.ts","../src/transfer/autodetect.ts","../src/replay/runner.ts","../src/replay/normalizers/shared.ts","../src/replay/normalizers/chatgpt.ts","../src/replay/normalizers/claude.ts","../src/replay/normalizers/openclaw.ts","../src/maintenance/archive-observations.ts","../src/maintenance/rebuild-memory-lifecycle-ledger.ts","../src/maintenance/backup-stamp.ts","../src/maintenance/rebuild-memory-projection.ts","../src/maintenance/rebuild-observations.ts","../src/maintenance/observation-ledger-utils.ts","../src/maintenance/migrate-observations.ts","../src/network/tailscale.ts","../src/network/webdav.ts","../src/compat/checks.ts"],"sourcesContent":["import path from \"node:path\";\nimport { access, readFile, readdir, unlink } from \"node:fs/promises\";\nimport { createHash } from \"node:crypto\";\nimport type { Readable, Writable } from \"node:stream\";\nimport type { Orchestrator } from \"./orchestrator.js\";\nimport { ThreadingManager } from \"./threading.js\";\nimport type {\n BehaviorSignalEvent,\n ContinuityIncidentRecord,\n MemoryActionEvent,\n MemoryFile,\n MemoryStatus,\n TranscriptEntry,\n} from \"./types.js\";\nimport { chunkContent } from \"./chunking.js\";\nimport { rescoreMemoryImportance } from \"./importance.js\";\nimport { exportJsonBundle } from \"./transfer/export-json.js\";\nimport { exportMarkdownBundle } from \"./transfer/export-md.js\";\nimport { backupMemoryDir } from \"./transfer/backup.js\";\nimport { exportSqlite } from \"./transfer/export-sqlite.js\";\nimport { importJsonBundle } from \"./transfer/import-json.js\";\nimport { importSqlite } from \"./transfer/import-sqlite.js\";\nimport { importMarkdownBundle } from \"./transfer/import-md.js\";\nimport { detectImportFormat } from \"./transfer/autodetect.js\";\nimport { buildReplayNormalizerRegistry, clampBatchSize, runReplay, type ReplayRunSummary } from \"./replay/runner.js\";\nimport { chatgptReplayNormalizer } from \"./replay/normalizers/chatgpt.js\";\nimport { claudeReplayNormalizer } from \"./replay/normalizers/claude.js\";\nimport { openclawReplayNormalizer } from \"./replay/normalizers/openclaw.js\";\nimport { isReplaySource, normalizeReplaySessionKey, type ReplaySource, type ReplayTurn } from \"./replay/types.js\";\nimport { archiveObservations } from \"./maintenance/archive-observations.js\";\nimport { rebuildMemoryLifecycleLedger } from \"./maintenance/rebuild-memory-lifecycle-ledger.js\";\nimport {\n listMemoryGovernanceRuns,\n readMemoryGovernanceRunArtifact,\n restoreMemoryGovernanceRun,\n runMemoryGovernance,\n} from \"./maintenance/memory-governance.js\";\nimport {\n rebuildMemoryProjection,\n repairMemoryProjection,\n verifyMemoryProjection,\n} from \"./maintenance/rebuild-memory-projection.js\";\nimport { rebuildObservations } from \"./maintenance/rebuild-observations.js\";\nimport { migrateObservations } from \"./maintenance/migrate-observations.js\";\nimport {\n listNamespaces,\n runNamespaceMigration,\n verifyNamespaces,\n} from \"./namespaces/migrate.js\";\nimport {\n runBenchmarkRecall,\n runOperatorConfigReview,\n runOperatorDoctor,\n runOperatorInventory,\n runOperatorRepair,\n runOperatorSetup,\n type BenchmarkRecallReport,\n type OperatorConfigReviewReport,\n type OperatorDoctorReport,\n type OperatorInventoryReport,\n type OperatorRepairReport,\n type OperatorSetupReport,\n} from \"./operator-toolkit.js\";\nimport { WorkStorage } from \"./work/storage.js\";\nimport type { WorkProjectStatus, WorkTaskPriority, WorkTaskStatus } from \"./work/types.js\";\nimport {\n selectRouteRule,\n validateRouteTarget,\n type RoutePatternType,\n type RouteRule,\n type RouteTarget,\n} from \"./routing/engine.js\";\nimport { RoutingRulesStore } from \"./routing/store.js\";\nimport { TailscaleHelper, type TailscaleSyncOptions } from \"./network/tailscale.js\";\nimport { WebDavServer } from \"./network/webdav.js\";\nimport { GraphDashboardServer, type DashboardStatus } from \"./dashboard-runtime.js\";\nimport { EngramAccessService } from \"./access-service.js\";\nimport { EngramAccessHttpServer } from \"./access-http.js\";\nimport { EngramMcpServer } from \"./access-mcp.js\";\nimport { runCompatChecks } from \"./compat/checks.js\";\nimport { parseConfig } from \"./config.js\";\nimport type { CompatReport, CompatRunner } from \"./compat/types.js\";\nimport {\n createEvalBaselineSnapshot,\n getEvalHarnessStatus,\n importEvalBenchmarkPack,\n type EvalBaselineSnapshot,\n type EvalBaselineDeltaReport,\n type EvalBenchmarkPackSummary,\n type EvalCiGateReport,\n type EvalStoredBaselineCiGateReport,\n type EvalHarnessStatus,\n runEvalBaselineDeltaReport,\n runEvalBenchmarkCiGate,\n runEvalStoredBaselineCiGate,\n validateEvalBenchmarkPack,\n} from \"./evals.js\";\nimport { analyzeGraphHealth, type GraphHealthReport } from \"./graph.js\";\nimport {\n getCausalTrajectoryStoreStatus,\n type CausalTrajectoryStoreStatus,\n} from \"./causal-trajectory.js\";\nimport {\n getAbstractionNodeStoreStatus,\n type AbstractionNodeStoreStatus,\n} from \"./abstraction-nodes.js\";\nimport {\n getCueAnchorStoreStatus,\n type CueAnchorStoreStatus,\n} from \"./cue-anchors.js\";\nimport {\n searchHarmonicRetrieval,\n type HarmonicRetrievalResult,\n} from \"./harmonic-retrieval.js\";\nimport {\n searchVerifiedEpisodes,\n type VerifiedEpisodeResult,\n} from \"./verified-recall.js\";\nimport {\n searchVerifiedSemanticRules,\n type VerifiedSemanticRuleResult,\n} from \"./semantic-rule-verifier.js\";\nimport {\n applyCommitmentLedgerLifecycle,\n getCommitmentLedgerStatus,\n recordCommitmentLedgerEntry,\n transitionCommitmentLedgerEntryState,\n type CommitmentLedgerEntry,\n type CommitmentLedgerLifecycleResult,\n type CommitmentLedgerStatus,\n} from \"./commitment-ledger.js\";\nimport {\n getWorkProductLedgerStatus,\n recordWorkProductLedgerEntry,\n searchWorkProductLedgerEntries,\n type WorkProductLedgerEntry,\n type WorkProductLedgerSearchResult,\n type WorkProductLedgerStatus,\n} from \"./work-product-ledger.js\";\nimport {\n getUtilityTelemetryStatus,\n recordUtilityTelemetryEvent,\n type UtilityTelemetryEvent,\n type UtilityTelemetryStatus,\n} from \"./utility-telemetry.js\";\nimport {\n getUtilityLearningStatus,\n learnUtilityPromotionWeights,\n type UtilityLearningResult,\n type UtilityLearningStatus,\n} from \"./utility-learner.js\";\nimport {\n buildResumeBundleFromState,\n getResumeBundleStatus,\n recordResumeBundle,\n type ResumeBundle,\n type ResumeBundleStatus,\n} from \"./resume-bundles.js\";\nimport {\n promoteSemanticRuleFromMemory,\n type SemanticRulePromotionReport,\n} from \"./semantic-rule-promotion.js\";\nimport { getObjectiveStateStoreStatus, type ObjectiveStateStoreStatus } from \"./objective-state.js\";\nimport {\n getTrustZoneStoreStatus,\n promoteTrustZoneRecord,\n seedTrustZoneDemoDataset,\n type TrustZoneDemoSeedResult,\n type TrustZoneName,\n type TrustZonePromotionResult,\n type TrustZoneStoreStatus,\n} from \"./trust-zones.js\";\nimport {\n analyzeSessionIntegrity,\n applySessionRepair,\n planSessionRepair,\n type SessionIntegrityReport,\n type SessionRepairApplyResult,\n type SessionRepairPlan,\n} from \"./session-integrity.js\";\nimport type { TierMigrationCycleSummary, TierMigrationStatusSnapshot } from \"./recall-state.js\";\nimport {\n readRuntimePolicySnapshot as readPolicyRuntimeSnapshot,\n sanitizeRuntimePolicyValues,\n type RuntimePolicyValues,\n} from \"./policy-runtime.js\";\nimport { resolveHomeDir } from \"./runtime/env.js\";\n\ninterface CliApi {\n registerCli(\n handler: (opts: { program: CliProgram }) => void,\n options: { commands: string[] },\n ): void;\n}\n\ninterface CliProgram {\n command(name: string): CliCommand;\n}\n\ninterface CliCommand {\n description(desc: string): CliCommand;\n option(flags: string, desc: string, defaultValue?: string): CliCommand;\n requiredOption(flags: string, desc: string, defaultValue?: string): CliCommand;\n argument(name: string, desc: string): CliCommand;\n action(fn: (...args: unknown[]) => Promise<void> | void): CliCommand;\n command(name: string): CliCommand;\n}\n\ninterface EngramMcpServerLike {\n runStdio(input: Readable, output: Writable): Promise<void>;\n}\n\nexport interface DedupeCandidate {\n path: string;\n content: string;\n frontmatter: {\n id?: string;\n confidence?: number;\n updated?: string;\n created?: string;\n };\n}\n\nexport interface ExactDedupePlan {\n groups: number;\n duplicates: number;\n keepPaths: string[];\n deletePaths: string[];\n}\n\nfunction rankCandidateForKeep(a: DedupeCandidate, b: DedupeCandidate): number {\n const aConfidence = typeof a.frontmatter.confidence === \"number\" ? a.frontmatter.confidence : 0;\n const bConfidence = typeof b.frontmatter.confidence === \"number\" ? b.frontmatter.confidence : 0;\n if (aConfidence !== bConfidence) return bConfidence - aConfidence;\n\n const aTs = Date.parse(a.frontmatter.updated ?? a.frontmatter.created ?? \"\");\n const bTs = Date.parse(b.frontmatter.updated ?? b.frontmatter.created ?? \"\");\n const aTime = Number.isNaN(aTs) ? 0 : aTs;\n const bTime = Number.isNaN(bTs) ? 0 : bTs;\n if (aTime !== bTime) return bTime - aTime;\n\n return a.path.localeCompare(b.path);\n}\n\nfunction buildDedupePlan(\n memories: DedupeCandidate[],\n keyBuilder: (memory: DedupeCandidate) => string,\n): ExactDedupePlan {\n const byKey = new Map<string, DedupeCandidate[]>();\n for (const memory of memories) {\n const key = keyBuilder(memory);\n if (key.length === 0) continue;\n const existing = byKey.get(key);\n if (existing) {\n existing.push(memory);\n } else {\n byKey.set(key, [memory]);\n }\n }\n\n const keepPaths: string[] = [];\n const deletePaths: string[] = [];\n let groups = 0;\n let duplicates = 0;\n\n for (const entries of byKey.values()) {\n if (entries.length <= 1) continue;\n groups += 1;\n duplicates += entries.length - 1;\n const ranked = [...entries].sort(rankCandidateForKeep);\n keepPaths.push(ranked[0].path);\n for (let i = 1; i < ranked.length; i += 1) {\n deletePaths.push(ranked[i].path);\n }\n }\n\n return { groups, duplicates, keepPaths, deletePaths };\n}\n\nfunction normalizeAggressiveBody(content: string): string {\n return content\n .normalize(\"NFKC\")\n .replace(/\\[([^\\]]+)\\]\\([^)]+\\)/g, \"$1\")\n .replace(/[`*_~>#-]+/g, \" \")\n .replace(/[^\\p{L}\\p{N}\\s]/gu, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n .toLowerCase();\n}\n\nexport function planExactDuplicateDeletions(memories: DedupeCandidate[]): ExactDedupePlan {\n return buildDedupePlan(memories, (memory) => memory.content.trim());\n}\n\nexport function planAggressiveDuplicateDeletions(memories: DedupeCandidate[]): ExactDedupePlan {\n return buildDedupePlan(memories, (memory) => normalizeAggressiveBody(memory.content));\n}\n\nexport interface ReplayCliCommandOptions {\n source: ReplaySource;\n inputPath: string;\n from?: string;\n to?: string;\n dryRun?: boolean;\n startOffset?: number;\n maxTurns?: number;\n batchSize?: number;\n defaultSessionKey?: string;\n strict?: boolean;\n runConsolidation?: boolean;\n extractionIdleTimeoutMs?: number;\n}\n\nexport interface ReplayCliOrchestrator {\n ingestReplayBatch(\n turns: ReplayTurn[],\n options?: { deadlineMs?: number },\n ): Promise<void>;\n waitForConsolidationIdle(timeoutMs?: number): Promise<boolean>;\n runConsolidationNow(): Promise<{ memoriesProcessed: number; merged: number; invalidated: number }>;\n}\n\nexport interface ArchiveObservationsCliCommandOptions {\n memoryDir: string;\n retentionDays?: number;\n write?: boolean;\n now?: Date;\n}\n\nexport interface RebuildObservationsCliCommandOptions {\n memoryDir: string;\n write?: boolean;\n now?: Date;\n}\n\nexport interface RebuildMemoryLifecycleLedgerCliCommandOptions {\n memoryDir: string;\n write?: boolean;\n now?: Date;\n}\n\nexport interface RebuildMemoryProjectionCliCommandOptions {\n memoryDir: string;\n defaultNamespace?: string;\n write?: boolean;\n now?: Date;\n updatedAfter?: string;\n updatedBefore?: string;\n}\n\nexport interface VerifyMemoryProjectionCliCommandOptions {\n memoryDir: string;\n defaultNamespace?: string;\n updatedAfter?: string;\n updatedBefore?: string;\n}\n\nexport interface RepairMemoryProjectionCliCommandOptions {\n memoryDir: string;\n defaultNamespace?: string;\n write?: boolean;\n now?: Date;\n updatedAfter?: string;\n updatedBefore?: string;\n}\n\nexport interface MemoryTimelineCliCommandOptions {\n memoryDir: string;\n memoryId: string;\n limit?: number;\n}\n\nexport interface MemoryGovernanceCliCommandOptions {\n memoryDir: string;\n mode: \"shadow\" | \"apply\";\n now?: Date;\n maxMemories?: number;\n batchSize?: number;\n recentDays?: number;\n}\n\nexport interface MemoryGovernanceReportCliCommandOptions {\n memoryDir: string;\n runId?: string;\n}\n\nexport interface MemoryGovernanceRestoreCliCommandOptions {\n memoryDir: string;\n runId: string;\n now?: Date;\n}\n\nexport interface MemoryReviewDispositionCliCommandOptions {\n memoryDir: string;\n memoryId: string;\n status: Extract<MemoryStatus, \"active\" | \"pending_review\" | \"rejected\" | \"quarantined\">;\n reasonCode?: string;\n now?: Date;\n}\n\nexport interface MigrateObservationsCliCommandOptions {\n memoryDir: string;\n write?: boolean;\n now?: Date;\n}\n\ninterface WorkTaskPatchInput {\n title?: string;\n description?: string;\n status?: WorkTaskStatus;\n priority?: WorkTaskPriority;\n owner?: string | null;\n assignee?: string | null;\n projectId?: string | null;\n tags?: string[];\n dueAt?: string | null;\n}\n\ninterface WorkProjectPatchInput {\n name?: string;\n description?: string;\n status?: WorkProjectStatus;\n owner?: string | null;\n tags?: string[];\n}\n\nexport interface WorkTaskCliCommandOptions {\n memoryDir: string;\n action: \"create\" | \"get\" | \"list\" | \"update\" | \"transition\" | \"delete\" | \"link\";\n id?: string;\n title?: string;\n description?: string;\n status?: WorkTaskStatus;\n priority?: WorkTaskPriority;\n owner?: string;\n assignee?: string;\n projectId?: string;\n tags?: string[];\n dueAt?: string;\n patch?: WorkTaskPatchInput;\n}\n\nexport interface WorkProjectCliCommandOptions {\n memoryDir: string;\n action: \"create\" | \"get\" | \"list\" | \"update\" | \"delete\";\n id?: string;\n name?: string;\n description?: string;\n status?: WorkProjectStatus;\n owner?: string;\n tags?: string[];\n patch?: WorkProjectPatchInput;\n}\n\nexport interface RouteCliCommandOptions {\n memoryDir: string;\n stateFile?: string;\n action: \"list\" | \"add\" | \"remove\" | \"test\";\n pattern?: string;\n patternType?: RoutePatternType;\n priority?: number;\n targetRaw?: string;\n text?: string;\n id?: string;\n}\n\ninterface TailscaleHelperLike {\n status(): Promise<{\n available: boolean;\n running: boolean;\n backendState?: string;\n version?: string;\n selfHostname?: string;\n selfIp?: string;\n }>;\n syncDirectory(options: TailscaleSyncOptions): Promise<void>;\n}\n\nexport interface ConversationIndexHealthCliOrchestrator {\n getConversationIndexHealth(): Promise<{\n enabled: boolean;\n backend: \"qmd\" | \"faiss\";\n status: \"ok\" | \"degraded\" | \"disabled\";\n chunkDocCount: number;\n lastUpdateAt: string | null;\n qmdAvailable?: boolean;\n faiss?: {\n ok: boolean;\n status: \"ok\" | \"degraded\" | \"error\";\n indexPath: string;\n message?: string;\n manifest?: {\n version: number;\n modelId: string;\n normalizedModelId: string;\n dimension: number;\n chunkCount: number;\n updatedAt: string;\n lastSuccessfulRebuildAt: string;\n };\n };\n }>;\n inspectConversationIndex(): Promise<{\n enabled: boolean;\n backend: \"qmd\" | \"faiss\";\n status: \"ok\" | \"degraded\" | \"disabled\";\n available: boolean;\n indexPath: string;\n supportsIncrementalUpdate: boolean;\n message?: string;\n chunkDocCount: number;\n lastUpdateAt: string | null;\n metadata: {\n chunkCount: number | null;\n qmdAvailable?: boolean;\n debugStatus?: string;\n hasIndex?: boolean;\n hasMetadata?: boolean;\n hasManifest?: boolean;\n manifest?: {\n version: number;\n modelId: string;\n normalizedModelId: string;\n dimension: number;\n chunkCount: number;\n updatedAt: string;\n lastSuccessfulRebuildAt: string;\n };\n };\n }>;\n rebuildConversationIndex(\n sessionKey?: string,\n hours?: number,\n opts?: { embed?: boolean },\n ): Promise<{\n chunks: number;\n skipped: boolean;\n reason?: string;\n embedded?: boolean;\n rebuilt?: boolean;\n }>;\n}\n\nexport interface GraphHealthCliCommandOptions {\n memoryDir: string;\n entityGraphEnabled?: boolean;\n timeGraphEnabled?: boolean;\n causalGraphEnabled?: boolean;\n includeRepairGuidance?: boolean;\n}\n\nexport interface SessionIntegrityCliCommandOptions {\n memoryDir: string;\n}\n\nexport interface SessionRepairCliCommandOptions {\n memoryDir: string;\n apply?: boolean;\n dryRun?: boolean;\n allowSessionFileRepair?: boolean;\n sessionFilesDir?: string;\n}\n\nexport interface TierMigrationCliOrchestrator {\n getTierMigrationStatus(): Promise<TierMigrationStatusSnapshot>;\n runTierMigrationNow(options?: { dryRun?: boolean; limit?: number }): Promise<TierMigrationCycleSummary>;\n}\n\nexport interface MemoryActionAuditCliCommandOptions {\n namespace?: string;\n limit?: number;\n}\n\nexport interface MemoryActionAuditCliNamespaceSummary {\n namespace: string;\n eventCount: number;\n actions: Record<string, number>;\n outcomes: Record<string, number>;\n policyDecisions: Record<string, number>;\n}\n\nexport interface MemoryActionAuditCliReport {\n generatedAt: string;\n limit: number;\n namespaces: MemoryActionAuditCliNamespaceSummary[];\n totals: {\n eventCount: number;\n actions: Record<string, number>;\n outcomes: Record<string, number>;\n policyDecisions: Record<string, number>;\n };\n}\n\ninterface MemoryActionAuditCliOrchestrator {\n config: {\n defaultNamespace: string;\n sharedNamespace: string;\n namespacesEnabled: boolean;\n namespacePolicies: Array<{ name: string }>;\n };\n getStorage(namespace?: string): Promise<{\n readMemoryActionEvents(limit?: number): Promise<MemoryActionEvent[]>;\n }>;\n}\n\nexport interface TailscaleStatusCliCommandOptions {\n helper?: TailscaleHelperLike;\n timeoutMs?: number;\n}\n\nexport interface TailscaleSyncCliCommandOptions extends TailscaleSyncOptions {\n helper?: TailscaleHelperLike;\n}\n\ninterface WebDavServerLike {\n start(): Promise<{ running: boolean; host: string; port: number; rootCount: number }>;\n stop(): Promise<void>;\n status(): { running: boolean; host: string; port: number; rootCount: number };\n}\n\nexport interface WebDavServeCliCommandOptions {\n enabled?: boolean;\n host?: string;\n port?: number;\n allowlistDirs: string[];\n authUsername?: string;\n authPassword?: string;\n createServer?: (options: {\n enabled?: boolean;\n host?: string;\n port: number;\n allowlistDirs: string[];\n auth?: {\n username: string;\n password: string;\n };\n }) => Promise<WebDavServerLike>;\n}\n\nexport interface CompatCliCommandOptions {\n repoRoot?: string;\n strict?: boolean;\n runner?: CompatRunner;\n now?: Date;\n}\n\ninterface DashboardServerLike {\n start(): Promise<DashboardStatus>;\n stop(): Promise<void>;\n status(): DashboardStatus;\n}\n\ninterface AccessHttpServerLike {\n start(): Promise<{ running: boolean; host: string; port: number; maxBodyBytes: number }>;\n stop(): Promise<void>;\n status(): { running: boolean; host: string; port: number; maxBodyBytes: number };\n}\n\nexport interface DashboardStartCliCommandOptions {\n memoryDir: string;\n host?: string;\n port?: number;\n publicDir?: string;\n createServer?: (options: {\n memoryDir: string;\n host?: string;\n port?: number;\n publicDir?: string;\n }) => DashboardServerLike;\n}\n\nexport interface AccessHttpServeCliCommandOptions {\n service: EngramAccessService;\n enabled?: boolean;\n host?: string;\n port?: number;\n authToken?: string;\n principal?: string;\n maxBodyBytes?: number;\n trustPrincipalHeader?: boolean;\n createServer?: (options: {\n service: EngramAccessService;\n host?: string;\n port?: number;\n authToken?: string;\n principal?: string;\n maxBodyBytes?: number;\n trustPrincipalHeader?: boolean;\n }) => AccessHttpServerLike;\n}\n\nexport function resolveAccessPrincipalOverride(\n explicitPrincipal: unknown,\n configuredPrincipal?: string,\n): string | undefined {\n if (typeof explicitPrincipal === \"string\" && explicitPrincipal.trim().length > 0) {\n return explicitPrincipal.trim();\n }\n return configuredPrincipal?.trim() || undefined;\n}\n\nlet activeWebDavServer: WebDavServerLike | null = null;\nlet webDavOperationChain: Promise<void> = Promise.resolve();\nlet activeDashboardServer: DashboardServerLike | null = null;\nlet dashboardOperationChain: Promise<void> = Promise.resolve();\nlet activeAccessHttpServer: AccessHttpServerLike | null = null;\nlet accessHttpOperationChain: Promise<void> = Promise.resolve();\n\nasync function withWebDavLock<T>(operation: () => Promise<T>): Promise<T> {\n const run = webDavOperationChain.then(operation, operation);\n webDavOperationChain = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n}\n\nasync function withDashboardLock<T>(operation: () => Promise<T>): Promise<T> {\n const run = dashboardOperationChain.then(operation, operation);\n dashboardOperationChain = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n}\n\nasync function withAccessHttpLock<T>(operation: () => Promise<T>): Promise<T> {\n const run = accessHttpOperationChain.then(operation, operation);\n accessHttpOperationChain = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n}\n\nfunction isRoutePatternType(value: string | undefined): value is RoutePatternType {\n return value === \"keyword\" || value === \"regex\";\n}\n\nfunction parseRouteTargetCliArg(raw: string): RouteTarget {\n const trimmed = raw.trim();\n if (trimmed.length === 0) throw new Error(\"missing target\");\n\n if (trimmed.startsWith(\"{\")) {\n const parsed = JSON.parse(trimmed) as RouteTarget;\n if (!parsed || typeof parsed !== \"object\") throw new Error(\"invalid target JSON\");\n return parsed;\n }\n\n const target: RouteTarget = {};\n for (const token of trimmed.split(\",\")) {\n const part = token.trim();\n if (part.length === 0) continue;\n const normalized = part.replace(\":\", \"=\");\n const [rawKey, ...rawValueParts] = normalized.split(\"=\");\n if (!rawKey || rawValueParts.length === 0) continue;\n const key = rawKey.trim().toLowerCase();\n const value = rawValueParts.join(\"=\").trim();\n if (value.length === 0) continue;\n if (key === \"category\") {\n target.category = value as RouteTarget[\"category\"];\n continue;\n }\n if (key === \"namespace\") {\n target.namespace = value;\n }\n }\n\n return target;\n}\n\nfunction normalizeNullableCliValue(value: string | undefined): string | null | undefined {\n if (value === undefined) return undefined;\n const trimmed = value.trim();\n if (trimmed.length === 0 || trimmed.toLowerCase() === \"null\") return null;\n return trimmed;\n}\n\nfunction parseTagsCsv(raw: string | undefined, preserveEmpty = false): string[] | undefined {\n if (raw === undefined) return undefined;\n const tags = raw\n .split(\",\")\n .map((tag) => tag.trim())\n .filter((tag) => tag.length > 0);\n if (tags.length === 0) {\n return preserveEmpty ? [] : undefined;\n }\n return tags;\n}\n\nfunction isWorkTaskStatus(value: string | undefined): value is \"todo\" | \"in_progress\" | \"blocked\" | \"done\" | \"cancelled\" {\n return value === \"todo\" || value === \"in_progress\" || value === \"blocked\" || value === \"done\" || value === \"cancelled\";\n}\n\nfunction isWorkTaskPriority(value: string | undefined): value is \"low\" | \"medium\" | \"high\" {\n return value === \"low\" || value === \"medium\" || value === \"high\";\n}\n\nfunction isWorkProjectStatus(value: string | undefined): value is \"active\" | \"on_hold\" | \"completed\" | \"archived\" {\n return value === \"active\" || value === \"on_hold\" || value === \"completed\" || value === \"archived\";\n}\n\nexport async function runArchiveObservationsCliCommand(\n options: ArchiveObservationsCliCommandOptions,\n) {\n return archiveObservations({\n memoryDir: options.memoryDir,\n retentionDays: options.retentionDays,\n dryRun: options.write !== true,\n now: options.now,\n });\n}\n\nexport async function runRebuildObservationsCliCommand(\n options: RebuildObservationsCliCommandOptions,\n) {\n return rebuildObservations({\n memoryDir: options.memoryDir,\n dryRun: options.write !== true,\n now: options.now,\n });\n}\n\nexport async function runRebuildMemoryLifecycleLedgerCliCommand(\n options: RebuildMemoryLifecycleLedgerCliCommandOptions,\n) {\n return rebuildMemoryLifecycleLedger({\n memoryDir: options.memoryDir,\n dryRun: options.write !== true,\n now: options.now,\n });\n}\n\nexport async function runRebuildMemoryProjectionCliCommand(\n options: RebuildMemoryProjectionCliCommandOptions,\n) {\n return rebuildMemoryProjection({\n memoryDir: options.memoryDir,\n defaultNamespace: options.defaultNamespace,\n dryRun: options.write !== true,\n now: options.now,\n updatedAfter: options.updatedAfter,\n updatedBefore: options.updatedBefore,\n });\n}\n\nexport async function runVerifyMemoryProjectionCliCommand(\n options: VerifyMemoryProjectionCliCommandOptions,\n) {\n return verifyMemoryProjection({\n memoryDir: options.memoryDir,\n defaultNamespace: options.defaultNamespace,\n updatedAfter: options.updatedAfter,\n updatedBefore: options.updatedBefore,\n });\n}\n\nexport async function runRepairMemoryProjectionCliCommand(\n options: RepairMemoryProjectionCliCommandOptions,\n) {\n return repairMemoryProjection({\n memoryDir: options.memoryDir,\n defaultNamespace: options.defaultNamespace,\n dryRun: options.write !== true,\n now: options.now,\n updatedAfter: options.updatedAfter,\n updatedBefore: options.updatedBefore,\n });\n}\n\nexport async function runMemoryTimelineCliCommand(\n options: MemoryTimelineCliCommandOptions,\n) {\n const storage = new (await import(\"./storage.js\")).StorageManager(options.memoryDir);\n return storage.getMemoryTimeline(options.memoryId, options.limit);\n}\n\nexport async function runMemoryGovernanceCliCommand(\n options: MemoryGovernanceCliCommandOptions,\n) {\n return runMemoryGovernance({\n memoryDir: options.memoryDir,\n mode: options.mode,\n now: options.now,\n maxMemories: options.maxMemories,\n batchSize: options.batchSize,\n recentDays: options.recentDays,\n });\n}\n\nexport async function runMemoryGovernanceReportCliCommand(\n options: MemoryGovernanceReportCliCommandOptions,\n) {\n const runId = options.runId ?? (await listMemoryGovernanceRuns(options.memoryDir))[0];\n if (!runId) {\n throw new Error(\"no governance runs found\");\n }\n return readMemoryGovernanceRunArtifact(options.memoryDir, runId);\n}\n\nexport async function runMemoryGovernanceRestoreCliCommand(\n options: MemoryGovernanceRestoreCliCommandOptions,\n) {\n return restoreMemoryGovernanceRun({\n memoryDir: options.memoryDir,\n runId: options.runId,\n now: options.now,\n });\n}\n\nexport async function runMemoryReviewDispositionCliCommand(\n options: MemoryReviewDispositionCliCommandOptions,\n) {\n const storage = new (await import(\"./storage.js\")).StorageManager(options.memoryDir);\n const memory = await storage.getMemoryById(options.memoryId);\n if (!memory) throw new Error(`memory not found: ${options.memoryId}`);\n const updated = await storage.writeMemoryFrontmatter(memory, {\n status: options.status,\n updated: (options.now ?? new Date()).toISOString(),\n }, {\n actor: \"cli.review-disposition\",\n reasonCode: options.reasonCode,\n ruleVersion: \"memory-governance.v1\",\n });\n if (!updated) {\n throw new Error(`failed to update memory disposition: ${options.memoryId}`);\n }\n return {\n memoryId: options.memoryId,\n status: options.status,\n reasonCode: options.reasonCode,\n };\n}\n\nexport async function runMigrateObservationsCliCommand(\n options: MigrateObservationsCliCommandOptions,\n) {\n return migrateObservations({\n memoryDir: options.memoryDir,\n dryRun: options.write !== true,\n now: options.now,\n });\n}\n\nexport async function runConversationIndexHealthCliCommand(\n orchestrator: ConversationIndexHealthCliOrchestrator,\n): Promise<{\n enabled: boolean;\n backend: \"qmd\" | \"faiss\";\n status: \"ok\" | \"degraded\" | \"disabled\";\n chunkDocCount: number;\n lastUpdateAt: string | null;\n qmdAvailable?: boolean;\n faiss?: {\n ok: boolean;\n status: \"ok\" | \"degraded\" | \"error\";\n indexPath: string;\n message?: string;\n manifest?: {\n version: number;\n modelId: string;\n normalizedModelId: string;\n dimension: number;\n chunkCount: number;\n updatedAt: string;\n lastSuccessfulRebuildAt: string;\n };\n };\n}> {\n return orchestrator.getConversationIndexHealth();\n}\n\nexport async function runConversationIndexInspectCliCommand(\n orchestrator: ConversationIndexHealthCliOrchestrator,\n) {\n return orchestrator.inspectConversationIndex();\n}\n\nexport async function runConversationIndexRebuildCliCommand(\n orchestrator: ConversationIndexHealthCliOrchestrator,\n options: {\n sessionKey?: string;\n hours?: number;\n embed?: boolean;\n },\n) {\n return orchestrator.rebuildConversationIndex(\n options.sessionKey,\n options.hours,\n { embed: options.embed },\n );\n}\n\nexport async function runGraphHealthCliCommand(\n options: GraphHealthCliCommandOptions,\n): Promise<GraphHealthReport> {\n return analyzeGraphHealth(options.memoryDir, {\n entityGraphEnabled: options.entityGraphEnabled,\n timeGraphEnabled: options.timeGraphEnabled,\n causalGraphEnabled: options.causalGraphEnabled,\n includeRepairGuidance: options.includeRepairGuidance,\n });\n}\n\nexport async function runBenchmarkStatusCliCommand(options: {\n memoryDir: string;\n evalStoreDir?: string;\n evalHarnessEnabled: boolean;\n evalShadowModeEnabled: boolean;\n benchmarkBaselineSnapshotsEnabled: boolean;\n memoryRedTeamBenchEnabled: boolean;\n}): Promise<EvalHarnessStatus> {\n return getEvalHarnessStatus({\n memoryDir: options.memoryDir,\n evalStoreDir: options.evalStoreDir,\n enabled: options.evalHarnessEnabled,\n shadowModeEnabled: options.evalShadowModeEnabled,\n baselineSnapshotsEnabled: options.benchmarkBaselineSnapshotsEnabled,\n memoryRedTeamBenchEnabled: options.memoryRedTeamBenchEnabled,\n });\n}\n\nexport async function runBenchmarkBaselineSnapshotCliCommand(options: {\n memoryDir: string;\n evalStoreDir?: string;\n benchmarkBaselineSnapshotsEnabled: boolean;\n snapshotId: string;\n createdAt?: string;\n notes?: string;\n gitRef?: string;\n}): Promise<{ targetPath: string; snapshot: EvalBaselineSnapshot }> {\n return createEvalBaselineSnapshot({\n memoryDir: options.memoryDir,\n evalStoreDir: options.evalStoreDir,\n baselineSnapshotsEnabled: options.benchmarkBaselineSnapshotsEnabled,\n snapshotId: options.snapshotId,\n createdAt: options.createdAt,\n notes: options.notes,\n gitRef: options.gitRef,\n });\n}\n\nexport async function runBenchmarkValidateCliCommand(options: {\n path: string;\n memoryRedTeamBenchEnabled: boolean;\n}): Promise<EvalBenchmarkPackSummary> {\n return validateEvalBenchmarkPack(options.path, {\n memoryRedTeamBenchEnabled: options.memoryRedTeamBenchEnabled,\n });\n}\n\nexport async function runBenchmarkImportCliCommand(options: {\n path: string;\n memoryDir: string;\n evalStoreDir?: string;\n force?: boolean;\n memoryRedTeamBenchEnabled: boolean;\n}): Promise<EvalBenchmarkPackSummary & { targetDir: string; overwritten: boolean }> {\n return importEvalBenchmarkPack({\n sourcePath: options.path,\n memoryDir: options.memoryDir,\n evalStoreDir: options.evalStoreDir,\n force: options.force === true,\n memoryRedTeamBenchEnabled: options.memoryRedTeamBenchEnabled,\n });\n}\n\nexport async function runBenchmarkCiGateCliCommand(options: {\n baseEvalStoreDir: string;\n candidateEvalStoreDir: string;\n}): Promise<EvalCiGateReport> {\n return runEvalBenchmarkCiGate({\n baseEvalStoreDir: options.baseEvalStoreDir,\n candidateEvalStoreDir: options.candidateEvalStoreDir,\n });\n}\n\nexport async function runBenchmarkStoredBaselineCiGateCliCommand(options: {\n baseEvalStoreDir: string;\n candidateEvalStoreDir: string;\n snapshotId: string;\n}): Promise<EvalStoredBaselineCiGateReport> {\n return runEvalStoredBaselineCiGate({\n baseEvalStoreDir: options.baseEvalStoreDir,\n candidateEvalStoreDir: options.candidateEvalStoreDir,\n snapshotId: options.snapshotId,\n });\n}\n\nexport async function runBenchmarkBaselineReportCliCommand(options: {\n memoryDir: string;\n evalStoreDir?: string;\n benchmarkDeltaReporterEnabled: boolean;\n snapshotId: string;\n}): Promise<EvalBaselineDeltaReport> {\n return runEvalBaselineDeltaReport({\n memoryDir: options.memoryDir,\n evalStoreDir: options.evalStoreDir,\n benchmarkDeltaReporterEnabled: options.benchmarkDeltaReporterEnabled,\n snapshotId: options.snapshotId,\n });\n}\n\nexport async function runObjectiveStateStatusCliCommand(options: {\n memoryDir: string;\n objectiveStateStoreDir?: string;\n objectiveStateMemoryEnabled: boolean;\n objectiveStateSnapshotWritesEnabled: boolean;\n}): Promise<ObjectiveStateStoreStatus> {\n return getObjectiveStateStoreStatus({\n memoryDir: options.memoryDir,\n objectiveStateStoreDir: options.objectiveStateStoreDir,\n enabled: options.objectiveStateMemoryEnabled,\n writesEnabled: options.objectiveStateSnapshotWritesEnabled,\n });\n}\n\nexport async function runCausalTrajectoryStatusCliCommand(options: {\n memoryDir: string;\n causalTrajectoryStoreDir?: string;\n causalTrajectoryMemoryEnabled: boolean;\n}): Promise<CausalTrajectoryStoreStatus> {\n return getCausalTrajectoryStoreStatus({\n memoryDir: options.memoryDir,\n causalTrajectoryStoreDir: options.causalTrajectoryStoreDir,\n enabled: options.causalTrajectoryMemoryEnabled,\n });\n}\n\nexport async function runTrustZoneStatusCliCommand(options: {\n memoryDir: string;\n trustZoneStoreDir?: string;\n trustZonesEnabled: boolean;\n quarantinePromotionEnabled: boolean;\n memoryPoisoningDefenseEnabled: boolean;\n}): Promise<TrustZoneStoreStatus> {\n return getTrustZoneStoreStatus({\n memoryDir: options.memoryDir,\n trustZoneStoreDir: options.trustZoneStoreDir,\n enabled: options.trustZonesEnabled,\n promotionEnabled: options.quarantinePromotionEnabled,\n poisoningDefenseEnabled: options.memoryPoisoningDefenseEnabled,\n });\n}\n\nexport async function runAbstractionNodeStatusCliCommand(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n harmonicRetrievalEnabled: boolean;\n abstractionAnchorsEnabled: boolean;\n}): Promise<AbstractionNodeStoreStatus> {\n return getAbstractionNodeStoreStatus({\n memoryDir: options.memoryDir,\n abstractionNodeStoreDir: options.abstractionNodeStoreDir,\n enabled: options.harmonicRetrievalEnabled,\n anchorsEnabled: options.abstractionAnchorsEnabled,\n });\n}\n\nexport async function runCueAnchorStatusCliCommand(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n harmonicRetrievalEnabled: boolean;\n abstractionAnchorsEnabled: boolean;\n}): Promise<CueAnchorStoreStatus> {\n return getCueAnchorStoreStatus({\n memoryDir: options.memoryDir,\n abstractionNodeStoreDir: options.abstractionNodeStoreDir,\n enabled: options.harmonicRetrievalEnabled,\n anchorsEnabled: options.abstractionAnchorsEnabled,\n });\n}\n\nexport async function runHarmonicSearchCliCommand(options: {\n memoryDir: string;\n abstractionNodeStoreDir?: string;\n harmonicRetrievalEnabled: boolean;\n abstractionAnchorsEnabled: boolean;\n query: string;\n maxResults?: number;\n sessionKey?: string;\n}): Promise<HarmonicRetrievalResult[]> {\n if (!options.harmonicRetrievalEnabled) return [];\n return searchHarmonicRetrieval({\n memoryDir: options.memoryDir,\n abstractionNodeStoreDir: options.abstractionNodeStoreDir,\n query: options.query,\n maxResults: Math.max(1, Math.floor(options.maxResults ?? 3)),\n sessionKey: options.sessionKey,\n anchorsEnabled: options.abstractionAnchorsEnabled,\n });\n}\n\nexport async function runVerifiedRecallSearchCliCommand(options: {\n memoryDir: string;\n verifiedRecallEnabled: boolean;\n query: string;\n maxResults?: number;\n boxRecallDays?: number;\n}): Promise<VerifiedEpisodeResult[]> {\n if (!options.verifiedRecallEnabled) return [];\n return searchVerifiedEpisodes({\n memoryDir: options.memoryDir,\n query: options.query,\n maxResults: Math.max(1, Math.floor(options.maxResults ?? 3)),\n boxRecallDays: options.boxRecallDays,\n });\n}\n\nexport async function runSemanticRulePromoteCliCommand(options: {\n memoryDir: string;\n semanticRulePromotionEnabled: boolean;\n sourceMemoryId: string;\n dryRun?: boolean;\n}): Promise<SemanticRulePromotionReport> {\n return promoteSemanticRuleFromMemory({\n memoryDir: options.memoryDir,\n enabled: options.semanticRulePromotionEnabled,\n sourceMemoryId: options.sourceMemoryId,\n dryRun: options.dryRun,\n });\n}\n\nexport async function runCompoundingPromoteCliCommand(options: {\n memoryDir: string;\n compoundingEnabled: boolean;\n compoundingSemanticEnabled: boolean;\n weekId: string;\n candidateId: string;\n dryRun?: boolean;\n}) {\n const { CompoundingEngine } = await import(\"./compounding/engine.js\");\n const config = parseConfig({\n memoryDir: options.memoryDir,\n qmdEnabled: false,\n sharedContextEnabled: false,\n compoundingEnabled: options.compoundingEnabled,\n compoundingSemanticEnabled: options.compoundingSemanticEnabled,\n });\n const engine = new CompoundingEngine(config);\n return engine.promoteCandidate({\n weekId: options.weekId,\n candidateId: options.candidateId,\n dryRun: options.dryRun,\n });\n}\n\nexport async function runSemanticRuleVerifyCliCommand(options: {\n memoryDir: string;\n semanticRuleVerificationEnabled: boolean;\n query: string;\n maxResults?: number;\n}): Promise<VerifiedSemanticRuleResult[]> {\n if (!options.semanticRuleVerificationEnabled) return [];\n return searchVerifiedSemanticRules({\n memoryDir: options.memoryDir,\n query: options.query,\n maxResults: Math.max(1, Math.floor(options.maxResults ?? 3)),\n });\n}\n\nexport async function runWorkProductStatusCliCommand(options: {\n memoryDir: string;\n workProductLedgerDir?: string;\n creationMemoryEnabled: boolean;\n}): Promise<WorkProductLedgerStatus> {\n return getWorkProductLedgerStatus({\n memoryDir: options.memoryDir,\n workProductLedgerDir: options.workProductLedgerDir,\n enabled: options.creationMemoryEnabled,\n });\n}\n\nexport async function runUtilityTelemetryStatusCliCommand(options: {\n memoryDir: string;\n memoryUtilityLearningEnabled: boolean;\n promotionByOutcomeEnabled: boolean;\n}): Promise<UtilityTelemetryStatus> {\n return getUtilityTelemetryStatus({\n memoryDir: options.memoryDir,\n enabled: options.memoryUtilityLearningEnabled,\n promotionByOutcomeEnabled: options.promotionByOutcomeEnabled,\n });\n}\n\nexport async function runUtilityTelemetryRecordCliCommand(options: {\n memoryDir: string;\n memoryUtilityLearningEnabled: boolean;\n event: UtilityTelemetryEvent;\n}): Promise<string | null> {\n if (!options.memoryUtilityLearningEnabled) return null;\n return recordUtilityTelemetryEvent({\n memoryDir: options.memoryDir,\n event: options.event,\n });\n}\n\nexport async function runUtilityLearningStatusCliCommand(options: {\n memoryDir: string;\n memoryUtilityLearningEnabled: boolean;\n promotionByOutcomeEnabled: boolean;\n}): Promise<UtilityLearningStatus> {\n return getUtilityLearningStatus({\n memoryDir: options.memoryDir,\n enabled: options.memoryUtilityLearningEnabled,\n promotionByOutcomeEnabled: options.promotionByOutcomeEnabled,\n });\n}\n\nexport async function runUtilityLearningCliCommand(options: {\n memoryDir: string;\n memoryUtilityLearningEnabled: boolean;\n learningWindowDays?: number;\n minEventCount?: number;\n maxWeightMagnitude?: number;\n}): Promise<UtilityLearningResult> {\n return learnUtilityPromotionWeights({\n memoryDir: options.memoryDir,\n enabled: options.memoryUtilityLearningEnabled,\n learningWindowDays: options.learningWindowDays ?? 14,\n minEventCount: options.minEventCount ?? 3,\n maxWeightMagnitude: options.maxWeightMagnitude ?? 0.35,\n });\n}\n\nexport async function runWorkProductRecordCliCommand(options: {\n memoryDir: string;\n workProductLedgerDir?: string;\n creationMemoryEnabled: boolean;\n entry: WorkProductLedgerEntry;\n}): Promise<string | null> {\n if (!options.creationMemoryEnabled) return null;\n return recordWorkProductLedgerEntry({\n memoryDir: options.memoryDir,\n workProductLedgerDir: options.workProductLedgerDir,\n entry: options.entry,\n });\n}\n\nexport async function runWorkProductRecallSearchCliCommand(options: {\n memoryDir: string;\n workProductLedgerDir?: string;\n creationMemoryEnabled: boolean;\n workProductRecallEnabled: boolean;\n query: string;\n maxResults?: number;\n sessionKey?: string;\n}): Promise<WorkProductLedgerSearchResult[]> {\n if (!options.creationMemoryEnabled || !options.workProductRecallEnabled) return [];\n return searchWorkProductLedgerEntries({\n memoryDir: options.memoryDir,\n workProductLedgerDir: options.workProductLedgerDir,\n query: options.query,\n maxResults: Math.max(1, Math.floor(options.maxResults ?? 3)),\n sessionKey: options.sessionKey,\n });\n}\n\nexport async function runResumeBundleStatusCliCommand(options: {\n memoryDir: string;\n resumeBundleDir?: string;\n creationMemoryEnabled: boolean;\n resumeBundlesEnabled: boolean;\n}): Promise<ResumeBundleStatus> {\n return getResumeBundleStatus({\n memoryDir: options.memoryDir,\n resumeBundleDir: options.resumeBundleDir,\n enabled: options.creationMemoryEnabled && options.resumeBundlesEnabled,\n });\n}\n\nexport async function runResumeBundleRecordCliCommand(options: {\n memoryDir: string;\n resumeBundleDir?: string;\n creationMemoryEnabled: boolean;\n resumeBundlesEnabled: boolean;\n bundle: ResumeBundle;\n}): Promise<string | null> {\n if (!options.creationMemoryEnabled || !options.resumeBundlesEnabled) return null;\n return recordResumeBundle({\n memoryDir: options.memoryDir,\n resumeBundleDir: options.resumeBundleDir,\n bundle: options.bundle,\n });\n}\n\nexport async function runResumeBundleBuildCliCommand(options: {\n memoryDir: string;\n resumeBundleDir?: string;\n objectiveStateStoreDir?: string;\n workProductLedgerDir?: string;\n commitmentLedgerDir?: string;\n creationMemoryEnabled: boolean;\n resumeBundlesEnabled: boolean;\n transcriptEnabled: boolean;\n objectiveStateMemoryEnabled: boolean;\n commitmentLedgerEnabled: boolean;\n bundleId: string;\n recordedAt: string;\n sessionKey: string;\n scope: string;\n}): Promise<{ bundle: ResumeBundle; filePath: string } | null> {\n if (!options.creationMemoryEnabled || !options.resumeBundlesEnabled) {\n return null;\n }\n\n const bundle = await buildResumeBundleFromState({\n memoryDir: options.memoryDir,\n sessionKey: options.sessionKey,\n bundleId: options.bundleId,\n recordedAt: options.recordedAt,\n scope: options.scope,\n transcriptEnabled: options.transcriptEnabled,\n objectiveStateMemoryEnabled: options.objectiveStateMemoryEnabled,\n objectiveStateStoreDir: options.objectiveStateStoreDir,\n creationMemoryEnabled: options.creationMemoryEnabled,\n workProductLedgerDir: options.workProductLedgerDir,\n commitmentLedgerEnabled: options.commitmentLedgerEnabled,\n commitmentLedgerDir: options.commitmentLedgerDir,\n });\n\n const filePath = await recordResumeBundle({\n memoryDir: options.memoryDir,\n resumeBundleDir: options.resumeBundleDir,\n bundle,\n });\n\n return { bundle, filePath };\n}\n\nexport async function runCommitmentStatusCliCommand(options: {\n memoryDir: string;\n commitmentLedgerDir?: string;\n creationMemoryEnabled: boolean;\n commitmentLedgerEnabled: boolean;\n commitmentLifecycleEnabled?: boolean;\n commitmentStaleDays?: number;\n commitmentDecayDays?: number;\n now?: string;\n}): Promise<CommitmentLedgerStatus> {\n return getCommitmentLedgerStatus({\n memoryDir: options.memoryDir,\n commitmentLedgerDir: options.commitmentLedgerDir,\n enabled: options.creationMemoryEnabled && options.commitmentLedgerEnabled,\n lifecycleEnabled:\n options.creationMemoryEnabled &&\n options.commitmentLedgerEnabled &&\n options.commitmentLifecycleEnabled === true,\n staleDays: options.commitmentStaleDays,\n decayDays: options.commitmentDecayDays,\n now: options.now,\n });\n}\n\nexport async function runCommitmentRecordCliCommand(options: {\n memoryDir: string;\n commitmentLedgerDir?: string;\n creationMemoryEnabled: boolean;\n commitmentLedgerEnabled: boolean;\n entry: CommitmentLedgerEntry;\n}): Promise<string | null> {\n if (!options.creationMemoryEnabled || !options.commitmentLedgerEnabled) return null;\n return recordCommitmentLedgerEntry({\n memoryDir: options.memoryDir,\n commitmentLedgerDir: options.commitmentLedgerDir,\n entry: options.entry,\n });\n}\n\nexport async function runCommitmentSetStateCliCommand(options: {\n memoryDir: string;\n commitmentLedgerDir?: string;\n creationMemoryEnabled: boolean;\n commitmentLedgerEnabled: boolean;\n commitmentLifecycleEnabled: boolean;\n entryId: string;\n nextState: CommitmentLedgerEntry[\"state\"];\n changedAt: string;\n}): Promise<CommitmentLedgerEntry | null> {\n if (\n !options.creationMemoryEnabled ||\n !options.commitmentLedgerEnabled ||\n !options.commitmentLifecycleEnabled\n ) {\n return null;\n }\n\n return transitionCommitmentLedgerEntryState({\n memoryDir: options.memoryDir,\n commitmentLedgerDir: options.commitmentLedgerDir,\n entryId: options.entryId,\n nextState: options.nextState,\n changedAt: options.changedAt,\n });\n}\n\nexport async function runCommitmentLifecycleCliCommand(options: {\n memoryDir: string;\n commitmentLedgerDir?: string;\n creationMemoryEnabled: boolean;\n commitmentLedgerEnabled: boolean;\n commitmentLifecycleEnabled: boolean;\n commitmentDecayDays: number;\n now?: string;\n}): Promise<CommitmentLedgerLifecycleResult | null> {\n if (\n !options.creationMemoryEnabled ||\n !options.commitmentLedgerEnabled ||\n !options.commitmentLifecycleEnabled\n ) {\n return null;\n }\n\n return applyCommitmentLedgerLifecycle({\n memoryDir: options.memoryDir,\n commitmentLedgerDir: options.commitmentLedgerDir,\n enabled: true,\n decayDays: options.commitmentDecayDays,\n now: options.now,\n });\n}\n\nexport async function runTrustZonePromoteCliCommand(options: {\n memoryDir: string;\n trustZoneStoreDir?: string;\n trustZonesEnabled: boolean;\n quarantinePromotionEnabled: boolean;\n memoryPoisoningDefenseEnabled: boolean;\n sourceRecordId: string;\n targetZone: TrustZoneName;\n promotionReason: string;\n recordedAt?: string;\n summary?: string;\n dryRun?: boolean;\n}): Promise<TrustZonePromotionResult & { dryRun: boolean }> {\n const result = await promoteTrustZoneRecord({\n memoryDir: options.memoryDir,\n trustZoneStoreDir: options.trustZoneStoreDir,\n enabled: options.trustZonesEnabled,\n promotionEnabled: options.quarantinePromotionEnabled,\n poisoningDefenseEnabled: options.memoryPoisoningDefenseEnabled,\n sourceRecordId: options.sourceRecordId,\n targetZone: options.targetZone,\n recordedAt: options.recordedAt ?? new Date().toISOString(),\n promotionReason: options.promotionReason,\n summary: options.summary,\n dryRun: options.dryRun === true,\n });\n\n return {\n ...result,\n dryRun: options.dryRun === true,\n };\n}\n\nexport async function runTrustZoneDemoSeedCliCommand(options: {\n memoryDir: string;\n trustZoneStoreDir?: string;\n trustZonesEnabled: boolean;\n scenario?: string;\n recordedAt?: string;\n dryRun?: boolean;\n}): Promise<TrustZoneDemoSeedResult> {\n return seedTrustZoneDemoDataset({\n memoryDir: options.memoryDir,\n trustZoneStoreDir: options.trustZoneStoreDir,\n enabled: options.trustZonesEnabled,\n scenario: options.scenario,\n recordedAt: options.recordedAt,\n dryRun: options.dryRun === true,\n });\n}\n\nexport async function runSessionCheckCliCommand(\n options: SessionIntegrityCliCommandOptions,\n): Promise<SessionIntegrityReport> {\n return analyzeSessionIntegrity({ memoryDir: options.memoryDir });\n}\n\nexport async function runSessionRepairCliCommand(\n options: SessionRepairCliCommandOptions,\n): Promise<{ report: SessionIntegrityReport; plan: SessionRepairPlan; applyResult: SessionRepairApplyResult }> {\n const report = await analyzeSessionIntegrity({ memoryDir: options.memoryDir });\n const dryRun = options.apply !== true || options.dryRun === true;\n const plan = planSessionRepair({\n report,\n dryRun,\n allowSessionFileRepair: options.allowSessionFileRepair === true,\n sessionFilesDir: options.sessionFilesDir,\n });\n const applyResult = await applySessionRepair({ plan });\n return { report, plan, applyResult };\n}\n\nexport async function runTierStatusCliCommand(\n orchestrator: TierMigrationCliOrchestrator,\n): Promise<TierMigrationStatusSnapshot> {\n return orchestrator.getTierMigrationStatus();\n}\n\nexport async function runTierMigrateCliCommand(\n orchestrator: TierMigrationCliOrchestrator,\n options: { dryRun?: boolean; limit?: number } = {},\n): Promise<TierMigrationCycleSummary> {\n return orchestrator.runTierMigrationNow({\n dryRun: options.dryRun === true,\n limit: options.limit,\n });\n}\n\nconst MIGRATE_LIMIT_CAP = 2000;\nconst REEXTRACT_LIMIT_CAP = 500;\n\ntype MigrateMemoryStorage = {\n readAllMemories(): Promise<MemoryFile[]>;\n readArchivedMemories(): Promise<MemoryFile[]>;\n writeMemoryFrontmatter(memory: MemoryFile, patch: Partial<MemoryFile[\"frontmatter\"]>): Promise<boolean>;\n getChunksForParent(parentId: string): Promise<MemoryFile[]>;\n updateMemory(id: string, newContent: string): Promise<boolean>;\n updateMemoryFrontmatter(id: string, patch: Partial<MemoryFile[\"frontmatter\"]>): Promise<boolean>;\n writeChunk(\n parentId: string,\n chunkIndex: number,\n chunkTotal: number,\n category: MemoryFile[\"frontmatter\"][\"category\"],\n content: string,\n options?: {\n confidence?: number;\n tags?: string[];\n entityRef?: string;\n source?: string;\n importance?: MemoryFile[\"frontmatter\"][\"importance\"];\n intentGoal?: string;\n intentActionType?: string;\n intentEntityTypes?: string[];\n memoryKind?: MemoryFile[\"frontmatter\"][\"memoryKind\"];\n },\n ): Promise<string>;\n invalidateMemory(id: string): Promise<boolean>;\n appendReextractJobs(events: Array<{\n memoryId: string;\n model: string;\n requestedAt: string;\n source: \"cli-migrate\";\n }>): Promise<number>;\n};\n\nexport interface MigrateCliOrchestrator {\n config: {\n defaultNamespace: string;\n };\n getStorage(namespace?: string): Promise<MigrateMemoryStorage>;\n}\n\nexport interface MigrateCliReport {\n action: \"normalize-frontmatter\" | \"rescore-importance\" | \"rechunk\" | \"reextract\";\n dryRun: boolean;\n scanned: number;\n changed: number;\n queued: number;\n limit: number;\n model?: string;\n}\n\nfunction clampMigrateLimit(limit: number | undefined, cap: number, fallback: number): number {\n if (typeof limit !== \"number\" || !Number.isFinite(limit)) return fallback;\n return Math.max(1, Math.min(cap, Math.floor(limit)));\n}\n\nasync function readMigrateCandidateMemories(\n storage: MigrateMemoryStorage,\n options: { includeArchived: boolean },\n): Promise<MemoryFile[]> {\n const merged = new Map<string, MemoryFile>();\n const addMany = (items: MemoryFile[]) => {\n for (const item of items) {\n if (!item.frontmatter?.id) continue;\n merged.set(item.path, item);\n }\n };\n addMany(await storage.readAllMemories());\n if (options.includeArchived) {\n addMany(await storage.readArchivedMemories());\n }\n return [...merged.values()]\n .sort((a, b) => a.path.localeCompare(b.path));\n}\n\nfunction sameImportance(a: MemoryFile[\"frontmatter\"][\"importance\"], b: MemoryFile[\"frontmatter\"][\"importance\"]): boolean {\n if (!a && !b) return true;\n if (!a || !b) return false;\n if (Math.abs(a.score - b.score) > 0.000001) return false;\n if (a.level !== b.level) return false;\n if (a.reasons.join(\"|\") !== b.reasons.join(\"|\")) return false;\n if (a.keywords.join(\"|\") !== b.keywords.join(\"|\")) return false;\n return true;\n}\n\nfunction sameChunkContent(existing: MemoryFile[], desired: string[]): boolean {\n if (existing.length !== desired.length) return false;\n for (let i = 0; i < desired.length; i += 1) {\n const current = existing[i]?.content?.trim() ?? \"\";\n if (current !== desired[i]?.trim()) {\n return false;\n }\n }\n return true;\n}\n\nexport async function runMigrateNormalizeFrontmatterCliCommand(\n orchestrator: MigrateCliOrchestrator,\n options: { write?: boolean; limit?: number } = {},\n): Promise<MigrateCliReport> {\n const limit = clampMigrateLimit(options.limit, MIGRATE_LIMIT_CAP, 200);\n const storage = await orchestrator.getStorage(orchestrator.config.defaultNamespace);\n const candidates = (await readMigrateCandidateMemories(storage, { includeArchived: true }))\n .slice(0, limit);\n if (options.write === true) {\n for (const memory of candidates) {\n await storage.writeMemoryFrontmatter(memory, {});\n }\n }\n return {\n action: \"normalize-frontmatter\",\n dryRun: options.write !== true,\n scanned: candidates.length,\n changed: candidates.length,\n queued: 0,\n limit,\n };\n}\n\nexport async function runMigrateRescoreImportanceCliCommand(\n orchestrator: MigrateCliOrchestrator,\n options: { write?: boolean; limit?: number } = {},\n): Promise<MigrateCliReport> {\n const limit = clampMigrateLimit(options.limit, MIGRATE_LIMIT_CAP, 200);\n const storage = await orchestrator.getStorage(orchestrator.config.defaultNamespace);\n const candidates = (await readMigrateCandidateMemories(storage, { includeArchived: true }))\n .slice(0, limit);\n let changed = 0;\n for (const memory of candidates) {\n const nextImportance = rescoreMemoryImportance(memory);\n if (sameImportance(memory.frontmatter.importance, nextImportance)) continue;\n changed += 1;\n if (options.write === true) {\n await storage.writeMemoryFrontmatter(memory, {\n importance: nextImportance,\n updated: new Date().toISOString(),\n });\n }\n }\n\n return {\n action: \"rescore-importance\",\n dryRun: options.write !== true,\n scanned: candidates.length,\n changed,\n queued: 0,\n limit,\n };\n}\n\nexport async function runMigrateRechunkCliCommand(\n orchestrator: MigrateCliOrchestrator,\n options: { write?: boolean; limit?: number } = {},\n): Promise<MigrateCliReport> {\n const limit = clampMigrateLimit(options.limit, MIGRATE_LIMIT_CAP, 200);\n const storage = await orchestrator.getStorage(orchestrator.config.defaultNamespace);\n const candidates = (await readMigrateCandidateMemories(storage, { includeArchived: false }))\n .filter((memory) => memory.frontmatter.parentId === undefined)\n .slice(0, limit);\n\n let changed = 0;\n for (const memory of candidates) {\n const existing = await storage.getChunksForParent(memory.frontmatter.id);\n const chunked = chunkContent(memory.content);\n if (!chunked.chunked) {\n if (existing.length === 0) continue;\n changed += 1;\n if (options.write === true) {\n for (const stale of existing) {\n await storage.invalidateMemory(stale.frontmatter.id);\n }\n }\n continue;\n }\n const desired = chunked.chunks.map((chunk) => chunk.content);\n if (sameChunkContent(existing, desired)) continue;\n changed += 1;\n if (options.write !== true) continue;\n\n const total = chunked.chunks.length;\n for (const chunk of chunked.chunks) {\n const existingChunk = existing[chunk.index];\n if (existingChunk) {\n await storage.updateMemory(existingChunk.frontmatter.id, chunk.content);\n await storage.updateMemoryFrontmatter(existingChunk.frontmatter.id, {\n chunkIndex: chunk.index,\n chunkTotal: total,\n updated: new Date().toISOString(),\n });\n continue;\n }\n await storage.writeChunk(\n memory.frontmatter.id,\n chunk.index,\n total,\n memory.frontmatter.category,\n chunk.content,\n {\n confidence: memory.frontmatter.confidence,\n tags: memory.frontmatter.tags,\n entityRef: memory.frontmatter.entityRef,\n source: \"migration-rechunk\",\n importance: memory.frontmatter.importance,\n intentGoal: memory.frontmatter.intentGoal,\n intentActionType: memory.frontmatter.intentActionType,\n intentEntityTypes: memory.frontmatter.intentEntityTypes,\n memoryKind: memory.frontmatter.memoryKind,\n },\n );\n }\n for (let idx = total; idx < existing.length; idx += 1) {\n const stale = existing[idx];\n if (stale?.frontmatter?.id) {\n await storage.invalidateMemory(stale.frontmatter.id);\n }\n }\n }\n\n return {\n action: \"rechunk\",\n dryRun: options.write !== true,\n scanned: candidates.length,\n changed,\n queued: 0,\n limit,\n };\n}\n\nexport async function runMigrateReextractCliCommand(\n orchestrator: MigrateCliOrchestrator,\n options: { model: string; write?: boolean; limit?: number },\n): Promise<MigrateCliReport> {\n const model = options.model.trim();\n if (model.length === 0) {\n throw new Error(\"missing --model for migrate reextract\");\n }\n const limit = clampMigrateLimit(options.limit, REEXTRACT_LIMIT_CAP, 100);\n const storage = await orchestrator.getStorage(orchestrator.config.defaultNamespace);\n const candidates = (await readMigrateCandidateMemories(storage, { includeArchived: false }))\n .filter((memory) => memory.frontmatter.parentId === undefined);\n const selected = candidates.slice(0, limit);\n let queued = 0;\n if (options.write === true && selected.length > 0) {\n queued = await storage.appendReextractJobs(\n selected.map((memory) => ({\n memoryId: memory.frontmatter.id,\n model,\n requestedAt: new Date().toISOString(),\n source: \"cli-migrate\",\n })),\n );\n }\n\n return {\n action: \"reextract\",\n dryRun: options.write !== true,\n scanned: selected.length,\n changed: selected.length,\n queued,\n limit,\n model,\n };\n}\n\ninterface RuntimePolicySnapshotPayload {\n version: number;\n updatedAt: string;\n values: RuntimePolicyValues;\n sourceAdjustmentCount: number;\n}\n\ninterface PolicySignalContribution {\n signalType: string;\n direction: string;\n count: number;\n lastSeenAt: string;\n}\n\nexport interface PolicyStatusCliReport {\n generatedAt: string;\n autoTuneEnabled: boolean;\n current: (RuntimePolicySnapshotPayload & { policyVersion: string }) | null;\n previous: (RuntimePolicySnapshotPayload & { policyVersion: string }) | null;\n topContributingSignals: PolicySignalContribution[];\n}\n\nexport interface PolicyDiffEntry {\n parameter: string;\n previousValue: number | null;\n nextValue: number | null;\n delta: number;\n evidenceCount: number;\n}\n\nexport interface PolicyDiffCliReport {\n generatedAt: string;\n since: string;\n sinceIso: string;\n currentPolicyVersion: string | null;\n previousPolicyVersion: string | null;\n deltas: PolicyDiffEntry[];\n topContributingSignals: PolicySignalContribution[];\n}\n\nexport interface PolicyRollbackCliReport {\n generatedAt: string;\n rolledBack: boolean;\n current: (RuntimePolicySnapshotPayload & { policyVersion: string }) | null;\n}\n\nexport interface PolicyTuningCliOrchestrator {\n config: {\n memoryDir: string;\n defaultNamespace: string;\n sharedNamespace: string;\n namespacesEnabled: boolean;\n behaviorLoopAutoTuneEnabled: boolean;\n behaviorLoopLearningWindowDays: number;\n lifecycleArchiveDecayThreshold: number;\n recencyWeight: number;\n lifecyclePromoteHeatThreshold: number;\n lifecycleStaleDecayThreshold: number;\n cronRecallInstructionHeavyTokenCap: number;\n namespacePolicies: Array<{ name: string }>;\n };\n getStorage(namespace?: string): Promise<{\n readBehaviorSignals(limit?: number): Promise<BehaviorSignalEvent[]>;\n }>;\n rollbackBehaviorRuntimePolicy(): Promise<boolean>;\n}\n\nfunction effectivePolicyValuesForVersion(\n values: RuntimePolicyValues,\n config: PolicyTuningCliOrchestrator[\"config\"],\n): Required<RuntimePolicyValues> {\n const candidate: RuntimePolicyValues = {\n recencyWeight: values.recencyWeight ?? config.recencyWeight,\n lifecyclePromoteHeatThreshold: values.lifecyclePromoteHeatThreshold ?? config.lifecyclePromoteHeatThreshold,\n lifecycleStaleDecayThreshold: values.lifecycleStaleDecayThreshold ?? config.lifecycleStaleDecayThreshold,\n cronRecallInstructionHeavyTokenCap:\n values.cronRecallInstructionHeavyTokenCap ?? config.cronRecallInstructionHeavyTokenCap,\n };\n const normalized = sanitizeRuntimePolicyValues(candidate, {\n maxStaleDecayThreshold: config.lifecycleArchiveDecayThreshold,\n });\n return {\n recencyWeight: normalized.recencyWeight ?? config.recencyWeight,\n lifecyclePromoteHeatThreshold:\n normalized.lifecyclePromoteHeatThreshold ?? config.lifecyclePromoteHeatThreshold,\n lifecycleStaleDecayThreshold:\n normalized.lifecycleStaleDecayThreshold ?? config.lifecycleStaleDecayThreshold,\n cronRecallInstructionHeavyTokenCap:\n normalized.cronRecallInstructionHeavyTokenCap ?? config.cronRecallInstructionHeavyTokenCap,\n };\n}\n\nfunction policyVersionForValues(\n values: RuntimePolicyValues,\n config: PolicyTuningCliOrchestrator[\"config\"],\n): string {\n const normalized = effectivePolicyValuesForVersion(values, config);\n return createHash(\"sha256\")\n .update(JSON.stringify(normalized))\n .digest(\"hex\")\n .slice(0, 12);\n}\n\nasync function readRuntimePolicySnapshot(\n config: PolicyTuningCliOrchestrator[\"config\"],\n fileName: string,\n): Promise<RuntimePolicySnapshotPayload | null> {\n const filePath = path.join(config.memoryDir, \"state\", fileName);\n const snapshot = await readPolicyRuntimeSnapshot(filePath, {\n maxStaleDecayThreshold: config.lifecycleArchiveDecayThreshold,\n });\n if (!snapshot) return null;\n return {\n version: snapshot.version,\n updatedAt: snapshot.updatedAt,\n values: snapshot.values,\n sourceAdjustmentCount: Math.max(0, Math.floor(snapshot.sourceAdjustmentCount)),\n };\n}\n\nfunction parseSinceDurationMs(since: string): number {\n const trimmed = since.trim().toLowerCase();\n const match = trimmed.match(/^(\\d+)\\s*([mhd])$/);\n if (!match) {\n throw new Error(`invalid --since value: ${since} (expected formats like 30m, 12h, 7d)`);\n }\n const amount = Number.parseInt(match[1] ?? \"0\", 10);\n const unit = match[2];\n if (!Number.isFinite(amount) || amount <= 0) {\n throw new Error(`invalid --since value: ${since}`);\n }\n if (unit === \"m\") return amount * 60 * 1000;\n if (unit === \"h\") return amount * 60 * 60 * 1000;\n return amount * 24 * 60 * 60 * 1000;\n}\n\nfunction resolvePolicySignalNamespaces(orchestrator: PolicyTuningCliOrchestrator): string[] {\n const names = new Set<string>([orchestrator.config.defaultNamespace]);\n if (orchestrator.config.namespacesEnabled) {\n names.add(orchestrator.config.sharedNamespace);\n for (const policy of orchestrator.config.namespacePolicies) {\n if (policy?.name) names.add(policy.name);\n }\n }\n return [...names];\n}\n\nasync function readBehaviorSignalsForNamespaces(\n orchestrator: PolicyTuningCliOrchestrator,\n limitPerNamespace: number,\n): Promise<BehaviorSignalEvent[]> {\n const namespaces = resolvePolicySignalNamespaces(orchestrator);\n const merged: BehaviorSignalEvent[] = [];\n for (const namespace of namespaces) {\n const storage = await orchestrator.getStorage(namespace);\n const events = await storage.readBehaviorSignals(limitPerNamespace);\n merged.push(...events);\n }\n return merged;\n}\n\nfunction summarizeTopSignals(\n signals: BehaviorSignalEvent[],\n cutoffIso?: string,\n topN: number = 5,\n): PolicySignalContribution[] {\n const cutoffMs = cutoffIso ? Date.parse(cutoffIso) : Number.NEGATIVE_INFINITY;\n const grouped = new Map<string, PolicySignalContribution>();\n for (const signal of signals) {\n const ts = Date.parse(signal.timestamp);\n if (Number.isFinite(cutoffMs) && (!Number.isFinite(ts) || ts < cutoffMs)) continue;\n const key = `${signal.signalType}:${signal.direction}`;\n const existing = grouped.get(key);\n if (existing) {\n existing.count += 1;\n if (signal.timestamp > existing.lastSeenAt) {\n existing.lastSeenAt = signal.timestamp;\n }\n } else {\n grouped.set(key, {\n signalType: signal.signalType,\n direction: signal.direction,\n count: 1,\n lastSeenAt: signal.timestamp,\n });\n }\n }\n\n return [...grouped.values()]\n .sort((a, b) => b.count - a.count || b.lastSeenAt.localeCompare(a.lastSeenAt))\n .slice(0, Math.max(1, topN));\n}\n\nexport async function runPolicyStatusCliCommand(\n orchestrator: PolicyTuningCliOrchestrator,\n): Promise<PolicyStatusCliReport> {\n const now = new Date();\n const current = await readRuntimePolicySnapshot(orchestrator.config, \"policy-runtime.json\");\n const previous = await readRuntimePolicySnapshot(orchestrator.config, \"policy-runtime.prev.json\");\n const signals = await readBehaviorSignalsForNamespaces(orchestrator, 1000);\n const defaultWindowMs = Math.max(0, orchestrator.config.behaviorLoopLearningWindowDays) * 24 * 60 * 60 * 1000;\n const cutoffIso = defaultWindowMs > 0 ? new Date(now.getTime() - defaultWindowMs).toISOString() : undefined;\n\n return {\n generatedAt: now.toISOString(),\n autoTuneEnabled: orchestrator.config.behaviorLoopAutoTuneEnabled,\n current: current\n ? {\n ...current,\n policyVersion: policyVersionForValues(current.values, orchestrator.config),\n }\n : null,\n previous: previous\n ? {\n ...previous,\n policyVersion: policyVersionForValues(previous.values, orchestrator.config),\n }\n : null,\n topContributingSignals: summarizeTopSignals(signals, cutoffIso),\n };\n}\n\nexport async function runPolicyDiffCliCommand(\n orchestrator: PolicyTuningCliOrchestrator,\n options: { since?: string } = {},\n): Promise<PolicyDiffCliReport> {\n const since = options.since?.trim() || \"7d\";\n const sinceMs = parseSinceDurationMs(since);\n const sinceIso = new Date(Date.now() - sinceMs).toISOString();\n const current = await readRuntimePolicySnapshot(orchestrator.config, \"policy-runtime.json\");\n const previous = await readRuntimePolicySnapshot(orchestrator.config, \"policy-runtime.prev.json\");\n const currentValues = current?.values ?? {};\n const previousValues = previous?.values ?? {};\n const parameterKeys = new Set<string>([\n ...Object.keys(currentValues),\n ...Object.keys(previousValues),\n ]);\n const deltas: PolicyDiffEntry[] = [];\n for (const parameter of parameterKeys) {\n const previousRaw = (previousValues as Record<string, unknown>)[parameter];\n const nextRaw = (currentValues as Record<string, unknown>)[parameter];\n const previousValue = typeof previousRaw === \"number\" ? previousRaw : null;\n const nextValue = typeof nextRaw === \"number\" ? nextRaw : null;\n if (previousValue === nextValue) continue;\n deltas.push({\n parameter,\n previousValue,\n nextValue,\n delta: (nextValue ?? 0) - (previousValue ?? 0),\n evidenceCount: current?.sourceAdjustmentCount ?? 0,\n });\n }\n deltas.sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta) || a.parameter.localeCompare(b.parameter));\n\n const signals = await readBehaviorSignalsForNamespaces(orchestrator, 1000);\n return {\n generatedAt: new Date().toISOString(),\n since,\n sinceIso,\n currentPolicyVersion: current ? policyVersionForValues(current.values, orchestrator.config) : null,\n previousPolicyVersion: previous ? policyVersionForValues(previous.values, orchestrator.config) : null,\n deltas,\n topContributingSignals: summarizeTopSignals(signals, sinceIso),\n };\n}\n\nexport async function runPolicyRollbackCliCommand(\n orchestrator: PolicyTuningCliOrchestrator,\n): Promise<PolicyRollbackCliReport> {\n const rolledBack = await orchestrator.rollbackBehaviorRuntimePolicy();\n const current = await readRuntimePolicySnapshot(orchestrator.config, \"policy-runtime.json\");\n return {\n generatedAt: new Date().toISOString(),\n rolledBack,\n current: current\n ? {\n ...current,\n policyVersion: policyVersionForValues(current.values, orchestrator.config),\n }\n : null,\n };\n}\n\nfunction incrementCounter(target: Record<string, number>, key: string): void {\n const normalized = key && key.length > 0 ? key : \"unknown\";\n target[normalized] = (target[normalized] ?? 0) + 1;\n}\n\nfunction resolveAuditNamespaces(\n orchestrator: MemoryActionAuditCliOrchestrator,\n namespace?: string,\n): string[] {\n if (namespace && namespace.length > 0) {\n return [namespace];\n }\n\n const names = new Set<string>([orchestrator.config.defaultNamespace]);\n if (orchestrator.config.namespacesEnabled) {\n names.add(orchestrator.config.sharedNamespace);\n for (const policy of orchestrator.config.namespacePolicies) {\n if (policy?.name) names.add(policy.name);\n }\n }\n\n return [...names];\n}\n\nexport async function runMemoryActionAuditCliCommand(\n orchestrator: MemoryActionAuditCliOrchestrator,\n options: MemoryActionAuditCliCommandOptions = {},\n): Promise<MemoryActionAuditCliReport> {\n const limit = Math.max(0, Math.floor(options.limit ?? 200));\n const namespaces = resolveAuditNamespaces(orchestrator, options.namespace);\n\n const namespaceSummaries: MemoryActionAuditCliNamespaceSummary[] = [];\n const totalsActions: Record<string, number> = {};\n const totalsOutcomes: Record<string, number> = {};\n const totalsPolicyDecisions: Record<string, number> = {};\n let totalEventCount = 0;\n\n for (const ns of namespaces) {\n const storage = await orchestrator.getStorage(ns);\n const events = await storage.readMemoryActionEvents(limit);\n\n const actions: Record<string, number> = {};\n const outcomes: Record<string, number> = {};\n const policyDecisions: Record<string, number> = {};\n\n for (const event of events) {\n incrementCounter(actions, event.action);\n incrementCounter(outcomes, event.outcome);\n incrementCounter(policyDecisions, event.policyDecision ?? \"unknown\");\n\n incrementCounter(totalsActions, event.action);\n incrementCounter(totalsOutcomes, event.outcome);\n incrementCounter(totalsPolicyDecisions, event.policyDecision ?? \"unknown\");\n }\n\n totalEventCount += events.length;\n namespaceSummaries.push({\n namespace: ns,\n eventCount: events.length,\n actions,\n outcomes,\n policyDecisions,\n });\n }\n\n return {\n generatedAt: new Date().toISOString(),\n limit,\n namespaces: namespaceSummaries,\n totals: {\n eventCount: totalEventCount,\n actions: totalsActions,\n outcomes: totalsOutcomes,\n policyDecisions: totalsPolicyDecisions,\n },\n };\n}\n\nexport async function runTailscaleStatusCliCommand(\n options: TailscaleStatusCliCommandOptions = {},\n): Promise<{\n available: boolean;\n running: boolean;\n backendState?: string;\n version?: string;\n selfHostname?: string;\n selfIp?: string;\n}> {\n const helper = options.helper ?? new TailscaleHelper({ timeoutMs: options.timeoutMs });\n return helper.status();\n}\n\nexport async function runTailscaleSyncCliCommand(\n options: TailscaleSyncCliCommandOptions,\n): Promise<{ ok: true }> {\n const helper = options.helper ?? new TailscaleHelper();\n await helper.syncDirectory({\n sourceDir: options.sourceDir,\n destination: options.destination,\n delete: options.delete,\n dryRun: options.dryRun,\n extraArgs: options.extraArgs,\n });\n return { ok: true };\n}\n\nexport async function runWebDavServeCliCommand(\n options: WebDavServeCliCommandOptions,\n): Promise<{ running: boolean; host: string; port: number; rootCount: number }> {\n return withWebDavLock(async () => {\n if (!Array.isArray(options.allowlistDirs) || options.allowlistDirs.length === 0) {\n throw new Error(\"webdav allowlist requires at least one directory\");\n }\n\n const usernameProvided = options.authUsername !== undefined;\n const passwordProvided = options.authPassword !== undefined;\n const username = options.authUsername?.trim();\n const password = options.authPassword?.trim();\n\n if ((usernameProvided && !username) || (passwordProvided && !password)) {\n throw new Error(\"webdav auth username/password must be non-empty when provided\");\n }\n\n if ((username && !password) || (!username && password)) {\n throw new Error(\"webdav auth requires both username and password\");\n }\n\n if (activeWebDavServer) {\n const current = activeWebDavServer.status();\n if (current.running) return current;\n }\n\n const createServer = options.createServer ?? WebDavServer.create;\n const server = await createServer({\n enabled: options.enabled ?? true,\n host: options.host,\n port: options.port ?? 8080,\n allowlistDirs: options.allowlistDirs,\n auth: username && password ? { username, password } : undefined,\n });\n\n activeWebDavServer = server;\n try {\n return await server.start();\n } catch (err) {\n if (activeWebDavServer === server) {\n activeWebDavServer = null;\n }\n throw err;\n }\n });\n}\n\nexport async function runWebDavStopCliCommand(): Promise<{ stopped: boolean }> {\n return withWebDavLock(async () => {\n if (!activeWebDavServer) {\n return { stopped: false };\n }\n\n const server = activeWebDavServer;\n await server.stop();\n if (activeWebDavServer === server) {\n activeWebDavServer = null;\n }\n return { stopped: true };\n });\n}\n\nexport async function runDashboardStartCliCommand(\n options: DashboardStartCliCommandOptions,\n): Promise<DashboardStatus> {\n return withDashboardLock(async () => {\n if (activeDashboardServer) {\n const status = activeDashboardServer.status();\n if (status.running) return status;\n }\n\n const createServer = options.createServer ?? ((opts: DashboardStartCliCommandOptions) =>\n new GraphDashboardServer({\n memoryDir: opts.memoryDir,\n host: opts.host,\n port: opts.port,\n publicDir: opts.publicDir,\n }));\n\n const server = createServer(options);\n activeDashboardServer = server;\n try {\n return await server.start();\n } catch (err) {\n if (activeDashboardServer === server) {\n activeDashboardServer = null;\n }\n throw err;\n }\n });\n}\n\nexport async function runDashboardStopCliCommand(): Promise<{ stopped: boolean }> {\n return withDashboardLock(async () => {\n if (!activeDashboardServer) return { stopped: false };\n const server = activeDashboardServer;\n await server.stop();\n if (activeDashboardServer === server) {\n activeDashboardServer = null;\n }\n return { stopped: true };\n });\n}\n\nexport async function runDashboardStatusCliCommand(): Promise<{ running: false } | DashboardStatus> {\n return withDashboardLock(async () => {\n if (!activeDashboardServer) return { running: false };\n return activeDashboardServer.status();\n });\n}\n\nexport async function runAccessHttpServeCliCommand(\n options: AccessHttpServeCliCommandOptions,\n): Promise<{ running: boolean; host: string; port: number; maxBodyBytes: number }> {\n return withAccessHttpLock(async () => {\n if (options.enabled === false) {\n throw new Error(\"engram access HTTP is disabled\");\n }\n if (activeAccessHttpServer) {\n const status = activeAccessHttpServer.status();\n if (status.running) return status;\n }\n\n const createServer = options.createServer ?? ((input: AccessHttpServeCliCommandOptions) =>\n new EngramAccessHttpServer({\n service: input.service,\n host: input.host,\n port: input.port,\n authToken: input.authToken,\n principal: input.principal,\n maxBodyBytes: input.maxBodyBytes,\n trustPrincipalHeader: input.trustPrincipalHeader,\n }));\n\n const server = createServer(options);\n activeAccessHttpServer = server;\n try {\n return await server.start();\n } catch (err) {\n if (activeAccessHttpServer === server) {\n activeAccessHttpServer = null;\n }\n throw err;\n }\n });\n}\n\nexport async function runAccessHttpStopCliCommand(): Promise<{ stopped: boolean }> {\n return withAccessHttpLock(async () => {\n if (!activeAccessHttpServer) return { stopped: false };\n const server = activeAccessHttpServer;\n await server.stop();\n if (activeAccessHttpServer === server) {\n activeAccessHttpServer = null;\n }\n return { stopped: true };\n });\n}\n\nexport async function runAccessHttpStatusCliCommand(): Promise<\n { running: false } | { running: boolean; host: string; port: number; maxBodyBytes: number }\n> {\n return withAccessHttpLock(async () => {\n if (!activeAccessHttpServer) return { running: false };\n return activeAccessHttpServer.status();\n });\n}\n\nexport async function runAccessMcpServeCliCommand(\n service: EngramAccessService,\n options: {\n principal?: string;\n createServer?: (service: EngramAccessService, options: { principal?: string }) => EngramMcpServerLike;\n stdin?: Readable;\n stdout?: Writable;\n } = {},\n): Promise<{ ok: true }> {\n const server = options.createServer?.(service, { principal: options.principal }) ?? new EngramMcpServer(service, {\n principal: options.principal,\n });\n await server.runStdio(options.stdin ?? process.stdin, options.stdout ?? process.stdout);\n return { ok: true };\n}\n\nexport async function runCompatCliCommand(\n options: CompatCliCommandOptions = {},\n): Promise<{ report: CompatReport; exitCode: number }> {\n const report = await runCompatChecks({\n repoRoot: options.repoRoot ?? process.cwd(),\n runner: options.runner,\n now: options.now,\n });\n const hasWarnOrError = report.summary.warn > 0 || report.summary.error > 0;\n const exitCode = options.strict === true && hasWarnOrError ? 1 : 0;\n return { report, exitCode };\n}\n\nexport async function runRouteCliCommand(options: RouteCliCommandOptions): Promise<unknown> {\n const store = new RoutingRulesStore(options.memoryDir, options.stateFile);\n\n if (options.action === \"list\") {\n const rules = await store.read();\n return [...rules].sort((a, b) => {\n if (b.priority !== a.priority) return b.priority - a.priority;\n return a.pattern.localeCompare(b.pattern);\n });\n }\n\n if (options.action === \"add\") {\n const pattern = options.pattern?.trim();\n if (!pattern) throw new Error(\"missing pattern\");\n if (!options.targetRaw || options.targetRaw.trim().length === 0) throw new Error(\"missing target\");\n const patternType = options.patternType ?? \"keyword\";\n if (!isRoutePatternType(patternType)) throw new Error(`invalid route pattern type: ${patternType}`);\n const priority = options.priority ?? 0;\n if (!Number.isFinite(priority)) throw new Error(\"invalid priority\");\n const target = parseRouteTargetCliArg(options.targetRaw);\n const validation = validateRouteTarget(target);\n if (!validation.ok || !validation.target) throw new Error(validation.error ?? \"invalid target\");\n\n const rule: RouteRule = {\n id: options.id?.trim() || \"\",\n patternType,\n pattern,\n priority: Math.trunc(priority),\n target: validation.target,\n enabled: true,\n };\n return store.upsert(rule);\n }\n\n if (options.action === \"remove\") {\n const pattern = options.pattern?.trim();\n if (!pattern) throw new Error(\"missing pattern\");\n return store.removeByPattern(pattern);\n }\n\n if (options.action === \"test\") {\n const text = options.text?.trim();\n if (!text) throw new Error(\"missing text\");\n const rules = await store.read();\n return selectRouteRule(text, rules);\n }\n\n throw new Error(`unsupported route action: ${options.action}`);\n}\n\nexport async function runWorkTaskCliCommand(options: WorkTaskCliCommandOptions): Promise<unknown> {\n const storage = new WorkStorage(options.memoryDir);\n\n if (options.action === \"create\") {\n if (!options.title || options.title.trim().length === 0) throw new Error(\"missing title\");\n if (options.status !== undefined && !isWorkTaskStatus(options.status)) throw new Error(`invalid task status: ${options.status}`);\n if (options.priority !== undefined && !isWorkTaskPriority(options.priority)) {\n throw new Error(`invalid task priority: ${options.priority}`);\n }\n const explicitId = options.id?.trim();\n if (explicitId && explicitId.length > 0) {\n const existing = await storage.getTask(explicitId);\n if (existing) throw new Error(`task already exists: ${explicitId}`);\n }\n return storage.createTask({\n id: explicitId && explicitId.length > 0 ? explicitId : undefined,\n title: options.title.trim(),\n description: options.description?.trim(),\n status: options.status,\n priority: options.priority,\n owner: normalizeNullableCliValue(options.owner),\n assignee: normalizeNullableCliValue(options.assignee),\n projectId: normalizeNullableCliValue(options.projectId),\n tags: options.tags,\n dueAt: normalizeNullableCliValue(options.dueAt),\n });\n }\n\n if (options.action === \"get\") {\n if (!options.id || options.id.trim().length === 0) throw new Error(\"missing id\");\n return storage.getTask(options.id.trim());\n }\n\n if (options.action === \"list\") {\n if (options.status !== undefined && !isWorkTaskStatus(options.status)) throw new Error(`invalid task status: ${options.status}`);\n return storage.listTasks({\n status: options.status,\n owner: options.owner?.trim() || undefined,\n assignee: options.assignee?.trim() || undefined,\n projectId: options.projectId?.trim() || undefined,\n });\n }\n\n if (options.action === \"update\") {\n if (!options.id || options.id.trim().length === 0) throw new Error(\"missing id\");\n const patch = options.patch ?? {};\n if (patch.status !== undefined && !isWorkTaskStatus(patch.status)) throw new Error(`invalid task status: ${patch.status}`);\n if (patch.priority !== undefined && !isWorkTaskPriority(patch.priority)) {\n throw new Error(`invalid task priority: ${patch.priority}`);\n }\n\n const sparsePatch: WorkTaskPatchInput = {};\n if (Object.prototype.hasOwnProperty.call(patch, \"title\")) sparsePatch.title = patch.title;\n if (Object.prototype.hasOwnProperty.call(patch, \"description\")) sparsePatch.description = patch.description;\n if (Object.prototype.hasOwnProperty.call(patch, \"status\")) sparsePatch.status = patch.status;\n if (Object.prototype.hasOwnProperty.call(patch, \"priority\")) sparsePatch.priority = patch.priority;\n if (Object.prototype.hasOwnProperty.call(patch, \"owner\")) sparsePatch.owner = patch.owner;\n if (Object.prototype.hasOwnProperty.call(patch, \"assignee\")) sparsePatch.assignee = patch.assignee;\n if (Object.prototype.hasOwnProperty.call(patch, \"projectId\")) sparsePatch.projectId = patch.projectId;\n if (Object.prototype.hasOwnProperty.call(patch, \"tags\")) sparsePatch.tags = patch.tags;\n if (Object.prototype.hasOwnProperty.call(patch, \"dueAt\")) sparsePatch.dueAt = patch.dueAt;\n\n return storage.updateTask(options.id.trim(), sparsePatch);\n }\n\n if (options.action === \"transition\") {\n if (!options.id || options.id.trim().length === 0) throw new Error(\"missing id\");\n if (!options.status || !isWorkTaskStatus(options.status)) throw new Error(`invalid task status: ${options.status}`);\n return storage.transitionTask(options.id.trim(), options.status);\n }\n\n if (options.action === \"delete\") {\n if (!options.id || options.id.trim().length === 0) throw new Error(\"missing id\");\n return storage.deleteTask(options.id.trim());\n }\n\n if (options.action === \"link\") {\n if (!options.id || options.id.trim().length === 0) throw new Error(\"missing id\");\n if (!options.projectId || options.projectId.trim().length === 0) throw new Error(\"missing projectId\");\n return storage.linkTaskToProject(options.id.trim(), options.projectId.trim());\n }\n\n throw new Error(`unsupported task action: ${options.action}`);\n}\n\nexport async function runWorkProjectCliCommand(options: WorkProjectCliCommandOptions): Promise<unknown> {\n const storage = new WorkStorage(options.memoryDir);\n\n if (options.action === \"create\") {\n if (!options.name || options.name.trim().length === 0) throw new Error(\"missing name\");\n if (options.status !== undefined && !isWorkProjectStatus(options.status)) {\n throw new Error(`invalid project status: ${options.status}`);\n }\n const explicitId = options.id?.trim();\n if (explicitId && explicitId.length > 0) {\n const existing = await storage.getProject(explicitId);\n if (existing) throw new Error(`project already exists: ${explicitId}`);\n }\n return storage.createProject({\n id: explicitId && explicitId.length > 0 ? explicitId : undefined,\n name: options.name.trim(),\n description: options.description?.trim(),\n status: options.status,\n owner: normalizeNullableCliValue(options.owner),\n tags: options.tags,\n });\n }\n\n if (options.action === \"get\") {\n if (!options.id || options.id.trim().length === 0) throw new Error(\"missing id\");\n return storage.getProject(options.id.trim());\n }\n\n if (options.action === \"list\") {\n return storage.listProjects();\n }\n\n if (options.action === \"update\") {\n if (!options.id || options.id.trim().length === 0) throw new Error(\"missing id\");\n const patch = options.patch ?? {};\n if (patch.status !== undefined && !isWorkProjectStatus(patch.status)) {\n throw new Error(`invalid project status: ${patch.status}`);\n }\n\n const sparsePatch: WorkProjectPatchInput = {};\n if (Object.prototype.hasOwnProperty.call(patch, \"name\")) sparsePatch.name = patch.name;\n if (Object.prototype.hasOwnProperty.call(patch, \"description\")) sparsePatch.description = patch.description;\n if (Object.prototype.hasOwnProperty.call(patch, \"status\")) sparsePatch.status = patch.status;\n if (Object.prototype.hasOwnProperty.call(patch, \"owner\")) sparsePatch.owner = patch.owner;\n if (Object.prototype.hasOwnProperty.call(patch, \"tags\")) sparsePatch.tags = patch.tags;\n\n return storage.updateProject(options.id.trim(), sparsePatch);\n }\n\n if (options.action === \"delete\") {\n if (!options.id || options.id.trim().length === 0) throw new Error(\"missing id\");\n return storage.deleteProject(options.id.trim());\n }\n\n throw new Error(`unsupported project action: ${options.action}`);\n}\n\nasync function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n timeoutMessage: string,\n): Promise<T> {\n let timer: NodeJS.Timeout | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<T>((_, reject) => {\n timer = setTimeout(() => reject(new Error(timeoutMessage)), timeoutMs);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nexport async function runReplayCliCommand(\n orchestrator: ReplayCliOrchestrator,\n options: ReplayCliCommandOptions,\n): Promise<ReplayRunSummary> {\n const extractionIdleTimeoutMs = Number.isFinite(options.extractionIdleTimeoutMs as number)\n ? Math.max(1_000, Math.floor(options.extractionIdleTimeoutMs as number))\n : 15 * 60_000;\n const inputRaw = await readFile(options.inputPath, \"utf-8\");\n const registry = buildReplayNormalizerRegistry([\n openclawReplayNormalizer,\n claudeReplayNormalizer,\n chatgptReplayNormalizer,\n ]);\n const ingestBatchSize = clampBatchSize(options.batchSize);\n const turnsBySession = new Map<string, ReplayTurn[]>();\n const ingestSessionChunk = async (sessionTurns: ReplayTurn[]): Promise<void> => {\n const deadlineMs = Date.now() + extractionIdleTimeoutMs;\n await withTimeout(\n orchestrator.ingestReplayBatch(sessionTurns, { deadlineMs }),\n extractionIdleTimeoutMs,\n `replay extraction batch did not complete before timeout (${extractionIdleTimeoutMs}ms)`,\n );\n };\n\n const summary = await runReplay(\n options.source,\n inputRaw,\n registry,\n {\n onBatch: async (batch) => {\n for (const turn of batch) {\n const key = normalizeReplaySessionKey(turn.sessionKey);\n const turns = turnsBySession.get(key) ?? [];\n turns.push(turn);\n turnsBySession.set(key, turns);\n while (turns.length >= ingestBatchSize) {\n const chunk = turns.splice(0, ingestBatchSize);\n await ingestSessionChunk(chunk);\n }\n }\n },\n },\n {\n from: options.from,\n to: options.to,\n dryRun: options.dryRun === true,\n startOffset: options.startOffset,\n maxTurns: options.maxTurns,\n batchSize: options.batchSize,\n defaultSessionKey: options.defaultSessionKey,\n strict: options.strict,\n },\n );\n\n if (!summary.dryRun) {\n for (const turns of turnsBySession.values()) {\n if (turns.length === 0) continue;\n await ingestSessionChunk(turns);\n }\n if (options.runConsolidation === true) {\n const consolidationIdle = await orchestrator.waitForConsolidationIdle(extractionIdleTimeoutMs);\n if (!consolidationIdle) {\n throw new Error(\n `replay consolidation did not become idle before timeout (${extractionIdleTimeoutMs}ms)`,\n );\n }\n await orchestrator.runConsolidationNow();\n }\n }\n\n return summary;\n}\n\nasync function getPluginVersion(): Promise<string> {\n try {\n const pkgPath = new URL(\"../package.json\", import.meta.url);\n const raw = await readFile(pkgPath, \"utf-8\");\n const parsed = JSON.parse(raw) as { version?: string };\n return parsed.version ?? \"unknown\";\n } catch {\n return \"unknown\";\n }\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function resolveMemoryDirForNamespace(\n orchestrator: Orchestrator,\n namespace?: string,\n options?: { rejectUnsupportedOverride?: boolean },\n): Promise<string> {\n const ns = (namespace ?? \"\").trim();\n if (!ns) return orchestrator.config.memoryDir;\n if (!orchestrator.config.namespacesEnabled) {\n if (options?.rejectUnsupportedOverride && ns !== orchestrator.config.defaultNamespace) {\n throw new Error(`namespaces are disabled; cannot target namespace: ${ns}`);\n }\n return orchestrator.config.memoryDir;\n }\n\n const candidate = path.join(orchestrator.config.memoryDir, \"namespaces\", ns);\n if (ns === orchestrator.config.defaultNamespace) {\n return (await exists(candidate)) ? candidate : orchestrator.config.memoryDir;\n }\n return candidate;\n}\n\nasync function readAllMemoryFiles(memoryDir: string): Promise<DedupeCandidate[]> {\n const roots = [path.join(memoryDir, \"facts\"), path.join(memoryDir, \"corrections\")];\n const out: DedupeCandidate[] = [];\n\n const walk = async (dir: string): Promise<void> => {\n let entries: Array<{ isDirectory(): boolean; isFile(): boolean; name: string | Buffer }>;\n try {\n entries = (await readdir(dir, { withFileTypes: true })) as Array<{\n isDirectory(): boolean;\n isFile(): boolean;\n name: string | Buffer;\n }>;\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const entryName = typeof entry.name === \"string\" ? entry.name : entry.name.toString(\"utf-8\");\n const fullPath = path.join(dir, entryName);\n if (entry.isDirectory()) {\n await walk(fullPath);\n continue;\n }\n if (!entry.isFile() || !entryName.endsWith(\".md\")) continue;\n\n try {\n const raw = await readFile(fullPath, \"utf-8\");\n const parsed = raw.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n if (!parsed) continue;\n const fmRaw = parsed[1];\n const body = parsed[2] ?? \"\";\n const get = (key: string): string => {\n const match = fmRaw.match(new RegExp(`^${key}:\\\\s*(.+)$`, \"m\"));\n return match ? match[1].trim() : \"\";\n };\n const confidenceRaw = get(\"confidence\");\n const confidence = confidenceRaw.length > 0 ? Number(confidenceRaw) : undefined;\n out.push({\n path: fullPath,\n content: body,\n frontmatter: {\n id: get(\"id\") || undefined,\n confidence: Number.isFinite(confidence as number) ? confidence : undefined,\n updated: get(\"updated\") || undefined,\n created: get(\"created\") || undefined,\n },\n });\n } catch {\n // Skip unreadable/malformed files.\n }\n }\n };\n\n for (const root of roots) {\n await walk(root);\n }\n\n return out;\n}\n\nfunction formatContinuityIncidentCli(incident: ContinuityIncidentRecord): string {\n const lines = [\n `${incident.id} [${incident.state}]`,\n ` opened: ${incident.openedAt}`,\n ];\n if (incident.closedAt) lines.push(` closed: ${incident.closedAt}`);\n if (incident.triggerWindow) lines.push(` window: ${incident.triggerWindow}`);\n lines.push(` symptom: ${incident.symptom}`);\n if (incident.suspectedCause) lines.push(` suspected-cause: ${incident.suspectedCause}`);\n if (incident.fixApplied) lines.push(` fix-applied: ${incident.fixApplied}`);\n if (incident.verificationResult) lines.push(` verification: ${incident.verificationResult}`);\n if (incident.preventiveRule) lines.push(` preventive-rule: ${incident.preventiveRule}`);\n if (incident.filePath) lines.push(` path: ${incident.filePath}`);\n return lines.join(\"\\n\");\n}\n\nfunction formatOperatorSetupCli(report: OperatorSetupReport): string {\n const lines = [\n \"=== Engram Setup ===\",\n \"\",\n `Config: ${report.config.parsed ? \"ok\" : \"error\"} (${report.config.path})`,\n `Memory dir: ${report.memoryDir}`,\n `Workspace dir: ${report.workspaceDir}`,\n `QMD: ${report.qmd.enabled ? `${report.qmd.available ? \"available\" : \"unavailable\"} (${report.qmd.collectionState})` : \"disabled\"}`,\n `Explicit capture: ${report.explicitCapture.enabled ? report.explicitCapture.captureMode : \"disabled\"}`,\n \"\",\n \"Directories:\",\n ...report.directories.map((entry) => `- ${entry.path} (${entry.exists ? \"present\" : \"missing\"}, ${entry.writable ? \"writable\" : \"read-only\"})`),\n ];\n if (report.explicitCapture.enabled) {\n lines.push(`Capture doc: ${report.explicitCapture.memoryDocPath} (${report.explicitCapture.memoryDocExists ? \"present\" : \"missing\"})`);\n if (report.explicitCapture.memoryDocInstalled) lines.push(\"Capture instructions: installed\");\n if (report.explicitCapture.memoryDocUpdated) lines.push(\"Capture instructions: updated\");\n if (report.explicitCapture.memoryDocRemoved) lines.push(\"Capture instructions: removed\");\n if (report.explicitCapture.preview) {\n lines.push(\"\", \"Capture instructions preview:\", report.explicitCapture.preview);\n }\n }\n lines.push(\"\", \"Next steps:\", ...report.nextSteps.map((step) => `- ${step}`));\n return lines.join(\"\\n\");\n}\n\nfunction formatOperatorDoctorCli(report: OperatorDoctorReport): string {\n const lines = [\n \"=== Engram Doctor ===\",\n \"\",\n `Summary: ok=${report.summary.ok} warn=${report.summary.warn} error=${report.summary.error}`,\n ];\n for (const check of report.checks) {\n lines.push(`- [${check.status.toUpperCase()}] ${check.key}: ${check.summary}`);\n if (check.remediation) lines.push(` remediation: ${check.remediation}`);\n }\n return lines.join(\"\\n\");\n}\n\nfunction formatOperatorConfigReviewCli(report: OperatorConfigReviewReport): string {\n const lines = [\n \"=== Engram Config Review ===\",\n \"\",\n `Config parsed: ${report.config.parsed ? \"yes\" : \"no\"}`,\n `Config path: ${report.config.path}`,\n `Preset: ${report.profile.memoryOsPreset ?? \"(unset)\"}`,\n `Search backend: ${report.profile.searchBackend}`,\n `QMD enabled: ${report.profile.qmdEnabled ? \"yes\" : \"no\"}`,\n `QMD daemon enabled: ${report.profile.qmdDaemonEnabled ? \"yes\" : \"no\"}`,\n `Native knowledge enabled: ${report.profile.nativeKnowledgeEnabled ? \"yes\" : \"no\"}`,\n `File hygiene enabled: ${report.profile.fileHygieneEnabled ? \"yes\" : \"no\"}`,\n `Conversation index enabled: ${report.profile.conversationIndexEnabled ? \"yes\" : \"no\"}`,\n \"\",\n `Summary: recommend=${report.summary.recommend} problem=${report.summary.problem}`,\n ];\n if (!report.config.parsed && report.config.error) {\n lines.push(`Config error: ${report.config.error}`);\n }\n for (const finding of report.findings) {\n lines.push(`- [${finding.status.toUpperCase()}] ${finding.key}: ${finding.summary}`);\n lines.push(` setting: ${finding.setting}`);\n lines.push(` current/default/recommended: ${finding.currentValue} / ${finding.defaultValue} / ${finding.recommendedValue}`);\n lines.push(` why: ${finding.rationale}`);\n }\n return lines.join(\"\\n\");\n}\n\nfunction formatOperatorInventoryCli(report: OperatorInventoryReport): string {\n const lines = [\n \"=== Engram Inventory ===\",\n \"\",\n `Memories: ${report.totals.memories}`,\n `Entities: ${report.totals.entities}`,\n `Namespaces: ${report.totals.namespaces}`,\n `Review queue: ${report.totals.reviewQueue}`,\n `Storage: ${report.totals.storageBytes} bytes`,\n `Conversation index: ${report.conversationIndex.status} (${report.conversationIndex.backend})`,\n \"\",\n \"By status:\",\n ...Object.entries(report.statuses).sort((a, b) => a[0].localeCompare(b[0])).map(([status, count]) => `- ${status}: ${count}`),\n \"\",\n \"By category:\",\n ...Object.entries(report.categories).sort((a, b) => a[0].localeCompare(b[0])).map(([category, count]) => `- ${category}: ${count}`),\n ];\n return lines.join(\"\\n\");\n}\n\nfunction formatBenchmarkRecallCli(report: BenchmarkRecallReport): string {\n const lines = [\n \"=== Engram Benchmark Recall ===\",\n \"\",\n `Mode: ${report.mode}`,\n `Harness enabled: ${report.status.enabled ? \"yes\" : \"no\"}`,\n `Benchmarks: ${report.status.benchmarks.valid}/${report.status.benchmarks.total} valid`,\n `Latest run: ${report.status.runs.latestRunId ?? \"none\"}`,\n ];\n if (report.validate) {\n lines.push(`Validated pack: ${report.validate.benchmarkId} (${report.validate.totalCases} cases)`);\n }\n if (report.snapshot) {\n lines.push(`Snapshot: ${report.snapshot.snapshotId}`);\n lines.push(`Path: ${report.snapshot.targetPath}`);\n }\n if (report.baselineReport) {\n lines.push(`Baseline passed: ${report.baselineReport.passed ? \"yes\" : \"no\"}`);\n }\n if (report.ciGate) {\n lines.push(`CI gate passed: ${report.ciGate.passed ? \"yes\" : \"no\"}`);\n }\n return lines.join(\"\\n\");\n}\n\nfunction formatOperatorRepairCli(report: OperatorRepairReport): string {\n const lines = [\n \"=== Engram Repair ===\",\n \"\",\n `Mode: ${report.dryRun ? \"dry-run\" : \"apply\"}`,\n `Session actions planned: ${report.sessionRepairPlan.actions.length}`,\n `Session actions applied: ${report.sessionRepairApply.actionsApplied}`,\n `Graph health: corruptLines=${report.graphHealth.totals.corruptLines}, validEdges=${report.graphHealth.totals.validEdges}`,\n ];\n if (report.graphHealth.repairGuidance && report.graphHealth.repairGuidance.length > 0) {\n lines.push(\"Graph guidance:\");\n for (const entry of report.graphHealth.repairGuidance) {\n lines.push(`- ${entry}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\nfunction reportHasMachineReadableOutput(options: Record<string, unknown>): boolean {\n return options.json === true;\n}\n\nfunction setupReportPassed(report: OperatorSetupReport): boolean {\n return report.directories.every((entry) => entry.exists && entry.writable);\n}\n\nfunction buildConversationIndexRebuildAction(orchestrator: Orchestrator) {\n return async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const hours = typeof options.hours === \"string\"\n ? Number.parseInt(options.hours, 10)\n : 24;\n const result = await runConversationIndexRebuildCliCommand(orchestrator, {\n sessionKey:\n typeof options.sessionKey === \"string\" && options.sessionKey.trim().length > 0\n ? options.sessionKey.trim()\n : undefined,\n hours: Number.isFinite(hours) ? hours : 24,\n embed: options.embed === true,\n });\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n };\n}\n\nexport function registerCli(api: CliApi, orchestrator: Orchestrator): void {\n api.registerCli(\n ({ program }) => {\n const cmd = program\n .command(\"engram\")\n .description(\"Engram local memory commands\");\n\n cmd\n .command(\"stats\")\n .description(\"Show memory system statistics\")\n .action(async () => {\n // Ensure QMD is probed before checking availability\n await orchestrator.qmd.probe();\n\n const meta = await orchestrator.storage.loadMeta();\n const memories = await orchestrator.storage.readAllMemories();\n const entities = await orchestrator.storage.readEntities();\n const profile = await orchestrator.storage.readProfile();\n\n console.log(\"=== Engram Memory Stats ===\\n\");\n console.log(`Total memories: ${memories.length}`);\n console.log(`Total entities: ${entities.length}`);\n console.log(`Profile size: ${profile.length} chars`);\n console.log(`Extractions: ${meta.extractionCount}`);\n console.log(`Last extraction: ${meta.lastExtractionAt ?? \"never\"}`);\n console.log(\n `Last consolidation: ${meta.lastConsolidationAt ?? \"never\"}`,\n );\n console.log(`QMD: ${orchestrator.qmd.isAvailable() ? \"available\" : \"not available\"}`);\n\n // Category breakdown\n const categories: Record<string, number> = {};\n for (const m of memories) {\n categories[m.frontmatter.category] =\n (categories[m.frontmatter.category] ?? 0) + 1;\n }\n if (Object.keys(categories).length > 0) {\n console.log(\"\\nBy category:\");\n for (const [cat, count] of Object.entries(categories)) {\n console.log(` ${cat}: ${count}`);\n }\n }\n });\n\n cmd\n .command(\"setup\")\n .description(\"Validate config, scaffold directories, and print first-run next steps\")\n .option(\"--install-capture-instructions\", \"Create workspace MEMORY.md when explicit capture is enabled and missing\")\n .option(\"--preview-capture-instructions\", \"Print the managed explicit-capture instruction snippet without writing files\")\n .option(\"--remove-capture-instructions\", \"Remove the managed explicit-capture instruction snippet from MEMORY.md\")\n .option(\"--json\", \"Emit machine-readable JSON only\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const captureInstructionsMode =\n options.removeCaptureInstructions === true\n ? \"remove\"\n : options.previewCaptureInstructions === true\n ? \"preview\"\n : options.installCaptureInstructions === true\n ? \"install\"\n : undefined;\n const report = await runOperatorSetup({\n orchestrator,\n installCaptureInstructions: options.installCaptureInstructions === true,\n captureInstructionsMode,\n });\n if (reportHasMachineReadableOutput(options)) {\n console.log(JSON.stringify(report, null, 2));\n } else {\n console.log(formatOperatorSetupCli(report));\n }\n if (!setupReportPassed(report)) {\n process.exitCode = 1;\n return;\n }\n if (!reportHasMachineReadableOutput(options)) console.log(\"OK\");\n });\n\n cmd\n .command(\"doctor\")\n .description(\"Run safe Engram health diagnostics with remediation guidance\")\n .option(\"--json\", \"Emit machine-readable JSON only\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const report = await runOperatorDoctor({ orchestrator });\n if (reportHasMachineReadableOutput(options)) {\n console.log(JSON.stringify(report, null, 2));\n } else {\n console.log(formatOperatorDoctorCli(report));\n }\n if (!report.ok) {\n process.exitCode = 1;\n return;\n }\n if (!reportHasMachineReadableOutput(options)) console.log(\"OK\");\n });\n\n cmd\n .command(\"config-review\")\n .description(\"Review Engram config defaults, recommendations, and contradictory settings\")\n .option(\"--json\", \"Emit machine-readable JSON only\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const report = await runOperatorConfigReview({ orchestrator });\n if (reportHasMachineReadableOutput(options)) {\n console.log(JSON.stringify(report, null, 2));\n } else {\n console.log(formatOperatorConfigReviewCli(report));\n }\n if (!report.ok) {\n process.exitCode = 1;\n return;\n }\n if (!reportHasMachineReadableOutput(options)) console.log(\"OK\");\n });\n\n cmd\n .command(\"inventory\")\n .description(\"Report namespace, memory, review, and storage inventory\")\n .option(\"--json\", \"Emit machine-readable JSON only\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const report = await runOperatorInventory({ orchestrator });\n if (reportHasMachineReadableOutput(options)) {\n console.log(JSON.stringify(report, null, 2));\n } else {\n console.log(formatOperatorInventoryCli(report));\n }\n if (!reportHasMachineReadableOutput(options)) console.log(\"OK\");\n });\n\n const namespacesCmd = cmd\n .command(\"namespaces\")\n .description(\"Manage namespace roots, migration, and verification\");\n\n namespacesCmd\n .command(\"ls\")\n .description(\"List configured namespaces and their storage roots\")\n .action(async () => {\n const namespaces = await listNamespaces({ config: orchestrator.config });\n if (namespaces.length === 0) {\n console.log(\"No namespaces configured.\");\n return;\n }\n\n console.log(\"=== Engram Namespaces ===\\n\");\n for (const entry of namespaces) {\n console.log(\n `${entry.namespace}\\n root: ${entry.rootDir}\\n exists: ${entry.exists ? \"yes\" : \"no\"}\\n legacy-root: ${entry.usesLegacyRoot ? \"yes\" : \"no\"}\\n has-data: ${entry.hasMemoryData ? \"yes\" : \"no\"}\\n collection: ${entry.collection}`,\n );\n }\n });\n\n namespacesCmd\n .command(\"verify\")\n .description(\"Verify namespace roots and detect legacy root drift\")\n .action(async () => {\n const report = await verifyNamespaces({ config: orchestrator.config });\n console.log(\"=== Namespace Verification ===\\n\");\n for (const entry of report.namespaces) {\n console.log(\n `${entry.namespace}\\n root: ${entry.rootDir}\\n exists: ${entry.exists ? \"yes\" : \"no\"}\\n legacy-root: ${entry.usesLegacyRoot ? \"yes\" : \"no\"}\\n has-data: ${entry.hasMemoryData ? \"yes\" : \"no\"}\\n collection: ${entry.collection}`,\n );\n }\n\n if (report.ok) {\n console.log(\"\\nOK\");\n return;\n }\n\n console.log(\"\\nProblems:\");\n for (const problem of report.problems) {\n console.log(`- ${problem}`);\n }\n process.exitCode = 1;\n });\n\n namespacesCmd\n .command(\"migrate\")\n .description(\"Move legacy root memory layout into a namespaced root\")\n .option(\"--to <ns>\", \"Target namespace (default: config defaultNamespace)\", \"\")\n .option(\"--dry-run\", \"Show the migration plan without moving files\")\n .action(async (optionsRaw: unknown) => {\n const options =\n optionsRaw && typeof optionsRaw === \"object\"\n ? optionsRaw as { to?: string; dryRun?: boolean }\n : {};\n const targetNamespace =\n typeof options.to === \"string\" && options.to.trim().length > 0\n ? options.to.trim()\n : orchestrator.config.defaultNamespace;\n const dryRun = options.dryRun === true;\n\n const plan = await runNamespaceMigration({\n config: orchestrator.config,\n to: targetNamespace,\n dryRun,\n });\n\n console.log(\"=== Namespace Migration Plan ===\\n\");\n console.log(`target namespace: ${targetNamespace}`);\n console.log(`source root: ${plan.fromRoot}`);\n console.log(`target root: ${plan.targetRoot}`);\n console.log(`entries: ${plan.moved.length}`);\n console.log(`collection: ${plan.collection}`);\n\n if (plan.moved.length > 0) {\n console.log(\"\\nEntries:\");\n for (const move of plan.moved) {\n console.log(`- ${path.basename(move.from)}`);\n }\n }\n\n if (dryRun) {\n console.log(\"\\nDRY RUN\");\n return;\n }\n\n console.log(\"\\nOK\");\n });\n\n cmd\n .command(\"export\")\n .description(\"Export Remnic memory to JSON, Markdown bundle, or SQLite\")\n .option(\"--format <format>\", \"Export format: json|md|sqlite\", \"json\")\n .option(\"--out <path>\", \"Output path (dir for json/md, file for sqlite)\")\n .option(\"--include-transcripts\", \"Include transcripts in export (default: false)\")\n .option(\"--namespace <ns>\", \"Namespace to export (v3.0+, default: config defaultNamespace)\", \"\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const format = String(options.format ?? \"json\");\n const out = options.out ? String(options.out) : \"\";\n const includeTranscripts = options.includeTranscripts === true;\n const namespace = options.namespace ? String(options.namespace) : \"\";\n if (!out) {\n console.log(\"Missing --out. Example: openclaw engram export --format json --out /tmp/engram-export\");\n return;\n }\n\n const pluginVersion = await getPluginVersion();\n const memoryDir = await resolveMemoryDirForNamespace(orchestrator, namespace, {\n rejectUnsupportedOverride: true,\n });\n if (format === \"json\") {\n await exportJsonBundle({\n memoryDir,\n outDir: out,\n includeTranscripts,\n pluginVersion,\n workspaceDir: orchestrator.config.workspaceDir,\n includeWorkspaceIdentity: true,\n });\n } else if (format === \"md\") {\n await exportMarkdownBundle({\n memoryDir,\n outDir: out,\n includeTranscripts,\n pluginVersion,\n });\n } else if (format === \"sqlite\") {\n await exportSqlite({\n memoryDir,\n outFile: out,\n includeTranscripts,\n pluginVersion,\n });\n } else {\n console.log(`Unknown format: ${format}`);\n return;\n }\n console.log(\"OK\");\n });\n\n cmd\n .command(\"import\")\n .description(\"Import Remnic memory from JSON bundle, Markdown bundle, or SQLite\")\n .option(\"--from <path>\", \"Import source path (dir or file)\")\n .option(\"--format <format>\", \"Import format: auto|json|md|sqlite\", \"auto\")\n .option(\"--conflict <mode>\", \"Conflict policy: skip|overwrite|dedupe\", \"skip\")\n .option(\"--dry-run\", \"Validate import without writing files\")\n .option(\"--namespace <ns>\", \"Namespace to import into (v3.0+, default: config defaultNamespace)\", \"\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const from = options.from ? String(options.from) : \"\";\n const formatOpt = String(options.format ?? \"auto\");\n const conflict = String(options.conflict ?? \"skip\") as \"skip\" | \"overwrite\" | \"dedupe\";\n const dryRun = options.dryRun === true;\n const namespace = options.namespace ? String(options.namespace) : \"\";\n if (!from) {\n console.log(\"Missing --from. Example: openclaw engram import --from /tmp/engram-export --format auto\");\n return;\n }\n\n const detected = formatOpt === \"auto\" ? await detectImportFormat(from) : (formatOpt as any);\n if (!detected) {\n console.log(\"Could not detect import format (use --format json|md|sqlite).\");\n return;\n }\n\n const targetMemoryDir = await resolveMemoryDirForNamespace(orchestrator, namespace);\n\n if (detected === \"json\") {\n await importJsonBundle({\n targetMemoryDir,\n fromDir: from,\n conflict,\n dryRun,\n workspaceDir: orchestrator.config.workspaceDir,\n });\n } else if (detected === \"sqlite\") {\n await importSqlite({\n targetMemoryDir,\n fromFile: from,\n conflict,\n dryRun,\n });\n } else if (detected === \"md\") {\n await importMarkdownBundle({\n targetMemoryDir,\n fromDir: from,\n conflict,\n dryRun,\n });\n } else {\n console.log(`Unknown detected format: ${detected}`);\n return;\n }\n console.log(\"OK\");\n });\n\n cmd\n .command(\"backup\")\n .description(\"Create a timestamped backup of the Remnic memory directory\")\n .option(\"--out-dir <dir>\", \"Backup root directory\")\n .option(\"--retention-days <n>\", \"Delete backups older than N days\", \"0\")\n .option(\"--include-transcripts\", \"Include transcripts (default false)\")\n .option(\"--namespace <ns>\", \"Namespace to back up (v3.0+, default: config defaultNamespace)\", \"\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const outDir = options.outDir ? String(options.outDir) : \"\";\n const retentionDays = parseInt(String(options.retentionDays ?? \"0\"), 10);\n const includeTranscripts = options.includeTranscripts === true;\n const namespace = options.namespace ? String(options.namespace) : \"\";\n if (!outDir) {\n console.log(\"Missing --out-dir. Example: openclaw engram backup --out-dir /tmp/engram-backups\");\n return;\n }\n const pluginVersion = await getPluginVersion();\n const memoryDir = await resolveMemoryDirForNamespace(orchestrator, namespace, {\n rejectUnsupportedOverride: true,\n });\n await backupMemoryDir({\n memoryDir,\n outDir,\n retentionDays: Number.isFinite(retentionDays) ? retentionDays : undefined,\n includeTranscripts,\n pluginVersion,\n });\n console.log(\"OK\");\n });\n\n cmd\n .command(\"compat\")\n .description(\"Run local compatibility diagnostics for Engram plugin wiring\")\n .option(\"--json\", \"Emit JSON output for automation\")\n .option(\"--strict\", \"Exit non-zero when warnings or errors are present\")\n .option(\"--repo-root <path>\", \"Repository root to inspect\", process.cwd())\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const strict = options.strict === true;\n const jsonOutput = options.json === true;\n const repoRoot =\n typeof options.repoRoot === \"string\" && options.repoRoot.trim().length > 0\n ? options.repoRoot.trim()\n : process.cwd();\n\n const result = await runCompatCliCommand({ repoRoot, strict });\n\n if (jsonOutput) {\n console.log(JSON.stringify({ strict, exitCode: result.exitCode, report: result.report }, null, 2));\n } else {\n console.log(\"=== Engram Compatibility Report ===\");\n for (const check of result.report.checks) {\n console.log(`- [${check.level.toUpperCase()}] ${check.title}: ${check.message}`);\n if (check.remediation) {\n console.log(` remediation: ${check.remediation}`);\n }\n }\n console.log(\n `Summary: ok=${result.report.summary.ok} warn=${result.report.summary.warn} error=${result.report.summary.error}`,\n );\n }\n\n if (result.exitCode !== 0) {\n process.exitCode = result.exitCode;\n }\n });\n\n cmd\n .command(\"replay\")\n .description(\"Import replay transcripts from external exports\")\n .option(\"--source <source>\", \"Replay source: openclaw|claude|chatgpt\")\n .option(\"--input <path>\", \"Path to replay export file\")\n .option(\"--from <iso>\", \"Inclusive lower bound timestamp (ISO UTC)\")\n .option(\"--to <iso>\", \"Inclusive upper bound timestamp (ISO UTC)\")\n .option(\"--dry-run\", \"Parse and validate only; do not enqueue extraction\")\n .option(\"--start-offset <n>\", \"Start replay at offset\", \"0\")\n .option(\"--max-turns <n>\", \"Maximum turns to process\", \"0\")\n .option(\"--batch-size <n>\", \"Replay ingestion batch size\", \"100\")\n .option(\"--default-session-key <key>\", \"Fallback session key when source session identifiers are missing\")\n .option(\"--strict\", \"Fail on invalid source rows\")\n .option(\"--run-consolidation\", \"Run consolidation after replay ingestion completes\")\n .option(\"--idle-timeout-ms <n>\", \"Extraction idle timeout per replay batch/final drain in milliseconds\", \"900000\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const sourceRaw = typeof options.source === \"string\" ? options.source.trim().toLowerCase() : \"\";\n const inputPath = typeof options.input === \"string\" ? options.input.trim() : \"\";\n if (!isReplaySource(sourceRaw)) {\n console.log(\"Missing or invalid --source. Use one of: openclaw, claude, chatgpt.\");\n return;\n }\n if (inputPath.length === 0) {\n console.log(\"Missing --input. Example: openclaw engram replay --source openclaw --input /tmp/replay.jsonl\");\n return;\n }\n\n const startOffset = parseInt(String(options.startOffset ?? \"0\"), 10);\n const maxTurnsRaw = parseInt(String(options.maxTurns ?? \"0\"), 10);\n const batchSize = parseInt(String(options.batchSize ?? \"100\"), 10);\n const idleTimeoutMs = parseInt(String(options.idleTimeoutMs ?? \"900000\"), 10);\n const summary = await runReplayCliCommand(orchestrator, {\n source: sourceRaw,\n inputPath,\n from: typeof options.from === \"string\" ? options.from : undefined,\n to: typeof options.to === \"string\" ? options.to : undefined,\n dryRun: options.dryRun === true,\n startOffset: Number.isFinite(startOffset) ? Math.max(0, startOffset) : 0,\n maxTurns: Number.isFinite(maxTurnsRaw) && maxTurnsRaw > 0 ? maxTurnsRaw : undefined,\n batchSize: Number.isFinite(batchSize) && batchSize > 0 ? batchSize : 100,\n defaultSessionKey:\n typeof options.defaultSessionKey === \"string\" && options.defaultSessionKey.trim().length > 0\n ? options.defaultSessionKey.trim()\n : undefined,\n strict: options.strict === true,\n runConsolidation: options.runConsolidation === true,\n extractionIdleTimeoutMs: Number.isFinite(idleTimeoutMs) && idleTimeoutMs > 0 ? idleTimeoutMs : 900_000,\n });\n\n console.log(`Replay source: ${summary.source}`);\n console.log(`Parsed turns: ${summary.parsedTurns}`);\n console.log(`Valid turns: ${summary.validTurns}`);\n console.log(`Invalid turns: ${summary.invalidTurns}`);\n console.log(`Filtered by date: ${summary.filteredByDate}`);\n console.log(`Skipped by offset: ${summary.skippedByOffset}`);\n console.log(`Processed turns: ${summary.processedTurns}`);\n console.log(`Batches: ${summary.batchCount}`);\n console.log(`Dry run: ${summary.dryRun ? \"yes\" : \"no\"}`);\n console.log(`Next offset: ${summary.nextOffset}`);\n if (summary.firstTimestamp) console.log(`First timestamp: ${summary.firstTimestamp}`);\n if (summary.lastTimestamp) console.log(`Last timestamp: ${summary.lastTimestamp}`);\n if (summary.warnings.length > 0) {\n console.log(`Warnings (${summary.warnings.length}):`);\n for (const warning of summary.warnings.slice(0, 20)) {\n const idx = typeof warning.index === \"number\" ? ` @${warning.index}` : \"\";\n console.log(` - ${warning.code}${idx}: ${warning.message}`);\n }\n if (summary.warnings.length > 20) {\n console.log(` ... and ${summary.warnings.length - 20} more`);\n }\n }\n console.log(\"OK\");\n });\n\n cmd\n .command(\"benchmark-status\")\n .description(\"Show benchmark/evaluation harness status, benchmark packs, and latest run summary\")\n .action(async () => {\n const status = await runBenchmarkStatusCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n evalStoreDir: orchestrator.config.evalStoreDir,\n evalHarnessEnabled: orchestrator.config.evalHarnessEnabled,\n evalShadowModeEnabled: orchestrator.config.evalShadowModeEnabled,\n benchmarkBaselineSnapshotsEnabled: orchestrator.config.benchmarkBaselineSnapshotsEnabled,\n memoryRedTeamBenchEnabled: orchestrator.config.memoryRedTeamBenchEnabled,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n const benchmarkCmd = cmd\n .command(\"benchmark\")\n .description(\"Grouped benchmark and recall-evaluation operator workflows\");\n\n benchmarkCmd\n .command(\"recall\")\n .description(\"Status, validate, snapshot, or compare recall benchmark artifacts\")\n .option(\"--validate <path>\", \"Validate a benchmark pack/manifest before import or rollout\")\n .option(\"--snapshot-id <id>\", \"Compare against or create a named stored baseline snapshot\")\n .option(\"--create-snapshot\", \"Create a baseline snapshot instead of reading an existing one\")\n .option(\"--notes <text>\", \"Optional notes to attach when creating a snapshot\")\n .option(\"--git-ref <ref>\", \"Git ref to record when creating a snapshot\")\n .option(\"--created-at <iso>\", \"Override snapshot creation timestamp\")\n .option(\"--base <path>\", \"Base eval store directory for CI-style comparison\")\n .option(\"--candidate <path>\", \"Candidate eval store directory for CI-style comparison\")\n .option(\"--json\", \"Emit machine-readable JSON only\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const report = await runBenchmarkRecall({\n config: {\n memoryDir: orchestrator.config.memoryDir,\n evalStoreDir: orchestrator.config.evalStoreDir,\n evalHarnessEnabled: orchestrator.config.evalHarnessEnabled,\n evalShadowModeEnabled: orchestrator.config.evalShadowModeEnabled,\n benchmarkBaselineSnapshotsEnabled: orchestrator.config.benchmarkBaselineSnapshotsEnabled,\n benchmarkDeltaReporterEnabled: orchestrator.config.benchmarkDeltaReporterEnabled,\n memoryRedTeamBenchEnabled: orchestrator.config.memoryRedTeamBenchEnabled,\n },\n validatePath: typeof options.validate === \"string\" ? options.validate : undefined,\n baseEvalStoreDir: typeof options.base === \"string\" ? options.base : undefined,\n candidateEvalStoreDir: typeof options.candidate === \"string\" ? options.candidate : undefined,\n snapshotId: typeof options.snapshotId === \"string\" ? options.snapshotId : undefined,\n createSnapshot: options.createSnapshot === true,\n snapshotNotes: typeof options.notes === \"string\" ? options.notes : undefined,\n gitRef: typeof options.gitRef === \"string\" ? options.gitRef : undefined,\n createdAt: typeof options.createdAt === \"string\" ? options.createdAt : undefined,\n });\n if (reportHasMachineReadableOutput(options)) {\n console.log(JSON.stringify(report, null, 2));\n } else {\n console.log(formatBenchmarkRecallCli(report));\n }\n const passed = report.ciGate?.passed ?? report.baselineReport?.passed ?? true;\n if (!passed) {\n process.exitCode = 1;\n return;\n }\n if (!reportHasMachineReadableOutput(options)) console.log(\"OK\");\n });\n\n cmd\n .command(\"benchmark-validate\")\n .description(\"Validate a benchmark manifest file or pack directory without importing it\")\n .argument(\"<path>\", \"Path to a benchmark manifest JSON file or a directory with manifest.json\")\n .action(async (...args: unknown[]) => {\n const inputPath = args[0];\n const summary = await runBenchmarkValidateCliCommand({\n path: typeof inputPath === \"string\" ? inputPath : \"\",\n memoryRedTeamBenchEnabled: orchestrator.config.memoryRedTeamBenchEnabled,\n });\n console.log(JSON.stringify(summary, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"benchmark-baseline-snapshot\")\n .description(\"Capture a versioned baseline snapshot of the latest completed benchmark runs\")\n .requiredOption(\"--snapshot-id <id>\", \"Stable snapshot identifier\")\n .option(\"--created-at <iso>\", \"Override snapshot creation timestamp\")\n .option(\"--git-ref <ref>\", \"Override the git ref recorded in the snapshot\")\n .option(\"--notes <text>\", \"Optional operator notes for the snapshot\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const summary = await runBenchmarkBaselineSnapshotCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n evalStoreDir: orchestrator.config.evalStoreDir,\n benchmarkBaselineSnapshotsEnabled: orchestrator.config.benchmarkBaselineSnapshotsEnabled,\n snapshotId: typeof options.snapshotId === \"string\" ? options.snapshotId : \"\",\n createdAt: typeof options.createdAt === \"string\" ? options.createdAt : undefined,\n gitRef: typeof options.gitRef === \"string\" ? options.gitRef : undefined,\n notes: typeof options.notes === \"string\" ? options.notes : undefined,\n });\n console.log(JSON.stringify(summary, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"benchmark-import\")\n .description(\"Validate and import a benchmark manifest file or pack directory into Engram's eval store\")\n .argument(\"<path>\", \"Path to a benchmark manifest JSON file or a directory with manifest.json\")\n .option(\"--force\", \"Replace an existing imported benchmark pack with the same benchmarkId\")\n .action(async (...args: unknown[]) => {\n const inputPath = args[0];\n const options = (args[1] ?? {}) as Record<string, unknown>;\n const summary = await runBenchmarkImportCliCommand({\n path: typeof inputPath === \"string\" ? inputPath : \"\",\n memoryDir: orchestrator.config.memoryDir,\n evalStoreDir: orchestrator.config.evalStoreDir,\n force: options.force === true,\n memoryRedTeamBenchEnabled: orchestrator.config.memoryRedTeamBenchEnabled,\n });\n console.log(JSON.stringify(summary, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"benchmark-ci-gate\")\n .description(\"Compare two eval stores and fail when the candidate regresses benchmark outcomes\")\n .requiredOption(\"--base <path>\", \"Path to the base eval store directory\")\n .requiredOption(\"--candidate <path>\", \"Path to the candidate eval store directory\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const summary = await runBenchmarkCiGateCliCommand({\n baseEvalStoreDir: typeof options.base === \"string\" ? options.base : \"\",\n candidateEvalStoreDir: typeof options.candidate === \"string\" ? options.candidate : \"\",\n });\n console.log(JSON.stringify(summary, null, 2));\n if (!summary.passed) {\n throw new Error(\"benchmark CI gate detected regressions\");\n }\n console.log(\"OK\");\n });\n\n cmd\n .command(\"benchmark-baseline-report\")\n .description(\"Compare the current eval store against a named stored benchmark baseline snapshot\")\n .requiredOption(\"--snapshot-id <id>\", \"Stable baseline snapshot identifier\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const summary = await runBenchmarkBaselineReportCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n evalStoreDir: orchestrator.config.evalStoreDir,\n benchmarkDeltaReporterEnabled: orchestrator.config.benchmarkDeltaReporterEnabled,\n snapshotId: typeof options.snapshotId === \"string\" ? options.snapshotId : \"\",\n });\n const { markdownReport, ...jsonSummary } = summary;\n console.log(JSON.stringify(jsonSummary, null, 2));\n console.log(markdownReport);\n if (!summary.passed) {\n throw new Error(\"benchmark baseline report detected regressions\");\n }\n console.log(\"OK\");\n });\n\n cmd\n .command(\"objective-state-status\")\n .description(\"Show objective-state store status, snapshot counts, and latest stored snapshot\")\n .action(async () => {\n const status = await runObjectiveStateStatusCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n objectiveStateStoreDir: orchestrator.config.objectiveStateStoreDir,\n objectiveStateMemoryEnabled: orchestrator.config.objectiveStateMemoryEnabled,\n objectiveStateSnapshotWritesEnabled: orchestrator.config.objectiveStateSnapshotWritesEnabled,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"causal-trajectory-status\")\n .description(\"Show causal-trajectory store status, record counts, and latest stored chain\")\n .action(async () => {\n const status = await runCausalTrajectoryStatusCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n causalTrajectoryStoreDir: orchestrator.config.causalTrajectoryStoreDir,\n causalTrajectoryMemoryEnabled: orchestrator.config.causalTrajectoryMemoryEnabled,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"trust-zone-status\")\n .description(\"Show trust-zone store status, zoned record counts, and latest stored record\")\n .action(async () => {\n const status = await runTrustZoneStatusCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n trustZoneStoreDir: orchestrator.config.trustZoneStoreDir,\n trustZonesEnabled: orchestrator.config.trustZonesEnabled,\n quarantinePromotionEnabled: orchestrator.config.quarantinePromotionEnabled,\n memoryPoisoningDefenseEnabled: orchestrator.config.memoryPoisoningDefenseEnabled,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"trust-zone-demo-seed\")\n .description(\"Explicitly seed an opt-in trust-zone demo dataset for buyer-facing walkthroughs\")\n .option(\"--scenario <scenario>\", \"Demo scenario id (default: enterprise-buyer-v1)\")\n .option(\"--recorded-at <isoTimestamp>\", \"Base ISO timestamp used to anchor demo records\")\n .option(\"--dry-run\", \"Preview the demo dataset without writing any trust-zone records\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const result = await runTrustZoneDemoSeedCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n trustZoneStoreDir: orchestrator.config.trustZoneStoreDir,\n trustZonesEnabled: orchestrator.config.trustZonesEnabled,\n scenario: typeof options.scenario === \"string\" ? options.scenario : undefined,\n recordedAt: typeof options.recordedAt === \"string\" ? options.recordedAt : undefined,\n dryRun: options.dryRun === true,\n });\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"abstraction-node-status\")\n .description(\"Show abstraction-node store status, abstraction counts, and latest stored node\")\n .action(async () => {\n const status = await runAbstractionNodeStatusCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n abstractionNodeStoreDir: orchestrator.config.abstractionNodeStoreDir,\n harmonicRetrievalEnabled: orchestrator.config.harmonicRetrievalEnabled,\n abstractionAnchorsEnabled: orchestrator.config.abstractionAnchorsEnabled,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"cue-anchor-status\")\n .description(\"Show cue-anchor index status, anchor counts, and the latest stored cue anchor\")\n .action(async () => {\n const status = await runCueAnchorStatusCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n abstractionNodeStoreDir: orchestrator.config.abstractionNodeStoreDir,\n harmonicRetrievalEnabled: orchestrator.config.harmonicRetrievalEnabled,\n abstractionAnchorsEnabled: orchestrator.config.abstractionAnchorsEnabled,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"harmonic-search\")\n .description(\"Preview harmonic retrieval blending over abstraction nodes and cue anchors\")\n .argument(\"<query>\", \"Prompt-like query to evaluate against harmonic retrieval storage\")\n .option(\"--max-results <count>\", \"Maximum number of blended results to return\", \"3\")\n .option(\"--session-key <sessionKey>\", \"Optional session key for same-session tie-breaking\")\n .action(async (...args: unknown[]) => {\n const query = typeof args[0] === \"string\" ? args[0] : \"\";\n const options = (args[1] ?? {}) as Record<string, unknown>;\n const maxResults = typeof options.maxResults === \"string\"\n ? Number.parseInt(options.maxResults, 10)\n : 3;\n const results = await runHarmonicSearchCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n abstractionNodeStoreDir: orchestrator.config.abstractionNodeStoreDir,\n harmonicRetrievalEnabled: orchestrator.config.harmonicRetrievalEnabled,\n abstractionAnchorsEnabled: orchestrator.config.abstractionAnchorsEnabled,\n query,\n maxResults: Number.isFinite(maxResults) ? maxResults : 3,\n sessionKey: typeof options.sessionKey === \"string\" ? options.sessionKey : undefined,\n });\n console.log(JSON.stringify(results, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"utility-status\")\n .description(\"Show utility-learning telemetry status, event counts, and the latest utility event\")\n .action(async () => {\n const status = await runUtilityTelemetryStatusCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n memoryUtilityLearningEnabled: orchestrator.config.memoryUtilityLearningEnabled,\n promotionByOutcomeEnabled: orchestrator.config.promotionByOutcomeEnabled,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"utility-record\")\n .description(\"Record a utility-learning telemetry event when utility learning is enabled\")\n .requiredOption(\"--event-id <eventId>\", \"Utility telemetry event id\")\n .requiredOption(\"--recorded-at <recordedAt>\", \"ISO timestamp for the event\")\n .requiredOption(\"--session-key <sessionKey>\", \"Session key associated with the event\")\n .requiredOption(\"--source <source>\", \"Event source (cli|system|benchmark|tool_result)\")\n .requiredOption(\"--target <target>\", \"Telemetry target (promotion|ranking)\")\n .requiredOption(\"--decision <decision>\", \"Decision taken (promote|demote|hold|boost|suppress)\")\n .requiredOption(\"--outcome <outcome>\", \"Observed outcome (helpful|neutral|harmful)\")\n .requiredOption(\"--utility-score <utilityScore>\", \"Bounded utility score between -1 and 1\")\n .requiredOption(\"--summary <summary>\", \"Human-readable summary of the measured utility event\")\n .option(\"--memory-id <memoryId...>\", \"Memory ids linked to the utility event\")\n .option(\"--entity-ref <entityRef...>\", \"Entity refs linked to the utility event\")\n .option(\"--tag <tag...>\", \"Tags to attach to the utility event\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const utilityScore = typeof options.utilityScore === \"string\"\n ? Number.parseFloat(options.utilityScore)\n : Number.NaN;\n const filePath = await runUtilityTelemetryRecordCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n memoryUtilityLearningEnabled: orchestrator.config.memoryUtilityLearningEnabled,\n event: {\n schemaVersion: 1,\n eventId: String(options.eventId ?? \"\"),\n recordedAt: String(options.recordedAt ?? \"\"),\n sessionKey: String(options.sessionKey ?? \"\"),\n source: String(options.source ?? \"\") as UtilityTelemetryEvent[\"source\"],\n target: String(options.target ?? \"\") as UtilityTelemetryEvent[\"target\"],\n decision: String(options.decision ?? \"\") as UtilityTelemetryEvent[\"decision\"],\n outcome: String(options.outcome ?? \"\") as UtilityTelemetryEvent[\"outcome\"],\n utilityScore,\n summary: String(options.summary ?? \"\"),\n memoryIds: Array.isArray(options.memoryId) ? options.memoryId.map(String) : undefined,\n entityRefs: Array.isArray(options.entityRef) ? options.entityRef.map(String) : undefined,\n tags: Array.isArray(options.tag) ? options.tag.map(String) : undefined,\n },\n });\n console.log(JSON.stringify({ wrote: filePath !== null, filePath }, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"utility-learning-status\")\n .description(\"Show offline utility-learning snapshot status and learned weight counts\")\n .action(async () => {\n const status = await runUtilityLearningStatusCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n memoryUtilityLearningEnabled: orchestrator.config.memoryUtilityLearningEnabled,\n promotionByOutcomeEnabled: orchestrator.config.promotionByOutcomeEnabled,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"utility-learn\")\n .description(\"Learn bounded offline promotion/ranking weights from recorded utility telemetry\")\n .option(\"--window-days <days>\", \"Telemetry lookback window in days\", \"14\")\n .option(\"--min-event-count <count>\", \"Minimum event count required per target/decision group\", \"3\")\n .option(\"--max-weight-magnitude <value>\", \"Maximum absolute learned weight magnitude\", \"0.35\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const learningWindowDays = typeof options.windowDays === \"string\"\n ? Number.parseInt(options.windowDays, 10)\n : 14;\n const minEventCount = typeof options.minEventCount === \"string\"\n ? Number.parseInt(options.minEventCount, 10)\n : 3;\n const maxWeightMagnitude = typeof options.maxWeightMagnitude === \"string\"\n ? Number.parseFloat(options.maxWeightMagnitude)\n : 0.35;\n const result = await runUtilityLearningCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n memoryUtilityLearningEnabled: orchestrator.config.memoryUtilityLearningEnabled,\n learningWindowDays,\n minEventCount,\n maxWeightMagnitude,\n });\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"resume-bundle-status\")\n .description(\"Show resume bundle status, bundle counts, and the latest recorded handoff bundle\")\n .action(async () => {\n const status = await runResumeBundleStatusCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n resumeBundleDir: orchestrator.config.resumeBundleDir,\n creationMemoryEnabled: orchestrator.config.creationMemoryEnabled,\n resumeBundlesEnabled: orchestrator.config.resumeBundlesEnabled,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"resume-bundle-record\")\n .description(\"Record an explicit resume bundle when creation-memory handoff bundles are enabled\")\n .requiredOption(\"--bundle-id <bundleId>\", \"Resume bundle id\")\n .requiredOption(\"--recorded-at <recordedAt>\", \"ISO timestamp for the bundle\")\n .requiredOption(\"--session-key <sessionKey>\", \"Session key that owns the bundle\")\n .requiredOption(\"--source <source>\", \"Bundle source (tool_result|cli|system|manual)\")\n .requiredOption(\"--scope <scope>\", \"Primary scope or recovery domain for the bundle\")\n .requiredOption(\"--summary <summary>\", \"Human-readable summary of what this bundle preserves\")\n .option(\"--key-fact <keyFact...>\", \"Short facts that a resumed agent should retain\")\n .option(\"--next-action <nextAction...>\", \"Explicit next actions for the resumed agent\")\n .option(\"--risk-flag <riskFlag...>\", \"Open risks or cautions attached to the bundle\")\n .option(\n \"--objective-state-snapshot-ref <objectiveStateSnapshotRef...>\",\n \"Objective-state snapshot refs attached to the bundle\",\n )\n .option(\n \"--work-product-entry-ref <workProductEntryRef...>\",\n \"Work-product ledger refs attached to the bundle\",\n )\n .option(\n \"--commitment-entry-ref <commitmentEntryRef...>\",\n \"Commitment ledger refs attached to the bundle\",\n )\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const filePath = await runResumeBundleRecordCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n resumeBundleDir: orchestrator.config.resumeBundleDir,\n creationMemoryEnabled: orchestrator.config.creationMemoryEnabled,\n resumeBundlesEnabled: orchestrator.config.resumeBundlesEnabled,\n bundle: {\n schemaVersion: 1,\n bundleId: String(options.bundleId ?? \"\"),\n recordedAt: String(options.recordedAt ?? \"\"),\n sessionKey: String(options.sessionKey ?? \"\"),\n source: String(options.source ?? \"\") as ResumeBundle[\"source\"],\n scope: String(options.scope ?? \"\"),\n summary: String(options.summary ?? \"\"),\n keyFacts: Array.isArray(options.keyFact) ? options.keyFact.map(String) : undefined,\n nextActions: Array.isArray(options.nextAction) ? options.nextAction.map(String) : undefined,\n riskFlags: Array.isArray(options.riskFlag) ? options.riskFlag.map(String) : undefined,\n objectiveStateSnapshotRefs: Array.isArray(options.objectiveStateSnapshotRef)\n ? options.objectiveStateSnapshotRef.map(String)\n : undefined,\n workProductEntryRefs: Array.isArray(options.workProductEntryRef)\n ? options.workProductEntryRef.map(String)\n : undefined,\n commitmentEntryRefs: Array.isArray(options.commitmentEntryRef)\n ? options.commitmentEntryRef.map(String)\n : undefined,\n },\n });\n console.log(JSON.stringify({ wrote: filePath !== null, filePath }, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"resume-bundle-build\")\n .description(\"Build and persist a resume bundle from transcript recovery, objective state, work products, and open commitments\")\n .requiredOption(\"--bundle-id <bundleId>\", \"Resume bundle id\")\n .requiredOption(\"--recorded-at <recordedAt>\", \"ISO timestamp for the bundle\")\n .requiredOption(\"--session-key <sessionKey>\", \"Session key that owns the bundle\")\n .requiredOption(\"--scope <scope>\", \"Primary scope or recovery domain for the bundle\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const built = await runResumeBundleBuildCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n resumeBundleDir: orchestrator.config.resumeBundleDir,\n objectiveStateStoreDir: orchestrator.config.objectiveStateStoreDir,\n workProductLedgerDir: orchestrator.config.workProductLedgerDir,\n commitmentLedgerDir: orchestrator.config.commitmentLedgerDir,\n creationMemoryEnabled: orchestrator.config.creationMemoryEnabled,\n resumeBundlesEnabled: orchestrator.config.resumeBundlesEnabled,\n transcriptEnabled: orchestrator.config.transcriptEnabled,\n objectiveStateMemoryEnabled: orchestrator.config.objectiveStateMemoryEnabled,\n commitmentLedgerEnabled: orchestrator.config.commitmentLedgerEnabled,\n bundleId: String(options.bundleId ?? \"\"),\n recordedAt: String(options.recordedAt ?? \"\"),\n sessionKey: String(options.sessionKey ?? \"\"),\n scope: String(options.scope ?? \"\"),\n });\n console.log(JSON.stringify({\n wrote: built !== null,\n filePath: built?.filePath ?? null,\n bundle: built?.bundle ?? null,\n }, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"commitment-status\")\n .description(\"Show commitment ledger status, entry counts, and the latest recorded commitment\")\n .action(async () => {\n const status = await runCommitmentStatusCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n commitmentLedgerDir: orchestrator.config.commitmentLedgerDir,\n creationMemoryEnabled: orchestrator.config.creationMemoryEnabled,\n commitmentLedgerEnabled: orchestrator.config.commitmentLedgerEnabled,\n commitmentLifecycleEnabled: orchestrator.config.commitmentLifecycleEnabled,\n commitmentStaleDays: orchestrator.config.commitmentStaleDays,\n commitmentDecayDays: orchestrator.config.commitmentDecayDays,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"commitment-record\")\n .description(\"Record a commitment ledger entry when commitment memory is enabled\")\n .requiredOption(\"--entry-id <entryId>\", \"Commitment entry id\")\n .requiredOption(\"--recorded-at <recordedAt>\", \"ISO timestamp for the entry\")\n .requiredOption(\"--session-key <sessionKey>\", \"Session key that owns the commitment\")\n .requiredOption(\"--source <source>\", \"Entry source (tool_result|cli|system|manual)\")\n .requiredOption(\"--kind <kind>\", \"Entry kind (promise|follow_up|deadline|deliverable)\")\n .requiredOption(\"--state <state>\", \"Entry state (open|fulfilled|cancelled|expired)\")\n .requiredOption(\"--scope <scope>\", \"Primary scope or identifier for the commitment\")\n .requiredOption(\"--summary <summary>\", \"Human-readable summary of the commitment\")\n .option(\"--due-at <dueAt>\", \"Optional due timestamp for the commitment\")\n .option(\"--tag <tag...>\", \"Tags to attach to the commitment entry\")\n .option(\"--entity-ref <entityRef...>\", \"Entity refs to attach to the commitment entry\")\n .option(\n \"--work-product-entry-ref <workProductEntryRef...>\",\n \"Work-product ledger refs that this commitment depends on\",\n )\n .option(\n \"--objective-state-snapshot-ref <objectiveStateSnapshotRef...>\",\n \"Objective-state snapshot refs to link to this commitment\",\n )\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const filePath = await runCommitmentRecordCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n commitmentLedgerDir: orchestrator.config.commitmentLedgerDir,\n creationMemoryEnabled: orchestrator.config.creationMemoryEnabled,\n commitmentLedgerEnabled: orchestrator.config.commitmentLedgerEnabled,\n entry: {\n schemaVersion: 1,\n entryId: String(options.entryId ?? \"\"),\n recordedAt: String(options.recordedAt ?? \"\"),\n sessionKey: String(options.sessionKey ?? \"\"),\n source: String(options.source ?? \"\") as CommitmentLedgerEntry[\"source\"],\n kind: String(options.kind ?? \"\") as CommitmentLedgerEntry[\"kind\"],\n state: String(options.state ?? \"\") as CommitmentLedgerEntry[\"state\"],\n scope: String(options.scope ?? \"\"),\n summary: String(options.summary ?? \"\"),\n dueAt: typeof options.dueAt === \"string\" ? options.dueAt : undefined,\n tags: Array.isArray(options.tag) ? options.tag.map(String) : undefined,\n entityRefs: Array.isArray(options.entityRef) ? options.entityRef.map(String) : undefined,\n workProductEntryRefs: Array.isArray(options.workProductEntryRef)\n ? options.workProductEntryRef.map(String)\n : undefined,\n objectiveStateSnapshotRefs: Array.isArray(options.objectiveStateSnapshotRef)\n ? options.objectiveStateSnapshotRef.map(String)\n : undefined,\n },\n });\n console.log(JSON.stringify({ wrote: filePath !== null, filePath }, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"commitment-set-state\")\n .description(\"Transition an existing commitment ledger entry when commitment lifecycle is enabled\")\n .requiredOption(\"--entry-id <entryId>\", \"Commitment entry id\")\n .requiredOption(\"--state <state>\", \"Next state (open|fulfilled|cancelled|expired)\")\n .requiredOption(\"--changed-at <changedAt>\", \"ISO timestamp for the lifecycle transition\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const entry = await runCommitmentSetStateCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n commitmentLedgerDir: orchestrator.config.commitmentLedgerDir,\n creationMemoryEnabled: orchestrator.config.creationMemoryEnabled,\n commitmentLedgerEnabled: orchestrator.config.commitmentLedgerEnabled,\n commitmentLifecycleEnabled: orchestrator.config.commitmentLifecycleEnabled,\n entryId: String(options.entryId ?? \"\"),\n nextState: String(options.state ?? \"\") as CommitmentLedgerEntry[\"state\"],\n changedAt: String(options.changedAt ?? \"\"),\n });\n console.log(JSON.stringify({ updated: entry !== null, entry }, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"commitment-lifecycle-run\")\n .description(\"Apply overdue-expiry and resolved-entry cleanup to the commitment ledger\")\n .option(\"--now <now>\", \"Override the lifecycle timestamp for testing or backfills\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const result = await runCommitmentLifecycleCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n commitmentLedgerDir: orchestrator.config.commitmentLedgerDir,\n creationMemoryEnabled: orchestrator.config.creationMemoryEnabled,\n commitmentLedgerEnabled: orchestrator.config.commitmentLedgerEnabled,\n commitmentLifecycleEnabled: orchestrator.config.commitmentLifecycleEnabled,\n commitmentDecayDays: orchestrator.config.commitmentDecayDays,\n now: typeof options.now === \"string\" ? options.now : undefined,\n });\n console.log(JSON.stringify({ applied: result !== null, result }, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"work-product-status\")\n .description(\"Show work-product ledger status, entry counts, and the latest recorded work product\")\n .action(async () => {\n const status = await runWorkProductStatusCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n workProductLedgerDir: orchestrator.config.workProductLedgerDir,\n creationMemoryEnabled: orchestrator.config.creationMemoryEnabled,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"work-product-record\")\n .description(\"Record a work-product ledger entry when creation-memory is enabled\")\n .requiredOption(\"--entry-id <entryId>\", \"Ledger entry id\")\n .requiredOption(\"--recorded-at <recordedAt>\", \"ISO timestamp for the entry\")\n .requiredOption(\"--session-key <sessionKey>\", \"Session key that created the work product\")\n .requiredOption(\"--source <source>\", \"Entry source (tool_result|cli|system|manual)\")\n .requiredOption(\"--kind <kind>\", \"Entry kind (artifact|file|record|report|workspace)\")\n .requiredOption(\n \"--entry-action <entryAction>\",\n \"Entry action (created|updated|deleted|referenced|published)\",\n )\n .requiredOption(\"--scope <scope>\", \"Primary scope or identifier for the created work product\")\n .requiredOption(\"--summary <summary>\", \"Human-readable summary of the work product\")\n .option(\"--artifact-path <artifactPath>\", \"Optional path to the created artifact\")\n .option(\"--tag <tag...>\", \"Tags to attach to the work-product entry\")\n .option(\"--entity-ref <entityRef...>\", \"Entity refs to attach to the work-product entry\")\n .option(\n \"--objective-state-snapshot-ref <objectiveStateSnapshotRef...>\",\n \"Objective-state snapshot refs to link to this work product\",\n )\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const filePath = await runWorkProductRecordCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n workProductLedgerDir: orchestrator.config.workProductLedgerDir,\n creationMemoryEnabled: orchestrator.config.creationMemoryEnabled,\n entry: {\n schemaVersion: 1,\n entryId: String(options.entryId ?? \"\"),\n recordedAt: String(options.recordedAt ?? \"\"),\n sessionKey: String(options.sessionKey ?? \"\"),\n source: String(options.source ?? \"\") as WorkProductLedgerEntry[\"source\"],\n kind: String(options.kind ?? \"\") as WorkProductLedgerEntry[\"kind\"],\n action: String(options.entryAction ?? \"\") as WorkProductLedgerEntry[\"action\"],\n scope: String(options.scope ?? \"\"),\n summary: String(options.summary ?? \"\"),\n artifactPath: typeof options.artifactPath === \"string\" ? options.artifactPath : undefined,\n tags: Array.isArray(options.tag) ? options.tag.map(String) : undefined,\n entityRefs: Array.isArray(options.entityRef) ? options.entityRef.map(String) : undefined,\n objectiveStateSnapshotRefs: Array.isArray(options.objectiveStateSnapshotRef)\n ? options.objectiveStateSnapshotRef.map(String)\n : undefined,\n },\n });\n console.log(JSON.stringify({ wrote: filePath !== null, filePath }, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"work-product-recall-search\")\n .description(\"Preview work-product recovery candidates when creation-memory recall is enabled\")\n .argument(\"<query>\", \"Prompt-like query to evaluate against the work-product ledger\")\n .option(\"--max-results <count>\", \"Maximum number of work-product results to return\", \"3\")\n .option(\"--session-key <sessionKey>\", \"Optional session key to boost same-session work products\")\n .action(async (...args: unknown[]) => {\n const query = typeof args[0] === \"string\" ? args[0] : \"\";\n const options = (args[1] ?? {}) as Record<string, unknown>;\n const maxResults = typeof options.maxResults === \"string\"\n ? Number.parseInt(options.maxResults, 10)\n : 3;\n const results = await runWorkProductRecallSearchCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n workProductLedgerDir: orchestrator.config.workProductLedgerDir,\n creationMemoryEnabled: orchestrator.config.creationMemoryEnabled,\n workProductRecallEnabled: orchestrator.config.workProductRecallEnabled,\n query,\n maxResults: Number.isFinite(maxResults) ? maxResults : 3,\n sessionKey: typeof options.sessionKey === \"string\" ? options.sessionKey : undefined,\n });\n console.log(JSON.stringify(results, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"trust-zone-promote\")\n .description(\"Dry-run or apply a trust-zone promotion with provenance enforcement\")\n .requiredOption(\"--record-id <recordId>\", \"Source trust-zone record id\")\n .requiredOption(\"--target-zone <targetZone>\", \"Promotion target zone (working|trusted)\")\n .requiredOption(\"--reason <reason>\", \"Human-readable promotion reason\")\n .option(\"--recorded-at <isoTimestamp>\", \"Promotion timestamp (defaults to now)\")\n .option(\"--summary <summary>\", \"Optional replacement summary for the promoted record\")\n .option(\"--dry-run\", \"Show the promotion plan without writing the promoted record\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const result = await runTrustZonePromoteCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n trustZoneStoreDir: orchestrator.config.trustZoneStoreDir,\n trustZonesEnabled: orchestrator.config.trustZonesEnabled,\n quarantinePromotionEnabled: orchestrator.config.quarantinePromotionEnabled,\n memoryPoisoningDefenseEnabled: orchestrator.config.memoryPoisoningDefenseEnabled,\n sourceRecordId: String(options.recordId ?? \"\"),\n targetZone: String(options.targetZone ?? \"\") as TrustZoneName,\n promotionReason: String(options.reason ?? \"\"),\n recordedAt: typeof options.recordedAt === \"string\" ? options.recordedAt : undefined,\n summary: typeof options.summary === \"string\" ? options.summary : undefined,\n dryRun: options.dryRun === true,\n });\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"verified-recall-search\")\n .description(\"Preview verified episodic recall over recent memory boxes\")\n .argument(\"<query>\", \"Prompt-like query to evaluate against verified episodic recall\")\n .option(\"--max-results <count>\", \"Maximum number of verified episodic results to return\", \"3\")\n .action(async (...args: unknown[]) => {\n const query = typeof args[0] === \"string\" ? args[0] : \"\";\n const options = (args[1] ?? {}) as Record<string, unknown>;\n const maxResults = typeof options.maxResults === \"string\"\n ? Number.parseInt(options.maxResults, 10)\n : 3;\n const results = await runVerifiedRecallSearchCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n verifiedRecallEnabled: orchestrator.config.verifiedRecallEnabled,\n query,\n maxResults: Number.isFinite(maxResults) ? maxResults : 3,\n boxRecallDays: orchestrator.config.boxRecallDays,\n });\n console.log(JSON.stringify(results, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"semantic-rule-promote\")\n .description(\"Promote an explicit IF/THEN rule from a verified episodic memory\")\n .requiredOption(\"--memory-id <memoryId>\", \"Verified episodic memory id to promote from\")\n .option(\"--dry-run\", \"Preview the promoted semantic rule without writing it\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const result = await runSemanticRulePromoteCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n semanticRulePromotionEnabled: orchestrator.config.semanticRulePromotionEnabled,\n sourceMemoryId: String(options.memoryId ?? \"\"),\n dryRun: options.dryRun === true,\n });\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"compounding-promote\")\n .description(\"Promote an advisory compounding candidate into a durable rule/principle memory\")\n .requiredOption(\"--week-id <weekId>\", \"Weekly compounding artifact id (YYYY-Www)\")\n .requiredOption(\"--candidate-id <candidateId>\", \"Promotion candidate id from weekly compounding JSON/report\")\n .option(\"--dry-run\", \"Preview the promoted guidance without writing it\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const result = await runCompoundingPromoteCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n compoundingEnabled: orchestrator.config.compoundingEnabled,\n compoundingSemanticEnabled: orchestrator.config.compoundingSemanticEnabled,\n weekId: String(options.weekId ?? \"\"),\n candidateId: String(options.candidateId ?? \"\"),\n dryRun: options.dryRun === true,\n });\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"semantic-rule-verify\")\n .description(\"Preview verified semantic-rule recall with provenance-aware confidence downgrades\")\n .argument(\"<query>\", \"Prompt-like query to evaluate against verified semantic-rule recall\")\n .option(\"--max-results <count>\", \"Maximum number of verified semantic rules to return\", \"3\")\n .action(async (...args: unknown[]) => {\n const query = typeof args[0] === \"string\" ? args[0] : \"\";\n const options = (args[1] ?? {}) as Record<string, unknown>;\n const maxResults = typeof options.maxResults === \"string\"\n ? Number.parseInt(options.maxResults, 10)\n : 3;\n const results = await runSemanticRuleVerifyCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n semanticRuleVerificationEnabled: orchestrator.config.semanticRuleVerificationEnabled,\n query,\n maxResults: Number.isFinite(maxResults) ? maxResults : 3,\n });\n console.log(JSON.stringify(results, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"conversation-index-health\")\n .description(\"Show conversation index backend health and index stats\")\n .action(async () => {\n const health = await runConversationIndexHealthCliCommand(orchestrator);\n console.log(JSON.stringify(health, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"conversation-index-inspect\")\n .description(\"Inspect conversation index backend metadata and artifact state\")\n .action(async () => {\n const inspection = await runConversationIndexInspectCliCommand(orchestrator);\n console.log(JSON.stringify(inspection, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"conversation-index-rebuild\")\n .description(\"Rebuild the conversation index backend from transcript history\")\n .option(\"--session-key <sessionKey>\", \"Optional session key to rebuild instead of all recent transcripts\")\n .option(\"--hours <count>\", \"Hours of transcript history to scan\", \"24\")\n .option(\"--embed\", \"Force embedding step for backends that support it\")\n .action(buildConversationIndexRebuildAction(orchestrator));\n\n cmd\n .command(\"rebuild-index\")\n .description(\"Alias for conversation-index-rebuild with operator-friendly naming\")\n .option(\"--session-key <sessionKey>\", \"Optional session key to rebuild instead of all recent transcripts\")\n .option(\"--hours <count>\", \"Hours of transcript history to scan\", \"24\")\n .option(\"--embed\", \"Force embedding step for backends that support it\")\n .action(buildConversationIndexRebuildAction(orchestrator));\n\n cmd\n .command(\"graph-health\")\n .description(\"Show graph edge-file integrity, node coverage, and corruption counts\")\n .option(\"--repair-guidance\", \"Include non-destructive repair guidance\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const report = await runGraphHealthCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n entityGraphEnabled: orchestrator.config.entityGraphEnabled,\n timeGraphEnabled: orchestrator.config.timeGraphEnabled,\n causalGraphEnabled: orchestrator.config.causalGraphEnabled,\n includeRepairGuidance: options.repairGuidance === true,\n });\n console.log(JSON.stringify(report, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"session-check\")\n .description(\"Analyze transcript/checkpoint continuity integrity without mutating files\")\n .action(async () => {\n const report = await runSessionCheckCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n });\n console.log(JSON.stringify(report, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"session-repair\")\n .description(\"Generate/apply bounded Engram session integrity repairs (dry-run by default)\")\n .option(\"--apply\", \"Apply repairs (default: dry-run)\")\n .option(\"--dry-run\", \"Force dry-run output\")\n .option(\"--allow-session-file-repair\", \"Allow explicit OpenClaw session-file repair path (still no automatic rewiring)\")\n .option(\"--session-files-dir <path>\", \"Optional OpenClaw session files directory for guarded repair workflow\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const result = await runSessionRepairCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n apply: options.apply === true,\n dryRun: options.dryRun === true,\n allowSessionFileRepair: options.allowSessionFileRepair === true,\n sessionFilesDir:\n typeof options.sessionFilesDir === \"string\" && options.sessionFilesDir.trim().length > 0\n ? options.sessionFilesDir.trim()\n : undefined,\n });\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"repair\")\n .description(\"Aggregate safe repair planning across session integrity and graph health\")\n .option(\"--apply\", \"Apply bounded Engram-managed session repairs\")\n .option(\"--dry-run\", \"Force dry-run output\")\n .option(\"--allow-session-file-repair\", \"Allow explicit OpenClaw session-file repair path (still no automatic rewiring)\")\n .option(\"--session-files-dir <path>\", \"Optional OpenClaw session files directory for guarded repair workflow\")\n .option(\"--json\", \"Emit machine-readable JSON only\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const report = await runOperatorRepair({\n config: {\n memoryDir: orchestrator.config.memoryDir,\n entityGraphEnabled: orchestrator.config.entityGraphEnabled,\n timeGraphEnabled: orchestrator.config.timeGraphEnabled,\n causalGraphEnabled: orchestrator.config.causalGraphEnabled,\n },\n apply: options.apply === true,\n dryRun: options.dryRun === true,\n allowSessionFileRepair: options.allowSessionFileRepair === true,\n sessionFilesDir:\n typeof options.sessionFilesDir === \"string\" && options.sessionFilesDir.trim().length > 0\n ? options.sessionFilesDir.trim()\n : undefined,\n });\n if (reportHasMachineReadableOutput(options)) {\n console.log(JSON.stringify(report, null, 2));\n } else {\n console.log(formatOperatorRepairCli(report));\n }\n if (!reportHasMachineReadableOutput(options)) console.log(\"OK\");\n });\n\n cmd\n .command(\"tier-status\")\n .description(\"Show tier migration telemetry and last-cycle summary\")\n .action(async () => {\n const status = await runTierStatusCliCommand(orchestrator);\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"tier-migrate\")\n .description(\"Run one tier migration pass (dry-run by default)\")\n .option(\"--dry-run\", \"Evaluate and report moves without writing\")\n .option(\"--write\", \"Apply migration writes (default: dry-run)\")\n .option(\"--limit <n>\", \"Override migration move limit for this run\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const limitRaw = parseInt(String(options.limit ?? \"\"), 10);\n const explicitDryRun = options.dryRun === true;\n const summary = await runTierMigrateCliCommand(orchestrator, {\n dryRun: explicitDryRun || options.write !== true,\n limit: Number.isFinite(limitRaw) ? Math.max(0, limitRaw) : undefined,\n });\n console.log(JSON.stringify(summary, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"policy-status\")\n .description(\"Show runtime behavior-loop policy status and top contributing signals\")\n .action(async () => {\n const status = await runPolicyStatusCliCommand(orchestrator);\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"policy-diff\")\n .description(\"Show runtime policy deltas and evidence since a relative duration (default: 7d)\")\n .option(\"--since <window>\", \"Relative duration window like 30m, 12h, 7d\", \"7d\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const since = typeof options.since === \"string\" ? options.since : \"7d\";\n const report = await runPolicyDiffCliCommand(orchestrator, { since });\n console.log(JSON.stringify(report, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"policy-rollback\")\n .description(\"Roll back runtime behavior policy to the previous snapshot\")\n .action(async () => {\n const report = await runPolicyRollbackCliCommand(orchestrator);\n console.log(JSON.stringify(report, null, 2));\n console.log(\"OK\");\n });\n\n const migrateCmd = cmd\n .command(\"migrate\")\n .description(\"Run memory migration helpers (dry-run by default)\");\n\n migrateCmd\n .command(\"normalize-frontmatter\")\n .description(\"Normalize memory frontmatter serialization\")\n .option(\"--write\", \"Apply frontmatter rewrites (default: dry-run)\")\n .option(\"--limit <n>\", \"Maximum memories to scan\", \"200\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const limitRaw = parseInt(String(options.limit ?? \"200\"), 10);\n const report = await runMigrateNormalizeFrontmatterCliCommand(orchestrator, {\n write: options.write === true,\n limit: Number.isFinite(limitRaw) ? limitRaw : 200,\n });\n console.log(JSON.stringify(report, null, 2));\n console.log(\"OK\");\n });\n\n migrateCmd\n .command(\"rescore-importance\")\n .description(\"Recompute memory importance scores using current local heuristics\")\n .option(\"--write\", \"Apply frontmatter updates (default: dry-run)\")\n .option(\"--limit <n>\", \"Maximum memories to scan\", \"200\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const limitRaw = parseInt(String(options.limit ?? \"200\"), 10);\n const report = await runMigrateRescoreImportanceCliCommand(orchestrator, {\n write: options.write === true,\n limit: Number.isFinite(limitRaw) ? limitRaw : 200,\n });\n console.log(JSON.stringify(report, null, 2));\n console.log(\"OK\");\n });\n\n migrateCmd\n .command(\"rechunk\")\n .description(\"Rebuild chunk files from current chunking heuristics\")\n .option(\"--write\", \"Apply chunk rewrites (default: dry-run)\")\n .option(\"--limit <n>\", \"Maximum parent memories to scan\", \"200\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const limitRaw = parseInt(String(options.limit ?? \"200\"), 10);\n const report = await runMigrateRechunkCliCommand(orchestrator, {\n write: options.write === true,\n limit: Number.isFinite(limitRaw) ? limitRaw : 200,\n });\n console.log(JSON.stringify(report, null, 2));\n console.log(\"OK\");\n });\n\n migrateCmd\n .command(\"reextract\")\n .description(\"Queue bounded memory re-extraction jobs for an explicit model\")\n .option(\"--model <id>\", \"Model id used for re-extraction request\")\n .option(\"--write\", \"Queue re-extraction jobs (default: dry-run)\")\n .option(\"--limit <n>\", \"Maximum memories to queue\", \"100\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const model = typeof options.model === \"string\" ? options.model : \"\";\n const limitRaw = parseInt(String(options.limit ?? \"100\"), 10);\n const report = await runMigrateReextractCliCommand(orchestrator, {\n model,\n write: options.write === true,\n limit: Number.isFinite(limitRaw) ? limitRaw : 100,\n });\n console.log(JSON.stringify(report, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"action-audit\")\n .description(\"Show namespace-aware memory action policy outcomes\")\n .option(\"--namespace <name>\", \"Filter to a single namespace\")\n .option(\"--limit <n>\", \"Max events to read per namespace\", \"200\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const limitRaw = parseInt(String(options.limit ?? \"200\"), 10);\n const report = await runMemoryActionAuditCliCommand(orchestrator, {\n namespace:\n typeof options.namespace === \"string\" && options.namespace.trim().length > 0\n ? options.namespace.trim()\n : undefined,\n limit: Number.isFinite(limitRaw) ? Math.max(0, limitRaw) : 200,\n });\n console.log(JSON.stringify(report, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"tailscale-status\")\n .description(\"Show Tailscale availability and daemon status\")\n .option(\"--timeout-ms <n>\", \"Command timeout in milliseconds\", \"10000\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const timeoutMsRaw = parseInt(String(options.timeoutMs ?? \"10000\"), 10);\n const status = await runTailscaleStatusCliCommand({\n timeoutMs: Number.isFinite(timeoutMsRaw) && timeoutMsRaw > 0 ? timeoutMsRaw : 10_000,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"tailscale-sync\")\n .description(\"Sync a local memory directory to a Tailscale destination using rsync\")\n .option(\"--source-dir <path>\", \"Source directory to sync\")\n .option(\"--destination <target>\", \"Rsync destination (for example host:/path)\")\n .option(\"--delete\", \"Delete destination entries that do not exist in source\")\n .option(\"--dry-run\", \"Show what would change without writing\")\n .option(\"--extra-args <csv>\", \"Additional rsync args as comma-separated values\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const sourceDir = typeof options.sourceDir === \"string\" ? options.sourceDir.trim() : \"\";\n const destination = typeof options.destination === \"string\" ? options.destination.trim() : \"\";\n if (!sourceDir) {\n throw new Error(\"missing --source-dir\");\n }\n if (!destination) {\n throw new Error(\"missing --destination\");\n }\n const extraArgs = typeof options.extraArgs === \"string\"\n ? options.extraArgs\n .split(\",\")\n .map((value) => value.trim())\n .filter((value) => value.length > 0)\n : undefined;\n\n await runTailscaleSyncCliCommand({\n sourceDir,\n destination,\n delete: options.delete === true,\n dryRun: options.dryRun === true,\n extraArgs,\n });\n console.log(\"OK\");\n });\n\n cmd\n .command(\"webdav-serve\")\n .description(\"Start local WebDAV service for allowlisted directories\")\n .option(\"--allowlist <csv>\", \"Comma-separated directories to expose\")\n .option(\"--host <host>\", \"Bind host\", \"127.0.0.1\")\n .option(\"--port <n>\", \"Bind port\", \"8080\")\n .option(\"--username <username>\", \"Optional basic auth username\")\n .option(\"--password <password>\", \"Optional basic auth password\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const allowlistRaw = typeof options.allowlist === \"string\" ? options.allowlist : \"\";\n const allowlistDirs = allowlistRaw\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n if (allowlistDirs.length === 0) {\n throw new Error(\"missing --allowlist\");\n }\n const portRaw = parseInt(String(options.port ?? \"8080\"), 10);\n const status = await runWebDavServeCliCommand({\n allowlistDirs,\n host: typeof options.host === \"string\" ? options.host : \"127.0.0.1\",\n port: Number.isFinite(portRaw) ? portRaw : 8080,\n authUsername: typeof options.username === \"string\" ? options.username : undefined,\n authPassword: typeof options.password === \"string\" ? options.password : undefined,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"webdav-stop\")\n .description(\"Stop the in-process WebDAV service\")\n .action(async () => {\n const result = await runWebDavStopCliCommand();\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n });\n\n const dashboardCmd = cmd\n .command(\"dashboard\")\n .description(\"Manage live graph dashboard service\");\n\n dashboardCmd\n .command(\"start\")\n .description(\"Start dashboard server (localhost by default)\")\n .option(\"--host <host>\", \"Bind host\", \"127.0.0.1\")\n .option(\"--port <n>\", \"Bind port\", \"4319\")\n .option(\"--public-dir <path>\", \"Override static dashboard assets path\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const portRaw = parseInt(String(options.port ?? \"4319\"), 10);\n const status = await runDashboardStartCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n host: typeof options.host === \"string\" ? options.host : \"127.0.0.1\",\n port: Number.isFinite(portRaw) ? portRaw : 4319,\n publicDir: typeof options.publicDir === \"string\" ? options.publicDir : undefined,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n dashboardCmd\n .command(\"stop\")\n .description(\"Stop dashboard server\")\n .action(async () => {\n const result = await runDashboardStopCliCommand();\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n });\n\n dashboardCmd\n .command(\"status\")\n .description(\"Show dashboard server status\")\n .action(async () => {\n const status = await runDashboardStatusCliCommand();\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n const accessService = new EngramAccessService(orchestrator);\n const accessCmd = cmd\n .command(\"access\")\n .description(\"Manage Engram HTTP and MCP access surfaces\");\n\n accessCmd\n .command(\"http-serve\")\n .description(\"Start local authenticated HTTP access server\")\n .option(\"--host <host>\", \"Bind host\", \"127.0.0.1\")\n .option(\"--port <n>\", \"Bind port\", \"4318\")\n .option(\"--token <token>\", \"Bearer token (defaults to config/env)\")\n .option(\"--principal <principal>\", \"Trusted principal (defaults to config/env)\")\n .option(\"--max-body-bytes <n>\", \"Maximum request body size\", \"131072\")\n .option(\"--trust-principal-header\", \"Trust the X-Engram-Principal header for per-request principal resolution. Only enable when the server is behind a trusted proxy or when the auth token provides sufficient trust.\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const portRaw = parseInt(String(options.port ?? \"4318\"), 10);\n const maxBodyBytesRaw = parseInt(String(options.maxBodyBytes ?? \"131072\"), 10);\n // Start the HTTP server FIRST so the port is available immediately,\n // then initialize the orchestrator in the background. Recall requests\n // that arrive during warmup still work — orchestrator.recall() awaits\n // its internal init gate (15s timeout) so callers get a correct (if\n // slightly delayed) response rather than \"connection refused\".\n const status = await runAccessHttpServeCliCommand({\n service: accessService,\n enabled: true,\n host: typeof options.host === \"string\" ? options.host : \"127.0.0.1\",\n port: Number.isFinite(portRaw) ? portRaw : 4318,\n authToken:\n typeof options.token === \"string\" && options.token.trim().length > 0\n ? options.token\n : orchestrator.config.agentAccessHttp.authToken,\n principal: resolveAccessPrincipalOverride(options.principal, orchestrator.config.agentAccessHttp.principal),\n maxBodyBytes: Number.isFinite(maxBodyBytesRaw) ? maxBodyBytesRaw : 131072,\n trustPrincipalHeader: options.trustPrincipalHeader === true,\n });\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n // Initialize the orchestrator AFTER the HTTP server is listening.\n // Without this call the init gate Promise never resolves, so every\n // recall waits the full 15s gate timeout — and QMD is never probed,\n // causing the embedding fallback to load a 300 MB JSON on every cold\n // path. But by running it here (not before), the port is available\n // immediately while warmup proceeds in the background.\n await orchestrator.initialize();\n });\n\n accessCmd\n .command(\"http-stop\")\n .description(\"Stop the in-process Engram HTTP access server\")\n .action(async () => {\n const result = await runAccessHttpStopCliCommand();\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n });\n\n accessCmd\n .command(\"http-status\")\n .description(\"Show Engram HTTP access server status\")\n .action(async () => {\n const status = await runAccessHttpStatusCliCommand();\n console.log(JSON.stringify(status, null, 2));\n console.log(\"OK\");\n });\n\n accessCmd\n .command(\"mcp-serve\")\n .description(\"Run the Engram MCP server over stdio\")\n .option(\"--principal <principal>\", \"Trusted principal (defaults to config/env)\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n await runAccessMcpServeCliCommand(accessService, {\n principal: resolveAccessPrincipalOverride(options.principal, orchestrator.config.agentAccessHttp.principal),\n });\n });\n\n const routeCmd = cmd\n .command(\"route\")\n .description(\"Manage custom memory routing rules\");\n\n routeCmd\n .command(\"list\")\n .description(\"List configured routing rules\")\n .action(async () => {\n const rules = await runRouteCliCommand({\n action: \"list\",\n memoryDir: orchestrator.config.memoryDir,\n stateFile: orchestrator.config.routingRulesStateFile,\n }) as RouteRule[];\n\n if (rules.length === 0) {\n console.log(\"No routing rules configured.\");\n return;\n }\n for (const rule of rules) {\n const targetParts = [\n rule.target.category ? `category=${rule.target.category}` : \"\",\n rule.target.namespace ? `namespace=${rule.target.namespace}` : \"\",\n ].filter((value) => value.length > 0);\n console.log(\n `${rule.id} type=${rule.patternType} priority=${rule.priority} pattern=\"${rule.pattern}\" target=${targetParts.join(\",\")}`,\n );\n }\n });\n\n routeCmd\n .command(\"add\")\n .description(\"Add or update a routing rule\")\n .argument(\"<pattern>\", \"Keyword or regex pattern\")\n .argument(\"<target>\", \"Target (JSON or category=<cat>,namespace=<ns>)\")\n .option(\"--type <type>\", \"Pattern type: keyword|regex\", \"keyword\")\n .option(\"--priority <n>\", \"Rule priority\", \"0\")\n .option(\"--id <id>\", \"Optional stable rule id\")\n .action(async (...args: unknown[]) => {\n const pattern = typeof args[0] === \"string\" ? args[0] : \"\";\n const targetRaw = typeof args[1] === \"string\" ? args[1] : \"\";\n const options = (args[2] ?? {}) as Record<string, unknown>;\n const patternTypeRaw = typeof options.type === \"string\" ? options.type.trim().toLowerCase() : \"keyword\";\n if (!isRoutePatternType(patternTypeRaw)) {\n throw new Error(`invalid route pattern type: ${patternTypeRaw}`);\n }\n const priorityInput = String(options.priority ?? \"0\").trim();\n if (!/^-?\\d+$/.test(priorityInput)) {\n throw new Error(`invalid route priority: ${priorityInput}`);\n }\n const priorityRaw = Number(priorityInput);\n const updated = await runRouteCliCommand({\n action: \"add\",\n memoryDir: orchestrator.config.memoryDir,\n stateFile: orchestrator.config.routingRulesStateFile,\n pattern,\n patternType: patternTypeRaw,\n priority: priorityRaw,\n targetRaw,\n id: typeof options.id === \"string\" ? options.id : undefined,\n }) as RouteRule[];\n console.log(`OK (${updated.length} rules)`);\n });\n\n routeCmd\n .command(\"remove\")\n .description(\"Remove routing rules by exact pattern\")\n .argument(\"<pattern>\", \"Pattern to remove\")\n .action(async (...args: unknown[]) => {\n const pattern = typeof args[0] === \"string\" ? args[0] : \"\";\n const next = await runRouteCliCommand({\n action: \"remove\",\n memoryDir: orchestrator.config.memoryDir,\n stateFile: orchestrator.config.routingRulesStateFile,\n pattern,\n }) as RouteRule[];\n console.log(`OK (${next.length} rules remain)`);\n });\n\n routeCmd\n .command(\"test\")\n .description(\"Test routing rule match for input text\")\n .argument(\"<text>\", \"Text to evaluate\")\n .action(async (...args: unknown[]) => {\n const text = typeof args[0] === \"string\" ? args[0] : \"\";\n const selection = await runRouteCliCommand({\n action: \"test\",\n memoryDir: orchestrator.config.memoryDir,\n stateFile: orchestrator.config.routingRulesStateFile,\n text,\n }) as { rule: RouteRule; target: RouteTarget } | null;\n if (!selection) {\n console.log(\"No route match.\");\n return;\n }\n const targetParts = [\n selection.target.category ? `category=${selection.target.category}` : \"\",\n selection.target.namespace ? `namespace=${selection.target.namespace}` : \"\",\n ].filter((value) => value.length > 0);\n console.log(\n `Matched ${selection.rule.id} type=${selection.rule.patternType} priority=${selection.rule.priority} target=${targetParts.join(\",\")}`,\n );\n });\n\n cmd\n .command(\"archive-observations\")\n .description(\"Archive aged observation artifacts (dry-run by default)\")\n .option(\"--retention-days <n>\", \"Archive files older than N days\", \"30\")\n .option(\"--write\", \"Apply archive mutations (default: dry-run)\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const retentionDays = parseInt(String(options.retentionDays ?? \"30\"), 10);\n const result = await runArchiveObservationsCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n retentionDays: Number.isFinite(retentionDays) ? retentionDays : 30,\n write: options.write === true,\n });\n\n console.log(`Dry run: ${result.dryRun ? \"yes\" : \"no\"}`);\n console.log(`Retention days: ${result.retentionDays}`);\n console.log(`Scanned files: ${result.scannedFiles}`);\n console.log(`Archived files: ${result.archivedFiles}`);\n console.log(`Archived bytes: ${result.archivedBytes}`);\n if (result.archivedRelativePaths.length > 0) {\n console.log(\"Archived paths:\");\n for (const relPath of result.archivedRelativePaths.slice(0, 20)) {\n console.log(` - ${relPath}`);\n }\n if (result.archivedRelativePaths.length > 20) {\n console.log(` ... and ${result.archivedRelativePaths.length - 20} more`);\n }\n }\n console.log(\"OK\");\n });\n\n cmd\n .command(\"rebuild-observations\")\n .description(\"Rebuild observation ledger from transcript history (dry-run by default)\")\n .option(\"--write\", \"Write rebuilt ledger (default: dry-run)\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const result = await runRebuildObservationsCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n write: options.write === true,\n });\n\n console.log(`Dry run: ${result.dryRun ? \"yes\" : \"no\"}`);\n console.log(`Scanned transcript files: ${result.scannedFiles}`);\n console.log(`Parsed turns: ${result.parsedTurns}`);\n console.log(`Malformed lines: ${result.malformedLines}`);\n console.log(`Rebuilt rows: ${result.rebuiltRows}`);\n console.log(`Output path: ${result.outputPath}`);\n if (result.backupPath) console.log(`Backup path: ${result.backupPath}`);\n console.log(\"OK\");\n });\n\n cmd\n .command(\"rebuild-memory-lifecycle-ledger\")\n .description(\"Rebuild the generic memory lifecycle ledger from markdown memories (dry-run by default)\")\n .option(\"--write\", \"Write rebuilt ledger (default: dry-run)\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const result = await runRebuildMemoryLifecycleLedgerCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n write: options.write === true,\n });\n\n console.log(`Dry run: ${result.dryRun ? \"yes\" : \"no\"}`);\n console.log(`Scanned memories: ${result.scannedMemories}`);\n console.log(`Rebuilt rows: ${result.rebuiltRows}`);\n console.log(`Output path: ${result.outputPath}`);\n if (result.backupPath) console.log(`Backup path: ${result.backupPath}`);\n console.log(\"OK\");\n });\n\n cmd\n .command(\"rebuild-memory-projection\")\n .description(\"Rebuild the derived memory projection store from markdown memories and lifecycle events (dry-run by default)\")\n .option(\"--write\", \"Write rebuilt projection (default: dry-run)\")\n .option(\"--namespace <ns>\", \"Namespace to rebuild (default: config defaultNamespace)\", \"\")\n .option(\"--updated-after <iso>\", \"Only report/rebuild memories updated on or after this ISO timestamp\", \"\")\n .option(\"--updated-before <iso>\", \"Only report/rebuild memories updated on or before this ISO timestamp\", \"\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const namespace = typeof options.namespace === \"string\" && options.namespace.trim().length > 0\n ? options.namespace.trim()\n : undefined;\n const memoryDir = await resolveMemoryDirForNamespace(orchestrator, namespace, {\n rejectUnsupportedOverride: true,\n });\n const result = await runRebuildMemoryProjectionCliCommand({\n memoryDir,\n defaultNamespace: namespace ?? orchestrator.config.defaultNamespace,\n write: options.write === true,\n updatedAfter: typeof options.updatedAfter === \"string\" && options.updatedAfter.trim().length > 0\n ? options.updatedAfter.trim()\n : undefined,\n updatedBefore: typeof options.updatedBefore === \"string\" && options.updatedBefore.trim().length > 0\n ? options.updatedBefore.trim()\n : undefined,\n });\n\n console.log(`Dry run: ${result.dryRun ? \"yes\" : \"no\"}`);\n console.log(`Scanned memories: ${result.scannedMemories}`);\n console.log(`Current-state rows: ${result.currentRows}`);\n console.log(`Timeline rows: ${result.timelineRows}`);\n console.log(`Entity-mention rows: ${result.entityMentionRows}`);\n console.log(`Native-knowledge rows: ${result.nativeKnowledgeRows}`);\n console.log(`Review-queue rows: ${result.reviewQueueRows}`);\n console.log(`Used lifecycle ledger: ${result.usedLifecycleLedger ? \"yes\" : \"no\"}`);\n console.log(`Updated-after scope: ${result.scope.updatedAfter ?? \"none\"}`);\n console.log(`Updated-before scope: ${result.scope.updatedBefore ?? \"none\"}`);\n console.log(`Output path: ${result.outputPath}`);\n if (result.backupPath) console.log(`Backup path: ${result.backupPath}`);\n console.log(\"OK\");\n });\n\n cmd\n .command(\"verify-memory-projection\")\n .description(\"Verify the derived memory projection against markdown memories and lifecycle events\")\n .option(\"--namespace <ns>\", \"Namespace to verify (default: config defaultNamespace)\", \"\")\n .option(\"--updated-after <iso>\", \"Only verify memories updated on or after this ISO timestamp\", \"\")\n .option(\"--updated-before <iso>\", \"Only verify memories updated on or before this ISO timestamp\", \"\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const namespace = typeof options.namespace === \"string\" && options.namespace.trim().length > 0\n ? options.namespace.trim()\n : undefined;\n const memoryDir = await resolveMemoryDirForNamespace(orchestrator, namespace);\n const result = await runVerifyMemoryProjectionCliCommand({\n memoryDir,\n defaultNamespace: namespace ?? orchestrator.config.defaultNamespace,\n updatedAfter: typeof options.updatedAfter === \"string\" && options.updatedAfter.trim().length > 0\n ? options.updatedAfter.trim()\n : undefined,\n updatedBefore: typeof options.updatedBefore === \"string\" && options.updatedBefore.trim().length > 0\n ? options.updatedBefore.trim()\n : undefined,\n });\n\n console.log(`Projection exists: ${result.projectionExists ? \"yes\" : \"no\"}`);\n console.log(`OK: ${result.ok ? \"yes\" : \"no\"}`);\n console.log(`Expected current rows: ${result.expectedCurrentRows}`);\n console.log(`Actual current rows: ${result.actualCurrentRows}`);\n console.log(`Expected timeline rows: ${result.expectedTimelineRows}`);\n console.log(`Actual timeline rows: ${result.actualTimelineRows}`);\n console.log(`Expected entity-mention rows: ${result.expectedEntityMentionRows}`);\n console.log(`Actual entity-mention rows: ${result.actualEntityMentionRows}`);\n console.log(`Expected native-knowledge rows: ${result.expectedNativeKnowledgeRows}`);\n console.log(`Actual native-knowledge rows: ${result.actualNativeKnowledgeRows}`);\n console.log(`Expected review-queue rows: ${result.expectedReviewQueueRows}`);\n console.log(`Actual review-queue rows: ${result.actualReviewQueueRows}`);\n console.log(`Missing current memories: ${result.missingCurrentMemoryIds.join(\", \") || \"none\"}`);\n console.log(`Extra current memories: ${result.extraCurrentMemoryIds.join(\", \") || \"none\"}`);\n console.log(`Mismatched current memories: ${result.mismatchedCurrentMemoryIds.join(\", \") || \"none\"}`);\n console.log(`Missing timeline events: ${result.missingTimelineEventIds.join(\", \") || \"none\"}`);\n console.log(`Extra timeline events: ${result.extraTimelineEventIds.join(\", \") || \"none\"}`);\n console.log(`Missing entity mentions: ${result.missingEntityMentionKeys.join(\", \") || \"none\"}`);\n console.log(`Extra entity mentions: ${result.extraEntityMentionKeys.join(\", \") || \"none\"}`);\n console.log(`Mismatched entity mentions: ${result.mismatchedEntityMentionKeys.join(\", \") || \"none\"}`);\n console.log(`Missing native-knowledge chunks: ${result.missingNativeKnowledgeChunkIds.join(\", \") || \"none\"}`);\n console.log(`Extra native-knowledge chunks: ${result.extraNativeKnowledgeChunkIds.join(\", \") || \"none\"}`);\n console.log(`Mismatched native-knowledge chunks: ${result.mismatchedNativeKnowledgeChunkIds.join(\", \") || \"none\"}`);\n console.log(`Missing review-queue entries: ${result.missingReviewQueueEntryIds.join(\", \") || \"none\"}`);\n console.log(`Extra review-queue entries: ${result.extraReviewQueueEntryIds.join(\", \") || \"none\"}`);\n console.log(`Mismatched review-queue entries: ${result.mismatchedReviewQueueEntryIds.join(\", \") || \"none\"}`);\n console.log(\"OK\");\n });\n\n cmd\n .command(\"repair-memory-projection\")\n .description(\"Repair projection drift by rebuilding the derived projection (dry-run by default)\")\n .option(\"--write\", \"Write repaired projection (default: dry-run)\")\n .option(\"--namespace <ns>\", \"Namespace to repair (default: config defaultNamespace)\", \"\")\n .option(\"--updated-after <iso>\", \"Only repair memories updated on or after this ISO timestamp\", \"\")\n .option(\"--updated-before <iso>\", \"Only repair memories updated on or before this ISO timestamp\", \"\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const namespace = typeof options.namespace === \"string\" && options.namespace.trim().length > 0\n ? options.namespace.trim()\n : undefined;\n const memoryDir = await resolveMemoryDirForNamespace(orchestrator, namespace);\n const result = await runRepairMemoryProjectionCliCommand({\n memoryDir,\n defaultNamespace: namespace ?? orchestrator.config.defaultNamespace,\n write: options.write === true,\n updatedAfter: typeof options.updatedAfter === \"string\" && options.updatedAfter.trim().length > 0\n ? options.updatedAfter.trim()\n : undefined,\n updatedBefore: typeof options.updatedBefore === \"string\" && options.updatedBefore.trim().length > 0\n ? options.updatedBefore.trim()\n : undefined,\n });\n\n console.log(`Dry run: ${result.dryRun ? \"yes\" : \"no\"}`);\n console.log(`Repaired: ${result.repaired ? \"yes\" : \"no\"}`);\n console.log(`Verification OK: ${result.verify.ok ? \"yes\" : \"no\"}`);\n if (result.rebuild) {\n console.log(`Output path: ${result.rebuild.outputPath}`);\n if (result.rebuild.backupPath) console.log(`Backup path: ${result.rebuild.backupPath}`);\n }\n console.log(\"OK\");\n });\n\n cmd\n .command(\"memory-timeline <memoryId>\")\n .description(\"Read one memory timeline from the derived projection store\")\n .option(\"--limit <n>\", \"Maximum timeline rows to print\", \"200\")\n .action(async (...args: unknown[]) => {\n const memoryId = String(args[0] ?? \"\");\n const options = (args[1] ?? {}) as Record<string, unknown>;\n const limit = parseInt(String(options.limit ?? \"200\"), 10);\n const rows = await runMemoryTimelineCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n memoryId,\n limit: Number.isFinite(limit) ? limit : 200,\n });\n\n if (rows.length === 0) {\n console.log(\"No timeline rows found. Rebuild the memory projection first if needed.\");\n console.log(\"OK\");\n return;\n }\n\n for (const row of rows) {\n console.log(`${row.timestamp} ${row.eventType} ${row.actor}`);\n }\n console.log(\"OK\");\n });\n\n cmd\n .command(\"governance-run\")\n .description(\"Run memory governance in shadow/apply mode and write audit artifacts\")\n .option(\"--mode <mode>\", \"Governance mode (shadow|apply)\", \"shadow\")\n .option(\"--max-memories <n>\", \"Maximum memories to scan in this run\")\n .option(\"--batch-size <n>\", \"File-read batch size for bounded governance runs\")\n .option(\"--recent-days <n>\", \"Only govern memories updated within the last N days\")\n .option(\"--namespace <ns>\", \"Namespace to govern (default: current default namespace)\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const mode = options.mode === \"apply\" ? \"apply\" : \"shadow\";\n const maxMemoriesRaw = Number.parseInt(String(options.maxMemories ?? \"\"), 10);\n const batchSizeRaw = Number.parseInt(String(options.batchSize ?? \"\"), 10);\n const recentDaysRaw = Number.parseInt(String(options.recentDays ?? \"\"), 10);\n const namespace = typeof options.namespace === \"string\" && options.namespace.trim().length > 0\n ? options.namespace.trim()\n : undefined;\n const memoryDir = await resolveMemoryDirForNamespace(orchestrator, namespace, {\n rejectUnsupportedOverride: true,\n });\n const result = await runMemoryGovernanceCliCommand({\n memoryDir,\n mode,\n maxMemories: Number.isFinite(maxMemoriesRaw) ? maxMemoriesRaw : undefined,\n batchSize: Number.isFinite(batchSizeRaw) ? batchSizeRaw : undefined,\n recentDays: Number.isFinite(recentDaysRaw) ? recentDaysRaw : undefined,\n });\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"governance-report\")\n .description(\"Read the latest or a named governance run artifact bundle\")\n .option(\"--run-id <id>\", \"Governance run id (default: latest)\")\n .option(\"--namespace <ns>\", \"Namespace to inspect (default: current default namespace)\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const namespace = typeof options.namespace === \"string\" && options.namespace.trim().length > 0\n ? options.namespace.trim()\n : undefined;\n const memoryDir = await resolveMemoryDirForNamespace(orchestrator, namespace, {\n rejectUnsupportedOverride: true,\n });\n const report = await runMemoryGovernanceReportCliCommand({\n memoryDir,\n runId: typeof options.runId === \"string\" && options.runId.trim().length > 0\n ? options.runId.trim()\n : undefined,\n });\n console.log(JSON.stringify(report, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"governance-restore\")\n .description(\"Restore memory files from a previous governance apply run\")\n .requiredOption(\"--run-id <id>\", \"Governance run id to restore\")\n .option(\"--namespace <ns>\", \"Namespace to restore (default: current default namespace)\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n if (typeof options.runId !== \"string\" || options.runId.trim().length === 0) {\n throw new Error(\"missing --run-id\");\n }\n const namespace = typeof options.namespace === \"string\" && options.namespace.trim().length > 0\n ? options.namespace.trim()\n : undefined;\n const memoryDir = await resolveMemoryDirForNamespace(orchestrator, namespace, {\n rejectUnsupportedOverride: true,\n });\n const result = await runMemoryGovernanceRestoreCliCommand({\n memoryDir,\n runId: options.runId.trim(),\n });\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"review-disposition <memoryId>\")\n .description(\"Manually set an operator review disposition on one memory\")\n .requiredOption(\"--status <status>\", \"Disposition status (active|pending_review|rejected|quarantined)\")\n .option(\"--reason-code <code>\", \"Optional reason code recorded in CLI output\")\n .action(async (...args: unknown[]) => {\n const memoryId = String(args[0] ?? \"\");\n const options = (args[1] ?? {}) as Record<string, unknown>;\n const statusOpt = typeof options.status === \"string\" ? options.status.trim() : \"\";\n if (\n statusOpt !== \"active\"\n && statusOpt !== \"pending_review\"\n && statusOpt !== \"rejected\"\n && statusOpt !== \"quarantined\"\n ) {\n throw new Error(`invalid review disposition status: ${statusOpt}`);\n }\n const result = await runMemoryReviewDispositionCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n memoryId,\n status: statusOpt,\n reasonCode: typeof options.reasonCode === \"string\" && options.reasonCode.trim().length > 0\n ? options.reasonCode.trim()\n : undefined,\n });\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"migrate-observations\")\n .description(\"Migrate legacy observation ledgers into rebuilt format (dry-run by default)\")\n .option(\"--write\", \"Write migrated ledger (default: dry-run)\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const result = await runMigrateObservationsCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n write: options.write === true,\n });\n\n console.log(`Dry run: ${result.dryRun ? \"yes\" : \"no\"}`);\n console.log(`Scanned legacy files: ${result.scannedFiles}`);\n console.log(`Parsed rows: ${result.parsedRows}`);\n console.log(`Malformed lines: ${result.malformedLines}`);\n console.log(`Migrated rows: ${result.migratedRows}`);\n if (result.sourceRelativePaths.length > 0) {\n console.log(\"Source files:\");\n for (const relPath of result.sourceRelativePaths) {\n console.log(` - ${relPath}`);\n }\n }\n console.log(`Output path: ${result.outputPath}`);\n if (result.backupPath) console.log(`Backup path: ${result.backupPath}`);\n console.log(\"OK\");\n });\n\n cmd\n .command(\"task\")\n .description(\"Manage work tasks\")\n .argument(\"<action>\", \"create|get|list|update|transition|delete|link\")\n .option(\"--id <id>\", \"Task ID\")\n .option(\"--title <title>\", \"Task title\")\n .option(\"--description <description>\", \"Task description\")\n .option(\"--status <status>\", \"Task status\")\n .option(\"--priority <priority>\", \"Task priority\")\n .option(\"--owner <owner>\", \"Task owner\")\n .option(\"--assignee <assignee>\", \"Task assignee\")\n .option(\"--project-id <projectId>\", \"Project ID\")\n .option(\"--tags <csv>\", \"Comma-separated tags\")\n .option(\"--due-at <iso>\", \"Due timestamp (ISO)\")\n .action(async (...args: unknown[]) => {\n const actionRaw = typeof args[0] === \"string\" ? args[0].trim().toLowerCase() : \"\";\n const options = (args[1] ?? {}) as Record<string, unknown>;\n const statusOptRaw = typeof options.status === \"string\" ? options.status.trim().toLowerCase() : undefined;\n const priorityOptRaw = typeof options.priority === \"string\" ? options.priority.trim().toLowerCase() : undefined;\n if (statusOptRaw !== undefined && !isWorkTaskStatus(statusOptRaw)) {\n throw new Error(`invalid task status: ${statusOptRaw}`);\n }\n if (priorityOptRaw !== undefined && !isWorkTaskPriority(priorityOptRaw)) {\n throw new Error(`invalid task priority: ${priorityOptRaw}`);\n }\n\n const patch: WorkTaskPatchInput = {};\n if (typeof options.title === \"string\") patch.title = options.title.trim();\n if (typeof options.description === \"string\") patch.description = options.description.trim();\n if (statusOptRaw !== undefined) patch.status = statusOptRaw;\n if (priorityOptRaw !== undefined) patch.priority = priorityOptRaw;\n if (typeof options.owner === \"string\") patch.owner = normalizeNullableCliValue(options.owner) ?? null;\n if (typeof options.assignee === \"string\") patch.assignee = normalizeNullableCliValue(options.assignee) ?? null;\n if (typeof options.projectId === \"string\") patch.projectId = normalizeNullableCliValue(options.projectId) ?? null;\n if (typeof options.tags === \"string\") {\n patch.tags = parseTagsCsv(options.tags, true);\n }\n if (typeof options.dueAt === \"string\") patch.dueAt = normalizeNullableCliValue(options.dueAt) ?? null;\n\n const result = await runWorkTaskCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n action: actionRaw as WorkTaskCliCommandOptions[\"action\"],\n id: typeof options.id === \"string\" ? options.id : undefined,\n title: typeof options.title === \"string\" ? options.title : undefined,\n description: typeof options.description === \"string\" ? options.description : undefined,\n status: statusOptRaw,\n priority: priorityOptRaw,\n owner: typeof options.owner === \"string\" ? options.owner : undefined,\n assignee: typeof options.assignee === \"string\" ? options.assignee : undefined,\n projectId: typeof options.projectId === \"string\" ? options.projectId : undefined,\n tags: typeof options.tags === \"string\"\n ? parseTagsCsv(options.tags, true)\n : undefined,\n dueAt: typeof options.dueAt === \"string\" ? options.dueAt : undefined,\n patch,\n });\n\n if (Array.isArray(result)) {\n console.log(`Count: ${result.length}`);\n }\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"project\")\n .description(\"Manage work projects\")\n .argument(\"<action>\", \"create|get|list|update|delete\")\n .option(\"--id <id>\", \"Project ID\")\n .option(\"--name <name>\", \"Project name\")\n .option(\"--description <description>\", \"Project description\")\n .option(\"--status <status>\", \"Project status\")\n .option(\"--owner <owner>\", \"Project owner\")\n .option(\"--tags <csv>\", \"Comma-separated tags\")\n .action(async (...args: unknown[]) => {\n const actionRaw = typeof args[0] === \"string\" ? args[0].trim().toLowerCase() : \"\";\n const options = (args[1] ?? {}) as Record<string, unknown>;\n const statusOptRaw = typeof options.status === \"string\" ? options.status.trim().toLowerCase() : undefined;\n if (statusOptRaw !== undefined && !isWorkProjectStatus(statusOptRaw)) {\n throw new Error(`invalid project status: ${statusOptRaw}`);\n }\n\n const patch: WorkProjectPatchInput = {};\n if (typeof options.name === \"string\") patch.name = options.name.trim();\n if (typeof options.description === \"string\") patch.description = options.description.trim();\n if (statusOptRaw !== undefined) patch.status = statusOptRaw;\n if (typeof options.owner === \"string\") patch.owner = normalizeNullableCliValue(options.owner) ?? null;\n if (typeof options.tags === \"string\") {\n patch.tags = parseTagsCsv(options.tags, true);\n }\n\n const result = await runWorkProjectCliCommand({\n memoryDir: orchestrator.config.memoryDir,\n action: actionRaw as WorkProjectCliCommandOptions[\"action\"],\n id: typeof options.id === \"string\" ? options.id : undefined,\n name: typeof options.name === \"string\" ? options.name : undefined,\n description: typeof options.description === \"string\" ? options.description : undefined,\n status: statusOptRaw,\n owner: typeof options.owner === \"string\" ? options.owner : undefined,\n tags: typeof options.tags === \"string\"\n ? parseTagsCsv(options.tags, true)\n : undefined,\n patch,\n });\n\n if (Array.isArray(result)) {\n console.log(`Count: ${result.length}`);\n }\n console.log(JSON.stringify(result, null, 2));\n console.log(\"OK\");\n });\n\n cmd\n .command(\"dedupe-exact\")\n .description(\"Delete exact duplicate memory entries (same body text), keeping highest-confidence/newest copy\")\n .option(\"--dry-run\", \"Show what would be deleted without deleting files\")\n .option(\"--namespace <ns>\", \"Namespace to dedupe (v3.0+, default: config defaultNamespace)\", \"\")\n .option(\"--qmd-sync\", \"Run QMD update/embed after deletions (default: off)\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const dryRun = options.dryRun === true;\n const namespace = options.namespace ? String(options.namespace) : \"\";\n const qmdSync = options.qmdSync === true;\n\n const memoryDir = await resolveMemoryDirForNamespace(orchestrator, namespace);\n const memories = await readAllMemoryFiles(memoryDir);\n const plan = planExactDuplicateDeletions(memories);\n\n console.log(`Scanned ${memories.length} memory files in ${memoryDir}`);\n console.log(`Duplicate groups: ${plan.groups}`);\n console.log(`Duplicate files to delete: ${plan.deletePaths.length}`);\n\n if (plan.deletePaths.length === 0) {\n console.log(\"No exact duplicates found.\");\n return;\n }\n\n if (dryRun) {\n console.log(\"Dry run enabled. No files deleted.\");\n for (const filePath of plan.deletePaths.slice(0, 50)) {\n console.log(` - ${filePath}`);\n }\n if (plan.deletePaths.length > 50) {\n console.log(` ... and ${plan.deletePaths.length - 50} more`);\n }\n return;\n }\n\n let deleted = 0;\n for (const filePath of plan.deletePaths) {\n try {\n await unlink(filePath);\n deleted += 1;\n } catch (err) {\n console.log(` failed to delete ${filePath}: ${String(err)}`);\n }\n }\n console.log(`Deleted ${deleted}/${plan.deletePaths.length} duplicate files.`);\n\n if (qmdSync) {\n await orchestrator.qmd.probe();\n if (orchestrator.qmd.isAvailable()) {\n await orchestrator.qmd.update();\n await orchestrator.qmd.embed();\n console.log(\"QMD sync complete.\");\n } else {\n console.log(`QMD unavailable in this process; skipped sync. Status: ${orchestrator.qmd.debugStatus()}`);\n }\n }\n });\n\n cmd\n .command(\"dedupe-aggressive\")\n .description(\n \"Delete aggressively-normalized duplicate memory entries (formatting/case/punctuation-insensitive)\",\n )\n .option(\"--dry-run\", \"Show what would be deleted without deleting files\")\n .option(\"--namespace <ns>\", \"Namespace to dedupe (v3.0+, default: config defaultNamespace)\", \"\")\n .option(\"--qmd-sync\", \"Run QMD update/embed after deletions (default: off)\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const dryRun = options.dryRun === true;\n const namespace = options.namespace ? String(options.namespace) : \"\";\n const qmdSync = options.qmdSync === true;\n\n const memoryDir = await resolveMemoryDirForNamespace(orchestrator, namespace);\n const memories = await readAllMemoryFiles(memoryDir);\n const plan = planAggressiveDuplicateDeletions(memories);\n\n console.log(`Scanned ${memories.length} memory files in ${memoryDir}`);\n console.log(`Duplicate groups: ${plan.groups}`);\n console.log(`Duplicate files to delete: ${plan.deletePaths.length}`);\n\n if (plan.deletePaths.length === 0) {\n console.log(\"No aggressive duplicates found.\");\n return;\n }\n\n if (dryRun) {\n console.log(\"Dry run enabled. No files deleted.\");\n for (const filePath of plan.deletePaths.slice(0, 50)) {\n console.log(` - ${filePath}`);\n }\n if (plan.deletePaths.length > 50) {\n console.log(` ... and ${plan.deletePaths.length - 50} more`);\n }\n return;\n }\n\n let deleted = 0;\n for (const filePath of plan.deletePaths) {\n try {\n await unlink(filePath);\n deleted += 1;\n } catch (err) {\n console.log(` failed to delete ${filePath}: ${String(err)}`);\n }\n }\n console.log(`Deleted ${deleted}/${plan.deletePaths.length} duplicate files.`);\n\n if (qmdSync) {\n await orchestrator.qmd.probe();\n if (orchestrator.qmd.isAvailable()) {\n await orchestrator.qmd.update();\n await orchestrator.qmd.embed();\n console.log(\"QMD sync complete.\");\n } else {\n console.log(`QMD unavailable in this process; skipped sync. Status: ${orchestrator.qmd.debugStatus()}`);\n }\n }\n });\n\n cmd\n .command(\"search\")\n .argument(\"<query>\", \"Search query\")\n .option(\"-n, --max-results <number>\", \"Max results\", \"8\")\n .description(\"Search memories via QMD\")\n .action(async (...args: unknown[]) => {\n const query = typeof args[0] === \"string\" ? args[0] : String(args[0] ?? \"\");\n const options = (args[1] ?? {}) as Record<string, string>;\n const maxResults = parseInt(options.maxResults ?? \"8\", 10);\n if (!query) {\n console.log(\"Missing query. Usage: openclaw engram search <query>\");\n return;\n }\n\n // Probe in this CLI process before availability check.\n await orchestrator.qmd.probe();\n\n if (orchestrator.qmd.isAvailable()) {\n const results = await orchestrator.qmd.search(\n query,\n undefined,\n maxResults,\n );\n if (results.length === 0) {\n console.log(`No results for: \"${query}\"`);\n return;\n }\n console.log(`\\n=== Memory Search: \"${query}\" ===\\n`);\n for (const r of results) {\n console.log(` ${r.path} (score: ${r.score.toFixed(3)})`);\n if (r.snippet) {\n console.log(\n ` ${r.snippet.slice(0, 150).replace(/\\n/g, \" \")}`,\n );\n }\n console.log();\n }\n } else {\n // Fallback: search filenames\n const memories = await orchestrator.storage.readAllMemories();\n const lowerQuery = query.toLowerCase();\n const matches = memories.filter(\n (m) =>\n m.content.toLowerCase().includes(lowerQuery) ||\n m.frontmatter.tags.some((t) => t.includes(lowerQuery)),\n );\n const qmdStatus = orchestrator.qmd.debugStatus();\n if (matches.length === 0) {\n console.log(\n `No results for: \"${query}\" (QMD unavailable in this CLI process; text search fallback).`,\n );\n console.log(`QMD status: ${qmdStatus}`);\n return;\n }\n console.log(`\\n=== Text Search Fallback: \"${query}\" (${matches.length} results) ===\\n`);\n console.log(`QMD status: ${qmdStatus}\\n`);\n for (const m of matches.slice(0, maxResults)) {\n console.log(` [${m.frontmatter.category}] ${m.content.slice(0, 120)}`);\n }\n }\n });\n\n cmd\n .command(\"profile\")\n .description(\"Show current user profile\")\n .action(async () => {\n const profile = await orchestrator.storage.readProfile();\n if (!profile) {\n console.log(\"No profile built yet.\");\n return;\n }\n console.log(profile);\n });\n\n cmd\n .command(\"entities\")\n .description(\"List all tracked entities\")\n .action(async () => {\n const entities = await orchestrator.storage.readEntities();\n if (entities.length === 0) {\n console.log(\"No entities tracked yet.\");\n return;\n }\n console.log(`=== Entities (${entities.length}) ===\\n`);\n for (const e of entities) {\n console.log(` - ${e}`);\n }\n });\n\n cmd\n .command(\"extract\")\n .description(\"Force extraction of buffered turns\")\n .action(async () => {\n await orchestrator.buffer.load();\n const turns = orchestrator.buffer.getTurns();\n if (turns.length === 0) {\n console.log(\"Buffer is empty. Nothing to extract.\");\n return;\n }\n console.log(`Extracting ${turns.length} buffered turns...`);\n // Trigger extraction by processing a dummy turn that forces extraction\n // Actually we need to call the internal extraction method\n // For now, inform the user\n console.log(\n \"Use the memory system in conversation to trigger extraction, or wait for the buffer threshold.\",\n );\n });\n\n cmd\n .command(\"bootstrap\")\n .description(\"Scan transcript history and seed memory from high-signal past turns\")\n .option(\"--dry-run\", \"Scan and report without writing memories\")\n .option(\"--sessions-dir <path>\", \"Override transcript sessions directory\")\n .option(\"--limit <number>\", \"Maximum sessions to process\")\n .option(\"--since <date>\", \"Only process turns after date (YYYY-MM-DD or ISO)\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const dryRun = options.dryRun === true;\n const sessionsDir = options.sessionsDir ? String(options.sessionsDir) : undefined;\n const limitRaw = options.limit ? Number(options.limit) : undefined;\n const limit = typeof limitRaw === \"number\" && Number.isFinite(limitRaw) && limitRaw > 0\n ? Math.floor(limitRaw)\n : undefined;\n\n let since: Date | undefined;\n if (options.since) {\n const parsed = new Date(String(options.since));\n if (Number.isNaN(parsed.getTime())) {\n console.log(`Invalid --since value: ${String(options.since)}`);\n return;\n }\n since = parsed;\n }\n\n console.log(\"Running bootstrap scan...\");\n const result = await orchestrator.runBootstrap({\n dryRun,\n sessionsDir,\n limit,\n since,\n });\n console.log(\n `Bootstrap complete. sessions=${result.sessionsScanned}, turns=${result.turnsProcessed}, highSignal=${result.highSignalTurns}, created=${result.memoriesCreated}, skipped=${result.skipped}`,\n );\n });\n\n cmd\n .command(\"consolidate\")\n .description(\"Run memory consolidation immediately\")\n .option(\"--verbose\", \"Show detailed consolidation stats\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const verbose = options.verbose === true;\n console.log(\"Running consolidation...\");\n const stats = await orchestrator.runConsolidationNow();\n if (verbose) {\n console.log(\n `Consolidation complete. memoriesProcessed=${stats.memoriesProcessed}, merged=${stats.merged}, invalidated=${stats.invalidated}`,\n );\n } else {\n console.log(`Consolidation complete. merged=${stats.merged}, invalidated=${stats.invalidated}`);\n }\n });\n\n cmd\n .command(\"semantic-consolidate\")\n .description(\"Run semantic consolidation of similar memories\")\n .option(\"--dry-run\", \"Show what would be consolidated without making changes\")\n .option(\"--verbose\", \"Show detailed cluster information\")\n .option(\"--threshold <n>\", \"Override token overlap threshold (0-1)\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const dryRun = options.dryRun === true;\n const verbose = options.verbose === true;\n const thresholdOverride = typeof options.threshold === \"string\"\n ? parseFloat(options.threshold)\n : undefined;\n\n console.log(`Running semantic consolidation${dryRun ? \" (dry run)\" : \"\"}...`);\n const result = await orchestrator.runSemanticConsolidationNow({\n dryRun,\n thresholdOverride,\n });\n\n if (verbose || dryRun) {\n console.log(`\\nClusters found: ${result.clustersFound}`);\n for (const cluster of result.clusters) {\n console.log(`\\n Category: ${cluster.category} (${cluster.memories.length} memories, overlap=${cluster.overlapScore.toFixed(2)})`);\n for (const m of cluster.memories) {\n const preview = m.content.length > 80 ? m.content.slice(0, 80) + \"...\" : m.content;\n console.log(` - ${m.frontmatter.id}: ${preview}`);\n }\n if (cluster.canonicalContent) {\n const preview = cluster.canonicalContent.length > 120\n ? cluster.canonicalContent.slice(0, 120) + \"...\"\n : cluster.canonicalContent;\n console.log(` → Canonical: ${preview}`);\n }\n }\n }\n\n console.log(\n `\\nSemantic consolidation complete. clusters=${result.clustersFound}, consolidated=${result.memoriesConsolidated}, archived=${result.memoriesArchived}, errors=${result.errors}`,\n );\n });\n\n cmd\n .command(\"questions\")\n .description(\"List open questions from memory extraction\")\n .option(\"-a, --all\", \"Show all questions including resolved\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const showAll = options.all === true;\n const questions = await orchestrator.storage.readQuestions({ unresolvedOnly: !showAll });\n if (questions.length === 0) {\n console.log(showAll ? \"No questions found.\" : \"No unresolved questions.\");\n return;\n }\n console.log(`\\n=== Questions (${questions.length}) ===\\n`);\n for (const q of questions) {\n const status = q.resolved ? \"[RESOLVED]\" : `[priority: ${q.priority.toFixed(2)}]`;\n console.log(` ${q.id} ${status}`);\n console.log(` ${q.question}`);\n console.log(` Context: ${q.context}`);\n console.log();\n }\n });\n\n cmd\n .command(\"identity\")\n .description(\"Show agent identity reflections\")\n .action(async () => {\n const workspaceDir = path.join(resolveHomeDir(), \".openclaw\", \"workspace\");\n const identity = await orchestrator.storage.readIdentity(workspaceDir);\n if (!identity) {\n console.log(\"No identity file found.\");\n return;\n }\n console.log(identity);\n });\n\n const continuityCmd = cmd\n .command(\"continuity\")\n .description(\"Identity continuity incident workflow commands\");\n\n continuityCmd\n .command(\"incidents\")\n .description(\"List continuity incidents\")\n .option(\"--state <state>\", \"Filter by state: open|closed|all\", \"open\")\n .option(\"--limit <number>\", \"Maximum incidents to list\", \"25\")\n .action(async (...args: unknown[]) => {\n if (!orchestrator.config.identityContinuityEnabled) {\n console.log(\"Identity continuity is disabled.\");\n return;\n }\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const stateRaw = String(options.state ?? \"open\").toLowerCase();\n const state: \"open\" | \"closed\" | \"all\" =\n stateRaw === \"closed\" || stateRaw === \"all\" ? stateRaw : \"open\";\n const limit = Math.max(1, Math.min(200, parseInt(String(options.limit ?? \"25\"), 10) || 25));\n const filtered = await orchestrator.storage.readContinuityIncidents(limit, state);\n if (filtered.length === 0) {\n console.log(`No continuity incidents found for state=${state}.`);\n return;\n }\n console.log(`=== Continuity Incidents (${filtered.length}, state=${state}) ===\\n`);\n for (const incident of filtered) {\n console.log(formatContinuityIncidentCli(incident));\n console.log();\n }\n });\n\n continuityCmd\n .command(\"incident-open\")\n .description(\"Open a continuity incident\")\n .option(\"--symptom <text>\", \"Required symptom description\")\n .option(\"--trigger-window <window>\", \"Optional incident trigger window\")\n .option(\"--suspected-cause <text>\", \"Optional suspected cause\")\n .action(async (...args: unknown[]) => {\n if (!orchestrator.config.identityContinuityEnabled) {\n console.log(\"Identity continuity is disabled.\");\n return;\n }\n if (!orchestrator.config.continuityIncidentLoggingEnabled) {\n console.log(\"Continuity incident logging is disabled.\");\n return;\n }\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const symptom = String(options.symptom ?? \"\").trim();\n if (!symptom) {\n console.log(\"Missing required --symptom.\");\n return;\n }\n const created = await orchestrator.storage.appendContinuityIncident({\n symptom,\n triggerWindow: options.triggerWindow ? String(options.triggerWindow) : undefined,\n suspectedCause: options.suspectedCause ? String(options.suspectedCause) : undefined,\n });\n console.log(\"Opened continuity incident:\\n\");\n console.log(formatContinuityIncidentCli(created));\n });\n\n continuityCmd\n .command(\"incident-close\")\n .description(\"Close a continuity incident\")\n .option(\"--id <id>\", \"Required incident ID\")\n .option(\"--fix-applied <text>\", \"Required fix description\")\n .option(\"--verification-result <text>\", \"Required verification result\")\n .option(\"--preventive-rule <text>\", \"Optional preventive rule\")\n .action(async (...args: unknown[]) => {\n if (!orchestrator.config.identityContinuityEnabled) {\n console.log(\"Identity continuity is disabled.\");\n return;\n }\n if (!orchestrator.config.continuityIncidentLoggingEnabled) {\n console.log(\"Continuity incident logging is disabled.\");\n return;\n }\n const options = (args[0] ?? {}) as Record<string, unknown>;\n const id = String(options.id ?? \"\").trim();\n const fixApplied = String(options.fixApplied ?? \"\").trim();\n const verificationResult = String(options.verificationResult ?? \"\").trim();\n const preventiveRule = options.preventiveRule ? String(options.preventiveRule).trim() : undefined;\n\n if (!id) {\n console.log(\"Missing required --id.\");\n return;\n }\n if (!fixApplied) {\n console.log(\"Missing required --fix-applied.\");\n return;\n }\n if (!verificationResult) {\n console.log(\"Missing required --verification-result.\");\n return;\n }\n\n const closed = await orchestrator.storage.closeContinuityIncident(id, {\n fixApplied,\n verificationResult,\n preventiveRule,\n });\n if (!closed) {\n console.log(`Incident not found: ${id}`);\n return;\n }\n console.log(\"Closed continuity incident:\\n\");\n console.log(formatContinuityIncidentCli(closed));\n });\n\n cmd\n .command(\"access-stats\")\n .description(\"Show memory access statistics\")\n .option(\"-n, --top <number>\", \"Show top N most accessed\", \"20\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, string>;\n const top = parseInt(options.top ?? \"20\", 10);\n\n const memories = await orchestrator.storage.readAllMemories();\n const withAccess = memories.filter((m) => m.frontmatter.accessCount && m.frontmatter.accessCount > 0);\n\n if (withAccess.length === 0) {\n console.log(\"No access tracking data yet. Memories will be tracked as they are retrieved.\");\n return;\n }\n\n // Sort by access count descending\n const sorted = withAccess.sort(\n (a, b) => (b.frontmatter.accessCount ?? 0) - (a.frontmatter.accessCount ?? 0),\n );\n\n console.log(`\\n=== Top ${Math.min(top, sorted.length)} Most Accessed Memories ===\\n`);\n for (const m of sorted.slice(0, top)) {\n const lastAccessed = m.frontmatter.lastAccessed\n ? new Date(m.frontmatter.lastAccessed).toLocaleDateString()\n : \"unknown\";\n console.log(` ${m.frontmatter.accessCount}x [${m.frontmatter.category}] ${m.content.slice(0, 80)}`);\n console.log(` Last accessed: ${lastAccessed} ID: ${m.frontmatter.id}`);\n console.log();\n }\n\n // Summary stats\n const totalAccess = withAccess.reduce((sum, m) => sum + (m.frontmatter.accessCount ?? 0), 0);\n console.log(`Total accesses tracked: ${totalAccess}`);\n console.log(`Memories with access data: ${withAccess.length} / ${memories.length}`);\n });\n\n cmd\n .command(\"flush-access\")\n .description(\"Flush pending access tracking updates to disk\")\n .action(async () => {\n await orchestrator.flushAccessTracking();\n console.log(\"Access tracking buffer flushed.\");\n });\n\n cmd\n .command(\"importance\")\n .description(\"Show importance score distribution across memories\")\n .option(\"-l, --level <level>\", \"Filter by importance level (critical, high, normal, low, trivial)\")\n .option(\"-n, --top <number>\", \"Show top N memories by importance\", \"15\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, string>;\n const filterLevel = options.level;\n const top = parseInt(options.top ?? \"15\", 10);\n\n const memories = await orchestrator.storage.readAllMemories();\n const withImportance = memories.filter((m) => m.frontmatter.importance);\n\n if (withImportance.length === 0) {\n console.log(\"No importance data yet. Importance is scored during extraction.\");\n return;\n }\n\n // Count by level\n const levelCounts: Record<string, number> = {\n critical: 0,\n high: 0,\n normal: 0,\n low: 0,\n trivial: 0,\n };\n for (const m of withImportance) {\n const level = m.frontmatter.importance?.level ?? \"normal\";\n levelCounts[level] = (levelCounts[level] ?? 0) + 1;\n }\n\n console.log(\"\\n=== Importance Distribution ===\\n\");\n for (const [level, count] of Object.entries(levelCounts)) {\n const bar = \"█\".repeat(Math.min(count, 50));\n console.log(` ${level.padEnd(10)} ${count.toString().padStart(4)} ${bar}`);\n }\n console.log(`\\n Total scored: ${withImportance.length} / ${memories.length} memories\\n`);\n\n // Filter by level if specified\n let filtered = withImportance;\n if (filterLevel) {\n filtered = withImportance.filter(\n (m) => m.frontmatter.importance?.level === filterLevel,\n );\n if (filtered.length === 0) {\n console.log(`No memories with importance level: ${filterLevel}`);\n return;\n }\n }\n\n // Sort by importance score descending\n const sorted = filtered.sort(\n (a, b) =>\n (b.frontmatter.importance?.score ?? 0) -\n (a.frontmatter.importance?.score ?? 0),\n );\n\n const heading = filterLevel\n ? `Top ${Math.min(top, sorted.length)} \"${filterLevel}\" Importance Memories`\n : `Top ${Math.min(top, sorted.length)} Most Important Memories`;\n console.log(`=== ${heading} ===\\n`);\n\n for (const m of sorted.slice(0, top)) {\n const imp = m.frontmatter.importance!;\n console.log(\n ` ${imp.score.toFixed(2)} [${imp.level}] [${m.frontmatter.category}]`,\n );\n console.log(` ${m.content.slice(0, 100)}`);\n if (imp.keywords.length > 0) {\n console.log(` Keywords: ${imp.keywords.join(\", \")}`);\n }\n console.log();\n }\n });\n cmd\n .command(\"topics\")\n .description(\"Show extracted topics from memory corpus\")\n .option(\"-n, --top <number>\", \"Show top N topics\", \"20\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, string>;\n const top = parseInt(options.top ?? \"20\", 10);\n\n const { topics, updatedAt } = await orchestrator.storage.loadTopics();\n\n if (topics.length === 0) {\n console.log(\"No topics extracted yet. Topics are extracted during consolidation.\");\n return;\n }\n\n console.log(`\\n=== Top ${Math.min(top, topics.length)} Topics ===`);\n console.log(`Last updated: ${updatedAt ?? \"unknown\"}\\n`);\n\n for (const topic of topics.slice(0, top)) {\n const bar = \"█\".repeat(Math.min(Math.round(topic.score * 10), 30));\n console.log(` ${topic.term.padEnd(20)} ${topic.score.toFixed(3)} (${topic.count}x) ${bar}`);\n }\n });\n\n cmd\n .command(\"summaries\")\n .description(\"Show memory summaries\")\n .option(\"-n, --top <number>\", \"Show top N most recent summaries\", \"5\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, string>;\n const top = parseInt(options.top ?? \"5\", 10);\n\n const summaries = await orchestrator.storage.readSummaries();\n\n if (summaries.length === 0) {\n console.log(\"No summaries yet. Summaries are created during consolidation when memory count exceeds threshold.\");\n return;\n }\n\n // Sort by createdAt desc\n const sorted = summaries.sort(\n (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),\n );\n\n console.log(`\\n=== Memory Summaries (${Math.min(top, sorted.length)} of ${sorted.length}) ===\\n`);\n\n for (const summary of sorted.slice(0, top)) {\n console.log(` ${summary.id}`);\n console.log(` Created: ${summary.createdAt}`);\n console.log(` Time range: ${summary.timeRangeStart.slice(0, 10)} to ${summary.timeRangeEnd.slice(0, 10)}`);\n console.log(` Source memories: ${summary.sourceEpisodeIds.length}`);\n console.log(` Key facts: ${summary.keyFacts.length}`);\n console.log(`\\n Summary: ${summary.summaryText.slice(0, 200)}...`);\n console.log();\n }\n });\n\n cmd\n .command(\"threads\")\n .description(\"Show conversation threads\")\n .option(\"-n, --top <number>\", \"Show top N most recent threads\", \"10\")\n .option(\"-t, --thread <id>\", \"Show details for a specific thread\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, string>;\n const threadId = options.thread;\n const top = parseInt(options.top ?? \"10\", 10);\n\n const memoryDir = path.join(resolveHomeDir(), \".openclaw\", \"workspace\", \"memory\", \"local\");\n const threading = new ThreadingManager(path.join(memoryDir, \"threads\"));\n\n if (threadId) {\n const thread = await threading.loadThread(threadId);\n if (!thread) {\n console.log(`Thread not found: ${threadId}`);\n return;\n }\n\n console.log(`\\n=== Thread: ${thread.title} ===\\n`);\n console.log(` ID: ${thread.id}`);\n console.log(` Created: ${thread.createdAt}`);\n console.log(` Updated: ${thread.updatedAt}`);\n console.log(` Session: ${thread.sessionKey ?? \"(none)\"}`);\n console.log(` Episodes: ${thread.episodeIds.length}`);\n\n if (thread.episodeIds.length > 0) {\n console.log(\"\\n Episode IDs:\");\n for (const id of thread.episodeIds.slice(0, 20)) {\n console.log(` - ${id}`);\n }\n if (thread.episodeIds.length > 20) {\n console.log(` ... and ${thread.episodeIds.length - 20} more`);\n }\n }\n\n if (thread.linkedThreadIds.length > 0) {\n console.log(\"\\n Linked threads:\");\n for (const id of thread.linkedThreadIds) {\n console.log(` - ${id}`);\n }\n }\n return;\n }\n\n const threads = await threading.getAllThreads();\n\n if (threads.length === 0) {\n console.log(\"No conversation threads yet. Enable threading with threadingEnabled: true\");\n return;\n }\n\n console.log(`\\n=== Conversation Threads (${Math.min(top, threads.length)} of ${threads.length}) ===\\n`);\n for (const thread of threads.slice(0, top)) {\n const updated = new Date(thread.updatedAt).toLocaleString();\n console.log(` ${thread.title}`);\n console.log(` ID: ${thread.id}`);\n console.log(` Episodes: ${thread.episodeIds.length} | Updated: ${updated}`);\n console.log();\n }\n });\n\n cmd\n .command(\"chunks\")\n .description(\"Show chunking statistics and orphaned chunks\")\n .option(\"-p, --parent <id>\", \"Show chunks for a specific parent memory ID\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, string>;\n const parentId = options.parent;\n\n const memories = await orchestrator.storage.readAllMemories();\n\n if (parentId) {\n // Show chunks for specific parent\n const chunks = memories\n .filter((m) => m.frontmatter.parentId === parentId)\n .sort((a, b) => (a.frontmatter.chunkIndex ?? 0) - (b.frontmatter.chunkIndex ?? 0));\n\n if (chunks.length === 0) {\n console.log(`No chunks found for parent: ${parentId}`);\n return;\n }\n\n const parent = memories.find((m) => m.frontmatter.id === parentId);\n console.log(`\\n=== Chunks for ${parentId} ===\\n`);\n if (parent) {\n console.log(`Parent: ${parent.content.slice(0, 100)}...`);\n console.log();\n }\n\n for (const chunk of chunks) {\n console.log(\n ` [${(chunk.frontmatter.chunkIndex ?? 0) + 1}/${chunk.frontmatter.chunkTotal}] ${chunk.content.slice(0, 80)}...`,\n );\n }\n return;\n }\n\n // Show overall chunking stats\n const chunked = memories.filter((m) => m.frontmatter.tags?.includes(\"chunked\"));\n const chunks = memories.filter((m) => m.frontmatter.parentId);\n\n // Find orphaned chunks (parent no longer exists)\n const parentIds = new Set(chunked.map((m) => m.frontmatter.id));\n const orphans = chunks.filter((m) => !parentIds.has(m.frontmatter.parentId!));\n\n console.log(\"\\n=== Chunking Statistics ===\\n\");\n console.log(` Chunked memories (parents): ${chunked.length}`);\n console.log(` Total chunks: ${chunks.length}`);\n console.log(` Orphaned chunks: ${orphans.length}`);\n\n if (chunked.length > 0) {\n // Calculate average chunks per parent\n const avgChunks = chunks.length / chunked.length;\n console.log(` Average chunks per parent: ${avgChunks.toFixed(1)}`);\n }\n\n if (orphans.length > 0) {\n console.log(\"\\n Orphaned chunk IDs:\");\n for (const orphan of orphans.slice(0, 10)) {\n console.log(` - ${orphan.frontmatter.id}`);\n }\n if (orphans.length > 10) {\n console.log(` ... and ${orphans.length - 10} more`);\n }\n }\n });\n\n // Transcript commands\n cmd\n .command(\"transcript\")\n .description(\"View conversation transcripts\")\n .option(\"--date <date>\", \"View transcript for specific date (YYYY-MM-DD)\")\n .option(\"--recent <duration>\", \"View recent transcript (e.g., 12h, 30m)\")\n .option(\"--channel <key>\", \"Filter by channel/session key\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, string>;\n const date = options.date;\n const recent = options.recent;\n let channel = options.channel;\n\n // Expand shorthand channel names to full sessionKey patterns\n if (channel && !channel.includes(\":\")) {\n // Convert \"main\" -> \"agent:generalist:main\"\n // Convert \"discord\" -> \"agent:generalist:discord\" (will match all discord channels)\n // Convert \"cron\" -> \"agent:generalist:cron\" (will match all cron jobs)\n if (channel === \"main\") {\n channel = \"agent:generalist:main\";\n } else if ([\"discord\", \"slack\", \"cron\", \"telegram\"].includes(channel)) {\n channel = `agent:generalist:${channel}`;\n }\n }\n\n if (date) {\n // Read specific date\n const entries = await orchestrator.transcript.readRange(\n `${date}T00:00:00Z`,\n `${date}T23:59:59Z`,\n channel,\n );\n console.log(formatTranscript(entries));\n } else if (recent) {\n // Parse duration (e.g., \"12h\", \"30m\")\n const hours = parseDuration(recent);\n const entries = await orchestrator.transcript.readRecent(hours, channel);\n console.log(formatTranscript(entries));\n } else {\n // Default: show today's transcript\n const today = new Date().toISOString().slice(0, 10);\n const entries = await orchestrator.transcript.readRange(\n `${today}T00:00:00Z`,\n `${today}T23:59:59Z`,\n channel,\n );\n console.log(formatTranscript(entries));\n }\n });\n\n // Checkpoint command\n cmd\n .command(\"checkpoint\")\n .description(\"View current compaction checkpoint (if any)\")\n .action(async () => {\n const checkpoint = await orchestrator.transcript.loadCheckpoint();\n if (!checkpoint) {\n console.log(\"No active checkpoint found.\");\n return;\n }\n console.log(`Checkpoint for session: ${checkpoint.sessionKey}`);\n console.log(`Captured at: ${checkpoint.capturedAt}`);\n console.log(`Expires at: ${checkpoint.ttl}`);\n console.log(`Turns: ${checkpoint.turns.length}`);\n console.log(\"\\n---\\n\");\n console.log(orchestrator.transcript.formatForRecall(checkpoint.turns, 2000));\n });\n\n // Summaries command\n cmd\n .command(\"hourly\")\n .description(\"View hourly summaries\")\n .option(\"--channel <key>\", \"Filter by channel/session key\")\n .option(\"--recent <hours>\", \"Show recent summaries (hours)\")\n .action(async (...args: unknown[]) => {\n const options = (args[0] ?? {}) as Record<string, string>;\n const channel = options.channel ?? \"default\";\n const recentHours = options.recent ? parseInt(options.recent, 10) : 24;\n\n const summaries = await orchestrator.summarizer.readRecent(channel, recentHours);\n if (summaries.length === 0) {\n console.log(`No summaries found for channel: ${channel}`);\n return;\n }\n\n console.log(orchestrator.summarizer.formatForRecall(summaries, summaries.length));\n });\n },\n { commands: [\"engram\"] },\n );\n}\n\nfunction formatTranscript(entries: TranscriptEntry[]): string {\n if (entries.length === 0) return \"No transcript entries found.\";\n\n return entries\n .map((e) => {\n const time = e.timestamp.slice(11, 16); // HH:MM\n return `[${time}] ${e.role}: ${e.content.slice(0, 200)}${e.content.length > 200 ? \"...\" : \"\"}`;\n })\n .join(\"\\n\");\n}\n\nfunction parseDuration(duration: string): number {\n // Parse strings like \"12h\", \"30m\", \"2h30m\"\n const hours = duration.match(/(\\d+)h/);\n const minutes = duration.match(/(\\d+)m/);\n let total = 0;\n if (hours) total += parseInt(hours[1], 10);\n if (minutes) total += parseInt(minutes[1], 10) / 60;\n return total || 12; // Default to 12 hours\n}\n","import path from \"node:path\";\nimport { mkdir, readFile } from \"node:fs/promises\";\nimport { EXPORT_FORMAT, EXPORT_SCHEMA_VERSION } from \"./constants.js\";\nimport { listFilesRecursive, sha256File, sha256String, toPosixRelPath, writeJsonFile } from \"./fs-utils.js\";\nimport type { ExportBundleV1, ExportManifestV1, ExportMemoryRecordV1 } from \"./types.js\";\n\nexport interface ExportCommonOptions {\n memoryDir: string;\n outDir: string;\n includeTranscripts?: boolean;\n includeWorkspaceIdentity?: boolean;\n workspaceDir?: string;\n pluginVersion: string;\n}\n\nconst DEFAULT_EXCLUDES = new Set([\n \"node_modules\",\n \".git\",\n]);\n\nfunction shouldExclude(relPosix: string, includeTranscripts: boolean): boolean {\n const parts = relPosix.split(\"/\");\n if (parts.some((p) => DEFAULT_EXCLUDES.has(p))) return true;\n if (!includeTranscripts && parts[0] === \"transcripts\") return true;\n return false;\n}\n\nexport async function exportJsonBundle(opts: ExportCommonOptions): Promise<void> {\n const includeTranscripts = opts.includeTranscripts === true;\n const outDirAbs = path.resolve(opts.outDir);\n await mkdir(outDirAbs, { recursive: true });\n\n const memoryDirAbs = path.resolve(opts.memoryDir);\n const filesAbs = await listFilesRecursive(memoryDirAbs);\n\n const records: ExportMemoryRecordV1[] = [];\n const manifestFiles: ExportManifestV1[\"files\"] = [];\n\n for (const abs of filesAbs) {\n const relPosix = toPosixRelPath(abs, memoryDirAbs);\n if (shouldExclude(relPosix, includeTranscripts)) continue;\n\n const content = await readFile(abs, \"utf-8\");\n records.push({ path: relPosix, content });\n const { sha256, bytes } = await sha256File(abs);\n manifestFiles.push({ path: relPosix, sha256, bytes });\n }\n\n // Optionally include workspace identity file (outside memoryDir).\n if (opts.includeWorkspaceIdentity !== false && opts.workspaceDir) {\n const identityPath = path.join(opts.workspaceDir, \"IDENTITY.md\");\n try {\n const content = await readFile(identityPath, \"utf-8\");\n const relPath = \"workspace/IDENTITY.md\";\n records.push({ path: relPath, content });\n const { sha256, bytes } = sha256String(content);\n manifestFiles.push({ path: relPath, sha256, bytes });\n } catch {\n // identity optional\n }\n }\n\n const manifest: ExportManifestV1 = {\n format: EXPORT_FORMAT,\n schemaVersion: EXPORT_SCHEMA_VERSION,\n createdAt: new Date().toISOString(),\n pluginVersion: opts.pluginVersion,\n includesTranscripts: includeTranscripts,\n files: manifestFiles.sort((a, b) => a.path.localeCompare(b.path)),\n };\n\n const bundle: ExportBundleV1 = { manifest, records };\n\n await writeJsonFile(path.join(outDirAbs, \"manifest.json\"), manifest);\n await writeJsonFile(path.join(outDirAbs, \"bundle.json\"), bundle);\n}\n","export const EXPORT_FORMAT = \"openclaw-engram-export\" as const;\nexport const EXPORT_SCHEMA_VERSION = 1 as const;\n\n","import { createHash } from \"node:crypto\";\nimport { mkdir, readdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport async function sha256File(filePath: string): Promise<{ sha256: string; bytes: number }> {\n const buf = await readFile(filePath);\n const sha256 = createHash(\"sha256\").update(buf).digest(\"hex\");\n return { sha256, bytes: buf.byteLength };\n}\n\nexport function sha256String(content: string): { sha256: string; bytes: number } {\n const buf = Buffer.from(content, \"utf-8\");\n const sha256 = createHash(\"sha256\").update(buf).digest(\"hex\");\n return { sha256, bytes: buf.byteLength };\n}\n\nexport async function writeJsonFile(filePath: string, value: unknown): Promise<void> {\n await mkdir(path.dirname(filePath), { recursive: true });\n await writeFile(filePath, JSON.stringify(value, null, 2) + \"\\n\", \"utf-8\");\n}\n\nexport async function readJsonFile<T>(filePath: string): Promise<T> {\n const raw = await readFile(filePath, \"utf-8\");\n return JSON.parse(raw) as T;\n}\n\nexport async function listFilesRecursive(rootDir: string): Promise<string[]> {\n const out: string[] = [];\n async function walk(dir: string): Promise<void> {\n const entries = await readdir(dir, { withFileTypes: true });\n for (const ent of entries) {\n const fp = path.join(dir, ent.name);\n if (ent.isDirectory()) {\n await walk(fp);\n } else if (ent.isFile()) {\n out.push(fp);\n }\n }\n }\n await walk(rootDir);\n return out.sort();\n}\n\nexport async function ensureDirExists(dirPath: string): Promise<void> {\n await mkdir(dirPath, { recursive: true });\n}\n\nexport async function fileExists(filePath: string): Promise<boolean> {\n try {\n await stat(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function toPosixRelPath(absPath: string, rootDir: string): string {\n const rel = path.relative(rootDir, absPath);\n // normalize to posix for portability across platforms\n return rel.split(path.sep).join(\"/\");\n}\n\nexport function fromPosixRelPath(relPath: string): string {\n return relPath.split(\"/\").join(path.sep);\n}\n","import path from \"node:path\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { EXPORT_FORMAT, EXPORT_SCHEMA_VERSION } from \"./constants.js\";\nimport { listFilesRecursive, sha256File, toPosixRelPath, writeJsonFile } from \"./fs-utils.js\";\nimport type { ExportManifestV1 } from \"./types.js\";\n\nexport interface ExportMdOptions {\n memoryDir: string;\n outDir: string;\n includeTranscripts?: boolean;\n pluginVersion: string;\n}\n\nfunction shouldExclude(relPosix: string, includeTranscripts: boolean): boolean {\n const parts = relPosix.split(\"/\");\n if (!includeTranscripts && parts[0] === \"transcripts\") return true;\n return false;\n}\n\nexport async function exportMarkdownBundle(opts: ExportMdOptions): Promise<void> {\n const includeTranscripts = opts.includeTranscripts === true;\n const outDirAbs = path.resolve(opts.outDir);\n await mkdir(outDirAbs, { recursive: true });\n\n const memDirAbs = path.resolve(opts.memoryDir);\n const filesAbs = await listFilesRecursive(memDirAbs);\n\n const manifestFiles: ExportManifestV1[\"files\"] = [];\n\n for (const abs of filesAbs) {\n const relPosix = toPosixRelPath(abs, memDirAbs);\n if (shouldExclude(relPosix, includeTranscripts)) continue;\n\n const dstAbs = path.join(outDirAbs, ...relPosix.split(\"/\"));\n await mkdir(path.dirname(dstAbs), { recursive: true });\n const content = await readFile(abs);\n await writeFile(dstAbs, content);\n const { sha256, bytes } = await sha256File(abs);\n manifestFiles.push({ path: relPosix, sha256, bytes });\n }\n\n const manifest: ExportManifestV1 = {\n format: EXPORT_FORMAT,\n schemaVersion: EXPORT_SCHEMA_VERSION,\n createdAt: new Date().toISOString(),\n pluginVersion: opts.pluginVersion,\n includesTranscripts: includeTranscripts,\n files: manifestFiles.sort((a, b) => a.path.localeCompare(b.path)),\n };\n\n await writeJsonFile(path.join(outDirAbs, \"manifest.json\"), manifest);\n}\n\nexport async function looksLikeEngramMdExport(fromDir: string): Promise<boolean> {\n const dirAbs = path.resolve(fromDir);\n try {\n const raw = await readFile(path.join(dirAbs, \"manifest.json\"), \"utf-8\");\n const parsed = JSON.parse(raw) as { format?: string; schemaVersion?: number };\n return parsed.format === EXPORT_FORMAT && parsed.schemaVersion === EXPORT_SCHEMA_VERSION;\n } catch {\n return false;\n }\n}\n\n","import path from \"node:path\";\nimport { mkdir, readdir, rm } from \"node:fs/promises\";\nimport { exportMarkdownBundle } from \"./export-md.js\";\n\nexport interface BackupOptions {\n memoryDir: string;\n outDir: string;\n includeTranscripts?: boolean;\n retentionDays?: number;\n pluginVersion: string;\n}\n\nfunction timestampDirName(now: Date): string {\n return now.toISOString().replace(/[:.]/g, \"-\");\n}\n\nexport async function backupMemoryDir(opts: BackupOptions): Promise<string> {\n const outDirAbs = path.resolve(opts.outDir);\n await mkdir(outDirAbs, { recursive: true });\n const ts = timestampDirName(new Date());\n const backupDir = path.join(outDirAbs, ts);\n\n await exportMarkdownBundle({\n memoryDir: opts.memoryDir,\n outDir: backupDir,\n includeTranscripts: opts.includeTranscripts,\n pluginVersion: opts.pluginVersion,\n });\n\n if (opts.retentionDays && opts.retentionDays > 0) {\n await enforceRetention(outDirAbs, opts.retentionDays);\n }\n\n return backupDir;\n}\n\nasync function enforceRetention(outDirAbs: string, retentionDays: number): Promise<void> {\n const entries = await readdir(outDirAbs, { withFileTypes: true });\n const cutoffMs = Date.now() - retentionDays * 24 * 60 * 60 * 1000;\n\n for (const ent of entries) {\n if (!ent.isDirectory()) continue;\n const name = ent.name;\n // Directory names are ISO8601 with [: .] replaced by \"-\" to be filesystem-friendly.\n // Example: 2026-02-11T05-06-07-123Z => 2026-02-11T05:06:07.123Z\n const m = name.match(\n /^(\\d{4}-\\d{2}-\\d{2})T(\\d{2})-(\\d{2})-(\\d{2})-(\\d{3})Z$/,\n );\n const iso = m ? `${m[1]}T${m[2]}:${m[3]}:${m[4]}.${m[5]}Z` : null;\n const tsMs = iso ? Date.parse(iso) : NaN;\n if (!Number.isFinite(tsMs)) continue;\n if (tsMs < cutoffMs) {\n await rm(path.join(outDirAbs, name), { recursive: true, force: true });\n }\n }\n}\n","import path from \"node:path\";\nimport { readFile } from \"node:fs/promises\";\nimport { SQLITE_SCHEMA_VERSION, SQLITE_TABLES_SQL } from \"./sqlite-schema.js\";\nimport { listFilesRecursive, sha256File, toPosixRelPath } from \"./fs-utils.js\";\nimport { openBetterSqlite3 } from \"../runtime/better-sqlite.js\";\n\nexport interface ExportSqliteOptions {\n memoryDir: string;\n outFile: string;\n includeTranscripts?: boolean;\n pluginVersion: string;\n}\n\nfunction shouldExclude(relPosix: string, includeTranscripts: boolean): boolean {\n const parts = relPosix.split(\"/\");\n if (!includeTranscripts && parts[0] === \"transcripts\") return true;\n return false;\n}\n\nexport async function exportSqlite(opts: ExportSqliteOptions): Promise<void> {\n const includeTranscripts = opts.includeTranscripts === true;\n const memDirAbs = path.resolve(opts.memoryDir);\n const outAbs = path.resolve(opts.outFile);\n\n const filesAbs = await listFilesRecursive(memDirAbs);\n const db = openBetterSqlite3(outAbs);\n try {\n db.exec(\"PRAGMA journal_mode=WAL;\");\n db.exec(SQLITE_TABLES_SQL);\n\n const insertMeta = db.prepare(\"INSERT OR REPLACE INTO meta(key,value) VALUES (?,?)\");\n insertMeta.run(\"schemaVersion\", String(SQLITE_SCHEMA_VERSION));\n insertMeta.run(\"createdAt\", new Date().toISOString());\n insertMeta.run(\"pluginVersion\", opts.pluginVersion);\n insertMeta.run(\"includesTranscripts\", includeTranscripts ? \"true\" : \"false\");\n\n const insertFile = db.prepare(\n \"INSERT OR REPLACE INTO files(path_rel, bytes, sha256, content) VALUES (?,?,?,?)\",\n );\n\n const tx = db.transaction((rows: Array<{ rel: string; bytes: number; sha256: string; content: string }>) => {\n for (const r of rows) insertFile.run(r.rel, r.bytes, r.sha256, r.content);\n });\n\n const rows: Array<{ rel: string; bytes: number; sha256: string; content: string }> = [];\n for (const abs of filesAbs) {\n const relPosix = toPosixRelPath(abs, memDirAbs);\n if (shouldExclude(relPosix, includeTranscripts)) continue;\n const content = await readFile(abs, \"utf-8\");\n const { sha256, bytes } = await sha256File(abs);\n rows.push({ rel: relPosix, bytes, sha256, content });\n }\n\n tx(rows);\n } finally {\n db.close();\n }\n}\n","export const SQLITE_SCHEMA_VERSION = 1 as const;\n\nexport const SQLITE_TABLES_SQL = `\nCREATE TABLE IF NOT EXISTS meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS files (\n path_rel TEXT PRIMARY KEY,\n bytes INTEGER NOT NULL,\n sha256 TEXT NOT NULL,\n content TEXT NOT NULL\n);\n`;\n\n","import path from \"node:path\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { ExportBundleV1Schema } from \"./types.js\";\nimport { fileExists, readJsonFile, fromPosixRelPath } from \"./fs-utils.js\";\n\nexport type ConflictPolicy = \"skip\" | \"overwrite\" | \"dedupe\";\n\nexport interface ImportJsonOptions {\n targetMemoryDir: string;\n fromDir: string;\n conflict?: ConflictPolicy;\n dryRun?: boolean;\n workspaceDir?: string;\n}\n\nfunction normalizeForDedupe(s: string): string {\n return s.replace(/\\s+/g, \" \").trim();\n}\n\nexport async function importJsonBundle(opts: ImportJsonOptions): Promise<{ written: number; skipped: number }> {\n const conflict = opts.conflict ?? \"skip\";\n const fromDirAbs = path.resolve(opts.fromDir);\n const bundlePath = path.join(fromDirAbs, \"bundle.json\");\n const bundle = ExportBundleV1Schema.parse(await readJsonFile(bundlePath));\n\n const memDirAbs = path.resolve(opts.targetMemoryDir);\n const written: Array<{ abs: string; content: string }> = [];\n\n let skipped = 0;\n\n for (const rec of bundle.records) {\n const isWorkspace = rec.path.startsWith(\"workspace/\");\n const targetBase = isWorkspace ? (opts.workspaceDir ? path.resolve(opts.workspaceDir) : null) : memDirAbs;\n if (isWorkspace && !targetBase) {\n skipped += 1;\n continue;\n }\n\n const relFs = fromPosixRelPath(isWorkspace ? rec.path.replace(/^workspace\\//, \"\") : rec.path);\n const absTarget = path.join(targetBase!, relFs);\n\n const exists = await fileExists(absTarget);\n if (exists) {\n if (conflict === \"skip\") {\n skipped += 1;\n continue;\n }\n if (conflict === \"dedupe\") {\n try {\n const existing = await (await import(\"node:fs/promises\")).readFile(absTarget, \"utf-8\");\n if (normalizeForDedupe(existing) === normalizeForDedupe(rec.content)) {\n skipped += 1;\n continue;\n }\n } catch {\n // if can't read, fall through to overwrite\n }\n }\n // overwrite: proceed\n }\n\n written.push({ abs: absTarget, content: rec.content });\n }\n\n if (opts.dryRun) {\n return { written: 0, skipped };\n }\n\n for (const w of written) {\n await mkdir(path.dirname(w.abs), { recursive: true });\n await writeFile(w.abs, w.content, \"utf-8\");\n }\n\n return { written: written.length, skipped };\n}\n\nexport function looksLikeEngramJsonExport(fromDir: string): Promise<boolean> {\n const dir = path.resolve(fromDir);\n return Promise.all([\n fileExists(path.join(dir, \"manifest.json\")),\n fileExists(path.join(dir, \"bundle.json\")),\n ]).then(([m, b]) => m && b);\n}\n\n","import { z } from \"zod\";\n\nexport const ExportManifestV1Schema = z.object({\n format: z.literal(\"openclaw-engram-export\"),\n schemaVersion: z.literal(1),\n createdAt: z.string(),\n pluginVersion: z.string(),\n includesTranscripts: z.boolean(),\n files: z.array(\n z.object({\n path: z.string(),\n sha256: z.string(),\n bytes: z.number().int().nonnegative(),\n }),\n ),\n});\n\nexport type ExportManifestV1 = z.infer<typeof ExportManifestV1Schema>;\n\nexport const ExportMemoryRecordV1Schema = z.object({\n path: z.string(),\n content: z.string(),\n});\n\nexport type ExportMemoryRecordV1 = z.infer<typeof ExportMemoryRecordV1Schema>;\n\nexport const ExportBundleV1Schema = z.object({\n manifest: ExportManifestV1Schema,\n records: z.array(ExportMemoryRecordV1Schema),\n});\n\nexport type ExportBundleV1 = z.infer<typeof ExportBundleV1Schema>;\n\n","import path from \"node:path\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { SQLITE_SCHEMA_VERSION } from \"./sqlite-schema.js\";\nimport { fileExists, fromPosixRelPath } from \"./fs-utils.js\";\nimport { openBetterSqlite3 } from \"../runtime/better-sqlite.js\";\n\nexport type ConflictPolicy = \"skip\" | \"overwrite\" | \"dedupe\";\n\nexport interface ImportSqliteOptions {\n targetMemoryDir: string;\n fromFile: string;\n conflict?: ConflictPolicy;\n dryRun?: boolean;\n}\n\nfunction normalizeForDedupe(s: string): string {\n return s.replace(/\\s+/g, \" \").trim();\n}\n\nexport async function importSqlite(opts: ImportSqliteOptions): Promise<{ written: number; skipped: number }> {\n const conflict = opts.conflict ?? \"skip\";\n const memDirAbs = path.resolve(opts.targetMemoryDir);\n const fromAbs = path.resolve(opts.fromFile);\n const db = openBetterSqlite3(fromAbs, { readonly: true });\n\n const written: Array<{ abs: string; content: string }> = [];\n let skipped = 0;\n\n try {\n const metaRows = db.prepare(\"SELECT key,value FROM meta\").all() as Array<{ key: string; value: string }>;\n const meta = Object.fromEntries(metaRows.map((r) => [r.key, r.value]));\n if (String(meta.schemaVersion) !== String(SQLITE_SCHEMA_VERSION)) {\n throw new Error(`unsupported sqlite schemaVersion: ${meta.schemaVersion}`);\n }\n\n const rows = db.prepare(\"SELECT path_rel, content FROM files\").all() as Array<{ path_rel: string; content: string }>;\n for (const r of rows) {\n const relFs = fromPosixRelPath(r.path_rel);\n const absTarget = path.join(memDirAbs, relFs);\n\n const exists = await fileExists(absTarget);\n if (exists) {\n if (conflict === \"skip\") {\n skipped += 1;\n continue;\n }\n if (conflict === \"dedupe\") {\n try {\n const existing = await (await import(\"node:fs/promises\")).readFile(absTarget, \"utf-8\");\n if (normalizeForDedupe(existing) === normalizeForDedupe(r.content)) {\n skipped += 1;\n continue;\n }\n } catch {\n // fall through\n }\n }\n }\n written.push({ abs: absTarget, content: r.content });\n }\n } finally {\n db.close();\n }\n\n if (opts.dryRun) return { written: 0, skipped };\n\n for (const w of written) {\n await mkdir(path.dirname(w.abs), { recursive: true });\n await writeFile(w.abs, w.content, \"utf-8\");\n }\n\n return { written: written.length, skipped };\n}\n","import path from \"node:path\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { fileExists, listFilesRecursive, toPosixRelPath, fromPosixRelPath } from \"./fs-utils.js\";\n\nexport type ConflictPolicy = \"skip\" | \"overwrite\" | \"dedupe\";\n\nexport interface ImportMdOptions {\n targetMemoryDir: string;\n fromDir: string;\n conflict?: ConflictPolicy;\n dryRun?: boolean;\n}\n\nfunction normalizeForDedupe(s: string): string {\n return s.replace(/\\s+/g, \" \").trim();\n}\n\nexport async function importMarkdownBundle(opts: ImportMdOptions): Promise<{ written: number; skipped: number }> {\n const conflict = opts.conflict ?? \"skip\";\n const fromAbs = path.resolve(opts.fromDir);\n const targetAbs = path.resolve(opts.targetMemoryDir);\n\n const filesAbs = await listFilesRecursive(fromAbs);\n const writes: Array<{ abs: string; content: string }> = [];\n let skipped = 0;\n\n for (const abs of filesAbs) {\n const relPosix = toPosixRelPath(abs, fromAbs);\n if (relPosix === \"manifest.json\") continue;\n const dstAbs = path.join(targetAbs, fromPosixRelPath(relPosix));\n const content = await readFile(abs, \"utf-8\");\n\n const exists = await fileExists(dstAbs);\n if (exists) {\n if (conflict === \"skip\") {\n skipped += 1;\n continue;\n }\n if (conflict === \"dedupe\") {\n try {\n const existing = await (await import(\"node:fs/promises\")).readFile(dstAbs, \"utf-8\");\n if (normalizeForDedupe(existing) === normalizeForDedupe(content)) {\n skipped += 1;\n continue;\n }\n } catch {\n // fall through to overwrite\n }\n }\n }\n\n writes.push({ abs: dstAbs, content });\n }\n\n if (opts.dryRun) return { written: 0, skipped };\n\n for (const w of writes) {\n await mkdir(path.dirname(w.abs), { recursive: true });\n await writeFile(w.abs, w.content, \"utf-8\");\n }\n\n return { written: writes.length, skipped };\n}\n\n","import path from \"node:path\";\nimport { stat } from \"node:fs/promises\";\nimport { looksLikeEngramJsonExport } from \"./import-json.js\";\nimport { looksLikeEngramMdExport } from \"./export-md.js\";\n\nexport type ImportFormat = \"json\" | \"sqlite\" | \"md\";\n\nexport async function detectImportFormat(fromPath: string): Promise<ImportFormat | null> {\n const abs = path.resolve(fromPath);\n let st: { isDirectory(): boolean; isFile(): boolean };\n try {\n st = await stat(abs);\n } catch {\n return null;\n }\n\n if (st.isFile()) {\n if (abs.endsWith(\".sqlite\") || abs.endsWith(\".db\")) return \"sqlite\";\n return null;\n }\n\n if (st.isDirectory()) {\n if (await looksLikeEngramJsonExport(abs)) return \"json\";\n if (await looksLikeEngramMdExport(abs)) return \"md\";\n return null;\n }\n\n return null;\n}\n\n","import {\n parseIsoTimestamp,\n type ReplayNormalizer,\n type ReplayParseOptions,\n type ReplaySource,\n type ReplayTurn,\n type ReplayWarning,\n type ReplayValidationIssue,\n validateReplayTurn,\n} from \"./types.js\";\n\nexport interface ReplayRunOptions extends ReplayParseOptions {\n dryRun?: boolean;\n startOffset?: number;\n maxTurns?: number;\n batchSize?: number;\n}\n\nexport interface ReplayRunHandlers {\n onTurn?: (turn: ReplayTurn) => Promise<void> | void;\n onBatch?: (turns: ReplayTurn[]) => Promise<void> | void;\n}\n\nexport interface ReplayRunSummary {\n source: ReplaySource;\n parsedTurns: number;\n validTurns: number;\n invalidTurns: number;\n filteredByDate: number;\n skippedByOffset: number;\n processedTurns: number;\n batchCount: number;\n dryRun: boolean;\n nextOffset: number;\n firstTimestamp?: string;\n lastTimestamp?: string;\n warnings: ReplayWarning[];\n}\n\nexport type ReplayNormalizerRegistry = Record<ReplaySource, ReplayNormalizer>;\n\nfunction clampNonNegativeInt(value: number | undefined, defaultValue: number): number {\n if (!Number.isFinite(value as number)) return defaultValue;\n return Math.max(0, Math.floor(value as number));\n}\n\nexport function clampBatchSize(value: number | undefined): number {\n const parsed = clampNonNegativeInt(value, 100);\n if (parsed < 1) return 1;\n return Math.min(parsed, 1000);\n}\n\nfunction toWarning(issue: ReplayValidationIssue): ReplayWarning {\n return {\n code: issue.code,\n message: issue.message,\n index: issue.index,\n };\n}\n\nfunction inDateRange(turn: ReplayTurn, fromTs: number | null, toTs: number | null): boolean {\n const turnTs = parseIsoTimestamp(turn.timestamp);\n if (turnTs === null) return false;\n if (fromTs !== null && turnTs < fromTs) return false;\n if (toTs !== null && turnTs > toTs) return false;\n return true;\n}\n\nexport function buildReplayNormalizerRegistry(normalizers: ReplayNormalizer[]): ReplayNormalizerRegistry {\n const registry = {} as ReplayNormalizerRegistry;\n for (const normalizer of normalizers) {\n if (!normalizer?.source) {\n throw new Error(\"replay normalizer source is required\");\n }\n if (registry[normalizer.source]) {\n throw new Error(`duplicate replay normalizer for source '${normalizer.source}'`);\n }\n registry[normalizer.source] = normalizer;\n }\n return registry;\n}\n\nexport async function runReplay(\n source: ReplaySource,\n input: unknown,\n registry: ReplayNormalizerRegistry,\n handlers: ReplayRunHandlers = {},\n options: ReplayRunOptions = {},\n): Promise<ReplayRunSummary> {\n const normalizer = registry[source];\n if (!normalizer) {\n throw new Error(`missing replay normalizer for source '${source}'`);\n }\n return runReplayWithNormalizer(normalizer, input, handlers, options);\n}\n\nexport async function runReplayWithNormalizer(\n normalizer: ReplayNormalizer,\n input: unknown,\n handlers: ReplayRunHandlers = {},\n options: ReplayRunOptions = {},\n): Promise<ReplayRunSummary> {\n const parseResult = await normalizer.parse(input, options);\n if (!parseResult || typeof parseResult !== \"object\") {\n throw new Error(`replay normalizer '${normalizer.source}' returned invalid parse result object`);\n }\n if (!Array.isArray(parseResult.turns)) {\n throw new Error(`replay normalizer '${normalizer.source}' returned invalid parse result: turns must be an array`);\n }\n if (parseResult.warnings != null && !Array.isArray(parseResult.warnings)) {\n throw new Error(`replay normalizer '${normalizer.source}' returned invalid parse result: warnings must be an array`);\n }\n const warnings: ReplayWarning[] = [...(parseResult.warnings ?? [])];\n const parsedTurns = parseResult.turns;\n\n const validTurns: ReplayTurn[] = [];\n let invalidTurns = 0;\n for (let i = 0; i < parsedTurns.length; i += 1) {\n const turn = parsedTurns[i];\n const issues = validateReplayTurn(turn, i);\n if (issues.length === 0 && turn.source !== normalizer.source) {\n issues.push({\n code: \"turn.source.mismatch\",\n message: `Replay turn source '${turn.source}' does not match normalizer source '${normalizer.source}'.`,\n index: i,\n });\n }\n if (issues.length > 0) {\n invalidTurns += 1;\n for (const issue of issues) warnings.push(toWarning(issue));\n continue;\n }\n validTurns.push(turn);\n }\n\n const sorted = [...validTurns].sort((a, b) => {\n const left = parseIsoTimestamp(a.timestamp) ?? 0;\n const right = parseIsoTimestamp(b.timestamp) ?? 0;\n return left - right;\n });\n\n const fromTs = options.from ? parseIsoTimestamp(options.from) : null;\n const toTs = options.to ? parseIsoTimestamp(options.to) : null;\n if (options.from && fromTs === null) {\n throw new Error(`invalid replay --from timestamp '${options.from}'`);\n }\n if (options.to && toTs === null) {\n throw new Error(`invalid replay --to timestamp '${options.to}'`);\n }\n if (fromTs !== null && toTs !== null && fromTs > toTs) {\n throw new Error(\"invalid replay date range: --from is after --to\");\n }\n\n const ranged = sorted.filter((turn) => inDateRange(turn, fromTs, toTs));\n const filteredByDate = sorted.length - ranged.length;\n\n const startOffset = clampNonNegativeInt(options.startOffset, 0);\n const skippedByOffset = Math.min(startOffset, ranged.length);\n const offsetApplied = ranged.slice(startOffset);\n\n const maxTurns = clampNonNegativeInt(options.maxTurns, offsetApplied.length);\n const selected = offsetApplied.slice(0, maxTurns);\n const dryRun = options.dryRun === true;\n const batchSize = clampBatchSize(options.batchSize);\n\n let batchCount = 0;\n if (!dryRun) {\n for (let i = 0; i < selected.length; i += batchSize) {\n const batch = selected.slice(i, i + batchSize);\n batchCount += 1;\n if (handlers.onBatch) await handlers.onBatch(batch);\n if (handlers.onTurn) {\n for (const turn of batch) {\n await handlers.onTurn(turn);\n }\n }\n }\n } else if (selected.length > 0) {\n batchCount = Math.ceil(selected.length / batchSize);\n }\n\n return {\n source: normalizer.source,\n parsedTurns: parsedTurns.length,\n validTurns: sorted.length,\n invalidTurns,\n filteredByDate,\n skippedByOffset,\n processedTurns: selected.length,\n batchCount,\n dryRun,\n nextOffset: startOffset + selected.length,\n firstTimestamp: selected[0]?.timestamp,\n lastTimestamp: selected[selected.length - 1]?.timestamp,\n warnings,\n };\n}\n","import { isReplayRole, type ReplayRole } from \"../types.js\";\n\ntype NormalizeRoleOptions = {\n assistantAliases?: string[];\n userAliases?: string[];\n};\n\ntype NormalizeTimestampOptions = {\n acceptDateObject?: boolean;\n trimString?: boolean;\n};\n\nexport function normalizeReplayRole(value: unknown, options: NormalizeRoleOptions = {}): ReplayRole | null {\n if (typeof value !== \"string\") return null;\n const role = value.trim().toLowerCase();\n if (isReplayRole(role)) return role;\n\n if (options.userAliases?.includes(role) || role === \"human\") return \"user\";\n if (options.assistantAliases?.includes(role) || role === \"ai\" || role === \"model\") return \"assistant\";\n return null;\n}\n\nexport function normalizeReplayContent(value: unknown): string | null {\n if (typeof value === \"string\") {\n const content = value.trim();\n return content.length > 0 ? content : null;\n }\n if (Array.isArray(value)) {\n const text = value\n .map((part) => (typeof part === \"string\" ? part : \"\"))\n .join(\"\\n\")\n .trim();\n return text.length > 0 ? text : null;\n }\n if (value && typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n if (Array.isArray(obj.parts)) return normalizeReplayContent(obj.parts);\n if (typeof obj.text === \"string\") return normalizeReplayContent(obj.text);\n }\n return null;\n}\n\nexport function normalizeReplayTimestamp(value: unknown, options: NormalizeTimestampOptions = {}): string | null {\n const toIso = (millis: number): string | null => {\n if (!Number.isFinite(millis)) return null;\n const date = new Date(millis);\n if (!Number.isFinite(date.getTime())) return null;\n try {\n return date.toISOString();\n } catch {\n return null;\n }\n };\n\n if (typeof value === \"number\" && Number.isFinite(value)) {\n const millis = value > 1e12 ? value : value * 1000;\n return toIso(millis);\n }\n\n if (options.acceptDateObject && value instanceof Date && Number.isFinite(value.getTime())) {\n return toIso(value.getTime());\n }\n\n if (typeof value !== \"string\") return null;\n const raw = options.trimString === false ? value : value.trim();\n if (raw.length === 0) return null;\n return toIso(Date.parse(raw));\n}\n","import {\n type ReplayNormalizer,\n type ReplayParseOptions,\n type ReplayParseResult,\n type ReplayTurn,\n} from \"../types.js\";\nimport { normalizeReplayContent, normalizeReplayRole, normalizeReplayTimestamp } from \"./shared.js\";\n\nfunction gatherConversations(input: unknown): Array<Record<string, unknown>> {\n if (Array.isArray(input)) {\n return input.filter((item): item is Record<string, unknown> => !!item && typeof item === \"object\");\n }\n if (!input || typeof input !== \"object\") return [];\n const obj = input as Record<string, unknown>;\n if (Array.isArray(obj.conversations)) {\n return obj.conversations.filter((item): item is Record<string, unknown> => !!item && typeof item === \"object\");\n }\n return [obj];\n}\n\nfunction extractFromMapping(conversation: Record<string, unknown>): Array<Record<string, unknown>> {\n const mapping = conversation.mapping;\n if (!mapping || typeof mapping !== \"object\") return [];\n const nodes = mapping as Record<string, unknown>;\n const currentNodeId = typeof conversation.current_node === \"string\" ? conversation.current_node : null;\n\n if (!currentNodeId || !nodes[currentNodeId] || typeof nodes[currentNodeId] !== \"object\") {\n // Fallback for malformed/legacy exports without a traversable active pointer.\n const loose: Array<Record<string, unknown>> = [];\n for (const node of Object.values(nodes)) {\n if (!node || typeof node !== \"object\") continue;\n const nodeObj = node as Record<string, unknown>;\n const message = nodeObj.message;\n if (!message || typeof message !== \"object\") continue;\n loose.push({\n ...(message as Record<string, unknown>),\n _nodeId: typeof nodeObj.id === \"string\" ? nodeObj.id : undefined,\n _nodeCreateTime: nodeObj.create_time,\n });\n }\n return loose;\n }\n\n const chain: Array<Record<string, unknown>> = [];\n const seen = new Set<string>();\n let cursor: string | null = currentNodeId;\n while (cursor && !seen.has(cursor)) {\n seen.add(cursor);\n const node = nodes[cursor];\n if (!node || typeof node !== \"object\") break;\n const nodeObj = node as Record<string, unknown>;\n const message = nodeObj.message;\n if (message && typeof message === \"object\") {\n chain.push({\n ...(message as Record<string, unknown>),\n _nodeId: typeof nodeObj.id === \"string\" ? nodeObj.id : cursor,\n _nodeCreateTime: nodeObj.create_time,\n });\n }\n cursor = typeof nodeObj.parent === \"string\" ? nodeObj.parent : null;\n }\n\n return chain.reverse();\n}\n\nexport const chatgptReplayNormalizer: ReplayNormalizer = {\n source: \"chatgpt\",\n parse(input: unknown, options: ReplayParseOptions = {}): ReplayParseResult {\n let parsedInput = input;\n if (typeof input === \"string\") {\n try {\n parsedInput = JSON.parse(input);\n } catch {\n parsedInput = [];\n }\n }\n\n const warnings: ReplayParseResult[\"warnings\"] = [];\n const turns: ReplayTurn[] = [];\n\n const conversations = gatherConversations(parsedInput);\n for (let i = 0; i < conversations.length; i += 1) {\n const conversation = conversations[i];\n const convIdRaw = conversation.id ?? conversation.conversation_id ?? conversation.uuid;\n const hasSourceConversationId = typeof convIdRaw === \"string\" && convIdRaw.trim().length > 0;\n const convId = hasSourceConversationId ? convIdRaw.trim() : `conv-${i + 1}`;\n const sessionKey = `replay:chatgpt:${convId}`;\n const fallbackSessionKey = options.defaultSessionKey?.trim() || sessionKey;\n\n const messageRows = Array.isArray(conversation.messages)\n ? conversation.messages.filter((item): item is Record<string, unknown> => !!item && typeof item === \"object\")\n : extractFromMapping(conversation);\n\n for (let j = 0; j < messageRows.length; j += 1) {\n const row = messageRows[j];\n const role = normalizeReplayRole(\n (row.author as Record<string, unknown> | undefined)?.role ?? row.role,\n );\n const content = normalizeReplayContent(\n (row.content as Record<string, unknown> | undefined)?.parts ?? row.content ?? row.text,\n );\n const timestamp = normalizeReplayTimestamp(\n row.create_time ?? row.timestamp ?? row._nodeCreateTime ?? row.created_at,\n );\n\n if (!role || !content || !timestamp) {\n const message = `Skipping invalid ChatGPT replay message at conversation ${i + 1}, index ${j}.`;\n if (options.strict) throw new Error(message);\n warnings.push({ code: \"replay.chatgpt.message.invalid\", message, index: j });\n continue;\n }\n\n const externalIdRaw = row.id ?? row._nodeId;\n\n turns.push({\n source: \"chatgpt\",\n sessionKey: hasSourceConversationId ? sessionKey : fallbackSessionKey,\n role,\n content,\n timestamp,\n externalId: typeof externalIdRaw === \"string\" ? externalIdRaw : undefined,\n metadata: {\n conversationId: convId,\n conversationTitle: typeof conversation.title === \"string\" ? conversation.title : undefined,\n },\n });\n }\n }\n\n return { turns, warnings };\n },\n};\n","import {\n type ReplayNormalizer,\n type ReplayParseOptions,\n type ReplayParseResult,\n type ReplayTurn,\n} from \"../types.js\";\nimport { normalizeReplayContent, normalizeReplayRole, normalizeReplayTimestamp } from \"./shared.js\";\n\nfunction gatherConversations(input: unknown): Array<Record<string, unknown>> {\n if (Array.isArray(input)) return input.filter((item): item is Record<string, unknown> => !!item && typeof item === \"object\");\n if (!input || typeof input !== \"object\") return [];\n\n const obj = input as Record<string, unknown>;\n if (Array.isArray(obj.conversations)) {\n return obj.conversations.filter((item): item is Record<string, unknown> => !!item && typeof item === \"object\");\n }\n\n if (Array.isArray(obj.chat_messages) || Array.isArray(obj.messages)) {\n return [obj];\n }\n\n return [];\n}\n\nexport const claudeReplayNormalizer: ReplayNormalizer = {\n source: \"claude\",\n parse(input: unknown, options: ReplayParseOptions = {}): ReplayParseResult {\n let parsedInput = input;\n if (typeof input === \"string\") {\n try {\n parsedInput = JSON.parse(input);\n } catch {\n parsedInput = [];\n }\n }\n\n const warnings: ReplayParseResult[\"warnings\"] = [];\n const turns: ReplayTurn[] = [];\n const conversations = gatherConversations(parsedInput);\n\n for (let i = 0; i < conversations.length; i += 1) {\n const conversation = conversations[i];\n const convoIdRaw = conversation.uuid ?? conversation.id ?? conversation.conversation_id;\n const hasSourceConversationId = typeof convoIdRaw === \"string\" && convoIdRaw.trim().length > 0;\n const convoId = hasSourceConversationId ? convoIdRaw.trim() : `conv-${i + 1}`;\n const sessionKey = `replay:claude:${convoId}`;\n const fallbackSessionKey = options.defaultSessionKey?.trim() || sessionKey;\n\n const messagesRaw = Array.isArray(conversation.chat_messages)\n ? conversation.chat_messages\n : Array.isArray(conversation.messages)\n ? conversation.messages\n : [];\n\n for (let j = 0; j < messagesRaw.length; j += 1) {\n const msg = messagesRaw[j];\n if (!msg || typeof msg !== \"object\") {\n warnings.push({\n code: \"replay.claude.message.invalid\",\n message: `Skipping malformed Claude message at conversation ${i + 1}, index ${j}.`,\n index: j,\n });\n continue;\n }\n\n const row = msg as Record<string, unknown>;\n const role = normalizeReplayRole(\n row.sender ?? row.role ?? (row.author as Record<string, unknown> | undefined)?.role,\n );\n const content = normalizeReplayContent(row.text ?? row.content ?? row.message);\n const timestamp = normalizeReplayTimestamp(\n row.created_at ?? row.createdAt ?? row.updated_at ?? row.updatedAt ?? row.timestamp,\n );\n\n if (!role || !content || !timestamp) {\n const message = `Skipping invalid Claude replay message at conversation ${i + 1}, index ${j}.`;\n if (options.strict) throw new Error(message);\n warnings.push({ code: \"replay.claude.message.invalid\", message, index: j });\n continue;\n }\n\n const externalIdRaw = row.uuid ?? row.id;\n\n turns.push({\n source: \"claude\",\n sessionKey: hasSourceConversationId ? sessionKey : fallbackSessionKey,\n role,\n content,\n timestamp,\n externalId: typeof externalIdRaw === \"string\" ? externalIdRaw : undefined,\n metadata: {\n conversationId: convoId,\n conversationName: typeof conversation.name === \"string\" ? conversation.name : undefined,\n },\n });\n }\n }\n\n return { turns, warnings };\n },\n};\n","import {\n type ReplayNormalizer,\n type ReplayParseOptions,\n type ReplayParseResult,\n type ReplayTurn,\n} from \"../types.js\";\nimport { normalizeReplayContent, normalizeReplayRole, normalizeReplayTimestamp } from \"./shared.js\";\n\nfunction parseJsonl(raw: string, warnings: Array<{ code: string; message: string; index?: number }>): unknown[] {\n const out: unknown[] = [];\n for (const [index, line] of raw.split(\"\\n\").entries()) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n out.push(JSON.parse(trimmed));\n } catch {\n warnings.push({\n code: \"replay.openclaw.jsonl.invalid_line\",\n message: `Skipping invalid JSONL line ${index + 1}.`,\n index,\n });\n }\n }\n return out;\n}\n\nfunction gatherCandidates(input: unknown, warnings: Array<{ code: string; message: string; index?: number }>): unknown[] {\n if (Array.isArray(input)) return input;\n\n if (typeof input === \"string\") {\n try {\n return gatherCandidates(JSON.parse(input), warnings);\n } catch {\n return parseJsonl(input, warnings);\n }\n }\n\n if (!input || typeof input !== \"object\") return [];\n const obj = input as Record<string, unknown>;\n\n if (Array.isArray(obj.turns)) return obj.turns;\n if (Array.isArray(obj.entries)) return obj.entries;\n if (Array.isArray(obj.messages)) return obj.messages;\n\n if (Array.isArray(obj.records)) {\n const rows: unknown[] = [];\n for (const rec of obj.records) {\n if (!rec || typeof rec !== \"object\") continue;\n const record = rec as Record<string, unknown>;\n const content = typeof record.content === \"string\" ? record.content : null;\n if (!content) continue;\n const path = typeof record.path === \"string\" ? record.path : \"\";\n if (!path.startsWith(\"transcripts/\") && !path.includes(\"/transcripts/\")) continue;\n rows.push(...parseJsonl(content, warnings));\n }\n return rows;\n }\n\n return [];\n}\n\nexport const openclawReplayNormalizer: ReplayNormalizer = {\n source: \"openclaw\",\n parse(input: unknown, options: ReplayParseOptions = {}): ReplayParseResult {\n const warnings: ReplayParseResult[\"warnings\"] = [];\n const rawTurns = gatherCandidates(input, warnings);\n const turns: ReplayTurn[] = [];\n\n const defaultSessionKey = options.defaultSessionKey?.trim() || \"replay:openclaw:import\";\n\n for (let i = 0; i < rawTurns.length; i += 1) {\n const raw = rawTurns[i];\n if (!raw || typeof raw !== \"object\") {\n warnings.push({\n code: \"replay.openclaw.turn.invalid\",\n message: \"Skipping non-object replay turn.\",\n index: i,\n });\n continue;\n }\n\n const row = raw as Record<string, unknown>;\n const role = normalizeReplayRole(row.role ?? row.sender ?? (row.author as Record<string, unknown> | undefined)?.role, {\n assistantAliases: [\"bot\"],\n });\n const content = normalizeReplayContent(row.content ?? row.text ?? row.message);\n const timestamp = normalizeReplayTimestamp(\n row.timestamp ?? row.createdAt ?? row.created_at ?? row.time ?? row.date,\n { acceptDateObject: true },\n );\n\n if (!role || !content || !timestamp) {\n const message = `Skipping invalid openclaw turn at index ${i}.`;\n if (options.strict) throw new Error(message);\n warnings.push({ code: \"replay.openclaw.turn.invalid\", message, index: i });\n continue;\n }\n\n const sessionKeyRaw = row.sessionKey ?? row.session_key;\n const sessionKey = typeof sessionKeyRaw === \"string\" && sessionKeyRaw.trim().length > 0\n ? sessionKeyRaw.trim()\n : defaultSessionKey;\n\n const externalIdRaw = row.turnId ?? row.turn_id ?? row.id;\n\n turns.push({\n source: \"openclaw\",\n sessionKey,\n role,\n content,\n timestamp,\n externalId: typeof externalIdRaw === \"string\" ? externalIdRaw : undefined,\n });\n }\n\n return { turns, warnings };\n },\n};\n","import path from \"node:path\";\nimport { mkdir, readdir, readFile, unlink, writeFile } from \"node:fs/promises\";\n\nconst DATE_FILE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})\\.(jsonl|md)$/;\n\nexport interface ArchiveObservationsOptions {\n memoryDir: string;\n retentionDays?: number;\n dryRun?: boolean;\n now?: Date;\n}\n\nexport interface ArchiveObservationsResult {\n dryRun: boolean;\n retentionDays: number;\n scannedFiles: number;\n archivedFiles: number;\n archivedBytes: number;\n archiveRoot: string;\n archivedRelativePaths: string[];\n}\n\ninterface CandidateFile {\n absolutePath: string;\n relativePath: string;\n}\n\nfunction normalizeRetentionDays(value: number | undefined): number {\n if (!Number.isFinite(value as number)) return 30;\n return Math.max(0, Math.floor(value as number));\n}\n\nfunction extractDateFromFilename(name: string): Date | null {\n const match = DATE_FILE_PATTERN.exec(name);\n if (!match) return null;\n const iso = `${match[1]}-${match[2]}-${match[3]}T00:00:00.000Z`;\n const parsed = new Date(iso);\n if (Number.isNaN(parsed.getTime())) return null;\n return parsed;\n}\n\nfunction startOfUtcDay(value: Date): number {\n return Date.UTC(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate());\n}\n\nasync function listFilesRecursive(root: string, relPrefix = \"\"): Promise<string[]> {\n const out: string[] = [];\n let entries: Array<{ name: string; isDirectory(): boolean; isFile(): boolean }>;\n try {\n entries = (await readdir(root, { withFileTypes: true })) as Array<{\n name: string;\n isDirectory(): boolean;\n isFile(): boolean;\n }>;\n } catch {\n return out;\n }\n\n for (const entry of entries) {\n const rel = relPrefix ? path.join(relPrefix, entry.name) : entry.name;\n const full = path.join(root, entry.name);\n if (entry.isDirectory()) {\n out.push(...(await listFilesRecursive(full, rel)));\n continue;\n }\n if (entry.isFile()) out.push(rel);\n }\n\n return out;\n}\n\nasync function collectArchiveCandidates(\n memoryDir: string,\n cutoffTimeMs: number,\n): Promise<CandidateFile[]> {\n const roots = [\"transcripts\", path.join(\"state\", \"tool-usage\"), path.join(\"summaries\", \"hourly\")];\n const out: CandidateFile[] = [];\n\n for (const relRoot of roots) {\n const absRoot = path.join(memoryDir, relRoot);\n const files = await listFilesRecursive(absRoot);\n for (const fileRel of files) {\n const filename = path.basename(fileRel);\n const parsedDate = extractDateFromFilename(filename);\n if (!parsedDate) continue;\n if (parsedDate.getTime() >= cutoffTimeMs) continue;\n out.push({\n absolutePath: path.join(absRoot, fileRel),\n relativePath: path.join(relRoot, fileRel),\n });\n }\n }\n\n out.sort((a, b) => a.relativePath.localeCompare(b.relativePath));\n return out;\n}\n\nexport async function archiveObservations(\n options: ArchiveObservationsOptions,\n): Promise<ArchiveObservationsResult> {\n const retentionDays = normalizeRetentionDays(options.retentionDays);\n const dryRun = options.dryRun !== false;\n const now = options.now ?? new Date();\n const cutoffDayStartUtc = startOfUtcDay(\n new Date(now.getTime() - retentionDays * 24 * 60 * 60 * 1000),\n );\n const stamp = now.toISOString().replace(/[-:]/g, \"\").replace(/\\.\\d{3}Z$/, \"Z\");\n const archiveRoot = path.join(options.memoryDir, \"archive\", \"observations\", stamp);\n const candidates =\n retentionDays === 0\n ? []\n : await collectArchiveCandidates(\n options.memoryDir,\n cutoffDayStartUtc,\n );\n\n let archivedFiles = 0;\n let archivedBytes = 0;\n const archivedRelativePaths: string[] = [];\n\n if (!dryRun && candidates.length > 0) {\n await mkdir(archiveRoot, { recursive: true });\n for (const candidate of candidates) {\n const archivePath = path.join(archiveRoot, candidate.relativePath);\n const archiveDir = path.dirname(archivePath);\n await mkdir(archiveDir, { recursive: true });\n const raw = await readFile(candidate.absolutePath);\n await writeFile(archivePath, raw);\n await unlink(candidate.absolutePath);\n archivedFiles += 1;\n archivedBytes += raw.byteLength;\n archivedRelativePaths.push(candidate.relativePath);\n }\n } else {\n archivedRelativePaths.push(...candidates.map((c) => c.relativePath));\n }\n\n return {\n dryRun,\n retentionDays,\n scannedFiles: candidates.length,\n archivedFiles,\n archivedBytes,\n archiveRoot,\n archivedRelativePaths,\n };\n}\n","import path from \"node:path\";\nimport { mkdir, rename, stat, writeFile } from \"node:fs/promises\";\nimport { StorageManager } from \"../storage.js\";\nimport type { MemoryLifecycleEvent } from \"../types.js\";\nimport { toBackupStamp } from \"./backup-stamp.js\";\nimport {\n buildLifecycleEventsForMemory,\n sortMemoryLifecycleEvents,\n} from \"../memory-lifecycle-ledger-utils.js\";\n\nexport interface RebuildMemoryLifecycleLedgerOptions {\n memoryDir: string;\n dryRun?: boolean;\n now?: Date;\n}\n\nexport interface RebuildMemoryLifecycleLedgerResult {\n dryRun: boolean;\n scannedMemories: number;\n rebuiltRows: number;\n outputPath: string;\n backupPath?: string;\n}\n\nasync function backupExistingLedger(\n memoryDir: string,\n outputPath: string,\n now: Date,\n): Promise<string | undefined> {\n try {\n await stat(outputPath);\n } catch {\n return undefined;\n }\n\n const backupPath = path.join(\n memoryDir,\n \"archive\",\n \"memory-lifecycle-ledger\",\n toBackupStamp(now),\n \"state\",\n \"memory-lifecycle-ledger.jsonl\",\n );\n await mkdir(path.dirname(backupPath), { recursive: true });\n await rename(outputPath, backupPath);\n return backupPath;\n}\n\nexport async function rebuildMemoryLifecycleLedger(\n options: RebuildMemoryLifecycleLedgerOptions,\n): Promise<RebuildMemoryLifecycleLedgerResult> {\n const dryRun = options.dryRun !== false;\n const now = options.now ?? new Date();\n const outputPath = path.join(options.memoryDir, \"state\", \"memory-lifecycle-ledger.jsonl\");\n const storage = new StorageManager(options.memoryDir);\n const allMemories = [...await storage.readAllMemories(), ...await storage.readArchivedMemories()]\n .sort((a, b) => a.frontmatter.id.localeCompare(b.frontmatter.id));\n\n const events: MemoryLifecycleEvent[] = sortMemoryLifecycleEvents(\n allMemories.flatMap((memory) => buildLifecycleEventsForMemory(memory)),\n );\n\n let backupPath: string | undefined;\n if (!dryRun) {\n backupPath = await backupExistingLedger(options.memoryDir, outputPath, now);\n await mkdir(path.dirname(outputPath), { recursive: true });\n const payload = events.map((event) => JSON.stringify(event)).join(\"\\n\");\n await writeFile(outputPath, payload.length > 0 ? `${payload}\\n` : \"\", \"utf-8\");\n }\n\n return {\n dryRun,\n scannedMemories: allMemories.length,\n rebuiltRows: events.length,\n outputPath,\n backupPath,\n };\n}\n","export function toBackupStamp(now: Date): string {\n return now.toISOString().replace(/[-:]/g, \"\").replace(/\\.\\d{3}Z$/, \"Z\");\n}\n","import path from \"node:path\";\nimport { mkdir, rename, rm, stat } from \"node:fs/promises\";\nimport { StorageManager } from \"../storage.js\";\nimport {\n listMemoryGovernanceRuns,\n readMemoryGovernanceRunArtifact,\n} from \"./memory-governance.js\";\nimport { loadPersistedNativeKnowledgeChunks } from \"../native-knowledge.js\";\nimport { toBackupStamp } from \"./backup-stamp.js\";\nimport type {\n MemoryFile,\n MemoryLifecycleEvent,\n MemoryProjectionCurrentState,\n MemoryStatus,\n} from \"../types.js\";\nimport {\n buildLifecycleEventsForMemory,\n inferMemoryStatus,\n MEMORY_LIFECYCLE_EVENT_SORT_ORDER,\n sortMemoryLifecycleEvents,\n toMemoryPathRel,\n} from \"../memory-lifecycle-ledger-utils.js\";\nimport {\n getMemoryProjectionPath,\n initializeMemoryProjectionDb,\n type ProjectedEntityMentionRow,\n type MemoryProjectionGovernanceAppliedActionRow,\n type MemoryProjectionGovernanceReviewQueueRow,\n type ProjectedNativeKnowledgeChunkRow,\n MEMORY_PROJECTION_SCHEMA_VERSION,\n memoryCurrentSelectExpressions,\n parseCurrentRow,\n readProjectedEntityMentions,\n readProjectedGovernanceRecord,\n readProjectedNativeKnowledgeChunks,\n parseTimelineRows,\n} from \"../memory-projection-store.js\";\nimport {\n normalizeProjectionPreview,\n normalizeProjectionTags,\n} from \"../memory-projection-format.js\";\nimport { openBetterSqlite3 } from \"../runtime/better-sqlite.js\";\n\nexport interface RebuildMemoryProjectionOptions {\n memoryDir: string;\n defaultNamespace?: string;\n dryRun?: boolean;\n now?: Date;\n updatedAfter?: string;\n updatedBefore?: string;\n}\n\nexport interface RebuildMemoryProjectionResult {\n dryRun: boolean;\n scannedMemories: number;\n currentRows: number;\n timelineRows: number;\n entityMentionRows: number;\n nativeKnowledgeRows: number;\n reviewQueueRows: number;\n outputPath: string;\n backupPath?: string;\n usedLifecycleLedger: boolean;\n scope: {\n updatedAfter: string | null;\n updatedBefore: string | null;\n };\n}\n\nexport interface VerifyMemoryProjectionOptions {\n memoryDir: string;\n defaultNamespace?: string;\n updatedAfter?: string;\n updatedBefore?: string;\n}\n\nexport interface VerifyMemoryProjectionResult {\n outputPath: string;\n projectionExists: boolean;\n ok: boolean;\n expectedCurrentRows: number;\n actualCurrentRows: number;\n expectedTimelineRows: number;\n actualTimelineRows: number;\n expectedEntityMentionRows: number;\n actualEntityMentionRows: number;\n expectedNativeKnowledgeRows: number;\n actualNativeKnowledgeRows: number;\n expectedReviewQueueRows: number;\n actualReviewQueueRows: number;\n missingCurrentMemoryIds: string[];\n extraCurrentMemoryIds: string[];\n mismatchedCurrentMemoryIds: string[];\n missingTimelineEventIds: string[];\n extraTimelineEventIds: string[];\n missingEntityMentionKeys: string[];\n extraEntityMentionKeys: string[];\n mismatchedEntityMentionKeys: string[];\n missingNativeKnowledgeChunkIds: string[];\n extraNativeKnowledgeChunkIds: string[];\n mismatchedNativeKnowledgeChunkIds: string[];\n missingReviewQueueEntryIds: string[];\n extraReviewQueueEntryIds: string[];\n mismatchedReviewQueueEntryIds: string[];\n usedLifecycleLedger: boolean;\n scope: {\n updatedAfter: string | null;\n updatedBefore: string | null;\n };\n}\n\nexport interface RepairMemoryProjectionOptions extends RebuildMemoryProjectionOptions {}\n\nexport interface RepairMemoryProjectionResult {\n dryRun: boolean;\n repaired: boolean;\n verify: VerifyMemoryProjectionResult;\n rebuild?: RebuildMemoryProjectionResult;\n}\n\nasync function backupExistingProjection(\n memoryDir: string,\n outputPath: string,\n now: Date,\n): Promise<string | undefined> {\n try {\n await stat(outputPath);\n } catch {\n return undefined;\n }\n\n const backupPath = path.join(\n memoryDir,\n \"archive\",\n \"memory-projection\",\n toBackupStamp(now),\n \"state\",\n \"memory-projection.sqlite\",\n );\n await mkdir(path.dirname(backupPath), { recursive: true });\n await rename(outputPath, backupPath);\n return backupPath;\n}\n\nfunction inferProjectedStatus(pathRel: string, memory: MemoryFile): MemoryStatus {\n return inferMemoryStatus(memory.frontmatter, pathRel);\n}\n\nfunction toCurrentStateRow(memoryDir: string, memory: MemoryFile): MemoryProjectionCurrentState {\n const pathRel = toMemoryPathRel(memoryDir, memory.path);\n return {\n memoryId: memory.frontmatter.id,\n category: memory.frontmatter.category,\n status: inferProjectedStatus(pathRel, memory),\n lifecycleState: memory.frontmatter.lifecycleState,\n path: memory.path,\n pathRel,\n created: memory.frontmatter.created,\n updated: memory.frontmatter.updated,\n archivedAt: memory.frontmatter.archivedAt,\n supersededAt: memory.frontmatter.supersededAt,\n entityRef: memory.frontmatter.entityRef,\n source: memory.frontmatter.source,\n confidence: memory.frontmatter.confidence,\n confidenceTier: memory.frontmatter.confidenceTier,\n memoryKind: memory.frontmatter.memoryKind,\n accessCount: memory.frontmatter.accessCount,\n lastAccessed: memory.frontmatter.lastAccessed,\n tags: normalizeProjectionTags(memory.frontmatter.tags),\n preview: normalizeProjectionPreview(memory.content),\n };\n}\n\nfunction buildEntityMentionRows(\n currentRows: MemoryProjectionCurrentState[],\n): ProjectedEntityMentionRow[] {\n return currentRows.flatMap((row) => {\n const mentions: ProjectedEntityMentionRow[] = [];\n if (row.entityRef) {\n mentions.push({\n memoryId: row.memoryId,\n entityRef: row.entityRef,\n mentionSource: \"frontmatter.entityRef\",\n created: row.created,\n updated: row.updated,\n });\n }\n for (const tag of row.tags ?? []) {\n if (!tag.includes(\":\")) continue;\n mentions.push({\n memoryId: row.memoryId,\n entityRef: tag,\n mentionSource: \"tag\",\n created: row.created,\n updated: row.updated,\n });\n }\n return mentions;\n });\n}\n\nfunction buildGovernanceActionRowKey(action: {\n action: string;\n memoryId: string;\n reasonCode: string;\n originalPath: string;\n currentPath: string;\n}): string {\n return [\n action.action,\n action.memoryId,\n action.reasonCode,\n action.originalPath,\n action.currentPath,\n ].join(\"::\");\n}\n\nasync function loadLatestGovernanceProjection(memoryDir: string): Promise<{\n runId: string;\n summary: unknown;\n metrics: unknown;\n reviewQueueRows: MemoryProjectionGovernanceReviewQueueRow[];\n appliedActionRows: MemoryProjectionGovernanceAppliedActionRow[];\n report: string;\n} | null> {\n const runId = (await listMemoryGovernanceRuns(memoryDir))[0];\n if (!runId) return null;\n try {\n const artifact = await readMemoryGovernanceRunArtifact(memoryDir, runId);\n return {\n runId,\n summary: artifact.summary,\n metrics: artifact.metrics,\n reviewQueueRows: artifact.reviewQueue.map((entry) => ({\n runId,\n entryId: entry.entryId,\n memoryId: entry.memoryId,\n path: entry.path,\n reasonCode: entry.reasonCode,\n severity: entry.severity,\n suggestedAction: entry.suggestedAction,\n suggestedStatus: entry.suggestedStatus,\n relatedMemoryIds: [...entry.relatedMemoryIds],\n })),\n appliedActionRows: artifact.appliedActions.map((action) => ({\n runId,\n rowKey: buildGovernanceActionRowKey(action),\n action: action.action,\n memoryId: action.memoryId,\n reasonCode: action.reasonCode,\n beforeStatus: action.beforeStatus,\n afterStatus: action.afterStatus,\n originalPath: action.originalPath,\n currentPath: action.currentPath,\n })),\n report: artifact.report,\n };\n } catch {\n return null;\n }\n}\n\nfunction loadTimelineEvents(\n memories: MemoryFile[],\n lifecycleEvents: MemoryLifecycleEvent[],\n): { events: MemoryLifecycleEvent[]; usedLifecycleLedger: boolean } {\n if (lifecycleEvents.length > 0) {\n return {\n events: sortMemoryLifecycleEvents(lifecycleEvents),\n usedLifecycleLedger: true,\n };\n }\n\n return {\n events: sortMemoryLifecycleEvents(memories.flatMap((memory) => buildLifecycleEventsForMemory(memory))),\n usedLifecycleLedger: false,\n };\n}\n\nfunction normalizeScopedIso(value: string | undefined): string | null {\n if (!value) return null;\n const trimmed = value.trim();\n if (!trimmed) return null;\n const parsed = new Date(trimmed);\n if (Number.isNaN(parsed.getTime())) {\n throw new Error(`invalid projection scope timestamp: ${value}`);\n }\n return parsed.toISOString();\n}\n\nfunction normalizeProjectionScope(options: {\n updatedAfter?: string;\n updatedBefore?: string;\n}): {\n updatedAfter: string | null;\n updatedBefore: string | null;\n} {\n const updatedAfter = normalizeScopedIso(options.updatedAfter);\n const updatedBefore = normalizeScopedIso(options.updatedBefore);\n if (\n updatedAfter &&\n updatedBefore &&\n new Date(updatedAfter).getTime() > new Date(updatedBefore).getTime()\n ) {\n throw new Error(\"updatedAfter must be less than or equal to updatedBefore\");\n }\n return {\n updatedAfter,\n updatedBefore,\n };\n}\n\nfunction hasScopedProjectionFilter(scope: {\n updatedAfter: string | null;\n updatedBefore: string | null;\n}): boolean {\n return scope.updatedAfter !== null || scope.updatedBefore !== null;\n}\n\nfunction memoryScopeTimestamp(memory: MemoryFile): string {\n const candidate = memory.frontmatter.updated || memory.frontmatter.created;\n return candidate;\n}\n\nfunction isTimestampInProjectionScope(\n timestamp: string,\n scope: { updatedAfter: string | null; updatedBefore: string | null },\n): boolean {\n if (!scope.updatedAfter && !scope.updatedBefore) return true;\n const parsed = new Date(timestamp);\n if (Number.isNaN(parsed.getTime())) return false;\n if (scope.updatedAfter && parsed.getTime() < new Date(scope.updatedAfter).getTime()) return false;\n if (scope.updatedBefore && parsed.getTime() > new Date(scope.updatedBefore).getTime()) return false;\n return true;\n}\n\nfunction filterMemoriesForProjectionScope(\n memories: MemoryFile[],\n scope: { updatedAfter: string | null; updatedBefore: string | null },\n): MemoryFile[] {\n if (!scope.updatedAfter && !scope.updatedBefore) return memories;\n return memories.filter((memory) => isTimestampInProjectionScope(memoryScopeTimestamp(memory), scope));\n}\n\nfunction filterCurrentStateRowsForProjectionScope(\n rows: MemoryProjectionCurrentState[],\n scope: { updatedAfter: string | null; updatedBefore: string | null },\n): MemoryProjectionCurrentState[] {\n if (!scope.updatedAfter && !scope.updatedBefore) return rows;\n return rows.filter((row) => isTimestampInProjectionScope(row.updated || row.created, scope));\n}\n\nfunction serializeCurrentStateRow(row: MemoryProjectionCurrentState): string {\n return JSON.stringify({\n memoryId: row.memoryId,\n category: row.category,\n status: row.status,\n lifecycleState: row.lifecycleState ?? null,\n pathRel: row.pathRel,\n created: row.created,\n updated: row.updated,\n archivedAt: row.archivedAt ?? null,\n supersededAt: row.supersededAt ?? null,\n entityRef: row.entityRef ?? null,\n source: row.source,\n confidence: row.confidence,\n confidenceTier: row.confidenceTier,\n memoryKind: row.memoryKind ?? null,\n accessCount: row.accessCount ?? null,\n lastAccessed: row.lastAccessed ?? null,\n tags: row.tags ?? [],\n preview: row.preview ?? \"\",\n });\n}\n\nfunction serializeTimelineEvent(event: MemoryLifecycleEvent): string {\n return JSON.stringify({\n eventId: event.eventId,\n memoryId: event.memoryId,\n eventType: event.eventType,\n timestamp: event.timestamp,\n actor: event.actor,\n reasonCode: event.reasonCode ?? null,\n ruleVersion: event.ruleVersion,\n relatedMemoryIds: event.relatedMemoryIds ?? [],\n before: event.before ?? null,\n after: event.after ?? null,\n correlationId: event.correlationId ?? null,\n });\n}\n\nfunction serializeEntityMentionRow(row: ProjectedEntityMentionRow): string {\n return JSON.stringify(row);\n}\n\nfunction serializeNativeKnowledgeRow(row: ProjectedNativeKnowledgeChunkRow): string {\n return JSON.stringify({\n chunkId: row.chunkId,\n sourceKind: row.sourceKind,\n sourcePath: row.sourcePath,\n title: row.title,\n startLine: row.startLine,\n endLine: row.endLine,\n namespace: row.namespace ?? null,\n privacyClass: row.privacyClass ?? null,\n derivedDate: row.derivedDate ?? null,\n sessionKey: row.sessionKey ?? null,\n workflowKey: row.workflowKey ?? null,\n author: row.author ?? null,\n agent: row.agent ?? null,\n sourceHash: row.sourceHash ?? null,\n preview: row.preview,\n });\n}\n\nfunction serializeGovernanceReviewQueueRow(\n row: MemoryProjectionGovernanceReviewQueueRow,\n): string {\n return JSON.stringify({\n runId: row.runId,\n entryId: row.entryId,\n memoryId: row.memoryId,\n path: row.path,\n reasonCode: row.reasonCode,\n severity: row.severity,\n suggestedAction: row.suggestedAction,\n suggestedStatus: row.suggestedStatus ?? null,\n relatedMemoryIds: row.relatedMemoryIds,\n });\n}\n\nasync function loadAuthoritativeProjectionSnapshot(options: {\n memoryDir: string;\n defaultNamespace?: string;\n updatedAfter?: string;\n updatedBefore?: string;\n}): Promise<{\n allMemories: MemoryFile[];\n currentRows: MemoryProjectionCurrentState[];\n timelineRows: MemoryLifecycleEvent[];\n scopedCurrentRows: MemoryProjectionCurrentState[];\n scopedTimelineRows: MemoryLifecycleEvent[];\n entityMentionRows: ProjectedEntityMentionRow[];\n scopedEntityMentionRows: ProjectedEntityMentionRow[];\n nativeKnowledgeRows: ProjectedNativeKnowledgeChunkRow[];\n governance:\n | {\n runId: string;\n summary: unknown;\n metrics: unknown;\n reviewQueueRows: MemoryProjectionGovernanceReviewQueueRow[];\n appliedActionRows: MemoryProjectionGovernanceAppliedActionRow[];\n report: string;\n }\n | null;\n usedLifecycleLedger: boolean;\n scope: {\n updatedAfter: string | null;\n updatedBefore: string | null;\n };\n}> {\n const storage = new StorageManager(options.memoryDir);\n // Force a fresh disk read — projection verify/rebuild must see the true\n // on-disk state, not a potentially stale in-process cache.\n storage.invalidateAllMemoriesCacheForDir();\n const allMemories = [...await storage.readAllMemories(), ...await storage.readArchivedMemories()]\n .sort((a, b) => a.frontmatter.id.localeCompare(b.frontmatter.id));\n const lifecycleEvents = await storage.readAllMemoryLifecycleEvents();\n const { events, usedLifecycleLedger } = loadTimelineEvents(allMemories, lifecycleEvents);\n const currentRows = allMemories.map((memory) => toCurrentStateRow(options.memoryDir, memory));\n const scope = normalizeProjectionScope(options);\n const scopedMemories = filterMemoriesForProjectionScope(allMemories, scope);\n const scopedMemoryIds = new Set(scopedMemories.map((memory) => memory.frontmatter.id));\n const nativeKnowledgeRows = await loadPersistedNativeKnowledgeChunks({\n memoryDir: options.memoryDir,\n defaultNamespace: options.defaultNamespace ?? \"default\",\n }).then((rows) => rows.map((row) => ({\n chunkId: row.chunkId,\n sourceKind: row.sourceKind,\n sourcePath: row.sourcePath,\n title: row.title,\n startLine: row.startLine,\n endLine: row.endLine,\n namespace: row.namespace ?? options.defaultNamespace ?? \"default\",\n privacyClass: row.privacyClass,\n derivedDate: row.derivedDate,\n sessionKey: row.sessionKey,\n workflowKey: row.workflowKey,\n author: row.author,\n agent: row.agent,\n sourceHash: row.sourceHash,\n preview: normalizeProjectionPreview(row.content),\n })));\n const governance = await loadLatestGovernanceProjection(options.memoryDir);\n const entityMentionRows = buildEntityMentionRows(currentRows);\n\n return {\n allMemories,\n currentRows,\n timelineRows: events,\n scopedCurrentRows: currentRows.filter((row) => scopedMemoryIds.has(row.memoryId)),\n scopedTimelineRows: events.filter((event) => scopedMemoryIds.has(event.memoryId)),\n entityMentionRows,\n scopedEntityMentionRows: entityMentionRows.filter((row) => scopedMemoryIds.has(row.memoryId)),\n nativeKnowledgeRows,\n governance,\n usedLifecycleLedger,\n scope,\n };\n}\n\nfunction readProjectedCurrentRows(\n memoryDir: string,\n): { projectionExists: boolean; rows: MemoryProjectionCurrentState[] } {\n const dbPath = getMemoryProjectionPath(memoryDir);\n try {\n const db = openBetterSqlite3(dbPath, { readonly: true, fileMustExist: true });\n try {\n const selectExpressions = memoryCurrentSelectExpressions(db);\n const rows = db.prepare(`\n SELECT\n memory_id,\n category,\n status,\n lifecycle_state,\n path_rel,\n created_at,\n updated_at,\n archived_at,\n superseded_at,\n entity_ref,\n source,\n confidence,\n confidence_tier,\n memory_kind,\n access_count,\n last_accessed,\n ${selectExpressions.tagsJson},\n ${selectExpressions.previewText}\n FROM memory_current\n `).all() as Array<Record<string, unknown>>;\n\n return {\n projectionExists: true,\n rows: rows\n .map((row) => parseCurrentRow(memoryDir, row))\n .filter((row): row is MemoryProjectionCurrentState => row !== null),\n };\n } finally {\n db.close();\n }\n } catch {\n return { projectionExists: false, rows: [] };\n }\n}\n\nfunction readProjectedTimelineRows(\n memoryDir: string,\n): { projectionExists: boolean; rows: MemoryLifecycleEvent[] } {\n const dbPath = getMemoryProjectionPath(memoryDir);\n try {\n const db = openBetterSqlite3(dbPath, { readonly: true, fileMustExist: true });\n try {\n const rows = db.prepare(`\n SELECT\n event_id,\n memory_id,\n event_type,\n timestamp,\n actor,\n reason_code,\n rule_version,\n related_memory_ids_json,\n before_json,\n after_json,\n correlation_id\n FROM memory_timeline\n `).all() as Array<Record<string, unknown>>;\n\n return {\n projectionExists: true,\n rows: parseTimelineRows(rows),\n };\n } finally {\n db.close();\n }\n } catch {\n return { projectionExists: false, rows: [] };\n }\n}\n\nfunction readProjectedEntityMentionRows(\n memoryDir: string,\n): { projectionExists: boolean; rows: ProjectedEntityMentionRow[] } {\n const rows = readProjectedEntityMentions(memoryDir);\n if (rows === null) return { projectionExists: false, rows: [] };\n return { projectionExists: true, rows };\n}\n\nfunction readProjectedNativeKnowledgeRows(\n memoryDir: string,\n): { projectionExists: boolean; rows: ProjectedNativeKnowledgeChunkRow[] } {\n const rows = readProjectedNativeKnowledgeChunks(memoryDir);\n if (rows === null) return { projectionExists: false, rows: [] };\n return { projectionExists: true, rows };\n}\n\nfunction readProjectedGovernanceRows(memoryDir: string): {\n projectionExists: boolean;\n runId: string | null;\n summary: unknown;\n metrics: unknown;\n reviewQueueRows: MemoryProjectionGovernanceReviewQueueRow[];\n appliedActionRows: MemoryProjectionGovernanceAppliedActionRow[];\n report: string;\n} {\n const record = readProjectedGovernanceRecord(memoryDir);\n if (record === null) {\n return {\n projectionExists: false,\n runId: null,\n summary: undefined,\n metrics: undefined,\n reviewQueueRows: [],\n appliedActionRows: [],\n report: \"\",\n };\n }\n return {\n projectionExists: true,\n runId: record.runId,\n summary: record.summary,\n metrics: record.metrics,\n reviewQueueRows: record.reviewQueueRows,\n appliedActionRows: record.appliedActionRows,\n report: record.report,\n };\n}\n\nfunction writeProjectionDb(\n dbPath: string,\n nowIso: string,\n currentRows: MemoryProjectionCurrentState[],\n timelineRows: MemoryLifecycleEvent[],\n entityMentionRows: ProjectedEntityMentionRow[],\n nativeKnowledgeRows: ProjectedNativeKnowledgeChunkRow[],\n governance: Awaited<ReturnType<typeof loadLatestGovernanceProjection>>,\n usedLifecycleLedger: boolean,\n): void {\n const db = openBetterSqlite3(dbPath);\n try {\n initializeMemoryProjectionDb(db);\n\n const insertMeta = db.prepare(\"INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)\");\n insertMeta.run(\"schemaVersion\", String(MEMORY_PROJECTION_SCHEMA_VERSION));\n insertMeta.run(\"rebuiltAt\", nowIso);\n insertMeta.run(\"usedLifecycleLedger\", usedLifecycleLedger ? \"true\" : \"false\");\n insertMeta.run(\"latestGovernanceRunId\", governance?.runId ?? \"\");\n\n const insertCurrent = db.prepare(`\n INSERT INTO memory_current (\n memory_id,\n category,\n status,\n lifecycle_state,\n path_rel,\n created_at,\n updated_at,\n archived_at,\n superseded_at,\n entity_ref,\n source,\n confidence,\n confidence_tier,\n memory_kind,\n access_count,\n last_accessed,\n tags_json,\n preview_text\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n const insertTimeline = db.prepare(`\n INSERT INTO memory_timeline (\n event_id,\n memory_id,\n event_type,\n timestamp,\n event_order,\n actor,\n reason_code,\n rule_version,\n related_memory_ids_json,\n before_json,\n after_json,\n correlation_id\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n const insertEntityMention = db.prepare(`\n INSERT INTO memory_entity_mentions (\n memory_id,\n entity_ref,\n mention_source,\n created_at,\n updated_at\n ) VALUES (?, ?, ?, ?, ?)\n `);\n\n const insertNativeKnowledge = db.prepare(`\n INSERT INTO native_knowledge_chunks (\n chunk_id,\n source_kind,\n source_path,\n title,\n start_line,\n end_line,\n namespace,\n privacy_class,\n derived_date,\n session_key,\n workflow_key,\n author,\n agent,\n source_hash,\n preview_text\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n const insertGovernanceReviewQueue = db.prepare(`\n INSERT INTO memory_review_queue (\n entry_id,\n run_id,\n memory_id,\n path,\n reason_code,\n severity,\n suggested_action,\n suggested_status,\n related_memory_ids_json\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n const insertGovernanceAppliedAction = db.prepare(`\n INSERT INTO memory_review_actions (\n row_key,\n run_id,\n action,\n memory_id,\n reason_code,\n before_status,\n after_status,\n original_path,\n current_path\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n const insertGovernanceRun = db.prepare(`\n INSERT INTO memory_review_runs (\n run_id,\n created_at,\n mode,\n summary_json,\n metrics_json,\n applied_actions_json,\n report_markdown\n ) VALUES (?, ?, ?, ?, ?, ?, ?)\n `);\n\n const writeTx = db.transaction(() => {\n for (const row of currentRows) {\n insertCurrent.run(\n row.memoryId,\n row.category,\n row.status,\n row.lifecycleState ?? null,\n row.pathRel,\n row.created,\n row.updated,\n row.archivedAt ?? null,\n row.supersededAt ?? null,\n row.entityRef ?? null,\n row.source,\n row.confidence,\n row.confidenceTier,\n row.memoryKind ?? null,\n row.accessCount ?? null,\n row.lastAccessed ?? null,\n JSON.stringify(row.tags ?? []),\n row.preview ?? \"\",\n );\n }\n\n for (const event of timelineRows) {\n insertTimeline.run(\n event.eventId,\n event.memoryId,\n event.eventType,\n event.timestamp,\n MEMORY_LIFECYCLE_EVENT_SORT_ORDER[event.eventType],\n event.actor,\n event.reasonCode ?? null,\n event.ruleVersion,\n JSON.stringify(event.relatedMemoryIds ?? []),\n event.before ? JSON.stringify(event.before) : null,\n event.after ? JSON.stringify(event.after) : null,\n event.correlationId ?? null,\n );\n }\n\n for (const row of entityMentionRows) {\n insertEntityMention.run(\n row.memoryId,\n row.entityRef,\n row.mentionSource,\n row.created,\n row.updated,\n );\n }\n\n for (const row of nativeKnowledgeRows) {\n insertNativeKnowledge.run(\n row.chunkId,\n row.sourceKind,\n row.sourcePath,\n row.title,\n row.startLine,\n row.endLine,\n row.namespace ?? null,\n row.privacyClass ?? null,\n row.derivedDate ?? null,\n row.sessionKey ?? null,\n row.workflowKey ?? null,\n row.author ?? null,\n row.agent ?? null,\n row.sourceHash ?? null,\n row.preview,\n );\n }\n\n for (const row of governance?.reviewQueueRows ?? []) {\n insertGovernanceReviewQueue.run(\n row.entryId,\n row.runId,\n row.memoryId,\n row.path,\n row.reasonCode,\n row.severity,\n row.suggestedAction,\n row.suggestedStatus ?? null,\n JSON.stringify(row.relatedMemoryIds),\n );\n }\n\n for (const row of governance?.appliedActionRows ?? []) {\n insertGovernanceAppliedAction.run(\n row.rowKey,\n row.runId,\n row.action,\n row.memoryId,\n row.reasonCode,\n row.beforeStatus,\n row.afterStatus ?? null,\n row.originalPath,\n row.currentPath,\n );\n }\n\n if (governance) {\n const createdAt =\n typeof (governance.summary as { createdAt?: unknown } | undefined)?.createdAt === \"string\"\n ? (governance.summary as { createdAt: string }).createdAt\n : nowIso;\n const mode =\n typeof (governance.summary as { mode?: unknown } | undefined)?.mode === \"string\"\n ? (governance.summary as { mode: string }).mode\n : \"shadow\";\n insertGovernanceRun.run(\n governance.runId,\n createdAt,\n mode,\n JSON.stringify(governance.summary ?? null),\n JSON.stringify(governance.metrics ?? null),\n JSON.stringify(\n (governance.appliedActionRows ?? []).map((row) => ({\n action: row.action,\n memoryId: row.memoryId,\n reasonCode: row.reasonCode,\n beforeStatus: row.beforeStatus,\n afterStatus: row.afterStatus,\n originalPath: row.originalPath,\n currentPath: row.currentPath,\n })),\n ),\n governance.report,\n );\n }\n });\n\n writeTx();\n } finally {\n db.close();\n }\n}\n\nfunction mergeScopedCurrentRows(\n existingRows: MemoryProjectionCurrentState[],\n replacementRows: MemoryProjectionCurrentState[],\n scopedMemoryIds: Set<string>,\n): MemoryProjectionCurrentState[] {\n return [...existingRows.filter((row) => !scopedMemoryIds.has(row.memoryId)), ...replacementRows]\n .sort((a, b) => a.memoryId.localeCompare(b.memoryId));\n}\n\nfunction mergeScopedTimelineRows(\n existingRows: MemoryLifecycleEvent[],\n replacementRows: MemoryLifecycleEvent[],\n scopedMemoryIds: Set<string>,\n): MemoryLifecycleEvent[] {\n return sortMemoryLifecycleEvents([\n ...existingRows.filter((event) => !scopedMemoryIds.has(event.memoryId)),\n ...replacementRows,\n ]);\n}\n\nfunction mergeScopedEntityMentionRows(\n existingRows: ProjectedEntityMentionRow[],\n replacementRows: ProjectedEntityMentionRow[],\n scopedMemoryIds: Set<string>,\n): ProjectedEntityMentionRow[] {\n return [\n ...existingRows.filter((row) => !scopedMemoryIds.has(row.memoryId)),\n ...replacementRows,\n ].sort((left, right) =>\n [left.entityRef, left.memoryId, left.mentionSource].join(\"::\").localeCompare(\n [right.entityRef, right.memoryId, right.mentionSource].join(\"::\"),\n )\n );\n}\n\nexport async function rebuildMemoryProjection(\n options: RebuildMemoryProjectionOptions,\n): Promise<RebuildMemoryProjectionResult> {\n const dryRun = options.dryRun !== false;\n const now = options.now ?? new Date();\n const outputPath = getMemoryProjectionPath(options.memoryDir);\n const snapshot = await loadAuthoritativeProjectionSnapshot(options);\n\n let backupPath: string | undefined;\n if (!dryRun) {\n let nextCurrentRows = snapshot.currentRows;\n let nextTimelineRows = snapshot.timelineRows;\n let nextEntityMentionRows = snapshot.entityMentionRows;\n let nextNativeKnowledgeRows = snapshot.nativeKnowledgeRows;\n let nextGovernance = snapshot.governance;\n if (hasScopedProjectionFilter(snapshot.scope)) {\n const projectedCurrent = readProjectedCurrentRows(options.memoryDir);\n const projectedTimeline = readProjectedTimelineRows(options.memoryDir);\n const projectedEntityMentions = readProjectedEntityMentionRows(options.memoryDir);\n const projectedNativeKnowledge = readProjectedNativeKnowledgeRows(options.memoryDir);\n const projectedGovernance = readProjectedGovernanceRows(options.memoryDir);\n if (projectedCurrent.projectionExists && projectedTimeline.projectionExists) {\n const actualScopedCurrentRows = filterCurrentStateRowsForProjectionScope(\n projectedCurrent.rows,\n snapshot.scope,\n );\n const scopedMemoryIds = new Set([\n ...snapshot.scopedCurrentRows.map((row) => row.memoryId),\n ...snapshot.scopedTimelineRows.map((event) => event.memoryId),\n ...actualScopedCurrentRows.map((row) => row.memoryId),\n ]);\n nextCurrentRows = mergeScopedCurrentRows(\n projectedCurrent.rows,\n snapshot.scopedCurrentRows,\n scopedMemoryIds,\n );\n nextTimelineRows = mergeScopedTimelineRows(\n projectedTimeline.rows,\n snapshot.scopedTimelineRows,\n scopedMemoryIds,\n );\n nextEntityMentionRows = mergeScopedEntityMentionRows(\n projectedEntityMentions.rows,\n snapshot.scopedEntityMentionRows,\n scopedMemoryIds,\n );\n }\n if (projectedNativeKnowledge.projectionExists) {\n // Native knowledge rows are always loaded from the full persisted sync state,\n // so scoped memory rebuilds should publish the fresh snapshot instead of\n // pinning the projection to stale previously projected rows.\n nextNativeKnowledgeRows = snapshot.nativeKnowledgeRows;\n }\n if (projectedGovernance.projectionExists && projectedGovernance.runId) {\n // Governance rows are also sourced from standalone artifact snapshots, so\n // scoped memory rebuilds should keep the latest governance artifact data\n // instead of restoring whatever happened to be in the prior projection.\n nextGovernance = snapshot.governance;\n }\n }\n\n const tempPath = `${outputPath}.tmp`;\n await mkdir(path.dirname(outputPath), { recursive: true });\n await rm(tempPath, { force: true });\n writeProjectionDb(\n tempPath,\n now.toISOString(),\n nextCurrentRows,\n nextTimelineRows,\n nextEntityMentionRows,\n nextNativeKnowledgeRows,\n nextGovernance,\n snapshot.usedLifecycleLedger,\n );\n backupPath = await backupExistingProjection(options.memoryDir, outputPath, now);\n await rename(tempPath, outputPath);\n }\n\n return {\n dryRun,\n scannedMemories: snapshot.allMemories.length,\n currentRows: snapshot.scopedCurrentRows.length,\n timelineRows: snapshot.scopedTimelineRows.length,\n entityMentionRows: snapshot.scopedEntityMentionRows.length,\n nativeKnowledgeRows: snapshot.nativeKnowledgeRows.length,\n reviewQueueRows: snapshot.governance?.reviewQueueRows.length ?? 0,\n outputPath,\n backupPath,\n usedLifecycleLedger: snapshot.usedLifecycleLedger,\n scope: snapshot.scope,\n };\n}\n\nexport async function verifyMemoryProjection(\n options: VerifyMemoryProjectionOptions,\n): Promise<VerifyMemoryProjectionResult> {\n const outputPath = getMemoryProjectionPath(options.memoryDir);\n const snapshot = await loadAuthoritativeProjectionSnapshot(options);\n const projectedCurrent = readProjectedCurrentRows(options.memoryDir);\n const projectedTimeline = readProjectedTimelineRows(options.memoryDir);\n const projectedEntityMentions = readProjectedEntityMentionRows(options.memoryDir);\n const projectedNativeKnowledge = readProjectedNativeKnowledgeRows(options.memoryDir);\n const projectedGovernance = readProjectedGovernanceRows(options.memoryDir);\n const projectionExists = projectedCurrent.projectionExists\n || projectedTimeline.projectionExists\n || projectedEntityMentions.projectionExists\n || projectedNativeKnowledge.projectionExists\n || projectedGovernance.projectionExists;\n\n const actualScopedCurrentRows = filterCurrentStateRowsForProjectionScope(projectedCurrent.rows, snapshot.scope);\n const expectedCurrentById = new Map(\n snapshot.scopedCurrentRows.map((row) => [row.memoryId, serializeCurrentStateRow(row)]),\n );\n const actualCurrentById = new Map(\n actualScopedCurrentRows.map((row) => [row.memoryId, serializeCurrentStateRow(row)]),\n );\n\n const missingCurrentMemoryIds = [...expectedCurrentById.keys()]\n .filter((memoryId) => !actualCurrentById.has(memoryId))\n .sort();\n const extraCurrentMemoryIds = [...actualCurrentById.keys()]\n .filter((memoryId) => !expectedCurrentById.has(memoryId))\n .sort();\n const mismatchedCurrentMemoryIds = [...expectedCurrentById.keys()]\n .filter((memoryId) =>\n actualCurrentById.has(memoryId) && actualCurrentById.get(memoryId) !== expectedCurrentById.get(memoryId)\n )\n .sort();\n\n const selectedMemoryIds = new Set([\n ...snapshot.scopedCurrentRows.map((row) => row.memoryId),\n ...actualScopedCurrentRows.map((row) => row.memoryId),\n ]);\n const expectedTimelineById = new Map(\n snapshot.scopedTimelineRows.map((event) => [event.eventId, serializeTimelineEvent(event)]),\n );\n const actualTimelineRows = projectedTimeline.rows.filter((event) => selectedMemoryIds.has(event.memoryId));\n const actualTimelineById = new Map(\n actualTimelineRows.map((event) => [event.eventId, serializeTimelineEvent(event)]),\n );\n const missingTimelineEventIds = [...expectedTimelineById.keys()]\n .filter((eventId) => !actualTimelineById.has(eventId))\n .sort();\n const extraTimelineEventIds = [...actualTimelineById.keys()]\n .filter((eventId) => !expectedTimelineById.has(eventId))\n .sort();\n\n const expectedEntityMentionsByKey = new Map(\n snapshot.scopedEntityMentionRows.map((row) => [\n `${row.memoryId}::${row.entityRef}::${row.mentionSource}`,\n serializeEntityMentionRow(row),\n ]),\n );\n const actualScopedEntityMentionRows = projectedEntityMentions.rows.filter((row) => selectedMemoryIds.has(row.memoryId));\n const actualEntityMentionsByKey = new Map(\n actualScopedEntityMentionRows.map((row) => [\n `${row.memoryId}::${row.entityRef}::${row.mentionSource}`,\n serializeEntityMentionRow(row),\n ]),\n );\n const missingEntityMentionKeys = [...expectedEntityMentionsByKey.keys()]\n .filter((key) => !actualEntityMentionsByKey.has(key))\n .sort();\n const extraEntityMentionKeys = [...actualEntityMentionsByKey.keys()]\n .filter((key) => !expectedEntityMentionsByKey.has(key))\n .sort();\n const mismatchedEntityMentionKeys = [...expectedEntityMentionsByKey.keys()]\n .filter((key) =>\n actualEntityMentionsByKey.has(key) && actualEntityMentionsByKey.get(key) !== expectedEntityMentionsByKey.get(key)\n )\n .sort();\n\n const expectedNativeKnowledgeById = new Map(\n snapshot.nativeKnowledgeRows.map((row) => [row.chunkId, serializeNativeKnowledgeRow(row)]),\n );\n const actualNativeKnowledgeById = new Map(\n projectedNativeKnowledge.rows.map((row) => [row.chunkId, serializeNativeKnowledgeRow(row)]),\n );\n const missingNativeKnowledgeChunkIds = [...expectedNativeKnowledgeById.keys()]\n .filter((chunkId) => !actualNativeKnowledgeById.has(chunkId))\n .sort();\n const extraNativeKnowledgeChunkIds = [...actualNativeKnowledgeById.keys()]\n .filter((chunkId) => !expectedNativeKnowledgeById.has(chunkId))\n .sort();\n const mismatchedNativeKnowledgeChunkIds = [...expectedNativeKnowledgeById.keys()]\n .filter((chunkId) =>\n actualNativeKnowledgeById.has(chunkId) && actualNativeKnowledgeById.get(chunkId) !== expectedNativeKnowledgeById.get(chunkId)\n )\n .sort();\n\n const expectedReviewQueueById = new Map(\n (snapshot.governance?.reviewQueueRows ?? []).map((row) => [\n `${row.runId}::${row.entryId}`,\n serializeGovernanceReviewQueueRow(row),\n ]),\n );\n const actualReviewQueueById = new Map(\n projectedGovernance.reviewQueueRows.map((row) => [\n `${row.runId}::${row.entryId}`,\n serializeGovernanceReviewQueueRow(row),\n ]),\n );\n const missingReviewQueueEntryIds = [...expectedReviewQueueById.keys()]\n .filter((entryId) => !actualReviewQueueById.has(entryId))\n .sort();\n const extraReviewQueueEntryIds = [...actualReviewQueueById.keys()]\n .filter((entryId) => !expectedReviewQueueById.has(entryId))\n .sort();\n const mismatchedReviewQueueEntryIds = [...expectedReviewQueueById.keys()]\n .filter((entryId) =>\n actualReviewQueueById.has(entryId) && actualReviewQueueById.get(entryId) !== expectedReviewQueueById.get(entryId)\n )\n .sort();\n\n return {\n outputPath,\n projectionExists,\n ok:\n projectionExists &&\n missingCurrentMemoryIds.length === 0 &&\n extraCurrentMemoryIds.length === 0 &&\n mismatchedCurrentMemoryIds.length === 0 &&\n missingTimelineEventIds.length === 0 &&\n extraTimelineEventIds.length === 0 &&\n missingEntityMentionKeys.length === 0 &&\n extraEntityMentionKeys.length === 0 &&\n mismatchedEntityMentionKeys.length === 0 &&\n missingNativeKnowledgeChunkIds.length === 0 &&\n extraNativeKnowledgeChunkIds.length === 0 &&\n mismatchedNativeKnowledgeChunkIds.length === 0 &&\n missingReviewQueueEntryIds.length === 0 &&\n extraReviewQueueEntryIds.length === 0 &&\n mismatchedReviewQueueEntryIds.length === 0,\n expectedCurrentRows: snapshot.scopedCurrentRows.length,\n actualCurrentRows: actualScopedCurrentRows.length,\n expectedTimelineRows: snapshot.scopedTimelineRows.length,\n actualTimelineRows: actualTimelineRows.length,\n expectedEntityMentionRows: snapshot.scopedEntityMentionRows.length,\n actualEntityMentionRows: actualScopedEntityMentionRows.length,\n expectedNativeKnowledgeRows: snapshot.nativeKnowledgeRows.length,\n actualNativeKnowledgeRows: projectedNativeKnowledge.rows.length,\n expectedReviewQueueRows: snapshot.governance?.reviewQueueRows.length ?? 0,\n actualReviewQueueRows: projectedGovernance.reviewQueueRows.length,\n missingCurrentMemoryIds,\n extraCurrentMemoryIds,\n mismatchedCurrentMemoryIds,\n missingTimelineEventIds,\n extraTimelineEventIds,\n missingEntityMentionKeys,\n extraEntityMentionKeys,\n mismatchedEntityMentionKeys,\n missingNativeKnowledgeChunkIds,\n extraNativeKnowledgeChunkIds,\n mismatchedNativeKnowledgeChunkIds,\n missingReviewQueueEntryIds,\n extraReviewQueueEntryIds,\n mismatchedReviewQueueEntryIds,\n usedLifecycleLedger: snapshot.usedLifecycleLedger,\n scope: snapshot.scope,\n };\n}\n\nexport async function repairMemoryProjection(\n options: RepairMemoryProjectionOptions,\n): Promise<RepairMemoryProjectionResult> {\n const dryRun = options.dryRun !== false;\n const verify = await verifyMemoryProjection(options);\n if (verify.ok) {\n return {\n dryRun,\n repaired: false,\n verify,\n };\n }\n if (dryRun) {\n return {\n dryRun: true,\n repaired: false,\n verify,\n };\n }\n\n const rebuild = await rebuildMemoryProjection({\n ...options,\n dryRun: false,\n });\n const verified = await verifyMemoryProjection(options);\n return {\n dryRun: false,\n repaired: verified.ok,\n verify: verified,\n rebuild,\n };\n}\n","import path from \"node:path\";\nimport { readdir, readFile } from \"node:fs/promises\";\nimport {\n backupAndWriteRebuiltObservations,\n toHourBucketIso,\n} from \"./observation-ledger-utils.js\";\n\ninterface TranscriptLikeEntry {\n timestamp?: string;\n role?: string;\n sessionKey?: string;\n}\n\ninterface ObservationAggregate {\n sessionKey: string;\n hour: string;\n turnCount: number;\n userTurns: number;\n assistantTurns: number;\n}\n\nexport interface RebuildObservationsOptions {\n memoryDir: string;\n dryRun?: boolean;\n now?: Date;\n}\n\nexport interface RebuildObservationsResult {\n dryRun: boolean;\n scannedFiles: number;\n parsedTurns: number;\n malformedLines: number;\n rebuiltRows: number;\n outputPath: string;\n backupPath?: string;\n}\n\nfunction toSortableKey(sessionKey: string, hour: string): string {\n return `${sessionKey}\\u0000${hour}`;\n}\n\nasync function listTranscriptFiles(root: string): Promise<string[]> {\n const out: string[] = [];\n let entries: Array<{\n name: string;\n isDirectory(): boolean;\n isFile(): boolean;\n isSymbolicLink(): boolean;\n }>;\n try {\n entries = (await readdir(root, { withFileTypes: true })) as Array<{\n name: string;\n isDirectory(): boolean;\n isFile(): boolean;\n isSymbolicLink(): boolean;\n }>;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code && code === \"ENOENT\") return out;\n throw err;\n }\n\n for (const entry of entries) {\n if (entry.name === \".\" || entry.name === \"..\") continue;\n if (entry.isSymbolicLink()) continue;\n const full = path.join(root, entry.name);\n if (entry.isDirectory()) {\n out.push(...(await listTranscriptFiles(full)));\n continue;\n }\n if (entry.isFile() && entry.name.endsWith(\".jsonl\")) {\n out.push(full);\n }\n }\n\n out.sort((a, b) => a.localeCompare(b));\n return out;\n}\n\nfunction buildLedgerRows(linesByFile: string[]): {\n aggregates: ObservationAggregate[];\n parsedTurns: number;\n malformedLines: number;\n} {\n const byKey = new Map<string, ObservationAggregate>();\n let parsedTurns = 0;\n let malformedLines = 0;\n\n for (const rawFile of linesByFile) {\n for (const line of rawFile.split(\"\\n\")) {\n if (!line.trim()) continue;\n let parsed: TranscriptLikeEntry;\n try {\n const candidate = JSON.parse(line);\n if (candidate == null || typeof candidate !== \"object\" || Array.isArray(candidate)) {\n malformedLines += 1;\n continue;\n }\n parsed = candidate as TranscriptLikeEntry;\n } catch {\n malformedLines += 1;\n continue;\n }\n\n if (typeof parsed.sessionKey !== \"string\" || parsed.sessionKey.length === 0) continue;\n if (parsed.role !== \"user\" && parsed.role !== \"assistant\") continue;\n if (typeof parsed.timestamp !== \"string\") continue;\n const hour = toHourBucketIso(parsed.timestamp);\n if (!hour) continue;\n\n const key = toSortableKey(parsed.sessionKey, hour);\n const existing = byKey.get(key) ?? {\n sessionKey: parsed.sessionKey,\n hour,\n turnCount: 0,\n userTurns: 0,\n assistantTurns: 0,\n };\n existing.turnCount += 1;\n if (parsed.role === \"user\") existing.userTurns += 1;\n if (parsed.role === \"assistant\") existing.assistantTurns += 1;\n byKey.set(key, existing);\n parsedTurns += 1;\n }\n }\n\n const aggregates = Array.from(byKey.values()).sort((a, b) => {\n if (a.sessionKey !== b.sessionKey) return a.sessionKey.localeCompare(b.sessionKey);\n return a.hour.localeCompare(b.hour);\n });\n\n return { aggregates, parsedTurns, malformedLines };\n}\n\nexport async function rebuildObservations(\n options: RebuildObservationsOptions,\n): Promise<RebuildObservationsResult> {\n const dryRun = options.dryRun !== false;\n const now = options.now ?? new Date();\n const transcriptsRoot = path.join(options.memoryDir, \"transcripts\");\n const outputPath = path.join(\n options.memoryDir,\n \"state\",\n \"observation-ledger\",\n \"rebuilt-observations.jsonl\",\n );\n\n const transcriptFiles = await listTranscriptFiles(transcriptsRoot);\n const contents: string[] = [];\n for (const file of transcriptFiles) {\n try {\n contents.push(await readFile(file, \"utf-8\"));\n } catch {\n // Fail-open: skip unreadable shards and continue rebuilding from healthy files.\n }\n }\n const { aggregates, parsedTurns, malformedLines } = buildLedgerRows(contents);\n\n let backupPath: string | undefined;\n if (!dryRun) {\n backupPath = await backupAndWriteRebuiltObservations({\n memoryDir: options.memoryDir,\n outputPath,\n rows: aggregates,\n now,\n });\n }\n\n return {\n dryRun,\n scannedFiles: transcriptFiles.length,\n parsedTurns,\n malformedLines,\n rebuiltRows: aggregates.length,\n outputPath,\n backupPath,\n };\n}\n","import path from \"node:path\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\n\ninterface LedgerWriteOptions<T extends object> {\n memoryDir: string;\n outputPath: string;\n rows: T[];\n now: Date;\n}\n\nexport function toHourBucketIso(timestamp: string): string | null {\n const normalized = /(?:Z|[+-]\\d{2}:\\d{2})$/u.test(timestamp) ? timestamp : `${timestamp}Z`;\n const ms = Date.parse(normalized);\n if (!Number.isFinite(ms)) return null;\n const d = new Date(ms);\n d.setUTCMinutes(0, 0, 0);\n return d.toISOString();\n}\n\nexport async function backupAndWriteRebuiltObservations<T extends object>(\n options: LedgerWriteOptions<T>,\n): Promise<string | undefined> {\n const stamp = options.now.toISOString().replace(/[-:]/g, \"\").replace(/\\.\\d{3}Z$/, \"Z\");\n const archiveRoot = path.join(options.memoryDir, \"archive\", \"observations\", stamp);\n let backupPath: string | undefined = path.join(\n archiveRoot,\n \"state\",\n \"observation-ledger\",\n \"rebuilt-observations.jsonl\",\n );\n try {\n const existing = await readFile(options.outputPath, \"utf-8\");\n await mkdir(path.dirname(backupPath), { recursive: true });\n await writeFile(backupPath, existing, \"utf-8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code && code === \"ENOENT\") {\n backupPath = undefined;\n } else {\n throw err;\n }\n }\n\n const rebuiltAt = options.now.toISOString();\n const lines = options.rows.map((row) =>\n JSON.stringify({\n ...row,\n rebuiltAt,\n }),\n );\n await mkdir(path.dirname(options.outputPath), { recursive: true });\n await writeFile(options.outputPath, lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\", \"utf-8\");\n return backupPath;\n}\n","import path from \"node:path\";\nimport { readdir, readFile } from \"node:fs/promises\";\nimport {\n backupAndWriteRebuiltObservations,\n toHourBucketIso,\n} from \"./observation-ledger-utils.js\";\n\ninterface CanonicalObservationRow {\n sessionKey: string;\n hour: string;\n turnCount: number;\n userTurns: number;\n assistantTurns: number;\n}\n\ntype JsonRecord = Record<string, unknown>;\n\nexport interface MigrateObservationsOptions {\n memoryDir: string;\n dryRun?: boolean;\n now?: Date;\n}\n\nexport interface MigrateObservationsResult {\n dryRun: boolean;\n scannedFiles: number;\n parsedRows: number;\n malformedLines: number;\n migratedRows: number;\n outputPath: string;\n backupPath?: string;\n sourceRelativePaths: string[];\n}\n\nfunction toNonNegativeInt(value: unknown): number | null {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return null;\n const normalized = Math.floor(value);\n if (normalized < 0) return null;\n return normalized;\n}\n\nfunction toHourIso(value: unknown): string | null {\n if (typeof value !== \"string\" || value.length === 0) return null;\n return toHourBucketIso(value);\n}\n\nfunction toSessionKey(row: JsonRecord): string | null {\n const candidates = [row.sessionKey, row.session, row.session_id, row.sessionId];\n for (const candidate of candidates) {\n if (typeof candidate === \"string\" && candidate.length > 0) return candidate;\n }\n return null;\n}\n\nfunction toLegacyHour(row: JsonRecord): string | null {\n const candidates = [row.hour, row.hourStart, row.timestamp, row.time];\n for (const candidate of candidates) {\n const hour = toHourIso(candidate);\n if (hour) return hour;\n }\n return null;\n}\n\nfunction toCounts(row: JsonRecord): { turnCount: number; userTurns: number; assistantTurns: number } | null {\n const role = row.role === \"user\" || row.role === \"assistant\" ? row.role : null;\n const explicitTurnCount =\n toNonNegativeInt(row.turnCount) ??\n toNonNegativeInt(row.turns) ??\n toNonNegativeInt(row.totalTurns);\n const explicitUserTurns =\n toNonNegativeInt(row.userTurns) ??\n toNonNegativeInt(row.user) ??\n toNonNegativeInt(row.userCount);\n const explicitAssistantTurns =\n toNonNegativeInt(row.assistantTurns) ??\n toNonNegativeInt(row.assistant) ??\n toNonNegativeInt(row.assistantCount);\n\n let turnCount = explicitTurnCount ?? 0;\n let userTurns = explicitUserTurns ?? 0;\n let assistantTurns = explicitAssistantTurns ?? 0;\n\n if (turnCount === 0 && userTurns === 0 && assistantTurns === 0 && role) {\n turnCount = 1;\n if (role === \"user\") userTurns = 1;\n if (role === \"assistant\") assistantTurns = 1;\n }\n\n if (turnCount === 0 && (userTurns > 0 || assistantTurns > 0)) {\n turnCount = userTurns + assistantTurns;\n }\n if (turnCount < userTurns + assistantTurns) {\n turnCount = userTurns + assistantTurns;\n }\n if (turnCount === 0) return null;\n return { turnCount, userTurns, assistantTurns };\n}\n\nasync function listLegacyObservationFiles(root: string): Promise<string[]> {\n let entries: Array<{ name: string; isFile(): boolean }>;\n try {\n entries = (await readdir(root, { withFileTypes: true })) as Array<{\n name: string;\n isFile(): boolean;\n }>;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code && code === \"ENOENT\") return [];\n throw err;\n }\n\n const files = entries\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".jsonl\"))\n .map((entry) => entry.name)\n .filter((name) => name !== \"rebuilt-observations.jsonl\")\n .sort((a, b) => a.localeCompare(b));\n return files;\n}\n\nexport async function migrateObservations(\n options: MigrateObservationsOptions,\n): Promise<MigrateObservationsResult> {\n const dryRun = options.dryRun !== false;\n const now = options.now ?? new Date();\n const ledgerRoot = path.join(options.memoryDir, \"state\", \"observation-ledger\");\n const outputPath = path.join(ledgerRoot, \"rebuilt-observations.jsonl\");\n const legacyFiles = await listLegacyObservationFiles(ledgerRoot);\n const sourceRelativePaths = legacyFiles.map((name) => path.join(\"state\", \"observation-ledger\", name));\n\n const byKey = new Map<string, CanonicalObservationRow>();\n let parsedRows = 0;\n let malformedLines = 0;\n\n for (const file of legacyFiles) {\n const full = path.join(ledgerRoot, file);\n const raw = await readFile(full, \"utf-8\");\n for (const line of raw.split(\"\\n\")) {\n if (!line.trim()) continue;\n let parsed: JsonRecord;\n try {\n const candidate = JSON.parse(line);\n if (candidate == null || typeof candidate !== \"object\" || Array.isArray(candidate)) {\n malformedLines += 1;\n continue;\n }\n parsed = candidate as JsonRecord;\n } catch {\n malformedLines += 1;\n continue;\n }\n\n const sessionKey = toSessionKey(parsed);\n const hour = toLegacyHour(parsed);\n const counts = toCounts(parsed);\n if (!sessionKey || !hour || !counts) {\n malformedLines += 1;\n continue;\n }\n\n const key = `${sessionKey}\\u0000${hour}`;\n const existing = byKey.get(key) ?? {\n sessionKey,\n hour,\n turnCount: 0,\n userTurns: 0,\n assistantTurns: 0,\n };\n existing.turnCount += counts.turnCount;\n existing.userTurns += counts.userTurns;\n existing.assistantTurns += counts.assistantTurns;\n if (existing.turnCount < existing.userTurns + existing.assistantTurns) {\n existing.turnCount = existing.userTurns + existing.assistantTurns;\n }\n byKey.set(key, existing);\n parsedRows += 1;\n }\n }\n\n const aggregates = Array.from(byKey.values()).sort((a, b) => {\n if (a.sessionKey !== b.sessionKey) return a.sessionKey.localeCompare(b.sessionKey);\n return a.hour.localeCompare(b.hour);\n });\n\n if (!dryRun && legacyFiles.length === 0) {\n return {\n dryRun,\n scannedFiles: legacyFiles.length,\n parsedRows,\n malformedLines,\n migratedRows: aggregates.length,\n outputPath,\n sourceRelativePaths,\n };\n }\n\n let backupPath: string | undefined;\n if (!dryRun) {\n backupPath = await backupAndWriteRebuiltObservations({\n memoryDir: options.memoryDir,\n outputPath,\n rows: aggregates,\n now,\n });\n }\n\n return {\n dryRun,\n scannedFiles: legacyFiles.length,\n parsedRows,\n malformedLines,\n migratedRows: aggregates.length,\n outputPath,\n backupPath,\n sourceRelativePaths,\n };\n}\n","import { stat } from \"node:fs/promises\";\nimport { launchProcess } from \"../runtime/child-process.js\";\n\nexport interface TailscaleCommandResult {\n code: number;\n stdout: string;\n stderr: string;\n}\n\nexport type TailscaleCommandRunner = (\n command: string,\n args: string[],\n options?: { timeoutMs?: number },\n) => Promise<TailscaleCommandResult>;\n\nexport interface TailscaleStatus {\n available: boolean;\n running: boolean;\n backendState?: string;\n version?: string;\n selfHostname?: string;\n selfIp?: string;\n}\n\nexport interface TailscaleSyncOptions {\n sourceDir: string;\n destination: string;\n delete?: boolean;\n dryRun?: boolean;\n extraArgs?: string[];\n}\n\nexport interface TailscaleHelperOptions {\n tailscaleBinary?: string;\n rsyncBinary?: string;\n timeoutMs?: number;\n runner?: TailscaleCommandRunner;\n}\n\ninterface TailscaleStatusJson {\n BackendState?: string;\n Version?: string;\n Self?: {\n HostName?: string;\n TailscaleIPs?: string[];\n };\n}\n\nexport class TailscaleHelper {\n private readonly tailscaleBinary: string;\n private readonly rsyncBinary: string;\n private readonly timeoutMs: number;\n private readonly runner: TailscaleCommandRunner;\n\n constructor(options: TailscaleHelperOptions = {}) {\n this.tailscaleBinary = options.tailscaleBinary ?? \"tailscale\";\n this.rsyncBinary = options.rsyncBinary ?? \"rsync\";\n this.timeoutMs = options.timeoutMs ?? 10_000;\n this.runner = options.runner ?? defaultCommandRunner;\n }\n\n async isAvailable(): Promise<boolean> {\n const result = await this.runner(this.tailscaleBinary, [\"version\"], { timeoutMs: this.timeoutMs });\n return result.code === 0;\n }\n\n async status(): Promise<TailscaleStatus> {\n const available = await this.isAvailable();\n if (!available) {\n return { available: false, running: false };\n }\n\n const result = await this.runner(this.tailscaleBinary, [\"status\", \"--json\"], { timeoutMs: this.timeoutMs });\n if (result.code !== 0) {\n return { available: true, running: false };\n }\n\n let parsed: TailscaleStatusJson;\n try {\n parsed = JSON.parse(result.stdout) as TailscaleStatusJson;\n } catch {\n throw new Error(\"tailscale status returned invalid JSON\");\n }\n\n const backendState = parsed.BackendState ?? \"\";\n return {\n available: true,\n running: backendState === \"Running\",\n backendState,\n version: parsed.Version,\n selfHostname: parsed.Self?.HostName,\n selfIp: parsed.Self?.TailscaleIPs?.[0],\n };\n }\n\n async syncDirectory(options: TailscaleSyncOptions): Promise<void> {\n await assertReadableDirectory(options.sourceDir);\n\n const tailscaleStatus = await this.status();\n if (!tailscaleStatus.available) {\n throw new Error(\"tailscale is not installed or not available in PATH\");\n }\n if (!tailscaleStatus.running) {\n throw new Error(\"tailscale daemon is not running\");\n }\n\n const args: string[] = [\"-az\"];\n if (options.delete) args.push(\"--delete\");\n if (options.dryRun) args.push(\"--dry-run\");\n if (options.extraArgs?.length) args.push(...options.extraArgs);\n\n const sourceWithTrailingSlash = options.sourceDir.endsWith(\"/\") ? options.sourceDir : `${options.sourceDir}/`;\n args.push(sourceWithTrailingSlash, options.destination);\n\n const result = await this.runner(this.rsyncBinary, args);\n if (result.code !== 0) {\n const stderr = result.stderr.trim();\n throw new Error(stderr ? `rsync failed: ${stderr}` : \"rsync failed\");\n }\n }\n}\n\nasync function assertReadableDirectory(dir: string): Promise<void> {\n const info = await stat(dir);\n if (!info.isDirectory()) {\n throw new Error(`sourceDir must be a directory: ${dir}`);\n }\n}\n\nconst defaultCommandRunner: TailscaleCommandRunner = (command, args, options) => {\n return new Promise((resolve) => {\n const child = launchProcess(command, args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n if (!child.stdout || !child.stderr) {\n resolve({ code: 1, stdout: \"\", stderr: \"command pipes unavailable\" });\n return;\n }\n\n let stdout = \"\";\n let stderr = \"\";\n let settled = false;\n\n const timeoutMs = options?.timeoutMs;\n const timeout = typeof timeoutMs === \"number\" && timeoutMs > 0\n ? setTimeout(() => {\n if (settled) return;\n settled = true;\n child.kill(\"SIGKILL\");\n resolve({\n code: 124,\n stdout,\n stderr: stderr || \"command timed out\",\n });\n }, timeoutMs)\n : null;\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n stdout += chunk.toString(\"utf-8\");\n });\n child.stderr.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString(\"utf-8\");\n });\n\n child.on(\"error\", () => {\n if (settled) return;\n settled = true;\n if (timeout) clearTimeout(timeout);\n resolve({ code: 1, stdout, stderr });\n });\n\n child.on(\"close\", (code) => {\n if (settled) return;\n settled = true;\n if (timeout) clearTimeout(timeout);\n resolve({ code: code ?? 1, stdout, stderr });\n });\n });\n};\n","import { createReadStream } from \"node:fs\";\nimport { mkdir, readdir, realpath, stat } from \"node:fs/promises\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { timingSafeEqual } from \"node:crypto\";\nimport path from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { URL } from \"node:url\";\n\nexport function hostToUrlAuthority(host: string): string {\n if (host.includes(\":\") && !host.startsWith(\"[\") && !host.endsWith(\"]\")) {\n return `[${host}]`;\n }\n return host;\n}\n\nexport interface WebDavAuth {\n username: string;\n password: string;\n}\n\nexport interface WebDavServerOptions {\n enabled?: boolean;\n host?: string;\n port: number;\n allowlistDirs: string[];\n auth?: WebDavAuth;\n}\n\nexport interface WebDavServerStatus {\n running: boolean;\n host: string;\n port: number;\n rootCount: number;\n}\n\ninterface AllowedRoot {\n absolute: string;\n name: string;\n}\n\nexport class WebDavServer {\n private readonly options: Required<Omit<WebDavServerOptions, \"auth\">> & Pick<WebDavServerOptions, \"auth\">;\n private readonly allowedRoots: AllowedRoot[];\n private server: Server | null = null;\n private boundPort: number;\n\n private constructor(\n options: Required<Omit<WebDavServerOptions, \"auth\">> & Pick<WebDavServerOptions, \"auth\">,\n allowedRoots: AllowedRoot[],\n ) {\n this.options = options;\n this.allowedRoots = allowedRoots;\n this.boundPort = options.port;\n }\n\n static async create(input: WebDavServerOptions): Promise<WebDavServer> {\n const options: Required<Omit<WebDavServerOptions, \"auth\">> & Pick<WebDavServerOptions, \"auth\"> = {\n enabled: input.enabled ?? false,\n host: input.host ?? \"127.0.0.1\",\n port: input.port,\n allowlistDirs: input.allowlistDirs,\n auth: input.auth,\n };\n\n if (!Array.isArray(options.allowlistDirs) || options.allowlistDirs.length === 0) {\n throw new Error(\"webdav allowlistDirs must include at least one directory\");\n }\n if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535) {\n throw new Error(`invalid webdav port: ${options.port}`);\n }\n\n const allowedRoots: AllowedRoot[] = [];\n const aliasSet = new Set<string>();\n for (const dir of options.allowlistDirs) {\n const resolved = path.resolve(dir);\n await mkdir(resolved, { recursive: true });\n const canonical = await realpath(resolved);\n const alias = path.basename(canonical) || \"root\";\n if (aliasSet.has(alias)) {\n throw new Error(`duplicate webdav allowlist alias: ${alias}`);\n }\n aliasSet.add(alias);\n allowedRoots.push({ absolute: canonical, name: alias });\n }\n\n return new WebDavServer(options, allowedRoots);\n }\n\n async start(): Promise<WebDavServerStatus> {\n if (!this.options.enabled) {\n throw new Error(\"webdav server is disabled; set enabled=true to start\");\n }\n if (this.server) {\n return this.status();\n }\n\n const server = createServer((req, res) => {\n this.handle(req, res).catch((err) => {\n if (res.headersSent) {\n res.destroy(err as Error);\n return;\n }\n res.writeHead(500, { \"Content-Type\": \"text/plain; charset=utf-8\" });\n res.end(\"webdav error\");\n });\n });\n this.server = server;\n\n try {\n await new Promise<void>((resolve, reject) => {\n const onError = (err: Error) => {\n server.removeListener(\"listening\", onListening);\n reject(err);\n };\n const onListening = () => {\n server.removeListener(\"error\", onError);\n resolve();\n };\n server.once(\"error\", onError);\n server.once(\"listening\", onListening);\n server.listen(this.options.port, this.options.host);\n });\n } catch (err) {\n this.server = null;\n server.close();\n throw err;\n }\n\n const address = server.address();\n if (address && typeof address !== \"string\") {\n this.boundPort = address.port;\n }\n\n return this.status();\n }\n\n async stop(): Promise<void> {\n if (!this.server) return;\n const server = this.server;\n this.server = null;\n this.boundPort = this.options.port;\n await new Promise<void>((resolve, reject) => {\n server.close((err) => (err ? reject(err) : resolve()));\n });\n }\n\n status(): WebDavServerStatus {\n return {\n running: this.server !== null,\n host: this.options.host,\n port: this.boundPort,\n rootCount: this.allowedRoots.length,\n };\n }\n\n private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {\n if (!this.isAuthorized(req)) {\n res.writeHead(401, {\n \"WWW-Authenticate\": 'Basic realm=\"Engram WebDAV\"',\n \"Content-Type\": \"text/plain; charset=utf-8\",\n });\n res.end(\"authentication required\");\n return;\n }\n\n const method = (req.method ?? \"GET\").toUpperCase();\n if (method === \"OPTIONS\") {\n res.writeHead(204, {\n Allow: \"OPTIONS, PROPFIND, GET, HEAD\",\n DAV: \"1\",\n });\n res.end();\n return;\n }\n\n const parsed = new URL(req.url ?? \"/\", `http://${hostToUrlAuthority(this.options.host)}`);\n const resolved = await this.resolvePath(parsed.pathname);\n if (!resolved.ok) {\n res.writeHead(resolved.code, { \"Content-Type\": \"text/plain; charset=utf-8\" });\n res.end(resolved.message);\n return;\n }\n\n if (method === \"PROPFIND\") {\n await this.handlePropfind(resolved.absolutePath, resolved.displayPath, res);\n return;\n }\n\n if (method === \"GET\" || method === \"HEAD\") {\n await this.handleRead(method, resolved.absolutePath, res);\n return;\n }\n\n res.writeHead(405, {\n Allow: \"OPTIONS, PROPFIND, GET, HEAD\",\n \"Content-Type\": \"text/plain; charset=utf-8\",\n });\n res.end(\"method not allowed\");\n }\n\n private isAuthorized(req: IncomingMessage): boolean {\n if (!this.options.auth) return true;\n const raw = req.headers.authorization;\n if (!raw) return false;\n const separator = raw.indexOf(\" \");\n if (separator <= 0) return false;\n const scheme = raw.slice(0, separator).toLowerCase();\n if (scheme !== \"basic\") return false;\n const encodedPart = raw.slice(separator + 1).trim();\n if (!encodedPart) return false;\n\n try {\n const decoded = Buffer.from(encodedPart, \"base64\").toString(\"utf-8\");\n const credentialSeparator = decoded.indexOf(\":\");\n if (credentialSeparator < 0) return false;\n const username = decoded.slice(0, credentialSeparator);\n const password = decoded.slice(credentialSeparator + 1);\n const usernameOk = this.timingSafeStringEqual(username, this.options.auth.username);\n const passwordOk = this.timingSafeStringEqual(password, this.options.auth.password);\n return Boolean((usernameOk ? 1 : 0) & (passwordOk ? 1 : 0));\n } catch {\n return false;\n }\n }\n\n private timingSafeStringEqual(a: string, b: string): boolean {\n const left = this.encodeAuthField(a);\n const right = this.encodeAuthField(b);\n if (!left || !right) return false;\n return timingSafeEqual(left, right);\n }\n\n private encodeAuthField(value: string): Buffer | null {\n const maxBytes = 512;\n const encoded = Buffer.from(value, \"utf-8\");\n if (encoded.length > maxBytes) return null;\n const out = Buffer.alloc(2 + maxBytes);\n out.writeUInt16BE(encoded.length, 0);\n encoded.copy(out, 2);\n return out;\n }\n\n private async resolvePath(requestPathname: string): Promise<\n | { ok: true; absolutePath: string; displayPath: string }\n | { ok: false; code: number; message: string }\n > {\n let decodedPath: string;\n try {\n decodedPath = decodeURIComponent(requestPathname || \"/\");\n } catch {\n return { ok: false, code: 400, message: \"invalid path encoding\" };\n }\n if (decodedPath.includes(\"\\0\")) {\n return { ok: false, code: 400, message: \"invalid path\" };\n }\n\n const normalized = path.posix.normalize(decodedPath);\n const segments = normalized.split(\"/\").filter((segment) => segment.length > 0);\n\n if (segments.length === 0) {\n return { ok: false, code: 403, message: \"root listing is not allowed\" };\n }\n\n const rootName = segments[0];\n const root = this.allowedRoots.find((entry) => entry.name === rootName);\n if (!root) {\n return { ok: false, code: 403, message: \"path is outside allowlist\" };\n }\n\n const relative = segments.slice(1);\n if (relative.some((segment) => segment === \"..\" || segment.includes(\"\\\\\"))) {\n return { ok: false, code: 403, message: \"path traversal is not allowed\" };\n }\n\n const candidate = path.resolve(root.absolute, ...relative);\n if (!this.isPathInside(root.absolute, candidate)) {\n return { ok: false, code: 403, message: \"path escaped allowlist\" };\n }\n\n try {\n const canonicalCandidate = await realpath(candidate);\n if (!this.isPathInside(root.absolute, canonicalCandidate)) {\n return { ok: false, code: 403, message: \"path escaped allowlist via symlink\" };\n }\n return { ok: true, absolutePath: canonicalCandidate, displayPath: `/${segments.join(\"/\")}` };\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") {\n return { ok: true, absolutePath: candidate, displayPath: `/${segments.join(\"/\")}` };\n }\n if (code === \"ENOTDIR\" || code === \"ELOOP\") {\n return { ok: false, code: 400, message: \"invalid path\" };\n }\n throw err;\n }\n }\n\n private async handleRead(method: \"GET\" | \"HEAD\", absolutePath: string, res: ServerResponse): Promise<void> {\n let info;\n try {\n info = await stat(absolutePath);\n } catch {\n res.writeHead(404, { \"Content-Type\": \"text/plain; charset=utf-8\" });\n res.end(\"not found\");\n return;\n }\n\n if (!info.isFile()) {\n res.writeHead(403, { \"Content-Type\": \"text/plain; charset=utf-8\" });\n res.end(\"path is not a file\");\n return;\n }\n\n res.writeHead(200, {\n \"Content-Length\": String(info.size),\n \"Content-Type\": \"application/octet-stream\",\n });\n\n if (method === \"HEAD\") {\n res.end();\n return;\n }\n\n await pipeline(createReadStream(absolutePath), res);\n }\n\n private async handlePropfind(absolutePath: string, displayPath: string, res: ServerResponse): Promise<void> {\n let info;\n try {\n info = await stat(absolutePath);\n } catch {\n res.writeHead(404, { \"Content-Type\": \"text/plain; charset=utf-8\" });\n res.end(\"not found\");\n return;\n }\n\n const entries: string[] = [];\n if (info.isDirectory()) {\n const children = await readdir(absolutePath, { withFileTypes: true });\n for (const child of children) {\n const childHref = toEncodedHref(`${displayPath.replace(/\\/$/, \"\")}/${child.name}`);\n entries.push(`\n <d:response>\n <d:href>${xmlEscape(childHref)}</d:href>\n <d:propstat><d:prop><d:resourcetype>${child.isDirectory() ? \"<d:collection/>\" : \"\"}</d:resourcetype></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>\n </d:response>`);\n }\n }\n\n const xml = `<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<d:multistatus xmlns:d=\"DAV:\">\n <d:response>\n <d:href>${xmlEscape(toEncodedHref(displayPath))}</d:href>\n <d:propstat><d:prop><d:resourcetype>${info.isDirectory() ? \"<d:collection/>\" : \"\"}</d:resourcetype></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>\n </d:response>${entries.join(\"\")}\n</d:multistatus>`;\n\n res.writeHead(207, { \"Content-Type\": \"application/xml; charset=utf-8\" });\n res.end(xml);\n }\n\n private isPathInside(root: string, target: string): boolean {\n if (target === root) return true;\n if (root === path.parse(root).root) {\n return target.startsWith(root);\n }\n return target.startsWith(`${root}${path.sep}`);\n }\n}\n\nfunction xmlEscape(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&apos;\");\n}\n\nfunction toEncodedHref(pathname: string): string {\n return pathname\n .split(\"/\")\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n}\n","import { access, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { CompatCheckOptions, CompatCheckResult, CompatReport, CompatRunner } from \"./types.js\";\nimport { compareVersions } from \"../version-utils.js\";\nimport { launchProcess } from \"../runtime/child-process.js\";\n\nconst REQUIRED_HOOKS_LEGACY = [\"before_agent_start\", \"agent_end\"];\nconst REQUIRED_HOOKS_NEW = [\"before_prompt_build\", \"agent_end\"];\n\nfunction isSafeCommandToken(command: string): boolean {\n return /^[a-zA-Z0-9._-]+$/.test(command);\n}\n\nconst defaultRunner: CompatRunner = {\n async commandExists(command: string): Promise<boolean> {\n if (!isSafeCommandToken(command)) return false;\n const binary = process.platform === \"win32\" ? \"where\" : \"which\";\n const args = [command];\n return new Promise<boolean>((resolve) => {\n const child = launchProcess(binary, args, { stdio: \"ignore\" });\n child.on(\"error\", () => resolve(false));\n child.on(\"close\", (code) => resolve(code === 0));\n });\n },\n};\n\nfunction summarize(checks: CompatCheckResult[]): { ok: number; warn: number; error: number } {\n const out = { ok: 0, warn: 0, error: 0 };\n for (const check of checks) {\n out[check.level] += 1;\n }\n return out;\n}\n\nfunction stripCommentsAndStrings(source: string): string {\n const out: string[] = [];\n let i = 0;\n while (i < source.length) {\n const ch = source[i];\n const next = source[i + 1];\n\n if (ch === \"/\" && next === \"/\") {\n out.push(\" \", \" \");\n i += 2;\n while (i < source.length && source[i] !== \"\\n\") {\n out.push(\" \");\n i += 1;\n }\n continue;\n }\n\n if (ch === \"/\" && next === \"*\") {\n out.push(\" \", \" \");\n i += 2;\n while (i < source.length) {\n const c = source[i];\n const n = source[i + 1];\n out.push(c === \"\\n\" ? \"\\n\" : \" \");\n i += 1;\n if (c === \"*\" && n === \"/\") {\n out.push(\" \");\n i += 1;\n break;\n }\n }\n continue;\n }\n\n if (ch === '\"' || ch === \"'\" || ch === \"`\") {\n const quote = ch;\n out.push(\" \");\n i += 1;\n while (i < source.length) {\n const c = source[i];\n if (c === \"\\\\\") {\n out.push(\" \");\n i += 1;\n if (i < source.length) {\n out.push(source[i] === \"\\n\" ? \"\\n\" : \" \");\n i += 1;\n }\n continue;\n }\n out.push(c === \"\\n\" ? \"\\n\" : \" \");\n i += 1;\n if (c === quote) break;\n }\n continue;\n }\n\n out.push(ch);\n i += 1;\n }\n return out.join(\"\");\n}\n\nfunction parseHookRegistrations(source: string): Set<string> {\n const hooks = new Set<string>();\n let i = 0;\n\n while (i < source.length) {\n const ch = source[i];\n const next = source[i + 1];\n\n if (ch === \"/\" && next === \"/\") {\n i += 2;\n while (i < source.length && source[i] !== \"\\n\") i += 1;\n continue;\n }\n\n if (ch === \"/\" && next === \"*\") {\n i += 2;\n while (i + 1 < source.length) {\n if (source[i] === \"*\" && source[i + 1] === \"/\") {\n i += 2;\n break;\n }\n i += 1;\n }\n continue;\n }\n\n if (ch === '\"' || ch === \"'\" || ch === \"`\") {\n const quote = ch;\n i += 1;\n while (i < source.length) {\n if (source[i] === \"\\\\\") {\n i += 2;\n continue;\n }\n if (source[i] === quote) {\n i += 1;\n break;\n }\n i += 1;\n }\n continue;\n }\n\n if (source.startsWith(\"api.on\", i) && (i === 0 || !/[a-zA-Z0-9_$\\.]/.test(source[i - 1]))) {\n let j = i + \"api.on\".length;\n while (j < source.length && /\\s/.test(source[j])) j += 1;\n if (source[j] !== \"(\") {\n i += 1;\n continue;\n }\n\n j += 1;\n while (j < source.length && /\\s/.test(source[j])) j += 1;\n const quote = source[j];\n if (quote !== '\"' && quote !== \"'\") {\n i += 1;\n continue;\n }\n\n j += 1;\n const start = j;\n while (j < source.length && source[j] !== quote) {\n if (source[j] === \"\\\\\") {\n j += 2;\n } else {\n j += 1;\n }\n }\n if (j < source.length) {\n const hook = source.slice(start, j);\n if (/^[a-z_]+$/.test(hook)) hooks.add(hook);\n i = j + 1;\n continue;\n }\n }\n\n i += 1;\n }\n\n return hooks;\n}\n\nfunction hasServiceStartRegistration(source: string): boolean {\n return /api\\.registerService\\s*\\(\\s*\\{[\\s\\S]*?\\bstart\\s*(?::|\\()/m.test(source);\n}\n\nfunction hasCliRegistration(source: string): boolean {\n return /registerCli\\s*\\([^)]*\\borchestrator\\b[^)]*\\)/m.test(source);\n}\n\nfunction parseNodeMinVersion(raw: string | undefined): [number, number, number] | null {\n if (!raw) return null;\n const match = raw.match(/(\\d+)\\.(\\d+)\\.(\\d+)/);\n if (!match) return null;\n return [Number(match[1]), Number(match[2]), Number(match[3])];\n}\n\nfunction parseCurrentNodeVersion(raw: string): [number, number, number] | null {\n const normalized = raw.startsWith(\"v\") ? raw.slice(1) : raw;\n const match = normalized.match(/^(\\d+)\\.(\\d+)\\.(\\d+)/);\n if (!match) return null;\n return [Number(match[1]), Number(match[2]), Number(match[3])];\n}\n\nexport async function runCompatChecks(options: CompatCheckOptions): Promise<CompatReport> {\n const checks: CompatCheckResult[] = [];\n const runner = options.runner ?? defaultRunner;\n const pluginJsonPath = path.join(options.repoRoot, \"openclaw.plugin.json\");\n const packageJsonPath = path.join(options.repoRoot, \"package.json\");\n const indexPath = path.join(options.repoRoot, \"src\", \"index.ts\");\n\n let pluginRaw = \"\";\n let pluginManifestPresent = false;\n try {\n pluginRaw = await readFile(pluginJsonPath, \"utf-8\");\n pluginManifestPresent = true;\n checks.push({\n id: \"plugin-manifest-present\",\n title: \"Plugin manifest present\",\n level: \"ok\",\n message: \"Found openclaw.plugin.json\",\n });\n } catch {\n checks.push({\n id: \"plugin-manifest-present\",\n title: \"Plugin manifest present\",\n level: \"error\",\n message: \"openclaw.plugin.json is missing\",\n remediation: \"Restore openclaw.plugin.json at repo root with plugin metadata.\",\n });\n }\n\n if (pluginManifestPresent) {\n try {\n const plugin = JSON.parse(pluginRaw) as { id?: string; kind?: string };\n if (plugin.id === \"openclaw-engram\" && plugin.kind === \"memory\") {\n checks.push({\n id: \"plugin-manifest-shape\",\n title: \"Plugin manifest ID and kind\",\n level: \"ok\",\n message: \"Plugin manifest id/kind match expected values.\",\n });\n } else {\n checks.push({\n id: \"plugin-manifest-shape\",\n title: \"Plugin manifest ID and kind\",\n level: \"error\",\n message: `Unexpected manifest values (id=${String(plugin.id)}, kind=${String(plugin.kind)})`,\n remediation: \"Set manifest id=openclaw-engram and kind=memory.\",\n });\n }\n } catch {\n checks.push({\n id: \"plugin-manifest-shape\",\n title: \"Plugin manifest ID and kind\",\n level: \"error\",\n message: \"openclaw.plugin.json is not valid JSON\",\n remediation: \"Fix JSON syntax in openclaw.plugin.json.\",\n });\n }\n }\n\n let packageRaw = \"\";\n let packageJsonPresent = false;\n try {\n packageRaw = await readFile(packageJsonPath, \"utf-8\");\n packageJsonPresent = true;\n } catch {\n checks.push({\n id: \"package-json-present\",\n title: \"package.json present\",\n level: \"error\",\n message: \"package.json is missing\",\n remediation: \"Restore package.json at repo root.\",\n });\n }\n\n if (packageJsonPresent) {\n try {\n const pkg = JSON.parse(packageRaw) as {\n openclaw?: { plugin?: string; extensions?: string[] };\n engines?: { node?: string };\n };\n const pluginPathOk = pkg.openclaw?.plugin === \"./openclaw.plugin.json\";\n const extOk = Array.isArray(pkg.openclaw?.extensions)\n && pkg.openclaw?.extensions.includes(\"./dist/index.js\");\n if (pluginPathOk && extOk) {\n checks.push({\n id: \"package-openclaw-exports\",\n title: \"package.json OpenClaw export wiring\",\n level: \"ok\",\n message: \"package.json openclaw.plugin/extensions wiring looks valid.\",\n });\n } else {\n checks.push({\n id: \"package-openclaw-exports\",\n title: \"package.json OpenClaw export wiring\",\n level: \"error\",\n message: \"package.json openclaw plugin/extension wiring is missing or invalid.\",\n remediation: \"Set openclaw.plugin to ./openclaw.plugin.json and include ./dist/index.js in openclaw.extensions.\",\n });\n }\n\n const minVersion = parseNodeMinVersion(pkg.engines?.node);\n const currentVersion = parseCurrentNodeVersion(process.version);\n if (!minVersion || !currentVersion) {\n checks.push({\n id: \"node-version-compat\",\n title: \"Node runtime compatibility\",\n level: \"warn\",\n message: \"Unable to parse node engine/current version.\",\n remediation: \"Confirm Node version meets package.json engines.node requirement.\",\n metadata: { enginesNode: pkg.engines?.node, currentNode: process.version },\n });\n } else if (compareVersions(currentVersion, minVersion) >= 0) {\n checks.push({\n id: \"node-version-compat\",\n title: \"Node runtime compatibility\",\n level: \"ok\",\n message: `Current Node ${process.version} satisfies engines requirement ${pkg.engines?.node}.`,\n });\n } else {\n checks.push({\n id: \"node-version-compat\",\n title: \"Node runtime compatibility\",\n level: \"error\",\n message: `Current Node ${process.version} is below required ${pkg.engines?.node}.`,\n remediation: \"Upgrade Node runtime to meet package.json engines.node minimum.\",\n });\n }\n } catch {\n checks.push({\n id: \"package-json-parse\",\n title: \"package.json parse\",\n level: \"error\",\n message: \"package.json is not valid JSON\",\n remediation: \"Fix JSON syntax in package.json.\",\n });\n }\n }\n\n try {\n await access(indexPath);\n const indexRaw = await readFile(indexPath, \"utf-8\");\n const structuralSource = stripCommentsAndStrings(indexRaw);\n const hooks = parseHookRegistrations(indexRaw);\n const missingLegacy = REQUIRED_HOOKS_LEGACY.filter((hook) => !hooks.has(hook));\n const missingNew = REQUIRED_HOOKS_NEW.filter((hook) => !hooks.has(hook));\n // registerMemoryPromptSection is a valid alternative to the recall hook.\n // Use the comment/string-stripped source and look for an actual call pattern\n // (`.registerMemoryPromptSection(`) rather than just the identifier name, to\n // avoid false positives from typeof checks or other non-registration usage.\n const hasMemoryPromptSection = structuralSource.includes(\".registerMemoryPromptSection(\");\n const missingLegacyAdj = hasMemoryPromptSection\n ? missingLegacy.filter((h) => h !== \"before_agent_start\")\n : missingLegacy;\n const missingNewAdj = hasMemoryPromptSection\n ? missingNew.filter((h) => h !== \"before_prompt_build\")\n : missingNew;\n // Accept whichever hook set has fewer missing entries\n const missingHooks = missingNewAdj.length <= missingLegacyAdj.length ? missingNewAdj : missingLegacyAdj;\n const hasGatewayStartHook = hooks.has(\"gateway_start\");\n const hasServiceStart = hasServiceStartRegistration(structuralSource);\n if (missingHooks.length === 0 && (hasGatewayStartHook || hasServiceStart)) {\n checks.push({\n id: \"hook-registration-core\",\n title: \"Core hook registration\",\n level: \"ok\",\n message: \"Core recall/extraction hooks and startup wiring are registered in src/index.ts.\",\n });\n } else {\n const missingParts: string[] = [];\n if (missingHooks.length > 0) {\n missingParts.push(`hooks: ${missingHooks.join(\", \")}`);\n }\n if (!hasGatewayStartHook && !hasServiceStart) {\n missingParts.push(\"startup wiring: gateway_start hook or api.registerService({ start })\");\n }\n checks.push({\n id: \"hook-registration-core\",\n title: \"Core hook registration\",\n level: \"error\",\n message: `Missing expected registration(s): ${missingParts.join(\"; \")}`,\n remediation: \"Ensure src/index.ts registers before_prompt_build (or before_agent_start) and agent_end, plus either gateway_start or api.registerService({ start }).\",\n });\n }\n\n const cliWired = hasCliRegistration(structuralSource);\n checks.push({\n id: \"cli-registration\",\n title: \"CLI registration wiring\",\n level: cliWired ? \"ok\" : \"warn\",\n message: cliWired\n ? \"CLI registration is wired in plugin bootstrap.\"\n : \"CLI registration call not found in src/index.ts.\",\n remediation: cliWired ? undefined : \"Call registerCli(api, orchestrator) during plugin registration.\",\n });\n } catch {\n checks.push({\n id: \"hook-registration-core\",\n title: \"Core hook registration\",\n level: \"error\",\n message: \"src/index.ts is missing; cannot validate hook wiring.\",\n remediation: \"Restore src/index.ts and register required hooks.\",\n });\n }\n\n const qmdAvailable = await runner.commandExists(\"qmd\");\n checks.push({\n id: \"qmd-binary-availability\",\n title: \"QMD binary availability\",\n level: qmdAvailable ? \"ok\" : \"warn\",\n message: qmdAvailable\n ? \"qmd binary is available in PATH.\"\n : \"qmd binary is not available in PATH.\",\n remediation: qmdAvailable ? undefined : \"Install qmd or configure qmdPath in plugin config.\",\n });\n\n return {\n generatedAt: (options.now ?? new Date()).toISOString(),\n checks,\n summary: summarize(checks),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,YAAU;AACjB,SAAS,UAAAC,SAAQ,YAAAC,YAAU,WAAAC,UAAS,UAAAC,eAAc;AAClD,SAAS,cAAAC,mBAAkB;;;ACF3B,OAAOC,WAAU;AACjB,SAAS,SAAAC,QAAO,YAAAC,iBAAgB;;;ACDzB,IAAM,gBAAgB;AACtB,IAAM,wBAAwB;;;ACDrC,SAAS,kBAAkB;AAC3B,SAAS,OAAO,SAAS,UAAU,MAAM,iBAAiB;AAC1D,OAAO,UAAU;AAEjB,eAAsB,WAAW,UAA8D;AAC7F,QAAM,MAAM,MAAM,SAAS,QAAQ;AACnC,QAAM,SAAS,WAAW,QAAQ,EAAE,OAAO,GAAG,EAAE,OAAO,KAAK;AAC5D,SAAO,EAAE,QAAQ,OAAO,IAAI,WAAW;AACzC;AAEO,SAAS,aAAa,SAAoD;AAC/E,QAAM,MAAM,OAAO,KAAK,SAAS,OAAO;AACxC,QAAM,SAAS,WAAW,QAAQ,EAAE,OAAO,GAAG,EAAE,OAAO,KAAK;AAC5D,SAAO,EAAE,QAAQ,OAAO,IAAI,WAAW;AACzC;AAEA,eAAsB,cAAc,UAAkB,OAA+B;AACnF,QAAM,MAAM,KAAK,QAAQ,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;AACvD,QA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C;AAC7B,cAAM,UAAU,QAAQ,WAAW;AACnC,cAAM,cAAc,QAAQ,SAAS,SAAS,QAAQ,QAAQ,EAAE,IAAI;AAEpE,cAAM,YAAY,MAAM,aAAa,WAAW,WAAW,SAAS,WAAW;AAC/E,YAAI,UAAU,WAAW,GAAG;AAC1B,kBAAQ,IAAI,mCAAmC,OAAO,EAAE;AACxD;AAAA,QACF;AAEA,gBAAQ,IAAI,aAAa,WAAW,gBAAgB,WAAW,UAAU,MAAM,CAAC;AAAA,MAClF,CAAC;AAAA,IACL;AAAA,IACA,EAAE,UAAU,CAAC,QAAQ,EAAE;AAAA,EACzB;AACF;AAEA,SAAS,iBAAiB,SAAoC;AAC5D,MAAI,QAAQ,WAAW,EAAG,QAAO;AAEjC,SAAO,QACJ,IAAI,CAAC,MAAM;AACV,UAAM,OAAO,EAAE,UAAU,MAAM,IAAI,EAAE;AACrC,WAAO,IAAI,IAAI,KAAK,EAAE,IAAI,KAAK,EAAE,QAAQ,MAAM,GAAG,GAAG,CAAC,GAAG,EAAE,QAAQ,SAAS,MAAM,QAAQ,EAAE;AAAA,EAC9F,CAAC,EACA,KAAK,IAAI;AACd;AAEA,SAAS,cAAc,UAA0B;AAE/C,QAAM,QAAQ,SAAS,MAAM,QAAQ;AACrC,QAAM,UAAU,SAAS,MAAM,QAAQ;AACvC,MAAI,QAAQ;AACZ,MAAI,MAAO,UAAS,SAAS,MAAM,CAAC,GAAG,EAAE;AACzC,MAAI,QAAS,UAAS,SAAS,QAAQ,CAAC,GAAG,EAAE,IAAI;AACjD,SAAO,SAAS;AAClB;","names":["path","access","readFile","readdir","unlink","createHash","path","mkdir","readFile","path","mkdir","readFile","path","mkdir","readFile","writeFile","shouldExclude","path","mkdir","readFile","writeFile","path","mkdir","readdir","path","mkdir","readdir","path","readFile","shouldExclude","path","rows","readFile","path","mkdir","writeFile","path","exists","mkdir","writeFile","path","mkdir","writeFile","normalizeForDedupe","path","exists","mkdir","writeFile","path","mkdir","readFile","writeFile","normalizeForDedupe","path","readFile","exists","mkdir","writeFile","path","stat","path","stat","gatherConversations","path","path","mkdir","readdir","readFile","writeFile","listFilesRecursive","path","mkdir","stat","writeFile","stat","path","mkdir","writeFile","path","mkdir","rename","rm","stat","stat","path","mkdir","rename","rm","path","readdir","readFile","path","mkdir","readFile","writeFile","readdir","path","readFile","path","readdir","readFile","readdir","path","readFile","stat","stat","mkdir","readdir","stat","path","URL","readFile","path","path","readFile","createHash","readRuntimePolicySnapshot","path","createServer","readFile","access","readdir","unlink","chunks"]}