@remnic/core 9.69.33 → 9.69.35

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 (766) hide show
  1. package/dist/access-admin-ops-surface.d.ts +14 -11
  2. package/dist/access-admin-ops-surface.js +65 -60
  3. package/dist/access-audit.js +2 -2
  4. package/dist/access-authorization-probe.d.ts +14 -11
  5. package/dist/access-authorization-probe.js +66 -61
  6. package/dist/access-boundary.d.ts +14 -11
  7. package/dist/access-boundary.js +65 -60
  8. package/dist/access-cli.js +137 -133
  9. package/dist/access-cli.js.map +1 -1
  10. package/dist/access-coding-context-resolution.d.ts +3 -1
  11. package/dist/access-coding-context-resolution.js +3 -3
  12. package/dist/access-extraction-force-flush.d.ts +14 -11
  13. package/dist/access-extraction-force-flush.js +65 -60
  14. package/dist/access-health-types.d.ts +3 -1
  15. package/dist/access-http-briefing.d.ts +14 -11
  16. package/dist/access-http-briefing.js +66 -61
  17. package/dist/access-http-lcm-compaction.d.ts +14 -11
  18. package/dist/access-http-lifecycle-flush.d.ts +14 -11
  19. package/dist/access-http-offline-stream.d.ts +14 -11
  20. package/dist/access-http-query.d.ts +4 -2
  21. package/dist/access-http-query.js +67 -62
  22. package/dist/access-http.d.ts +15 -12
  23. package/dist/access-http.js +86 -82
  24. package/dist/access-identity-continuity-surface.d.ts +12 -9
  25. package/dist/access-identity-continuity-surface.js +65 -60
  26. package/dist/access-lcm-surface.d.ts +14 -11
  27. package/dist/access-lcm-surface.js +65 -60
  28. package/dist/access-mcp.d.ts +14 -11
  29. package/dist/access-mcp.js +74 -70
  30. package/dist/access-memory-search-fanout.d.ts +4 -2
  31. package/dist/{access-namespace-preflight-DMR-jOMS.d.ts → access-namespace-preflight-D8qri11P.d.ts} +1 -1
  32. package/dist/access-namespace-preflight.d.ts +5 -3
  33. package/dist/access-namespace-preflight.js +65 -60
  34. package/dist/access-observe-transcript.d.ts +12 -9
  35. package/dist/access-observe-transcript.js +3 -3
  36. package/dist/access-observe-write-surface.d.ts +16 -13
  37. package/dist/access-observe-write-surface.js +65 -60
  38. package/dist/access-offline-manifest.d.ts +48 -11
  39. package/dist/access-offline-manifest.js +18 -16
  40. package/dist/access-operations-batch.js +68 -64
  41. package/dist/access-operations.d.ts +15 -12
  42. package/dist/access-operations.js +73 -69
  43. package/dist/access-recall-concurrency.d.ts +14 -11
  44. package/dist/access-recall-concurrency.js +65 -60
  45. package/dist/access-recall-response.d.ts +14 -11
  46. package/dist/access-recall-response.js +65 -60
  47. package/dist/access-recall-surface.d.ts +14 -11
  48. package/dist/access-recall-surface.js +65 -60
  49. package/dist/access-schema.d.ts +56 -13
  50. package/dist/access-schema.js +15 -1
  51. package/dist/{access-service-CJQoQvRa.d.ts → access-service-CKu5ixg9.d.ts} +52 -50
  52. package/dist/access-service-helpers.d.ts +14 -11
  53. package/dist/access-service.d.ts +14 -11
  54. package/dist/access-service.js +65 -60
  55. package/dist/access-surface-catalog.d.ts +14 -11
  56. package/dist/access-surface-catalog.js +67 -62
  57. package/dist/access-surface-catalog.js.map +1 -1
  58. package/dist/access-wearables-meetings-surface.d.ts +5 -3
  59. package/dist/action-confidence.d.ts +3 -1
  60. package/dist/active-memory-bridge.d.ts +3 -1
  61. package/dist/active-memory-bridge.js +2 -2
  62. package/dist/active-recall.d.ts +3 -1
  63. package/dist/active-recall.js +12 -10
  64. package/dist/active-recall.js.map +1 -1
  65. package/dist/activity/digest.d.ts +3 -1
  66. package/dist/adapters/index.d.ts +46 -1
  67. package/dist/adapters/index.js +10 -6
  68. package/dist/adapters/registry.js +2 -2
  69. package/dist/ambient-provenance.d.ts +3 -1
  70. package/dist/artifact-search.d.ts +3 -1
  71. package/dist/{auto-sync-NSHLUAQI.js → auto-sync-4YFATLFQ.js} +10 -9
  72. package/dist/{auto-sync-NSHLUAQI.js.map → auto-sync-4YFATLFQ.js.map} +1 -1
  73. package/dist/behavior-learner.d.ts +3 -1
  74. package/dist/behavior-signals.d.ts +3 -1
  75. package/dist/bootstrap.d.ts +12 -9
  76. package/dist/briefing-window.d.ts +4 -2
  77. package/dist/briefing.d.ts +4 -2
  78. package/dist/briefing.js +26 -25
  79. package/dist/buffer-surprise-report.d.ts +3 -1
  80. package/dist/buffer-turn-helpers.d.ts +3 -1
  81. package/dist/buffer.d.ts +4 -2
  82. package/dist/buffer.js +11 -10
  83. package/dist/bulk-import/index.d.ts +5 -3
  84. package/dist/calibration.d.ts +3 -1
  85. package/dist/calibration.js +3 -2
  86. package/dist/calibration.js.map +1 -1
  87. package/dist/capabilities.d.ts +3 -1
  88. package/dist/{capsule-merge-IPG4IOFP.js → capsule-merge-ZCXUPLNJ.js} +2 -2
  89. package/dist/{catalog-8O9KY9eA.d.ts → catalog-Bq1AxZwF.d.ts} +1 -1
  90. package/dist/causal-behavior.d.ts +3 -1
  91. package/dist/causal-consolidation.d.ts +3 -1
  92. package/dist/causal-consolidation.js +27 -26
  93. package/dist/causal-consolidation.js.map +1 -1
  94. package/dist/causal-trajectory-graph.d.ts +3 -1
  95. package/dist/{chunk-CDKHKZL5.js → chunk-2524MOWK.js} +2 -2
  96. package/dist/{chunk-HVAEXYPL.js → chunk-255PC37A.js} +47 -25
  97. package/dist/chunk-255PC37A.js.map +1 -0
  98. package/dist/{chunk-2C3S7J2S.js → chunk-2BQ4ZIWC.js} +741 -28
  99. package/dist/chunk-2BQ4ZIWC.js.map +1 -0
  100. package/dist/{chunk-RKBLRTNT.js → chunk-2YLMUME2.js} +2 -2
  101. package/dist/{chunk-QOIOACIE.js → chunk-326KUXIR.js} +15 -648
  102. package/dist/chunk-326KUXIR.js.map +1 -0
  103. package/dist/{chunk-DBQWVT2H.js → chunk-3CBI2ZSA.js} +2 -2
  104. package/dist/{chunk-MWFGUESQ.js → chunk-3FJKJ5UZ.js} +2 -2
  105. package/dist/{chunk-NZXEK3UF.js → chunk-3Q3N35W7.js} +2 -2
  106. package/dist/{chunk-YYGZJPOK.js → chunk-42DJ235G.js} +2 -2
  107. package/dist/{chunk-SO7SV523.js → chunk-4MDKNUV4.js} +1 -1
  108. package/dist/chunk-4MDKNUV4.js.map +1 -0
  109. package/dist/chunk-5HYUUFMQ.js +1280 -0
  110. package/dist/chunk-5HYUUFMQ.js.map +1 -0
  111. package/dist/{chunk-2JVJ7UHC.js → chunk-5JG5EBVL.js} +4 -2
  112. package/dist/chunk-5JG5EBVL.js.map +1 -0
  113. package/dist/{chunk-HV7OY4DM.js → chunk-5VAF4ID4.js} +643 -202
  114. package/dist/chunk-5VAF4ID4.js.map +1 -0
  115. package/dist/{chunk-N7RWREIQ.js → chunk-65RENJGB.js} +6 -1
  116. package/dist/chunk-65RENJGB.js.map +1 -0
  117. package/dist/{chunk-JTH2SE6B.js → chunk-6J6K3STG.js} +8 -8
  118. package/dist/{chunk-H4VH5VIB.js → chunk-776GVKL7.js} +2 -2
  119. package/dist/{chunk-BUTCAMJM.js → chunk-A2YQL2FF.js} +5 -5
  120. package/dist/chunk-A5UQ52YQ.js +211 -0
  121. package/dist/chunk-A5UQ52YQ.js.map +1 -0
  122. package/dist/{chunk-X2NFFBTO.js → chunk-A7GQBJP5.js} +4 -4
  123. package/dist/{chunk-CGC5UQCF.js → chunk-AKE4GGQ3.js} +2 -2
  124. package/dist/{chunk-B325AGLK.js → chunk-AZSKROVQ.js} +2 -2
  125. package/dist/{chunk-I5DZ3WGR.js → chunk-BJETIR53.js} +3 -3
  126. package/dist/{chunk-JT3EB7ZL.js → chunk-BNGHPYZU.js} +5 -5
  127. package/dist/chunk-BRZWWUCJ.js +13 -0
  128. package/dist/{chunk-FYDW33ZB.js.map → chunk-BRZWWUCJ.js.map} +1 -1
  129. package/dist/{chunk-3JVLGJCY.js → chunk-C6KRO3SU.js} +2 -2
  130. package/dist/{chunk-5NANRSCD.js → chunk-CNV2A557.js} +5 -5
  131. package/dist/{chunk-PBGVVDLY.js → chunk-DK4X5B6I.js} +2 -2
  132. package/dist/{chunk-MFDTVQJX.js → chunk-DVOBLPSQ.js} +22 -7
  133. package/dist/chunk-DVOBLPSQ.js.map +1 -0
  134. package/dist/{chunk-N2ZNPHA3.js → chunk-ECKG5WSI.js} +2 -2
  135. package/dist/{chunk-PYLL63BF.js → chunk-EEBQFG5E.js} +9 -9
  136. package/dist/{chunk-ET356KSB.js → chunk-F4TWWUMP.js} +2 -2
  137. package/dist/{chunk-RHQMKJFG.js → chunk-F6IVBYFS.js} +55 -51
  138. package/dist/{chunk-RHQMKJFG.js.map → chunk-F6IVBYFS.js.map} +1 -1
  139. package/dist/{chunk-CLLPJ6QT.js → chunk-FQXJAC3T.js} +2 -2
  140. package/dist/{chunk-JGHXXQ2G.js → chunk-FVJ4D6L7.js} +2 -2
  141. package/dist/{chunk-DD5JFCWM.js → chunk-GCBIXUPT.js} +2 -2
  142. package/dist/{chunk-MN3LK3KN.js → chunk-GLZH5VEN.js} +2 -2
  143. package/dist/{chunk-S7T2TY65.js → chunk-HC4GFLMQ.js} +3 -3
  144. package/dist/{chunk-EQHDH4C2.js → chunk-HUT2JR6I.js} +3 -3
  145. package/dist/{chunk-UUQG7HAD.js → chunk-HXSAWV3A.js} +4 -4
  146. package/dist/{chunk-XXIHX75O.js → chunk-J7PB5UQ4.js} +3 -3
  147. package/dist/{chunk-UGPUYIET.js → chunk-JHZCXUQI.js} +221 -400
  148. package/dist/chunk-JHZCXUQI.js.map +1 -0
  149. package/dist/{chunk-LTIZHLV7.js → chunk-JR6H5CYS.js} +2 -2
  150. package/dist/{chunk-FCSZ4K2X.js → chunk-JR6PP7UM.js} +3 -3
  151. package/dist/{chunk-TCUKRAMK.js → chunk-JRWW7GM6.js} +10 -10
  152. package/dist/{chunk-Q726HSJO.js → chunk-JSRVXI6E.js} +16 -15
  153. package/dist/chunk-JSRVXI6E.js.map +1 -0
  154. package/dist/{chunk-DB5TGMLZ.js → chunk-JZ2CHRLB.js} +6 -4
  155. package/dist/{chunk-DB5TGMLZ.js.map → chunk-JZ2CHRLB.js.map} +1 -1
  156. package/dist/{chunk-JEIXTYVG.js → chunk-L2QLDZJC.js} +46 -17
  157. package/dist/chunk-L2QLDZJC.js.map +1 -0
  158. package/dist/{chunk-PL7FYKHT.js → chunk-L2WQVSKP.js} +2 -2
  159. package/dist/{chunk-JSN44KIB.js → chunk-LEMD7WZJ.js} +9 -9
  160. package/dist/{chunk-VZWXFXLX.js → chunk-LMCD5W5B.js} +2 -2
  161. package/dist/{chunk-7BMXZCOT.js → chunk-LNDLXMH6.js} +3 -3
  162. package/dist/{chunk-3QQTXYZ6.js → chunk-LSLCFCCQ.js} +2 -1
  163. package/dist/chunk-LSLCFCCQ.js.map +1 -0
  164. package/dist/{chunk-EONF76DT.js → chunk-LYDJRF45.js} +2 -2
  165. package/dist/{chunk-MKD3OMPS.js → chunk-M3MYMWXG.js} +2 -2
  166. package/dist/{chunk-VGXM5B4H.js → chunk-MNIPH6LD.js} +2 -2
  167. package/dist/{chunk-A7XEPMQ6.js → chunk-MVAQ2WM3.js} +6 -6
  168. package/dist/chunk-MVAQ2WM3.js.map +1 -0
  169. package/dist/{chunk-6N3TQFZU.js → chunk-NN4JEFON.js} +3 -3
  170. package/dist/chunk-NPNSKE76.js +220 -0
  171. package/dist/chunk-NPNSKE76.js.map +1 -0
  172. package/dist/{chunk-MOZXTRC2.js → chunk-OQ7SSRXP.js} +19 -19
  173. package/dist/{chunk-XU6OEECT.js → chunk-OQQXGYMX.js} +3 -3
  174. package/dist/{chunk-4MHYKEOM.js → chunk-OS2AT2JU.js} +10 -10
  175. package/dist/{chunk-N57A4KPV.js → chunk-P3ONDDIJ.js} +2 -2
  176. package/dist/chunk-PCEYGOSL.js +66 -0
  177. package/dist/chunk-PCEYGOSL.js.map +1 -0
  178. package/dist/{chunk-R3HKWWUB.js → chunk-PHP3MUGF.js} +2 -2
  179. package/dist/{chunk-EEOUMG3J.js → chunk-PWPIERBM.js} +38 -6
  180. package/dist/chunk-PWPIERBM.js.map +1 -0
  181. package/dist/chunk-Q4AUIFUA.js +111 -0
  182. package/dist/chunk-Q4AUIFUA.js.map +1 -0
  183. package/dist/{chunk-P3SB5BNT.js → chunk-QATYVTP7.js} +2 -2
  184. package/dist/{chunk-LSYDG6MJ.js → chunk-QBLDCI6E.js} +2 -2
  185. package/dist/{chunk-KCB7F4J7.js → chunk-QURNMKME.js} +2 -2
  186. package/dist/{chunk-XOVKXJEP.js → chunk-R3TLVTWW.js} +3 -3
  187. package/dist/{chunk-XXE5P6HJ.js → chunk-RRZKTSFG.js} +2 -2
  188. package/dist/{chunk-44T3Y7SZ.js → chunk-RUXPVSML.js} +5 -5
  189. package/dist/{chunk-DCJ3YFIC.js → chunk-S2ULTQZR.js} +2 -2
  190. package/dist/{chunk-H272ZPQ3.js → chunk-SHEHQBCG.js} +124 -23
  191. package/dist/chunk-SHEHQBCG.js.map +1 -0
  192. package/dist/{chunk-EEC4PCG5.js → chunk-SZDLX763.js} +2 -2
  193. package/dist/{chunk-E2ZHGBAK.js → chunk-T2JSUEH6.js} +2 -2
  194. package/dist/{chunk-227UFSEQ.js → chunk-TFA6HPOA.js} +2 -2
  195. package/dist/{chunk-BA6WOZOT.js → chunk-TK4FHQRN.js} +4 -4
  196. package/dist/{chunk-W27OW7AB.js → chunk-TKFSXDOB.js} +2 -2
  197. package/dist/chunk-TLHNF6GA.js +647 -0
  198. package/dist/chunk-TLHNF6GA.js.map +1 -0
  199. package/dist/{chunk-7K5Q6COX.js → chunk-TVVEYCNW.js} +4 -4
  200. package/dist/{chunk-FDLDOEO6.js → chunk-UBG4GAEP.js} +51 -6
  201. package/dist/chunk-UBG4GAEP.js.map +1 -0
  202. package/dist/{chunk-CETXNLEX.js → chunk-UDZYNIDJ.js} +2 -2
  203. package/dist/{chunk-H5AFCNGA.js → chunk-UJX4I26O.js} +2 -2
  204. package/dist/{chunk-E6TDQRF6.js → chunk-UYUCCQ46.js} +2 -2
  205. package/dist/{chunk-BLUYQFRH.js → chunk-VELCIWJZ.js} +15 -11
  206. package/dist/chunk-VELCIWJZ.js.map +1 -0
  207. package/dist/{chunk-OQDPBRQ6.js → chunk-VYXDUPYE.js} +2 -2
  208. package/dist/{chunk-ZG74PWRW.js → chunk-VZAKYDMJ.js} +2 -2
  209. package/dist/chunk-W6IJMWTZ.js +72 -0
  210. package/dist/chunk-W6IJMWTZ.js.map +1 -0
  211. package/dist/{chunk-NB5BCFUY.js → chunk-WHHEPAO3.js} +4 -4
  212. package/dist/{chunk-H3TKENU4.js → chunk-WIKO4SCR.js} +5 -5
  213. package/dist/{chunk-TX2UTLXC.js → chunk-WPDKBUWX.js} +2 -2
  214. package/dist/{chunk-YFLLGRXO.js → chunk-X2QPKLPL.js} +2 -2
  215. package/dist/{chunk-PFFZWDPE.js → chunk-XCOV45MO.js} +3 -3
  216. package/dist/{chunk-5BCNEBEN.js → chunk-XPJNT6PI.js} +4 -4
  217. package/dist/chunk-XW2T4QAW.js +1 -0
  218. package/dist/{chunk-J7HFPA6O.js → chunk-Y63ZFP4X.js} +2 -2
  219. package/dist/{chunk-D223ZDQV.js → chunk-YEDVOYL2.js} +2 -2
  220. package/dist/{chunk-TLPZ6MKZ.js → chunk-YEN4TREG.js} +541 -5
  221. package/dist/chunk-YEN4TREG.js.map +1 -0
  222. package/dist/{chunk-22FVR2KE.js → chunk-YJ6VCDMZ.js} +6 -2
  223. package/dist/chunk-YJ6VCDMZ.js.map +1 -0
  224. package/dist/{chunk-RC5DXXWC.js → chunk-YM7YN37H.js} +2 -2
  225. package/dist/{chunk-BPJNF7J2.js → chunk-YNN26CIZ.js} +2 -2
  226. package/dist/{chunk-VLXBE57O.js → chunk-YVGXH72Y.js} +2 -2
  227. package/dist/{chunk-YQAXP5AC.js → chunk-YXLUTALO.js} +5 -5
  228. package/dist/{chunk-DGGB65KC.js → chunk-Z7ACR6MJ.js} +3 -3
  229. package/dist/{chunk-X35W4S3L.js → chunk-ZBEGS7OB.js} +4 -4
  230. package/dist/{chunk-O75CRYGF.js → chunk-ZEFVK7XC.js} +1 -1
  231. package/dist/chunk-ZEFVK7XC.js.map +1 -0
  232. package/dist/{chunk-XUE46UYW.js → chunk-ZLN7AROH.js} +6 -6
  233. package/dist/{chunk-E6JA6XWY.js → chunk-ZTG4P7NZ.js} +1013 -1317
  234. package/dist/chunk-ZTG4P7NZ.js.map +1 -0
  235. package/dist/{chunk-HK32G473.js → chunk-ZWEZXVYH.js} +2 -2
  236. package/dist/{cli-D57e2Mqt.d.ts → cli-Bk7Ctql4.d.ts} +5 -5
  237. package/dist/cli-fallback.d.ts +11 -4
  238. package/dist/cli-fallback.js +5 -1
  239. package/dist/cli.d.ts +16 -13
  240. package/dist/cli.js +107 -103
  241. package/dist/coding/export-okf-codegraph.d.ts +3 -1
  242. package/dist/coding/export-okf-codegraph.js +32 -30
  243. package/dist/coding/export-okf-codegraph.js.map +1 -1
  244. package/dist/coding/pre-action-gate.d.ts +3 -1
  245. package/dist/compat/checks.js +2 -2
  246. package/dist/compat/codex-cli-fallback.d.ts +1 -1
  247. package/dist/compat/codex-cli-fallback.js +5 -1
  248. package/dist/compat/codex-cli-fallback.js.map +1 -1
  249. package/dist/compounding/engine.d.ts +4 -2
  250. package/dist/compounding/engine.js +27 -26
  251. package/dist/compounding/preference-consolidator.d.ts +3 -1
  252. package/dist/compression-optimizer.d.ts +3 -1
  253. package/dist/config.d.ts +3 -1
  254. package/dist/config.js +12 -10
  255. package/dist/connectors/codex-materialize-runner.d.ts +3 -1
  256. package/dist/connectors/codex-materialize-runner.js +26 -25
  257. package/dist/connectors/codex-materialize.d.ts +3 -1
  258. package/dist/connectors/index.d.ts +3 -1
  259. package/dist/connectors/index.js +28 -27
  260. package/dist/consolidation-provenance-check.d.ts +4 -2
  261. package/dist/consolidation-undo.d.ts +4 -2
  262. package/dist/contradiction/index.d.ts +5 -3
  263. package/dist/contradiction/index.js +5 -5
  264. package/dist/{contradiction-scan-NOYMFG66.js → contradiction-scan-GVD4JJ7B.js} +3 -3
  265. package/dist/converge-config.d.ts +3 -1
  266. package/dist/convergence-refresh.d.ts +4 -2
  267. package/dist/convergence-refresh.js +28 -27
  268. package/dist/conversation-index/backend.d.ts +3 -1
  269. package/dist/conversation-index/backend.js +3 -3
  270. package/dist/conversation-index/chunker.d.ts +3 -1
  271. package/dist/conversation-index/faiss-adapter.d.ts +3 -1
  272. package/dist/conversation-index/faiss-adapter.js +2 -2
  273. package/dist/conversation-index/indexer.d.ts +3 -1
  274. package/dist/conversation-index/search.d.ts +3 -1
  275. package/dist/corpus-watermark.d.ts +3 -1
  276. package/dist/corpus-watermark.js +29 -28
  277. package/dist/cross-lingual-recall.d.ts +3 -1
  278. package/dist/day-summary.d.ts +3 -1
  279. package/dist/deep-recall-http-glue.d.ts +14 -11
  280. package/dist/deep-recall-http-glue.js +12 -2
  281. package/dist/deep-recall-mcp-tools.d.ts +14 -11
  282. package/dist/deep-recall-policy-llm.d.ts +3 -1
  283. package/dist/deep-recall-policy-llm.js +4 -3
  284. package/dist/deep-recall-seeds.d.ts +3 -1
  285. package/dist/delinearize.d.ts +3 -1
  286. package/dist/dependency-propagation-config.d.ts +3 -1
  287. package/dist/{dependency-propagation-delivery-CmniEsUK.d.ts → dependency-propagation-delivery-DLiAtj25.d.ts} +1 -1
  288. package/dist/direct-answer-wiring.d.ts +3 -1
  289. package/dist/direct-answer.d.ts +3 -1
  290. package/dist/embedding-fallback.d.ts +3 -1
  291. package/dist/enrichment/index.d.ts +3 -1
  292. package/dist/entity-origin-fields.d.ts +3 -1
  293. package/dist/entity-retrieval.d.ts +4 -2
  294. package/dist/entity-retrieval.js +26 -25
  295. package/dist/entity-schema.d.ts +3 -1
  296. package/dist/episodic-context.d.ts +3 -1
  297. package/dist/eval-trajectory-contracts.d.ts +3 -1
  298. package/dist/eval-trajectory-store.d.ts +3 -1
  299. package/dist/eval-trajectory.d.ts +3 -1
  300. package/dist/explicit-capture.d.ts +12 -9
  301. package/dist/explicit-capture.js +6 -6
  302. package/dist/external-wiki-access.d.ts +14 -11
  303. package/dist/external-wiki-access.js +66 -61
  304. package/dist/external-wiki-collection-registration.d.ts +3 -1
  305. package/dist/external-wiki-collection.d.ts +3 -1
  306. package/dist/external-wiki-mcp-tools.d.ts +14 -11
  307. package/dist/extraction-error-classification.d.ts +3 -1
  308. package/dist/extraction-faithfulness.d.ts +3 -1
  309. package/dist/extraction-faithfulness.js +4 -3
  310. package/dist/extraction-judge-telemetry.d.ts +3 -1
  311. package/dist/extraction-judge-training.d.ts +3 -1
  312. package/dist/extraction-judge.d.ts +3 -1
  313. package/dist/extraction-judge.js +5 -4
  314. package/dist/extraction-liveness.d.ts +3 -1
  315. package/dist/extraction-normalization.d.ts +3 -1
  316. package/dist/extraction-prompt.d.ts +3 -1
  317. package/dist/extraction-source-grounding-rules.d.ts +3 -1
  318. package/dist/extraction-source-grounding.d.ts +3 -1
  319. package/dist/extraction.d.ts +3 -1
  320. package/dist/extraction.js +38 -36
  321. package/dist/fallback-llm.d.ts +3 -1
  322. package/dist/fallback-llm.js +3 -2
  323. package/dist/{first-start-migration-RC345GPL.js → first-start-migration-L3UFX5CU.js} +3 -3
  324. package/dist/generic-recall-paths-DbitKJI5.d.ts +23 -0
  325. package/dist/graph-append-error.d.ts +3 -1
  326. package/dist/graph-dashboard-diff.d.ts +3 -1
  327. package/dist/graph-dashboard-key.d.ts +3 -1
  328. package/dist/graph-dashboard-parser.d.ts +3 -1
  329. package/dist/graph-edge-reinforcement.d.ts +3 -1
  330. package/dist/graph-jsonl.d.ts +3 -1
  331. package/dist/graph-path-reconstruction.d.ts +3 -1
  332. package/dist/graph-path-scoring.d.ts +3 -1
  333. package/dist/graph-snapshot.d.ts +3 -1
  334. package/dist/graph.d.ts +3 -1
  335. package/dist/harmonic-retrieval.js +2 -2
  336. package/dist/importance.d.ts +3 -1
  337. package/dist/importers/index.d.ts +3 -1
  338. package/dist/importers/test-utils.d.ts +3 -1
  339. package/dist/in-flight-reads.d.ts +3 -1
  340. package/dist/{index-BTAsSkPG.d.ts → index-BINUgPFo.d.ts} +2 -2
  341. package/dist/index.d.ts +303 -245
  342. package/dist/index.js +316 -214
  343. package/dist/intent.d.ts +3 -1
  344. package/dist/lcm/engine.d.ts +3 -1
  345. package/dist/lcm/engine.js +2 -2
  346. package/dist/lcm/index.d.ts +3 -1
  347. package/dist/lcm/index.js +7 -7
  348. package/dist/lcm/tools.d.ts +3 -1
  349. package/dist/lifecycle.d.ts +3 -1
  350. package/dist/live-connectors-runner.d.ts +3 -1
  351. package/dist/local-llm-config.d.ts +26 -0
  352. package/dist/local-llm-config.js +1 -0
  353. package/dist/local-llm.d.ts +5 -1
  354. package/dist/local-llm.js +3 -3
  355. package/dist/local-model-endpoint.d.ts +3 -1
  356. package/dist/location/index.d.ts +5 -3
  357. package/dist/location/index.js +29 -28
  358. package/dist/maintenance/memory-governance.d.ts +3 -1
  359. package/dist/maintenance/memory-governance.js +26 -25
  360. package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +4 -2
  361. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +26 -25
  362. package/dist/maintenance/rebuild-memory-projection.d.ts +4 -2
  363. package/dist/maintenance/rebuild-memory-projection.js +27 -26
  364. package/dist/{maintenance-DCvQGTzL.d.ts → maintenance-ag1gYztC.d.ts} +378 -4
  365. package/dist/mcp-memory-inspector-app.d.ts +14 -11
  366. package/dist/memory-action-policy.d.ts +3 -1
  367. package/dist/memory-cache.d.ts +3 -1
  368. package/dist/memory-controller.d.ts +3 -1
  369. package/dist/memory-lifecycle-ledger-utils.d.ts +3 -1
  370. package/dist/memory-projection-store.d.ts +3 -1
  371. package/dist/memory-provenance.d.ts +3 -1
  372. package/dist/memory-snapshot.d.ts +3 -1
  373. package/dist/memory-subject-cli.d.ts +14 -11
  374. package/dist/memory-subject.d.ts +14 -11
  375. package/dist/memory-worth-outcomes.d.ts +4 -2
  376. package/dist/migrate/from-engram.js +2 -2
  377. package/dist/models-json.d.ts +3 -1
  378. package/dist/namespaces/migrate.d.ts +5 -3
  379. package/dist/namespaces/migrate.js +27 -26
  380. package/dist/namespaces/principal.d.ts +3 -1
  381. package/dist/namespaces/search.d.ts +3 -1
  382. package/dist/namespaces/search.js +8 -8
  383. package/dist/namespaces/storage.d.ts +5 -3
  384. package/dist/namespaces/storage.js +26 -25
  385. package/dist/native-knowledge.d.ts +3 -1
  386. package/dist/network/tailscale.js +2 -2
  387. package/dist/offline-sync-impression-drain.d.ts +3 -1
  388. package/dist/offline-sync-impression-drain.js +6 -6
  389. package/dist/operator-doctor-corpus.d.ts +3 -1
  390. package/dist/operator-doctor-corpus.js +30 -29
  391. package/dist/operator-doctor-replica.d.ts +3 -1
  392. package/dist/operator-toolkit.d.ts +5 -3
  393. package/dist/operator-toolkit.js +44 -42
  394. package/dist/orchestration/compression-guideline-coordinator.d.ts +4 -2
  395. package/dist/orchestration/maintenance.d.ts +6 -4
  396. package/dist/orchestration/maintenance.js +44 -39
  397. package/dist/{orchestrator-CvCsp1tz.d.ts → orchestrator-Cf3G-3Ed.d.ts} +17 -29
  398. package/dist/orchestrator.d.ts +12 -9
  399. package/dist/orchestrator.js +141 -135
  400. package/dist/patterns-cli.d.ts +3 -1
  401. package/dist/{pipeline-JAdwKBS7.d.ts → pipeline-AwB03fw_.d.ts} +1 -1
  402. package/dist/policy-runtime.d.ts +3 -1
  403. package/dist/proactive-contention.d.ts +3 -1
  404. package/dist/provenance.d.ts +3 -1
  405. package/dist/{public-http-h-yWu9rj.d.ts → public-http-BetSQn7q.d.ts} +1 -1
  406. package/dist/{qmd-Cvw9RWKr.d.ts → qmd-Bfaydrfm.d.ts} +1 -1
  407. package/dist/qmd-preflight.d.ts +4 -2
  408. package/dist/qmd-recall-cache.d.ts +3 -1
  409. package/dist/qmd.d.ts +4 -2
  410. package/dist/qmd.js +2 -2
  411. package/dist/recall-concurrency-config.d.ts +3 -1
  412. package/dist/recall-disclosure-escalation.d.ts +3 -1
  413. package/dist/recall-explain-renderer.d.ts +3 -1
  414. package/dist/recall-explain-renderer.js +3 -3
  415. package/dist/recall-memory-map.d.ts +3 -1
  416. package/dist/recall-navigate-access.d.ts +3 -1
  417. package/dist/recall-navigate-access.js +2 -2
  418. package/dist/recall-navigate-disclosure.d.ts +3 -1
  419. package/dist/recall-navigate-disclosure.js +1 -1
  420. package/dist/recall-navigate.d.ts +3 -1
  421. package/dist/recall-navigate.js +2 -2
  422. package/dist/recall-planner-llm.d.ts +3 -1
  423. package/dist/recall-planner-llm.js +3 -2
  424. package/dist/recall-planner-llm.js.map +1 -1
  425. package/dist/recall-state-view-admission.d.ts +57 -0
  426. package/dist/recall-state-view-admission.js +39 -0
  427. package/dist/recall-state-view-admission.js.map +1 -0
  428. package/dist/recall-state-view-inject.js +2 -2
  429. package/dist/recall-state-view-render.js +2 -2
  430. package/dist/recall-state-view-widen.d.ts +18 -1
  431. package/dist/recall-state-view-widen.js +2 -2
  432. package/dist/recall-state-view-wire.d.ts +1 -1
  433. package/dist/recall-state-view-wire.js +3 -3
  434. package/dist/recall-state-view.d.ts +1 -0
  435. package/dist/recall-state-view.js +1 -1
  436. package/dist/recall-state.d.ts +3 -1
  437. package/dist/recall-tag-filter.d.ts +3 -1
  438. package/dist/recall-timings.d.ts +3 -1
  439. package/dist/recall-xray-cli.d.ts +3 -1
  440. package/dist/recall-xray-cli.js +4 -4
  441. package/dist/recall-xray-renderer.d.ts +3 -1
  442. package/dist/recall-xray-renderer.js +3 -3
  443. package/dist/recall-xray.d.ts +10 -1
  444. package/dist/recall-xray.js +2 -2
  445. package/dist/reconcile/cursor.d.ts +12 -2
  446. package/dist/reconcile/cursor.js +6 -4
  447. package/dist/reconcile/cursor.js.map +1 -1
  448. package/dist/reconcile/manifest.d.ts +38 -2
  449. package/dist/reconcile/manifest.js +15 -5
  450. package/dist/reconcile/plan.d.ts +3 -1
  451. package/dist/replay/normalizers/chatgpt.d.ts +3 -1
  452. package/dist/replay/normalizers/claude.d.ts +3 -1
  453. package/dist/replay/normalizers/openclaw.d.ts +3 -1
  454. package/dist/replay/normalizers/shared.d.ts +3 -1
  455. package/dist/replay/runner.d.ts +3 -1
  456. package/dist/replay/types.d.ts +3 -1
  457. package/dist/replica-divergence.d.ts +3 -1
  458. package/dist/replica-peers-config.d.ts +3 -1
  459. package/dist/{resolution-VKATP2HT.js → resolution-OHJZG45O.js} +6 -6
  460. package/dist/resolution-OHJZG45O.js.map +1 -0
  461. package/dist/resolve-auth-token.d.ts +3 -1
  462. package/dist/resume-bundles.js +13 -11
  463. package/dist/retrieval-agents.d.ts +4 -2
  464. package/dist/retrieval-tiers.d.ts +3 -1
  465. package/dist/routing/engine.d.ts +3 -1
  466. package/dist/routing/store.d.ts +3 -1
  467. package/dist/runtime/child-process.d.ts +1 -1
  468. package/dist/runtime/child-process.js +1 -1
  469. package/dist/salvage-envelope.d.ts +3 -1
  470. package/dist/salvage-envelope.js +2 -2
  471. package/dist/{scope-profiles-BShpTPeV.d.ts → scope-profiles-nxTKvjE-.d.ts} +1 -1
  472. package/dist/search/embed-helper.d.ts +3 -1
  473. package/dist/search/factory.d.ts +3 -1
  474. package/dist/search/factory.js +7 -7
  475. package/dist/search/index.d.ts +3 -1
  476. package/dist/search/index.js +11 -11
  477. package/dist/search/lancedb-backend.d.ts +3 -1
  478. package/dist/search/meilisearch-backend.d.ts +3 -1
  479. package/dist/search/noop-backend.d.ts +3 -1
  480. package/dist/search/orama-backend.d.ts +3 -1
  481. package/dist/search/port.d.ts +3 -1
  482. package/dist/search/remote-backend.d.ts +3 -1
  483. package/dist/{semantic-consolidation-CusOpe9F.d.ts → semantic-consolidation-C83DVakV.d.ts} +1 -1
  484. package/dist/semantic-consolidation.d.ts +4 -2
  485. package/dist/semantic-consolidation.js +27 -26
  486. package/dist/semantic-rule-promotion.js +26 -25
  487. package/dist/semantic-rule-verifier.d.ts +3 -1
  488. package/dist/semantic-rule-verifier.js +26 -25
  489. package/dist/{service-BbuVh1eS.d.ts → service-q-xtOoAr.d.ts} +2 -2
  490. package/dist/session-observer-bands.d.ts +3 -1
  491. package/dist/session-observer-state.d.ts +3 -1
  492. package/dist/shared-context/manager.d.ts +3 -1
  493. package/dist/signal.d.ts +3 -1
  494. package/dist/source-agent-qualifier.d.ts +3 -1
  495. package/dist/source-agent-qualifier.js +35 -33
  496. package/dist/standup/build.js +26 -25
  497. package/dist/{storage-BBLLuVTF.d.ts → storage-Ca0MbTfm.d.ts} +67 -6
  498. package/dist/storage.d.ts +5 -3
  499. package/dist/storage.js +25 -24
  500. package/dist/subject-config.d.ts +3 -1
  501. package/dist/subject-config.js +2 -2
  502. package/dist/summarizer.d.ts +3 -1
  503. package/dist/summarizer.js +6 -6
  504. package/dist/summary-snapshot.d.ts +3 -1
  505. package/dist/support-passport/index.d.ts +50 -15
  506. package/dist/support-passport/index.js +73 -64
  507. package/dist/temporal-supersession.d.ts +4 -2
  508. package/dist/temporal-timeline-recall.d.ts +3 -1
  509. package/dist/temporal-validity.d.ts +3 -1
  510. package/dist/threading.d.ts +3 -1
  511. package/dist/tier-migration.d.ts +4 -2
  512. package/dist/tier-routing.d.ts +3 -1
  513. package/dist/tier-routing.js +2 -2
  514. package/dist/{tier-stats-KA6OZX2C.js → tier-stats-VK5PCO2L.js} +3 -3
  515. package/dist/topics.d.ts +3 -1
  516. package/dist/transcript.d.ts +3 -1
  517. package/dist/transfer/capsule-import.js +1 -1
  518. package/dist/transfer/export-okf.d.ts +3 -1
  519. package/dist/transfer/export-okf.js +27 -26
  520. package/dist/transfer/types.d.ts +24 -24
  521. package/dist/trust-score-stage.d.ts +3 -1
  522. package/dist/trust-score.d.ts +3 -1
  523. package/dist/{types-igV4-sbB.d.ts → types-yDgWDkrJ.d.ts} +60 -34
  524. package/dist/types.d.ts +3 -1
  525. package/dist/types.js +1 -1
  526. package/dist/utility-runtime.d.ts +3 -1
  527. package/dist/verified-recall.js +26 -25
  528. package/dist/who-knows-cli.d.ts +14 -11
  529. package/dist/who-knows-cli.js +27 -26
  530. package/dist/who-knows.d.ts +14 -11
  531. package/dist/who-knows.js +26 -25
  532. package/dist/write-envelope.d.ts +5 -2
  533. package/dist/write-envelope.js +3 -1
  534. package/package.json +2 -2
  535. package/src/access-category-alias.test.ts +216 -0
  536. package/src/access-mcp.test.ts +73 -0
  537. package/src/access-mcp.ts +6 -6
  538. package/src/access-observe-write-surface.ts +19 -4
  539. package/src/access-offline-manifest.ts +297 -16
  540. package/src/access-recall-surface.ts +5 -5
  541. package/src/access-schema.ts +76 -7
  542. package/src/access-service.ts +11 -2
  543. package/src/activity/config.test.ts +124 -1
  544. package/src/activity/config.ts +150 -18
  545. package/src/activity/index.ts +3 -0
  546. package/src/activity/journal-extract-storage.test.ts +129 -0
  547. package/src/activity/journal-extract.test.ts +314 -0
  548. package/src/activity/journal-extract.ts +247 -0
  549. package/src/activity/journal-heading.test.ts +24 -1
  550. package/src/activity/journal-heading.ts +36 -0
  551. package/src/activity/journal-read.test.ts +242 -0
  552. package/src/activity/journal-read.ts +183 -0
  553. package/src/activity/journal-source.test.ts +15 -15
  554. package/src/activity/journal-source.ts +21 -14
  555. package/src/activity/journal-state.lock-worker.ts +30 -0
  556. package/src/activity/journal-state.test.ts +144 -0
  557. package/src/activity/journal-state.ts +107 -0
  558. package/src/activity/journal-strip.test.ts +106 -52
  559. package/src/activity/journal-strip.ts +35 -10
  560. package/src/activity/journal-vault-integration.test.ts +230 -0
  561. package/src/activity/journal-vault-provenance.test.ts +9 -7
  562. package/src/activity/journal-vault-provenance.ts +4 -10
  563. package/src/activity/journal-vault-read.test.ts +3 -2
  564. package/src/activity/journal-vault-read.ts +9 -139
  565. package/src/activity/journal.test.ts +74 -23
  566. package/src/activity/runner.test.ts +116 -1
  567. package/src/activity/runner.ts +25 -0
  568. package/src/activity/scheduler.ts +4 -0
  569. package/src/activity/store.test.ts +18 -0
  570. package/src/activity/store.ts +14 -0
  571. package/src/activity/sync-registration.ts +4 -0
  572. package/src/activity/timeline/analysis-metadata.ts +2 -0
  573. package/src/activity/timeline/analysis-provider.ts +140 -0
  574. package/src/activity/timeline/analysis-run.test.ts +419 -0
  575. package/src/activity/timeline/analysis-run.ts +106 -0
  576. package/src/activity/timeline/analysis.ts +66 -37
  577. package/src/activity/timeline/corrections.ts +9 -0
  578. package/src/activity/timeline/index.ts +3 -0
  579. package/src/activity/timeline/query.test.ts +71 -0
  580. package/src/activity/timeline/query.ts +57 -8
  581. package/src/activity/timeline/regenerate.test.ts +505 -0
  582. package/src/activity/timeline/regenerate.ts +373 -0
  583. package/src/activity/types.ts +40 -5
  584. package/src/adapters/grok-opencode.test.ts +146 -0
  585. package/src/adapters/grok.ts +53 -0
  586. package/src/adapters/index.ts +2 -0
  587. package/src/adapters/opencode.ts +52 -0
  588. package/src/adapters/registry.ts +4 -0
  589. package/src/cli-fallback.ts +13 -4
  590. package/src/config.test.ts +27 -1
  591. package/src/config.ts +17 -1
  592. package/src/dedup/merge.test.ts +732 -25
  593. package/src/fallback-llm.test.ts +53 -0
  594. package/src/fallback-llm.ts +12 -0
  595. package/src/index.ts +2 -0
  596. package/src/local-llm-config.ts +25 -0
  597. package/src/local-llm.ts +3 -1
  598. package/src/orchestration/dependency-propagation-recovery-replay.ts +1 -1
  599. package/src/orchestration/extraction-persist-deps.ts +9 -0
  600. package/src/orchestration/extraction-persist-promotion.test.ts +265 -6
  601. package/src/orchestration/extraction-persist-promotion.ts +42 -3
  602. package/src/orchestration/extraction-persist.ts +3 -3
  603. package/src/orchestration/harmonic-construction-persist.test.ts +115 -4
  604. package/src/orchestration/harmonic-construction-persist.ts +34 -6
  605. package/src/orchestration/maintenance.ts +1 -0
  606. package/src/orchestration/orchestrator-helpers.ts +6 -0
  607. package/src/orchestration/recall-entry.ts +16 -0
  608. package/src/orchestration/recall-internal-deps.ts +14 -0
  609. package/src/orchestration/recall-internal.ts +41 -58
  610. package/src/orchestration/recall-result-formatter.ts +11 -1
  611. package/src/orchestration/recall-search-pipeline.ts +121 -11
  612. package/src/orchestration/recall-state-view-pipeline.test.ts +211 -0
  613. package/src/orchestration/semantic-merge-commit-effects.ts +76 -17
  614. package/src/orchestration/semantic-merge-persist.ts +121 -16
  615. package/src/orchestration/semantic-merge-promotion-payload.ts +133 -54
  616. package/src/orchestrator.ts +7 -35
  617. package/src/providers/codex-subscription.test.ts +666 -0
  618. package/src/providers/codex-subscription.ts +743 -0
  619. package/src/recall-disclosure.test.ts +20 -0
  620. package/src/recall-state-view-admission.ts +114 -0
  621. package/src/recall-state-view-asof.test.ts +176 -0
  622. package/src/recall-state-view-call.test.ts +175 -0
  623. package/src/recall-state-view-config.test.ts +16 -0
  624. package/src/recall-state-view-widen.test.ts +70 -0
  625. package/src/recall-state-view-widen.ts +28 -7
  626. package/src/recall-state-view-wire.ts +3 -1
  627. package/src/recall-state-view-zero-diff.test.ts +20 -11
  628. package/src/recall-state-view.test.ts +142 -0
  629. package/src/recall-state-view.ts +72 -24
  630. package/src/recall-xray-renderer.test.ts +27 -0
  631. package/src/recall-xray-renderer.ts +4 -0
  632. package/src/recall-xray.ts +13 -0
  633. package/src/reconcile/cursor.ts +23 -33
  634. package/src/reconcile/manifest.ts +96 -11
  635. package/src/reconcile-identity-cache.test.ts +378 -0
  636. package/src/runtime/child-process.ts +1 -1
  637. package/src/storage/cas-revision-host.ts +75 -0
  638. package/src/storage/cas-revision-store.test.ts +459 -0
  639. package/src/storage/cas-revision-store.ts +661 -0
  640. package/src/storage/deletion-revision-store.ts +80 -6
  641. package/src/storage/tombstone-blocked-capture-index.ts +15 -0
  642. package/src/storage/tombstone-blocked-capture-mutation.ts +67 -7
  643. package/src/storage/tombstone-blocked-capture-sync.ts +55 -20
  644. package/src/storage-contract/failure-semantics.test.ts +1 -1
  645. package/src/storage-frontmatter-cas.test.ts +698 -1
  646. package/src/storage-replay.test.ts +166 -3
  647. package/src/storage.ts +41 -41
  648. package/src/support-passport/card-projection.ts +82 -33
  649. package/src/temporal-supersession.test.ts +10 -10
  650. package/src/types.ts +10 -29
  651. package/src/write-envelope.ts +1 -1
  652. package/dist/chunk-22FVR2KE.js.map +0 -1
  653. package/dist/chunk-2C3S7J2S.js.map +0 -1
  654. package/dist/chunk-2JVJ7UHC.js.map +0 -1
  655. package/dist/chunk-2QSZNTDO.js +0 -56
  656. package/dist/chunk-2QSZNTDO.js.map +0 -1
  657. package/dist/chunk-3QQTXYZ6.js.map +0 -1
  658. package/dist/chunk-5VCDKQWQ.js +0 -560
  659. package/dist/chunk-5VCDKQWQ.js.map +0 -1
  660. package/dist/chunk-A7XEPMQ6.js.map +0 -1
  661. package/dist/chunk-BLUYQFRH.js.map +0 -1
  662. package/dist/chunk-E6JA6XWY.js.map +0 -1
  663. package/dist/chunk-EEOUMG3J.js.map +0 -1
  664. package/dist/chunk-FDLDOEO6.js.map +0 -1
  665. package/dist/chunk-FYDW33ZB.js +0 -13
  666. package/dist/chunk-H272ZPQ3.js.map +0 -1
  667. package/dist/chunk-HV7OY4DM.js.map +0 -1
  668. package/dist/chunk-HVAEXYPL.js.map +0 -1
  669. package/dist/chunk-JEIXTYVG.js.map +0 -1
  670. package/dist/chunk-LRICZIGN.js +0 -52
  671. package/dist/chunk-LRICZIGN.js.map +0 -1
  672. package/dist/chunk-MFDTVQJX.js.map +0 -1
  673. package/dist/chunk-N7RWREIQ.js.map +0 -1
  674. package/dist/chunk-O75CRYGF.js.map +0 -1
  675. package/dist/chunk-Q726HSJO.js.map +0 -1
  676. package/dist/chunk-QOIOACIE.js.map +0 -1
  677. package/dist/chunk-SEDEKFYQ.js +0 -1
  678. package/dist/chunk-SO7SV523.js.map +0 -1
  679. package/dist/chunk-TLPZ6MKZ.js.map +0 -1
  680. package/dist/chunk-UGPUYIET.js.map +0 -1
  681. package/src/activity/journal-mode.test.ts +0 -32
  682. package/src/activity/journal-mode.ts +0 -20
  683. /package/dist/{capsule-merge-IPG4IOFP.js.map → capsule-merge-ZCXUPLNJ.js.map} +0 -0
  684. /package/dist/{chunk-CDKHKZL5.js.map → chunk-2524MOWK.js.map} +0 -0
  685. /package/dist/{chunk-RKBLRTNT.js.map → chunk-2YLMUME2.js.map} +0 -0
  686. /package/dist/{chunk-DBQWVT2H.js.map → chunk-3CBI2ZSA.js.map} +0 -0
  687. /package/dist/{chunk-MWFGUESQ.js.map → chunk-3FJKJ5UZ.js.map} +0 -0
  688. /package/dist/{chunk-NZXEK3UF.js.map → chunk-3Q3N35W7.js.map} +0 -0
  689. /package/dist/{chunk-YYGZJPOK.js.map → chunk-42DJ235G.js.map} +0 -0
  690. /package/dist/{chunk-JTH2SE6B.js.map → chunk-6J6K3STG.js.map} +0 -0
  691. /package/dist/{chunk-H4VH5VIB.js.map → chunk-776GVKL7.js.map} +0 -0
  692. /package/dist/{chunk-BUTCAMJM.js.map → chunk-A2YQL2FF.js.map} +0 -0
  693. /package/dist/{chunk-X2NFFBTO.js.map → chunk-A7GQBJP5.js.map} +0 -0
  694. /package/dist/{chunk-CGC5UQCF.js.map → chunk-AKE4GGQ3.js.map} +0 -0
  695. /package/dist/{chunk-B325AGLK.js.map → chunk-AZSKROVQ.js.map} +0 -0
  696. /package/dist/{chunk-I5DZ3WGR.js.map → chunk-BJETIR53.js.map} +0 -0
  697. /package/dist/{chunk-JT3EB7ZL.js.map → chunk-BNGHPYZU.js.map} +0 -0
  698. /package/dist/{chunk-3JVLGJCY.js.map → chunk-C6KRO3SU.js.map} +0 -0
  699. /package/dist/{chunk-5NANRSCD.js.map → chunk-CNV2A557.js.map} +0 -0
  700. /package/dist/{chunk-PBGVVDLY.js.map → chunk-DK4X5B6I.js.map} +0 -0
  701. /package/dist/{chunk-N2ZNPHA3.js.map → chunk-ECKG5WSI.js.map} +0 -0
  702. /package/dist/{chunk-PYLL63BF.js.map → chunk-EEBQFG5E.js.map} +0 -0
  703. /package/dist/{chunk-ET356KSB.js.map → chunk-F4TWWUMP.js.map} +0 -0
  704. /package/dist/{chunk-CLLPJ6QT.js.map → chunk-FQXJAC3T.js.map} +0 -0
  705. /package/dist/{chunk-JGHXXQ2G.js.map → chunk-FVJ4D6L7.js.map} +0 -0
  706. /package/dist/{chunk-DD5JFCWM.js.map → chunk-GCBIXUPT.js.map} +0 -0
  707. /package/dist/{chunk-MN3LK3KN.js.map → chunk-GLZH5VEN.js.map} +0 -0
  708. /package/dist/{chunk-S7T2TY65.js.map → chunk-HC4GFLMQ.js.map} +0 -0
  709. /package/dist/{chunk-EQHDH4C2.js.map → chunk-HUT2JR6I.js.map} +0 -0
  710. /package/dist/{chunk-UUQG7HAD.js.map → chunk-HXSAWV3A.js.map} +0 -0
  711. /package/dist/{chunk-XXIHX75O.js.map → chunk-J7PB5UQ4.js.map} +0 -0
  712. /package/dist/{chunk-LTIZHLV7.js.map → chunk-JR6H5CYS.js.map} +0 -0
  713. /package/dist/{chunk-FCSZ4K2X.js.map → chunk-JR6PP7UM.js.map} +0 -0
  714. /package/dist/{chunk-TCUKRAMK.js.map → chunk-JRWW7GM6.js.map} +0 -0
  715. /package/dist/{chunk-PL7FYKHT.js.map → chunk-L2WQVSKP.js.map} +0 -0
  716. /package/dist/{chunk-JSN44KIB.js.map → chunk-LEMD7WZJ.js.map} +0 -0
  717. /package/dist/{chunk-VZWXFXLX.js.map → chunk-LMCD5W5B.js.map} +0 -0
  718. /package/dist/{chunk-7BMXZCOT.js.map → chunk-LNDLXMH6.js.map} +0 -0
  719. /package/dist/{chunk-EONF76DT.js.map → chunk-LYDJRF45.js.map} +0 -0
  720. /package/dist/{chunk-MKD3OMPS.js.map → chunk-M3MYMWXG.js.map} +0 -0
  721. /package/dist/{chunk-VGXM5B4H.js.map → chunk-MNIPH6LD.js.map} +0 -0
  722. /package/dist/{chunk-6N3TQFZU.js.map → chunk-NN4JEFON.js.map} +0 -0
  723. /package/dist/{chunk-MOZXTRC2.js.map → chunk-OQ7SSRXP.js.map} +0 -0
  724. /package/dist/{chunk-XU6OEECT.js.map → chunk-OQQXGYMX.js.map} +0 -0
  725. /package/dist/{chunk-4MHYKEOM.js.map → chunk-OS2AT2JU.js.map} +0 -0
  726. /package/dist/{chunk-N57A4KPV.js.map → chunk-P3ONDDIJ.js.map} +0 -0
  727. /package/dist/{chunk-R3HKWWUB.js.map → chunk-PHP3MUGF.js.map} +0 -0
  728. /package/dist/{chunk-P3SB5BNT.js.map → chunk-QATYVTP7.js.map} +0 -0
  729. /package/dist/{chunk-LSYDG6MJ.js.map → chunk-QBLDCI6E.js.map} +0 -0
  730. /package/dist/{chunk-KCB7F4J7.js.map → chunk-QURNMKME.js.map} +0 -0
  731. /package/dist/{chunk-XOVKXJEP.js.map → chunk-R3TLVTWW.js.map} +0 -0
  732. /package/dist/{chunk-XXE5P6HJ.js.map → chunk-RRZKTSFG.js.map} +0 -0
  733. /package/dist/{chunk-44T3Y7SZ.js.map → chunk-RUXPVSML.js.map} +0 -0
  734. /package/dist/{chunk-DCJ3YFIC.js.map → chunk-S2ULTQZR.js.map} +0 -0
  735. /package/dist/{chunk-EEC4PCG5.js.map → chunk-SZDLX763.js.map} +0 -0
  736. /package/dist/{chunk-E2ZHGBAK.js.map → chunk-T2JSUEH6.js.map} +0 -0
  737. /package/dist/{chunk-227UFSEQ.js.map → chunk-TFA6HPOA.js.map} +0 -0
  738. /package/dist/{chunk-BA6WOZOT.js.map → chunk-TK4FHQRN.js.map} +0 -0
  739. /package/dist/{chunk-W27OW7AB.js.map → chunk-TKFSXDOB.js.map} +0 -0
  740. /package/dist/{chunk-7K5Q6COX.js.map → chunk-TVVEYCNW.js.map} +0 -0
  741. /package/dist/{chunk-CETXNLEX.js.map → chunk-UDZYNIDJ.js.map} +0 -0
  742. /package/dist/{chunk-H5AFCNGA.js.map → chunk-UJX4I26O.js.map} +0 -0
  743. /package/dist/{chunk-E6TDQRF6.js.map → chunk-UYUCCQ46.js.map} +0 -0
  744. /package/dist/{chunk-OQDPBRQ6.js.map → chunk-VYXDUPYE.js.map} +0 -0
  745. /package/dist/{chunk-ZG74PWRW.js.map → chunk-VZAKYDMJ.js.map} +0 -0
  746. /package/dist/{chunk-NB5BCFUY.js.map → chunk-WHHEPAO3.js.map} +0 -0
  747. /package/dist/{chunk-H3TKENU4.js.map → chunk-WIKO4SCR.js.map} +0 -0
  748. /package/dist/{chunk-TX2UTLXC.js.map → chunk-WPDKBUWX.js.map} +0 -0
  749. /package/dist/{chunk-YFLLGRXO.js.map → chunk-X2QPKLPL.js.map} +0 -0
  750. /package/dist/{chunk-PFFZWDPE.js.map → chunk-XCOV45MO.js.map} +0 -0
  751. /package/dist/{chunk-5BCNEBEN.js.map → chunk-XPJNT6PI.js.map} +0 -0
  752. /package/dist/{chunk-SEDEKFYQ.js.map → chunk-XW2T4QAW.js.map} +0 -0
  753. /package/dist/{chunk-J7HFPA6O.js.map → chunk-Y63ZFP4X.js.map} +0 -0
  754. /package/dist/{chunk-D223ZDQV.js.map → chunk-YEDVOYL2.js.map} +0 -0
  755. /package/dist/{chunk-RC5DXXWC.js.map → chunk-YM7YN37H.js.map} +0 -0
  756. /package/dist/{chunk-BPJNF7J2.js.map → chunk-YNN26CIZ.js.map} +0 -0
  757. /package/dist/{chunk-VLXBE57O.js.map → chunk-YVGXH72Y.js.map} +0 -0
  758. /package/dist/{chunk-YQAXP5AC.js.map → chunk-YXLUTALO.js.map} +0 -0
  759. /package/dist/{chunk-DGGB65KC.js.map → chunk-Z7ACR6MJ.js.map} +0 -0
  760. /package/dist/{chunk-X35W4S3L.js.map → chunk-ZBEGS7OB.js.map} +0 -0
  761. /package/dist/{chunk-XUE46UYW.js.map → chunk-ZLN7AROH.js.map} +0 -0
  762. /package/dist/{chunk-HK32G473.js.map → chunk-ZWEZXVYH.js.map} +0 -0
  763. /package/dist/{contradiction-scan-NOYMFG66.js.map → contradiction-scan-GVD4JJ7B.js.map} +0 -0
  764. /package/dist/{first-start-migration-RC345GPL.js.map → first-start-migration-L3UFX5CU.js.map} +0 -0
  765. /package/dist/{resolution-VKATP2HT.js.map → local-llm-config.js.map} +0 -0
  766. /package/dist/{tier-stats-KA6OZX2C.js.map → tier-stats-VK5PCO2L.js.map} +0 -0
@@ -5,18 +5,20 @@ import {
5
5
  rejectSymlinkPath,
6
6
  renderFrontmatter,
7
7
  writeBundleFile
8
- } from "./chunk-H5AFCNGA.js";
8
+ } from "./chunk-UJX4I26O.js";
9
9
  import {
10
10
  parseOaiMemCitation
11
11
  } from "./chunk-D24OXEPB.js";
12
12
  import {
13
13
  resolveNamespaceChildRoot
14
14
  } from "./chunk-3UXOZBHV.js";
15
+ import {
16
+ StorageManager
17
+ } from "./chunk-5VAF4ID4.js";
15
18
  import {
16
19
  OKF_PROFILE_TYPE,
17
- StorageManager,
18
20
  okfTypeForMemory
19
- } from "./chunk-HV7OY4DM.js";
21
+ } from "./chunk-PCEYGOSL.js";
20
22
  import {
21
23
  normalizeProjectionPreview
22
24
  } from "./chunk-SCU65EZI.js";
@@ -270,4 +272,4 @@ export {
270
272
  exportOkfBundle,
271
273
  firstHeading
272
274
  };
273
- //# sourceMappingURL=chunk-DB5TGMLZ.js.map
275
+ //# sourceMappingURL=chunk-JZ2CHRLB.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/transfer/export-okf.ts"],"sourcesContent":["import { mkdirSync, rmSync } from \"node:fs\";\nimport { mkdtemp } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { parseOaiMemCitation } from \"../citations.js\";\nimport { inferMemoryStatus } from \"../memory-lifecycle-ledger-utils.js\";\nimport { normalizeProjectionPreview } from \"../memory-projection-format.js\";\nimport { lintOkfDir } from \"../okf/lint.js\";\nimport { okfTypeForMemory, OKF_PROFILE_TYPE } from \"../okf/type-mapping.js\";\nimport { resolveNamespaceChildRoot } from \"../namespaces/path.js\";\nimport {\n OKF_EXPORT_VERSION,\n publishBundle,\n renderFrontmatter,\n rejectSymlinkPath,\n writeBundleFile,\n} from \"../okf/render.js\";\n// Re-exported for the existing `@remnic/core/export-okf` consumers and tests\n// (one public surface; the value itself now lives in okf/render.ts).\nexport { OKF_EXPORT_VERSION };\nimport { StorageManager } from \"../storage.js\";\nimport type { MemoryFile, MemoryLink, MemoryStatus } from \"../types.js\";\n\n// Shared bundle mechanics (frontmatter, publish, symlink guard, file write)\n// live in ../okf/render.ts — one source of truth for every OKF exporter.\nexport const OKF_LOG_TRUNCATION_MARKER = \"<!-- okf-log-truncated -->\";\nexport const DEFAULT_OKF_LOG_MAX_ENTRIES = 500;\n\nconst MEMORY_STATUSES: readonly MemoryStatus[] = [\n \"active\",\n \"pending_review\",\n \"rejected\",\n \"quarantined\",\n \"superseded\",\n \"archived\",\n \"forgotten\",\n];\n\nexport interface ExportOkfOptions {\n memoryDir: string;\n /**\n * Optional namespace segment. Resolved here, once, through the shared\n * containment guard: both CLI entry points used to join the raw operator\n * value onto `memoryDir/namespaces`, so `--namespace ../../..` escaped the\n * namespace root and exported an arbitrary tree (rule 9 — one resolver, not\n * a per-caller guard).\n */\n namespace?: string;\n outDir: string;\n includeStatus?: readonly string[];\n includeCategories?: readonly string[];\n excludeTags?: readonly string[];\n includeProfile?: boolean;\n includeWearables?: boolean;\n includeLog?: boolean;\n logMaxEntries?: number;\n force?: boolean;\n}\n\nexport interface ExportOkfResult {\n exported: number;\n excluded: number;\n byCategory: Record<string, number>;\n plaintextWarning: boolean;\n}\n\nexport function parseIncludeStatus(raw: unknown): MemoryStatus[] {\n const values = splitCsv(raw);\n if (values.length === 0) return [\"active\"];\n const allowed = new Set<string>(MEMORY_STATUSES);\n for (const value of values) {\n if (!allowed.has(value)) {\n throw new Error(`invalid --include-status ${value}; allowed: ${MEMORY_STATUSES.join(\", \")}`);\n }\n }\n return values as MemoryStatus[];\n}\n\nexport async function exportOkfBundle(opts: ExportOkfOptions): Promise<ExportOkfResult> {\n const outDir = path.resolve(opts.outDir);\n rejectSymlinkPath(outDir);\n const namespace = (opts.namespace ?? \"\").trim();\n const memoryDir = namespace\n ? resolveNamespaceChildRoot(opts.memoryDir, namespace, \"--namespace\")\n : opts.memoryDir;\n const includeStatus = new Set(parseIncludeStatus(opts.includeStatus));\n const includeCategories = opts.includeCategories?.length ? new Set(opts.includeCategories) : null;\n const excludeTags = new Set(opts.excludeTags ?? []);\n const storage = new StorageManager(memoryDir);\n const memories = await storage.readAllMemories();\n const included: MemoryFile[] = [];\n let excluded = 0;\n for (const memory of memories) {\n const rel = toRel(memory.path, memoryDir);\n if (!opts.includeWearables && rel.startsWith(\"wearables/\")) {\n excluded += 1;\n continue;\n }\n const status = inferMemoryStatus(memory.frontmatter, memory.path);\n if (!includeStatus.has(status)) {\n excluded += 1;\n continue;\n }\n if (includeCategories && !includeCategories.has(memory.frontmatter.category)) {\n excluded += 1;\n continue;\n }\n if ((memory.frontmatter.tags ?? []).some((tag) => excludeTags.has(tag))) {\n excluded += 1;\n continue;\n }\n included.push(memory);\n }\n included.sort((a, b) => toRel(a.path, memoryDir).localeCompare(toRel(b.path, memoryDir)));\n\n // Stage inside the destination's parent, not the OS temp dir: publishBundle\n // finishes with a rename, and a rename across filesystems fails with EXDEV\n // whenever --out lives on a different mount than /tmp.\n mkdirSync(path.dirname(outDir), { recursive: true });\n const staging = await mkdtemp(path.join(path.dirname(outDir), \".remnic-okf-export-\"));\n const byCategory: Record<string, number> = {};\n const idToRel = new Map<string, string>();\n for (const memory of included) {\n const rel = toRel(memory.path, memoryDir);\n idToRel.set(memory.frontmatter.id, rel);\n }\n for (const memory of included) {\n const rel = toRel(memory.path, memoryDir);\n const rendered = renderMemory(memory, rel, idToRel);\n writeBundleFile(staging, rel, rendered);\n const category = memory.frontmatter.category;\n byCategory[category] = (byCategory[category] ?? 0) + 1;\n }\n\n if (opts.includeProfile) {\n try {\n const profile = await storage.readProfile();\n if (profile) {\n writeBundleFile(\n staging,\n \"profile.md\",\n renderFrontmatter({\n type: OKF_PROFILE_TYPE,\n title: \"User Profile\",\n timestamp: new Date(0).toISOString(),\n }) + profile.replace(/^\\uFEFF/, \"\"),\n );\n }\n } catch {\n // Profile is optional even when requested.\n }\n }\n\n if (opts.includeLog) {\n const events = await storage.readAllMemoryLifecycleEvents();\n writeBundleFile(staging, \"log.md\", renderLog(events, idToRel, opts.logMaxEntries ?? DEFAULT_OKF_LOG_MAX_ENTRIES));\n }\n\n writeIndexes(staging, included, memoryDir);\n const lint = lintOkfDir(staging);\n const blocking = lint.findings.filter((f) => f.code !== \"skipped_encrypted\" && f.code !== \"reserved_basename\");\n if (blocking.length > 0) {\n rmSync(staging, { recursive: true, force: true });\n throw new Error(`OKF export failed lint: ${blocking.map((f) => `${f.file}: ${f.message}`).join(\"; \")}`);\n }\n\n publishBundle(staging, outDir, opts.force === true);\n return {\n exported: included.length,\n excluded,\n byCategory,\n plaintextWarning: true,\n };\n}\n\n\nfunction renderMemory(memory: MemoryFile, rel: string, idToRel: Map<string, string>): string {\n const fm = memory.frontmatter;\n const title = firstHeading(memory.content) ?? `${humanize(fm.category)} ${fm.created.slice(0, 10)}`;\n const type = fm.type ?? okfTypeForMemory(fm);\n const fields: Record<string, unknown> = {\n ...fm,\n type,\n title,\n description: normalizeProjectionPreview(memory.content),\n tags: fm.tags ?? [],\n timestamp: fm.updated,\n };\n if (fm.artifactType) fields.resource = rel;\n let body = memory.content.trim();\n const citation = parseOaiMemCitation(body);\n if (citation) {\n const start = body.indexOf(\"<oai-mem-citation>\");\n const end = body.indexOf(\"</oai-mem-citation>\");\n if (start >= 0 && end > start) {\n body = `${body.slice(0, start).trimEnd()}\\n\\n${body.slice(end + \"</oai-mem-citation>\".length).trimStart()}`.trim();\n }\n const lines = citation.entries.map((entry, index) => `${index + 1}. [${entry.path}](${entry.path})`);\n body = `${body}\\n\\n# Citations\\n\\n${lines.join(\"\\n\")}\\n`;\n }\n const links = fm.links ?? [];\n if (links.length > 0) {\n body += `\\n# Related\\n\\n${links.map((link) => renderRelated(link, idToRel)).join(\"\\n\")}\\n`;\n }\n return renderFrontmatter(fields) + body + (body.endsWith(\"\\n\") ? \"\" : \"\\n\");\n}\n\nfunction renderRelated(link: MemoryLink, idToRel: Map<string, string>): string {\n const target = idToRel.get(link.targetId) ?? link.targetId;\n const href = target.startsWith(\"/\") ? target : `/${target}`;\n return `- ${link.linkType}: [${link.targetId}](${href})`;\n}\n\nfunction writeIndexes(root: string, memories: MemoryFile[], memoryDir: string): void {\n const groups = new Map<string, MemoryFile[]>();\n for (const memory of memories) {\n const rel = toRel(memory.path, memoryDir);\n const dir = path.posix.dirname(rel);\n const key = dir === \".\" ? \"\" : dir.split(\"/\")[0] ?? \"\";\n const list = groups.get(key) ?? [];\n list.push(memory);\n groups.set(key, list);\n }\n const sections = [...groups.keys()].sort().map((key) => {\n const heading = key === \"\" ? \"Root\" : humanize(key);\n const lines = (groups.get(key) ?? [])\n .sort((a, b) => toRel(a.path, memoryDir).localeCompare(toRel(b.path, memoryDir)))\n .map((memory) => {\n const rel = toRel(memory.path, memoryDir);\n const title = firstHeading(memory.content) ?? memory.frontmatter.id;\n const description = normalizeProjectionPreview(memory.content);\n return `* [${title}](/${rel}) - ${description}`;\n });\n return `## ${heading}\\n\\n${lines.join(\"\\n\")}`;\n });\n writeBundleFile(root, \"index.md\", `---\\nokf_version: \"${OKF_EXPORT_VERSION}\"\\n---\\n\\n${sections.join(\"\\n\\n\")}\\n`);\n}\n\nfunction renderLog(\n events: Array<{ timestamp?: string; type?: string; action?: string; memoryId?: string }>,\n idToRel: Map<string, string>,\n maxEntries: number,\n): string {\n const sorted = [...events].sort((a, b) => String(b.timestamp ?? \"\").localeCompare(String(a.timestamp ?? \"\")));\n const truncated = sorted.length > maxEntries;\n const kept = sorted.slice(0, maxEntries);\n const byDay = new Map<string, typeof kept>();\n for (const event of kept) {\n const day = String(event.timestamp ?? \"\").slice(0, 10) || \"unknown\";\n const list = byDay.get(day) ?? [];\n list.push(event);\n byDay.set(day, list);\n }\n const days = [...byDay.keys()].sort((a, b) => b.localeCompare(a));\n const parts = [\"# Log\", \"\"];\n for (const day of days) {\n parts.push(`## ${day}`, \"\");\n for (const event of byDay.get(day) ?? []) {\n const action = boldAction(event.type ?? event.action ?? \"Update\");\n const id = event.memoryId;\n const rel = id ? idToRel.get(id) : undefined;\n const target = rel ? `[${id}](/${rel})` : id ?? \"\";\n parts.push(`- **${action}** ${target}`.trimEnd());\n }\n parts.push(\"\");\n }\n if (truncated) parts.push(OKF_LOG_TRUNCATION_MARKER, \"\");\n return `${parts.join(\"\\n\")}\\n`;\n}\n\nfunction boldAction(raw: string): string {\n const lower = raw.toLowerCase();\n if (lower.includes(\"create\") || lower.includes(\"add\")) return \"Creation\";\n if (lower.includes(\"deprecat\") || lower.includes(\"delete\") || lower.includes(\"archiv\")) return \"Deprecation\";\n return \"Update\";\n}\n\n\nexport function firstHeading(content: string): string | undefined {\n for (const line of content.split(\"\\n\")) {\n // `\\S` makes the capture boundary disjoint from `\\s+`, so the regex\n // cannot backtrack across split points — `\\s+(.+)` was superlinear on\n // whitespace-heavy lines (CodeQL js/polynomial-redos). `.` still excludes\n // \\r\\u2028\\u2029, preserving the skip-line behavior on those lines.\n const match = /^#\\s+(\\S.*)$/.exec(line.trim());\n if (match) return match[1]!.trim();\n }\n return undefined;\n}\n\nfunction humanize(value: string): string {\n return value.replace(/[_-]/g, \" \").replace(/\\b\\w/g, (ch) => ch.toUpperCase());\n}\n\n\n\nfunction splitCsv(raw: unknown): string[] {\n if (raw === undefined || raw === null || raw === \"\") return [];\n const parts = Array.isArray(raw) ? raw.map(String) : String(raw).split(\",\");\n return parts.map((part) => part.trim()).filter((part) => part.length > 0);\n}\n\nfunction toRel(abs: string, root: string): string {\n return path.relative(path.resolve(root), path.resolve(abs)).split(path.sep).join(\"/\");\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,WAAW,cAAc;AAClC,SAAS,eAAe;AACxB,OAAO,UAAU;AAuBV,IAAM,4BAA4B;AAClC,IAAM,8BAA8B;AAE3C,IAAM,kBAA2C;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA8BO,SAAS,mBAAmB,KAA8B;AAC/D,QAAM,SAAS,SAAS,GAAG;AAC3B,MAAI,OAAO,WAAW,EAAG,QAAO,CAAC,QAAQ;AACzC,QAAM,UAAU,IAAI,IAAY,eAAe;AAC/C,aAAW,SAAS,QAAQ;AAC1B,QAAI,CAAC,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,CAAC,SAAS,KAAK,SAAS,CAAC;AAC1E;AAEA,SAAS,MAAM,KAAa,MAAsB;AAChD,SAAO,KAAK,SAAS,KAAK,QAAQ,IAAI,GAAG,KAAK,QAAQ,GAAG,CAAC,EAAE,MAAM,KAAK,GAAG,EAAE,KAAK,GAAG;AACtF;","names":[]}
1
+ {"version":3,"sources":["../src/transfer/export-okf.ts"],"sourcesContent":["import { mkdirSync, rmSync } from \"node:fs\";\nimport { mkdtemp } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { parseOaiMemCitation } from \"../citations.js\";\nimport { inferMemoryStatus } from \"../memory-lifecycle-ledger-utils.js\";\nimport { normalizeProjectionPreview } from \"../memory-projection-format.js\";\nimport { lintOkfDir } from \"../okf/lint.js\";\nimport { okfTypeForMemory, OKF_PROFILE_TYPE } from \"../okf/type-mapping.js\";\nimport { resolveNamespaceChildRoot } from \"../namespaces/path.js\";\nimport {\n OKF_EXPORT_VERSION,\n publishBundle,\n renderFrontmatter,\n rejectSymlinkPath,\n writeBundleFile,\n} from \"../okf/render.js\";\n// Re-exported for the existing `@remnic/core/export-okf` consumers and tests\n// (one public surface; the value itself now lives in okf/render.ts).\nexport { OKF_EXPORT_VERSION };\nimport { StorageManager } from \"../storage.js\";\nimport type { MemoryFile, MemoryLink, MemoryStatus } from \"../types.js\";\n\n// Shared bundle mechanics (frontmatter, publish, symlink guard, file write)\n// live in ../okf/render.ts — one source of truth for every OKF exporter.\nexport const OKF_LOG_TRUNCATION_MARKER = \"<!-- okf-log-truncated -->\";\nexport const DEFAULT_OKF_LOG_MAX_ENTRIES = 500;\n\nconst MEMORY_STATUSES: readonly MemoryStatus[] = [\n \"active\",\n \"pending_review\",\n \"rejected\",\n \"quarantined\",\n \"superseded\",\n \"archived\",\n \"forgotten\",\n];\n\nexport interface ExportOkfOptions {\n memoryDir: string;\n /**\n * Optional namespace segment. Resolved here, once, through the shared\n * containment guard: both CLI entry points used to join the raw operator\n * value onto `memoryDir/namespaces`, so `--namespace ../../..` escaped the\n * namespace root and exported an arbitrary tree (rule 9 — one resolver, not\n * a per-caller guard).\n */\n namespace?: string;\n outDir: string;\n includeStatus?: readonly string[];\n includeCategories?: readonly string[];\n excludeTags?: readonly string[];\n includeProfile?: boolean;\n includeWearables?: boolean;\n includeLog?: boolean;\n logMaxEntries?: number;\n force?: boolean;\n}\n\nexport interface ExportOkfResult {\n exported: number;\n excluded: number;\n byCategory: Record<string, number>;\n plaintextWarning: boolean;\n}\n\nexport function parseIncludeStatus(raw: unknown): MemoryStatus[] {\n const values = splitCsv(raw);\n if (values.length === 0) return [\"active\"];\n const allowed = new Set<string>(MEMORY_STATUSES);\n for (const value of values) {\n if (!allowed.has(value)) {\n throw new Error(`invalid --include-status ${value}; allowed: ${MEMORY_STATUSES.join(\", \")}`);\n }\n }\n return values as MemoryStatus[];\n}\n\nexport async function exportOkfBundle(opts: ExportOkfOptions): Promise<ExportOkfResult> {\n const outDir = path.resolve(opts.outDir);\n rejectSymlinkPath(outDir);\n const namespace = (opts.namespace ?? \"\").trim();\n const memoryDir = namespace\n ? resolveNamespaceChildRoot(opts.memoryDir, namespace, \"--namespace\")\n : opts.memoryDir;\n const includeStatus = new Set(parseIncludeStatus(opts.includeStatus));\n const includeCategories = opts.includeCategories?.length ? new Set(opts.includeCategories) : null;\n const excludeTags = new Set(opts.excludeTags ?? []);\n const storage = new StorageManager(memoryDir);\n const memories = await storage.readAllMemories();\n const included: MemoryFile[] = [];\n let excluded = 0;\n for (const memory of memories) {\n const rel = toRel(memory.path, memoryDir);\n if (!opts.includeWearables && rel.startsWith(\"wearables/\")) {\n excluded += 1;\n continue;\n }\n const status = inferMemoryStatus(memory.frontmatter, memory.path);\n if (!includeStatus.has(status)) {\n excluded += 1;\n continue;\n }\n if (includeCategories && !includeCategories.has(memory.frontmatter.category)) {\n excluded += 1;\n continue;\n }\n if ((memory.frontmatter.tags ?? []).some((tag) => excludeTags.has(tag))) {\n excluded += 1;\n continue;\n }\n included.push(memory);\n }\n included.sort((a, b) => toRel(a.path, memoryDir).localeCompare(toRel(b.path, memoryDir)));\n\n // Stage inside the destination's parent, not the OS temp dir: publishBundle\n // finishes with a rename, and a rename across filesystems fails with EXDEV\n // whenever --out lives on a different mount than /tmp.\n mkdirSync(path.dirname(outDir), { recursive: true });\n const staging = await mkdtemp(path.join(path.dirname(outDir), \".remnic-okf-export-\"));\n const byCategory: Record<string, number> = {};\n const idToRel = new Map<string, string>();\n for (const memory of included) {\n const rel = toRel(memory.path, memoryDir);\n idToRel.set(memory.frontmatter.id, rel);\n }\n for (const memory of included) {\n const rel = toRel(memory.path, memoryDir);\n const rendered = renderMemory(memory, rel, idToRel);\n writeBundleFile(staging, rel, rendered);\n const category = memory.frontmatter.category;\n byCategory[category] = (byCategory[category] ?? 0) + 1;\n }\n\n if (opts.includeProfile) {\n try {\n const profile = await storage.readProfile();\n if (profile) {\n writeBundleFile(\n staging,\n \"profile.md\",\n renderFrontmatter({\n type: OKF_PROFILE_TYPE,\n title: \"User Profile\",\n timestamp: new Date(0).toISOString(),\n }) + profile.replace(/^\\uFEFF/, \"\"),\n );\n }\n } catch {\n // Profile is optional even when requested.\n }\n }\n\n if (opts.includeLog) {\n const events = await storage.readAllMemoryLifecycleEvents();\n writeBundleFile(staging, \"log.md\", renderLog(events, idToRel, opts.logMaxEntries ?? DEFAULT_OKF_LOG_MAX_ENTRIES));\n }\n\n writeIndexes(staging, included, memoryDir);\n const lint = lintOkfDir(staging);\n const blocking = lint.findings.filter((f) => f.code !== \"skipped_encrypted\" && f.code !== \"reserved_basename\");\n if (blocking.length > 0) {\n rmSync(staging, { recursive: true, force: true });\n throw new Error(`OKF export failed lint: ${blocking.map((f) => `${f.file}: ${f.message}`).join(\"; \")}`);\n }\n\n publishBundle(staging, outDir, opts.force === true);\n return {\n exported: included.length,\n excluded,\n byCategory,\n plaintextWarning: true,\n };\n}\n\n\nfunction renderMemory(memory: MemoryFile, rel: string, idToRel: Map<string, string>): string {\n const fm = memory.frontmatter;\n const title = firstHeading(memory.content) ?? `${humanize(fm.category)} ${fm.created.slice(0, 10)}`;\n const type = fm.type ?? okfTypeForMemory(fm);\n const fields: Record<string, unknown> = {\n ...fm,\n type,\n title,\n description: normalizeProjectionPreview(memory.content),\n tags: fm.tags ?? [],\n timestamp: fm.updated,\n };\n if (fm.artifactType) fields.resource = rel;\n let body = memory.content.trim();\n const citation = parseOaiMemCitation(body);\n if (citation) {\n const start = body.indexOf(\"<oai-mem-citation>\");\n const end = body.indexOf(\"</oai-mem-citation>\");\n if (start >= 0 && end > start) {\n body = `${body.slice(0, start).trimEnd()}\\n\\n${body.slice(end + \"</oai-mem-citation>\".length).trimStart()}`.trim();\n }\n const lines = citation.entries.map((entry, index) => `${index + 1}. [${entry.path}](${entry.path})`);\n body = `${body}\\n\\n# Citations\\n\\n${lines.join(\"\\n\")}\\n`;\n }\n const links = fm.links ?? [];\n if (links.length > 0) {\n body += `\\n# Related\\n\\n${links.map((link) => renderRelated(link, idToRel)).join(\"\\n\")}\\n`;\n }\n return renderFrontmatter(fields) + body + (body.endsWith(\"\\n\") ? \"\" : \"\\n\");\n}\n\nfunction renderRelated(link: MemoryLink, idToRel: Map<string, string>): string {\n const target = idToRel.get(link.targetId) ?? link.targetId;\n const href = target.startsWith(\"/\") ? target : `/${target}`;\n return `- ${link.linkType}: [${link.targetId}](${href})`;\n}\n\nfunction writeIndexes(root: string, memories: MemoryFile[], memoryDir: string): void {\n const groups = new Map<string, MemoryFile[]>();\n for (const memory of memories) {\n const rel = toRel(memory.path, memoryDir);\n const dir = path.posix.dirname(rel);\n const key = dir === \".\" ? \"\" : dir.split(\"/\")[0] ?? \"\";\n const list = groups.get(key) ?? [];\n list.push(memory);\n groups.set(key, list);\n }\n const sections = [...groups.keys()].sort().map((key) => {\n const heading = key === \"\" ? \"Root\" : humanize(key);\n const lines = (groups.get(key) ?? [])\n .sort((a, b) => toRel(a.path, memoryDir).localeCompare(toRel(b.path, memoryDir)))\n .map((memory) => {\n const rel = toRel(memory.path, memoryDir);\n const title = firstHeading(memory.content) ?? memory.frontmatter.id;\n const description = normalizeProjectionPreview(memory.content);\n return `* [${title}](/${rel}) - ${description}`;\n });\n return `## ${heading}\\n\\n${lines.join(\"\\n\")}`;\n });\n writeBundleFile(root, \"index.md\", `---\\nokf_version: \"${OKF_EXPORT_VERSION}\"\\n---\\n\\n${sections.join(\"\\n\\n\")}\\n`);\n}\n\nfunction renderLog(\n events: Array<{ timestamp?: string; type?: string; action?: string; memoryId?: string }>,\n idToRel: Map<string, string>,\n maxEntries: number,\n): string {\n const sorted = [...events].sort((a, b) => String(b.timestamp ?? \"\").localeCompare(String(a.timestamp ?? \"\")));\n const truncated = sorted.length > maxEntries;\n const kept = sorted.slice(0, maxEntries);\n const byDay = new Map<string, typeof kept>();\n for (const event of kept) {\n const day = String(event.timestamp ?? \"\").slice(0, 10) || \"unknown\";\n const list = byDay.get(day) ?? [];\n list.push(event);\n byDay.set(day, list);\n }\n const days = [...byDay.keys()].sort((a, b) => b.localeCompare(a));\n const parts = [\"# Log\", \"\"];\n for (const day of days) {\n parts.push(`## ${day}`, \"\");\n for (const event of byDay.get(day) ?? []) {\n const action = boldAction(event.type ?? event.action ?? \"Update\");\n const id = event.memoryId;\n const rel = id ? idToRel.get(id) : undefined;\n const target = rel ? `[${id}](/${rel})` : id ?? \"\";\n parts.push(`- **${action}** ${target}`.trimEnd());\n }\n parts.push(\"\");\n }\n if (truncated) parts.push(OKF_LOG_TRUNCATION_MARKER, \"\");\n return `${parts.join(\"\\n\")}\\n`;\n}\n\nfunction boldAction(raw: string): string {\n const lower = raw.toLowerCase();\n if (lower.includes(\"create\") || lower.includes(\"add\")) return \"Creation\";\n if (lower.includes(\"deprecat\") || lower.includes(\"delete\") || lower.includes(\"archiv\")) return \"Deprecation\";\n return \"Update\";\n}\n\n\nexport function firstHeading(content: string): string | undefined {\n for (const line of content.split(\"\\n\")) {\n // `\\S` makes the capture boundary disjoint from `\\s+`, so the regex\n // cannot backtrack across split points — `\\s+(.+)` was superlinear on\n // whitespace-heavy lines (CodeQL js/polynomial-redos). `.` still excludes\n // \\r\\u2028\\u2029, preserving the skip-line behavior on those lines.\n const match = /^#\\s+(\\S.*)$/.exec(line.trim());\n if (match) return match[1]!.trim();\n }\n return undefined;\n}\n\nfunction humanize(value: string): string {\n return value.replace(/[_-]/g, \" \").replace(/\\b\\w/g, (ch) => ch.toUpperCase());\n}\n\n\n\nfunction splitCsv(raw: unknown): string[] {\n if (raw === undefined || raw === null || raw === \"\") return [];\n const parts = Array.isArray(raw) ? raw.map(String) : String(raw).split(\",\");\n return parts.map((part) => part.trim()).filter((part) => part.length > 0);\n}\n\nfunction toRel(abs: string, root: string): string {\n return path.relative(path.resolve(root), path.resolve(abs)).split(path.sep).join(\"/\");\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,WAAW,cAAc;AAClC,SAAS,eAAe;AACxB,OAAO,UAAU;AAuBV,IAAM,4BAA4B;AAClC,IAAM,8BAA8B;AAE3C,IAAM,kBAA2C;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA8BO,SAAS,mBAAmB,KAA8B;AAC/D,QAAM,SAAS,SAAS,GAAG;AAC3B,MAAI,OAAO,WAAW,EAAG,QAAO,CAAC,QAAQ;AACzC,QAAM,UAAU,IAAI,IAAY,eAAe;AAC/C,aAAW,SAAS,QAAQ;AAC1B,QAAI,CAAC,QAAQ,IAAI,KAAK,GAAG;AACvB,YAAM,IAAI,MAAM,4BAA4B,KAAK,cAAc,gBAAgB,KAAK,IAAI,CAAC,EAAE;AAAA,IAC7F;AAAA,EACF;AACA,SAAO;AACT;AAEA,eAAsB,gBAAgB,MAAkD;AACtF,QAAM,SAAS,KAAK,QAAQ,KAAK,MAAM;AACvC,oBAAkB,MAAM;AACxB,QAAM,aAAa,KAAK,aAAa,IAAI,KAAK;AAC9C,QAAM,YAAY,YACd,0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MEMORY_CATEGORY_NAMES,
9
+ isMemoryCategory
10
+ } from "./chunk-LSLCFCCQ.js";
7
11
  import {
8
12
  ACTION_CONFIDENCE_CONTEXT_READINESS,
9
13
  ACTION_CONFIDENCE_RISK_CATEGORIES,
@@ -92,7 +96,14 @@ var recallRequestSchema = z.object({
92
96
  * Include graph edges below `graphTraversalConfidenceFloor` for diagnostic
93
97
  * recall traversal (issue #681). Defaults to false.
94
98
  */
95
- includeLowConfidence: z.boolean().optional()
99
+ includeLowConfidence: z.boolean().optional(),
100
+ /**
101
+ * #1952 — per-call opt-in to state-aware recall views for this recall.
102
+ * ORs with the `recallStateViews` config flag; a change-intent query
103
+ * (e.g. "when did", "used to", "switched") is still required for any
104
+ * effect, so this can never perturb ordinary recalls.
105
+ */
106
+ stateView: z.boolean().optional()
96
107
  });
97
108
  var recallExplainRequestSchema = z.object({
98
109
  sessionKey: sessionKeySchema,
@@ -175,21 +186,37 @@ var deepRecallRequestSchema = z.object({
175
186
  sessionKey: z.string().optional()
176
187
  });
177
188
  var writeContentSchema = z.string().min(1, "content is required").max(5e4);
178
- var categorySchema = z.enum([
179
- "fact",
180
- "preference",
181
- "correction",
182
- "entity",
183
- "decision",
184
- "relationship",
185
- "principle",
186
- "commitment",
187
- "moment",
188
- "skill",
189
- "rule",
190
- "procedure",
191
- "reasoning_trace"
192
- ]).optional();
189
+ var PROJECT_CATEGORY_ALIASES = {
190
+ project: true,
191
+ project_state: true,
192
+ "project-state": true,
193
+ project_update: true
194
+ };
195
+ function coerceProjectCategoryAlias(request) {
196
+ const category = request.category;
197
+ if (category === void 0 || PROJECT_CATEGORY_ALIASES[category] !== true) {
198
+ return { request };
199
+ }
200
+ return { request: { ...request, category: "fact" }, categoryCoercion: { from: category, to: "fact" } };
201
+ }
202
+ function reapplyCategoryCoercion(response, categoryCoercion) {
203
+ if (categoryCoercion !== void 0) {
204
+ return { ...response, categoryCoercion };
205
+ }
206
+ if (response.categoryCoercion === void 0) {
207
+ return response;
208
+ }
209
+ const { categoryCoercion: _stored, ...rest } = response;
210
+ return rest;
211
+ }
212
+ var categorySchema = z.string().superRefine((value, ctx) => {
213
+ if (isMemoryCategory(value)) return;
214
+ if (PROJECT_CATEGORY_ALIASES[value] === true) return;
215
+ ctx.addIssue({
216
+ code: z.ZodIssueCode.custom,
217
+ message: `category must be one of: ${MEMORY_CATEGORY_NAMES.join(", ")}; for project state/facts use "fact"`
218
+ });
219
+ }).optional();
193
220
  var confidenceSchema = z.number().min(0).max(1).optional();
194
221
  var tagsSchema = z.array(z.string().max(256)).max(50).optional();
195
222
  var entityRefSchema = z.string().trim().max(512).optional();
@@ -472,6 +499,8 @@ export {
472
499
  setCodingContextRequestSchema,
473
500
  observeRequestSchema,
474
501
  deepRecallRequestSchema,
502
+ coerceProjectCategoryAlias,
503
+ reapplyCategoryCoercion,
475
504
  memoryStoreRequestSchema,
476
505
  suggestionSubmitRequestSchema,
477
506
  reviewDispositionRequestSchema,
@@ -492,4 +521,4 @@ export {
492
521
  actionConfidenceRequestSchema,
493
522
  validateRequest
494
523
  };
495
- //# sourceMappingURL=chunk-JEIXTYVG.js.map
524
+ //# sourceMappingURL=chunk-L2QLDZJC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/access-schema.ts"],"sourcesContent":["// Request/response schema validation for the Remnic HTTP API.\n// Uses zod for runtime validation — returns structured 400 errors with\n// field-level detail so consumers get clear feedback on malformed requests.\n\nimport { z } from \"zod\";\nimport { isMemoryCategory, MEMORY_CATEGORY_NAMES } from \"./write-envelope.js\";\nimport type { MemoryCategory } from \"./types.js\";\nimport {\n ACTION_CONFIDENCE_CONTEXT_READINESS,\n ACTION_CONFIDENCE_RISK_CATEGORIES,\n ACTION_CONFIDENCE_RULE_KINDS,\n} from \"./action-confidence.js\";\nimport { isValidCapsuleSince } from \"./transfer/capsule-export.js\";\nimport { validateArchiveRelativePath } from \"./transfer/fs-utils.js\";\nimport { CAPSULE_ID_PATTERN } from \"./transfer/types.js\";\nimport {\n OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES,\n OFFLINE_SYNC_MAX_MTIME_MS,\n} from \"./offline-sync.js\";\n\n// ---------------------------------------------------------------------------\n// Error formatting\n// ---------------------------------------------------------------------------\n\nexport interface SchemaValidationError {\n error: string;\n code: \"validation_error\";\n details: Array<{ field: string; message: string }>;\n}\n\nexport function formatZodError(error: z.ZodError): SchemaValidationError {\n return {\n error: \"request validation failed\",\n code: \"validation_error\",\n details: error.issues.map((issue) => ({\n field: issue.path.join(\".\") || \"(root)\",\n message: issue.message,\n })),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Shared fields\n// ---------------------------------------------------------------------------\n\nconst namespaceSchema = z.string().trim().max(256).optional();\nconst sessionKeySchema = z.string().trim().min(1).max(512).optional();\nconst idempotencyKeySchema = z.string().trim().min(1).max(256).optional();\nconst cwdSchema = z.string().trim().min(1, \"cwd must be non-empty when provided\").max(2048).optional();\nconst projectTagSchema = z\n .string()\n .trim()\n .min(1, \"projectTag must be non-empty when provided\")\n .max(256)\n .optional();\nconst deadlineMsSchema = z.number().finite().min(0).max(Number.MAX_SAFE_INTEGER).optional();\nconst dryRunSchema = z.boolean().optional();\nconst schemaVersionSchema = z.number().int().optional();\nconst timeZoneSchema = z\n .string()\n .trim()\n .min(1)\n .max(128)\n .refine((value) => {\n try {\n Intl.DateTimeFormat(undefined, { timeZone: value });\n return true;\n } catch {\n return false;\n }\n }, \"must be a valid IANA timezone\");\n\n// ---------------------------------------------------------------------------\n// Recall\n// ---------------------------------------------------------------------------\n\n/**\n * Coding-agent context (issue #569). Optional payload that connectors may\n * ship with a recall request so the project/branch namespace overlay\n * applies to that recall. All fields are validated per CLAUDE.md #51 —\n * empty-string projectId / rootPath is rejected, not silently accepted.\n */\nexport const codingContextSchema = z\n .object({\n projectId: z.string().trim().min(1, \"codingContext.projectId is required\").max(128),\n branch: z.string().trim().max(256).nullable(),\n rootPath: z.string().trim().min(1, \"codingContext.rootPath is required\").max(1024),\n defaultBranch: z.string().trim().max(256).nullable(),\n })\n .nullable();\n\n/**\n * Recall disclosure depth (issue #677). Mirrors the `RecallDisclosure`\n * type in `types.ts` — keep these in sync. Default-application happens\n * inside `EngramAccessService.recall()`; the schema only accepts/rejects.\n * Invalid values throw a structured 400 instead of silently defaulting,\n * per CLAUDE.md rule 51.\n */\nexport const recallDisclosureSchema = z.enum([\"chunk\", \"section\", \"raw\"]);\n\n/**\n * Tag-match semantics (issue #689). `any` (default when `tags` is provided\n * and `tagMatch` is omitted) admits a result when it carries at least one\n * of the filter tags. `all` requires every filter tag to be present.\n * Schema rejects unknown values up front — never silently defaults\n * (CLAUDE.md rule 51).\n */\nexport const tagMatchSchema = z.enum([\"any\", \"all\"]);\n\nexport const recallRequestSchema = z.object({\n query: z.string().min(1, \"query is required\"),\n sessionKey: sessionKeySchema,\n namespace: namespaceSchema,\n topK: z.number().int().min(0).max(200).optional(),\n mode: z.enum([\"auto\", \"no_recall\", \"minimal\", \"full\", \"graph_mode\"]).optional(),\n includeDebug: z.boolean().optional(),\n idempotencyKey: idempotencyKeySchema,\n disclosure: recallDisclosureSchema.optional(),\n codingContext: codingContextSchema.optional(),\n /** Working directory for auto git-context resolution (issue #569). */\n cwd: cwdSchema,\n /**\n * Arbitrary project tag for non-git-based project scoping (issue #569).\n * Creates a coding context with `projectId: \"tag:<projectTag>\"`.\n */\n projectTag: projectTagSchema,\n /**\n * Historical recall pin (issue #680). ISO 8601 timestamp. The\n * schema only enforces the basic shape; the access service runs\n * `Date.parse` and emits a structured 400 on malformed input\n * (CLAUDE.md rule 51).\n */\n asOf: z.string().trim().min(1, \"asOf must be a non-empty ISO 8601 timestamp\").max(64).optional(),\n /**\n * Free-form recall tag filter (issue #689). When provided, recall results\n * whose frontmatter `tags` do not match the filter are removed before the\n * response is returned. Comparison is case-sensitive exact match.\n */\n tags: z.array(z.string().trim().min(1).max(256)).max(50).optional(),\n /**\n * Match mode for `tags` (issue #689). Defaults to `\"any\"` when `tags` is\n * provided and `tagMatch` is omitted. Ignored when `tags` is absent.\n */\n tagMatch: tagMatchSchema.optional(),\n /**\n * Include graph edges below `graphTraversalConfidenceFloor` for diagnostic\n * recall traversal (issue #681). Defaults to false.\n */\n includeLowConfidence: z.boolean().optional(),\n /**\n * #1952 — per-call opt-in to state-aware recall views for this recall.\n * ORs with the `recallStateViews` config flag; a change-intent query\n * (e.g. \"when did\", \"used to\", \"switched\") is still required for any\n * effect, so this can never perturb ordinary recalls.\n */\n stateView: z.boolean().optional(),\n});\n\nexport const recallExplainRequestSchema = z.object({\n sessionKey: sessionKeySchema,\n namespace: namespaceSchema,\n});\n\n/**\n * Standalone \"set coding context\" request. Used by the HTTP endpoint\n * `POST /engram/v1/coding-context` and the MCP `remnic.set_coding_context`\n * tool (PR 7). `codingContext: null` clears the attached context.\n */\nexport const setCodingContextRequestSchema = z\n .object({\n sessionKey: z.string().trim().min(1, \"sessionKey is required\").max(512),\n codingContext: codingContextSchema.optional(),\n /**\n * Project tag shorthand for non-git-based project scoping. When\n * `codingContext` is omitted, this becomes\n * `{ projectId: \"tag:<projectTag>\", branch: null, rootPath: \"tag:<projectTag>\", defaultBranch: null }`.\n */\n projectTag: z.string().trim().min(1, \"projectTag must be non-empty when provided\").max(256).optional(),\n })\n .superRefine((value, ctx) => {\n if (value.codingContext === undefined && value.projectTag === undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"codingContext or projectTag is required\",\n path: [\"codingContext\"],\n });\n }\n });\n\n// ---------------------------------------------------------------------------\n// Observe\n// ---------------------------------------------------------------------------\n\nconst messageSchema = z.object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().min(1, \"message content must be non-empty\"),\n sourceFormat: z\n .enum([\"openai\", \"anthropic\", \"openclaw\", \"pi\", \"lossless-claw\", \"remnic\"])\n .nullable()\n .optional(),\n rawContent: z.unknown().nullable().optional(),\n parts: z\n .array(\n z.object({\n ordinal: z.number().int().min(0).nullable().optional(),\n kind: z.enum([\n \"text\",\n \"tool_call\",\n \"tool_result\",\n \"patch\",\n \"file_read\",\n \"file_write\",\n \"step_start\",\n \"step_finish\",\n \"snapshot\",\n \"retry\",\n ]),\n payload: z.record(z.string(), z.unknown()),\n toolName: z.string().nullable().optional(),\n tool_name: z.string().nullable().optional(),\n filePath: z.string().nullable().optional(),\n file_path: z.string().nullable().optional(),\n createdAt: z.string().nullable().optional(),\n created_at: z.string().nullable().optional(),\n }),\n )\n .nullable()\n .optional(),\n});\n\nexport const observeRequestSchema = z.object({\n sessionKey: z.string().trim().min(1, \"sessionKey is required\").max(512),\n messages: z.array(messageSchema).min(1, \"messages must be a non-empty array\"),\n namespace: namespaceSchema,\n skipExtraction: z.boolean().optional(),\n /**\n * Optional idempotency key for server-side dedup of retried observe POSTs\n * (issue #1649). A retry that reaches the daemon after the first attempt\n * already processed is replayed from cache instead of re-ingested. When the\n * key is reused with a DIFFERENT payload the request is rejected as a\n * conflict (same contract as memory_store/suggestion_submit).\n */\n idempotencyKey: idempotencyKeySchema,\n /** Working directory for auto git-context resolution (issue #569). */\n cwd: cwdSchema,\n /**\n * Arbitrary project tag for non-git-based project scoping (issue #569).\n * Creates a coding context with `projectId: \"tag:<projectTag>\"`.\n */\n projectTag: projectTagSchema,\n});\n\n// ---------------------------------------------------------------------------\n// Deep recall (issue #2332)\n// ---------------------------------------------------------------------------\n\nexport const deepRecallRequestSchema = z.object({\n query: z.string().trim().min(1, \"query is required\").max(2000),\n /** Optional policy-step ceiling; validated against the configured maximum in the service. */\n maxSteps: z.union([z.number().int().min(0), z.string()]).optional(),\n namespace: namespaceSchema,\n sessionKey: z.string().optional(),\n});\n\n// ---------------------------------------------------------------------------\n// Memory store / suggestion submit\n// ---------------------------------------------------------------------------\n\nconst writeContentSchema = z.string().min(1, \"content is required\").max(50000);\n/**\n * #2780: the canonical category set stays authoritative (`isMemoryCategory`),\n * with exactly four admitted input-compat aliases — the project-shaped\n * spellings fleet telemetry actually shows (`project`, `project_state`,\n * `project-state`, `project_update`) — for a project-shaped category that\n * does not exist. Exact match only, no case folding: `Project_State` and\n * near-misses like `projection` reject like any other invalid category.\n * Aliases are NOT enum members: the write-surface funnel coerces them to\n * \"fact\" and reports the coercion on the response. Everything else rejects\n * naming the full valid set plus a \"use fact\" hint so callers learn the\n * canonical name.\n */\nconst PROJECT_CATEGORY_ALIASES: Record<string, true> = {\n project: true,\n project_state: true,\n \"project-state\": true,\n project_update: true,\n};\n\nexport interface CategoryAliasCoercion {\n from: string;\n to: \"fact\";\n}\n\nexport function coerceProjectCategoryAlias<T extends { category?: string }>(\n request: T,\n): { request: T; categoryCoercion?: CategoryAliasCoercion } {\n const category = request.category;\n if (category === undefined || PROJECT_CATEGORY_ALIASES[category] !== true) {\n return { request };\n }\n return { request: { ...request, category: \"fact\" }, categoryCoercion: { from: category, to: \"fact\" } };\n}\n\n/**\n * #2780 fix B: an idempotent replay returns the FIRST request's stored\n * response, whose coercion note names that request's spelling. Rewrite the\n * note from the CURRENT raw request so every response identifies what its\n * caller actually sent; the stored idempotent result is reused untouched.\n */\nexport function reapplyCategoryCoercion<T extends { categoryCoercion?: CategoryAliasCoercion }>(\n response: T,\n categoryCoercion: CategoryAliasCoercion | undefined,\n): T {\n if (categoryCoercion !== undefined) {\n return { ...response, categoryCoercion };\n }\n if (response.categoryCoercion === undefined) {\n return response;\n }\n const { categoryCoercion: _stored, ...rest } = response;\n return rest as T;\n}\n\nconst categorySchema = (\n z\n .string()\n .superRefine((value, ctx) => {\n if (isMemoryCategory(value)) return;\n if (PROJECT_CATEGORY_ALIASES[value] === true) return;\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `category must be one of: ${MEMORY_CATEGORY_NAMES.join(\", \")}; for project state/facts use \"fact\"`,\n });\n })\n .optional() as unknown as z.ZodType<MemoryCategory | undefined, z.ZodTypeDef, MemoryCategory | undefined>\n);\nconst confidenceSchema = z.number().min(0).max(1).optional();\nconst tagsSchema = z.array(z.string().max(256)).max(50).optional();\nconst entityRefSchema = z.string().trim().max(512).optional();\nconst ttlSchema = z.string().trim().max(128).optional();\nconst sourceReasonSchema = z.string().trim().max(2000).optional();\n\nexport const memoryStoreRequestSchema = z.object({\n schemaVersion: schemaVersionSchema,\n idempotencyKey: idempotencyKeySchema,\n dryRun: dryRunSchema,\n sessionKey: sessionKeySchema,\n content: writeContentSchema,\n category: categorySchema,\n confidence: confidenceSchema,\n namespace: namespaceSchema,\n tags: tagsSchema,\n entityRef: entityRefSchema,\n ttl: ttlSchema,\n sourceReason: sourceReasonSchema,\n // Git/project context for project-scoped writes (#1434). When no explicit\n // `namespace` is given, these route the write to the same project namespace\n // recall/observe resolve from `cwd`/`projectTag` (issue #569, rule 42). Also\n // lets MCP clients that auto-inject `cwd` (e.g. Pi MCPorter) call write tools.\n cwd: cwdSchema,\n projectTag: projectTagSchema,\n});\n\nexport const suggestionSubmitRequestSchema = memoryStoreRequestSchema;\n\n// ---------------------------------------------------------------------------\n// Review disposition\n// ---------------------------------------------------------------------------\n\nexport const reviewDispositionRequestSchema = z.object({\n memoryId: z.string().trim().min(1, \"memoryId is required\"),\n status: z.enum([\n \"active\", \"pending_review\", \"quarantined\", \"rejected\", \"superseded\", \"archived\",\n ]),\n reasonCode: z.string().trim().min(1, \"reasonCode is required\"),\n namespace: namespaceSchema,\n});\n\n// ---------------------------------------------------------------------------\n// Trust-zone promote\n// ---------------------------------------------------------------------------\n\nexport const trustZonePromoteRequestSchema = z.object({\n recordId: z.string().trim().min(1, \"recordId is required\"),\n targetZone: z.enum([\"working\", \"trusted\"], {\n errorMap: () => ({ message: \"targetZone must be 'working' or 'trusted'\" }),\n }),\n promotionReason: z.string().trim().min(1, \"promotionReason is required\"),\n recordedAt: z.string().trim().optional(),\n summary: z.string().trim().max(5000).optional(),\n dryRun: dryRunSchema,\n namespace: namespaceSchema,\n});\n\n// ---------------------------------------------------------------------------\n// Trust-zone demo-seed\n// ---------------------------------------------------------------------------\n\nexport const trustZoneDemoSeedRequestSchema = z.object({\n scenario: z.string().trim().max(256).optional(),\n recordedAt: z.string().trim().optional(),\n dryRun: dryRunSchema,\n namespace: namespaceSchema,\n});\n\n// ---------------------------------------------------------------------------\n// LCM search\n// ---------------------------------------------------------------------------\n\nexport const lcmSearchRequestSchema = z.object({\n query: z.string().min(1, \"query is required\"),\n sessionKey: sessionKeySchema,\n sessionPrefix: z.string().trim().min(1).max(512).optional(),\n namespace: namespaceSchema,\n limit: z.number().int().min(1).max(100).optional(),\n});\n\nexport const lcmCompactionFlushRequestSchema = z\n .object({\n sessionKey: z.string().trim().min(1, \"sessionKey is required\").max(512),\n namespace: namespaceSchema,\n cwd: cwdSchema,\n projectTag: projectTagSchema,\n /**\n * Optional multi-namespace flush used by delegate lifecycle replay. The\n * server handles the whole list as one quota-counted write.\n */\n namespaces: z.array(z.string().trim().max(256)).min(1).max(64).optional(),\n })\n .superRefine((value, ctx) => {\n if (value.namespace !== undefined && value.namespaces !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"namespace and namespaces are mutually exclusive\",\n path: [\"namespaces\"],\n });\n }\n if (\n value.namespaces !== undefined &&\n new Set(value.namespaces).size !== value.namespaces.length\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"namespaces must not contain duplicates\",\n path: [\"namespaces\"],\n });\n }\n });\n\nexport const extractionForceFlushRequestSchema = z.object({\n sessionKey: z.string().trim().min(1, \"sessionKey is required\").max(512),\n namespace: namespaceSchema,\n cwd: cwdSchema,\n projectTag: projectTagSchema,\n deadlineMs: deadlineMsSchema,\n});\n\nexport const lcmCompactionRecordRequestSchema = z.object({\n sessionKey: z.string().trim().min(1, \"sessionKey is required\").max(512),\n namespace: namespaceSchema,\n tokensBefore: z.number().int().min(0, \"tokensBefore must be a non-negative integer\"),\n tokensAfter: z.number().int().min(0, \"tokensAfter must be a non-negative integer\"),\n});\n\n// ---------------------------------------------------------------------------\n// Day summary\n// ---------------------------------------------------------------------------\n\nexport const daySummaryRequestSchema = z.object({\n memories: z.string().max(100000).optional(),\n sessionKey: sessionKeySchema,\n namespace: namespaceSchema,\n timeZone: timeZoneSchema.optional(),\n});\n\n// ---------------------------------------------------------------------------\n// Capsule export\n// ---------------------------------------------------------------------------\n\nconst capsuleTopLevelSegmentSchema = z\n .string()\n .trim()\n .min(1)\n .max(128)\n .refine(\n (value) => !value.includes(\"/\") && !value.includes(\"\\\\\"),\n \"must be a top-level directory name without path separators\",\n );\n\nconst capsulePeerIdSchema = z\n .string()\n .trim()\n .min(1)\n .max(256)\n .refine(\n (value) => value !== \".\" && value !== \"..\" && !value.includes(\"/\") && !value.includes(\"\\\\\"),\n \"must be a plain peer id without path separators\",\n );\n\nconst capsuleIsoSinceSchema = z\n .string()\n .trim()\n .min(1, \"since must be a non-empty ISO 8601 timestamp\")\n .max(128)\n .refine(\n isValidCapsuleSince,\n \"since must be a valid ISO 8601 timestamp with no calendar overflow\",\n );\n\nexport const capsuleExportRequestSchema = z\n .object({\n name: z\n .string()\n .trim()\n .min(1, \"name is required\")\n .max(64, \"name must be 64 characters or fewer\")\n .regex(\n CAPSULE_ID_PATTERN,\n \"name must be alphanumeric with single dashes (no spaces, no leading/trailing dashes)\",\n ),\n namespace: namespaceSchema,\n since: capsuleIsoSinceSchema.optional(),\n includeKinds: z.array(capsuleTopLevelSegmentSchema).max(50).optional(),\n peerIds: z.array(capsulePeerIdSchema).max(100).optional(),\n includeTranscripts: z.boolean().optional(),\n encrypt: z.boolean().optional(),\n });\n\nexport const capsuleImportRequestSchema = z\n .object({\n archivePath: z.string().trim().min(1, \"archivePath is required\").max(4096),\n namespace: namespaceSchema,\n mode: z.enum([\"skip\", \"overwrite\", \"fork\"]).optional(),\n passphrase: z.string().min(1, \"passphrase must not be empty\").max(4096).optional(),\n });\n\nexport const capsuleListRequestSchema = z\n .object({\n namespace: namespaceSchema,\n sessionKey: sessionKeySchema,\n });\n\n// ---------------------------------------------------------------------------\n// Offline sync\n// ---------------------------------------------------------------------------\n\nfunction isValidOfflineSyncPath(value: string): boolean {\n try {\n validateArchiveRelativePath(value, \"path\");\n return true;\n } catch {\n return false;\n }\n}\n\nconst offlineSyncPathSchema = z\n .string()\n .trim()\n .min(1, \"path must be non-empty\")\n .max(4096)\n .refine(\n isValidOfflineSyncPath,\n \"path must be a POSIX relative path without unsafe segments\",\n );\n\nconst offlineSyncFileStateSchema = z.object({\n path: offlineSyncPathSchema,\n sha256: z.string().regex(/^[a-f0-9]{64}$/i, \"sha256 must be a 64-character hex digest\"),\n bytes: z.number().int().min(0),\n mtimeMs: z.number().finite().min(0).max(OFFLINE_SYNC_MAX_MTIME_MS),\n});\n\nconst offlineSyncBaseCapturedAtSchema = z\n .string()\n .trim()\n .min(1, \"baseCapturedAt must be non-empty when provided\")\n .max(64)\n .refine((value) => Number.isFinite(Date.parse(value)), {\n message: \"baseCapturedAt must be a valid ISO 8601 timestamp\",\n });\n\nexport const offlineSyncSnapshotRequestSchema = z.object({\n namespace: namespaceSchema,\n includeTranscripts: z.boolean().optional(),\n includeContent: z.boolean().optional(),\n baseCapturedAt: offlineSyncBaseCapturedAtSchema.optional(),\n baseFiles: z\n .array(offlineSyncFileStateSchema)\n .max(300_000, \"baseFiles must contain 300000 or fewer entries\")\n .optional(),\n});\n\nexport const offlineSyncApplyRequestSchema = z\n .object({\n namespace: namespaceSchema,\n changeset: z.unknown(),\n returnCurrentFiles: z.boolean().optional(),\n })\n .refine((value) => value.changeset !== undefined && value.changeset !== null, {\n message: \"changeset is required\",\n path: [\"changeset\"],\n });\n\nexport const offlineSyncFilesRequestSchema = z.object({\n namespace: namespaceSchema,\n includeTranscripts: z.boolean().optional(),\n paths: z\n .array(offlineSyncPathSchema)\n .max(5000, \"paths must contain 5000 or fewer entries\"),\n});\n\nexport const offlineSyncFileContentRequestSchema = z.object({\n namespace: namespaceSchema,\n includeTranscripts: z.boolean().optional(),\n path: offlineSyncPathSchema,\n offset: z.number().int().min(0).optional(),\n length: z.number().int().min(1).max(OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES).optional(),\n});\n\n// ---------------------------------------------------------------------------\n// Action confidence\n// ---------------------------------------------------------------------------\n\nconst nullableOptional = <T extends z.ZodTypeAny>(schema: T) =>\n schema.optional().nullable().transform((value) => value ?? undefined);\n\nconst actionConfidenceRuleSchema = z\n .object({\n kind: z.enum(ACTION_CONFIDENCE_RULE_KINDS),\n description: nullableOptional(z.string().trim().min(1).max(2000)),\n matched: nullableOptional(z.boolean()),\n })\n .strict();\n\nconst actionConfidenceMemorySchema = z\n .object({\n source: nullableOptional(z.string().trim().min(1).max(256)),\n created: nullableOptional(z.string().trim().min(1).max(128)),\n updated: nullableOptional(z.string().trim().min(1).max(128)),\n scope: nullableOptional(z.string().trim().min(1).max(512)),\n userContextScopes: nullableOptional(z.array(z.string().trim().min(1).max(128)).max(50)),\n retrievalReason: nullableOptional(z.string().trim().min(1).max(2000)),\n confidence: nullableOptional(z.number().min(0).max(1)),\n stale: nullableOptional(z.boolean()),\n corrected: nullableOptional(z.boolean()),\n correctionState: nullableOptional(z.enum([\"none\", \"correction\", \"superseded\", \"disputed\", \"forgotten\"])),\n safeToUse: nullableOptional(z.boolean()),\n safety: nullableOptional(z.enum([\"safe\", \"requires-review\", \"blocked\"])),\n safetyReasons: nullableOptional(z.array(z.string().trim().min(1).max(1000)).max(50)),\n })\n .strict();\n\nexport const actionConfidenceRequestSchema = z\n .object({\n intendedAction: nullableOptional(z.string().trim().min(1).max(1000)),\n confidence: nullableOptional(z.number().min(0).max(1)),\n risk: nullableOptional(z.enum(ACTION_CONFIDENCE_RISK_CATEGORIES)),\n contextReadiness: nullableOptional(z.enum(ACTION_CONFIDENCE_CONTEXT_READINESS)),\n currentContextScopes: nullableOptional(z.array(z.string().trim().min(1).max(128)).max(50)),\n userRules: nullableOptional(z.array(actionConfidenceRuleSchema).max(100)),\n retrievedMemories: nullableOptional(z.array(actionConfidenceMemorySchema).max(200)),\n })\n .strict();\n\n// ---------------------------------------------------------------------------\n// Inferred types\n// ---------------------------------------------------------------------------\n\nexport type RecallRequest = z.infer<typeof recallRequestSchema>;\nexport type RecallExplainRequest = z.infer<typeof recallExplainRequestSchema>;\nexport type SetCodingContextRequest = z.infer<typeof setCodingContextRequestSchema>;\nexport type ObserveRequest = z.infer<typeof observeRequestSchema>;\nexport type MemoryStoreRequest = z.infer<typeof memoryStoreRequestSchema>;\nexport type SuggestionSubmitRequest = z.infer<typeof suggestionSubmitRequestSchema>;\nexport type ReviewDispositionRequest = z.infer<typeof reviewDispositionRequestSchema>;\nexport type TrustZonePromoteRequest = z.infer<typeof trustZonePromoteRequestSchema>;\nexport type TrustZoneDemoSeedRequest = z.infer<typeof trustZoneDemoSeedRequestSchema>;\nexport type LcmSearchRequest = z.infer<typeof lcmSearchRequestSchema>;\nexport type LcmCompactionFlushRequest = z.infer<typeof lcmCompactionFlushRequestSchema>;\nexport type ExtractionForceFlushRequest = z.infer<typeof extractionForceFlushRequestSchema>;\nexport type LcmCompactionRecordRequest = z.infer<typeof lcmCompactionRecordRequestSchema>;\nexport type DaySummaryRequest = z.infer<typeof daySummaryRequestSchema>;\nexport type CapsuleExportRequest = z.infer<typeof capsuleExportRequestSchema>;\nexport type CapsuleImportRequest = z.infer<typeof capsuleImportRequestSchema>;\nexport type CapsuleListRequest = z.infer<typeof capsuleListRequestSchema>;\nexport type OfflineSyncApplyRequest = z.infer<typeof offlineSyncApplyRequestSchema>;\nexport type OfflineSyncSnapshotRequest = z.infer<typeof offlineSyncSnapshotRequestSchema>;\nexport type OfflineSyncFilesRequest = z.infer<typeof offlineSyncFilesRequestSchema>;\nexport type OfflineSyncFileContentRequest = z.infer<typeof offlineSyncFileContentRequestSchema>;\nexport type ActionConfidenceRequest = z.infer<typeof actionConfidenceRequestSchema>;\n\n// ---------------------------------------------------------------------------\n// Validation helper\n// ---------------------------------------------------------------------------\n\nexport type SchemaName =\n | \"recall\"\n | \"recallExplain\"\n | \"setCodingContext\"\n | \"observe\"\n | \"memoryStore\"\n | \"suggestionSubmit\"\n | \"reviewDisposition\"\n | \"trustZonePromote\"\n | \"trustZoneDemoSeed\"\n | \"lcmSearch\"\n | \"lcmCompactionFlush\"\n | \"extractionForceFlush\"\n | \"lcmCompactionRecord\"\n | \"daySummary\"\n | \"capsuleExport\"\n | \"capsuleImport\"\n | \"capsuleList\"\n | \"offlineSyncSnapshot\"\n | \"offlineSyncFiles\"\n | \"offlineSyncFileContent\"\n | \"offlineSyncApply\"\n | \"actionConfidence\";\n\nexport type SchemaTypeFor<N extends SchemaName> =\n N extends \"recall\" ? RecallRequest\n : N extends \"recallExplain\" ? RecallExplainRequest\n : N extends \"setCodingContext\" ? SetCodingContextRequest\n : N extends \"observe\" ? ObserveRequest\n : N extends \"memoryStore\" ? MemoryStoreRequest\n : N extends \"suggestionSubmit\" ? SuggestionSubmitRequest\n : N extends \"reviewDisposition\" ? ReviewDispositionRequest\n : N extends \"trustZonePromote\" ? TrustZonePromoteRequest\n : N extends \"trustZoneDemoSeed\" ? TrustZoneDemoSeedRequest\n : N extends \"lcmSearch\" ? LcmSearchRequest\n : N extends \"lcmCompactionFlush\" ? LcmCompactionFlushRequest\n : N extends \"extractionForceFlush\" ? ExtractionForceFlushRequest\n : N extends \"lcmCompactionRecord\" ? LcmCompactionRecordRequest\n : N extends \"daySummary\" ? DaySummaryRequest\n : N extends \"capsuleExport\" ? CapsuleExportRequest\n : N extends \"capsuleImport\" ? CapsuleImportRequest\n : N extends \"capsuleList\" ? CapsuleListRequest\n : N extends \"offlineSyncSnapshot\" ? OfflineSyncSnapshotRequest\n : N extends \"offlineSyncFiles\" ? OfflineSyncFilesRequest\n : N extends \"offlineSyncFileContent\" ? OfflineSyncFileContentRequest\n : N extends \"offlineSyncApply\" ? OfflineSyncApplyRequest\n : N extends \"actionConfidence\" ? ActionConfidenceRequest\n : never;\n\nconst schemas: Record<SchemaName, z.ZodTypeAny> = {\n recall: recallRequestSchema,\n recallExplain: recallExplainRequestSchema,\n setCodingContext: setCodingContextRequestSchema,\n observe: observeRequestSchema,\n memoryStore: memoryStoreRequestSchema,\n suggestionSubmit: suggestionSubmitRequestSchema,\n reviewDisposition: reviewDispositionRequestSchema,\n trustZonePromote: trustZonePromoteRequestSchema,\n trustZoneDemoSeed: trustZoneDemoSeedRequestSchema,\n lcmSearch: lcmSearchRequestSchema,\n lcmCompactionFlush: lcmCompactionFlushRequestSchema,\n extractionForceFlush: extractionForceFlushRequestSchema,\n lcmCompactionRecord: lcmCompactionRecordRequestSchema,\n daySummary: daySummaryRequestSchema,\n capsuleExport: capsuleExportRequestSchema,\n capsuleImport: capsuleImportRequestSchema,\n capsuleList: capsuleListRequestSchema,\n offlineSyncSnapshot: offlineSyncSnapshotRequestSchema,\n offlineSyncFiles: offlineSyncFilesRequestSchema,\n offlineSyncFileContent: offlineSyncFileContentRequestSchema,\n offlineSyncApply: offlineSyncApplyRequestSchema,\n actionConfidence: actionConfidenceRequestSchema,\n};\n\n/**\n * Validate a request body against the named schema.\n * Returns `{ success: true, data }` on pass or\n * `{ success: false, error }` on failure with field-level detail.\n */\nexport function validateRequest<T = unknown>(\n schemaName: SchemaName,\n body: unknown,\n): { success: true; data: T } | { success: false; error: SchemaValidationError } {\n const schema = schemas[schemaName];\n if (!schema) {\n return {\n success: false,\n error: {\n error: `unknown schema: ${schemaName}`,\n code: \"validation_error\",\n details: [],\n },\n };\n }\n const result = schema.safeParse(stripNullsExceptCodingContext(body));\n if (result.success) {\n return { success: true, data: result.data as T };\n }\n return { success: false, error: formatZodError(result.error) };\n}\n\nfunction stripNullsExceptCodingContext(data: unknown): unknown {\n if (!data || typeof data !== \"object\" || Array.isArray(data)) return data;\n const cleaned: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data as Record<string, unknown>)) {\n if (value === null && key !== \"codingContext\") continue;\n cleaned[key] = value;\n }\n return cleaned;\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,SAAS;AA0BX,SAAS,eAAe,OAA0C;AACvE,SAAO;AAAA,IACL,OAAO;AAAA,I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,kBAAkB;AAAA,EAClB,wBAAwB;AAAA,EACxB,kBAAkB;AAAA,EAClB,kBAAkB;AACpB;AAOO,SAAS,gBACd,YACA,MAC+E;AAC/E,QAAM,SAAS,QAAQ,UAAU;AACjC,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO;AAAA,QACL,OAAO,mBAAmB,UAAU;AAAA,QACpC,MAAM;AAAA,QACN,SAAS,CAAC;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AACA,QAAM,SAAS,OAAO,UAAU,8BAA8B,IAAI,CAAC;AACnE,MAAI,OAAO,SAAS;AAClB,WAAO,EAAE,SAAS,MAAM,MAAM,OAAO,KAAU;AAAA,EACjD;AACA,SAAO,EAAE,SAAS,OAAO,OAAO,eAAe,OAAO,KAAK,EAAE;AAC/D;AAEA,SAAS,8BAA8B,MAAwB;AAC7D,MAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,EAAG,QAAO;AACrE,QAAM,UAAmC,CAAC;AAC1C,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,IAA+B,GAAG;AAC1E,QAAI,UAAU,QAAQ,QAAQ,gBAAiB;AAC/C,YAAQ,GAAG,IAAI;AAAA,EACjB;AACA,SAAO;AACT;","names":[]}
@@ -4,7 +4,7 @@ import {
4
4
  import {
5
5
  computeCorpusWatermarks,
6
6
  resolveCorpusNamespaceRoots
7
- } from "./chunk-N2ZNPHA3.js";
7
+ } from "./chunk-ECKG5WSI.js";
8
8
 
9
9
  // src/operator-doctor-corpus.ts
10
10
  var DIGEST_PREFIX_LENGTH = 12;
@@ -78,4 +78,4 @@ export {
78
78
  corpusWatermarksFromCheck,
79
79
  summarizeCorpusAndReplica
80
80
  };
81
- //# sourceMappingURL=chunk-PL7FYKHT.js.map
81
+ //# sourceMappingURL=chunk-L2WQVSKP.js.map
@@ -3,7 +3,7 @@ import {
3
3
  headerConnector,
4
4
  renderExtractionConversation,
5
5
  resolveSourceConnector
6
- } from "./chunk-5BCNEBEN.js";
6
+ } from "./chunk-XPJNT6PI.js";
7
7
  import {
8
8
  ConsolidationResultSchema,
9
9
  DaySummaryResultSchema,
@@ -71,25 +71,25 @@ import {
71
71
  } from "./chunk-WLZYGLJ4.js";
72
72
  import {
73
73
  LocalLlmClient
74
- } from "./chunk-A7XEPMQ6.js";
75
- import {
76
- isMemoryCategory
77
- } from "./chunk-3QQTXYZ6.js";
74
+ } from "./chunk-MVAQ2WM3.js";
78
75
  import {
79
76
  FallbackLlmClient,
80
77
  fallbackLlmRuntimeContextFromConfig,
81
78
  gatewayTaskChainOptions
82
- } from "./chunk-TLPZ6MKZ.js";
79
+ } from "./chunk-YEN4TREG.js";
83
80
  import {
84
81
  buildChatCompletionTokenLimit,
85
82
  shouldAssumeOpenAiChatCompletions
86
83
  } from "./chunk-L2EXJQJP.js";
84
+ import {
85
+ normalizeProcedureSteps
86
+ } from "./chunk-QDW3E4RD.js";
87
87
  import {
88
88
  extractJsonCandidates
89
89
  } from "./chunk-RGMVMVMF.js";
90
90
  import {
91
- normalizeProcedureSteps
92
- } from "./chunk-QDW3E4RD.js";
91
+ isMemoryCategory
92
+ } from "./chunk-LSLCFCCQ.js";
93
93
  import {
94
94
  sanitizeMemoryContent
95
95
  } from "./chunk-5GKPFL3S.js";
@@ -2387,4 +2387,4 @@ export {
2387
2387
  shouldEnableLocalExtractionThinking,
2388
2388
  ExtractionEngine
2389
2389
  };
2390
- //# sourceMappingURL=chunk-JSN44KIB.js.map
2390
+ //# sourceMappingURL=chunk-LEMD7WZJ.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  deepRecallRequestSchema
3
- } from "./chunk-JEIXTYVG.js";
3
+ } from "./chunk-L2QLDZJC.js";
4
4
  import {
5
5
  EngramAccessInputError
6
6
  } from "./chunk-2Z24E5W2.js";
@@ -39,4 +39,4 @@ async function respondDeepRecall(req, res, respondJson, readJsonBody, service, s
39
39
  export {
40
40
  respondDeepRecall
41
41
  };
42
- //# sourceMappingURL=chunk-VZWXFXLX.js.map
42
+ //# sourceMappingURL=chunk-LMCD5W5B.js.map
@@ -4,10 +4,10 @@ import {
4
4
  } from "./chunk-CARRTDKC.js";
5
5
  import {
6
6
  composeSalvagedEnvelope
7
- } from "./chunk-RC5DXXWC.js";
7
+ } from "./chunk-YM7YN37H.js";
8
8
  import {
9
9
  StorageManager
10
- } from "./chunk-HV7OY4DM.js";
10
+ } from "./chunk-5VAF4ID4.js";
11
11
  import {
12
12
  parseContinuityImprovementLoops
13
13
  } from "./chunk-LDXUBPMO.js";
@@ -1283,4 +1283,4 @@ export {
1283
1283
  defaultTierMigrationCycleBudget,
1284
1284
  CompoundingEngine
1285
1285
  };
1286
- //# sourceMappingURL=chunk-7BMXZCOT.js.map
1286
+ //# sourceMappingURL=chunk-LNDLXMH6.js.map
@@ -431,6 +431,7 @@ function buildObserveRequestFingerprint(parts) {
431
431
  export {
432
432
  TAG_LIMITS,
433
433
  STRUCTURED_ATTRIBUTE_LIMITS,
434
+ MEMORY_CATEGORY_NAMES,
434
435
  isMemoryCategory,
435
436
  composeMemoryEnvelope,
436
437
  isSealedMemoryEnvelope,
@@ -442,4 +443,4 @@ export {
442
443
  buildAccessWriteRequestFingerprint,
443
444
  buildObserveRequestFingerprint
444
445
  };
445
- //# sourceMappingURL=chunk-3QQTXYZ6.js.map
446
+ //# sourceMappingURL=chunk-LSLCFCCQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/write-envelope.ts"],"sourcesContent":["/**\n * Sealed memory-write envelope (issue #1989, umbrella #1988).\n *\n * THE single stamping point for cross-cutting memory-creation fields.\n *\n * Why this exists: PR #1852 needed 27 rework commits because adding one\n * cross-cutting field (`sourceConnector`) required hand-editing every\n * write call site and every idempotency payload, and reviewers discovered\n * missed sites one round at a time. This module removes the fan-out:\n *\n * 1. `composeMemoryEnvelope()` is the only way to mint a\n * `SealedMemoryEnvelope` — the brand is a non-exported `unique symbol`,\n * so a hand-built object literal fails `tsc` (`npm run check-types`\n * is already a required repo-wide gate; the type system IS the fence).\n * 2. `buildWriteIdempotencyPayload()` derives every access-surface\n * idempotency payload from ONE ordered field registry\n * (`WRITE_FINGERPRINT_FIELDS`). Adding a fingerprint-relevant field is\n * a one-line registry change picked up by every surface; forgetting to\n * classify a new `MemoryWriteInput` field is a compile error (see the\n * exhaustiveness guards at the bottom of this file).\n *\n * PR1 scope (no call-site changes): the composer, the registry, and the\n * payload builder, fully tested. PR2–PR4 migrate storage entry points and\n * the write call sites onto this module (see #1989 for the slicing).\n */\n\nimport { isMemorySubject } from \"./memory-subject.js\";\nimport type { MemoryCategory, MemorySubject } from \"./types.js\";\nimport { normalizeTags } from \"./recall-tag-filter.js\";\nimport { parseFlexibleIsoTimestamp } from \"./utils/iso-timestamp.js\";\nimport { assemblePersistedBody } from \"./structured-attributes.js\";\n\n// ---------------------------------------------------------------------------\n// Input surface\n// ---------------------------------------------------------------------------\n\n/**\n * Every cross-cutting memory-creation field lives HERE and only here.\n *\n * When you add a field you MUST also add it to either\n * `WRITE_FINGERPRINT_FIELDS` or `FINGERPRINT_EXEMPT_FIELDS` — the\n * exhaustiveness guard below makes forgetting a compile error.\n */\nexport interface MemoryWriteInput {\n /** Raw memory content. Must be non-empty after trimming. */\n content: string;\n /** Memory category — validated against the canonical category set. */\n category: MemoryCategory;\n /** Free-form labels; normalized (trim/dedupe) and capped, see TAG_LIMITS. */\n tags?: string[];\n /** String→string structured attributes; non-string values are rejected. */\n structuredAttributes?: Record<string, string>;\n /** Entity file reference (e.g. `person-jane-doe`). */\n entityRef?: string;\n /** Extraction confidence in [0, 1]. */\n confidence?: number;\n /** Opaque TTL expression (e.g. `90d` or an ISO date) — validated non-empty. */\n ttl?: string;\n /** Event-time validity start (ISO 8601). */\n validAt?: string;\n /** Connector identity that produced this write (issue #1852). */\n sourceConnector?: string;\n /** Origin class stamped at creation time (issue #1955). */\n origin?: string;\n /** Whom the memory models (issue #2372): \"user\" or \"agent\". */\n subject?: MemorySubject;\n /** Human-readable provenance note. */\n sourceReason?: string;\n}\n\n/** Context supplied by the write path, not by the payload author. */\nexport interface WriteContext {\n /** Frontmatter `source` string (e.g. `extraction`, `wearable:bee`). */\n source: string;\n /** Clock override for tests. */\n now?: () => Date;\n}\n\n/** Scope facts that participate in idempotency but never in frontmatter. */\nexport interface FingerprintScope {\n /** Access surface performing the write (e.g. `memory_store`, `observe`). */\n surface: string;\n namespace?: string;\n principal?: string;\n codingContext?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Normalization limits (single source of truth — docs/tags.md contract)\n// ---------------------------------------------------------------------------\n\nexport const TAG_LIMITS = Object.freeze({\n /** Maximum number of tags persisted per memory. */\n maxTags: 50,\n /** Maximum length of a single tag. */\n maxTagLength: 256,\n});\n\nexport const STRUCTURED_ATTRIBUTE_LIMITS = Object.freeze({\n /** Maximum number of structured attributes per memory. */\n maxEntries: 64,\n /** Maximum length of one attribute key. */\n maxKeyLength: 128,\n /** Maximum length of one attribute value. */\n maxValueLength: 1024,\n});\n\nconst MEMORY_CATEGORY_TABLE: Record<MemoryCategory, true> = {\n fact: true,\n preference: true,\n correction: true,\n entity: true,\n decision: true,\n relationship: true,\n principle: true,\n commitment: true,\n moment: true,\n skill: true,\n rule: true,\n procedure: true,\n reasoning_trace: true,\n};\n\nexport const MEMORY_CATEGORY_NAMES = Object.keys(MEMORY_CATEGORY_TABLE).sort();\n\nexport function isMemoryCategory(value: string): value is MemoryCategory {\n return Object.prototype.hasOwnProperty.call(MEMORY_CATEGORY_TABLE, value);\n}\n\n// ---------------------------------------------------------------------------\n// Sealed envelope\n// ---------------------------------------------------------------------------\n\ndeclare const sealed: unique symbol;\n\n/**\n * A normalized, validated memory-write envelope.\n *\n * Opaque: only `composeMemoryEnvelope()` can mint one. Storage creation\n * entry points accept this type (PR2), so every write path is forced\n * through the composer at compile time.\n */\nexport interface SealedMemoryEnvelope {\n readonly [sealed]: true;\n /**\n * Caller-supplied content VERBATIM (validated non-empty-after-trim).\n * `StorageManager.writeMemory` persists content byte-for-byte (callers\n * that trim, e.g. explicit capture, do so before composing), so the\n * envelope must not transform it — the earlier compose-time trim/sanitize\n * broke byte-parity with extraction writes and was removed in PR2.\n */\n readonly content: string;\n /**\n * The exact body persistence will write: attribute-suffix enrichment then\n * combined sanitization, produced by the SAME `assemblePersistedBody`\n * helper `writeMemory` uses (issue #1989 PR2; AGENTS.md §13). This is the\n * form write-idempotency fingerprints hash.\n */\n readonly persistedBody: string;\n /** Injection patterns matched during body assembly (empty = clean). */\n readonly sanitizeViolations: readonly string[];\n /**\n * Salvage-mode hygiene notes (empty in strict mode): each dropped/clamped\n * invalid optional field is recorded here — visible, never silent\n * (repo rule 34). Callers persisting machine-generated input log these.\n */\n readonly salvageNotes: readonly string[];\n readonly category: MemoryCategory;\n readonly tags: readonly string[];\n /**\n * CANONICAL attributes (keys trim+lowercase, values trim) — the form\n * fingerprints and downstream consumers use; stable across caller casing.\n */\n readonly structuredAttributes: Readonly<Record<string, string>> | undefined;\n /**\n * The validated ORIGINAL attribute map, byte-preserved. `writeMemory`\n * persists frontmatter attributes raw (canonicalizing only the body\n * suffix via normalizeAttributePairs) — a pre-existing raw/canonical\n * inconsistency (supersession keys read the raw form). The sealed path\n * preserves those bytes; canonicalizing the frontmatter at the storage\n * boundary is a follow-up once the legacy path retires (#1989 PR4).\n */\n readonly rawStructuredAttributes: Readonly<Record<string, string>> | undefined;\n readonly entityRef: string | undefined;\n readonly confidence: number | undefined;\n readonly ttl: string | undefined;\n readonly validAt: string | undefined;\n readonly sourceConnector: string | undefined;\n readonly origin: string | undefined;\n readonly subject: MemorySubject | undefined;\n readonly sourceReason: string | undefined;\n readonly source: string;\n /** ISO timestamp the envelope was composed (from ctx.now). */\n readonly composedAt: string;\n}\n\nfunction fail(field: string, message: string): never {\n throw new Error(`composeMemoryEnvelope: ${field} ${message}`);\n}\n\n/**\n * Compose-time input hygiene mode (issue #1989 PR2, review round on #2014).\n *\n * - `strict` (default): every invalid field throws — correct for OPERATOR\n * and API input (explicit capture, memory_store), where a bad value is a\n * caller bug that must surface.\n * - `salvage`: for MACHINE-GENERATED input (LLM extraction, wearable\n * ingestion). One malformed fact from an extractor must not abort a whole\n * persistence batch that legacy `writeMemory` would have accepted.\n * Invalid tags/attributes/optional fields are DROPPED with a note pushed\n * to `envelope.salvageNotes` — visible, never silent (repo rule 34);\n * callers log the notes. Content, category, ctx.source, and validAt stay\n * FATAL in both modes (legacy writeMemory also throws on bad validAt, and\n * a write without valid content/category cannot proceed).\n */\nexport interface ComposeEnvelopeOptions {\n salvage?: boolean;\n}\n\n/** Internal reporter: throws in strict mode, records a note in salvage. */\ninterface Hygiene {\n salvage: boolean;\n notes: string[];\n flag(field: string, message: string): void;\n}\n\nfunction makeHygiene(salvage: boolean): Hygiene {\n const notes: string[] = [];\n return {\n salvage,\n notes,\n flag(field: string, message: string): void {\n if (!salvage) fail(field, message);\n notes.push(`${field} ${message}`);\n },\n };\n}\n\n/**\n * Validate and CANONICALIZE `validAt` via the repo's shared flexible ISO\n * parser (`utils/iso-timestamp.ts`) — the same family durable writes use, so\n * the envelope can never accept a value storage would reject or reinterpret\n * (review findings on #1998: no second validation convention; reduced\n * precision like `2026-07-17T09:30Z` is valid; offsets are bounded ±14:00;\n * `Date.parse` alone is not an ISO validator).\n *\n * Canonical form is the epoch round-trip (`Date.toISOString()`), so\n * fingerprints are identical for `...T09:30Z`, `...T09:30:00.000Z`, and the\n * same instant expressed with an offset (§13 hash-consistency).\n */\nfunction validateIsoTimestamp(field: string, value: string): string {\n const trimmed = value.trim();\n if (trimmed.length === 0) fail(field, \"must be a non-empty ISO 8601 timestamp\");\n const epochMs = parseFlexibleIsoTimestamp(trimmed);\n if (epochMs === null) {\n fail(\n field,\n `is not a valid ISO 8601 date/timestamp: ${JSON.stringify(value)} (date-only, reduced precision, Z, and ±HH:MM offsets up to ±14:00 are accepted; calendar overflow is not)`,\n );\n }\n return new Date(epochMs).toISOString();\n}\n\nfunction normalizeEnvelopeTags(raw: string[] | undefined, hygiene: Hygiene): readonly string[] {\n if (raw === undefined) return Object.freeze([]);\n if (!Array.isArray(raw)) {\n hygiene.flag(\"tags\", \"must be an array of strings — dropped\");\n return Object.freeze([]);\n }\n const usable: string[] = [];\n for (const tag of raw) {\n if (typeof tag !== \"string\") {\n hygiene.flag(\"tags\", `entries must be strings (got ${typeof tag})`);\n continue;\n }\n if (tag.trim().length > TAG_LIMITS.maxTagLength) {\n hygiene.flag(\"tags\", `entry exceeds ${TAG_LIMITS.maxTagLength} characters: ${JSON.stringify(tag.slice(0, 40))}…`);\n continue;\n }\n usable.push(tag);\n }\n let normalized = normalizeTags(usable) ?? [];\n if (normalized.length > TAG_LIMITS.maxTags) {\n hygiene.flag(\"tags\", `exceed the ${TAG_LIMITS.maxTags}-tag limit (got ${normalized.length}) — keeping the first ${TAG_LIMITS.maxTags}`);\n normalized = normalized.slice(0, TAG_LIMITS.maxTags);\n }\n return Object.freeze(normalized);\n}\n\nfunction normalizeStructuredAttributes(\n raw: Record<string, string> | undefined,\n hygiene: Hygiene,\n): { canonical: Readonly<Record<string, string>>; raw: Readonly<Record<string, string>> } | undefined {\n if (raw === undefined) return undefined;\n if (\n raw === null ||\n typeof raw !== \"object\" ||\n Array.isArray(raw) ||\n (Object.getPrototypeOf(raw) !== Object.prototype && Object.getPrototypeOf(raw) !== null)\n ) {\n // Map/Date/class instances have empty Object.entries() and would\n // silently normalize to \"no attributes\" (review finding on #1998\n // round 5) — never a plain pass-through.\n hygiene.flag(\"structuredAttributes\", \"must be a plain object of string values (Map, Date, and class instances are rejected) — dropped\");\n return undefined;\n }\n let entries = Object.entries(raw);\n if (entries.length === 0) return undefined;\n if (entries.length > STRUCTURED_ATTRIBUTE_LIMITS.maxEntries) {\n hygiene.flag(\n \"structuredAttributes\",\n `exceed the ${STRUCTURED_ATTRIBUTE_LIMITS.maxEntries}-entry limit (got ${entries.length}) — keeping the first ${STRUCTURED_ATTRIBUTE_LIMITS.maxEntries} in insertion order`,\n );\n entries = entries.slice(0, STRUCTURED_ATTRIBUTE_LIMITS.maxEntries);\n }\n // Keys that collide with Object.prototype machinery are REJECTED outright:\n // `hashAccessIdempotencyPayload`'s stableStringify rebuilds objects with\n // plain assignment, where a \"__proto__\" own property silently vanishes —\n // so such a key can never round-trip through the fingerprint faithfully\n // (review finding on #1998 round 3). Rejection beats smuggling (§1/§39).\n const FORBIDDEN_ATTRIBUTE_KEYS = [\"__proto__\", \"constructor\", \"prototype\"];\n const out: Record<string, string> = Object.create(null);\n const survivingOriginal: Array<[string, string]> = [];\n for (const [key, value] of entries) {\n // Canonicalize exactly like storage's normalizeAttributePairs\n // (storage.ts:1277): keys trim+lowercase, values trim — so the\n // fingerprint and the persisted searchable form can never diverge\n // (review finding on #1998; AGENTS.md §13 hash-consistency).\n const cleanKey = key.trim().toLowerCase();\n if (cleanKey.length === 0) {\n hygiene.flag(\"structuredAttributes\", \"contain an empty key\");\n continue;\n }\n if (cleanKey.length > STRUCTURED_ATTRIBUTE_LIMITS.maxKeyLength) {\n hygiene.flag(\"structuredAttributes\", `key exceeds ${STRUCTURED_ATTRIBUTE_LIMITS.maxKeyLength} characters: ${JSON.stringify(cleanKey.slice(0, 40))}…`);\n continue;\n }\n if (typeof value !== \"string\") {\n hygiene.flag(\"structuredAttributes\", `value for ${JSON.stringify(cleanKey)} must be a string (got ${typeof value}) — stringify numbers/booleans at the call site`);\n continue;\n }\n const cleanValue = value.trim();\n if (FORBIDDEN_ATTRIBUTE_KEYS.includes(cleanKey)) {\n hygiene.flag(\n \"structuredAttributes\",\n `contain the reserved key ${JSON.stringify(cleanKey)} — prototype-machinery names cannot round-trip through fingerprint serialization`,\n );\n continue;\n }\n if (cleanValue.length > STRUCTURED_ATTRIBUTE_LIMITS.maxValueLength) {\n hygiene.flag(\"structuredAttributes\", `value for ${JSON.stringify(cleanKey)} exceeds ${STRUCTURED_ATTRIBUTE_LIMITS.maxValueLength} characters`);\n continue;\n }\n if (Object.hasOwn(out, cleanKey)) {\n hygiene.flag(\"structuredAttributes\", `contain duplicate key after canonicalization (trim + lowercase): ${JSON.stringify(cleanKey)}`);\n continue;\n }\n out[cleanKey] = cleanValue;\n survivingOriginal.push([key, value]);\n }\n if (Object.keys(out).length === 0) return undefined;\n // Copy onto a normal object so downstream JSON/stableStringify behavior is\n // unchanged; keys are already validated. The RAW map carries only the\n // SURVIVING original pairs — dropped entries must not reach frontmatter.\n return {\n canonical: Object.freeze({ ...out }),\n raw: Object.freeze(Object.fromEntries(survivingOriginal)),\n };\n}\n\nfunction normalizeOptionalString(\n field: string,\n value: string | undefined,\n hygiene: Hygiene,\n): string | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"string\") {\n hygiene.flag(field, `must be a string (got ${typeof value}) — dropped`);\n return undefined;\n }\n const trimmed = value.trim();\n if (trimmed.length === 0) {\n hygiene.flag(field, \"must be non-empty when provided — dropped\");\n return undefined;\n }\n return trimmed;\n}\n\n/**\n * Compose (normalize + validate + seal) a memory-write envelope.\n *\n * Strict mode (default) throws on any invalid input — never silently\n * defaults (AGENTS.md §1/§39). Salvage mode (`{ salvage: true }`, for\n * machine-generated input like LLM extraction) drops invalid OPTIONAL\n * fields with notes on `envelope.salvageNotes` instead of aborting the\n * batch; content/category/source/validAt stay fatal in both modes.\n */\nexport function composeMemoryEnvelope(\n input: MemoryWriteInput,\n ctx: WriteContext,\n opts: ComposeEnvelopeOptions = {},\n): SealedMemoryEnvelope {\n if (input === null || typeof input !== \"object\") fail(\"input\", \"must be an object\");\n if (ctx === null || typeof ctx !== \"object\") fail(\"ctx\", \"must be an object\");\n const hygiene = makeHygiene(opts.salvage === true);\n\n if (typeof input.content !== \"string\" || input.content.trim().length === 0) {\n fail(\"content\", \"must be a non-empty string\");\n }\n if (typeof input.category !== \"string\" || !isMemoryCategory(input.category)) {\n fail(\n \"category\",\n `must be one of: ${MEMORY_CATEGORY_NAMES.join(\", \")} (got ${JSON.stringify(input.category)})`,\n );\n }\n if (typeof ctx.source !== \"string\" || ctx.source.trim().length === 0) {\n fail(\"ctx.source\", \"must be a non-empty string\");\n }\n\n let confidence: number | undefined;\n if (input.confidence !== undefined) {\n if (\n typeof input.confidence !== \"number\" ||\n !Number.isFinite(input.confidence) ||\n input.confidence < 0 ||\n input.confidence > 1\n ) {\n hygiene.flag(\n \"confidence\",\n `must be a finite number within [0, 1] (got ${String(input.confidence)}) — dropped (storage defaults apply)`,\n );\n } else {\n confidence = input.confidence;\n }\n }\n\n let subject: MemorySubject | undefined;\n if (input.subject !== undefined) {\n if (!isMemorySubject(input.subject)) {\n hygiene.flag(\n \"subject\",\n `must be \"user\" or \"agent\" (got ${JSON.stringify(input.subject)}) — dropped`,\n );\n } else {\n subject = input.subject;\n }\n }\n\n // validAt stays FATAL in salvage too: legacy writeMemory throws on an\n // invalid validAt (normalizeMemoryWriteTimestamp), so salvage-dropping it\n // would CHANGE behavior rather than preserve it.\n const validAt =\n input.validAt === undefined ? undefined : validateIsoTimestamp(\"validAt\", input.validAt);\n\n const now = ctx.now ? ctx.now() : new Date();\n if (!(now instanceof Date) || Number.isNaN(now.getTime())) {\n fail(\"ctx.now\", \"must return a valid Date\");\n }\n\n const attributes = normalizeStructuredAttributes(input.structuredAttributes, hygiene);\n // Assemble the EXACT persisted form (attribute suffix + combined sanitize)\n // with the same helper writeMemory uses — fingerprints hash this form, so\n // envelope and storage cannot diverge (§13; #1998 round-8 thread resolved\n // here in PR2 as promised). writeMemory assembles from the RAW map;\n // normalizeAttributePairs canonicalizes internally, so raw and canonical\n // maps yield the same suffix — asserted by the parity suite.\n const assembled = assemblePersistedBody(\n input.content,\n attributes ? { ...attributes.raw } : undefined,\n );\n if (assembled.text.trim().length === 0) {\n fail(\"content\", \"is empty after sanitization\");\n }\n\n const body = {\n content: input.content,\n persistedBody: assembled.text,\n sanitizeViolations: Object.freeze([...assembled.violations]),\n category: input.category,\n tags: normalizeEnvelopeTags(input.tags, hygiene),\n structuredAttributes: attributes?.canonical,\n rawStructuredAttributes: attributes?.raw,\n entityRef: normalizeOptionalString(\"entityRef\", input.entityRef, hygiene),\n origin: normalizeOptionalString(\"origin\", input.origin, hygiene),\n subject,\n confidence,\n ttl: normalizeOptionalString(\"ttl\", input.ttl, hygiene),\n validAt,\n sourceConnector: normalizeOptionalString(\"sourceConnector\", input.sourceConnector, hygiene),\n sourceReason: normalizeOptionalString(\"sourceReason\", input.sourceReason, hygiene),\n source: ctx.source.trim(),\n composedAt: now.toISOString(),\n salvageNotes: Object.freeze([...hygiene.notes]),\n };\n const envelope = Object.freeze(body) as unknown as SealedMemoryEnvelope;\n SEALED_ENVELOPES.add(envelope);\n return envelope;\n}\n\n// The runtime seal registry. The declared `sealed` unique symbol exists only\n// at the type level (compile-time fence); this WeakSet is the runtime fence.\nconst SEALED_ENVELOPES = new WeakSet<object>();\n\n/**\n * TOCTOU guard for the structural arm (#2014 round 4): a frozen object may\n * still carry ACCESSOR properties whose getters return different values on\n * each read — valid data during re-composition, forged data when the write\n * path reads the field again. Frozen DATA properties are immutable, so\n * requiring data-only descriptors (on the envelope and its array/map\n * fields) makes every later read provably identical to the validated one.\n */\nfunction hasOnlyFrozenDataProperties(value: object): boolean {\n if (!Object.isFrozen(value)) return false;\n // Inherited accessors are as dangerous as own ones (round 5): a frozen\n // object can inherit a `tags` getter from a custom prototype. Composer\n // envelopes are plain object literals and plain arrays — require exactly\n // those prototypes so prototype-supplied getters cannot serve fields.\n const proto = Object.getPrototypeOf(value);\n if (Array.isArray(value)) {\n if (proto !== Array.prototype) return false;\n } else if (proto !== Object.prototype && proto !== null) {\n return false;\n }\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor || descriptor.get !== undefined || descriptor.set !== undefined) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Runtime check (belt) — the compile-time brand is the real fence.\n *\n * Fast path: WeakSet membership (same module graph). Fallback: RE-COMPOSITION\n * EQUIVALENCE — Node resolves `@remnic/core` through `dist/` for built\n * consumers and `src/` for tsx-loaded tests, and each graph gets its OWN\n * WeakSet, so identity alone would reject genuinely-sealed envelopes that\n * crossed a build boundary. The structural arm requires frozen DATA-only\n * properties (no accessors — TOCTOU guard, round 4), then re-runs the\n * STRICT composer on the candidate's own inputs and demands every envelope\n * field reproduce exactly (#2014 round 2: shape-only validation admitted\n * lookalikes with 51 tags or out-of-range confidence). A value that\n * survives has, by construction, passed every composer invariant, and its\n * fields cannot change between validation and the write that follows.\n *\n * `salvageNotes` is deliberately NOT compared: a legitimately salvage-minted\n * envelope carries notes while the strict re-composition of its (already\n * clean) surviving fields yields none. Notes are advisory provenance, not\n * identity — every load-bearing field is still verified.\n */\n\nexport function isSealedMemoryEnvelope(value: unknown): value is SealedMemoryEnvelope {\n if (typeof value !== \"object\" || value === null) return false;\n if (SEALED_ENVELOPES.has(value)) return true;\n if (!hasOnlyFrozenDataProperties(value)) return false;\n const v = value as Partial<SealedMemoryEnvelope>;\n if (\n typeof v.content !== \"string\" ||\n typeof v.persistedBody !== \"string\" ||\n typeof v.source !== \"string\" ||\n typeof v.composedAt !== \"string\" ||\n typeof v.category !== \"string\" ||\n !isMemoryCategory(v.category) ||\n !Array.isArray(v.tags) ||\n !hasOnlyFrozenDataProperties(v.tags) ||\n !Array.isArray(v.sanitizeViolations) ||\n !hasOnlyFrozenDataProperties(v.sanitizeViolations) ||\n !Array.isArray(v.salvageNotes) ||\n !hasOnlyFrozenDataProperties(v.salvageNotes)\n ) {\n return false;\n }\n const attrs = v.rawStructuredAttributes;\n if (\n attrs !== undefined &&\n (attrs === null || typeof attrs !== \"object\" || Array.isArray(attrs) || !hasOnlyFrozenDataProperties(attrs))\n ) {\n return false;\n }\n const canonicalAttrs = v.structuredAttributes;\n if (\n canonicalAttrs !== undefined &&\n (canonicalAttrs === null ||\n typeof canonicalAttrs !== \"object\" ||\n Array.isArray(canonicalAttrs) ||\n !hasOnlyFrozenDataProperties(canonicalAttrs))\n ) {\n return false;\n }\n let rebuilt: SealedMemoryEnvelope;\n try {\n rebuilt = composeMemoryEnvelope(\n {\n content: v.content,\n category: v.category,\n ...(v.tags.length > 0 ? { tags: [...(v.tags as string[])] } : {}),\n ...(attrs !== undefined ? { structuredAttributes: { ...attrs } } : {}),\n ...(v.entityRef !== undefined ? { entityRef: v.entityRef } : {}),\n ...(v.confidence !== undefined ? { confidence: v.confidence } : {}),\n ...(v.ttl !== undefined ? { ttl: v.ttl } : {}),\n ...(v.validAt !== undefined ? { validAt: v.validAt } : {}),\n ...(v.sourceConnector !== undefined ? { sourceConnector: v.sourceConnector } : {}),\n ...(v.origin !== undefined ? { origin: v.origin } : {}),\n ...(v.sourceReason !== undefined ? { sourceReason: v.sourceReason } : {}),\n },\n { source: v.source, now: () => new Date(v.composedAt as string) },\n );\n } catch {\n // Strict re-composition rejected an input — the candidate carries a\n // value the composer would never have minted.\n return false;\n }\n const sameArray = (a: readonly string[], b: readonly string[]): boolean =>\n a.length === b.length && a.every((entry, i) => entry === b[i]);\n const sameMap = (\n a: Readonly<Record<string, string>> | undefined,\n b: Readonly<Record<string, string>> | undefined,\n ): boolean => {\n if (a === undefined || b === undefined) return a === b;\n const ak = Object.keys(a);\n const bk = Object.keys(b);\n return ak.length === bk.length && ak.every((k) => Object.hasOwn(b, k) && a[k] === b[k]);\n };\n return (\n rebuilt.content === v.content &&\n rebuilt.persistedBody === v.persistedBody &&\n rebuilt.category === v.category &&\n rebuilt.source === v.source &&\n rebuilt.composedAt === v.composedAt &&\n rebuilt.confidence === v.confidence &&\n rebuilt.entityRef === v.entityRef &&\n rebuilt.ttl === v.ttl &&\n rebuilt.validAt === v.validAt &&\n rebuilt.sourceConnector === v.sourceConnector &&\n rebuilt.origin === v.origin &&\n rebuilt.sourceReason === v.sourceReason &&\n sameArray(rebuilt.tags, v.tags as string[]) &&\n sameArray(rebuilt.sanitizeViolations, v.sanitizeViolations as string[]) &&\n sameMap(rebuilt.structuredAttributes, v.structuredAttributes) &&\n sameMap(rebuilt.rawStructuredAttributes, attrs)\n );\n}\n\n/**\n * The ONE mapping from a sealed envelope (+ extras) to the legacy\n * `writeMemory(category, content, options)` argument shape. Used by\n * `StorageManager.writeSealedMemory` AND by test doubles that stub storage —\n * so mock fidelity (AGENTS.md §21) cannot drift from production.\n */\nexport function sealedWriteToLegacyArgs(\n envelope: SealedMemoryEnvelope,\n extras: Record<string, unknown> = {},\n): { category: MemoryCategory; content: string; options: Record<string, unknown> } {\n return {\n category: envelope.category,\n content: envelope.content,\n options: {\n ...extras,\n confidence: envelope.confidence,\n tags: envelope.tags.length > 0 ? [...envelope.tags] : undefined,\n entityRef: envelope.entityRef,\n source: envelope.source,\n expiresAt: envelope.ttl,\n validAt: envelope.validAt,\n // RAW map for frontmatter byte-parity with the legacy path; the body\n // suffix canonicalizes identically from either form.\n structuredAttributes: envelope.rawStructuredAttributes\n ? { ...envelope.rawStructuredAttributes }\n : undefined,\n // Unconditional (round 3): envelope-owned fields must ALWAYS overwrite\n // extras — a conditional spread let extras.sourceConnector smuggle\n // unvalidated connector provenance past the sealed envelope when the\n // envelope had none.\n origin: envelope.origin,\n sourceConnector: envelope.sourceConnector,\n subject: envelope.subject,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Idempotency field registry\n// ---------------------------------------------------------------------------\n\n/**\n * Ordered registry of envelope fields that participate in write-idempotency\n * fingerprints. Adding a fingerprint-relevant field = one entry here; every\n * surface that builds its payload via `buildWriteIdempotencyPayload()` picks\n * it up automatically.\n */\nexport const WRITE_FINGERPRINT_FIELDS = [\n \"content\",\n \"category\",\n \"tags\",\n \"structuredAttributes\",\n \"entityRef\",\n \"ttl\",\n \"validAt\",\n \"sourceConnector\",\n] as const satisfies readonly (keyof MemoryWriteInput)[];\n\n/**\n * Envelope fields deliberately EXCLUDED from fingerprints. Exempting a field\n * is a visible, reviewable decision — this list exists so the exhaustiveness\n * guard can force every new `MemoryWriteInput` field to be classified.\n */\nexport const FINGERPRINT_EXEMPT_FIELDS = [\n // Confidence is a scoring detail: two extractions of the same fact with\n // slightly different confidence are the same write for dedup purposes.\n \"confidence\",\n // Free-text provenance note; carries no identity.\n // Origin is provenance metadata, not write identity (#1955).\n \"origin\",\n // Subject is derived classification metadata (#2372): two writes identical\n // except subject are the same memory for dedup purposes.\n \"subject\",\n \"sourceReason\",\n] as const satisfies readonly (keyof MemoryWriteInput)[];\n\n/** Scope keys always folded into the fingerprint payload. */\nexport const FINGERPRINT_SCOPE_FIELDS = [\n \"surface\",\n \"namespace\",\n \"principal\",\n \"codingContext\",\n] as const satisfies readonly (keyof FingerprintScope)[];\n\n// --- compile-time exhaustiveness guards ------------------------------------\n// A new MemoryWriteInput field that is in NEITHER list is a compile error;\n// a registry entry that names a non-existent field is a compile error; a\n// field in BOTH lists is a compile error.\n\ntype RegistryField = (typeof WRITE_FINGERPRINT_FIELDS)[number];\ntype ExemptField = (typeof FINGERPRINT_EXEMPT_FIELDS)[number];\ntype UnclassifiedField = Exclude<keyof MemoryWriteInput, RegistryField | ExemptField>;\ntype DoublyClassifiedField = RegistryField & ExemptField;\n\nconst assertEveryFieldClassified: UnclassifiedField extends never ? true : never = true;\nconst assertNoDoubleClassification: DoublyClassifiedField extends never ? true : never = true;\nvoid assertEveryFieldClassified;\nvoid assertNoDoubleClassification;\n\n// ---------------------------------------------------------------------------\n// Payload builder\n// ---------------------------------------------------------------------------\n\n/**\n * Build the canonical write-idempotency payload for a sealed envelope.\n *\n * Determinism guarantees (AGENTS.md §26):\n * - tags are SORTED in the payload (tag order never changes identity);\n * - structured attributes are serialized key-sorted by the existing\n * `stableStringify` inside `hashAccessIdempotencyPayload`;\n * - the payload shape is versioned (`v: 1`) so a future field-semantics\n * change can migrate stored idempotency state explicitly instead of\n * silently colliding.\n *\n * Feed the result to `hashAccessIdempotencyPayload()` — this module does\n * not hash so surfaces keep a single hashing implementation.\n */\nexport function buildWriteIdempotencyPayload(\n envelope: SealedMemoryEnvelope,\n scope: FingerprintScope,\n): Record<string, unknown> {\n if (!isSealedMemoryEnvelope(envelope)) {\n throw new Error(\n \"buildWriteIdempotencyPayload: envelope must be minted by composeMemoryEnvelope\",\n );\n }\n if (scope === null || typeof scope !== \"object\") {\n throw new Error(\"buildWriteIdempotencyPayload: scope must be an object\");\n }\n if (typeof scope.surface !== \"string\" || scope.surface.trim().length === 0) {\n throw new Error(\"buildWriteIdempotencyPayload: scope.surface must be a non-empty string\");\n }\n\n const fields: Record<string, unknown> = {};\n for (const field of WRITE_FINGERPRINT_FIELDS) {\n const value = envelope[field];\n if (value === undefined) continue;\n if (field === \"tags\") {\n const tags = value as readonly string[];\n if (tags.length === 0) continue;\n fields.tags = [...tags].sort();\n continue;\n }\n if (field === \"content\") {\n // Fingerprints hash the PERSISTED form (attribute suffix + combined\n // sanitize), not the raw input — one instant of stored state, one\n // fingerprint (§13; issue #1989 PR2).\n fields.content = envelope.persistedBody;\n continue;\n }\n fields[field] = value;\n }\n // The write source (extraction vs wearable:bee vs observe replay, ...) is\n // identity: the same content arriving from two different sources must not\n // dedupe into one write (review finding on #1998). Not a MemoryWriteInput\n // key, so it rides beside the registry fields explicitly.\n fields.source = envelope.source;\n\n const scopeOut: Record<string, string> = {};\n for (const key of FINGERPRINT_SCOPE_FIELDS) {\n const value = scope[key];\n if (value === undefined) continue;\n if (typeof value !== \"string\") {\n throw new Error(`buildWriteIdempotencyPayload: scope.${key} must be a string`);\n }\n // Trimmed: \"ns\" and \"ns \" must not mint distinct fingerprints (review\n // finding on #1998). Empty-after-trim optional scope values are dropped.\n const cleanValue = value.trim();\n if (key === \"surface\" || cleanValue.length > 0) {\n scopeOut[key] = cleanValue;\n }\n }\n\n return { v: 1, kind: \"memory-write\", fields, scope: scopeOut };\n}\n\n// ---------------------------------------------------------------------------\n// Access-surface request fingerprints (issue #1989 PR3)\n// ---------------------------------------------------------------------------\n//\n// The access surfaces (memory_store / suggestion_submit writes, their peek\n// twins, and observe) key their idempotency dedup on a hash of the RAW\n// request — computed BEFORE validation, and persisted indefinitely in\n// `AccessIdempotencyStore` (last-512 LRU, no time TTL). Those stored hashes\n// are load-bearing state: changing the payload shape would silently break\n// replay/conflict detection for every in-flight key. So these builders\n// REPRODUCE each surface's historical shape byte-for-byte (asserted by the\n// parity suite) instead of adopting the versioned envelope payload above —\n// a versioned migration of stored state is the explicit prerequisite for\n// unifying them (#1989 PR3 scope note).\n//\n// What centralizing buys even under byte-parity: one module now owns every\n// fingerprint shape, and the compile-time assertion below ties the write\n// shape to WRITE_FINGERPRINT_FIELDS — adding a fingerprint-relevant field\n// to MemoryWriteInput fails compilation here until the author decides how\n// the access surfaces represent it.\n\n/** The raw request fields the write surfaces fingerprint (legacy shape). */\nexport interface AccessWriteFingerprintParts {\n schemaVersion: number;\n namespace: string;\n content: string;\n category?: string;\n confidence?: number;\n tags?: string[];\n entityRef?: string;\n ttl?: string;\n sourceReason?: string;\n sourceConnector?: string;\n}\n\n// Registry coupling: every fingerprint-relevant MemoryWriteInput field must\n// either appear in AccessWriteFingerprintParts or be named in this explicit\n// exemption list. `structuredAttributes` and `validAt` are exempt because\n// the access write requests cannot express them today (ExplicitCaptureInput\n// has no such fields) — the moment they become representable, this type\n// stops compiling and forces a fingerprint decision (+ versioned state\n// migration) instead of a silent dedup gap.\ntype AccessSurfaceUnrepresentable = \"structuredAttributes\" | \"validAt\";\ntype UncoveredAccessFingerprintField = Exclude<\n Extract<RegistryField, keyof MemoryWriteInput>,\n keyof AccessWriteFingerprintParts | AccessSurfaceUnrepresentable\n>;\nconst assertAccessFingerprintCoversRegistry: UncoveredAccessFingerprintField extends never\n ? true\n : never = true;\nvoid assertAccessFingerprintCoversRegistry;\n\n/**\n * Fingerprint payload for `memory_store` / `suggestion_submit` (write AND\n * peek paths — both MUST call this so peek can never diverge from the\n * write it predicts). Key set and values reproduce the historical inline\n * literals exactly; `hashAccessIdempotencyPayload`'s stableStringify sorts\n * keys and drops `undefined`, so optional absent fields hash identically\n * to the old shape.\n */\nexport function buildAccessWriteRequestFingerprint(\n parts: AccessWriteFingerprintParts,\n): Record<string, unknown> {\n return {\n schemaVersion: parts.schemaVersion,\n content: parts.content,\n category: parts.category,\n confidence: parts.confidence,\n namespace: parts.namespace,\n tags: parts.tags,\n entityRef: parts.entityRef,\n ttl: parts.ttl,\n sourceReason: parts.sourceReason,\n sourceConnector: parts.sourceConnector,\n };\n}\n\n/** The raw request fields the observe surface fingerprints (legacy shape). */\nexport interface ObserveFingerprintParts {\n sessionKey: string;\n messages: unknown;\n namespace?: string;\n skipExtraction?: boolean;\n authenticatedPrincipal?: string;\n cwd?: string;\n projectTag?: string;\n /** Resolved coding context — `null` (not undefined) when absent, matching the historical literal. */\n effectiveCodingContext: unknown;\n sourceConnector?: string;\n}\n\n/**\n * Fingerprint payload for `observe` — turn ingestion, not a memory write,\n * so it fingerprints session/message identity rather than MemoryWriteInput\n * fields. Shape reproduces the historical inline literal exactly.\n */\nexport function buildObserveRequestFingerprint(\n parts: ObserveFingerprintParts,\n): Record<string, unknown> {\n return {\n sessionKey: parts.sessionKey,\n messages: parts.messages,\n namespace: parts.namespace,\n skipExtraction: parts.skipExtraction,\n authenticatedPrincipal: parts.authenticatedPrincipal,\n cwd: parts.cwd,\n projectTag: parts.projectTag,\n effectiveCodingContext: parts.effectiveCodingContext,\n sourceConnector: parts.sourceConnector,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA2FO,IAAM,aAAa,OAAO,OAAO;AAAA;AAAA,EAEtC,SAAS;AAAA;AAAA,EAET,cAAc;AAChB,CAAC;AAEM,IAAM,8BAA8B,OAAO,OAAO;AAAA;AAAA,EAEvD,YAAY;AAAA;AAAA,EAEZ,cAAc;AAAA;AAAA,EAEd,gBAAgB;AAClB,CAAC;AAED,IAAM,wBAAsD;AAAA,EAC1D,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,cAAc;AAAA,EACd,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,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AAO,UAAU,UAAU;AAC7B,YAAM,IAAI,MAAM,uCAAuC,GAAG,mBAAmB;AAAA,IAC/E;AAGA,UAAM,aAAa,MAAM,KAAK;AAC9B,QAAI,QAAQ,aAAa,WAAW,SAAS,GAAG;AAC9C,eAAS,GAAG,IAAI;AAAA,IAClB;AAAA,EACF;AAEA,SAAO,EAAE,GAAG,GAAG,MAAM,gBAAgB,QAAQ,OAAO,SAAS;AAC/D;AA8DO,SAAS,mCACd,OACyB;AACzB,SAAO;AAAA,IACL,eAAe,MAAM;AAAA,IACrB,SAAS,MAAM;AAAA,IACf,UAAU,MAAM;AAAA,IAChB,YAAY,MAAM;AAAA,IAClB,WAAW,MAAM;AAAA,IACjB,MAAM,MAAM;AAAA,IACZ,WAAW,MAAM;AAAA,IACjB,KAAK,MAAM;AAAA,IACX,cAAc,MAAM;AAAA,IACpB,iBAAiB,MAAM;AAAA,EACzB;AACF;AAqBO,SAAS,+BACd,OACyB;AACzB,SAAO;AAAA,IACL,YAAY,MAAM;AAAA,IAClB,UAAU,MAAM;AAAA,IAChB,WAAW,MAAM;AAAA,IACjB,gBAAgB,MAAM;AAAA,IACtB,wBAAwB,MAAM;AAAA,IAC9B,KAAK,MAAM;AAAA,IACX,YAAY,MAAM;AAAA,IAClB,wBAAwB,MAAM;AAAA,IAC9B,iBAAiB,MAAM;AAAA,EACzB;AACF;","names":[]}
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-7T4TOGMS.js";
4
4
  import {
5
5
  defineOperation
6
- } from "./chunk-UGPUYIET.js";
6
+ } from "./chunk-JHZCXUQI.js";
7
7
 
8
8
  // src/external-wiki-access.ts
9
9
  import { z } from "zod";
@@ -26,4 +26,4 @@ var externalWikiSearchOperation = defineOperation({
26
26
  export {
27
27
  externalWikiSearchOperation
28
28
  };
29
- //# sourceMappingURL=chunk-EONF76DT.js.map
29
+ //# sourceMappingURL=chunk-LYDJRF45.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  formatSupersededPrefix
3
- } from "./chunk-HVAEXYPL.js";
3
+ } from "./chunk-255PC37A.js";
4
4
 
5
5
  // src/recall-state-view-render.ts
6
6
  function renderStateViewLine(result, options = {}) {
@@ -17,4 +17,4 @@ function renderStateViewLine(result, options = {}) {
17
17
  export {
18
18
  renderStateViewLine
19
19
  };
20
- //# sourceMappingURL=chunk-MKD3OMPS.js.map
20
+ //# sourceMappingURL=chunk-M3MYMWXG.js.map
@@ -15,7 +15,7 @@ import {
15
15
  import {
16
16
  combineNamespaces,
17
17
  stableHash
18
- } from "./chunk-NZXEK3UF.js";
18
+ } from "./chunk-3Q3N35W7.js";
19
19
 
20
20
  // src/namespaces/scope-profiles.ts
21
21
  import { createHash } from "crypto";
@@ -338,4 +338,4 @@ export {
338
338
  resolveScopeProfilePlan,
339
339
  expandScopeProfileReadNamespaces
340
340
  };
341
- //# sourceMappingURL=chunk-VGXM5B4H.js.map
341
+ //# sourceMappingURL=chunk-MNIPH6LD.js.map