@inkeep/open-knowledge 0.25.0-beta.16 → 0.25.0-beta.17

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 (288) hide show
  1. package/dist/assets/skills/discovery/SKILL.md +1 -1
  2. package/dist/assets/skills/project/SKILL.md +1 -1
  3. package/dist/cli.mjs +19 -19
  4. package/dist/constants-u4lg1sDo.mjs +2 -0
  5. package/dist/{dist-C1MZNyof.mjs → dist-CHMoEx27.mjs} +1 -1
  6. package/dist/{dist-B923c31q.mjs → dist-CefxLzs-.mjs} +9 -8
  7. package/dist/{gh-detect-C_0kt1kp.mjs → gh-detect-agW-_3XF.mjs} +2 -2
  8. package/dist/{git-handle-BM0b1rwW-DuV-KO4L.mjs → git-handle-B4hCEi7c-CXOP12Ds.mjs} +2 -2
  9. package/dist/git-handle-DG8d2xCi-C_CAAChL.mjs +1 -0
  10. package/dist/index.mjs +1 -1
  11. package/dist/init-DrHm6UJF.mjs +1 -0
  12. package/dist/{init-ICH9ja53.mjs → init-hugxd53g.mjs} +5 -5
  13. package/dist/{loader-Dv5atXyy.mjs → loader--DLOVwU4.mjs} +3 -3
  14. package/dist/loader-BiTnSGzo.mjs +1 -0
  15. package/dist/{preview-CQG9jtTU.mjs → preview-BAF22TOz.mjs} +2 -2
  16. package/dist/preview-BdhhmEGp.mjs +1 -0
  17. package/dist/public/assets/ActivityModeContent-CJFUc7RW.js +2 -0
  18. package/dist/public/assets/ConsentDialogBody-CndpLVpa.js +2 -0
  19. package/dist/public/assets/DocumentContext-BUrGKvmA.js +32 -0
  20. package/dist/public/assets/EnableSyncConfirmDialog-BCBYaNI1.js +1 -0
  21. package/dist/public/assets/{GraphPanel-NJL83_At.js → GraphPanel-q480x3Pp.js} +9 -9
  22. package/dist/public/assets/ManagedArtifactProperties-UH7x5288.js +1 -0
  23. package/dist/public/assets/McpConsentDialogBody-NG01mM3X.js +1 -0
  24. package/dist/public/assets/PropertyPanel-DfIZg5rp.js +2 -0
  25. package/dist/public/assets/SettingsDialogBody-BcsIU5IO.js +7 -0
  26. package/dist/public/assets/ShareBranchSwitchDialog-DEixS5ow.js +1 -0
  27. package/dist/public/assets/ShareReceiveDialog-B-a7ftvp.js +1 -0
  28. package/dist/public/assets/ShareReceiveMissDialog-DuqsMjIE.js +1 -0
  29. package/dist/public/assets/SkillEditorActions-D99amW-6.js +1 -0
  30. package/dist/public/assets/SourceEditor-DYmBrxoa.js +2 -0
  31. package/dist/public/assets/{TerminalPanel-Bb5Hbdf3.js → TerminalPanel-CEcImr1_.js} +3 -3
  32. package/dist/public/assets/{_baseFor-D25oCqSU.js → _baseFor-M6ASkr3S.js} +1 -1
  33. package/dist/public/assets/{agent-presence-BRmBPq78.js → agent-presence-hQFriJP_.js} +1 -1
  34. package/dist/public/assets/{arc-DHpQGPKi.js → arc-BT8Hati9.js} +1 -1
  35. package/dist/public/assets/architecture-YZFGNWBL-BVEBoCy0.js +1 -0
  36. package/dist/public/assets/{architectureDiagram-Q4EWVU46-Dl6zKdMi.js → architectureDiagram-Q4EWVU46-BnLULocP.js} +1 -1
  37. package/dist/public/assets/{blockDiagram-DXYQGD6D-TTNbipzm.js → blockDiagram-DXYQGD6D-DgcakmQd.js} +1 -1
  38. package/dist/public/assets/{c4Diagram-AHTNJAMY-DJ6_yNro.js → c4Diagram-AHTNJAMY-MpS57keD.js} +1 -1
  39. package/dist/public/assets/{calendar-BefXYqrv.js → calendar-DPQ_ICRf.js} +1 -1
  40. package/dist/public/assets/channel-BnB1CAkA.js +1 -0
  41. package/dist/public/assets/check-CAsS5Elz.js +1 -0
  42. package/dist/public/assets/checkbox-DYATp18o.js +1 -0
  43. package/dist/public/assets/{chunk-2KRD3SAO-tPsWTtQ8.js → chunk-2KRD3SAO-kMTRGKj1.js} +1 -1
  44. package/dist/public/assets/{chunk-336JU56O-BDNF8ABQ.js → chunk-336JU56O-D9l-iSoM.js} +2 -2
  45. package/dist/public/assets/chunk-426QAEUC-CGz89IOu.js +1 -0
  46. package/dist/public/assets/{chunk-4BX2VUAB-B11p4CCh.js → chunk-4BX2VUAB-CxNONOIl.js} +1 -1
  47. package/dist/public/assets/{chunk-4TB4RGXK-k8il4Vah.js → chunk-4TB4RGXK-BJBCQpxu.js} +1 -1
  48. package/dist/public/assets/chunk-55IACEB6-hdKwekPD.js +1 -0
  49. package/dist/public/assets/{chunk-5FUZZQ4R-BhDATrAC.js → chunk-5FUZZQ4R-qTd1X-_B.js} +1 -1
  50. package/dist/public/assets/{chunk-5PVQY5BW-7GSXpGpA.js → chunk-5PVQY5BW-yDTy3kh2.js} +1 -1
  51. package/dist/public/assets/{chunk-67CJDMHE-DhsO5dA4.js → chunk-67CJDMHE-BoJfX61q.js} +1 -1
  52. package/dist/public/assets/{chunk-7N4EOEYR-_OPnqGDq.js → chunk-7N4EOEYR-CZeloxNb.js} +1 -1
  53. package/dist/public/assets/{chunk-AA7GKIK3-CmQNMaMq.js → chunk-AA7GKIK3-C2HwyAHF.js} +1 -1
  54. package/dist/public/assets/{chunk-BSJP7CBP-DRn1Q8qZ.js → chunk-BSJP7CBP-C-dn2Mkj.js} +1 -1
  55. package/dist/public/assets/{chunk-CIAEETIT-B6L60eSe.js → chunk-CIAEETIT-CUjsY9Jn.js} +1 -1
  56. package/dist/public/assets/{chunk-EDXVE4YY-TfqLQBKW.js → chunk-EDXVE4YY-GdX4IlNB.js} +1 -1
  57. package/dist/public/assets/{chunk-ENJZ2VHE-CqUfmxZL.js → chunk-ENJZ2VHE-B1deOUrZ.js} +1 -1
  58. package/dist/public/assets/{chunk-FMBD7UC4-_M3xiFqk.js → chunk-FMBD7UC4-4T3_kXBp.js} +1 -1
  59. package/dist/public/assets/{chunk-FOC6F5B3-R--gjWDw.js → chunk-FOC6F5B3-BdKFMbn0.js} +1 -1
  60. package/dist/public/assets/{chunk-ICPOFSXX-MhneOmo1.js → chunk-ICPOFSXX-CIVLR_5F.js} +2 -2
  61. package/dist/public/assets/{chunk-K5T4RW27-kfFBI7dm.js → chunk-K5T4RW27-B1SmKEZd.js} +1 -1
  62. package/dist/public/assets/{chunk-KGLVRYIC-MGoiNxXR.js → chunk-KGLVRYIC-CAvDRDdi.js} +1 -1
  63. package/dist/public/assets/{chunk-LIHQZDEY-3OBi6RFi.js → chunk-LIHQZDEY-BxEqkW3d.js} +1 -1
  64. package/dist/public/assets/{chunk-ORNJ4GCN-D1jJqGHz.js → chunk-ORNJ4GCN-Bb0szYVA.js} +1 -1
  65. package/dist/public/assets/{chunk-OYMX7WX6-Dn8GoIJo.js → chunk-OYMX7WX6-CBdUWkfK.js} +1 -1
  66. package/dist/public/assets/chunk-QZHKN3VN-D0cDmajJ.js +1 -0
  67. package/dist/public/assets/{chunk-U2HBQHQK-Wd4MIHD7.js → chunk-U2HBQHQK-BRyN8JBd.js} +1 -1
  68. package/dist/public/assets/{chunk-X2U36JSP-DgR3BYDC.js → chunk-X2U36JSP-o7MzjrQ3.js} +1 -1
  69. package/dist/public/assets/{chunk-XPW4576I-BIhGQhfc.js → chunk-XPW4576I-90AsGlZ-.js} +1 -1
  70. package/dist/public/assets/{chunk-YZCP3GAM-DfCU0Z-P.js → chunk-YZCP3GAM-08XDtemD.js} +1 -1
  71. package/dist/public/assets/{chunk-ZZ45TVLE-Bml1MOax.js → chunk-ZZ45TVLE-D2TDKoTv.js} +1 -1
  72. package/dist/public/assets/classDiagram-6PBFFD2Q-djt6-qsq.js +1 -0
  73. package/dist/public/assets/classDiagram-v2-HSJHXN6E-D9XE0jQw.js +1 -0
  74. package/dist/public/assets/clone--IpWXAZg.js +1 -0
  75. package/dist/public/assets/{collapsible-CjgfK1G5.js → collapsible-D2ThJMi2.js} +1 -1
  76. package/dist/public/assets/config-context-DJjTs62C.js +1 -0
  77. package/dist/public/assets/config-provider-BCrd1h3n.js +4 -0
  78. package/dist/public/assets/config-validation-events-c0bJLYdD.js +11 -0
  79. package/dist/public/assets/{cose-bilkent-S5V4N54A-CIV0yZWV.js → cose-bilkent-S5V4N54A-DKuOZr0O.js} +1 -1
  80. package/dist/public/assets/{dagre-KV5264BT-Bscv1HQo.js → dagre-KV5264BT-BH1vMnyV.js} +1 -1
  81. package/dist/public/assets/{dagre-BUnZfAns.js → dagre-ezBFxVi8.js} +1 -1
  82. package/dist/public/assets/desktop-bridge-types-C7nfug4w.js +1 -0
  83. package/dist/public/assets/{diagram-5BDNPKRD-QBP7yg8z.js → diagram-5BDNPKRD-C3DmjuH3.js} +1 -1
  84. package/dist/public/assets/{diagram-G4DWMVQ6-CMdeZ41j.js → diagram-G4DWMVQ6-J-UKxuT2.js} +1 -1
  85. package/dist/public/assets/{diagram-MMDJMWI5-DCz0ew8n.js → diagram-MMDJMWI5-DGIv4ujt.js} +1 -1
  86. package/dist/public/assets/{diagram-TYMM5635-zN9Dx1fB.js → diagram-TYMM5635-Cvs7rTa0.js} +1 -1
  87. package/dist/public/assets/dialog-DtVLDjny.js +45 -0
  88. package/dist/public/assets/{dist-AQSp7Qij.js → dist-AfBTOr2C.js} +1 -1
  89. package/dist/public/assets/{dist-E5KjgWw7.js → dist-BItEDTx8.js} +1 -1
  90. package/dist/public/assets/dist-BVOt51sU.js +1 -0
  91. package/dist/public/assets/dist-CBR3Gop_.js +23 -0
  92. package/dist/public/assets/dist-CWy4ixNG.js +1 -0
  93. package/dist/public/assets/dist-CgWVxeSo.js +1 -0
  94. package/dist/public/assets/dist-CgXWsFwX.js +1 -0
  95. package/dist/public/assets/dist-CyjUE1fU.js +1 -0
  96. package/dist/public/assets/dist-D0XhAWW8.js +1 -0
  97. package/dist/public/assets/{dist-BXd_K33i.js → dist-DXkiONdP.js} +1 -1
  98. package/dist/public/assets/dist-DwqkXXNG.js +9 -0
  99. package/dist/public/assets/{dist-DWaLpHcz.js → dist-Dx825WER2.js} +1 -1
  100. package/dist/public/assets/dist-JtyGhtXW.js +1 -0
  101. package/dist/public/assets/dist-QeKS_yUr.js +1 -0
  102. package/dist/public/assets/dist-SKUoQS3T.js +1 -0
  103. package/dist/public/assets/dist-guh9-s27.js +1 -0
  104. package/dist/public/assets/{dist-B2N5XdpF.js → dist-wye24uC6.js} +171 -171
  105. package/dist/public/assets/{documents-events-BQEuksqI.js → documents-events-B83ksr6N.js} +1 -1
  106. package/dist/public/assets/{erDiagram-SMLLAGMA-CFPPEjz0.js → erDiagram-SMLLAGMA-BisuKprM.js} +1 -1
  107. package/dist/public/assets/file-tree-adapter-a1FGMOP8.js +1 -0
  108. package/dist/public/assets/{flatten-sS3L8FSH.js → flatten-xNYSAL8G.js} +1 -1
  109. package/dist/public/assets/{flowDiagram-DWJPFMVM-DOjygKY4.js → flowDiagram-DWJPFMVM-B0HG4XkI.js} +1 -1
  110. package/dist/public/assets/{ganttDiagram-T4ZO3ILL-Cox3d5Yp.js → ganttDiagram-T4ZO3ILL-DQMAnJX0.js} +1 -1
  111. package/dist/public/assets/git-branch-GmlkrJG1.js +1 -0
  112. package/dist/public/assets/gitGraph-7Q5UKJZL-sYXFuH-f.js +1 -0
  113. package/dist/public/assets/{gitGraphDiagram-UUTBAWPF-BXvw3bmB.js → gitGraphDiagram-UUTBAWPF-D_atUqHK.js} +1 -1
  114. package/dist/public/assets/{graphlib-FYrXvm7X.js → graphlib-CssuwrQ0.js} +1 -1
  115. package/dist/public/assets/index-B3AzmMEn.css +1 -0
  116. package/dist/public/assets/index-Bh-HkPzm.js +2003 -0
  117. package/dist/public/assets/info-OMHHGYJF-BjKjxbM2.js +1 -0
  118. package/dist/public/assets/{infoDiagram-42DDH7IO-Bk54rrHD.js → infoDiagram-42DDH7IO-BSBW6Pan.js} +1 -1
  119. package/dist/public/assets/{isEmpty-DKKUMPPC.js → isEmpty-ORz5JRVb.js} +1 -1
  120. package/dist/public/assets/isSymbol-DXuURO6J.js +1 -0
  121. package/dist/public/assets/{ishikawaDiagram-UXIWVN3A-Bc3G_190.js → ishikawaDiagram-UXIWVN3A-BQ069xL3.js} +1 -1
  122. package/dist/public/assets/{journeyDiagram-VCZTEJTY-CLrtuKm7.js → journeyDiagram-VCZTEJTY-MGSlWbE2.js} +1 -1
  123. package/dist/public/assets/{kanban-definition-6JOO6SKY-DwQiIK5Z.js → kanban-definition-6JOO6SKY-Gdd-cuhS.js} +1 -1
  124. package/dist/public/assets/{keyboard-shortcuts-MXDWcMuC.js → keyboard-shortcuts-BO_yaXFa.js} +1 -1
  125. package/dist/public/assets/{label-DyT4OD9H.js → label-iXNPopUN.js} +1 -1
  126. package/dist/public/assets/{line-Dk1foLQO.js → line-BsWA6ttc.js} +1 -1
  127. package/dist/public/assets/{linear-D7qoVA2u.js → linear-DYHJjwmm.js} +1 -1
  128. package/dist/public/assets/loader-circle-B10CtBnC.js +1 -0
  129. package/dist/public/assets/{mermaid-parser.core-WlD4T62P.js → mermaid-parser.core-BkIpaEsR.js} +2 -2
  130. package/dist/public/assets/{mermaid.core-CLOkRfd8.js → mermaid.core-DTlyBC51.js} +3 -3
  131. package/dist/public/assets/{mindmap-definition-QFDTVHPH-DYJRBCQs.js → mindmap-definition-QFDTVHPH-RCGyFFgC.js} +1 -1
  132. package/dist/public/assets/miss-dialog-store-B0FbFVHM.js +1 -0
  133. package/dist/public/assets/{navigation-targets-0j0dncXj.js → navigation-targets-DiRykhu5.js} +1 -1
  134. package/dist/public/assets/{now-C9pOxV0O.js → now-CtwaUqv3.js} +1 -1
  135. package/dist/public/assets/{open-managed-artifact-tab-Ba10qvGi.js → open-managed-artifact-tab-DrODiIEr.js} +1 -1
  136. package/dist/public/assets/{ordinal-BLFf0NQg.js → ordinal-xd87TCK5.js} +1 -1
  137. package/dist/public/assets/packet-4T2RLAQJ-CCsYpon-.js +1 -0
  138. package/dist/public/assets/pie-ZZUOXDRM-BEHBBBt7.js +1 -0
  139. package/dist/public/assets/{pieDiagram-DEJITSTG-BtJ94Yhu.js → pieDiagram-DEJITSTG-e0uyQE_X.js} +1 -1
  140. package/dist/public/assets/{project-paths-CcPGtodV.js → project-paths-CB2fAetg.js} +1 -1
  141. package/dist/public/assets/prop-types-CSx_Gmsn.js +1 -0
  142. package/dist/public/assets/{propagation-api-CR2CQW4x.js → propagation-api-2R98p81r.js} +1 -1
  143. package/dist/public/assets/{quadrantDiagram-34T5L4WZ-B8wf6FVG.js → quadrantDiagram-34T5L4WZ-fiYcYSyL.js} +1 -1
  144. package/dist/public/assets/radar-PYXPWWZC-C3-Fl7K_.js +1 -0
  145. package/dist/public/assets/radio-group-CBK4VVOo.js +1 -0
  146. package/dist/public/assets/receive-store-93o2FscZ.js +2 -0
  147. package/dist/public/assets/{reduce-CrpTR7cO.js → reduce-CLK8gX02.js} +1 -1
  148. package/dist/public/assets/refresh-cw-BxQJQoCU.js +1 -0
  149. package/dist/public/assets/{requirementDiagram-MS252O5E-PrH6Wk-f.js → requirementDiagram-MS252O5E-Cu0OR6JE.js} +1 -1
  150. package/dist/public/assets/{sankeyDiagram-XADWPNL6-DuDWdyws.js → sankeyDiagram-XADWPNL6-CuBGw_FO.js} +1 -1
  151. package/dist/public/assets/{selection-context-BXIaKU4B.js → selection-context-_7ApBUWm.js} +1 -1
  152. package/dist/public/assets/{sequenceDiagram-FGHM5R23-BvF_oV_w.js → sequenceDiagram-FGHM5R23-CvdTGqtB.js} +1 -1
  153. package/dist/public/assets/share-metadata-rows-CPUEqGaU.js +1 -0
  154. package/dist/public/assets/share-receive-miss-content-CptbjUbT.js +1 -0
  155. package/dist/public/assets/skill-actions-X_rLke6F.js +1 -0
  156. package/dist/public/assets/skill-scope-CFcSL9PO.js +1 -0
  157. package/dist/public/assets/skills-api-D2ixHCpn.js +1 -0
  158. package/dist/public/assets/{src-DEzC9TbA.js → src-CbbwOucf.js} +1 -1
  159. package/dist/public/assets/{stateDiagram-FHFEXIEX-BvOoHTsD.js → stateDiagram-FHFEXIEX-CotJyv0o.js} +1 -1
  160. package/dist/public/assets/stateDiagram-v2-QKLJ7IA2-Dgzdjh4b.js +1 -0
  161. package/dist/public/assets/{target-navigation-intent-CCM8wm3X.js → target-navigation-intent-Bfuh_WMb.js} +1 -1
  162. package/dist/public/assets/{telemetry-impl-BM7BnAv2.js → telemetry-impl-Bq6GTn3R.js} +2 -2
  163. package/dist/public/assets/telemetry-startup-D90YW7_1.js +1 -0
  164. package/dist/public/assets/{timeline-definition-GMOUNBTQ-_VzX4HAF.js → timeline-definition-GMOUNBTQ-D8Me4q53.js} +1 -1
  165. package/dist/public/assets/{toggle-group-Bc5FaFo3.js → toggle-group-Duj35QHX.js} +1 -1
  166. package/dist/public/assets/tooltip-zcVXnhGV.js +1 -0
  167. package/dist/public/assets/treeView-SZITEDCU-Bhp29JF9.js +1 -0
  168. package/dist/public/assets/treemap-W4RFUUIX-_XMcXETA.js +1 -0
  169. package/dist/public/assets/{typing-burst-detector-3hSyllA2.js → typing-burst-detector-gS73Iqz3.js} +3 -3
  170. package/dist/public/assets/{vennDiagram-DHZGUBPP-BiS2w_m-.js → vennDiagram-DHZGUBPP-W-XqbYNU.js} +1 -1
  171. package/dist/public/assets/wardley-RL74JXVD-CPivDOW3.js +1 -0
  172. package/dist/public/assets/{wardleyDiagram-NUSXRM2D-BgB2gOdF.js → wardleyDiagram-NUSXRM2D-DB3DcQtI.js} +1 -1
  173. package/dist/public/assets/{xychartDiagram-5P7HB3ND-DIurDFny.js → xychartDiagram-5P7HB3ND-DxutAraW.js} +1 -1
  174. package/dist/public/index.html +68 -56
  175. package/dist/{repair-launch-json-BmK9QMNQ.mjs → repair-launch-json-Z-uZUDrj.mjs} +2 -2
  176. package/dist/{repair-mcp-configs-BDNpoQWE.mjs → repair-mcp-configs-D1udS6-V.mjs} +2 -2
  177. package/dist/repair-skills-CGLJdO86.mjs +1 -0
  178. package/dist/{repair-skills-Bu_8HPr_.mjs → repair-skills-PBaCPknU.mjs} +2 -2
  179. package/dist/server-lock-LsXsWtim-BLIrqdzC.mjs +1 -0
  180. package/dist/{server-lock-ltHt39S2-BMGVBKsW.mjs → server-lock-ltHt39S2-FrJuEUby.mjs} +39 -39
  181. package/dist/{src-DnmgOJh8.mjs → src-w1N05aF-.mjs} +2 -2
  182. package/dist/{start-S_2D11FR.mjs → start-C7JGfaJq.mjs} +2 -2
  183. package/dist/start-DIE265YH.mjs +1 -0
  184. package/dist/{write-project-skill-C02OzQla.mjs → write-project-skill-D_ylGqEf.mjs} +2 -2
  185. package/package.json +1 -1
  186. package/dist/constants-DLfnk8-s.mjs +0 -2
  187. package/dist/git-handle-D7c_AnSg-mtlScJx8.mjs +0 -1
  188. package/dist/init-DqGkmmfN.mjs +0 -1
  189. package/dist/loader-SibEgXZ1.mjs +0 -1
  190. package/dist/preview-BIIOpGNN.mjs +0 -1
  191. package/dist/public/assets/ActivityModeContent-DGWY0tgl.js +0 -2
  192. package/dist/public/assets/ConsentDialogBody-CPX75E6Q.js +0 -2
  193. package/dist/public/assets/DocumentContext-BGDV4Qfa.js +0 -34
  194. package/dist/public/assets/ManagedArtifactProperties-uPllyloX.js +0 -1
  195. package/dist/public/assets/McpConsentDialogBody-ByCv3Eox.js +0 -1
  196. package/dist/public/assets/PropertyPanel-BxwXftk5.js +0 -2
  197. package/dist/public/assets/SettingsDialogBody-DV-JvdHK.js +0 -7
  198. package/dist/public/assets/SkillEditorActions-Bs0Vh4_e.js +0 -1
  199. package/dist/public/assets/SourceEditor-BSma1xNX.js +0 -2
  200. package/dist/public/assets/architecture-YZFGNWBL-0pWnpYMK.js +0 -1
  201. package/dist/public/assets/channel-ClECMrL_.js +0 -1
  202. package/dist/public/assets/checkbox-EGJP9xna.js +0 -1
  203. package/dist/public/assets/chunk-426QAEUC-UlKin18B.js +0 -1
  204. package/dist/public/assets/chunk-55IACEB6-maKdi3q_.js +0 -1
  205. package/dist/public/assets/chunk-QZHKN3VN-DUJDGGgJ.js +0 -1
  206. package/dist/public/assets/classDiagram-6PBFFD2Q-C9zXtHUq.js +0 -1
  207. package/dist/public/assets/classDiagram-v2-HSJHXN6E-BLmW_Iw2.js +0 -1
  208. package/dist/public/assets/clone-1iKEKVKL.js +0 -1
  209. package/dist/public/assets/config-context-DhhN0rlf.js +0 -1
  210. package/dist/public/assets/config-validation-events-r0o3-Vnb.js +0 -11
  211. package/dist/public/assets/dialog-CIq9aQLf.js +0 -45
  212. package/dist/public/assets/dist-3l3ADjEo.js +0 -1
  213. package/dist/public/assets/dist-BZEgBj4N.js +0 -23
  214. package/dist/public/assets/dist-BdwnfcKi.js +0 -1
  215. package/dist/public/assets/dist-BgLh90uo2.js +0 -1
  216. package/dist/public/assets/dist-Bqo1ZTng.js +0 -1
  217. package/dist/public/assets/dist-C3ftUzLd.js +0 -1
  218. package/dist/public/assets/dist-CHEQzAl9.js +0 -1
  219. package/dist/public/assets/dist-Dtxdqotp.js +0 -1
  220. package/dist/public/assets/dist-ICp_3rWY.js +0 -1
  221. package/dist/public/assets/dist-znFZQjzE.js +0 -9
  222. package/dist/public/assets/file-tree-adapter-DosgCKNV.js +0 -1
  223. package/dist/public/assets/gitGraph-7Q5UKJZL-DNLE-2Tt.js +0 -1
  224. package/dist/public/assets/index-D3I_UcNL.js +0 -2004
  225. package/dist/public/assets/index-Now3zu6y.css +0 -1
  226. package/dist/public/assets/info-OMHHGYJF-BiaOigFV.js +0 -1
  227. package/dist/public/assets/isSymbol-BgthEULk.js +0 -1
  228. package/dist/public/assets/packet-4T2RLAQJ-v1yqEdTP.js +0 -1
  229. package/dist/public/assets/pie-ZZUOXDRM-pmbX_rAr.js +0 -1
  230. package/dist/public/assets/prop-types-CU5h6mJM.js +0 -1
  231. package/dist/public/assets/radar-PYXPWWZC-CQRfh76o.js +0 -1
  232. package/dist/public/assets/radio-group-CFPLlVag.js +0 -1
  233. package/dist/public/assets/skill-actions-UNGn_f8Z.js +0 -1
  234. package/dist/public/assets/skills-api-b3UP0fvy.js +0 -1
  235. package/dist/public/assets/stateDiagram-v2-QKLJ7IA2-B02IOISZ.js +0 -1
  236. package/dist/public/assets/telemetry-startup-Pz1ro4a2.js +0 -1
  237. package/dist/public/assets/tooltip-DiL7DBhT.js +0 -1
  238. package/dist/public/assets/treeView-SZITEDCU-iExObZ_v.js +0 -1
  239. package/dist/public/assets/treemap-W4RFUUIX-B-jRsyTq.js +0 -1
  240. package/dist/public/assets/wardley-RL74JXVD-DGsNLwY0.js +0 -1
  241. package/dist/repair-skills-DHq977uN.mjs +0 -1
  242. package/dist/server-lock-LsXsWtim-DBIg_FmA.mjs +0 -1
  243. package/dist/start-CC5yeIBq.mjs +0 -1
  244. /package/dist/public/assets/{ActivityPanelDiffView-TEHR9A38.js → ActivityPanelDiffView-BTxPvMxJ.js} +0 -0
  245. /package/dist/public/assets/{__vite-browser-external-DimdflAw.js → __vite-browser-external-B36MovhX.js} +0 -0
  246. /package/dist/public/assets/{array-CXyn2wAU.js → array-BUzQ4ozH.js} +0 -0
  247. /package/dist/public/assets/{chevron-down-CzFz_0zd.js → chevron-down-BaPMAfbX.js} +0 -0
  248. /package/dist/public/assets/{chevron-left-Bb3WBx0B.js → chevron-left-CGj9PTYZ.js} +0 -0
  249. /package/dist/public/assets/{chevron-right-jyIhGBkw.js → chevron-right-CVuQ_gVm.js} +0 -0
  250. /package/dist/public/assets/{clike-kHME1xsl.js → clike-D_SjGvvg.js} +0 -0
  251. /package/dist/public/assets/{colors-DOVRXUpv.js → colors-BGvj6s84.js} +0 -0
  252. /package/dist/public/assets/{cursor-CpjEfgnv.js → cursor-BVozWV54.js} +0 -0
  253. /package/dist/public/assets/{cytoscape.esm-DGKrBfTH.js → cytoscape.esm-btr3n05v.js} +0 -0
  254. /package/dist/public/assets/{defaultLocale-CIVmmKdD.js → defaultLocale-CSBjhTZR.js} +0 -0
  255. /package/dist/public/assets/{diff-B_7QuALZ.js → diff-BqkTpocs.js} +0 -0
  256. /package/dist/public/assets/{dist-BAzUe-Rb.js → dist-BGPDbC1a.js} +0 -0
  257. /package/dist/public/assets/{dist-ug68MPTZ.js → dist-BzWUi0nJ.js} +0 -0
  258. /package/dist/public/assets/{dist-KBKQayVB.js → dist-DQW1FoW-.js} +0 -0
  259. /package/dist/public/assets/{external-link-Bc6KvE1i.js → external-link-BKUUNWAX.js} +0 -0
  260. /package/dist/public/assets/{file-tree-rename-validation-BqGkSO9-.js → file-tree-rename-validation-DeKIxKnc.js} +0 -0
  261. /package/dist/public/assets/{format-Fsxus_sZ.js → format-CZkN23Sx.js} +0 -0
  262. /package/dist/public/assets/{go-DlHfV6Cv.js → go-WnOHx5P6.js} +0 -0
  263. /package/dist/public/assets/{init-DAmDTHXL.js → init-DJv5Kvsb.js} +0 -0
  264. /package/dist/public/assets/{input-DkQ8Zmzd.js → input-DMhjBZpj.js} +0 -0
  265. /package/dist/public/assets/{isObjectLike-0yTn5bno.js → isObjectLike-zJ40xofy.js} +0 -0
  266. /package/dist/public/assets/{katex-gTwLOSI2.js → katex-jl-BtNZi.js} +0 -0
  267. /package/dist/public/assets/{lua-Cpo6SgEb.js → lua-2OwjZGy8.js} +0 -0
  268. /package/dist/public/assets/{mcp-consent-store-Q_heVQ86.js → mcp-consent-store-GcVZt2zP.js} +0 -0
  269. /package/dist/public/assets/{min-CGFu6QbN.js → min-DIoz8hPy.js} +0 -0
  270. /package/dist/public/assets/{panzoom.es-1vRDHCmL.js → panzoom.es-hRq5wJMJ.js} +0 -0
  271. /package/dist/public/assets/{path-1iyJ-o9O.js → path-B3Eut0a4.js} +0 -0
  272. /package/dist/public/assets/{pdf-BjE4l7oX.js → pdf-Bn4xV8-w.js} +0 -0
  273. /package/dist/public/assets/{pdf.worker-CU7PVDgr.js → pdf.worker-CALBpSPV.js} +0 -0
  274. /package/dist/public/assets/{perl-uq5LpsPX.js → perl-D9Q8bKYZ.js} +0 -0
  275. /package/dist/public/assets/{properties-DuLkwqft.js → properties-DZ6bJxbX.js} +0 -0
  276. /package/dist/public/assets/{r-DcEDABBa.js → r-BZ7xig1P.js} +0 -0
  277. /package/dist/public/assets/{rough.esm-Bk-GM2I8.js → rough.esm-NnATA0En.js} +0 -0
  278. /package/dist/public/assets/{ruby-C6V5dDsD.js → ruby-B91hJOIB.js} +0 -0
  279. /package/dist/public/assets/{shell-CVvCNjui.js → shell-BjiMLAaM.js} +0 -0
  280. /package/dist/public/assets/{sql-CQQBnjZX.js → sql-sVzScOxQ.js} +0 -0
  281. /package/dist/public/assets/{src-C3imF5Zq.js → src-DQu6B2Zu.js} +0 -0
  282. /package/dist/public/assets/{startup-marks-CWTDb1CP.js → startup-marks-1TBx3O5Y.js} +0 -0
  283. /package/dist/public/assets/{stex-coA_FIxI.js → stex-DLTwoWCs.js} +0 -0
  284. /package/dist/public/assets/{swift-BBOV2SBg.js → swift-C0Ab_xUH.js} +0 -0
  285. /package/dist/public/assets/{textarea-BQFFQ9_l.js → textarea-BD5DUwDS.js} +0 -0
  286. /package/dist/public/assets/{toml-lQGk0tnp.js → toml-bNnB195d.js} +0 -0
  287. /package/dist/public/assets/{trace-api-MhJXZpsM.js → trace-api-6NqWxY5v.js} +0 -0
  288. /package/dist/public/assets/{w3c-keyname-beU76Hfb.js → w3c-keyname-F3byfno6.js} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as __require$2,n as __esmMin,o as __toCommonJS,r as __exportAll,s as __toESM$2,t as __commonJSMin$2}from"./chunk-C94x7I9S.mjs";import{$ as CONFIG_DOC_NAME_PROJECT_LOCAL,$i as projectSkillContentDocName,$n as SkillInstallRequestSchema,$r as applyPatchToFm,$t as MANAGED_ARTIFACT_PREFIX_TEMPLATE,A as ApiConfigSuccessSchema,Aa as DEFAULT_SPANS_MAX_BYTES,Ai as instantiateDoc,An as SYSTEM_DOC_NAME,Ao as safeParseAsync$1,Ar as TEMPLATE_IDENTITY_KEY,At as FrontmatterPatchSuccessSchema,B as CC1DerivedViewPayloadSchema,Ba as addConfigSpanEvent,Bi as mergeThreeWay,Bn as ServerInfoSuccessSchema,Br as TemplatesListSuccessSchema,Bt as InstalledSkillsSchema,C as AgentPatchSuccessSchema,Ca as ASSET_EXTENSIONS,Ci as fnv1aDigest,Cn as SKILL_NAME_REGEX,Co as describe$1,Cr as SyncConflictContentSuccessSchema,Ct as EmbedDetectSuccessSchema,D as AgentWriteMdSuccessSchema,Da as DEFAULT_EMBEDDINGS_BASE_URL,Di as getParseHealth,Dn as SKILL_TARGETS_REL,Do as parse$1,Dr as SyncStatusSchema,Dt as FolderConfigPutSuccessSchema,E as AgentWriteMdRequestSchema,Ea as DEFAULT_DEDUP_MODE,Ei as getHeadingSlug,En as SKILL_STATE_VERSION_RE,Eo as $ZodType,Er as SyncResolveConflictSuccessSchema,Et as FolderConfigPutRequestSchema,F as BridgeMergeContentLossError,Fa as LOCAL_DIR,Fi as isManagedArtifactDocName,Fn as SeedApplyRequestSchema,Fo as $constructor,Fr as TemplateGetSuccessSchema,Ft as HubsSuccessSchema,G as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Ga as isValidAttachmentFolderPath,Gi as parseManagedArtifactName,Gn as SharePublishRequestSchema,Gr as TrashCleanupRequestSchema,Gt as LocalOpAuthSetIdentityRequestSchema,H as CC1ServerInfoPayloadSchema,Ha as detectRemovedKeys,Hi as parseFrontmatterYaml,Hn as ShareConstructUrlResponseSchema,Hr as TestRescanBacklinksSuccessSchema,Ht as LinkGraphSuccessSchema,I as BrokenLinkSchema,Ia as OK_PROJECT_MARKER,Ii as isOrphanMode,In as SeedApplySuccessSchema,Ir as TemplateMoveRequestSchema,It as INSTALLED_SKILLS_REL,J as CC1_CONTRACT_VERSION,Ja as normalizeAttachmentFolderPath,Ji as parseTemplateFile,Jn as SkillFileDeleteSuccessSchema,Jr as UploadAssetSuccessSchema,Jt as LocalOpEmbeddingsMutationSuccessSchema,K as CC1_CHANNEL_DISK_ACK,Ka as locateIssue,Ki as parseProjectSkillBundleDoc,Kn as SharePublishResponseSchema,Kr as TrashCleanupSuccessSchema,Kt as LocalOpAuthStatusSuccessSchema,L as CC1BranchSwitchedPayloadSchema,Li as isParseEquivalentBridge,Ln as SeedListPacksSuccessSchema,Lo as require_dist$1,Lr as TemplateMoveSuccessSchema,Lt as InstallSkillRequestSchema,M as BacklinksSuccessSchema,Ma as EXECUTABLE_BLOCKLIST_EXTENSIONS,Mi as isFrontmatterValueEmpty,Mn as SaveVersionSuccessSchema,Mo as clone,Mr as TagsForNameSuccessSchema,N as BranchInfoResponseSchema,Na as INLINE_RENDERABLE_EXTENSIONS,Ni as isHiddenDocName,Nn as SearchRequestSchema,No as defineLazy,Nr as TagsListSuccessSchema,Nt as HistorySuccessSchema,O as AgentWriteRequestSchema,Oa as DEFAULT_EMBEDDINGS_MODEL,Oi as getWikiLinkText,Oo as parseAsync,Or as SyncTriggerRequestSchema,Ot as ForwardLinksSuccessSchema,P as BridgeInvariantViolationError,Pa as LINKABLE_ASSET_EXTENSIONS,Pn as SearchSuccessSchema,Po as normalizeParams,Pr as TemplateDeleteSuccessSchema,Pt as HistoryVersionSuccessSchema,Q as CONFIG_DOC_NAME_PROJECT,Qa as withConfigSpanSync,Qi as projectMergeBoundarySpace,Qn as SkillGetSuccessSchema,Qr as applyIncrementalDiff,Qt as MANAGED_ARTIFACT_PREFIX_SKILL,R as CC1ConfigIgnoreNestedErrorPayloadSchema,Ra as SANDBOXED_HTML_CSP,Ri as isValidBranchName,Rn as SeedPlanSuccessSchema,Rr as TemplatePutRequestSchema,Rt as InstallSkillSuccessSchema,S as AgentPatchRequestSchema,Sa as Fragment,Si as extractFrontmatterTags,Sn as SKILL_CONTENT_ROOT,Sr as SuggestLinksSuccessSchema,St as EDITOR_PROJECT_SKILL_ROOT,T as AgentUndoSuccessSchema,Ta as ConfigSchema$1,Ti as getAgentCanonicalDescriptors,Tn as SKILL_STATE_TARGETS,To as $ZodObject,Tr as SyncResolveConflictRequestSchema,Tt as FolderConfigGetSuccessSchema,U as CC1_CHANNEL_BRANCH_SWITCHED,Ua as humanFormat,Ui as parseGlobalSkillBundleDoc,Un as SharePublishNameCheckResponseSchema,Ur as TestRescanFilesSuccessSchema,Ut as LocalOpAuthEmptySuccessSchema,V as CC1DiskAckPayloadSchema,Va as applyPatchToDocument,Vi as normalizeBridge,Vn as ShareConstructUrlRequestSchema,Vr as TestFlushGitSuccessSchema,Vt as LINEAGE_EPOCH_KEY,W as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Wa as isKnownConfigError,Wi as parseInstalledSkills,Wn as SharePublishOwnersResponseSchema,Wr as TestResetSuccessSchema,Wt as LocalOpAuthHostRequestSchema,X as CONFIG_DOC_NAMES,Xa as validatePatchScopes,Xi as previewEmbedFence,Xn as SkillFilePutRequestSchema,Xr as WorkspaceSuccessSchema,Xt as LocalOpOkInitRequestSchema,Y as CLIENT_VERSION_HEADER,Ya as toConfigIssue,Yi as prependFrontmatter,Yn as SkillFileGetSuccessSchema,Yr as UploadRequestSchema,Yt as LocalOpEmbeddingsSetKeyRequestSchema,Z as CONFIG_DOC_NAME_OKIGNORE,Za as withConfigSpan,Zi as projectFull,Zn as SkillFilePutSuccessSchema,Zr as applyFastDiff,Zt as LocalOpOkInitResponseSchema,_ as AGENT_ICON_COLORS,_a as unwrapFrontmatterFences,_i as emitToleranceFire,_n as RenamePathRequestSchema,_o as union,_r as SkillUpdateRequestSchema,_t as DocumentReadSuccessSchema,a as acquireProcessLock,aa as resolveSkillBundleWikiTarget,ai as colorFromSeed,an as MetricsReconciliationSuccessSchema,ao as boolean,ar as SkillPutSuccessSchema,at as CreateFolderRequestSchema,b as AgentActivitySuccessSchema,ba as getSchema,bi as encodeShareUrl,bn as RollbackRequestSchema,bo as datetime,br as SpawnCursorSuccessSchema,c as isValidLockPid,ca as setToleranceTelemetryHook,ci as createBasenameIndex,cn as PARSE_EQUIVALENCE_TOLERANCE,co as intersection,cr as SkillScopeSchema,ct as CreatePageSuccessSchema,da as skillLiveDocName,di as createWorkspaceSearchCorpus,dn as PROJECT_SKILL_EDITOR_IDS,do as number,dr as SkillTargetsGetSuccessSchema,ea as readFmMap,ei as assertNeverProblemType,en as MANAGED_ARTIFACT_SCOPES,eo as ZodOptional$1,er as SkillInstallStateSuccessSchema,et as CONFIG_DOC_NAME_USER,f as readServerLock,fa as splitLeadingDocBoundary,fi as createWorkspaceSearchDocument,fn as PROTOCOL_VERSION,fo as object$1,fr as SkillTargetsPutRequestSchema,ft as DOCUMENT_OPEN_BYTE_LIMIT,ga as toWikiLinkSlug,gi as displayNameFromClientName,gn as ProblemDetailsSchema,go as string,gr as SkillUninstallSuccessSchema,gt as DocumentListSuccessSchema,h as updateProcessLockPort,ha as toBridgeInvariantLog,hi as detectFmRegion,hn as PrincipalSuccessSchema,ho as record,hr as SkillUninstallRequestSchema,ht as DeletePathSuccessSchema,ia as resolveInternalHref,in as MetricsParseHealthSuccessSchema,io as array,ir as SkillPutRequestSchema,it as ClientLogsSuccessSchema,j as BacklinkCountsSuccessSchema,ja as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,ji as isBranchNotFoundGitError,jn as SaveVersionRequestSchema,jo as prettifyError,jr as TEMPLATE_NAME_REGEX,jt as FrontmatterValueSchema,k as AgentWriteSuccessSchema,ka as DEFAULT_LOGS_MAX_BYTES,ki as iconFromClientName,kn as SUPPORTED_DOC_EXTENSIONS,ko as safeParse$1,kr as SyncTriggerSuccessSchema,kt as FrontmatterPatchRequestSchema,la as sharedExtensions,li as createCodeFenceTracker,ln as PREVIEW_EMBED_STARTERS,lo as literal,lr as SkillStateSchema,m as releaseServerLock,ma as tagsMatchingPrefix,mi as detectAppliedToleranceClasses,mn as PagesSuccessSchema,mo as preprocess,mr as SkillTargetsSchema,mt as DeletePathRequestSchema,n as RUNTIME_VERSION,na as renderInventoryFooter,ni as classifyMarkdownHref,nn as MarkdownManager,no as _null,nr as SkillMoveRequestSchema,nt as CheckoutResponseSchema,o as acquireServerLock,oa as searchWorkspaceCorpus,oi as composeTemplateFile,on as ORPHAN_MODES,oo as custom,or as SkillRestoreRequestSchema,ot as CreateFolderSuccessSchema,p as releaseProcessLock,pa as stripFrontmatter,pi as defaultScheduler,pn as PageHeadingsSuccessSchema,po as optional,pr as SkillTargetsPutSuccessSchema,pt as DeadLinksSuccessSchema,q as CC1_CHANNEL_SERVER_INFO,qa as mediaKindForSidebarAssetExtension,qi as parseSkillTargets,qn as SkillDeleteSuccessSchema,qr as UA_PATTERNS,qt as LocalOpCloneRequestSchema,ra as resolveAssetProjectPath,ri as classifyWikiLinkTarget,rn as MetricsAgentPresenceSuccessSchema,rr as SkillMoveSuccessSchema,rt as ClientLogsRequestSchema,s as isProcessAlive,sa as serializeFrontmatterMap,si as containsXmlTag,sn as OrphansSuccessSchema,so as discriminatedUnion,sr as SkillRestoreSuccessSchema,st as CreatePageRequestSchema,t as ProcessLockCollisionError,ta as reattachLeadingDocBoundary,ti as classifyGitAuthError,tn as MCP_SERVER_NAME,to as _enum,tr as SkillInstallSuccessSchema,tt as CheckoutRequestSchema,u as readProcessLock,ui as createTagInTextRegex,un as PREVIEW_THEME_TOKENS,uo as looseObject,ur as SkillTargetEditorSchema,va as validateDocName,vi as emptyInstalledSkills,vn as RenamePathSuccessSchema,vo as unknown,vr as SkillUpdateSuccessSchema,vt as DuplicatePathRequestSchema,w as AgentUndoRequestSchema,wa as CONFIG_SCHEMA_MAJOR_PATH,wi as formatFileSize,wn as SKILL_STATE_REL,wo as meta$1,wr as SyncConflictsSuccessSchema,wt as EmptyRequestSchema,x as AgentBurstDiffSuccessSchema,xa as PluginKey,xi as expandTagToHierarchy,xn as RollbackSuccessSchema,xo as toJSONSchema,xr as StreamingProblemEventSchema,xt as EDITOR_PROJECT_CONFIG_PATH,y as AdvisoryWarningSchema,ya as withFences,yi as emptySkillState,yn as RescueListSuccessSchema,yr as SkillsListSuccessSchema,yt as DuplicatePathSuccessSchema,z as CC1ConfigValidationRejectedPayloadSchema,za as SANDBOXED_HTML_EXTENSIONS,zi as managedArtifactDocNameFromContentTarget,zn as SemanticIndexStatusSchema,zr as TemplatePutSuccessSchema,zt as InstalledAgentsSuccessSchema}from"./server-lock-ltHt39S2-BMGVBKsW.mjs";import{a as metrics,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-BQ4-CT8p.mjs";import{a as simpleGit,i as esm_default,n as createGitInstance,o as require_src$15,r as withParentLock,t as applyGitEnv}from"./git-handle-BM0b1rwW-DuV-KO4L.mjs";import{t as createPatch}from"./libesm-_Wi8iuGI.mjs";import{n as mimes,t as build_default}from"./build-CCNlCFyu.mjs";import{t as require_yazl}from"./yazl-DgCFuIuD.mjs";import{t as b1}from"./chunk-YNYSPYQ5-DHter9G3.mjs";import{a as c,c as h,d as m,f as p,h as x,i as b,l as i,m as v,n as C,o as d,p as u,r as a,s as f,t as $$1,u as l}from"./chunk-GFQRA5P5-DigWkxW2.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-D6YUa1Xl.mjs";import{a as d$1,c as m$1,d as y,i as c$1,l as p$1,n as N,o as f$1,r as P$1,s as h$1,t as $$2,u as v$1}from"./chunk-XHM67O4N-2lBQUjKO.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-XKIhMSUi.mjs";import{r as o$1}from"./chunk-CWQS3NFK-DNm_iIwd.mjs";import"./chunk-DXB73IDG-Bx-Ikbnu.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-_0tQyQsf.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-Kbs3GRxW.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-LGuZyK6R.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-BoP5OA93.mjs";import{n as n$1}from"./chunk-3THT3N7L-CBWmNncQ.mjs";import{t as n$2}from"./chunk-44UOCSGV-B6GSHp1s.mjs";import{t as import_websocket_server$1}from"./wrapper-CGw3ogaz.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import{basename,delimiter,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{homedir,hostname,platform,tmpdir}from"node:os";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,readlinkSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,symlinkSync,unlinkSync,writeFileSync}from"node:fs";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,lstat,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import Crypto from"crypto";import crypto$1,{createHash,randomUUID as randomUUID$1,webcrypto as webcrypto$1}from"node:crypto";import*as zlib from"zlib";import{Readable as Readable$1}from"stream";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{promisify}from"node:util";import{Http2ServerRequest,constants as constants$2}from"http2";import{AsyncLocalStorage}from"node:async_hooks";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let s=relative(e,t);return s===``||s===`.`||s.startsWith(`..`)||isAbsolute(s)?``:s}function findAncestorGitEntry(e){let t=homedir(),s=resolve(e),g=64;for(let e=0;e<64;e++){if(s===t)return null;let e=dirname(s);if(e===s||e===t)return null;let g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${t??`unknown`}); skipping ancestor`)}s=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),s=classifyGitEntry(resolve(t,`.git`),t,t);if(s.kind!==`absent`)return s;let g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),s=64;if(t.length<=64)return t||`sub`;let g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}function djb2(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33+e.charCodeAt(s)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,s){let g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. Run \`git worktree prune\` from the source repo and try again.`,s),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let s=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${s}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let s of e.split(`
1
+ import{a as __require$2,n as __esmMin,o as __toCommonJS,r as __exportAll,s as __toESM$2,t as __commonJSMin$2}from"./chunk-C94x7I9S.mjs";import{$ as CONFIG_DOC_NAME_PROJECT_LOCAL,$a as withConfigSpan,$i as projectFull,$n as SkillFilePutSuccessSchema,$r as applyFastDiff,$t as MANAGED_ARTIFACT_PREFIX_TEMPLATE,A as ApiConfigSuccessSchema,Aa as DEFAULT_EMBEDDINGS_MODEL,Ai as getWikiLinkText,An as SYSTEM_DOC_NAME,Ao as parseAsync,Ar as SyncTriggerRequestSchema,At as FrontmatterPatchSuccessSchema,B as CC1DerivedViewPayloadSchema,Ba as SANDBOXED_HTML_CSP,Bi as isValidBranchName,Bn as ServerInfoSuccessSchema,Br as TemplatePutRequestSchema,Bt as InstalledSkillsSchema,C as AgentPatchSuccessSchema,Ca as PluginKey,Ci as expandTagToHierarchy,Cn as SKILL_NAME_REGEX,Co as toJSONSchema,Cr as StreamingProblemEventSchema,Ct as EmbedDetectSuccessSchema,D as AgentWriteMdSuccessSchema,Da as ConfigSchema$1,Di as getAgentCanonicalDescriptors,Dn as SKILL_TARGETS_REL,Do as $ZodObject,Dr as SyncResolveConflictRequestSchema,Dt as FolderConfigPutSuccessSchema,E as AgentWriteMdRequestSchema,Ea as CONFIG_SCHEMA_MAJOR_PATH,Ei as formatFileSize,En as SKILL_STATE_VERSION_RE,Eo as meta$1,Er as SyncConflictsSuccessSchema,Et as FolderConfigPutRequestSchema,F as BridgeMergeContentLossError,Fa as INLINE_RENDERABLE_EXTENSIONS,Fi as isHiddenDocName,Fn as SeedApplyRequestSchema,Fo as defineLazy,Fr as TagsListSuccessSchema,Ft as HubsSuccessSchema,G as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Ga as humanFormat,Gi as parseGlobalSkillBundleDoc,Gn as SharePublishRequestSchema,Gr as TestRescanFilesSuccessSchema,Gt as LocalOpAuthSetIdentityRequestSchema,H as CC1ServerInfoPayloadSchema,Ha as addConfigSpanEvent,Hi as mergeThreeWay,Hn as ShareConstructUrlResponseSchema,Hr as TemplatesListSuccessSchema,Ht as LinkGraphSuccessSchema,I as BrokenLinkSchema,Ia as LINKABLE_ASSET_EXTENSIONS,In as SeedApplySuccessSchema,Io as normalizeParams,Ir as TemplateDeleteSuccessSchema,It as INSTALLED_SKILLS_REL,J as CC1_CONTRACT_VERSION,Ja as locateIssue,Ji as parseProjectSkillBundleDoc,Jn as ShareTargetStatusResponseSchema,Jr as TrashCleanupSuccessSchema,Jt as LocalOpEmbeddingsMutationSuccessSchema,K as CC1_CHANNEL_DISK_ACK,Ka as isKnownConfigError,Ki as parseInstalledSkills,Kn as SharePublishResponseSchema,Kr as TestResetSuccessSchema,Kt as LocalOpAuthStatusSuccessSchema,L as CC1BranchSwitchedPayloadSchema,La as LOCAL_DIR,Li as isManagedArtifactDocName,Ln as SeedListPacksSuccessSchema,Lo as $constructor,Lr as TemplateGetSuccessSchema,Lt as InstallSkillRequestSchema,M as BacklinksSuccessSchema,Ma as DEFAULT_SPANS_MAX_BYTES,Mi as instantiateDoc,Mn as SaveVersionSuccessSchema,Mo as safeParseAsync$1,Mr as TEMPLATE_IDENTITY_KEY,N as BranchInfoResponseSchema,Na as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,Ni as isBranchNotFoundGitError,Nn as SearchRequestSchema,No as prettifyError,Nr as TEMPLATE_NAME_REGEX,Nt as HistorySuccessSchema,O as AgentWriteRequestSchema,Oa as DEFAULT_DEDUP_MODE,Oi as getHeadingSlug,Oo as $ZodType,Or as SyncResolveConflictSuccessSchema,Ot as ForwardLinksSuccessSchema,P as BridgeInvariantViolationError,Pa as EXECUTABLE_BLOCKLIST_EXTENSIONS,Pi as isFrontmatterValueEmpty,Pn as SearchSuccessSchema,Po as clone,Pr as TagsForNameSuccessSchema,Pt as HistoryVersionSuccessSchema,Q as CONFIG_DOC_NAME_PROJECT,Qa as validatePatchScopes,Qi as previewEmbedFence,Qn as SkillFilePutRequestSchema,Qr as WorkspaceSuccessSchema,Qt as MANAGED_ARTIFACT_PREFIX_SKILL,R as CC1ConfigIgnoreNestedErrorPayloadSchema,Ra as OK_PROJECT_MARKER,Ri as isOrphanMode,Rn as SeedPlanSuccessSchema,Rr as TemplateMoveRequestSchema,Rt as InstallSkillSuccessSchema,S as AgentPatchRequestSchema,Sa as getSchema,Si as encodeShareUrl,Sn as SKILL_CONTENT_ROOT,So as datetime,Sr as SpawnCursorSuccessSchema,St as EDITOR_PROJECT_SKILL_ROOT,T as AgentUndoSuccessSchema,Ta as ASSET_EXTENSIONS,Ti as fnv1aDigest,Tn as SKILL_STATE_TARGETS,To as describe$1,Tr as SyncConflictContentSuccessSchema,Tt as FolderConfigGetSuccessSchema,U as CC1_CHANNEL_BRANCH_SWITCHED,Ua as applyPatchToDocument,Ui as normalizeBridge,Un as SharePublishNameCheckResponseSchema,Ur as TestFlushGitSuccessSchema,Ut as LocalOpAuthEmptySuccessSchema,V as CC1DiskAckPayloadSchema,Va as SANDBOXED_HTML_EXTENSIONS,Vi as managedArtifactDocNameFromContentTarget,Vn as ShareConstructUrlRequestSchema,Vr as TemplatePutSuccessSchema,Vt as LINEAGE_EPOCH_KEY,W as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Wa as detectRemovedKeys,Wi as parseFrontmatterYaml,Wn as SharePublishOwnersResponseSchema,Wr as TestRescanBacklinksSuccessSchema,Wt as LocalOpAuthHostRequestSchema,X as CONFIG_DOC_NAMES,Xa as normalizeAttachmentFolderPath,Xi as parseTemplateFile,Xn as SkillFileDeleteSuccessSchema,Xr as UploadAssetSuccessSchema,Xt as LocalOpOkInitRequestSchema,Y as CLIENT_VERSION_HEADER,Ya as mediaKindForSidebarAssetExtension,Yi as parseSkillTargets,Yn as SkillDeleteSuccessSchema,Yr as UA_PATTERNS,Yt as LocalOpEmbeddingsSetKeyRequestSchema,Z as CONFIG_DOC_NAME_OKIGNORE,Za as toConfigIssue,Zi as prependFrontmatter,Zn as SkillFileGetSuccessSchema,Zr as UploadRequestSchema,Zt as LocalOpOkInitResponseSchema,_ as AGENT_ICON_COLORS,_a as toBridgeInvariantLog,_i as detectFmRegion,_n as RenamePathRequestSchema,_o as record,_r as SkillUninstallRequestSchema,_t as DocumentReadSuccessSchema,a as acquireProcessLock,aa as resolveAssetProjectPath,ai as classifyWikiLinkTarget,an as MetricsReconciliationSuccessSchema,ar as SkillMoveSuccessSchema,at as CreateFolderRequestSchema,b as AgentActivitySuccessSchema,ba as validateDocName,bi as emptyInstalledSkills,bn as RollbackRequestSchema,bo as unknown,br as SkillUpdateSuccessSchema,c as isValidLockPid,ca as searchWorkspaceCorpus,ci as composeTemplateFile,cn as PARSE_EQUIVALENCE_TOLERANCE,co as custom,cr as SkillRestoreRequestSchema,ct as CreatePageSuccessSchema,da as sharedExtensions,di as createCodeFenceTracker,dn as PROJECT_SKILL_EDITOR_IDS,do as literal,dr as SkillStateSchema,ea as projectMergeBoundarySpace,ei as applyIncrementalDiff,en as MANAGED_ARTIFACT_SCOPES,eo as withConfigSpanSync,er as SkillGetSuccessSchema,et as CONFIG_DOC_NAME_USER,f as readServerLock,fi as createTagInTextRegex,fn as PROTOCOL_VERSION,fo as looseObject,fr as SkillTargetEditorSchema,ft as DOCUMENT_OPEN_BYTE_LIMIT,ga as tagsMatchingPrefix,gi as detectAppliedToleranceClasses,gn as ProblemDetailsSchema,go as preprocess,gr as SkillTargetsSchema,gt as DocumentListSuccessSchema,h as updateProcessLockPort,ha as stripFrontmatter,hi as defaultScheduler,hn as PrincipalSuccessSchema,ho as optional,hr as SkillTargetsPutSuccessSchema,ht as DeletePathSuccessSchema,ia as renderInventoryFooter,ii as classifyMarkdownHref,in as MetricsParseHealthSuccessSchema,io as _null,ir as SkillMoveRequestSchema,it as ClientLogsSuccessSchema,j as BacklinkCountsSuccessSchema,ja as DEFAULT_LOGS_MAX_BYTES,ji as iconFromClientName,jn as SaveVersionRequestSchema,jo as safeParse$1,jr as SyncTriggerSuccessSchema,jt as FrontmatterValueSchema,k as AgentWriteSuccessSchema,ka as DEFAULT_EMBEDDINGS_BASE_URL,ki as getParseHealth,kn as SUPPORTED_DOC_EXTENSIONS,ko as parse$1,kr as SyncStatusSchema,kt as FrontmatterPatchRequestSchema,la as serializeFrontmatterMap,li as containsXmlTag,ln as PREVIEW_EMBED_STARTERS,lo as discriminatedUnion,lr as SkillRestoreSuccessSchema,m as releaseServerLock,ma as splitLeadingDocBoundary,mi as createWorkspaceSearchDocument,mn as PagesSuccessSchema,mo as object$1,mr as SkillTargetsPutRequestSchema,mt as DeletePathRequestSchema,n as RUNTIME_VERSION,na as readFmMap,ni as assertNeverProblemType,nn as MarkdownManager,no as ZodOptional$1,nr as SkillInstallStateSuccessSchema,nt as CheckoutResponseSchema,o as acquireServerLock,oa as resolveInternalHref,on as ORPHAN_MODES,oo as array,or as SkillPutRequestSchema,ot as CreateFolderSuccessSchema,p as releaseProcessLock,pa as skillLiveDocName,pi as createWorkspaceSearchCorpus,pn as PageHeadingsSuccessSchema,po as number,pr as SkillTargetsGetSuccessSchema,pt as DeadLinksSuccessSchema,q as CC1_CHANNEL_SERVER_INFO,qa as isValidAttachmentFolderPath,qi as parseManagedArtifactName,qn as ShareTargetStatusRequestSchema,qr as TrashCleanupRequestSchema,qt as LocalOpCloneRequestSchema,ra as reattachLeadingDocBoundary,ri as classifyGitAuthError,rn as MetricsAgentPresenceSuccessSchema,ro as _enum,rr as SkillInstallSuccessSchema,rt as ClientLogsRequestSchema,s as isProcessAlive,sa as resolveSkillBundleWikiTarget,si as colorFromSeed,sn as OrphansSuccessSchema,so as boolean,sr as SkillPutSuccessSchema,st as CreatePageRequestSchema,t as ProcessLockCollisionError,ta as projectSkillContentDocName,ti as applyPatchToFm,tn as MCP_SERVER_NAME,tr as SkillInstallRequestSchema,tt as CheckoutRequestSchema,u as readProcessLock,ua as setToleranceTelemetryHook,ui as createBasenameIndex,un as PREVIEW_THEME_TOKENS,uo as intersection,ur as SkillScopeSchema,va as toWikiLinkSlug,vi as displayNameFromClientName,vn as RenamePathSuccessSchema,vo as string,vr as SkillUninstallSuccessSchema,vt as DuplicatePathRequestSchema,w as AgentUndoRequestSchema,wa as Fragment,wi as extractFrontmatterTags,wn as SKILL_STATE_REL,wr as SuggestLinksSuccessSchema,wt as EmptyRequestSchema,x as AgentBurstDiffSuccessSchema,xa as withFences,xi as emptySkillState,xn as RollbackSuccessSchema,xr as SkillsListSuccessSchema,xt as EDITOR_PROJECT_CONFIG_PATH,y as AdvisoryWarningSchema,ya as unwrapFrontmatterFences,yi as emitToleranceFire,yn as RescueListSuccessSchema,yo as union,yr as SkillUpdateRequestSchema,yt as DuplicatePathSuccessSchema,z as CC1ConfigValidationRejectedPayloadSchema,zi as isParseEquivalentBridge,zn as SemanticIndexStatusSchema,zo as require_dist$1,zr as TemplateMoveSuccessSchema,zt as InstalledAgentsSuccessSchema}from"./server-lock-ltHt39S2-FrJuEUby.mjs";import{a as metrics,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-BQ4-CT8p.mjs";import{a as simpleGit,i as esm_default,n as createGitInstance,o as require_src$15,r as withParentLock,t as applyGitEnv}from"./git-handle-B4hCEi7c-CXOP12Ds.mjs";import{t as createPatch}from"./libesm-_Wi8iuGI.mjs";import{n as mimes,t as build_default}from"./build-CCNlCFyu.mjs";import{t as require_yazl}from"./yazl-DgCFuIuD.mjs";import{t as b1}from"./chunk-YNYSPYQ5-DHter9G3.mjs";import{a as c,c as h,d as m,f as p,h as x,i as b,l as i,m as v,n as C,o as d,p as u,r as a,s as f,t as $$1,u as l}from"./chunk-GFQRA5P5-DigWkxW2.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-D6YUa1Xl.mjs";import{a as d$1,c as m$1,d as y,i as c$1,l as p$1,n as N,o as f$1,r as P$1,s as h$1,t as $$2,u as v$1}from"./chunk-XHM67O4N-2lBQUjKO.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-XKIhMSUi.mjs";import{r as o$1}from"./chunk-CWQS3NFK-DNm_iIwd.mjs";import"./chunk-DXB73IDG-Bx-Ikbnu.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-_0tQyQsf.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-Kbs3GRxW.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-LGuZyK6R.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-BoP5OA93.mjs";import{n as n$1}from"./chunk-3THT3N7L-CBWmNncQ.mjs";import{t as n$2}from"./chunk-44UOCSGV-B6GSHp1s.mjs";import{t as import_websocket_server$1}from"./wrapper-CGw3ogaz.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import{basename,delimiter,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{homedir,hostname,platform,tmpdir}from"node:os";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,readlinkSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,symlinkSync,unlinkSync,writeFileSync}from"node:fs";import{Transform,Writable}from"node:stream";import{access,constants as constants$1,lstat,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import Crypto from"crypto";import crypto$1,{createHash,randomUUID as randomUUID$1,webcrypto as webcrypto$1}from"node:crypto";import*as zlib from"zlib";import{Readable as Readable$1}from"stream";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{promisify}from"node:util";import{Http2ServerRequest,constants as constants$2}from"http2";import{AsyncLocalStorage}from"node:async_hooks";import{lookup}from"node:dns";import{createServer}from"node:http";const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,s){let g;try{g=statSync(e)}catch(t){let s=t.code;return s===`ENOENT`||s===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let S=computeProjectSubPath(t,s);if(g.isDirectory())return{kind:`directory`,path:e,projectSubPath:S};if(g.isFile()){let s;try{s=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let g=s.match(/^gitdir:\s*(.+)$/);return g?{kind:`linked`,path:resolve(t,g[1]),gitPath:e,projectSubPath:S}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let s=relative(e,t);return s===``||s===`.`||s.startsWith(`..`)||isAbsolute(s)?``:s}function findAncestorGitEntry(e){let t=homedir(),s=resolve(e),g=64;for(let e=0;e<64;e++){if(s===t)return null;let e=dirname(s);if(e===s||e===t)return null;let g=resolve(e,`.git`);try{let t=statSync(g);if(t.isDirectory()||t.isFile())return{gitPath:g,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${g} (${t??`unknown`}); skipping ancestor`)}s=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),s=classifyGitEntry(resolve(t,`.git`),t,t);if(s.kind!==`absent`)return s;let g=findAncestorGitEntry(t);return g===null?{kind:`absent`}:classifyGitEntry(g.gitPath,g.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),s=64;if(t.length<=64)return t||`sub`;let g=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${g}`}function djb2(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33+e.charCodeAt(s)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,s){let g=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${g}. Run \`git worktree prune\` from the source repo and try again.`,s),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let s=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${s}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let s of e.split(`
2
2
  `)){let e=s.trim();if(e.startsWith(OK_CONTRIBUTORS_PREFIX))try{let s=JSON.parse(e.slice(17));if(typeof s==`object`&&s&&`id`in s&&typeof s.id==`string`&&`name`in s&&typeof s.name==`string`&&`docs`in s&&Array.isArray(s.docs)&&s.docs.every(e=>typeof e==`string`)&&(!(`colorSeed`in s)||typeof s.colorSeed==`string`)){let e=s;if(`summaries`in e){let t=e.summaries;(!Array.isArray(t)||!t.every(e=>typeof e==`string`))&&delete e.summaries}t.push(s)}}catch{}}return t}const OK_CHECKPOINT_PREFIX=`ok-checkpoint-v1: `;function parseCheckpoint(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(OK_CHECKPOINT_PREFIX))continue;let s;try{s=JSON.parse(e.slice(18))}catch{return null}if(typeof s!=`object`||!s)return null;let g=s,S=g.kind,w=g.metadata;if(typeof w!=`object`||!w)return null;let E=typeof g.docName==`string`?g.docName:null,D=typeof g.size==`number`&&Number.isFinite(g.size)?g.size:null;if(S===`bridge-merge-loss`){let e=w;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:E,size:D,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(S===`external-change-rescue`){let e=w;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:E,size:D,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}if(S===`auto-consolidation`){let e=w;return typeof e.foldedRefs==`number`&&Number.isFinite(e.foldedRefs)&&typeof e.trigger==`string`?{kind:`auto-consolidation`,docName:E,size:D,metadata:{foldedRefs:e.foldedRefs,trigger:e.trigger}}:null}return null}return null}function formatCheckpointBodyLine(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${OK_CHECKPOINT_PREFIX}${JSON.stringify(t)}`}const OK_ACTOR_PREFIX=`ok-actor: `;function formatOkActor(e){let{summaries:t,previous_paths:s,...g}=e,S={...g};return t&&t.length>0&&(S.summaries=t),s&&s.length>0&&(S.previous_paths=s),`${OK_ACTOR_PREFIX}${JSON.stringify(S)}`}function parseOkActorObject(e){if(e.v!==1||!(`display_name`in e)||typeof e.display_name!=`string`||!(`docs`in e)||!Array.isArray(e.docs))return null;let t=typeof e.principal==`string`?e.principal:null,s=typeof e.agent_session==`string`?e.agent_session:null,g;if(typeof e.writer_id==`string`&&e.writer_id.length>0)g=e.writer_id;else if(s)g=`agent-${s}`;else if(t)g=t;else switch(e.display_name){case`File System`:g=`file-system`;break;case`Git (upstream)`:g=`git-upstream`;break;default:g=`openknowledge-service`}let S=`summaries`in e&&Array.isArray(e.summaries)&&e.summaries.every(e=>typeof e==`string`)?e.summaries:void 0,w=parsePreviousPaths(e);return{v:1,writer_id:g,principal:t,agent_session:s,agent_type:typeof e.agent_type==`string`?e.agent_type:null,client_name:typeof e.client_name==`string`?e.client_name:null,client_version:typeof e.client_version==`string`?e.client_version:null,label:typeof e.label==`string`?e.label:null,display_name:e.display_name,color_seed:typeof e.color_seed==`string`?e.color_seed:`unknown`,docs:e.docs.filter(e=>typeof e==`string`),...S&&S.length>0?{summaries:S}:{},...w&&w.length>0?{previous_paths:w}:{}}}function parsePreviousPaths(e){if(!(`previous_paths`in e)||!Array.isArray(e.previous_paths))return;let t=[];for(let s of e.previous_paths){if(typeof s!=`object`||!s)continue;let e=s;typeof e.from!=`string`||typeof e.to!=`string`||t.push({from:e.from,to:e.to})}return t}function parseOkActor(e){if(!e)return null;for(let t of e.split(`
4
4
  `)){let e=t.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let s;try{s=JSON.parse(e.slice(10))}catch{return null}return typeof s!=`object`||!s?null:parseOkActorObject(s)}return null}function parseOkActors(e){if(!e)return[];let t=[];for(let s of e.split(`
@@ -825,8 +825,9 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
825
825
  `),g=e=>e.endsWith(`\r`)?e.slice(0,-1):e,S=0;for(;S<s.length;){let e=g(s[S]??``),w=e.match(/^ {0,3}(`{3,}|~{3,})[ \t]*([^\s`]*)/);if(!w){S++;continue}let E=w[1]??``,D=E[0]??"`";if(D==="`"&&e.slice(e.indexOf(E)+E.length).includes("`")){S++;continue}let O=w[2]??``,k=RegExp(`^ {0,3}\\${D}{${E.length},}[ \t]*$`),j=[],F=S+1;for(;F<s.length&&!k.test(g(s[F]??``));)j.push(s[F]??``),F++;if(O===`mermaid`){let e=j.join(`
826
826
  `),s=(j.find(e=>e.trim().length>0)?.trim()??``).slice(0,MAX_FIRST_LINE_CHARS);t.push({firstLine:s,body:e})}S=F+1}return t}async function initMermaid(){let{Window:e}=await import(`./lib-CCQO9uWA.mjs`),t=new e({url:`http://localhost/`}),s={window:t,document:t.document,navigator:t.navigator,location:t.location,DOMParser:t.DOMParser,Element:t.Element,Node:t.Node,SVGElement:t.SVGElement,HTMLElement:t.HTMLElement,MutationObserver:t.MutationObserver},g=new Map;try{for(let[e,t]of Object.entries(s))g.set(e,Object.getOwnPropertyDescriptor(globalThis,e)),Object.defineProperty(globalThis,e,{value:t,configurable:!0,writable:!0});let e=(await import(`./mermaid.core-LrO0u_wA.mjs`)).default;return e.initialize({startOnLoad:!1,securityLevel:`strict`,suppressErrorRendering:!0}),await e.parse(`graph LR
827
827
  A-->B`),e}finally{for(let[e,t]of g)t?Object.defineProperty(globalThis,e,t):delete globalThis[e]}}function getMermaid(e){return initPromise??=initMermaid().catch(t=>(log$10.warn({err:t,"doc.name":e},`mermaid validator unavailable — render validation disabled for this process`),null)),initPromise}function extractLineNumber(e){let t=e.match(/Parse error on line (\d+)/);if(!t?.[1])return;let s=Number(t[1]);return Number.isSafeInteger(s)&&s>0?s:void 0}async function validateMermaidFences(e,t){try{if(!e.includes(`mermaid`))return;let{body:s}=detectFmRegion(e),g=extractMermaidFences(s);if(g.length===0)return;let S=performance.now(),w=await getMermaid(t);if(w===null)return;let E=performance.now(),D=[],O=0;for(let e=0;e<g.length&&D.length<MAX_WARNINGS&&!(O>=MAX_FENCES_PARSED);e++){if(performance.now()-E>TOTAL_PARSE_BUDGET_MS){log$10.debug({"doc.name":t,skippedFrom:e+1,fences:g.length},`mermaid validation budget exceeded — remaining fences skipped`);break}let s=g[e];if(s!==void 0){if(s.body.length>MAX_FENCE_BYTES||s.body.split(`
828
- `).length>MAX_FENCE_LINES){log$10.debug({"doc.name":t,fenceIndex:e+1},`mermaid fence over validation caps — skipped`);continue}try{O++,await w.parse(s.body)}catch(g){if(g instanceof TypeError){log$10.debug({err:g,"doc.name":t,fenceIndex:e+1},`mermaid validation skipped fence — environment failure`);continue}let S=g instanceof Error?g.message:String(g),w=S.slice(0,MAX_MESSAGE_CHARS),E=extractLineNumber(S);D.push({kind:`mermaid-parse-error`,fenceIndex:e+1,fenceFirstLine:s.firstLine,message:w,...E===void 0?{}:{line:E}})}}}let k=Math.round(performance.now()-S);if(D.length===0){k>250&&log$10.debug({"doc.name":t,durationMs:k,fences:g.length},`mermaid validation slow (no warnings)`);return}return log$10.debug({"doc.name":t,count:D.length,durationMs:k},`mermaid render warnings emitted`),D}catch(e){log$10.warn({err:e,"doc.name":t},`mermaid validation errored unexpectedly — skipped`);return}}const PANE_TARGET_FILE=`pane-target.json`,PANE_TARGET_TTL_MS=3e4;function armPaneTarget(e,t,s=Date.now()){if(!t.startsWith(`#/`))return!1;tracedMkdirSync(e,{recursive:!0});let g={route:t,armedAtMs:s};return tracedWriteFileSync(resolve(e,PANE_TARGET_FILE),JSON.stringify(g)),!0}function readArmedPaneTarget(e,t=Date.now(),s=PANE_TARGET_TTL_MS){let g=resolve(e,PANE_TARGET_FILE);if(!existsSync(g))return null;try{let e=JSON.parse(readFileSync(g,`utf-8`));return typeof e.route!=`string`||typeof e.armedAtMs!=`number`||t-e.armedAtMs>s?null:e.route}catch(e){let t=e.code;return(t===`EACCES`||t===`EPERM`||t===`EIO`)&&process.stderr.write(`[pane-target] readArmedPaneTarget failed at ${g}: ${e instanceof Error?e.message:String(e)}\n`),null}}function clearArmedPaneTarget(e){let t=resolve(e,PANE_TARGET_FILE);if(existsSync(t))try{tracedUnlinkSync(t)}catch{}}const SHARE_BASE_URL=`https://openknowledge.ai/d/`,SHARE_CONSTRUCT_URL_HANDLER_TAG=`share-construct-url`;function isValidSharePath(e,t){if(e===``)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function buildGitHubBlobUrl(e,t,s,g){return`https://github.com/${e}/${t}/blob/${encodeURIComponent(s)}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function buildGitHubTreeUrl(e,t,s,g){let S=`https://github.com/${e}/${t}/tree/${encodeURIComponent(s)}`;return g===``?S:`${S}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function emitShareConstructUrlLog(e,t){let s=t?.branchExists,g=t?.kind;getLogger(`share`).info({action:`construct-url`,result:e,...s===void 0?{}:{branchExists:s},...g===void 0?{}:{kind:g}},`share action`)}function resolveGitDir$1(e){let t=resolve(e,`.git`);if(!existsSync(t))return null;let s;try{s=statSync(t)}catch{return null}if(s.isDirectory())return t;if(s.isFile()){let s;try{s=readFileSync(t,`utf-8`)}catch{return null}let g=/^gitdir:\s*(.+)$/m.exec(s.trim());if(!g)return null;let S=g[1].trim(),w=isAbsolute(S)?S:resolve(e,S);return existsSync(w)?w:null}return null}function resolveCommonDir(e){let t=join(e,`commondir`);if(!existsSync(t))return e;let s;try{s=readFileSync(t,`utf-8`).trim()}catch{return e}return s.length===0?e:isAbsolute(s)?s:resolve(e,s)}function readGitHeadBranch(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(t,`HEAD`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=/^ref:\s*refs\/heads\/(.+)$/.exec(g.trim());return S?S[1]:null}function stripCommentAndTrim(e){let t=e.indexOf(`#`),s=e.indexOf(`;`),g=-1;return t>=0&&s>=0?g=Math.min(t,s):t>=0?g=t:s>=0&&(g=s),(g===-1?e:e.slice(0,g)).trim()}function extractOriginUrl(e){let t=!1;for(let s of e.split(/\r?\n/)){let e=stripCommentAndTrim(s);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let g=/^url\s*=\s*(.+)$/.exec(e);if(!g)continue;let S=g[1].trim();if((S.startsWith(`"`)&&S.endsWith(`"`)||S.startsWith(`'`)&&S.endsWith(`'`))&&(S=S.slice(1,-1)),S.length>0)return S}return null}function parseGitHubOriginUrl(e){let t=e.trim();if(!t)return null;let s=/^https?:\/\/(?:www\.)?github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return s||(s=/^ssh:\/\/(?:[\w.-]+@)?github\.com(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)||(s=/^[\w.-]+@github\.com:([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),s)||(s=/^git:\/\/github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)?{owner:s[1],repo:s[2]}:null}function readParsedOrigin(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(resolveCommonDir(t),`config`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=extractOriginUrl(g);return S?{originUrl:S,github:parseGitHubOriginUrl(S)}:null}function readOriginGitHubRepo(e){let t=readParsedOrigin(e);return t?t.github?{kind:`ok`,owner:t.github.owner,repo:t.github.repo}:{kind:`non-github`}:{kind:`no-remote`}}function readSyncRemoteInfo(e){let t=readParsedOrigin(e);return t?t.github?{label:`${t.github.owner}/${t.github.repo}`,webUrl:`https://github.com/${t.github.owner}/${t.github.repo}`}:{label:labelFromNonGitHubUrl(t.originUrl),webUrl:null}:null}function labelFromNonGitHubUrl(e){let t=e.trim().replace(/\.git$/,``),s=/^[\w.-]+@([^:/]+):(.+)$/.exec(t);if(s)return`${s[1]}/${s[2]}`;let g=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)*(.+)$/i.exec(t);return g?g[1]:t}function branchExistsOnOrigin(e,t){let s=resolveGitDir$1(e);if(!s)return!1;let g=resolveCommonDir(s);if(existsSync(join(g,`refs`,`remotes`,`origin`,t)))return!0;let S=join(g,`packed-refs`);if(!existsSync(S))return!1;let w;try{w=readFileSync(S,`utf-8`)}catch{return!1}let E=`refs/remotes/origin/${t}`;for(let e of w.split(/\r?\n/)){let t=e.trim();if(t.length===0||t.startsWith(`#`)||t.startsWith(`^`))continue;let s=t.split(/\s+/);if(s.length===2&&s[1]===E)return!0}return!1}const SHARE_PUBLISH_OWNERS_HANDLER_TAG=`share-publish-owners`,SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG=`share-publish-name-check`,SHARE_PUBLISH_HANDLER_TAG=`share-publish`,SHARE_PUBLISH_OWNERS_KEY=`/api/share/publish/owners`,SHARE_PUBLISH_NAME_CHECK_KEY=`/api/share/publish/name-check`,SHARE_PUBLISH_KEY=`/api/share/publish`,SHARE_PUBLISH_TIMEOUT_MS=3e4;function isValidShareRepoName(e){return e.length===0||e.length>100||e.startsWith(`.`)||e.startsWith(`-`)||/^-+$/.test(e)?!1:/^[A-Za-z0-9._-]+$/.test(e)}function isValidShareOwnerName(e){return e.length===0||e.length>39||e.startsWith(`-`)||e.endsWith(`-`)?!1:/^[A-Za-z0-9-]+$/.test(e)}function pickTerminalJsonLine(e){let t=e.split(`
829
- `).map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e--)try{let s=JSON.parse(t[e]);if(s&&typeof s==`object`&&!Array.isArray(s))return s}catch{}return null}function parseOwnersEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`owners`&&Array.isArray(e.owners)){let t=[];for(let s of e.owners){if(!s||typeof s!=`object`)continue;let e=s,g=typeof e.login==`string`?e.login:null,S=e.kind===`user`||e.kind===`org`?e.kind:null;if(g===null||S===null)continue;let w=typeof e.avatarUrl==`string`?e.avatarUrl:void 0;t.push({login:g,kind:S,...w?{avatarUrl:w}:{}})}return{ok:!0,owners:t}}return e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function isOwnersErrorCode(e){return e===`auth-required`||e===`network`}function parseNameCheckEvent(e){return e===null?{ok:!1,error:`network`}:e.type===`name-check`&&typeof e.available==`boolean`?{ok:!0,available:e.available}:e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}const PUBLISH_ERROR_CODES=new Set([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]);function isPublishErrorCode(e){return typeof e==`string`&&PUBLISH_ERROR_CODES.has(e)}function parsePublishEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`publish`){let t=typeof e.ownerLogin==`string`?e.ownerLogin:null,s=typeof e.repoName==`string`?e.repoName:null,g=typeof e.cloneUrl==`string`?e.cloneUrl:null,S=typeof e.defaultBranch==`string`?e.defaultBranch:null;return t!==null&&s!==null&&g!==null&&S!==null?{ok:!0,ownerLogin:t,repoName:s,cloneUrl:g,defaultBranch:S}:{ok:!1,error:`network`}}return e.type===`error`?{ok:!1,error:isPublishErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function emitSharePublishLog(e,t,s){getLogger(`share`).info({action:e,result:t,...s?.count===void 0?{}:{count:s.count},...s?.available===void 0?{}:{available:s.available}},`share action`)}function redactShareSubprocessStderr(e){return e.replace(/(https?:\/\/)([^:@\s/]+):([^@\s/]+)@/g,`$1$2:***@`)}const BUNDLE_SKILL_NAME={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`},BUNDLE_IDS=Object.keys(BUNDLE_SKILL_NAME),BUNDLE_SCOPE={discovery:`user`,project:`project`,"write-skill":`user`},USER_GLOBAL_BUNDLE_IDS=BUNDLE_IDS.filter(e=>BUNDLE_SCOPE[e]===`user`);function bundleSkillMdPath(e){return`packages/server/assets/skills/${e}/SKILL.md`}const MAX_ZIP_BYTES=102400,DESKTOP_SKILLS_REL=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function resolveBundledSkillDir(e,t={}){let s=t.platform??process.platform,g=t.checkDesktop??!1,S=t.home??homedir(),w=[];g&&s===`darwin`&&(w.push(join(`/Applications`,DESKTOP_SKILLS_REL,e)),w.push(join(S,`Applications`,DESKTOP_SKILLS_REL,e))),w.push(fileURLToPath(new URL(`../dist/assets/skills/${e}`,import.meta.url))),w.push(fileURLToPath(new URL(`../assets/skills/${e}`,import.meta.url))),w.push(fileURLToPath(new URL(`./assets/skills/${e}`,import.meta.url)));for(let e of w)if(existsSync(e))return e;throw Error(`Bundled skill asset directory not found for bundle '${e}'. Tried: ${w.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function*walkFiles(e,t=e){let s=await readdir(e,{withFileTypes:!0});for(let g of s){let s=join(e,g.name);g.isDirectory()?yield*walkFiles(s,t):g.isFile()&&(yield relative(t,s))}}function computeWrapperFolderName(e,t=basename){return t(e)||`open-knowledge`}function toPosixZipPath(e,t=sep){return t===`/`?e:e.split(t).join(`/`)}async function zipDirectory(e,t,s=computeWrapperFolderName(e)){let g=new import_yazl.ZipFile;g.addEmptyDirectory(`${s}/`);let S=[];for await(let t of walkFiles(e))S.push(t);S.sort();for(let t of S){let S=join(e,t),w=`${s}/${toPosixZipPath(t)}`;g.addFile(S,w)}g.end(),await new Promise((e,s)=>{let S=createWriteStream(t);g.outputStream.pipe(S),S.on(`close`,()=>e()),S.on(`error`,s),g.outputStream.on(`error`,s)})}async function sha256OfFile(e){return new Promise((t,s)=>{let g=createHash(`sha256`),S=createReadStream(e);S.on(`data`,e=>g.update(e)),S.on(`end`,()=>t(g.digest(`hex`))),S.on(`error`,s)})}function extractMetadataVersion(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return;let s=unwrapFrontmatterFences(t),g=s.search(/^metadata:/m);if(g<0)return;let S=s.slice(g).split(`
828
+ `).length>MAX_FENCE_LINES){log$10.debug({"doc.name":t,fenceIndex:e+1},`mermaid fence over validation caps — skipped`);continue}try{O++,await w.parse(s.body)}catch(g){if(g instanceof TypeError){log$10.debug({err:g,"doc.name":t,fenceIndex:e+1},`mermaid validation skipped fence — environment failure`);continue}let S=g instanceof Error?g.message:String(g),w=S.slice(0,MAX_MESSAGE_CHARS),E=extractLineNumber(S);D.push({kind:`mermaid-parse-error`,fenceIndex:e+1,fenceFirstLine:s.firstLine,message:w,...E===void 0?{}:{line:E}})}}}let k=Math.round(performance.now()-S);if(D.length===0){k>250&&log$10.debug({"doc.name":t,durationMs:k,fences:g.length},`mermaid validation slow (no warnings)`);return}return log$10.debug({"doc.name":t,count:D.length,durationMs:k},`mermaid render warnings emitted`),D}catch(e){log$10.warn({err:e,"doc.name":t},`mermaid validation errored unexpectedly — skipped`);return}}const PANE_TARGET_FILE=`pane-target.json`,PANE_TARGET_TTL_MS=3e4;function armPaneTarget(e,t,s=Date.now()){if(!t.startsWith(`#/`))return!1;tracedMkdirSync(e,{recursive:!0});let g={route:t,armedAtMs:s};return tracedWriteFileSync(resolve(e,PANE_TARGET_FILE),JSON.stringify(g)),!0}function readArmedPaneTarget(e,t=Date.now(),s=PANE_TARGET_TTL_MS){let g=resolve(e,PANE_TARGET_FILE);if(!existsSync(g))return null;try{let e=JSON.parse(readFileSync(g,`utf-8`));return typeof e.route!=`string`||typeof e.armedAtMs!=`number`||t-e.armedAtMs>s?null:e.route}catch(e){let t=e.code;return(t===`EACCES`||t===`EPERM`||t===`EIO`)&&process.stderr.write(`[pane-target] readArmedPaneTarget failed at ${g}: ${e instanceof Error?e.message:String(e)}\n`),null}}function clearArmedPaneTarget(e){let t=resolve(e,PANE_TARGET_FILE);if(existsSync(t))try{tracedUnlinkSync(t)}catch{}}const SHARE_BASE_URL=`https://openknowledge.ai/d/`,SHARE_CONSTRUCT_URL_HANDLER_TAG=`share-construct-url`;function isValidSharePath(e,t){if(e===``)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function buildGitHubBlobUrl(e,t,s,g){return`https://github.com/${e}/${t}/blob/${encodeURIComponent(s)}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function buildGitHubTreeUrl(e,t,s,g){let S=`https://github.com/${e}/${t}/tree/${encodeURIComponent(s)}`;return g===``?S:`${S}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function emitShareConstructUrlLog(e,t){let s=t?.branchExists,g=t?.kind,S=t?.freshness;getLogger(`share`).info({action:`construct-url`,result:e,...s===void 0?{}:{branchExists:s},...g===void 0?{}:{kind:g},...S===void 0?{}:{freshness:S}},`share action`)}function truncateError(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,500)}…`:t}const FRESHNESS_PROBE_TIMEOUT_MS=5e3;async function computeShareFreshness(e,t,s,g){try{let{git:g}=createGitInstance(e,{timeoutMs:FRESHNESS_PROBE_TIMEOUT_MS}),S=`refs/remotes/origin/${t}`;await g.raw([`rev-parse`,`--verify`,S]);let w=s===``?`.`:s,[E,D,O]=await Promise.all([g.raw([`cat-file`,`-e`,`${S}:${s}`]).then(()=>!0).catch(()=>!1),g.raw([`diff`,`--name-only`,S,`--`,w]),g.raw([`status`,`--porcelain`,`--untracked-files=all`,`--`,w])]);return E?D.trim()!==``||O.trim()!==``?`stale`:`current`:`absent`}catch(e){let t=truncateError(e);getLogger(`share`).warn({action:`freshness-probe-failed`,kind:g,error:t},`[share] freshness probe failed; omitting freshness`);return}}function resolveGitDir$1(e){let t=resolve(e,`.git`);if(!existsSync(t))return null;let s;try{s=statSync(t)}catch{return null}if(s.isDirectory())return t;if(s.isFile()){let s;try{s=readFileSync(t,`utf-8`)}catch{return null}let g=/^gitdir:\s*(.+)$/m.exec(s.trim());if(!g)return null;let S=g[1].trim(),w=isAbsolute(S)?S:resolve(e,S);return existsSync(w)?w:null}return null}function resolveCommonDir(e){let t=join(e,`commondir`);if(!existsSync(t))return e;let s;try{s=readFileSync(t,`utf-8`).trim()}catch{return e}return s.length===0?e:isAbsolute(s)?s:resolve(e,s)}function readGitHeadBranch(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(t,`HEAD`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=/^ref:\s*refs\/heads\/(.+)$/.exec(g.trim());return S?S[1]:null}function stripCommentAndTrim(e){let t=e.indexOf(`#`),s=e.indexOf(`;`),g=-1;return t>=0&&s>=0?g=Math.min(t,s):t>=0?g=t:s>=0&&(g=s),(g===-1?e:e.slice(0,g)).trim()}function extractOriginUrl(e){let t=!1;for(let s of e.split(/\r?\n/)){let e=stripCommentAndTrim(s);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let g=/^url\s*=\s*(.+)$/.exec(e);if(!g)continue;let S=g[1].trim();if((S.startsWith(`"`)&&S.endsWith(`"`)||S.startsWith(`'`)&&S.endsWith(`'`))&&(S=S.slice(1,-1)),S.length>0)return S}return null}function parseGitHubOriginUrl(e){let t=e.trim();if(!t)return null;let s=/^https?:\/\/(?:www\.)?github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return s||(s=/^ssh:\/\/(?:[\w.-]+@)?github\.com(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)||(s=/^[\w.-]+@github\.com:([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),s)||(s=/^git:\/\/github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)?{owner:s[1],repo:s[2]}:null}function readParsedOrigin(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(resolveCommonDir(t),`config`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=extractOriginUrl(g);return S?{originUrl:S,github:parseGitHubOriginUrl(S)}:null}function readOriginGitHubRepo(e){let t=readParsedOrigin(e);return t?t.github?{kind:`ok`,owner:t.github.owner,repo:t.github.repo}:{kind:`non-github`}:{kind:`no-remote`}}function readSyncRemoteInfo(e){let t=readParsedOrigin(e);return t?t.github?{label:`${t.github.owner}/${t.github.repo}`,webUrl:`https://github.com/${t.github.owner}/${t.github.repo}`}:{label:labelFromNonGitHubUrl(t.originUrl),webUrl:null}:null}function labelFromNonGitHubUrl(e){let t=e.trim().replace(/\.git$/,``),s=/^[\w.-]+@([^:/]+):(.+)$/.exec(t);if(s)return`${s[1]}/${s[2]}`;let g=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)*(.+)$/i.exec(t);return g?g[1]:t}function branchExistsOnOrigin(e,t){let s=resolveGitDir$1(e);if(!s)return!1;let g=resolveCommonDir(s);if(existsSync(join(g,`refs`,`remotes`,`origin`,t)))return!0;let S=join(g,`packed-refs`);if(!existsSync(S))return!1;let w;try{w=readFileSync(S,`utf-8`)}catch{return!1}let E=`refs/remotes/origin/${t}`;for(let e of w.split(/\r?\n/)){let t=e.trim();if(t.length===0||t.startsWith(`#`)||t.startsWith(`^`))continue;let s=t.split(/\s+/);if(s.length===2&&s[1]===E)return!0}return!1}const SHARE_PUBLISH_OWNERS_HANDLER_TAG=`share-publish-owners`,SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG=`share-publish-name-check`,SHARE_PUBLISH_HANDLER_TAG=`share-publish`,SHARE_PUBLISH_OWNERS_KEY=`/api/share/publish/owners`,SHARE_PUBLISH_NAME_CHECK_KEY=`/api/share/publish/name-check`,SHARE_PUBLISH_KEY=`/api/share/publish`,SHARE_PUBLISH_TIMEOUT_MS=3e4;function isValidShareRepoName(e){return e.length===0||e.length>100||e.startsWith(`.`)||e.startsWith(`-`)||/^-+$/.test(e)?!1:/^[A-Za-z0-9._-]+$/.test(e)}function isValidShareOwnerName(e){return e.length===0||e.length>39||e.startsWith(`-`)||e.endsWith(`-`)?!1:/^[A-Za-z0-9-]+$/.test(e)}function pickTerminalJsonLine(e){let t=e.split(`
829
+ `).map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e--)try{let s=JSON.parse(t[e]);if(s&&typeof s==`object`&&!Array.isArray(s))return s}catch{}return null}function parseOwnersEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`owners`&&Array.isArray(e.owners)){let t=[];for(let s of e.owners){if(!s||typeof s!=`object`)continue;let e=s,g=typeof e.login==`string`?e.login:null,S=e.kind===`user`||e.kind===`org`?e.kind:null;if(g===null||S===null)continue;let w=typeof e.avatarUrl==`string`?e.avatarUrl:void 0;t.push({login:g,kind:S,...w?{avatarUrl:w}:{}})}return{ok:!0,owners:t}}return e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function isOwnersErrorCode(e){return e===`auth-required`||e===`network`}function parseNameCheckEvent(e){return e===null?{ok:!1,error:`network`}:e.type===`name-check`&&typeof e.available==`boolean`?{ok:!0,available:e.available}:e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}const PUBLISH_ERROR_CODES=new Set([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]);function isPublishErrorCode(e){return typeof e==`string`&&PUBLISH_ERROR_CODES.has(e)}function parsePublishEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`publish`){let t=typeof e.ownerLogin==`string`?e.ownerLogin:null,s=typeof e.repoName==`string`?e.repoName:null,g=typeof e.cloneUrl==`string`?e.cloneUrl:null,S=typeof e.defaultBranch==`string`?e.defaultBranch:null;return t!==null&&s!==null&&g!==null&&S!==null?{ok:!0,ownerLogin:t,repoName:s,cloneUrl:g,defaultBranch:S}:{ok:!1,error:`network`}}return e.type===`error`?{ok:!1,error:isPublishErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function emitSharePublishLog(e,t,s){getLogger(`share`).info({action:e,result:t,...s?.count===void 0?{}:{count:s.count},...s?.available===void 0?{}:{available:s.available}},`share action`)}function redactShareSubprocessStderr(e){return e.replace(/(https?:\/\/)([^:@\s/]+):([^@\s/]+)@/g,`$1$2:***@`)}const SHARE_TARGET_STATUS_HANDLER_TAG=`share-target-status`,DEFAULT_FETCH_TIMEOUT_MS=15e3;function parseNameStatus(e){let t=[];for(let s of e.split(`
830
+ `)){if(s.trim()===``)continue;let e=s.split(` `),g=e[0]??``;(g.startsWith(`R`)||g.startsWith(`C`))&&e.length>=3?t.push({status:g,from:e[1]??``,to:e[2]??``}):t.push({status:g,from:e[1]??``,to:e[1]??``})}return t}function classifyDoc(e,t){for(let s of e)if(s.from===t){if(s.status.startsWith(`R`))return{verdict:`renamed`,renamedTo:s.to};if(s.status===`D`)return{verdict:`deleted`}}return{verdict:`deleted`}}function classifyFolder(e,t){let s=t.endsWith(`/`)?t:`${t}/`,g=new Set;for(let t of e){if(!t.from.startsWith(s)||!t.status.startsWith(`R`))continue;let e=t.from.slice(s.length);t.to.endsWith(`/${e}`)?g.add(t.to.slice(0,t.to.length-e.length-1)):g.add(`\0ambiguous`)}let S=g.size===1?[...g][0]:void 0;return S!==void 0&&S!==`\0ambiguous`?{verdict:`renamed`,renamedTo:S}:{verdict:`deleted`}}async function computeShareTargetStatus(e,t,s,g,S={}){let w=getLogger(`share`),E=e=>(w.info({action:`target-status`,verdict:e.verdict,kind:g},`target-status verdict`),e),{git:D}=createGitInstance(e,S.skipFetch?{}:{timeoutMs:S.fetchTimeoutMs??DEFAULT_FETCH_TIMEOUT_MS});if(!S.skipFetch)try{await D.raw([`fetch`,`origin`,t])}catch(e){return w.warn({action:`target-status`,kind:g,error:truncateError(e)},`target-status fetch failed`),E({verdict:`unknown`})}let O=`origin/${t}`;try{if(await D.raw([`cat-file`,`-e`,`${O}:${s}`]).then(()=>!0).catch(()=>!1)){let t=await D.raw([`cat-file`,`-e`,`HEAD:${s}`]).then(()=>!0).catch(()=>!1),g=existsSync(join(e,s));return E(t&&!g?{verdict:`changed-locally`}:{verdict:`on-origin`})}let t=(await D.raw([`log`,`-1`,`--format=%H`,O,`--`,s])).trim();if(t===``)return E({verdict:`never-on-branch`});let S=parseNameStatus(await D.raw([`diff-tree`,`-M`,`-r`,`--no-commit-id`,`--name-status`,`${t}^1`,t])),w=g===`folder`?classifyFolder(S,s):classifyDoc(S,s);return w.verdict===`renamed`&&!await D.raw([`cat-file`,`-e`,`${O}:${w.renamedTo}`]).then(()=>!0).catch(()=>!1)?E({verdict:`deleted`}):E(w)}catch(e){return w.warn({action:`target-status`,kind:g,error:truncateError(e)},`target-status detection failed`),E({verdict:`unknown`})}}const BUNDLE_SKILL_NAME={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`},BUNDLE_IDS=Object.keys(BUNDLE_SKILL_NAME),BUNDLE_SCOPE={discovery:`user`,project:`project`,"write-skill":`user`},USER_GLOBAL_BUNDLE_IDS=BUNDLE_IDS.filter(e=>BUNDLE_SCOPE[e]===`user`);function bundleSkillMdPath(e){return`packages/server/assets/skills/${e}/SKILL.md`}const MAX_ZIP_BYTES=102400,DESKTOP_SKILLS_REL=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function resolveBundledSkillDir(e,t={}){let s=t.platform??process.platform,g=t.checkDesktop??!1,S=t.home??homedir(),w=[];g&&s===`darwin`&&(w.push(join(`/Applications`,DESKTOP_SKILLS_REL,e)),w.push(join(S,`Applications`,DESKTOP_SKILLS_REL,e))),w.push(fileURLToPath(new URL(`../dist/assets/skills/${e}`,import.meta.url))),w.push(fileURLToPath(new URL(`../assets/skills/${e}`,import.meta.url))),w.push(fileURLToPath(new URL(`./assets/skills/${e}`,import.meta.url)));for(let e of w)if(existsSync(e))return e;throw Error(`Bundled skill asset directory not found for bundle '${e}'. Tried: ${w.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function*walkFiles(e,t=e){let s=await readdir(e,{withFileTypes:!0});for(let g of s){let s=join(e,g.name);g.isDirectory()?yield*walkFiles(s,t):g.isFile()&&(yield relative(t,s))}}function computeWrapperFolderName(e,t=basename){return t(e)||`open-knowledge`}function toPosixZipPath(e,t=sep){return t===`/`?e:e.split(t).join(`/`)}async function zipDirectory(e,t,s=computeWrapperFolderName(e)){let g=new import_yazl.ZipFile;g.addEmptyDirectory(`${s}/`);let S=[];for await(let t of walkFiles(e))S.push(t);S.sort();for(let t of S){let S=join(e,t),w=`${s}/${toPosixZipPath(t)}`;g.addFile(S,w)}g.end(),await new Promise((e,s)=>{let S=createWriteStream(t);g.outputStream.pipe(S),S.on(`close`,()=>e()),S.on(`error`,s),g.outputStream.on(`error`,s)})}async function sha256OfFile(e){return new Promise((t,s)=>{let g=createHash(`sha256`),S=createReadStream(e);S.on(`data`,e=>g.update(e)),S.on(`end`,()=>t(g.digest(`hex`))),S.on(`error`,s)})}function extractMetadataVersion(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return;let s=unwrapFrontmatterFences(t),g=s.search(/^metadata:/m);if(g<0)return;let S=s.slice(g).split(`
830
831
  `).slice(1);for(let e of S){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,s={}){let g=s.bundle??`project`,S=statSync(e).size;if(S>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${S} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let w=await sha256OfFile(e),E=await readFile$1(join(s.sourceDir??resolveBundledSkillDir(g,{checkDesktop:!1}),`SKILL.md`),`utf-8`),D=BUNDLE_SKILL_NAME[g];if(!RegExp(`^name:\\s+${D}$`,`m`).test(E.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${D}'. Check packages/server/assets/skills/${g}/SKILL.md frontmatter.`);let O=extractMetadataVersion(E);if(t!==void 0){if(!O)throw Error(`SKILL.md metadata.version missing. Add it to packages/server/assets/skills/${g}/SKILL.md.`);if(O!==t)throw Error(`SKILL.md metadata.version (${O}) does not match expected version (${t}).`)}return{size:S,sha256:w,skillVersion:O}}async function buildSkillZip(e={}){let t=e.bundle??`project`,s=e.sourceDir??resolveBundledSkillDir(t,{checkDesktop:e.checkDesktop??!1}),g=e.outputPath??join(process.cwd(),`openknowledge.skill`);await zipDirectory(s,g,BUNDLE_SKILL_NAME[t]);let{size:S,sha256:w,skillVersion:E}=await validateSkillZip(g,e.expectedSkillVersion,{bundle:t,sourceDir:s});return{outputPath:g,size:S,sha256:w,skillVersion:E}}const SKILL_INSTALL_EVENTS_FILE_REL=[`.ok`,`skill-install-events.jsonl`];async function recordSkillInstallEvent(e,t){let s=t?.homedir??(()=>process.env.HOME??``),g=t?.warn??((e,t)=>{console.warn(t,e)}),S=s();if(!S){g({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let w=join(S,...SKILL_INSTALL_EVENTS_FILE_REL),E=`${JSON.stringify(e)}\n`;try{await tracedMkdir(dirname(w),{recursive:!0})}catch(e){g({event:`skill-install-events.mkdir-failed`,error:String(e)},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await tracedWriteFile(w,E,{flag:`a`,encoding:`utf-8`})}catch(e){g({event:`skill-install-events.append-failed`,error:String(e)},`[skill-install-events] append failed; telemetry skipped`)}}const readFileAsync=promisify(readFile);function skillStateYamlPath(e){return join(e,...SKILL_STATE_REL)}const DEFAULT_LOGGER={warn:(e,t)=>console.warn(t,e)};async function readSkillStateFile(e,t=DEFAULT_LOGGER){let s=skillStateYamlPath(e),g;try{g=await readFileAsync(s,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let S=(0,import_dist$1.parseDocument)(g);if(S.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:s,errors:S.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let w=SkillStateSchema.safeParse(S.toJSON());if(!w.success){let e=w.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:s,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:s,issues:w.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return w.data}async function writeSkillStateFile(e,t){let s=SkillStateSchema.safeParse(t);if(!s.success)throw Error(`Refusing to write invalid skill-state: ${s.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let g=skillStateYamlPath(e);await tracedMkdir(dirname(g),{recursive:!0});let S=(0,import_dist$1.parseDocument)(``);S.contents=S.createNode(s.data),await atomicWriteFile(g,S.toString(),{fs:tracedAtomicFs})}async function readTargetVersion(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.version??null}async function readTargetRecordedAt(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.recordedAt??null}async function writeTargetVersion(e,t,s,g,S){if(!SKILL_STATE_VERSION_RE.test(s))throw Error(`Refusing to write invalid version string: ${s}`);let w=await readSkillStateFile(e,S)??emptySkillState(),E=new Date().toISOString(),D=w.targets[t],O=g===void 0?D?.surface??void 0:g,k=O===void 0?{version:s,recordedAt:E}:{version:s,recordedAt:E,surface:O};await writeSkillStateFile(e,{...w,targets:{...w.targets,[t]:k}})}async function readServerPackageVersion(){let e=await readFileAsync(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}async function readSkillInstallStateSnapshot(e,t){let[s,g]=await Promise.all([readServerPackageVersion(),readAllTargets(e,t)]);return{currentVersion:s,targets:g}}async function readAllTargets(e,t=DEFAULT_LOGGER){let s=null;try{s=await readSkillStateFile(e,t)}catch(g){t.warn({event:`skill-state.read-error`,path:skillStateYamlPath(e),error:String(g)},`non-ENOENT error reading skill-state.yml; treating as absent`),s=null}let g=SKILL_STATE_TARGETS.map(e=>{let t=s?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(g)}const CENTRAL_SKILL_DIR_REL=[`.agents`,`skills`,`open-knowledge-discovery`],LEGACY_USER_SKILL_NAME=`open-knowledge`,LEGACY_USER_SKILL_HOST_DIRS=[`.claude`,`.cursor`,`.agents`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS$4=6e4;function centralSkillDir(e){return join(e,...CENTRAL_SKILL_DIR_REL)}async function centralSkillExists(e){try{return(await stat$1(centralSkillDir(e))).isDirectory()}catch{return!1}}function quoteForWindowsShell(e){return/\s/.test(e)?`"${e.replaceAll(`"`,`\\"`)}"`:e}function runSpawn(e,t,s,g,S,w){return new Promise(E=>{let D,O=w===`win32`,k=O?s.map(quoteForWindowsShell):s;try{D=e(t,k,{env:g,stdio:[`ignore`,`pipe`,`pipe`],...O?{shell:!0}:{}})}catch(e){E({kind:`spawn-error`,stderr:``,error:e});return}let j=``,F=!1,L=e=>{F||(F=!0,clearTimeout(B),E(e))};D.stderr?.on(`data`,e=>{j+=typeof e==`string`?e:e.toString(`utf-8`)}),D.on(`error`,e=>{L({kind:`spawn-error`,stderr:j,error:e})}),D.on(`exit`,e=>{L(e===0?{kind:`ok`,exitCode:e,stderr:j}:{kind:`nonzero`,exitCode:e,stderr:j})});let B=setTimeout(()=>{try{D.kill(`SIGTERM`)}catch{}L({kind:`timeout`,stderr:j})},S)})}async function anyLegacyUserSkillExists(e){for(let t of LEGACY_USER_SKILL_HOST_DIRS)try{if((await stat$1(join(e,t,`skills`,LEGACY_USER_SKILL_NAME))).isDirectory())return!0}catch{}return!1}async function removeLegacyUserSkill(e,t,s,g,S,w){if(!await anyLegacyUserSkillExists(e))return;let E=await runSpawn(t,`npx`,[`-y`,SKILLS_CLI_SPEC,`remove`,`--agent`,`*`,`-g`,LEGACY_USER_SKILL_NAME],s,g,w);E.kind!==`ok`&&S.warn({event:`skill-install.legacy-remove-failed`,reason:E.kind,exitCode:E.exitCode,stderr:E.stderr},"Legacy `open-knowledge` skill removal did not exit cleanly; continuing with install.")}async function installUserSkill(e={}){let t=e.home??homedir(),s=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},g=e.spawn??spawn,S=e.timeoutMs??DEFAULT_TIMEOUT_MS$4,w=e.surface??`cli-npx-skills-add`,E=e.platform??process.platform,D=async(e,g,S)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:w,target:`cli-hosts`,bundle:`discovery`,outcome:e,...g===void 0?{}:{version:g},...S===void 0?{}:{reason:S}},{homedir:()=>t,warn:s.warn})},O;try{O=await readServerPackageVersion()}catch(e){return s.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await D(`failed`,void 0,`version-read-failed`),`failed`}let k=await readTargetVersion(t,`cli-hosts`,s).catch(e=>(s.warn({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(k!==null&&k===O){if(await centralSkillExists(t))return s.info?.({event:`skill-install.skip-current`,version:O},`OpenKnowledge skill already installed at current version; skipping.`),await D(`skip-current`,O),`skip-current`;s.info?.({event:`skill-install.reinstall-missing`,version:O,path:centralSkillDir(t)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let j;try{j=resolveBundledSkillDir(`discovery`,{checkDesktop:!1})}catch(e){return s.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled discovery SKILL.md asset not found.`),await D(`failed`,O,`bundled-asset-missing`),`failed`}let F={...process.env,HOME:t};await removeLegacyUserSkill(t,g,F,S,s,E);let L=await runSpawn(g,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,j,`--agent`,`*`,`-g`,`-y`,`--copy`],F,S,E);if(L.kind===`ok`){try{await writeTargetVersion(t,`cli-hosts`,O,w,s)}catch(e){return s.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),await D(`failed`,O,`sidecar-write-failed`),`failed`}return s.info?.({event:`skill-install.installed`,version:O},`OpenKnowledge skill installed to detected agent hosts.`),await D(`installed`,O),`installed`}return L.kind===`timeout`?(s.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:S,stderr:L.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${j} --agent '*' -g -y --copy`),await D(`failed`,O,`timeout`),`failed`):L.kind===`spawn-error`?(s.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(L.error),stderr:L.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${j} --agent '*' -g -y --copy`),await D(`failed`,O,`spawn-error`),`failed`):(s.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:L.exitCode,stderr:L.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${j} --agent '*' -g -y --copy`),await D(`failed`,O,`nonzero-exit:${L.exitCode??`unknown`}`),`failed`)}const DOWNLOADS_DIR=`Downloads`,SKILL_FILENAME=`openknowledge.skill`;function defaultDownloadsPath(e){return join(e,DOWNLOADS_DIR,SKILL_FILENAME)}function invokeFileAssociation(e,t,s){let g={detached:!0,stdio:`ignore`};try{return t===`darwin`?(s(`open`,[e],g).unref(),{ok:!0}):t===`win32`?(s(`cmd`,[`/c`,`start`,`""`,e],g).unref(),{ok:!0}):t===`linux`?(s(`xdg-open`,[e],g).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function buildAndOpenSkill(e={}){let t=e.home??homedir(),s=resolve(e.out??defaultDownloadsPath(t)),g=e.platformName??platform(),S=e.spawnFn??spawn,w=e.logger,E=async(e,s,g)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...s===void 0?{}:{version:s},...g===void 0?{}:{reason:g}},{homedir:()=>t,warn:w?.warn})};if(!e.force){let e=null;try{e=await readServerPackageVersion()}catch(e){w?.warn?.({event:`skill-install.gate.version-read-failed`,error:String(e)},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let s=null,g=null;try{[s,g]=await Promise.all([readTargetVersion(t,`claude-cowork`,w),readTargetRecordedAt(t,`claude-cowork`,w)])}catch(e){w?.warn?.({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read claude-cowork install-state; rebuilding.`)}if(s!==null&&s===e)return w?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`OpenKnowledge skill already delivered at current version; skipping rebuild.`),await E(`skip-current`,e),{status:`skip-current`,skillVersion:e,...g===null?{}:{recordedAt:g}}}}try{await tracedMkdir(dirname(s),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let D;try{D=await buildSkillZip({outputPath:s,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let O={status:`built`,outputPath:D.outputPath,size:D.size,sha256:D.sha256,skillVersion:D.skillVersion};if(D.skillVersion)try{await writeTargetVersion(t,`claude-cowork`,D.skillVersion,`server-build-and-open`,w)}catch(e){w?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:D.skillVersion,error:String(e)},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await E(`built`,D.skillVersion),O;let k=invokeFileAssociation(D.outputPath,g,S);return k.ok?(await E(`installed`,D.skillVersion),{...O,status:`installed`}):(await E(`built`,D.skillVersion,`handoff-${k.reason}`),{...O,handoffError:{reason:k.reason,message:k.message}})}const logger$3=getLogger(`skill-management`),SKILL_MANAGEMENT_REL=[`.ok`,`local`,`skill-management.json`],SCHEMA_VERSION=1;function skillManagementPath(e){return join(e,...SKILL_MANAGEMENT_REL)}function readSkillManagement(e){let t=skillManagementPath(e);if(!existsSync(t))return null;try{let e=JSON.parse(readFileSync(t,`utf-8`));if(e&&typeof e==`object`&&typeof e.manageEditorSkills==`boolean`){let t=e;return{version:typeof t.version==`number`?t.version:SCHEMA_VERSION,manageEditorSkills:t.manageEditorSkills,decidedAt:typeof t.decidedAt==`string`?t.decidedAt:void 0,surface:typeof t.surface==`string`?t.surface:void 0}}return logger$3.warn({path:t},`skill-management marker malformed — treating as unset`),null}catch(e){return logger$3.warn({err:e,path:t},`skill-management marker unreadable — treating as unset`),null}}async function writeSkillManagement(e,t){let s={version:SCHEMA_VERSION,manageEditorSkills:t.manageEditorSkills,decidedAt:t.now??new Date().toISOString(),...t.surface?{surface:t.surface}:{}},g=skillManagementPath(e);await tracedMkdir(dirname(g),{recursive:!0}),await atomicWriteFile(g,`${JSON.stringify(s,null,2)}\n`,{fs:tracedAtomicFs})}function isProjectSkillManaged(e,t=process.env){if(t.OK_RECLAIM_DISABLE===`1`)return!1;let s=t.OK_SKILL_MANAGE;return s===`1`||s===`true`?!0:s===`0`||s===`false`?!1:readSkillManagement(e)?.manageEditorSkills??!1}const MIN_GIT_VERSION=`2.31.0`,PROBE_TIMEOUT_MS$1=5e3;var GitNotAvailableError=class extends Error{code=`GIT_NOT_AVAILABLE`;platform;guidance;constructor(e,t,s){super(buildMissingMessage(t),s),this.name=`GitNotAvailableError`,this.platform=e,this.guidance=t}},GitTooOldError=class extends Error{code=`GIT_TOO_OLD`;platform;detected;required;resolvedPath;guidance;constructor(e,t,s,g,S,w){super(buildTooOldMessage(t,s,g,S),w),this.name=`GitTooOldError`,this.platform=e,this.detected=t,this.required=s,this.resolvedPath=g,this.guidance=S}};function detectGit(){let e=probeGit(`git`);if(e.kind===`ok`)return{ok:!0,version:e.version,resolvedPath:e.resolvedPath,source:`PATH`};for(let e of fallbackPaths(process.platform)){if(!existsSync(e))continue;let t=probeGit(e);if(t.kind===`ok`)return{ok:!0,version:t.version,resolvedPath:e,source:`fallback`}}throw new GitNotAvailableError(process.platform,buildGuidance(process.platform))}function assertGitAvailable(){let e=detectGit();if(compareSemver(e.version,`2.31.0`)<0)throw new GitTooOldError(process.platform,e.version,MIN_GIT_VERSION,e.resolvedPath,buildGuidance(process.platform));return e}function probeGit(e){let t=spawnSync(e,[`--version`],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1,env:{...process.env,LANG:`C`,LC_ALL:`C`}});if(t.error)return`signal`in t&&t.signal===`SIGTERM`?{kind:`fail`,reason:`timeout`}:{kind:`fail`,reason:`enoent`};if(t.status!==0)return{kind:`fail`,reason:`nonzero`};let s=parseGitVersion(typeof t.stdout==`string`?t.stdout:``);return s===null?{kind:`fail`,reason:`unparseable`}:{kind:`ok`,version:s,resolvedPath:e===`git`?resolveOnPath(`git`)??e:e}}function parseGitVersion(e){let t=e.match(/git version (\d+)\.(\d+)\.(\d+)/);return t?`${t[1]}.${t[2]}.${t[3]}`:null}const SAFE_COMMAND_NAME_RE=/^[a-zA-Z0-9_.-]+$/,resolveOnPathCache=new Map;function resolveOnPath(e){if(!SAFE_COMMAND_NAME_RE.test(e))return null;let t=resolveOnPathCache.get(e);if(t!==void 0)return t;let s;if(process.platform===`win32`){let t=spawnSync(`where`,[e],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1});s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}else{let t=spawnSync(`/bin/sh`,[`-c`,`command -v ${e}`],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1});s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}return s!==null&&resolveOnPathCache.set(e,s),s}function fallbackPaths(e){switch(e){case`darwin`:return[`/opt/homebrew/bin/git`,`/usr/local/bin/git`,`/Library/Developer/CommandLineTools/usr/bin/git`,`/usr/bin/git`];case`win32`:return[`C:\\Program Files\\Git\\cmd\\git.exe`,`C:\\Program Files (x86)\\Git\\cmd\\git.exe`,join(homedir(),`scoop`,`apps`,`git`,`current`,`cmd`,`git.exe`)];default:return[`/usr/bin/git`,`/usr/local/bin/git`,join(homedir(),`.local`,`bin`,`git`),`/snap/bin/git`]}}function buildGuidance(e){switch(e){case`darwin`:{let e=[];return hasBrew()&&e.push({label:`Install with Homebrew (recommended; no admin needed)`,command:`brew install git`,requiresAdmin:!1}),e.push({label:`Install Xcode Command Line Tools`,command:`xcode-select --install`,requiresAdmin:!0}),{product:`Git`,url:`https://git-scm.com/download/mac`,options:e}}case`win32`:{let e=[];return hasWinget()&&e.push({label:`Install with winget`,command:`winget install --id Git.Git -e --source winget`,requiresAdmin:!0}),hasScoop()&&e.push({label:`Install with Scoop (no admin)`,command:`scoop install git`,requiresAdmin:!1}),hasChoco()&&e.push({label:`Install with Chocolatey`,command:`choco install git -y`,requiresAdmin:!0}),e.push({label:`Download the official installer`,command:`Open https://gitforwindows.org/ in your browser`,requiresAdmin:!1}),{product:`Git for Windows`,url:`https://gitforwindows.org/`,options:e}}default:return{product:`Git`,url:`https://git-scm.com/download/linux`,options:linuxInstallOptions()}}}function linuxInstallOptions(){switch(detectLinuxFamily()){case`debian`:return[{label:`Install with apt`,command:`sudo apt install git`,requiresAdmin:!0}];case`fedora`:return[{label:`Install with dnf`,command:`sudo dnf install git`,requiresAdmin:!0}];case`arch`:return[{label:`Install with pacman`,command:`sudo pacman -S git`,requiresAdmin:!0}];case`opensuse`:return[{label:`Install with zypper`,command:`sudo zypper install git`,requiresAdmin:!0}];case`alpine`:return[{label:`Install with apk`,command:`sudo apk add git`,requiresAdmin:!0}];default:return[{label:`Use your distribution's package manager`,command:`apt / dnf / pacman / zypper / apk install git (one of these will fit your system)`,requiresAdmin:!0}]}}function detectLinuxFamily(e){let t=e;if(t===void 0)try{t=readFileSync(`/etc/os-release`,`utf-8`)}catch{return`unknown`}let s=[/^ID=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``),...(/^ID_LIKE=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``)??``).split(/\s+/)].filter(e=>!!e);return s.some(e=>/^(debian|ubuntu|mint|pop)$/i.test(e))?`debian`:s.some(e=>/^(fedora|rhel|centos|alma|rocky)$/i.test(e))?`fedora`:s.some(e=>/^(arch|manjaro|endeavouros)$/i.test(e))?`arch`:s.some(e=>/^opensuse/i.test(e))||s.includes(`suse`)?`opensuse`:s.some(e=>/^alpine$/i.test(e))?`alpine`:`unknown`}function hasCommand(e){return resolveOnPath(e)!==null}function hasBrew(){return hasCommand(`brew`)}function hasWinget(){return hasCommand(`winget`)}function hasScoop(){return hasCommand(`scoop`)}function hasChoco(){return hasCommand(`choco`)}function buildMissingMessage(e){let t=[];if(t.push(`OpenKnowledge needs ${e.product} to track changes to your knowledge base, but it isn't installed (or isn't on PATH).`),t.push(``),e.options.length>0){t.push(`Install ${e.product}:`);for(let s of e.options){let e=s.requiresAdmin?` (admin required)`:``;t.push(` • ${s.label}${e}`),t.push(` ${s.command}`)}t.push(``)}return t.push(`Or download from: ${e.url}`),t.push(``),t.push(`After installing, re-run OpenKnowledge.`),t.push("Run `ok diagnose health --check git` to verify your installation."),t.join(`
831
832
  `)}function buildTooOldMessage(e,t,s,g){let S=[];if(S.push(`OpenKnowledge requires ${g.product} ${t} or newer (detected ${e} at ${s}).`),S.push(``),g.options.length>0){S.push(`Update ${g.product}:`);for(let e of g.options){let t=e.requiresAdmin?` (admin required)`:``;S.push(` • ${e.label}${t}`),S.push(` ${e.command}`)}S.push(``)}return S.push(`Or download from: ${g.url}`),S.push(``),S.push(`After updating, re-run OpenKnowledge.`),S.push("Run `ok diagnose health --check git` to verify your installation."),S.join(`
832
833
  `)}function compareSemver(e,t){let s=e.split(`.`).map(e=>Number.parseInt(e,10)||0),g=t.split(`.`).map(e=>Number.parseInt(e,10)||0);for(let e=0;e<3;e++){let t=s[e]??0,S=g[e]??0;if(t!==S)return t-S}return 0}function resolvedHosts(e){let t=PROJECT_SKILL_EDITOR_IDS;return e.filter(e=>t.includes(e))}const RESERVED_SKILL_PREFIX=`open-knowledge`,PACK_SKILL_PREFIX=`open-knowledge-pack-`,SHIPPED_SKILL_NAME=`open-knowledge`,FRONTMATTER_RE=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,CONFLICT_MARKER_RES=[/^<{7} /m,/^={7}$/m,/^>{7} /m];function parseFrontmatter(e){let t=e.match(FRONTMATTER_RE);if(!t)return null;try{let e=(0,import_dist$1.parse)(t[1]??``);return e&&typeof e==`object`&&!Array.isArray(e)?e:null}catch{return null}}function validateSkillForInstall(e,t,s){let g=[],S=join(e,`SKILL.md`),w=existsSync(join(e,`scripts`))&&statSync(join(e,`scripts`)).isDirectory(),E=t.startsWith(RESERVED_SKILL_PREFIX)&&!t.startsWith(`open-knowledge-pack-`);if(!s?.allowReservedName&&E&&g.push(`"${t}" uses the reserved \`${RESERVED_SKILL_PREFIX}*\` prefix (reserved for OK's shipped skills) — choose another name.`),!existsSync(S))return g.push(`No SKILL.md found at ${e}.`),{ok:g.length===0,errors:g,hasScripts:w};let D;try{D=readFileSync(S,`utf-8`)}catch(e){return g.push(`Cannot read SKILL.md: ${e.message}.`),{ok:!1,errors:g,hasScripts:w}}CONFLICT_MARKER_RES.some(e=>e.test(D))&&g.push("SKILL.md contains git conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`). Resolve the conflict before installing.");let O=parseFrontmatter(D);if(O===null)g.push("SKILL.md has no valid `---` frontmatter block (name + description required).");else{let e=O.name,s=O.description;typeof e!=`string`||e.length===0?g.push(`SKILL.md frontmatter.name is missing or empty.`):e!==t&&g.push(`SKILL.md frontmatter.name ("${e}") must equal the skill directory ("${t}").`),(typeof s!=`string`||s.length===0)&&g.push(`SKILL.md frontmatter.description is missing or empty.`),(typeof e==`string`&&containsXmlTag(e)||typeof s==`string`&&containsXmlTag(s))&&g.push("SKILL.md name/description contains XML tags (`<...>`), which break the skill loader.")}return{ok:g.length===0,errors:g,hasScripts:w}}function detectProjectConfiguredTargets(e){return PROJECT_SKILL_EDITOR_IDS.filter(t=>{let s=EDITOR_PROJECT_CONFIG_PATH[t];return s!==null&&existsSync(resolve(e,s))})}function resolveSkillTargets(e,t){if(t&&t.length>0){let e=new Set(PROJECT_SKILL_EDITOR_IDS);return t.filter(t=>e.has(t))}return detectProjectConfiguredTargets(e)}function skillHostDir(e,t,s){let g=EDITOR_PROJECT_SKILL_ROOT[t];return g===null?null:resolve(e,g,s)}function hostSkillsRootEscapes(e,t){if(!existsSync(t))return!1;try{let s=relative(realpathSync(e),realpathSync(t));return s.startsWith(`..`)||isAbsolute(s)}catch{return!0}}function skillLinkTarget(e,t,s){let g=resolve(s),S=relative(resolve(e),g);return S!==``&&!S.startsWith(`..`)&&!isAbsolute(S)?relative(t,g):g}function projectSkill(e,t,s,g){let S=[];for(let w of g){let g=skillHostDir(s,w,t);if(g===null)continue;let E=dirname(g);hostSkillsRootEscapes(s,E)||(tracedRmSync(g,{recursive:!0,force:!0}),tracedMkdirSync(E,{recursive:!0}),tracedSymlinkSync(skillLinkTarget(s,E,e),g,`dir`),S.push(w))}return S}function reverseProjectSkill(e,t,s){let g=[];for(let S of s){let s=skillHostDir(t,S,e);if(s===null)continue;let w=!1;try{lstatSync(s),w=!0}catch{w=!1}w&&(tracedRmSync(s,{recursive:!0,force:!0}),g.push(S))}return g}function projectBundleSkill(e,t){let s;try{s=resolveBundledSkillDir(`project`,{checkDesktop:!0})}catch{return[]}let g=[];for(let S of t){let t=skillHostDir(e,S,SHIPPED_SKILL_NAME);t!==null&&(hostSkillsRootEscapes(e,dirname(t))||(tracedRmSync(t,{recursive:!0,force:!0}),tracedCpSync(s,t,{recursive:!0}),g.push(S)))}return g}function reverseBundleSkill(e,t){return reverseProjectSkill(SHIPPED_SKILL_NAME,e,t)}const MAX_BUNDLED_FILE_BYTES=256*1024;function listSkillFiles(e,t=``){let s=[];for(let g of readdirSync(e,{withFileTypes:!0})){let S=t?`${t}/${g.name}`:g.name;g.isDirectory()?s.push(...listSkillFiles(join(e,g.name),S)):g.isFile()&&s.push(S)}return s.sort()}function readSkillBundledFiles(e){if(!existsSync(e))return[];let t=[];for(let s of listSkillFiles(e)){if(s===`SKILL.md`)continue;let g=null;try{let t=readFileSync(join(e,s));t.length<=MAX_BUNDLED_FILE_BYTES&&!t.includes(0)&&(g=t.toString(`utf-8`))}catch(e){if(e?.code!==`ENOENT`)throw e;g=null}t.push({path:s,text:g})}return t}function isPackSkillName(e){return e.startsWith(PACK_SKILL_PREFIX)}function packIdFromSkillName(e){return isPackSkillName(e)?e.slice(20):null}function readSkillVersion(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return;let{map:s}=parseFrontmatterYaml(unwrapFrontmatterFences(t)),g=s?.version;return typeof g==`string`&&g.trim()!==``?g:void 0}function bundledPackSkillDir(e){let t=packIdFromSkillName(e);if(t===null)return null;try{return resolveBundledSkillDir(`packs/${t}`,{checkDesktop:!1})}catch{return null}}function bundledPackVersion(e){let t=bundledPackSkillDir(e);if(t!==null)try{return readSkillVersion(readFileSync(join(t,`SKILL.md`),`utf-8`))}catch{return}}function readBundledPackSkill(e){let t=bundledPackSkillDir(e);if(t===null)return null;let s;try{s=readFileSync(join(t,`SKILL.md`),`utf-8`)}catch{return null}return{content:s,version:readSkillVersion(s)}}function packUpdateAvailable(e,t){return e===void 0?!0:compareSemver(t,e)>0}function computePackUpdateStatus(e,t){let s=bundledPackVersion(e);return s===void 0?{}:{bundledVersion:s,updateAvailable:packUpdateAvailable(t,s)}}const logger$2=getLogger(`skill-reconcile`),SHIPPED_BUNDLE_NAMES=new Set([`open-knowledge`,`open-knowledge-discovery`]);function detectionRoots(){let e=[];for(let t of PROJECT_SKILL_EDITOR_IDS){let s=EDITOR_PROJECT_SKILL_ROOT[t];s!==null&&e.push({rel:s,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function relativeLinkTarget(e,t){let s=relative(e,resolve(t));return isAbsolute(s)?resolve(t):s}const DIRS_EQUAL_MAX_BYTES=1048576;function dirsEqual(e,t){let s=listFiles(e),g=listFiles(t);if(s.length!==g.length)return!1;let S=0;for(let w=0;w<s.length;w+=1){if(s[w]!==g[w])return!1;let E=s[w],D=join(e,E),O=join(t,E);if(S+=statSync(D).size+statSync(O).size,S>DIRS_EQUAL_MAX_BYTES||!readFileSync(D).equals(readFileSync(O)))return!1}return!0}function parseSkillManifest(e){let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{fm:g,body:s}}function skillManifestsSame(e,t){let s=parseSkillManifest(e),g=parseSkillManifest(t);if(s.body!==g.body)return!1;for(let e of Object.keys(s.fm))if(e in g.fm&&JSON.stringify(s.fm[e])!==JSON.stringify(g.fm[e]))return!1;return!0}function sameSkillModuloFrontmatter(e,t){let s=listFiles(e),g=listFiles(t);if(s.length!==g.length)return!1;let S=0;for(let w=0;w<s.length;w+=1){if(s[w]!==g[w])return!1;let E=s[w],D=join(e,E),O=join(t,E);if(S+=statSync(D).size+statSync(O).size,S>DIRS_EQUAL_MAX_BYTES)return!1;let k=readFileSync(D),j=readFileSync(O);if(!k.equals(j)&&(E!==`SKILL.md`||!skillManifestsSame(k.toString(`utf8`),j.toString(`utf8`))))return!1}return!0}function listFiles(e,t=``){let s=[];for(let g of readdirSync(e,{withFileTypes:!0})){let S=t?`${t}/${g.name}`:g.name;g.isDirectory()?s.push(...listFiles(join(e,g.name),S)):g.isFile()&&s.push(S)}return s.sort()}function moveDir(e,t){tracedMkdirSync(dirname(t),{recursive:!0});try{tracedRenameSync(e,t)}catch(s){if(!(s instanceof Error)||s.code!==`EXDEV`)throw s;tracedCpSync(e,t,{recursive:!0}),tracedRmSync(e,{recursive:!0,force:!0})}}function linkInto(e,t,s){tracedRmSync(t,{recursive:!0,force:!0}),tracedMkdirSync(e,{recursive:!0}),tracedSymlinkSync(relativeLinkTarget(e,s),t,`dir`)}function pointsAtSource(e,t){try{let s=readlinkSync(e);return resolve(isAbsolute(s)?s:resolve(dirname(e),s))===resolve(t)}catch{return!1}}function countImportableEditorSkills(e){let{projectDir:t,skillsRoot:s}=e,g=new Set;for(let{rel:e}of detectionRoots()){let S=resolve(t,e);if(!existsSync(S)||hostSkillsRootEscapes(t,S))continue;let w;try{w=readdirSync(S)}catch(e){logger$2.warn({hostRoot:S,err:e.message},`reconcile: skipped unreadable host skills root`);continue}for(let e of w){if(SHIPPED_BUNDLE_NAMES.has(e)||!SKILL_NAME_REGEX.test(e))continue;let t=join(S,e),w;try{w=lstatSync(t)}catch{continue}if(w.isSymbolicLink()||!w.isDirectory())continue;let E=resolve(s,e);existsSync(E)&&(dirsEqual(t,E)||sameSkillModuloFrontmatter(t,E))||g.add(e)}}return g.size}async function reconcileSkillInstalls(e){let{projectDir:t,skillsRoot:s}=e,g={healed:[],adopted:[],replaced:[],collided:[],orphansRemoved:[],skipped:[]},S=isProjectSkillManaged(t),w=new Map,E=(e,t)=>{if(t===null)return;let s=w.get(e)??new Set;s.add(t),w.set(e,s)};for(let{rel:e,editor:w}of detectionRoots()){let D=resolve(t,e);if(!existsSync(D)||hostSkillsRootEscapes(t,D))continue;let O;try{O=readdirSync(D)}catch(e){logger$2.warn({hostRoot:D,err:e.message},`reconcile: skipped unreadable host skills root`);continue}for(let e of O){if(SHIPPED_BUNDLE_NAMES.has(e))continue;let t=join(D,e),O=resolve(s,e),k=existsSync(O);try{let j=lstatSync(t);if(j.isSymbolicLink()){if(pointsAtSource(t,O)&&k)continue;k?(linkInto(D,t,O),g.healed.push({name:e,editor:w})):(tracedRmSync(t,{recursive:!0,force:!0}),g.orphansRemoved.push({name:e,editor:w}));continue}if(!j.isDirectory())continue;if(!SKILL_NAME_REGEX.test(e)){logger$2.warn({skill:e,editor:w},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(k&&(dirsEqual(t,O)||sameSkillModuloFrontmatter(t,O))){linkInto(D,t,O),g.replaced.push({name:e,editor:w}),E(e,w);continue}if(!S){g.skipped.push({name:e,editor:w});continue}if(!k)moveDir(t,O),linkInto(D,t,O),g.adopted.push({name:e,editor:w}),E(e,w);else{let S=`${e}-${w??`agents`}`,O=resolve(s,S);if(existsSync(O)){logger$2.warn({skill:e,editor:w,suffixed:S},`collision: suffixed slot already occupied — skipping (manual resolution needed)`);continue}moveDir(t,O),linkInto(D,join(D,S),O),g.collided.push({name:e,editor:w}),E(S,w)}}catch(t){logger$2.warn({err:t,skill:e,editor:w},`reconcile skipped one skill entry after error`)}}}if(w.size>0){let e=readInstalledSkills(t);for(let[g,S]of w){let w=resolve(s,g);if(!existsSync(w))continue;let E=e.skills[g],D=Array.from(new Set([...E?.hosts??[],...S]));try{await recordSkillInstall(t,g,{hosts:D,scope:E?.scope??`project`,scripts:E?.scripts??validateSkillForInstall(w,g).hasScripts,installedAt:E?.installedAt??new Date().toISOString()})}catch(e){logger$2.warn({err:e,skill:g},`reconcile marker update failed (non-fatal)`)}}}return g}const logger$1=getLogger(`skill-reproject`),SKILL_SURFACE_EDITORS=PROJECT_SKILL_EDITOR_IDS;async function reprojectAllManagedSkills(e){let{projectDir:t,skillsRoot:s,targets:g}=e,S=new Set(g),w=readInstalledSkills(t),E=[];for(let[e,D]of Object.entries(w.skills)){if(D.scope!==`project`)continue;let w=resolvedHosts(D.hosts);try{let O=resolve(s,e),k=!existsSync(O),j=k?null:validateSkillForInstall(O,e);if(k||!j?.ok){!k&&j&&!j.ok&&logger$1.warn({skill:e,errors:j.errors},`managed skill failed validation — left un-projected; fix SKILL.md (e.g. frontmatter.name must equal the folder name)`),reverseProjectSkill(e,t,w),await recordSkillInstall(t,e,{...D,hosts:[]}),E.push({name:e,hosts:[]});continue}let F=w.filter(e=>!S.has(e));F.length>0&&reverseProjectSkill(e,t,F);let L=projectSkill(O,e,t,g);await recordSkillInstall(t,e,{...D,hosts:L}),E.push({name:e,hosts:L})}catch(t){logger$1.warn({err:t,skill:e},`reproject skipped one skill after error`)}}return reverseBundleSkill(t,SKILL_SURFACE_EDITORS.filter(e=>!S.has(e))),{reprojected:E,bundleHosts:projectBundleSkill(t,g)}}const logger=getLogger(`skill-targets-store`);function skillTargetsPath(e){return join(e,...SKILL_TARGETS_REL)}function readSkillTargets(e){let t=skillTargetsPath(e);if(!existsSync(t))return null;try{let e=parseSkillTargets(readFileSync(t,`utf-8`));return e?e.targets:null}catch(e){return logger.warn({err:e,path:t},`skill-targets store unreadable`),null}}async function writeSkillTargets(e,t){let s=Array.from(new Set(t)),g=SkillTargetsSchema.safeParse({schema:1,targets:s});if(!g.success)throw Error(`Refusing to write invalid skill-targets: ${g.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let S=skillTargetsPath(e);await tracedMkdir(dirname(S),{recursive:!0}),await atomicWriteFile(S,`${JSON.stringify(g.data,null,2)}\n`,{fs:tracedAtomicFs})}var UiLockCollisionError=class extends ProcessLockCollisionError{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function acquireUiLock(e,t){try{return acquireProcessLock({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof ProcessLockCollisionError&&e.lockName===`ui`?new UiLockCollisionError(e.existing,e.lockPath):e}}function updateUiLockPort(e,t){updateProcessLockPort({lockName:`ui`,lockDir:e,port:t})}function readUiLock(e){return readProcessLock({lockName:`ui`,lockDir:e})}function releaseUiLock(e){releaseProcessLock({lockName:`ui`,lockDir:e})}var UploadWriteError=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function uploadStatusFor(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return assertNeverProblemType(e)}}function classifyUploadErrno(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function uploadTitleFor(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return assertNeverProblemType(e)}}const log$9=getLogger(`upload-streaming`);var HashingPassThrough=class extends Transform{hash=createHash(`sha256`);bytes=0;digested=!1;_transform(e,t,s){this.hash.update(e),this.bytes+=e.length,s(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function tmpUploadDir(e){return resolve(getLocalDir(e),`tmp`)}function mintTempUploadPath(e){let t=tmpUploadDir(e);return tracedMkdirSync(t,{recursive:!0}),resolve(t,`upload-${randomUUID$1()}`)}function linkTempToFinalWithCollisionRetry(e,t,s){let g=extname(s),S=s.slice(0,s.length-g.length),w=[s,...Array.from({length:99},(e,t)=>`${S}-${t+1}${g}`)];for(let s of w){let g=resolve(t,s);try{tracedLinkSync(e,g);try{tracedUnlinkSync(e)}catch{}return s}catch(t){let s=t.code;if(s===`EEXIST`)continue;try{tracedUnlinkSync(e)}catch{}throw s===`ENOSPC`||s===`EDQUOT`?new UploadWriteError(`urn:ok:error:storage-full`,t):s===`EROFS`||s===`EACCES`||s===`EPERM`?new UploadWriteError(`urn:ok:error:storage-readonly`,t):new UploadWriteError(`urn:ok:error:storage-error`,t)}}try{tracedUnlinkSync(e)}catch{}throw new UploadWriteError(`urn:ok:error:collision-exhaustion`)}function cleanupOrphanUploadTempfiles(e,{ageMs:t=1440*60*1e3}={}){let s=tmpUploadDir(e),g={scanned:0,deleted:0,errors:0};if(!existsSync(s))return g;let S;try{S=readdirSync(s)}catch(e){return log$9.warn({err:e,dir:s},`[upload-tempfile-sweep] readdir failed`),g.errors++,g}let w=Date.now()-t;for(let e of S){if(!e.startsWith(`upload-`))continue;g.scanned++;let t=resolve(s,e);try{if(statSync(t).mtimeMs>=w)continue;tracedUnlinkSync(t),g.deleted++}catch(e){log$9.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),g.errors++}}return(g.deleted>0||g.errors>0)&&log$9.info({dir:s,scanned:g.scanned,deleted:g.deleted,errors:g.errors},`[upload-tempfile-sweep] swept ${g.deleted}/${g.scanned} (errors: ${g.errors})`),g}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let s=t[1],g=s[0];return g!=="`"&&g!==`~`?null:{char:g,length:s.length}}function isFenceClose$2(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$2(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$2(e,t){let s=0;for(;e[t+s]==="`";)s++;if(s===0)return null;let g=t+s,S=g;for(;S<e.length;){if(e[S]!=="`"){S++;continue}let t=0;for(;e[S+t]==="`";)t++;if(t===s)return{nextIndex:S+s};S+=t}return{nextIndex:g}}function readWikiLink$2(e,t){let s=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!s)return null;let g=s[1]?.trim(),S=s[2]?.trim()||null,w=s[3]?.trim()||null;return g?{target:g,alias:w,anchor:S,nextIndex:t+s[0].length}:null}function readWikiLinkOrEmbed(e,t){if(e[t]===`!`&&e[t+1]===`[`&&e[t+2]===`[`){let s=readWikiLink$2(e,t+1);return s?{...s,embed:!0}:null}if(e[t]===`[`&&e[t+1]===`[`){let s=readWikiLink$2(e,t);return s?{...s,embed:!1}:null}return null}function readMarkdownLink$2(e,t){let s=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!s)return null;let g=s[2]??``;return{text:s[1]??``,hrefRaw:g,href:g.startsWith(`<`)&&g.endsWith(`>`)?g.slice(1,-1):g,titleSuffix:s[3]??``,nextIndex:t+s[0].length}}function readImageRef(e,t){let s=/^!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!s)return null;let g=s[2]??``;return{alt:s[1]??``,hrefRaw:g,href:g.startsWith(`<`)&&g.endsWith(`>`)?g.slice(1,-1):g,titleSuffix:s[3]??``,nextIndex:t+s[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),s=[];for(let e=0;e<t.length;e+=2)s.push({line:t[e]??``,ending:t[e+1]??``});return s}function rewriteWikiLinksInLine(e,t,s){let g=``,S=0,w=0,E=leadingMarkdownPrefixLength$2(e);for(E>0&&(g+=e.slice(0,E),w=E);w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let E=readWikiLink$2(e,w);if(E){E.target===t?(g+=`[[${s}${E.anchor?`#${E.anchor}`:``}${E.alias?`|${E.alias}`:``}]]`,S++):g+=e.slice(w,E.nextIndex),w=E.nextIndex;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function recomputeRelativeImageHref(e,t,s){let g=e.indexOf(`#`),S=g>=0?e.slice(g):``,w=g>=0?e.slice(0,g):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``,O=E>=0?w.slice(0,E):w;if(O.startsWith(`/`)||O.startsWith(`//`)||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(O))return null;let k=posix.dirname(t),j=posix.dirname(s);if(k===j)return null;let F=k===`.`?`/`:`/${k}/`,L=posix.resolve(F,O).slice(1),B=posix.relative(j===`.`?``:j,L);return B||=posix.basename(L),O.startsWith(`./`)&&!B.startsWith(`./`)&&!B.startsWith(`../`)&&(B=`./${B}`),`${B}${D}${S}`}function decodeHrefForAssetResolution(e){try{return decodeURI(e)}catch{return e}}function splitHrefPathAndSuffix(e){let t=e.indexOf(`#`),s=t>=0?e.slice(t):``,g=t>=0?e.slice(0,t):e,S=g.indexOf(`?`),w=S>=0?g.slice(S):``;return{pathPart:S>=0?g.slice(0,S):g,suffix:`${w}${s}`}}function buildAssetHrefFromSource(e,t,s,g={}){let S=g.encodePath??!0,w=e=>S?encodeURI(e):e,{pathPart:E,suffix:D}=splitHrefPathAndSuffix(e);if(E.startsWith(`/`))return`/${w(s)}${D}`;let O=posix.dirname(t),k=posix.relative(O===`.`?``:O,s);return k||=posix.basename(s),E.startsWith(`./`)&&!k.startsWith(`./`)&&!k.startsWith(`../`)&&(k=`./${k}`),`${w(k)}${D}`}function rewriteAssetHrefForRename(e,t,s,g,S={}){return resolveAssetProjectPath(decodeHrefForAssetResolution(e),t)===s?buildAssetHrefFromSource(e,t,g,S):null}function recomputeRelativeMarkdownHref(e,t,s){let g=e.indexOf(`#`),S=g>=0?e.slice(g):``,w=g>=0?e.slice(0,g):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``,O=E>=0?w.slice(0,E):w,k=O.startsWith(`/`),j=posix.dirname(t),F=k?`/${s}`:posix.relative(j===`.`?``:j,s);return F||=posix.basename(s),O.endsWith(`.mdx`)?F+=`.mdx`:O.endsWith(`.md`)&&(F+=`.md`),!k&&O.startsWith(`./`)&&!F.startsWith(`./`)&&!F.startsWith(`../`)&&(F=`./${F}`),`${F}${D}${S}`}function rewriteMarkdownLinksInLine(e,t,s,g){let S=``,w=0,E=0,D=leadingMarkdownPrefixLength$2(e);for(D>0&&(S+=e.slice(0,D),E=D);E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e.slice(E,E+2),E+=2;continue}if(e[E]==="`"){let t=readInlineCode$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}if(e[E]===`[`&&e[E+1]===`[`){let t=readWikiLink$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}if(e[E]===`!`&&e[E+1]===`[`){let D=readImageRef(e,E);if(D){let O=t===s&&s!==g?recomputeRelativeImageHref(D.href,s,g):null;if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`![${D.alt}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}if(e[E]===`[`){let D=readMarkdownLink$2(e,E);if(D){if(resolveInternalHref(D.href,t)?.docName===s){let e=recomputeRelativeMarkdownHref(D.href,t,g),s=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${e}>`:e;S+=`[${D.text}](${s}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}S+=e[E],E++}return{markdown:S,rewrites:w}}function renderWikiLinkOrEmbed(e,t){return`${e.embed?`!`:``}[[${t}${e.anchor?`#${e.anchor}`:``}${e.alias?`|${e.alias}`:``}]]`}const HTML_ASSET_ATTR_RE=/(\s(?:href|src)\s*=\s*)(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function rewriteHtmlAssetAttrsInTag(e,t,s,g){let S=0;return{markdown:e.replace(HTML_ASSET_ATTR_RE,(e,w,E,D,O,k)=>{let j=E??D??O??k;if(typeof j!=`string`)return e;let F=rewriteAssetHrefForRename(j,t,s,g);return F===null?e:(S++,E===void 0?D===void 0?O===void 0?`${w}${F}`:`${w}“${F}”`:`${w}'${F}'`:`${w}"${F}"`)}),rewrites:S}}function rewriteAssetReferencesInLine(e,t,s,g){let S=``,w=0,E=0,D=leadingMarkdownPrefixLength$2(e);for(D>0&&(S+=e.slice(0,D),E=D);E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e.slice(E,E+2),E+=2;continue}if(e[E]==="`"){let t=readInlineCode$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}let D=readWikiLinkOrEmbed(e,E);if(D){let O=rewriteAssetHrefForRename(D.target,t,s,g,{encodePath:!1});O===null?S+=e.slice(E,D.nextIndex):(S+=renderWikiLinkOrEmbed(D,O),w++),E=D.nextIndex;continue}if(e.startsWith(`<!--`,E)){let t=e.indexOf(`-->`,E+4);if(t===-1){S+=e.slice(E);break}S+=e.slice(E,t+3),E=t+3;continue}if(e[E]===`<`){let D=e.indexOf(`>`,E+1);if(D!==-1){let O=rewriteHtmlAssetAttrsInTag(e.slice(E,D+1),t,s,g);if(O.rewrites>0){S+=O.markdown,w+=O.rewrites,E=D+1;continue}}}if(e[E]===`!`&&e[E+1]===`[`){let D=readImageRef(e,E);if(D){let O=rewriteAssetHrefForRename(D.href,t,s,g);if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`![${D.alt}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}if(e[E]===`[`){let D=readMarkdownLink$2(e,E);if(D){let O=rewriteAssetHrefForRename(D.href,t,s,g);if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`[${D.text}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}S+=e[E],E++}return{markdown:S,rewrites:w}}const MIRROR_TAG_RE=/<Mirror\b([^>]*)\/>/g,MIRROR_SRC_ATTR_RE=/(\bsrc=)(["'])([^"']*)\2/g;function rewriteMirrorSrcInLine(e,t,s){let g=``,S=0,w=0;for(;w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`<`){let E=new RegExp(MIRROR_TAG_RE.source),D=e.slice(w),O=E.exec(D);if(O&&O.index===0){let[e,E]=O,D=new RegExp(MIRROR_SRC_ATTR_RE.source,MIRROR_SRC_ATTR_RE.flags),k=E.replace(D,(e,g,w,E)=>E===t?(S++,`${g}${w}${s}${w}`):e);g+=`<Mirror${k}/>`,w+=e.length;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function rewriteMirrorSrcForDocumentRename(e,t,s){let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteMirrorSrcInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}function rewriteWikiLinksForDocumentRename(e,t,s){let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteWikiLinksInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}function rewriteMarkdownLinksForDocumentRename(e,t,s,g){let S=null,w=0;return{markdown:splitLines(e).map(({line:e,ending:E})=>{if(S)return isFenceClose$2(e,S)&&(S=null),`${e}${E}`;let D=matchFence$2(e);if(D)return S=D,`${e}${E}`;let O=rewriteMarkdownLinksInLine(e,t,s,g);return w+=O.rewrites,`${O.markdown}${E}`}).join(``),rewrites:w}}function rewriteAssetReferencesForRename(e,t,s,g){let S=null,w=0;return{markdown:splitLines(e).map(({line:e,ending:E})=>{if(S)return isFenceClose$2(e,S)&&(S=null),`${e}${E}`;let D=matchFence$2(e);if(D)return S=D,`${e}${E}`;let O=rewriteAssetReferencesInLine(e,t,s,g);return w+=O.rewrites,`${O.markdown}${E}`}).join(``),rewrites:w}}function rewriteOutboundMarkdownLinksInLine(e,t,s){let g=``,S=0,w=0,E=leadingMarkdownPrefixLength$2(e);for(E>0&&(g+=e.slice(0,E),w=E);w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let t=readWikiLink$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`!`&&e[w+1]===`[`){let t=readImageRef(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`){let E=readMarkdownLink$2(e,w);if(E){let D=resolveInternalHref(E.href,t);if(D!==null){let t=recomputeRelativeMarkdownHref(E.href,s,D.docName);if(t!==E.href){let e=E.hrefRaw.startsWith(`<`)&&E.hrefRaw.endsWith(`>`)?`<${t}>`:t;g+=`[${E.text}](${e}${E.titleSuffix})`,S++}else g+=e.slice(w,E.nextIndex)}else g+=e.slice(w,E.nextIndex);w=E.nextIndex;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function rewriteOutboundMarkdownLinksForSourceMove(e,t,s){if(posix.dirname(t)===posix.dirname(s))return{markdown:e,rewrites:0};let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteOutboundMarkdownLinksInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}var ManagedRenameCollisionError=class extends Error{colliding;constructor(e){super(`Managed rename collision: ${e.map(e=>`'${e.existing}' and '${e.incoming}' both target '${e.to}'`).join(`; `)}`),this.name=`ManagedRenameCollisionError`,this.colliding=e}},ManagedRenameSourceNotFoundError=class extends Error{kind;constructor(e,t=`${e} does not exist`){super(t),this.name=`ManagedRenameSourceNotFoundError`,this.kind=e}},ManagedRenameDestinationExistsError=class extends Error{constructor(){super(`Destination already exists`),this.name=`ManagedRenameDestinationExistsError`}},ManagedRenameSourceTypeMismatchError=class extends Error{kind;constructor(e,t=`Source path is not a ${e}`){super(t),this.name=`ManagedRenameSourceTypeMismatchError`,this.kind=e}},ManagedRenameInvalidRequestError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameInvalidRequestError`}},ManagedRenameReservedPathError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameReservedPathError`}},SymlinkEscapeError=class extends Error{constructor(e){super(`symlink-escape: ${e}`),this.name=`SymlinkEscapeError`}},BacklinkIndexRequiredError=class extends Error{constructor(){super(`Managed rename requires backlink index support`),this.name=`BacklinkIndexRequiredError`}},ManagedRenameSnapshotMissingError=class extends Error{docName;constructor(e){super(`Cannot snapshot missing document: ${e}`),this.name=`ManagedRenameSnapshotMissingError`,this.docName=e}},ManagedRenameMissingDocumentError=class extends Error{docName;constructor(e){super(`Cannot rename missing document: ${e}`),this.name=`ManagedRenameMissingDocumentError`,this.docName=e}};function buildRenameMap(e){let t=new Map,s=[];for(let{from:g,to:S}of e){for(let[e,w]of t)e!==g&&w===S&&s.push({existing:e,incoming:g,to:S});t.set(g,S)}if(s.length>0)throw new ManagedRenameCollisionError(s);return t}function rewriteSupportedLinksForRename(e,t,s,g){let{frontmatter:S,body:w}=stripFrontmatter(e),E=rewriteWikiLinksForDocumentRename(w,s,g),D=rewriteMarkdownLinksForDocumentRename(E.markdown,t,s,g),O=rewriteMirrorSrcForDocumentRename(D.markdown,s,g);return{markdown:prependFrontmatter(S,O.markdown),rewrites:E.rewrites+D.rewrites+O.rewrites}}function applyRenameMap(e,t,s){let g=e,S=0,w,E=[];for(let[e,g]of s)e!==g&&(e===t?w=g:E.push([e,g]));if(w!==void 0){let e=rewriteSupportedLinksForRename(g,t,t,w);g=e.markdown,S+=e.rewrites;let{frontmatter:s,body:E}=stripFrontmatter(g),D=rewriteOutboundMarkdownLinksForSourceMove(E,t,w);g=prependFrontmatter(s,D.markdown),S+=D.rewrites}let D=w??t,O=new Map;for(let[e,t]of E){let s=`__OK_RENAME_${randomUUID$1().replaceAll(`-`,``)}__`,w=rewriteSupportedLinksForRename(g,D,e,s);w.rewrites>0&&(g=w.markdown,S+=w.rewrites,O.set(s,t))}for(let[e,t]of O)g=rewriteSupportedLinksForRename(g,D,e,t).markdown;return{markdown:g,rewrites:S}}const WIKI_LINK_RE$1=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE$1=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function createEmptyState$1(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function parseSkillBundleDocAnyScope(e){let t=parseProjectSkillBundleDoc(e);if(t)return{name:t.name,kind:t.kind,skillDocName:skillLiveDocName(`project`,t.name)};let s=parseGlobalSkillBundleDoc(e);return s?{name:s.name,kind:s.kind,skillDocName:skillLiveDocName(`global`,s.name)}:null}function mergeLinkMeta(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function getRepresentativeAnchor(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function externalNodeId(e){return`external:${e}`}function externalUrlFromNodeId(e){return e.startsWith(`external:`)?e.slice(9):null}function normalizeSnippet$1(e){return e.replace(/\s+/g,` `).trim()}function snippetAround$1(e,t,s){if(!normalizeSnippet$1(e))return null;let g=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
@@ -853,7 +854,7 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
853
854
  `).split(`
854
855
  `),D=[],O=new Set,k=null,j=(e,t,s)=>{O.has(e)||(O.add(e),D.push({href:e,resolvedTo:t,reason:s}))},F=e=>{let s=e.trim();if(s.startsWith(`#`))return;let w=classifyMarkdownHref(s,t);if(!w){j(s,null,`unresolvable`);return}if(w.kind===`doc`){S.has(w.docName)||j(s,w.docName,`no-such-doc`);return}if(w.kind===`asset`){if(!g)return;let e=resolveAssetProjectPath(w.url,t);if(e===null){j(s,null,`unresolvable`);return}g(e)||j(s,e,`no-such-file`);return}},L=(e,t)=>{let s=classifyWikiLinkTarget(e,t);!s||s.kind!==`doc`||S.has(s.docName)||j(`[[${e}${t?`#${t}`:``}]]`,s.docName,`no-such-doc`)};for(let e of E){if(k){isFenceClose$1(e,k)&&(k=null);continue}let t=matchFence$1(e);if(t){k=t;continue}let s=leadingMarkdownPrefixLength$1(e);for(;s<e.length;){if(e[s]===`\\`&&s+1<e.length){s+=2;continue}if(e[s]==="`"){let t=readInlineCode$1(e,s);if(t){s=t.nextIndex;continue}}if(e[s]===`[`&&e[s+1]===`[`){let t=readWikiLink$1(e,s);if(t){L(t.target,t.anchor),s=t.nextIndex;continue}}if(e[s]===`[`&&e[s-1]!==`!`){let t=readMarkdownLink$1(e,s);if(t){F(t.href),s=t.nextIndex;continue}}s++}}return D}function serializeState(e){return{backward:Object.fromEntries([...e.backward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet}))])),forward:Object.fromEntries([...e.forward.entries()].map(([e,t])=>[e,[...t].sort()])),externalForward:Object.fromEntries([...e.externalForward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url))]))}}function buildExternalBackward(e){let t=new Map;for(let[s,g]of e)for(let[e,S]of g){let g=t.get(e);g||(g=new Map,t.set(e,g)),g.set(s,S)}return t}function deserializeState(e){let t=new Map(Object.entries(e.externalForward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.url,{label:e.label??null,snippet:e.snippet??null}]))]));return{backward:new Map(Object.entries(e.backward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.source,{anchor:e.anchor??null,snippet:e.snippet??null}]))])),forward:new Map(Object.entries(e.forward??{}).map(([e,t])=>[e,new Set(t)])),externalForward:t,externalBackward:buildExternalBackward(t)}}var BacklinkIndex=class{projectDir;contentDir;contentFilter;states=new Map;mtimesByBranch=new Map;activeBranch=`main`;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.states.set(this.activeBranch,createEmptyState$1())}getState(e=this.activeBranch){let t=this.states.get(e);return t||(t=createEmptyState$1(),this.states.set(e,t)),t}structuralBundleNeighbors(e,t=this.activeBranch){let s=parseSkillBundleDocAnyScope(e),g=new Set;if(!s)return g;let S=this.getState(t);if(!S.forward.has(e))return g;if(s.kind===`skill`)for(let t of S.forward.keys()){let s=parseSkillBundleDocAnyScope(t);s?.kind===`reference`&&s.skillDocName===e&&g.add(t)}else S.forward.has(s.skillDocName)&&g.add(s.skillDocName);return g}getActiveBranch(){return this.activeBranch}switchBranch(e){this.activeBranch=e,this.getState(e)}cachePath(e=this.activeBranch){return resolve(getLocalDir(this.projectDir),`cache`,e,`backlinks.json`)}registerNodeOnly(e,t=this.activeBranch){let s=this.getState(t),g=s.forward.get(e)??new Set,S=s.externalForward.get(e)??new Map;for(let t of g){let g=s.backward.get(t);g&&(g.delete(e),g.size===0&&s.backward.delete(t))}for(let t of S.keys()){let g=s.externalBackward.get(t);g&&(g.delete(e),g.size===0&&s.externalBackward.delete(t))}s.forward.set(e,new Set),s.externalForward.set(e,new Map)}registerGlobalSkillBundleNode(e,t=this.activeBranch){parseGlobalSkillBundleDoc(e)&&this.registerNodeOnly(e,t)}updateDocument(e,t,s=[],g=this.activeBranch){if(isLinkIndexExcludedDoc(e))return;if(parseGlobalSkillBundleDoc(e)){this.registerNodeOnly(e,g);return}let S=this.getState(g),w=S.forward.get(e)??new Set,E=S.externalForward.get(e)??new Map;for(let t of w){let s=S.backward.get(t);s&&(s.delete(e),s.size===0&&S.backward.delete(t))}for(let t of E.keys()){let s=S.externalBackward.get(t);s&&(s.delete(e),s.size===0&&S.externalBackward.delete(t))}let D=new Set,O=new Map;S.forward.set(e,D),S.externalForward.set(e,O);for(let s of t){if(!s.target)continue;let t=managedArtifactDocNameFromContentTarget(s.target)??s.target;D.add(t);let g=S.backward.get(t);g||(g=new Map,S.backward.set(t,g)),g.set(e,mergeLinkMeta(g.get(e),{anchor:s.anchor,snippet:s.snippet}))}for(let t of s){if(!t.url)continue;O.set(t.url,{label:t.label,snippet:t.snippet});let s=S.externalBackward.get(t.url);s||(s=new Map,S.externalBackward.set(t.url,s)),(!s.has(e)||!s.get(e)?.snippet&&t.snippet)&&s.set(e,{label:t.label,snippet:t.snippet})}}updateDocumentFromMarkdown(e,t,s=this.activeBranch){try{let{body:g}=stripFrontmatter(t),S=extractWikiLinksFromMarkdown(g,e),w=extractMarkdownLinksFromMarkdown(g,e),E=extractExternalWikiLinksFromMarkdown(g),D=extractExternalMarkdownLinksFromMarkdown(g,e),O=new Set(S.map(e=>e.target)),k=[...S,...w.filter(e=>!O.has(e.target))],j=new Set(E.map(e=>e.url)),F=[...E,...D.filter(e=>!j.has(e.url))];this.updateDocument(e,k,F,s)}catch(t){console.warn(`[backlinks] Failed to scan ${e} for link extraction:`,t),this.deleteDocument(e,s)}}deleteDocument(e,t=this.activeBranch){if(isLinkIndexExcludedDoc(e))return;let s=this.getState(t),g=s.forward.get(e)??new Set,S=s.externalForward.get(e)??new Map;for(let t of g){let g=s.backward.get(t);g&&(g.delete(e),g.size===0&&s.backward.delete(t))}for(let t of S.keys()){let g=s.externalBackward.get(t);g&&(g.delete(e),g.size===0&&s.externalBackward.delete(t))}s.forward.delete(e),s.externalForward.delete(e)}renameDocument(e,t,s,g=this.activeBranch){this.deleteDocument(e,g),this.updateDocumentFromMarkdown(t,s,g)}getBacklinks(e,t=this.activeBranch){let s=this.getState(t).backward.get(e),g=new Map;if(s)for(let[e,t]of s)g.set(e,{source:e,anchor:t.anchor,snippet:t.snippet});for(let s of this.structuralBundleNeighbors(e,t))g.has(s)||g.set(s,{source:s,anchor:null,snippet:null});return[...g.values()].sort((e,t)=>e.source.localeCompare(t.source))}getBacklinkCount(e,t=this.activeBranch){let s=this.getState(t).backward.get(e),g=this.structuralBundleNeighbors(e,t);if(g.size===0)return s?.size??0;let S=new Set(s?.keys()??[]);for(let e of g)S.add(e);return S.size}getForwardLinks(e,t=this.activeBranch){let s=this.getState(t),g=new Set(s.forward.get(e)??new Set);for(let s of this.structuralBundleNeighbors(e,t))g.add(s);return[...g].sort((e,t)=>e.localeCompare(t))}getForwardLinkEntries(e,t=this.activeBranch){let s=this.getState(t),g=this.getForwardLinks(e,t).map(t=>({kind:`doc`,target:t,anchor:s.backward.get(t)?.get(e)?.anchor??null,snippet:s.backward.get(t)?.get(e)?.snippet??null})),S=[...(s.externalForward.get(e)??new Map).entries()].map(([e,t])=>({kind:`external`,url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url));return[...g,...S]}getOrphans(e,t=`both`,s=this.activeBranch){let g=this.getState(s),S=new Set;for(let e of g.forward.keys()){let t=parseSkillBundleDocAnyScope(e);t?.kind===`reference`&&S.add(t.skillDocName)}let w=e=>{let t=parseSkillBundleDocAnyScope(e);return!t||!g.forward.has(e)?!1:t.kind===`skill`?S.has(e):g.forward.has(t.skillDocName)};return[...e].filter(e=>{let s=w(e),S=s||(g.backward.get(e)?.size??0)>0,E=s||(g.forward.get(e)?.size??0)>0;return t===`incoming`?!S:(t===`outgoing`||!S)&&!E}).sort((e,t)=>e.localeCompare(t))}getHubs(e=20,t=this.activeBranch){return[...this.getState(t).backward.entries()].map(([e,t])=>({docName:e,count:t.size})).sort((e,t)=>t.count===e.count?e.docName.localeCompare(t.docName):t.count-e.count).slice(0,e)}getIndexedDocNames(e=this.activeBranch){return[...this.getState(e).forward.keys()]}getDeadLinks(e,t,s=this.activeBranch){let g=this.getState(s),S=new Set(e),w=t?.length?new Set(t):null;return[...g.backward.entries()].filter(([e,t])=>{if(S.has(e)||g.forward.has(e))return!1;if(!w)return t.size>0;for(let e of t.keys())if(w.has(e))return!0;return!1}).map(([e,t])=>({target:e,sources:[...t.entries()].filter(([e])=>!w||w.has(e)).map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet})).sort((e,t)=>e.source.localeCompare(t.source))})).filter(e=>e.sources.length>0).sort((e,t)=>t.sources.length===e.sources.length?e.target.localeCompare(t.target):t.sources.length-e.sources.length)}getLinkGraph(e=this.activeBranch){let t=this.getState(e),s=new Map,g=[];for(let[e,S]of t.forward){s.set(e,{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(t.backward.get(e))});for(let w of S)s.set(w,{kind:`doc`,id:w,docName:w,anchor:getRepresentativeAnchor(t.backward.get(w))}),g.push({source:e,target:w})}for(let[e,S]of t.externalForward){s.set(e,{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(t.backward.get(e))});for(let[t,w]of S){let S=externalNodeId(t);s.set(S,{kind:`external`,id:S,url:t,label:w.label}),g.push({source:e,target:S})}}for(let S of t.forward.keys())if(parseSkillBundleDocAnyScope(S)?.kind===`skill`)for(let w of this.structuralBundleNeighbors(S,e))t.forward.get(S)?.has(w)||t.forward.get(w)?.has(S)||(s.set(S,{kind:`doc`,id:S,docName:S,anchor:getRepresentativeAnchor(t.backward.get(S))}),s.set(w,{kind:`doc`,id:w,docName:w,anchor:getRepresentativeAnchor(t.backward.get(w))}),g.push({source:S,target:w}));return{nodes:[...s.values()].sort((e,t)=>e.id.localeCompare(t.id)),links:g}}getLinkGraphNeighborhood(e,t,s=this.activeBranch){let g=this.getState(s),S=new Map;for(let e of g.externalForward.values())for(let[t,s]of e)S.has(t)||S.set(t,s.label);let w=new Set([e]),E=[{nodeId:e,degree:0}],D=0;for(;D<E.length;){let e=E[D++];if(e.degree>=t)continue;let S=externalUrlFromNodeId(e.nodeId),O=new Set;if(S)for(let e of g.externalBackward.get(S)?.keys()??[])O.add(e);else{for(let t of g.forward.get(e.nodeId)??new Set)O.add(t);for(let t of g.externalForward.get(e.nodeId)?.keys()??[])O.add(externalNodeId(t));for(let t of g.backward.get(e.nodeId)?.keys()??[])O.add(t);for(let t of this.structuralBundleNeighbors(e.nodeId,s))O.add(t)}for(let t of O)w.has(t)||(w.add(t),E.push({nodeId:t,degree:e.degree+1}))}let O=[];for(let[e,t]of g.forward)if(w.has(e))for(let s of t)w.has(s)&&O.push({source:e,target:s});for(let[e,t]of g.externalForward)if(w.has(e))for(let s of t.keys()){let t=externalNodeId(s);w.has(t)&&O.push({source:e,target:t})}for(let e of w)if(parseSkillBundleDocAnyScope(e)?.kind===`skill`)for(let t of this.structuralBundleNeighbors(e,s))w.has(t)&&(g.forward.get(e)?.has(t)||g.forward.get(t)?.has(e)||O.push({source:e,target:t}));return{nodes:[...w].sort().map(e=>{let t=externalUrlFromNodeId(e);return t?{kind:`external`,id:e,url:t,label:S.get(t)??null}:{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(g.backward.get(e))}}),links:O}}async saveToDisk(e=this.activeBranch){let t=this.cachePath(e);mkdirSync(dirname(t),{recursive:!0});let s=this.getState(e),g=this.mtimesByBranch.get(e),S={...serializeState(s),...g?{mtimes:Object.fromEntries(g)}:{}};await writeFile(t,JSON.stringify(S,null,2),`utf-8`)}async loadFromDisk(e=this.activeBranch){let t=this.cachePath(e);if(!existsSync(t))return!1;try{let s=await readFile$1(t,`utf-8`),g=JSON.parse(s);return this.states.set(e,deserializeState(g)),g.mtimes?this.mtimesByBranch.set(e,new Map(Object.entries(g.mtimes))):this.mtimesByBranch.delete(e),!0}catch(t){return console.warn(`[backlinks] Failed to load cache for ${e}:`,t),!1}}clear(e=this.activeBranch){this.states.set(e,createEmptyState$1()),this.mtimesByBranch.delete(e)}async rebuildFromDisk(e=this.activeBranch){let t=createEmptyState$1(),s=new Map,g=[];await this.walkForPaths(this.contentDir,g);let S=new Set,w=g.filter(({docName:e})=>S.has(e)?!1:(S.add(e),!0)),E=50;for(let e=0;e<w.length;e+=50){let g=w.slice(e,e+50),S=await Promise.allSettled(g.map(async({docName:e,filePath:t})=>{let[s,g]=await Promise.all([stat$1(t),readFile$1(t,`utf-8`)]);return{docName:e,mtimeMs:s.mtimeMs,markdown:g}}));for(let e of S){if(e.status===`rejected`){console.warn(`[backlinks] Failed to rebuild entry:`,e.reason);continue}let{docName:g,mtimeMs:S,markdown:w}=e.value;s.set(g,S);let{body:E}=stripFrontmatter(w),D=extractWikiLinksFromMarkdown(E,g),O=extractMarkdownLinksFromMarkdown(E,g),k=extractExternalWikiLinksFromMarkdown(E),j=extractExternalMarkdownLinksFromMarkdown(E,g),F=new Set(D.map(e=>e.target)),L=[...D,...O.filter(e=>!F.has(e.target))],B=new Set(k.map(e=>e.url)),H=[...k,...j.filter(e=>!B.has(e.url))],q=new Set,ee=new Map;t.forward.set(g,q),t.externalForward.set(g,ee);for(let e of L){if(!e.target)continue;let s=managedArtifactDocNameFromContentTarget(e.target)??e.target;q.add(s);let S=t.backward.get(s);S||(S=new Map,t.backward.set(s,S)),S.set(g,mergeLinkMeta(S.get(g),{anchor:e.anchor,snippet:e.snippet}))}for(let e of H){if(!e.url)continue;ee.set(e.url,{label:e.label,snippet:e.snippet});let s=t.externalBackward.get(e.url);s||(s=new Map,t.externalBackward.set(e.url,s)),s.set(g,{label:e.label,snippet:e.snippet})}}}this.states.set(e,t),this.mtimesByBranch.set(e,s)}async walkForPaths(e,t){let s;try{s=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[backlinks] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=toPosix(relative(this.contentDir,s));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkForPaths(s,t)}else if(g.isFile()&&isSupportedDocFile(g.name)){let e=toPosix(relative(this.contentDir,s));if(this.contentFilter?.isExcluded(e))continue;t.push({docName:stripDocExtension(e),filePath:s})}}}async reconcileWithDisk(e=this.activeBranch){if(!existsSync(this.contentDir))return{added:0,updated:0,deleted:0};let t=this.mtimesByBranch.get(e)??new Map,s=[];await this.walkForPaths(this.contentDir,s);let g=new Set,S=s.filter(({docName:e})=>g.has(e)?!1:(g.add(e),!0)),w=new Set(S.map(e=>e.docName)),E=new Map,D=0,O=0,k=[],j=await Promise.allSettled(S.map(async({docName:e,filePath:t})=>({docName:e,filePath:t,mtimeMs:(await stat$1(t)).mtimeMs})));for(let e of j){if(e.status===`rejected`)continue;let{docName:s,filePath:g,mtimeMs:S}=e.value,w=t.get(s);if(w!==void 0&&w===S){E.set(s,S);continue}k.push({docName:s,filePath:g,mtimeMs:S,isNew:w===void 0})}let F=50;for(let t=0;t<k.length;t+=50){let s=k.slice(t,t+50),g=await Promise.allSettled(s.map(async({docName:e,filePath:t,mtimeMs:s,isNew:g})=>({docName:e,mtimeMs:s,isNew:g,markdown:await readFile$1(t,`utf-8`)})));for(let t of g){if(t.status===`rejected`){console.warn(`[backlinks] Failed to reconcile file:`,t.reason);continue}let{docName:s,mtimeMs:g,isNew:S,markdown:w}=t.value;this.updateDocumentFromMarkdown(s,w,e),E.set(s,g),S?D++:O++}}let L=0,B=new Set([...t.keys(),...this.getState(e).forward.keys()]);for(let t of B)parseGlobalSkillBundleDoc(t)||w.has(t)||(this.deleteDocument(t,e),L++);return this.mtimesByBranch.set(e,E),{added:D,updated:O,deleted:L}}async ingestGlobalSkillBundles(e,t=this.activeBranch){let s=new Set;for(let g of e){if(!existsSync(g))continue;let e;try{e=await readdir(g,{withFileTypes:!0})}catch(e){console.warn(`[backlinks] Failed to read global skills root ${g}:`,e);continue}for(let S of e){if(!S.isDirectory())continue;let e=S.name,w=join(g,e),E=skillLiveDocName(`global`,e);existsSync(join(w,`SKILL.md`))&&parseGlobalSkillBundleDoc(E)&&(this.registerNodeOnly(E,t),s.add(E));let D=[];await this.walkGlobalSkillReferences(join(w,`references`),e,``,D);for(let{docName:e}of D)this.registerNodeOnly(e,t),s.add(e)}}let g=[];for(let e of this.getState(t).forward.keys())parseGlobalSkillBundleDoc(e)&&!s.has(e)&&g.push(e);for(let e of g)this.deleteDocument(e,t)}async walkGlobalSkillReferences(e,t,s,g){let S;try{S=await readdir(e,{withFileTypes:!0})}catch(t){t?.code!==`ENOENT`&&console.warn(`[backlinks] Failed to read skill references dir ${e}:`,t);return}for(let w of S){let S=s?`${s}/${w.name}`:w.name;if(w.isDirectory())await this.walkGlobalSkillReferences(join(e,w.name),t,S,g);else if(w.isFile()&&isSupportedDocFile(w.name)){let e=stripDocExtension(S);g.push({docName:`${MANAGED_ARTIFACT_PREFIX_SKILL}global/${t}/references/${e}`})}}}};let current,bootStartMono;function startBootTimings(e=new Date().toISOString()){current={startedAt:e},bootStartMono=performance.now()}function bootElapsedMs(){if(bootStartMono!==void 0)return Math.round(performance.now()-bootStartMono)}function recordBootPhase(e,t){current&&(current[e]=t)}function setBootField(e,t){current&&(current[e]=t)}function getBootTimings(){return current}function extractActorIdentity(e,t){let s=normalizeSummary(e.summary);if(s.kind===`invalid`)return{kind:`invalid-summary`};let g=parseAgentBodyFields(e),S=t?.()??null;return g.rawAgentId!==void 0&&g.writerId!==void 0?{kind:`agent`,writerId:g.writerId,displayName:g.displayName,colorSeed:g.colorSeed??g.rawAgentId,clientName:g.clientName,clientVersion:g.clientVersion,label:g.label,actor:{principalId:S?.id,agentType:resolveAgentType(g.clientName),clientName:g.clientName,clientVersion:g.clientVersion,label:g.label},summary:s}:S?{kind:`principal`,writerId:S.id,displayName:S.display_name,colorSeed:S.id,actor:{principalId:S.id},summary:s}:{kind:`anonymous`,summary:s}}const ANCESTOR_WALK_DEPTH_LIMIT$1=30;function isProjectRoot(e){try{return statSync(resolve(e,OK_PROJECT_MARKER)).isFile()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function findEnclosingProjectRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT$1;){let e=!1;try{e=isProjectRoot(t)}catch{e=!1}if(e)return{rootPath:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}function parsePorcelainPaths(e){let t=[];for(let s of e.split(`
855
856
  `)){if(s.length<4)continue;let e=s.slice(3),g=e.indexOf(` -> `),S=g>=0?e.slice(g+4):e;S.length>0&&t.push(S)}return t}function parseDiffPaths(e){return e.split(`
856
- `).map(e=>e.trim()).filter(e=>e.length>0)}async function dirtyFilesOverlapWith(e,t){let{git:s}=createGitInstance(e),[g,S]=await Promise.all([s.raw([`status`,`--porcelain`]),s.raw([`diff`,`--name-only`,`HEAD..${t}`])]),w=new Set(parsePorcelainPaths(g));if(w.size===0)return{conflicts:!1,files:[]};let E=parseDiffPaths(S);if(E.length===0)return{conflicts:!1,files:[]};let D=new Set;for(let e of E)w.has(e)&&D.add(e);return D.size===0?{conflicts:!1,files:[]}:{conflicts:!0,files:Array.from(D).sort()}}function isValidBranchInfoPath(e,t){if(typeof e!=`string`)return!1;if(e.length===0)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t.length===0||t===`..`||t===`.git`)return!1;return!0}async function computeBranchInfo(e,t,s,g){let{git:S}=createGitInstance(e);await S.raw([`rev-parse`,`--git-dir`]);let w=(async()=>{try{let e=(await S.raw([`symbolic-ref`,`HEAD`])).trim(),t=/^refs\/heads\/(.+)$/.exec(e);return{detached:!1,currentBranch:t?t[1]:null,currentHeadSha:null}}catch{let e=(await S.raw([`rev-parse`,`--short=7`,`HEAD`])).trim();return e.length===0?{detached:!1,currentBranch:null,currentHeadSha:null}:{detached:!0,currentBranch:null,currentHeadSha:e}}})(),E=w.then(async e=>{if(g===`folder`&&s===``)return!0;let t=e.detached?`HEAD`:e.currentBranch;if(!t)return!1;try{return await S.raw([`cat-file`,`-e`,`${t}:${s}`]),!0}catch{return!1}}),D=S.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1),O=dirtyFilesOverlapWith(e,t).catch(e=>{if(isBranchResolutionError(e))return{conflicts:!1,files:[]};let s=e instanceof Error?e.message:String(e),g=s.length>500?`${s.slice(0,500)}…`:s;return console.warn(`[git-branch-info] action=dirty-overlap-failed branch=${t} error=${g}`),{conflicts:!1,files:[]}}),[k,j,F,L]=await Promise.all([w,E,D,O]);return k.detached?{detached:!0,currentBranch:null,currentHeadSha:k.currentHeadSha,shareTargetExists:j,dirtyConflicts:L,branchIsLocal:F}:{detached:!1,currentBranch:k.currentBranch,currentHeadSha:null,shareTargetExists:j,dirtyConflicts:L,branchIsLocal:F}}const BRANCH_INFO_HANDLER_TAG=`git-branch-info`;function isBranchResolutionError(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const BRANCH_IN_OTHER_WORKTREE_RE=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function isBranchInOtherWorktreeError(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(BRANCH_IN_OTHER_WORKTREE_RE);if(t===null)return{held:!1};let s=t[1];if(s===void 0||s.length===0)return{held:!1};let g;try{g=realpathSync(s)}catch{g=s}return{held:!0,path:g}}const CHECKOUT_HANDLER_TAG=`git-checkout`,isBranchNotFoundFetchError=isBranchNotFoundGitError;async function runCheckoutFlow(e,t){let{git:s}=createGitInstance(e),g=await s.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1);if(!g)try{await s.raw([`fetch`,`origin`,t])}catch(e){return{ok:!1,reason:isBranchNotFoundFetchError(e)?`branch-not-found`:`fetch-failed`}}let S=await dirtyFilesOverlapWith(e,g?t:`origin/${t}`);if(S.conflicts)return{ok:!1,reason:`dirty-conflict`,files:S.files};try{return await s.raw([`checkout`,t]),{ok:!0}}catch(e){let s=isBranchInOtherWorktreeError(e);if(s.held)return console.warn(`[git-checkout] reason=branch-in-other-worktree branch=${t} held_at=${s.path}`),{ok:!1,reason:`branch-in-other-worktree`,otherWorktreePath:s.path};let g=e instanceof Error?e.message:String(e),S=g.length>500?`${g.slice(0,500)}…`:g;return console.warn(`[git-checkout] action=checkout-failed branch=${t} error=${S}`),{ok:!1,reason:`checkout-failed`}}}const defaultGitConfigReader=(e,t,s)=>{let g=spawnSync(`git`,[`config`,s===`worktree`?`--worktree`:s===`local`?`--local`:`--global`,t],{cwd:e,encoding:`utf-8`,timeout:5e3});return g.status!==0||!g.stdout?null:g.stdout.trim()||null};function isLinkedWorktree(e){let t=spawnSync(`git`,[`rev-parse`,`--git-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||s.status!==0?!1:resolve(e,t.stdout.trim())!==resolve(e,s.stdout.trim())}function ensureWorktreeConfigExtension(e){let t=spawnSync(`git`,[`config`,`--local`,`--get`,`extensions.worktreeConfig`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&/^(true|yes|on|1)$/i.test(t.stdout.trim()))return;let s=spawnSync(`git`,[`config`,`--local`,`extensions.worktreeConfig`,`true`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(s.status!==0){let e=s.stderr?.trim()??``,t=s.error?` [${s.error.message}]`:``;throw Error(`failed to enable extensions.worktreeConfig: ${e}${t}`)}}async function resolveGitIdentity(e,t,s,g=defaultGitConfigReader){let S=g(e,`user.name`,`worktree`),w=g(e,`user.email`,`worktree`);if(S&&w)return{name:S,email:w};let E=g(e,`user.name`,`local`),D=g(e,`user.email`,`local`);if(E&&D)return{name:E,email:D};let O=g(e,`user.name`,`global`),k=g(e,`user.email`,`global`);if(O&&k)return{name:O,email:k};if(t&&s){let e=await t.get(s);if(e){let t=e.name??e.login,s=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:s}}}return null}function writeGitIdentity(e,t,s){let g=`--local`;isLinkedWorktree(e)&&(ensureWorktreeConfigExtension(e),g=`--worktree`);let S=(t,s)=>{let S=spawnSync(`git`,[`config`,g,t,s],{cwd:e,encoding:`utf-8`,timeout:5e3});if(S.status!==0){let e=S.stderr?.trim()??``,s=S.error?` [${S.error.message}]`:``;throw Error(`git config ${g} ${t} failed: ${e}${s}`)}};S(`user.name`,t),S(`user.email`,s)}const CONFIG_FILENAME=`config.yml`;function assertNotSymlink(e,t){let s;try{s=lstatSync(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(s.isSymbolicLink())throw Error(`Refusing to follow symlink at ${t} (${e}). An untrusted upstream may have committed this symlink to redirect writes outside the project. Remove the symlink and re-run.`)}function packageVersionMajorMinor(e){let[t=`0`,s=`0`]=e.split(`.`);return`${t.length>0?t:`0`}.${s.length>0?s:`0`}`}function quoteYamlScalar(e){return/^[A-Za-z0-9._\-/]+$/.test(e)?e:JSON.stringify(e)}function buildConfigYmlContent(e,t){let s=`# yaml-language-server: $schema=https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${CONFIG_SCHEMA_MAJOR_PATH}/config.project.schema.json
857
+ `).map(e=>e.trim()).filter(e=>e.length>0)}async function dirtyFilesOverlapWith(e,t){let{git:s}=createGitInstance(e),[g,S]=await Promise.all([s.raw([`status`,`--porcelain`]),s.raw([`diff`,`--name-only`,`HEAD..${t}`])]),w=new Set(parsePorcelainPaths(g));if(w.size===0)return{conflicts:!1,files:[]};let E=parseDiffPaths(S);if(E.length===0)return{conflicts:!1,files:[]};let D=new Set;for(let e of E)w.has(e)&&D.add(e);return D.size===0?{conflicts:!1,files:[]}:{conflicts:!0,files:Array.from(D).sort()}}function isValidBranchInfoPath(e,t){if(typeof e!=`string`)return!1;if(e.length===0)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t.length===0||t===`..`||t===`.git`)return!1;return!0}async function computeBranchInfo(e,t,s,g){let{git:S}=createGitInstance(e);await S.raw([`rev-parse`,`--git-dir`]);let w=(async()=>{try{let e=(await S.raw([`symbolic-ref`,`HEAD`])).trim(),t=/^refs\/heads\/(.+)$/.exec(e);return{detached:!1,currentBranch:t?t[1]:null,currentHeadSha:null}}catch{let e=(await S.raw([`rev-parse`,`--short=7`,`HEAD`])).trim();return e.length===0?{detached:!1,currentBranch:null,currentHeadSha:null}:{detached:!0,currentBranch:null,currentHeadSha:e}}})(),E=w.then(async e=>{if(g===`folder`&&s===``)return!0;let t=e.detached?`HEAD`:e.currentBranch;if(!t)return!1;try{return await S.raw([`cat-file`,`-e`,`${t}:${s}`]),!0}catch{return!1}}),D=S.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1),O=(async()=>{let e=`origin/${t}`;if(await S.raw([`rev-parse`,`--verify`,e]).then(()=>!0).catch(()=>!1))return g===`folder`&&s===``?!0:S.raw([`cat-file`,`-e`,`${e}:${s}`]).then(()=>!0).catch(()=>!1)})(),k=dirtyFilesOverlapWith(e,t).catch(e=>{if(isBranchResolutionError(e))return{conflicts:!1,files:[]};let s=truncateError(e);return console.warn(`[git-branch-info] action=dirty-overlap-failed branch=${t} error=${s}`),{conflicts:!1,files:[]}}),[j,F,L,B,H]=await Promise.all([w,E,D,k,O]);return j.detached?{detached:!0,currentBranch:null,currentHeadSha:j.currentHeadSha,shareTargetExists:F,dirtyConflicts:B,branchIsLocal:L,shareTargetOnOriginBranch:H}:{detached:!1,currentBranch:j.currentBranch,currentHeadSha:null,shareTargetExists:F,dirtyConflicts:B,branchIsLocal:L,shareTargetOnOriginBranch:H}}const BRANCH_INFO_HANDLER_TAG=`git-branch-info`;function isBranchResolutionError(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const FF_FETCH_TIMEOUT_MS=15e3,BRANCH_IN_OTHER_WORKTREE_RE=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function isBranchInOtherWorktreeError(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(BRANCH_IN_OTHER_WORKTREE_RE);if(t===null)return{held:!1};let s=t[1];if(s===void 0||s.length===0)return{held:!1};let g;try{g=realpathSync(s)}catch{g=s}return{held:!0,path:g}}const CHECKOUT_HANDLER_TAG=`git-checkout`,isBranchNotFoundFetchError=isBranchNotFoundGitError;async function runCheckoutFlow(e,t,s){if(s?.fastForward&&await fastForwardBranchToOrigin(e,t)===`diverged`)return{ok:!1,reason:`ff-diverged`};let{git:g}=createGitInstance(e),S=await g.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1);if(!S)try{await g.raw([`fetch`,`origin`,t])}catch(e){return{ok:!1,reason:isBranchNotFoundFetchError(e)?`branch-not-found`:`fetch-failed`}}let w=await dirtyFilesOverlapWith(e,S?t:`origin/${t}`);if(w.conflicts)return{ok:!1,reason:`dirty-conflict`,files:w.files};try{return await g.raw([`checkout`,t]),{ok:!0}}catch(e){let s=isBranchInOtherWorktreeError(e);if(s.held)return console.warn(`[git-checkout] reason=branch-in-other-worktree branch=${t} held_at=${s.path}`),{ok:!1,reason:`branch-in-other-worktree`,otherWorktreePath:s.path};let g=truncateError(e);return console.warn(`[git-checkout] action=checkout-failed branch=${t} error=${g}`),{ok:!1,reason:`checkout-failed`}}}async function fastForwardBranchToOrigin(e,t){let{git:s}=createGitInstance(e,{timeoutMs:FF_FETCH_TIMEOUT_MS}),g=e=>s.raw([`rev-parse`,`--verify`,e]).then(e=>e.trim()).catch(()=>null);try{await s.raw([`fetch`,`origin`,t])}catch(e){let s=truncateError(e);return console.warn(`[git-checkout] action=ff-fetch-failed branch=${t} error=${s}`),`unavailable`}let S=await g(`refs/remotes/origin/${t}`);if(!S)return`unavailable`;let w=await g(`refs/heads/${t}`);if(!w||w===S)return`up-to-date`;let E=await s.raw([`merge-base`,w,S]).then(e=>e.trim()).catch(()=>``);if(E===w){try{await s.raw([`fetch`,`origin`,`${t}:${t}`])}catch(e){let s=truncateError(e);return console.warn(`[git-checkout] action=ff-advance-failed branch=${t} error=${s}`),`unavailable`}return await g(`refs/heads/${t}`)===S?`advanced`:`unavailable`}return E===S?`up-to-date`:`diverged`}const defaultGitConfigReader=(e,t,s)=>{let g=spawnSync(`git`,[`config`,s===`worktree`?`--worktree`:s===`local`?`--local`:`--global`,t],{cwd:e,encoding:`utf-8`,timeout:5e3});return g.status!==0||!g.stdout?null:g.stdout.trim()||null};function isLinkedWorktree(e){let t=spawnSync(`git`,[`rev-parse`,`--git-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||s.status!==0?!1:resolve(e,t.stdout.trim())!==resolve(e,s.stdout.trim())}function ensureWorktreeConfigExtension(e){let t=spawnSync(`git`,[`config`,`--local`,`--get`,`extensions.worktreeConfig`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&/^(true|yes|on|1)$/i.test(t.stdout.trim()))return;let s=spawnSync(`git`,[`config`,`--local`,`extensions.worktreeConfig`,`true`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(s.status!==0){let e=s.stderr?.trim()??``,t=s.error?` [${s.error.message}]`:``;throw Error(`failed to enable extensions.worktreeConfig: ${e}${t}`)}}async function resolveGitIdentity(e,t,s,g=defaultGitConfigReader){let S=g(e,`user.name`,`worktree`),w=g(e,`user.email`,`worktree`);if(S&&w)return{name:S,email:w};let E=g(e,`user.name`,`local`),D=g(e,`user.email`,`local`);if(E&&D)return{name:E,email:D};let O=g(e,`user.name`,`global`),k=g(e,`user.email`,`global`);if(O&&k)return{name:O,email:k};if(t&&s){let e=await t.get(s);if(e){let t=e.name??e.login,s=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:s}}}return null}function writeGitIdentity(e,t,s){let g=`--local`;isLinkedWorktree(e)&&(ensureWorktreeConfigExtension(e),g=`--worktree`);let S=(t,s)=>{let S=spawnSync(`git`,[`config`,g,t,s],{cwd:e,encoding:`utf-8`,timeout:5e3});if(S.status!==0){let e=S.stderr?.trim()??``,s=S.error?` [${S.error.message}]`:``;throw Error(`git config ${g} ${t} failed: ${e}${s}`)}};S(`user.name`,t),S(`user.email`,s)}const CONFIG_FILENAME=`config.yml`;function assertNotSymlink(e,t){let s;try{s=lstatSync(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(s.isSymbolicLink())throw Error(`Refusing to follow symlink at ${t} (${e}). An untrusted upstream may have committed this symlink to redirect writes outside the project. Remove the symlink and re-run.`)}function packageVersionMajorMinor(e){let[t=`0`,s=`0`]=e.split(`.`);return`${t.length>0?t:`0`}.${s.length>0?s:`0`}`}function quoteYamlScalar(e){return/^[A-Za-z0-9._\-/]+$/.test(e)?e:JSON.stringify(e)}function buildConfigYmlContent(e,t){let s=`# yaml-language-server: $schema=https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${CONFIG_SCHEMA_MAJOR_PATH}/config.project.schema.json
857
858
  # OpenKnowledge — project configuration
858
859
  #
859
860
  # This file overrides built-in defaults for this project. Every key below
@@ -1945,7 +1946,7 @@ Change history for this knowledge base, newest entry first. Add a dated entry (\
1945
1946
  `),S=s.nextFenced+(g?`
1946
1947
  `:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),ce=!0}se=!0},te.origin)})}finally{ge?.touchMode(O,`idle`)}if(oe){let e;switch(oe.kind){case`invalid_value`:e={[oe.key]:oe.reason};break;case`reserved_key`:e={[oe.key]:`'${oe.key}' is reserved`};break;case`unknown_key`:e={[oe.key]:`'${oe.key}' is not a recognized key`};break;case`duplicate_target`:e={[oe.key]:`'${oe.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${oe.expected.join(`, `)}; got: ${oe.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${oe.bytes} > ${oe.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${oe.reason}`};break;case`invalid_path`:e={[oe.path.map(String).join(`.`)||`__path__`]:oe.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(oe)})`}}errorResponse(w,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(se&&ue.length>0){if(recordContributor(D,O,k,j,void 0,Zi({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),xs(ee),ce){let e=await Ut(D);if(e?.kind===`failure`){Wt(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Kt(w,`frontmatter-patch`);return}}Ht(D,`frontmatter-patch`)}me?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),_e?.();let de=Bt(D),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=$t(ne);Fr(D,te.dc.document.getText(`source`).toString());let ye=jr();ye.add(D);let Ce=computeBrokenOutboundLinks(te.dc.document.getText(`source`).toString(),D,ye,Mr);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:de,systemSubscriberCount:fe,appliedKeys:ue,...J?{summary:J}:{},...ve?{warning:ve,warnings:[ve]}:{},brokenLinks:Ce},{handler:`frontmatter-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$6.error({err:e},`[frontmatter-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Ps(e){let t=e.getMap(`lifecycle`),s=t.get(`status`);if(typeof s!=`string`||s.length===0)return null;let g=t.get(`reason`);return{status:s,reason:typeof g==`string`?g:``}}let Is=withValidation(EmptyRequestSchema,async(e,s)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(S)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let w=zt(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`document-read`});return}let E=t.documents.get(w);if(E){successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:E.getText(`source`).toString(),lifecycle:Ps(E)},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(g,`file`,w))){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document not found: ${w}.`,{handler:`document-read`});return}let D=await t.openDirectConnection(w);try{let e=D.document;if(!e){errorResponse(s,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:e.getText(`source`).toString(),lifecycle:Ps(e)},{handler:`document-read`})}finally{await D.disconnect()}}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$6.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=s.searchParams.get(`dir`),E=s.searchParams.get(`showAll`)===`true`,O=s.searchParams.get(`depth`)===`1`?1:1/0;if(S)try{safeSubdir(g,S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(E&&De&&showAllWantsNdjson(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let s=createStreamingErrorWriter(t,`document-list`),w=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let s=()=>{t.off(`drain`,s),t.off(`close`,s),e()};t.once(`drain`,s),t.once(`close`,s)})};try{let t=getShowAllMaxEntries(),s=streamShowAllEntries({contentDir:g,contentFilter:De,dirFilter:S,getDocExtension,maxEntries:t,maxDepth:O,signal:e.signal}),E=0,D=await s.next();for(;!D.done;)await w(`${JSON.stringify(D.value)}\n`),E+=1,D=await s.next();let{truncated:k}=D.value;k&&log$6.info({handler:`document-list`,maxEntries:t,count:E},`[document-list][showAll] stream truncated at entry cap`),await w(`${JSON.stringify({type:`complete`,truncated:k,count:E})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?s(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):log$6.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(E&&De){let e=`showAll:${O===1?`d1:`:``}${S??``}`,s=Ke.get(e);if(!s){let t=new AbortController,w=(async()=>{let e=[],s=getShowAllMaxEntries(),{truncated:w}=await walkContentDirForShowAll({contentDir:g,contentFilter:De,dirFilter:S,documents:e,getDocExtension,maxEntries:s,maxDepth:O,signal:t.signal});return e.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),w&&log$6.info({handler:`document-list`,maxEntries:s,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:w}})();s={promise:w,controller:t,waiters:0};let E=s;Ke.set(e,E),w.finally(()=>{Ke.get(e)===E&&Ke.delete(e)})}let w=s;w.waiters+=1;let E=!1,D=()=>{t.writableEnded||E||(E=!0,--w.waiters,w.waiters<=0&&(w.controller.abort(),Ke.get(e)===w&&Ke.delete(e)))};t.on(`close`,D);try{let{documents:e,truncated:s}=await w.promise;if(E)return;successResponse(t,200,DocumentListSuccessSchema,s?{documents:e,truncated:s}:{documents:e},{handler:`document-list`})}catch(e){if(E)return;errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,D)}return}let k=w(),F=D(),L=j?.()??new Map,H=[];for(let[e,t]of L)S&&!e.startsWith(`${S}/`)&&e!==S||H.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let q=[];try{let e=vt(k);$e?.signature!==e&&($e={signature:e,assets:collectReferencedAssets({contentDir:g,fileIndex:k,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:De?e=>De.isPathIgnored(e):void 0})}),q=$e?.assets??[]}catch(e){$e=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}let ee=new Set;for(let e of q)S&&!e.path.startsWith(`${S}/`)&&e.path!==S||(ee.add(e.path),H.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of F){if(t.kind===`markdown`){if(S&&!e.startsWith(`${S}/`)&&e!==S)continue;let s=getDocExtension(e);H.push({kind:`document`,docName:e,docExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let w of t.aliases){if(S&&!w.startsWith(`${S}/`)&&w!==S)continue;let E=toPosix(relative(g,t.canonicalPath));H.push({kind:`document`,docName:w,docExt:s,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:E})}continue}if((!S||e===S||e.startsWith(`${S}/`))&&!ee.has(e)){let s=synthesizeShowAllAssetExt(e);H.push({kind:`file`,docName:e,path:e,docExt:`.${s}`,assetExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let s of t.aliases){if(!(!S||s===S||s.startsWith(`${S}/`))||ee.has(s))continue;let w=toPosix(relative(g,t.canonicalPath)),E=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${E}`,assetExt:E,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:w})}}let J=B?.()??new Map;if(J.size>0){let e=e=>!S||e===S||e.startsWith(`${S}/`),t=new Map;for(let[e,s]of J){let g=t.get(s);g?g.push(e):t.set(s,[e])}for(let[s,S]of t){let t=L.get(s),w=t?toPosix(relative(g,t.canonicalPath)):s;for(let g of S)e(g)&&H.push({kind:`folder`,path:g,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:s,targetPath:w})}let s=(s,g)=>{for(let S=s.indexOf(`/`);S!==-1;S=s.indexOf(`/`,S+1)){let w=t.get(s.slice(0,S));if(!w)continue;let E=s.slice(S);for(let t of w){let s=`${t}${E}`;e(s)&&g(s)}}};for(let[e,t]of L)s(e,s=>{H.push({kind:`folder`,path:s,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:toPosix(relative(g,t.canonicalPath))})});for(let[e,t]of F)s(e,s=>{let S=toPosix(relative(g,t.canonicalPath));if(t.kind===`markdown`)H.push({kind:`document`,docName:s,docExt:getDocExtension(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S});else{let g=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${g}`,assetExt:g,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S})}})}H.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),successResponse(t,200,DocumentListSuccessSchema,{documents:H},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),$s=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}successResponse(t,200,BacklinksSuccessSchema,{docName:s,backlinks:ue.getBacklinks(s).map(e=>({source:e.source,anchor:e.anchor,title:jt(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),ec=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let g={};for(let e of s.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(g[t]=ue.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:g},{handler:`backlink-counts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),tc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let g=jr();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ue.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Mt(e.target,g),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),nc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`docName`);if(g&&!isSafeDocName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let S=s.searchParams.get(`degrees`);if(S&&!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let w,E;if(S&&g){let e=Number.parseInt(S,10);if(!Number.isFinite(e)||e<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:w,links:E}=ue.getLinkGraphNeighborhood(g,e))}else ({nodes:w,links:E}=ue.getLinkGraph());let D=jr();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=Lt(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Mt(e.docName,D),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:E},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),rc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}successResponse(t,200,OrphansSuccessSchema,{orphans:ue.getOrphans([...w().keys()],s).map(e=>({docName:e,title:jt(e)}))},{handler:`orphans`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),ic=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),g=s?Number.parseInt(s,10):20,S=Number.isFinite(g)&&g>0?g:20,w=jr();successResponse(t,200,HubsSuccessSchema,{hubs:ue.getHubs(S).map(e=>({docName:e.docName,title:Mt(e.docName,w),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),ac=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(s.some(e=>e.length===0||!isSafeDocName(e))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let g=s.length?[...new Set(s.map(e=>zt(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ue.getDeadLinks(jr(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:jt(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),oc=withValidation(AgentPatchRequestSchema,async(S,w,E)=>{try{let{find:S,replace:D,offset:O}=E,k=requireNonEmptyDocName(E.docName,w,`agent-patch`);if(k===null)return;let j=zt(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=Xi(E);if(findLooksLikeFrontmatter(S)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H}),te=reconcileDiskBeforeAgentWrite(t,j,g,e.resolveEmbed),ne=new Date().toISOString(),ae=!1,oe=!1,se=!1,ce;try{let t=iconFromClientName(H),s=AGENT_ICON_COLORS[t]??colorFromSeed(B??F);if(ge?.setPresence(F,{displayName:L,icon:t,color:s,currentDoc:j,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),F,B,H),Y.dc.document.transact(()=>{let{frontmatter:t,body:s}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),g=prependFrontmatter(t,s),w=O==null?g.indexOf(S):g.slice(O,O+S.length)===S?O:-1;if(w===-1){O==null?ae=!0:oe=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":j,findLength:S.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(w<t.length){se=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));ce=applyAgentMarkdownWrite(Y.dc.document,E,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0),Y.dc.document.getMap(`agent-flash`).set(F,{agentId:F,timestamp:Date.now(),type:`insert`,description:`Patched (${L}): ${S.slice(0,50)}`})},Y.origin),ce!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":j,position:`patch`,intendedBytes:ce.intendedBytes,actualBytes:ce.actualBytes,byteDelta:ce.byteDelta,"agent.id":F,"agent.client_name":H})),!ae&&!oe&&!se){let{stored:e}=ka(J);recordContributor(j,F,L,B,void 0,Zi({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),xs(J),recordContentDivergenceGate(`agent-patch`,ce)}}finally{ge?.touchMode(F,`idle`)}if(oe){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(ae){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(se){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let ue=await Ut(j);if(ue?.kind===`failure`){Wt(w,ue.failure,`agent-patch`);return}if(ue?.kind===`divergence`){Kt(w,`agent-patch`);return}Ht(j,`agent-patch`),me?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),_e?.();let de=Bt(j),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=ka(J),ye=Y.dc.document.getText(`source`).toString();Fr(j,ye);let Ce=await validateMermaidFences(ye,j),we=jr();we.add(j);let Te=computeBrokenOutboundLinks(ye,j,we,Mr),De=$t(te),je=ce===void 0?void 0:toContentDivergenceWarning(ce),Me=[...je?[je]:[],...De?[De]:[],...Ce??[]];successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ne,subscriberCount:de,systemSubscriberCount:fe,...ve?{summary:ve}:{},...je?{warning:je}:De?{warning:De}:{},...Me.length>0?{warnings:Me}:{},brokenLinks:Te},{handler:`agent-patch`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-patch`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-patch`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$6.error({err:e},`[agent-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),sc=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=zt(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Xi(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(g,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:L}=S,B=S.scope===`session`||S.scope===`file`?`session`:`last`;if(!s.hasSession(w,L)){errorResponse(g,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let H=await s.getSession(w,L),q=!1;try{let t=iconFromClientName(k),s=AGENT_ICON_COLORS[t]??colorFromSeed(O??E);ge?.setPresence(E,{displayName:D,icon:t,color:s,currentDoc:w,mode:`writing`,ts:Date.now()}),q=applyAgentUndo(H,B,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:w}:void 0),q&&recordContributor(w,L,D,O,void 0,Zi({clientName:k,clientVersion:j,label:F}))}finally{ge?.touchMode(E,`idle`)}if(q){let e=await Ut(w);if(e?.kind===`failure`){Wt(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Kt(g,`agent-undo`);return}Ht(w,`agent-undo`)}me?.setFocus(L,{agentName:L,currentDoc:w,writeKind:`undo`,ts:Date.now()}),successResponse(g,200,AgentUndoSuccessSchema,{docName:w,scope:B,undone:q},{handler:`agent-undo`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(g,e,`agent-undo`);return}log$6.error({err:e},`[agent-undo] handler failed`),errorResponse(g,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),cc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(g===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(s,g),{handler:`agent-activity`})}catch(e){log$6.error({err:e},`[agent-activity] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),lc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=validateAgentId(g.searchParams.get(`agentId`)),w=g.searchParams.get(`docName`),E=g.searchParams.get(`stackIndex`);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!w||w.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let D=zt(w);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!E||Number.isNaN(Number(E))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let O=Number(E);if(!Number.isInteger(O)||O<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let k=s.getLiveSession(D,S);if(!k){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let j=k.um;if(O>=j.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${O} out of range (stack has ${j.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let F=j.undoStack[O];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(F,k.dc.document.getText(`source`),D),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$6.error({err:e},`[agent-burst-diff] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),uc=withValidation(EmptyRequestSchema,async(e,t)=>{try{await J?.(),successResponse(t,200,TestFlushGitSuccessSchema,{},{handler:`test-flush-git`})}catch(e){log$6.error({err:e},`[test-flush-git] flush failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:e})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),dc=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=zt(w.searchParams.get(`docName`)??`test-doc`),D;try{D=safeContentPath(E,g)}catch(e){log$6.error({err:e,docName:E},`[test-reset] safeContentPath rejected docName`),errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await s.closeAll(E),t.closeConnections(E);let O=`onStoreDocument-${E}`;t.debouncer.isDebounced(O)&&await t.debouncer.executeNow(O);let k=t.documents.get(E);if(k&&await(Me??t.unloadDocument.bind(t))(k),writeFileSync(D,``,`utf-8`),ue&&(ue.deleteDocument(E),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${E}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),w.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(g,`.okignore`),s=t.documents.get(CONFIG_DOC_NAME_OKIGNORE);if(s){let e=s.getText(`source`);e.length>0&&s.transact(()=>{e.delete(0,e.length)},CONFIG_VALIDATION_REVERT_ORIGIN)}existsSync(e)&&writeFileSync(e,``,`utf-8`),De&&await De.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}fe?.(`files`),successResponse(S,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),fc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ue.rebuildFromDisk(),await ue.ingestGlobalSkillBundles([resolve(nu,`.ok`,`skills`)]),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),fe?.(`backlinks`),fe?.(`graph`),successResponse(t,200,TestRescanBacklinksSuccessSchema,{},{handler:`test-rescan-backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),pc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!H){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await H(),fe?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),mc=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Xi(s),E=ee?.current;if(!E){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let D=/^[a-zA-Z0-9_-]+$/,O=[],k=!1;if(Array.isArray(s.writers))try{O=s.writers.map(e=>{let t=e.id??`unknown`;if(!D.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let j=oe?.()??`main`;if(O.length===0)if(e!==void 0)O=[{id:g,name:w?`${S} (${w})`:S,email:`${g}@openknowledge.local`}];else{let e=(await enumerateWipChains(E,j)).filter(e=>!e.isPark);O=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[SERVICE_WRITER],k=!0}let F=ce??`.`,L=normalizeSummary(typeof s.summary==`string`?s.summary:void 0),B=await saveVersion(E,F,O,j,L.kind===`value`?L.value:void 0,k?{includeUpstream:!1}:void 0);getLogger(`history`).info({checkpointRef:B.checkpointRef},`checkpoint`);try{await gcRenameLog(E,getOrLoadRenameLogIndex(E.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:B.checkpointRef},{handler:`save-version`})}catch(e){log$6.error({err:e},`[save-version] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),hc=withValidation(EmptyRequestSchema,async(e,t)=>{let s=ee?.current;if(!s){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`docName`)??``,w=g.searchParams.get(`folder`),E=g.searchParams.get(`branch`)??oe?.()??`main`;if(!S&&w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(E.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(w!==null&&!S){let e=Il(w,t,`folder`,`history`);if(!e)return;let S=Number(g.searchParams.get(`limit`)??`50`),D=Math.min(200,Number.isFinite(S)?S:50),O=Number(g.searchParams.get(`offset`)??`0`),k=Math.max(0,Number.isFinite(O)?O:0),j=`folder\0${E}\0${e.folderRel}\0${D}\0${k}`,{promise:F,coalesced:L}=Xe.run(j,()=>getFolderTimeline(s,e.folderRel,ce??`.`,{branch:E,limit:D,offset:k}));L&&recordTimelineCoalesced(`folder`),successResponse(t,200,HistorySuccessSchema,{...await F},{handler:`history`});return}let D=ce??`.`,O=safeDocPath(S,D);if(`error`in O){errorResponse(t,400,`urn:ok:error:invalid-request`,O.error,{handler:`history`});return}let k=Number(g.searchParams.get(`limit`)??`50`),j=Number(g.searchParams.get(`offset`)??`0`),F=Math.min(200,Number.isFinite(k)?k:50),L=Number.isFinite(j)?j:0,B=g.searchParams.get(`type`)??void 0,H=g.searchParams.get(`author`)??void 0,q=g.searchParams.get(`excludeAuthor`)??void 0,J=g.searchParams.get(`includeAutoCheckpoints`)===`true`,Y=`doc\0${E}\0${S}\0${F}\0${L}\0${B??``}\0${H??``}\0${q??``}\0${J?`1`:`0`}`,te=Date.now();try{let{promise:e,coalesced:g}=Xe.run(Y,()=>getDocumentHistory(s,{docName:S,branch:E,limit:F,offset:L,type:B,author:H,excludeAuthor:q,includeAutoCheckpoints:J},D));g&&recordTimelineCoalesced(`doc`);let w=await e,O=Date.now()-te;getLogger(`timeline`).info({docName:S,entries:w.entries.length,durationMs:O},`query`),successResponse(t,200,HistorySuccessSchema,{...w},{handler:`history`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function gc(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let g=ee?.current;if(!g){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,w=ce??`.`,E=safeDocPath(S,w);if(`error`in E){errorResponse(t,400,`urn:ok:error:invalid-request`,E.error,{handler:`history-version`});return}let D=shadowGit(g),O=oe?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await resolveDocPathAtCommit(g,S,s,O,getOrLoadRenameLogIndex(g.gitDir),e=>{let t=safeDocPath(e,w);return`error`in t?`${e}.md`:t.path},createAncestorShaSetCache());if(e===null){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let E=await D.raw(`show`,`${s}:${e}`),[k=``,j=``]=(await D.raw(`log`,`-1`,`--format=%aI%x00%an`,s)).trim().split(`\0`);successResponse(t,200,HistoryVersionSuccessSchema,{sha:s,content:E,timestamp:k,author:j},{handler:`history-version`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let _c=withValidation(RollbackRequestSchema,async(s,g,S)=>{let w=extractActorIdentity(S,we);if(w.kind===`invalid-summary`){errorResponse(g,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let E=t.documents.get(S.docName);if(E&&isDocInConflict(E)){respondDocInConflict(g,new DocInConflictError({file:`${S.docName}${getDocExtension(S.docName)}`}),`rollback`);return}let D=ee?.current;if(!D){errorResponse(g,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:O,commitSha:k}=S,j=ce??`.`,F=safeDocPath(O,j);if(`error`in F){errorResponse(g,400,`urn:ok:error:invalid-request`,F.error,{handler:`rollback`});return}let L=shadowGit(D),B=Date.now();try{let s=getOrLoadRenameLogIndex(D.gitDir),S=createAncestorShaSetCache(),E=await resolveDocPathAtCommit(D,O,k,oe?.()??`main`,s,e=>{let t=safeDocPath(e,j);return`error`in t?`${e}.md`:t.path},S);if(E===null){errorResponse(g,404,`urn:ok:error:doc-not-found`,`Commit ${k.slice(0,7)} does not contain document ${O} at any known historical path.`,{handler:`rollback`});return}let F=await L.raw(`show`,`${k}:${E}`),H=new Date().toISOString();await safetyCheckpoint(D,j,{action:`rollback`,context:{docName:O,targetSha:k}});let q=t.documents.get(O);if(!q){errorResponse(g,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let ee=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0,J;q.transact(()=>{replaceRawBody(q,F,ee),J=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),J!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:J.intendedBytes,actualBytes:J.actualBytes,byteDelta:J.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,J);let Y;switch(w.kind){case`agent`:{let e=k.slice(0,8),t=w.summary.kind===`value`,s=t?w.summary:normalizeSummary(`Restored to ${e}`),g=ka(s);Y=t||!g.response?g.response:_s(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),xs(s,!t);break}case`principal`:{let e=ka(w.summary);Y=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),xs(w.summary,!1);break}case`anonymous`:log$6.debug({docName:O,commitSha:k.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(w.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:w.kind});let te=await Ut(O);if(te?.kind===`failure`){Wt(g,te.failure,`rollback`);return}if(te?.kind===`divergence`){Kt(g,`rollback`);return}Ht(O,`rollback`);let ne=Date.now()-B;getLogger(`rollback`).info({docName:O,from:k.slice(0,8),durationMs:ne},`rollback`),w.kind===`agent`&&me?.setFocus(w.writerId,{agentName:w.displayName,currentDoc:O,writeKind:`rollback-apply`,ts:Date.now()});let ae=J===void 0?void 0:toContentDivergenceWarning(J);successResponse(g,200,RollbackSuccessSchema,{restoredFrom:k,timestamp:H,...Y?{summary:Y}:{},...ae?{warning:ae,warnings:[ae]}:{}},{handler:`rollback`})}catch(e){errorResponse(g,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),vc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$6.error({err:e},`[metrics-reconciliation] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),yc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$6.error({err:e},`[metrics-parse-health] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),bc=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$6.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=se?.(),g=getBootTimings();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s},...g===void 0?{}:{boot:g}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function xc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let s=we?.()??null;if(!s){errorResponse(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}successResponse(t,200,PrincipalSuccessSchema,s,{handler:`principal`})}async function Sc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=ge?.getPresenceMap()??{},s=Date.now(),g={};for(let[t,S]of Object.entries(e))s-S.ts<2e4&&(g[t]=S);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:g},{handler:`metrics-agent-presence`})}catch(e){log$6.error({err:e},`[metrics-agent-presence] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function Cc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let s=embedProbeRing.read();successResponse(t,200,EmbedDetectSuccessSchema,{entries:s,count:s.length,detection:deriveDetection(s[0])},{handler:`embed-detect`})}async function wc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let s=resolve(g),S=s,w=!0;try{S=realpathSync(s)}catch(e){let g=e?.code;if(g===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:s}),w=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:s,err:e}),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:g??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:S,pathSeparator:sep,symlinkResolved:w},{handler:`workspace`})}let Tc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let S=assetContentTypeForPath(s),w=extname(s).slice(1).toLowerCase();if(!S||!ASSET_EXTENSIONS.has(w)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let E=realpathSync(g),D=resolve(E,s),O;try{O=realpathSync(D)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(O,E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let k;try{k=statSync(O)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!k.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let j=toContentRelativePath(E,O);if(j!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(De?.isPathIgnored(j)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let F=SANDBOXED_HTML_EXTENSIONS.has(w),L={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)||F?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`?L[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:F&&(L[`Content-Security-Policy`]=SANDBOXED_HTML_CSP),t.writeHead(200,L);try{await pipeline(createReadStream(O),t)}catch(e){log$6.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:s,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),Ec=1048576,Dc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let S=realpathSync(g),w=resolve(S,s),E;try{E=realpathSync(w)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!isWithinContentDir(E,S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let D;try{D=statSync(E)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!D.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(toContentRelativePath(S,E)!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(D.size>Ec){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${Ec}-byte text-viewer cap.`,{handler:`asset-text`});return}let O=(await readFile$1(E)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(O)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),Oc=1440*60*1e3,kc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ee?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),s=[],g=resolve(ee.current.gitDir,`rescue`);if(existsSync(g))try{let t=readdirSync(g).filter(e=>isSupportedDocFile(e));for(let S of t){let t=resolve(g,S),w=statSync(t);if(e-w.mtimeMs>864e5){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}s.push({docName:stripDocExtension(S),timestamp:w.mtime.toISOString(),size:w.size,source:`flat`})}}catch(e){log$6.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=oe?.()??`main`,t=await listRescueCheckpoints(ee.current,e);for(let e of t)s.push({...e,source:`timeline`})}catch(e){log$6.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}successResponse(t,200,RescueListSuccessSchema,s,{handler:`rescue-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),Ac=withValidation(CreatePageRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let S=s.path;if(!isSupportedDocFile(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(S.includes(`..`)||S.startsWith(`/`)||S.includes(`\0`)||S.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let w=resolve(g),E=resolve(w,S);if(!isWithinDir(E,w)){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let D=stripDocExtension(S);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`});return}if(S.split(`/`)[0]===`.ok`||isManagedArtifactDocName(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page under .ok/ — skills and templates are authored through their own validating flows.`});return}let k=typeof s.template==`string`?s.template.trim():``,j=``,F;if(k.length>0){if(!/^[A-Za-z0-9_-]+$/.test(k)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let s=S.includes(`/`)?S.slice(0,S.lastIndexOf(`/`)):``,g=resolveTemplatesAvailable(w,s),E=g.find(e=>e.name===k);if(!E){let e=g.length===0?`(none)`:g.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${k}" does not resolve for folder "${s||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let D=resolve(w,E.path),O;try{O=readFileSync(D,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${E.path}.`,{handler:`create-page`,cause:e});return}let L=instantiateDoc(O),B=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;j=applySubstitution(L,{date:todayIsoUtc(),user:B}),F=E.scope}mkdirSync(dirname(E),{recursive:!0});try{writeFileSync(E,j,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let L=stripDocExtension(S);switch(Ie?.delete(L),De&&De.incrementMdDir(dirname(L)),registerWrite(E,contentHash(j)),e.kind){case`agent`:case`principal`:recordContributor(L,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}O?.({kind:`create`,path:E,docName:L,content:j}),ue&&(ue.updateDocumentFromMarkdown(L,j),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${L}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),F!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:k,templateScope:F,docName:L})),successResponse(t,200,CreatePageSuccessSchema,{docName:L},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),jc=withValidation(CreateFolderRequestSchema,async(e,t,s)=>{try{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=s.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(De?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let S=resolveContentEntryPath(g,`folder`,e);if(existsSync(S)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(S,{recursive:!0}),it(e),fe?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),Mc=withValidation(DuplicatePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:w}=S,E=w===`file`?stripDocExtension(S.path):S.path;if(!isValidRelativeContentPath(E)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||w===`file`&&(isSystemDoc(E)||isConfigDoc(E))||w===`folder`&&isReservedSyntheticFolderPath(E)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}w===`file`&&probeAndRegisterSourceFileExtension(g,E);let D=resolveContentEntryPath(g,w,E);if(!existsSync(D)){if(w===`file`){let e=resolveContentEntryPath(g,`folder`,E);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}}errorResponse(s,404,`urn:ok:error:doc-not-found`,`${w} does not exist.`,{handler:`duplicate-path`});return}let k=statSync(D);if(w===`file`&&!k.isFile()||w===`folder`&&!k.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}let j=w===`file`?[E]:Hi(resolveContentEntryPath(g,`folder`,E)),F=ve?.(),L=new Set(F?F.getConflicts().map(e=>e.file):[]);for(let e of j){let g=stripDocExtension(e),S=t.documents.get(g),w=`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),D=L.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let B,H=[];if(w===`file`){let e=extname(D);if(B=nextAvailableDuplicateDocName(g,E).docName,isSystemDoc(B)||isConfigDoc(B)||De?.isExcluded(`${B}${e}`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let t=resolveDuplicateDocPath(g,B,e),S=readFileSync(D,`utf-8`),w=dirname(t),k=existsSync(w);try{tracedMkdirSync(w,{recursive:!0}),tracedWriteFileSync(t,S,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!k)try{tracedRmdirSync(w)}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTEMPTY`&&console.warn(`[duplicate-path] failed to clean duplicate parent directory:`,{destinationDir:w,err:e})}throw e}let j=!1;try{registerDocExtension(B,e),Ie?.delete(B),De&&(De.incrementMdDir(dirname(B)),j=!0),registerWrite(t,contentHash(S)),O?.({kind:`create`,path:t,docName:B,content:S}),ue?.updateDocumentFromMarkdown(B,S),H=[B]}catch(e){try{tracedRmSync(t,{force:!0})}catch(e){console.warn(`[duplicate-path] failed to clean partial file duplicate:`,{destinationPath:t,err:e})}throw forgetDocExtension(B),De&&j&&De.decrementMdDir(dirname(B)),O?.({kind:`delete`,path:t,docName:B}),e}}else{if(B=nextAvailableDuplicateFolderPath(g,E).folderPath,De?.isDirExcluded(B)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=resolveContentEntryPath(g,`folder`,B);try{tracedCpSync(D,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of collectFolderPaths(g,B))it(e);let e=collectMarkdownCopies(g,B);H=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(t.docName,e),Ie?.delete(t.docName),De&&De.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),O?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),ue?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{tracedRmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[duplicate-path] failed to clean partial folder duplicate:`,{destinationPath:e,err:t})}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of H)recordContributor(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}ue&&H.length>0&&(ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),successResponse(s,200,DuplicatePathSuccessSchema,{kind:w,path:B,duplicatedDocNames:H},{handler:`duplicate-path`})}catch(e){if(e instanceof DuplicateNameExhaustedError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=classifyDuplicatePathFilesystemProblem(e);if(t){errorResponse(s,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),Nc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s||s.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let g=Dt(s);if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(g)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:s,headings:extractHeadings(readFileSync(g,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),Pc=withValidation(RenamePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:w,fromPath:E,toPath:D}=S;if(!isValidRelativeContentPath(E)||!isValidRelativeContentPath(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(w===`file`&&(isSystemDoc(E)||isSystemDoc(D)||isConfigDoc(E)||isConfigDoc(D))){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||D===`.ok`||D.startsWith(`.ok/`)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(E===D){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let O=w===`asset`&&isSupportedDocFile(E)&&isSupportedDocFile(D)?`file`:w;if(O===`asset`){let t;try{t=isSupportedDocFile(E)&&!isSupportedDocFile(D)?await Ki(E,D):await Gi(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=Br(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&Tt();let g;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let s=`Renamed asset ${E} → ${D}`;g=Cs(e,s,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:s})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$6.debug({kind:`asset`,fromPath:E,toPath:D,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(renameAttributionCounter().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...g?{summary:g}:{}},{handler:`rename-path`});return}let k=O===`file`?[stripDocExtension(E)]:Hi(resolveContentEntryPath(g,`folder`,E)),j=ve?.(),F=new Set(j?j.getConflicts().map(e=>e.file):[]);for(let e of k){let g=stripDocExtension(e),S=t.documents.get(g),w=O===`file`?E:`${g}${getDocExtension(e)}`,D=S!==void 0&&isDocInConflict(S),k=F.has(w);if(D||k){respondDocInConflict(s,new DocInConflictError({file:w}),`rename-path`);return}}if(O===`file`&&probeAndRegisterSourceFileExtension(g,E),De&&(O===`file`?De.isExcluded(isSupportedDocFile(D)?D:`${D}${getDocExtension(E)}`):De.isDirExcluded(D))){errorResponse(s,400,`urn:ok:error:invalid-request`,`Destination ${O===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}let L=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,B;try{B=await Yi(E,D,O,L?{actor:L}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,zr(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(B.renamed.length===0&&B.renamedAssets.length===0){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}B.renamedAssets.length>0&&Tt();let H,q=B.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(q.length>0&&(H=Cs(e,`Renamed ${E} → ${D}`,q.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$6.debug({kind:w,fromPath:E,toPath:D,affectedDocs:B.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${O}`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:B.renamed,renamedAssets:B.renamedAssets,rewrittenDocs:B.rewrittenDocs,...H?{summary:H}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:g,error:S}=Br(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Fc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Xi(S);let{kind:e,path:w}=S;if(!isValidRelativeContentPath(w)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let E=e===`asset`?ji(w):{path:w,ambiguous:!1};if(E.ambiguous){errorResponse(s,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let D=E.path,k=e===`asset`&&isSupportedDocFile(D)?`file`:e;if(k===`file`&&probeAndRegisterSourceFileExtension(g,D),k===`asset`&&isReservedProjectStatePath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let j=k===`asset`?resolveContentEntryPath(g,`folder`,D):resolveContentEntryPath(g,k,D);if(!existsSync(j)){errorResponse(s,404,`urn:ok:error:doc-not-found`,`${k} does not exist.`,{handler:`delete-path`});return}let F=statSync(j);if(k===`file`&&!F.isFile()||k===`asset`&&!F.isFile()||k===`folder`&&!F.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${k}.`,{handler:`delete-path`});return}let L=k===`asset`?[]:k===`file`?[stripDocExtension(D)]:Hi(resolveContentEntryPath(g,`folder`,D)),B=ve?.(),H=new Set(B?B.getConflicts().map(e=>e.file):[]);for(let e of L){let g=stripDocExtension(e),S=t.documents.get(g),w=k===`file`&&isSupportedDocFile(D)?D:`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),O=H.has(w);if(E||O){respondDocInConflict(s,new DocInConflictError({file:w}),`delete-path`);return}}if(await Vr(L),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));k===`file`||k===`asset`?tracedUnlinkSync(j):(tracedRmSync(j,{recursive:!0,force:!1}),at(D)),Tt();for(let e of L)O?.({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e});fe?.(`files`),successResponse(s,200,DeletePathSuccessSchema,{deletedDocNames:L},{handler:`delete-path`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Ic=withValidation(TrashCleanupRequestSchema,async(e,t,s)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":s.kind,"ok.cleanup.path":normalizeFsPath(s.path),"ok.cleanup.path.role":classifyFsPath(s.path)}},async()=>{try{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:S}=s;if(!isValidRelativeContentPath(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let E=e===`asset`&&isSupportedDocFile(S)?`file`:e,D=stripDocExtension(S);E===`file`&&probeAndRegisterSourceFileExtension(g,S);let k=E===`folder`&&isReservedSyntheticFolderPath(S),j=E===`asset`&&isReservedProjectStatePath(S);if(E===`file`&&(isSystemDoc(D)||isConfigDoc(D))||k||j){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${S}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(E===`asset`){Tt(),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let F=w(),L=E===`file`?F.has(D)?[D]:[]:listAffectedDocNames(F,E,S);if(Tt(),L.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Vr(L),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of L)O?.({kind:`delete`,path:resolve(g,`${e}${getDocExtension(e)}`),docName:e});E===`folder`&&at(S),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:L},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Lc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=w(),s=[];for(let[t,S]of e){let e=getDocExtension(t),w,E;if(S.title!==void 0)w=S.title,E=S.icon;else{w=t;try{let s=readFileSync(resolve(g,`${t}${e}`),`utf-8`);w=extractPageTitle(s,t),E=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}}s.push({docName:t,title:w,docExt:e,size:S.size,modified:S.modified,icon:E})}s.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:s},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),Rc=withValidation(EmptyRequestSchema,async(e,s)=>{try{let g=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!g){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(g)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(g)||isConfigDoc(g)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${g}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(s,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:w(),docName:g}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function zc(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let s;try{s=await readUploadBody(e,Ce??g)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:S,tempPath:w,sha:D,byteLength:O,parentDocName:k,placement:j}=s,F=()=>{if(existsSync(w))try{unlinkSync(w)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:k,placement:j||void 0},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B,placement:H}=L.value,{agentId:q,agentName:ee}=Xi(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(O===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(g),Y;try{Y=H===`parent-dir`?`./`:E?.()??`./`}catch(e){F(),log$6.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!isValidAttachmentFolderPath(Y)){F(),errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let te=resolveUploadDestDir(B,normalizeAttachmentFolderPath(Y),J);if(!isWithinContentDir(te,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(te,J)}catch(e){if(F(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$6.error({err:e,destDir:te},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(te,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){F();let s=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(s),s,uploadTitleFor(s),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(te),s;try{s=realpathSync(J)}catch{s=J}if(!isWithinContentDir(e,s)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ne=readTempFileHead(w,4100),ae=await fileTypeFromBuffer(ne),oe=ae?.mime,se=ae?.ext;if(!oe){let e=ne.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(oe=`image/svg+xml`,se=`svg`)}{let s=await findDuplicateAsset(te,D,O);if(s){F();let S=toPosix(relative(g,resolve(te,s)));log$6.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!0,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!0},{handler:`upload-asset`});return}}let ce;if(!S||S===`upload`||GENERIC_PASTE_NAMES.test(S)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=S?extname(S).slice(1):``,s=se??t??``;ce=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else ce=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,te,ce),S=toPosix(relative(g,resolve(te,s)));log$6.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!1,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!1},{handler:`upload-asset`})}catch(s){let g=s instanceof UploadWriteError?s.reason:`urn:ok:error:storage-error`;log$6.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,filename:ce,size:O,reason:g,httpStatus:uploadStatusFor(g),err:s},`[upload] write failed`),errorResponse(t,uploadStatusFor(g),g,uploadTitleFor(g),{handler:`upload-asset`,cause:s})}}let Bc=`/api/local-op/clone`,Vc=`/api/local-op/ok-init`,Hc=600*1e3,Uc=45e3,Wc=`local-op-clone`,Gc=withValidation(LocalOpCloneRequestSchema,Kc,{handler:Wc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Wc})});async function Kc(e,t,s){let{url:g,dir:S,branch:w}=s;if(!isAllowedGitUrl(g)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:Wc,cause:Error(`url=${g}`)});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:Wc,cause:Error(`dir=${S}`)});return}if(!Ge.tryAcquire(Bc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Wc,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,Wc),D=null,O=runCloneSubprocess({cliArgs:ye,url:g,dir:S,branch:w,timeoutMs:Hc,onEvent:e=>{if(e.type===`complete`){D=e.dir;return}if(e.type===`error`){e.message&&log$6.warn({stderr:redactShareSubprocessStderr(e.message),url:g,dir:S},`[local-op/clone] clone failed`);let t=classifyCloneError(e.message??``);E(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(redactShareSubprocessStderr(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await O.done,D&&!t.writableEnded&&!t.destroyed){let e=await qc(D);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:D})}\n`):E(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?E(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$6.error({err:e,handler:Wc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ge.release(Bc)}})(),t.on(`close`,()=>{O.cancel()})}async function qc(e,t){let s=resolve(expandTilde(e)),g=getLocalDir(s),S=readUiLock(g);if(S&&S.port>0)return{port:S.port};let[w,...E]=ye,D=e=>{let s=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...E,e,...s]},O=async e=>{let t=spawn(w,D(e),{cwd:s,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),S=[];t.stderr?.on(`data`,t=>{S.push(t),log$6.warn({cwd:s,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/clone] child stderr`)});let E=null,O=null,k=null;t.on(`exit`,(e,t)=>{E=e??-1,O=t??null}),t.on(`error`,t=>{k=t.message,E=-1,log$6.error({cwd:s,cliCmd:e,err:t.message},`[local-op/clone] failed to spawn child`)}),t.unref();let j=Date.now()+45e3;for(;Date.now()<j;){await setTimeout$1(500);let t=readUiLock(g);if(t&&t.port>0)return{port:t.port};if(E!==null){let t=Buffer.concat(S).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${k?`spawn failed: ${k}`:O?`killed by ${O}`:`code ${E}`})${t?` — ${t}`:``}`,exited:!0}}}let F=Buffer.concat(S).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${F?` — ${F}`:``}`,exited:!1}},k=readServerLock(g),j=k&&k.port>0?`ui`:`start`,F=await O(j);if(j===`start`&&`error`in F&&F.exited){let e=readServerLock(g);if(e&&e.port>0){let e=await O(`ui`);return`port`in e?e:{error:`${F.error}; connect fallback failed: ${e.error}`}}}return`port`in F?F:{error:F.error}}let Jc=`local-op-ok-init`,Yc=withValidation(LocalOpOkInitRequestSchema,async(e,t,s)=>{let{projectPath:g}=s;if(!isAbsolute(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:Jc,cause:Error(`projectPath=${g}`)});return}let S;try{S=realpathSync(g)}catch(e){successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:Jc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Jc,cause:Error(`projectPath=${g}`)});return}let w=resolveGitDirDetailed(S).kind;if(w!==`directory`&&w!==`linked`){console.warn(`[ok-init] action=init project=${basename(S)} result=not-a-git-worktree kind=${w}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${w}).`},{handler:Jc});return}if(isProjectRoot(S)){console.warn(`[ok-init] action=init project=${basename(S)} result=already-initialized`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Jc});return}if(!Ge.tryAcquire(Vc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Jc,extraHeaders:{"Retry-After":`2`}});return}try{await withParentLock(async()=>{initContent(S)}),console.warn(`[ok-init] action=init project=${basename(S)} result=success`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Jc})}catch(e){let s=e instanceof Error?e.message:String(e);console.warn(`[ok-init] action=init project=${basename(S)} result=failed reason=${s}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`init-failed`,message:s},{handler:Jc})}finally{Ge.release(Vc)}},{handler:Jc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Jc})}),Xc=`/api/local-op/auth/login`,Zc=`/api/local-op/auth/status`,Qc=`/api/local-op/auth/repos`,$c=`/api/local-op/auth/signout`,nl=null,il=`local-op-auth-login`,al=withValidation(LocalOpAuthHostRequestSchema,cl,{handler:il,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:il})});async function cl(e,t,s){let g=s.host??`github.com`;if(!Ge.tryAcquire(Xc)){let e=nl;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-login-slot-no-controller`,channel:`auth`,transport:`http`})),errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:il,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),nl=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,il),w=runDeviceFlowSubprocess({cliArgs:ye,host:g,timeoutMs:Hc,onEvent:e=>{if(e.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(resumeSyncOnAuthEvent(e,ve),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});nl=w;let E=()=>{w.cancel(),nl===w&&(nl=null,Ge.release(Xc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}nl===w&&(nl=null,Ge.release(Xc))})}let ll=`local-op-auth-status`,ul=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire(Zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:ll,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`status`,`--json`,`--host`,g],w=(await new Promise((t,s)=>{let g=spawn(e,S,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,g.kill(`SIGTERM`)},3e4),D=[];g.stdout.on(`data`,e=>D.push(e)),g.on(`close`,()=>{if(clearTimeout(E),w){s(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(D).toString(`utf-8`))}),g.on(`error`,e=>{clearTimeout(E),s(e)})})).split(`
1947
1948
  `).map(e=>e.trim()).filter(Boolean),E=null;for(let e=w.length-1;e>=0;e--)try{E=JSON.parse(w[e]);break}catch{}E===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:ll}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,E,{handler:ll})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:ll,cause:e})}finally{Ge.release(Zc)}},{handler:ll,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ll})}),dl=`local-op-auth-repos`,fl=withValidation(LocalOpAuthHostRequestSchema,pl,{handler:dl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:dl})});async function pl(e,t,s){let g=s.host??`github.com`;if(!Ge.tryAcquire(Qc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:dl,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,dl),[w,...E]=ye,D=[...E,`auth`,`repos`,`--json`,`--host`,g],O=!1,k=``,j=spawn(w,D,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),F=setTimeout(()=>{j.kill(`SIGTERM`)},Hc);j.stdout.on(`data`,e=>{k+=e.toString(`utf-8`);let s=k.split(`
1948
- `);k=s.pop()??``;for(let e of s){if(!e.trim())continue;let s=null;try{s=JSON.parse(e)}catch{}if(s&&s.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof s.message==`string`?s.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),j.stderr.on(`data`,e=>{log$6.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),j.on(`close`,e=>{clearTimeout(F),O||(O=!0,e!==0&&!t.writableEnded&&S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Ge.release(Qc))}),j.on(`error`,e=>{clearTimeout(F),O||(O=!0,t.writableEnded||(S(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),Ge.release(Qc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Ge.release(Qc))})}let ml=`local-op-auth-signout`,hl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire($c)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:ml,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`signout`,`--host`,g];await new Promise((t,s)=>{let g=spawn(e,S,{stdio:`ignore`,env:{...process.env}}),w=setTimeout(()=>{g.kill(`SIGTERM`)},3e4);g.on(`close`,()=>{clearTimeout(w),t()}),g.on(`error`,e=>{clearTimeout(w),s(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:ml})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:ml,cause:e})}finally{Ge.release($c)}},{handler:ml,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ml})}),gl=`/api/local-op/auth/set-identity`,_l=`local-op-auth-set-identity`,vl=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!Ce){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:_l});return}if(!Ge.tryAcquire(gl)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:_l,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(Ce,g,S),ve?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:_l})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:_l,cause:e})}finally{Ge.release(gl)}},{handler:_l,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:_l})});async function yl(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let xl=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let S=s.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:S},{handler:`sync-trigger`}),g.trigger(S)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Cl(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Tl=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:S,strategy:w,content:E}=s;try{await g.resolveConflict(S,w,E),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function El(e,s){if(!checkLocalOpSecurity(e,s,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(s,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!Ce){errorResponse(s,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`file`);if(!S){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=stripDocExtension(S),E=t.documents.get(w)?.getMap(`lifecycle`).get(`status`)===`conflict`,D=ve?.(),O=D?D.getConflicts().some(e=>e.file===S):!1;if(!E&&!O){errorResponse(s,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:S}});return}let k=g.searchParams.get(`source`),j=esm_default({baseDir:Ce,timeout:{block:15e3}});async function F(e){try{return{present:!0,content:await j.raw([`show`,`:${e}:${S}`])}}catch(t){let s=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(s))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:S,detail:s,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,g,w]=await Promise.all([F(1),F(2),F(3)]),E=e.present?e.content:``,D=w.present?w.content:``,O=g.present&&w.present?`both-modified`:!g.present&&w.present?`delete-modify`:g.present&&!w.present?`modify-delete`:`both-modified`,j=g.present?g.content:``,L=null;if(k===`ytext`){let e=stripDocExtension(S),s=t.documents.get(e);if(s){let t=s.getMap(`lifecycle`).get(`status`);if(L=typeof t==`string`&&t.length>0?t:null,O!==`delete-modify`){let t=Re?Re(e):null;t!==null&&!ytextHasConflictMarkers(t)?j=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(s,200,SyncConflictContentSuccessSchema,{file:S,base:E,ours:j,theirs:D,kind:O,lifecycleStatus:L},{handler:`sync-conflict-content`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Dl(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let s=new URL(e.url??`/`,`http://localhost`),S=s.searchParams.get(`rootDir`)??void 0,w=s.searchParams.get(`packId`),E=coercePackId(w);if(w!==null&&w!==``&&E===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${w}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:g,rootDir:S,packId:E})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Ol=withValidation(SeedApplyRequestSchema,async(e,t,s)=>{let S=s.plan;if(!S||typeof S!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let w=S,E=s.packId,D=coercePackId(E);if(typeof E==`string`&&E.length>0&&D===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${E}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(w,{projectDir:g,packId:D})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function kl(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let jl=withValidation(InstallSkillRequestSchema,async(e,t,s)=>{if(s.out!==void 0&&!isSafeLocalPath(s.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...s.noOpen===void 0?{}:{noOpen:s.noOpen},...s.out===void 0?{}:{out:s.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function Ml(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Et.probeAll)}catch(e){t.headersSent||(log$6.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}let Pl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:de.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Fl(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let g;try{g=decodeURIComponent(s)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=de.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:jt(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:g,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function Il(e,t,s=`path`,S=`folder-config`){let w=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(w.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${s}: must be project-root-relative.`,{handler:S}),null;let E=resolve(g),D=w===``?E:resolve(E,w);return D!==E&&!D.startsWith(`${E}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:S}),null):{folderRel:w,resolvedContentDir:E}}let Ll=/^[A-Za-z0-9_-]+$/;function Rl(e,t,s=`template`){return!e||!Ll.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:s}),!1):!0}function zl(e,t,s){let g=t===``?[]:t.split(`/`);for(let t=g.length;t>=0;t--){let S=t===0?``:g.slice(0,t).join(`/`),w=S===``?e:resolve(e,S);if(w!==e&&!w.startsWith(`${e}${sep}`))continue;let E=resolve(w,`.ok`,`templates`,`${s}.md`);if(existsSync(E))return{abs:E,folder:S,scope:t===g.length?`local`:`inherited`}}return null}function Bl(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[s,g]of Object.entries(e))g!==void 0&&(t[s]=g);return t}async function Vl(e,t){if(e.method===`GET`)return Hl(e,t);if(e.method===`PUT`)return Ul(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Hl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=Il(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!s)return;let g=await enrichDirectory(s.folderRel,{projectDir:s.resolvedContentDir}),S=resolve(resolve(s.resolvedContentDir,s.folderRel,`.ok`),`frontmatter.yml`),w=null;if(existsSync(S))try{let e=(0,import_dist$1.parse)(await readFile$1(S,`utf-8`));w=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${S}: ${t}`),w=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:g,frontmatter_local:w},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),Ul=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let g=Il(s.path,t,`path`,`folder-config-put`);if(!g)return;let S=[];if(s.frontmatter!==void 0){let w=applyFolderFrontmatterPatch({anchorDir:g.resolvedContentDir,folderRel:g.folderRel,patch:s.frontmatter});if(!w.ok){let e=w.error.code===`WRITE_ERROR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:w.error.message,{handler:`folder-config-put`,detail:w.error.code,cause:Error(w.error.message)});return}S.push({path:w.path,action:w.action}),w.action!==`noop`&&(Ds(e,Ts(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Os(`folder-config-put`))}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:S},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function Wl(e,s,g,S){if(!s)return!1;let w=e===``?`.ok/templates/${s}`:`${e.replace(/\/$/,``)}/.ok/templates/${s}`,E=t.documents.get(w);return E&&isDocInConflict(E)?(respondDocInConflict(S,new DocInConflictError({file:`${w}.md`}),g),!0):!1}function Gl(e,s,g){let S=t.documents.get(e);return S&&isDocInConflict(S)?(respondDocInConflict(g,new DocInConflictError({file:`${e}.md`}),s),!0):!1}let Kl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=resolveProjectTemplates(resolve(g));successResponse(t,200,TemplatesListSuccessSchema,{templates:e.templates.map(e=>{let{scope:t,...s}=e;return s}),truncated:e.truncated},{handler:`templates-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list templates.`,{handler:`templates-list`,cause:e})}},{handler:`templates-list`,method:`GET`,skipBodyParse:!0});async function ql(e,t){if(e.method===`GET`)return Yl(e,t);if(e.method===`PUT`)return Xl(e,t);if(e.method===`POST`)return Ql(e,t);if(e.method===`DELETE`)return Zl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Jl=e=>{let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{frontmatter:g,body:s}},Yl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Rl(g,t,`template-get`))return;let S=Il(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=zl(E,w,g);if(!D){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${g}" not found for folder "${w||`.`}". Walked leaf → root.`});return}let{abs:O,folder:k,scope:j}=D,F=parseTemplateFile(await readFile$1(O,`utf-8`)),L=F.identity,B=F.starterContent;successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:L,body:B}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),Xl=withValidation(TemplatePutRequestSchema,async(e,t,g)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let S=g.name;if(!Rl(S,t,`template-put`))return;let w=Il(g.folder,t,`folder`,`template-put`);if(!w||Wl(w.folderRel,S,`template-put`,t))return;let E=composeTemplateContent({name:S,body:typeof g.body==`string`?g.body:``,frontmatter:Bl(g.frontmatter)});if(!E.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}let D=resolve(w.resolvedContentDir,w.folderRel,`.ok`,`templates`,`${S}.md`),O=!existsSync(D),k=relative(w.resolvedContentDir,D).split(/[\\/]/).filter(Boolean).join(`/`),j=iu(w.folderRel,S),{agentId:F,agentName:L,colorSeed:B,clientName:H}=Xi(g),q=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H});q.dc.document.transact(()=>{composeAndWriteRawBody(q.dc.document,E.content,`agent`)},q.origin);let ee=await Ut(j);if(ee?.kind===`failure`){Wt(t,ee.failure,`template-put`);return}if(ee?.kind===`divergence`){Kt(t,`template-put`);return}Ds(e,Ts(`template`,w.folderRel,S),`${O?`template-create`:`template-edit`}: ${k}`),await Os(`template-put`),successResponse(t,200,TemplatePutSuccessSchema,{path:k,created:O,warnings:E.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),Zl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Rl(g,t,`template-delete`))return;let S=Il(s.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!S)return;let w=s.searchParams,E=extractActorIdentity({agentId:w.get(`agentId`)??void 0,agentName:w.get(`agentName`)??void 0,colorSeed:w.get(`colorSeed`)??void 0,clientName:w.get(`clientName`)??void 0,clientVersion:w.get(`clientVersion`)??void 0,label:w.get(`label`)??void 0,summary:w.get(`summary`)??void 0},we);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Wl(S.folderRel,g,`template-delete`,t))return;await Vr([iu(S.folderRel,g)]);let D=applyTemplateDelete({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}D.existed&&(Ds(E,Ts(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Os(`template-delete`)),successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),Ql=withValidation(TemplateMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Rl(s.fromName,t,`template-move`)||!Rl(s.toName,t,`template-move`))return;let g=Il(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=Il(s.toFolder,t,`folder`,`template-move`);if(!S||Wl(g.folderRel,s.fromName,`template-move`,t))return;await Vr([iu(g.folderRel,s.fromName)]);let w=await applyTemplateMove({projectDir:g.resolvedContentDir,fromFolder:g.folderRel,fromName:s.fromName,toFolder:S.folderRel,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!w.ok){if(w.error.code===`TEMPLATE_NOT_FOUND`){let e=zl(g.resolvedContentDir,g.folderRel,s.fromName);if(e?.scope===`inherited`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${s.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${g.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:w.error.message});return}if(w.error.code===`TEMPLATE_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,w.error.message,{handler:`template-move`,detail:w.error.code});return}let e=w.error.code===`WRITE_ERROR`||w.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:w.error.code,cause:Error(w.error.message)});return}let E=null;if(s.body!==void 0||s.frontmatter!==void 0){let e;if(typeof s.body==`string`)e=s.body;else try{e=instantiateDoc(readFileSync(resolve(S.resolvedContentDir,w.toPath),`utf-8`))}catch{e=null}if(e===null)E={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=applyTemplateWrite({projectDir:S.resolvedContentDir,folder:S.folderRel,name:s.toName,body:e,frontmatter:Bl(s.frontmatter)});t.ok||(E=t.error)}}if(Ds(e,Ts(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Os(`template-move`),fe?.(`files`),E){let e=E.code===`WRITE_ERROR`||E.code===`READ_FAILED`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${w.toPath}", but updating its content failed.`,{handler:`template-move`,detail:E.code,cause:Error(E.message)});return}successResponse(t,200,TemplateMoveSuccessSchema,{from:w.fromPath,to:w.toPath,committed:w.committed},{handler:`template-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),$l=500;function eu(e,t,s){return!e||e.length>64||!SKILL_NAME_REGEX.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:s}),!1):!0}function tu(e,t,s){let g=SkillScopeSchema.safeParse(e??`project`);return g.success?g.data:(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:s}),null)}let nu=Te??homedir();function ru(e){return resolve(e===`global`?nu:g,`.ok`,`skills`)}function iu(e,t){return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function au(e){return e===`navigation`||e===`relevance`?e:void 0}function ou(e,t){return relative(t===`global`?nu:g,e).split(/[\\/]/).filter(Boolean).join(`/`)}function su(e){return e===`global`?nu:Ce}async function cu(e,t){let s=await removeSkillInstall(e,t);return reverseProjectSkill(t,e,PROJECT_SKILL_EDITOR_IDS),s!==null}function lu(e,t){let s=[];if(!existsSync(e))return{skills:s,truncated:!1};let g;try{g=readdirSync(e,{withFileTypes:!0})}catch(g){return getLogger(`skills`).warn({err:g,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:s,truncated:!1}}let S=!1;for(let w of g.sort((e,t)=>e.name.localeCompare(t.name))){if(!w.isDirectory()||!SKILL_NAME_REGEX.test(w.name))continue;if(s.length>=500){S=!0;break}let g=resolve(e,w.name,`SKILL.md`);if(!existsSync(g))continue;let E,D;try{let{frontmatter:e}=Jl(readFileSync(g,`utf-8`));typeof e.description==`string`&&(E=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(D=e.version)}catch{}s.push({name:w.name,...E===void 0?{}:{description:E},scope:t,path:ou(g,t),absolutePath:g,...D===void 0?{}:{installedVersion:D}})}return{skills:s,truncated:S}}let uu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=lu(ru(`project`),`project`),s=lu(ru(`global`),`global`),g=Ce?readInstalledSkills(Ce).skills:{},S=readInstalledSkills(nu).skills,w=(e,t)=>e.skills.map(e=>{let s=t[e.name]?.hosts??[],g=computePackUpdateStatus(e.name,e.installedVersion);return{...e,installed:s.length>0,hosts:s,...g}});successResponse(t,200,SkillsListSuccessSchema,{skills:[...w(e,g),...w(s,S)],truncated:e.truncated||s.truncated},{handler:`skills-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list skills.`,{handler:`skills-list`,cause:e})}},{handler:`skills-list`,method:`GET`,skipBodyParse:!0});async function du(e,t){if(e.method===`GET`)return _u(e,t);if(e.method===`PUT`)return vu(e,t);if(e.method===`POST`)return bu(e,t);if(e.method===`DELETE`)return yu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let fu=object$1({managed:boolean().nullable(),importable:number().int().nonnegative()}),pu=()=>({managed:Ce?readSkillManagement(Ce)?.manageEditorSkills??null:null,importable:Ce?countImportableEditorSkills({projectDir:Ce,skillsRoot:ru(`project`)}):0}),mu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}successResponse(t,200,fu,pu(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),hu=withValidation(object$1({manageEditorSkills:boolean()}),async(e,t,s)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await writeSkillManagement(Ce,{manageEditorSkills:s.manageEditorSkills,surface:`ui`}),s.manageEditorSkills){let e=await reconcileSkillInstalls({projectDir:Ce,skillsRoot:ru(`project`)});e.adopted.length+e.collided.length>0&&fe?.(`files`)}successResponse(t,200,fu,pu(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`});async function gu(e,t){if(e.method===`GET`)return mu(e,t);if(e.method===`PUT`)return hu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skills-management`,extraHeaders:{Allow:`GET, PUT`}})}let _u=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-get`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-get`);if(S===null)return;let w=ru(S),E=resolve(w,g,`SKILL.md`);if(!existsSync(E)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${g}" not found in ${S} scope.`});return}let{frontmatter:D,body:O}=Jl(await readFile$1(E,`utf-8`));successResponse(t,200,SkillGetSuccessSchema,{skill:{name:g,scope:S,path:ou(E,S),frontmatter:{name:typeof D.name==`string`?D.name:g,description:typeof D.description==`string`?D.description:``},body:O,files:readSkillBundledFiles(resolve(w,g))}},{handler:`skill-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),vu=withValidation(SkillPutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!eu(g.name,t,`skill-put`))return;let S=composeSkillContent({name:g.name,body:typeof g.body==`string`?g.body:``,frontmatter:{name:g.frontmatter.name,description:g.frontmatter.description}});if(!S.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:S.error.code,cause:Error(S.error.message)});return}let w=ru(g.scope),E=resolve(w,g.name,`SKILL.md`),D=!existsSync(E),O=relative(w,E).split(/[\\/]/).filter(Boolean).join(`/`),k=skillLiveDocName(g.scope,g.name);if(Gl(k,`skill-put`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Xi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-put`);return}if(q?.kind===`divergence`){Kt(t,`skill-put`);return}g.scope===`project`&&(Ds(e,Ts(`skill`,``,g.name),`${D?`skill-create`:`skill-edit`}: ${O}`),await Os(`skill-put`)),fe?.(`files`),successResponse(t,200,SkillPutSuccessSchema,{path:O,created:D,warnings:S.warnings},{handler:`skill-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),yu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-delete`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-delete`);if(S===null)return;let w=ru(S),E=s.searchParams,D=extractActorIdentity({agentId:E.get(`agentId`)??void 0,agentName:E.get(`agentName`)??void 0,colorSeed:E.get(`colorSeed`)??void 0,clientName:E.get(`clientName`)??void 0,clientVersion:E.get(`clientVersion`)??void 0,label:E.get(`label`)??void 0,summary:E.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Vr([skillLiveDocName(S,g)]);let O=applySkillDelete({skillsRoot:w,name:g});if(!O.ok){let e=O.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:O.error.code,cause:Error(O.error.message)});return}O.existed&&(S===`project`&&(Ds(D,Ts(`skill`,``,g),`skill-delete: ${O.path}`),await Os(`skill-delete`)),fe?.(`files`));let k=su(S);k&&await cu(k,g),successResponse(t,200,SkillDeleteSuccessSchema,{existed:O.existed,path:O.path},{handler:`skill-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),bu=withValidation(SkillMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!eu(s.fromName,t,`skill-move`)||!eu(s.toName,t,`skill-move`))return;let g=ru(s.scope);await Vr([skillLiveDocName(s.scope,s.fromName)]);let S=await applySkillMove({skillsRoot:g,fromName:s.fromName,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!S.ok){if(S.error.code===`SKILL_NOT_FOUND`){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:S.error.message});return}if(S.error.code===`SKILL_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,S.error.message,{handler:`skill-move`,detail:S.error.code});return}let e=S.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:S.error.code,cause:Error(S.error.message)});return}let w=null,E=resolve(g,s.toName,`SKILL.md`),D=``,O=``;try{let e=Jl(readFileSync(E,`utf-8`));D=e.body,typeof e.frontmatter.description==`string`&&(O=e.frontmatter.description)}catch{}let k=typeof s.body==`string`?s.body:D,j=s.frontmatter===void 0?O:s.frontmatter.description,F=applySkillWrite({skillsRoot:g,name:s.toName,body:k,frontmatter:{name:s.toName,description:j}});if(F.ok||(w=F.error),s.scope===`project`&&!w)try{Tu(g,s.fromName,s.toName)}catch(e){getLogger(`skill-move`).warn({err:e,fromName:s.fromName,toName:s.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let L=ou(resolve(g,s.fromName),s.scope),B=ou(resolve(g,s.toName),s.scope);s.scope===`project`&&(Ds(e,Ts(`skill`,``,s.toName),`skill-rename: ${L} -> ${B}`,[{from:L,to:B}]),await Os(`skill-move`));let H=su(s.scope);if(H){let e=await removeSkillInstall(H,s.fromName);if(e){let t=resolvedHosts(e.hosts);reverseProjectSkill(s.fromName,H,t);let S=projectSkill(resolve(g,s.toName),s.toName,H,t);await recordSkillInstall(H,s.toName,{...e,hosts:S})}}if(fe?.(`files`),w){let e=w.code===`WRITE_ERROR`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${s.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:w.code,cause:Error(w.message)});return}successResponse(t,200,SkillMoveSuccessSchema,{from:L,to:B,committed:S.committed},{handler:`skill-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`});function xu(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function Su(e,t,s){return e===`project`&&t===`reference`&&s.toLowerCase().endsWith(`.md`)}function Cu(e,t){let s=t.replace(/\.md$/i,``);return`${projectSkillContentDocName(e).replace(/\/SKILL$/,``)}/${s}`}function wu(e,t){let s=resolve(e,t,`references`);if(!existsSync(s))return[];let g=[],S=(e,t)=>{for(let s of readdirSync(e,{withFileTypes:!0})){let w=t?`${t}/${s.name}`:s.name;s.isDirectory()?S(resolve(e,s.name),w):s.isFile()&&s.name.toLowerCase().endsWith(`.md`)&&g.push(`references/${w}`)}};return S(s,``),g}function Tu(e,t,s){if(!ue)return;let g=(e,t,s)=>{let g;try{g=readFileSync(s,`utf-8`)}catch{ue.deleteDocument(e),de?.deleteDocument(e);return}ue.renameDocument(e,t,g),de?.renameDocument(e,t,g)};g(projectSkillContentDocName(t),projectSkillContentDocName(s),resolve(e,s,`SKILL.md`));for(let S of wu(e,s))g(Cu(t,S),Cu(s,S),resolve(e,s,S));fe?.(`backlinks`),fe?.(`graph`)}let Eu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-file-get`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-file-get`);if(S===null)return;let w=s.searchParams.get(`path`)??``,E=xu(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let D=resolve(ru(S),g),O=resolve(D,w);if(O!==D&&!O.startsWith(`${D}${sep}`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let k=O,j=w;if(!existsSync(k)){let e=w.match(/^(.*)\.(?:md|mdx)$/),s=e?SUPPORTED_DOC_EXTENSIONS.map(t=>`${e[1]}${t}`).find(e=>e!==w&&existsSync(resolve(D,e))):void 0;if(s===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${w} not found in skill "${g}" (${S}).`});return}j=s,k=resolve(D,s)}let F=await readFile$1(k);if(F.includes(0)){errorResponse(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}successResponse(t,200,SkillFileGetSuccessSchema,{path:j.replace(/\\/g,`/`),kind:E,text:F.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),Du=withValidation(SkillFilePutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!eu(g.name,t,`skill-file-put`))return;let S=xu(g.path);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(g.content,`utf-8`)>262144){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let w=ru(g.scope);if(!existsSync(resolve(w,g.name,`SKILL.md`))){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${g.name}" before adding bundle files.`});return}let E=g.path.replace(/\\/g,`/`),D=Su(g.scope,S,E),O;if(D){let e=Cu(g.name,E);if(Gl(e,`skill-file-put`,t))return;if(O=!existsSync(resolve(w,g.name,E)),O&&countBundleFiles(resolve(w,g.name))>=50){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${g.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:S,agentName:D,colorSeed:k,clientName:j}=Xi(g),F=await s.getSession(e,S,{displayName:D,colorSeed:k,clientName:j});F.dc.document.transact(()=>{composeAndWriteRawBody(F.dc.document,g.content,`agent`)},F.origin);let L=await Ut(e);if(L?.kind===`failure`){Wt(t,L.failure,`skill-file-put`);return}if(L?.kind===`divergence`){Kt(t,`skill-file-put`);return}}else{let e=applySkillBundleFileWrite({skillsRoot:w,name:g.name,relPath:E,content:g.content});if(!e.ok){let s=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;errorResponse(t,s,s===500?`urn:ok:error:internal-server-error`:s===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,s===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}O=e.created}g.scope===`project`&&(Ds(e,Ts(`skill`,``,g.name),`${O?`skill-file-create`:`skill-file-edit`}: .ok/skills/${g.name}/${E}`),await Os(`skill-file-put`)),fe?.(`files`),successResponse(t,200,SkillFilePutSuccessSchema,{path:E,created:O,kind:S,content:D},{handler:`skill-file-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),Ou=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams,g=s.get(`name`)??``;if(!eu(g,t,`skill-file-delete`))return;let S=tu(s.get(`scope`),t,`skill-file-delete`);if(S===null)return;let w=(s.get(`path`)??``).replace(/\\/g,`/`),E=xu(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let D=extractActorIdentity({agentId:s.get(`agentId`)??void 0,agentName:s.get(`agentName`)??void 0,colorSeed:s.get(`colorSeed`)??void 0,clientName:s.get(`clientName`)??void 0,clientVersion:s.get(`clientVersion`)??void 0,label:s.get(`label`)??void 0,summary:s.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let O=ru(S);Su(S,E,w)&&await Vr([Cu(g,w)]);let k=applySkillBundleFileDelete({skillsRoot:O,name:g,relPath:w});if(!k.ok){let e=k.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:k.error.code,cause:Error(k.error.message)});return}k.existed&&S===`project`&&(Ds(D,Ts(`skill`,``,g),`skill-file-delete: .ok/skills/${g}/${w}`),await Os(`skill-file-delete`)),k.existed&&fe?.(`files`),successResponse(t,200,SkillFileDeleteSuccessSchema,{path:w,existed:k.existed,kind:E},{handler:`skill-file-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0});async function ku(e,t){if(e.method===`GET`)return Eu(e,t);if(e.method===`PUT`)return Du(e,t);if(e.method===`DELETE`)return Ou(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-file`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Au=withValidation(SkillInstallRequestSchema,async(e,t,s)=>{try{let e=ru(s.scope);if(!eu(s.name,t,`skill-install`))return;if(s.scope===`project`&&!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let g=su(s.scope),S=resolve(e,s.name);if(!existsSync(S)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${s.name}" not found in ${s.scope} scope — create it with write({ skill }) first.`});return}let w=validateSkillForInstall(S,s.name);if(!w.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${s.name}" cannot be installed: ${w.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let E=s.scope===`global`?s.targets?PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)):[...PROJECT_SKILL_EDITOR_IDS]:s.targets===void 0?resolveSkillTargets(g,readSkillTargets(g)??void 0):PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)),D=[],O=[];E.length===0&&s.targets===void 0&&(D.push(s.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),O.push(`no-targets`)),w.hasScripts&&(D.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),O.push(`scripts-present`));let k=resolvedHosts(readInstalledSkills(g).skills[s.name]?.hosts??[]).filter(e=>!E.includes(e));k.length>0&&reverseProjectSkill(s.name,g,k);let j=projectSkill(S,s.name,g,E);j.length===0?await removeSkillInstall(g,s.name):await recordSkillInstall(g,s.name,{hosts:j,scope:s.scope,scripts:w.hasScripts,installedAt:new Date().toISOString()}),fe?.(`files`),successResponse(t,200,SkillInstallSuccessSchema,{name:s.name,hosts:j,scripts:w.hasScripts,warnings:D,warningCodes:O},{handler:`skill-install`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),ju=withValidation(SkillUninstallRequestSchema,async(e,t,s)=>{try{if(!eu(s.name,t,`skill-uninstall`))return;let e=su(s.scope);if(!e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let g=await cu(e,s.name);fe?.(`files`),successResponse(t,200,SkillUninstallSuccessSchema,{name:s.name,uninstalled:g},{handler:`skill-uninstall`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`});async function Mu(e,t){if(e.method===`GET`)return Nu(e,t);if(e.method===`PUT`)return Pu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-targets`,extraHeaders:{Allow:`GET, PUT`}})}let Nu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=Ce?readSkillTargets(Ce):null;successResponse(t,200,SkillTargetsGetSuccessSchema,{targets:resolveSkillTargets(Ce??``,e??void 0),configured:e!==null},{handler:`skill-targets-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),Pu=withValidation(SkillTargetsPutRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let e=s.targets,g=new Set(e),S=resolveSkillTargets(Ce,readSkillTargets(Ce)??void 0),w=ru(`project`);await writeSkillTargets(Ce,e);let{reprojected:E,bundleHosts:D}=await reprojectAllManagedSkills({projectDir:Ce,skillsRoot:w,targets:e});fe?.(`files`),successResponse(t,200,SkillTargetsPutSuccessSchema,{targets:e,reprojected:E,bundleHosts:D,removedFrom:S.filter(e=>!g.has(e))},{handler:`skill-targets-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`}),Fu=withValidation(SkillRestoreRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!eu(s.name,t,`skill-restore`))return;if(s.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let S=ee?.current;if(!S){errorResponse(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let w=await restoreSkillVersion({shadow:S,contentDir:g,contentRoot:ce??`.`,name:s.name,version:s.version});if(!w.ok){let[e,s]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[w.code];errorResponse(t,e,s,w.error,{handler:`skill-restore`,detail:w.code});return}let E=[],D=validateSkillForInstall(resolve(g,`.ok`,`skills`,s.name),s.name);D.ok||E.push(`Restored, but the skill no longer validates: ${D.errors.join(` `)}`),E.push("Run `install` to push the restored version to your editors."),Ds(e,Ts(`skill`,``,s.name),`skill-restore: ${s.name} @ ${s.version.slice(0,8)}`),await Os(`skill-restore`),fe?.(`files`),successResponse(t,200,SkillRestoreSuccessSchema,{name:s.name,version:s.version,restoredFiles:w.restoredFiles,warnings:E},{handler:`skill-restore`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Iu=withValidation(SkillUpdateRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!eu(g.name,t,`skill-update`))return;if(!isPackSkillName(g.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(g.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let S=readBundledPackSkill(g.name);if(S===null||S.version===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let w=resolve(ru(`project`),g.name,`SKILL.md`);if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let E;try{E=readSkillVersion(readFileSync(w,`utf-8`))}catch{}let D,O=ee?.current;if(O)try{let e=oe?.()??`main`;D=(await saveVersion(O,ce??`.`,[SERVICE_WRITER],e,`Before updating ${g.name} (${E??`unversioned`} → ${S.version})`)).checkpointRef}catch(e){getLogger(`skills`).warn({err:e,skill:g.name},`pre-update checkpoint failed — proceeding with overwrite`)}let k=skillLiveDocName(`project`,g.name);if(Gl(k,`skill-update`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Xi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-update`);return}if(q?.kind===`divergence`){Kt(t,`skill-update`);return}Ds(e,Ts(`skill`,``,g.name),`skill-pack-update: ${g.name} (${E??`unversioned`} → ${S.version})`),await Os(`skill-update`),fe?.(`files`),successResponse(t,200,SkillUpdateSuccessSchema,{name:g.name,version:S.version,...E===void 0?{}:{previousVersion:E},...D===void 0?{}:{checkpointRef:D}},{handler:`skill-update`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function Lu(e){let t=new Map;for(let s of e){let e=s.path.split(`/`).filter(Boolean);e.pop();for(let g=1;g<=e.length;g++){let S=e.slice(0,g).join(`/`);t.set(S,Math.max(t.get(S)??0,s.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function Ru(e,t){let s=t.trim().toLowerCase();if(!s||!e)return;let g=e.toLowerCase().indexOf(s);if(g<0)return;let S=Math.max(0,g-80),w=Math.min(e.length,g+s.length+120),E=S>0?`…`:``,D=w<e.length?`…`:``;return`${E}${e.slice(S,w).replace(/\s+/g,` `).trim()}${D}`}function zu(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Bu(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let s=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return s.length>0?s:void 0}function Vu(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Hu(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function Uu(e,t,s,g){let S=g.documents.filter(e=>!isHiddenDocName(e.path)),w=S.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!Be?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:w,capable:!1};Be.embedCorpus(S);let E,D=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await Be.queryScores(e,S);if(D=performance.now()-t,s&&s.size>0){let e=Ve?.();E=e===void 0?{scores:s}:{scores:s,similarityFloor:e}}}let O=Be.getStatus();return{input:E,status:{capable:O.capable,applied:!1,coverage:{embedded:O.embeddedCount,total:w}},queryEmbedMs:D,pageTotal:w,capable:O.capable}}function Wu(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Ru(e.document.content,t):void 0}}async function Gu(e){let t=performance.now();if(ed())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:s,truncated:g}=await td(),S=await Uu(e.query,e.intent,e.semanticParam,s),w=searchWorkspaceCorpus(s,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:S.input}).map(t=>Wu(t,e.query)),E;if(S.status){let t=w.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),s=t>0;E={...S.status,applied:s},recordSemanticQuery({outcome:S.capable?s?`applied`:S.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:S.capable,embedded:S.status.coverage.embedded,total:S.pageTotal,queryEmbedMs:S.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:w,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...E?{semantic:E}:{},...g?{truncated:!0}:{}}}function Ku(){let e=ru(`project`);if(!existsSync(e))return[];let t;try{t=readdirSync(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let g of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!g.isDirectory()||!SKILL_NAME_REGEX.test(g.name))continue;let t=resolve(e,g.name,`SKILL.md`);try{let e=statSync(t);s.push({name:g.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return s}function qu(){let e=[];for(let t of Ku()){let s=t.name,g=``;try{let{frontmatter:e,body:S}=Jl(readFileSync(t.absolutePath,`utf-8`));typeof e.name==`string`&&e.name&&(s=e.name),g=`${typeof e.description==`string`?e.description:``}\n\n${S}`.trim()}catch{}e.push(createWorkspaceSearchDocument({kind:`page`,path:skillLiveDocName(`project`,t.name),title:s,content:g,modifiedTs:t.mtimeMs}))}return e}function Ju(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let Yu=new Map;async function Xu(){let e=[],t=[],s=new Set;for(let[g,S]of D()){if(isSystemDoc(g)||isConfigDoc(g)||g.startsWith(`.ok/skills/`))continue;if(S.kind===`file`){t.push(createWorkspaceSearchDocument({kind:`file`,path:g,modifiedTs:Date.parse(S.modified),aliases:S.aliases}));continue}s.add(g);let w=Ju(S),E=Yu.get(g);if(E&&E.key===w){e.push(E.doc);continue}let D=``,O=g,k=!1;try{D=await readFile$1(S.canonicalPath,`utf-8`)}catch(e){k=!0,console.warn(`[search] Failed to read ${g}:`,e)}if(!k)try{O=extractPageTitle(D,g)}catch(e){console.warn(`[search] Failed to extract title for ${g}:`,e)}let j=createWorkspaceSearchDocument({kind:`page`,path:g,title:O,content:D,modifiedTs:Date.parse(S.modified),aliases:S.aliases});k||Yu.set(g,{key:w,doc:j}),e.push(j)}for(let e of Yu.keys())s.has(e)||Yu.delete(e);let g=getSearchMaxEntries(),S=t,w=!1;return t.length>g&&(w=!0,S=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,g),getLogger(`search`).warn({dropped:t.length-S.length,retained:S.length,limit:g},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),searchCorpusTruncatedCounter().add(1)),{documents:[...e,...qu(),...S,...Lu([...e,...S])],truncated:w}}function Zu(){return Ku().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function Qu(){return k?`gen:${k()}|skills${Zu()}`:`${[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${Ju(t)}`).join(``)}|skills${Zu()}`}let $u=Pe===void 0;Pe?.then(()=>{$u=!0},e=>{$u=!0,log$6.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function ed(){return!$u}async function td(){let e=`${g}${Ce??``}`,t=Qu(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return{corpus:s.corpus,truncated:s.truncated??!1};if(s?.fingerprint===t&&s.pending)return s.pending;let S=Xu().then(({documents:e,truncated:t})=>({corpus:createWorkspaceSearchCorpus(e),truncated:t}));workspaceSearchCaches.set(e,{fingerprint:t,pending:S});try{let s=await S;return workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:s.corpus,truncated:s.truncated}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function nd(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{td().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}nd();async function rd(e,t){if(e.method===`GET`)return ad(e,t);if(e.method===`POST`)return od(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let ad=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=zu(s.searchParams.get(`intent`)),E=au(s.searchParams.get(`ranking`)),D=Bu(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),O=Vu(s.searchParams.get(`semantic`)),k=Hu(s.searchParams.get(`source`)),j=g===null?void 0:Number(g);if(S.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{successResponse(t,200,SearchSuccessSchema,await Gu({query:S,intent:w,ranking:E,scopes:D,limit:j,semanticParam:O,source:k}),{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),od=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=zu(s.intent),w=au(s.ranking),E=Bu(s.scopes??s.scope),D=typeof s.limit==`number`?s.limit:void 0,O=Vu(s.semantic),k=Hu(s.source);if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{successResponse(t,200,SearchSuccessSchema,await Gu({query:g,intent:S,ranking:w,scopes:E,limit:D,semanticParam:O,source:k}),{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),sd=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function cd(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform,isSchemeRegistered:Et.probeWithCache})}catch(e){t.headersSent||(log$6.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function ld(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$6.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let ud=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!Ce){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!isValidSharePath(s.kind===`doc`?s.docPath:s.folderPath,s.kind)){emitShareConstructUrlLog(`invalid-path`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=readGitHeadBranch(Ce);if(e===null){if(readOriginGitHubRepo(Ce).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let S=readOriginGitHubRepo(Ce);if(S.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(S.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(Ce,e)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=toGitRelativePath(Ce,g);if(w===null)throw Error(`content dir is not contained within the project dir`);let E=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;w!==``&&E&&getLogger(`share`).warn({action:`construct-url`,kind:s.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let D;if(s.kind===`doc`)D=buildGitHubBlobUrl(S.owner,S.repo,e,s.docPath);else{let t=s.folderPath===``?w:s.folderPath;D=buildGitHubTreeUrl(S.owner,S.repo,e,t)}let O=`${SHARE_BASE_URL}${encodeShareUrl(D)}`;emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:O,sharedUrl:D,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}),dd=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`branch`),S=s.searchParams.get(`path`),w=s.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!isValidBranchName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoPath(S,w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(Ce,g,S,w),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),fd=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(Ce,s.branch)),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function pd(e){let[t,...s]=ye,g=[...s,...e];return await new Promise((e,s)=>{let S=spawn(t,g,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,S.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),D=[],O=[];S.stdout.on(`data`,e=>D.push(e)),S.stderr.on(`data`,e=>O.push(e)),S.on(`close`,t=>{if(clearTimeout(E),w){s(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let g=Buffer.concat(D).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(O).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:g,code:t})}),S.on(`error`,e=>{clearTimeout(E),s(e)})})}let md=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await pd([`share`,`owners`,`--json`]),s=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,s.ok?`ok`:s.error,s.ok?{count:s.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,s,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),hd=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`owner`)??``,S=s.searchParams.get(`name`)??``;if(!isValidShareOwnerName(g)||!isValidShareRepoName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!Ge.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await pd([`share`,`name-check`,`--owner`,g,`--name`,S,`--json`]),s=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,s.ok?`ok`:s.error,s.ok?{available:s.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,s,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),gd=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!Ce){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(s.owner)||!isValidShareRepoName(s.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!Ge.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,s.owner,`--name`,s.name,`--visibility`,s.visibility,`--project-dir`,Ce,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await pd(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&ve?.()?.refreshRemote().catch(()=>{}),successResponse(t,200,SharePublishResponseSchema,S,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),_d=withValidation(ClientLogsRequestSchema,async(e,t,s)=>{try{let e=getLogger(`renderer`);for(let t of s.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}successResponse(t,200,ClientLogsSuccessSchema,{accepted:s.entries.length},{handler:`client-logs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`client-logs`})}),vd=Ce?getLocalDir(Ce):null;async function yd(e,t){if(e.method===`DELETE`){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-config`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-config`});return}vd&&clearArmedPaneTarget(vd),t.setHeader(`Cache-Control`,`no-store`),t.statusCode=204,t.end();return}if(e.method===`GET`||e.method===`HEAD`){try{let s=e.headers.host,g={collabUrl:s?`ws://${s}/collab`:null,previewUrl:null,port:vd?readServerLock(vd)?.port??0:0,paneTarget:vd?readArmedPaneTarget(vd):null,singleFile:We};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}successResponse(t,200,ApiConfigSuccessSchema,g,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD, DELETE`}})}let bd=`local-op-embeddings-set-key`,xd=`local-op-embeddings-clear-key`,Sd=`/api/local-op/embeddings`,Cd=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Ge.tryAcquire(Sd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:bd,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(Ue).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:bd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:bd,cause:e})}finally{Ge.release(Sd)}},{handler:bd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:bd})}),wd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(Sd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:xd,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(Ue),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:xd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:xd,cause:e})}finally{Ge.release(Sd)}},{handler:xd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:xd})}),Td=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(Be){let t=Be.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(Ue).get(),D=process.env.OK_EMBEDDINGS_API_KEY??null,O=E?`file`:D?`env`:null,k=O!==null,j=E??D,F=j&&j.length>=8?j.slice(-4):null,L=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(L+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:k,keySource:O,keyHint:F,ready:s,capable:g,embedded:S,total:L},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Ed={"/api/config":yd,"/api/asset":Tc,"/api/asset-text":Dc,"/api/document":Is,"/api/documents":Rs,"/api/backlinks":$s,"/api/backlink-counts":ec,"/api/forward-links":tc,"/api/link-graph":nc,"/api/dead-links":ac,"/api/orphans":rc,"/api/hubs":ic,"/api/tags":Pl,"/api/pages":Lc,"/api/folder-config":Vl,"/api/template":ql,"/api/templates":Kl,"/api/skill":du,"/api/skill-file":ku,"/api/skills":uu,"/api/skills/management":gu,"/api/skill/install":Au,"/api/skill/uninstall":ju,"/api/skill/restore":Fu,"/api/skill/update":Iu,"/api/skill-targets":Mu,"/api/search":rd,"/api/semantic-status":Td,"/api/suggest-links":Rc,"/api/page-headings":Nc,"/api/create-page":Ac,"/api/create-folder":jc,"/api/duplicate-path":Mc,"/api/rename-path":Pc,"/api/delete-path":Fc,"/api/trash/cleanup":Ic,"/api/upload":zc,"/api/agent-write":ks,"/api/agent-write-md":As,"/api/frontmatter-patch":Ns,"/api/agent-patch":oc,"/api/agent-undo":sc,"/api/agent-activity":cc,"/api/agent-burst-diff":lc,"/api/save-version":mc,"/api/history":hc,"/api/rollback":_c,"/api/metrics/reconciliation":vc,"/api/metrics/parse-health":yc,"/api/metrics/agent-presence":Sc,"/api/__embed-detect":Cc,"/api/server-info":bc,"/api/share/construct-url":ud,"/api/git/branch-info":dd,"/api/git/checkout":fd,"/api/share/publish/owners":md,"/api/share/publish/name-check":hd,"/api/share/publish":gd,"/api/principal":xc,"/api/rescue":kc,"/api/workspace":wc,"/api/sync/status":yl,"/api/sync/trigger":xl,"/api/sync/conflicts":Cl,"/api/sync/conflict-content":El,"/api/sync/resolve-conflict":Tl,"/api/local-op/clone":Gc,"/api/local-op/ok-init":Yc,"/api/local-op/auth/login":al,"/api/local-op/auth/status":ul,"/api/local-op/auth/repos":fl,"/api/local-op/auth/signout":hl,"/api/local-op/auth/set-identity":vl,"/api/local-op/embeddings/set-key":Cd,"/api/local-op/embeddings/clear-key":wd,"/api/installed-agents":Ml,"/api/spawn-cursor":ld,"/api/handoff":cd,"/api/install-skill":jl,"/api/skill/install-state":sd,"/api/seed/plan":Dl,"/api/seed/apply":Ol,"/api/seed/packs":kl,"/api/client-logs":_d};q&&(Ed[`/api/test-reset`]=dc,Ed[`/api/test-flush-git`]=uc,Ed[`/api/test-rescan-backlinks`]=fc,Ed[`/api/test-rescan-files`]=pc);let Dd=new Set(`/api/upload./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),Od=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let s=e.url?.split(`?`)[0];if(!s)return;let g=t=>{let s=e.headers[t];if(s!==void 0)return Array.isArray(s)?s.join(`, `):s};if(recordEmbedProbe({ts:Date.now(),url:s,method:e.method??``,ua:g(`user-agent`),origin:g(`origin`),referer:g(`referer`),host:g(`host`),remote:e.socket?.remoteAddress,secChUa:g(`sec-ch-ua`),secChUaMobile:g(`sec-ch-ua-mobile`),secChUaPlatform:g(`sec-ch-ua-platform`),secFetchSite:g(`sec-fetch-site`),secFetchDest:g(`sec-fetch-dest`),secFetchMode:g(`sec-fetch-mode`),secFetchUser:g(`sec-fetch-user`)}),s.startsWith(`/api/`)){let s=e.headers.origin;if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${CLIENT_VERSION_HEADER.protocol}, ${CLIENT_VERSION_HEADER.runtime}, ${CLIENT_VERSION_HEADER.kind}`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Dd.has(s)||Od.some(e=>s.startsWith(e))){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(We&&s.startsWith(`/api/`)){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:Ed[s]||(E=`/api/*`);let D=getTracer(),O=Date.now();await context.with(S,()=>D.startActiveSpan(`HTTP ${w} ${E}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_URL_PATH]:s,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async g=>{try{let S=Ed[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await gc(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await Fl(e,t,g))}E||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${w} ${s}`});let D=t.statusCode;g.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,D),D>=500&&g.setStatus({code:SpanStatusCode.ERROR,message:`status ${D}`})}catch(e){throw g.recordException(e),g.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E,cause:e}),e}finally{g.end();let e=(Date.now()-O)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedSingleDirBasenameIndex(e){let t;try{t=readdirSync(e.contentDir,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,e.contentDir);return}for(let s of t)s.isFile()&&isSupportedAssetFile(s.name,ASSET_EXTENSIONS)&&e.basenameIndex.add(s.name)}async function seedBasenameIndex(e){let t=e.contentDir,s=new Set;async function g(S){let w;try{w=await readdir(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=toPosix(relative(t,w));if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=await lstat(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=await realpath(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=await stat$1(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?await g(S):E.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),await g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}await g(t)}var AutoStartDisabledError=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const log$5=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$5.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$5.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$5.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,s,g=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:S}=await import(`./git-handle-D7c_AnSg-mtlScJx8.mjs`),w=S(this.projectDir,{credentialArgs:g});switch(t){case`mine`:await w.git.raw([`checkout`,`--ours`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`theirs`:await w.git.raw([`checkout`,`--theirs`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`content`:{if(s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),g=resolve(t,e);if(!isWithinDir(g,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(g,s,`utf-8`),await w.git.raw([`add`,`--`,e]);break}case`delete`:await w.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await w.git.raw([`commit`,`--no-edit`]),log$5.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let e=(await w.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
1949
+ `);k=s.pop()??``;for(let e of s){if(!e.trim())continue;let s=null;try{s=JSON.parse(e)}catch{}if(s&&s.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof s.message==`string`?s.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),j.stderr.on(`data`,e=>{log$6.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),j.on(`close`,e=>{clearTimeout(F),O||(O=!0,e!==0&&!t.writableEnded&&S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Ge.release(Qc))}),j.on(`error`,e=>{clearTimeout(F),O||(O=!0,t.writableEnded||(S(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),Ge.release(Qc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Ge.release(Qc))})}let ml=`local-op-auth-signout`,hl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire($c)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:ml,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`signout`,`--host`,g];await new Promise((t,s)=>{let g=spawn(e,S,{stdio:`ignore`,env:{...process.env}}),w=setTimeout(()=>{g.kill(`SIGTERM`)},3e4);g.on(`close`,()=>{clearTimeout(w),t()}),g.on(`error`,e=>{clearTimeout(w),s(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:ml})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:ml,cause:e})}finally{Ge.release($c)}},{handler:ml,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ml})}),gl=`/api/local-op/auth/set-identity`,_l=`local-op-auth-set-identity`,vl=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!Ce){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:_l});return}if(!Ge.tryAcquire(gl)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:_l,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(Ce,g,S),ve?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:_l})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:_l,cause:e})}finally{Ge.release(gl)}},{handler:_l,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:_l})});async function yl(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let xl=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let S=s.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:S},{handler:`sync-trigger`}),g.trigger(S)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Cl(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Tl=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:S,strategy:w,content:E}=s;try{await g.resolveConflict(S,w,E),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function El(e,s){if(!checkLocalOpSecurity(e,s,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(s,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!Ce){errorResponse(s,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`file`);if(!S){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=stripDocExtension(S),E=t.documents.get(w)?.getMap(`lifecycle`).get(`status`)===`conflict`,D=ve?.(),O=D?D.getConflicts().some(e=>e.file===S):!1;if(!E&&!O){errorResponse(s,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:S}});return}let k=g.searchParams.get(`source`),j=esm_default({baseDir:Ce,timeout:{block:15e3}});async function F(e){try{return{present:!0,content:await j.raw([`show`,`:${e}:${S}`])}}catch(t){let s=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(s))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:S,detail:s,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,g,w]=await Promise.all([F(1),F(2),F(3)]),E=e.present?e.content:``,D=w.present?w.content:``,O=g.present&&w.present?`both-modified`:!g.present&&w.present?`delete-modify`:g.present&&!w.present?`modify-delete`:`both-modified`,j=g.present?g.content:``,L=null;if(k===`ytext`){let e=stripDocExtension(S),s=t.documents.get(e);if(s){let t=s.getMap(`lifecycle`).get(`status`);if(L=typeof t==`string`&&t.length>0?t:null,O!==`delete-modify`){let t=Re?Re(e):null;t!==null&&!ytextHasConflictMarkers(t)?j=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(s,200,SyncConflictContentSuccessSchema,{file:S,base:E,ours:j,theirs:D,kind:O,lifecycleStatus:L},{handler:`sync-conflict-content`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Dl(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let s=new URL(e.url??`/`,`http://localhost`),S=s.searchParams.get(`rootDir`)??void 0,w=s.searchParams.get(`packId`),E=coercePackId(w);if(w!==null&&w!==``&&E===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${w}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:g,rootDir:S,packId:E})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Ol=withValidation(SeedApplyRequestSchema,async(e,t,s)=>{let S=s.plan;if(!S||typeof S!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let w=S,E=s.packId,D=coercePackId(E);if(typeof E==`string`&&E.length>0&&D===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${E}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(w,{projectDir:g,packId:D})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function kl(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let jl=withValidation(InstallSkillRequestSchema,async(e,t,s)=>{if(s.out!==void 0&&!isSafeLocalPath(s.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...s.noOpen===void 0?{}:{noOpen:s.noOpen},...s.out===void 0?{}:{out:s.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function Ml(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Et.probeAll)}catch(e){t.headersSent||(log$6.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}let Pl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:de.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Fl(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let g;try{g=decodeURIComponent(s)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=de.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:jt(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:g,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function Il(e,t,s=`path`,S=`folder-config`){let w=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(w.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${s}: must be project-root-relative.`,{handler:S}),null;let E=resolve(g),D=w===``?E:resolve(E,w);return D!==E&&!D.startsWith(`${E}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:S}),null):{folderRel:w,resolvedContentDir:E}}let Ll=/^[A-Za-z0-9_-]+$/;function Rl(e,t,s=`template`){return!e||!Ll.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:s}),!1):!0}function zl(e,t,s){let g=t===``?[]:t.split(`/`);for(let t=g.length;t>=0;t--){let S=t===0?``:g.slice(0,t).join(`/`),w=S===``?e:resolve(e,S);if(w!==e&&!w.startsWith(`${e}${sep}`))continue;let E=resolve(w,`.ok`,`templates`,`${s}.md`);if(existsSync(E))return{abs:E,folder:S,scope:t===g.length?`local`:`inherited`}}return null}function Bl(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[s,g]of Object.entries(e))g!==void 0&&(t[s]=g);return t}async function Vl(e,t){if(e.method===`GET`)return Hl(e,t);if(e.method===`PUT`)return Ul(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Hl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=Il(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!s)return;let g=await enrichDirectory(s.folderRel,{projectDir:s.resolvedContentDir}),S=resolve(resolve(s.resolvedContentDir,s.folderRel,`.ok`),`frontmatter.yml`),w=null;if(existsSync(S))try{let e=(0,import_dist$1.parse)(await readFile$1(S,`utf-8`));w=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${S}: ${t}`),w=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:g,frontmatter_local:w},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),Ul=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let g=Il(s.path,t,`path`,`folder-config-put`);if(!g)return;let S=[];if(s.frontmatter!==void 0){let w=applyFolderFrontmatterPatch({anchorDir:g.resolvedContentDir,folderRel:g.folderRel,patch:s.frontmatter});if(!w.ok){let e=w.error.code===`WRITE_ERROR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:w.error.message,{handler:`folder-config-put`,detail:w.error.code,cause:Error(w.error.message)});return}S.push({path:w.path,action:w.action}),w.action!==`noop`&&(Ds(e,Ts(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Os(`folder-config-put`))}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:S},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function Wl(e,s,g,S){if(!s)return!1;let w=e===``?`.ok/templates/${s}`:`${e.replace(/\/$/,``)}/.ok/templates/${s}`,E=t.documents.get(w);return E&&isDocInConflict(E)?(respondDocInConflict(S,new DocInConflictError({file:`${w}.md`}),g),!0):!1}function Gl(e,s,g){let S=t.documents.get(e);return S&&isDocInConflict(S)?(respondDocInConflict(g,new DocInConflictError({file:`${e}.md`}),s),!0):!1}let Kl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=resolveProjectTemplates(resolve(g));successResponse(t,200,TemplatesListSuccessSchema,{templates:e.templates.map(e=>{let{scope:t,...s}=e;return s}),truncated:e.truncated},{handler:`templates-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list templates.`,{handler:`templates-list`,cause:e})}},{handler:`templates-list`,method:`GET`,skipBodyParse:!0});async function ql(e,t){if(e.method===`GET`)return Yl(e,t);if(e.method===`PUT`)return Xl(e,t);if(e.method===`POST`)return Ql(e,t);if(e.method===`DELETE`)return Zl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Jl=e=>{let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{frontmatter:g,body:s}},Yl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Rl(g,t,`template-get`))return;let S=Il(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=zl(E,w,g);if(!D){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${g}" not found for folder "${w||`.`}". Walked leaf → root.`});return}let{abs:O,folder:k,scope:j}=D,F=parseTemplateFile(await readFile$1(O,`utf-8`)),L=F.identity,B=F.starterContent;successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:L,body:B}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),Xl=withValidation(TemplatePutRequestSchema,async(e,t,g)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let S=g.name;if(!Rl(S,t,`template-put`))return;let w=Il(g.folder,t,`folder`,`template-put`);if(!w||Wl(w.folderRel,S,`template-put`,t))return;let E=composeTemplateContent({name:S,body:typeof g.body==`string`?g.body:``,frontmatter:Bl(g.frontmatter)});if(!E.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}let D=resolve(w.resolvedContentDir,w.folderRel,`.ok`,`templates`,`${S}.md`),O=!existsSync(D),k=relative(w.resolvedContentDir,D).split(/[\\/]/).filter(Boolean).join(`/`),j=iu(w.folderRel,S),{agentId:F,agentName:L,colorSeed:B,clientName:H}=Xi(g),q=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H});q.dc.document.transact(()=>{composeAndWriteRawBody(q.dc.document,E.content,`agent`)},q.origin);let ee=await Ut(j);if(ee?.kind===`failure`){Wt(t,ee.failure,`template-put`);return}if(ee?.kind===`divergence`){Kt(t,`template-put`);return}Ds(e,Ts(`template`,w.folderRel,S),`${O?`template-create`:`template-edit`}: ${k}`),await Os(`template-put`),successResponse(t,200,TemplatePutSuccessSchema,{path:k,created:O,warnings:E.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),Zl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Rl(g,t,`template-delete`))return;let S=Il(s.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!S)return;let w=s.searchParams,E=extractActorIdentity({agentId:w.get(`agentId`)??void 0,agentName:w.get(`agentName`)??void 0,colorSeed:w.get(`colorSeed`)??void 0,clientName:w.get(`clientName`)??void 0,clientVersion:w.get(`clientVersion`)??void 0,label:w.get(`label`)??void 0,summary:w.get(`summary`)??void 0},we);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Wl(S.folderRel,g,`template-delete`,t))return;await Vr([iu(S.folderRel,g)]);let D=applyTemplateDelete({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}D.existed&&(Ds(E,Ts(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Os(`template-delete`)),successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),Ql=withValidation(TemplateMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Rl(s.fromName,t,`template-move`)||!Rl(s.toName,t,`template-move`))return;let g=Il(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=Il(s.toFolder,t,`folder`,`template-move`);if(!S||Wl(g.folderRel,s.fromName,`template-move`,t))return;await Vr([iu(g.folderRel,s.fromName)]);let w=await applyTemplateMove({projectDir:g.resolvedContentDir,fromFolder:g.folderRel,fromName:s.fromName,toFolder:S.folderRel,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!w.ok){if(w.error.code===`TEMPLATE_NOT_FOUND`){let e=zl(g.resolvedContentDir,g.folderRel,s.fromName);if(e?.scope===`inherited`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${s.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${g.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:w.error.message});return}if(w.error.code===`TEMPLATE_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,w.error.message,{handler:`template-move`,detail:w.error.code});return}let e=w.error.code===`WRITE_ERROR`||w.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:w.error.code,cause:Error(w.error.message)});return}let E=null;if(s.body!==void 0||s.frontmatter!==void 0){let e;if(typeof s.body==`string`)e=s.body;else try{e=instantiateDoc(readFileSync(resolve(S.resolvedContentDir,w.toPath),`utf-8`))}catch{e=null}if(e===null)E={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=applyTemplateWrite({projectDir:S.resolvedContentDir,folder:S.folderRel,name:s.toName,body:e,frontmatter:Bl(s.frontmatter)});t.ok||(E=t.error)}}if(Ds(e,Ts(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Os(`template-move`),fe?.(`files`),E){let e=E.code===`WRITE_ERROR`||E.code===`READ_FAILED`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${w.toPath}", but updating its content failed.`,{handler:`template-move`,detail:E.code,cause:Error(E.message)});return}successResponse(t,200,TemplateMoveSuccessSchema,{from:w.fromPath,to:w.toPath,committed:w.committed},{handler:`template-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),$l=500;function eu(e,t,s){return!e||e.length>64||!SKILL_NAME_REGEX.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:s}),!1):!0}function tu(e,t,s){let g=SkillScopeSchema.safeParse(e??`project`);return g.success?g.data:(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:s}),null)}let nu=Te??homedir();function ru(e){return resolve(e===`global`?nu:g,`.ok`,`skills`)}function iu(e,t){return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function au(e){return e===`navigation`||e===`relevance`?e:void 0}function ou(e,t){return relative(t===`global`?nu:g,e).split(/[\\/]/).filter(Boolean).join(`/`)}function su(e){return e===`global`?nu:Ce}async function cu(e,t){let s=await removeSkillInstall(e,t);return reverseProjectSkill(t,e,PROJECT_SKILL_EDITOR_IDS),s!==null}function lu(e,t){let s=[];if(!existsSync(e))return{skills:s,truncated:!1};let g;try{g=readdirSync(e,{withFileTypes:!0})}catch(g){return getLogger(`skills`).warn({err:g,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:s,truncated:!1}}let S=!1;for(let w of g.sort((e,t)=>e.name.localeCompare(t.name))){if(!w.isDirectory()||!SKILL_NAME_REGEX.test(w.name))continue;if(s.length>=500){S=!0;break}let g=resolve(e,w.name,`SKILL.md`);if(!existsSync(g))continue;let E,D;try{let{frontmatter:e}=Jl(readFileSync(g,`utf-8`));typeof e.description==`string`&&(E=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(D=e.version)}catch{}s.push({name:w.name,...E===void 0?{}:{description:E},scope:t,path:ou(g,t),absolutePath:g,...D===void 0?{}:{installedVersion:D}})}return{skills:s,truncated:S}}let uu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=lu(ru(`project`),`project`),s=lu(ru(`global`),`global`),g=Ce?readInstalledSkills(Ce).skills:{},S=readInstalledSkills(nu).skills,w=(e,t)=>e.skills.map(e=>{let s=t[e.name]?.hosts??[],g=computePackUpdateStatus(e.name,e.installedVersion);return{...e,installed:s.length>0,hosts:s,...g}});successResponse(t,200,SkillsListSuccessSchema,{skills:[...w(e,g),...w(s,S)],truncated:e.truncated||s.truncated},{handler:`skills-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list skills.`,{handler:`skills-list`,cause:e})}},{handler:`skills-list`,method:`GET`,skipBodyParse:!0});async function du(e,t){if(e.method===`GET`)return _u(e,t);if(e.method===`PUT`)return vu(e,t);if(e.method===`POST`)return bu(e,t);if(e.method===`DELETE`)return yu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let fu=object$1({managed:boolean().nullable(),importable:number().int().nonnegative()}),pu=()=>({managed:Ce?readSkillManagement(Ce)?.manageEditorSkills??null:null,importable:Ce?countImportableEditorSkills({projectDir:Ce,skillsRoot:ru(`project`)}):0}),mu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}successResponse(t,200,fu,pu(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),hu=withValidation(object$1({manageEditorSkills:boolean()}),async(e,t,s)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await writeSkillManagement(Ce,{manageEditorSkills:s.manageEditorSkills,surface:`ui`}),s.manageEditorSkills){let e=await reconcileSkillInstalls({projectDir:Ce,skillsRoot:ru(`project`)});e.adopted.length+e.collided.length>0&&fe?.(`files`)}successResponse(t,200,fu,pu(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`});async function gu(e,t){if(e.method===`GET`)return mu(e,t);if(e.method===`PUT`)return hu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skills-management`,extraHeaders:{Allow:`GET, PUT`}})}let _u=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-get`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-get`);if(S===null)return;let w=ru(S),E=resolve(w,g,`SKILL.md`);if(!existsSync(E)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${g}" not found in ${S} scope.`});return}let{frontmatter:D,body:O}=Jl(await readFile$1(E,`utf-8`));successResponse(t,200,SkillGetSuccessSchema,{skill:{name:g,scope:S,path:ou(E,S),frontmatter:{name:typeof D.name==`string`?D.name:g,description:typeof D.description==`string`?D.description:``},body:O,files:readSkillBundledFiles(resolve(w,g))}},{handler:`skill-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),vu=withValidation(SkillPutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!eu(g.name,t,`skill-put`))return;let S=composeSkillContent({name:g.name,body:typeof g.body==`string`?g.body:``,frontmatter:{name:g.frontmatter.name,description:g.frontmatter.description}});if(!S.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:S.error.code,cause:Error(S.error.message)});return}let w=ru(g.scope),E=resolve(w,g.name,`SKILL.md`),D=!existsSync(E),O=relative(w,E).split(/[\\/]/).filter(Boolean).join(`/`),k=skillLiveDocName(g.scope,g.name);if(Gl(k,`skill-put`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Xi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-put`);return}if(q?.kind===`divergence`){Kt(t,`skill-put`);return}g.scope===`project`&&(Ds(e,Ts(`skill`,``,g.name),`${D?`skill-create`:`skill-edit`}: ${O}`),await Os(`skill-put`)),fe?.(`files`),successResponse(t,200,SkillPutSuccessSchema,{path:O,created:D,warnings:S.warnings},{handler:`skill-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),yu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-delete`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-delete`);if(S===null)return;let w=ru(S),E=s.searchParams,D=extractActorIdentity({agentId:E.get(`agentId`)??void 0,agentName:E.get(`agentName`)??void 0,colorSeed:E.get(`colorSeed`)??void 0,clientName:E.get(`clientName`)??void 0,clientVersion:E.get(`clientVersion`)??void 0,label:E.get(`label`)??void 0,summary:E.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Vr([skillLiveDocName(S,g)]);let O=applySkillDelete({skillsRoot:w,name:g});if(!O.ok){let e=O.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:O.error.code,cause:Error(O.error.message)});return}O.existed&&(S===`project`&&(Ds(D,Ts(`skill`,``,g),`skill-delete: ${O.path}`),await Os(`skill-delete`)),fe?.(`files`));let k=su(S);k&&await cu(k,g),successResponse(t,200,SkillDeleteSuccessSchema,{existed:O.existed,path:O.path},{handler:`skill-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),bu=withValidation(SkillMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!eu(s.fromName,t,`skill-move`)||!eu(s.toName,t,`skill-move`))return;let g=ru(s.scope);await Vr([skillLiveDocName(s.scope,s.fromName)]);let S=await applySkillMove({skillsRoot:g,fromName:s.fromName,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!S.ok){if(S.error.code===`SKILL_NOT_FOUND`){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:S.error.message});return}if(S.error.code===`SKILL_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,S.error.message,{handler:`skill-move`,detail:S.error.code});return}let e=S.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:S.error.code,cause:Error(S.error.message)});return}let w=null,E=resolve(g,s.toName,`SKILL.md`),D=``,O=``;try{let e=Jl(readFileSync(E,`utf-8`));D=e.body,typeof e.frontmatter.description==`string`&&(O=e.frontmatter.description)}catch{}let k=typeof s.body==`string`?s.body:D,j=s.frontmatter===void 0?O:s.frontmatter.description,F=applySkillWrite({skillsRoot:g,name:s.toName,body:k,frontmatter:{name:s.toName,description:j}});if(F.ok||(w=F.error),s.scope===`project`&&!w)try{Tu(g,s.fromName,s.toName)}catch(e){getLogger(`skill-move`).warn({err:e,fromName:s.fromName,toName:s.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let L=ou(resolve(g,s.fromName),s.scope),B=ou(resolve(g,s.toName),s.scope);s.scope===`project`&&(Ds(e,Ts(`skill`,``,s.toName),`skill-rename: ${L} -> ${B}`,[{from:L,to:B}]),await Os(`skill-move`));let H=su(s.scope);if(H){let e=await removeSkillInstall(H,s.fromName);if(e){let t=resolvedHosts(e.hosts);reverseProjectSkill(s.fromName,H,t);let S=projectSkill(resolve(g,s.toName),s.toName,H,t);await recordSkillInstall(H,s.toName,{...e,hosts:S})}}if(fe?.(`files`),w){let e=w.code===`WRITE_ERROR`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${s.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:w.code,cause:Error(w.message)});return}successResponse(t,200,SkillMoveSuccessSchema,{from:L,to:B,committed:S.committed},{handler:`skill-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`});function xu(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function Su(e,t,s){return e===`project`&&t===`reference`&&s.toLowerCase().endsWith(`.md`)}function Cu(e,t){let s=t.replace(/\.md$/i,``);return`${projectSkillContentDocName(e).replace(/\/SKILL$/,``)}/${s}`}function wu(e,t){let s=resolve(e,t,`references`);if(!existsSync(s))return[];let g=[],S=(e,t)=>{for(let s of readdirSync(e,{withFileTypes:!0})){let w=t?`${t}/${s.name}`:s.name;s.isDirectory()?S(resolve(e,s.name),w):s.isFile()&&s.name.toLowerCase().endsWith(`.md`)&&g.push(`references/${w}`)}};return S(s,``),g}function Tu(e,t,s){if(!ue)return;let g=(e,t,s)=>{let g;try{g=readFileSync(s,`utf-8`)}catch{ue.deleteDocument(e),de?.deleteDocument(e);return}ue.renameDocument(e,t,g),de?.renameDocument(e,t,g)};g(projectSkillContentDocName(t),projectSkillContentDocName(s),resolve(e,s,`SKILL.md`));for(let S of wu(e,s))g(Cu(t,S),Cu(s,S),resolve(e,s,S));fe?.(`backlinks`),fe?.(`graph`)}let Eu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-file-get`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-file-get`);if(S===null)return;let w=s.searchParams.get(`path`)??``,E=xu(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let D=resolve(ru(S),g),O=resolve(D,w);if(O!==D&&!O.startsWith(`${D}${sep}`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let k=O,j=w;if(!existsSync(k)){let e=w.match(/^(.*)\.(?:md|mdx)$/),s=e?SUPPORTED_DOC_EXTENSIONS.map(t=>`${e[1]}${t}`).find(e=>e!==w&&existsSync(resolve(D,e))):void 0;if(s===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${w} not found in skill "${g}" (${S}).`});return}j=s,k=resolve(D,s)}let F=await readFile$1(k);if(F.includes(0)){errorResponse(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}successResponse(t,200,SkillFileGetSuccessSchema,{path:j.replace(/\\/g,`/`),kind:E,text:F.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),Du=withValidation(SkillFilePutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!eu(g.name,t,`skill-file-put`))return;let S=xu(g.path);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(g.content,`utf-8`)>262144){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let w=ru(g.scope);if(!existsSync(resolve(w,g.name,`SKILL.md`))){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${g.name}" before adding bundle files.`});return}let E=g.path.replace(/\\/g,`/`),D=Su(g.scope,S,E),O;if(D){let e=Cu(g.name,E);if(Gl(e,`skill-file-put`,t))return;if(O=!existsSync(resolve(w,g.name,E)),O&&countBundleFiles(resolve(w,g.name))>=50){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${g.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:S,agentName:D,colorSeed:k,clientName:j}=Xi(g),F=await s.getSession(e,S,{displayName:D,colorSeed:k,clientName:j});F.dc.document.transact(()=>{composeAndWriteRawBody(F.dc.document,g.content,`agent`)},F.origin);let L=await Ut(e);if(L?.kind===`failure`){Wt(t,L.failure,`skill-file-put`);return}if(L?.kind===`divergence`){Kt(t,`skill-file-put`);return}}else{let e=applySkillBundleFileWrite({skillsRoot:w,name:g.name,relPath:E,content:g.content});if(!e.ok){let s=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;errorResponse(t,s,s===500?`urn:ok:error:internal-server-error`:s===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,s===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}O=e.created}g.scope===`project`&&(Ds(e,Ts(`skill`,``,g.name),`${O?`skill-file-create`:`skill-file-edit`}: .ok/skills/${g.name}/${E}`),await Os(`skill-file-put`)),fe?.(`files`),successResponse(t,200,SkillFilePutSuccessSchema,{path:E,created:O,kind:S,content:D},{handler:`skill-file-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),Ou=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams,g=s.get(`name`)??``;if(!eu(g,t,`skill-file-delete`))return;let S=tu(s.get(`scope`),t,`skill-file-delete`);if(S===null)return;let w=(s.get(`path`)??``).replace(/\\/g,`/`),E=xu(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let D=extractActorIdentity({agentId:s.get(`agentId`)??void 0,agentName:s.get(`agentName`)??void 0,colorSeed:s.get(`colorSeed`)??void 0,clientName:s.get(`clientName`)??void 0,clientVersion:s.get(`clientVersion`)??void 0,label:s.get(`label`)??void 0,summary:s.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let O=ru(S);Su(S,E,w)&&await Vr([Cu(g,w)]);let k=applySkillBundleFileDelete({skillsRoot:O,name:g,relPath:w});if(!k.ok){let e=k.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:k.error.code,cause:Error(k.error.message)});return}k.existed&&S===`project`&&(Ds(D,Ts(`skill`,``,g),`skill-file-delete: .ok/skills/${g}/${w}`),await Os(`skill-file-delete`)),k.existed&&fe?.(`files`),successResponse(t,200,SkillFileDeleteSuccessSchema,{path:w,existed:k.existed,kind:E},{handler:`skill-file-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0});async function ku(e,t){if(e.method===`GET`)return Eu(e,t);if(e.method===`PUT`)return Du(e,t);if(e.method===`DELETE`)return Ou(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-file`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Au=withValidation(SkillInstallRequestSchema,async(e,t,s)=>{try{let e=ru(s.scope);if(!eu(s.name,t,`skill-install`))return;if(s.scope===`project`&&!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let g=su(s.scope),S=resolve(e,s.name);if(!existsSync(S)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${s.name}" not found in ${s.scope} scope — create it with write({ skill }) first.`});return}let w=validateSkillForInstall(S,s.name);if(!w.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${s.name}" cannot be installed: ${w.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let E=s.scope===`global`?s.targets?PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)):[...PROJECT_SKILL_EDITOR_IDS]:s.targets===void 0?resolveSkillTargets(g,readSkillTargets(g)??void 0):PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)),D=[],O=[];E.length===0&&s.targets===void 0&&(D.push(s.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),O.push(`no-targets`)),w.hasScripts&&(D.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),O.push(`scripts-present`));let k=resolvedHosts(readInstalledSkills(g).skills[s.name]?.hosts??[]).filter(e=>!E.includes(e));k.length>0&&reverseProjectSkill(s.name,g,k);let j=projectSkill(S,s.name,g,E);j.length===0?await removeSkillInstall(g,s.name):await recordSkillInstall(g,s.name,{hosts:j,scope:s.scope,scripts:w.hasScripts,installedAt:new Date().toISOString()}),fe?.(`files`),successResponse(t,200,SkillInstallSuccessSchema,{name:s.name,hosts:j,scripts:w.hasScripts,warnings:D,warningCodes:O},{handler:`skill-install`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),ju=withValidation(SkillUninstallRequestSchema,async(e,t,s)=>{try{if(!eu(s.name,t,`skill-uninstall`))return;let e=su(s.scope);if(!e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let g=await cu(e,s.name);fe?.(`files`),successResponse(t,200,SkillUninstallSuccessSchema,{name:s.name,uninstalled:g},{handler:`skill-uninstall`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`});async function Mu(e,t){if(e.method===`GET`)return Nu(e,t);if(e.method===`PUT`)return Pu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-targets`,extraHeaders:{Allow:`GET, PUT`}})}let Nu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=Ce?readSkillTargets(Ce):null;successResponse(t,200,SkillTargetsGetSuccessSchema,{targets:resolveSkillTargets(Ce??``,e??void 0),configured:e!==null},{handler:`skill-targets-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),Pu=withValidation(SkillTargetsPutRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let e=s.targets,g=new Set(e),S=resolveSkillTargets(Ce,readSkillTargets(Ce)??void 0),w=ru(`project`);await writeSkillTargets(Ce,e);let{reprojected:E,bundleHosts:D}=await reprojectAllManagedSkills({projectDir:Ce,skillsRoot:w,targets:e});fe?.(`files`),successResponse(t,200,SkillTargetsPutSuccessSchema,{targets:e,reprojected:E,bundleHosts:D,removedFrom:S.filter(e=>!g.has(e))},{handler:`skill-targets-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`}),Fu=withValidation(SkillRestoreRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!eu(s.name,t,`skill-restore`))return;if(s.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let S=ee?.current;if(!S){errorResponse(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let w=await restoreSkillVersion({shadow:S,contentDir:g,contentRoot:ce??`.`,name:s.name,version:s.version});if(!w.ok){let[e,s]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[w.code];errorResponse(t,e,s,w.error,{handler:`skill-restore`,detail:w.code});return}let E=[],D=validateSkillForInstall(resolve(g,`.ok`,`skills`,s.name),s.name);D.ok||E.push(`Restored, but the skill no longer validates: ${D.errors.join(` `)}`),E.push("Run `install` to push the restored version to your editors."),Ds(e,Ts(`skill`,``,s.name),`skill-restore: ${s.name} @ ${s.version.slice(0,8)}`),await Os(`skill-restore`),fe?.(`files`),successResponse(t,200,SkillRestoreSuccessSchema,{name:s.name,version:s.version,restoredFiles:w.restoredFiles,warnings:E},{handler:`skill-restore`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Iu=withValidation(SkillUpdateRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!eu(g.name,t,`skill-update`))return;if(!isPackSkillName(g.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(g.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let S=readBundledPackSkill(g.name);if(S===null||S.version===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let w=resolve(ru(`project`),g.name,`SKILL.md`);if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let E;try{E=readSkillVersion(readFileSync(w,`utf-8`))}catch{}let D,O=ee?.current;if(O)try{let e=oe?.()??`main`;D=(await saveVersion(O,ce??`.`,[SERVICE_WRITER],e,`Before updating ${g.name} (${E??`unversioned`} → ${S.version})`)).checkpointRef}catch(e){getLogger(`skills`).warn({err:e,skill:g.name},`pre-update checkpoint failed — proceeding with overwrite`)}let k=skillLiveDocName(`project`,g.name);if(Gl(k,`skill-update`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Xi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-update`);return}if(q?.kind===`divergence`){Kt(t,`skill-update`);return}Ds(e,Ts(`skill`,``,g.name),`skill-pack-update: ${g.name} (${E??`unversioned`} → ${S.version})`),await Os(`skill-update`),fe?.(`files`),successResponse(t,200,SkillUpdateSuccessSchema,{name:g.name,version:S.version,...E===void 0?{}:{previousVersion:E},...D===void 0?{}:{checkpointRef:D}},{handler:`skill-update`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function Lu(e){let t=new Map;for(let s of e){let e=s.path.split(`/`).filter(Boolean);e.pop();for(let g=1;g<=e.length;g++){let S=e.slice(0,g).join(`/`);t.set(S,Math.max(t.get(S)??0,s.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function Ru(e,t){let s=t.trim().toLowerCase();if(!s||!e)return;let g=e.toLowerCase().indexOf(s);if(g<0)return;let S=Math.max(0,g-80),w=Math.min(e.length,g+s.length+120),E=S>0?`…`:``,D=w<e.length?`…`:``;return`${E}${e.slice(S,w).replace(/\s+/g,` `).trim()}${D}`}function zu(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Bu(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let s=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return s.length>0?s:void 0}function Vu(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Hu(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function Uu(e,t,s,g){let S=g.documents.filter(e=>!isHiddenDocName(e.path)),w=S.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!Be?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:w,capable:!1};Be.embedCorpus(S);let E,D=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await Be.queryScores(e,S);if(D=performance.now()-t,s&&s.size>0){let e=Ve?.();E=e===void 0?{scores:s}:{scores:s,similarityFloor:e}}}let O=Be.getStatus();return{input:E,status:{capable:O.capable,applied:!1,coverage:{embedded:O.embeddedCount,total:w}},queryEmbedMs:D,pageTotal:w,capable:O.capable}}function Wu(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Ru(e.document.content,t):void 0}}async function Gu(e){let t=performance.now();if(ed())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:s,truncated:g}=await td(),S=await Uu(e.query,e.intent,e.semanticParam,s),w=searchWorkspaceCorpus(s,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:S.input}).map(t=>Wu(t,e.query)),E;if(S.status){let t=w.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),s=t>0;E={...S.status,applied:s},recordSemanticQuery({outcome:S.capable?s?`applied`:S.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:S.capable,embedded:S.status.coverage.embedded,total:S.pageTotal,queryEmbedMs:S.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:w,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...E?{semantic:E}:{},...g?{truncated:!0}:{}}}function Ku(){let e=ru(`project`);if(!existsSync(e))return[];let t;try{t=readdirSync(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let g of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!g.isDirectory()||!SKILL_NAME_REGEX.test(g.name))continue;let t=resolve(e,g.name,`SKILL.md`);try{let e=statSync(t);s.push({name:g.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return s}function qu(){let e=[];for(let t of Ku()){let s=t.name,g=``;try{let{frontmatter:e,body:S}=Jl(readFileSync(t.absolutePath,`utf-8`));typeof e.name==`string`&&e.name&&(s=e.name),g=`${typeof e.description==`string`?e.description:``}\n\n${S}`.trim()}catch{}e.push(createWorkspaceSearchDocument({kind:`page`,path:skillLiveDocName(`project`,t.name),title:s,content:g,modifiedTs:t.mtimeMs}))}return e}function Ju(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let Yu=new Map;async function Xu(){let e=[],t=[],s=new Set;for(let[g,S]of D()){if(isSystemDoc(g)||isConfigDoc(g)||g.startsWith(`.ok/skills/`))continue;if(S.kind===`file`){t.push(createWorkspaceSearchDocument({kind:`file`,path:g,modifiedTs:Date.parse(S.modified),aliases:S.aliases}));continue}s.add(g);let w=Ju(S),E=Yu.get(g);if(E&&E.key===w){e.push(E.doc);continue}let D=``,O=g,k=!1;try{D=await readFile$1(S.canonicalPath,`utf-8`)}catch(e){k=!0,console.warn(`[search] Failed to read ${g}:`,e)}if(!k)try{O=extractPageTitle(D,g)}catch(e){console.warn(`[search] Failed to extract title for ${g}:`,e)}let j=createWorkspaceSearchDocument({kind:`page`,path:g,title:O,content:D,modifiedTs:Date.parse(S.modified),aliases:S.aliases});k||Yu.set(g,{key:w,doc:j}),e.push(j)}for(let e of Yu.keys())s.has(e)||Yu.delete(e);let g=getSearchMaxEntries(),S=t,w=!1;return t.length>g&&(w=!0,S=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,g),getLogger(`search`).warn({dropped:t.length-S.length,retained:S.length,limit:g},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),searchCorpusTruncatedCounter().add(1)),{documents:[...e,...qu(),...S,...Lu([...e,...S])],truncated:w}}function Zu(){return Ku().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function Qu(){return k?`gen:${k()}|skills${Zu()}`:`${[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${Ju(t)}`).join(``)}|skills${Zu()}`}let $u=Pe===void 0;Pe?.then(()=>{$u=!0},e=>{$u=!0,log$6.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function ed(){return!$u}async function td(){let e=`${g}${Ce??``}`,t=Qu(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return{corpus:s.corpus,truncated:s.truncated??!1};if(s?.fingerprint===t&&s.pending)return s.pending;let S=Xu().then(({documents:e,truncated:t})=>({corpus:createWorkspaceSearchCorpus(e),truncated:t}));workspaceSearchCaches.set(e,{fingerprint:t,pending:S});try{let s=await S;return workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:s.corpus,truncated:s.truncated}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function nd(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{td().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}nd();async function rd(e,t){if(e.method===`GET`)return ad(e,t);if(e.method===`POST`)return od(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let ad=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=zu(s.searchParams.get(`intent`)),E=au(s.searchParams.get(`ranking`)),D=Bu(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),O=Vu(s.searchParams.get(`semantic`)),k=Hu(s.searchParams.get(`source`)),j=g===null?void 0:Number(g);if(S.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{successResponse(t,200,SearchSuccessSchema,await Gu({query:S,intent:w,ranking:E,scopes:D,limit:j,semanticParam:O,source:k}),{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),od=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=zu(s.intent),w=au(s.ranking),E=Bu(s.scopes??s.scope),D=typeof s.limit==`number`?s.limit:void 0,O=Vu(s.semantic),k=Hu(s.source);if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{successResponse(t,200,SearchSuccessSchema,await Gu({query:g,intent:S,ranking:w,scopes:E,limit:D,semanticParam:O,source:k}),{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),sd=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function cd(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform,isSchemeRegistered:Et.probeWithCache})}catch(e){t.headersSent||(log$6.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function ld(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$6.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let ud=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!Ce){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=s.kind===`doc`?s.docPath:s.folderPath;if(!isValidSharePath(e,s.kind)){emitShareConstructUrlLog(`invalid-path`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let S=readGitHeadBranch(Ce);if(S===null){if(readOriginGitHubRepo(Ce).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=readOriginGitHubRepo(Ce);if(w.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(w.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(Ce,S)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:S},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let E=toGitRelativePath(Ce,g);if(E===null)throw Error(`content dir is not contained within the project dir`);let D=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;E!==``&&D&&getLogger(`share`).warn({action:`construct-url`,kind:s.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let O;if(s.kind===`doc`)O=buildGitHubBlobUrl(w.owner,w.repo,S,s.docPath);else{let e=s.folderPath===``?E:s.folderPath;O=buildGitHubTreeUrl(w.owner,w.repo,S,e)}let k=`${SHARE_BASE_URL}${encodeShareUrl(O)}`,j=await computeShareFreshness(Ce,S,E===``?e:e===``?E:`${E}/${e}`,s.kind);emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind,freshness:j}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:k,sharedUrl:O,branch:S,freshness:j},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}),dd=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`branch`),S=s.searchParams.get(`path`),w=s.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!isValidBranchName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoPath(S,w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(Ce,g,S,w),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),fd=withValidation(ShareTargetStatusRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}if(!isValidBranchInfoPath(s.path,s.kind)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}let e=toGitRelativePath(Ce,g);if(e===null)throw Error(`content dir is not contained within the project dir`);let S=e===``?s.path:s.path===``?e:`${e}/${s.path}`;successResponse(t,200,ShareTargetStatusResponseSchema,await computeShareTargetStatus(Ce,s.branch,S,s.kind),{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG,cause:e})}},{handler:SHARE_TARGET_STATUS_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}),pd=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(Ce,s.branch,{fastForward:s.fastForward===!0})),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function md(e){let[t,...s]=ye,g=[...s,...e];return await new Promise((e,s)=>{let S=spawn(t,g,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,S.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),D=[],O=[];S.stdout.on(`data`,e=>D.push(e)),S.stderr.on(`data`,e=>O.push(e)),S.on(`close`,t=>{if(clearTimeout(E),w){s(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let g=Buffer.concat(D).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(O).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:g,code:t})}),S.on(`error`,e=>{clearTimeout(E),s(e)})})}let hd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await md([`share`,`owners`,`--json`]),s=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,s.ok?`ok`:s.error,s.ok?{count:s.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,s,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),gd=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`owner`)??``,S=s.searchParams.get(`name`)??``;if(!isValidShareOwnerName(g)||!isValidShareRepoName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!Ge.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await md([`share`,`name-check`,`--owner`,g,`--name`,S,`--json`]),s=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,s.ok?`ok`:s.error,s.ok?{available:s.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,s,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),_d=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!Ce){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(s.owner)||!isValidShareRepoName(s.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!Ge.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,s.owner,`--name`,s.name,`--visibility`,s.visibility,`--project-dir`,Ce,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await md(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&ve?.()?.refreshRemote().catch(()=>{}),successResponse(t,200,SharePublishResponseSchema,S,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),vd=withValidation(ClientLogsRequestSchema,async(e,t,s)=>{try{let e=getLogger(`renderer`);for(let t of s.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}successResponse(t,200,ClientLogsSuccessSchema,{accepted:s.entries.length},{handler:`client-logs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`client-logs`})}),yd=Ce?getLocalDir(Ce):null;async function bd(e,t){if(e.method===`DELETE`){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-config`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-config`});return}yd&&clearArmedPaneTarget(yd),t.setHeader(`Cache-Control`,`no-store`),t.statusCode=204,t.end();return}if(e.method===`GET`||e.method===`HEAD`){try{let s=e.headers.host,g={collabUrl:s?`ws://${s}/collab`:null,previewUrl:null,port:yd?readServerLock(yd)?.port??0:0,paneTarget:yd?readArmedPaneTarget(yd):null,singleFile:We};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}successResponse(t,200,ApiConfigSuccessSchema,g,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD, DELETE`}})}let xd=`local-op-embeddings-set-key`,Sd=`local-op-embeddings-clear-key`,Cd=`/api/local-op/embeddings`,wd=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Ge.tryAcquire(Cd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:xd,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(Ue).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:xd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:xd,cause:e})}finally{Ge.release(Cd)}},{handler:xd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:xd})}),Td=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(Cd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Sd,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(Ue),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:Sd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Sd,cause:e})}finally{Ge.release(Cd)}},{handler:Sd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Sd})}),Ed=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(Be){let t=Be.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(Ue).get(),D=process.env.OK_EMBEDDINGS_API_KEY??null,O=E?`file`:D?`env`:null,k=O!==null,j=E??D,F=j&&j.length>=8?j.slice(-4):null,L=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(L+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:k,keySource:O,keyHint:F,ready:s,capable:g,embedded:S,total:L},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Dd={"/api/config":bd,"/api/asset":Tc,"/api/asset-text":Dc,"/api/document":Is,"/api/documents":Rs,"/api/backlinks":$s,"/api/backlink-counts":ec,"/api/forward-links":tc,"/api/link-graph":nc,"/api/dead-links":ac,"/api/orphans":rc,"/api/hubs":ic,"/api/tags":Pl,"/api/pages":Lc,"/api/folder-config":Vl,"/api/template":ql,"/api/templates":Kl,"/api/skill":du,"/api/skill-file":ku,"/api/skills":uu,"/api/skills/management":gu,"/api/skill/install":Au,"/api/skill/uninstall":ju,"/api/skill/restore":Fu,"/api/skill/update":Iu,"/api/skill-targets":Mu,"/api/search":rd,"/api/semantic-status":Ed,"/api/suggest-links":Rc,"/api/page-headings":Nc,"/api/create-page":Ac,"/api/create-folder":jc,"/api/duplicate-path":Mc,"/api/rename-path":Pc,"/api/delete-path":Fc,"/api/trash/cleanup":Ic,"/api/upload":zc,"/api/agent-write":ks,"/api/agent-write-md":As,"/api/frontmatter-patch":Ns,"/api/agent-patch":oc,"/api/agent-undo":sc,"/api/agent-activity":cc,"/api/agent-burst-diff":lc,"/api/save-version":mc,"/api/history":hc,"/api/rollback":_c,"/api/metrics/reconciliation":vc,"/api/metrics/parse-health":yc,"/api/metrics/agent-presence":Sc,"/api/__embed-detect":Cc,"/api/server-info":bc,"/api/share/construct-url":ud,"/api/share/target-status":fd,"/api/git/branch-info":dd,"/api/git/checkout":pd,"/api/share/publish/owners":hd,"/api/share/publish/name-check":gd,"/api/share/publish":_d,"/api/principal":xc,"/api/rescue":kc,"/api/workspace":wc,"/api/sync/status":yl,"/api/sync/trigger":xl,"/api/sync/conflicts":Cl,"/api/sync/conflict-content":El,"/api/sync/resolve-conflict":Tl,"/api/local-op/clone":Gc,"/api/local-op/ok-init":Yc,"/api/local-op/auth/login":al,"/api/local-op/auth/status":ul,"/api/local-op/auth/repos":fl,"/api/local-op/auth/signout":hl,"/api/local-op/auth/set-identity":vl,"/api/local-op/embeddings/set-key":wd,"/api/local-op/embeddings/clear-key":Td,"/api/installed-agents":Ml,"/api/spawn-cursor":ld,"/api/handoff":cd,"/api/install-skill":jl,"/api/skill/install-state":sd,"/api/seed/plan":Dl,"/api/seed/apply":Ol,"/api/seed/packs":kl,"/api/client-logs":vd};q&&(Dd[`/api/test-reset`]=dc,Dd[`/api/test-flush-git`]=uc,Dd[`/api/test-rescan-backlinks`]=fc,Dd[`/api/test-rescan-files`]=pc);let Od=new Set(`/api/upload./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),kd=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let s=e.url?.split(`?`)[0];if(!s)return;let g=t=>{let s=e.headers[t];if(s!==void 0)return Array.isArray(s)?s.join(`, `):s};if(recordEmbedProbe({ts:Date.now(),url:s,method:e.method??``,ua:g(`user-agent`),origin:g(`origin`),referer:g(`referer`),host:g(`host`),remote:e.socket?.remoteAddress,secChUa:g(`sec-ch-ua`),secChUaMobile:g(`sec-ch-ua-mobile`),secChUaPlatform:g(`sec-ch-ua-platform`),secFetchSite:g(`sec-fetch-site`),secFetchDest:g(`sec-fetch-dest`),secFetchMode:g(`sec-fetch-mode`),secFetchUser:g(`sec-fetch-user`)}),s.startsWith(`/api/`)){let s=e.headers.origin;if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${CLIENT_VERSION_HEADER.protocol}, ${CLIENT_VERSION_HEADER.runtime}, ${CLIENT_VERSION_HEADER.kind}`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Od.has(s)||kd.some(e=>s.startsWith(e))){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(We&&s.startsWith(`/api/`)){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:Dd[s]||(E=`/api/*`);let D=getTracer(),O=Date.now();await context.with(S,()=>D.startActiveSpan(`HTTP ${w} ${E}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_URL_PATH]:s,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async g=>{try{let S=Dd[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await gc(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await Fl(e,t,g))}E||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${w} ${s}`});let D=t.statusCode;g.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,D),D>=500&&g.setStatus({code:SpanStatusCode.ERROR,message:`status ${D}`})}catch(e){throw g.recordException(e),g.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E,cause:e}),e}finally{g.end();let e=(Date.now()-O)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedSingleDirBasenameIndex(e){let t;try{t=readdirSync(e.contentDir,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,e.contentDir);return}for(let s of t)s.isFile()&&isSupportedAssetFile(s.name,ASSET_EXTENSIONS)&&e.basenameIndex.add(s.name)}async function seedBasenameIndex(e){let t=e.contentDir,s=new Set;async function g(S){let w;try{w=await readdir(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=toPosix(relative(t,w));if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=await lstat(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=await realpath(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=await stat$1(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?await g(S):E.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),await g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}await g(t)}var AutoStartDisabledError=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const log$5=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$5.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$5.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$5.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,s,g=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:S}=await import(`./git-handle-DG8d2xCi-C_CAAChL.mjs`),w=S(this.projectDir,{credentialArgs:g});switch(t){case`mine`:await w.git.raw([`checkout`,`--ours`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`theirs`:await w.git.raw([`checkout`,`--theirs`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`content`:{if(s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),g=resolve(t,e);if(!isWithinDir(g,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(g,s,`utf-8`),await w.git.raw([`add`,`--`,e]);break}case`delete`:await w.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await w.git.raw([`commit`,`--no-edit`]),log$5.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let e=(await w.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
1949
1950
  `).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:s});g=e.length>0}catch(e){log$5.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}g||this.addConflict({file:e,detectedAt:s}),log$5.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let S=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${g?`unmerged files re-added`:`original file re-added`} — ${S}`,{cause:t})}}};const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,s=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,g=0,S=null,w=null,E=!1,D=!1;function O(){S!==null&&(t.clearTimeout(S),S=null),w!==null&&(t.clearTimeout(w),w=null)}function k(){O(),!(D||E)&&g===0&&(s>0&&s<e.thresholdMs&&(w=t.setTimeout(()=>{w=null,g===0&&!E&&e.log?.warn({msUntilShutdown:s,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-s)),S=t.setTimeout(()=>{if(S=null,!(D||E)&&g===0){E=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let j=(e,t)=>{e.url?.startsWith(`/collab`)&&(g++,O(),t.once(`close`,()=>{g--,g<0&&(g=0),g===0&&k()}))};return e.httpServer.on(`upgrade`,j),k(),{detach:()=>{D||(D=!0,e.httpServer.off(`upgrade`,j),O())}}}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function readRawSinkBlock(e){if(!existsSync(e))return{};let t;try{t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!isObject(t))return{};let s=t.telemetry;if(!isObject(s))return{};let g=s.localSink;return isObject(g)?g:{}}function readBoolean(e){return typeof e==`boolean`?e:void 0}function readPositiveNumber(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function readStringArray(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function readMaxBytes(e){if(isObject(e))return readPositiveNumber(e.maxBytes)}function resolveLocalSinkConfig(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=readRawSinkBlock(resolveConfigPath(`project`,e.projectDir)),s=readRawSinkBlock(resolveConfigPath(`project-local`,e.projectDir));if((readBoolean(s.enabled)??readBoolean(t.enabled)??!0)===!1)return null;let g=readMaxBytes(s.spans)??readMaxBytes(t.spans)??52428800,S=readMaxBytes(s.logs)??readMaxBytes(t.logs)??26214400,w=readStringArray(s.attributeDenylist)??readStringArray(t.attributeDenylist)??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:g,attributeDenylist:w},logs:{projectDir:e.projectDir,maxBytes:S}}}const MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let s=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return s?s.slice(0,128):t}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let s=t.validateToolInput;if(typeof s!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,g){if(!e.inputSchema||!isZodSchema(e.inputSchema))return s.call(this,e,t,g);let S=await e.inputSchema.safeParseAsync(t);if(S.success)return S.data;let w=prettifyError(S.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${g}:\n${w}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const SPAWN_TIMEOUT_MS=2e3,LOCK_SCAN_MAX_DEPTH=3,LOCK_SCAN_MAX_ENTRIES=2e3,OK_LOCK_DIR_ARG_PREFIX=`--ok-lock-dir-b64=`,OK_PROJECT_PATH_ARG_PREFIX=`--ok-project-path=`,OK_PROCESS_PGREP_QUERY=`cli\\.mjs|open-knowledge|Open ?Knowledge(\\.app| Helper)|--ok-lock-dir-b64=|--ok-project-path=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`,OK_PROCESS_PATTERNS=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function isOkProcess(e){return OK_PROCESS_PATTERNS.some(t=>t.test(e))}function extractMarkedLockDir(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(OK_LOCK_DIR_ARG_PREFIX));if(t==null)return null;let s=t.slice(18);if(!s)return null;try{let e=Buffer.from(s,`base64url`).toString(`utf8`);return isAbsolute(e)?e:null}catch{return null}}function extractProjectPathArg(e){let t=e.indexOf(OK_PROJECT_PATH_ARG_PREFIX);if(t===-1)return null;let s=t+18,g=e.slice(s),S=g.search(/\s--/),w=(S===-1?g:g.slice(0,S)).trim();return w&&isAbsolute(w)?w:null}function parsePgrepOutput(e){let t=[];for(let s of e.split(`
1950
1951
  `)){let e=s.trim();if(!e)continue;let g=e.indexOf(` `);if(g===-1)continue;let S=e.slice(0,g),w=e.slice(g+1),E=Number.parseInt(S,10);!Number.isNaN(E)&&isOkProcess(w)&&t.push({pid:E,command:w})}return t}function parsePsOutput(e){let t=[],s=e.split(`
1951
1952
  `);for(let e=1;e<s.length;e++){let g=s[e]?.trim();if(!g)continue;let S=g.indexOf(` `);if(S===-1)continue;let w=g.slice(0,S),E=g.slice(S+1).trim(),D=Number.parseInt(w,10);!Number.isNaN(D)&&isOkProcess(E)&&t.push({pid:D,command:E})}return t}async function findOkProcessEntries(){let e=spawnSync(`pgrep`,[`-a`,`-f`,OK_PROCESS_PGREP_QUERY],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});if(!(e.error!=null&&e.error.code===`ENOENT`)){let t=e.stdout??``,s=parsePgrepOutput(t);if(s.length>0||t.trim()===``)return s}let t=spawnSync(`ps`,[`-axo`,`pid,command`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});return t.error!=null||!t.stdout?[]:parsePsOutput(t.stdout)}function extractOkBinaryPath(e){let t=e.trim().split(/\s+/).filter(Boolean);for(let e of t){if(e.startsWith(`@`))continue;let t=basename(e);if(t===`open-knowledge`||t===`ok`||e.endsWith(`/packages/cli/src/cli.ts`)||e.endsWith(`/packages/cli/dist/cli.mjs`)||t===`cli.mjs`||t===`cli.ts`)return e}return null}function processCommand(e){let t=spawnSync(`ps`,[`-p`,String(e),`-o`,`command=`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});return t.error!=null||!t.stdout?null:t.stdout.trim()||null}function processUsage(e){let t=spawnSync(`ps`,[`-p`,String(e),`-o`,`%cpu=,%mem=`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});if(t.error!=null||!t.stdout)return null;let[s,g]=t.stdout.trim().split(/\s+/),S=Number.parseFloat(s??``),w=Number.parseFloat(g??``);return Number.isNaN(S)||Number.isNaN(w)?null:{cpuPercent:S,memPercent:w}}async function pidCwd(e){let t=spawnSync(`lsof`,[`-p`,String(e),`-a`,`-d`,`cwd`,`-Fn`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});if(t.error!=null)return null;let s=t.stdout??``;for(let e of s.split(`
@@ -2005,7 +2006,7 @@ $$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-p
2005
2006
  `),{document:E,version:e.version,previewUrl:J?.url??null,...J?{previewUrlSource:J.source}:{},...j?{summary:j}:{},...L?{warnings:L}:{}})})}const DESCRIPTION$4=["[Requires: Hocuspocus server] Ranked retrieval across ALL non-ignored files (markdown by title/body, other file types by name/path, plus folders) — pair with `exec` `grep` for exhaustive content search. The cmd-K engine (title boost + body BM25 + recency).",``,"NAMES/paths are indexed for all files; BODY content for markdown only. Two-tier agent model: run this fast indexed `search` (all files by name/path + markdown content) IN PARALLEL with `exec` (`grep`) for exhaustive literal-string content search across every file — instant ranked hits plus full content coverage. Reach for `exec` grep when you need to match content inside code/config/data files.",``,"When semantic search is enabled for the workspace (an opt-in setting with an API key), an embeddings signal is additionally fused into `full_text` ranking, surfacing conceptually-related pages that share no keywords. This tool opts in by default; the `semantic` block in the response reports coverage. Note: with semantic enabled, the query and matching page content are sent to the configured embeddings provider (content egress). Set `semantic: false` to force pure-lexical ranking for a call.",``,"Returns scored `page`, `folder`, and name-only `file` hits, each with a `signals` breakdown (lexical / fullText / recency / vector); markdown `page` hits also carry a body snippet (`file` hits never do — name-only). `exec`-grep covers every content occurrence and needs no server.",``,'Cold start: right after the server boots, the response may carry `ready: false` with an empty `results` while the index is still building. That empty set is NOT authoritative — wait ~2-3 seconds, then retry (agents have no built-in delay, so do not retry in immediate succession). If it is still `ready: false` after 2-3 retries (e.g. a very large workspace), fall back to `exec("grep ...")` rather than polling further. Once `ready` is true/omitted the results are complete.',``,`**Parameters:**`,"- `query` — Free-form; tokenized across title, name, path segments, and (with `full_text`) body.","- `intent` (optional) — `omnibar` searches title/path/folders only (fast); `full_text` includes body. Default `full_text`.","- `scopes` (optional) — Result scope: `page` | `folder` | `file` | `content`. Defaults derive from `intent`.","- `limit` (optional) — Max rows; default 20, max 100.","- `semantic` (optional) — Set `false` to force pure-lexical ranking even when semantic search is enabled. Omit to use semantic when available.",``,'If the server is down, the tool returns a recovery hint — use `exec("grep ...")` as the server-free fallback.'].join(`
2006
2007
  `),InputSchema={query:string().describe(`Search query — title, path, or body terms.`),intent:_enum([`omnibar`,`full_text`]).optional().describe(`'omnibar' for title/path/folder only (fast); 'full_text' includes body content. Default 'full_text'.`),scopes:array(_enum([`page`,`folder`,`content`,`file`])).optional().describe(`Override the default scope set. Members: 'page', 'folder', 'file', 'content'. Defaults derive from intent.`),limit:number().int().min(1).max(100).optional().describe(`Max rows; default 20, max 100.`),semantic:boolean().optional().describe(`Set false to force pure-lexical ranking for this call even when semantic search is enabled. Omit to use semantic when available.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},SearchResultRowSchema=object$1({kind:_enum([`page`,`folder`,`file`]),path:string(),docName:string(),title:string().nullable(),score:number(),signals:object$1({lexical:number(),fullText:number(),recency:number(),vector:number().optional()}),snippet:string().optional(),previewUrl:string().nullable(),previewUrlSource:_enum(PREVIEW_URL_SOURCES).optional()}),SearchSemanticStatusSchema=object$1({capable:boolean(),applied:boolean(),coverage:object$1({embedded:number().int(),total:number().int()})}),OutputSchema$1=outputSchemaWithText({cwd:string(),query:string(),intent:string(),resultCount:number().int(),results:array(SearchResultRowSchema),elapsedMs:number().nullable(),semantic:SearchSemanticStatusSchema.optional(),ready:literal(!1).optional()});function isSearchKind(e){return e===`page`||e===`folder`||e===`file`}function normalizeSignals(e){return{lexical:typeof e?.lexical==`number`?e.lexical:0,fullText:typeof e?.fullText==`number`?e.fullText:0,recency:typeof e?.recency==`number`?e.recency:0,...typeof e?.vector==`number`?{vector:e.vector}:{}}}function normalizeSemanticStatus(e){if(!(!e||typeof e.capable!=`boolean`))return{capable:e.capable,applied:e.applied===!0,coverage:{embedded:typeof e.coverage?.embedded==`number`?e.coverage.embedded:0,total:typeof e.coverage?.total==`number`?e.coverage.total:0}}}function formatSemanticNote(e){if(!e)return``;if(!e.capable)return`> Semantic: enabled but not ready (no API key, or warming up) — lexical ranking only.`;let{embedded:t,total:s}=e.coverage;return e.applied?`> Semantic: on — vector signal contributed (${t}/${s} pages embedded).`:t<s?`> Semantic: on — indexing ${t}/${s} pages; vectors are still filling in, re-run for fuller coverage.`:`> Semantic: on — no page cleared the similarity threshold for this query.`}function formatResultsBlock(e){if(e.length===0)return``;let t=[];for(let s of e){let e=s.title?.trim()||s.path;t.push(`### ${e} (${s.path})`),t.push(`Score ${s.score.toFixed(2)} — kind: ${s.kind}`),s.snippet&&t.push(s.snippet),t.push(``)}return t.join(`
2007
2008
  `)}function register$4(e,t){e.registerTool(`search`,{description:DESCRIPTION$4,inputSchema:InputSchema,outputSchema:OutputSchema$1,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async e=>{try{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(`${HOCUSPOCUS_NOT_RUNNING_ERROR}\nFor server-free literal-string search, use \`exec("grep ...")\` instead — it walks the filesystem and does not need Hocuspocus.`,!0);let E=e.intent??`full_text`,D=e.limit??20,O={query:e.query,intent:E,limit:D,semantic:e.semantic??!0,source:`mcp`};e.scopes&&(O.scopes=e.scopes);let k=await httpPost(w,`/api/search`,O);if(!k.ok)return textResult(`Error: ${k.error}`,!0);let{resolve:j}=await buildListResolver({config:S,resolveCwd:async()=>g},g),F=(k.results??[]).flatMap(e=>{if(!isSearchKind(e.kind)||typeof e.path!=`string`)return[];let t=docNameFromPath(e.path),s=j(t);return[{kind:e.kind,path:e.path,docName:t,title:e.title??null,score:typeof e.score==`number`?e.score:0,signals:normalizeSignals(e.signals),...e.snippet?{snippet:e.snippet}:{},previewUrl:s?.url??null,...s?{previewUrlSource:s.source}:{}}]}),L=normalizeSemanticStatus(k.semantic),B=k.ready!==!1,H={cwd:g,query:e.query,intent:E,resultCount:F.length,results:F,elapsedMs:typeof k.elapsedMs==`number`?k.elapsedMs:null,...L?{semantic:L}:{},...B?{}:{ready:!1}},q=`## Search results for "${e.query}" (${F.length} hit${F.length===1?``:`s`}, intent: ${E})`,ee=formatSemanticNote(L),J=B?F.length===0?`No matches for "${e.query}".`:`${q}\n\n${formatResultsBlock(F)}`:`The workspace search index is still warming — results for "${e.query}" are not ready yet. Wait ~2-3 seconds, then retry; if it is still warming after 2-3 retries, use \`exec("grep ...")\` for an index-free search instead.`;return textPlusStructured(ee?`${J}\n${ee}`:J,H)}catch(e){return textResult(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}const DESCRIPTION$3=["[Requires: Hocuspocus server] Build a shareable GitHub-substrate URL (`https://openknowledge.ai/d/...`) pinned to the project's current branch + the focused target (a doc or a folder). Read-only against the working tree — no commits, no pushes, no `git fetch`.",``,`Use this when the user asks for a share link / shareable link / URL to send to a teammate. Recipients open the link to receive the doc (or folder subtree) into their own OpenKnowledge install.`,``,"**Publishing is a user act.** Agents do NOT publish projects to GitHub from this tool. When the project has no GitHub remote, this tool returns an error pointing the user at the Share wizard (or `gh repo create` + `git push`) — it does not run those steps itself.",``,`**Parameters:**`,'- `path` — Content-dir-relative target. For a doc, extension-less (trailing `.md`/`.mdx` is stripped; the on-disk file is probed automatically). For a folder, the directory path. The empty string `""` is the content-root sentinel (folder-only).',"- `kind` (optional) — `'doc'` or `'folder'`. Omit to auto-probe disk (`.mdx` → `.md` → directory, first hit wins). REQUIRED when `path` is empty (`\"\"`), since auto-probe cannot disambiguate the root.","- `cwd` (optional) — Project root (see `cwd` description below).",``,"**Preconditions:** project on a named branch (not detached HEAD); origin set to a `github.com` remote; the branch already pushed to origin."].join(`
2008
- `);function messageForShareError(e,t){switch(e){case`no-remote`:return"This project has no GitHub remote. Ask the user to push it to GitHub first (e.g. `gh repo create` then `git push -u origin <branch>`), or use the Share button in the editor to run the Publish wizard. Agents do not publish projects from this tool.";case`detached-head`:return"HEAD is detached (no branch checked out). Ask the user to check out a branch (`git checkout <branch>`) before sharing.";case`branch-not-on-origin`:{let e=" (If the user says it is already pushed, ask them to `git fetch origin` first to refresh the local mirror, then retry.)";return t?`Branch \`${t}\` is not on origin yet. Ask the user to push it (\`git push -u origin ${t}\`), then retry.${e}`:`The current branch is not on origin yet. Ask the user to push it (\`git push -u origin <branch>\`), then retry.${e}`}case`non-github-remote`:return"Origin is not a `github.com` remote. Share links are GitHub-only in v1.";case`invalid-path`:return"The resolved share path is not shareable (escapes the project root or names the `.git` subtree). Pass a normal target path under the content directory.";default:return`Unknown share-construct-url error: ${String(e)}`}}function isExistingDirectory(e){try{return statSync(e).isDirectory()}catch{return!1}}function resolveExistingDocPath(e,t){for(let s of SUPPORTED_DOC_EXTENSIONS){let g=`${t}${s}`;if(existsSync(g)){let t=resolveWithinRoot(e,g);return t.ok?t.rel:null}}return null}function resolveShareTarget(e,t,s,g){if(s===``)return g===`folder`?{ok:!0,kind:`folder`,sharePath:``}:{ok:!1,code:`invalid-path`};let S=resolveWithinRoot(t,s);if(!S.ok)return{ok:!1,code:`target-not-found`};let w=resolveExistingDocPath(e,S.abs.replace(/\.(mdx|md)$/i,``)),E=isExistingDirectory(S.abs);if(g===`doc`)return w===null?E?{ok:!1,code:`kind-mismatch`}:{ok:!1,code:`target-not-found`}:{ok:!0,kind:`doc`,sharePath:w};if(g===`folder`){if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return w===null?{ok:!1,code:`target-not-found`}:{ok:!1,code:`kind-mismatch`}}if(w!==null)return{ok:!0,kind:`doc`,sharePath:w};if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return{ok:!1,code:`target-not-found`}}const OutputSchema=outputSchemaWithText({ok:boolean().describe(`Success discriminator.`),shareUrl:string().optional().describe(`Marketing share URL (success only).`),sharedUrl:string().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:string().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:_enum([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),error:_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:string().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:string().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:string().optional().describe(`Internal: preview-URL provenance.`)});function register$3(e,t){e.registerTool(`share_link`,{description:DESCRIPTION$3,inputSchema:{path:string().describe('Content-dir-relative target. Doc paths are extension-less (`.md`/`.mdx` stripped). Folder paths name a directory. `""` is the content-root sentinel (folder-only).'),kind:_enum([`doc`,`folder`]).optional().describe("Target kind. Omit to auto-probe disk (`.mdx` → `.md` → directory). REQUIRED when `path` is empty."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=resolveShareTarget(g,join(g,S.content.dir),e.path,e.kind);if(!E.ok){let t;if(E.code===`kind-mismatch`){let s=e.kind===`folder`?`folder`:`doc`;t=`\`${e.path}\` exists, but not as a ${s}. Pass \`kind: '${s===`doc`?`folder`:`doc`}'\` to share it as the other kind.`}else t=E.code===`invalid-path`?'Cannot share the content root from an empty path without `kind: "folder"`. Pass a non-empty path, or `kind: "folder"` to share the root.':`Target \`${e.path}\` does not exist under the content directory (looked for \`.md\`, \`.mdx\`, and a directory).`;let s={ok:!1,error:E.code,message:t};return textPlusStructured(`Error: ${t}`,s,!0)}let D=E.kind===`doc`?{kind:`doc`,docPath:E.sharePath}:{kind:`folder`,folderPath:E.sharePath},O;try{O=await fetch(`${w}/api/share/construct-url`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(D),signal:AbortSignal.timeout(3e4)})}catch(e){let t=`Server unreachable: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}let k;try{k=await O.json()}catch(e){let t=`Server returned non-JSON body: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}if(!O.ok){let e;if(k&&typeof k==`object`){let t=k,s=typeof t.title==`string`?t.title:void 0,g=typeof t.detail==`string`?t.detail:void 0;e=s&&g?`${s}: ${g}`:s||g||`HTTP ${O.status}`}else e=`HTTP ${O.status}`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let j=ShareConstructUrlResponseSchema.safeParse(k);if(!j.success){let e=`Server returned an unexpected share-construct-url response shape.`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let F=j.data;if(!F.ok){let e=messageForShareError(F.error,F.branch),t={ok:!1,error:F.error,message:e,...F.branch?{branch:F.branch}:{}};return textPlusStructured(`Error: ${e}`,t,!0)}let{shareUrl:L,sharedUrl:B,branch:H}=F,q={ok:!0,shareUrl:L,sharedUrl:B,branch:H,resolvedKind:E.kind},ee={config:t.config,resolveCwd:t.resolveCwd},J=await resolvePreviewUrlForTool(E.sharePath.replace(/\.(mdx|md)$/i,``),ee,g);if(J&&E.kind===`folder`){let e=E.sharePath.replace(/^\/+|\/+$/g,``),t=e===``?`/#/`:`/#/${encodeDocName(e)}/`;J={...J,url:t}}let Y=e.path===``?`(content root)`:e.path;return textPlusStructured(`Share link for ${E.kind} \`${Y}\` on branch \`${H}\`:\n${L}`,{...q,previewUrl:J?.url??null,...J?{previewUrlSource:J.source}:{}})})}function bundleFileKind(e){return e.replace(/\\/g,`/`).startsWith(`scripts/`)?`script`:`reference`}const INTERNAL_BUNDLE_SKILL_NAMES=new Set(Object.values(BUNDLE_SKILL_NAME));function internalSkillHint(e){return[`"${e}" is one of OpenKnowledge's built-in agent skills — it is NOT managed by this tool and cannot be read or listed here.`,`It is already provided to you in your loaded skill list (a hidden runtime skill projected into your editor); don't fetch or re-load it — just follow the skill you already have.`,"The `skills` tool only covers skills authored as KB content (`.ok/skills` = project, `~/.ok/skills` = global). Built-in `open-knowledge*` skills never appear in either scope."].join(` `)}const SCOPE_FIELD_DESCRIBE="Which level the skill lives at. `project` = this KB's `.ok/skills/` (shared via git with everyone on the project); `global` = your user-level `~/.ok/skills/` (available in every project on this machine, not shared).",SkillListEntryOutputSchema=object$1({name:string().describe("Skill name (its identity; pass to `edit`/`move`/`delete`/`install`)."),scope:_enum([`project`,`global`]).describe(SCOPE_FIELD_DESCRIBE),description:string().optional().describe(`The skill's one-line description (when present).`),installed:boolean().describe(`True when projected into ≥1 editor; false = a Draft.`),hosts:array(string()).describe(`Editor ids the skill is installed into.`),updateAvailable:boolean().optional().describe(`Starter-pack skills only: a newer bundled version is available.`)}),SkillBundleFileEntrySchema=object$1({path:string().describe(`Skill-relative path (e.g. "references/tiers.md").`),kind:_enum([`reference`,`script`]).describe("`reference` (under references/) or `script` (under scripts/).")}),SkillReadOutputSchema=object$1({name:string().describe(`Skill name (its identity).`),scope:_enum([`project`,`global`]).describe(SCOPE_FIELD_DESCRIBE),description:string().describe(`The skill's one-line description (empty if none).`),body:string().describe(`The SKILL.md body (markdown, frontmatter stripped).`),files:array(SkillBundleFileEntrySchema).describe("Bundle files beside SKILL.md (path + kind, no inline text). Read one via `file`.")}),SkillFileReadOutputSchema=object$1({path:string().describe(`Skill-relative path read.`),kind:_enum([`reference`,`script`]).describe("`reference` or `script`."),text:string().describe(`Full text of the bundle file.`)}),DESCRIPTION$2=["[Requires: Hocuspocus server] Read-only discovery for SKILLS — the read half of the skill vocabulary (`write`/`edit`/`delete`/`move`/`install` are the mutate half).",``,"This is how you find and read skills. Skills are addressed by `name` + `scope`, NOT by path — do NOT `ls`/`cat` `.ok/skills/` or pass raw `.ok/...` paths; `.ok/` is opaque internal state.",``,"Covers only skills authored as KB content. OpenKnowledge's own built-in `open-knowledge*` skills (e.g. the `open-knowledge` project skill) are runtime skills already loaded in your skill list — they are NOT here, and you never fetch them through this tool.",``,`**Three modes:**`,"- **List** (omit `name`): every skill across BOTH levels — Project (this KB) and Global (user-level). Returns name, scope, description, installed/hosts, and (for starter packs) `updateAvailable`.","- **Read skill** (pass `name`): that skill's description + body + a `files` list (`{ path, kind }`, no inline text) of its `references/**`+`scripts/**` bundle files. `scope` optional — omitted, it resolves by name (preferring Project when a name exists at both levels).","- **Read file** (pass `name` + `file`): one bundle file's text — the universal read path for references + scripts (no native `cat`)."].join(`
2009
+ `);function freshnessWarning(e,t){return e===`absent`?`This ${t} isn't on GitHub yet. The link won't work until it's pushed.\n\n`:e===`stale`?`This ${t} has unpushed changes. Recipients will see the last pushed version.\n\n`:``}function messageForShareError(e,t){switch(e){case`no-remote`:return"This project has no GitHub remote. Ask the user to push it to GitHub first (e.g. `gh repo create` then `git push -u origin <branch>`), or use the Share button in the editor to run the Publish wizard. Agents do not publish projects from this tool.";case`detached-head`:return"HEAD is detached (no branch checked out). Ask the user to check out a branch (`git checkout <branch>`) before sharing.";case`branch-not-on-origin`:{let e=" (If the user says it is already pushed, ask them to `git fetch origin` first to refresh the local mirror, then retry.)";return t?`Branch \`${t}\` is not on origin yet. Ask the user to push it (\`git push -u origin ${t}\`), then retry.${e}`:`The current branch is not on origin yet. Ask the user to push it (\`git push -u origin <branch>\`), then retry.${e}`}case`non-github-remote`:return"Origin is not a `github.com` remote. Share links are GitHub-only in v1.";case`invalid-path`:return"The resolved share path is not shareable (escapes the project root or names the `.git` subtree). Pass a normal target path under the content directory.";default:return`Unknown share-construct-url error: ${String(e)}`}}function isExistingDirectory(e){try{return statSync(e).isDirectory()}catch{return!1}}function resolveExistingDocPath(e,t){for(let s of SUPPORTED_DOC_EXTENSIONS){let g=`${t}${s}`;if(existsSync(g)){let t=resolveWithinRoot(e,g);return t.ok?t.rel:null}}return null}function resolveShareTarget(e,t,s,g){if(s===``)return g===`folder`?{ok:!0,kind:`folder`,sharePath:``}:{ok:!1,code:`invalid-path`};let S=resolveWithinRoot(t,s);if(!S.ok)return{ok:!1,code:`target-not-found`};let w=resolveExistingDocPath(e,S.abs.replace(/\.(mdx|md)$/i,``)),E=isExistingDirectory(S.abs);if(g===`doc`)return w===null?E?{ok:!1,code:`kind-mismatch`}:{ok:!1,code:`target-not-found`}:{ok:!0,kind:`doc`,sharePath:w};if(g===`folder`){if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return w===null?{ok:!1,code:`target-not-found`}:{ok:!1,code:`kind-mismatch`}}if(w!==null)return{ok:!0,kind:`doc`,sharePath:w};if(E){let t=resolveWithinRoot(e,S.abs);return t.ok?{ok:!0,kind:`folder`,sharePath:t.rel}:{ok:!1,code:`target-not-found`}}return{ok:!1,code:`target-not-found`}}const OutputSchema=outputSchemaWithText({ok:boolean().describe(`Success discriminator.`),shareUrl:string().optional().describe(`Marketing share URL (success only).`),sharedUrl:string().optional().describe(`Unencoded GitHub blob/tree URL (success only).`),branch:string().optional().describe(`Branch the share URL pins to (success only).`),resolvedKind:_enum([`doc`,`folder`]).optional().describe(`Kind the target resolved to (success only).`),freshness:_enum([`current`,`stale`,`absent`]).optional().describe(`Whether the shared target matches origin (success only): current, stale (unpushed edits), or absent (not on origin). Omitted when the probe could not run.`),error:_enum([`no-remote`,`detached-head`,`branch-not-on-origin`,`non-github-remote`,`invalid-path`,`target-not-found`,`kind-mismatch`,`unknown`]).optional().describe(`Failure code (error path only).`),message:string().optional().describe(`Agent-actionable error message (error path only).`),previewUrl:string().nullable().optional().describe("Route-only preview URL (no host:port): `/#/<doc>` for a doc, `/#/<folder>/` for a folder, `/#/` for the content root. `null` when no UI is running."),previewUrlSource:string().optional().describe(`Internal: preview-URL provenance.`)});function register$3(e,t){e.registerTool(`share_link`,{description:DESCRIPTION$3,inputSchema:{path:string().describe('Content-dir-relative target. Doc paths are extension-less (`.md`/`.mdx` stripped). Folder paths name a directory. `""` is the content-root sentinel (folder-only).'),kind:_enum([`doc`,`folder`]).optional().describe("Target kind. Omit to auto-probe disk (`.mdx` → `.md` → directory). REQUIRED when `path` is empty."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:OutputSchema,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s;if(!w)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=resolveShareTarget(g,join(g,S.content.dir),e.path,e.kind);if(!E.ok){let t;if(E.code===`kind-mismatch`){let s=e.kind===`folder`?`folder`:`doc`;t=`\`${e.path}\` exists, but not as a ${s}. Pass \`kind: '${s===`doc`?`folder`:`doc`}'\` to share it as the other kind.`}else t=E.code===`invalid-path`?'Cannot share the content root from an empty path without `kind: "folder"`. Pass a non-empty path, or `kind: "folder"` to share the root.':`Target \`${e.path}\` does not exist under the content directory (looked for \`.md\`, \`.mdx\`, and a directory).`;let s={ok:!1,error:E.code,message:t};return textPlusStructured(`Error: ${t}`,s,!0)}let D=E.kind===`doc`?{kind:`doc`,docPath:E.sharePath}:{kind:`folder`,folderPath:E.sharePath},O;try{O=await fetch(`${w}/api/share/construct-url`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(D),signal:AbortSignal.timeout(3e4)})}catch(e){let t=`Server unreachable: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}let k;try{k=await O.json()}catch(e){let t=`Server returned non-JSON body: ${e instanceof Error?e.message:String(e)}`;return textPlusStructured(`Error: ${t}`,{ok:!1,error:`unknown`,message:t},!0)}if(!O.ok){let e;if(k&&typeof k==`object`){let t=k,s=typeof t.title==`string`?t.title:void 0,g=typeof t.detail==`string`?t.detail:void 0;e=s&&g?`${s}: ${g}`:s||g||`HTTP ${O.status}`}else e=`HTTP ${O.status}`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let j=ShareConstructUrlResponseSchema.safeParse(k);if(!j.success){let e=`Server returned an unexpected share-construct-url response shape.`;return textPlusStructured(`Error: ${e}`,{ok:!1,error:`unknown`,message:e},!0)}let F=j.data;if(!F.ok){let e=messageForShareError(F.error,F.branch),t={ok:!1,error:F.error,message:e,...F.branch?{branch:F.branch}:{}};return textPlusStructured(`Error: ${e}`,t,!0)}let{shareUrl:L,sharedUrl:B,branch:H,freshness:q}=F,ee={ok:!0,shareUrl:L,sharedUrl:B,branch:H,resolvedKind:E.kind,...q?{freshness:q}:{}},J={config:t.config,resolveCwd:t.resolveCwd},Y=await resolvePreviewUrlForTool(E.sharePath.replace(/\.(mdx|md)$/i,``),J,g);if(Y&&E.kind===`folder`){let e=E.sharePath.replace(/^\/+|\/+$/g,``),t=e===``?`/#/`:`/#/${encodeDocName(e)}/`;Y={...Y,url:t}}let te=e.path===``?`(content root)`:e.path;return textPlusStructured(`${freshnessWarning(q,E.kind)}Share link for ${E.kind} \`${te}\` on branch \`${H}\`:\n${L}`,{...ee,previewUrl:Y?.url??null,...Y?{previewUrlSource:Y.source}:{}})})}function bundleFileKind(e){return e.replace(/\\/g,`/`).startsWith(`scripts/`)?`script`:`reference`}const INTERNAL_BUNDLE_SKILL_NAMES=new Set(Object.values(BUNDLE_SKILL_NAME));function internalSkillHint(e){return[`"${e}" is one of OpenKnowledge's built-in agent skills — it is NOT managed by this tool and cannot be read or listed here.`,`It is already provided to you in your loaded skill list (a hidden runtime skill projected into your editor); don't fetch or re-load it — just follow the skill you already have.`,"The `skills` tool only covers skills authored as KB content (`.ok/skills` = project, `~/.ok/skills` = global). Built-in `open-knowledge*` skills never appear in either scope."].join(` `)}const SCOPE_FIELD_DESCRIBE="Which level the skill lives at. `project` = this KB's `.ok/skills/` (shared via git with everyone on the project); `global` = your user-level `~/.ok/skills/` (available in every project on this machine, not shared).",SkillListEntryOutputSchema=object$1({name:string().describe("Skill name (its identity; pass to `edit`/`move`/`delete`/`install`)."),scope:_enum([`project`,`global`]).describe(SCOPE_FIELD_DESCRIBE),description:string().optional().describe(`The skill's one-line description (when present).`),installed:boolean().describe(`True when projected into ≥1 editor; false = a Draft.`),hosts:array(string()).describe(`Editor ids the skill is installed into.`),updateAvailable:boolean().optional().describe(`Starter-pack skills only: a newer bundled version is available.`)}),SkillBundleFileEntrySchema=object$1({path:string().describe(`Skill-relative path (e.g. "references/tiers.md").`),kind:_enum([`reference`,`script`]).describe("`reference` (under references/) or `script` (under scripts/).")}),SkillReadOutputSchema=object$1({name:string().describe(`Skill name (its identity).`),scope:_enum([`project`,`global`]).describe(SCOPE_FIELD_DESCRIBE),description:string().describe(`The skill's one-line description (empty if none).`),body:string().describe(`The SKILL.md body (markdown, frontmatter stripped).`),files:array(SkillBundleFileEntrySchema).describe("Bundle files beside SKILL.md (path + kind, no inline text). Read one via `file`.")}),SkillFileReadOutputSchema=object$1({path:string().describe(`Skill-relative path read.`),kind:_enum([`reference`,`script`]).describe("`reference` or `script`."),text:string().describe(`Full text of the bundle file.`)}),DESCRIPTION$2=["[Requires: Hocuspocus server] Read-only discovery for SKILLS — the read half of the skill vocabulary (`write`/`edit`/`delete`/`move`/`install` are the mutate half).",``,"This is how you find and read skills. Skills are addressed by `name` + `scope`, NOT by path — do NOT `ls`/`cat` `.ok/skills/` or pass raw `.ok/...` paths; `.ok/` is opaque internal state.",``,"Covers only skills authored as KB content. OpenKnowledge's own built-in `open-knowledge*` skills (e.g. the `open-knowledge` project skill) are runtime skills already loaded in your skill list — they are NOT here, and you never fetch them through this tool.",``,`**Three modes:**`,"- **List** (omit `name`): every skill across BOTH levels — Project (this KB) and Global (user-level). Returns name, scope, description, installed/hosts, and (for starter packs) `updateAvailable`.","- **Read skill** (pass `name`): that skill's description + body + a `files` list (`{ path, kind }`, no inline text) of its `references/**`+`scripts/**` bundle files. `scope` optional — omitted, it resolves by name (preferring Project when a name exists at both levels).","- **Read file** (pass `name` + `file`): one bundle file's text — the universal read path for references + scripts (no native `cat`)."].join(`
2009
2010
  `);function register$2(e,t){e.registerTool(`skills`,{description:DESCRIPTION$2,inputSchema:{name:string().optional().describe(`Omit to LIST all skills; pass a skill name to READ that skill.`),file:string().optional().describe("With `name`: read ONE bundle file by its skill-relative path (`references/...`/`scripts/...`)."),scope:SkillScopeArg.optional(),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({skills:array(SkillListEntryOutputSchema).optional().describe(`Present in LIST mode: every skill across Project + Global levels.`),skill:SkillReadOutputSchema.optional().describe(`Present in READ-skill mode: the named skill (description, body, files list).`),file:SkillFileReadOutputSchema.optional().describe(`Present in READ-file mode: one bundle file (path, kind, text).`)})},async e=>{if(e.name!==void 0&&INTERNAL_BUNDLE_SKILL_NAMES.has(e.name))return textResult(`Error: ${internalSkillHint(e.name)}`,!0);let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(e.file!==void 0&&e.name===void 0)return textResult('Error: `file` reads ONE bundle file of a skill — pass `name` too: skills({ name, file: "references/x.md" }).',!0);if(e.file!==void 0){let t=resolveSkillFilePath(e.file);if(!t.ok)return textResult(`Error: ${t.error}`,!0)}if(e.name===void 0){let e=await httpGet(g,`/api/skills`);if(!e.ok)return textResult(`Error: ${e.error}`,!0);let{ok:t,...s}=e,S=(Array.isArray(s.skills)?s.skills:[]).map(e=>({name:e.name,scope:e.scope,...typeof e.description==`string`?{description:e.description}:{},installed:e.installed===!0,hosts:Array.isArray(e.hosts)?e.hosts:[],...typeof e.updateAvailable==`boolean`?{updateAvailable:e.updateAvailable}:{}}));return textPlusStructured(JSON.stringify({skills:S},null,2),{skills:S})}let S=e.scope;if(S===void 0){let t=await httpGet(g,`/api/skills`);if(!t.ok)return textResult(`Error: ${t.error}`,!0);let{ok:s,...w}=t,E=(Array.isArray(w.skills)?w.skills:[]).filter(t=>t.name===e.name);if(E.length===0)return textResult(`Error: no skill named "${e.name}" (Project or Global).`,!0);S=E.find(e=>e.scope===`project`)===void 0?E[0]?.scope:`project`}if(e.file!==void 0){let t=await readSkillFile(g,S,e.name,e.file);if(!t.ok)return textResult(`Error: ${t.error}`,!0);let s={path:t.path,kind:t.kind,text:t.text};return textPlusStructured(JSON.stringify({file:s},null,2),{file:s})}let w=await fetchSkill(g,S,e.name);if(!w.ok)return textResult(`Error: ${w.error}`,!0);let E={name:e.name,scope:S,description:w.description,body:w.body,files:w.files.map(e=>({path:e.path,kind:bundleFileKind(e.path)}))};return textPlusStructured(JSON.stringify({skill:E},null,2),{skill:E})})}function buildConsolidateBody(e,t){return`Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
2010
2011
 
2011
2012
  Topic: ${e}
@@ -3262,7 +3263,7 @@ Incremental by default — don't re-read the whole repo.
3262
3263
  `,`
3263
3264
  `).split(`
3264
3265
  `),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();initChain=Promise.resolve();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!isLinkIndexExcludedDoc(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(isLinkIndexExcludedDoc(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(){let e=this.initChain.then(()=>this.initOnce());return this.initChain=e.catch(e=>{console.warn(`[tag-index] init failed (chain cleared for next init):`,e)}),e}async initOnce(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=await this.listDocsWithPaths(),t=50;for(let t=0;t<e.length;t+=50){let s=e.slice(t,t+50),g=await Promise.all(s.map(async({docName:e,filePath:t})=>{try{return{docName:e,markdown:await readFile$1(t,`utf-8`)}}catch(t){return console.warn(`[tag-index] Failed to read ${e} during init:`,t),null}}));for(let e of g)if(e)try{this.updateDocumentFromMarkdown(e.docName,e.markdown)}catch(t){console.warn(`[tag-index] Failed to index ${e.docName} during init:`,t)}}}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))}async listDocsWithPaths(){let e=[];await 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))}async walkContentDir(e,t){let s;try{s=await readdir(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=toPosix(relative(this.contentDir,s));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=toPosix(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 buildSyncCredentialArgs(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(shellEscape).join(` `)} auth git-credential`]}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,singleDocRelPath:ee,ephemeral:J=!1}=e,Y=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=isKnownConfigError(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}Y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function ne(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;if(t!=null)return t===!0;e.valid||Y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let g=readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});return g.valid||Y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),g.value.autoSync?.default===!0}function ae(){return readProjectLocalSemanticConfig(s,{configHomedirOverride:k,onWarn:e=>Y.warn({message:e},`[config] could not read project-local config`)})}function oe(e){return`${normalizeProviderId(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}function se(e){let t;(e===`__config__/project`||e===`__local__/project`)&&(t=ne(),jr?.setEnabled(t).catch(s=>{Y.warn({err:s,enabled:t,docName:e},`[sync] failed to apply autoSync.enabled from config`)}));let s=ae();ze.applyConfig({enabled:s.enabled,providerFingerprint:oe(s)}),Y.info({docName:e,autoSyncEnabled:t,semanticEnabled:s.enabled},`[config] applied persisted config to in-process consumers`)}initTelemetry();let ce=randomUUID$1(),ue=getLocalDir(s);if(acquireServerLock(ue,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:ue,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(ue),e}let de=createBasenameIndex(),fe=(e,t)=>de.resolveEmbed(e,t),me=(e,s)=>{let g=de.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g);if(!isWithinDir(S,resolve(t)))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},ge,_e,ve,ye,Ce,we,Te,De,je=null,Me=null,Pe=null,Ie=null,Re=ae(),ze=new SemanticSearchService({loadEmbedder:e.embedderLoader??(()=>{let t=ae();return loadOpenAiEmbedder({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:join(getLocalDir(s),`embeddings`),enabled:Re.enabled,providerFingerprint:oe(Re)}),Be=null,Ve=new Set,Ue=!1,We,Ge,Ke,Xe=new Promise((e,t)=>{Ge=e,Ke=t});function $e(e){je?.signal(e)}let nt=2e3,rt=null;function it(){rt!==null&&clearTimeout(rt),rt=setTimeout(()=>{rt=null,_e.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let at=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),st=(e,t)=>{isReservedForUserTree(e)||at.setRenamed(e,t)},vt=e=>{if(!isReservedForUserTree(e)){if(at.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}at.setDeleted(e)}},Tt=e=>{isReservedForUserTree(e)||at.delete(e)};try{ge=createContentFilter({projectDir:s,contentDir:t,singleDocRelPath:ee,onAfterRebuild:()=>{_e.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),ve.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),reconcileFileIndexAfterFilterRebuild($t).then(({prunedFiles:e,prunedFolders:t})=>{let s=e+t;s>0?getLogger(`server-factory`).info({pruned:s,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):getLogger(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),_e=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:ge}),ve=new TagIndex({contentDir:t,contentFilter:ge}),ve.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[server-factory] tag-index init failed; continuing with empty index`)}),ye={current:F},Ce=E?createMaintenanceCoordinator({getShadow:()=>ye.current??null,getCurrentBranch:()=>en?.getLastKnownBranch()??null,contentRoot:L??``,projectGitDir:resolveGitDir(s)??void 0,isWriterLive:e=>{if(!Pe&&!De)return getLogger(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Pe?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of De?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,we=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:ye,ephemeral:J,contentRoot:L,backlinkIndex:_e,configHomedirOverride:k,getCurrentBranch:()=>en?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:me,getPrincipal:()=>Be,onAgentCommit:()=>je?.signal(`session-activity`),onFlushCommit:()=>Ce?.noteFlushCommit(),onDiskFlush:(e,t,s,g)=>{je?.emitDiskAck(e,t),!isReservedForUserTree(e)&&assetReferencesChanged(g,s)&&(Ie?.(),$e(`files`))},onConfigRejected:(e,t)=>je?.emitConfigValidationRejected(e,t),onConfigPersisted:se,mdManager:e.mdManager}),Te=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[we.extension]});let B=Te.shouldUnloadDocument.bind(Te);Te.shouldUnloadDocument=e=>{if(Ve.has(e)||Ue&&B(e))return!0;let t=e.name;return isReservedForUserTree(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},We=async e=>{Ve.add(e);try{await Te.unloadDocument(e)}finally{Ve.delete(e)}},je=new CC1Broadcaster(Te),Me=new AgentFocusBroadcaster(Te),Pe=new AgentPresenceBroadcaster(Te),De=new AgentSessionManager(Te);let q=createLiveDerivedIndexExtension({backlinkIndex:_e,tagIndex:ve,signalChannel:$e});Te.configuration.extensions.push(q),Te.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!==ce)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ce}`);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`&&(Be&&s.principalId===Be.id?E.principalId=Be.id:Be?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Be.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),Te.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName)&&!isManagedArtifactDoc(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})`)}});let Y=resolve(t);function ne(e){if(!isSafeDocName(e))return null;let t=resolve(Y,`${e}${getDocExtension(e)}`);return isWithinDir(t,Y)?t:null}Te.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:at,resolveFilePath:ne,fileExists:existsSync})}}),Te.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=parseHocuspocusAuthToken(e.token);runDocLineageGuard(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Te.documents.get(e)})}}),Te.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 oe=createApiExtension({hocuspocus:Te,sessionManager:De,contentDir:t,contentFilter:ge,serverInstanceId:ce,getFileIndex:()=>$t?$t.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>$t?$t.getAllFilesIndex():new Map,getFileIndexGeneration:()=>$t?.getFileIndexGeneration()??0,mutateFileIndex:e=>$t?.mutateFileIndex(e),getFolderIndex:()=>$t?$t.getFolderIndex():new Map,getAliasMap:()=>$t?$t.getAliasMap():new Map,getFolderAliasIndex:()=>$t?$t.getFolderAliasIndex():new Map,rescanFiles:()=>$t?.rescanFromDisk(),enableTestRoutes:j,shadowRef:ye,flushGitCommit:()=>we.flushPendingGitCommit(),flushContributors:()=>we.flushContributors(),takeStoreFailure:e=>we.takeStoreFailure(e),takeStoreDivergence:e=>we.takeStoreDivergence(e),markAgentWriteStore:e=>we.markAgentWriteStore(e),getCurrentBranch:()=>en?.getLastKnownBranch()??null,getDiskAckSVs:()=>je?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:_e,tagIndex:ve,signalChannel:$e,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>jr,localOpCliArgs:H,projectDir:s,resolveEmbed:fe,getPrincipal:()=>Be,homeDirOverride:k,forceUnloadDocument:We,ready:Xe,recentlyRemovedDocs:at,serializeDoc:Ft,evictManagedArtifactLkg:e=>{we.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:ze,getSemanticSimilarityFloor:()=>ae().similarityFloor,embeddingsSecretsFile:secretsFilePath(k),ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{Ie=e}});Te.configuration.extensions.push(oe),Te.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:ye,contentRoot:L,getCurrentBranch:()=>en?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:me})),Te.configuration.extensions.push(createSyncHandshakeSpanExtension()),Te.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>jr,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(ue),e}let Et=null,Dt=new Map,jt=[];function Mt(e,t){let s=resolve(e,`rescue`),g=resolve(s,`${t}${getDocExtension(t)}`);return isWithinDir(g,s)?g:null}function Ft(e){let t=Te.documents.get(e);return t?serializeYDocSource(t):null}let It=(e,t)=>applyExternalChange(Te,e,t,fe,me);function Lt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Rt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of Te.documents){if(isReservedForUserTree(s))continue;let g=Te.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,fe,s)},FILE_WATCHER_ORIGIN)}catch(t){Y.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},zt=null,Bt=e=>{e&&(zt===null&&(zt=new Set,setImmediate(()=>{let e=zt;if(zt=null,e)try{for(let t of e)Rt(t)}catch(t){Y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),zt.add(e))};function Vt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Ht(e){try{switch(e.kind){case`create`:Y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),_e.updateDocumentFromMarkdown(e.docName,e.content),it(),ve.updateDocumentFromMarkdown(e.docName,e.content),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),Tt(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=Te.documents.get(t);if(!g){_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`);return}let S=getReconciledBase(t)??``,w=Ft(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(Y.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`:Lt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`);break;case`clean`:try{It(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Lt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),Lt(g)}break;case`merged`:try{It(t,E.newContent),setReconciledBase(t,s),incrementReconcile(),Lt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),Lt(g)}break;case`conflicts`:try{It(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,s)}{let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}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=Te.documents.get(t);if(!s){_e.deleteDocument(t),it(),ve.deleteDocument(t),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),vt(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=Ft(t)??``,w=S!==g;if(w&&ye.current){let e=ye.current,s=en?.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(),Y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{Y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),_e.deleteDocument(t),it(),ve.deleteDocument(t),Y.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),Te.closeConnections(t),await We(s),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),vt(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:s,content:g}=e,S=Te.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),_e.renameDocument(t,s,g),it(),ve.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}Y.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),st(t,s),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:s,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,s=Te.documents.get(t);if(!s)return;let g=Ft(t);g===null?Y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,g);let S=s.getMap(`lifecycle`);S.set(`status`,`conflict`),S.set(`reason`,`conflict-markers`),Y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:de.add(e.relativePath),$e(`files`),Bt(basename(e.relativePath));break;case`asset-delete`:de.remove(e.relativePath),$e(`files`),Bt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:$e(`files`);break;case`file-create`:case`file-update`:case`file-delete`:$e(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Vt(e);Y.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let Ut=[];async function Wt(e){if(isBatchInProgress()){Ut.push(e);return}await Ht(e)}async function Kt(){let e=Ut.splice(0,Ut.length);for(let t of e)await Ht(t)}let $t=null,en=null,jr=null,Mr=null;async function Fr(e){if(Te.documents.size===0)return;let t=!1,s=new Promise(e=>{Te.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(Te.documents.keys());Te.closeConnections(),Te.flushPendingStores();for(let e of Te.documents.values())e.getConnectionsCount()===0&&Te.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(Te.documents.keys()),S=[],E=[];if(ye.current){for(let e of s)if(!isReservedForUserTree(e))try{let t=Ft(e);if(t===null){Y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=Mt(ye.current.gitDir,e);if(!s){Y.warn({docName:e,gitDir:ye.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),Y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),Y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else Y.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 Ir(){return Mr||(Mr=(async()=>{let e=Date.now(),t=[];Ue=!0,rt!==null&&(clearTimeout(rt),rt=null);let g,S=await Promise.race([Xe.then(()=>`completed`,e=>(Y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&Y.warn({},`[server] init did not complete within 5s during shutdown`);let w=Te.documents.size;Ce?.destroy();try{try{try{en&&=(await en.unsubscribe(),null),$t&&=(await $t.unsubscribe(),null);for(let{docName:e,cleanup:t}of jt)try{await t()}catch(t){Y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}jt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{je?.destroy(),Pe?.destroy(),Et&&=(await Et.disconnect(),null);for(let[e,t]of Dt)try{await t.disconnect()}catch(t){Y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Dt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await De.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Fr(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await we.flushPendingGitCommit(),await we.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)}),Y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{jr&&=(await jr.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(ye.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(ye.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(ye.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?Y.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):Y.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ue)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),Y.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)})}}})(),Mr)}let Lr=[];async function zr(){try{Be=await loadPrincipal(s),Y.info({principalId:Be.id},`[server] principal loaded`)}catch(e){Y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!ye.current)try{ye.current=await initShadowRepo(s),Y.info({gitDir:ye.current.gitDir},`[server] history repo initialized at ${ye.current.gitDir}`)}catch(e){Y.error({err:e},`[server] history repo init failed`),Lr.push(`shadow-repo`)}if(ye.current){let e=null;try{e=loadRenameLogIndex(ye.current.gitDir),sweepLazyPopOrphans(ye.current.gitDir,e),setRenameLogIndex(ye.current.gitDir,e),Y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){Y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(ye.current,e,{rebuild:!0}),new Promise((e,s)=>setTimeout(()=>s(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){Y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await Ce?.runBootMaintenance()}catch(e){Y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(ye.current)try{await shadowGit(ye.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`)){Y.warn({},`[server] history repo appears corrupted — reinitializing`);try{ye.current=await initShadowRepo(s)}catch(e){Y.error({err:e},`[server] history repo reinit failed`),ye.current=void 0,Lr.includes(`shadow-repo`)||Lr.push(`shadow-repo`)}}else Y.error({err:e},`[server] history repo check failed (transient?)`)}if(ye.current)try{let e=resolve(ye.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{}Y.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(ye.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){Y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else Y.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){Y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){Y.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,s);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;Y.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){Y.error({err:e},`[server] managed rename recovery failed`),Lr.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(s);(e.deleted>0||e.errors>0)&&Y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){Y.error({err:e},`[server] upload-tempfile sweep failed`),Lr.push(`upload-tempfile-sweep`)}try{Et=await Te.openDirectConnection(SYSTEM_DOC_NAME),je?.emitServerInfo(ce,getActiveBranch())}catch(e){Y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Lr.push(`cc1-push`)}let g=J?[]:CONFIG_DOC_NAMES;for(let e of g)try{let t=await Te.openDirectConnection(e);Dt.set(e,t)}catch(t){Y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Lr.push(`config-doc:${e}`)}let S=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 e of g){let t=S.get(e);if(t)try{Y.info({docName:e,path:t},`[config-file-watcher] starting`);let s=await startConfigFileWatcher(t,t=>{let s=Te.documents.get(e);Y.info({docName:e,hasDocument:s!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,e,t,we.configPersistenceCtx);Y.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),se(e)});jt.push({docName:e,cleanup:s}),Y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(s){Y.warn({err:s,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Lr.push(`config-file-watcher:${e}`)}}if(!J){let e=(e,t)=>{let s=managedArtifactDocNameForPath(e,we.managedArtifactCtx);if(!s)return;let g=applyExternalManagedArtifactChange(Te.documents.get(s)??null,s,t,we.managedArtifactCtx);Y.info({docName:s,outcome:g},`[managed-artifact-watcher] external change`),parseGlobalSkillBundleDoc(s)&&_e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),getActiveBranch()).then(()=>{$e(`backlinks`),$e(`graph`)}).catch(e=>{Y.warn({err:e,docName:s},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=managedArtifactSkillsRoots(we.managedArtifactCtx),s=await startManagedArtifactWatcher(t,e);jt.push({docName:`__skill-files__`,cleanup:s}),Y.info({roots:t},`[managed-artifact-watcher] skills started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),Lr.push(`managed-artifact-watcher:skills`)}try{let t=new Set([``]);try{for(let e of resolveProjectTemplates(s).templates)t.add(e.source_folder)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let g=[...t].map(e=>e?resolve(s,e,`.ok`,`templates`):resolve(s,`.ok`,`templates`)),S=await startManagedArtifactWatcher(g,e,TEMPLATE_WATCH_OPTIONS);jt.push({docName:`__template-files__`,cleanup:S}),Y.info({rootCount:g.length},`[managed-artifact-watcher] templates started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),Lr.push(`managed-artifact-watcher:templates`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:s,encoding:`utf-8`,timeout:5e3});if(e.status===0&&e.stdout){let t=join(resolve(s,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(S=t)}}catch{}let w=S?[e,g,S]:[e,g],E=Y;E.info({okignorePath:e,gitignorePath:g,gitInfoExcludePath:S,ephemeral:J},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let D=J?null:await startMultiPathConfigFileWatcher(w,(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(Te.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,we.configPersistenceCtx);E.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){E.error({err:e,changedPath:relative(s,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let S=await ge.rebuildIgnorePatterns();if(S.ok)E.info({changedPath:relative(s,t),patternCount:S.patternCount,nestedFileCount:S.nestedFileCount,durationMs:S.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),je?.signal(`files`);else{let e=relative(s,t)||`.`;E.warn({changedPath:e,error:S.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),je?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});D&&(jt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`))}catch(e){Y.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Lr.push(`ignore-files-watcher`)}let w=resolveGitDir(s),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),_e.switchBranch(E);let D=performance.now();try{await withSpan(`ok.boot.indexes`,void 0,async()=>{let e=getActiveBranch();try{if(await _e.loadFromDisk(e)){let t=await _e.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&Y.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await _e.rebuildFromDisk(e);try{await _e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),e)}catch(t){Y.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}_e.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){Y.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}let s=performance.now();$t=await withSpan(`ok.boot.seed-walk`,void 0,async()=>startWatcher(t,Wt,ge)),recordBootPhase(`seedWalkMs`,Math.round(performance.now()-s));try{await ve.init()}catch(e){Y.error({err:e},`[tag-index] startup re-init failed; tag index updates incrementally via watcher events`),Lr.push(`tag-index`)}let g=0;try{ee===void 0?await seedBasenameIndex({contentDir:t,contentFilter:ge,basenameIndex:de,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):seedSingleDirBasenameIndex({contentDir:t,basenameIndex:de,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),g>0&&(Y.warn({count:g},`[basename-index] startup seed completed with ${g} skipped entries — embeds under inaccessible subtrees will not resolve`),Lr.push(`basename-index-partial`))}catch(e){Y.error({err:e},`[basename-index] startup seed failed`),Lr.push(`basename-index`)}})}catch(e){Y.error({err:e},`[server] disk bridge watcher failed to start`),Lr.push(`file-watcher`)}finally{recordBootPhase(`indexesMs`,Math.round(performance.now()-D)),$t&&setBootField(`fileCount`,$t.getFileIndex().size)}try{en=await startHeadWatcher(s,async({trigger:e})=>{if(Y.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),Te.flushPendingStores(),await we.flushPendingGitCommit(),setBatchInProgress(!0),ye.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of Te.documents){if(isReservedForUserTree(e))continue;let s=null;if(t.transact(()=>{s=Ft(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(ye.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),Y.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){Y.error({err:e},`[shadow] park failed`)}}},async e=>{let s=Ut.length,g=e.newBranch??`main`;if(Y.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`){if(setBatchInProgress(!1),await Kt(),await we.flushDeferredStores(`within-branch`),jr!==null)try{await jr.reconcileConflictsFromGit()}catch(e){Y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),Ut.splice(0,Ut.length),switchReconciledBaseScope(g),rt!==null&&(clearTimeout(rt),rt=null),_e.switchBranch(g),ge.rebuildDirCount();try{let e=0;de.clear(),await seedBasenameIndex({contentDir:t,contentFilter:ge,basenameIndex:de,onSkip:(t,s,S)=>{e++,Y.warn({reason:t,code:s,path:S,branch:g},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.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`),Lr.includes(`basename-index-partial`)||Lr.push(`basename-index-partial`))}catch(e){Y.error({err:e,branch:g},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of Te.documents)if(!isReservedForUserTree(e))try{let S=safeContentPath(e,t);if(!existsSync(S)){let t=getReconciledBase(e)??``,S=Ft(e)??``;if(S!==t&&ye.current){let t=ye.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(),Y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{Y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Y.info({docName:e,branch:g},`[branch-switch] tombstone: ${e} (not on ${g})`);continue}let w=readFileSync(S,`utf-8`);It(e,w),setReconciledBase(e,w),Y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){Y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}Y.info({branch:g,docCount:Te.documents.size},`[branch-switch] loaded branch ${g} (${Te.documents.size} docs)`);try{if(await _e.loadFromDisk(g)){let e=await _e.reconcileWithDisk(g);(e.added>0||e.updated>0||e.deleted>0)&&Y.info(e,`[backlinks] branch-switch reconcile for ${g}`)}else await _e.rebuildFromDisk(g);try{await _e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),g)}catch(e){Y.warn({err:e,branch:g},`[backlinks] branch-switch global skill bundle ingest failed`)}_e.saveToDisk(g).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${g}:`,e)})}catch(e){Y.error({err:e,branch:g},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(await ve.init(),ye.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Te.documents)if(!isReservedForUserTree(t))try{let s=await readParkedState(ye.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`:It(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:It(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=Te.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){Y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&Y.info({count:e,branch:g},`[branch-switch] restored ${e} parked docs on ${g}`)}if(e.oldBranch?.startsWith(`detached-`)&&ye.current)try{let t=shadowGit(ye.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
3265
- `))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await we.flushDeferredStores(`discard-stale`),je?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&ye.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(ye.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),Y.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){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Lr.push(`head-watcher`)}function O(e){for(let g of e)try{let e=toPosix(relative(t,join(s,g)));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=Te.documents.get(S);if(!w)continue;let E=Ft(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let j=buildSyncCredentialArgs(H);try{jr=new SyncEngine({projectDir:s,contentDir:t,contentFilter:ge,contentRoot:L,syncEnabled:ne(),credentialArgs:j,cc1Broadcaster:je,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||we.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:O,onAutoDisable:async e=>{Y.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||Y.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 jr.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),jr=null}$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`);let F=bootElapsedMs();F!==void 0&&recordBootPhase(`readyMs`,F)}return zr().then(Ge,Ke),{hocuspocus:Te,sessionManager:De,cc1Broadcaster:je,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,maintenanceCoordinator:Ce,contentFilter:ge,basenameIndex:de,serverInstanceId:ce,destroy:Ir,ready:Xe,degraded:Lr,lockDir:ue,get syncEngine(){return jr}}}const SERVER_MEMORY_SCHEMA_VERSION=1,BYTES_PER_MB=1024*1024;function toMb(e){return e/BYTES_PER_MB}function captureServerMemorySnapshot(){let e=process.memoryUsage();return{schemaVersion:SERVER_MEMORY_SCHEMA_VERSION,capturedAt:new Date().toISOString(),snapshot:{rssMb:toMb(e.rss),heapTotalMb:toMb(e.heapTotal),heapUsedMb:toMb(e.heapUsed),externalMb:toMb(e.external),arrayBuffersMb:toMb(e.arrayBuffers)}}}let cachedGauge=null;onTelemetryShutdown(()=>{cachedGauge=null});function installServerMemoryGauge(){if(cachedGauge)return;let e=getMeter().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=captureServerMemorySnapshot();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),cachedGauge=e}const TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`,TELEMETRY_PREV_FILENAME=`tolerance-telemetry.prev.jsonl`,TELEMETRY_MAX_BYTES=8*1024*1024;let appender=null,appendFailureWarned=!1;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);appender=new RotatingAppender({currentPath:resolve(t,TELEMETRY_FILENAME),previousPath:resolve(t,TELEMETRY_PREV_FILENAME),maxBytes:TELEMETRY_MAX_BYTES}),setToleranceTelemetryHook(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};appender?.append(`${JSON.stringify(t)}\n`).catch(e=>{appendFailureWarned||(appendFailureWarned=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null),await appender?.drain(),appender=null,appendFailureWarned=!1}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,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){startBootTimings();let t=e.projectDir??e.contentDir,s=resolveLocalSinkConfig({projectDir:t});if(s){let e=s.telemetry.attributeDenylist,t=[];for(let s of e){t.push(s);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)t.push(`${`*.`.repeat(e)}${s}`)}loggerFactory.configure({pinoConfig:{fileSink:s.logs,redactPaths:t}})}initTelemetry({localSink:s?.telemetry}),initToleranceTelemetryWriter(t),installServerMemoryGauge();let{kind:g,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":g};S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S));let E=process.env.OK_STARTUP_TRACEPARENT,D=()=>withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e));if(E)try{let e=propagation.extract(context.active(),{traceparent:E});return context.with(e,D)}catch(e){getLogger(`boot`).warn({err:e instanceof Error?e.message:String(e)},`ok.boot trace-join failed — starting unparented boot`)}return D()}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-LsXsWtim-DBIg_FmA.mjs`),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=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=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,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:q,destroy:ee,ready:J,degraded:Y,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se}=H,ce=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ue=e.port??0,de=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:S}),fe=D();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:H.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ge=!1;if(e.reactShellDistDir)try{acquireUiLock(te,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ge=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:te},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await ee().catch(()=>{}),e}let _e=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ve=mountMcpAndApi({httpServer:fe,hocuspocus:q,mcpHttpHandler:de,log:S,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:_e,ephemeral:e.ephemeral}),ye=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Ce=null;g!==null&&(Ce=attachIdleShutdown({httpServer:fe,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ye()})})),await restoreLifecycleFromConflictsJson({hocuspocus:q,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);fe.once(`error`,g),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,g),t()})})}catch(e){if(ge)try{releaseUiLock(te)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await ee().catch(()=>{}),e}let we=bootElapsedMs();we!==void 0&&recordBootPhase(`httpListenMs`,we);let Te=fe.address(),De=typeof Te==`object`&&Te?Te.port:e.port??0;if(ue=De,O(te,De),ge&&updateUiLockPort(te,De),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:te,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let je=!1,Me=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)}};ye=async()=>{if(je)return;je=!0;let e=[],t=async(t,s)=>{try{await Me(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{Ce?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ve.shutdown()),de!==void 0&&await t(`mcpHttpHandler.close`,()=>de.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ve.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>ee()),ge&&await t(`releaseUiLock`,async()=>releaseUiLock(te)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await reconcileSkillInstalls({projectDir:j,skillsRoot:resolve(e.contentDir,`.ok`,`skills`)}),s=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;s>0&&S.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${s} editor skill entr${s===1?`y`:`ies`} to the symlink model.`)}catch(e){S.warn?.({event:`installed-skills-reconcile-failed`,error:String(e)},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:fe,destroy:ye,lockDir:te,contentDir:e.contentDir,port:De,ready:J,degraded:Y,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
3266
+ `))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await we.flushDeferredStores(`discard-stale`),je?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&ye.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(ye.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),Y.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){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Lr.push(`head-watcher`)}function O(e){for(let g of e)try{let e=toPosix(relative(t,join(s,g)));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=Te.documents.get(S);if(!w)continue;let E=Ft(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let j=buildSyncCredentialArgs(H);try{jr=new SyncEngine({projectDir:s,contentDir:t,contentFilter:ge,contentRoot:L,syncEnabled:ne(),credentialArgs:j,cc1Broadcaster:je,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||we.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:O,onAutoDisable:async e=>{Y.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||Y.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 jr.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),jr=null}$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`);let F=bootElapsedMs();F!==void 0&&recordBootPhase(`readyMs`,F)}return zr().then(Ge,Ke),{hocuspocus:Te,sessionManager:De,cc1Broadcaster:je,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,maintenanceCoordinator:Ce,contentFilter:ge,basenameIndex:de,serverInstanceId:ce,destroy:Ir,ready:Xe,degraded:Lr,lockDir:ue,get syncEngine(){return jr}}}const SERVER_MEMORY_SCHEMA_VERSION=1,BYTES_PER_MB=1024*1024;function toMb(e){return e/BYTES_PER_MB}function captureServerMemorySnapshot(){let e=process.memoryUsage();return{schemaVersion:SERVER_MEMORY_SCHEMA_VERSION,capturedAt:new Date().toISOString(),snapshot:{rssMb:toMb(e.rss),heapTotalMb:toMb(e.heapTotal),heapUsedMb:toMb(e.heapUsed),externalMb:toMb(e.external),arrayBuffersMb:toMb(e.arrayBuffers)}}}let cachedGauge=null;onTelemetryShutdown(()=>{cachedGauge=null});function installServerMemoryGauge(){if(cachedGauge)return;let e=getMeter().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=captureServerMemorySnapshot();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),cachedGauge=e}const TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`,TELEMETRY_PREV_FILENAME=`tolerance-telemetry.prev.jsonl`,TELEMETRY_MAX_BYTES=8*1024*1024;let appender=null,appendFailureWarned=!1;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);appender=new RotatingAppender({currentPath:resolve(t,TELEMETRY_FILENAME),previousPath:resolve(t,TELEMETRY_PREV_FILENAME),maxBytes:TELEMETRY_MAX_BYTES}),setToleranceTelemetryHook(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};appender?.append(`${JSON.stringify(t)}\n`).catch(e=>{appendFailureWarned||(appendFailureWarned=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null),await appender?.drain(),appender=null,appendFailureWarned=!1}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,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){startBootTimings();let t=e.projectDir??e.contentDir,s=resolveLocalSinkConfig({projectDir:t});if(s){let e=s.telemetry.attributeDenylist,t=[];for(let s of e){t.push(s);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)t.push(`${`*.`.repeat(e)}${s}`)}loggerFactory.configure({pinoConfig:{fileSink:s.logs,redactPaths:t}})}initTelemetry({localSink:s?.telemetry}),initToleranceTelemetryWriter(t),installServerMemoryGauge();let{kind:g,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":g};S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S));let E=process.env.OK_STARTUP_TRACEPARENT,D=()=>withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e));if(E)try{let e=propagation.extract(context.active(),{traceparent:E});return context.with(e,D)}catch(e){getLogger(`boot`).warn({err:e instanceof Error?e.message:String(e)},`ok.boot trace-join failed — starting unparented boot`)}return D()}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-LsXsWtim-BLIrqdzC.mjs`),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=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=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,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:q,destroy:ee,ready:J,degraded:Y,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se}=H,ce=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ue=e.port??0,de=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:S}),fe=D();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:H.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ge=!1;if(e.reactShellDistDir)try{acquireUiLock(te,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ge=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:te},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await ee().catch(()=>{}),e}let _e=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ve=mountMcpAndApi({httpServer:fe,hocuspocus:q,mcpHttpHandler:de,log:S,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:_e,ephemeral:e.ephemeral}),ye=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Ce=null;g!==null&&(Ce=attachIdleShutdown({httpServer:fe,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ye()})})),await restoreLifecycleFromConflictsJson({hocuspocus:q,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);fe.once(`error`,g),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,g),t()})})}catch(e){if(ge)try{releaseUiLock(te)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await ee().catch(()=>{}),e}let we=bootElapsedMs();we!==void 0&&recordBootPhase(`httpListenMs`,we);let Te=fe.address(),De=typeof Te==`object`&&Te?Te.port:e.port??0;if(ue=De,O(te,De),ge&&updateUiLockPort(te,De),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:te,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let je=!1,Me=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)}};ye=async()=>{if(je)return;je=!0;let e=[],t=async(t,s)=>{try{await Me(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{Ce?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ve.shutdown()),de!==void 0&&await t(`mcpHttpHandler.close`,()=>de.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ve.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>ee()),ge&&await t(`releaseUiLock`,async()=>releaseUiLock(te)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await reconcileSkillInstalls({projectDir:j,skillsRoot:resolve(e.contentDir,`.ok`,`skills`)}),s=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;s>0&&S.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${s} editor skill entr${s===1?`y`:`ies`} to the symlink model.`)}catch(e){S.warn?.({event:`installed-skills-reconcile-failed`,error:String(e)},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:fe,destroy:ye,lockDir:te,contentDir:e.contentDir,port:De,ready:J,degraded:Y,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
3266
3267
  `).map(e=>e.trim()).filter(Boolean):[])}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}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 OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!0});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},g)}function flushFileLogger(e,t=250){return new Promise(s=>{if(!e){s();return}let g=e[import_pino.default.symbols.streamSym],S=!1,w=()=>{S||(S=!0,s())};if(!g||typeof g.flushSync!=`function`){w();return}let E=()=>{try{g.flushSync?.()}catch{}w()},D=setTimeout(w,t);typeof D.unref==`function`&&D.unref(),typeof g.fd==`number`&&g.fd>=0?(clearTimeout(D),E()):typeof g.once==`function`?g.once(`ready`,()=>{clearTimeout(D),E()}):(clearTimeout(D),E())})}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e,t){try{let{stdout:s}=await execFileAsync(e,[`rev-parse`,`--is-inside-work-tree`],{cwd:t});return s.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};log.info({},`detected partial .git/ — running git init to repair`),S=!0}let w;try{w=assertGitAvailable()}catch(e){throw e instanceof GitNotAvailableError||e instanceof GitTooOldError?(emitPreflightFailureSpan(e),log.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof GitTooOldError?`too_old`:`not_available`,detectedVersion:e instanceof GitTooOldError?e.detected:``},e instanceof GitTooOldError?`git binary too old`:`git binary not found`)):log.warn({event:`git_preflight_unexpected_error`,message:e instanceof Error?e.message:String(e)},`unexpected error during git preflight`),e}let E=w.resolvedPath;if(!S&&await isInsideExistingWorkTree(E,t))return{didInit:!1};let D=``;try{D=(await execFileAsync(E,[`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(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,D);return S?(log.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(log.info({path:t,branch:`main`},`initialized .git/`),{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}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:s}of HOME_PATH_PATTERNS)t=t.replace(e,s);return t}function serializeError(e,t=0,s=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(s.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};s.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,s)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let g=e;return{name:String(g.name??`ObjectError`),message:scrubPaths(String(g.message??``))??``,stack:scrubPaths(g.stack),code:g.code,cause:g.cause===void 0?void 0:serializeError(g.cause,t+1,s)}}return{name:`UnknownError`,message:String(e)}}var SingleFileNotFoundError=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},SingleFileNotAFileError=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},SingleFileNotMarkdownError=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function prepareSingleFileOpen(e){if(!isSupportedDocFile(e))throw new SingleFileNotMarkdownError(e);let t;try{t=realpathSync(resolve(e))}catch(t){throw t.code===`ENOENT`?new SingleFileNotFoundError(e):t}if(!statSync(t).isFile())throw new SingleFileNotAFileError(e);let s=dirname(t),g=findEnclosingProjectRoot(s);if(g){let e=g.rootPath;return{mode:`project`,projectRoot:e,docName:stripDocExtension(relative(resolveProjectContentDir(e),t).split(sep).join(`/`)),canonicalFilePath:t}}let S=basename(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:s,singleDocRelPath:S,docName:stripDocExtension(S)}}function resolveProjectContentDir(e){return resolve(e,readConfigSafely({absPath:resolveConfigPath(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function createEphemeralProjectDir(e){let t=mkdtempSync(resolve(tmpdir(),`ok-ephemeral-`)),s=resolve(t,`.ok`);return mkdirSync(s,{recursive:!0}),writeFileSync(resolve(s,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),writeFileSync(resolve(s,`.gitignore`),`local/
3267
3268
  `,`utf-8`),t}export{STARTER_PACKS as $,withSpan as $i,isAllowedWorkspaceHostHeader as $n,resolveBundledSkillDir as $r,createExternalChangeHandler as $t,HocuspocusAuthRejection as A,spawnDetached as Ai,formatPackRationale as An,planSeed as Ar,bundleSkillMdPath as At,McpLogger as B,tracedMkdirSync as Bi,handleCollabSocketError as Bn,readSkillManagement as Br,compareSemver as Bt,FILE_WATCHER_ORIGIN as C,serializeError as Ci,fallbackPaths as Cn,normalizeFsPath as Cr,bootServer as Ct,GitNotAvailableError as D,skillManagementPath as Di,formatAuthRejectionWire as Dn,parseHocuspocusAuthToken as Dr,buildSkillZip as Dt,GIT_UPSTREAM_WRITER as E,shutdownTelemetry as Ei,flushFileLogger as En,parseGitVersion as Er,buildExecResult as Et,MANAGED_RENAME_ORIGIN as F,teardownToleranceTelemetryWriter as Fi,getLogger as Fn,readArmedPaneTarget as Fr,clearEmbeddingsKeyFromAllBackends as Ft,PinoLogger as G,tracedUnlinkSync as Gi,initContent as Gn,reconcile as Gr,countStaleAgentWipRefs as Gt,OBSERVER_SYNC_ORIGIN as H,tracedRenameSync as Hi,hasGcLogLatch as Hn,readTargetRecordedAt as Hr,contentHash as Ht,MAX_AGENT_SESSIONS as I,toBroadcasterKey as Ii,getLogsDir as In,readBranchFromHead as Ir,coercePackId as It,ROOT_GITIGNORE_TEMPLATE as J,updateLastKnownHash as Ji,initToleranceTelemetryWriter as Jn,registerAllTools as Jr,createAssetServeMiddleware as Jt,ProjectGitInitError as K,tracedWriteFile as Ki,initShadowRepo as Kn,recordContributor as Kr,countWipRefs as Kt,MCP_CONNECTION_ID_HEADER as L,tracedAppendFileSync as Li,getMeter as Ln,readProjectLocalSemanticConfig as Lr,commitUpstreamImport as Lt,INSTALLED_AGENTS_SCHEMES as M,startWatcher as Mi,getCurrentMcpLogger as Mn,processCommand as Mr,classifyFsPath as Mt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as N,streamingProblemEvent as Ni,getLocalDir as Nn,processUsage as Nr,clearArmedPaneTarget as Nt,GitTooOldError as O,spansCurrentPath as Oi,formatContributors as On,parseKeepaliveConnectionId as Or,buildStarterFolderFrontmatterYaml as Ot,LOG_MD_TEMPLATE as P,swapContributors as Pi,getLogFilePath as Pn,readAllTargets as Pr,clearContributors as Pt,STARTER_FOLDER_FRONTMATTER_FILENAME as Q,validateSkillZip as Qi,isAllowedApiOrigin as Qn,resetMetrics as Qr,createEphemeralProjectDir as Qt,MIN_GIT_VERSION as R,tracedLinkSync as Ri,getMetrics as Rn,readServerPackageVersion as Rr,commitWip as Rt,FILE_SYSTEM_WRITER as S,seedBasenameIndex as Si,extractWikiLinksFromMarkdown as Sn,mountMcpAndApi as Sr,attachIdleShutdown as St,GIT_PREFLIGHT_FAIL_SPAN_NAME as T,shadowGit as Ti,findEnclosingProjectRoot as Tn,parseAuthRejectionWire as Tr,buildConfigYmlContent as Tt,OK_OKIGNORE_TEMPLATE as U,tracedRmSync as Ui,incrementCollabSocketFilteredError as Un,readTargetVersion as Ur,contributorCount as Ut,MissingOkConfigError as V,tracedRename as Vi,handleSpawnCursor as Vn,readStateManifest as Vr,containsConflictMarkers as Vt,PANE_TARGET_TTL_MS as W,tracedRmdirSync as Wi,incrementServerObserverFire as Wn,readUiLock as Wr,countShadowObjects as Wt,SKILL_INSTALL_EVENTS_FILE_REL as X,validateAgentId as Xi,installTestLoggers as Xn,releaseUiLock as Xr,createContentFilterAsync as Xt,SERVICE_WRITER as Y,updateUiLockPort as Yi,installPrettyZodErrors as Yn,registerWrite as Yr,createContentFilter as Yt,STARTER_FOLDERS as Z,validateCloneInputs as Zi,installUserSkill as Zn,removeLastKnownHash as Zr,createEmbeddingsSecretStore as Zt,ConfigSchema as _,GitDirAccessError as _a,safeSubdir as _i,encodeSkillRoute as _n,loadPrincipal as _r,applySeed as _t,AgentPresenceBroadcaster as a,writeTracker as aa,resolvePackageVersion as ai,createServer$1 as an,isManagedArtifactDoc as ar,SingleFileNotAFileError as at,DEFAULT_PACK_ID as b,resolveGitDirDetailed as ba,saveInMemoryCheckpoint as bi,evictStaleTrackerEntries as bn,logsPreviousPath as br,assertGitAvailable as bt,AutoStartDisabledError as c,LATEST_PROTOCOL_VERSION as ca,restoreLifecycleFromConflictsJson as ci,createTestLogger as cn,isProjectRoot as cr,StateManifestError as ct,BUNDLE_SKILL_NAME as d,isJSONRPCResultResponse as da,runAuthReposSubprocess as di,detectGit as dn,isSelfWrite as dr,UiLockCollisionError as dt,withSpanSync as ea,resolveContentDir as ei,createFileLogger as en,isConfigDoc as er,STARTER_PACK_IDS as et,BacklinkIndex as f,atomicWriteFileSync as fa,runAuthStatusSubprocess as fi,detectProjectShape as fn,isSystemDoc as fr,__getShowAllWalkStatsForTesting as ft,CURSOR_BUNDLE_PATHS_BY_PLATFORM as g,writeConfigPatch as ga,safeContentPath as gi,encodeFolderRoute as gn,listStarterPacks as gr,applyExternalChange as gt,CONFLICT_MARKER_RE as h,withFileLockSync as ha,runWithMcpLogger as hi,encodeDocName as hn,listRescueCheckpoints as hr,applyAgentMarkdownWrite as ht,AgentFocusBroadcaster as i,writeTargetVersion as ia,resolvePack as ii,createPersistenceExtension as in,isLoopbackAddress as ir,SeedRootDirError as it,HocuspocusAuthTokenSchema as j,splitMarkdownBlocks as ji,gcCheckpointRefs as jn,prepareSingleFileOpen as jr,classifyEvents as jt,HOCUSPOCUS_AUTH_REJECTION_REASONS as k,spansPreviousPath as ki,formatContributorsFrom as kn,pathToDocName as kr,buildWipTree as kt,BUNDLE_IDS as l,isInitializedNotification as la,rewriteMarkdownLinksForDocumentRename as li,describeStoredEmbeddingsKey as ln,isProjectSkillManaged as lr,TagIndex as lt,CONFIG_FILENAME as m,resolveConfigPath as ma,runDeviceFlowSubprocess as mi,emitPreflightFailureSpan as mn,lastKnownHash as mr,acquireUiLock as mt,AGENT_ID_RE as n,writeSkillManagement as na,resolveCursorSpawnInvocation as ni,createMcpHttpHandler as nn,isKnownPackId as nr,STATE_MANIFEST_FILENAME as nt,AgentSessionCapacityError as o,McpServer as oa,resolveUiInfo as oi,createServerObserverExtension as on,isPairedWriteOrigin as or,SingleFileNotFoundError as ot,CC1Broadcaster as p,readConfigSafely as pa,runCloneSubprocess as pi,discoverLockDirs as pn,isToleranceTelemetryEnabled as pr,__resetShowAllWalkStatsForTesting as pt,ROLLBACK_ORIGIN as q,tracedWriteFileSync as qi,initTelemetry as qn,recordSkillInstallEvent as qr,createApiExtension as qt,AGENT_WRITE_ORIGIN as r,writeStateManifest as ra,resolveLockDir as ri,createOsProbe as rn,isLinkIndexExcludedDoc as rr,SeedPrerequisiteError as rt,AgentSessionManager as s,JSONRPCMessageSchema as sa,restoreContributors as si,createStreamingErrorWriter as sn,isPathWithinDir as sr,SingleFileNotMarkdownError as st,AGENT_ID_MAX_LEN as t,writeRootGitignoreForNewRepo as ta,resolveCursorBinaryDefault as ti,createLiveDerivedIndexExtension as tn,isHocuspocusAuthRejectionReason as tr,STARTER_TEMPLATES as tt,BUNDLE_SCOPE as u,isJSONRPCRequest as ua,rewriteWikiLinksForDocumentRename as ui,detectClaudeDesktopPresence as un,isReservedForUserTree as ur,USER_GLOBAL_BUNDLE_IDS as ut,DEFAULT_CHECKPOINT_RETENTION as v,MalformedGitPointerError as va,safetyCheckpoint as vi,ensureProjectGit as vn,loggerFactory as vr,armPaneTarget as vt,FileEmbeddingsBackend as w,setActiveSpanAttributes as wi,findEnclosingGitRoot as wn,packageVersionMajorMinor as wr,buildAndOpenSkill as wt,EMBEDDINGS_API_KEY_ENV as x,resolveShadowDir as xa,saveVersion as xi,extractOkBinaryPath as xn,makeLazyEmbeddingsKeyStore as xr,assertNeverDiskEvent as xt,DEFAULT_EMBEDDINGS_DIMENSIONS as y,parseCheckpoint as ya,sanitizeClientName as yi,errorResponse as yn,logsCurrentPath as yr,assertCompatibleStateManifest as yt,MISSING_OK_CONFIG_MESSAGE as z,tracedMkdir as zi,getTracer as zn,readSkillInstallStateSnapshot as zr,commitWipFromTree as zt};
3268
- //# sourceMappingURL=dist-B923c31q.mjs.map
3269
+ //# sourceMappingURL=dist-CefxLzs-.mjs.map