@inkeep/open-knowledge 0.4.0-beta.14 → 0.4.0-beta.15

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 (185) hide show
  1. package/dist/assets/skills/open-knowledge/SKILL.md +1 -1
  2. package/dist/cli.mjs +5 -5
  3. package/dist/constants-Cf7m1y2Y.mjs +2 -0
  4. package/dist/{dist-BqKhpKRA.mjs → dist-Bu-MwAbD.mjs} +1 -1
  5. package/dist/{dist-C7zRUYkF.mjs → dist-D4M20vXU.mjs} +3 -3
  6. package/dist/index.mjs +1 -1
  7. package/dist/init-CCbNydWa.mjs +1 -0
  8. package/dist/{init-DFIKzR_a.mjs → init-CIe9xion.mjs} +3 -3
  9. package/dist/loader-CMdR0tCR.mjs +1 -0
  10. package/dist/{loader-CLqzLLmP.mjs → loader-RuexJG94.mjs} +2 -2
  11. package/dist/preview-CgKJyIsb.mjs +1 -0
  12. package/dist/{preview-CYyF4Y9W.mjs → preview-DJNoVm8P.mjs} +2 -2
  13. package/dist/public/assets/{ActivityModeContent-DJ6-L4Kr.js → ActivityModeContent-BS-F_q5b.js} +2 -2
  14. package/dist/public/assets/{DocumentContext-DbBJqgtS.js → DocumentContext-CKgn09Wu.js} +17 -17
  15. package/dist/public/assets/{GraphPanel-Dg1nfluQ.js → GraphPanel-BYxZ6mOr.js} +2 -2
  16. package/dist/public/assets/McpConsentDialogBody-C-eBNOSk.js +1 -0
  17. package/dist/public/assets/{OutlinePanel-gcmWb8gC.js → OutlinePanel-B1VwD6nb.js} +1 -1
  18. package/dist/public/assets/SettingsPane-Byz_-VcF.js +11 -0
  19. package/dist/public/assets/{SourceEditor-ChbvYuYH.js → SourceEditor-CF1C1jlS.js} +2 -2
  20. package/dist/public/assets/{_baseFor-CX8dsZbW.js → _baseFor-DTImdh6y.js} +1 -1
  21. package/dist/public/assets/{agent-presence-Ds2n3U5P.js → agent-presence-CaGG2gp7.js} +1 -1
  22. package/dist/public/assets/{arc-BL_OKZmE.js → arc-VNWsD8TF.js} +1 -1
  23. package/dist/public/assets/architecture-YZFGNWBL-BiRl99NU.js +1 -0
  24. package/dist/public/assets/{architectureDiagram-Q4EWVU46-BKKtWWhU.js → architectureDiagram-Q4EWVU46-C7EDVIb_.js} +1 -1
  25. package/dist/public/assets/{blockDiagram-DXYQGD6D-fzO4vZye.js → blockDiagram-DXYQGD6D-RDoQRmSR.js} +1 -1
  26. package/dist/public/assets/button-qDXa0MxS.js +1 -0
  27. package/dist/public/assets/{c4Diagram-AHTNJAMY-BkXqEjiP.js → c4Diagram-AHTNJAMY-DWq5v6f-.js} +1 -1
  28. package/dist/public/assets/channel-C0UNiHDS.js +1 -0
  29. package/dist/public/assets/checkbox-kWXLLH40.js +1 -0
  30. package/dist/public/assets/{chunk-2KRD3SAO-DQj0pw3H.js → chunk-2KRD3SAO-BTibUhx6.js} +1 -1
  31. package/dist/public/assets/{chunk-336JU56O-CBajDulv.js → chunk-336JU56O-Bm6IwRki.js} +2 -2
  32. package/dist/public/assets/chunk-426QAEUC-BexV_O4G.js +1 -0
  33. package/dist/public/assets/{chunk-4BX2VUAB-D8pbSOlJ.js → chunk-4BX2VUAB-Dzrv7xRQ.js} +1 -1
  34. package/dist/public/assets/{chunk-4TB4RGXK-mA6CujZO.js → chunk-4TB4RGXK-n_VCZ-Dw.js} +1 -1
  35. package/dist/public/assets/chunk-55IACEB6-yo8vOoww.js +1 -0
  36. package/dist/public/assets/{chunk-5FUZZQ4R-BVDLgFg2.js → chunk-5FUZZQ4R-CwFS-NM9.js} +1 -1
  37. package/dist/public/assets/{chunk-5PVQY5BW-Cxi5d3lT.js → chunk-5PVQY5BW-Cf3pEIAB.js} +1 -1
  38. package/dist/public/assets/{chunk-67CJDMHE-CdrAY8qZ.js → chunk-67CJDMHE-B1qjR6o5.js} +1 -1
  39. package/dist/public/assets/{chunk-7N4EOEYR-CJ3HBg3c.js → chunk-7N4EOEYR-9LthribN.js} +1 -1
  40. package/dist/public/assets/{chunk-AA7GKIK3-D0ckJAXt.js → chunk-AA7GKIK3-DFgv_Jxv.js} +1 -1
  41. package/dist/public/assets/{chunk-BSJP7CBP-D4bNhKd7.js → chunk-BSJP7CBP-BMfaq0VP.js} +1 -1
  42. package/dist/public/assets/{chunk-CIAEETIT-D1Fpp2md.js → chunk-CIAEETIT-DUfZ-zCl.js} +1 -1
  43. package/dist/public/assets/{chunk-EDXVE4YY-ChhT3Iyo.js → chunk-EDXVE4YY-BKbUy63F.js} +1 -1
  44. package/dist/public/assets/{chunk-ENJZ2VHE-Bby39so4.js → chunk-ENJZ2VHE-DIZOQmDi.js} +1 -1
  45. package/dist/public/assets/{chunk-FMBD7UC4-pRkDIOZn.js → chunk-FMBD7UC4-DA5iFIgZ.js} +1 -1
  46. package/dist/public/assets/{chunk-FOC6F5B3-BsB4oTj4.js → chunk-FOC6F5B3-DlEcGgqD.js} +1 -1
  47. package/dist/public/assets/{chunk-ICPOFSXX-CrnuSfeJ.js → chunk-ICPOFSXX-BDU_0nPa.js} +2 -2
  48. package/dist/public/assets/{chunk-K5T4RW27-CtREah_n.js → chunk-K5T4RW27-CZi_8YH2.js} +1 -1
  49. package/dist/public/assets/{chunk-KGLVRYIC-DtDxSfKu.js → chunk-KGLVRYIC-q8yxX2UV.js} +1 -1
  50. package/dist/public/assets/{chunk-LIHQZDEY-D63TRk6j.js → chunk-LIHQZDEY-BqlaDvTQ.js} +1 -1
  51. package/dist/public/assets/{chunk-ORNJ4GCN-Dv2PvYVu.js → chunk-ORNJ4GCN-B6A2jdfA.js} +1 -1
  52. package/dist/public/assets/{chunk-OYMX7WX6-BhfqKepC.js → chunk-OYMX7WX6-BtgGgZZ0.js} +1 -1
  53. package/dist/public/assets/chunk-QZHKN3VN-Dm2czGiD.js +1 -0
  54. package/dist/public/assets/{chunk-U2HBQHQK-6BAKH95D.js → chunk-U2HBQHQK-LrOM0aht.js} +1 -1
  55. package/dist/public/assets/{chunk-X2U36JSP-Cqpkx90-.js → chunk-X2U36JSP-CsEhwsxu.js} +1 -1
  56. package/dist/public/assets/{chunk-XPW4576I-DSytTnq4.js → chunk-XPW4576I-D3W7wPR1.js} +1 -1
  57. package/dist/public/assets/{chunk-YZCP3GAM-Dt9awjVh.js → chunk-YZCP3GAM-C2TR8l-U.js} +1 -1
  58. package/dist/public/assets/{chunk-ZZ45TVLE-JGFITgiO.js → chunk-ZZ45TVLE-DGa_Hgat.js} +1 -1
  59. package/dist/public/assets/classDiagram-6PBFFD2Q-DqMO_sxB.js +1 -0
  60. package/dist/public/assets/classDiagram-v2-HSJHXN6E-BbC-74zc.js +1 -0
  61. package/dist/public/assets/clone-DpRB82L-.js +1 -0
  62. package/dist/public/assets/config-validation-events-BX5T6Pv4.js +7 -0
  63. package/dist/public/assets/{cose-bilkent-S5V4N54A-B9nG-SHi.js → cose-bilkent-S5V4N54A-cxoevGhk.js} +1 -1
  64. package/dist/public/assets/{dagre-BEdPLXba.js → dagre-DoC3Vx7E.js} +1 -1
  65. package/dist/public/assets/{dagre-KV5264BT-DKn5nGCC.js → dagre-KV5264BT-CjRUxU3J.js} +1 -1
  66. package/dist/public/assets/{diagram-5BDNPKRD-BQuwYEd0.js → diagram-5BDNPKRD-DlgILr6_.js} +1 -1
  67. package/dist/public/assets/{diagram-G4DWMVQ6-BmzIMyV5.js → diagram-G4DWMVQ6-CA3PL8En.js} +1 -1
  68. package/dist/public/assets/{diagram-MMDJMWI5-CI5eJfgr.js → diagram-MMDJMWI5-DVx-bZhM.js} +1 -1
  69. package/dist/public/assets/{diagram-TYMM5635-Cc8TJ7v3.js → diagram-TYMM5635-DCl_Xx4h.js} +1 -1
  70. package/dist/public/assets/dialog-CV9Q4JrD.js +45 -0
  71. package/dist/public/assets/{dist-nPpvoMNC.js → dist-BEF_m-Pp.js} +1 -1
  72. package/dist/public/assets/{dist-BH1b1nWB.js → dist-BJPjDIRr.js} +1 -1
  73. package/dist/public/assets/{dist-S8LJmtzL.js → dist-Bf3rdSRu.js} +1 -1
  74. package/dist/public/assets/{dist-D08h1pJc.js → dist-ByDNshqn.js} +1 -1
  75. package/dist/public/assets/{dist-B4kUko7n.js → dist-CSfB7p8y.js} +1 -1
  76. package/dist/public/assets/{dist-VyzSEzD4.js → dist-DVWct0HX.js} +1 -1
  77. package/dist/public/assets/{dist-BOapDt7N.js → dist-Gvva1zQ6.js} +1 -1
  78. package/dist/public/assets/{doc-hash-BAwyNVVo.js → doc-hash-CfmBVnag.js} +6 -6
  79. package/dist/public/assets/{erDiagram-SMLLAGMA-BkrhGWMT.js → erDiagram-SMLLAGMA-ChTvmoDx.js} +1 -1
  80. package/dist/public/assets/{flatten-UmyAv3V9.js → flatten-DXpXo4tl.js} +1 -1
  81. package/dist/public/assets/{flowDiagram-DWJPFMVM-qh62fanI.js → flowDiagram-DWJPFMVM-8ceKQudh.js} +1 -1
  82. package/dist/public/assets/{ganttDiagram-T4ZO3ILL-DXuCeCk6.js → ganttDiagram-T4ZO3ILL-uadeK_KN.js} +1 -1
  83. package/dist/public/assets/gitGraph-7Q5UKJZL-CN7yaTu1.js +1 -0
  84. package/dist/public/assets/{gitGraphDiagram-UUTBAWPF-BbcuenPj.js → gitGraphDiagram-UUTBAWPF-BcANz6_Q.js} +1 -1
  85. package/dist/public/assets/{graphlib-CasrTmMJ.js → graphlib-D3l3HBM4.js} +1 -1
  86. package/dist/public/assets/index-B4T9ZPge.js +1854 -0
  87. package/dist/public/assets/index-DFiz58v4.css +1 -0
  88. package/dist/public/assets/info-OMHHGYJF-oSrA8B1G.js +1 -0
  89. package/dist/public/assets/{infoDiagram-42DDH7IO-WFAMbO2S.js → infoDiagram-42DDH7IO-qKcHjiUa.js} +1 -1
  90. package/dist/public/assets/{isEmpty-DWJlzxR1.js → isEmpty-D9j5AQZB.js} +1 -1
  91. package/dist/public/assets/isSymbol-C4J31wCa.js +1 -0
  92. package/dist/public/assets/{ishikawaDiagram-UXIWVN3A-BJBiReWg.js → ishikawaDiagram-UXIWVN3A-DyndBZjz.js} +1 -1
  93. package/dist/public/assets/{journeyDiagram-VCZTEJTY-Boq77pl6.js → journeyDiagram-VCZTEJTY-CTiuXUzg.js} +1 -1
  94. package/dist/public/assets/{kanban-definition-6JOO6SKY-DYMSr18F.js → kanban-definition-6JOO6SKY-D03tqXqX.js} +1 -1
  95. package/dist/public/assets/label-BOVWulDu.js +1 -0
  96. package/dist/public/assets/{line-_p5Px7MV.js → line-CZuyNGqX.js} +1 -1
  97. package/dist/public/assets/{linear-DwuDS4qT.js → linear-CoY1VP-w.js} +1 -1
  98. package/dist/public/assets/{mermaid-parser.core-BcBb_Ows.js → mermaid-parser.core-D4O7MeLl.js} +2 -2
  99. package/dist/public/assets/{mermaid.core-ZLTnLqVQ.js → mermaid.core-4xgx5kDJ.js} +3 -3
  100. package/dist/public/assets/{mindmap-definition-QFDTVHPH-BSxM4djR.js → mindmap-definition-QFDTVHPH-BaMNW13B.js} +1 -1
  101. package/dist/public/assets/{now-BBH4UqDm.js → now-CJgVN_7h.js} +1 -1
  102. package/dist/public/assets/{ordinal-CeOFUmRv.js → ordinal-BZbu6HlW.js} +1 -1
  103. package/dist/public/assets/packet-4T2RLAQJ-N-KqWOhj.js +1 -0
  104. package/dist/public/assets/{panel-BgMqDESF.js → panel-BaN47PCr.js} +1 -1
  105. package/dist/public/assets/pie-ZZUOXDRM-BcRf7Q2g.js +1 -0
  106. package/dist/public/assets/{pieDiagram-DEJITSTG-CHRE_Jie.js → pieDiagram-DEJITSTG-_dBzvPAb.js} +1 -1
  107. package/dist/public/assets/{propagation-api-qAYD7s-v.js → propagation-api-CuTE-jIt.js} +1 -1
  108. package/dist/public/assets/{quadrantDiagram-34T5L4WZ-CQkE5TwH.js → quadrantDiagram-34T5L4WZ-jnOwhGSn.js} +1 -1
  109. package/dist/public/assets/radar-PYXPWWZC-CqcGRFrW.js +1 -0
  110. package/dist/public/assets/{reduce-DotyoGA7.js → reduce-Cn1fAmcq.js} +1 -1
  111. package/dist/public/assets/{requirementDiagram-MS252O5E-DHK98tKS.js → requirementDiagram-MS252O5E-DpZY5MOe.js} +1 -1
  112. package/dist/public/assets/{sankeyDiagram-XADWPNL6-BIXaStZh.js → sankeyDiagram-XADWPNL6-CNLrFRka.js} +1 -1
  113. package/dist/public/assets/{sequenceDiagram-FGHM5R23-BCNH3kJo.js → sequenceDiagram-FGHM5R23-Cqjio9cN.js} +1 -1
  114. package/dist/public/assets/{src-C9jsS3p4.js → src-CVigMQ0t.js} +1 -1
  115. package/dist/public/assets/{stateDiagram-FHFEXIEX-BC5mjB6x.js → stateDiagram-FHFEXIEX-rE9sZdwc.js} +1 -1
  116. package/dist/public/assets/stateDiagram-v2-QKLJ7IA2-CrJSNsUc.js +1 -0
  117. package/dist/public/assets/{target-navigation-intent-Bh5w39Ar.js → target-navigation-intent-CNDuSbLi.js} +1 -1
  118. package/dist/public/assets/{telemetry-impl-CMeDUVKn.js → telemetry-impl-iq6UBtaA.js} +2 -2
  119. package/dist/public/assets/{timeline-definition-GMOUNBTQ-VNxUGgXp.js → timeline-definition-GMOUNBTQ-B_X3o8J_.js} +1 -1
  120. package/dist/public/assets/tooltip-csUfbEtd.js +1 -0
  121. package/dist/public/assets/treeView-SZITEDCU-B1rO_oUt.js +1 -0
  122. package/dist/public/assets/treemap-W4RFUUIX-DXE3h2Bn.js +1 -0
  123. package/dist/public/assets/{vennDiagram-DHZGUBPP-DV2Y2j0r.js → vennDiagram-DHZGUBPP-Cs25K1vw.js} +1 -1
  124. package/dist/public/assets/wardley-RL74JXVD-ChWi2iyS.js +1 -0
  125. package/dist/public/assets/{wardleyDiagram-NUSXRM2D-C1mMZ3kx.js → wardleyDiagram-NUSXRM2D-RgfpVD8G.js} +1 -1
  126. package/dist/public/assets/{xychartDiagram-5P7HB3ND-CxFcwN2X.js → xychartDiagram-5P7HB3ND-BrRrEDJB.js} +1 -1
  127. package/dist/public/index.html +20 -19
  128. package/dist/src-CKsVM5vq.mjs +1 -0
  129. package/dist/start-BNFHnj8Y.mjs +1 -0
  130. package/dist/{start-BCn0MNGh.mjs → start-DDlnyNgo.mjs} +2 -2
  131. package/package.json +1 -1
  132. package/dist/constants-DAN-q5Vg.mjs +0 -2
  133. package/dist/init-CfMPjjjj.mjs +0 -1
  134. package/dist/loader-CvkCArFH.mjs +0 -1
  135. package/dist/preview-CZVcnhT0.mjs +0 -1
  136. package/dist/public/assets/McpConsentDialogBody-CJwPf_uv.js +0 -1
  137. package/dist/public/assets/SettingsPane-DymjUZrj.js +0 -11
  138. package/dist/public/assets/architecture-YZFGNWBL-DVxNz-zn.js +0 -1
  139. package/dist/public/assets/button-BsFpqlpT.js +0 -1
  140. package/dist/public/assets/channel-CR-xJel6.js +0 -1
  141. package/dist/public/assets/chunk-426QAEUC-BoBKbVmN.js +0 -1
  142. package/dist/public/assets/chunk-55IACEB6-CqVyNzhX.js +0 -1
  143. package/dist/public/assets/chunk-QZHKN3VN-DBRWHtgj.js +0 -1
  144. package/dist/public/assets/classDiagram-6PBFFD2Q-oopM_Z0m.js +0 -1
  145. package/dist/public/assets/classDiagram-v2-HSJHXN6E-ZAL74u9S.js +0 -1
  146. package/dist/public/assets/clone-C5y6xhRJ.js +0 -1
  147. package/dist/public/assets/config-validation-events-BtacxwV0.js +0 -7
  148. package/dist/public/assets/dialog-Cv1qneWl.js +0 -45
  149. package/dist/public/assets/gitGraph-7Q5UKJZL-CYhZlmk3.js +0 -1
  150. package/dist/public/assets/index-CE2NorF0.css +0 -1
  151. package/dist/public/assets/index-Dm1y4Z6N.js +0 -1854
  152. package/dist/public/assets/info-OMHHGYJF-BslcKZhH.js +0 -1
  153. package/dist/public/assets/isSymbol-BP7IOIqG.js +0 -1
  154. package/dist/public/assets/mcp-consent-store-BBTXqzE6.js +0 -1
  155. package/dist/public/assets/packet-4T2RLAQJ-QVnYA304.js +0 -1
  156. package/dist/public/assets/pie-ZZUOXDRM-C61c5byc.js +0 -1
  157. package/dist/public/assets/radar-PYXPWWZC-CMxjRtd8.js +0 -1
  158. package/dist/public/assets/stateDiagram-v2-QKLJ7IA2-B8L3BBt1.js +0 -1
  159. package/dist/public/assets/tooltip-BIapPAuP.js +0 -1
  160. package/dist/public/assets/treeView-SZITEDCU-DfSa_Oiv.js +0 -1
  161. package/dist/public/assets/treemap-W4RFUUIX-Cp0s5wEq.js +0 -1
  162. package/dist/public/assets/wardley-RL74JXVD-CXcBKCuj.js +0 -1
  163. package/dist/src-DiAwFfNV.mjs +0 -1
  164. package/dist/start-BbI1Pu4P.mjs +0 -1
  165. /package/dist/public/assets/{ActivityPanelDiffView-DoHWP1ak.js → ActivityPanelDiffView-B_49ivYc.js} +0 -0
  166. /package/dist/public/assets/{__vite-browser-external-FEGw1XPd.js → __vite-browser-external-6Gb3h3lj.js} +0 -0
  167. /package/dist/public/assets/{array-X0JlPOfd.js → array-DO1uCttT.js} +0 -0
  168. /package/dist/public/assets/{colors-XIJoz9Bd.js → colors-BjbB2MOj.js} +0 -0
  169. /package/dist/public/assets/{cytoscape.esm-BkjNfcSF.js → cytoscape.esm-AyAnQ5hQ.js} +0 -0
  170. /package/dist/public/assets/{defaultLocale-ZxyFnXCb.js → defaultLocale-B6RGN4id.js} +0 -0
  171. /package/dist/public/assets/{dist-CIRuNcH5.js → dist-0bM9CqzR.js} +0 -0
  172. /package/dist/public/assets/{go-a33xvodr.js → go-BRhAdNMM.js} +0 -0
  173. /package/dist/public/assets/{init-CBj3ecIW.js → init-BmUWJJHz.js} +0 -0
  174. /package/dist/public/assets/{isObjectLike-AdQZ65l0.js → isObjectLike-CjYO71dq.js} +0 -0
  175. /package/dist/public/assets/{katex-qwlL5fSd.js → katex-DBuiuHex.js} +0 -0
  176. /package/dist/public/assets/{min-HKuGSUqa.js → min-CwjSmrJ6.js} +0 -0
  177. /package/dist/public/assets/{path-rUlDLHdA.js → path-CoPyR7c2.js} +0 -0
  178. /package/dist/public/assets/{pdf-a35ddrIO.js → pdf-DaFpV-4n.js} +0 -0
  179. /package/dist/public/assets/{pdf.worker-CM-zAFN-.js → pdf.worker-Cq62cyp3.js} +0 -0
  180. /package/dist/public/assets/{rough.esm-BFJ-MgcB.js → rough.esm-ec8xsRC7.js} +0 -0
  181. /package/dist/public/assets/{shell-40VLet8r.js → shell-DT_H80Gx.js} +0 -0
  182. /package/dist/public/assets/{src-zyMpT2LE.js → src-CWigLjcs.js} +0 -0
  183. /package/dist/public/assets/{stex-BKMR5xQj.js → stex-DQW679lh.js} +0 -0
  184. /package/dist/public/assets/{trace-api-DPMyR1_m.js → trace-api-CbLDdnQA.js} +0 -0
  185. /package/dist/public/assets/{w3c-keyname-Dfj2imOv.js → w3c-keyname-B5t0fahT.js} +0 -0
@@ -781,7 +781,7 @@ ${e.terminator}`}function Qa(e){return`(${Ee(e.body)})${ke(e.redirections)}`}fun
781
781
  `).trim()),S=[]):S.push(e)}if(S.length>0){let e=S.join(`
782
782
  `).trim();e&&g.push(e)}return g}function reconcile(e){if(isSystemDoc(e.docName)||isConfigDoc(e.docName))return{kind:`noop`};let{base:t,ours:s,theirs:g}=e;if(containsConflictMarkers(g))return{kind:`refused`,reason:`conflict-markers`};if(g===t)return{kind:`noop`};if(s===t)return{kind:`clean`,newContent:g};let S=splitMarkdownBlocks(t),w=splitMarkdownBlocks(s),E=splitMarkdownBlocks(g);return(S.length+1)*(w.length+1)>4e6||(S.length+1)*(E.length+1)>4e6?{kind:`refused`,reason:`too-large`}:mergeBlocks(S,w,E)}function mergeBlocks(e,t,s){let g=computeEditOps(e,t),S=computeEditOps(e,s),w=[],E=[];for(let t=0;t<e.length;t++){let s=e[t],D=g.get(t),O=S.get(t),k=D?.insertsBefore??[],j=O?.insertsBefore??[];w.push(...k,...j);let F=D?.action??`keep`,L=O?.action??`keep`;if(F===`keep`&&L===`keep`)w.push(s);else if(F===`keep`&&L!==`keep`)L===`modify`&&O?.newContent!==void 0&&w.push(O.newContent);else if(F!==`keep`&&L===`keep`)F===`modify`&&D?.newContent!==void 0&&w.push(D.newContent);else{let e=F===`modify`?D?.newContent:null,g=L===`modify`?O?.newContent:null;e===g||E.push({blockIndex:t,base:s,ours:e??``,theirs:g??``}),e!=null&&w.push(e)}}let D=g.get(e.length),O=S.get(e.length);D?.insertsBefore&&w.push(...D.insertsBefore),O?.insertsBefore&&w.push(...O.insertsBefore);let k=w.length>0?`${w.join(`
783
783
 
784
- `)}\n`:``;return E.length>0?{kind:`conflicts`,newContent:k,conflicts:E}:{kind:`merged`,newContent:k,mergedBlocks:w.length}}function computeEditOps(e,t){let s=new Map,g=longestCommonSubsequence(e,t);for(let t=0;t<=e.length;t++)s.set(t,{action:`keep`,insertsBefore:[]});let S=new Set,w=new Set;for(let[e,t]of g)S.add(e),w.add(t);let E=-1;for(let D=0;D<e.length;D++)if(S.has(D)){let e=g.find(e=>e[0]===D)?.[1]??-1,S=[];for(let s=E+1;s<e;s++)w.has(s)||S.push(t[s]);let O=s.get(D);O&&(O.insertsBefore=S),E=e}else{let e=g.find(e=>e[0]>D),S=e?e[1]:t.length,O=[];for(let e=E+1;e<S;e++)w.has(e)||O.push(e);if(O.length>0){let e=O[0];w.add(e);let g=s.get(D);g&&(g.action=`modify`,g.newContent=t[e])}else{let e=s.get(D);e&&(e.action=`delete`)}}let D=[];for(let e=E+1;e<t.length;e++)w.has(e)||D.push(t[e]);let O=s.get(e.length);return O&&(O.insertsBefore=D),s}function longestCommonSubsequence(e,t){let s=e.length,g=t.length,S=g+1,w=new Uint32Array((s+1)*S);for(let E=1;E<=s;E++){let s=E*S,D=(E-1)*S;for(let S=1;S<=g;S++)if(e[E-1]===t[S-1])w[s+S]=w[D+(S-1)]+1;else{let e=w[D+S],t=w[s+(S-1)];w[s+S]=e>t?e:t}}let E=[],D=s,O=g;for(;D>0&&O>0;)e[D-1]===t[O-1]?(E.push([D-1,O-1]),D--,O--):w[(D-1)*S+O]>=w[D*S+(O-1)]?D--:O--;return E.reverse()}function assertNeverDiskEvent(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let s=writeTracker.get(e)??[];s.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,s)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,s]of writeTracker){let g=s.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);g.length===0?writeTracker.delete(t):g.length!==s.length&&writeTracker.set(t,g)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function eventEscapesContentDir(e,t){let s;try{s=lstatSync(e)}catch(t){let s=t.code;return s===`ENOENT`?!1:(console.warn(`[file-watcher] lstat failed for escape check on ${e} (${s}), dropping event`),!0)}if(!s.isSymbolicLink())return!1;let g;try{g=realpathSync(e)}catch(t){let s=t.code;return s!==`ENOENT`&&s!==`ELOOP`&&console.warn(`[file-watcher] realpath failed for escape check on ${e} (${s}), dropping event`),!0}return!isWithinContentDir(g,t)}function pathToDocName(e,t){return stripDocExtension(relative(t,e))}function extractDocExtension(e){let t=extname(e);if(t===``)return null;let s=t.toLowerCase();return s===`.mdx`||s===`.md`?t:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,s,g){let S=[],w=[],E=[];for(let g of e)if(isSupportedDocFile(g.path)){if(s){let e=relative(t,g.path);if(s.isExcluded(e))continue}switch(g.type){case`delete`:S.push(g);break;case`create`:lastKnownHash.has(g.path)?E.push(g):w.push(g);break;case`update`:E.push(g);break}}let D=new Map,O=new Map;for(let e of w)try{D.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of E)try{O.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function k(e){let s=pathToDocName(e,t);if(!g)return s;let S=null;try{S=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),g.has(s)&&g.delete(s),s}if(!S.isSymbolicLink())return g.has(s)&&g.delete(s),s;let w;try{w=realpathSync(e)}catch(t){let S=t.code;return S!==`ENOENT`&&S!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),g.delete(s),s}if(!isWithinContentDir(w,t))return g.delete(s),s;let E=pathToDocName(w,t);return E===s?s:(g.set(s,E),E)}let j=[],F=new Set,L=new Set;for(let e of S){let t=removeLastKnownHash(e.path);if(t)for(let s of w){if(F.has(s.path))continue;let g=D.get(s.path);if(g===void 0)continue;let S=contentHash(g);if(S===t){F.add(s.path),L.add(e.path),updateLastKnownHash(s.path,S),j.push({kind:`rename`,oldPath:e.path,newPath:s.path,oldDocName:k(e.path),newDocName:k(s.path),content:g});break}}}for(let e of S)L.has(e.path)||(removeLastKnownHash(e.path),j.push({kind:`delete`,path:e.path,docName:k(e.path)}));for(let e of w){if(F.has(e.path))continue;let t=D.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`create`,path:e.path,docName:k(e.path),content:t})}for(let e of E){let t=O.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`update`,path:e.path,docName:k(e.path),content:t})}return j}function isSelfWrite(e,t){let s=writeTracker.get(e);if(!s)return!1;let g=s.findIndex(e=>e.hash===t);return g<0?!1:(s.splice(g,1),s.length===0&&writeTracker.delete(e),!0)}function seedLastKnownHashes(e,t,s,g,S,w){let E=w??new Set;try{let w=readdirSync(e,{withFileTypes:!0});for(let D of w){let w=join(e,D.name),O;try{O=lstatSync(w)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${w}, skipping:`,e);continue}if(O.isSymbolicLink()){let e;try{e=realpathSync(w)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${w}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${w}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${w} → ${e}, skipping`);continue}try{let O=statSync(e);if(E.has(O.ino)){if(O.isFile()&&isSupportedDocFile(D.name)){let s=pathToDocName(w,t),E=pathToDocName(e,t);S.set(s,E);let D=g.get(E);D&&!D.aliases.includes(s)&&D.aliases.push(s)}continue}if(E.add(O.ino),O.isDirectory()){if(s){let g=relative(t,e);if(s.isDirExcluded(g))continue}seedLastKnownHashes(e,t,s,g,S,E)}else if(O.isFile()&&isSupportedDocFile(D.name)){if(s){let g=relative(t,e);if(s.isExcluded(g))continue}let E=pathToDocName(w,t),D=pathToDocName(e,t);S.set(E,D);try{let t=contentHash(readFileSync(e,`utf-8`));lastKnownHash.set(e,t);let s=extractDocExtension(e);if(s){let e=registerDocExtension(D,s);if(e.shadowed&&(console.warn(`[file-watcher] docName "${D}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(D,{size:O.size,modified:O.mtime.toISOString(),canonicalPath:e,inode:O.ino,aliases:[E]})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(O.isDirectory()){if(s){let e=relative(t,w);if(s.isDirExcluded(e))continue}seedLastKnownHashes(w,t,s,g,S,E)}else if(O.isFile()&&isSupportedDocFile(D.name)){if(E.has(O.ino))continue;if(E.add(O.ino),s){let e=relative(t,w);if(s.isExcluded(e))continue}try{let e=readFileSync(w,`utf-8`);lastKnownHash.set(w,contentHash(e));let s=pathToDocName(w,t),S=extractDocExtension(w);if(S){let e=registerDocExtension(s,S);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(s,{size:O.size,modified:O.mtime.toISOString(),canonicalPath:w,inode:O.ino,aliases:[]})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${w}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${w}:`,e)}}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(e.kind===`asset-create`||e.kind===`asset-delete`)return;let s=e.kind===`rename`?e.newDocName:e.docName;if(!(isSystemDoc(s)||isConfigDoc(s)))switch(e.kind){case`create`:case`update`:case`conflict`:{let s=e.docName,g=t.get(s),S=extractDocExtension(e.path);S&&registerDocExtension(s,S),t.set(s,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:g?.canonicalPath??e.path,inode:g?.inode??0,aliases:g?.aliases??[]});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,s]of t){let t=s.aliases.indexOf(e.docName);if(t!==-1){s.aliases.splice(t,1);break}}break;case`rename`:{let s=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let g=extractDocExtension(e.newPath);g&&registerDocExtension(e.newDocName,g),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:s?.canonicalPath??e.newPath,inode:s?.inode??0,aliases:s?.aliases??[]});break}}}async function handleRawEvents(e,t,s,g,S,w){let E=e.filter(e=>eventEscapesContentDir(e.path,t)?(console.warn(`[file-watcher] Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),D=E.filter(e=>isSupportedDocFile(e.path)),O=E.filter(e=>isSupportedAssetFile(e.path,ASSET_EXTENSIONS));if(D.length===0&&O.length===0)return;let k=D.length>0?await classifyEvents(D,t,s,w):[];for(let e of k){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let s=contentHash(e.content),g=e.path;try{g=realpathSync(e.path)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${s})`)}t=isSelfWrite(g,s)}else if(e.kind===`rename`){let s=contentHash(e.content),g=e.newPath;try{g=realpathSync(e.newPath)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${s})`)}t=isSelfWrite(g,s)}if(updateFileIndex(e,g),s&&!t)switch(e.kind){case`create`:s.incrementMdDir(dirname(e.docName));break;case`delete`:s.decrementMdDir(dirname(e.docName));break;case`rename`:s.decrementMdDir(dirname(e.oldDocName)),s.incrementMdDir(dirname(e.newDocName));break}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let w=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(w),"disk.path.role":classifyFsPath(w)}},async()=>S(e))}for(let e of O){if(s){let g=relative(t,e.path);if(s.isExcluded(g))continue}let g=relative(t,e.path);await S(e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:g}:{kind:`asset-create`,path:e.path,relativePath:g})}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,s,g,S){let w;try{w=await import(`@parcel/watcher`)}catch(e){return console.warn(`[file-watcher] @parcel/watcher import failed:`,e instanceof Error?e.message:e),null}try{let E=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await w.subscribe(e,async(w,E)=>{if(w){console.error(`[file-watcher]`,w);return}try{await handleRawEvents(E.map(e=>({type:e.type,path:e.path})),e,t,s,g,S)}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},E)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,s,g,S){let{watch:w}=await import(`./chokidar-CxU7f6JW.mjs`);console.warn(`[file-watcher] @parcel/watcher unavailable, using chokidar fallback`);let E=w(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(s,g)=>{let S=relative(e,s);return S===``||S===`.`?!1:g?.isDirectory()?t.isDirExcluded(S):t.isExcluded(S)}:void 0});E.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let D=50,O=[],k=null;function j(w,E){O.push({type:w,path:E}),k||=setTimeout(()=>{let w=O;O=[],k=null,handleRawEvents(w,e,t,s,g,S).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return E.on(`add`,e=>j(`create`,e)),E.on(`change`,e=>j(`update`,e)),E.on(`unlink`,e=>j(`delete`,e)),{unsubscribe:()=>(k&&(clearTimeout(k),k=null,O=[]),E.close())}}async function startWatcher(e,t,s){let g;try{g=realpathSync(e)}catch{g=e}let S=new Map,w=new Map;seedLastKnownHashes(g,g,s,S,w);let E=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),D,O;try{let e=await startParcelWatcher(g,s,S,t,w);e?(D=e,O=`parcel`):(D=await startChokidarWatcher(g,s,S,t,w),O=`chokidar`)}catch(e){throw clearInterval(E),e}let k=D.unsubscribe.bind(D);return console.log(`[file-watcher] Watching ${g} for external .md changes (backend: ${O})`),{async unsubscribe(){return clearInterval(E),writeTracker.clear(),lastKnownHash.clear(),k()},getFileIndex(){return S},getAliasMap(){return w}}}function normalizeBody(e){let{body:t}=stripFrontmatter(e);return normalizeBridge(t).trim()}function isWhitespace(e){return e===` `||e===`
784
+ `)}\n`:``;return E.length>0?{kind:`conflicts`,newContent:k,conflicts:E}:{kind:`merged`,newContent:k,mergedBlocks:w.length}}function computeEditOps(e,t){let s=new Map,g=longestCommonSubsequence(e,t);for(let t=0;t<=e.length;t++)s.set(t,{action:`keep`,insertsBefore:[]});let S=new Set,w=new Set;for(let[e,t]of g)S.add(e),w.add(t);let E=-1;for(let D=0;D<e.length;D++)if(S.has(D)){let e=g.find(e=>e[0]===D)?.[1]??-1,S=[];for(let s=E+1;s<e;s++)w.has(s)||S.push(t[s]);let O=s.get(D);O&&(O.insertsBefore=S),E=e}else{let e=g.find(e=>e[0]>D),S=e?e[1]:t.length,O=[];for(let e=E+1;e<S;e++)w.has(e)||O.push(e);if(O.length>0){let e=O[0];w.add(e);let g=s.get(D);g&&(g.action=`modify`,g.newContent=t[e])}else{let e=s.get(D);e&&(e.action=`delete`)}}let D=[];for(let e=E+1;e<t.length;e++)w.has(e)||D.push(t[e]);let O=s.get(e.length);return O&&(O.insertsBefore=D),s}function longestCommonSubsequence(e,t){let s=e.length,g=t.length,S=g+1,w=new Uint32Array((s+1)*S);for(let E=1;E<=s;E++){let s=E*S,D=(E-1)*S;for(let S=1;S<=g;S++)if(e[E-1]===t[S-1])w[s+S]=w[D+(S-1)]+1;else{let e=w[D+S],t=w[s+(S-1)];w[s+S]=e>t?e:t}}let E=[],D=s,O=g;for(;D>0&&O>0;)e[D-1]===t[O-1]?(E.push([D-1,O-1]),D--,O--):w[(D-1)*S+O]>=w[D*S+(O-1)]?D--:O--;return E.reverse()}function assertNeverDiskEvent(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let s=writeTracker.get(e)??[];s.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,s)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,s]of writeTracker){let g=s.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);g.length===0?writeTracker.delete(t):g.length!==s.length&&writeTracker.set(t,g)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function eventEscapesContentDir(e,t){let s;try{s=lstatSync(e)}catch(t){let s=t.code;return s===`ENOENT`?!1:(console.warn(`[file-watcher] lstat failed for escape check on ${e} (${s}), dropping event`),!0)}if(!s.isSymbolicLink())return!1;let g;try{g=realpathSync(e)}catch(t){let s=t.code;return s!==`ENOENT`&&s!==`ELOOP`&&console.warn(`[file-watcher] realpath failed for escape check on ${e} (${s}), dropping event`),!0}return!isWithinContentDir(g,t)}function pathToDocName(e,t){return stripDocExtension(relative(t,e))}function extractDocExtension(e){let t=extname(e);if(t===``)return null;let s=t.toLowerCase();return s===`.mdx`||s===`.md`?t:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,s,g){let S=[],w=[],E=[];for(let g of e)if(isSupportedDocFile(g.path)){if(s){let e=relative(t,g.path);if(s.isExcluded(e))continue}switch(g.type){case`delete`:S.push(g);break;case`create`:lastKnownHash.has(g.path)?E.push(g):w.push(g);break;case`update`:E.push(g);break}}let D=new Map,O=new Map;for(let e of w)try{D.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of E)try{O.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function k(e){let s=pathToDocName(e,t);if(!g)return s;let S=null;try{S=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),g.has(s)&&g.delete(s),s}if(!S.isSymbolicLink())return g.has(s)&&g.delete(s),s;let w;try{w=realpathSync(e)}catch(t){let S=t.code;return S!==`ENOENT`&&S!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),g.delete(s),s}if(!isWithinContentDir(w,t))return g.delete(s),s;let E=pathToDocName(w,t);return E===s?s:(g.set(s,E),E)}let j=[],F=new Set,L=new Set;for(let e of S){let t=removeLastKnownHash(e.path);if(t)for(let s of w){if(F.has(s.path))continue;let g=D.get(s.path);if(g===void 0)continue;let S=contentHash(g);if(S===t){F.add(s.path),L.add(e.path),updateLastKnownHash(s.path,S),j.push({kind:`rename`,oldPath:e.path,newPath:s.path,oldDocName:k(e.path),newDocName:k(s.path),content:g});break}}}for(let e of S)L.has(e.path)||(removeLastKnownHash(e.path),j.push({kind:`delete`,path:e.path,docName:k(e.path)}));for(let e of w){if(F.has(e.path))continue;let t=D.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`create`,path:e.path,docName:k(e.path),content:t})}for(let e of E){let t=O.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`update`,path:e.path,docName:k(e.path),content:t})}return j}function isSelfWrite(e,t){let s=writeTracker.get(e);if(!s)return!1;let g=s.findIndex(e=>e.hash===t);return g<0?!1:(s.splice(g,1),s.length===0&&writeTracker.delete(e),!0)}function seedLastKnownHashes(e,t,s,g,S,w){let E=w??new Set;try{let w=readdirSync(e,{withFileTypes:!0});for(let D of w){let w=join(e,D.name),O;try{O=lstatSync(w)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${w}, skipping:`,e);continue}if(O.isSymbolicLink()){let e;try{e=realpathSync(w)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${w}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${w}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${w} → ${e}, skipping`);continue}try{let O=statSync(e);if(E.has(O.ino)){if(O.isFile()&&isSupportedDocFile(D.name)){let s=pathToDocName(w,t),E=pathToDocName(e,t);S.set(s,E);let D=g.get(E);D&&!D.aliases.includes(s)&&D.aliases.push(s)}continue}if(E.add(O.ino),O.isDirectory()){if(s){let g=relative(t,e);if(s.isDirExcluded(g))continue}seedLastKnownHashes(e,t,s,g,S,E)}else if(O.isFile()&&isSupportedDocFile(D.name)){if(s){let g=relative(t,e);if(s.isExcluded(g))continue}let E=pathToDocName(w,t),D=pathToDocName(e,t);S.set(E,D);try{let t=contentHash(readFileSync(e,`utf-8`));lastKnownHash.set(e,t);let s=extractDocExtension(e);if(s){let e=registerDocExtension(D,s);if(e.shadowed&&(console.warn(`[file-watcher] docName "${D}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(D,{size:O.size,modified:O.mtime.toISOString(),canonicalPath:e,inode:O.ino,aliases:[E]})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(O.isDirectory()){if(s){let e=relative(t,w);if(s.isDirExcluded(e))continue}seedLastKnownHashes(w,t,s,g,S,E)}else if(O.isFile()&&isSupportedDocFile(D.name)){if(E.has(O.ino))continue;if(E.add(O.ino),s){let e=relative(t,w);if(s.isExcluded(e))continue}try{let e=readFileSync(w,`utf-8`);lastKnownHash.set(w,contentHash(e));let s=pathToDocName(w,t),S=extractDocExtension(w);if(S){let e=registerDocExtension(s,S);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(s,{size:O.size,modified:O.mtime.toISOString(),canonicalPath:w,inode:O.ino,aliases:[]})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${w}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${w}:`,e)}}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(e.kind===`asset-create`||e.kind===`asset-delete`)return;let s=e.kind===`rename`?e.newDocName:e.docName;if(!(isSystemDoc(s)||isConfigDoc(s)))switch(e.kind){case`create`:case`update`:case`conflict`:{let s=e.docName,g=t.get(s),S=extractDocExtension(e.path);S&&registerDocExtension(s,S),t.set(s,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:g?.canonicalPath??e.path,inode:g?.inode??0,aliases:g?.aliases??[]});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,s]of t){let t=s.aliases.indexOf(e.docName);if(t!==-1){s.aliases.splice(t,1);break}}break;case`rename`:{let s=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let g=extractDocExtension(e.newPath);g&&registerDocExtension(e.newDocName,g),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:s?.canonicalPath??e.newPath,inode:s?.inode??0,aliases:s?.aliases??[]});break}}}async function handleRawEvents(e,t,s,g,S,w){let E=e.filter(e=>eventEscapesContentDir(e.path,t)?(console.warn(`[file-watcher] Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),D=E.filter(e=>isSupportedDocFile(e.path)),O=E.filter(e=>isSupportedAssetFile(e.path,ASSET_EXTENSIONS));if(D.length===0&&O.length===0)return;let k=D.length>0?await classifyEvents(D,t,s,w):[];for(let e of k){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let s=contentHash(e.content),g=e.path;try{g=realpathSync(e.path)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${s})`)}t=isSelfWrite(g,s)}else if(e.kind===`rename`){let s=contentHash(e.content),g=e.newPath;try{g=realpathSync(e.newPath)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${s})`)}t=isSelfWrite(g,s)}if(updateFileIndex(e,g),s&&!t)switch(e.kind){case`create`:s.incrementMdDir(dirname(e.docName));break;case`delete`:s.decrementMdDir(dirname(e.docName));break;case`rename`:s.decrementMdDir(dirname(e.oldDocName)),s.incrementMdDir(dirname(e.newDocName));break}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let w=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(w),"disk.path.role":classifyFsPath(w)}},async()=>S(e))}for(let e of O){if(s){let g=relative(t,e.path);if(s.isExcluded(g))continue}let g=relative(t,e.path);await S(e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:g}:{kind:`asset-create`,path:e.path,relativePath:g})}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,s,g,S){let w;try{w=await import(`@parcel/watcher`)}catch(e){return console.warn(`[file-watcher] @parcel/watcher import failed:`,e instanceof Error?e.message:e),null}try{let E=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await w.subscribe(e,async(w,E)=>{if(w){console.error(`[file-watcher]`,w);return}try{await handleRawEvents(E.map(e=>({type:e.type,path:e.path})),e,t,s,g,S)}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},E)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,s,g,S){let{watch:w}=await import(`./chokidar-CxU7f6JW.mjs`);console.warn(`[file-watcher] @parcel/watcher unavailable, using chokidar fallback`);let E=w(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(s,g)=>{let S=relative(e,s);return S===``||S===`.`?!1:g?.isDirectory()?t.isDirExcluded(S):t.isExcluded(S)}:void 0});E.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let D=50,O=[],k=null;function j(w,E){O.push({type:w,path:E}),k||=setTimeout(()=>{let w=O;O=[],k=null,handleRawEvents(w,e,t,s,g,S).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return E.on(`add`,e=>j(`create`,e)),E.on(`change`,e=>j(`update`,e)),E.on(`unlink`,e=>j(`delete`,e)),{unsubscribe:()=>(k&&(clearTimeout(k),k=null,O=[]),E.close())}}async function startWatcher(e,t,s){let g;try{g=realpathSync(e)}catch{g=e}let S=new Map,w=new Map;seedLastKnownHashes(g,g,s,S,w);let E=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),D,O;try{let e=await startParcelWatcher(g,s,S,t,w);e?(D=e,O=`parcel`):(D=await startChokidarWatcher(g,s,S,t,w),O=`chokidar`)}catch(e){throw clearInterval(E),e}let k=D.unsubscribe.bind(D);return console.log(`[file-watcher] Watching ${g} for external .md changes (backend: ${O})`),{async unsubscribe(){return clearInterval(E),writeTracker.clear(),lastKnownHash.clear(),k()},getFileIndex(){return S},getAliasMap(){return w},pruneFileIndexNowExcluded(){if(!s)return 0;let e=0;for(let[t,w]of S){let E=relative(g,w.canonicalPath);s.isExcluded(E)&&(S.delete(t),e++)}return e}}}function normalizeBody(e){let{body:t}=stripFrontmatter(e);return normalizeBridge(t).trim()}function isWhitespace(e){return e===` `||e===`
785
785
  `||e===` `||e===`\r`}function classifyDuplication(e,t){let s=normalizeBody(t);if(s.length===0)return{kind:`allow`,reason:`empty-base`};let g=normalizeBody(e);if(g===s)return{kind:`allow`,reason:`identical`};if(g.length<s.length*2)return{kind:`allow`,reason:`too-short`};let S=0,w=0;for(;S<g.length;){if(g.slice(S,S+s.length)!==s)return{kind:`allow`,reason:`not-integer-multiple`};for(S+=s.length,w++;S<g.length&&isWhitespace(g[S]??``);)S++}return w>=2?{kind:`block`,reason:`structural-duplication`,copies:w}:{kind:`allow`,reason:`single-copy`}}const OBSERVER_SYNC_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`observer-sync`}},isPairedWriteOrigin=e=>typeof e!=`object`||!e?!1:e.context?.paired===!0;function shouldRethrowBridgeMergeLoss(e=process.env){return e.NODE_ENV===`test`||e.OK_RETHROW_BRIDGE_LOSS===`1`}function setupServerObservers(e){let{doc:t,xmlFragment:s,ytext:g,mdManager:S,schema:w}=e,E=(t,s)=>{let g=process.env.OK_TELEMETRY_VERBOSE===`1`;console.warn(JSON.stringify({...t.toLog({verbose:g}),docName:e.docName??null,timestamp:new Date().toISOString()})),incrementBridgeMergeContentLoss();let S=e.shadow?.();if(!S||!e.docName)return;let w=e.getBranch?.()??`main`,E=e.contentRoot??``;queueMicrotask(()=>{saveInMemoryCheckpoint(S,E,{kind:`bridge-merge-loss`,docName:e.docName,contents:s,label:`Before concurrent merge @ ${new Date().toISOString()}`,branch:w,metadata:{lostSubstrings:t.info.lostSubstrings}}).then(t=>{incrementBridgeMergeCheckpointCreated(),console.warn(JSON.stringify({event:`bridge-merge-checkpoint-created`,docName:e.docName,sha:t,kind:`bridge-merge-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{let t=e instanceof Error?e:Error(String(e));console.warn(`[Server Observer A] Silent checkpoint write failed:`,{name:t.name,message:t.message,stack:t.stack?.split(`
786
786
  `).slice(0,4).join(`
787
787
  `)})})})},D=``,O=!1,k=!1,j=()=>stripFrontmatter(g.toString()).frontmatter;try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e);D=prependFrontmatter(j(),t)}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),D=``}let F=()=>{try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),O=S.serialize(e),k=prependFrontmatter(j(),O);if(D===k)return;let F=g.toString();if(normalizeBridge(F)===normalizeBridge(k)){D=k;return}let L=D,B={mergedText:null};t.transact(()=>{if(F===D)applyIncrementalDiff(g,F,k);else try{let e=mergeThreeWay(D,k,F);applyFastDiff(g,F,e),B.mergedText=e}catch(e){if(!(e instanceof BridgeMergeContentLossError)||(E(e,L),shouldRethrowBridgeMergeLoss()))throw e;applyFastDiff(g,F,e.info.result),B.mergedText=e.info.result}},OBSERVER_SYNC_ORIGIN),B.mergedText!==null&&(incrementObserverAPathBFires(),console.warn(JSON.stringify({event:`observer-a-path-b-fired`,xmlFragmentAdvanced:!0,ytextDiverged:!0,mergeBytesChanged:Math.abs(B.mergedText.length-F.length)}))),incrementServerObserverFire(`a`),D=g.toString()}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,e);try{D=g.toString()}catch(e){console.warn(`[Server Observer A] Baseline recovery also failed:`,e)}}},L=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=j();D=g.toString(),B=e}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),O=!0}return}O=!0}};if(s.length>0&&g.length===0)try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),E=S.serialize(e),O=prependFrontmatter(j(),E);t.transact(()=>{g.insert(0,O)},OBSERVER_SYNC_ORIGIN),D=O}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),D=``}let B=j(),H=()=>{try{let w=g.toString(),{frontmatter:E,body:O}=stripFrontmatter(w);if(normalizeBridge(D)===normalizeBridge(w)){B!==E&&(recordFrontmatterEditSurface(`source-mode`),B=E);return}let k=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,sourcePath:e.docName}:void 0,j=S.parseWithFallback(O,k),F=e.schema.nodeFromJSON(j);t.transact(()=>{updateYFragment(t,s,F,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN),B!==E&&(recordFrontmatterEditSurface(`source-mode`),B=E),incrementServerObserverFire(`b`);try{let t=prependFrontmatter(E,S.serialize(j));assertBridgeInvariant(g.toString(),t,{site:`observer-b`,docName:e.docName}),D=t}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),D=prependFrontmatter(E,O)}}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;incrementServerObserverError(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=yXmlFragmentToProseMirrorRootNode(s,w).toJSON(),t=S.serialize(e);D=prependFrontmatter(j(),t)}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},q=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=j();D=g.toString(),B=e}catch(e){incrementServerObserverError(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),k=!0}return}k=!0}},J=(t,s)=>{if(!O&&!k){e.onDispatch?.(`none`);return}if(s.every(e=>e.origin===OBSERVER_SYNC_ORIGIN)){O=!1,k=!1,e.onDispatch?.(`none`);return}O&&(O=!1,e.onDispatch?.(`a`),F()),k&&(k=!1,e.onDispatch?.(`b`),H())};s.observeDeep(L),g.observe(q),t.on(`afterAllTransactions`,J);let Y=attachQuiescenceTracker(t);return()=>{Y(),t.off(`afterAllTransactions`,J),s.unobserveDeep(L),g.unobserve(q)}}const log$5=getLogger(`persistence`);function resolveWriterFromOrigin(e,t){if(!e||typeof e!=`object`)return null;let s=e;if(s.source===`local`){let e=s.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?FILE_SYSTEM_WRITER:e.origin===`upstream-import`||e.origin===`git-upstream`?GIT_UPSTREAM_WRITER:SERVICE_WRITER}if(s.source===`connection`){let e=s.connection?.context;if(typeof e?.principalId==`string`){let s=e.principalId,g=t?.();return g&&g.id===s&&g.display_name&&g.display_email?{id:g.id,name:g.display_name,email:g.display_email}:{id:s,name:`Local User`,email:`${s}@openknowledge.local`}}return SERVICE_WRITER}return null}function captureDocSnapshotForPersistence(e){return{sv:encodeStateVector(e),json:yXmlFragmentToProseMirrorRootNode(e.getXmlFragment(`default`),schema).toJSON()}}function safeContentPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let s=resolve(t,`${e}${getDocExtension(e)}`);if(!s.startsWith(`${t}/`))throw Error(`Invalid document name: ${e}`);return s}function isWithinContentDir(e,t){return e===t||e.startsWith(t+sep)}const reconciledBaseByBranch=new Map;let activeBranch=`main`;function switchReconciledBaseScope(e){activeBranch=e,reconciledBaseByBranch.has(e)||reconciledBaseByBranch.set(e,new Map)}function getActiveBranch(){return activeBranch}function getReconciledBase(e){return reconciledBaseByBranch.get(activeBranch)?.get(e)}function setReconciledBase(e,t){reconciledBaseByBranch.has(activeBranch)||reconciledBaseByBranch.set(activeBranch,new Map),reconciledBaseByBranch.get(activeBranch)?.set(e,t)}function deleteReconciledBase(e){reconciledBaseByBranch.get(activeBranch)?.delete(e)}let batchInProgress=!1;function setBatchInProgress(e){batchInProgress=e}function isBatchInProgress(){return batchInProgress}function createPersistenceExtension(e){let t=e?.contentDir??process.cwd(),s;try{s=realpathSync(t)}catch{s=t}let g=e?.projectDir??process.cwd(),S=e?.shadowRef,w=e?.contentRoot??(relative(g,s)||`.`),E=e?.backlinkIndex,D=e?.getPrincipal,O=e?.onAgentCommit,k=e?.onDiskFlush,j={projectDir:g,contentDir:s,lkgCache:new Map,homedirOverride:e?.configHomedirOverride,onConfigRejected:e?.onConfigRejected},F=new Set,L=e?.applyDiskContentToDoc??applyDiskContentToDoc,B=null,H=8,q=new Map,J=e?.gitEnabled??!0,Y=e?.commitDebounceMs??15e3,ee=e?.wipRef??`refs/wip/main`,te=e?.getCurrentBranch,ne=null,ae=0,oe=null,se=!1,ce=null,ue=new Map;async function de(){Te();let e=Date.now();return withSpan(`persistence.commitToWipRef`,void 0,async()=>await fe()).finally(()=>{we?.record((Date.now()-e)/1e3)})}async function fe(){let e=S?.current;if(e){let t=swapContributors(),s=te?.()??`main`;if(t.size===0){let t={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},g=`${formatWipSubject([])}\n\n${formatOkActor(t)}`;try{let t=await commitWip(e,SERVICE_WRITER,w,g,s);ae=0,log$5.info({sha:t.slice(0,8),writer:SERVICE_WRITER.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${SERVICE_WRITER.id}`)}catch(e){ae++,incrementGitAutoSaveFailure(),log$5.error({err:e,attempt:ae},`[persistence] Shadow commit failed (attempt ${ae})`),ae>=3&&log$5.error({attempt:ae},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let g;try{g=await buildWipTree(e,w)}catch(e){restoreContributors(t),ae++,incrementGitAutoSaveFailure(),log$5.error({err:e,attempt:ae},`[persistence] Shadow WIP tree build failed (attempt ${ae})`);return}let S=!1;for(let[w,E]of t){let t={id:w,name:E.displayName,email:`${w}@openknowledge.local`},D=[...E.docs],k=E.actor,j=[...E.summaries],F={v:1,writer_id:w,principal:k?.principalId??null,agent_session:w.startsWith(`agent-`)?w.slice(6):null,agent_type:k?.agentType??null,client_name:k?.clientName??null,client_version:k?.clientVersion??null,label:k?.label??null,display_name:E.displayName,color_seed:E.colorSeed,docs:D,...j.length>0?{summaries:j}:{}},L=`${composeCommitSubject(E.subjectOverride??formatWipSubject(D),j)}\n\n${formatOkActor(F)}`;try{let E=await commitWipFromTree(e,t,g,L,s);S=!0,log$5.info({sha:E.slice(0,8),writer:w,tree:g.slice(0,8)},`[persistence] Shadow WIP commit: ${E.slice(0,8)} on refs/wip/${w}`),w.startsWith(`agent-`)&&O?.()}catch(e){restoreContributorEntry(w,E),incrementGitWriterCommitFailure(),log$5.error({err:e,writer:w},`[persistence] Per-writer shadow commit failed for ${w}`)}}S?ae=0:(ae++,incrementGitAutoSaveFailure(),ae>=3&&log$5.error({attempt:ae},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=shadowGit({gitDir:resolve(g,`.git`),workTree:g}),s=resolve(g,`.git/index-wip`),E={GIT_INDEX_FILE:s};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(E).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?log$5.info({},`[persistence] Empty repo — starting with empty index`):log$5.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(E).raw(`add`,w);let e=(await t.env(E).raw(`write-tree`)).trim(),s=null;try{s=(await t.raw(`rev-parse`,ee)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let g=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];s&&g.push(`-p`,s);let S=(await t.raw(...g)).trim();await t.raw(`update-ref`,ee,S),ae=0,log$5.info({sha:S.slice(0,8),wipRef:ee},`[persistence] Git commit: ${S.slice(0,8)} on ${ee}`)}catch(e){ae++,incrementGitAutoSaveFailure(),log$5.error({err:e,attempt:ae},`[persistence] Git commit failed (attempt ${ae})`),ae>=3&&log$5.error({attempt:ae},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{tracedUnlinkSync(s)}catch{}}}function me(e){if(e<=0)return Y;let t=2**Math.min(e,5),s=Math.random()*.25*Y;return Y*t+s}function ge(){J&&(isBatchInProgress()||(ne&&clearTimeout(ne),ne=setTimeout(()=>{if(ne=null,oe){se=!0;return}oe=de().finally(()=>{oe=null,se&&(se=!1,ge())})},me(ae))))}async function _e(){ne&&(clearTimeout(ne),ne=null,oe||=de().finally(()=>{oe=null,se&&(se=!1,ge())})),oe&&await oe}function ve(t,s,g){try{let S=t.getXmlFragment(`default`),w=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:g}:void 0,E=mdManager.parseWithFallback(s,w),D=schema.nodeFromJSON(E);t.transact(()=>{updateYFragment(t,S,D,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN)}catch(e){incrementPersistenceReconciliationFailures(),log$5.warn({err:e,documentName:g},`[persistence] reconcileFragmentNow failed for ${g}`)}}let ye=null,Ce=null,we=null;function Te(){if(ye)return;let e=getMeter();ye=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),Ce=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),we=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}async function De({document:e,documentName:t,lastTransactionOrigin:g}){Te();let S=Date.now();return withSpan(`persistence.onStoreDocument`,{attributes:{"doc.name":t}},async()=>{let S=e.getMap(`lifecycle`).get(`status`);if(S===`deleted-upstream`||S===`renamed`){log$5.info({documentName:t,lifecycleStatus:S},`[persistence] Skipped store for ${t}: lifecycle=${S}`),q.delete(t),F.delete(t);return}if(!isDocQuiescent(e)){let s=q.get(t)??0;if(s<8){let g=getMsSinceLastUserTx(e);console.warn(JSON.stringify({event:`persistence-skip-non-quiescent`,"doc.name":t,wallClockMsSinceLastTransaction:g??null,deferCount:s})),incrementPersistenceSkipNonQuiescent(),q.set(t,s+1);return}console.warn(JSON.stringify({event:`persistence-force-flush-during-burst`,"doc.name":t,wallClockMsSinceLastTransaction:getMsSinceLastUserTx(e)??null,deferCount:s})),incrementPersistenceForceFlushDuringBurst()}let{sv:w,json:O}=captureDocSnapshotForPersistence(e),{frontmatter:j,body:B}=stripFrontmatter(e.getText(`source`).toString()),H=prependFrontmatter(j,B),J;try{J=assertBridgeInvariant(H,prependFrontmatter(j,mdManager.serialize(O)),{site:`persistence`,docName:t,suppressDevThrow:!0})}catch(e){incrementPersistenceSanityCheckSerializeFailures(),console.warn(JSON.stringify({event:`persistence-sanity-check-serialize-failed`,"doc.name":t,"error.type":e instanceof Error?e.constructor.name:typeof e,timestamp:new Date().toISOString()})),log$5.warn({err:e,documentName:t},`[persistence] Sanity-check serialize failed for ${t}; proceeding with ytext bytes`),J=!1}J||ve(e,B,t);let Y=getReconciledBase(t);if(Y!==void 0&&normalizeBridge(H)===normalizeBridge(Y)){contributorCount()>0&&ge(),q.delete(t);return}if(Y===void 0&&normalizeBridge(H)===``){log$5.warn({documentName:t},`[persistence] Skipped phantom write for ${t}: empty Y.Doc with no reconciled base`),q.delete(t);return}let ee=resolveWriterFromOrigin(g,D);if(ee&&ee.id!==SERVICE_WRITER.id&&(hasContributor(ee.id)||recordContributor(t,ee.id,ee.name,ee.id)),Y!==void 0){let g=classifyDuplication(H,Y);if(g.kind===`block`){if(F.has(t)){log$5.warn({documentName:t},`[persistence] Tripwire breaker active — skipping duplicate store for ${t}`);return}let S=e.getXmlFragment(`default`).length;console.warn(JSON.stringify({event:`ok-persistence-duplication-blocked`,"doc.name":t,candidateBytes:H.length,baseBytes:Y.length,fragmentChildren:S,copies:g.copies,reason:g.reason}));try{let g=safeContentPath(t,s),S;if(existsSync(g)){let e=null;try{e=realpathSync(g)}catch(e){log$5.warn({err:e,documentName:t},`[persistence] Tripwire reset realpath failed for ${t}; using currentBase`)}if(e&&isWithinContentDir(e,s))try{S=readFileSync(e,`utf-8`)}catch(s){log$5.warn({err:s,documentName:t,canonical:e},`[persistence] Tripwire reset readFileSync failed for ${t}; using currentBase`),S=Y}else e&&console.warn(`[persistence] symlink-escape on tripwire reset: ${g} → ${e}, using currentBase`,{docName:t,originalPath:g,canonical:e,contentDir:s}),S=Y}else S=Y;e.transact(()=>{L(e,S)},FILE_WATCHER_ORIGIN),F.delete(t)}catch(e){F.add(t),log$5.error({err:e,documentName:t},`[persistence] Tripwire reset failed for ${t}`)}q.delete(t);return}}let te=safeContentPath(t,s);await tracedMkdir(dirname(te),{recursive:!0});let ne;try{ne=await realpath(te)}catch(e){let s=e.code;if(s===`ENOENT`){let e=!1;try{e=lstatSync(te).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&log$5.warn({err:e,path:te},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:t,reason:`broken-symlink`}),ne=te}else if(s===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${te}`),Error(`Symlink cycle detected at ${te}`);else throw e}if(!isWithinContentDir(ne,s)){let e=`symlink-escape: ${te} resolves to ${ne} outside ${s}`;throw console.error(`[persistence] ${e}`,{docName:t,originalPath:te,canonical:ne,contentDir:s}),Error(e)}let ae=`${ne}.tmp.${crypto.randomUUID()}`;try{await tracedWriteFile(ae,H,`utf-8`),await tracedRename(ae,ne),registerWrite(ne,contentHash(H)),incrementPersistenceDiskWrite();try{k?.(t,w)}catch(e){log$5.warn({err:e,documentName:t},`[persistence] onDiskFlush callback failed for ${t}`)}}catch(e){try{tracedUnlinkSync(ae)}catch{}throw q.delete(t),log$5.error({err:e,documentName:t},`[persistence] Failed to save ${t}`),e}log$5.info({filePath:ne,bytes:H.length},`[persistence] Wrote ${ne} (${H.length} bytes)`),setReconciledBase(t,H),F.delete(t),q.delete(t),E&&(E.updateDocumentFromMarkdown(t,H),E.saveToDisk().catch(e=>{log$5.warn({err:e,documentName:t},`[backlinks] Failed to persist cache for ${t}`)})),setActiveSpanAttributes({"persistence.bytes":H.length}),ge()}).finally(()=>{Ce?.record((Date.now()-S)/1e3)})}function je({document:e,documentName:t,lastTransactionOrigin:s}){ue.set(t,{branch:getActiveBranch(),document:e,lastTransactionOrigin:s})}async function Me(e=`within-branch`){return ce?(B=B===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,ce):(ce=(async()=>{let t=e;for(;;){let e=[...ue.entries()];if(ue.clear(),t!==`discard-stale`){for(let[t,s]of e)if(s.branch===getActiveBranch())try{await De({document:s.document,documentName:t,lastTransactionOrigin:s.lastTransactionOrigin})}catch(e){log$5.error({err:e,documentName:t},`[persistence] Deferred store failed for ${t}`)}}let s=B;if(B=null,ue.size===0&&s===null)break;t=s??`within-branch`}})().finally(()=>{ce=null}),ce)}let Pe={async onLoadDocument({document:t,documentName:g,context:S}){if(isSystemDoc(g))return;if(isConfigDoc(g)){loadConfigDoc(t,g,j);return}Te();let w=Date.now();return withSpan(`persistence.onLoadDocument`,{attributes:{"doc.name":g}},async()=>{log$5.info({documentName:g,connections:t.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${g} (connections: ${t.getConnectionsCount?.()??`?`})`);let S=safeContentPath(g,s);if(!existsSync(S))return;try{let e=realpathSync(S);if(!isWithinContentDir(e,s)){console.warn(`[persistence] symlink-escape on load: ${S} → ${e}, refusing`);return}}catch(e){if(e.code===`ELOOP`){console.warn(`[persistence] Symlink cycle on load: ${S}, refusing`);return}}let w=readFileSync(S,`utf-8`),E=t.getXmlFragment(`default`);log$5.info({documentName:g,fragmentLength:E.length},`[persistence] onLoadDocument ${g}: fragment.length=${E.length} before update`),E.length===0?(t.transact(()=>{applyDiskContentToDoc(t,w,e?.resolveEmbed,g)},FILE_WATCHER_ORIGIN),log$5.info({filePath:S,children:E.length},`[persistence] Loaded ${S} into Y.Doc (${E.length} children)`),E.observeDeep(()=>{log$5.info({documentName:g,fragmentLength:E.length},`[persistence] MUTATION on ${g}: fragment.length=${E.length}`)})):log$5.info({documentName:g,children:E.length},`[persistence] Skipped load for ${g} — fragment already has ${E.length} children`),setReconciledBase(g,w)}).finally(()=>{ye?.record((Date.now()-w)/1e3)})},async onStoreDocument({document:e,documentName:t,lastTransactionOrigin:s,lastContext:g}){if(!isSystemDoc(t)){if(isConfigDoc(t)){await storeConfigDoc(e,t,s,j);return}if(isBatchInProgress()){je({document:e,documentName:t,lastTransactionOrigin:s});return}return De({document:e,documentName:t,lastTransactionOrigin:s})}}};async function Ie(){oe&&await oe}return{extension:Pe,flushDeferredStores:Me,flushPendingGitCommit:_e,waitForPendingCommits:Ie,configPersistenceCtx:j}}const MARKDOWN_LINK_OR_IMAGE_RE=/!?\[[^\]\n]*(?:\][^[\]\n]*)?\]\((?:<([^>\n]+)>|([^)\s]+))(?:\s+['"][^'"]*['"])?\)/g,WIKI_LINK_OR_EMBED_RE=/!?\[\[([^[\]|#]+?)(?:#[^\]|]+?)?(?:\|[^\]]+?)?\]\]/g,HTML_LINK_ATTR_RE=/<[\w:-]+\b[^>]*?\s+(?:href|src)\s*=\s*(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function isRemoteOrOpaqueHref(e){return e.startsWith(`#`)||e.startsWith(`//`)||e.startsWith(`data:`)||/^[a-z][a-z0-9+.-]*:/i.test(e)}function stripHrefDecorations(e){let t=e.trim().replace(/^<(.+)>$/,`$1`),s=t.indexOf(`#`),g=s>=0?t.slice(0,s):t,S=g.indexOf(`?`);return S>=0?g.slice(0,S):g}function decodeHrefPath(e){let t=stripHrefDecorations(e);try{return decodeURI(t)}catch{return t}}function mediaKindForAssetPath(e){return mediaKindForSidebarAssetExtension(extname(e).slice(1).toLowerCase())}function errnoCode$1(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`?e.code:null}function collectHrefsFromLine(e,t){for(let s of e.matchAll(MARKDOWN_LINK_OR_IMAGE_RE)){let e=s[1]??s[2];e&&t.add(e)}for(let s of e.matchAll(WIKI_LINK_OR_EMBED_RE)){let e=s[1];e&&t.add(e)}for(let s of e.matchAll(HTML_LINK_ATTR_RE)){let e=s[1]??s[2]??s[3]??s[4];e&&t.add(e)}}function stripHtmlComments(e,t){let s=e,g=``;for(;s.length>0;){if(t.inComment){let e=s.indexOf(`-->`);if(e===-1)return g;s=s.slice(e+3),t.inComment=!1;continue}let e=s.indexOf(`<!--`);if(e===-1)return g+s;g+=s.slice(0,e),s=s.slice(e+4),t.inComment=!0}return g}function extractLocalAssetHrefs(e){let t=new Set,s=createCodeFenceTracker(),g={inComment:!1};for(let S of e.replaceAll(`\r
@@ -1605,6 +1605,6 @@ In headless mode, write the recap into the research article's "Further reading"
1605
1605
  `).map(e=>e.trim()).filter(Boolean):[]}catch(t){log.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.error=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let s=[],g=[];for(let e of t){let t=join(this.projectDir,e),S=relative(this.contentDir,t);!S.startsWith(`..`)&&!this.contentFilter.isExcluded(S)?s.push(e):g.push(e)}for(let t of g)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log.warn({err:e,file:t},`[sync] auto-resolve failed — escalating to content conflict`),s.push(t)}if(s.length>0){for(let e of s)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log.warn({files:s},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),log.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async abortMerge(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),log.info({},`[sync] merge aborted`)}catch(e){log.warn({err:e},`[sync] git merge --abort failed — conflicts.json still cleared`)}this.conflictStore.clear(),this.conflictCount=0,this.transitionTo(`idle`),this.scheduleSaveState()}handleError(e){this.error=e.message,log.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,log.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:this.pausedReason,pausedSinceUtc:this.pausedReason?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};writeFileSync(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){log.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason;let s=t.inflightConflicts??[];if(s.length>0){for(let e of s)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log.warn({err:e},`[sync] failed to load sync state`)}}};const TAG_VALUE_RE=createTagInTextRegex();function createEmptyState(){return{byTag:new Map,byDoc:new Map,byDocLiteral:new Map}}function stripInlineCodeSpans(e){return e.replace(/`[^`]*`/g,``)}function extractInlineTagsFromBody(e){let t=e.replaceAll(`\r
1606
1606
  `,`
1607
1607
  `).split(`
1608
- `),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);if(e===null)break;let t=e[2];t&&s.push(t)}}return s}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:s,body:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let s of t){let t=this.state.byTag.get(s);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(s))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,s){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,s)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let s=[];for(let g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].sort((e,t)=>e.localeCompare(t))})}return s.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),s=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&s.add(e.slice(0,t));let g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!s.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:s}of e)try{let e=readFileSync(s,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,s){let g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.size===0&&this.state.byTag.delete(t))}for(let t of s){let s=this.state.byTag.get(t);s||(s=new Set,this.state.byTag.set(t,s)),s.add(e)}s.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,s),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let s;try{s=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=relative(this.contentDir,s);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=relative(this.contentDir,s);this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),filePath:s})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:s=t,quiet:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1}=e,J=getLogger(`server`);function Y(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>J.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||J.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>J.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ee=randomUUID(),te=getLocalDir(t);if(acquireServerLock(te,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:te,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(te),e}let ne=createBasenameIndex(),ae=(e,t)=>ne.resolveEmbed(e,t),oe,se,ce,ue,de,fe,me,ge=null,_e=null,ve=null,ye=null,Ce=new Set,we=!1,Te;function De(e){ge?.signal(e)}let je=2e3,Me=null;function Pe(){Me!==null&&clearTimeout(Me),Me=setTimeout(()=>{Me=null,se.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}try{oe=createContentFilter({projectDir:s,contentDir:t,onAfterRebuild:()=>{se.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{ce.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}}}),se=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:oe}),ce=new TagIndex({contentDir:t,contentFilter:oe});try{ce.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}ue={current:F},de=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:ue,contentRoot:L,backlinkIndex:se,configHomedirOverride:k,getCurrentBranch:()=>st?.getLastKnownBranch()??null,resolveEmbed:ae,getPrincipal:()=>ye,onAgentCommit:()=>ge?.signal(`session-activity`),onDiskFlush:(e,t)=>ge?.emitDiskAck(e,t),onConfigRejected:(e,t)=>ge?.emitConfigValidationRejected(e,t)}),fe=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[de.extension]});let B=fe.shouldUnloadDocument.bind(fe);fe.shouldUnloadDocument=e=>{if((we||Ce.has(e))&&B(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},Te=async e=>{Ce.add(e);try{await fe.unloadDocument(e)}finally{Ce.delete(e)}},ge=new CC1Broadcaster(fe),_e=new AgentFocusBroadcaster(fe),ve=new AgentPresenceBroadcaster(fe),me=new AgentSessionManager(fe);let q=createLiveDerivedIndexExtension({backlinkIndex:se,tagIndex:ce,signalChannel:De});fe.configuration.extensions.push(q),fe.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,s=parseHocuspocusAuthToken(t),g=s?.expectedServerInstanceId;if(typeof g==`string`&&g.length>0&&g!==ee)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ee}`);let S=s?.expectedBranch,w=getActiveBranch();if(typeof S==`string`&&S.length>0&&S!==w)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${S}, server is on ${w}`);if(!s)return;let E=e.context;typeof s.principalId==`string`&&(ye&&s.principalId===ye.id?E.principalId=ye.id:ye?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:ye.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),fe.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,s=t.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s))throw Error(`config-doc admission requires loopback peer (peer=${s}, doc=${e.documentName})`);let g=e.requestHeaders,S=(g&&typeof g.get==`function`?g.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(S))throw Error(`config-doc admission requires loopback Host header (host=${S??`<absent>`}, doc=${e.documentName})`)}}),fe.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let J=createApiExtension({hocuspocus:fe,sessionManager:me,contentDir:t,contentFilter:oe,serverInstanceId:ee,getFileIndex:()=>at?at.getFileIndex():new Map,getAliasMap:()=>at?at.getAliasMap():new Map,enableTestRoutes:j,shadowRef:ue,flushGitCommit:()=>de.flushPendingGitCommit(),getCurrentBranch:()=>st?.getLastKnownBranch()??null,getDiskAckSVs:()=>ge?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:se,tagIndex:ce,signalChannel:De,agentFocusBroadcaster:_e,agentPresenceBroadcaster:ve,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>vt,localOpCliArgs:H,projectDir:s,resolveEmbed:ae,getPrincipal:()=>ye,forceUnloadDocument:Te});fe.configuration.extensions.push(J),fe.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:ue,contentRoot:L,getCurrentBranch:()=>st?.getLastKnownBranch()??null,resolveEmbed:ae}))}catch(e){throw releaseServerLock(te),e}let Ie=null,Re=new Map,ze=[];function Be(e,t){let s=resolve(e,`rescue`),g=resolve(s,`${t}${getDocExtension(t)}`);return g.startsWith(`${s}/`)?g:null}function Ve(e){let t=fe.documents.get(e);if(!t)return null;let{frontmatter:s,body:g}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(s,g)}let Ue=(e,t)=>applyExternalChange(fe,e,t,ae),We=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of fe.documents){if(isSystemDoc(s)||isConfigDoc(s))continue;let g=fe.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,ae,s)},FILE_WATCHER_ORIGIN)}catch(t){J.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},Ge=null,Ke=e=>{e&&(Ge===null&&(Ge=new Set,setImmediate(()=>{let e=Ge;if(Ge=null,e)try{for(let t of e)We(t)}catch(t){J.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Ge.add(e))};function Xe(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:return e.relativePath;default:return e.docName}}async function $e(e){try{switch(e.kind){case`create`:J.info({docName:e.docName},`[reconcile] create: ${e.docName}`),se.updateDocumentFromMarkdown(e.docName,e.content),Pe(),ce.updateDocumentFromMarkdown(e.docName,e.content),De(`files`),De(`backlinks`),De(`graph`),De(`tags`);break;case`update`:{let{docName:t,content:s}=e,g=fe.documents.get(t);if(!g){se.updateDocumentFromMarkdown(t,s),Pe(),ce.updateDocumentFromMarkdown(t,s),De(`backlinks`),De(`graph`),De(`tags`);return}let S=getReconciledBase(t)??``,w=Ve(t)??S,E=reconcile({docName:t,base:S,ours:w,theirs:s}),D=contentHash(S).slice(0,6),O=contentHash(w).slice(0,6),k=contentHash(s).slice(0,6);switch(J.info({docName:t,base:D,ours:O,theirs:k,result:E.kind},`[reconcile] ${t} base=${D} ours=${O} theirs=${k} result=${E.kind}`),E.kind){case`noop`:se.updateDocumentFromMarkdown(t,s),Pe(),ce.updateDocumentFromMarkdown(t,s),De(`backlinks`),De(`graph`),De(`tags`);break;case`clean`:try{Ue(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),se.updateDocumentFromMarkdown(t,s),Pe(),ce.updateDocumentFromMarkdown(t,s),De(`backlinks`),De(`graph`),De(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`merged`:try{Ue(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),se.updateDocumentFromMarkdown(t,s),Pe(),ce.updateDocumentFromMarkdown(t,s),De(`backlinks`),De(`graph`),De(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`conflicts`:try{Ue(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),se.updateDocumentFromMarkdown(t,s),Pe(),ce.updateDocumentFromMarkdown(t,s),De(`backlinks`),De(`graph`),De(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`refused`:{incrementConflict();let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,E.reason);break}}break}case`delete`:{let{docName:t}=e,s=fe.documents.get(t);if(!s){se.deleteDocument(t),Pe(),ce.deleteDocument(t),De(`files`),De(`backlinks`),De(`graph`),De(`tags`);return}let g=getReconciledBase(t)??``,S=Ve(t)??``,w=S!==g;if(w&&ue.current){let e=ue.current,s=st?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,L??``,{kind:`external-change-rescue`,docName:t,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:s,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),J.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{J.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),se.deleteDocument(t),Pe(),ce.deleteDocument(t),J.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),fe.closeConnections(t),await Te(s),De(`files`),De(`backlinks`),De(`graph`),De(`tags`);break}case`rename`:{let{oldDocName:t,newDocName:s,content:g}=e,S=fe.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),se.renameDocument(t,s,g),Pe(),ce.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}J.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),De(`files`),De(`backlinks`),De(`graph`),De(`tags`);break}case`conflict`:{let{docName:t}=e,s=fe.documents.get(t);if(!s)return;let g=s.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),J.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ne.add(e.relativePath),De(`files`),Ke(basename(e.relativePath));break;case`asset-delete`:ne.remove(e.relativePath),De(`files`),Ke(basename(e.relativePath));break;default:assertNeverDiskEvent(e)}}catch(t){let s=Xe(e);J.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let nt=[];async function rt(e){if(isBatchInProgress()){nt.push(e);return}await $e(e)}async function it(){let e=nt.splice(0,nt.length);for(let t of e)await $e(t)}let at=null,st=null,vt=null,Tt=null;async function Et(e){if(fe.documents.size===0)return;let t=!1,s=new Promise(e=>{fe.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(fe.documents.keys());fe.closeConnections(),fe.flushPendingStores();for(let e of fe.documents.values())e.getConnectionsCount()===0&&fe.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let S,w=new Promise((s,w)=>{S=setTimeout(()=>{t=!0;let s=Array.from(fe.documents.keys()),S=[],E=[];if(ue.current){for(let e of s)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=Ve(e);if(t===null){J.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=Be(ue.current.gitDir,e);if(!s){J.warn({docName:e,gitDir:ue.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),E.push(e);continue}mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,t,`utf-8`),incrementRescueBuffer(),S.push(e),J.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),J.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else J.warn({stillLoadedCount:s.length},`[rescue] shadow repo unavailable at flush timeout — ${s.length} doc(s) will be lost: [${s.join(`, `)}]`),E.push(...s);let D=S.length>0||E.length>0?` — rescued [${S.join(`, `)}]${E.length>0?`, lost [${E.join(`, `)}]`:``}`:``;w(Error(`flushAllStoresAndWait timeout after ${e}ms — ${s.length}/${g.length} docs did not unload: [${s.join(`, `)}]${D}`))},e)});try{await Promise.race([s,w])}finally{S!==void 0&&clearTimeout(S)}}async function Dt(){return Tt||(Tt=(async()=>{let e=Date.now(),t=[];we=!0,Me!==null&&(clearTimeout(Me),Me=null);let g,S=await Promise.race([Ft.then(()=>`completed`,e=>(J.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&J.warn({},`[server] init did not complete within 5s during shutdown`);let w=fe.documents.size;try{try{try{st&&=(await st.unsubscribe(),null),at&&=(await at.unsubscribe(),null);for(let{docName:e,cleanup:t}of ze)try{await t()}catch(t){J.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}ze.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ge?.destroy(),ve?.destroy(),Ie&&=(await Ie.disconnect(),null);for(let[e,t]of Re)try{await t.disconnect()}catch(t){J.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Re.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await me.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Et(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await de.flushPendingGitCommit(),await de.waitForPendingCommits()})(),new Promise((t,s)=>{e=setTimeout(()=>s(Error(`L2 git flush timeout`)),B)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{vt&&=(await vt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(ue.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(ue.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(ue.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?J.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):J.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(te)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Tt)}let jt=[];async function Mt(){try{ye=await loadPrincipal(t),J.info({principalId:ye.id},`[server] principal loaded`)}catch(e){J.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!ue.current)try{ue.current=await initShadowRepo(s),J.info({gitDir:ue.current.gitDir},`[server] history repo initialized at ${ue.current.gitDir}`)}catch(e){J.error({err:e},`[server] history repo init failed`),jt.push(`shadow-repo`)}if(ue.current)try{await shadowGit(ue.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){J.warn({},`[server] history repo appears corrupted — reinitializing`);try{ue.current=await initShadowRepo(s)}catch(e){J.error({err:e},`[server] history repo reinit failed`),ue.current=void 0,jt.includes(`shadow-repo`)||jt.push(`shadow-repo`)}}else J.error({err:e},`[server] history repo check failed (transient?)`)}if(ue.current)try{let e=resolve(ue.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let g=null;try{g=(await esm_default({baseDir:s,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(g!==null){if(g!==t){let e=`main`;try{let t=(await esm_default({baseDir:s,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}J.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(ue.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){J.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else J.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){J.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){J.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,s=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;J.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){J.error({err:e},`[server] managed rename recovery failed`),jt.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(t);(e.deleted>0||e.errors>0)&&J.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){J.error({err:e},`[server] upload-tempfile sweep failed`),jt.push(`upload-tempfile-sweep`)}try{Ie=await fe.openDirectConnection(SYSTEM_DOC_NAME),ge?.emitServerInfo(ee,getActiveBranch())}catch(e){J.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),jt.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await fe.openDirectConnection(e);Re.set(e,t)}catch(t){J.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),jt.push(`config-doc:${e}`)}let e=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,s)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,s)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,s,k)]]);for(let t of CONFIG_DOC_NAMES){let s=e.get(t);if(s)try{J.info({docName:t,path:s},`[config-file-watcher] starting`);let e=await startConfigFileWatcher(s,e=>{let s=fe.documents.get(t);J.info({docName:t,hasDocument:s!==void 0,contentLength:e.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,t,e,de.configPersistenceCtx);if(J.info({docName:t,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),t===`__config__/project`||t===`__local__/project`){let e=Y();vt?.setEnabled(e).catch(t=>{J.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});ze.push({docName:t,cleanup:e}),J.info({docName:t,path:s},`[config-file-watcher] started`)}catch(e){J.warn({err:e,docName:t,path:s},`[config-file-watcher] failed to start for ${t}`),jt.push(`config-file-watcher:${t}`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=J;S.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore`);let w=await startMultiPathConfigFileWatcher([e,g],(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(fe.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,de.configPersistenceCtx);S.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){S.error({err:e,changedPath:relative(s,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let w=await oe.rebuildIgnorePatterns();if(w.ok)S.info({changedPath:relative(s,t),patternCount:w.patternCount,nestedFileCount:w.nestedFileCount,durationMs:w.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ge?.signal(`files`);else{let e=relative(s,t)||`.`;S.warn({changedPath:e,error:w.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ge?.emitConfigIgnoreNestedError(e,w.error.message)}})().catch(e=>{S.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});ze.push({docName:`__ignore-files__`,cleanup:w}),S.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`)}catch(e){J.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),jt.push(`ignore-files-watcher`)}let g=resolveGitDir(s),S=g?readBranchFromHead(g)??`main`:`main`;switchReconciledBaseScope(S),se.switchBranch(S);try{{let e=getActiveBranch();try{if(await se.loadFromDisk(e)){let t=await se.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&J.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await se.rebuildFromDisk(e);se.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){J.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}at=await startWatcher(t,rt,oe),ce.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:oe,basenameIndex:ne,onSkip:(t,s,g)=>{e++,J.warn({reason:t,code:s,path:g},`[basename-index] skipped entry during seed (${t}${s?` ${s}`:``})`)}}),e>0&&(J.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),jt.push(`basename-index-partial`))}catch(e){J.error({err:e},`[basename-index] startup seed failed`),jt.push(`basename-index`)}}catch(e){J.error({err:e},`[server] disk bridge watcher failed to start`),jt.push(`file-watcher`)}try{st=await startHeadWatcher(s,async({trigger:e})=>{if(J.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),fe.flushPendingStores(),await de.flushPendingGitCommit(),setBatchInProgress(!0),ue.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of fe.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let s=null;if(t.transact(()=>{s=Ve(e)},PARK_SNAPSHOT_ORIGIN),s===null)continue;let g=getReconciledBase(e)??s;S.push({docName:e,markdown:s,diskSnapshot:g})}if(S.length>0)try{let t=await parkBranch(ue.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),J.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){J.error({err:e},`[shadow] park failed`)}}},async e=>{let s=nt.length,g=e.newBranch??`main`;if(J.info({kind:e.batchKind,headMoved:e.headMoved,docs:s,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${s}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)setBatchInProgress(!1),await it(),await de.flushDeferredStores(`within-branch`);else{incrementBranchSwitch(),nt.splice(0,nt.length),switchReconciledBaseScope(g),Me!==null&&(clearTimeout(Me),Me=null),se.switchBranch(g),oe.rebuildDirCount();try{let e=0;ne.clear(),seedBasenameIndex({contentDir:t,contentFilter:oe,basenameIndex:ne,onSkip:(t,s,S)=>{e++,J.warn({reason:t,code:s,path:S,branch:g},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(J.warn({count:e,branch:g},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),jt.includes(`basename-index-partial`)||jt.push(`basename-index-partial`))}catch(e){J.error({err:e,branch:g},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of fe.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let S=safeContentPath(e,t);if(!existsSync(S)){let t=getReconciledBase(e)??``,S=Ve(e)??``;if(S!==t&&ue.current){let t=ue.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:g,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),J.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{J.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),J.info({docName:e,branch:g},`[branch-switch] tombstone: ${e} (not on ${g})`);continue}let w=readFileSync(S,`utf-8`);Ue(e,w),setReconciledBase(e,w),J.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){J.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}J.info({branch:g,docCount:fe.documents.size},`[branch-switch] loaded branch ${g} (${fe.documents.size} docs)`);try{if(await se.loadFromDisk(g)){let e=await se.reconcileWithDisk(g);(e.added>0||e.updated>0||e.deleted>0)&&J.info(e,`[backlinks] branch-switch reconcile for ${g}`)}else await se.rebuildFromDisk(g);se.saveToDisk(g).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${g}:`,e)})}catch(e){J.error({err:e,branch:g},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(ce.init(),ue.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of fe.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let s=await readParkedState(ue.current,g,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let S=getReconciledBase(t);if(!S)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:S});switch(w.kind){case`merged`:case`clean`:Ue(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:Ue(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){J.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&J.info({count:e,branch:g},`[branch-switch] restored ${e} parked docs on ${g}`)}if(e.oldBranch?.startsWith(`detached-`)&&ue.current)try{let t=shadowGit(ue.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
1608
+ `),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);if(e===null)break;let t=e[2];t&&s.push(t)}}return s}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:s,body:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let s of t){let t=this.state.byTag.get(s);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(s))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,s){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,s)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let s=[];for(let g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].sort((e,t)=>e.localeCompare(t))})}return s.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),s=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&s.add(e.slice(0,t));let g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!s.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:s}of e)try{let e=readFileSync(s,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,s){let g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.size===0&&this.state.byTag.delete(t))}for(let t of s){let s=this.state.byTag.get(t);s||(s=new Set,this.state.byTag.set(t,s)),s.add(e)}s.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,s),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let s;try{s=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=relative(this.contentDir,s);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=relative(this.contentDir,s);this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),filePath:s})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:s=t,quiet:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1}=e,J=getLogger(`server`);function Y(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>J.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||J.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>J.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ee=randomUUID(),te=getLocalDir(t);if(acquireServerLock(te,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:te,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(te),e}let ne=createBasenameIndex(),ae=(e,t)=>ne.resolveEmbed(e,t),oe,se,ce,ue,de,fe,me,ge=null,_e=null,ve=null,ye=null,Ce=new Set,we=!1,Te;function De(e){ge?.signal(e)}let je=2e3,Me=null;function Pe(){Me!==null&&clearTimeout(Me),Me=setTimeout(()=>{Me=null,se.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}try{oe=createContentFilter({projectDir:s,contentDir:t,onAfterRebuild:()=>{se.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{ce.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let e=at?.pruneFileIndexNowExcluded()??0;e>0&&getLogger(`server-factory`).info({pruned:e},`[content-filter] pruned now-excluded entries from fileIndex`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] fileIndex prune failed after onAfterRebuild`)}}}),se=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:oe}),ce=new TagIndex({contentDir:t,contentFilter:oe});try{ce.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}ue={current:F},de=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:ue,contentRoot:L,backlinkIndex:se,configHomedirOverride:k,getCurrentBranch:()=>st?.getLastKnownBranch()??null,resolveEmbed:ae,getPrincipal:()=>ye,onAgentCommit:()=>ge?.signal(`session-activity`),onDiskFlush:(e,t)=>ge?.emitDiskAck(e,t),onConfigRejected:(e,t)=>ge?.emitConfigValidationRejected(e,t)}),fe=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[de.extension]});let B=fe.shouldUnloadDocument.bind(fe);fe.shouldUnloadDocument=e=>{if((we||Ce.has(e))&&B(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},Te=async e=>{Ce.add(e);try{await fe.unloadDocument(e)}finally{Ce.delete(e)}},ge=new CC1Broadcaster(fe),_e=new AgentFocusBroadcaster(fe),ve=new AgentPresenceBroadcaster(fe),me=new AgentSessionManager(fe);let q=createLiveDerivedIndexExtension({backlinkIndex:se,tagIndex:ce,signalChannel:De});fe.configuration.extensions.push(q),fe.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,s=parseHocuspocusAuthToken(t),g=s?.expectedServerInstanceId;if(typeof g==`string`&&g.length>0&&g!==ee)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ee}`);let S=s?.expectedBranch,w=getActiveBranch();if(typeof S==`string`&&S.length>0&&S!==w)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${S}, server is on ${w}`);if(!s)return;let E=e.context;typeof s.principalId==`string`&&(ye&&s.principalId===ye.id?E.principalId=ye.id:ye?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:ye.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),fe.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,s=t.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s))throw Error(`config-doc admission requires loopback peer (peer=${s}, doc=${e.documentName})`);let g=e.requestHeaders,S=(g&&typeof g.get==`function`?g.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(S))throw Error(`config-doc admission requires loopback Host header (host=${S??`<absent>`}, doc=${e.documentName})`)}}),fe.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let J=createApiExtension({hocuspocus:fe,sessionManager:me,contentDir:t,contentFilter:oe,serverInstanceId:ee,getFileIndex:()=>at?at.getFileIndex():new Map,getAliasMap:()=>at?at.getAliasMap():new Map,enableTestRoutes:j,shadowRef:ue,flushGitCommit:()=>de.flushPendingGitCommit(),getCurrentBranch:()=>st?.getLastKnownBranch()??null,getDiskAckSVs:()=>ge?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:se,tagIndex:ce,signalChannel:De,agentFocusBroadcaster:_e,agentPresenceBroadcaster:ve,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>vt,localOpCliArgs:H,projectDir:s,resolveEmbed:ae,getPrincipal:()=>ye,forceUnloadDocument:Te});fe.configuration.extensions.push(J),fe.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:ue,contentRoot:L,getCurrentBranch:()=>st?.getLastKnownBranch()??null,resolveEmbed:ae}))}catch(e){throw releaseServerLock(te),e}let Ie=null,Re=new Map,ze=[];function Be(e,t){let s=resolve(e,`rescue`),g=resolve(s,`${t}${getDocExtension(t)}`);return g.startsWith(`${s}/`)?g:null}function Ve(e){let t=fe.documents.get(e);if(!t)return null;let{frontmatter:s,body:g}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(s,g)}let Ue=(e,t)=>applyExternalChange(fe,e,t,ae),We=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of fe.documents){if(isSystemDoc(s)||isConfigDoc(s))continue;let g=fe.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,ae,s)},FILE_WATCHER_ORIGIN)}catch(t){J.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},Ge=null,Ke=e=>{e&&(Ge===null&&(Ge=new Set,setImmediate(()=>{let e=Ge;if(Ge=null,e)try{for(let t of e)We(t)}catch(t){J.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Ge.add(e))};function Xe(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:return e.relativePath;default:return e.docName}}async function $e(e){try{switch(e.kind){case`create`:J.info({docName:e.docName},`[reconcile] create: ${e.docName}`),se.updateDocumentFromMarkdown(e.docName,e.content),Pe(),ce.updateDocumentFromMarkdown(e.docName,e.content),De(`files`),De(`backlinks`),De(`graph`),De(`tags`);break;case`update`:{let{docName:t,content:s}=e,g=fe.documents.get(t);if(!g){se.updateDocumentFromMarkdown(t,s),Pe(),ce.updateDocumentFromMarkdown(t,s),De(`backlinks`),De(`graph`),De(`tags`);return}let S=getReconciledBase(t)??``,w=Ve(t)??S,E=reconcile({docName:t,base:S,ours:w,theirs:s}),D=contentHash(S).slice(0,6),O=contentHash(w).slice(0,6),k=contentHash(s).slice(0,6);switch(J.info({docName:t,base:D,ours:O,theirs:k,result:E.kind},`[reconcile] ${t} base=${D} ours=${O} theirs=${k} result=${E.kind}`),E.kind){case`noop`:se.updateDocumentFromMarkdown(t,s),Pe(),ce.updateDocumentFromMarkdown(t,s),De(`backlinks`),De(`graph`),De(`tags`);break;case`clean`:try{Ue(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),se.updateDocumentFromMarkdown(t,s),Pe(),ce.updateDocumentFromMarkdown(t,s),De(`backlinks`),De(`graph`),De(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`merged`:try{Ue(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),se.updateDocumentFromMarkdown(t,s),Pe(),ce.updateDocumentFromMarkdown(t,s),De(`backlinks`),De(`graph`),De(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`conflicts`:try{Ue(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),se.updateDocumentFromMarkdown(t,s),Pe(),ce.updateDocumentFromMarkdown(t,s),De(`backlinks`),De(`graph`),De(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`refused`:{incrementConflict();let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,E.reason);break}}break}case`delete`:{let{docName:t}=e,s=fe.documents.get(t);if(!s){se.deleteDocument(t),Pe(),ce.deleteDocument(t),De(`files`),De(`backlinks`),De(`graph`),De(`tags`);return}let g=getReconciledBase(t)??``,S=Ve(t)??``,w=S!==g;if(w&&ue.current){let e=ue.current,s=st?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,L??``,{kind:`external-change-rescue`,docName:t,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:s,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),J.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{J.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),se.deleteDocument(t),Pe(),ce.deleteDocument(t),J.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),fe.closeConnections(t),await Te(s),De(`files`),De(`backlinks`),De(`graph`),De(`tags`);break}case`rename`:{let{oldDocName:t,newDocName:s,content:g}=e,S=fe.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),se.renameDocument(t,s,g),Pe(),ce.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}J.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),De(`files`),De(`backlinks`),De(`graph`),De(`tags`);break}case`conflict`:{let{docName:t}=e,s=fe.documents.get(t);if(!s)return;let g=s.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),J.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ne.add(e.relativePath),De(`files`),Ke(basename(e.relativePath));break;case`asset-delete`:ne.remove(e.relativePath),De(`files`),Ke(basename(e.relativePath));break;default:assertNeverDiskEvent(e)}}catch(t){let s=Xe(e);J.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let nt=[];async function rt(e){if(isBatchInProgress()){nt.push(e);return}await $e(e)}async function it(){let e=nt.splice(0,nt.length);for(let t of e)await $e(t)}let at=null,st=null,vt=null,Tt=null;async function Et(e){if(fe.documents.size===0)return;let t=!1,s=new Promise(e=>{fe.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(fe.documents.keys());fe.closeConnections(),fe.flushPendingStores();for(let e of fe.documents.values())e.getConnectionsCount()===0&&fe.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let S,w=new Promise((s,w)=>{S=setTimeout(()=>{t=!0;let s=Array.from(fe.documents.keys()),S=[],E=[];if(ue.current){for(let e of s)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=Ve(e);if(t===null){J.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=Be(ue.current.gitDir,e);if(!s){J.warn({docName:e,gitDir:ue.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),E.push(e);continue}mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,t,`utf-8`),incrementRescueBuffer(),S.push(e),J.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),J.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else J.warn({stillLoadedCount:s.length},`[rescue] shadow repo unavailable at flush timeout — ${s.length} doc(s) will be lost: [${s.join(`, `)}]`),E.push(...s);let D=S.length>0||E.length>0?` — rescued [${S.join(`, `)}]${E.length>0?`, lost [${E.join(`, `)}]`:``}`:``;w(Error(`flushAllStoresAndWait timeout after ${e}ms — ${s.length}/${g.length} docs did not unload: [${s.join(`, `)}]${D}`))},e)});try{await Promise.race([s,w])}finally{S!==void 0&&clearTimeout(S)}}async function Dt(){return Tt||(Tt=(async()=>{let e=Date.now(),t=[];we=!0,Me!==null&&(clearTimeout(Me),Me=null);let g,S=await Promise.race([Ft.then(()=>`completed`,e=>(J.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&J.warn({},`[server] init did not complete within 5s during shutdown`);let w=fe.documents.size;try{try{try{st&&=(await st.unsubscribe(),null),at&&=(await at.unsubscribe(),null);for(let{docName:e,cleanup:t}of ze)try{await t()}catch(t){J.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}ze.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ge?.destroy(),ve?.destroy(),Ie&&=(await Ie.disconnect(),null);for(let[e,t]of Re)try{await t.disconnect()}catch(t){J.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Re.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await me.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Et(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await de.flushPendingGitCommit(),await de.waitForPendingCommits()})(),new Promise((t,s)=>{e=setTimeout(()=>s(Error(`L2 git flush timeout`)),B)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{vt&&=(await vt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(ue.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(ue.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(ue.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?J.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):J.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(te)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Tt)}let jt=[];async function Mt(){try{ye=await loadPrincipal(t),J.info({principalId:ye.id},`[server] principal loaded`)}catch(e){J.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!ue.current)try{ue.current=await initShadowRepo(s),J.info({gitDir:ue.current.gitDir},`[server] history repo initialized at ${ue.current.gitDir}`)}catch(e){J.error({err:e},`[server] history repo init failed`),jt.push(`shadow-repo`)}if(ue.current)try{await shadowGit(ue.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){J.warn({},`[server] history repo appears corrupted — reinitializing`);try{ue.current=await initShadowRepo(s)}catch(e){J.error({err:e},`[server] history repo reinit failed`),ue.current=void 0,jt.includes(`shadow-repo`)||jt.push(`shadow-repo`)}}else J.error({err:e},`[server] history repo check failed (transient?)`)}if(ue.current)try{let e=resolve(ue.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let g=null;try{g=(await esm_default({baseDir:s,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(g!==null){if(g!==t){let e=`main`;try{let t=(await esm_default({baseDir:s,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}J.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(ue.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){J.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else J.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){J.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){J.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,s=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;J.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){J.error({err:e},`[server] managed rename recovery failed`),jt.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(t);(e.deleted>0||e.errors>0)&&J.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){J.error({err:e},`[server] upload-tempfile sweep failed`),jt.push(`upload-tempfile-sweep`)}try{Ie=await fe.openDirectConnection(SYSTEM_DOC_NAME),ge?.emitServerInfo(ee,getActiveBranch())}catch(e){J.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),jt.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await fe.openDirectConnection(e);Re.set(e,t)}catch(t){J.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),jt.push(`config-doc:${e}`)}let e=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,s)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,s)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,s,k)]]);for(let t of CONFIG_DOC_NAMES){let s=e.get(t);if(s)try{J.info({docName:t,path:s},`[config-file-watcher] starting`);let e=await startConfigFileWatcher(s,e=>{let s=fe.documents.get(t);J.info({docName:t,hasDocument:s!==void 0,contentLength:e.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,t,e,de.configPersistenceCtx);if(J.info({docName:t,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),t===`__config__/project`||t===`__local__/project`){let e=Y();vt?.setEnabled(e).catch(t=>{J.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});ze.push({docName:t,cleanup:e}),J.info({docName:t,path:s},`[config-file-watcher] started`)}catch(e){J.warn({err:e,docName:t,path:s},`[config-file-watcher] failed to start for ${t}`),jt.push(`config-file-watcher:${t}`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=J;S.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore`);let w=await startMultiPathConfigFileWatcher([e,g],(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(fe.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,de.configPersistenceCtx);S.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){S.error({err:e,changedPath:relative(s,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let w=await oe.rebuildIgnorePatterns();if(w.ok)S.info({changedPath:relative(s,t),patternCount:w.patternCount,nestedFileCount:w.nestedFileCount,durationMs:w.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ge?.signal(`files`);else{let e=relative(s,t)||`.`;S.warn({changedPath:e,error:w.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ge?.emitConfigIgnoreNestedError(e,w.error.message)}})().catch(e=>{S.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});ze.push({docName:`__ignore-files__`,cleanup:w}),S.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`)}catch(e){J.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),jt.push(`ignore-files-watcher`)}let g=resolveGitDir(s),S=g?readBranchFromHead(g)??`main`:`main`;switchReconciledBaseScope(S),se.switchBranch(S);try{{let e=getActiveBranch();try{if(await se.loadFromDisk(e)){let t=await se.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&J.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await se.rebuildFromDisk(e);se.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){J.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}at=await startWatcher(t,rt,oe),ce.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:oe,basenameIndex:ne,onSkip:(t,s,g)=>{e++,J.warn({reason:t,code:s,path:g},`[basename-index] skipped entry during seed (${t}${s?` ${s}`:``})`)}}),e>0&&(J.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),jt.push(`basename-index-partial`))}catch(e){J.error({err:e},`[basename-index] startup seed failed`),jt.push(`basename-index`)}}catch(e){J.error({err:e},`[server] disk bridge watcher failed to start`),jt.push(`file-watcher`)}try{st=await startHeadWatcher(s,async({trigger:e})=>{if(J.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),fe.flushPendingStores(),await de.flushPendingGitCommit(),setBatchInProgress(!0),ue.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of fe.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let s=null;if(t.transact(()=>{s=Ve(e)},PARK_SNAPSHOT_ORIGIN),s===null)continue;let g=getReconciledBase(e)??s;S.push({docName:e,markdown:s,diskSnapshot:g})}if(S.length>0)try{let t=await parkBranch(ue.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),J.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){J.error({err:e},`[shadow] park failed`)}}},async e=>{let s=nt.length,g=e.newBranch??`main`;if(J.info({kind:e.batchKind,headMoved:e.headMoved,docs:s,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${s}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)setBatchInProgress(!1),await it(),await de.flushDeferredStores(`within-branch`);else{incrementBranchSwitch(),nt.splice(0,nt.length),switchReconciledBaseScope(g),Me!==null&&(clearTimeout(Me),Me=null),se.switchBranch(g),oe.rebuildDirCount();try{let e=0;ne.clear(),seedBasenameIndex({contentDir:t,contentFilter:oe,basenameIndex:ne,onSkip:(t,s,S)=>{e++,J.warn({reason:t,code:s,path:S,branch:g},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(J.warn({count:e,branch:g},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),jt.includes(`basename-index-partial`)||jt.push(`basename-index-partial`))}catch(e){J.error({err:e,branch:g},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of fe.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let S=safeContentPath(e,t);if(!existsSync(S)){let t=getReconciledBase(e)??``,S=Ve(e)??``;if(S!==t&&ue.current){let t=ue.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:g,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),J.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{J.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),J.info({docName:e,branch:g},`[branch-switch] tombstone: ${e} (not on ${g})`);continue}let w=readFileSync(S,`utf-8`);Ue(e,w),setReconciledBase(e,w),J.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){J.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}J.info({branch:g,docCount:fe.documents.size},`[branch-switch] loaded branch ${g} (${fe.documents.size} docs)`);try{if(await se.loadFromDisk(g)){let e=await se.reconcileWithDisk(g);(e.added>0||e.updated>0||e.deleted>0)&&J.info(e,`[backlinks] branch-switch reconcile for ${g}`)}else await se.rebuildFromDisk(g);se.saveToDisk(g).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${g}:`,e)})}catch(e){J.error({err:e,branch:g},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(ce.init(),ue.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of fe.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let s=await readParkedState(ue.current,g,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let S=getReconciledBase(t);if(!S)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:S});switch(w.kind){case`merged`:case`clean`:Ue(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:Ue(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){J.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&J.info({count:e,branch:g},`[branch-switch] restored ${e} parked docs on ${g}`)}if(e.oldBranch?.startsWith(`detached-`)&&ue.current)try{let t=shadowGit(ue.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
1609
1609
  `))e&&await t.raw(`update-ref`,`-d`,e);J.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){J.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await de.flushDeferredStores(`discard-stale`),ge?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&ue.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(ue.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),J.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){J.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){J.error({err:e},`[server] HEAD watcher failed to start`),jt.push(`head-watcher`)}let w=H?.[0]??`open-knowledge`,E=[`-c`,`credential.helper=!${H&&H.length>1?H.join(` `):w} auth git-credential`];try{vt=new SyncEngine({projectDir:s,contentDir:t,contentFilter:oe,contentRoot:L,syncEnabled:Y(),credentialArgs:E,cc1Broadcaster:ge,setBatchInProgress:e=>{setBatchInProgress(e),e||de.flushDeferredStores(`within-branch`).catch(e=>{J.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{J.info({state:e},`[sync] state → ${e}`)},onAutoDisable:async e=>{J.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||J.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await vt.start()}catch(e){J.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),vt=null}}let Ft=Mt();return{hocuspocus:fe,sessionManager:me,cc1Broadcaster:ge,agentFocusBroadcaster:_e,agentPresenceBroadcaster:ve,contentFilter:oe,basenameIndex:ne,serverInstanceId:ee,destroy:Dt,ready:Ft,degraded:jt,lockDir:te,get syncEngine(){return vt}}}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let s=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&s.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let g=resolve(e,t);try{existsSync(g)&&statSync(g).isDirectory()&&s.push(`${t}/`)}catch{}}return s}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3;async function bootServer(e){initTelemetry();let{kind:t,gitdir:s}=computeWorktreeAttributes(e.projectDir??e.contentDir),g={"ok.worktree.kind":t};return s!==null&&(g[`ok.worktree.gitdir`]=normalizeFsPath(s)),withSpan(`ok.boot`,{attributes:g},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-D7DXNVql-B5nINglj.mjs`).then(e=>e.a),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let L=findLegacyRuntimeFiles(F);L.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${L.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let B=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck}),{hocuspocus:H,destroy:q,ready:J,degraded:Y,lockDir:ee,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:ae}=B,oe=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),se=e.port??0,ce=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${oe}:${se}`,log:S}),ue=D(),de=mountMcpAndApi({httpServer:ue,hocuspocus:H,mcpHttpHandler:ce,log:S,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:ae,keepaliveGraceMs:e.keepaliveGraceMs}),fe=null;g!==null&&(fe=attachIdleShutdown({httpServer:ue,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await q()})})),await new Promise((t,s)=>{let g=e=>s(e);ue.once(`error`,g),ue.listen(e.port,e.host,()=>{ue.removeListener(`error`,g),t()})});let me=ue.address(),ge=typeof me==`object`&&me?me.port:e.port??0;if(se=ge,O(ee,ge),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ee,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let _e=!1,ve=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};return{httpServer:ue,destroy:async()=>{if(_e)return;_e=!0;let e=[],t=async(t,s)=>{try{await ve(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{fe?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>de.shutdown()),await t(`mcpHttpHandler.close`,()=>ce.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{de.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{ue.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ue.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>q()),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},lockDir:ee,contentDir:e.contentDir,port:ge,ready:J,degraded:Y,didAutoInit:k,serverInstance:B}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`);if(existsSync(s)||await isInsideExistingWorkTree(t))return{didInit:!1};let g=``;try{g=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let s=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,s,{cause:e})}if(!existsSync(resolve(s,`HEAD`)))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,g);return console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0}}async function resolvePackageVersion(e,t){let s;try{s=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(s),g=0;g<32;g+=1){let s=join(t,`package.json`);if(existsSync(s))try{let t=JSON.parse(await readFile$1(s,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let g=dirname(t);if(g===t)return;t=g}}export{buildSkillZip as $,LATEST_PROTOCOL_VERSION as $n,mountMcpAndApi as $t,ROLLBACK_ORIGIN as A,safeContentPath as An,getLogger as At,TagIndex as B,startWatcher as Bn,installUserSkill as Bt,MCP_SERVER_NAME as C,rewriteMarkdownLinksForDocumentRename as Cn,ensureProjectGit as Ct,OBSERVER_SYNC_ORIGIN as D,runCloneSubprocess as Dn,gcCheckpointRefs as Dt,MissingOkConfigError as E,runAuthStatusSubprocess as En,formatContributors as Et,STARTER_TEMPLATES as F,seedBasenameIndex as Fn,incrementCollabSocketFilteredError as Ft,applySeed as G,validateCloneInputs as Gn,isLoopbackAddress as Gt,acquireUiLock as H,updateLastKnownHash as Hn,isAllowedWorkspaceHostHeader as Ht,STATE_MANIFEST_FILENAME as I,setActiveSpanAttributes as In,incrementServerObserverFire as It,attachIdleShutdown as J,withSpanSync as Jn,isSystemDoc as Jt,assertCompatibleStateManifest as K,validateSkillZip as Kn,isPairedWriteOrigin as Kt,SeedPrerequisiteError as L,shadowGit as Ln,initShadowRepo as Lt,SKILL_INSTALL_EVENTS_FILE_REL as M,safetyCheckpoint as Mn,getMetrics as Mt,STARTER_FOLDERS as N,saveInMemoryCheckpoint as Nn,getTracer as Nt,PinoLogger as O,runDeviceFlowSubprocess as On,getCurrentMcpLogger as Ot,STARTER_FOLDER_FRONTMATTER_FILENAME as P,saveVersion as Pn,handleCollabSocketError as Pt,buildReadResult as Q,JSONRPCMessageSchema as Qn,loggerFactory as Qt,SeedRootDirError as R,shutdownTelemetry as Rn,initTelemetry as Rt,MAX_AGENT_SESSIONS as S,resolvePackageVersion as Sn,detectProjectShape as St,McpLogger as T,runAuthReposSubprocess as Tn,extractWikiLinksFromMarkdown as Tt,applyAgentMarkdownWrite as U,updateUiLockPort as Un,isConfigDoc as Ut,UiLockCollisionError as V,toBroadcasterKey as Vn,isAllowedApiOrigin as Vt,applyExternalChange as W,validateAgentId as Wn,isHocuspocusAuthRejectionReason as Wt,buildAndOpenSkill as X,writeTargetVersion as Xn,listRescueCheckpoints as Xt,bootServer as Y,writeStateManifest as Yn,lastKnownHash as Yt,buildExecResult as Z,writeTracker as Zn,loadPrincipal as Zt,HocuspocusAuthRejection as _,removeLastKnownHash as _n,createPersistenceExtension as _t,AgentPresenceBroadcaster as a,readBranchFromHead as an,writeConfigPatch as ar,commitWip as at,LOG_MD_TEMPLATE as b,resolveContentDir as bn,createTestLogger as bt,BacklinkIndex as c,readStateManifest as cn,contentHash as ct,ConfigSchema as d,readUiLock as dn,createAssetServeMiddleware as dt,parseHocuspocusAuthToken as en,isInitializedNotification as er,buildStarterFolderFrontmatterYaml as et,DEFAULT_CHECKPOINT_RETENTION as f,reconcile as fn,createContentFilter as ft,HOCUSPOCUS_AUTH_REJECTION_REASONS as g,releaseUiLock as gn,createMcpHttpHandler as gt,GIT_UPSTREAM_WRITER as h,registerWrite as hn,createLiveDerivedIndexExtension as ht,AgentFocusBroadcaster as i,readAllTargets as in,resolveConfigPath as ir,commitUpstreamImport as it,SERVICE_WRITER as j,safeSubdir as jn,getMeter as jt,ProjectGitInitError as k,runWithMcpLogger as kn,getLocalDir as kt,CC1Broadcaster as l,readTargetRecordedAt as ln,contributorCount as lt,FILE_WATCHER_ORIGIN as m,recordSkillInstallEvent as mn,createExternalChangeHandler as mt,AGENT_ID_RE as n,pathToDocName as nn,isJSONRPCResultResponse as nr,classifyEvents as nt,AgentSessionCapacityError as o,readServerPackageVersion as on,GitDirAccessError as or,commitWipFromTree as ot,FILE_SYSTEM_WRITER as p,recordContributor as pn,createContentFilterAsync as pt,assertNeverDiskEvent as q,withSpan as qn,isSelfWrite as qt,AGENT_WRITE_ORIGIN as r,planSeed as rn,readConfigSafely as rr,clearContributors as rt,AgentSessionManager as s,readSkillInstallStateSnapshot as sn,MalformedGitPointerError as sr,containsConflictMarkers as st,AGENT_ID_MAX_LEN as t,parseKeepaliveConnectionId as tn,isJSONRPCRequest as tr,buildWipTree as tt,CONFLICT_MARKER_RE as u,readTargetVersion as un,createApiExtension as ut,HocuspocusAuthTokenSchema as v,resetMetrics as vn,createServer$1 as vt,MISSING_OK_CONFIG_MESSAGE as w,rewriteWikiLinksForDocumentRename as wn,evictStaleTrackerEntries as wt,MANAGED_RENAME_ORIGIN as x,resolveLockDir as xn,detectClaudeDesktopPresence as xt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as y,resolveBundledSkillDir as yn,createServerObserverExtension as yt,StateManifestError as z,splitMarkdownBlocks as zn,installTestLoggers as zt};
1610
- //# sourceMappingURL=dist-C7zRUYkF.mjs.map
1610
+ //# sourceMappingURL=dist-D4M20vXU.mjs.map
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{c as e,d as t,i as n,l as r,s as i,t as a,u as o}from"./init-DFIKzR_a.mjs";import{t as s}from"./loader-CLqzLLmP.mjs";import"./src-DiAwFfNV.mjs";export{r as ALL_EDITOR_IDS,o as EDITOR_TARGETS,a as detectInstalledEditors,t as initContent,s as loadConfig,n as readExistingMcpEntry,i as writeEditorMcpConfig,e as writeUserMcpConfigs};
1
+ import{c as e,d as t,i as n,l as r,s as i,t as a,u as o}from"./init-CIe9xion.mjs";import{t as s}from"./loader-RuexJG94.mjs";import"./src-CKsVM5vq.mjs";export{r as ALL_EDITOR_IDS,o as EDITOR_TARGETS,a as detectInstalledEditors,t as initContent,s as loadConfig,n as readExistingMcpEntry,i as writeEditorMcpConfig,e as writeUserMcpConfigs};
@@ -0,0 +1 @@
1
+ import{o as e}from"./init-CIe9xion.mjs";export{e as runInit};
@@ -1,4 +1,4 @@
1
- import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{r,t as i}from"./esm-CEs3LWY3.mjs";import{bt as a,vt as o}from"./dist-DfIz2LcA.mjs";import{Bt as s,C as c,Ct as l,k as u,xt as d,yn as f}from"./dist-C7zRUYkF.mjs";import{n as p,t as m}from"./constants-DAN-q5Vg.mjs";import{t as h}from"./is-object-DF0ZeuvD.mjs";import{i as g,o as _,r as v,s as y,t as b}from"./colors-BNufdynn.mjs";import{t as x}from"./preview-CYyF4Y9W.mjs";import S,{basename as C,dirname as w,isAbsolute as T,join as E,posix as ee,relative as D,resolve as O,sep as k,win32 as te}from"node:path";import{cpSync as ne,existsSync as A,lstatSync as re,mkdirSync as j,readFileSync as M,realpathSync as ie,rmSync as ae,writeFileSync as N}from"node:fs";import P from"node:process";import{homedir as F}from"node:os";import{AsyncLocalStorage as oe,AsyncResource as se}from"node:async_hooks";import{stripVTControlCharacters as ce,styleText as I}from"node:util";import*as le from"node:readline";function ue(){return P.platform.startsWith(`win`)?!!P.env.CI||!!P.env.WT_SESSION||!!P.env.TERMINUS_SUBLIME||P.env.ConEmuTask===`{cmd::Cmder}`||P.env.TERM_PROGRAM===`Terminus-Sublime`||P.env.TERM_PROGRAM===`vscode`||P.env.TERM===`xterm-256color`||P.env.TERM===`alacritty`||P.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:P.env.TERM!==`linux`}const de={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},fe={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},pe={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},me={...de,...fe},he={...de,...pe},L=ue()?me:he;Object.entries(fe);var ge=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const _e=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),ve=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,ye=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,be=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,xe=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Se=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Ce=/\t{1,1000}/y,we=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Te=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Ee=/\p{M}+/gu,De={limit:1/0,ellipsis:``},Oe=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Oe(i,De,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Te,l],[be,0],[xe,o],[Ce,s],[we,c],[Se,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(Ee,``)){let t=e.codePointAt(0)||0;if(S=ve(t)?2:ye(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===Se?_e(e.slice(p,n.lastIndex)):n===we?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},ke={limit:1/0,ellipsis:``,ellipsisWidth:0},R=(e,t={})=>Oe(e,ke,t).width,Ae=`]8;;`,je=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ae}(?<uri>.*))`,`y`),Me=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Ne=e=>`[${e}m`,Pe=e=>`${Ae}${e}`,Fe=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:R(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=R(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Ae,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Ie=e=>{let t=e.split(` `),n=t.length;for(;n&&!R(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Le=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=R(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=R(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Fe(s,r,t),c=R(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Fe(s,r,t),c=R(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Fe(s,r,t),c=R(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Ie(e)));let l=s.join(`
1
+ import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{r,t as i}from"./esm-CEs3LWY3.mjs";import{bt as a,vt as o}from"./dist-DfIz2LcA.mjs";import{Bt as s,C as c,Ct as l,k as u,xt as d,yn as f}from"./dist-D4M20vXU.mjs";import{n as p,t as m}from"./constants-Cf7m1y2Y.mjs";import{t as h}from"./is-object-DF0ZeuvD.mjs";import{i as g,o as _,r as v,s as y,t as b}from"./colors-BNufdynn.mjs";import{t as x}from"./preview-DJNoVm8P.mjs";import S,{basename as C,dirname as w,isAbsolute as T,join as E,posix as ee,relative as D,resolve as O,sep as k,win32 as te}from"node:path";import{cpSync as ne,existsSync as A,lstatSync as re,mkdirSync as j,readFileSync as M,realpathSync as ie,rmSync as ae,writeFileSync as N}from"node:fs";import P from"node:process";import{homedir as F}from"node:os";import{AsyncLocalStorage as oe,AsyncResource as se}from"node:async_hooks";import{stripVTControlCharacters as ce,styleText as I}from"node:util";import*as le from"node:readline";function ue(){return P.platform.startsWith(`win`)?!!P.env.CI||!!P.env.WT_SESSION||!!P.env.TERMINUS_SUBLIME||P.env.ConEmuTask===`{cmd::Cmder}`||P.env.TERM_PROGRAM===`Terminus-Sublime`||P.env.TERM_PROGRAM===`vscode`||P.env.TERM===`xterm-256color`||P.env.TERM===`alacritty`||P.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:P.env.TERM!==`linux`}const de={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},fe={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},pe={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},me={...de,...fe},he={...de,...pe},L=ue()?me:he;Object.entries(fe);var ge=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const _e=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),ve=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,ye=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,be=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,xe=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Se=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Ce=/\t{1,1000}/y,we=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Te=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Ee=/\p{M}+/gu,De={limit:1/0,ellipsis:``},Oe=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Oe(i,De,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Te,l],[be,0],[xe,o],[Ce,s],[we,c],[Se,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(Ee,``)){let t=e.codePointAt(0)||0;if(S=ve(t)?2:ye(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===Se?_e(e.slice(p,n.lastIndex)):n===we?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},ke={limit:1/0,ellipsis:``,ellipsisWidth:0},R=(e,t={})=>Oe(e,ke,t).width,Ae=`]8;;`,je=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ae}(?<uri>.*))`,`y`),Me=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Ne=e=>`[${e}m`,Pe=e=>`${Ae}${e}`,Fe=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:R(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=R(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Ae,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Ie=e=>{let t=e.split(` `),n=t.length;for(;n&&!R(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Le=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=R(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=R(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Fe(s,r,t),c=R(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Fe(s,r,t),c=R(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Fe(s,r,t),c=R(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Ie(e)));let l=s.join(`
2
2
  `),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===`›`){je.lastIndex=e+1;let t=je.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
3
3
  `){a&&(r+=Pe(``));let e=i?Me(i):void 0;i&&e&&(r+=Ne(e))}else t===`
4
4
  `&&(i&&Me(i)&&(r+=Ne(i)),a&&(r+=Pe(a)))}return r},Re=/\r?\n/;function ze(e,t,n){return String(e).normalize().split(Re).map(e=>Le(e,t,n)).join(`
@@ -393,5 +393,5 @@ ${a}/
393
393
  `)?n:`${n}\n`,`utf-8`)}function ar(e,t){let n;try{n=ie(t)}catch{n=O(t)}let r;try{r=re(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(r?.isSymbolicLink())throw Error(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run \`ok init\`, or pass \`--no-mcp\` to skip MCP config writes.`);let i=w(e);for(;i.length>1&&i!==k;){let t;try{t=ie(i)}catch(e){if(e.code===`ENOENT`){i=w(i);continue}throw e}let r=D(n,t);if(r===``||!r.startsWith(`..`)&&!T(r))return;throw Error(`Refusing to write at ${e}: ancestor ${i} resolves to ${t}, which is outside the project directory ${n}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run, or pass \`--no-mcp\`.`)}}const or=e=>e!==`project`,sr=e=>e!==`user`;async function cr(){let e=await $t({message:`Where should the MCP server be configured?
394
394
  `,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function lr(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??cr)():`both`}const ur=`0.0.1`,dr=`open-knowledge-ui`;function fr(e,t={}){let n=E(e,`.claude`,`launch.json`),r=t.mode===`dev`?{name:dr,runtimeExecutable:`node`,runtimeArgs:[Hn(),`ui`],port:3e3}:{name:dr,runtimeExecutable:`npx`,runtimeArgs:[`@inkeep/open-knowledge`,`ui`],port:3e3};try{if(ar(n,e),!A(n))return j(w(n),{recursive:!0}),N(n,`${JSON.stringify({version:ur,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let t=M(n,`utf-8`).trim(),i=t?JSON.parse(t):{};if(!h(i))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let a=Array.isArray(i.configurations)?i.configurations:[],o=a.findIndex(e=>h(e)&&e.name===dr);o>=0?a[o]=r:a.push(r);let s={...i,version:i.version??ur,configurations:a};return N(n,`${JSON.stringify(s,null,2)}\n`,`utf-8`),{action:o>=0?`merged`:`created`,configPath:n}}catch(e){return{action:`failed`,configPath:n,error:e instanceof Error?e.message:String(e)}}}function pr(e,t,n){try{return A(e.detectPath?.(t,n)??w(e.configPath(t,n)))}catch{return!1}}function $(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}if(!i&&!n.skipAvailabilityCheck&&!pr(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{ar(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}let s;try{s=e.format===`toml`?nr(o):tr(o)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let c=s[e.topLevelKey]??{},l=c[a],u;try{u=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let d={...s,[e.topLevelKey]:{...c,[a]:u}};try{e.format===`toml`?ir(o,d):rr(o,d)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}return{editorId:e.id,label:e.label,action:l===void 0?`written`:`overwritten`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}function mr(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=f(),i=w(n);ar(i,t);let a=A(n)?`overwritten`:`written`;return ae(i,{recursive:!0,force:!0}),j(w(i),{recursive:!0}),ne(r,i,{recursive:!0}),{editorId:e.id,label:e.label,action:a,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function hr(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!A(n)))return{editorId:e.id,label:e.label,path:n}}async function gr(e){let t=er(e.editors),n={mode:`published`,cliPath:e.cliPath,skipAvailabilityCheck:!0};return t.map(t=>$(t,``,n,e.home))}function _r(e,t,n){let r;try{r=e.configPath(t,n)}catch{return null}let i;try{i=e.format===`toml`?nr(r):tr(r)}catch{return null}let a=i[e.topLevelKey];if(!h(a))return null;let o=a[e.serverName(t)];return h(o)?o:null}async function vr(e={}){let t=O(e.cwd??process.cwd()),n={mode:e.devMcp?`dev`:`published`},r=await l(t),i;try{i=Rn(t)}catch(n){let i=Q.claude.configPath(t,e.home);return{contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:r.didInit,claudeDesktopDetected:!1,mcpAction:`failed`,mcpPath:i,mcpError:`Content scaffolding failed: ${n instanceof Error?n.message:String(n)}`}}let a=await lr({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),o=e.editors??br(t,e.home),c=e.editors??zn.filter(e=>Q[e].projectConfigPath!==void 0),u=er(o),f=er(c),p=e.mcp===!1||a===null,m=Array.from(new Map([...u,...p?[]:f].map(e=>[e.id,e])).values()),h=u.filter(n=>pr(n,t,e.home)),g=[],_=[],v=new Set;for(let r of m){if(p){let n=``;try{n=r.configPath(t,e.home)}catch{}g.push({editorId:r.id,label:r.label,action:`skipped-flag`,configPath:n,serverName:r.serverName(t)});continue}if(or(a)&&u.includes(r)&&g.push($(r,t,n,e.home)),sr(a)&&f.includes(r)&&r.projectConfigPath){let i=r.projectConfigPath(t),a=$(r,t,n,e.home,i);g.push(a),(a.action===`written`||a.action===`overwritten`)&&(v.add(i),_.push(mr(r,t)))}}let y=!p&&a!==null&&sr(a)?f.filter(e=>!e.projectConfigPath).map(e=>e.label):void 0,b=p?[]:h.map(e=>hr(e,t)).filter(e=>e!==void 0).filter(e=>!v.has(e.path)),x=h.some(e=>e.id===`claude`)&&!p?fr(t,n):void 0,S=await(e.installUserSkill??s)({home:e.home}),C=d({home:e.home}),w=p?`skipped-flag`:`skipped-missing`,T=g.find(e=>e.editorId===`claude`)??g[0]??{action:w,configPath:Q.claude.configPath(t,e.home)};return{contentCreated:i.created,contentUpdated:i.updated,contentSkipped:i.skipped,editors:g,projectSkills:_,legacyProjectConfigs:b,launchJson:x,skillInstall:S,didGitInit:r.didInit,claudeDesktopDetected:C,mcpAction:T.action,mcpPath:T.configPath,mcpError:`error`in T?T.error:void 0,projectScopeUnsupportedLabels:y}}function yr(e,t){let n=[],r=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),i=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),a=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`),s=e=>{let n=e.configPath.startsWith(t)?D(t,e.configPath):e.configPath;switch(e.action){case`created`:return` app preview server ${n} configured for Claude Code Desktop embedded browser`;case`merged`:return` app preview server ${n} updated for Claude Code Desktop embedded browser`;case`failed`:return` app preview server ${n} FAILED: ${e.error}`}};e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/ (default branch: main)`);let c=E(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(b(`Content scaffolded at ${c}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(b(`Content already present at ${c}/`)),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0)if(n.push(b(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`);else if(a)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(o)n.push(b(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(b(`MCP server configuration:`));for(let r of e.editors){let i=r.configPath.startsWith(t)?D(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),a=r.serverName===`open-knowledge`?``:` (${r.serverName})`,o=r.configScope===`project`?` (project)`:``,c=`${r.label}${o}`,l=` `.repeat(Math.max(1,20-c.length)),u=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${c}${l}${i} ${_(`registered`)}${a}${u}`);break;case`overwritten`:n.push(` ${c}${l}${i} ${_(`updated`)}${a}${u}`);break;case`skipped-missing`:n.push(` ${c}${l}${i} config root missing; skipped`);break;case`failed`:n.push(` ${c}${l}${i} ${v(`FAILED`)}: ${r.error}`);break;case`skipped-flag`:break}r.editorId===`claude`&&e.launchJson&&n.push(s(e.launchJson))}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}}if(e.projectSkills.length>0){n.push(``),n.push(b(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?D(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${_(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${_(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${v(`FAILED`)}: ${r.error}`);break}}}if(i&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${D(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall)switch(n.push(``),n.push(b(`User-global skill:`)),e.skillInstall){case`installed`:n.push(` open-knowledge ${_(`installed to detected agent hosts`)} via \`npx skills\``);break;case`skip-current`:n.push(` open-knowledge ${_(`already installed at current version`)}`);break;case`failed`:n.push(` ${y(`open-knowledge install failed — MCP still configured; run manually:`)}`),n.push(` ${y(` npx skills@~1.5.0 add <bundled-path> --agent '*' -g -y --copy`)}`);break}if(e.claudeDesktopDetected&&(n.push(``),n.push(`Claude Desktop App detected. To enable in Claude Chat & Cowork, run: ${b(`ok install-skill`)}`)),e.preview?(n.push(``),n.push(x(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),r){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`${_(`✓`)} ${b(`Next steps:`)}`),n.push(` 1. Open your editor (${g(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ${g(`ok seed`)}`),n.push(` 4. Use the three MCP workflow tools as you build the wiki:`),n.push(` - ${g(`mcp__open-knowledge__ingest`)} — capture an external source`),n.push(` - ${g(`mcp__open-knowledge__research`)} — gather sources and write findings`),n.push(` - ${g(`mcp__open-knowledge__consolidate`)} — promote research to canonical articles`)}return n.join(`
395
395
  `)}function br(e,t){let n=[];for(let r of zn)pr(Q[r],e,t)&&n.push(r);return n}function xr(){return new i(`init`).description(`Scaffold .ok/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the .ok/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging`).addOption(new r(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).action(async e=>{let t=process.cwd(),n;try{n=await vr({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope})}catch(e){if(e instanceof u){process.stderr.write(`open-knowledge requires git to initialize a parent repo. Install git or run 'git init' yourself, then re-run.
396
- `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-CZVcnhT0.mjs`),{loadConfig:r}=await import(`./loader-CvkCArFH.mjs`),{resolveContentDir:i}=await import(`./dist-BqKhpKRA.mjs`),{config:a}=r(t),o=i(a,t);n.preview=e({projectDir:t,contentDir:o})}catch(e){n.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${yr(n,t)}\n`),(n.editors.some(e=>e.action===`failed`)||n.mcpAction===`failed`)&&(process.exitCode=1)})}export{L as S,ot as _,lr as a,ze as b,gr as c,Rn as d,rt as f,nt as g,it as h,_r as i,zn as l,tt as m,yr as n,vr as o,et as p,xr as r,$ as s,br as t,Q as u,Ze as v,ge as x,Be as y};
397
- //# sourceMappingURL=init-DFIKzR_a.mjs.map
396
+ `),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-CgKJyIsb.mjs`),{loadConfig:r}=await import(`./loader-CMdR0tCR.mjs`),{resolveContentDir:i}=await import(`./dist-Bu-MwAbD.mjs`),{config:a}=r(t),o=i(a,t);n.preview=e({projectDir:t,contentDir:o})}catch(e){n.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${yr(n,t)}\n`),(n.editors.some(e=>e.action===`failed`)||n.mcpAction===`failed`)&&(process.exitCode=1)})}export{L as S,ot as _,lr as a,ze as b,gr as c,Rn as d,rt as f,nt as g,it as h,_r as i,zn as l,tt as m,yr as n,vr as o,et as p,xr as r,$ as s,br as t,Q as u,Ze as v,ge as x,Be as y};
397
+ //# sourceMappingURL=init-CIe9xion.mjs.map
@@ -0,0 +1 @@
1
+ import{t as e}from"./loader-RuexJG94.mjs";export{e as loadConfig};
@@ -1,4 +1,4 @@
1
- import{Ct as e,Q as t,dn as n}from"./dist-DfIz2LcA.mjs";import{d as r,rr as i}from"./dist-C7zRUYkF.mjs";import{t as a}from"./constants-DAN-q5Vg.mjs";import{t as o}from"./is-object-DF0ZeuvD.mjs";import{resolve as s}from"node:path";import{existsSync as c,readFileSync as l}from"node:fs";import{homedir as u}from"node:os";var d=n();function f(e,t){let n={...e};for(let r of Object.keys(t)){let i=e[r],a=t[r];o(a)&&o(i)?n[r]=f(i,a):a!==void 0&&(n[r]=a)}return n}function p(e){if(!c(e))return{value:null,path:e,source:null,doc:null};let t;try{t=l(e,`utf-8`)}catch(t){return console.warn(`[config] Failed to read ${e}: ${t instanceof Error?t.message:t}`),{value:null,path:e,source:null,doc:null}}let n=(0,d.parseDocument)(t);if(n.errors.length>0)return console.warn(`[config] Failed to parse ${e}: ${n.errors.map(e=>e.message).join(`; `)}`),{value:null,path:e,source:t,doc:null};let r=n.toJSON();return o(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}const m=[`include`,`exclude`];function h(e){let t="Run `ok config migrate` to strip the obsolete key from config.yml automatically, or remove it by hand.";return e===`exclude`?[`Move these patterns to .okignore at the project root (gitignore syntax, 1:1 migration).`,t].join(` `):[`content.include has been removed.`,`For subdirectory scoping, set content.dir in .ok/config.yml instead.`,`For pattern-based filtering, use .okignore (gitignore syntax — exclude-only; do not copy include patterns directly).`,t].join(` `)}function g(t){let n=t.value;if(!o(n))return[];let r=n.content;if(!o(r))return[];let i=[];for(let n of m)if(n in r){let r=[`content`,n],a;t.doc!==null&&t.source!==null&&(a=e({file:t.path,source:t.source,doc:t.doc,path:r})),i.push({code:`REMOVED_KEY`,path:r,redirect:h(n),...a===void 0?{}:{source:a}})}return i}function _(t,n){return t.map(t=>{let r=t.path.map(e=>typeof e==`symbol`?String(e):e),i={path:r,message:t.message,issueCode:t.code};if(n.doc!==null&&n.source!==null){let t=e({file:n.path,source:n.source,doc:n.doc,path:r});if(t!==void 0)return{...i,source:t}}return i})}function v(e){let n=e??process.cwd(),o=[],c=s(u(),`.ok`,a),l=i({absPath:c}),d={};l.valid&&l.source!==void 0?(d=f(d,l.value),o.push(c)):l.valid;let m=s(n,`.ok`,a),h=p(m);if(h.value!==null){let e=g(h);if(e.length>0)throw Error(e.map(t).join(`
1
+ import{Ct as e,Q as t,dn as n}from"./dist-DfIz2LcA.mjs";import{d as r,rr as i}from"./dist-D4M20vXU.mjs";import{t as a}from"./constants-Cf7m1y2Y.mjs";import{t as o}from"./is-object-DF0ZeuvD.mjs";import{resolve as s}from"node:path";import{existsSync as c,readFileSync as l}from"node:fs";import{homedir as u}from"node:os";var d=n();function f(e,t){let n={...e};for(let r of Object.keys(t)){let i=e[r],a=t[r];o(a)&&o(i)?n[r]=f(i,a):a!==void 0&&(n[r]=a)}return n}function p(e){if(!c(e))return{value:null,path:e,source:null,doc:null};let t;try{t=l(e,`utf-8`)}catch(t){return console.warn(`[config] Failed to read ${e}: ${t instanceof Error?t.message:t}`),{value:null,path:e,source:null,doc:null}}let n=(0,d.parseDocument)(t);if(n.errors.length>0)return console.warn(`[config] Failed to parse ${e}: ${n.errors.map(e=>e.message).join(`; `)}`),{value:null,path:e,source:t,doc:null};let r=n.toJSON();return o(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}const m=[`include`,`exclude`];function h(e){let t="Run `ok config migrate` to strip the obsolete key from config.yml automatically, or remove it by hand.";return e===`exclude`?[`Move these patterns to .okignore at the project root (gitignore syntax, 1:1 migration).`,t].join(` `):[`content.include has been removed.`,`For subdirectory scoping, set content.dir in .ok/config.yml instead.`,`For pattern-based filtering, use .okignore (gitignore syntax — exclude-only; do not copy include patterns directly).`,t].join(` `)}function g(t){let n=t.value;if(!o(n))return[];let r=n.content;if(!o(r))return[];let i=[];for(let n of m)if(n in r){let r=[`content`,n],a;t.doc!==null&&t.source!==null&&(a=e({file:t.path,source:t.source,doc:t.doc,path:r})),i.push({code:`REMOVED_KEY`,path:r,redirect:h(n),...a===void 0?{}:{source:a}})}return i}function _(t,n){return t.map(t=>{let r=t.path.map(e=>typeof e==`symbol`?String(e):e),i={path:r,message:t.message,issueCode:t.code};if(n.doc!==null&&n.source!==null){let t=e({file:n.path,source:n.source,doc:n.doc,path:r});if(t!==void 0)return{...i,source:t}}return i})}function v(e){let n=e??process.cwd(),o=[],c=s(u(),`.ok`,a),l=i({absPath:c}),d={};l.valid&&l.source!==void 0?(d=f(d,l.value),o.push(c)):l.valid;let m=s(n,`.ok`,a),h=p(m);if(h.value!==null){let e=g(h);if(e.length>0)throw Error(e.map(t).join(`
2
2
 
3
3
  `));d=f(d,h.value),o.push(m)}y(d,[`upload`,`maxBytes`],`streaming uploads have no user-facing cap`),y(d,[`github`,`oauthAppClientId`],`use the OPEN_KNOWLEDGE_GITHUB_CLIENT_ID env var instead`),y(d,[`server`,`host`],`use the --host flag or HOST env var instead`),y(d,[`server`,`openOnAgentEdit`]),y(d,[`mcp`,`autoStart`],`to disable auto-start, set OK_MCP_AUTOSTART=0`),y(d,[`mcp`,`tools`,`read_document`,`historyDepth`]),y(d,[`mcp`,`tools`,`grep`,`maxResults`]),y(d,[`mcp`,`tools`,`search`,`maxResults`]);let v=r.safeParse(d);if(!v.success){let e={code:`SCHEMA_INVALID`,issues:_(v.error.issues,h)};throw Error(t(e))}return{config:v.data,sources:o}}function y(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){if(!o(r))return;r=r[t[e]]}if(!o(r))return;let i=t[t.length-1];if(r[i]===void 0)return;let a=t.join(`.`);console.warn(`[config] ${a} is no longer user-configurable; ${n??`the value is hardcoded in @inkeep/open-knowledge-core`}. Remove the key to silence this warning.`)}export{v as t};
4
- //# sourceMappingURL=loader-CLqzLLmP.mjs.map
4
+ //# sourceMappingURL=loader-RuexJG94.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./preview-DJNoVm8P.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -1,3 +1,3 @@
1
- import{ft as e}from"./dist-C7zRUYkF.mjs";import"./constants-DAN-q5Vg.mjs";import{join as t,relative as n}from"node:path";import{existsSync as r,lstatSync as i,readdirSync as a,realpathSync as o,statSync as s}from"node:fs";function c(r){let{projectDir:c,contentDir:l,sampleCap:u=5}=r,d=[],f=[];try{i(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=e({projectDir:c,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let r;try{r=a(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);d.push(`could not read directory ${n(l,e)||`.`}: ${r}`);return}for(let i of r){let r=t(e,i.name);if(i.isSymbolicLink()){let e;try{e=o(r)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?d.push(`broken or cyclic symlink: ${n(l,r)}`):d.push(`cannot resolve symlink ${n(l,r)}: ${t??`unknown error`}`);continue}let t;try{t=s(e)}catch{continue}if(t.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(t.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}else if(i.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(i.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function l(e,i){let a=[],o=n(i,e.contentDir),s=o===``?`./`:`./${o}`;if(a.push(`Content:`),a.push(` Found ${e.totalCount} markdown files in ${s}`),e.sample.length>0){let t=e.sample.join(`, `),n=e.totalCount>e.sample.length?`, …`:``;a.push(` Sample: ${t}${n}`)}if(e.warnings.length>0)for(let t of e.warnings)a.push(` Warning: ${t}`);return a.push(``),r(t(i,`.ok`,`config.yml`))?(a.push(` To adjust scope, add patterns to .okignore at the project root.`),a.push(` To change the content root, edit .ok/config.yml → content.dir.`)):a.push(" Run `open-knowledge init` to scaffold config + .okignore."),a.push(``),a.push(` Re-check anytime: open-knowledge preview`),a.join(`
1
+ import{ft as e}from"./dist-D4M20vXU.mjs";import"./constants-Cf7m1y2Y.mjs";import{join as t,relative as n}from"node:path";import{existsSync as r,lstatSync as i,readdirSync as a,realpathSync as o,statSync as s}from"node:fs";function c(r){let{projectDir:c,contentDir:l,sampleCap:u=5}=r,d=[],f=[];try{i(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=e({projectDir:c,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let r;try{r=a(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);d.push(`could not read directory ${n(l,e)||`.`}: ${r}`);return}for(let i of r){let r=t(e,i.name);if(i.isSymbolicLink()){let e;try{e=o(r)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?d.push(`broken or cyclic symlink: ${n(l,r)}`):d.push(`cannot resolve symlink ${n(l,r)}: ${t??`unknown error`}`);continue}let t;try{t=s(e)}catch{continue}if(t.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(t.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}else if(i.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(i.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function l(e,i){let a=[],o=n(i,e.contentDir),s=o===``?`./`:`./${o}`;if(a.push(`Content:`),a.push(` Found ${e.totalCount} markdown files in ${s}`),e.sample.length>0){let t=e.sample.join(`, `),n=e.totalCount>e.sample.length?`, …`:``;a.push(` Sample: ${t}${n}`)}if(e.warnings.length>0)for(let t of e.warnings)a.push(` Warning: ${t}`);return a.push(``),r(t(i,`.ok`,`config.yml`))?(a.push(` To adjust scope, add patterns to .okignore at the project root.`),a.push(` To change the content root, edit .ok/config.yml → content.dir.`)):a.push(" Run `open-knowledge init` to scaffold config + .okignore."),a.push(``),a.push(` Re-check anytime: open-knowledge preview`),a.join(`
2
2
  `)}export{c as n,l as t};
3
- //# sourceMappingURL=preview-CYyF4Y9W.mjs.map
3
+ //# sourceMappingURL=preview-DJNoVm8P.mjs.map
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ActivityPanelDiffView-DoHWP1ak.js","./chunk-CFjPhJqf.js","./compiler-runtime-CVnuRdak.js","./ActivityPanelDiffView-legcy4jI.css"])))=>i.map(i=>d[i]);
2
- import{o as e}from"./chunk-CFjPhJqf.js";import{t}from"./preload-helper-2ej06EnG.js";import{n,r,t as i}from"./compiler-runtime-CVnuRdak.js";import{m as a}from"./doc-hash-BAwyNVVo.js";import{C as o,t as s}from"./button-BsFpqlpT.js";import{Ft as c,Xt as l,Yt as u,Zt as d,n as f,r as p}from"./DocumentContext-DbBJqgtS.js";import{f as m,i as h,m as g,r as _,t as v}from"./agent-presence-Ds2n3U5P.js";import{a as y,c as b,i as x,o as S,s as C,t as w,x as T}from"./dialog-Cv1qneWl.js";import{i as E,n as D,t as O}from"./tooltip-BIapPAuP.js";var k=o(`rewind`,[[`path`,{d:`M12 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 12 18z`,key:`2a1g8i`}],[`path`,{d:`M22 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 22 18z`,key:`rg3s36`}]]),A=i(),j=e(n(),1),M=500,ee=64;async function te(e){let t=`/api/agent-activity?agentId=${encodeURIComponent(e)}`,n=await fetch(t);if(!n.ok)throw Error(`agent-activity fetch failed: HTTP ${n.status}`);let r=await n.json();if(!r.ok)throw Error(r.error??`agent-activity fetch not ok`);return{sessionAlive:r.sessionAlive??!1,agent:r.agent??null,files:r.files??[]}}async function N(e,t,n){let r=`/api/agent-burst-diff?agentId=${encodeURIComponent(e)}&docName=${encodeURIComponent(t)}&stackIndex=${n}`,i=await fetch(r);if(!i.ok)throw Error(`agent-burst-diff fetch failed: HTTP ${i.status}`);let a=await i.json();if(!a.ok)throw Error(a.error??`agent-burst-diff fetch not ok`);return a.diff??``}function ne(e){let t=(0,A.c)(23),{systemProvider:n}=f(),[r,i]=(0,j.useState)(null),[o,s]=(0,j.useState)(`idle`),[c,l]=(0,j.useState)(null),u;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=new h(ee),t[0]=u):u=t[0];let d=(0,j.useRef)(u),p=(0,j.useRef)(0),m;t[1]===n?m=t[2]:(m=e=>{let t=p.current+=1;s(`loading`),l(null),te(e).then(r=>{if(p.current!==t)return;let a=ie(n,e);i({...r,writingDocs:a}),s(`ready`)}).catch(e=>{p.current===t&&(l(e instanceof Error?e.message:String(e)),s(`error`))})},t[1]=n,t[2]=m);let g=m,_;t[3]!==e||t[4]!==g?(_=()=>{if(!e){p.current+=1,i(null),s(`idle`),l(null),d.current.clear();return}d.current.clear(),g(e);let t=null,n=a(n=>{n.includes(`session-activity`)&&(t&&clearTimeout(t),t=setTimeout(()=>{t=null,g(e)},M))});return()=>{t&&clearTimeout(t),n()}},t[3]=e,t[4]=g,t[5]=_):_=t[5];let v;t[6]===e?v=t[7]:(v=[e],t[6]=e,t[7]=v),(0,j.useEffect)(_,v);let y,b;t[8]!==e||t[9]!==n?(y=()=>{if(!e||!n)return;let t=()=>{if(!n.awareness)return;let t=ie(n,e);i(e=>!e||re(e.writingDocs,t)?e:{...e,writingDocs:t})},r=n.awareness;if(!r||typeof r.on!=`function`){t();return}r.on(`update`,t),t();let a=setInterval(t,1e3);return()=>{clearInterval(a),typeof r.off==`function`&&r.off(`update`,t)}},b=[e,n],t[8]=e,t[9]=n,t[10]=y,t[11]=b):(y=t[10],b=t[11]),(0,j.useEffect)(y,b);let x;t[12]===e?x=t[13]:(x=async(t,n)=>{if(!e)return``;let r=`${t}\0${n}`,i=d.current.get(r);if(i!==void 0)return i;let a=await N(e,t,n);return d.current.set(r,a),a},t[12]=e,t[13]=x);let S=x,C;t[14]!==e||t[15]!==g?(C=()=>{e&&g(e)},t[14]=e,t[15]=g,t[16]=C):C=t[16];let w=C,T;return t[17]!==r||t[18]!==c||t[19]!==S||t[20]!==w||t[21]!==o?(T={data:r,status:o,error:c,reload:w,fetchBurstDiff:S},t[17]=r,t[18]=c,t[19]=S,t[20]=w,t[21]=o,t[22]=T):T=t[22],T}function re(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function ie(e,t){let n=new Set;if(!e)return n;let r=e.awareness;if(!v(r))return n;let i=[t,t.startsWith(`agent-`)?t.slice(6):`agent-${t}`];for(let e of r.getStates().values()){let t=e.agentPresence;if(t)for(let e of i){let r=t[e];r&&r.mode===`writing`&&r.currentDoc&&n.add(r.currentDoc)}}return n}var P=r(),ae=(0,j.lazy)(async()=>({default:(await t(()=>import(`./ActivityPanelDiffView-DoHWP1ak.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)).ActivityPanelDiffView}));function oe(e,t){let n=Math.max(0,t-e);return n<6e4?`${Math.round(n/1e3)}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:new Date(e).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function se(e){let t=(0,A.c)(38),{burst:n,docName:r,fetchBurstDiff:i}=e,[a,o]=(0,j.useState)(!1),[s,c]=(0,j.useState)(null),[u,f]=(0,j.useState)(null),[p,m]=(0,j.useState)(!1),[h,g]=(0,j.useState)(ce),_,v;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(_=()=>{let e=setInterval(()=>g(Date.now()),3e4);return()=>clearInterval(e)},v=[],t[0]=_,t[1]=v):(_=t[0],v=t[1]),(0,j.useEffect)(_,v);let y;t[2]!==n.stackIndex||t[3]!==s||t[4]!==r||t[5]!==a||t[6]!==i||t[7]!==p?(y=()=>{let e=!a;o(e),e&&s===null&&!p&&(m(!0),f(null),i(r,n.stackIndex).then(e=>{c(e),m(!1)}).catch(e=>{f(e instanceof Error?e.message:String(e)),m(!1)}))},t[2]=n.stackIndex,t[3]=s,t[4]=r,t[5]=a,t[6]=i,t[7]=p,t[8]=y):y=t[8];let b=y,x=`${a?`Collapse`:`Expand`} burst ${n.stackIndex+1} diff`,S;t[9]===a?S=t[10]:(S=a?(0,P.jsx)(d,{className:`size-3 shrink-0`,"aria-hidden":`true`}):(0,P.jsx)(l,{className:`size-3 shrink-0`,"aria-hidden":`true`}),t[9]=a,t[10]=S);let C;t[11]!==n.ts||t[12]!==h?(C=oe(n.ts,h),t[11]=n.ts,t[12]=h,t[13]=C):C=t[13];let w;t[14]===C?w=t[15]:(w=(0,P.jsx)(`span`,{className:`font-mono`,children:C}),t[14]=C,t[15]=w);let T;t[16]===n.additions?T=t[17]:(T=(0,P.jsxs)(`span`,{className:`text-green-600 dark:text-green-400`,children:[`+`,n.additions]}),t[16]=n.additions,t[17]=T);let E;t[18]===n.deletions?E=t[19]:(E=(0,P.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,n.deletions]}),t[18]=n.deletions,t[19]=E);let D;t[20]!==T||t[21]!==E?(D=(0,P.jsxs)(`span`,{className:`ml-auto font-mono`,children:[T,` `,E]}),t[20]=T,t[21]=E,t[22]=D):D=t[22];let O;t[23]!==a||t[24]!==D||t[25]!==x||t[26]!==S||t[27]!==w||t[28]!==b?(O=(0,P.jsxs)(`button`,{type:`button`,onClick:b,className:`flex w-full items-center gap-2 px-4 py-1.5 text-xs text-muted-foreground hover:bg-muted/40`,"aria-expanded":a,"aria-label":x,children:[S,w,D]}),t[23]=a,t[24]=D,t[25]=x,t[26]=S,t[27]=w,t[28]=b,t[29]=O):O=t[29];let k;t[30]!==s||t[31]!==a||t[32]!==u||t[33]!==p?(k=a?(0,P.jsx)(`div`,{className:`bg-muted/20`,children:p?(0,P.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:`Loading diff…`}):u?(0,P.jsxs)(`div`,{className:`px-4 py-2 text-xs text-destructive`,children:[`Failed: `,u]}):s===null?(0,P.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:`No diff.`}):(0,P.jsx)(j.Suspense,{fallback:(0,P.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:`Loading diff…`}),children:(0,P.jsx)(ae,{diff:s})})}):null,t[30]=s,t[31]=a,t[32]=u,t[33]=p,t[34]=k):k=t[34];let M;return t[35]!==O||t[36]!==k?(M=(0,P.jsxs)(`div`,{className:`border-t border-border/50`,children:[O,k]}),t[35]=O,t[36]=k,t[37]=M):M=t[37],M}function ce(){return Date.now()}function le(e,t){let n=Math.max(0,t-e);return n<6e4?`${Math.round(n/1e3)}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:`${Math.round(n/36e5)}h ago`}function ue(e){let t=(0,A.c)(93),{file:n,sessionAlive:r,isWriting:i,onNavigate:a,onUndoLast:o,onUndoAll:c,fetchBurstDiff:u}=e,[f,p]=(0,j.useState)(!1),[h,g]=(0,j.useState)(!1),[_,v]=(0,j.useState)(!1),[T,M]=(0,j.useState)(fe),ee,te;if(t[0]===Symbol.for(`react.memo_cache_sentinel`)?(ee=()=>{let e=setInterval(()=>M(Date.now()),3e4);return()=>clearInterval(e)},te=[],t[0]=ee,t[1]=te):(ee=t[0],te=t[1]),(0,j.useEffect)(ee,te),n.bursts.length===0)return null;let N=!r||n.bursts.length===0||_,ne=r?n.bursts.length===0?`Nothing to undo on this file`:null:`Session ended — undo unavailable`,re;t[2]!==N||t[3]!==n.docName||t[4]!==o?(re=e=>{e.stopPropagation(),!N&&(v(!0),Promise.resolve(o(n.docName)).finally(()=>v(!1)))},t[2]=N,t[3]=n.docName,t[4]=o,t[5]=re):re=t[5];let ie=re,ae;t[6]===N?ae=t[7]:(ae=e=>{e.stopPropagation(),!N&&g(!0)},t[6]=N,t[7]=ae);let oe=ae,ce;t[8]!==N||t[9]!==n.docName||t[10]!==c?(ce=()=>{g(!1),!N&&(v(!0),Promise.resolve(c(n.docName)).finally(()=>v(!1)))},t[8]=N,t[9]=n.docName,t[10]=c,t[11]=ce):ce=t[11];let ue=ce,F;t[12]===Symbol.for(`react.memo_cache_sentinel`)?(F=()=>p(de),t[12]=F):F=t[12];let pe=f?`Collapse ${n.docName}`:`Expand ${n.docName}`,I;t[13]===f?I=t[14]:(I=f?(0,P.jsx)(d,{className:`size-4`,"aria-hidden":`true`}):(0,P.jsx)(l,{className:`size-4`,"aria-hidden":`true`}),t[13]=f,t[14]=I);let L;t[15]!==f||t[16]!==pe||t[17]!==I?(L=(0,P.jsx)(`button`,{type:`button`,onClick:F,className:`flex size-5 shrink-0 items-center justify-center rounded hover:bg-muted`,"aria-expanded":f,"aria-label":pe,"data-testid":`activity-panel-file-row-carrot`,children:I}),t[15]=f,t[16]=pe,t[17]=I,t[18]=L):L=t[18];let R;t[19]!==n.docName||t[20]!==a?(R=()=>a(n.docName),t[19]=n.docName,t[20]=a,t[21]=R):R=t[21];let me=`Navigate to ${n.docName}`,z;t[22]!==n.docName||t[23]!==R||t[24]!==me?(z=(0,P.jsx)(`button`,{type:`button`,onClick:R,className:`min-w-0 flex-1 truncate text-left text-foreground hover:underline focus-visible:outline-ring`,"aria-label":me,"data-testid":`activity-panel-file-row-filename`,title:n.docName,children:n.docName}),t[22]=n.docName,t[23]=R,t[24]=me,t[25]=z):z=t[25];let he=`Undo last edit on ${n.docName}`,ge;t[26]===Symbol.for(`react.memo_cache_sentinel`)?(ge=(0,P.jsx)(m,{className:`size-3.5`,"aria-hidden":`true`}),t[26]=ge):ge=t[26];let B;t[27]!==N||t[28]!==ie||t[29]!==he?(B=(0,P.jsx)(E,{asChild:!0,children:(0,P.jsx)(s,{type:`button`,variant:`ghost`,size:`icon`,className:`size-6 shrink-0`,onClick:ie,disabled:N,"aria-label":he,"data-testid":`activity-panel-undo-last`,children:ge})}),t[27]=N,t[28]=ie,t[29]=he,t[30]=B):B=t[30];let _e=ne??`Undo last edit`,V;t[31]===_e?V=t[32]:(V=(0,P.jsx)(D,{side:`bottom`,children:_e}),t[31]=_e,t[32]=V);let H;t[33]!==B||t[34]!==V?(H=(0,P.jsxs)(O,{children:[B,V]}),t[33]=B,t[34]=V,t[35]=H):H=t[35];let ve=`Undo all edits on ${n.docName}`,ye;t[36]===Symbol.for(`react.memo_cache_sentinel`)?(ye=(0,P.jsx)(k,{className:`size-3.5`,"aria-hidden":`true`}),t[36]=ye):ye=t[36];let be;t[37]!==N||t[38]!==oe||t[39]!==ve?(be=(0,P.jsx)(E,{asChild:!0,children:(0,P.jsx)(s,{type:`button`,variant:`ghost`,size:`icon`,className:`size-6 shrink-0`,onClick:oe,disabled:N,"aria-label":ve,"data-testid":`activity-panel-undo-all`,children:ye})}),t[37]=N,t[38]=oe,t[39]=ve,t[40]=be):be=t[40];let xe=ne??`Undo all edits`,U;t[41]===xe?U=t[42]:(U=(0,P.jsx)(D,{side:`bottom`,children:xe}),t[41]=xe,t[42]=U);let W;t[43]!==be||t[44]!==U?(W=(0,P.jsxs)(O,{children:[be,U]}),t[43]=be,t[44]=U,t[45]=W):W=t[45];let G;t[46]===n.additionsTotal?G=t[47]:(G=(0,P.jsxs)(`span`,{className:`text-green-600 dark:text-green-400`,children:[`+`,n.additionsTotal]}),t[46]=n.additionsTotal,t[47]=G);let K;t[48]===n.deletionsTotal?K=t[49]:(K=(0,P.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,n.deletionsTotal]}),t[48]=n.deletionsTotal,t[49]=K);let q;t[50]!==G||t[51]!==K?(q=(0,P.jsxs)(`span`,{className:`shrink-0 font-mono text-xs`,children:[G,` `,K]}),t[50]=G,t[51]=K,t[52]=q):q=t[52];let J;t[53]!==n.lastTs||t[54]!==T?(J=le(n.lastTs,T),t[53]=n.lastTs,t[54]=T,t[55]=J):J=t[55];let Y;t[56]===J?Y=t[57]:(Y=(0,P.jsx)(`span`,{className:`shrink-0 font-mono text-[11px] text-muted-foreground`,children:J}),t[56]=J,t[57]=Y);let X;t[58]===i?X=t[59]:(X=i?(0,P.jsx)(`span`,{className:`shrink-0 text-[11px] text-primary animate-pulse`,role:`status`,children:`writing…`}):null,t[58]=i,t[59]=X);let Z;t[60]!==z||t[61]!==H||t[62]!==W||t[63]!==q||t[64]!==Y||t[65]!==X||t[66]!==L?(Z=(0,P.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 text-sm`,children:[L,z,H,W,q,Y,X]}),t[60]=z,t[61]=H,t[62]=W,t[63]=q,t[64]=Y,t[65]=X,t[66]=L,t[67]=Z):Z=t[67];let Q;t[68]!==f||t[69]!==u||t[70]!==n.bursts||t[71]!==n.docName?(Q=f?(0,P.jsx)(`div`,{children:n.bursts.map(e=>(0,P.jsx)(se,{burst:e,docName:n.docName,fetchBurstDiff:u},`${n.docName}:${e.stackIndex}`))}):null,t[68]=f,t[69]=u,t[70]=n.bursts,t[71]=n.docName,t[72]=Q):Q=t[72];let Se;t[73]===Symbol.for(`react.memo_cache_sentinel`)?(Se=(0,P.jsx)(b,{children:`Undo all edits on this file?`}),t[73]=Se):Se=t[73];let Ce;t[74]===n.docName?Ce=t[75]:(Ce=(0,P.jsx)(`span`,{className:`font-mono text-foreground`,children:n.docName}),t[74]=n.docName,t[75]=Ce);let we=n.bursts.length===1?``:`s`,Te;t[76]!==n.bursts.length||t[77]!==Ce||t[78]!==we?(Te=(0,P.jsxs)(C,{children:[Se,(0,P.jsxs)(y,{children:[`This will revert every change this agent has made to`,` `,Ce,` in their current session (`,n.bursts.length,` burst`,we,`). Other files and other writers are not affected.`]})]}),t[76]=n.bursts.length,t[77]=Ce,t[78]=we,t[79]=Te):Te=t[79];let Ee;t[80]===Symbol.for(`react.memo_cache_sentinel`)?(Ee=(0,P.jsx)(s,{type:`button`,variant:`outline`,onClick:()=>g(!1),"data-testid":`activity-panel-undo-all-cancel`,children:`Cancel`}),t[80]=Ee):Ee=t[80];let De;t[81]===ue?De=t[82]:(De=(0,P.jsxs)(S,{children:[Ee,(0,P.jsx)(s,{type:`button`,variant:`destructive`,onClick:ue,"data-testid":`activity-panel-undo-all-confirm`,children:`Undo all`})]}),t[81]=ue,t[82]=De);let Oe;t[83]!==Te||t[84]!==De?(Oe=(0,P.jsxs)(x,{className:`sm:max-w-md`,children:[Te,De]}),t[83]=Te,t[84]=De,t[85]=Oe):Oe=t[85];let $;t[86]!==h||t[87]!==Oe?($=(0,P.jsx)(w,{open:h,onOpenChange:g,children:Oe}),t[86]=h,t[87]=Oe,t[88]=$):$=t[88];let ke;return t[89]!==Z||t[90]!==Q||t[91]!==$?(ke=(0,P.jsxs)(`div`,{className:`border-b border-border`,"data-testid":`activity-panel-file-row`,children:[Z,Q,$]}),t[89]=Z,t[90]=Q,t[91]=$,t[92]=ke):ke=t[92],ke}function de(e){return!e}function fe(){return Date.now()}async function F(e){let t=await fetch(`/api/agent-undo`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,agentId:e.connectionId})});if(!t.ok)throw Error(`agent-undo failed: HTTP ${t.status}`)}function pe(e){return`#/${e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`)}`}function I(e){typeof window>`u`||(window.location.hash=pe(e))}function L(){let e=(0,A.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,P.jsxs)(`div`,{className:`flex h-full items-center justify-center p-6 text-muted-foreground`,role:`status`,"aria-busy":`true`,children:[(0,P.jsx)(c,{className:`mr-2 size-4 animate-spin`,"aria-hidden":`true`}),(0,P.jsx)(`span`,{className:`text-sm`,children:`Loading agent activity…`})]}),e[0]=t):t=e[0],t}function R(e){let t=(0,A.c)(9),{error:n,onRetry:r}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,P.jsx)(u,{className:`size-6 text-destructive`,"aria-hidden":`true`}),t[0]=i):i=t[0];let a;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,P.jsx)(`p`,{className:`text-sm font-medium`,children:`Failed to load activity`}),t[1]=a):a=t[1];let o;t[2]===n?o=t[3]:(o=(0,P.jsxs)(`div`,{className:`space-y-1`,children:[a,(0,P.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:n})]}),t[2]=n,t[3]=o);let c;t[4]===r?c=t[5]:(c=(0,P.jsx)(s,{type:`button`,variant:`outline`,size:`sm`,onClick:r,children:`Retry`}),t[4]=r,t[5]=c);let l;return t[6]!==o||t[7]!==c?(l=(0,P.jsxs)(`div`,{className:`flex flex-col items-center gap-3 p-6 text-center`,role:`alert`,"data-testid":`activity-panel-error`,children:[i,o,c]}),t[6]=o,t[7]=c,t[8]=l):l=t[8],l}function me(){let e=(0,A.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,P.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-muted-foreground`,"data-testid":`activity-panel-empty`,children:(0,P.jsx)(`p`,{className:`text-sm italic`,children:`No edits yet.`})}),e[0]=t):t=e[0],t}function z(e){let t=(0,A.c)(8),{onExit:n}=e,r;t[0]===n?r=t[1]:(r=(0,P.jsx)(he,{onClick:n}),t[0]=n,t[1]=r);let i;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,P.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:`Agent activity`}),t[2]=i):i=t[2];let a;t[3]===r?a=t[4]:(a=(0,P.jsxs)(`div`,{className:`flex shrink-0 flex-row items-center gap-2 border-b border-border px-3 py-2`,children:[r,i]}),t[3]=r,t[4]=a);let o;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,P.jsx)(`div`,{className:`flex flex-1 items-center justify-center p-6 text-muted-foreground`,children:(0,P.jsx)(`p`,{className:`text-center text-sm italic`,children:`Click an agent's avatar in the presence bar to view their session.`})}),t[5]=o):o=t[5];let s;return t[6]===a?s=t[7]:(s=(0,P.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col`,"data-testid":`activity-panel-no-agent`,"aria-label":`Agent activity`,children:[a,o]}),t[6]=a,t[7]=s),s}function he(e){let t=(0,A.c)(6),{onClick:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,P.jsx)(g,{}),t[0]=r):r=t[0];let i;t[1]===n?i=t[2]:(i=(0,P.jsx)(E,{asChild:!0,children:(0,P.jsx)(s,{type:`button`,variant:`ghost`,size:`icon`,className:`size-7 shrink-0`,onClick:n,"aria-label":`Back to document view`,"data-testid":`docpanel-exit-agent-mode`,children:r})}),t[1]=n,t[2]=i);let a;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,P.jsx)(D,{side:`bottom`,children:`Back to document view`}),t[3]=a):a=t[3];let o;return t[4]===i?o=t[5]:(o=(0,P.jsxs)(O,{children:[i,a]}),t[4]=i,t[5]=o),o}function ge(e){let t=(0,A.c)(9),{lastTs:n}=e,[r]=(0,j.useState)(B),i;t[0]!==n||t[1]!==r?(i=n?_e(r-n):null,t[0]=n,t[1]=r,t[2]=i):i=t[2];let a=i,o;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,P.jsx)(`span`,{className:`font-medium`,children:`Session ended`}),t[3]=o):o=t[3];let s;t[4]===a?s=t[5]:(s=a?(0,P.jsxs)(`span`,{children:[` · `,a]}):null,t[4]=a,t[5]=s);let c;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,P.jsx)(`div`,{className:`mt-1 opacity-80`,children:`Undo buttons are disabled — per-session state has been garbage-collected.`}),t[6]=c):c=t[6];let l;return t[7]===s?l=t[8]:(l=(0,P.jsxs)(`div`,{className:`border-b border-border bg-muted/40 px-4 py-3 text-xs text-muted-foreground`,"data-testid":`activity-panel-session-ended`,children:[o,s,c]}),t[7]=s,t[8]=l),l}function B(){return Date.now()}function _e(e){let t=Math.max(0,e);return t<6e4?`${Math.round(t/1e3)}s ago`:t<36e5?`${Math.round(t/6e4)}m ago`:`${Math.round(t/36e5)}h ago`}function V(e){let t=(0,A.c)(10),{agent:n,size:r}=e,i=r===void 0?28:r,a;t[0]!==n.color||t[1]!==i?(a={backgroundColor:n.color,width:i,height:i},t[0]=n.color,t[1]=i,t[2]=a):a=t[2];let o=i*.57,s=i*.57,c;t[3]!==n.icon||t[4]!==o||t[5]!==s?(c=(0,P.jsx)(_,{icon:n.icon,width:o,height:s}),t[3]=n.icon,t[4]=o,t[5]=s,t[6]=c):c=t[6];let l;return t[7]!==a||t[8]!==c?(l=(0,P.jsx)(`span`,{className:`inline-flex shrink-0 items-center justify-center rounded-full text-white ring-2 ring-background`,style:a,"aria-hidden":`true`,children:c}),t[7]=a,t[8]=c,t[9]=l):l=t[9],l}function H(e){let t=(0,A.c)(20),{data:n,status:r,error:i,reload:a,fetchBurstDiff:o,onExit:s,onNavigate:c,onUndoLast:l,onUndoAll:u}=e,d=n?.files?.[0]?.lastTs??null,f;t[0]===s?f=t[1]:(f=(0,P.jsx)(he,{onClick:s}),t[0]=s,t[1]=f);let p;t[2]===n?p=t[3]:(p=n?.agent?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(V,{agent:n.agent}),(0,P.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,P.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:n.agent.displayName}),(0,P.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[n.sessionAlive?`Active`:`Ended`,n.files.length>0?` · ${n.files.length} file${n.files.length===1?``:`s`}`:``]})]})]}):(0,P.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,P.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:`Agent activity`})}),t[2]=n,t[3]=p);let m;t[4]!==f||t[5]!==p?(m=(0,P.jsxs)(`div`,{className:`flex flex-row items-center gap-2 border-b border-border px-3 py-2 shrink-0`,children:[f,p]}),t[4]=f,t[5]=p,t[6]=m):m=t[6];let h;t[7]!==n||t[8]!==i||t[9]!==o||t[10]!==d||t[11]!==c||t[12]!==u||t[13]!==l||t[14]!==a||t[15]!==r?(h=(0,P.jsx)(`div`,{className:`flex-1 overflow-y-auto`,"data-testid":`activity-panel-body`,children:r===`loading`&&n===null?(0,P.jsx)(L,{}):r===`error`&&i?(0,P.jsx)(R,{error:i,onRetry:a}):n===null?(0,P.jsx)(me,{}):(0,P.jsxs)(P.Fragment,{children:[n.sessionAlive?null:(0,P.jsx)(ge,{lastTs:d}),n.files.length===0?(0,P.jsx)(me,{}):n.files.map(e=>(0,P.jsx)(ue,{file:e,sessionAlive:n.sessionAlive,isWriting:n.writingDocs.has(e.docName),onNavigate:c,onUndoLast:l,onUndoAll:u,fetchBurstDiff:o},e.docName))]})}),t[7]=n,t[8]=i,t[9]=o,t[10]=d,t[11]=c,t[12]=u,t[13]=l,t[14]=a,t[15]=r,t[16]=h):h=t[16];let g;return t[17]!==m||t[18]!==h?(g=(0,P.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col`,"data-testid":`activity-panel`,"aria-label":`Agent activity`,children:[m,h]}),t[17]=m,t[18]=h,t[19]=g):g=t[19],g}function ve(){let e=(0,A.c)(22),{docPanelAgentId:t,closeActivityPanel:n}=f(),{openDocumentTransition:r}=p(),{data:i,status:a,error:o,reload:s,fetchBurstDiff:c}=ne(t);if(t===null){let t;return e[0]===n?t=e[1]:(t=(0,P.jsx)(z,{onExit:n}),e[0]=n,e[1]=t),t}let l;e[2]===r?l=e[3]:(l=e=>{r(e),I(e)},e[2]=r,e[3]=l);let u=l,d;e[4]!==i||e[5]!==t||e[6]!==s?(d=async e=>{try{await F({connectionId:t,docName:e,scope:`last`,agentName:i?.agent?.displayName}),s()}catch(e){let t=e,n=t instanceof Error?t.message:String(t);T.error(`Undo failed: ${n}`),s()}},e[4]=i,e[5]=t,e[6]=s,e[7]=d):d=e[7];let m=d,h;e[8]!==i||e[9]!==t||e[10]!==s?(h=async e=>{try{await F({connectionId:t,docName:e,scope:`file`,agentName:i?.agent?.displayName}),T.success(`Undone all edits on ${e}`),s()}catch(e){let t=e,n=t instanceof Error?t.message:String(t);T.error(`Undo all failed: ${n}`),s()}},e[8]=i,e[9]=t,e[10]=s,e[11]=h):h=e[11];let g=h,_;return e[12]!==n||e[13]!==i||e[14]!==o||e[15]!==c||e[16]!==u||e[17]!==g||e[18]!==m||e[19]!==s||e[20]!==a?(_=(0,P.jsx)(H,{data:i,status:a,error:o,reload:s,fetchBurstDiff:c,onExit:n,onNavigate:u,onUndoLast:m,onUndoAll:g}),e[12]=n,e[13]=i,e[14]=o,e[15]=c,e[16]=u,e[17]=g,e[18]=m,e[19]=s,e[20]=a,e[21]=_):_=e[21],_}export{ve as ActivityModeContent};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ActivityPanelDiffView-B_49ivYc.js","./chunk-CFjPhJqf.js","./compiler-runtime-CVnuRdak.js","./ActivityPanelDiffView-legcy4jI.css"])))=>i.map(i=>d[i]);
2
+ import{o as e}from"./chunk-CFjPhJqf.js";import{t}from"./preload-helper-2ej06EnG.js";import{n,r,t as i}from"./compiler-runtime-CVnuRdak.js";import{m as a}from"./doc-hash-CfmBVnag.js";import{t as o,w as s}from"./button-qDXa0MxS.js";import{Jt as c,Pt as l,Xt as u,Yt as d,n as f,r as p}from"./DocumentContext-CKgn09Wu.js";import{f as m,i as h,m as g,r as _,t as v}from"./agent-presence-CaGG2gp7.js";import{S as y,a as b,c as x,i as S,o as C,s as w,t as T}from"./dialog-CV9Q4JrD.js";import{i as E,n as D,t as O}from"./tooltip-csUfbEtd.js";var k=s(`rewind`,[[`path`,{d:`M12 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 12 18z`,key:`2a1g8i`}],[`path`,{d:`M22 6a2 2 0 0 0-3.414-1.414l-6 6a2 2 0 0 0 0 2.828l6 6A2 2 0 0 0 22 18z`,key:`rg3s36`}]]),A=i(),j=e(n(),1),M=500,ee=64;async function te(e){let t=`/api/agent-activity?agentId=${encodeURIComponent(e)}`,n=await fetch(t);if(!n.ok)throw Error(`agent-activity fetch failed: HTTP ${n.status}`);let r=await n.json();if(!r.ok)throw Error(r.error??`agent-activity fetch not ok`);return{sessionAlive:r.sessionAlive??!1,agent:r.agent??null,files:r.files??[]}}async function N(e,t,n){let r=`/api/agent-burst-diff?agentId=${encodeURIComponent(e)}&docName=${encodeURIComponent(t)}&stackIndex=${n}`,i=await fetch(r);if(!i.ok)throw Error(`agent-burst-diff fetch failed: HTTP ${i.status}`);let a=await i.json();if(!a.ok)throw Error(a.error??`agent-burst-diff fetch not ok`);return a.diff??``}function ne(e){let t=(0,A.c)(23),{systemProvider:n}=f(),[r,i]=(0,j.useState)(null),[o,s]=(0,j.useState)(`idle`),[c,l]=(0,j.useState)(null),u;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=new h(ee),t[0]=u):u=t[0];let d=(0,j.useRef)(u),p=(0,j.useRef)(0),m;t[1]===n?m=t[2]:(m=e=>{let t=p.current+=1;s(`loading`),l(null),te(e).then(r=>{if(p.current!==t)return;let a=ie(n,e);i({...r,writingDocs:a}),s(`ready`)}).catch(e=>{p.current===t&&(l(e instanceof Error?e.message:String(e)),s(`error`))})},t[1]=n,t[2]=m);let g=m,_;t[3]!==e||t[4]!==g?(_=()=>{if(!e){p.current+=1,i(null),s(`idle`),l(null),d.current.clear();return}d.current.clear(),g(e);let t=null,n=a(n=>{n.includes(`session-activity`)&&(t&&clearTimeout(t),t=setTimeout(()=>{t=null,g(e)},M))});return()=>{t&&clearTimeout(t),n()}},t[3]=e,t[4]=g,t[5]=_):_=t[5];let v;t[6]===e?v=t[7]:(v=[e],t[6]=e,t[7]=v),(0,j.useEffect)(_,v);let y,b;t[8]!==e||t[9]!==n?(y=()=>{if(!e||!n)return;let t=()=>{if(!n.awareness)return;let t=ie(n,e);i(e=>!e||re(e.writingDocs,t)?e:{...e,writingDocs:t})},r=n.awareness;if(!r||typeof r.on!=`function`){t();return}r.on(`update`,t),t();let a=setInterval(t,1e3);return()=>{clearInterval(a),typeof r.off==`function`&&r.off(`update`,t)}},b=[e,n],t[8]=e,t[9]=n,t[10]=y,t[11]=b):(y=t[10],b=t[11]),(0,j.useEffect)(y,b);let x;t[12]===e?x=t[13]:(x=async(t,n)=>{if(!e)return``;let r=`${t}\0${n}`,i=d.current.get(r);if(i!==void 0)return i;let a=await N(e,t,n);return d.current.set(r,a),a},t[12]=e,t[13]=x);let S=x,C;t[14]!==e||t[15]!==g?(C=()=>{e&&g(e)},t[14]=e,t[15]=g,t[16]=C):C=t[16];let w=C,T;return t[17]!==r||t[18]!==c||t[19]!==S||t[20]!==w||t[21]!==o?(T={data:r,status:o,error:c,reload:w,fetchBurstDiff:S},t[17]=r,t[18]=c,t[19]=S,t[20]=w,t[21]=o,t[22]=T):T=t[22],T}function re(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function ie(e,t){let n=new Set;if(!e)return n;let r=e.awareness;if(!v(r))return n;let i=[t,t.startsWith(`agent-`)?t.slice(6):`agent-${t}`];for(let e of r.getStates().values()){let t=e.agentPresence;if(t)for(let e of i){let r=t[e];r&&r.mode===`writing`&&r.currentDoc&&n.add(r.currentDoc)}}return n}var P=r(),ae=(0,j.lazy)(async()=>({default:(await t(()=>import(`./ActivityPanelDiffView-B_49ivYc.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)).ActivityPanelDiffView}));function oe(e,t){let n=Math.max(0,t-e);return n<6e4?`${Math.round(n/1e3)}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:new Date(e).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function se(e){let t=(0,A.c)(38),{burst:n,docName:r,fetchBurstDiff:i}=e,[a,o]=(0,j.useState)(!1),[s,c]=(0,j.useState)(null),[l,f]=(0,j.useState)(null),[p,m]=(0,j.useState)(!1),[h,g]=(0,j.useState)(ce),_,v;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(_=()=>{let e=setInterval(()=>g(Date.now()),3e4);return()=>clearInterval(e)},v=[],t[0]=_,t[1]=v):(_=t[0],v=t[1]),(0,j.useEffect)(_,v);let y;t[2]!==n.stackIndex||t[3]!==s||t[4]!==r||t[5]!==a||t[6]!==i||t[7]!==p?(y=()=>{let e=!a;o(e),e&&s===null&&!p&&(m(!0),f(null),i(r,n.stackIndex).then(e=>{c(e),m(!1)}).catch(e=>{f(e instanceof Error?e.message:String(e)),m(!1)}))},t[2]=n.stackIndex,t[3]=s,t[4]=r,t[5]=a,t[6]=i,t[7]=p,t[8]=y):y=t[8];let b=y,x=`${a?`Collapse`:`Expand`} burst ${n.stackIndex+1} diff`,S;t[9]===a?S=t[10]:(S=a?(0,P.jsx)(u,{className:`size-3 shrink-0`,"aria-hidden":`true`}):(0,P.jsx)(d,{className:`size-3 shrink-0`,"aria-hidden":`true`}),t[9]=a,t[10]=S);let C;t[11]!==n.ts||t[12]!==h?(C=oe(n.ts,h),t[11]=n.ts,t[12]=h,t[13]=C):C=t[13];let w;t[14]===C?w=t[15]:(w=(0,P.jsx)(`span`,{className:`font-mono`,children:C}),t[14]=C,t[15]=w);let T;t[16]===n.additions?T=t[17]:(T=(0,P.jsxs)(`span`,{className:`text-green-600 dark:text-green-400`,children:[`+`,n.additions]}),t[16]=n.additions,t[17]=T);let E;t[18]===n.deletions?E=t[19]:(E=(0,P.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,n.deletions]}),t[18]=n.deletions,t[19]=E);let D;t[20]!==T||t[21]!==E?(D=(0,P.jsxs)(`span`,{className:`ml-auto font-mono`,children:[T,` `,E]}),t[20]=T,t[21]=E,t[22]=D):D=t[22];let O;t[23]!==a||t[24]!==D||t[25]!==x||t[26]!==S||t[27]!==w||t[28]!==b?(O=(0,P.jsxs)(`button`,{type:`button`,onClick:b,className:`flex w-full items-center gap-2 px-4 py-1.5 text-xs text-muted-foreground hover:bg-muted/40`,"aria-expanded":a,"aria-label":x,children:[S,w,D]}),t[23]=a,t[24]=D,t[25]=x,t[26]=S,t[27]=w,t[28]=b,t[29]=O):O=t[29];let k;t[30]!==s||t[31]!==a||t[32]!==l||t[33]!==p?(k=a?(0,P.jsx)(`div`,{className:`bg-muted/20`,children:p?(0,P.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:`Loading diff…`}):l?(0,P.jsxs)(`div`,{className:`px-4 py-2 text-xs text-destructive`,children:[`Failed: `,l]}):s===null?(0,P.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:`No diff.`}):(0,P.jsx)(j.Suspense,{fallback:(0,P.jsx)(`div`,{className:`px-4 py-2 text-xs text-muted-foreground italic`,children:`Loading diff…`}),children:(0,P.jsx)(ae,{diff:s})})}):null,t[30]=s,t[31]=a,t[32]=l,t[33]=p,t[34]=k):k=t[34];let M;return t[35]!==O||t[36]!==k?(M=(0,P.jsxs)(`div`,{className:`border-t border-border/50`,children:[O,k]}),t[35]=O,t[36]=k,t[37]=M):M=t[37],M}function ce(){return Date.now()}function le(e,t){let n=Math.max(0,t-e);return n<6e4?`${Math.round(n/1e3)}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:`${Math.round(n/36e5)}h ago`}function ue(e){let t=(0,A.c)(93),{file:n,sessionAlive:r,isWriting:i,onNavigate:a,onUndoLast:s,onUndoAll:c,fetchBurstDiff:l}=e,[f,p]=(0,j.useState)(!1),[h,g]=(0,j.useState)(!1),[_,v]=(0,j.useState)(!1),[y,M]=(0,j.useState)(fe),ee,te;if(t[0]===Symbol.for(`react.memo_cache_sentinel`)?(ee=()=>{let e=setInterval(()=>M(Date.now()),3e4);return()=>clearInterval(e)},te=[],t[0]=ee,t[1]=te):(ee=t[0],te=t[1]),(0,j.useEffect)(ee,te),n.bursts.length===0)return null;let N=!r||n.bursts.length===0||_,ne=r?n.bursts.length===0?`Nothing to undo on this file`:null:`Session ended — undo unavailable`,re;t[2]!==N||t[3]!==n.docName||t[4]!==s?(re=e=>{e.stopPropagation(),!N&&(v(!0),Promise.resolve(s(n.docName)).finally(()=>v(!1)))},t[2]=N,t[3]=n.docName,t[4]=s,t[5]=re):re=t[5];let ie=re,ae;t[6]===N?ae=t[7]:(ae=e=>{e.stopPropagation(),!N&&g(!0)},t[6]=N,t[7]=ae);let oe=ae,ce;t[8]!==N||t[9]!==n.docName||t[10]!==c?(ce=()=>{g(!1),!N&&(v(!0),Promise.resolve(c(n.docName)).finally(()=>v(!1)))},t[8]=N,t[9]=n.docName,t[10]=c,t[11]=ce):ce=t[11];let ue=ce,F;t[12]===Symbol.for(`react.memo_cache_sentinel`)?(F=()=>p(de),t[12]=F):F=t[12];let pe=f?`Collapse ${n.docName}`:`Expand ${n.docName}`,I;t[13]===f?I=t[14]:(I=f?(0,P.jsx)(u,{className:`size-4`,"aria-hidden":`true`}):(0,P.jsx)(d,{className:`size-4`,"aria-hidden":`true`}),t[13]=f,t[14]=I);let L;t[15]!==f||t[16]!==pe||t[17]!==I?(L=(0,P.jsx)(`button`,{type:`button`,onClick:F,className:`flex size-5 shrink-0 items-center justify-center rounded hover:bg-muted`,"aria-expanded":f,"aria-label":pe,"data-testid":`activity-panel-file-row-carrot`,children:I}),t[15]=f,t[16]=pe,t[17]=I,t[18]=L):L=t[18];let R;t[19]!==n.docName||t[20]!==a?(R=()=>a(n.docName),t[19]=n.docName,t[20]=a,t[21]=R):R=t[21];let me=`Navigate to ${n.docName}`,z;t[22]!==n.docName||t[23]!==R||t[24]!==me?(z=(0,P.jsx)(`button`,{type:`button`,onClick:R,className:`min-w-0 flex-1 truncate text-left text-foreground hover:underline focus-visible:outline-ring`,"aria-label":me,"data-testid":`activity-panel-file-row-filename`,title:n.docName,children:n.docName}),t[22]=n.docName,t[23]=R,t[24]=me,t[25]=z):z=t[25];let he=`Undo last edit on ${n.docName}`,ge;t[26]===Symbol.for(`react.memo_cache_sentinel`)?(ge=(0,P.jsx)(m,{className:`size-3.5`,"aria-hidden":`true`}),t[26]=ge):ge=t[26];let B;t[27]!==N||t[28]!==ie||t[29]!==he?(B=(0,P.jsx)(E,{asChild:!0,children:(0,P.jsx)(o,{type:`button`,variant:`ghost`,size:`icon`,className:`size-6 shrink-0`,onClick:ie,disabled:N,"aria-label":he,"data-testid":`activity-panel-undo-last`,children:ge})}),t[27]=N,t[28]=ie,t[29]=he,t[30]=B):B=t[30];let _e=ne??`Undo last edit`,V;t[31]===_e?V=t[32]:(V=(0,P.jsx)(D,{side:`bottom`,children:_e}),t[31]=_e,t[32]=V);let H;t[33]!==B||t[34]!==V?(H=(0,P.jsxs)(O,{children:[B,V]}),t[33]=B,t[34]=V,t[35]=H):H=t[35];let ve=`Undo all edits on ${n.docName}`,ye;t[36]===Symbol.for(`react.memo_cache_sentinel`)?(ye=(0,P.jsx)(k,{className:`size-3.5`,"aria-hidden":`true`}),t[36]=ye):ye=t[36];let be;t[37]!==N||t[38]!==oe||t[39]!==ve?(be=(0,P.jsx)(E,{asChild:!0,children:(0,P.jsx)(o,{type:`button`,variant:`ghost`,size:`icon`,className:`size-6 shrink-0`,onClick:oe,disabled:N,"aria-label":ve,"data-testid":`activity-panel-undo-all`,children:ye})}),t[37]=N,t[38]=oe,t[39]=ve,t[40]=be):be=t[40];let xe=ne??`Undo all edits`,U;t[41]===xe?U=t[42]:(U=(0,P.jsx)(D,{side:`bottom`,children:xe}),t[41]=xe,t[42]=U);let W;t[43]!==be||t[44]!==U?(W=(0,P.jsxs)(O,{children:[be,U]}),t[43]=be,t[44]=U,t[45]=W):W=t[45];let G;t[46]===n.additionsTotal?G=t[47]:(G=(0,P.jsxs)(`span`,{className:`text-green-600 dark:text-green-400`,children:[`+`,n.additionsTotal]}),t[46]=n.additionsTotal,t[47]=G);let K;t[48]===n.deletionsTotal?K=t[49]:(K=(0,P.jsxs)(`span`,{className:`text-red-600 dark:text-red-400`,children:[`−`,n.deletionsTotal]}),t[48]=n.deletionsTotal,t[49]=K);let q;t[50]!==G||t[51]!==K?(q=(0,P.jsxs)(`span`,{className:`shrink-0 font-mono text-xs`,children:[G,` `,K]}),t[50]=G,t[51]=K,t[52]=q):q=t[52];let J;t[53]!==n.lastTs||t[54]!==y?(J=le(n.lastTs,y),t[53]=n.lastTs,t[54]=y,t[55]=J):J=t[55];let Y;t[56]===J?Y=t[57]:(Y=(0,P.jsx)(`span`,{className:`shrink-0 font-mono text-[11px] text-muted-foreground`,children:J}),t[56]=J,t[57]=Y);let X;t[58]===i?X=t[59]:(X=i?(0,P.jsx)(`span`,{className:`shrink-0 text-[11px] text-primary animate-pulse`,role:`status`,children:`writing…`}):null,t[58]=i,t[59]=X);let Z;t[60]!==z||t[61]!==H||t[62]!==W||t[63]!==q||t[64]!==Y||t[65]!==X||t[66]!==L?(Z=(0,P.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 text-sm`,children:[L,z,H,W,q,Y,X]}),t[60]=z,t[61]=H,t[62]=W,t[63]=q,t[64]=Y,t[65]=X,t[66]=L,t[67]=Z):Z=t[67];let Q;t[68]!==f||t[69]!==l||t[70]!==n.bursts||t[71]!==n.docName?(Q=f?(0,P.jsx)(`div`,{children:n.bursts.map(e=>(0,P.jsx)(se,{burst:e,docName:n.docName,fetchBurstDiff:l},`${n.docName}:${e.stackIndex}`))}):null,t[68]=f,t[69]=l,t[70]=n.bursts,t[71]=n.docName,t[72]=Q):Q=t[72];let Se;t[73]===Symbol.for(`react.memo_cache_sentinel`)?(Se=(0,P.jsx)(x,{children:`Undo all edits on this file?`}),t[73]=Se):Se=t[73];let Ce;t[74]===n.docName?Ce=t[75]:(Ce=(0,P.jsx)(`span`,{className:`font-mono text-foreground`,children:n.docName}),t[74]=n.docName,t[75]=Ce);let we=n.bursts.length===1?``:`s`,Te;t[76]!==n.bursts.length||t[77]!==Ce||t[78]!==we?(Te=(0,P.jsxs)(w,{children:[Se,(0,P.jsxs)(b,{children:[`This will revert every change this agent has made to`,` `,Ce,` in their current session (`,n.bursts.length,` burst`,we,`). Other files and other writers are not affected.`]})]}),t[76]=n.bursts.length,t[77]=Ce,t[78]=we,t[79]=Te):Te=t[79];let Ee;t[80]===Symbol.for(`react.memo_cache_sentinel`)?(Ee=(0,P.jsx)(o,{type:`button`,variant:`outline`,onClick:()=>g(!1),"data-testid":`activity-panel-undo-all-cancel`,children:`Cancel`}),t[80]=Ee):Ee=t[80];let De;t[81]===ue?De=t[82]:(De=(0,P.jsxs)(C,{children:[Ee,(0,P.jsx)(o,{type:`button`,variant:`destructive`,onClick:ue,"data-testid":`activity-panel-undo-all-confirm`,children:`Undo all`})]}),t[81]=ue,t[82]=De);let Oe;t[83]!==Te||t[84]!==De?(Oe=(0,P.jsxs)(S,{className:`sm:max-w-md`,children:[Te,De]}),t[83]=Te,t[84]=De,t[85]=Oe):Oe=t[85];let $;t[86]!==h||t[87]!==Oe?($=(0,P.jsx)(T,{open:h,onOpenChange:g,children:Oe}),t[86]=h,t[87]=Oe,t[88]=$):$=t[88];let ke;return t[89]!==Z||t[90]!==Q||t[91]!==$?(ke=(0,P.jsxs)(`div`,{className:`border-b border-border`,"data-testid":`activity-panel-file-row`,children:[Z,Q,$]}),t[89]=Z,t[90]=Q,t[91]=$,t[92]=ke):ke=t[92],ke}function de(e){return!e}function fe(){return Date.now()}async function F(e){let t=await fetch(`/api/agent-undo`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,agentId:e.connectionId})});if(!t.ok)throw Error(`agent-undo failed: HTTP ${t.status}`)}function pe(e){return`#/${e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`)}`}function I(e){typeof window>`u`||(window.location.hash=pe(e))}function L(){let e=(0,A.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,P.jsxs)(`div`,{className:`flex h-full items-center justify-center p-6 text-muted-foreground`,role:`status`,"aria-busy":`true`,children:[(0,P.jsx)(l,{className:`mr-2 size-4 animate-spin`,"aria-hidden":`true`}),(0,P.jsx)(`span`,{className:`text-sm`,children:`Loading agent activity…`})]}),e[0]=t):t=e[0],t}function R(e){let t=(0,A.c)(9),{error:n,onRetry:r}=e,i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,P.jsx)(c,{className:`size-6 text-destructive`,"aria-hidden":`true`}),t[0]=i):i=t[0];let a;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,P.jsx)(`p`,{className:`text-sm font-medium`,children:`Failed to load activity`}),t[1]=a):a=t[1];let s;t[2]===n?s=t[3]:(s=(0,P.jsxs)(`div`,{className:`space-y-1`,children:[a,(0,P.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:n})]}),t[2]=n,t[3]=s);let l;t[4]===r?l=t[5]:(l=(0,P.jsx)(o,{type:`button`,variant:`outline`,size:`sm`,onClick:r,children:`Retry`}),t[4]=r,t[5]=l);let u;return t[6]!==s||t[7]!==l?(u=(0,P.jsxs)(`div`,{className:`flex flex-col items-center gap-3 p-6 text-center`,role:`alert`,"data-testid":`activity-panel-error`,children:[i,s,l]}),t[6]=s,t[7]=l,t[8]=u):u=t[8],u}function me(){let e=(0,A.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,P.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-muted-foreground`,"data-testid":`activity-panel-empty`,children:(0,P.jsx)(`p`,{className:`text-sm italic`,children:`No edits yet.`})}),e[0]=t):t=e[0],t}function z(e){let t=(0,A.c)(8),{onExit:n}=e,r;t[0]===n?r=t[1]:(r=(0,P.jsx)(he,{onClick:n}),t[0]=n,t[1]=r);let i;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(i=(0,P.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:`Agent activity`}),t[2]=i):i=t[2];let a;t[3]===r?a=t[4]:(a=(0,P.jsxs)(`div`,{className:`flex shrink-0 flex-row items-center gap-2 border-b border-border px-3 py-2`,children:[r,i]}),t[3]=r,t[4]=a);let o;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,P.jsx)(`div`,{className:`flex flex-1 items-center justify-center p-6 text-muted-foreground`,children:(0,P.jsx)(`p`,{className:`text-center text-sm italic`,children:`Click an agent's avatar in the presence bar to view their session.`})}),t[5]=o):o=t[5];let s;return t[6]===a?s=t[7]:(s=(0,P.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col`,"data-testid":`activity-panel-no-agent`,"aria-label":`Agent activity`,children:[a,o]}),t[6]=a,t[7]=s),s}function he(e){let t=(0,A.c)(6),{onClick:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,P.jsx)(g,{}),t[0]=r):r=t[0];let i;t[1]===n?i=t[2]:(i=(0,P.jsx)(E,{asChild:!0,children:(0,P.jsx)(o,{type:`button`,variant:`ghost`,size:`icon`,className:`size-7 shrink-0`,onClick:n,"aria-label":`Back to document view`,"data-testid":`docpanel-exit-agent-mode`,children:r})}),t[1]=n,t[2]=i);let a;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,P.jsx)(D,{side:`bottom`,children:`Back to document view`}),t[3]=a):a=t[3];let s;return t[4]===i?s=t[5]:(s=(0,P.jsxs)(O,{children:[i,a]}),t[4]=i,t[5]=s),s}function ge(e){let t=(0,A.c)(9),{lastTs:n}=e,[r]=(0,j.useState)(B),i;t[0]!==n||t[1]!==r?(i=n?_e(r-n):null,t[0]=n,t[1]=r,t[2]=i):i=t[2];let a=i,o;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,P.jsx)(`span`,{className:`font-medium`,children:`Session ended`}),t[3]=o):o=t[3];let s;t[4]===a?s=t[5]:(s=a?(0,P.jsxs)(`span`,{children:[` · `,a]}):null,t[4]=a,t[5]=s);let c;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,P.jsx)(`div`,{className:`mt-1 opacity-80`,children:`Undo buttons are disabled — per-session state has been garbage-collected.`}),t[6]=c):c=t[6];let l;return t[7]===s?l=t[8]:(l=(0,P.jsxs)(`div`,{className:`border-b border-border bg-muted/40 px-4 py-3 text-xs text-muted-foreground`,"data-testid":`activity-panel-session-ended`,children:[o,s,c]}),t[7]=s,t[8]=l),l}function B(){return Date.now()}function _e(e){let t=Math.max(0,e);return t<6e4?`${Math.round(t/1e3)}s ago`:t<36e5?`${Math.round(t/6e4)}m ago`:`${Math.round(t/36e5)}h ago`}function V(e){let t=(0,A.c)(10),{agent:n,size:r}=e,i=r===void 0?28:r,a;t[0]!==n.color||t[1]!==i?(a={backgroundColor:n.color,width:i,height:i},t[0]=n.color,t[1]=i,t[2]=a):a=t[2];let o=i*.57,s=i*.57,c;t[3]!==n.icon||t[4]!==o||t[5]!==s?(c=(0,P.jsx)(_,{icon:n.icon,width:o,height:s}),t[3]=n.icon,t[4]=o,t[5]=s,t[6]=c):c=t[6];let l;return t[7]!==a||t[8]!==c?(l=(0,P.jsx)(`span`,{className:`inline-flex shrink-0 items-center justify-center rounded-full text-white ring-2 ring-background`,style:a,"aria-hidden":`true`,children:c}),t[7]=a,t[8]=c,t[9]=l):l=t[9],l}function H(e){let t=(0,A.c)(20),{data:n,status:r,error:i,reload:a,fetchBurstDiff:o,onExit:s,onNavigate:c,onUndoLast:l,onUndoAll:u}=e,d=n?.files?.[0]?.lastTs??null,f;t[0]===s?f=t[1]:(f=(0,P.jsx)(he,{onClick:s}),t[0]=s,t[1]=f);let p;t[2]===n?p=t[3]:(p=n?.agent?(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(V,{agent:n.agent}),(0,P.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,P.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:n.agent.displayName}),(0,P.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[n.sessionAlive?`Active`:`Ended`,n.files.length>0?` · ${n.files.length} file${n.files.length===1?``:`s`}`:``]})]})]}):(0,P.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,P.jsx)(`h2`,{className:`truncate text-sm font-medium`,children:`Agent activity`})}),t[2]=n,t[3]=p);let m;t[4]!==f||t[5]!==p?(m=(0,P.jsxs)(`div`,{className:`flex flex-row items-center gap-2 border-b border-border px-3 py-2 shrink-0`,children:[f,p]}),t[4]=f,t[5]=p,t[6]=m):m=t[6];let h;t[7]!==n||t[8]!==i||t[9]!==o||t[10]!==d||t[11]!==c||t[12]!==u||t[13]!==l||t[14]!==a||t[15]!==r?(h=(0,P.jsx)(`div`,{className:`flex-1 overflow-y-auto`,"data-testid":`activity-panel-body`,children:r===`loading`&&n===null?(0,P.jsx)(L,{}):r===`error`&&i?(0,P.jsx)(R,{error:i,onRetry:a}):n===null?(0,P.jsx)(me,{}):(0,P.jsxs)(P.Fragment,{children:[n.sessionAlive?null:(0,P.jsx)(ge,{lastTs:d}),n.files.length===0?(0,P.jsx)(me,{}):n.files.map(e=>(0,P.jsx)(ue,{file:e,sessionAlive:n.sessionAlive,isWriting:n.writingDocs.has(e.docName),onNavigate:c,onUndoLast:l,onUndoAll:u,fetchBurstDiff:o},e.docName))]})}),t[7]=n,t[8]=i,t[9]=o,t[10]=d,t[11]=c,t[12]=u,t[13]=l,t[14]=a,t[15]=r,t[16]=h):h=t[16];let g;return t[17]!==m||t[18]!==h?(g=(0,P.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col`,"data-testid":`activity-panel`,"aria-label":`Agent activity`,children:[m,h]}),t[17]=m,t[18]=h,t[19]=g):g=t[19],g}function ve(){let e=(0,A.c)(22),{docPanelAgentId:t,closeActivityPanel:n}=f(),{openDocumentTransition:r}=p(),{data:i,status:a,error:o,reload:s,fetchBurstDiff:c}=ne(t);if(t===null){let t;return e[0]===n?t=e[1]:(t=(0,P.jsx)(z,{onExit:n}),e[0]=n,e[1]=t),t}let l;e[2]===r?l=e[3]:(l=e=>{r(e),I(e)},e[2]=r,e[3]=l);let u=l,d;e[4]!==i||e[5]!==t||e[6]!==s?(d=async e=>{try{await F({connectionId:t,docName:e,scope:`last`,agentName:i?.agent?.displayName}),s()}catch(e){let t=e,n=t instanceof Error?t.message:String(t);y.error(`Undo failed: ${n}`),s()}},e[4]=i,e[5]=t,e[6]=s,e[7]=d):d=e[7];let m=d,h;e[8]!==i||e[9]!==t||e[10]!==s?(h=async e=>{try{await F({connectionId:t,docName:e,scope:`file`,agentName:i?.agent?.displayName}),y.success(`Undone all edits on ${e}`),s()}catch(e){let t=e,n=t instanceof Error?t.message:String(t);y.error(`Undo all failed: ${n}`),s()}},e[8]=i,e[9]=t,e[10]=s,e[11]=h):h=e[11];let g=h,_;return e[12]!==n||e[13]!==i||e[14]!==o||e[15]!==c||e[16]!==u||e[17]!==g||e[18]!==m||e[19]!==s||e[20]!==a?(_=(0,P.jsx)(H,{data:i,status:a,error:o,reload:s,fetchBurstDiff:c,onExit:n,onNavigate:u,onUndoLast:m,onUndoAll:g}),e[12]=n,e[13]=i,e[14]=o,e[15]=c,e[16]=u,e[17]=g,e[18]=m,e[19]=s,e[20]=a,e[21]=_):_=e[21],_}export{ve as ActivityModeContent};