@inkeep/open-knowledge 0.86.13-beta.6 → 0.86.13-beta.7

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 (158) hide show
  1. package/dist/assets/skills/discovery/SKILL.md +4 -0
  2. package/dist/assets/skills/packs/codebase-wiki/SKILL.md +1 -1
  3. package/dist/assets/skills/packs/codebase-wiki/references/generate-and-refresh.md +4 -4
  4. package/dist/assets/skills/packs/entity-vault/SKILL.md +1 -1
  5. package/dist/assets/skills/packs/knowledge-base/SKILL.md +1 -1
  6. package/dist/assets/skills/packs/knowledge-base/consolidate/SKILL.md +1 -1
  7. package/dist/assets/skills/packs/knowledge-base/research/SKILL.md +1 -1
  8. package/dist/assets/skills/packs/plain-notes/SKILL.md +1 -1
  9. package/dist/assets/skills/packs/software-lifecycle/SKILL.md +1 -1
  10. package/dist/assets/skills/packs/software-lifecycle/frame-a-proposal/SKILL.md +1 -1
  11. package/dist/assets/skills/packs/software-lifecycle/record-a-decision/SKILL.md +1 -1
  12. package/dist/assets/skills/packs/software-lifecycle/review-a-design/SKILL.md +1 -1
  13. package/dist/assets/skills/packs/software-lifecycle/write-a-postmortem/SKILL.md +1 -1
  14. package/dist/assets/skills/packs/software-lifecycle/write-a-spec/SKILL.md +1 -1
  15. package/dist/assets/skills/packs/worldbuilding/SKILL.md +1 -1
  16. package/dist/assets/skills/packs/writing-pipeline/SKILL.md +1 -1
  17. package/dist/assets/skills/project/SKILL.md +2 -0
  18. package/dist/assets/skills/write-skill/SKILL.md +1 -1
  19. package/dist/cli.mjs +18 -19
  20. package/dist/constants-Cu2M0SgL.mjs +1 -0
  21. package/dist/{dist-B-LAoRmW.mjs → dist-BCF9Elq9.mjs} +9 -9
  22. package/dist/{dist-DFHKTwRq.mjs → dist-BmGKbb5v.mjs} +1 -1
  23. package/dist/index.mjs +97 -97
  24. package/dist/init-C_89v3Le.mjs +1 -0
  25. package/dist/{init-DsTDW8PN.mjs → init-DS83zNJg.mjs} +8 -8
  26. package/dist/{launch-json-removal-C0-wLRJG.mjs → launch-json-removal-BedPjyEk.mjs} +1 -1
  27. package/dist/loader-D_glh6x6.mjs +1 -0
  28. package/dist/{loader-B14ip6IN.mjs → loader-Y1qsx7iK.mjs} +1 -1
  29. package/dist/{md-manager-BGnqyqi1-CPATjLIj.mjs → md-manager-BGnqyqi1-j5JtqA4V.mjs} +1 -1
  30. package/dist/{open-browser-DfTjiF9R.mjs → open-browser-Dtph3PJv.mjs} +1 -1
  31. package/dist/parse-worker.mjs +1 -1
  32. package/dist/preview-CHrr1wqj.mjs +1 -0
  33. package/dist/preview-D7WB5XGp.mjs +2 -0
  34. package/dist/public/assets/AccountSection-BVvQP8wu.js +1 -0
  35. package/dist/public/assets/{ActivityModeContent-CcroJ-DG.js → ActivityModeContent-CqWgOtPv.js} +1 -1
  36. package/dist/public/assets/{AddPropertiesButton-Ack7vynK.js → AddPropertiesButton-9Whmx-r4.js} +1 -1
  37. package/dist/public/assets/{AgentDiffPane-DiwxFrFb.js → AgentDiffPane-BAoGGQLw.js} +1 -1
  38. package/dist/public/assets/{AttachmentsSection-85LnQHCB.js → AttachmentsSection-CRvJt4Um.js} +1 -1
  39. package/dist/public/assets/{CodeMirrorPropInput-UA1el3M1.js → CodeMirrorPropInput-B6B811CW.js} +1 -1
  40. package/dist/public/assets/{ContentRulesSection-mTywn1H0.js → ContentRulesSection-DKMjTgvf.js} +1 -1
  41. package/dist/public/assets/{DocumentContext-Bpjsqo1P.js → DocumentContext-Bgu1O1jH.js} +1 -1
  42. package/dist/public/assets/{EditorModeToggle-BxZG0GCz.js → EditorModeToggle-DBhBKluO.js} +1 -1
  43. package/dist/public/assets/{ExcalidrawDocEditor-zDA0vdbs.js → ExcalidrawDocEditor-BVGoOqw4.js} +1 -1
  44. package/dist/public/assets/FeedbackForm-BUy2zQy5.js +1 -0
  45. package/dist/public/assets/{ImportSkillDialog-30iXeyF6.js → ImportSkillDialog-B2fWoj-i.js} +1 -1
  46. package/dist/public/assets/{LinkPreviewsSection-Dunim138.js → LinkPreviewsSection-Di9GNnsl.js} +1 -1
  47. package/dist/public/assets/{LintConfigEditor-DOaH26Y3.js → LintConfigEditor-cF--We5r.js} +1 -1
  48. package/dist/public/assets/{LintingSection-CR6EIafl.js → LintingSection-DOLNP1BE.js} +1 -1
  49. package/dist/public/assets/{ManagedArtifactProperties-aljVpK04.js → ManagedArtifactProperties-8I47_E0r.js} +1 -1
  50. package/dist/public/assets/ManagedArtifactProperties-BJVzJ5Oi.js +1 -0
  51. package/dist/public/assets/{MermaidDocEditor-B8TfaHGr.js → MermaidDocEditor-DZGMDLM_.js} +1 -1
  52. package/dist/public/assets/NetworkAccessSection-BKPX0RQb.js +1 -0
  53. package/dist/public/assets/{PropertyDisplayRow-PpwMWELQ.js → PropertyDisplayRow-DIHb-w_S.js} +1 -1
  54. package/dist/public/assets/{PublishToGitHubDialog-DHCNHDEf.js → PublishToGitHubDialog-B_FwTSpj.js} +1 -1
  55. package/dist/public/assets/ReportBugDialogBody-Dg2IkIA3.js +3 -0
  56. package/dist/public/assets/{ReportBugMenuTrigger-D7K_uENa.js → ReportBugMenuTrigger-Ci3sZ7ND.js} +1 -1
  57. package/dist/public/assets/{SchemaConfigEditor-LrnwWr8i.js → SchemaConfigEditor-4q3RhsgM.js} +1 -1
  58. package/dist/public/assets/{SearchSection-ey8z-UyU.js → SearchSection-CT4lGY8n.js} +1 -1
  59. package/dist/public/assets/{SessionsHost-DV3rQaV6.js → SessionsHost-DsoCAke2.js} +2 -2
  60. package/dist/public/assets/SettingsDialogBody-D_rR3yws.js +2 -0
  61. package/dist/public/assets/{ShareReceiveMissDialog-MpyX-2te.js → ShareReceiveMissDialog-B3Ka8Ew4.js} +1 -1
  62. package/dist/public/assets/SharingSection-JalgaNUI.js +1 -0
  63. package/dist/public/assets/{SkillToolbarControls-EF87XEf5.js → SkillToolbarControls-C3OYGj04.js} +1 -1
  64. package/dist/public/assets/{SourceEditor-Dns11FYK.js → SourceEditor-1iVWbn2b.js} +1 -1
  65. package/dist/public/assets/{SpellingSettings-DTFaJnWZ.js → SpellingSettings-CkbtGI2P.js} +1 -1
  66. package/dist/public/assets/{SyncSection-BIbeHZvp.js → SyncSection-BWizU8W7.js} +1 -1
  67. package/dist/public/assets/{SyncStatusBadge-DaMofnew.js → SyncStatusBadge-Dq6snLd8.js} +1 -1
  68. package/dist/public/assets/TerminalSection-vsjRf3fK.js +1 -0
  69. package/dist/public/assets/{TerminalWindowApp-LE6KPay1.js → TerminalWindowApp-1aEv3-5a.js} +1 -1
  70. package/dist/public/assets/{TextDocEditor-BcJtDjng.js → TextDocEditor-CTl1OGJ2.js} +1 -1
  71. package/dist/public/assets/{ThemePluginSection-ebkfP2XH.js → ThemePluginSection-Dg9mwDpx.js} +1 -1
  72. package/dist/public/assets/{ThreadView-DI-eMUWY.js → ThreadView-XFBxMvdh.js} +1 -1
  73. package/dist/public/assets/{TimelineDiffPane-SShlUARz.js → TimelineDiffPane-U187joMr.js} +1 -1
  74. package/dist/public/assets/{client-version-CdR5OEoA.js → client-version-wtJeBeRf.js} +1 -1
  75. package/dist/public/assets/{comment-chips-CGV3uBng.js → comment-chips-ChoSGZhD.js} +1 -1
  76. package/dist/public/assets/{config-provider-DyQHdVWH.js → config-provider-CiwHZgiM.js} +1 -1
  77. package/dist/public/assets/config-schema-CB4GNK5W.js +1 -0
  78. package/dist/public/assets/{doc-undo-manager-BzYAqvBQ.js → doc-undo-manager-BkVml-pO.js} +1 -1
  79. package/dist/public/assets/field-controls-B2JH6eAk.js +1 -0
  80. package/dist/public/assets/{field-controls-BuDfcEQ5.js → field-controls-QW3Zq7gs.js} +1 -1
  81. package/dist/public/assets/{index-BUWsL8h_.js → index-DwTpR-kG.js} +16 -16
  82. package/dist/public/assets/{lint-config-client-CCGSFVIS.js → lint-config-client-CzUiAfZa.js} +1 -1
  83. package/dist/public/assets/{lint-plugins-KeEVAAw5.js → lint-plugins-WikiN2fX.js} +1 -1
  84. package/dist/public/assets/{markdown-lint-Sq_kGPCg.js → markdown-lint-awUbUFP1.js} +1 -1
  85. package/dist/public/assets/{markdownlint-rule-browser-dtdwuRgB.js → markdownlint-rule-browser-DsVyNt4Y.js} +1 -1
  86. package/dist/public/assets/messages-B4H1bF4j.js +1 -0
  87. package/dist/public/assets/messages-BABf_IxD.js +1 -0
  88. package/dist/public/assets/messages-BhENKFH1.js +1 -0
  89. package/dist/public/assets/messages-Bw4znuq4.js +1 -0
  90. package/dist/public/assets/messages-C5lHUEUq.js +1 -0
  91. package/dist/public/assets/messages-CLz9EZwz.js +1 -0
  92. package/dist/public/assets/messages-C_OEIU6A.js +1 -0
  93. package/dist/public/assets/messages-CgH-igPR.js +1 -0
  94. package/dist/public/assets/messages-DIJUuXJT.js +1 -0
  95. package/dist/public/assets/messages-DhjzGkZH.js +1 -0
  96. package/dist/public/assets/messages-Dic-JCYe.js +1 -0
  97. package/dist/public/assets/messages-DvzXmL36.js +1 -0
  98. package/dist/public/assets/messages-Dy0m4Uu0.js +1 -0
  99. package/dist/public/assets/{pending-receive-nav-store-tATiLz5K.js → pending-receive-nav-store-CfOGwcVY.js} +1 -1
  100. package/dist/public/assets/{preferred-session-events-D23QukOQ.js → preferred-session-events-BnES3CJg.js} +1 -1
  101. package/dist/public/assets/{progress-DqKVGUPv.js → progress-CXFLjUA1.js} +1 -1
  102. package/dist/public/assets/{saved-themes-client-D8_0b0C1.js → saved-themes-client-xjluD_xq.js} +1 -1
  103. package/dist/public/assets/{schema-section-Bx7R1XV-.js → schema-section-D_Cucwam.js} +1 -1
  104. package/dist/public/assets/{selection-context-C7GkLjF6.js → selection-context-BrHLE7Lq.js} +1 -1
  105. package/dist/public/assets/{src-BXx-EsNC.js → src-MgZQzOCn.js} +1 -1
  106. package/dist/public/assets/{telemetry-impl-Cwb_fUix.js → telemetry-impl-tOpPF19w.js} +1 -1
  107. package/dist/public/assets/{telemetry-startup-Beq4pPTJ.js → telemetry-startup-B556Mu54.js} +1 -1
  108. package/dist/public/assets/{typing-burst-detector-Bky0Uf5I.js → typing-burst-detector-uKwEIRfB.js} +1 -1
  109. package/dist/public/assets/{uninstall-C4YeoIWy.js → uninstall-BhKucRvy.js} +1 -1
  110. package/dist/public/assets/{use-activity-panel-BcSX-2vK.js → use-activity-panel-Coug5SFo.js} +1 -1
  111. package/dist/public/assets/{use-apply-config-language-BKdqjjzN.js → use-apply-config-language-nPCm4LZz.js} +2 -2
  112. package/dist/public/assets/use-installed-clis-DAeDvnHP.js +2 -0
  113. package/dist/public/assets/{use-open-skill-CwYfqsE-.js → use-open-skill-B_t5wgnE.js} +1 -1
  114. package/dist/public/assets/{use-terminal-enabled-BtJN1Ej9.js → use-terminal-enabled-DoP_cmB-.js} +1 -1
  115. package/dist/public/assets/{use-timeline-entry-diff-C_vMkhk8.js → use-timeline-entry-diff-y3DAK3rE.js} +1 -1
  116. package/dist/public/index.html +25 -25
  117. package/dist/public/uninstall.html +3 -3
  118. package/dist/{registry-probes-BCYLuGAW.mjs → registry-probes-C324p0fU.mjs} +1 -1
  119. package/dist/{removal-file-path-C94YYdie.mjs → removal-file-path-Hkd3h7jX.mjs} +1 -1
  120. package/dist/{repair-launch-json-BLHEsJOF.mjs → repair-launch-json-CqL7MbsW.mjs} +1 -1
  121. package/dist/{repair-mcp-configs-CRfhQbOD.mjs → repair-mcp-configs-BqF2is4H.mjs} +1 -1
  122. package/dist/src-B4gueXu4.mjs +1 -0
  123. package/dist/src-CfD3HYk7.mjs +16 -0
  124. package/dist/start-CkRDxU9K.mjs +1 -0
  125. package/dist/{start-uMGB8N0f.mjs → start-DBS7SlTn.mjs} +3 -3
  126. package/package.json +4 -4
  127. package/dist/constants-QhGcX1jP.mjs +0 -1
  128. package/dist/init-DNcF_zUp.mjs +0 -1
  129. package/dist/loader-CEVDxJIa.mjs +0 -1
  130. package/dist/preview-DCs1uVu5.mjs +0 -2
  131. package/dist/preview-DptKn8iO.mjs +0 -1
  132. package/dist/public/assets/AccountSection-CowlGJFs.js +0 -1
  133. package/dist/public/assets/FeedbackForm-6XiRSy77.js +0 -1
  134. package/dist/public/assets/ManagedArtifactProperties-BmUZv2uD.js +0 -1
  135. package/dist/public/assets/NetworkAccessSection-TETzOWD_.js +0 -1
  136. package/dist/public/assets/ReportBugDialogBody-De5A5a-_.js +0 -3
  137. package/dist/public/assets/SettingsDialogBody-Bcv_vYHe.js +0 -2
  138. package/dist/public/assets/SharingSection-B50Zk2JJ.js +0 -1
  139. package/dist/public/assets/TerminalSection-DQWuBL3s.js +0 -1
  140. package/dist/public/assets/config-schema-DztM21_Q.js +0 -1
  141. package/dist/public/assets/field-controls-C5yOp45E.js +0 -1
  142. package/dist/public/assets/messages-B2YPV5Co.js +0 -1
  143. package/dist/public/assets/messages-BQLLVaWc.js +0 -1
  144. package/dist/public/assets/messages-ByPbljzk.js +0 -1
  145. package/dist/public/assets/messages-C1IqqliI.js +0 -1
  146. package/dist/public/assets/messages-C38RwffO.js +0 -1
  147. package/dist/public/assets/messages-CQD9Zv2_.js +0 -1
  148. package/dist/public/assets/messages-CcPUfHL6.js +0 -1
  149. package/dist/public/assets/messages-Cu4wBll6.js +0 -1
  150. package/dist/public/assets/messages-DRr6R8Yc.js +0 -1
  151. package/dist/public/assets/messages-DknEs27Z.js +0 -1
  152. package/dist/public/assets/messages-DtNdaU-R.js +0 -1
  153. package/dist/public/assets/messages-H7A2LMjG.js +0 -1
  154. package/dist/public/assets/messages-rA0JxP4D.js +0 -1
  155. package/dist/public/assets/use-installed-clis-BzkmtX4n.js +0 -2
  156. package/dist/src-C2dLuB-4.mjs +0 -16
  157. package/dist/src-DwoGfost.mjs +0 -1
  158. package/dist/start-B4k7Ovrz.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{a as e,i as t,n,o as r,r as i,t as a}from"./rolldown-runtime-tZXQYakl.mjs";import{$ as o,$a as s,$c as c,$d as l,$i as u,$l as d,$n as f,$o as p,$r as m,$s as h,$t as g,$u as _,A as v,Aa as y,Ac as b,Ad as x,Ai as S,Al as C,An as w,Ao as T,Ar as E,As as D,At as O,Au as ee,B as k,Ba as A,Bc as te,Bd as j,Bi as M,Bl as ne,Bn as re,Bo as ie,Br as ae,Bs as N,Bt as oe,Bu as se,Ca as ce,Cc as le,Cd as ue,Cf as de,Ci as fe,Cl as pe,Cn as me,Co as he,Cr as ge,Cs as _e,Ct as ve,Cu as ye,D as be,Da as xe,Dc as Se,Dd as Ce,Di as we,Dl as Te,Dn as Ee,Do as De,Dr as Oe,Ds as ke,Dt as Ae,Du as je,E as Me,Ea as Ne,Ec as Pe,Ed as P,Ei as Fe,El as Ie,En as Le,Eo as Re,Er as ze,Es as Be,Et as Ve,Eu as He,Fa as Ue,Fc as We,Fd as F,Fi as Ge,Fn as Ke,Fo as qe,Fr as Je,Fs as Ye,Ft as Xe,Fu as Ze,Ga as Qe,Gc as $e,Gd as et,Gi as tt,Gl as nt,Gn as rt,Go as it,Gr as at,Gs as ot,Gt as st,Gu as ct,H as lt,Ha as ut,Hc as dt,Hi as ft,Hl as pt,Hn as mt,Ho as ht,Hr as gt,Hs as _t,Ht as vt,Hu as yt,Ia as bt,Ic as xt,Id as I,Ii as St,In as Ct,Io as wt,Ir as Tt,Is as Et,It as Dt,Iu as Ot,J as kt,Ja as At,Jc as jt,Jd as Mt,Ji as Nt,Jn as Pt,Jo as Ft,Jr as It,Js as Lt,Jt as Rt,Ju as zt,K as Bt,Ka as Vt,Kc as Ht,Kd as Ut,Ki as Wt,Kl as Gt,Kn as Kt,Ko as qt,Kr as Jt,Ks as Yt,Kt as Xt,Ku as Zt,L as Qt,La as $t,Lc as en,Ld as tn,Li as nn,Ll as rn,Ln as an,Lo as on,Lr as sn,Ls as cn,Lt as ln,Lu as un,M as dn,Ma as fn,Mc as pn,Md as L,Mi as mn,Ml as hn,Mn as gn,Mo as _n,Mr as vn,Ms as yn,Mt as bn,Mu as xn,Na as Sn,Nc as Cn,Nd as R,Ni as wn,Nl as Tn,Nn as En,No as Dn,Nr as On,Ns as kn,Nt as An,Nu as jn,O as Mn,Oa as Nn,Oc as Pn,Od as Fn,Oi as In,Ol as Ln,On as Rn,Oo as zn,Or as Bn,Os as Vn,Ot as Hn,Ou as Un,P as Wn,Pa as Gn,Pc as Kn,Pd as qn,Pi as Jn,Pn as Yn,Po as Xn,Pr as Zn,Ps as Qn,Pt as $n,Pu as er,Q as tr,Qa as nr,Qc as rr,Qd as ir,Qi as ar,Qn as or,Qo as eee,Qr as sr,Qs as cr,Qt as lr,Qu as ur,R as dr,Ra as fr,Rd as pr,Ri as tee,Rn as mr,Ro as hr,Rr as gr,Rs as _r,Rt as vr,Ru as yr,Sa as nee,Sc as br,Sd as xr,Si as Sr,Sl as Cr,Sn as ree,So as wr,Sr as Tr,Ss as Er,St as Dr,Su as Or,T as kr,Ta as Ar,Tc as jr,Td as Mr,Tf as Nr,Ti as Pr,Tl as Fr,Tn as Ir,To as Lr,Tr as iee,Ts as aee,Tt as Rr,Tu as zr,Ua as oee,Uc as see,Ud as cee,Ui as lee,Ul as Br,Un as Vr,Uo as uee,Ur as dee,Us as fee,Ut as pee,Uu as Hr,V as Ur,Va as Wr,Vc as Gr,Vd as Kr,Vi as qr,Vl as Jr,Vn as Yr,Vo as Xr,Vr as Zr,Vs as mee,Vt as hee,Vu as Qr,Wa as $r,Wc as gee,Wd as _ee,Wi as vee,Wl as ei,Wn as yee,Wo as bee,Wr as xee,Ws as See,Wt as Cee,Wu as wee,Xa as Tee,Xd as Eee,Xi as Dee,Xl as Oee,Xn as ti,Xo as kee,Xr as Aee,Xt as ni,Xu as ri,Y as jee,Ya as ii,Yd as Mee,Yi as Nee,Yl as Pee,Yn as Fee,Yo as Iee,Yr as Lee,Ys as Ree,Yt as ai,Yu as oi,Za as zee,Zc as Bee,Zd as Vee,Zi as Hee,Zn as Uee,Zo as Wee,Zr as Gee,Zs as Kee,Zt as si,Zu as ci,_ as qee,_a as Jee,_c as li,_d as ui,_i as di,_l as Yee,_n as Xee,_o as Zee,_r as fi,_s as Qee,_t as pi,_u as mi,a as $ee,aa as hi,ac as ete,ad as tte,ai as nte,al as rte,an as ite,ao as ate,ar as ote,as as ste,at as cte,au as lte,b as ute,ba as gi,bc as _i,bd as z,bf as vi,bi as dte,bl as fte,bn as pte,bo as mte,br as yi,bs as hte,bt as gte,bu as _te,c as vte,ca as yte,cd as bte,ci as xte,cl as Ste,cn as bi,co as xi,cr as Cte,cs as wte,ct as Si,cu as Tte,d as Ci,da as Ete,dc as wi,di as Dte,dl as Ote,dn as kte,do as Ate,dr as jte,ds as Mte,dt as Ti,du as Ei,ea as Nte,ec as Pte,ed as Di,ef as Oi,ei as ki,el as Ai,en as Fte,eo as Ite,er as ji,es as Mi,et as Lte,eu as Ni,fa as Rte,fc as Pi,fd as zte,fi as Bte,fl as Vte,fn as Hte,fo as Ute,fr as Wte,fs as Gte,ft as Fi,fu as Ii,g as Kte,ga as Li,gd as qte,gf as Jte,gi as Yte,gl as Ri,gn as Xte,go as zi,gr as Zte,gs as Qte,gt as Bi,gu as $te,h as ene,ha as Vi,hc as Hi,hf as tne,hi as nne,hn as rne,ho as Ui,hr as ine,hs as ane,ht as one,hu as Wi,ia as sne,ic as cne,id as lne,if as Gi,ii as une,il as dne,in as fne,io as pne,ir as mne,is as hne,it as Ki,iu as gne,j as qi,ja as Ji,jc as _ne,jd as vne,ji as yne,jl as bne,jn as xne,jo as Yi,jr as Sne,js as Xi,jt as Cne,ju as Zi,kd as B,kf as wne,ki as Qi,kl as $i,kn as Tne,ko as Ene,kr as Dne,ks as One,kt as kne,ku as Ane,la as ea,lc as ta,ld as jne,lf as Mne,li as Nne,ll as na,ln as Pne,lo as Fne,lr as Ine,ls as Lne,lt as ra,lu as Rne,m as ia,ma as zne,mc as aa,mf as Bne,mi as Vne,mn as Hne,mo as Une,mr as Wne,ms as Gne,mt as Kne,mu as oa,n as sa,na as qne,nc as Jne,nd as Yne,nf as Xne,ni as Zne,nl as Qne,nn as $ne,no as ca,nr as ere,ns as tre,nt as nre,nu as rre,o as ire,oa as are,od as ore,of as la,oi as sre,ol as ua,on as cre,oo as lre,or as ure,os as dre,ot as da,ou as fre,pa as pre,pc as mre,pd as hre,pi as gre,pn as _re,po as vre,pr as fa,ps as yre,pt as pa,pu as bre,qa as xre,qd as Sre,qi as Cre,ql as ma,qn as ha,qo as wre,qr as Tre,qs as Ere,qt as Dre,qu as Ore,ra as kre,rc as Are,rd as jre,ri as Mre,rl as Nre,rn as Pre,ro as Fre,rr as Ire,rs as Lre,rt as Rre,ru as zre,s as ga,sa as _a,sc as va,sd as Bre,sf as ya,si as ba,sl as xa,sn as Vre,so as Hre,sr as Ure,ss as Wre,st as Sa,su as Ca,t as wa,tc as Ta,td as Gre,tf as Kre,ti as Ea,tn as qre,to as Jre,tr as Yre,ts as Da,tu as Xre,ua as Zre,uc as Oa,ud as Qre,uf as ka,ui as $re,ul as Aa,un as eie,uo as tie,ur as nie,us as rie,ut as ja,uu as Ma,v as iie,vc as Na,vd as Pa,vf as aie,vi as oie,vn as Fa,vo as Ia,vr as La,vs as sie,vt as Ra,vu as cie,w as lie,wa as za,wc as uie,wd as Ba,wf as Va,wi as die,wl as fie,wn as pie,wo as mie,wr as hie,ws as gie,wt as Ha,wu as _ie,x as vie,xa as yie,xc as Ua,xd as Wa,xf as bie,xi as xie,xl as Sie,xn as Cie,xo as wie,xr as Tie,xs as Eie,xt as Ga,xu as Die,y as Oie,yc as kie,yf as Ka,yi as qa,yl as Aie,yn as Ja,yo as jie,yr as Mie,ys as Nie,yt as Ya,yu as Pie,za as Xa,zc as Fie,zd as Iie,zi as Lie,zl as Rie,zn as zie,zo as Za,zr as Bie,zs as Vie,zt as Qa,zu as Hie}from"./md-manager-BGnqyqi1-CPATjLIj.mjs";import{c as $a,d as eo,h as Uie,i as to,l as no,n as ro,o as io,p as ao,t as oo}from"./esm-B3YyV3nD.mjs";import{t as Wie}from"./libesm-DRoEqbAC.mjs";import{t as Gie}from"./yazl-BBz29IQN.mjs";import{t as so}from"./chunk-B74TABJS-DAm9lxFL.mjs";import{a as co,c as lo,d as Kie,f as uo,h as qie,i as fo,l as po,m as mo,n as ho,o as go,p as _o,r as vo,s as yo,t as bo,u as xo}from"./chunk-GFQRA5P5-ZJVBMLyZ.mjs";import{A as So,B as Co,C as wo,D as To,E as Jie,F as Yie,H as Xie,I as Zie,L as Eo,M as Do,N as Oo,O as ko,P as Ao,S as Qie,T as $ie,V as eae,_ as tae,a as jo,b as Mo,c as No,d as Po,f as Fo,g as nae,h as rae,i as Io,j as Lo,k as Ro,l as zo,m as iae,n as aae,o as Bo,p as Vo,r as Ho,s as Uo,t as oae,u as Wo,v as Go,w as Ko,x as qo,y as Jo,z as Yo}from"./chunk-BGSUD5R5-Do2r1ZFF.mjs";import{n as Xo,r as Zo,t as Qo}from"./chunk-R6VWJ2ZL-DJY9gweS.mjs";import{r as $o}from"./chunk-CWQS3NFK-BbpS-dVt.mjs";import{t as sae}from"./chunk-DXB73IDG-DFy9txNR.mjs";import{n as es,t as ts}from"./chunk-5QMZ5MUS-BuB3i_B5.mjs";import{n as cae,t as lae}from"./chunk-A5O5YHGN-BRMz0iFo.mjs";import{n as ns,r as rs,t as uae}from"./chunk-OJDRYQWQ-JGMWNwO9.mjs";import{r as dae,t as is}from"./chunk-24IMIIXA-Dj5K6qOb.mjs";import{n as as}from"./chunk-3THT3N7L-DVKHLRUO.mjs";import{t as os}from"./chunk-44UOCSGV-CeGMLWmo.mjs";import{t as fae}from"./wrapper-BF8oRx3G.mjs";import{createRequire as ss}from"node:module";import{execFile as cs,execFileSync as pae,spawn as ls,spawnSync as us}from"node:child_process";import*as ds from"node:path";import{basename as fs,delimiter as ps,dirname as V,extname as ms,isAbsolute as hs,join as H,normalize as gs,parse as mae,posix as _s,relative as U,resolve as W,sep as vs,win32 as ys}from"node:path";import{URLSearchParams as hae,fileURLToPath as bs,pathToFileURL as xs}from"node:url";import*as Ss from"node:fs";import{accessSync as gae,appendFileSync as _ae,chmodSync as Cs,closeSync as ws,constants as Ts,cpSync as vae,createReadStream as Es,createWriteStream as Ds,existsSync as G,fchmodSync as yae,fstatSync as bae,linkSync as xae,lstatSync as Os,mkdirSync as ks,mkdtempSync as As,openSync as js,opendirSync as Sae,readFile as Cae,readFileSync as K,readSync as wae,readdirSync as Ms,readlinkSync as Tae,realpathSync as Ns,renameSync as Ps,rmSync as Fs,rmdirSync as Is,statSync as Ls,symlinkSync as Eae,unlinkSync as Rs,watch as Dae,writeFileSync as zs,writeSync as Bs}from"node:fs";import{arch as Vs,availableParallelism as Oae,homedir as Hs,hostname as Us,platform as Ws,tmpdir as Gs,userInfo as kae}from"node:os";import{access as Ks,appendFile as Aae,chmod as jae,constants as qs,glob as Mae,lstat as Js,mkdir as Ys,readFile as Xs,readdir as Zs,readlink as Nae,realpath as Qs,rename as $s,rm as Pae,stat as ec,unlink as Fae,writeFile as tc}from"node:fs/promises";import{Readable as nc,Transform as Iae,Writable as rc}from"node:stream";import Lae from"crypto";import ic,{createHash as ac,randomUUID as oc,webcrypto as sc}from"node:crypto";import{EventEmitter as cc}from"node:events";import{Worker as Rae}from"node:worker_threads";import*as zae from"zlib";import{Readable as lc}from"stream";import{readdirSync as Bae,statSync as Vae}from"fs";import{spawn as Hae}from"child_process";import{promisify as uc,stripVTControlCharacters as Uae}from"node:util";import{DatabaseSync as dc}from"node:sqlite";import{monitorEventLoopDelay as Wae,performance as fc}from"node:perf_hooks";import{createInterface as Gae}from"node:readline";import{setImmediate as Kae,setTimeout as pc}from"node:timers/promises";import{AsyncLocalStorage as mc}from"node:async_hooks";import{pipeline as hc}from"node:stream/promises";import{request as qae}from"node:http";import{Http2ServerRequest as gc,constants as Jae}from"node:http2";import{lookup as Yae}from"node:dns/promises";import{request as Xae}from"node:https";import{createBrotliDecompress as Zae,createGunzip as Qae,createInflate as $ae}from"node:zlib";import{join as _c,resolve as eoe}from"path";import*as toe from"node:querystring";import{Http2ServerRequest as vc,constants as noe}from"http2";import{lookup as roe}from"node:dns";import ioe from"node:tls";const aoe=2,yc={protocol:`x-ok-client-protocol`,runtime:`x-ok-client-runtime`,kind:`x-ok-client-kind`},ooe={desktop:!0,browser:!0,"embedded:cursor":!0,"embedded:codex":!0,"embedded:claude-desktop":!0},soe={mcp:!0,"desktop-main":!0,cli:!0};function coe(e){return Object.hasOwn(ooe,e)}function loe(e){if(!(e===void 0||e.length===0||Object.hasOwn(soe,e)))return coe(e)?e:`unknown`}function uoe({kind:e,runtimeVersion:t}){return{[yc.protocol]:`2`,[yc.runtime]:t,[yc.kind]:e}}const doe=new Set([`*`,`_`,"`",`~`,`\\`,`$`]),foe=/^={2,}/,bc=/^<(?:[A-Za-z][A-Za-z0-9+.-]*:[^<>\s]*|[^\s<>@]+@[^\s<>]+)>/;function poe(e,t){return bc.test(e.slice(t,t+512))}function moe(e,t){let n=e.lastIndexOf(`<`,t);return n<0||t-n>512?!1:bc.exec(e.slice(n,t+1))?.[0].length===t+1-n}const hoe=/^<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^>]*?)?\/?>/,goe=/^!(?=\[)/,_oe=/^\[\^/,voe=/^\]\[[^\]]*\]/,yoe=/^\[\[[^\][|]*\|/,boe=/^#[^\][|]*(?=\]\])/,xoe=/^\]\([^)]*\)/,Soe=/^(?:#{1,6}[ \t]+|>[ \t]?|(?:[-*+]|\d{1,9}[.)])[ \t]+(?:\[[ xX]\][ \t]+)?)/,Coe=/^(?:`{3,}[^`\n]*|~{3,}[^\n]*)$/,woe=/^(?:(?:[-*_][ \t]*){3,}|=+[ \t]*|[|\-: \t]*-[|\-: \t]*)$/;function Toe(e,t){let n=e.indexOf(`
1
+ import{a as e,i as t,n,o as r,r as i,t as a}from"./rolldown-runtime-tZXQYakl.mjs";import{$ as o,$a as s,$c as c,$d as l,$i as u,$l as d,$n as f,$o as p,$r as m,$s as h,$t as g,$u as _,A as v,Aa as y,Ac as b,Ad as x,Ai as S,Al as C,An as w,Ao as T,Ar as E,As as D,At as O,Au as ee,B as k,Ba as A,Bc as te,Bd as j,Bi as M,Bl as ne,Bn as re,Bo as ie,Br as ae,Bs as N,Bt as oe,Bu as se,Ca as ce,Cc as le,Cd as ue,Cf as de,Ci as fe,Cl as pe,Cn as me,Co as he,Cr as ge,Cs as _e,Ct as ve,Cu as ye,D as be,Da as xe,Dc as Se,Dd as Ce,Di as we,Dl as Te,Dn as Ee,Do as De,Dr as Oe,Ds as ke,Dt as Ae,Du as je,E as Me,Ea as Ne,Ec as Pe,Ed as P,Ei as Fe,El as Ie,En as Le,Eo as Re,Er as ze,Es as Be,Et as Ve,Eu as He,Fa as Ue,Fc as We,Fd as F,Fi as Ge,Fn as Ke,Fo as qe,Fr as Je,Fs as Ye,Ft as Xe,Fu as Ze,Ga as Qe,Gc as $e,Gd as et,Gi as tt,Gl as nt,Gn as rt,Go as it,Gr as at,Gs as ot,Gt as st,Gu as ct,H as lt,Ha as ut,Hc as dt,Hi as ft,Hl as pt,Hn as mt,Ho as ht,Hr as gt,Hs as _t,Ht as vt,Hu as yt,Ia as bt,Ic as xt,Id as I,Ii as St,In as Ct,Io as wt,Ir as Tt,Is as Et,It as Dt,Iu as Ot,J as kt,Ja as At,Jc as jt,Jd as Mt,Ji as Nt,Jn as Pt,Jo as Ft,Jr as It,Js as Lt,Jt as Rt,Ju as zt,K as Bt,Ka as Vt,Kc as Ht,Kd as Ut,Ki as Wt,Kl as Gt,Kn as Kt,Ko as qt,Kr as Jt,Ks as Yt,Kt as Xt,Ku as Zt,L as Qt,La as $t,Lc as en,Ld as tn,Li as nn,Ll as rn,Ln as an,Lo as on,Lr as sn,Ls as cn,Lt as ln,Lu as un,M as dn,Ma as fn,Mc as pn,Md as L,Mi as mn,Ml as hn,Mn as gn,Mo as _n,Mr as vn,Ms as yn,Mt as bn,Mu as xn,Na as Sn,Nc as Cn,Nd as R,Ni as wn,Nl as Tn,Nn as En,No as Dn,Nr as On,Ns as kn,Nt as An,Nu as jn,O as Mn,Oa as Nn,Oc as Pn,Od as Fn,Oi as In,Ol as Ln,On as Rn,Oo as zn,Or as Bn,Os as Vn,Ot as Hn,Ou as Un,P as Wn,Pa as Gn,Pc as Kn,Pd as qn,Pi as Jn,Pn as Yn,Po as Xn,Pr as Zn,Ps as Qn,Pt as $n,Pu as er,Q as tr,Qa as nr,Qc as rr,Qd as ir,Qi as ar,Qn as or,Qo as eee,Qr as sr,Qs as cr,Qt as lr,Qu as ur,R as dr,Ra as fr,Rd as pr,Ri as tee,Rn as mr,Ro as hr,Rr as gr,Rs as _r,Rt as vr,Ru as yr,Sa as nee,Sc as br,Sd as xr,Si as Sr,Sl as Cr,Sn as ree,So as wr,Sr as Tr,Ss as Er,St as Dr,Su as Or,T as kr,Ta as Ar,Tc as jr,Td as Mr,Tf as Nr,Ti as Pr,Tl as Fr,Tn as Ir,To as Lr,Tr as iee,Ts as aee,Tt as Rr,Tu as zr,Ua as oee,Uc as see,Ud as cee,Ui as lee,Ul as Br,Un as Vr,Uo as uee,Ur as dee,Us as fee,Ut as pee,Uu as Hr,V as Ur,Va as Wr,Vc as Gr,Vd as Kr,Vi as qr,Vl as Jr,Vn as Yr,Vo as Xr,Vr as Zr,Vs as mee,Vt as hee,Vu as Qr,Wa as $r,Wc as gee,Wd as _ee,Wi as vee,Wl as ei,Wn as yee,Wo as bee,Wr as xee,Ws as See,Wt as Cee,Wu as wee,Xa as Tee,Xd as Eee,Xi as Dee,Xl as Oee,Xn as ti,Xo as kee,Xr as Aee,Xt as ni,Xu as ri,Y as jee,Ya as ii,Yd as Mee,Yi as Nee,Yl as Pee,Yn as Fee,Yo as Iee,Yr as Lee,Ys as Ree,Yt as ai,Yu as oi,Za as zee,Zc as Bee,Zd as Vee,Zi as Hee,Zn as Uee,Zo as Wee,Zr as Gee,Zs as Kee,Zt as si,Zu as ci,_ as qee,_a as Jee,_c as li,_d as ui,_i as di,_l as Yee,_n as Xee,_o as Zee,_r as fi,_s as Qee,_t as pi,_u as mi,a as $ee,aa as hi,ac as ete,ad as tte,ai as nte,al as rte,an as ite,ao as ate,ar as ote,as as ste,at as cte,au as lte,b as ute,ba as gi,bc as _i,bd as z,bf as vi,bi as dte,bl as fte,bn as pte,bo as mte,br as yi,bs as hte,bt as gte,bu as _te,c as vte,ca as yte,cd as bte,ci as xte,cl as Ste,cn as bi,co as xi,cr as Cte,cs as wte,ct as Si,cu as Tte,d as Ci,da as Ete,dc as wi,di as Dte,dl as Ote,dn as kte,do as Ate,dr as jte,ds as Mte,dt as Ti,du as Ei,ea as Nte,ec as Pte,ed as Di,ef as Oi,ei as ki,el as Ai,en as Fte,eo as Ite,er as ji,es as Mi,et as Lte,eu as Ni,fa as Rte,fc as Pi,fd as zte,fi as Bte,fl as Vte,fn as Hte,fo as Ute,fr as Wte,fs as Gte,ft as Fi,fu as Ii,g as Kte,ga as Li,gd as qte,gf as Jte,gi as Yte,gl as Ri,gn as Xte,go as zi,gr as Zte,gs as Qte,gt as Bi,gu as $te,h as ene,ha as Vi,hc as Hi,hf as tne,hi as nne,hn as rne,ho as Ui,hr as ine,hs as ane,ht as one,hu as Wi,ia as sne,ic as cne,id as lne,if as Gi,ii as une,il as dne,in as fne,io as pne,ir as mne,is as hne,it as Ki,iu as gne,j as qi,ja as Ji,jc as _ne,jd as vne,ji as yne,jl as bne,jn as xne,jo as Yi,jr as Sne,js as Xi,jt as Cne,ju as Zi,kd as B,kf as wne,ki as Qi,kl as $i,kn as Tne,ko as Ene,kr as Dne,ks as One,kt as kne,ku as Ane,la as ea,lc as ta,ld as jne,lf as Mne,li as Nne,ll as na,ln as Pne,lo as Fne,lr as Ine,ls as Lne,lt as ra,lu as Rne,m as ia,ma as zne,mc as aa,mf as Bne,mi as Vne,mn as Hne,mo as Une,mr as Wne,ms as Gne,mt as Kne,mu as oa,n as sa,na as qne,nc as Jne,nd as Yne,nf as Xne,ni as Zne,nl as Qne,nn as $ne,no as ca,nr as ere,ns as tre,nt as nre,nu as rre,o as ire,oa as are,od as ore,of as la,oi as sre,ol as ua,on as cre,oo as lre,or as ure,os as dre,ot as da,ou as fre,pa as pre,pc as mre,pd as hre,pi as gre,pn as _re,po as vre,pr as fa,ps as yre,pt as pa,pu as bre,qa as xre,qd as Sre,qi as Cre,ql as ma,qn as ha,qo as wre,qr as Tre,qs as Ere,qt as Dre,qu as Ore,ra as kre,rc as Are,rd as jre,ri as Mre,rl as Nre,rn as Pre,ro as Fre,rr as Ire,rs as Lre,rt as Rre,ru as zre,s as ga,sa as _a,sc as va,sd as Bre,sf as ya,si as ba,sl as xa,sn as Vre,so as Hre,sr as Ure,ss as Wre,st as Sa,su as Ca,t as wa,tc as Ta,td as Gre,tf as Kre,ti as Ea,tn as qre,to as Jre,tr as Yre,ts as Da,tu as Xre,ua as Zre,uc as Oa,ud as Qre,uf as ka,ui as $re,ul as Aa,un as eie,uo as tie,ur as nie,us as rie,ut as ja,uu as Ma,v as iie,vc as Na,vd as Pa,vf as aie,vi as oie,vn as Fa,vo as Ia,vr as La,vs as sie,vt as Ra,vu as cie,w as lie,wa as za,wc as uie,wd as Ba,wf as Va,wi as die,wl as fie,wn as pie,wo as mie,wr as hie,ws as gie,wt as Ha,wu as _ie,x as vie,xa as yie,xc as Ua,xd as Wa,xf as bie,xi as xie,xl as Sie,xn as Cie,xo as wie,xr as Tie,xs as Eie,xt as Ga,xu as Die,y as Oie,yc as kie,yf as Ka,yi as qa,yl as Aie,yn as Ja,yo as jie,yr as Mie,ys as Nie,yt as Ya,yu as Pie,za as Xa,zc as Fie,zd as Iie,zi as Lie,zl as Rie,zn as zie,zo as Za,zr as Bie,zs as Vie,zt as Qa,zu as Hie}from"./md-manager-BGnqyqi1-j5JtqA4V.mjs";import{c as $a,d as eo,h as Uie,i as to,l as no,n as ro,o as io,p as ao,t as oo}from"./esm-B3YyV3nD.mjs";import{t as Wie}from"./libesm-DRoEqbAC.mjs";import{t as Gie}from"./yazl-BBz29IQN.mjs";import{t as so}from"./chunk-B74TABJS-DAm9lxFL.mjs";import{a as co,c as lo,d as Kie,f as uo,h as qie,i as fo,l as po,m as mo,n as ho,o as go,p as _o,r as vo,s as yo,t as bo,u as xo}from"./chunk-GFQRA5P5-ZJVBMLyZ.mjs";import{A as So,B as Co,C as wo,D as To,E as Jie,F as Yie,H as Xie,I as Zie,L as Eo,M as Do,N as Oo,O as ko,P as Ao,S as Qie,T as $ie,V as eae,_ as tae,a as jo,b as Mo,c as No,d as Po,f as Fo,g as nae,h as rae,i as Io,j as Lo,k as Ro,l as zo,m as iae,n as aae,o as Bo,p as Vo,r as Ho,s as Uo,t as oae,u as Wo,v as Go,w as Ko,x as qo,y as Jo,z as Yo}from"./chunk-BGSUD5R5-Do2r1ZFF.mjs";import{n as Xo,r as Zo,t as Qo}from"./chunk-R6VWJ2ZL-DJY9gweS.mjs";import{r as $o}from"./chunk-CWQS3NFK-BbpS-dVt.mjs";import{t as sae}from"./chunk-DXB73IDG-DFy9txNR.mjs";import{n as es,t as ts}from"./chunk-5QMZ5MUS-BuB3i_B5.mjs";import{n as cae,t as lae}from"./chunk-A5O5YHGN-BRMz0iFo.mjs";import{n as ns,r as rs,t as uae}from"./chunk-OJDRYQWQ-JGMWNwO9.mjs";import{r as dae,t as is}from"./chunk-24IMIIXA-Dj5K6qOb.mjs";import{n as as}from"./chunk-3THT3N7L-DVKHLRUO.mjs";import{t as os}from"./chunk-44UOCSGV-CeGMLWmo.mjs";import{t as fae}from"./wrapper-BF8oRx3G.mjs";import{createRequire as ss}from"node:module";import{execFile as cs,execFileSync as pae,spawn as ls,spawnSync as us}from"node:child_process";import*as ds from"node:path";import{basename as fs,delimiter as ps,dirname as V,extname as ms,isAbsolute as hs,join as H,normalize as gs,parse as mae,posix as _s,relative as U,resolve as W,sep as vs,win32 as ys}from"node:path";import{URLSearchParams as hae,fileURLToPath as bs,pathToFileURL as xs}from"node:url";import*as Ss from"node:fs";import{accessSync as gae,appendFileSync as _ae,chmodSync as Cs,closeSync as ws,constants as Ts,cpSync as vae,createReadStream as Es,createWriteStream as Ds,existsSync as G,fchmodSync as yae,fstatSync as bae,linkSync as xae,lstatSync as Os,mkdirSync as ks,mkdtempSync as As,openSync as js,opendirSync as Sae,readFile as Cae,readFileSync as K,readSync as wae,readdirSync as Ms,readlinkSync as Tae,realpathSync as Ns,renameSync as Ps,rmSync as Fs,rmdirSync as Is,statSync as Ls,symlinkSync as Eae,unlinkSync as Rs,watch as Dae,writeFileSync as zs,writeSync as Bs}from"node:fs";import{arch as Vs,availableParallelism as Oae,homedir as Hs,hostname as Us,platform as Ws,tmpdir as Gs,userInfo as kae}from"node:os";import{access as Ks,appendFile as Aae,chmod as jae,constants as qs,glob as Mae,lstat as Js,mkdir as Ys,readFile as Xs,readdir as Zs,readlink as Nae,realpath as Qs,rename as $s,rm as Pae,stat as ec,unlink as Fae,writeFile as tc}from"node:fs/promises";import{Readable as nc,Transform as Iae,Writable as rc}from"node:stream";import Lae from"crypto";import ic,{createHash as ac,randomUUID as oc,webcrypto as sc}from"node:crypto";import{EventEmitter as cc}from"node:events";import{Worker as Rae}from"node:worker_threads";import*as zae from"zlib";import{Readable as lc}from"stream";import{readdirSync as Bae,statSync as Vae}from"fs";import{spawn as Hae}from"child_process";import{promisify as uc,stripVTControlCharacters as Uae}from"node:util";import{DatabaseSync as dc}from"node:sqlite";import{monitorEventLoopDelay as Wae,performance as fc}from"node:perf_hooks";import{createInterface as Gae}from"node:readline";import{setImmediate as Kae,setTimeout as pc}from"node:timers/promises";import{AsyncLocalStorage as mc}from"node:async_hooks";import{pipeline as hc}from"node:stream/promises";import{request as qae}from"node:http";import{Http2ServerRequest as gc,constants as Jae}from"node:http2";import{lookup as Yae}from"node:dns/promises";import{request as Xae}from"node:https";import{createBrotliDecompress as Zae,createGunzip as Qae,createInflate as $ae}from"node:zlib";import{join as _c,resolve as eoe}from"path";import*as toe from"node:querystring";import{Http2ServerRequest as vc,constants as noe}from"http2";import{lookup as roe}from"node:dns";import ioe from"node:tls";const aoe=2,yc={protocol:`x-ok-client-protocol`,runtime:`x-ok-client-runtime`,kind:`x-ok-client-kind`},ooe={desktop:!0,browser:!0,"embedded:cursor":!0,"embedded:codex":!0,"embedded:claude-desktop":!0},soe={mcp:!0,"desktop-main":!0,cli:!0};function coe(e){return Object.hasOwn(ooe,e)}function loe(e){if(!(e===void 0||e.length===0||Object.hasOwn(soe,e)))return coe(e)?e:`unknown`}function uoe({kind:e,runtimeVersion:t}){return{[yc.protocol]:`2`,[yc.runtime]:t,[yc.kind]:e}}const doe=new Set([`*`,`_`,"`",`~`,`\\`,`$`]),foe=/^={2,}/,bc=/^<(?:[A-Za-z][A-Za-z0-9+.-]*:[^<>\s]*|[^\s<>@]+@[^\s<>]+)>/;function poe(e,t){return bc.test(e.slice(t,t+512))}function moe(e,t){let n=e.lastIndexOf(`<`,t);return n<0||t-n>512?!1:bc.exec(e.slice(n,t+1))?.[0].length===t+1-n}const hoe=/^<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^>]*?)?\/?>/,goe=/^!(?=\[)/,_oe=/^\[\^/,voe=/^\]\[[^\]]*\]/,yoe=/^\[\[[^\][|]*\|/,boe=/^#[^\][|]*(?=\]\])/,xoe=/^\]\([^)]*\)/,Soe=/^(?:#{1,6}[ \t]+|>[ \t]?|(?:[-*+]|\d{1,9}[.)])[ \t]+(?:\[[ xX]\][ \t]+)?)/,Coe=/^(?:`{3,}[^`\n]*|~{3,}[^\n]*)$/,woe=/^(?:(?:[-*_][ \t]*){3,}|=+[ \t]*|[|\-: \t]*-[|\-: \t]*)$/;function Toe(e,t){let n=e.indexOf(`
2
2
  `,t),r=n===-1?e.length:n;if(r>t&&e[r-1]===`\r`&&--r,r-t>1024)return 0;let i=e.slice(t,r);return i.length===0||!Coe.test(i)&&!woe.test(i)?0:i.length}const xc=/&#(?:x[0-9A-Fa-f]+|X[0-9A-Fa-f]+|[0-9]+);/y;function Sc(e,t){if(e[t]!==`&`)return null;let n=t,r=``;for(;;){xc.lastIndex=n;let t=xc.exec(e)?.[0];if(t===void 0)break;let i=gne(t);if(i===null)break;r+=i,n+=t.length}return n===t?null:{length:n-t,rendered:r}}function Cc(e){return e===` `||e===` `||e===`
3
3
  `||e===`\r`||e===`\f`||e===`\v`}function wc(e,t){for(let n=t-1;n>=0;--n){let t=e[n];if(t===`
4
4
  `)return!0;if(t!==` `&&t!==` `)return!1}return!0}function Tc(e,t){let n=e[t];if(n===void 0)return 0;if(wc(e,t)){let n=Toe(e,t);if(n>0)return n}if(n===`|`)return 1;if(n===`<`){let n=hoe.exec(e.slice(t,t+512))?.[0].length;return n===void 0?+!!poe(e,t):n}if(n===`>`&&moe(e,t))return 1;if(n===`=`){let n=foe.exec(e.slice(t,t+3))?.[0].length;if(n!==void 0)return n}if(n===`!`)return+!!goe.test(e.slice(t,t+2));if(doe.has(n))return 1;if(n===`[`){let n=e.slice(t,t+512),r=yoe.exec(n)?.[0].length;return r===void 0?_oe.test(n)?2:1:r}if(n===`#`){let n=boe.exec(e.slice(t,t+512))?.[0].length;if(n!==void 0)return n}if(n===`]`){if(e[t+1]===`]`)return 2;let n=e.slice(t,t+512),r=xoe.exec(n)?.[0].length;if(r!==void 0)return r;let i=voe.exec(n)?.[0].length;return i===void 0?1:i}return wc(e,t)?Soe.exec(e.slice(t,t+32))?.[0].length??0:0}function Eoe(e,t,{syntaxIn:n}){let r=[];if(t.length===0)return r;let i=n===`haystack`;for(let n=0;n<e.length;n+=1){let a=e[n];if(a===void 0||Cc(a)||i&&a!==t[0]&&(Tc(e,n)>0||Sc(e,n)!==null))continue;let o=n,s=0;for(;o<e.length&&s<t.length;){let n=e[o],r=t[s];if(n===r){o+=1,s+=1;continue}if(Cc(r)){s+=1;continue}if(Cc(n)){o+=1;continue}let a=i?Tc(e,o):Tc(t,s);if(a>0){i?o+=a:s+=a;continue}let c=i?Sc(e,o):Sc(t,s);if(c!==null){let n=i?t:e,r=i?s:o,a=!0;for(let e of c.rendered)if(!Cc(e)){for(;r<n.length&&Cc(n[r]);)r+=1;if(n[r]!==e){a=!1;break}r+=1}if(!a)break;i?(o+=c.length,s=r):(s+=c.length,o=r);continue}break}for(;s<t.length&&Cc(t[s]);)s+=1;s===t.length&&r.push({start:n,end:o})}return r}function Ec(e,t,n,r){let i=``,a=Math.max(0,t),o=Math.min(e.length,n);for(;a<o;){let t=e[a];if(Cc(t)){a+=1;continue}if(r){let t=Tc(e,a);if(t>0){a+=t;continue}let n=Sc(e,a);if(n!==null){for(let e of n.rendered)Cc(e)||(i+=e);a+=n.length;continue}}i+=t,a+=1}return i}function Doe(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[e.length-1-r]===t[t.length-1-r];)r+=1;return r}function Ooe(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function Dc(e,t,n,{syntaxIn:r,syntaxInContext:i=!1}){let a=n.prefix??``,o=n.suffix??``,s=r===`haystack`,c=0;if(a.length>0){let n=a.length*8+64;c+=Doe(Ec(a,0,a.length,i),Ec(e,t.start-n,t.start,s))}if(o.length>0){let n=o.length*8+64;c+=Ooe(Ec(o,0,o.length,i),Ec(e,t.end,t.end+n,s))}return c}function koe(e,{syntaxInContext:t=!1}={}){let n=Ec(e.prefix??``,0,1/0,t).length+Ec(e.suffix??``,0,1/0,t).length;return Math.min(8,n)}function Aoe(e){return Math.max(e*4,e+64)}function Oc(e,t){let n=e.length,r=t.length,i=0;for(;i<n&&i<r&&e[i]===t[i];)i++;let a=n,o=r;for(;a>i&&o>i&&e[a-1]===t[o-1];)a--,o--;return o<=i?null:{from:i,to:o}}const kc=`epoch`,Ac=524288,jc={cursor:/\bCursor(?:\([^)]+\))?\/\d/,codex:/\bCodex(?:\([^)]+\))?\/\d/,"claude-desktop":/\bClaude(?:\([^)]+\))?\/\d/},Mc=[`incoming`,`outgoing`,`both`];function Nc(e){return Mc.includes(e)}const joe=[{id:`chart`,title:`Chart`,description:`A bar chart whose series colors track the OK chart palette.`,html:`<div style="font-family:system-ui,sans-serif;padding:20px;color:var(--foreground)">
@@ -874,7 +874,7 @@ ${e.terminator}`}function Nqe(e){return`(${sB(e.body)})${oB(e.redirections)}`}fu
874
874
  `;)h+=1;continue}if(e==="`"||e===`(`||e===`)`)return null;if(e===`$`){let e=EV(t,h,d);if(e===null)return null;h=e;continue}if(e===`*`||e===`?`||e===`[`||e===`{`||e===`}`||e===`~`&&!s){d(e,!1),h+=1;continue}if(e===`
875
875
  `||e===`;`){p(),h+=1;continue}if(e===`|`){p(),h+=n===`|`||n===`&`?2:1;continue}if(e===`&`){if(n===`&`){p(),h+=2;continue}return null}if(e===`>`){if(!m()||l)return null;if(n===`&`){let e=xYe(t,h+2);if(e===null)return null;h=e;continue}let e=h+1;(t[e]===`>`||t[e]===`|`)&&(e+=1);let r=SYe(t,e);if(r===null)return null;h=r;continue}if(e===`<`){if(n===`<`||n===`(`||n===`&`||n===`>`||!m()||l)return null;l=!0,h+=1;continue}if(e===` `||e===` `){f(),h+=1;continue}d(e,!0),h+=1}return c===null?(p(),u?null:n):null}function EV(e,t,n){let r=e[t+1];if(r===void 0)return n(`$`,!1),t+1;if(r===`(`||r===`[`||r===`'`||r===`"`)return null;if(r===`{`){let r=t+2,i=``;for(;r<e.length&&e[r]!==`}`;)i+=e[r],r+=1;return e[r]!==`}`||!eYe.test(i)?null:(n(`\${${i}}`,!1),r+1)}if(tYe.test(r)){let r=t+1,i=``;for(;r<e.length&&nYe.test(e[r]??``);)i+=e[r],r+=1;return n(`$${i}`,!1),r}return rYe.test(r)?(n(`$${r}`,!1),t+2):(n(`$`,!1),t+1)}function DV(e,t){let n=e[t];return n===void 0||sYe.has(n)}function xYe(e,t){let n=e[t]??``;return n!==`-`&&!gV.test(n)?null:DV(e,t+1)?t+1:null}function SYe(e,t){let n=t;for(;e[n]===` `||e[n]===` `;)n+=1;let r=``;for(;n<e.length&&!oYe.has(e[n]??``);)r+=e[n],n+=1;return r===_V&&DV(e,n)?n:null}function CYe(e){let t=e;for(;t.length>0&&$Je.test(t[0]?.text??``);){if(!QJe.test(t[0]?.text??``))return!1;t=t.slice(1)}t[0]?.text===`!`&&(t=t.slice(1));let n=t[0];if(n===void 0)return!0;if(t.some(e=>e.text===`{`||e.text===`}`)||!n.literal)return!1;let r=wYe(n.text);if(r===null)return!1;if(XJe.has(r))return!0;let i=DYe.get(r);if(i===void 0)return!1;let a=t.slice(1);return a.every(e=>e.literal)?i(a.map(e=>e.text)):!1}function wYe(e){if(!e.includes(`/`))return e;let t=ZJe.find(t=>e.startsWith(t));if(t===void 0)return null;let n=e.slice(t.length);return n.includes(`/`)||n===``?null:n}function OV(e,t){return!e.startsWith(`-`)||e.startsWith(`--`)||e.length<2?!1:Array.from(e.slice(1)).some(e=>t.includes(e))}function TYe(e){return e===`-`||!e.startsWith(`-`)}function kV(e){return e.split(`=`,1)[0]??e}function AV(e,t,n){if(!e.startsWith(`--`))return!1;let r=kV(e);return r.startsWith(n)&&t.startsWith(r)}function EYe(e){return e.some((t,n)=>{if(t===`--show-signature`)return!0;if(!fYe.some(e=>AV(t,e,e.slice(0,3))))return!1;let r=kV(t),i=r===t?e[n+1]??``:t.slice(r.length+1);return pYe.test(i)})}function jV(e,t,n){return e.startsWith(`--`)?t.has(kV(e)):!e.startsWith(`-`)||e.length<2?!1:Array.from(e.slice(1)).every(e=>n.includes(e))}const DYe=new Map([[`command`,e=>(e[0]===`-v`||e[0]===`-V`)&&e.length>1],[`curl`,kYe],[`date`,e=>!e.some(e=>AV(e,`--set`,`--s`)||OV(e,`s`))],[`find`,e=>!e.some(e=>cYe.has(e))],[`git`,OYe],[`hostname`,e=>e.every(e=>_Ye.has(e))],[`sort`,e=>!e.some(e=>AV(e,`--output`,`--o`)||AV(e,`--temporary-directory`,`--t`)||AV(e,`--compress-program`,`--c`)||OV(e,`oT`))],[`tree`,e=>!e.some(e=>OV(e,`o`))],[`uniq`,e=>e.filter(TYe).length<=1]]);function OYe(e){let t=0;for(;t<e.length&&(e[t]??``).startsWith(`-`);){let n=e[t];if(n===`--no-pager`||n===`-P`){t+=1;continue}if(n===`-C`&&e[t+1]!==void 0){t+=2;continue}return!1}let n=e[t];if(n===void 0)return!1;let r=e.slice(t+1),i=dYe.get(n)??[];if(EYe(r)||r.some(e=>uYe.has(e)||mYe.some(t=>e.startsWith(t))||i.some(([t,n])=>AV(e,t,n))||OV(e,`O`)))return!1;if(lYe.has(n))return!0;switch(n){case`branch`:return r.every(e=>jV(e,hYe,`arvli`));case`tag`:return r.every(e=>jV(e,gYe,`lni0123456789`));case`remote`:return r.every(e=>e===`-v`||e===`--verbose`)||r[0]===`show`||r[0]===`get-url`;case`stash`:return r[0]===`list`||r[0]===`show`;case`worktree`:return r[0]===`list`;case`reflog`:return r.length===0||r[0]===`show`;case`config`:return[`--get`,`--get-all`,`--get-regexp`,`--list`,`-l`].includes(r[0]??``);default:return!1}}function kYe(e){let t=!1;for(let n=0;n<e.length;n+=1){let r=e[n]??``;if(r.startsWith(`--`)){let i=r.indexOf(`=`),a=i===-1?r:r.slice(0,i),o=i===-1?null:r.slice(i+1);if(vV.has(a)){if(o!==null)return!1;continue}let s=wV[a];if(s===void 0)return!1;let c=o;if(c===null&&(n+=1,c=e[n]??null),c===null||!s(c))return!1;a===`--url`&&(t=!0);continue}if(r.startsWith(`-`)&&r.length>1){let t=Array.from(r.slice(1));for(let[r,i]of t.entries()){let a=`-${i}`;if(vV.has(a))continue;let o=wV[a];if(o===void 0)return!1;let s=t.slice(r+1).join(``),c=s===``?null:s;if(c===null&&(n+=1,c=e[n]??null),c===null||!o(c))return!1;break}continue}if(!hV.test(r))return!1;t=!0}return t}const AYe=new Set,MV=new Set(Kre);function jYe(e){let t=Ox(e,`known`)?.tool;return t!==void 0&&MV.has(t)}const NV=new Set;function PV(e,t,n){return jx({absPath:Vx(`user`,e,t),sideline:!1,warn:e=>{n===void 0||NV.has(e)||(NV.add(e),n.warn({message:e},`[acp-permissions] user config could not be read`))}}).value.agents}function MYe(e,t,n){return PV(e,t,n)?.autoApproveOkTools!==!1}function FV(e,t,n){return PV(e,t,n)?.browserTools===!0}function NYe(e,t){return e.kind===`none`?t:t.filter(e=>e.kind!==`allow_always`)}function IV(e){return e.kind??`other`}function PYe(e,t){return t.kind!==`none`||jYe(e)?null:IV(e)}function FYe(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var LV=class{filePath;log;grants=null;constructor(e,t){this.filePath=H(e,`acp-permissions.json`),this.log=t}decide(e,t,n,r,i=AYe,a=!0){let o=FYe(n,[`allow_once`,`allow_always`]);if(o===void 0)return{auto:null};let s={auto:{optionId:o.optionId}};if(r.kind!==`none`)return{auto:null};let c=Ox(t,`known`)?.tool;if(c!==void 0){if(MV.has(c))return{auto:null};if(a)return s}let l=IV(t);return l===`read`||i.has(`read_only_shell`)&&TV(t)!==null||this.hasAllowAlways(e,l)?s:{auto:null}}hasAllowAlways(e,t){return this.loadGrants().some(n=>n.agentId===e&&n.toolKind===t)}async recordChoice(e,t,n,r){if(n.kind!==`allow_always`)return;let i=PYe(t,r);if(i===null||this.hasAllowAlways(e,i))return;let a=[...this.loadGrants(),{agentId:e,toolKind:i}];this.grants=a;try{let{tracedMkdir:e,tracedWriteFile:t}=await Promise.resolve().then(()=>NH);await e(H(this.filePath,`..`),{recursive:!0});let n={version:1,grants:a};await t(this.filePath,`${JSON.stringify(n,null,2)}\n`)}catch(e){this.log.warn({err:e},`[acp-permissions] persisting allow_always grant failed`)}}loadGrants(){if(this.grants!==null)return this.grants;try{let e=JSON.parse(K(this.filePath,`utf8`));this.grants=Array.isArray(e?.grants)?e.grants.filter(e=>typeof e?.agentId==`string`&&typeof e?.toolKind==`string`):[]}catch{this.grants=[]}return this.grants}};const RV=Qre,zV=bte,BV=`acp-agents.json`,VV=`acp-registry-cache.json`;function HV(){let e=Ws(),t=Vs(),n=e===`darwin`?`darwin`:e===`linux`?`linux`:e===`win32`?`windows`:null,r=t===`arm64`?`aarch64`:t===`x64`?`x86_64`:null;return n===null||r===null?null:`${n}-${r}`}const IYe=new Set([`goose`,`fast-agent`,`crow-cli`]);function LYe(e,t){let n=t.trim();return n.length===0?e:IYe.has(e)||n!==n.toLowerCase()?n:n.split(/\s+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function RYe(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.name==`string`&&typeof t.version==`string`&&typeof t.distribution==`object`&&t.distribution!==null}function UV(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(RYe).map(e=>({...e,name:LYe(e.id,e.name)})):null}var WV=class{localDir;log;ttlMs;fetchImpl;memory=null;inflight=null;constructor(e){this.localDir=e.localDir,this.log=e.log,this.ttlMs=e.ttlMs??36e5,this.fetchImpl=e.fetchImpl??fetch}async getCatalog(){return this.memory!==null&&Date.now()-this.memory.fetchedAt<this.ttlMs&&!this.memory.stale?this.memory:(this.inflight===null&&(this.inflight=this.refresh().finally(()=>{this.inflight=null})),this.inflight)}async getAgent(e){let{agents:t}=await this.getCatalog();return t.find(t=>t.id===e)}async refresh(){try{let e=await this.fetchImpl(`https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json`,{signal:AbortSignal.timeout(15e3)});if(!e.ok)throw Error(`registry fetch failed: HTTP ${e.status}`);let t=await e.text(),n=UV(t);if(n===null)throw Error(`registry payload did not parse as a catalog`);this.memory={agents:n,fetchedAt:Date.now(),stale:!1};try{let{tracedMkdir:e,tracedWriteFile:n}=await Promise.resolve().then(()=>NH);await e(this.localDir,{recursive:!0}),await n(H(this.localDir,VV),t)}catch(e){this.log.warn({err:e},`[acp-registry] disk cache write failed`)}return this.memory}catch(e){let t=await this.readDiskCache();if(t!==null)return this.log.warn({err:e},`[acp-registry] CDN unreachable — serving disk cache`),this.memory=t,t;if(this.memory!==null)return this.log.warn({err:e},`[acp-registry] CDN unreachable — serving stale memory copy`),this.memory={...this.memory,stale:!0},this.memory;throw e instanceof Error?e:Error(String(e))}}async readDiskCache(){try{let e=UV(await Xs(H(this.localDir,VV),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function GV(e,t){let n;try{n=await Xs(H(e,BV),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({error:e instanceof Error?e.name:`unknown`,position:zYe(e)},`[acp-registry] ${BV} is not valid JSON — ignoring`),[]}if(!Array.isArray(r))return t.warn({topLevel:r===null?`null`:typeof r},`[acp-registry] ${BV} must be a JSON array of agents — ignoring`),[];let i=[];for(let[e,n]of r.entries()){let r=BYe(n);r.ok?i.push(r.entry):t.warn({index:e,id:r.id,problem:r.problem},`[acp-registry] dropping malformed ${BV} entry`)}return i}function zYe(e){if(!(e instanceof Error))return;let t=/at position (\d+)/.exec(e.message);return t===null?void 0:Number(t[1])}function BYe(e){let t=typeof e==`object`&&e&&!Array.isArray(e)?e:{},n=typeof t.id==`string`?t.id:void 0,r=e=>({ok:!1,id:n,problem:e});return n===void 0||!/^[a-zA-Z0-9_-]+$/.test(n)?r(`id must use only letters, digits, _ and -`):typeof t.name==`string`?typeof t.command!=`string`||t.command.length===0?r(`command must be a non-empty string`):t.args!==void 0&&!(Array.isArray(t.args)&&t.args.every(e=>typeof e==`string`))?r(`args must be an array of strings`):t.env!==void 0&&!(typeof t.env==`object`&&t.env!==null&&!Array.isArray(t.env)&&Object.values(t.env).every(e=>typeof e==`string`))?r(`env must be an object of string values`):{ok:!0,entry:{id:n,name:t.name,command:t.command,args:t.args,env:t.env??void 0}}:r(`name must be a string`)}function KV(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,128)}const qV=/^[a-zA-Z0-9_-]+$/,VYe=64;function JV(e){return typeof e==`string`?e.length===0?`empty`:e.length>64?`too-long`:qV.test(e)?null:`charset`:`not-a-string`}function YV(e){return typeof e==`string`&&JV(e)===null?e:null}function XV(e){return e.startsWith(`agent-`)?e:`agent-${e}`}function ZV(e){return!e.startsWith(`principal-`)}function QV(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)||t.startsWith(`local-agent-mode-`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}const $V=`principal-anonymous`,eH=`claude-1`,HYe=new Set([$V,eH]);function tH(e){return e}function nH(e){if(!HYe.has(e.agentId))return tH(e.agentId)}function rH(e){let t=e.agentId,n=t===void 0?null:JV(t),r=n===null&&typeof t==`string`?t:void 0;return n!==null&&q(`agent-write`).warn({event:`agent-id-validation-failed`,reason:n,agentIdType:typeof t,agentIdMaxLen:64},`request agentId failed validation and was discarded before writer-identity resolution`),{rawAgentId:r,suppliedWriterId:r===void 0?void 0:tH(XV(r)),displayName:typeof e.agentName==`string`?KV(e.agentName):`Claude`,clientName:typeof e.clientName==`string`?KV(e.clientName):void 0,clientVersion:typeof e.clientVersion==`string`?KV(e.clientVersion):void 0,label:typeof e.label==`string`?KV(e.label):void 0,colorSeed:typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):void 0}}async function iH(e){try{let t=e.snapshot===void 0?null:await e.snapshot(),n=Gre({agentId:e.agentId,mode:e.mode,probes:t?.probes??null,detection:t?.detection??null});return e.log.info(Bre(e.site,n),`[agent-gate] readiness`),n}catch(t){return e.log.warn({err:t,site:e.site,mode:e.mode},`[agent-gate] readiness could not be assessed`),null}}function aH(e){let t=ri(e);return t.frontmatter===``?t:ct(ci(t.frontmatter)).map===null?{frontmatter:``,body:e}:t}const oH=`open-knowledge-server`;let sH=null,cH=null,lH=null;function uH(){return{tracer:to.getTracer(oH),meter:$a.getMeter(oH)}}function dH(e={}){let t=e.localSink!==void 0,n=process.env.OTEL_SDK_DISABLED===`false`;if(!t&&!n||sH)return uH();try{let r=(0,ake.resourceFromAttributes)({[Ly]:process.env.OTEL_SERVICE_NAME||`open-knowledge-server`,[Ry]:process.env.OTEL_SERVICE_VERSION||`0.2.0`}),i=new nke.AsyncLocalStorageContextManager;eo.setGlobalContextManager(i);let a=[],o=e.localSink?.attributeDenylist??Ri;a.push(new N_e({attributeDenylist:o})),t&&e.localSink!==void 0&&(lH=new A_e({projectDir:e.localSink.projectDir,maxBytes:e.localSink.spansMaxBytes}),a.push(new bO.SimpleSpanProcessor(lH))),n&&a.push(new bO.BatchSpanProcessor(new ike.OTLPTraceExporter));let s=new bO.BasicTracerProvider({resource:r,spanProcessors:a});to.setGlobalTracerProvider(s),sH=s;try{io.setGlobalPropagator(new _b.W3CTraceContextPropagator)}catch(e){q(`telemetry`).warn({err:e},`OpenTelemetry propagator init failed — file sink active, distributed trace correlation degraded`)}let c=null;if(n){let e=new rke.OTLPMetricExporter;c=new yO.MeterProvider({resource:r,readers:[new yO.PeriodicExportingMetricReader({exporter:e})]}),$a.setGlobalMeterProvider(c)}cH=c,q(`telemetry`).info({file_sink_enabled:t,otlp_push_enabled:n,otlp_endpoint:n?process.env.OTEL_EXPORTER_OTLP_ENDPOINT||`http://localhost:4318`:null,service_name:r.attributes[Ly]},`OpenTelemetry initialized`)}catch(e){let t=q(`telemetry`);sH===null?(t.error({err:e},`failed to initialize OpenTelemetry — falling back to no-op`),cH=null,lH=null):(t.warn({err:e},`OpenTelemetry metrics init failed — traces still active, metrics degraded`),cH=null)}return uH()}const fH=5e3,pH=new Set;function mH(e){pH.add(e)}async function hH(){let e=q(`telemetry`);for(let t of pH)try{t()}catch(t){e.warn({err:t},`telemetry shutdown reset hook threw; continuing teardown`)}if(!sH&&!cH)return;let t=(lH?lH.forceFlush().catch(t=>{e.warn({err:t},`telemetry file-sink flush failed during shutdown`)}):Promise.resolve()).then(()=>Promise.all([sH?.shutdown().catch(t=>{e.warn({err:t},`tracer provider shutdown failed`)}),cH?.shutdown().catch(t=>{e.warn({err:t},`meter provider shutdown failed`)})])),n;await Promise.race([t.then(()=>(n!==void 0&&clearTimeout(n),!1)),new Promise(e=>{n=setTimeout(()=>e(!0),fH),n.unref?.()})])&&e.warn({},`telemetry shutdown timed out after ${fH}ms — data may be lost`),sH=null,cH=null,lH=null,to.disable(),$a.disable(),eo.disable()}function gH(){return to.getTracer(oH)}function _H(){return $a.getMeter(oH)}async function vH(e,t,n){return gH().startActiveSpan(e,t??{},async e=>{try{let t=await n(e);return e.isRecording(),t}catch(t){throw e.recordException(t),e.setStatus({code:ao.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function yH(e,t,n){return gH().startActiveSpan(e,t??{},e=>{try{return n(e)}catch(t){throw e.recordException(t),e.setStatus({code:ao.ERROR,message:t instanceof Error?t.message:String(t)}),t}finally{e.end()}})}function bH(e){let t=to.getSpan(eo.active());t&&t.setAttributes(e)}function xH(e,t,n,r){let{body:i}=ri(t);return r!==void 0&&r.rawContent===t?r.parsedJson:yH(`md.parseWithFallback`,{attributes:{"body.bytes":i.length,"doc.name":e.guid}},()=>wa.parseWithFallback(i,SH(n)))}function SH(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function CH(e){return wa.serialize(tD(e,sa).toJSON())}function wH(e,t,n,r,i,a){let o=CH(r),s=wa.serialize(n),{body:c}=ri(e.baselineFullMd),l=wa.serialize(wa.parseWithFallback(c,a));e.report({pendingBody:t,baselineBody:l,ytextDerivedBody:s,rebuiltBody:o,restorePayload:mi(i,t).md})}function TH(e,t,n,r,i,a){yH(`bridge.composeAndWriteRawBody`,{attributes:{surface:n,"body.bytes":t.length,"doc.name":e.guid}},()=>{let n=e.getXmlFragment(`default`),o=e.getText(`source`),s=o.toString(),c=xH(e,t,r,i),l=sa.nodeFromJSON(c),u=a?CH(n):void 0;if(s!==t&&Wi(o,s,t),$E(e,n,l,{mapping:new Map,isOMark:new Map}),a&&u!==void 0){let{frontmatter:e}=ri(a.baselineFullMd);wH(a,u,c,n,e,SH(r))}})}function EH(e,t,n,r,i){yH(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let a=e.getXmlFragment(`default`),o=e.getText(`source`),s=xH(e,t,n,r),c=sa.nodeFromJSON(s),l=i?CH(a):void 0,u=o.toString();if(u!==t&&(o.delete(0,u.length),o.insert(0,t)),$E(e,a,c,{mapping:new Map,isOMark:new Map}),i&&l!==void 0){let{frontmatter:e}=ri(i.baselineFullMd);wH(i,l,s,a,e,SH(n))}})}function UYe(e,t,n){let r=e.getXmlFragment(`default`),i=e.getText(`source`).toString(),{frontmatter:a,body:o}=ri(i),s=SH(t),c=wa.parseWithFallback(o,s),l=sa.nodeFromJSON(c),u=n?wa.serialize(tD(r,sa).toJSON()):void 0;if($E(e,r,l,{mapping:new Map,isOMark:new Map}),n&&u!==void 0){let e=wa.serialize(tD(r,sa).toJSON()),t=wa.serialize(c),{body:i}=ri(n.baselineFullMd),o=wa.serialize(wa.parseWithFallback(i,s));n.report({pendingBody:u,baselineBody:o,ytextDerivedBody:t,rebuiltBody:e,restorePayload:mi(a,u).md})}}const WYe=q(`loss-capture`),DH=`detector-trip`,OH=`backstop-trip`,kH=`checkpoint-write`;B({ts:Fn(),schemaVersion:Fn(),seq:Fn(),event:R(),docName:R(),writerId:R().nullable(),site:R().optional(),direction:R().optional(),lostLen:Fn().optional(),digest:R().optional(),checkpointSha:R().optional(),which:R().optional(),witnessAvailable:Wa().optional(),connections:Fn().optional()});const AH=[`.ok`,`local`,`loss-capture`];function GYe(e){return H(e,...AH,`loss-current.jsonl`)}function KYe(e){return H(e,...AH,`loss-prev.jsonl`)}var qYe=class{#e;#t;#n=new Map;constructor(e){this.#e=new Jb({currentPath:GYe(e.projectDir),previousPath:KYe(e.projectDir),maxBytes:e.maxBytes}),this.#t=e.now??Date.now}record(e){let t=(this.#n.get(e.docName)??0)+1;this.#n.set(e.docName,t);let n={ts:this.#t(),schemaVersion:1,seq:t,event:e.event,docName:e.docName,writerId:e.writerId,...e.site===void 0?{}:{site:e.site},...e.direction===void 0?{}:{direction:e.direction},...e.lostLen===void 0?{}:{lostLen:e.lostLen},...e.digest===void 0?{}:{digest:e.digest},...e.checkpointSha===void 0?{}:{checkpointSha:e.checkpointSha},...e.which===void 0?{}:{which:e.which},...e.witnessAvailable===void 0?{}:{witnessAvailable:e.witnessAvailable},...e.connections===void 0?{}:{connections:e.connections}};return this.#e.append(`${JSON.stringify(n)}\n`).catch(t=>{WYe.warn({event:e.event,err:t},`[loss-capture] failed to write loss-class event`)})}async drain(){await this.#e.drain()}};const jH=q(`checkpoint-chain`);async function MH(e,t){let n;try{n=await e.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch(e){throw jH.warn({branch:t,err:e},`[checkpoint-chain] for-each-ref failed; anchors are unknown`),e}let r=n.trim().split(`
876
876
  `).map(e=>e.trim()).filter(e=>e.length===40);if(r.length===0)return[];let i;try{i=await e.raw(`log`,`--no-walk`,`--format=%H%x00%B%x1e`,...r)}catch(e){throw jH.warn({branch:t,shaCount:r.length,err:e},`[checkpoint-chain] checkpoint body read failed; anchors are unknown`),e}let a=[];for(let e of i.split(``)){let t=e.trimStart();if(!t)continue;let[n=``,r=``]=t.split(`\0`);n.length===40&&Tte(Ma(r)?.kind??null)&&a.push(n)}if(a.length<=1)return a;try{let t=(await e.raw(`merge-base`,`--independent`,...a)).trim().split(`
877
- `).map(e=>e.trim()).filter(e=>e.length===40);return t.length>0?t:a}catch(e){return jH.warn({branch:t,anchorCount:a.length,err:e},`[checkpoint-chain] tip reduction failed; adopting the full anchor set`),a}}var NH=xb({classifyFsPath:()=>FH,normalizeFsPath:()=>PH,tracedAppendFile:()=>BH,tracedAppendFileSync:()=>GH,tracedAtomicFs:()=>tU,tracedChmodSync:()=>LH,tracedCpSync:()=>JH,tracedLinkSync:()=>ZH,tracedMkdir:()=>UH,tracedMkdirSync:()=>KH,tracedOpenSync:()=>YH,tracedRename:()=>HH,tracedRenameSync:()=>qH,tracedRm:()=>VH,tracedRmSync:()=>$H,tracedRmdirSync:()=>eU,tracedSymlinkSync:()=>QH,tracedUnlinkSync:()=>XH,tracedWriteFile:()=>zH,tracedWriteFileSync:()=>WH});function PH(e){let t=e.split(vs).filter(Boolean);return t.length<=2?e:`...${vs}${t.slice(-2).join(vs)}`}function FH(e){return e.includes(`${vs}.git${vs}ok${vs}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${vs}.git${vs}`)?`git`:fs(e).endsWith(`.lock`)||fs(e)===`lock`?`lock`:fs(e)===`principal.json`?`principal`:e.includes(`${vs}.ok${vs}`)&&(fs(e)===`conflicts.json`||e.includes(`${vs}conflicts${vs}`))?`conflict`:e.includes(`${vs}.ok${vs}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function IH(e,t,n){let r={"fs.operation":e,"fs.path":PH(t),"fs.path.role":FH(t)};return n&&Object.assign(r,n),r}const LH=(e,t)=>yH(`fs.chmodSync`,{attributes:IH(`chmodSync`,String(e))},()=>Cs(e,t));function RH(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function zH(e,t,n){return vH(`fs.writeFile`,{attributes:IH(`writeFile`,e,{"fs.bytes":RH(t)})},async()=>{await tc(e,t,n)})}async function BH(e,t,n){return vH(`fs.appendFile`,{attributes:IH(`appendFile`,e,{"fs.bytes":RH(t)})},async()=>{await Aae(e,t,n)})}async function VH(e,t){return vH(`fs.rm`,{attributes:IH(`rm`,e)},async()=>{await Pae(e,t)})}async function HH(e,t){return vH(`fs.rename`,{attributes:IH(`rename`,t,{"fs.source_path":PH(e)})},async()=>{await $s(e,t)})}async function UH(e,t){return vH(`fs.mkdir`,{attributes:IH(`mkdir`,e)},async()=>Ys(e,t))}function WH(e,t,n){yH(`fs.writeFileSync`,{attributes:IH(`writeFileSync`,e,{"fs.bytes":RH(t)})},()=>{zs(e,t,n)})}function GH(e,t,n){yH(`fs.appendFileSync`,{attributes:IH(`appendFileSync`,e,{"fs.bytes":RH(t)})},()=>{_ae(e,t,n)})}function KH(e,t){return yH(`fs.mkdirSync`,{attributes:IH(`mkdirSync`,e)},()=>ks(e,t))}function qH(e,t){yH(`fs.renameSync`,{attributes:IH(`renameSync`,t,{"fs.source_path":PH(e)})},()=>{Ps(e,t)})}function JH(e,t,n){yH(`fs.cpSync`,{attributes:IH(`cpSync`,t,{"fs.source_path":PH(e)})},()=>{vae(e,t,n)})}function YH(e,t,n){return yH(`fs.openSync`,{attributes:IH(`openSync`,e)},()=>js(e,t,n))}function XH(e){yH(`fs.unlinkSync`,{attributes:IH(`unlinkSync`,e)},()=>{Rs(e)})}function ZH(e,t){yH(`fs.linkSync`,{attributes:IH(`linkSync`,t,{"fs.source_path":PH(e)})},()=>{xae(e,t)})}function QH(e,t,n){yH(`fs.symlinkSync`,{attributes:IH(`symlinkSync`,t,{"fs.source_path":PH(e)})},()=>{Eae(e,t,n)})}function $H(e,t){yH(`fs.rmSync`,{attributes:IH(`rmSync`,e)},()=>{Fs(e,t)})}function eU(e){yH(`fs.rmdirSync`,{attributes:IH(`rmdirSync`,e)},()=>{Is(e)})}const tU={writeFile:(e,t,n)=>zH(e,t,n),rename:(e,t)=>HH(e,t)},nU=[`status`,`--porcelain`,`-uall`];function rU(e){return e.split(`\0`).filter(e=>e.length>0)}function JYe(e){let t=[],n=e.split(`\0`);for(let e=0;e<n.length;e++){let r=n[e]??``;r.length<4||(t.push(r.slice(3)),(r[0]===`R`||r[0]===`C`||r[1]===`R`||r[1]===`C`)&&e++)}return t}function YYe(e){let t=[],n=e.split(`\0`);for(let e=0;e<n.length;e++){let r=n[e]??``;if(r.length<4)continue;let i=r[0]??` `,a=r[1]??` `,o={x:i,y:a,path:r.slice(3)};if(i===`R`||i===`C`||a===`R`||a===`C`){let t=n[e+1];t!==void 0&&t.length>0&&(o.origPath=t),e++}t.push(o)}return t}function XYe(e){let t=e.split(`\0`),n=[],r=0;for(;r<t.length;){let e=t[r]??``;if(e===``)break;if(e[0]===`R`||e[0]===`C`)n.push({status:e,from:t[r+1]??``,to:t[r+2]??``}),r+=3;else{let i=t[r+1]??``;n.push({status:e,from:i,to:i}),r+=2}}return n}function ZYe(e){let t=[];for(let n of e.split(`\0`)){if(!n)continue;let e=n.indexOf(` `);if(e<0)continue;let[r=``,i=``,a=``,o=`0`]=n.slice(0,e).trim().split(/\s+/),s=Number(o);t.push({mode:r,type:i,object:a,size:Number.isFinite(s)?s:0,path:n.slice(e+1)})}return t}function iU(e,t){let[n=``,...r]=t;return e.raw([n,`-z`,...r])}async function aU(e,t){return rU(await iU(e,t))}async function QYe(e,t=nU){return JYe(await iU(e,t))}async function oU(e,t=nU){return YYe(await iU(e,t))}async function sU(e,t){return XYe(await iU(e,t))}async function $Ye(e,t){return ZYe(await iU(e,t))}var cU=class extends Error{projectRoot;constructor(e){super(`Refusing to set up an OpenKnowledge project in your home directory (${e}).\n A project here would run 'git init' in your home directory and write project config\n and skills into your editors' user-global directories (~/.cursor, ~/.codex, ~/.claude).\n Make a folder for this project, then run 'ok init' inside it.`),this.name=`HomeProjectRootError`,this.projectRoot=e}},lU=class extends Error{projectRoot;constructor(e){super(`Refusing to set up an OpenKnowledge project at the top of a drive (${e}).\n A project here would scan every file on the drive and run 'git init' at its root.\n Make a folder for this project, then run 'ok init' inside it.`),this.name=`FilesystemRootProjectError`,this.projectRoot=e}};function uU(e){try{return Ns.native(e)}catch{return e}}function dU(e,t=Hs()){return uU(W(e))===uU(t)}function fU(e,t=process.platform){let n=t===`win32`?ys:_s,r=n.resolve(e),i=t===process.platform?uU(r):r;return n.dirname(i)===i||t===`darwin`&&i===`/System/Volumes/Data`}function pU(e,t){if(dU(e,t))throw new cU(W(e));if(fU(e))throw new lU(W(e))}const mU=`config.yml`;var hU=class extends Error{constructor(e,t){super(`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.`),this.name=`SymlinkRefusedError`}};function gU(e,t){let n;try{n=Os(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(n.isSymbolicLink())throw new hU(e,t)}function eXe(e){let[t=`0`,n=`0`]=e.split(`.`);return`${t.length>0?t:`0`}.${n.length>0?n:`0`}`}function tXe(e){return/^[A-Za-z0-9._\-/]+$/.test(e)?e:JSON.stringify(e)}function _U(e,t){let n=`# yaml-language-server: $schema=https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${$e}/config.project.schema.json
877
+ `).map(e=>e.trim()).filter(e=>e.length===40);return t.length>0?t:a}catch(e){return jH.warn({branch:t,anchorCount:a.length,err:e},`[checkpoint-chain] tip reduction failed; adopting the full anchor set`),a}}var NH=xb({classifyFsPath:()=>FH,normalizeFsPath:()=>PH,tracedAppendFile:()=>BH,tracedAppendFileSync:()=>GH,tracedAtomicFs:()=>tU,tracedChmodSync:()=>LH,tracedCpSync:()=>JH,tracedLinkSync:()=>ZH,tracedMkdir:()=>UH,tracedMkdirSync:()=>KH,tracedOpenSync:()=>YH,tracedRename:()=>HH,tracedRenameSync:()=>qH,tracedRm:()=>VH,tracedRmSync:()=>$H,tracedRmdirSync:()=>eU,tracedSymlinkSync:()=>QH,tracedUnlinkSync:()=>XH,tracedWriteFile:()=>zH,tracedWriteFileSync:()=>WH});function PH(e){let t=e.split(vs).filter(Boolean);return t.length<=2?e:`...${vs}${t.slice(-2).join(vs)}`}function FH(e){return e.includes(`${vs}.git${vs}ok${vs}`)||e.includes(`shadow-repo`)?`shadow-repo`:e.includes(`${vs}.git${vs}`)?`git`:fs(e).endsWith(`.lock`)||fs(e)===`lock`?`lock`:fs(e)===`principal.json`?`principal`:e.includes(`${vs}.ok${vs}`)&&(fs(e)===`conflicts.json`||e.includes(`${vs}conflicts${vs}`))?`conflict`:e.includes(`${vs}.ok${vs}`)?`ok-internal`:e.endsWith(`.md`)||e.endsWith(`.mdx`)?`content-md`:`other`}function IH(e,t,n){let r={"fs.operation":e,"fs.path":PH(t),"fs.path.role":FH(t)};return n&&Object.assign(r,n),r}const LH=(e,t)=>yH(`fs.chmodSync`,{attributes:IH(`chmodSync`,String(e))},()=>Cs(e,t));function RH(e){return typeof e==`string`?Buffer.byteLength(e,`utf-8`):e instanceof Uint8Array?e.byteLength:e.byteLength??0}async function zH(e,t,n){return vH(`fs.writeFile`,{attributes:IH(`writeFile`,e,{"fs.bytes":RH(t)})},async()=>{await tc(e,t,n)})}async function BH(e,t,n){return vH(`fs.appendFile`,{attributes:IH(`appendFile`,e,{"fs.bytes":RH(t)})},async()=>{await Aae(e,t,n)})}async function VH(e,t){return vH(`fs.rm`,{attributes:IH(`rm`,e)},async()=>{await Pae(e,t)})}async function HH(e,t){return vH(`fs.rename`,{attributes:IH(`rename`,t,{"fs.source_path":PH(e)})},async()=>{await $s(e,t)})}async function UH(e,t){return vH(`fs.mkdir`,{attributes:IH(`mkdir`,e)},async()=>Ys(e,t))}function WH(e,t,n){yH(`fs.writeFileSync`,{attributes:IH(`writeFileSync`,e,{"fs.bytes":RH(t)})},()=>{zs(e,t,n)})}function GH(e,t,n){yH(`fs.appendFileSync`,{attributes:IH(`appendFileSync`,e,{"fs.bytes":RH(t)})},()=>{_ae(e,t,n)})}function KH(e,t){return yH(`fs.mkdirSync`,{attributes:IH(`mkdirSync`,e)},()=>ks(e,t))}function qH(e,t){yH(`fs.renameSync`,{attributes:IH(`renameSync`,t,{"fs.source_path":PH(e)})},()=>{Ps(e,t)})}function JH(e,t,n){yH(`fs.cpSync`,{attributes:IH(`cpSync`,t,{"fs.source_path":PH(e)})},()=>{vae(e,t,n)})}function YH(e,t,n){return yH(`fs.openSync`,{attributes:IH(`openSync`,e)},()=>js(e,t,n))}function XH(e){yH(`fs.unlinkSync`,{attributes:IH(`unlinkSync`,e)},()=>{Rs(e)})}function ZH(e,t){yH(`fs.linkSync`,{attributes:IH(`linkSync`,t,{"fs.source_path":PH(e)})},()=>{xae(e,t)})}function QH(e,t,n){yH(`fs.symlinkSync`,{attributes:IH(`symlinkSync`,t,{"fs.source_path":PH(e)})},()=>{Eae(e,t,n)})}function $H(e,t){yH(`fs.rmSync`,{attributes:IH(`rmSync`,e)},()=>{Fs(e,t)})}function eU(e){yH(`fs.rmdirSync`,{attributes:IH(`rmdirSync`,e)},()=>{Is(e)})}const tU={writeFile:(e,t,n)=>zH(e,t,n),rename:(e,t)=>HH(e,t)},nU=[`status`,`--porcelain`,`-uall`];function rU(e){return e.split(`\0`).filter(e=>e.length>0)}function JYe(e){let t=[],n=e.split(`\0`);for(let e=0;e<n.length;e++){let r=n[e]??``;r.length<4||(t.push(r.slice(3)),(r[0]===`R`||r[0]===`C`||r[1]===`R`||r[1]===`C`)&&e++)}return t}function YYe(e){let t=[],n=e.split(`\0`);for(let e=0;e<n.length;e++){let r=n[e]??``;if(r.length<4)continue;let i=r[0]??` `,a=r[1]??` `,o={x:i,y:a,path:r.slice(3)};if(i===`R`||i===`C`||a===`R`||a===`C`){let t=n[e+1];t!==void 0&&t.length>0&&(o.origPath=t),e++}t.push(o)}return t}function XYe(e){let t=e.split(`\0`),n=[],r=0;for(;r<t.length;){let e=t[r]??``;if(e===``)break;if(e[0]===`R`||e[0]===`C`)n.push({status:e,from:t[r+1]??``,to:t[r+2]??``}),r+=3;else{let i=t[r+1]??``;n.push({status:e,from:i,to:i}),r+=2}}return n}function ZYe(e){let t=[];for(let n of e.split(`\0`)){if(!n)continue;let e=n.indexOf(` `);if(e<0)continue;let[r=``,i=``,a=``,o=`0`]=n.slice(0,e).trim().split(/\s+/),s=Number(o);t.push({mode:r,type:i,object:a,size:Number.isFinite(s)?s:0,path:n.slice(e+1)})}return t}function iU(e,t){let[n=``,...r]=t;return e.raw([n,`-z`,...r])}async function aU(e,t){return rU(await iU(e,t))}async function QYe(e,t=nU){return JYe(await iU(e,t))}async function oU(e,t=nU){return YYe(await iU(e,t))}async function sU(e,t){return XYe(await iU(e,t))}async function $Ye(e,t){return ZYe(await iU(e,t))}var cU=class extends Error{projectRoot;constructor(e){super(`Refusing to set up an OpenKnowledge project in your home directory (${e}).\n A project here would run 'git init' in your home directory and write project config\n and skills into your editors' user-global directories (~/.cursor, ~/.codex, ~/.claude).\n Make a folder for this project, then run '${de()} init' inside it.`),this.name=`HomeProjectRootError`,this.projectRoot=e}},lU=class extends Error{projectRoot;constructor(e){super(`Refusing to set up an OpenKnowledge project at the top of a drive (${e}).\n A project here would scan every file on the drive and run 'git init' at its root.\n Make a folder for this project, then run '${de()} init' inside it.`),this.name=`FilesystemRootProjectError`,this.projectRoot=e}};function uU(e){try{return Ns.native(e)}catch{return e}}function dU(e,t=Hs()){return uU(W(e))===uU(t)}function fU(e,t=process.platform){let n=t===`win32`?ys:_s,r=n.resolve(e),i=t===process.platform?uU(r):r;return n.dirname(i)===i||t===`darwin`&&i===`/System/Volumes/Data`}function pU(e,t){if(dU(e,t))throw new cU(W(e));if(fU(e))throw new lU(W(e))}const mU=`config.yml`;var hU=class extends Error{constructor(e,t){super(`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.`),this.name=`SymlinkRefusedError`}};function gU(e,t){let n;try{n=Os(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(n.isSymbolicLink())throw new hU(e,t)}function eXe(e){let[t=`0`,n=`0`]=e.split(`.`);return`${t.length>0?t:`0`}.${n.length>0?n:`0`}`}function tXe(e){return/^[A-Za-z0-9._\-/]+$/.test(e)?e:JSON.stringify(e)}function _U(e,t){let n=`# yaml-language-server: $schema=https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${$e}/config.project.schema.json
878
878
  # OpenKnowledge — project configuration
879
879
  #
880
880
  # This file overrides built-in defaults for this project. Every key below
@@ -1002,8 +1002,8 @@ ${eW.join(`
1002
1002
  `)},peekFreshInPlaceSkillDirsFingerprint(){if(!e.rescanInPlaceSkillDirs)return[...a].sort().join(`
1003
1003
  `);try{return[...e.rescanInPlaceSkillDirs(a)].sort().join(`
1004
1004
  `)}catch{return[...a].sort().join(`
1005
- `)}},async rebuildIgnorePatterns(){let t=e=>(C=e().finally(()=>{C=null}),C),n=async()=>{if(c.reset(),e.rescanInPlaceSkillDirs)try{a=e.rescanInPlaceSkillDirs(a)}catch(e){yG.warn({err:e},`in-place skill re-scan failed — keeping previous allow-list`)}let t=d,n=f,i=p,o=new Map(h),s=Date.now();return vH(`config.ignore.rebuild`,{attributes:{}},async e=>{try{await S();let t=Date.now()-s;if(e.setAttributes({"ok.ignore.pattern_count":m,"ok.ignore.nested_file_count":0,"ok.ignore.bytes":0}),yG.info({durationMs:t},`content-filter async rebuild succeeded`),r)try{r()}catch(e){yG.warn({err:e instanceof Error?e:Error(String(e))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:m,nestedFileCount:0,bytes:0,durationMs:t}}catch(e){d=t,f=n,p=i,h.clear();for(let[e,t]of o)h.set(e,t);let r=e instanceof Error?e.message:String(e);return yG.warn({err:e instanceof Error?e:Error(r)},`content-filter async rebuild failed — rolled back`),{ok:!1,error:{message:r}}}})};return C===null?t(n):(w===null&&(w=C.catch(()=>null).then(()=>(w=null,t(n)))),w)}}}function aK(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const IQe=new class{_tail=Promise.resolve();enqueue(e){let t=this._tail.then(()=>e());return this._tail=t.catch(()=>void 0),t}};function oK(e){return IQe.enqueue(e)}function LQe(e){try{return G(e)&&Ls(e).isDirectory()}catch{return!1}}const RQe=[`HOME`,`USERPROFILE`,`HOMEDRIVE`,`HOMEPATH`,`APPDATA`,`LOCALAPPDATA`,`ProgramData`,`ALLUSERSPROFILE`,`SystemRoot`,`WINDIR`,`windir`,`ComSpec`,`TEMP`,`TMP`,`USERNAME`,`USERDOMAIN`,`PATHEXT`,`SSH_AUTH_SOCK`,`ELECTRON_RUN_AS_NODE`];function zQe(e){let t={LANG:`C`,LC_ALL:`C`,GIT_TERMINAL_PROMPT:`0`,GIT_MERGE_AUTOEDIT:`no`,GIT_OPTIONAL_LOCKS:`0`},n=process.env.PATH??process.env.Path;t.PATH=kr(n,{platform:process.platform,homeDir:Hs(),isDir:LQe,delimiter:ps});for(let e of RQe){let n=process.env[e];n!==void 0&&(t[e]=n)}return e&&(t.OK_GH_TOKEN=e.token,t.OK_GH_TOKEN_HOST=e.host,e.login&&(t.OK_GH_TOKEN_LOGIN=e.login)),t}function BQe(e,t){let n={...e.env};for(let[e,r]of Object.entries(t))r!==void 0&&(n[e]=r);return e.git.env(n)}function sK(e,t){let{credentialConfig:n,gitIndexFile:r,ghToken:i,timeoutMs:a,abortSignal:o}=t,s=zQe(i);return r&&(s.GIT_INDEX_FILE=W(e,r)),{git:yj({baseDir:e,config:[`commit.gpgsign=false`,`core.autocrlf=false`,`credential.interactive=false`,...n],unsafe:{allowUnsafeCredentialHelper:!0},...a===void 0?{}:{timeout:{block:a}},...o===void 0?{}:{abort:o}}).env(s),projectDir:e,credentialConfig:n,env:s}}function VQe(e,t){let n=(e&&e.length>0?e:[`open-knowledge`]).map(aK).join(` `),r=wne(),i=`credential.helper=!${r===`stable`?``:`${bie}=${r} `}${n} auth git-credential`;return t.resetAmbient?[`credential.helper=`,i]:[i]}const cK=`2.31.0`;var lK=class extends Error{code=`GIT_NOT_AVAILABLE`;platform;guidance;probe;constructor(e,t,n){super(ZQe(t),n),this.name=`GitNotAvailableError`,this.platform=e,this.guidance=t,this.probe=n?.probe??null}},uK=class extends Error{code=`GIT_TOO_OLD`;platform;detected;required;resolvedPath;guidance;constructor(e,t,n,r,i,a){super(QQe(t,n,r,i),a),this.name=`GitTooOldError`,this.platform=e,this.detected=t,this.required=n,this.resolvedPath=r,this.guidance=i}};function dK(){let e=pK(`git`);if(e.kind===`ok`)return{ok:!0,version:e.version,resolvedPath:e.resolvedPath,source:`PATH`};let t=null;for(let e of vK(process.platform)){if(!G(e))continue;let n=pK(e);if(n.kind===`ok`)return{ok:!0,version:n.version,resolvedPath:e,source:`fallback`};t=n.reason}throw new lK(process.platform,yK(process.platform),{probe:{path:e.reason,fallback:t}})}function fK(){let e=dK();if(xK(e.version,`2.31.0`)<0)throw new uK(process.platform,e.version,cK,e.resolvedPath,yK(process.platform));return e}function pK(e){let t=vG({encoding:`utf-8`,timeout:5e3,env:{...process.env,LANG:`C`,LC_ALL:`C`}}),n=us(e,[`--version`],t);if(n.error)return`signal`in n&&n.signal===`SIGTERM`?{kind:`fail`,reason:`timeout`}:{kind:`fail`,reason:n.error.code===`ENOENT`?`enoent`:`spawn-failed`};if(n.status!==0)return{kind:`fail`,reason:`nonzero`};let r=mK(typeof n.stdout==`string`?n.stdout:``);return r===null?{kind:`fail`,reason:`unparseable`}:{kind:`ok`,version:r,resolvedPath:e===`git`?_K(`git`)??e:e}}function mK(e){let t=e.match(/git version (\d+)\.(\d+)\.(\d+)/);return t?`${t[1]}.${t[2]}.${t[3]}`:null}const HQe=/^[a-zA-Z0-9_.-]+$/,hK=new Map;function gK(e){if(process.platform!==`win32`)return process.env[e];let t=Object.keys(process.env).find(t=>t.toUpperCase()===e);return t===void 0?void 0:process.env[t]}function UQe(e){if(process.platform!==`win32`)return[e];let t=(gK(`PATHEXT`)??``).split(`;`).map(e=>e.trim().toLowerCase()).filter(e=>e.startsWith(`.`)),n=t.length>0?t:[`.com`,`.exe`,`.bat`,`.cmd`],r=e.toLowerCase();return n.some(e=>r.endsWith(e))?[e]:n.map(t=>`${e}${t}`)}function WQe(e){try{return Ls(e).isFile()?(process.platform!==`win32`&&gae(e,Ts.X_OK),!0):!1}catch{return!1}}function _K(e,t){if(!HQe.test(e))return null;let n=t===void 0?e:`${t}\u0000${e}`,r=hK.get(n);if(r!==void 0)return r;let i=(t??gK(`PATH`)??``).split(ps).map(e=>e.trim().replace(/^"(.*)"$/,`$1`)).filter(e=>e!==``&&hs(e)),a=UQe(e);for(let e of i)for(let t of a){let r=H(e,t);if(WQe(r))return hK.set(n,r),r}return null}function vK(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`,H(Hs(),`scoop`,`apps`,`git`,`current`,`cmd`,`git.exe`)];default:return[`/usr/bin/git`,`/usr/local/bin/git`,H(Hs(),`.local`,`bin`,`git`),`/snap/bin/git`]}}function yK(e){switch(e){case`darwin`:{let e=[];return qQe()&&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 JQe()&&e.push({label:`Install with winget`,command:`winget install --id Git.Git -e --source winget`,requiresAdmin:!0}),YQe()&&e.push({label:`Install with Scoop (no admin)`,command:`scoop install git`,requiresAdmin:!1}),XQe()&&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:GQe()}}}function GQe(){switch(KQe()){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 KQe(e){let t=e;if(t===void 0)try{t=K(`/etc/os-release`,`utf-8`)}catch{return`unknown`}let n=[/^ID=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``),...(/^ID_LIKE=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``)??``).split(/\s+/)].filter(e=>!!e);return n.some(e=>/^(debian|ubuntu|mint|pop)$/i.test(e))?`debian`:n.some(e=>/^(fedora|rhel|centos|alma|rocky)$/i.test(e))?`fedora`:n.some(e=>/^(arch|manjaro|endeavouros)$/i.test(e))?`arch`:n.some(e=>/^opensuse/i.test(e))||n.includes(`suse`)?`opensuse`:n.some(e=>/^alpine$/i.test(e))?`alpine`:`unknown`}function bK(e){return _K(e)!==null}function qQe(){return bK(`brew`)}function JQe(){return bK(`winget`)}function YQe(){return bK(`scoop`)}function XQe(){return bK(`choco`)}function ZQe(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 n of e.options){let e=n.requiresAdmin?` (admin required)`:``;t.push(` • ${n.label}${e}`),t.push(` ${n.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(`
1006
- `)}function QQe(e,t,n,r){let i=[];if(i.push(`OpenKnowledge requires ${r.product} ${t} or newer (detected ${e} at ${n}).`),i.push(``),r.options.length>0){i.push(`Update ${r.product}:`);for(let e of r.options){let t=e.requiresAdmin?` (admin required)`:``;i.push(` • ${e.label}${t}`),i.push(` ${e.command}`)}i.push(``)}return i.push(`Or download from: ${r.url}`),i.push(``),i.push(`After updating, re-run OpenKnowledge.`),i.push("Run `ok diagnose health --check git` to verify your installation."),i.join(`
1005
+ `)}},async rebuildIgnorePatterns(){let t=e=>(C=e().finally(()=>{C=null}),C),n=async()=>{if(c.reset(),e.rescanInPlaceSkillDirs)try{a=e.rescanInPlaceSkillDirs(a)}catch(e){yG.warn({err:e},`in-place skill re-scan failed — keeping previous allow-list`)}let t=d,n=f,i=p,o=new Map(h),s=Date.now();return vH(`config.ignore.rebuild`,{attributes:{}},async e=>{try{await S();let t=Date.now()-s;if(e.setAttributes({"ok.ignore.pattern_count":m,"ok.ignore.nested_file_count":0,"ok.ignore.bytes":0}),yG.info({durationMs:t},`content-filter async rebuild succeeded`),r)try{r()}catch(e){yG.warn({err:e instanceof Error?e:Error(String(e))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:m,nestedFileCount:0,bytes:0,durationMs:t}}catch(e){d=t,f=n,p=i,h.clear();for(let[e,t]of o)h.set(e,t);let r=e instanceof Error?e.message:String(e);return yG.warn({err:e instanceof Error?e:Error(r)},`content-filter async rebuild failed — rolled back`),{ok:!1,error:{message:r}}}})};return C===null?t(n):(w===null&&(w=C.catch(()=>null).then(()=>(w=null,t(n)))),w)}}}function aK(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const IQe=new class{_tail=Promise.resolve();enqueue(e){let t=this._tail.then(()=>e());return this._tail=t.catch(()=>void 0),t}};function oK(e){return IQe.enqueue(e)}function LQe(e){try{return G(e)&&Ls(e).isDirectory()}catch{return!1}}const RQe=[`HOME`,`USERPROFILE`,`HOMEDRIVE`,`HOMEPATH`,`APPDATA`,`LOCALAPPDATA`,`ProgramData`,`ALLUSERSPROFILE`,`SystemRoot`,`WINDIR`,`windir`,`ComSpec`,`TEMP`,`TMP`,`USERNAME`,`USERDOMAIN`,`PATHEXT`,`SSH_AUTH_SOCK`,`ELECTRON_RUN_AS_NODE`];function zQe(e){let t={LANG:`C`,LC_ALL:`C`,GIT_TERMINAL_PROMPT:`0`,GIT_MERGE_AUTOEDIT:`no`,GIT_OPTIONAL_LOCKS:`0`},n=process.env.PATH??process.env.Path;t.PATH=kr(n,{platform:process.platform,homeDir:Hs(),isDir:LQe,delimiter:ps});for(let e of RQe){let n=process.env[e];n!==void 0&&(t[e]=n)}return e&&(t.OK_GH_TOKEN=e.token,t.OK_GH_TOKEN_HOST=e.host,e.login&&(t.OK_GH_TOKEN_LOGIN=e.login)),t}function BQe(e,t){let n={...e.env};for(let[e,r]of Object.entries(t))r!==void 0&&(n[e]=r);return e.git.env(n)}function sK(e,t){let{credentialConfig:n,gitIndexFile:r,ghToken:i,timeoutMs:a,abortSignal:o}=t,s=zQe(i);return r&&(s.GIT_INDEX_FILE=W(e,r)),{git:yj({baseDir:e,config:[`commit.gpgsign=false`,`core.autocrlf=false`,`credential.interactive=false`,...n],unsafe:{allowUnsafeCredentialHelper:!0},...a===void 0?{}:{timeout:{block:a}},...o===void 0?{}:{abort:o}}).env(s),projectDir:e,credentialConfig:n,env:s}}function VQe(e,t){let n=(e&&e.length>0?e:[`open-knowledge`]).map(aK).join(` `),r=wne(),i=`credential.helper=!${r===`stable`?``:`${bie}=${r} `}${n} auth git-credential`;return t.resetAmbient?[`credential.helper=`,i]:[i]}const cK=`2.31.0`;var lK=class extends Error{code=`GIT_NOT_AVAILABLE`;platform;guidance;probe;constructor(e,t,n){super(ZQe(t),n),this.name=`GitNotAvailableError`,this.platform=e,this.guidance=t,this.probe=n?.probe??null}},uK=class extends Error{code=`GIT_TOO_OLD`;platform;detected;required;resolvedPath;guidance;constructor(e,t,n,r,i,a){super(QQe(t,n,r,i),a),this.name=`GitTooOldError`,this.platform=e,this.detected=t,this.required=n,this.resolvedPath=r,this.guidance=i}};function dK(){let e=pK(`git`);if(e.kind===`ok`)return{ok:!0,version:e.version,resolvedPath:e.resolvedPath,source:`PATH`};let t=null;for(let e of vK(process.platform)){if(!G(e))continue;let n=pK(e);if(n.kind===`ok`)return{ok:!0,version:n.version,resolvedPath:e,source:`fallback`};t=n.reason}throw new lK(process.platform,yK(process.platform),{probe:{path:e.reason,fallback:t}})}function fK(){let e=dK();if(xK(e.version,`2.31.0`)<0)throw new uK(process.platform,e.version,cK,e.resolvedPath,yK(process.platform));return e}function pK(e){let t=vG({encoding:`utf-8`,timeout:5e3,env:{...process.env,LANG:`C`,LC_ALL:`C`}}),n=us(e,[`--version`],t);if(n.error)return`signal`in n&&n.signal===`SIGTERM`?{kind:`fail`,reason:`timeout`}:{kind:`fail`,reason:n.error.code===`ENOENT`?`enoent`:`spawn-failed`};if(n.status!==0)return{kind:`fail`,reason:`nonzero`};let r=mK(typeof n.stdout==`string`?n.stdout:``);return r===null?{kind:`fail`,reason:`unparseable`}:{kind:`ok`,version:r,resolvedPath:e===`git`?_K(`git`)??e:e}}function mK(e){let t=e.match(/git version (\d+)\.(\d+)\.(\d+)/);return t?`${t[1]}.${t[2]}.${t[3]}`:null}const HQe=/^[a-zA-Z0-9_.-]+$/,hK=new Map;function gK(e){if(process.platform!==`win32`)return process.env[e];let t=Object.keys(process.env).find(t=>t.toUpperCase()===e);return t===void 0?void 0:process.env[t]}function UQe(e){if(process.platform!==`win32`)return[e];let t=(gK(`PATHEXT`)??``).split(`;`).map(e=>e.trim().toLowerCase()).filter(e=>e.startsWith(`.`)),n=t.length>0?t:[`.com`,`.exe`,`.bat`,`.cmd`],r=e.toLowerCase();return n.some(e=>r.endsWith(e))?[e]:n.map(t=>`${e}${t}`)}function WQe(e){try{return Ls(e).isFile()?(process.platform!==`win32`&&gae(e,Ts.X_OK),!0):!1}catch{return!1}}function _K(e,t){if(!HQe.test(e))return null;let n=t===void 0?e:`${t}\u0000${e}`,r=hK.get(n);if(r!==void 0)return r;let i=(t??gK(`PATH`)??``).split(ps).map(e=>e.trim().replace(/^"(.*)"$/,`$1`)).filter(e=>e!==``&&hs(e)),a=UQe(e);for(let e of i)for(let t of a){let r=H(e,t);if(WQe(r))return hK.set(n,r),r}return null}function vK(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`,H(Hs(),`scoop`,`apps`,`git`,`current`,`cmd`,`git.exe`)];default:return[`/usr/bin/git`,`/usr/local/bin/git`,H(Hs(),`.local`,`bin`,`git`),`/snap/bin/git`]}}function yK(e){switch(e){case`darwin`:{let e=[];return qQe()&&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 JQe()&&e.push({label:`Install with winget`,command:`winget install --id Git.Git -e --source winget`,requiresAdmin:!0}),YQe()&&e.push({label:`Install with Scoop (no admin)`,command:`scoop install git`,requiresAdmin:!1}),XQe()&&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:GQe()}}}function GQe(){switch(KQe()){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 KQe(e){let t=e;if(t===void 0)try{t=K(`/etc/os-release`,`utf-8`)}catch{return`unknown`}let n=[/^ID=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``),...(/^ID_LIKE=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``)??``).split(/\s+/)].filter(e=>!!e);return n.some(e=>/^(debian|ubuntu|mint|pop)$/i.test(e))?`debian`:n.some(e=>/^(fedora|rhel|centos|alma|rocky)$/i.test(e))?`fedora`:n.some(e=>/^(arch|manjaro|endeavouros)$/i.test(e))?`arch`:n.some(e=>/^opensuse/i.test(e))||n.includes(`suse`)?`opensuse`:n.some(e=>/^alpine$/i.test(e))?`alpine`:`unknown`}function bK(e){return _K(e)!==null}function qQe(){return bK(`brew`)}function JQe(){return bK(`winget`)}function YQe(){return bK(`scoop`)}function XQe(){return bK(`choco`)}function ZQe(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 n of e.options){let e=n.requiresAdmin?` (admin required)`:``;t.push(` • ${n.label}${e}`),t.push(` ${n.command}`)}t.push(``)}return t.push(`Or download from: ${e.url}`),t.push(``),t.push(`After installing, re-run OpenKnowledge.`),t.push(`Run \`${de()} diagnose health --check git\` to verify your installation.`),t.join(`
1006
+ `)}function QQe(e,t,n,r){let i=[];if(i.push(`OpenKnowledge requires ${r.product} ${t} or newer (detected ${e} at ${n}).`),i.push(``),r.options.length>0){i.push(`Update ${r.product}:`);for(let e of r.options){let t=e.requiresAdmin?` (admin required)`:``;i.push(` • ${e.label}${t}`),i.push(` ${e.command}`)}i.push(``)}return i.push(`Or download from: ${r.url}`),i.push(``),i.push(`After updating, re-run OpenKnowledge.`),i.push(`Run \`${de()} diagnose health --check git\` to verify your installation.`),i.join(`
1007
1007
  `)}function xK(e,t){let n=e.split(`.`).map(e=>Number.parseInt(e,10)||0),r=t.split(`.`).map(e=>Number.parseInt(e,10)||0);for(let e=0;e<3;e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t-i}return 0}const $Qe=`2.38.0`,SK=`2.38`,CK=`120000`,wK=4096,e$e=/[\u200C-\u200F\u202A-\u202E\u206A-\u206F\uFEFF]/gu,t$e=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu,n$e=[`GIT_DIR`,`GIT_WORK_TREE`,`GIT_COMMON_DIR`,`GIT_INDEX_FILE`,`GIT_OBJECT_DIRECTORY`,`GIT_ALTERNATE_OBJECT_DIRECTORIES`,`GIT_NAMESPACE`];function TK(e){return e.replace(e$e,``).normalize(`NFC`).toUpperCase().toLowerCase().normalize(`NFC`)}function EK(e){let t=TK(e);for(let e=0;e<4;e++){let e=TK(t);if(e===t)break;t=e}return t.replace(/[. ]+$/u,(e,t)=>t===0?e:``)}function DK(e){return e.split(`/`).map(EK).join(`/`)}const OK=new Set([`.ok`,`.open-knowledge`,`.openknowledge`,...Object.values(vi).map(({userHomeDirName:e})=>e)].map(EK)),r$e=new Set([...We,...xt,...Fie].map(EK));function i$e(e){let t=new Set;for(let n of e){let e=n.replace(/^\.+/u,``);if(!/^[a-z0-9-]+$/u.test(e))throw Error(`cannot derive 8.3 short names for config dir "${n}"`);e.length<=2?t.add(`${e}[0-9a-f]{4}`):(t.add(e.slice(0,6)),t.add(`${e.slice(0,2)}[0-9a-f]{4}`))}return RegExp(`^(?:${[...t].join(`|`)})~\\d+$`,`u`)}const a$e=i$e(OK);function o$e(e){return/^[^.~]{1,7}~\d{1,7}(?:\.[^.]{1,3})?$/u.test(e)}function s$e(e){return e===`.git`||/^git~\d+$/u.test(e)}function kK(e){return OK.has(e)||a$e.test(e)}function AK(e){return e.findIndex((t,n)=>s$e(t)||kK(t)&&(n===e.length-1||r$e.has(e[n+1]??``)))}function jK(e){return AK(e)>=0}function MK(e,t){let n=DK(e).split(`/`),r=DK(t).split(`/`);if(n.join(`/`)===r.join(`/`))return!1;let i=AK(r);if(i<0)return!1;let a=r.length-1;return!(i===a&&kK(r[a]??``)&&n[n.length-1]===r[a])}function NK(e){return e===``||e.includes(`\0`)||e.includes(`\\`)||e.includes(`:`)||Buffer.byteLength(e,`utf-8`)>wK}async function PK(e,t,n,r){let i=new Set,a=e=>({reason:e,crossed:i,complete:!0}),o=()=>({reason:`unverifiable-target`,crossed:i,complete:!1});if(NK(t))return a(`unverifiable-target`);if(t.startsWith(`/`))return a(`outside-repository`);let s=[...e.split(`/`).slice(0,-1),...t.split(`/`)],c=[],l=[],u=0,d=0;for(;s.length>0;){let e=s.shift()??``;if(u+=1,--r.steps,u>256||r.steps<0)return o();if(e===``||e===`.`)continue;if(e===`..`){if(c.length===0)return a(`outside-repository`);c.pop(),l.pop();continue}c.push(e);let t=EK(e);if(l.push(t),o$e(t))return jK(l)?{reason:`private-state`,crossed:i,complete:!1}:o();let f=l.join(`/`);i.add(f);let p=await n(f,c.join(`/`));if(p.kind===`unverifiable`)return o();if(p.kind===`link`){if(d+=1,d>40||NK(p.target))return o();if(p.target.startsWith(`/`))return a(`outside-repository`);c.pop(),l.pop(),s.unshift(...p.target.split(`/`))}}if(l.length===0)return a(`repository-root`);if(jK(l))return a(`private-state`);let f=l.join(`/`);return KG(f)||GG(f)?a(`secret-file`):a(null)}function c$e(e,t){let n=t.split(`/`);for(let t=1;t<=n.length;t++){let r=n.slice(0,t).join(`/`),i=DK(r),a=e.get(i);a===void 0?e.set(i,new Set([r])):a.add(r)}}async function l$e(e,t){let n=await e.raw([`ls-tree`,`-r`,`-z`,`-l`,`--full-tree`,t]),r=[],i=new Map;for(let e of n.split(`\0`)){if(e===``)continue;let t=e.indexOf(` `),[n,,a,o]=e.slice(0,Math.max(t,0)).trim().split(/\s+/u);if(t<0||n===void 0||a===void 0||o===void 0)throw Error(`unparseable git ls-tree record while inspecting incoming symlinks`);let s=e.slice(t+1);c$e(i,s),n===CK&&r.push({path:s,folded:DK(s),blob:a,size:Number(o)})}return{links:r,spellings:i}}async function FK(e,t,n){let r=(await e.raw([`diff-tree`,`-r`,`-z`,`--raw`,`--no-renames`,`--no-abbrev`,t,n])).split(`\0`),i=new Map;for(let e=0;e+1<r.length;e+=2){let t=r[e]??``,n=r[e+1]??``,[a,o]=t.replace(/^\n?:/u,``).split(` `);if(!t.includes(`:`)||o===void 0||n===``)throw Error(`unparseable git diff-tree record while inspecting incoming symlinks`);(a===CK||o===CK)&&i.set(DK(n),n)}return i}function u$e(e){let t={...e??process.env};for(let e of n$e)delete t[e];return t.GIT_TERMINAL_PROMPT=`0`,t.GIT_NO_LAZY_FETCH=`1`,t}var d$e=class extends Error{failure;detail;stderr;constructor(e,t,n){super(`could not read incoming symlink targets from git (${e})`),this.name=`IncomingBlobReadError`,this.failure=e,this.detail=t,this.stderr=n}};function f$e(e,t,n){let r=[...new Set(t.filter(e=>Number.isFinite(e.size)&&e.size<=wK).map(e=>e.blob))];return r.length===0?Promise.resolve(new Map):new Promise((t,i)=>{let a=!1,o=[],s=0,c=e=>{if(!a){if(a=!0,clearTimeout(u),e instanceof Map){t(e);return}i(new d$e(e.failure,e.detail,Buffer.concat(o).toString(`utf-8`)))}},l=ls(`git`,[`cat-file`,`--batch`],{cwd:e,env:u$e(n),stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0}),u=setTimeout(()=>{l.kill(`SIGKILL`),c({failure:`timeout`})},6e4),d=[];l.stdout.on(`data`,e=>d.push(e)),l.stderr.on(`data`,e=>{s>=4096||(o.push(e),s+=e.length)}),l.stdin.on(`error`,e=>c({failure:`stdin`,detail:rG(e)})),l.on(`error`,e=>c({failure:`spawn`,detail:rG(e)})),l.on(`close`,(e,t)=>{if(e!==0){c({failure:`exit`,detail:t??e});return}let n=Buffer.concat(d),i=new Map,a=0;for(let e of r){let t=n.indexOf(10,a),[r,o,s]=n.subarray(a,t).toString(`utf-8`).split(` `),l=Number(s);if(t<0||r!==e||o!==`blob`||!Number.isFinite(l)){c({failure:`output`});return}i.set(e,n.subarray(t+1,t+1+l).toString(`utf-8`)),a=t+1+l+1}c(i)}),l.stdin.end(`${r.join(`
1008
1008
  `)}\n`)})}async function p$e(e){return(await e.raw([`rev-parse`,`--show-object-format`])).trim()===`sha256`?`6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321`:`4b825dc642cb6eb9a060e54bf8d69288fbee4904`}async function m$e(e,t,n){return(await e.raw([`merge-base`,t,n])).trim()===t}async function h$e(e){let t=mK(await e.raw([`version`]));return t===null||xK(t,`2.38.0`)>=0}async function g$e(e,t,n){let[r=``,...i]=(await e.raw([`merge-tree`,`--write-tree`,`-z`,`--no-messages`,t,n])).split(`\0`);if(!/^[0-9a-f]{40,64}$/u.test(r))throw Error(`unexpected git merge-tree output while inspecting incoming symlinks`);let a=[],o=new Map;for(let t of i){if(t===``)continue;let n=t.indexOf(` `),[r,i,s]=t.slice(0,Math.max(n,0)).split(` `),c=t.slice(n+1);if(n<0||r===void 0||i===void 0||s===void 0||!/^[123]$/u.test(s)||c===``)throw Error(`unparseable git merge-tree record while inspecting incoming symlinks`);let l=o.get(c)??new Map;if(l.set(s,{mode:r,blob:i}),o.set(c,l),r!==CK||s!==`3`)continue;let u=Number((await e.raw([`cat-file`,`-s`,i])).trim());a.push({path:c,stage:s,blob:i,size:u})}let s=[];for(let[e,t]of o)[...t.values()].some(({mode:e})=>e===CK)&&s.push({path:e,folded:DK(e)});return{tree:r,candidates:a,conflicted:s}}let IK;async function _$e(e,t,n,r,i,a){let o=JSON.stringify([t,n,r,i]);if(IK?.key===o)return IK.inspection;let s=n??await p$e(e),c=r,l=[],u=[];if(i===`merge`&&n!==null&&!await m$e(e,n,r)){if(!await h$e(e)){let t=(await e.raw([`merge-base`,`--all`,n,r])).split(`
1009
1009
  `).map(e=>e.trim()).filter(e=>e!==``),i=new Map;for(let a of t.length>0?t:[n])for(let[t,n]of await FK(e,a,r))i.set(t,n);return i.size===0?null:{links:[],spellings:new Map,changed:new Set(i.keys()),changedPaths:[...i.values()],candidates:[],conflicted:[],refused:[...i.values()].map(e=>({path:e,reason:`requires-newer-git`})),targets:new Map}}let t=await g$e(e,n,r);c=t.tree,l=t.candidates,u=t.conflicted}let d=await FK(e,s,c);for(let e of u)d.set(e.folded,e.path);let f=null;if(d.size>0||l.length>0){let n=await l$e(e,c);f={links:n.links,spellings:n.spellings,changed:new Set(d.keys()),changedPaths:[...d.values()],candidates:l,conflicted:u,refused:[],targets:await f$e(t,[...n.links,...l],a)}}return IK={key:o,inspection:f},f}async function LK(e,t,n,r,i=`head`){let a=(await e.raw([`rev-parse`,`--show-toplevel`])).trim();if(a===``)throw Error(`could not resolve the repository root`);let o=i===`empty-tree`?``:(await e.raw([`rev-parse`,`--verify`,`--quiet`,`HEAD^{commit}`])).trim(),s=await _$e(e,a,o===``?null:o,t,n,r);if(s===null)return[];let{spellings:c,changed:l,candidates:u,targets:d}=s;if(s.refused.length>0)return s.refused;let{links:f}=s,p=new Set(s.conflicted.map(({folded:e})=>e)),m=[...[...p].map(e=>e.replace(/~[^/]*$/u,``)),...l],h=e=>p.has(e)||m.some(t=>e.startsWith(`${t}~`)),g=new Map;for(let e of f){let t=g.get(e.folded);t===void 0?g.set(e.folded,[e]):t.push(e)}let _=e=>d.get(e)??`\0`,v=new Map,y=async(e,t)=>{if(h(e))return{kind:`unverifiable`};let n=c.get(e),r=g.get(e);if(r!==void 0){if(r.length>1||n!==void 0&&n.size>1)return{kind:`unverifiable`};let[e]=r;return e===void 0?{kind:`unverifiable`}:{kind:`link`,target:_(e.blob)}}if(n!==void 0)return{kind:`plain`};let i=H(a,t);try{return(await Js(i)).isSymbolicLink()?{kind:`link`,target:await Nae(i)}:{kind:`plain`}}catch(e){let t=rG(e);return t===`ENOENT`||t===`ENOTDIR`?{kind:`plain`}:{kind:`unverifiable`}}},b=(e,t)=>{let n=`${e}\0${t}`,r=v.get(n);return r===void 0&&(r=y(e,t),v.set(n,r)),r},x={steps:2e4},S=[],C=new Set,w=(e,t)=>{C.has(e)||(C.add(e),S.push({path:e,reason:t}))};for(let e of u){let{reason:t}=await PK(e.path,_(e.blob),b,x);t!==null&&w(e.path,t)}for(let e of f){let t=l.has(e.folded);if(t&&jK(e.folded.split(`/`))){w(e.path,`inside-private-state`);continue}let{reason:n,crossed:r,complete:i}=await PK(e.path,_(e.blob),b,x);n!==null&&(t||!i||[...r].some(e=>l.has(e)))&&w(e.path,n)}if(x.steps<0)for(let e of[...s.changedPaths,...u.map(({path:e})=>e)])w(e,`unverifiable-target`);return S}async function RK(e,t){let n=(await e.raw([`rev-parse`,`--verify`,`--quiet`,`${t}^{commit}`])).trim();if(!/^[0-9a-f]{40,64}$/u.test(n))throw Error(`cannot resolve the incoming commit`);return n}function v$e(e){switch(e){case`outside-repository`:return`points outside the repository`;case`repository-root`:return`points at the repository root`;case`private-state`:return`points into private .git or OpenKnowledge state`;case`secret-file`:return`points at a file that may hold secrets, such as .env or a key`;case`inside-private-state`:return`is placed inside private .git or OpenKnowledge state`;case`requires-newer-git`:return`needs Git ${SK} or newer to check during a merge`;case`unverifiable-target`:return`has a target that cannot be checked`;default:return e}}function zK(e){return JSON.stringify(e).slice(1,-1).replace(t$e,e=>Array.from({length:e.length},(t,n)=>`\\u${e.charCodeAt(n).toString(16).padStart(4,`0`)}`).join(``))}var BK=class extends Error{unsafe;constructor(e){super(`refusing to pull: incoming symlinks are unsafe to check out`),this.name=`UnsafeIncomingSymlinkError`,this.unsafe=e}displayPaths(){return this.unsafe.slice(0,50).map(({path:e})=>zK(e))}describeLinks(){let e=this.unsafe.slice(0,5).map(({path:e,reason:t})=>`"${zK(e)}" (${v$e(t)})`),t=this.unsafe.length>5?`, and ${this.unsafe.length-5} more`:``;return`${e.join(`, `)}${t}`}};async function VK(e,t,n,r){let i=await LK(e,await RK(e,t),n,r);if(i.length>0)throw new BK(i)}async function HK(e,t,n){let r=await LK(e,await RK(e,t),`checkout`,n,`empty-tree`);if(r.length>0)throw new BK(r)}async function y$e(e,t){let n=sK(e,{credentialConfig:[]});await HK(n.git,t,n.env)}var UK=class extends Error{ref;constructor(e){super(`the incoming branch moved after its incoming symlinks were inspected; pull again`),this.name=`IncomingRefMovedError`,this.ref=e}},WK=class extends Error{shadowedName;constructor(e){super(`another ref with the incoming branch name, such as a tag, shadows it, so sync will not merge it until that ref is deleted here and on the remote`),this.name=`IncomingRefShadowedError`,this.shadowedName=e}};async function GK(e,t){return(await e.raw([`rev-parse`,`--verify`,`--quiet`,`${t}^{commit}`])).trim()}async function KK(e,t){if(await GK(e,t.trackingRef)!==t.commit)throw new UK(t.trackingRef);if(await GK(e,t.name)!==t.commit)throw new WK(t.name)}var qK=class extends Error{constructor(e){super(`symlink-escape: ${e}`),this.name=`SymlinkEscapeError`}},JK=class extends qK{constructor(){super(`path resolves into private repository state`),this.name=`PrivateStateSymlinkError`}},b$e=class extends Error{constructor(e){super(e),this.name=`ContentRootUnavailableError`}};function YK(e,t){return U(e,t).split(vs).join(`/`)}function XK(e,t,n){return MK(YK(n,e),YK(n,t))}function ZK(e,t,n){let r=n;try{r=Ns(n)}catch{return!0}return!gG(t,r)||MK(YK(gG(e,n)?n:r,e),YK(r,t))}function QK(e,t){let n;try{n=Ns(t)}catch(e){throw rG(e)===`ENOENT`?new b$e(`content directory does not exist`):e}let r=e;for(;;)try{let i=Ns(r);if(!gG(i,n))throw new qK(`path resolves outside content directory`);let a=gG(e,t)?t:n;if(XK(H(n,U(a,e)),H(i,U(r,e)),n))throw new JK;pG(e,t);return}catch(e){let i=rG(e);if(i===`ELOOP`)throw new qK(`symlink cycle in path`);if(i!==`ENOENT`)throw e;let a=V(r);if(a===r)throw e;let o=a===t||a.startsWith(`${t}${vs}`),s=a===n||a.startsWith(`${n}${vs}`);if(!o&&!s)throw e;r=a}}function $K(e){try{return Os(e).isSymbolicLink()?{kind:`symlink`}:{kind:`not-symlink`}}catch(e){let t=rG(e);return t===`ENOENT`?{kind:`not-symlink`}:{kind:`unverifiable`,code:t}}}var eq=class extends Error{constructor(e){super(e),this.name=`PathContainmentError`}};function tq(e){return e instanceof eq||e instanceof qK}function nq(e,t,n){e.warn({path:PH(t),code:rG(n),err:n},`[fs-safety] reserved-path canonicalization fell back to the lexical path; a symlink-based reserved-subtree check may be stale for this request`)}function rq(e,t,n,r=Ns,i={join:H,relative:U,dirname:V,sep:vs}){let a=e=>e.split(i.sep).join(`/`),o;try{o=r(t)}catch(e){rG(e)!==`ENOENT`&&nq(n,t,e),o=t}let s=e;for(;;)try{let t=r(s),n=i.join(t,i.relative(s,e));return a(i.relative(o,n))}catch(t){if(rG(t)!==`ENOENT`)return nq(n,s,t),a(i.relative(o,e));let r=i.dirname(s);if(r===s)return a(i.relative(o,e));s=r}}function iq(e){let t=rG(e);return t===`EEXIST`||t===`ERR_FS_CP_EEXIST`||t===`ERR_FS_CP_DIR_TO_NON_DIR`||t===`ERR_FS_CP_NON_DIR_TO_DIR`}const aq=new Set;var oq=class extends Error{leasePath;kind;constructor(e,t){super(`Content ownership lease could not be verified at ${e}`,{cause:t}),this.name=`ServerAuthorityLeaseVerificationError`,this.leasePath=e;let n=t,r=typeof n?.errcode==`number`?n.errcode&255:void 0;if(this.kind=t instanceof SyntaxError||r===1||r===11||r===26?`invalid-data`:n?.code===`ENOENT`?`missing`:`unavailable`,r===14)try{Os(e)}catch(e){e.code===`ENOENT`&&(this.kind=`missing`)}}};function sq(e,t){return W(V(e),Ci,`${pr().parse(t)}.sqlite`)}function cq(e){try{XH(e)}catch(t){if(t.code===`ENOENT`)return;q(`server-authority`).warn({err:t,leasePath:e},`Retired ownership lease file cleanup failed`)}}function x$e(e,t){let n=sq(e,t);KH(V(n),{recursive:!0,mode:448}),WH(n,``,{flag:`wx`,mode:384});let r;try{r=new dc(n,{timeout:0}),r.exec(`PRAGMA journal_mode=DELETE`),r.exec(`CREATE TABLE lease (owner_token TEXT PRIMARY KEY) STRICT`),r.prepare(`INSERT INTO lease VALUES (?)`).run(t),r.exec(`BEGIN EXCLUSIVE`)}catch(e){try{r?.close()}catch(e){q(`server-authority`).warn({err:e,leasePath:n},`Failed ownership lease close failed`)}throw cq(n),e}aq.add(n);let i=!1;return()=>{i||(r.close(),aq.delete(n),i=!0,cq(n))}}function S$e(e,t){return lq(sq(e,t),t,!1)}function lq(e,t,n){if(aq.has(e))return!1;let r;try{r=new dc(e,{readOnly:!0,timeout:0});try{r.exec(`BEGIN EXCLUSIVE`)}catch(e){let t=e.errcode;if(typeof t==`number`&&((t&255)==5||(t&255)==6))return!1;throw e}if(r.prepare(`PRAGMA journal_mode`).get()?.journal_mode!==`delete`)throw SyntaxError(`Content ownership lease must use SQLite DELETE-mode file locking`);if(n&&r.prepare(`SELECT count(*) AS count FROM sqlite_schema`).get()?.count===0)return!0;let i=r.prepare(`SELECT owner_token FROM lease`).get()?.owner_token;if(n&&i===void 0)return!0;if(i!==t)throw SyntaxError(`Content ownership lease token does not match its registry row`);return!0}catch(t){let n=t.code;throw t instanceof SyntaxError||n===`ERR_SQLITE_ERROR`||[`EACCES`,`EPERM`,`ENOENT`,`EIO`,`EBUSY`].includes(n??``)?new oq(e,t):t}finally{r?.close()}}function C$e(e,t){cq(sq(e,t))}function w$e(e,t,n){if(!t.isTransaction)throw Error(`Ownership lease collection requires a held registry transaction`);let r=W(V(e),Ci);try{for(let e of Ms(r,{withFileTypes:!0})){if(!e.isFile()||!e.name.endsWith(`.sqlite`))continue;let t=pr().safeParse(e.name.slice(0,-7));if(!t.success||n.has(t.data))continue;let i=W(r,e.name);try{lq(i,t.data,!0)&&cq(i)}catch(e){q(`server-authority`).warn({err:e,leasePath:i},`Unreferenced ownership lease could not be verified`)}}}catch(e){if(e.code===`ENOENT`)return;q(`server-authority`).warn({err:e,leasePath:r},`Ownership lease directory cleanup unavailable`)}}function uq(e){return`Run ${de()} stop all and confirm every OpenKnowledge server under this OS account has exited. Then back up and remove ${e??`the named ownership registry`} together with its -journal file if present, keeping them together as one backup. Never remove either while a server is running.`}function T$e(e,t,n){let r=`Existing content ownership for ${e.scope.path} in ${e.projectDir} could not be verified. `;if(n.kind===`protocol-mismatch`)return`${r}The ownership protocol ${n.protocol} is not supported by this runtime. Update every OpenKnowledge runtime to a compatible version; no ownership record was cleared.`;let i=n.error,a=`Lease ${i.leasePath}: ${i.cause instanceof Error?i.cause.message:String(i.cause)}. `,o=uq(t);return r+a+(i.kind===`unavailable`?`Lease access may be temporarily unavailable. First check access to the named lease and retry. If the failure persists, use manual recovery: ${o}`:o)}var dq=class extends Error{existing;verifiedLease;leasePath;constructor(e,t,n={kind:`held`}){super(n.kind===`held`?`OpenKnowledge content ownership is already held by ${e.scope.kind===`file`?`a single-file preview of ${e.scope.path}`:`the project server for ${e.projectDir}`} (pid ${e.pid}, content ${e.scope.path}). Close that session before opening an overlapping content scope.`:T$e(e,t,n),n.kind===`failed`?{cause:n.error}:void 0),this.name=`ServerAuthorityCollisionError`,this.existing=e,this.verifiedLease=n.kind===`held`,this.leasePath=n.kind===`failed`?n.error.leasePath:void 0}},fq=class extends Error{kind;registryPath;constructor(e,t,n){let r={"unsupported-version":`This runtime does not support the content ownership registry version`,"retired-version":`This runtime no longer reads the retired pre-release content ownership registry layout`,contention:`The content ownership registry is being updated by another runtime`,unavailable:`The content ownership registry cannot be accessed`,"invalid-data":`The content ownership registry contains invalid data`,unknown:`The content ownership registry could not be read or updated`},i={"unsupported-version":`Update every OpenKnowledge runtime to a compatible version.`,"retired-version":uq(t),contention:`Another runtime is updating the registry; try starting again.`,unavailable:`Check the named location and its permissions; the default registry requires a registered, writable OS-account home.`,"invalid-data":uq(t),unknown:`Check the underlying error before retrying. The registry has not been reset and ownership protection cannot be disabled.`};super(`${r[e]}. ${t===void 0?`The OS-account home could not be resolved`:`Registry: ${t}`}. ${n instanceof Error?n.message:String(n)}. ${i[e]}`,{cause:n}),this.name=`ServerAuthorityRegistryError`,this.kind=e,this.registryPath=t}};function E$e(e){let t=typeof e==`object`&&e?e:void 0,n=typeof t?.errcode==`number`?t.errcode&255:void 0;return n===5||n===6?`contention`:n===11||n===26||e instanceof Iie||e instanceof SyntaxError?`invalid-data`:typeof t?.code==`string`&&[`EACCES`,`EPERM`,`ENOENT`,`ENOTDIR`,`EROFS`,`ERR_SYSTEM_ERROR`].includes(t.code)?`unavailable`:`unknown`}const pq=R().min(1).refine(e=>!e.includes(`\0`)&&hs(e)&&gs(e)===e),D$e=ue(`kind`,[B({kind:P(`file`),path:pq}),B({kind:P(`tree`),path:pq,excluded:z(pq)}).refine(({path:e,excluded:t})=>t.every(t=>U(e,t)!==``&&gq(e,t)))]),O$e=B({server_instance_id:R().min(1),owner_token:pr(),pid:Fn().int().positive(),lease_protocol:R().min(1),project_dir:pq,scope_json:R(),started_at:j()}),mq=new Set;let hq=!1;function gq(e,t){let n=U(e,t);return n===``||n!==`..`&&!n.startsWith(`..${vs}`)&&!hs(n)}function _q(e,t){return hs(t)&&gq(e.path,t)&&(e.kind===`file`?U(e.path,t)===``:!e.excluded.some(e=>gq(e,t)))}function k$e(e,t){if(e.kind===`file`)return _q(t,e.path);if(t.kind===`file`)return _q(e,t.path);let n=gq(e.path,t.path)?t.path:e.path;return _q(e,n)&&_q(t,n)}function vq(e){let t=D$e.parse(e);return t.kind===`file`?Object.freeze(t):Object.freeze({...t,excluded:Object.freeze(t.excluded)})}function yq(e,t,n){return yH(`fs.serverAuthority`,{attributes:{"fs.operation":`serverAuthority`,"fs.path":PH(t),"fs.path.role":`ok-internal`,"fs.sqlite.operation":e}},n)}function A$e(e){let t=vq(e.scope),n=pq.parse(e.projectDir),r=R().min(1).parse(e.serverInstanceId),i;try{i=kae().homedir}catch(t){if(e.registryPath===void 0)throw new fq(`unavailable`,void 0,t);i=V(e.registryPath)}let a=e.registryPath??W(i,`.ok`,`local`,`server-authority.sqlite`);pq.parse(a);let o=oc(),s,c=yq(`acquire`,a,()=>{let e,i=[];try{KH(V(a),{recursive:!0,mode:448});try{WH(a,``,{flag:`wx`,mode:384})}catch(e){if(e.code!==`EEXIST`)throw e}LH(a,384),e=new dc(a,{timeout:5e3}),e.exec(`BEGIN IMMEDIATE`);let c=e.prepare(`PRAGMA user_version`).get()?.user_version,l=c===1&&e.prepare(`PRAGMA table_info(server_authority)`).all().map(e=>e.name).join(`,`)===`server_instance_id,owner_token,pid,hostname,machine_id,project_dir,scope_json,started_at`&&e.prepare(`SELECT count(*) AS count FROM server_authority`).get()?.count===0;if(c!==0&&c!==2&&!l)throw new fq(c===1?`retired-version`:`unsupported-version`,a,Error(`Registry layout version ${c} is not supported by this runtime`));if(e.prepare(`PRAGMA journal_mode`).get()?.journal_mode!==`delete`)throw new fq(`unsupported-version`,a,Error(`Content ownership requires SQLite DELETE-mode file locking`));l&&e.exec(`DROP TABLE server_authority`),e.exec(`
@@ -1108,7 +1108,7 @@ ${eW.join(`
1108
1108
  `),u=[],d=new Set,f=null,p=(e,t,n,r)=>{let i=`${r??`md`}\0${e}`;d.has(i)||(d.add(i),u.push({href:e,resolvedTo:t,reason:n,...r?{sourceForm:r}:{}}))},m=e=>{let n=e.trim();if(n.startsWith(`#`))return;let c=Bi(n,t);if(!c){p(n,null,`unresolvable`);return}if(c.kind===`doc`){if(o.resolve(c.docName)!==void 0)return;let e=Ya(n,t,{literal:!1});if(e!==null&&!kW(n,t)&&r?.(e)===!0)return;if(e!==null&&a?.(e)===!0){p(n,e,`excluded`);return}i?.(c.docName)!==!0&&p(n,c.docName,`no-such-doc`);return}if(c.kind===`asset`){if(!r)return;let e=Ya(c.url,t,{literal:c.literal});if(e===null){p(n,null,`unresolvable`);return}r(e)||p(n,e,s(e));return}},h=(e,n)=>{if(n===``)return;if(Ra(n)){p(n,null,`unresolvable`,`jsx`);return}let a=dJ(e,n,t);if(a===null){p(n,null,`unresolvable`,`jsx`);return}if(ei(a)){if(!r)return;r(a)||p(n,a,s(a),`jsx`);return}o.resolve(a)===void 0&&i?.(a)!==!0&&p(n,a,`no-such-doc`,`jsx`)},g,_=(e,t)=>{g??=EJ(o);let n=cte(e,t,g);n?.kind===`doc`&&da(n.docName,g)===void 0&&i?.(n.docName)!==!0&&p(`[[${e}${t?`#${t}`:``}]]`,n.docName,`no-such-doc`)};for(let e of l){if(f){Q2(e,f)&&(f=null);continue}let t=Z2(e);if(t){f=t;continue}let n=$2(e);for(;n<e.length;){if(e[n]===`\\`&&n+1<e.length){n+=2;continue}if(e[n]==="`"){let t=e4(e,n);if(t){n=t.nextIndex;continue}}if(e[n]===`<`){let t=lJ(e,n);if(t){for(let e of t.attrs.matchAll(uJ(t.spec.attrName)))h(t.spec,e[3]??``);n+=t.matchLength;continue}}if(e[n]===`[`&&e[n+1]===`[`){let t=t4(e,n);if(t){_(t.target,t.anchor),n=t.nextIndex;continue}}if(e[n]===`[`&&e[n-1]!==`!`){let t=n4(e,n);if(t){m(t.href),n=t.nextIndex;continue}}n++}}return u}function cat(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,sourceForm:t.sourceForm,line:t.line,column:t.column,...t.rawWikiTarget===!0?{rawWikiTarget:!0}:{}}))])),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))])),skillRefs:Object.fromEntries([...e.skillRefs.entries()].map(([e,t])=>[e,[...t].sort()])),sourceLinks:Object.fromEntries([...e.sourceLinks.entries()].map(([e,t])=>[e,t.map(e=>({...e}))]))}}function lat(e){let t=new Map;for(let[n,r]of e)for(let[e,i]of r){let r=t.get(e);r||(r=new Map,t.set(e,r)),r.set(n,i)}return t}function i4(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:void 0}function uat(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,sourceForm:e.sourceForm===`wiki`||e.sourceForm===`markdown`||e.sourceForm===`jsx`?e.sourceForm:void 0,line:i4(e.line),column:i4(e.column),rawWikiTarget:e.rawWikiTarget===!0}]))])),forward:new Map(Object.entries(e.forward??{}).map(([e,t])=>[e,new Set(t)])),externalForward:t,externalBackward:lat(t),skillRefs:new Map(Object.entries(e.skillRefs??{}).map(([e,t])=>[e,new Set(t)])),sourceLinks:new Map(Object.entries(e.sourceLinks??{}).map(([e,t])=>[e,t.map(e=>({target:e.target,anchor:e.anchor??null,snippet:e.snippet??null,sourceForm:e.sourceForm===`wiki`||e.sourceForm===`markdown`||e.sourceForm===`jsx`?e.sourceForm:void 0,line:i4(e.line),column:i4(e.column),rawWikiTarget:e.rawWikiTarget===!0}))])),inventoryEpoch:0}}var a4=class{projectDir;contentDir;contentFilter;getFileOracle;documentNames;states=new Map;mtimesByBranch=new Map;documentLookups=new WeakMap;resolvedGraphs=new WeakMap;fixedDocumentNames;activeBranch=`main`;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.getFileOracle=e.getFileOracle??(()=>void 0),this.documentNames=[...e.documentNames??[]],this.fixedDocumentNames=new Set(this.documentNames),this.states.set(this.activeBranch,U2())}getState(e=this.activeBranch){let t=this.states.get(e);return t||(t=U2(),this.states.set(e,t)),t}structuralBundleNeighbors(e,t=this.activeBranch){let n=K2(e),r=new Set;if(!n)return r;let i=this.getState(t);if(!i.forward.has(e))return r;if(n.kind===`skill`)for(let t of i.forward.keys()){let n=K2(t);n?.kind===`reference`&&n.skillDocName===e&&r.add(t)}else i.forward.has(n.skillDocName)&&r.add(n.skillDocName);return r}skillRefNeighbors(e,t=this.activeBranch){let n=new Set,r=this.getState(t);if(!r.forward.has(e))return n;let i=K2(e);if(!i)return n;let a=e.startsWith(Hi),o=r.skillRefs.get(e);if(o){for(let e of o)if(e!==i.name){if(a){let t=Se(`global`,e);r.forward.has(t)&&n.add(t)}else for(let t of r.forward.keys()){let r=K2(t);r?.kind===`skill`&&r.name===e&&!t.startsWith(`__skill__/`)&&n.add(t)}}}if(i.kind===`skill`)for(let[t,o]of r.skillRefs)t===e||!o.has(i.name)||t.startsWith(`__skill__/`)===a&&r.forward.has(t)&&n.add(t);return n}bundleNeighbors(e,t=this.activeBranch){if(e[0]!==`.`&&!e.startsWith(`__skill__/`)||!K2(e))return Git;let n=this.structuralBundleNeighbors(e,t);for(let r of this.skillRefNeighbors(e,t))n.add(r);return n}recordSkillRefs(e,t,n=this.activeBranch){this.recordSkillRefsInto(this.getState(n),e,t)}recordSkillRefsInto(e,t,n){if(!K2(t))return;let r=oee(n);r.length===0?e.skillRefs.delete(t):e.skillRefs.set(t,new Set(r))}getActiveBranch(){return this.activeBranch}switchBranch(e){this.activeBranch=e,this.getState(e)}cachePath(e=this.activeBranch){return W(Vq(this.projectDir),`cache`,e,`backlinks.json`)}registerNodeOnly(e,t=this.activeBranch){let n=this.getState(t),r=!n.forward.has(e),i=n.forward.get(e)??new Set,a=n.externalForward.get(e)??new Map;for(let t of i){let r=n.backward.get(t);r&&(r.delete(e),r.size===0&&n.backward.delete(t))}for(let t of a.keys()){let r=n.externalBackward.get(t);r&&(r.delete(e),r.size===0&&n.externalBackward.delete(t))}n.forward.set(e,new Set),n.sourceLinks.set(e,[]),n.externalForward.set(e,new Map),r&&this.inventoryChanged(n,e,!0),this.refreshResolvedSource(n,e,t)}registerGlobalSkillBundleNode(e,t=this.activeBranch){br(e)&&this.registerNodeOnly(e,t)}updateDocument(e,t,n=[],r=this.activeBranch,i=t){if(XW(e))return;if(br(e)){this.registerNodeOnly(e,r);return}let a=this.getState(r),o=!a.forward.has(e),s=a.forward.get(e)??new Set,c=a.externalForward.get(e)??new Map;for(let t of s){let n=a.backward.get(t);n&&(n.delete(e),n.size===0&&a.backward.delete(t))}for(let t of c.keys()){let n=a.externalBackward.get(t);n&&(n.delete(e),n.size===0&&a.externalBackward.delete(t))}let l=new Set,u=new Map;a.forward.set(e,l),a.sourceLinks.set(e,i.map(e=>({...e}))),a.externalForward.set(e,u);for(let n of t){if(!n.target)continue;l.add(n.target);let t=a.backward.get(n.target);t||(t=new Map,a.backward.set(n.target,t)),t.set(e,q2(t.get(e),{anchor:n.anchor,snippet:n.snippet,sourceForm:n.sourceForm,line:n.line,column:n.column,rawWikiTarget:n.rawWikiTarget===!0}))}for(let t of n){if(!t.url)continue;u.set(t.url,{label:t.label,snippet:t.snippet});let n=a.externalBackward.get(t.url);n||(n=new Map,a.externalBackward.set(t.url,n)),(!n.has(e)||!n.get(e)?.snippet&&t.snippet)&&n.set(e,{label:t.label,snippet:t.snippet})}o&&this.inventoryChanged(a,e,!0),this.refreshResolvedSource(a,e,r)}updateDocumentFromMarkdown(e,t,n=this.activeBranch){try{let{frontmatter:r,body:i}=ri(t),a=tat(r),o=r4(i,e,a).map(e=>({...e,sourceForm:`wiki`})),s=nat(i,e,a,this.getFileOracle()).map(e=>({...e,sourceForm:`markdown`})),c=eat(i,e,a).map(e=>({...e,sourceForm:`jsx`})),l=aat(i),u=oat(i,e),d=new Set(o.map(e=>e.target)),f=[...o,...s.filter(e=>!d.has(e.target))];for(let e of f)d.add(e.target);f.push(...c.filter(e=>!d.has(e.target)));let p=new Set(l.map(e=>e.url)),m=[...l,...u.filter(e=>!p.has(e.url))];this.recordSkillRefs(e,i,n),this.updateDocument(e,f,m,n,[...o,...s,...c])}catch(t){H2.warn({docName:e,err:t},`Failed to scan ${e} for link extraction`),this.deleteDocument(e,n)}}deleteDocument(e,t=this.activeBranch){if(XW(e))return;let n=this.getState(t),r=n.forward.get(e)??new Set,i=n.externalForward.get(e)??new Map;for(let t of r){let r=n.backward.get(t);r&&(r.delete(e),r.size===0&&n.backward.delete(t))}for(let t of i.keys()){let r=n.externalBackward.get(t);r&&(r.delete(e),r.size===0&&n.externalBackward.delete(t))}let a=n.forward.delete(e);n.externalForward.delete(e),n.skillRefs.delete(e),n.sourceLinks.delete(e),a&&this.inventoryChanged(n,e,!1)}renameDocument(e,t,n,r=this.activeBranch){this.deleteDocument(e,r),this.updateDocumentFromMarkdown(t,n,r)}getBacklinks(e,t=this.activeBranch){let n=this.canonicalDocName(e,t),r=this.resolvedState(t),i=r.backward.get(n),a=this.bundleNeighbors(n,t);if(a.size===0)return r.sortedBacklinks.get(n)?.map(e=>({...e}))??[];let o=new Map;if(i)for(let[e,t]of i)o.set(e,{source:e,anchor:t.anchor,snippet:t.snippet});for(let e of a)o.has(e)||o.set(e,{source:e,anchor:null,snippet:null});return[...o.values()].sort((e,t)=>e.source.localeCompare(t.source))}getBacklinkCount(e,t=this.activeBranch){let n=this.canonicalDocName(e,t),r=this.resolvedBackward(t).get(n),i=this.bundleNeighbors(n,t);if(i.size===0)return r?.size??0;let a=new Set(r?.keys()??[]);for(let e of i)a.add(e);return a.size}getForwardLinks(e,t=this.activeBranch){let n=this.resolvedGraph(t),r=new Set(n.forward.get(e)??new Set);for(let n of this.bundleNeighbors(e,t))r.add(n);return[...r].sort((e,t)=>e.localeCompare(t))}getForwardLinkEntries(e,t=this.activeBranch){let n=this.resolvedGraph(t),r=this.getForwardLinks(e,t).map(t=>({kind:`doc`,target:t,anchor:n.backward.get(t)?.get(e)?.anchor??null,snippet:n.backward.get(t)?.get(e)?.snippet??null})),i=[...(n.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[...r,...i]}getOrphans(e,t=`both`,n=this.activeBranch){let r=this.resolvedGraph(n),i=new Set;for(let e of r.forward.keys()){let t=K2(e);t?.kind===`reference`&&i.add(t.skillDocName)}let a=e=>{let t=K2(e);return!t||!r.forward.has(e)?!1:t.kind===`skill`?i.has(e):r.forward.has(t.skillDocName)};return[...e].filter(e=>{let n=a(e),i=n||(r.backward.get(e)?.size??0)>0,o=n||(r.forward.get(e)?.size??0)>0;return t===`incoming`?!i:(t===`outgoing`||!i)&&!o}).sort((e,t)=>e.localeCompare(t))}getHubs(e=20,t=this.activeBranch){return[...this.resolvedGraph(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()]}getRenameSourceInventory(e=this.activeBranch){let t=this.getState(e),n=this.mtimesByBranch.get(e);return[...t.forward].map(([e])=>({docName:e,wikiTargets:Kit(t,e).filter(e=>e.sourceForm===`wiki`).map(e=>e.target),indexedMtimeMs:n?.get(e)}))}getDeadLinks(e,t,n=this.activeBranch,r){let i=this.resolvedGraph(n),a=ra(`document`,e);for(let e of i.forward.keys())a.add(e);let o=t?.length?new Set(t):null,s=Sa(ra(`folder`,r??[]),a);return[...i.backward.entries()].filter(([e,t])=>{if(a.resolve(e)!==void 0||s.resolve(e.replace(/\/+$/,``))!==void 0)return!1;if(!o)return t.size>0;for(let e of t.keys())if(o.has(e))return!0;return!1}).map(([e,t])=>({target:e,sources:[...t.entries()].filter(([,e])=>e.rawWikiTarget!==!0).filter(([,t])=>{if(t.sourceForm!==`jsx`||!ei(e))return!0;let n=this.getFileOracle();return n!==void 0&&!n.hasFile(e)}).filter(([,t])=>t.sourceForm!==`wiki`||da(e,this.documentLookup(n))===void 0).filter(([e])=>!o||o.has(e)).map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet,sourceForm:t.sourceForm,line:t.line,column:t.column})).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)}canonicalDocName(e,t){return ja(this.documentLookup(t).pages,e)??e}documentLookup(e=this.activeBranch){let t=this.getState(e),n=this.documentLookups.get(t);if(n?.epoch===t.inventoryEpoch)return n.lookup;let r=EJ([...t.forward.keys(),...this.documentNames]),i=new Map,a=new Map;for(let e of r.pages){if(br(e))continue;let t=ea(e),n=ea(e.slice(e.lastIndexOf(`/`)+1));if(t){let n=i.get(t)??new Set;n.add(e),i.set(t,n)}if(n){let t=a.get(n)??new Set;t.add(e),a.set(n,t)}}let o=ra(`document`,r.pages),s={pages:o,pagesBySlug:new Map(r.pagesBySlug),pagesByBasename:new Map(r.pagesByBasename)};return this.documentLookups.set(t,{epoch:t.inventoryEpoch,lookup:s,pages:o,slugBuckets:i,basenameBuckets:a}),s}updateDocumentLookup(e,t,n){let r=this.documentLookups.get(e);if(!r||r.epoch!==e.inventoryEpoch-1||(r.epoch=e.inventoryEpoch,!n&&this.fixedDocumentNames.has(t)))return;let i=r.pages;if((n?i.has(t):!i.has(t))||(n?i.add(t):i.delete(t),br(t)))return;let a=ea(t),o=ea(t.slice(t.lastIndexOf(`/`)+1)),s=(e,r,i)=>{if(!e)return;let a=r.get(e)??new Set;n?a.add(t):a.delete(t),a.size?r.set(e,a):r.delete(e);let o=i,s=[...a].sort()[0];s?o.set(e,s):o.delete(e)};s(a,r.slugBuckets,r.lookup.pagesBySlug),s(o,r.basenameBuckets,r.lookup.pagesByBasename??new Map)}inventoryChanged(e,t,n){e.inventoryEpoch++,this.updateDocumentLookup(e,t,n);let r=this.resolvedGraphs.get(e);if(!r||r.inventoryEpoch!==e.inventoryEpoch-1)return;r.inventoryEpoch=e.inventoryEpoch;let i=Ti(t),a=Ti(t.slice(t.lastIndexOf(`/`)+1)),o=new Set([...r.sourcesByPathSlug.get(i)??[],...r.wikiSourcesByBasenameSlug.get(a)??[]]),s=t.lastIndexOf(`/`);if(s!==-1){let e=t.slice(0,s),n=pa(`document`,t.slice(s+1)),i=pa(`document`,e.slice(e.lastIndexOf(`/`)+1));if(n===pa(`document`,`index`)||n===i)for(let t of r.wikiSourcesByFolder.get(Fi(`folder`,e))??[])o.add(t)}o.add(t);let c=this.documentLookupForResolved(e),l=new Set;for(let t of o)for(let n of this.resolveSource(e,r,t,c))l.add(n);for(let e of l)this.refreshSortedBacklinks(r,e)}documentLookupForResolved(e){let t=this.documentLookups.get(e);if(!t||t.epoch!==e.inventoryEpoch)throw Error(`Resolved link graph has no matching document lookup`);return t.lookup}resolveSource(e,t,n,r){let i=t.keysBySource.get(n);i&&(G2(t.sourcesByPathSlug,i.paths,n),G2(t.wikiSourcesByBasenameSlug,i.basenames,n),G2(t.wikiSourcesByFolder,i.folders,n));let a=new Set(t.forward.get(n)??[]);for(let e of a){let r=t.backward.get(e);r?.delete(n),r?.size===0&&t.backward.delete(e)}let o=new Set;e.forward.has(n)?t.forward.set(n,o):t.forward.delete(n);let s={paths:new Set,basenames:new Set,folders:new Set},c=e.forward.has(n)?Kit(e,n):[];for(let e of c){let i=e.target;if(!i)continue;let c;if(e.sourceForm===`wiki`||e.sourceForm===void 0){let t=i.trim();for(let e of[t,t.replace(/\.(md|mdx)$/i,``)]){let t=Ti(e);s.paths.add(t),e.includes(`/`)||s.basenames.add(t),s.folders.add(Fi(`folder`,e))}let n=da(i,r);if(e.rawWikiTarget===!0&&n===void 0)continue;c=n??i}else s.paths.add(Ti(i)),c=ja(r.pages,i)??i;o.add(c),a.add(c);let l=t.backward.get(c);l||(l=new Map,t.backward.set(c,l)),l.set(n,q2(l.get(n),e))}return e.forward.has(n)?(t.keysBySource.set(n,s),W2(t.sourcesByPathSlug,s.paths,n),W2(t.wikiSourcesByBasenameSlug,s.basenames,n),W2(t.wikiSourcesByFolder,s.folders,n)):t.keysBySource.delete(n),a}refreshSortedBacklinks(e,t){let n=e.backward.get(t);if(!n){e.sortedBacklinks.delete(t);return}e.sortedBacklinks.set(t,Array.from(n,([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet})).sort((e,t)=>qit(e.source,t.source)))}updateSortedBacklink(e,t,n){let r=e.backward.get(t)?.get(n),i=e.sortedBacklinks.get(t)??[],a=0,o=i.length;for(;a<o;){let e=a+o>>>1;qit(i[e].source,n)<0?a=e+1:o=e}let s=i[a]?.source===n;r?i.splice(a,+!!s,{source:n,anchor:r.anchor,snippet:r.snippet}):s&&i.splice(a,1),i.length>0?e.sortedBacklinks.set(t,i):e.sortedBacklinks.delete(t)}refreshResolvedSource(e,t,n){let r=this.resolvedGraphs.get(e);if(r?.inventoryEpoch===e.inventoryEpoch)for(let i of this.resolveSource(e,r,t,this.documentLookup(n)))this.updateSortedBacklink(r,i,t)}resolvedState(e){let t=this.getState(e),n=this.resolvedGraphs.get(t);if(n?.inventoryEpoch===t.inventoryEpoch)return n;this.resolvedGraph(e);let r=this.resolvedGraphs.get(t);if(!r)throw Error(`Resolved link graph was not created`);return r}resolvedBackward(e){return this.resolvedState(e).backward}resolvedGraph(e=this.activeBranch){let t=this.getState(e),n=this.resolvedGraphs.get(t);if(n?.inventoryEpoch!==t.inventoryEpoch){n={inventoryEpoch:t.inventoryEpoch,forward:new Map,backward:new Map,sortedBacklinks:new Map,sourcesByPathSlug:new Map,wikiSourcesByBasenameSlug:new Map,wikiSourcesByFolder:new Map,keysBySource:new Map};let r=this.documentLookup(e);for(let e of t.forward.keys())this.resolveSource(t,n,e,r);for(let e of n.backward.keys())this.refreshSortedBacklinks(n,e);this.resolvedGraphs.set(t,n)}return{...t,...n}}getLinkGraph(e=this.activeBranch){let t=this.resolvedGraph(e),n=new Map,r=[],i=e=>{n.has(e)||n.set(e,{kind:`doc`,id:e,docName:e,anchor:J2(t.backward.get(e))})};for(let[e,n]of t.forward){i(e);for(let t of n)i(t),r.push({source:e,target:t})}for(let[e,i]of t.externalForward){n.set(e,{kind:`doc`,id:e,docName:e,anchor:J2(t.backward.get(e))});for(let[t,a]of i){let i=Y2(t);n.set(i,{kind:`external`,id:i,url:t,label:a.label}),r.push({source:e,target:i})}}for(let i of t.forward.keys())if(K2(i)?.kind===`skill`)for(let a of this.bundleNeighbors(i,e))t.forward.get(i)?.has(a)||t.forward.get(a)?.has(i)||(n.set(i,{kind:`doc`,id:i,docName:i,anchor:J2(t.backward.get(i))}),n.set(a,{kind:`doc`,id:a,docName:a,anchor:J2(t.backward.get(a))}),r.push({source:i,target:a}));return{nodes:[...n.values()].sort((e,t)=>e.id.localeCompare(t.id)),links:r}}getLinkGraphNeighborhood(e,t,n=this.activeBranch){let r=this.resolvedGraph(n),i=new Map;for(let e of r.externalForward.values())for(let[t,n]of e)i.has(t)||i.set(t,n.label);let a=new Set([e]),o=[{nodeId:e,degree:0}],s=0;for(;s<o.length;){let e=o[s++];if(e.degree>=t)continue;let i=Jit(e.nodeId),c=new Set;if(i)for(let e of r.externalBackward.get(i)?.keys()??[])c.add(e);else{for(let t of r.forward.get(e.nodeId)??new Set)c.add(t);for(let t of r.externalForward.get(e.nodeId)?.keys()??[])c.add(Y2(t));for(let t of r.backward.get(e.nodeId)?.keys()??[])c.add(t);for(let t of this.bundleNeighbors(e.nodeId,n))c.add(t)}for(let t of c)a.has(t)||(a.add(t),o.push({nodeId:t,degree:e.degree+1}))}let c=[];for(let[e,t]of r.forward)if(a.has(e))for(let n of t)a.has(n)&&c.push({source:e,target:n});for(let[e,t]of r.externalForward)if(a.has(e))for(let n of t.keys()){let t=Y2(n);a.has(t)&&c.push({source:e,target:t})}for(let e of a)if(K2(e)?.kind===`skill`)for(let t of this.bundleNeighbors(e,n))a.has(t)&&(r.forward.get(e)?.has(t)||r.forward.get(t)?.has(e)||c.push({source:e,target:t}));return{nodes:[...a].sort().map(e=>{let t=Jit(e);return t?{kind:`external`,id:e,url:t,label:i.get(t)??null}:{kind:`doc`,id:e,docName:e,anchor:J2(r.backward.get(e))}}),links:c}}async saveToDisk(e=this.activeBranch){let t=this.cachePath(e);await UH(V(t),{recursive:!0});let n=this.getState(e),r=this.mtimesByBranch.get(e),i={version:4,...cat(n),...r?{mtimes:Object.fromEntries(r)}:{}};await Lx(t,JSON.stringify(i,null,2),{fs:tU})}async loadFromDisk(e=this.activeBranch){let t=this.cachePath(e);if(!G(t))return!1;let n;try{n=await Xs(t,`utf-8`)}catch(t){return H2.warn({branch:e,err:t},`Failed to load cache for ${e}`),!1}try{let r=JSON.parse(n);return r.version===4?!r.sourceLinks||Object.entries(r.forward??{}).some(([e,t])=>{let n=r.sourceLinks?.[e];return!Array.isArray(n)||t.length>0&&n.length===0})?(H2.warn({branch:e},`Incomplete backlink cache snapshot for ${e}; rebuilding from disk`),await this.discardCorruptSnapshot(t,e,`incomplete`),!1):(this.states.set(e,uat(r)),r.mtimes?this.mtimesByBranch.set(e,new Map(Object.entries(r.mtimes))):this.mtimesByBranch.delete(e),!0):!1}catch(n){return H2.warn({branch:e,err:n},`Corrupt backlink cache snapshot for ${e}; rebuilding from disk`),await this.discardCorruptSnapshot(t,e,`malformed`),!1}}async discardCorruptSnapshot(e,t,n){try{await VH(e,{force:!0})}catch(e){H2.warn({branch:t,reason:n,err:e},`Failed to discard corrupt backlink cache snapshot`)}}clear(e=this.activeBranch){this.states.set(e,U2()),this.mtimesByBranch.delete(e)}async rebuildFromDisk(e=this.activeBranch){return B2(`backlink`,`full`,()=>this.rebuildFromDiskUnspanned(e))}async rebuildFromDiskUnspanned(e){let t=U2(),n=new Map,r=[];await this.walkForPaths(this.contentDir,r);let i=new Set,a=r.filter(({docName:e})=>!i.has(e)&&(i.add(e),!0));for(let e=0;e<a.length;e+=50){let r=a.slice(e,e+50),i=await Promise.allSettled(r.map(async({docName:e,filePath:t})=>{let[n,r]=await Promise.all([ec(t),Xs(t,`utf-8`)]);return{docName:e,mtimeMs:n.mtimeMs,markdown:r}}));for(let e of i){if(e.status===`rejected`){H2.warn({err:e.reason},`Failed to rebuild entry`);continue}let{docName:r,mtimeMs:i,markdown:a}=e.value;n.set(r,i);let{frontmatter:o,body:s}=ri(a),c=tat(o),l=r4(s,r,c).map(e=>({...e,sourceForm:`wiki`})),u=nat(s,r,c,this.getFileOracle()).map(e=>({...e,sourceForm:`markdown`})),d=eat(s,r,c).map(e=>({...e,sourceForm:`jsx`})),f=aat(s),p=oat(s,r),m=new Set(l.map(e=>e.target)),h=[...l,...u.filter(e=>!m.has(e.target))];for(let e of h)m.add(e.target);h.push(...d.filter(e=>!m.has(e.target)));let g=new Set(f.map(e=>e.url)),_=[...f,...p.filter(e=>!g.has(e.url))],v=new Set,y=new Map;this.recordSkillRefsInto(t,r,s),t.forward.set(r,v),t.sourceLinks.set(r,[...l,...u,...d]),t.externalForward.set(r,y);for(let e of h){if(!e.target)continue;v.add(e.target);let n=t.backward.get(e.target);n||(n=new Map,t.backward.set(e.target,n)),n.set(r,q2(n.get(r),{anchor:e.anchor,snippet:e.snippet,sourceForm:e.sourceForm,line:e.line,column:e.column,rawWikiTarget:e.rawWikiTarget===!0}))}for(let e of _){if(!e.url)continue;y.set(e.url,{label:e.label,snippet:e.snippet});let n=t.externalBackward.get(e.url);n||(n=new Map,t.externalBackward.set(e.url,n)),n.set(r,{label:e.label,snippet:e.snippet})}}}this.states.set(e,t),this.mtimesByBranch.set(e,n)}async walkForPaths(e,t){let n;try{n=await Zs(e,{withFileTypes:!0})}catch(t){H2.warn({dir:e,err:t},`Failed to read directory ${e}`);return}for(let r of n){let n=H(e,r.name);if(r.isDirectory()){let e=eG(U(this.contentDir,n));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkForPaths(n,t)}else if(r.isFile()&&OW(r.name)){let e=eG(U(this.contentDir,n));if(this.contentFilter?.isExcluded(e))continue;t.push({docName:jW(e),filePath:n})}}}async reconcileWithDisk(e=this.activeBranch){return B2(`backlink`,`reconcile`,()=>this.reconcileWithDiskUnspanned(e),e=>({"index.added":e.added,"index.updated":e.updated,"index.deleted":e.deleted}))}async reconcileWithDiskUnspanned(e){if(!G(this.contentDir))return{added:0,updated:0,deleted:0,deletedDocNames:[],changedDocs:[]};let t=this.mtimesByBranch.get(e)??new Map,n=[];await this.walkForPaths(this.contentDir,n);let r=new Set,i=n.filter(({docName:e})=>!r.has(e)&&(r.add(e),!0)),a=new Set(i.map(e=>e.docName)),o=new Map,s=0,c=0,l=[],u=await Promise.allSettled(i.map(async({docName:e,filePath:t})=>({docName:e,filePath:t,mtimeMs:(await ec(t)).mtimeMs})));for(let e of u){if(e.status===`rejected`)continue;let{docName:n,filePath:r,mtimeMs:i}=e.value,a=t.get(n);if(a!==void 0&&a===i){o.set(n,i);continue}l.push({docName:n,filePath:r,mtimeMs:i,isNew:a===void 0})}for(let t=0;t<l.length;t+=50){let n=l.slice(t,t+50),r=await Promise.allSettled(n.map(async({docName:e,filePath:t,mtimeMs:n,isNew:r})=>({docName:e,mtimeMs:n,isNew:r,markdown:await Xs(t,`utf-8`)})));for(let t of r){if(t.status===`rejected`){H2.warn({err:t.reason},`Failed to reconcile file`);continue}let{docName:n,mtimeMs:r,isNew:i,markdown:a}=t.value;this.updateDocumentFromMarkdown(n,a,e),o.set(n,r),i?s++:c++}}let d=0,f=[],p=new Set([...t.keys(),...this.getState(e).forward.keys()]);for(let t of p)br(t)||a.has(t)||(this.deleteDocument(t,e),d++,f.push(t));return this.mtimesByBranch.set(e,o),{added:s,updated:c,deleted:d,deletedDocNames:f,changedDocs:l.map(({docName:e,filePath:t})=>({docName:e,filePath:t}))}}async ingestGlobalSkillBundles(e,t=this.activeBranch){let n=new Set;for(let r of e){if(!G(r))continue;let e;try{e=await Zs(r,{withFileTypes:!0})}catch(e){H2.warn({root:r,err:e},`Failed to read global skills root ${r}`);continue}for(let i of e){if(!i.isDirectory())continue;let e=i.name,a=H(r,e),o=Se(`global`,e);if(G(H(a,`SKILL.md`))&&br(o)){this.registerNodeOnly(o,t),n.add(o);try{let e=await Xs(H(a,`SKILL.md`),`utf-8`);this.recordSkillRefs(o,ri(e).body,t)}catch(e){H2.warn({dir:a,err:e},`global skill ref-scan failed; edges skipped`)}}let s=[];await this.walkGlobalSkillReferences(H(a,`references`),e,``,s);for(let{docName:e}of s)this.registerNodeOnly(e,t),n.add(e)}}let r=[];for(let e of this.getState(t).forward.keys())br(e)&&!n.has(e)&&r.push(e);for(let e of r)this.deleteDocument(e,t)}async walkGlobalSkillReferences(e,t,n,r){let i;try{i=await Zs(e,{withFileTypes:!0})}catch(t){t?.code!==`ENOENT`&&H2.warn({dir:e,err:t},`Failed to read skill references dir ${e}`);return}for(let a of i){let i=n?`${n}/${a.name}`:a.name;if(a.isDirectory())await this.walkGlobalSkillReferences(H(e,a.name),t,i,r);else if(a.isFile()&&OW(a.name)){let e=jW(i);r.push({docName:`${Hi}global/${t}/references/${e}`})}}}};function o4(e){return e.filter(e=>z2(e))}function dat(e){return e.filter(e=>z2(e)||F2(e.occurrence)!==null)}function fat(e){let t=Mn();for(let n of e)t.add(n);return t}function pat(e){return`file-basename:${pa(`file`,e.slice(e.lastIndexOf(`/`)+1))}`}function mat(e){return`wiki-file:${Kne(e)}`}function hat(e){let t=F2(e.occurrence);if(t===null)return[];let n=xit(e.occurrence.href);if(n===null)return[];let r=[n.includes(`/`)?mat(n):pat(n)];return e.targetKind===`file`&&e.status===`missing`&&r.push(...vat(t)),r}function s4(e,t,n){if(t===void 0||!t.isExcludedByIgnoreFiles(n)||t.isPathIgnored(n,{bypassFilters:!0}))return!1;let r=W(e,n);if(!tG(r,e))return!1;try{return Ls(r).isFile()}catch{return!1}}function c4(e,t){let n=[],r=[];if(e.resolvedTarget!==null&&(e.targetKind===`document`?n.push(e.resolvedTarget):e.targetKind===`file`&&r.push(e.resolvedTarget)),e.occurrence.role===`link`){let i=Bi(e.occurrence.href,t);if(i?.kind===`doc`){n.push(i.docName);let a=Ya(e.occurrence.href,t,{literal:!1});a===i.docName&&r.push(a)}}return e.fallbackTarget!==null&&n.push(e.fallbackTarget),{docs:n,files:r}}function gat(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function _at(e,t,n){let r=e.get(t);r&&(r.delete(n),r.size===0&&e.delete(t))}function vat(e){let t=[],n=ea(e);return n&&t.push(`slug:${n}`),!e.includes(`/`)&&n&&t.push(`basename:${n}`),t.push(l4(e)),t}function l4(e){return`folder:${Fi(`folder`,e)}`}function u4(e){let t=[],n=ea(e);n&&t.push(`slug:${n}`);let r=e.slice(e.lastIndexOf(`/`)+1),i=ea(r);i&&t.push(`basename:${i}`);let a=e.indexOf(`/`);for(;a!==-1;)t.push(l4(e.slice(0,a))),a=e.indexOf(`/`,a+1);return t}function d4(e,t,n,r){if(t)for(let i of t)n.has(i)||_at(e,i,r);for(let i of n)t?.has(i)||gat(e,i,r)}function f4(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];if(!r)return!1;let i=e.occurrence.reference,a=r.occurrence.reference;return e.targetKind===r.targetKind&&e.resolvedTarget===r.resolvedTarget&&e.status===r.status&&e.reason===r.reason&&e.resolutionMethod===r.resolutionMethod&&e.fallbackTarget===r.fallbackTarget&&e.occurrence.role===r.occurrence.role&&e.occurrence.sourceForm===r.occurrence.sourceForm&&e.occurrence.href===r.occurrence.href&&e.occurrence.range.start===r.occurrence.range.start&&e.occurrence.range.end===r.occurrence.range.end&&e.occurrence.line===r.occurrence.line&&e.occurrence.column===r.occurrence.column&&i?.label===a?.label&&i?.kind===a?.kind&&i?.definition.href===a?.definition.href&&i?.definition.repairRange.start===a?.definition.repairRange.start&&i?.definition.repairRange.end===a?.definition.repairRange.end})}var yat=class e{contentDir;canonicalContentDir;contentFilter;readDocument;readDirectory;sourceAssessments=new Map;sourceDocKeys=new Map;sourceFileDeps=new Map;sourceFileKeys=new Map;reverseByDoc=new Map;reverseByFile=new Map;reverseByTolerant=new Map;sourceTolerantDeps=new Map;documents=ra(`document`);tolerantDocumentResolver=()=>null;files=ra(`file`);fileBasenames=Mn();wikiFileResolver=null;generationValue=0;freshnessEpoch=0;readyValue=!1;closed=!1;folderPaths=ra(`folder`);injectedFolderPaths=ra(`folder`);inventory={resolveDocument:e=>this.documents.resolve(e),resolveFile:e=>this.files.resolve(e),resolveFileByBasename:(e,t)=>this.fileBasenames.resolveEmbed(e,t)??void 0,resolveWikiFile:e=>(this.wikiFileResolver??=Ki(this.files),this.wikiFileResolver(e)),isExcludedFile:e=>s4(this.contentDir,this.contentFilter,e),resolveTolerantDocument:e=>this.tolerantDocumentResolver(e),resolveFolder:e=>this.folderPaths.resolve(e)??this.injectedFolderPaths.resolve(e)};constructor(e){this.contentDir=e.contentDir,this.canonicalContentDir=sG(W(e.contentDir),{root:`content`,component:`local-target-index`}),this.contentFilter=e.contentFilter,this.readDocument=e.readDocument??(e=>Xs(e,`utf-8`)),this.readDirectory=e.readDirectory??(e=>Zs(e,{withFileTypes:!0}))}get generation(){return this.generationValue}isReady(){return this.readyValue}markUnavailable(){this.readyValue&&this.freshnessEpoch++,this.readyValue=!1}get freshnessToken(){return`${this.generationValue}:${this.freshnessEpoch}`}getAssessments(e){return o4(this.sourceAssessments.get(e)??[])}getAssessmentsForSources(e){let t=e&&e.length>0?new Set(e):null,n=[];for(let[e,r]of this.sourceAssessments){if(t&&!t.has(e))continue;let i=o4(r);i.length>0&&n.push({source:e,assessments:i})}return n}getDocumentDependents(e){let t=new Set(this.reverseByDoc.get(Fi(`document`,e))??[]);for(let n of u4(e))for(let e of this.reverseByTolerant.get(n)??[])t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}getFileDependents(e){return[...this.reverseByFile.get(Fi(`file`,e))??[]].sort((e,t)=>e.localeCompare(t))}getStats(){let e=0,t=0,n=new Set,r=new Set;for(let[i,a]of this.sourceAssessments){let o=o4(a);if(o.length!==0){e++,t+=o.length;for(let e of o){let{docs:t,files:a}=c4(e,i);for(let e of t)n.add(Fi(`document`,e));for(let e of a)r.add(Fi(`file`,e))}}}return{sources:e,occurrences:t,documentTargets:n.size,fileTargets:r.size}}close(){this.closed=!0}setSource(e,t){return!XW(e)&&V2(`local-target`,`source`,()=>{let n=this.sourceAssessments.get(e)??[],r=!this.documents.has(e);this.documents.add(e),r&&this.refreshTolerantDocumentIndexes();let i=dat(L2(A2(t),e,this.inventory));f4(n,i)||this.applySourceAssessments(e,i);let a=o4(i),o=!f4(o4(n),a),s=r?this.reassessDocumentDependents(e):0,c=o||s>0;return c&&this.generationValue++,{changed:c,occurrences:a.length,affectedSources:s+ +!!o}},e=>({"index.occurrences":e.occurrences,"index.affected_sources":e.affectedSources})).changed}removeSource(e){return!XW(e)&&V2(`local-target`,`document-target`,()=>{let t=o4(this.sourceAssessments.get(e)??[]).length,n=t>0,r=this.documents.delete(e);r&&this.refreshTolerantDocumentIndexes(),this.applySourceAssessments(e,[]);let i=r?this.reassessDocumentDependents(e):0,a=n||i>0;return a&&this.generationValue++,{changed:a,occurrences:t,affectedSources:i+ +!!n}},e=>({"index.occurrences":e.occurrences,"index.affected_sources":e.affectedSources})).changed}renameSource(e,t,n){let r=this.removeSource(e),i=this.setSource(t,n);return r||i}setFileTarget(e,t){return this.files.has(e)===t?0:V2(`local-target`,`file-target`,()=>{t?(this.files.add(e),this.fileBasenames.add(e)):(this.files.delete(e),this.fileBasenames.remove(e)),this.wikiFileResolver=null;let n=this.countFileOccurrences(e),r=this.reassessFileDependents(e);return r>0&&this.generationValue++,{affected:r,occurrences:n}},e=>({"index.occurrences":e.occurrences,"index.affected_sources":e.affected})).affected}reconcileDocumentTargets(e){let t=ra(`document`,e),n=new Set;for(let e of this.documents)t.has(e)||n.add(e);for(let e of t)this.documents.has(e)||n.add(e);if(n.size===0)return 0;let r=new Set;for(let e of n){for(let t of this.reverseByDoc.get(Fi(`document`,e))??[])r.add(t);for(let t of u4(e))for(let e of this.reverseByTolerant.get(t)??[])r.add(e)}this.documents=t,this.refreshTolerantDocumentIndexes();let i=0;for(let e of r)this.reassessSource(e)&&i++;return i>0&&this.generationValue++,i}reconcileFolderTargets(e){let t=ra(`folder`,e),n=new Set;for(let e of this.injectedFolderPaths)t.has(e)||n.add(e);for(let e of t)this.injectedFolderPaths.has(e)||n.add(e);if(n.size===0)return 0;let r=new Set;for(let e of n)for(let t of this.reverseByTolerant.get(l4(e))??[])r.add(t);this.injectedFolderPaths=t;let i=0;for(let e of r)this.reassessSource(e)&&i++;return i>0&&this.generationValue++,i}reconcileFileTargets(e){let t=ra(`file`,e),n=new Set;for(let e of this.files)t.has(e)||n.add(e);for(let e of t)this.files.has(e)||n.add(e);return n.size===0?0:V2(`local-target`,`file-target`,()=>{let e=new Set,r=0;for(let t of n){r+=this.countFileOccurrences(t);for(let n of this.fileDependents(t))e.add(n)}this.files=t,this.fileBasenames=fat(t),this.wikiFileResolver=null;let i=0;for(let t of e)this.reassessSource(t)&&i++;return i>0&&this.generationValue++,{affected:i,occurrences:r}},e=>({"index.occurrences":e.occurrences,"index.affected_sources":e.affected})).affected}async reconcileDependentFileTargetsFromDisk(e){let t=new Set;for(let e of this.sourceFileDeps.values())for(let n of e)t.add(n);let n=[...t],r=await Promise.all(n.map(e=>this.isAdmittedFileOnDisk(e))),i=0;for(let[t,a]of n.entries()){let n=r[t]??!1,o=this.setFileTarget(a,n);o>0&&e?.(a,n),i+=o}return i}async isAdmittedFileOnDisk(e){if(this.contentFilter?.isPathIgnored(e))return!1;try{let t=await Qs(H(this.contentDir,e)),n=U(this.canonicalContentDir,t);return n===``||n===`..`||n.startsWith(`..${process.platform===`win32`?`\\`:`/`}`)||hs(n)?!1:(await ec(t)).isFile()}catch{return!1}}countFileOccurrences(e){let t=Fi(`file`,e),n=0;for(let e of this.reverseByFile.get(t)??[])for(let r of o4(this.sourceAssessments.get(e)??[])){let{files:i}=c4(r,e);i.some(e=>Fi(`file`,e)===t)&&n++}return n}rebuildFromDisk(e){return B2(`local-target`,`full`,()=>this.rebuildOnce(e),e=>({"index.sources":e.sources,"index.occurrences":e.occurrences,"index.affected_sources":e.sources}))}async rebuildOnce(t){let n=this.hasProjectableRows();this.freshnessEpoch++,this.readyValue=!1;let r=new e({contentDir:this.contentDir,contentFilter:this.contentFilter,readDocument:this.readDocument,readDirectory:this.readDirectory}),i=await r.populateFromDisk(t);return this.sourceAssessments=r.sourceAssessments,this.sourceDocKeys=r.sourceDocKeys,this.sourceFileDeps=r.sourceFileDeps,this.sourceFileKeys=r.sourceFileKeys,this.reverseByDoc=r.reverseByDoc,this.reverseByFile=r.reverseByFile,this.reverseByTolerant=r.reverseByTolerant,this.sourceTolerantDeps=r.sourceTolerantDeps,this.documents=r.documents,this.tolerantDocumentResolver=r.tolerantDocumentResolver,this.folderPaths=r.folderPaths,this.injectedFolderPaths=r.injectedFolderPaths,this.files=r.files,this.fileBasenames=r.fileBasenames,this.wikiFileResolver=null,this.readyValue=!0,(n||this.hasProjectableRows())&&this.generationValue++,i}hasProjectableRows(){for(let e of this.sourceAssessments.values())if(e.some(e=>z2(e)))return!0;return!1}async populateFromDisk(e){for(let t of e.documentTargets)this.documents.add(t);for(let t of e.fileTargets)this.files.add(t),this.fileBasenames.add(t);for(let t of e.folderTargets??[])this.injectedFolderPaths.add(t);if(this.refreshTolerantDocumentIndexes(),!G(this.contentDir))return this.readyValue=!0,{sources:0,occurrences:0};let t=await this.listDocsWithPaths();for(let{docName:e}of t)this.documents.add(e);this.refreshTolerantDocumentIndexes();let n=0,r=0;for(let e=0;e<t.length&&!this.closed;e+=50){let i=t.slice(e,e+50),a=await Promise.all(i.map(async({docName:e,filePath:t})=>({docName:e,markdown:await this.readDocument(t)})));for(let e of a){if(XW(e.docName))continue;let t=dat(L2(A2(e.markdown),e.docName,this.inventory));this.applySourceAssessments(e.docName,t);let i=o4(t).length;i>0&&n++,r+=i}}return this.readyValue=!0,{sources:n,occurrences:r}}applySourceAssessments(e,t){let n=new Set,r=new Set,i=new Set,a=new Set;for(let o of t){let{docs:t,files:s}=c4(o,e);for(let e of t)n.add(Fi(`document`,e));for(let e of s)r.add(e),i.add(Fi(`file`,e));if(o.targetKind===`document`&&o.resolvedTarget!==null&&(o.status!==`exact`||!this.documents.has(o.resolvedTarget)))for(let e of vat(o.resolvedTarget))a.add(e);for(let e of hat(o))a.add(e)}if(d4(this.reverseByDoc,this.sourceDocKeys.get(e),n,e),d4(this.reverseByFile,this.sourceFileKeys.get(e),i,e),d4(this.reverseByTolerant,this.sourceTolerantDeps.get(e),a,e),t.length===0){this.sourceAssessments.delete(e),this.sourceDocKeys.delete(e),this.sourceFileDeps.delete(e),this.sourceFileKeys.delete(e),this.sourceTolerantDeps.delete(e);return}this.sourceAssessments.set(e,t),this.sourceDocKeys.set(e,n),this.sourceFileDeps.set(e,r),this.sourceFileKeys.set(e,i),this.sourceTolerantDeps.set(e,a)}reassessSource(e){let t=this.sourceAssessments.get(e);if(!t)return!1;let n=L2(t.map(e=>e.occurrence),e,this.inventory);return!f4(t,n)&&(this.applySourceAssessments(e,n),!f4(o4(t),o4(n)))}reassessDocumentDependents(e){let t=new Set(this.reverseByDoc.get(Fi(`document`,e))??[]);for(let n of u4(e))for(let e of this.reverseByTolerant.get(n)??[])t.add(e);let n=0;for(let e of t)this.reassessSource(e)&&(n+=1);return n}fileDependents(e){let t=new Set(this.reverseByFile.get(Fi(`file`,e))??[]),n=this.reverseByTolerant.get(pat(e));for(let e of n??[])t.add(e);let r=this.reverseByTolerant.get(mat(e));for(let e of r??[])t.add(e);return t}reassessFileDependents(e){let t=0;for(let n of this.fileDependents(e))this.reassessSource(n)&&(t+=1);return t}refreshTolerantDocumentIndexes(){this.tolerantDocumentResolver=j2(this.documents),this.folderPaths=Sa(ra(`folder`),this.documents)}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)&&(t.add(e),!0))}async walkContentDir(e,t){let n=await this.readDirectory(e);for(let r of n){let n=H(e,r.name);if(r.isDirectory()){let e=eG(U(this.contentDir,n));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(n,t);continue}if(!r.isFile()||!OW(r.name))continue;let i=eG(U(this.contentDir,n));this.contentFilter?.isExcluded(i)||t.push({docName:jW(i),filePath:n})}}};const bat=q(`local-target-inventory`),xat=new WeakMap;function Sat(e,t){let n=eG(U(e,t));return n.length===0||n===`..`||n.startsWith(`../`)||hs(n)?null:n}function p4(e,t){let n=[...e];for(let[r,i]of t)for(let t of n)t===i?e.add(r):t.startsWith(`${i}/`)&&e.add(`${r}${t.slice(i.length)}`)}function m4(e,t){if(!e)return null;let n=e.getFileIndexGeneration(),r=xat.get(e);if(r?.contentDir===t&&r.generation===n)return r.inventory;let i=h4(e.getAllFilesIndex(),e.getFolderAliasIndex(),t,e.getFolderIndex?.());return xat.set(e,{contentDir:t,generation:n,inventory:i}),i}function h4(e,t,n,r){let i=new Set,a=new Set,o=new Set(r?.keys()??[]);for(let[t,r]of e){let e=r.kind===`markdown`?i:a,{resolved:o,members:s}=bY(n,t,r);for(let t of s)e.add(t.path);if(o)continue;let c=Sat(n,r.canonicalPath);c&&e.add(r.kind===`markdown`?jW(c):c)}return p4(i,t),p4(a,t),p4(o,t),{documentTargets:[...i],fileTargets:[...a],folderTargets:[...o]}}function Cat(e,t){let n=null,r=()=>void 0;return i=>{let a=e();if(a!==null)return a.fileTargets!==n&&(n=a.fileTargets,r=t(n)),r(i)}}function wat(e){return Cat(e,e=>{let t=ra(`file`,e);return e=>t.resolve(e)})}function Tat(e){return Cat(e,Ki)}function Eat(e){let t=Mn();for(let n of e)t.add(n);return(e,n)=>t.resolveEmbed(e,n)??void 0}function Dat(e,t,n){let r=Si(`file`,e),i=Ns(t);return e=>{if(r.resolve(e)!==void 0)return!0;if(n?.isPathIgnored(e))return!1;let a=W(t,e);if(!tG(a,t))return!1;try{let e=Ns(a);return tG(e,i)&&Ls(e).isFile()}catch(e){return e.code!==`ENOENT`&&bat.debug({err:e,candidate:a},`linked-file existence fallback could not canonicalize; treating as absent`),!1}}}function Oat(e,t,n){let r=e.resolvedScope;if(r?.kind!==`file`||!OW(r.path))return;let i=jW(r.path),a=ms(r.path).toLowerCase();if(!va.some(e=>e!==a&&p2(`${i}${e}`,!0)?.isFile()))return;let o=eG(U(t.contentDir,r.path)),s=jW(o),c=$G({projectDir:t.projectDir,contentDir:t.contentDir});if(c.isExcluded(o))return;let l=Ns(t.contentDir),u=Ns(r.path);if(!gG(u,l))throw Error(`symlink-escape: audit scope resolves outside the content directory`);let d=(t.docFilePathFor(s)===o?t.liveSourceFor?.(o):null)??K(u,`utf8`),f=(e,n)=>{let r=W(t.contentDir,e);if(!gG(r,t.contentDir)||(n===`file`?c.isExcluded(e):c.isDirExcluded(e)))return!1;let i=p2(r,!0);return i===void 0||!gG(Ns(r),l)?!1:n===`file`?i.isFile():i.isDirectory()},p=Si(`document`,n),m=t.localTargetInventory?.()??null,h=m===null?null:Si(`file`,m.fileTargets),g=m===null?null:Sa(ra(`folder`,m.folderTargets),p),_=e=>h===null?f(e,`file`)?e:void 0:h.resolve(e),v=e=>g===null?f(e,`dir`)?e:void 0:g.resolve(e),y=e=>_(e)!==void 0,b=e=>v(e)!==void 0,x=new a4({projectDir:t.projectDir,contentDir:t.contentDir,documentNames:n,getFileOracle:()=>({hasFile:y})});x.updateDocumentFromMarkdown(s,d);let S=Cit(d,s,{resolveDocument:e=>p.resolve(e),resolveFile:_,resolveFileByBasename:h===null?null:Eat(h),...h===null?{}:{resolveWikiFile:Ki(h)},resolveFolder:v,isExcludedFile:e=>s4(t.contentDir,c,e),resolveTolerantDocument:j2(p)});return{source:s,file:o,deadLinks:x.getDeadLinks(n,[s]).filter(e=>!b(e.target)),localTargets:[{source:s,assessments:S}]}}function kat(e){return{files:e.files.map(e=>({file:e.file,...Zee(e.diagnostics)})),fileCount:e.fileCount,errorCount:e.errorCount,warningCount:e.warningCount,warnings:e.warnings,...e.brokenLinkSuppression===void 0?{}:{brokenLinkSuppression:e.brokenLinkSuppression}}}function Aat(e,t){return e.kind===`validator`?`validator "${e.id}" failed: ${t}`:`source family "${e.sourceFamily}" validation failed: ${t}`}function jat(e,t){return`source family "${e}" validation degraded: ${t}`}function Mat(e){return[Fat(e),Iat(e),Dit(e)]}async function Nat(e,t={}){let n=await Promise.all(e.map(async e=>{let n=e.sourceFamilies;try{let r=await e.run(t);return{...r,ran:r.ran??n}}catch(t){if(t instanceof C2)throw t;q(`validation-audit`).error({err:t,validatorId:e.id},`[audit] validator threw; degrading to a plane warning`);let r=t instanceof Error?t.message:String(t);return{files:[],fileCount:0,warnings:[Aat(e.failureSourceFamily===void 0?{kind:`validator`,id:e.id}:{kind:`source-family`,sourceFamily:e.failureSourceFamily},r)],ran:n}}})),r=new Map,i=[],a=new Set,o=0,s=0;for(let e of n){i.push(...e.warnings);for(let t of e.ran??[])a.add(t);o+=e.suppressedBrokenLinkCount??0,s=Math.max(s,e.fileCount);for(let t of e.files){let e=r.get(t.file);e?e.push(...t.diagnostics):r.set(t.file,[...t.diagnostics])}}let c=[...r.entries()].map(([e,t])=>({file:e,diagnostics:t.sort(Pat)})).sort((e,t)=>e.file.localeCompare(t.file)),l=0,u=0;for(let e of c)for(let t of e.diagnostics)t.severity===`error`?l++:u++;let d=Xrt(o);return{files:c,fileCount:s,errorCount:l,warningCount:u,warnings:i,ran:[...a],...d===void 0?{}:{brokenLinkSuppression:d}}}function Pat(e,t){return e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character||e.source.localeCompare(t.source)||e.code.localeCompare(t.code)}function Fat(e){return{id:`lint`,sourceFamilies:Ia(e.baseConfig,{mode:`lint`}),async run(t){let n=await Lrt({projectDir:e.projectDir,contentDir:e.contentDir,baseConfig:e.baseConfig,targetPath:t.targetPath,resolvedScope:t.resolvedScope,liveSourceFor:e.liveSourceFor,cache:e.cache,auditGeneration:e.auditGeneration});return{files:n.files,fileCount:n.fileCount,warnings:n.warnings,ran:n.ran}}}}function Iat(e){let t=e.linkPolicy.links,n=e.linkPolicy.suppressLogLinkAdvisories;return{id:`links`,sourceFamilies:Ia(e.baseConfig,{mode:`audit`,linksValidation:t}).filter(e=>e===`links`),failureSourceFamily:`links`,async run(r){if(t===`off`||T2(r.resolvedScope??{path:W(e.contentDir,r.targetPath??``)},e.contentDir,r.targetPath)!==void 0)return{files:[],fileCount:0,warnings:[]};let i=t===`error`?`error`:`warning`;if(!e.derivedDocumentIndex)return{files:[],fileCount:0,warnings:[Aat({kind:`source-family`,sourceFamily:`links`},`backlink index is not configured`)]};let a=e.auditGeneration?.(),o=()=>{if(e.auditGeneration!==void 0&&e.auditGeneration()!==a)throw new C2},s=[...await e.admittedDocNames()],c={...r,resolvedScope:r.resolvedScope??E2(r.targetPath,e.contentDir)},l=Oat(c,e,s),u=l===void 0?zat(s,c.resolvedScope,e):[l.source],d=t=>l?.source===t?l.file:e.docFilePathFor(t)??`${t}.md`;if(u!==void 0&&u.length===0)return o(),{files:[],fileCount:0,warnings:[]};let f=l?.deadLinks??await e.derivedDocumentIndex.getDeadLinks(s,u),p=e=>tit(e,n),m=new Map,h=(e,t)=>{let n=m.get(e)??[];n.push(t),m.set(e,n)},g=[],_=new Set,v=new Set,y=[],b=0;try{let t=l?.localTargets??await e.derivedDocumentIndex.getLocalTargetAssessmentsForSources(u);for(let{source:e,assessments:n}of t){if(ZW(e))continue;let t=p(e),r=d(e);for(let a of n){let n=Rat(a,i);n&&(t?b++:g.push({file:r,diagnostic:n}),a.targetKind===`document`&&a.resolvedTarget!==null&&_.add(`${e}\0${a.resolvedTarget}`))}for(let t of n)t.status===`exact`&&t.resolvedTarget!==null&&v.add(`${e}\0${t.resolvedTarget}`)}}catch(e){if(e instanceof C2)throw e;q(`validation-audit`).warn({err:e},`[audit] local-target projection unavailable; preserving graph link findings`);let t=e instanceof Error?e.message:String(e);y.push(jat(`links`,`local-target projection unavailable: ${t}`))}for(let{target:e,sources:t}of f)for(let n of t){if(ZW(n.source))continue;let t=`${n.source}\0${e}`;if(n.sourceForm!==`wiki`&&(_.has(t)||v.has(t)))continue;if(p(n.source)){b++;continue}let r=d(n.source),a=n.line??0,o=n.column??0;h(r,{range:{start:{line:a,character:o},end:{line:a,character:o}},severity:i,source:`links`,code:`dead-link`,message:`Link target "${e}" does not resolve to an existing document.`,linkTarget:e})}for(let{file:e,diagnostic:t}of g)h(e,t);return o(),{files:[...m.entries()].map(([e,t])=>({file:e,diagnostics:t})),fileCount:0,warnings:y,...b>0?{suppressedBrokenLinkCount:b}:{}}}}}function Lat(e,t){let n=e.occurrence.role===`image`;return e.reason===`unresolvable`?n?`Image target "${t}" could not be resolved to a project-local file.`:`Link target "${t}" could not be resolved to a project-local target.`:e.reason===`excluded`?n?`Image target "${t}" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a "!" rule in .okignore.`:`Link target "${t}" exists but is excluded by .gitignore or .okignore. Re-include it, or its folder, with a "!" rule in .okignore.`:e.targetKind===`file`?n?`Image target "${t}" does not resolve to an existing file.`:`Link target "${t}" does not resolve to an existing file.`:`Link target "${t}" does not resolve to an existing document.`}function Rat(e,t){if(e.reason===null)return null;let{occurrence:n,targetKind:r}=e,i=wit(e,e.reason);if(i===null)return null;let a=e.resolvedTarget??n.href,o=n.line,s=n.column,c={range:{start:{line:o,character:s},end:{line:o,character:s}},severity:t,source:`links`,code:`dead-link`,message:Lat(e,a),localTarget:i};return r===`document`&&e.status===`missing`&&e.resolvedTarget!==null&&(c.linkTarget=e.resolvedTarget),c}function zat(e,t,n){let r=eG(U(n.contentDir,t.path));if(t.kind===`file`)return e.filter(e=>n.docFilePathFor(e)===r);if(r!==``)return e.filter(e=>n.docFilePathFor(e)?.startsWith(`${r}/`))}function Bat({homeDirOverride:e,log:t}){let n=0,r=null,i=null;function a(){n+=1}function o(e){let t=`${e?.projectDir??``}|${e&&`home`in e?e.home:``}`,r=Date.now();if(i!==null&&i.gen===n&&i.key===t&&r-i.at<5e3)return{freshBuild:!1,key:t,value:i.value};let a=WFe({...e,hashOf:Ktt});return i={at:Date.now(),gen:n,key:t,value:a},{freshBuild:!0,key:t,value:a}}function s(e){return o(e).value}function c(e){return r!==null&&r.fp!==e&&a(),r!==null&&r.gen===n&&r.fp===e&&Date.now()-r.at<5e3?{body:r.body}:null}function l(e,t){r={at:Date.now(),gen:n,fp:e,body:t}}let u=null;function d(r){let a=Date.now();if(u&&u.identity===r&&a-u.at<3e4)return u.byName;let s=new Map,c=null;try{c=o(e===void 0?{projectDir:r}:{home:e,projectDir:r}),s=$t(c.value.skills,Ktt)}catch(e){t.warn({err:e},`plugin upstream index failed; origins will be omitted`)}let l=Date.now();return c?.freshBuild===!0&&i?.gen===n&&i.key===c.key&&i.value===c.value&&(i.at=l),u={at:l,identity:r,byName:s},s}return{bumpSkillsCatalogGen:a,enumerateInstalledSkillsCached:s,readList:c,writeList:l,pluginSkillsByName:d}}function g4(e){return e.split(`/`).some(e=>{let t=e.toLowerCase();return t===`.ok`||t===`.git`})}function Vat(e,t){let{contentDir:n,contentFilter:r,docNameForPath:i}=t,a=[];try{if(!Ls(e).isDirectory())return a}catch(e){let t=rG(e);if(t===`ENOENT`||t===`ENOTDIR`)return a;throw e}function o(e){for(let t of Ms(e,{withFileTypes:!0})){let s=W(e,t.name),c=U(n,s).split(vs).join(`/`);if(g4(c))continue;if(t.isDirectory()){if(r?.isDirExcluded(c))continue;o(s);continue}if(!t.isFile()||!OW(c)||r?.isExcluded(c))continue;let l=i(c);IW(jW(c),ms(c)),a.push(l)}}return o(e),a.sort((e,t)=>e.localeCompare(t)),a}const _4=q(`tag-index`),Hat=ce();function Uat(e){if(typeof e!=`object`||!e)return!1;let{version:t}=e;return typeof t==`number`&&t!==2}function Wat(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.version!==2)return!1;let{docs:n,files:r}=t;if(typeof n!=`object`||!n||Array.isArray(n)||typeof r!=`object`||!r||Array.isArray(r))return!1;for(let e of Object.values(n))if(!Array.isArray(e)||!e.every(e=>typeof e==`string`&&e.length>0))return!1;for(let e of Object.values(r)){if(typeof e!=`object`||!e)return!1;let{mtimeMs:t,size:n}=e;if(typeof t!=`number`||typeof n!=`number`)return!1}return!0}function v4(){return{byTag:new Map,byDoc:new Map,byDocLiteral:new Map}}function Gat(e){return e.replace(/`[^`]*`/g,``)}function Kat(e){let t=e.replaceAll(`\r
1109
1109
  `,`
1110
1110
  `).split(`
1111
- `),n=[],r=!1,i=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){r?RegExp(`^\\s{0,3}${i[0]==="`"?"`":`~`}{${i.length},}\\s*$`).test(e)&&(r=!1,i=``):(r=!0,i=t[1]);continue}if(r)continue;let a=Gat(e);for(Hat.lastIndex=0;;){let e=Hat.exec(a);if(e===null)break;let t=e[2];t&&n.push(t)}}return n}var qat=class{contentDir;contentFilter;projectDir;state=v4();fileMeta=new Map;initChain=Promise.resolve();closed=!1;constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.projectDir=e.projectDir}snapshotPath(){return this.projectDir?W(Vq(this.projectDir),`cache`,`tags.json`):null}enqueue(e){let t=this.initChain.then(e);return this.initChain=t.then(()=>void 0,e=>{_4.warn({err:e},`queued tag-index task failed (chain cleared for next task)`)}),t}close(){return this.closed=!0,this.initChain}updateDocumentFromMarkdown(e,t){if(!XW(e))try{let{frontmatter:n,body:r}=ri(t),i=n?ci(n):``,a=nee(i),o=Kat(r),s=new Set([...a,...o]),c=new Set;for(let e of s)for(let t of dn(e))c.add(t);this.applyDocSnapshot(e,s,c)}catch(t){_4.warn({docName:e,err:t},`Failed to scan ${e} for tag extraction`),this.deleteDocument(e)}}deleteDocument(e){if(XW(e))return;let t=this.state.byDoc.get(e);if(t){for(let n of t){let t=this.state.byTag.get(n);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(n))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,n){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,n)}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 n=[];for(let r of t){let t=this.state.byDocLiteral.get(r);if(!t)continue;let i=Lte(t,e);n.push({docName:r,matchingTags:[...i].sort((e,t)=>e.localeCompare(t))})}return n.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),n=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&n.add(e.slice(0,t));let r=t;for(;r>0;)n.add(e.slice(0,r)),r=e.indexOf(`/`,r+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!n.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){return this.enqueue(()=>B2(`tag`,`full`,()=>this.initOnce()))}async initOnce(){if(this.closed||(this.state=v4(),this.fileMeta=new Map,!G(this.contentDir)))return;let e=await this.listDocsWithPaths();for(let t=0;t<e.length;t+=50){let n=e.slice(t,t+50),r=await Promise.all(n.map(async({docName:e,filePath:t})=>{try{let[n,r]=await Promise.all([ec(t),Xs(t,`utf-8`)]);return{docName:e,markdown:r,mtimeMs:n.mtimeMs,size:n.size}}catch(t){return _4.warn({docName:e,err:t},`Failed to read ${e} during init`),null}}));for(let e of r)if(e)try{this.updateDocumentFromMarkdown(e.docName,e.markdown),this.fileMeta.set(e.docName,{mtimeMs:e.mtimeMs,size:e.size})}catch(t){_4.warn({docName:e.docName,err:t},`Failed to index ${e.docName} during init`)}}}loadFromDisk(){return this.enqueue(()=>this.loadOnce())}async loadOnce(){if(this.closed)return!1;let e=this.snapshotPath();if(!e||!G(e))return!1;let t;try{t=await Xs(e,`utf-8`)}catch(e){return _4.warn({err:e},`Failed to read tag snapshot; falling back to full rebuild`),!1}let n;try{n=JSON.parse(t)}catch(t){return _4.warn({err:t},`Corrupt tag snapshot; rebuilding from disk`),await this.discardCorruptSnapshot(e,`malformed`),!1}if(Uat(n))return!1;if(!Wat(n))return _4.warn({},`Incomplete tag snapshot; rebuilding from disk`),await this.discardCorruptSnapshot(e,`incomplete`),!1;this.state=v4(),this.fileMeta=new Map(Object.entries(n.files));for(let[e,t]of Object.entries(n.docs)){if(XW(e))continue;let n=new Set(t),r=new Set;for(let e of n)for(let t of dn(e))r.add(t);this.applyDocSnapshot(e,n,r)}return!0}async discardCorruptSnapshot(e,t){try{await VH(e,{force:!0})}catch(e){_4.warn({reason:t,err:e},`Failed to discard corrupt tag snapshot`)}}saveToDisk(){return this.enqueue(()=>this.saveOnce())}async saveOnce(){if(this.closed)return;let e=this.snapshotPath();if(!e)return;let t={version:2,docs:Object.fromEntries([...this.state.byDocLiteral.entries()].map(([e,t])=>[e,[...t].sort((e,t)=>e.localeCompare(t))])),files:Object.fromEntries(this.fileMeta)};await UH(V(e),{recursive:!0}),await Lx(e,JSON.stringify(t,null,2),{fs:tU})}reconcileWithDisk(){return this.enqueue(()=>B2(`tag`,`reconcile`,()=>this.reconcileOnce(),e=>({"index.added":e.added,"index.updated":e.updated,"index.deleted":e.deleted})))}async reconcileOnce(){if(this.closed||!G(this.contentDir))return{added:0,updated:0,deleted:0};let e=await this.listDocsWithPaths(),t=new Set(e.map(e=>e.docName)),n=new Map,r=0,i=0,a=[],o=await Promise.allSettled(e.map(async({docName:e,filePath:t})=>{let n=await ec(t);return{docName:e,filePath:t,meta:{mtimeMs:n.mtimeMs,size:n.size}}}));for(let e of o){if(e.status===`rejected`)continue;let{docName:t,filePath:r,meta:i}=e.value,o=this.fileMeta.get(t);if(o!==void 0&&o.mtimeMs===i.mtimeMs&&o.size===i.size){n.set(t,i);continue}a.push({docName:t,filePath:r,meta:i,isNew:o===void 0})}for(let e=0;e<a.length;e+=50){let t=a.slice(e,e+50),o=await Promise.allSettled(t.map(async({docName:e,meta:t,isNew:n,filePath:r})=>({docName:e,meta:t,isNew:n,markdown:await Xs(r,`utf-8`)})));for(let e of o){if(e.status===`rejected`){_4.warn({err:e.reason},`Failed to reconcile file`);continue}let{docName:t,meta:a,isNew:o,markdown:s}=e.value;this.updateDocumentFromMarkdown(t,s),n.set(t,a),o?r++:i++}}let s=0,c=new Set([...this.fileMeta.keys(),...this.state.byDoc.keys()]);for(let e of c)t.has(e)||(this.deleteDocument(e),s++);return this.fileMeta=n,{added:r,updated:i,deleted:s}}applyDocSnapshot(e,t,n){let r=this.state.byDoc.get(e)??new Set;for(let t of r){if(n.has(t))continue;let r=this.state.byTag.get(t);r&&(r.delete(e),r.size===0&&this.state.byTag.delete(t))}for(let t of n){let n=this.state.byTag.get(t);n||(n=new Set,this.state.byTag.set(t,n)),n.add(e)}n.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,n),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)&&(t.add(e),!0))}async walkContentDir(e,t){let n;try{n=await Zs(e,{withFileTypes:!0})}catch(t){_4.warn({dir:e,err:t},`Failed to read directory ${e}`);return}for(let r of n){let n=H(e,r.name);if(r.isDirectory()){let e=eG(U(this.contentDir,n));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(n,t);continue}if(!r.isFile()||!OW(r.name))continue;let i=eG(U(this.contentDir,n));this.contentFilter?.isExcluded(i)||t.push({docName:jW(i),filePath:n})}}};const y4=q(`derived-document-index`);function Jat(e){return typeof e==`string`&&Nc(e)}function b4(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}var Yat=class extends Error{constructor(){super(`Derived document index is closed`),this.name=`DerivedDocumentIndexClosedError`}};function x4(e){return e instanceof Yat}var Xat=class extends Error{constructor(){super(`Local-target index is not ready`),this.name=`LocalTargetIndexNotReadyError`}};function Zat(e){return e instanceof Xat}var Qat=class{testOnly;backlinkIndex;tagIndex;localTargetIndex;contentFilter;getGlobalSkillRoots;getLocalTargetInventory;signalChannel;onRecoveredFileTarget;startupAdmission=b4();readyBarrier=b4();tail=Promise.resolve();saveTimer=null;localTargetRebuildRetryTimer=null;localTargetFileExistenceTimer;localTargetRebuildRetryAttempt=0;graphFileTargetsSource=null;graphFileTargets=null;startupBranch=null;graphBuiltWithoutFileOracle=!1;saveTagsOnNextDebounce=!1;branchTransition=null;startupBegun=!1;startupBegunAt=0;startupSettled=!1;ready=!1;liveUpdateToken=0;lastSignaledLocalTargetGeneration=0;closed=!1;closePromise=null;constructor(e){this.backlinkIndex=new a4({projectDir:e.projectDir,contentDir:e.contentDir,contentFilter:e.contentFilter,getFileOracle:()=>this.graphFileOracle()}),this.tagIndex=new qat({projectDir:e.projectDir,contentDir:e.contentDir,contentFilter:e.contentFilter}),this.localTargetIndex=new yat({contentDir:e.contentDir,contentFilter:e.contentFilter}),this.contentFilter=e.contentFilter,this.getGlobalSkillRoots=e.getGlobalSkillRoots,this.getLocalTargetInventory=e.getLocalTargetInventory??(()=>({documentTargets:[],fileTargets:[],folderTargets:[]})),this.signalChannel=e.signalChannel,this.onRecoveredFileTarget=e.onRecoveredFileTarget,this.testOnly={resetDocumentForTest:e=>this.resetDocumentForTest(e),rescanBacklinksForTest:()=>this.rescanBacklinksForTest()},this.localTargetFileExistenceTimer=setInterval(()=>{this.closed||!this.startupSettled||!this.localTargetIndex.isReady()||this.runCommand(async()=>{let e=await this.localTargetIndex.reconcileDependentFileTargetsFromDisk(this.onRecoveredFileTarget);this.maybeSignalLocalTargets(),e>0&&this.signalChannel(`files`)}).catch(e=>{this.closed||y4.warn({err:e},`[local-target] dependent file-existence sweep failed`)})},5e3),this.localTargetFileExistenceTimer.unref?.()}beginStartup(e){if(this.assertOpen(),this.startupBegun)throw Error(`Derived document index startup has already begun`);this.startupBegun=!0,this.startupBegunAt=performance.now(),this.startupBranch=e,this.backlinkIndex.switchBranch(e);let t=Promise.withResolvers(),n=this.initializeBacklinks(e,t.resolve),r=this.warmTags();return this.tail=Promise.all([n.then(()=>void 0),r]).then(()=>void 0),this.startupAdmission.resolve(),{backlinksReady:n,offlineDeletionsReady:t.promise}}async settleStartupAfterWatcherSeed(){if(this.assertOpen(),!this.startupBegun)throw Error(`Derived document index startup has not begun`);if(this.startupSettled)throw Error(`Derived document index startup has already settled`);this.startupSettled=!0;try{return await this.enqueueInternal(async()=>{let e=!1;try{let e=await this.tagIndex.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&y4.info(e,`[tag-index] startup reconcile: offline changes applied`),await this.saveTagsLogOnly(`startup`)}catch(t){y4.error({err:t},`[tag-index] startup reconcile failed; tag index updates incrementally via watcher events`),e=!0}return await this.rebuildLocalTargets(`startup`)&&this.syncLocalTargetBaseline(),this.startupBranch!==null&&await this.reconcileGraphWithFileInventory(this.startupBranch),{tagIndexDegraded:e}})}finally{this.ready=!0,this.readyBarrier.resolve();let e=Math.round(performance.now()-this.startupBegunAt);(e>=1e4?y4.info:y4.debug).call(y4,{startupMs:e},`[derived-index] startup settled; deferred link checks resume`)}}async beginBranchSwitch(e){if(this.assertOpen(),this.branchTransition)throw Error(`Derived document index branch switch already active`);let t={branch:e,barrier:b4()};this.liveUpdateToken++,this.branchTransition=t,this.cancelScheduledSave();try{return await this.startupAdmission.promise,await this.readyBarrier.promise,this.assertOpen(),await this.enqueueInternal(async()=>{this.backlinkIndex.switchBranch(e)}),t}catch(e){throw this.releaseBranchTransition(t),e}}async settleBranchFromDisk(e){if(this.assertOpen(),this.branchTransition!==e)throw Error(`No derived document index branch switch is active`);try{await this.enqueueInternal(async()=>{let t=e.branch;if(await this.backlinkIndex.loadFromDisk(t)){let e=await this.backlinkIndex.reconcileWithDisk(t);(e.added>0||e.updated>0||e.deleted>0)&&y4.info(e,`[backlinks] branch-switch reconcile for ${t}`)}else await this.backlinkIndex.rebuildFromDisk(t);let n=!1,r;try{await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots(),t)}catch(e){n=!0,r=e}await this.saveBacklinksLogOnly(`branch-switch`,t);try{let e=await this.tagIndex.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&y4.info(e,`[tag-index] branch-switch reconcile for ${t}`)}catch(e){y4.warn({err:e,branch:t},`[tag-index] branch-switch reconcile failed; falling back to full rebuild`),await this.tagIndex.init()}if(await this.saveTagsLogOnly(`branch-switch`),await this.rebuildLocalTargets(`branch-switch`)&&this.syncLocalTargetBaseline(),n)throw r})}finally{this.releaseBranchTransition(e)}}abortBranchSwitch(e){e&&this.releaseBranchTransition(e)}captureLiveUpdateToken(){return this.closed?null:this.liveUpdateToken}recordLiveDocument(e,t,n){return this.closed||n!==this.liveUpdateToken?Promise.resolve():this.runCommand(async()=>{n===this.liveUpdateToken&&(this.updateBoth(e,t),this.signalAllRelations())})}recordDurableStore(e,t){return this.runCommand(async()=>{this.updateBacklinks(e,t),this.scheduleSave(!1)})}recordDiskUpsert(e,t){return this.runCommand(async()=>{this.updateBoth(e,t),this.reconcileLocalTargetInventory(),this.scheduleSave(),this.signalAllRelations()})}recordDiskDelete(e){return this.runCommand(async()=>{this.deleteBoth(e),this.reconcileLocalTargetInventory(),this.scheduleSave(),this.signalAllRelations()})}recordDiskRename(e,t,n){return this.runCommand(async()=>{this.renameBoth(e,t,n),this.reconcileLocalTargetInventory(),this.scheduleSave(),this.signalAllRelations()})}recordInventoryReconciled(){return this.runCommand(async()=>{this.reconcileLocalTargetInventory(),this.maybeSignalLocalTargets()})}recordFileTargetUpsert(e){return this.runCommand(async()=>{let t=this.reconcileLocalTargetInventory();(t===null||!t.fileTargets.includes(e))&&this.localTargetIndex.setFileTarget(e,!0),this.maybeSignalLocalTargets()})}recordFileTargetDelete(e){return this.runCommand(async()=>{let t=this.reconcileLocalTargetInventory();(t===null||t.fileTargets.includes(e))&&this.localTargetIndex.setFileTarget(e,!1),this.maybeSignalLocalTargets()})}recordDirectDocument(e,t){return this.recordDirectMutations([{kind:`upsert`,documentName:e,markdown:t}])}recordDirectDelete(e){return this.recordDirectMutations([{kind:`delete`,documentName:e}])}recordDirectRename(e,t,n){return this.recordDirectMutations([{kind:`rename`,oldDocumentName:e,newDocumentName:t,markdown:n}])}recordLinkRewrite(e,t){return this.runCommand(async()=>{this.updateBacklinks(e,t),this.scheduleSave(!1),this.signalBacklinks()})}recordDirectMutations(e){return e.length===0?Promise.resolve():this.runCommand(async()=>{let t=!1;for(let n of e)switch(n.kind){case`upsert`:this.updateBoth(n.documentName,n.markdown),t=!0;break;case`delete`:this.deleteBoth(n.documentName),t=!0;break;case`rename`:this.renameBoth(n.oldDocumentName,n.newDocumentName,n.markdown),t=!0;break;case`link-rewrite`:this.updateBacklinks(n.documentName,n.markdown)}t?(this.reconcileLocalTargetInventory(),await this.saveBothLogOnly(`direct-batch`),this.signalAllRelations()):(await this.saveBacklinksLogOnly(`direct-batch`),this.signalBacklinks())})}refreshGlobalSkillNodes(){return this.runCommand(async()=>{await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots()),this.reconcileLocalTargetInventory(),this.signalBacklinks()})}refreshContentScope(){return this.runCommand(async()=>{let e=this.backlinkIndex.getActiveBranch(),t=await this.backlinkIndex.reconcileWithDisk(e),n=!1,r;try{await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots(),e)}catch(e){n=!0,r=e}await this.tagIndex.reconcileWithDisk(),this.reconcileLocalTargetInventory();for(let{docName:e,filePath:n}of t.changedDocs)try{this.localTargetIndex.setSource(e,await Xs(n,`utf-8`))}catch{this.localTargetIndex.removeSource(e)}for(let e of t.deletedDocNames)this.localTargetIndex.removeSource(e);if(await this.saveBothLogOnly(`content-filter`,e),this.signalAllRelations(),n)throw r})}announceReadyViews(){this.assertOpen(),this.signalAllRelations()}isReady(){return this.ready&&!this.closed}getBacklinks(e){return this.runQuery(()=>this.backlinkIndex.getBacklinks(e))}getBacklinkCount(e){return this.runQuery(()=>this.backlinkIndex.getBacklinkCount(e))}getBacklinkCounts(e){return this.runQuery(()=>Object.fromEntries(e.map(e=>[e,this.backlinkIndex.getBacklinkCount(e)])))}getForwardLinkEntries(e){return this.runQuery(()=>this.backlinkIndex.getForwardLinkEntries(e))}getLinkGraphNeighborhood(e,t){return this.runQuery(()=>this.backlinkIndex.getLinkGraphNeighborhood(e,t))}getLinkGraph(){return this.runQuery(()=>this.backlinkIndex.getLinkGraph())}getHubs(e){return this.runQuery(()=>this.backlinkIndex.getHubs(e))}getOrphans(e,t){return this.runQuery(()=>this.backlinkIndex.getOrphans(e,t))}getDeadLinks(e,t){return this.runQuery(()=>this.backlinkIndex.getDeadLinks(e,t,void 0,this.getLocalTargetInventory()?.folderTargets))}getIndexedDocNames(){return this.runQuery(()=>this.backlinkIndex.getIndexedDocNames())}getRenameSourceInventory(){return this.runQuery(()=>this.backlinkIndex.getRenameSourceInventory())}getAllTags(){return this.runQuery(()=>this.tagIndex.getAllTags())}getDocsForTagWithMatches(e){return this.runQuery(()=>this.tagIndex.getDocsForTagWithMatches(e))}getLocalTargetAssessments(e){return this.runLocalTargetQuery(()=>this.localTargetIndex.getAssessments(e))}getLocalTargetAssessmentsForSources(e){return this.runLocalTargetQuery(()=>this.localTargetIndex.getAssessmentsForSources(e))}getLocalTargetGeneration(){return this.runLocalTargetQuery(()=>this.localTargetIndex.generation)}readLocalTargetGeneration(){return this.localTargetIndex.freshnessToken}getLocalTargetStats(){return this.runLocalTargetQuery(()=>this.localTargetIndex.getStats())}getLocalTargetDocumentDependents(e){return this.runLocalTargetQuery(()=>this.localTargetIndex.getDocumentDependents(e))}getLocalTargetFileDependents(e){return this.runLocalTargetQuery(()=>this.localTargetIndex.getFileDependents(e))}close(){if(this.closePromise)return this.closePromise;let e=this.cancelScheduledSave();return e!==null&&this.enqueueInternal(()=>this.saveScheduledCache(e,`close-flush`)),this.closed=!0,clearInterval(this.localTargetFileExistenceTimer),this.cancelLocalTargetRebuildRetry(),this.localTargetIndex.close(),this.startupAdmission.resolve(),this.readyBarrier.resolve(),this.releaseBranchTransition(this.branchTransition),this.closePromise=this.tail.then(()=>this.tagIndex.close()).then(()=>void 0,()=>void 0),this.closePromise}resetDocumentForTest(e){return this.runCommand(async()=>{this.deleteBoth(e),await this.saveBothLogOnly(`test-reset`),this.signalAllRelations()})}rescanBacklinksForTest(){return this.runCommand(async()=>{let e=this.backlinkIndex.getActiveBranch();await this.backlinkIndex.rebuildFromDisk(e),await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots(),e),this.reconcileLocalTargetInventory(),await this.saveBacklinksLogOnly(`test-rescan`,e),this.signalBacklinks()})}async initializeBacklinks(e,t){try{if(this.graphFileOracle(),await this.backlinkIndex.loadFromDisk(e)){let n=await this.backlinkIndex.reconcileWithDisk(e);t(n.deletedDocNames),(n.added>0||n.updated>0||n.deleted>0)&&y4.info({added:n.added,updated:n.updated,deleted:n.deleted},`[backlinks] startup reconcile`)}else t([]),await this.backlinkIndex.rebuildFromDisk(e);return await this.ingestGlobalSkillNodesLogOnly(e,`startup`),await this.saveBacklinksLogOnly(`startup`,e),{backlinkIndexDegraded:!1}}catch(n){return t([]),y4.error({err:n,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`),{backlinkIndexDegraded:!0}}}async warmTags(){try{await this.tagIndex.loadFromDisk()?await this.tagIndex.reconcileWithDisk():await this.tagIndex.init()}catch(e){y4.warn({err:e},`[derived-document-index] tag-index warm boot failed; continuing with stale or empty index`)}}updateBoth(e,t){this.updateBacklinks(e,t),this.isAdmitted(e)?this.tagIndex.updateDocumentFromMarkdown(e,t):this.tagIndex.deleteDocument(e)}updateBacklinks(e,t){this.isAdmitted(e)?(this.backlinkIndex.updateDocumentFromMarkdown(e,t),this.localTargetIndex.setSource(e,t)):(this.backlinkIndex.deleteDocument(e),this.localTargetIndex.removeSource(e))}deleteBoth(e){this.backlinkIndex.deleteDocument(e),this.tagIndex.deleteDocument(e),this.localTargetIndex.removeSource(e)}renameBoth(e,t,n){this.isAdmitted(t)?(this.backlinkIndex.renameDocument(e,t,n),this.tagIndex.renameDocument(e,t,n),this.localTargetIndex.renameSource(e,t,n)):(this.backlinkIndex.deleteDocument(e),this.backlinkIndex.deleteDocument(t),this.tagIndex.deleteDocument(e),this.tagIndex.deleteDocument(t),this.localTargetIndex.removeSource(e),this.localTargetIndex.removeSource(t))}isAdmitted(e){return XW(e)?!1:GW(e)?!0:!this.contentFilter.isExcluded(BW(e))}signalBacklinks(){this.signalChannel(`backlinks`),this.signalChannel(`graph`),this.maybeSignalLocalTargets()}signalAllRelations(){this.signalBacklinks(),this.signalChannel(`tags`)}maybeSignalLocalTargets(){let e=this.localTargetIndex.generation,t=e-this.lastSignaledLocalTargetGeneration;t!==0&&(Uit(`local-target`,`signal`,t),this.lastSignaledLocalTargetGeneration=e,this.signalChannel(`local-targets`))}graphFileOracle(){let e=this.getLocalTargetInventory();if(!e){this.graphBuiltWithoutFileOracle=!0;return}this.graphFileTargetsSource!==e.fileTargets&&(this.graphFileTargetsSource=e.fileTargets,this.graphFileTargets=ra(`file`,e.fileTargets));let t=this.graphFileTargets;return t?{hasFile:e=>t.resolve(e)!==void 0}:void 0}async reconcileGraphWithFileInventory(e){if(this.graphBuiltWithoutFileOracle&&this.graphFileOracle()){this.graphBuiltWithoutFileOracle=!1;try{await this.backlinkIndex.rebuildFromDisk(e),await this.saveBacklinksLogOnly(`file-inventory-reconcile`,e),this.signalChannel(`backlinks`),this.signalChannel(`graph`)}catch(t){this.graphBuiltWithoutFileOracle=!0,y4.warn({err:t,branch:e},`[backlinks] file-inventory reconciliation failed; graph retains its startup extraction`)}}}async rebuildLocalTargets(e){try{let t=this.getLocalTargetInventory();if(t===null)return this.localTargetIndex.markUnavailable(),y4.warn({reason:e},`[local-target] watcher inventory unavailable; index remains not ready`),!1;let n={documentTargets:new Set([...this.backlinkIndex.getIndexedDocNames(),...t.documentTargets]),fileTargets:t.fileTargets};return await this.localTargetIndex.rebuildFromDisk(n),this.localTargetRebuildRetryAttempt=0,this.cancelLocalTargetRebuildRetry(),!0}catch(t){return y4.warn({err:t,reason:e},`[local-target] rebuild failed; retaining the last complete snapshot and scheduling recovery`),this.scheduleLocalTargetRebuildRetry(e),!1}}reconcileLocalTargetInventory(){let e=this.getLocalTargetInventory();return e===null?(this.localTargetIndex.markUnavailable(),null):(this.localTargetIndex.reconcileDocumentTargets(new Set([...this.backlinkIndex.getIndexedDocNames(),...e.documentTargets])),this.localTargetIndex.reconcileFileTargets(e.fileTargets),this.localTargetIndex.reconcileFolderTargets(e.folderTargets),e)}syncLocalTargetBaseline(){let e=this.localTargetIndex.generation,t=e-this.lastSignaledLocalTargetGeneration;t>0&&Uit(`local-target`,`baseline`,t),this.lastSignaledLocalTargetGeneration=e}scheduleLocalTargetRebuildRetry(e){if(this.closed||this.localTargetRebuildRetryTimer!==null)return;let t=Math.min(1e3*2**this.localTargetRebuildRetryAttempt,3e4);this.localTargetRebuildRetryAttempt++,this.localTargetRebuildRetryTimer=setTimeout(()=>{this.localTargetRebuildRetryTimer=null,this.runCommand(async()=>{await this.rebuildLocalTargets(`retry:${e}`)&&this.maybeSignalLocalTargets()}).catch(t=>{this.closed||y4.warn({err:t,reason:e},`[local-target] recovery enqueue failed`)})},t),this.localTargetRebuildRetryTimer.unref?.()}cancelLocalTargetRebuildRetry(){this.localTargetRebuildRetryTimer!==null&&(clearTimeout(this.localTargetRebuildRetryTimer),this.localTargetRebuildRetryTimer=null)}scheduleSave(e=!0){let t=this.saveTagsOnNextDebounce||e;this.cancelScheduledSave(),this.saveTagsOnNextDebounce=t,this.saveTimer=setTimeout(()=>{this.saveTimer=null;let e=this.saveTagsOnNextDebounce;this.saveTagsOnNextDebounce=!1,this.enqueueInternal(()=>this.saveScheduledCache(e,`debounced`)).catch(e=>{y4.warn({err:e},`Failed to enqueue debounced derived-index cache save`)})},2e3)}cancelScheduledSave(){let e=this.saveTimer===null?null:this.saveTagsOnNextDebounce;return this.saveTimer!==null&&clearTimeout(this.saveTimer),this.saveTimer=null,this.saveTagsOnNextDebounce=!1,e}saveScheduledCache(e,t){return e?this.saveBothLogOnly(t):this.saveBacklinksLogOnly(`${t}-backlinks`)}releaseBranchTransition(e){let t=this.branchTransition;!e||t!==e||(this.branchTransition=null,t.barrier.resolve())}async saveBothLogOnly(e,t){await this.saveBacklinksLogOnly(e,t),await this.saveTagsLogOnly(e)}async saveBacklinksLogOnly(e,t){try{await this.backlinkIndex.saveToDisk(t)}catch(n){y4.warn({err:n,reason:e,branch:t},`Failed to persist backlink cache`)}}async saveTagsLogOnly(e){try{await this.tagIndex.saveToDisk()}catch(t){y4.warn({err:t,reason:e},`Failed to persist tag snapshot`)}}async ingestGlobalSkillNodesLogOnly(e,t){try{await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots(),e)}catch(n){y4.warn({err:n,branch:e,reason:t},`Global skill bundle ingest failed`)}}async runCommand(e){return this.assertOpen(),await this.startupAdmission.promise,this.assertOpen(),this.enqueueAfterBranchAdmission(e)}async runQuery(e){return this.assertOpen(),await this.startupAdmission.promise,await this.readyBarrier.promise,this.assertOpen(),this.enqueueAfterBranchAdmission(e)}runLocalTargetQuery(e){return this.runQuery(()=>{if(!this.localTargetIndex.isReady())throw new Xat;return e()})}async enqueueAfterBranchAdmission(e){for(;;){let t=this.branchTransition;if(!t)return this.assertOpen(),this.enqueueInternal(()=>(this.assertOpen(),e()));await t.barrier.promise,this.assertOpen()}}enqueueInternal(e){let t=this.tail.then(e);return this.tail=t.then(()=>void 0,e=>{x4(e)?y4.debug({err:e},`Derived document index operation rejected after close`):y4.warn({err:e},`Derived document index operation failed; queue remains available`)}),t}assertOpen(){if(this.closed)throw new Yat}};function $at(e){throw Error(`[StorePublishOutcome] unhandled variant: ${JSON.stringify(e)}`)}function eot(e){throw Error(`[DeferredStoreWait] unhandled variant: ${JSON.stringify(e)}`)}const S4=`OK_DOC_REMOVED`,C4=2e4,w4=18e5;function tot(e){return e.reduce((e,t)=>Math.min(e,t.at+w4),1/0)}function T4(e){let t=[`{"version":1,"branches":{`];for(let[n,r]of Object.entries(Object.fromEntries(e))){t.length>1&&t.push(`,`),t.push(JSON.stringify(n),`:[`);for(let[e,n]of r.entries())e>0&&t.push(`,`),t.push(n);t.push(`]`)}return t.push(`}}`),t}function not(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&typeof e.then==`function`}function rot(e,t){let n;try{n=t instanceof Error?String(t.message):String(t)}catch{n=`unserializable rejection reason`}console.warn(JSON.stringify({event:`persistence-store-publish-async-rejected`,"doc.name":e.docName,generation:e.generation,error:n}))}function iot(e,t){return e?.docName===t?.docName&&e?.file===t?.file&&e?.diskHash===t?.diskHash&&e?.diskContent===t?.diskContent&&e?.retainedContent===t?.retainedContent&&e?.detectedAt===t?.detectedAt}var E4=class extends Error{kind;path;constructor(e,t,n){let r=n instanceof Error&&`code`in n&&typeof n.code==`string`?n.code:void 0,i=t===`unreadable`?r===`EACCES`||r===`EPERM`?`Check the snapshot and parent-directory permissions for the account running OpenKnowledge, then retry.`:r===`EISDIR`?`The snapshot path must be a regular file, not a directory. Preserve that directory and restore the snapshot file to this path.`:`Check the filesystem or mount and restore read access to this path, then retry.`:t===`incompatible`?`This build does not support the snapshot schema. Preserve the file and restore a compatible backup or contact support to identify a compatible build.`:`Restore this snapshot from a known-good backup, or contact support to recover its protected edits.`;super(`Cannot safely open this project: its stale-write recovery snapshot is ${t}${r?` [${r}]`:``} (${e}). The snapshot has been preserved because it may contain the only copy of protected edits. ${i} Run ok bug-report from the project directory to collect diagnostics without starting the server. Do not delete it to bypass recovery.`,{cause:n}),this.name=`DocumentDurabilityStateError`,this.kind=t,this.path=e}};function D4(e,t,n){n===void 0?e.delete(t):e.set(t,n)}function aot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.hash==`string`&&typeof t.at==`number`}function oot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.file==`string`&&typeof t.diskHash==`string`&&typeof t.diskContent==`string`&&typeof t.detectedAt==`string`&&(t.retainedContent===void 0||typeof t.retainedContent==`string`)}function sot(e){if(!e||typeof e!=`object`)return null;let t=e;if(t.version!==1||!t.branches||typeof t.branches!=`object`||Array.isArray(t.branches))return null;let n=new Map;for(let[e,r]of Object.entries(t.branches)){if(!Array.isArray(r))return null;let t=[];for(let e of r){if(!e||typeof e!=`object`)return null;let n=e;if(typeof n.docName!=`string`||typeof n.acknowledgedContent!=`string`||!Array.isArray(n.displacedVersions)||!n.displacedVersions.every(aot)||n.staleExternalWrite!==void 0&&(!oot(n.staleExternalWrite)||n.staleExternalWrite.docName!==n.docName||n.staleExternalWrite.diskHash!==_Y(n.staleExternalWrite.diskContent)))return null;t.push({docName:n.docName,acknowledgedContent:n.acknowledgedContent,displacedVersions:n.displacedVersions,...n.staleExternalWrite?{staleExternalWrite:n.staleExternalWrite}:{}})}n.set(e,t)}return{version:1,branches:Object.fromEntries(n)}}var O4=class{reconciledBaseByBranch=new Map;displacedVersionsByBranch=new Map;staleExternalWritesByBranch=new Map;inFlightFlushByDoc=new Map;storeAttemptGenerations=new Map;publishedStoreGenerations=new Map;documentsWithPublishInFlight=new Set;agentWriteStores=new Set;refusedStoreDocNames=new Set;storeFailures=new Map;storeDivergences=new Set;staleExternalWriteFreezes=new Set;persistencePath;fileForDocName;onStaleExternalWriteChange;onStoreRefused;hasResolvedExtension;cachedDocumentsByBranch=new Map;lastPersistedParts=T4(new Map);nextDisplacedExpiryAt=1/0;activeBranch;batchInProgress=!1;writeAdmissionHolds=0;writeAdmissionWaiters=new Set;writeWaitDeadline=new mc;deferredStoreOutcomes=new Map;constructor(e=`main`,t={}){this.activeBranch=e,this.persistencePath=t.persistencePath,this.fileForDocName=t.fileForDocName??(e=>`${e}.md`),this.onStaleExternalWriteChange=t.onStaleExternalWriteChange,this.onStoreRefused=t.onStoreRefused,this.hasResolvedExtension=t.hasResolvedExtension,this.reconciledBaseByBranch.set(e,new Map),this.restore()}switchReconciledBaseScope(e){this.persist(),this.activeBranch=e,this.reconciledBaseByBranch.has(e)||this.reconciledBaseByBranch.set(e,new Map)}getActiveBranch(){return this.activeBranch}getReconciledBase(e){return this.reconciledBaseByBranch.get(this.activeBranch)?.get(e)}setReconciledBase(e,t){let n=this.reconciledBaseByBranch.get(this.activeBranch);if(n||(n=new Map,this.reconciledBaseByBranch.set(this.activeBranch,n)),!(n.get(e)===t&&Date.now()<this.nextDisplacedExpiryAt)){if(!this.isPersistedDocument(e)){n.set(e,t);return}this.mutateDocument(e,()=>n.set(e,t))}}recordSuccessfulStore(e,t,n){if(n===void 0){this.setReconciledBase(e,t);return}let r=Date.now(),i=_Y(n);this.mutateDocument(e,()=>{let n=this.reconciledBaseByBranch.get(this.activeBranch);n||(n=new Map,this.reconciledBaseByBranch.set(this.activeBranch,n));let a=this.displacedVersionsByBranch.get(this.activeBranch);a||(a=new Map,this.displacedVersionsByBranch.set(this.activeBranch,a));let o=(a.get(e)??[]).filter(e=>e.at>r-18e5&&e.hash!==i);o.push({hash:i,at:r}),n.set(e,t),a.set(e,o.slice(-8))})}deleteReconciledBase(e){this.refusedStoreDocNames.delete(e),this.storeFailures.delete(e);let t=this.isPersistedDocument(e);if(!t){this.reconciledBaseByBranch.get(this.activeBranch)?.delete(e),this.inFlightFlushByDoc.delete(e);return}this.mutateDocument(e,()=>{this.reconciledBaseByBranch.get(this.activeBranch)?.delete(e),this.inFlightFlushByDoc.delete(e),this.displacedVersionsByBranch.get(this.activeBranch)?.delete(e),this.staleExternalWritesByBranch.get(this.activeBranch)?.delete(e)},t)}freshDisplacedVersions(e){let t=this.displacedVersionsByBranch.get(this.activeBranch),n=t?.get(e);if(!t||!n)return[];let r=Date.now()-w4,i=n.filter(e=>e.at>r);return i.length===n.length?n:(this.mutateDocument(e,()=>{i.length===0?t.delete(e):t.set(e,i)}),i)}recordDisplacedVersion(e,t){let n=_Y(t),r=this.freshDisplacedVersions(e).filter(e=>e.hash!==n);r.push({hash:n,at:Date.now()});let i=this.displacedVersionsByBranch.get(this.activeBranch);i||(i=new Map,this.displacedVersionsByBranch.set(this.activeBranch,i)),this.mutateDocument(e,()=>i.set(e,r.slice(-8)))}clearDisplacedVersions(e){this.displacedVersionsByBranch.get(this.activeBranch)?.has(e)&&this.mutateDocument(e,()=>this.displacedVersionsByBranch.get(this.activeBranch)?.delete(e))}isDisplacedVersion(e,t){let n=this.freshDisplacedVersions(e);if(n.length===0)return!1;let r=_Y(t);return n.some(e=>e.hash===r)}recordStaleExternalWrite(e,t,n){let r=this.staleExternalWritesByBranch.get(this.activeBranch);r||(r=new Map,this.staleExternalWritesByBranch.set(this.activeBranch,r));let i=_Y(t),a=r.get(e);if(a?.diskHash===i&&(n===void 0||n===a.retainedContent))return a;let o=a?.diskHash!==i,s=n??a?.retainedContent,c={docName:e,file:this.fileForDocName(e),diskHash:i,diskContent:t,...s===void 0?{}:{retainedContent:s},detectedAt:a?.diskHash===i?a.detectedAt:new Date().toISOString()};return this.mutateDocument(e,()=>r.set(e,c)),o&&sXe(),c}staleExternalWriteMatches(e,t){let n=this.staleExternalWritesByBranch.get(this.activeBranch)?.get(e);return n!==void 0&&n.diskHash===_Y(t)}listStaleExternalWrites(){return[...this.staleExternalWritesByBranch.get(this.activeBranch)?.values()??[]].map(e=>this.withResolvedFile(e))}getStaleExternalWrite(e){let t=this.staleExternalWritesByBranch.get(this.activeBranch)?.get(e);return t===void 0?void 0:this.withResolvedFile(t)}withResolvedFile(e){if(this.hasResolvedExtension&&!this.hasResolvedExtension(e.docName))return e;let t=this.fileForDocName(e.docName);return t===e.file?e:{...e,file:t}}clearStaleExternalWrite(e){let t=this.staleExternalWritesByBranch.get(this.activeBranch);t?.get(e)&&this.mutateDocument(e,()=>t?.delete(e))}restoreStaleExternalWrite(e,t){let n=this.staleExternalWritesByBranch.get(t);n||(n=new Map,this.staleExternalWritesByBranch.set(t,n)),!n.has(e.docName)&&this.mutateDocument(e.docName,()=>n.set(e.docName,e))}mutateDocument(e,t,n=!0){let r=this.reconciledBaseByBranch.get(this.activeBranch)??new Map,i=this.displacedVersionsByBranch.get(this.activeBranch)??new Map,a=this.staleExternalWritesByBranch.get(this.activeBranch)??new Map,o=r.get(e),s=i.get(e),c=a.get(e),l=this.inFlightFlushByDoc.get(e),u;try{u=t(),n&&this.persist()}catch(t){throw D4(r,e,o),D4(i,e,s),D4(a,e,c),D4(this.inFlightFlushByDoc,e,l),this.reconciledBaseByBranch.set(this.activeBranch,r),this.displacedVersionsByBranch.set(this.activeBranch,i),this.staleExternalWritesByBranch.set(this.activeBranch,a),t}return c!==a.get(e)&&this.onStaleExternalWriteChange?.(),u}isPersistedDocument(e){return this.displacedVersionsByBranch.get(this.activeBranch)?.has(e)===!0||this.staleExternalWritesByBranch.get(this.activeBranch)?.has(e)===!0}restore(){if(!this.persistencePath)return;let e;try{e=K(this.persistencePath,`utf-8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw new E4(this.persistencePath,`unreadable`,e)}let t;try{t=JSON.parse(e)}catch(e){throw new E4(this.persistencePath,`corrupt`,e)}if(t&&typeof t==`object`&&`version`in t&&t.version!==1)throw new E4(this.persistencePath,`incompatible`);let n=sot(t);if(!n)throw new E4(this.persistencePath,`corrupt`);let r=Date.now()-w4,i=new Map;for(let[e,t]of Object.entries(n.branches)){let n=new Map,a=new Map,o=new Map,s=new Map,c=[];for(let e of t){if(e.staleExternalWrite)try{this.fileForDocName(e.docName)}catch(e){throw new E4(this.persistencePath,`corrupt`,e)}let t=JSON.stringify(e);c.push(t);let i=tot(e.displacedVersions);this.nextDisplacedExpiryAt=Math.min(this.nextDisplacedExpiryAt,i);let l=e.displacedVersions.filter(e=>e.at>r);l.length===0&&!e.staleExternalWrite||(n.set(e.docName,e.acknowledgedContent),l.length>0&&a.set(e.docName,l),e.staleExternalWrite&&o.set(e.docName,e.staleExternalWrite),l.length===e.displacedVersions.length&&s.set(e.docName,{acknowledgedContent:e.acknowledgedContent,displacedVersions:a.get(e.docName),staleExternalWrite:e.staleExternalWrite?{...e.staleExternalWrite}:void 0,expiresAt:i,serialized:t}))}i.set(e,c),this.reconciledBaseByBranch.set(e,n),a.size>0&&this.displacedVersionsByBranch.set(e,a),o.size>0&&this.staleExternalWritesByBranch.set(e,o),s.size>0&&this.cachedDocumentsByBranch.set(e,s)}this.reconciledBaseByBranch.has(this.activeBranch)||this.reconciledBaseByBranch.set(this.activeBranch,new Map),this.lastPersistedParts=T4(i)}pruneExpiredDisplacedVersions(e){this.nextDisplacedExpiryAt=1/0;for(let[t,n]of this.displacedVersionsByBranch){for(let[t,r]of n){let i=r.filter(t=>t.at>e);i.length===0?n.delete(t):i.length!==r.length&&n.set(t,i);for(let e of i)this.nextDisplacedExpiryAt=Math.min(this.nextDisplacedExpiryAt,e.at+w4)}n.size===0&&this.displacedVersionsByBranch.delete(t)}}persist(){let e=Date.now()-w4;if(!this.persistencePath){this.pruneExpiredDisplacedVersions(e);return}let t=new Map,n=new Map,r=new Set([...this.displacedVersionsByBranch.keys(),...this.staleExternalWritesByBranch.keys()]);for(let i of r){let r=new Set([...this.displacedVersionsByBranch.get(i)?.keys()??[],...this.staleExternalWritesByBranch.get(i)?.keys()??[]]),a=[],o=new Map;for(let t of r){let n=this.reconciledBaseByBranch.get(i)?.get(t);if(n===void 0)continue;let r=this.displacedVersionsByBranch.get(i)?.get(t),s=this.staleExternalWritesByBranch.get(i)?.get(t),c=this.cachedDocumentsByBranch.get(i)?.get(t);if(c&&c.acknowledgedContent===n&&c.displacedVersions===r&&iot(c.staleExternalWrite,s)&&c.expiresAt>e+18e5){a.push(c.serialized),o.set(t,c);continue}let l=(r??[]).filter(t=>t.at>e);if(l.length===0&&!s)continue;let u={docName:t,acknowledgedContent:n,displacedVersions:l,...s?{staleExternalWrite:s}:{}},d=JSON.stringify(u);a.push(d),o.set(t,{acknowledgedContent:n,displacedVersions:r,staleExternalWrite:s?{...s}:void 0,expiresAt:tot(l),serialized:d})}a.length>0&&(t.set(i,a),n.set(i,o))}let i=T4(t);if(i.length===this.lastPersistedParts.length&&i.every((e,t)=>e===this.lastPersistedParts[t])){this.cachedDocumentsByBranch=n,this.pruneExpiredDisplacedVersions(e);return}let a=i.join(``);KH(V(this.persistencePath),{recursive:!0});let o=Fx(this.persistencePath);try{WH(o,a,{encoding:`utf-8`,mode:384,flag:`wx`}),qH(o,this.persistencePath),this.lastPersistedParts=i,this.cachedDocumentsByBranch=n}catch(e){try{G(o)&&XH(o)}catch(t){q(`document-durability-state`).warn({err:t,writeError:e instanceof Error?e.message:String(e),temporaryPath:o},`Unable to remove failed recovery snapshot temporary file`)}throw e}this.pruneExpiredDisplacedVersions(e)}freshInFlightFlushes(e){let t=this.inFlightFlushByDoc.get(e);if(!t)return[];let n=Date.now(),r=t.filter(e=>n-e.at<=6e4);return r.length===t.length?t:(SZe(t.length-r.length),r.length===0?this.inFlightFlushByDoc.delete(e):this.inFlightFlushByDoc.set(e,r),r)}beginInFlightFlush(e,t){let n=this.freshInFlightFlushes(e);n.push({value:t,at:Date.now()}),this.inFlightFlushByDoc.set(e,n)}peekInFlightFlush(e){let t=this.freshInFlightFlushes(e);return t[t.length-1]?.value}inFlightFlushCount(e){return this.freshInFlightFlushes(e).length}hasInFlightFlush(e,t){return this.freshInFlightFlushes(e).some(e=>e.value===t)}finishInFlightFlush(e,t){let n=this.freshInFlightFlushes(e);for(let r=n.length-1;r>=0;r--)if(n[r]?.value===t){n.splice(r,1),n.length===0&&this.inFlightFlushByDoc.delete(e);return}}beginStoreAttempt(e){let t=(this.storeAttemptGenerations.get(e)??0)+1;return this.storeAttemptGenerations.set(e,t),{docName:e,generation:t}}tryPublishStore(e,t){if(this.documentsWithPublishInFlight.has(e.docName))return`reentrant`;let n=this.publishedStoreGenerations.get(e.docName)??0;if(e.generation<=n)return`stale`;this.documentsWithPublishInFlight.add(e.docName);try{let n=t();if(not(n)){try{n.then(()=>{},t=>rot(e,t))}catch{}throw TypeError(`tryPublishStore: the publish callback must complete synchronously, but it returned a thenable (${e.docName} generation ${e.generation})`)}return this.publishedStoreGenerations.set(e.docName,e.generation),`published`}finally{this.documentsWithPublishInFlight.delete(e.docName)}}setBatchInProgress(e){this.batchInProgress=e}isBatchInProgress(){return this.batchInProgress}holdWriteAdmission(){this.writeAdmissionHolds++;let e=!1;return()=>{if(e||(e=!0,this.writeAdmissionHolds--,this.writeAdmissionHolds>0))return;let t=[...this.writeAdmissionWaiters];this.writeAdmissionWaiters.clear();for(let e of t)e()}}isWriteAdmissionHeld(){return this.writeAdmissionHolds>0}runWithinWriteWaitBudget(e,t=C4){return this.writeWaitDeadline.run(Date.now()+t,e)}remainingWriteWait(e){let t=this.writeWaitDeadline.getStore();return t===void 0?e:Math.max(0,Math.min(e,t-Date.now()))}async whenWriteAdmitted(e=C4){if(!this.isWriteAdmissionHeld())return!0;let t=this.remainingWriteWait(e);if(t===0)return!1;let n=()=>{},r=!1,i=setTimeout(()=>{r=!0,n()},t);try{for(;this.isWriteAdmissionHeld()&&!r;)await new Promise(e=>{n=e,this.writeAdmissionWaiters.add(e)}),this.writeAdmissionWaiters.delete(n);return!this.isWriteAdmissionHeld()}finally{clearTimeout(i)}}openDeferredStore(e){let{promise:t,resolve:n}=Promise.withResolvers();return this.deferredStoreOutcomes.set(e,t),{settle:r=>{this.deferredStoreOutcomes.get(e)===t&&this.deferredStoreOutcomes.delete(e),n(r)}}}async awaitDeferredStoreOutcome(e,t=C4){let n=this.deferredStoreOutcomes.get(e);if(n===void 0||!this.isWriteAdmissionHeld())return;let r={kind:`unsettled`},i=this.remainingWriteWait(t);if(i===0)return r;let a,o=new Promise(e=>{a=setTimeout(()=>e(r),i)});try{return await Promise.race([n,o])}finally{clearTimeout(a)}}markAgentWriteStore(e){this.agentWriteStores.add(e)}consumeAgentWriteStore(e){return this.agentWriteStores.delete(e)}markStoreRefused(e){this.refusedStoreDocNames.add(e),this.onStoreRefused?.(e)}clearStoreRefused(e){this.refusedStoreDocNames.delete(e)}isStoreRefused(e){return this.refusedStoreDocNames.has(e)}getRefusedStoreDocNames(){return[...this.refusedStoreDocNames]}recordStoreFailure(e,t){this.storeFailures.set(e,t)}clearStoreFailure(e){this.storeFailures.delete(e)}takeStoreFailure(e){let t=this.storeFailures.get(e)??null;return this.storeFailures.delete(e),t}recordStoreDivergence(e){this.storeDivergences.add(e)}takeStoreDivergence(e){return this.storeDivergences.delete(e)}recordStaleExternalWriteFreeze(e){this.staleExternalWriteFreezes.add(e)}takeStaleExternalWriteFreeze(e){return this.staleExternalWriteFreezes.delete(e)}};const k4=3000000000n,cot=()=>BigInt(Date.now())*1000000n,A4=e=>`${e.dev}:${e.ino}:${e.size}:${e.mtimeNs}:${e.ctimeNs}`,j4=(e,t)=>e.ctimeNs+k4>t||e.mtimeNs+k4>t&&e.mtimeNs<=t+k4,lot=/^[ -~]*$/,uot=new Map,M4=new Map;function dot(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function fot(e){let t=cot();try{let n=Ls(e,{bigint:!0});return{signature:A4(n),racy:j4(n,t)}}catch(e){if(e.code===`ENOENT`)return null;throw e}}function pot(e){let t=new Set;for(let n of e){let e=n;for(;e!==``&&!t.has(e);)t.add(e),e=dot(e)}return t}async function mot(e,t,n){let r=W(t),i=uot.get(r);i===void 0&&(i=W(r,(await e.raw(`rev-parse`,`--git-path`,`index`)).trim()),uot.set(r,i));let a=fot(i);if(a===null)return M4.delete(r),!1;let o=dot(n),s=M4.get(r),c=!a.racy&&lot.test(n);return c&&s?.indexSignature===a.signature&&s.scope===o?(s.listing??=pot(await aU(e,[`ls-files`,...o===``?[]:Bt([o])])),s.listing.has(n)):(c&&M4.set(r,{indexSignature:a.signature,scope:o,listing:void 0}),(await aU(e,[`ls-files`,...Bt([n])])).length>0)}function hot(e){let{assetService:t,log:n}=e,r={"missing-path":[400,`urn:ok:error:invalid-request`,`Missing asset path.`],"unsupported-type":[415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`],"not-found":[404,`urn:ok:error:asset-not-found`,`Asset not found.`],"invalid-path":[400,`urn:ok:error:invalid-request`,`Invalid asset path.`]},i=Z(me,async(e,i)=>{try{let a=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`),o=t.resolveServableAsset(a);if(!o.ok){let[e,t,n]=r[o.reason];X(i,e,t,n,{handler:`asset`,...o.cause===void 0?{}:{cause:o.cause}});return}let{asset:s}=o,c={"Content-Type":s.contentType,"Content-Length":String(s.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":s.disposition,"Cache-Control":`no-store`};s.csp!==null&&(c[`Content-Security-Policy`]=s.csp);let l=s.canonicalPath;i.writeHead(200,c);try{await hc(Es(l),i)}catch(e){let t=to.getActiveSpan(),r=rG(e),o=r===`ERR_STREAM_PREMATURE_CLOSE`||r===`ECONNRESET`||r===`EPIPE`;t?.setAttribute(Ny,o?`connection_closed`:`stream_failure`),t?.recordException(e instanceof Error?e:String(e)),t?.setStatus({code:ao.ERROR,message:`Asset transfer incomplete`}),n.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:a,err:e},`[asset] pipeline failed mid-stream`),i.destroyed||i.destroy(e instanceof Error?e:void 0)}}catch(e){X(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),a=1048576;return P$({"/api/asset":i,"/api/asset-text":Z(me,async(e,n)=>{try{let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`),o=t.resolveTextAsset(i);if(!o.ok){let[e,t,i]=r[o.reason];X(n,e,t,i,{handler:`asset-text`,...o.cause===void 0?{}:{cause:o.cause}});return}if(o.size>a){X(n,413,`urn:ok:error:payload-too-large`,`File exceeds the ${a}-byte text-viewer cap.`,{handler:`asset-text`});return}let s=(await Xs(o.canonicalPath)).toString(`utf-8`);n.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),n.end(s)}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0})})}const N4=`comments`,got={maxBytes:65536,timeoutMs:1e4},_ot={start:Fn().int().nonnegative().optional(),end:Fn().int().nonnegative().optional(),quote:R().min(1).optional(),prefix:R().max(1e3).optional(),suffix:R().max(1e3).optional()},vot=B({docName:R().min(1),..._ot,propertyKey:R().min(1).optional(),propertyPath:z(F([R(),Fn().int().nonnegative()])).optional(),body:R(),queue:Wa().optional(),summary:R().optional()}),P4=pr(),yot=ue(`action`,[B({action:P(`edit`),id:P4,body:R(),summary:R().optional()}),B({action:P(`resolve`),id:P4,summary:R().optional()}),B({action:P(`reopen`),id:P4,summary:R().optional()}),B({action:P(`replace`),id:P4,..._ot,summary:R().optional()}),B({action:P(`queue`),id:P4,summary:R().optional()}),B({action:P(`unqueue`),id:P4,summary:R().optional()}),B({action:P(`dispatch-prepare`),id:P4,summary:R().optional()}),B({action:P(`dispatch-complete`),id:P4,summary:R().optional()}),B({action:P(`dispatch-prepare-batch`),ids:z(P4).min(1).max(200),summary:R().optional()}),B({action:P(`dispatch-complete-batch`),ids:z(P4).min(1).max(200),summary:R().optional()})]);function bot(e){let{service:t,getPrincipal:n,onChanged:r}=e;async function i(e,n){let r=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??void 0;try{let e=await t.listThreads(r);Q(n,200,tt,{threads:e},{handler:N4})}catch(e){L4(n,e,`Failed to list comment threads.`)}}function a(e,t){let n=new URL(e.url??``,`http://localhost`).searchParams.get(`id`);return n?P4.safeParse(n).success?n:(F4(t,`id must be a comment thread UUID.`),null):(F4(t,`id query parameter is required.`),null)}async function o(e,n){let r=a(e,n);if(r!==null)try{let e=await t.readThread(r);Q(n,200,bi,e,{handler:N4})}catch(e){if(e instanceof k1)return I4(n,`Comment thread not found.`);L4(n,e,`Failed to read comment thread.`)}}async function s(e,i){let a=await xot(e,i,vot);if(!a)return;let o=y$(a,n);if(o.kind===`invalid-summary`)return F4(i,`Summary must be a string.`);let s=Sot(o);if(!s)return F4(i,`A principal or agent identity is required to comment.`);try{let e=await t.createThread({docName:a.docName,start:a.start,end:a.end,quote:a.quote,prefix:a.prefix,suffix:a.suffix,propertyKey:a.propertyKey,propertyPath:a.propertyPath,author:s,body:a.body,queue:a.queue});r?.(),Q(i,201,bi,e,{handler:N4})}catch(e){if(e instanceof O1)return I4(i,`Document not found.`);if(e instanceof j1)return F4(i,`The quoted passage is not in the document.`);if(e instanceof A1)return F4(i,`That property is not in the document: ${e.message}`);if(e instanceof RangeError||e instanceof Error&&/invalid selection|is required/.test(e.message))return F4(i,`Selection range is invalid for the document.`);L4(i,e,`Failed to create comment thread.`)}}async function c(e,i){let a=await xot(e,i,yot);if(!a)return;let o=y$(a,n);if(o.kind===`invalid-summary`)return F4(i,`Summary must be a string.`);try{switch(a.action){case`edit`:return Sot(o)?u(i,await t.editComment(a.id,a.body)):F4(i,`An identity is required to edit a comment.`);case`resolve`:return u(i,await t.resolve(a.id));case`reopen`:return u(i,await t.reopen(a.id));case`replace`:return u(i,await t.replaceAnchor(a.id,{start:a.start,end:a.end,quote:a.quote,prefix:a.prefix,suffix:a.suffix}));case`queue`:{let e=await t.queueForDispatch(a.id);return r?.(),Q(i,200,jte,e,{handler:N4})}case`unqueue`:return u(i,await t.unqueue(a.id));case`dispatch-prepare`:{let e=await t.prepareDispatch(a.id);return r?.(),Q(i,200,nie,e,{handler:N4})}case`dispatch-complete`:return u(i,await t.completeDispatch(a.id));case`dispatch-prepare-batch`:{let e=await t.prepareDispatchBatch(a.ids);return r?.(),Q(i,200,Ine,{results:e},{handler:N4})}case`dispatch-complete-batch`:{let e=await t.completeDispatchBatch(a.ids);return r?.(),Q(i,200,Pne,{results:e},{handler:N4})}}}catch(e){if(e instanceof k1)return I4(i,`Comment thread not found.`);if(e instanceof O1)return I4(i,`Document not found.`);if(e instanceof j1)return F4(i,`The quoted passage is not in the document.`);if(e instanceof A1)return F4(i,`That property is not in the document: ${e.message}`);if(e instanceof Error&&/invalid selection|is required/.test(e.message))return F4(i,`Selection range is invalid for the document.`);L4(i,e,`Failed to update comment thread.`)}}async function l(e,n){let i=a(e,n);if(i!==null)try{await t.delete(i),r?.(),Q(n,200,Xee,{threadId:i},{handler:N4})}catch(e){L4(n,e,`Failed to delete comment thread.`)}}function u(e,t){r?.(),Q(e,200,bi,t,{handler:N4})}return{list:i,read:o,create:s,mutate:c,remove:l}}async function xot(e,t,n){let r;try{r=await L$(e,got)}catch(e){return e instanceof R$?(z$(t,N4),null):(F4(t,`Request body could not be read.`),null)}let i;try{i=JSON.parse(r.toString(`utf8`)||`{}`)}catch{return F4(t,`Request body must be valid JSON.`),null}let a=n.safeParse(i);return a.success?a.data:(F4(t,`Request body is invalid.`),null)}function Sot(e){return e.kind===`agent`||e.kind===`principal`?e.writerId:null}function F4(e,t){X(e,400,`urn:ok:error:invalid-request`,t,{handler:N4})}function I4(e,t){X(e,404,`urn:ok:error:not-found`,t,{handler:N4})}function L4(e,t,n){X(e,500,`urn:ok:error:internal-server-error`,n,{handler:N4,cause:t})}function Cot(e){let{commentService:t,getPrincipal:n,signalChannel:r}=e,i=bot({service:t,getPrincipal:n,onChanged:()=>r?.(`comments`)});return P$({"/api/comments":i2({GET:i.list,POST:i.create},{handler:`comments`}),"/api/comment":i2({GET:i.read,POST:i.mutate,DELETE:i.remove},{handler:`comment`})},{mutating:[`/api/comments`,`/api/comment`]})}function wot(e,t,n){return e.filter(W8e).map(e=>{let r=B8e(e),i=r.at(-1)??null;return{value:e.slug,label:e.slug,description:null,group:null,source:`native-cli`,fingerprint:t,freshness:{kind:`cached`,at:n},selectability:`candidate`,context:i===null?null:{effectiveTokens:z8e(i,e),origin:`native-catalog`},contextChoices:r,setPhase:`launch-only`}})}function Tot(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function R4(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Eot(e){let t;try{t=JSON.parse(e)}catch{return[]}let n=Tot(t),r=Array.isArray(t)?t:n.models;return Array.isArray(r)?r.flatMap(e=>{let t=Tot(e),n=t.slug;return typeof n!=`string`||n===``?[]:[{slug:n,visibility:typeof t.visibility==`string`?t.visibility:null,contextWindow:R4(t.context_window),maxContextWindow:R4(t.max_context_window),effectivePercent:R4(t.effective_context_window_percent)}]}):[]}function Dot(e,t,n){let r={};for(let[e,n]of Object.entries(t))typeof n==`string`&&(r[e]=n);let i=n===`win32`,a=i?SQ(e,yQ(r)):e,o=i&&/\.(cmd|bat)$/i.test(a);return{...o?CQ(a,[`debug`,`models`]):{cmd:a,args:[`debug`,`models`]},wrap:o,env:r}}async function Oot(e,t=process.env,n=process.platform){let{cmd:r,args:i,wrap:a,env:o}=Dot(e,t,n);return new Promise(e=>{let t;try{t=ls(r,i,{env:o,stdio:[`ignore`,`pipe`,`ignore`],shell:!1,detached:n!==`win32`,windowsHide:!0,windowsVerbatimArguments:a})}catch(t){e(t.code===`ENOENT`?{outcome:`not-found`}:{outcome:`failed`});return}let s=()=>{DQ(t,{graceMs:1e3})},c=``,l=0,u=!1,d=t=>{u||(u=!0,clearTimeout(f),e(t))},f=setTimeout(()=>{s(),d({outcome:`failed`})},8e3);t.stdout?.on(`data`,e=>{if(l+=e.length,l>4194304){s(),d({outcome:`failed`});return}c+=e.toString(`utf8`)}),t.on(`error`,e=>{d(e.code===`ENOENT`?{outcome:`not-found`}:{outcome:`failed`})}),t.on(`close`,e=>{d(e===0?{outcome:`ok`,models:Eot(c)}:{outcome:`failed`})})})}let z4,B4;function kot(e=new Date().toISOString()){z4={startedAt:e},B4=performance.now()}function Aot(){if(B4!==void 0)return Math.round(performance.now()-B4)}function V4(e,t){z4&&(z4[e]=t)}function jot(e,t){z4&&(z4[e]=t)}function Mot(){return z4}function Not(e){let t=e.host;if(!t)return null;let n=e[`x-forwarded-proto`];return`${(Array.isArray(n)?n[0]:n)===`https`?`wss`:`ws`}://${t}/collab`}const Pot=q(`embeddings`);let Fot=null,Iot=null,Lot=null,Rot=null,zot=null;function Bot(){return Fot||=_H().createCounter(`ok.embeddings.tokens_total`,{description:`Embeddings tokens billed, by role. Bounded label: role ∈ {query, document}. Makes spend legible; never includes content.`}),Fot}function Vot(){return Iot||=_H().createCounter(`ok.embeddings.provider_errors_total`,{description:`Embeddings provider failures, by reason. Bounded label: reason ∈ {rate_limit, timeout, http_error, network, dims_mismatch, malformed_response}.`}),Iot}function Hot(){return Lot||=_H().createHistogram(`ok.embeddings.request_duration_ms`,{description:`Wall-clock duration of one embeddings API request. Bounded label: role.`,unit:`ms`}),Lot}function Uot(){return Rot||=_H().createCounter(`ok.search.semantic_query_total`,{description:`Semantic-requested searches, by outcome and caller surface. Bounded labels: outcome ∈ {applied, no_match, warming, incapable, provider_error}, source ∈ {omnibar, mcp, http}. The omnibar/mcp split separates interactive cost from agent cost.`}),Rot}function Wot(){return zot||=_H().createHistogram(`ok.search.semantic_query_embed_ms`,{description:`Wall-clock latency of the per-query embed on the semantic search path.`,unit:`ms`}),zot}function Got(e,t){t>0&&Bot().add(t,{role:e})}function Kot(e){Vot().add(1,{reason:e})}function qot(e,t){Hot().record(Math.max(0,t),{role:e})}function Jot(e){Uot().add(1,{outcome:e.outcome,source:e.source}),e.queryEmbedMs!==null&&Wot().record(Math.max(0,e.queryEmbedMs)),Pot.debug({outcome:e.outcome,source:e.source,capable:e.capable,embedded:e.embedded,total:e.total,coverage:e.total>0?e.embedded/e.total:0,queryEmbedMs:e.queryEmbedMs,vectorContributors:e.vectorContributors},`[search] semantic query`)}const Yot=q(`embeddings`),Xot=1536,Zot=`OK_EMBEDDINGS_API_KEY`;var H4=class extends Error{reason;status;constructor(e,t,n,r){super(t,r),this.reason=e,this.status=n,this.name=`EmbeddingProviderError`}},U4=class extends H4{name=`EmbeddingDimsMismatchError`;expected;got;constructor(e,t){super(`dims_mismatch`,`embeddings provider returned ${t}-dim vectors, expected ${e}`),this.expected=e,this.got=t}},W4=class extends H4{name=`MalformedEmbeddingResponseError`;constructor(e){super(`malformed_response`,e)}};function Qot(e,t){let n=0,r=Math.min(e.length,t.length);for(let i=0;i<r;i++)n+=e[i]*t[i];return n}function $ot(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];if(t=Math.sqrt(t),t>0)for(let n=0;n<e.length;n++)e[n]/=t;return e}const G4={maxBatchSize:96,maxBatchChars:Vte,docTimeoutMs:Ote,queryTimeoutMs:8e3,maxRetries:4,backoffBaseMs:500};function K4(e){try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${n}`}catch{return e.trim().replace(/\/+$/,``)}}function est(e){let t=pe(e);if(t===null)return;if(t===`invalid-url`)throw Error(`embeddings baseUrl is not a valid URL: ${e}`);let n=new URL(e);throw Error(`refusing to send the embeddings API key to a non-HTTPS endpoint (${n.protocol}//${n.host}); use https:// (http:// is allowed only for localhost)`)}const tst=new Set([408,409,429,500,502,503,504]);function q4(e,t={}){let n=t.fetchImpl??fetch,r=t.sleep??Ai,i=t.maxBatchSize??G4.maxBatchSize,a=t.maxBatchChars??G4.maxBatchChars,o=t.maxRetries??G4.maxRetries,s=t.backoffBaseMs??G4.backoffBaseMs,c=t.docTimeoutMs??G4.docTimeoutMs,l=t.queryTimeoutMs??G4.queryTimeoutMs;est(e.baseUrl);let u=e.dimensions??null,d=`${e.baseUrl.replace(/\/+$/,``)}/embeddings`;function f(e){let t=[],n=[],r=0;for(let o of e)n.length>0&&(n.length>=i||r+o.length>a)&&(t.push(n),n=[],r=0),n.push(o),r+=o.length;return n.length>0&&t.push(n),t}async function p(t,r,i,a){let o=new AbortController,s=setTimeout(()=>o.abort(),a),c=performance.now();try{let a=await n(d,{method:`POST`,headers:{"Content-Type":`application/json`,...e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}},body:t,signal:o.signal});if(qot(i,performance.now()-c),!a.ok){await a.text().catch(()=>``);let e=a.status===429?`rate_limit`:`http_error`,t=new H4(e,`embeddings request failed: HTTP ${a.status}`,a.status);return tst.has(a.status)?{kind:`retry`,reason:e,error:t}:{kind:`fatal`,reason:e,error:t}}let s;try{s=await a.json()}catch{throw new W4(`embeddings endpoint returned a non-JSON body — check the base URL`)}let l=h(s,r);return u??=l.dims,Got(i,s.usage?.total_tokens??0),{kind:`ok`,vectors:l.vectors}}catch(e){if(e instanceof U4)return{kind:`fatal`,reason:`dims_mismatch`,error:e};if(e instanceof W4)return{kind:`fatal`,reason:`malformed_response`,error:e};let t=e instanceof Error&&e.name===`AbortError`,n=e instanceof Error?e:Error(String(e));return{kind:`retry`,reason:t?`timeout`:`network`,error:n}}finally{clearTimeout(s)}}async function m(t,n){let i=n===`query`?l:c,a=n===`query`?`query`:`document`,u=JSON.stringify({model:e.model,input:t,encoding_format:`float`,...e.dimensions===void 0?{}:{dimensions:e.dimensions}}),d=0;for(;;){let e=await p(u,t.length,a,i);if(e.kind===`ok`)return e.vectors;if(Kot(e.reason),e.kind===`fatal`||d>=o)throw e.error instanceof H4?e.error:new H4(e.reason,e.error.message,void 0,{cause:e.error});d+=1;let n=s*2**(d-1);await r(Math.round(n/2+n/2*Math.random()))}}function h(e,t){let n=e.data;if(!Array.isArray(n)||n.length!==t)throw new W4(`embeddings response had ${n?.length??0} vectors, expected ${t}`);let r=[...n].sort((e,t)=>(e.index??0)-(t.index??0)),i=[],a=u;for(let e of r){let t=e.embedding;if(!Array.isArray(t))throw new W4(`embeddings response contained a non-array embedding (expected float vectors)`);if(a??=t.length,t.length!==a)throw new U4(a,t.length);i.push($ot(Float32Array.from(t)))}if(a===null)throw new W4(`embeddings response contained no vectors`);return{vectors:i,dims:a}}return{providerId:K4(e.baseUrl),modelId:e.model,get dims(){return u},pinDims(e){u??=e},async embed(e,{role:t}){if(e.length===0)return[];let n=[];for(let r of f(e))n.push(...await m(r,t));return n}}}function nst(e){return K4(e)===K4(Aa)}async function J4(e,t,n){let r=e?await e.resolveForProject(t,n).catch(e=>(Yot.warn({err:e},`[embeddings] failed to read the stored key — treating as unset`),null)):null;if(r?.key){let e=r.source===`file`?`file`:`project`;return{apiKey:r.key,keyless:!1,source:e}}if(nst(n)){let e=process.env[Zot];if(e)return{apiKey:e,keyless:!1,source:`env`}}return fie(n)?{apiKey:null,keyless:!0,source:`none`}:{apiKey:null,keyless:!1,source:`none`}}async function rst(e){let t=await J4(e.keyStore,e.projectDir,e.config.baseUrl);return t.apiKey?q4({...e.config,apiKey:t.apiKey},e.options):t.keyless?q4({...e.config},e.options):null}async function ist(e){let t;try{t=q4({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:e.apiKey},{fetchImpl:e.fetchImpl,maxRetries:0,queryTimeoutMs:e.timeoutMs??1e4})}catch{return{ok:!1,reason:`invalid_endpoint`}}try{let[e]=await t.embed([`OpenKnowledge embeddings connection test`],{role:`query`});return!e||e.length===0?{ok:!1,reason:`malformed_response`}:{ok:!0,dimensions:e.length}}catch(e){return e instanceof H4?{ok:!1,reason:e.reason,status:e.status}:{ok:!1,reason:`network`}}}const ast=K4(Aa),Y4=`OPENAI_API_KEY`,X4=`embeddings`,Z4=`embeddings_projects`;function Q4(e){try{return Ns.native(e)}catch{return W(e)}}function ost(e){return H(Mx(e??Hs()),te)}function sst(e){return e&&e.length>=8?e.slice(-4):null}function cst(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}var $4=class{backend=`file`;secretsFile;constructor(e){this.secretsFile=e??ost()}withLock(e){let t=`${this.secretsFile}.lock`,n=V(this.secretsFile);G(n)||KH(n,{recursive:!0,mode:448});let r=Date.now(),i=!1;for(;!i;)try{let e=js(t,`wx`,384);Bs(e,String(process.pid)),ws(e),i=!0}catch(e){if(e.code!==`EEXIST`){let t=e instanceof Error?e.message:`unknown error`;process.stderr.write(`[embeddings] could not acquire the secrets write-lock (${t}); proceeding without cross-process serialization.\n`);break}try{if(Date.now()-Ls(t).mtimeMs>1e4){Rs(t);continue}}catch{continue}if(Date.now()-r>2e3)break;cst(15)}try{return e()}finally{if(i)try{Rs(t)}catch{}}}tightenPermsIfLoose(){let e;try{e=Ls(this.secretsFile).mode&511}catch{return}if(e&63)try{Cs(this.secretsFile,384),process.stderr.write(`[embeddings] ${this.secretsFile} was readable beyond your user account (mode ${e.toString(8)}); tightened to 600. It stores an API key.\n`)}catch(t){let n=t instanceof Error?t.message:`unknown error`;process.stderr.write(`[embeddings] ${this.secretsFile} is readable beyond your user account (mode ${e.toString(8)}) and could not be tightened (${n}); your API key remains exposed — run: chmod 600 ${this.secretsFile}\n`)}}read(){if(!G(this.secretsFile))return{};this.tightenPermsIfLoose();try{return(0,Fc.parse)(K(this.secretsFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[embeddings] Failed to parse ${this.secretsFile}: ${t}. Starting with empty secrets.\n`),{}}}write(e){let t=V(this.secretsFile);G(t)||KH(t,{recursive:!0,mode:448});let n=`${this.secretsFile}.tmp`;WH(n,(0,Fc.stringify)(e),{mode:384}),Cs(n,384),qH(n,this.secretsFile),Cs(this.secretsFile,384)}writeOrUnlink(e){if(Object.keys(e).length===0){try{XH(this.secretsFile)}catch(e){if(e.code!==`ENOENT`){let t=e instanceof Error?e.message:`unknown error`;process.stderr.write(`[embeddings] could not remove ${this.secretsFile} (${t}); a cleared key may remain on disk — delete the file manually if needed.\n`)}}return}this.write(e)}readProjects(e){let t=e[Z4];return t&&typeof t==`object`?t:{}}legacyKey(e){let t=e[Y4]??e[X4];return typeof t==`string`&&t!==``?t:null}resolveForProject(e,t){let n=this.read(),r=K4(t),i=this.readProjects(n)[Q4(e)]?.[r];if(typeof i==`string`&&i!==``)return Promise.resolve({key:i,source:`project`});if(r===ast){let e=this.legacyKey(n);if(e)return Promise.resolve({key:e,source:`file`})}return Promise.resolve({key:null,source:null})}describeForProject(e,t){return this.resolveForProject(e,t).then(({key:e,source:t})=>({present:e!==null,hint:sst(e),source:t}))}getLegacyKey(){return Promise.resolve(this.legacyKey(this.read()))}setForProject(e,t,n){return this.withLock(()=>{let r=this.read(),i=this.readProjects(r),a=Q4(e);i[a]={...i[a],[K4(t)]:n},r[Z4]=i,this.write(r)}),Promise.resolve()}clearForProject(e,t){let n=this.withLock(()=>{let n=this.read(),r=this.readProjects(n),i=Q4(e),a=K4(t);return r[i]?.[a]!==void 0&&(delete r[i][a],Object.keys(r[i]).length===0&&delete r[i],Object.keys(r).length===0?delete n[Z4]:n[Z4]=r,this.writeOrUnlink(n),!0)});return Promise.resolve(n)}clearAllForProject(e){let t=this.withLock(()=>{let t=this.read(),n=this.readProjects(t),r=Q4(e);return n[r]!==void 0&&(delete n[r],Object.keys(n).length===0?delete t[Z4]:t[Z4]=n,this.writeOrUnlink(t),!0)});return Promise.resolve(t)}clearAll(){let e=this.withLock(()=>{let e=this.read(),t=e[Z4]!==void 0||e[Y4]!==void 0||e[X4]!==void 0;return delete e[Z4],delete e[Y4],delete e[X4],t&&this.writeOrUnlink(e),t});return Promise.resolve(e?{touched:[`file`]}:{touched:[]})}listProjects(){let e=this.readProjects(this.read()),t=Object.entries(e).map(([e,t])=>({projectKey:e,endpoints:Object.entries(t).map(([e,t])=>({endpoint:e,hint:sst(t)}))}));return Promise.resolve(t)}};function lst(e){return new $4(e)}function ust(e){return new $4(e)}async function dst(e,t,n){return new $4(n).describeForProject(e,t)}async function fst(e){return new $4(e).clearAll()}function pst(e,t){let n=jx({absPath:Vx(`project-local`,e,t?.configHomedirOverride),sideline:!1,warn:t?.onWarn??(()=>{})}).value.search?.semantic;return{enabled:n?.enabled===!0,baseUrl:n?.baseUrl??`https://api.openai.com/v1`,model:n?.model??`text-embedding-3-small`,dimensions:n?.dimensions??void 0,similarityFloor:n?.similarityFloor??void 0,maxBatchSize:n?.maxBatchSize??96,maxBatchChars:n?.maxBatchChars??96e3,docTimeoutMs:n?.docTimeoutMs??3e4}}function mst(e,t={}){let n=Math.max(1,t.targetChars??8e3),r=Math.max(0,Math.min(t.overlapChars??400,n-1)),i=t.maxChunks??80;if(e.trim().length===0)return[];if(e.length<=n)return[e.trim()];let a=[],o=0;for(;o<e.length&&a.length<i;){let t=Math.min(e.length,o+n);if(t<e.length){let r=Math.max(e.lastIndexOf(` `,t),e.lastIndexOf(`
1111
+ `),n=[],r=!1,i=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){r?RegExp(`^\\s{0,3}${i[0]==="`"?"`":`~`}{${i.length},}\\s*$`).test(e)&&(r=!1,i=``):(r=!0,i=t[1]);continue}if(r)continue;let a=Gat(e);for(Hat.lastIndex=0;;){let e=Hat.exec(a);if(e===null)break;let t=e[2];t&&n.push(t)}}return n}var qat=class{contentDir;contentFilter;projectDir;state=v4();fileMeta=new Map;initChain=Promise.resolve();closed=!1;constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.projectDir=e.projectDir}snapshotPath(){return this.projectDir?W(Vq(this.projectDir),`cache`,`tags.json`):null}enqueue(e){let t=this.initChain.then(e);return this.initChain=t.then(()=>void 0,e=>{_4.warn({err:e},`queued tag-index task failed (chain cleared for next task)`)}),t}close(){return this.closed=!0,this.initChain}updateDocumentFromMarkdown(e,t){if(!XW(e))try{let{frontmatter:n,body:r}=ri(t),i=n?ci(n):``,a=nee(i),o=Kat(r),s=new Set([...a,...o]),c=new Set;for(let e of s)for(let t of dn(e))c.add(t);this.applyDocSnapshot(e,s,c)}catch(t){_4.warn({docName:e,err:t},`Failed to scan ${e} for tag extraction`),this.deleteDocument(e)}}deleteDocument(e){if(XW(e))return;let t=this.state.byDoc.get(e);if(t){for(let n of t){let t=this.state.byTag.get(n);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(n))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,n){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,n)}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 n=[];for(let r of t){let t=this.state.byDocLiteral.get(r);if(!t)continue;let i=Lte(t,e);n.push({docName:r,matchingTags:[...i].sort((e,t)=>e.localeCompare(t))})}return n.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),n=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&n.add(e.slice(0,t));let r=t;for(;r>0;)n.add(e.slice(0,r)),r=e.indexOf(`/`,r+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!n.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){return this.enqueue(()=>B2(`tag`,`full`,()=>this.initOnce()))}async initOnce(){if(this.closed||(this.state=v4(),this.fileMeta=new Map,!G(this.contentDir)))return;let e=await this.listDocsWithPaths();for(let t=0;t<e.length;t+=50){let n=e.slice(t,t+50),r=await Promise.all(n.map(async({docName:e,filePath:t})=>{try{let[n,r]=await Promise.all([ec(t),Xs(t,`utf-8`)]);return{docName:e,markdown:r,mtimeMs:n.mtimeMs,size:n.size}}catch(t){return _4.warn({docName:e,err:t},`Failed to read ${e} during init`),null}}));for(let e of r)if(e)try{this.updateDocumentFromMarkdown(e.docName,e.markdown),this.fileMeta.set(e.docName,{mtimeMs:e.mtimeMs,size:e.size})}catch(t){_4.warn({docName:e.docName,err:t},`Failed to index ${e.docName} during init`)}}}loadFromDisk(){return this.enqueue(()=>this.loadOnce())}async loadOnce(){if(this.closed)return!1;let e=this.snapshotPath();if(!e||!G(e))return!1;let t;try{t=await Xs(e,`utf-8`)}catch(e){return _4.warn({err:e},`Failed to read tag snapshot; falling back to full rebuild`),!1}let n;try{n=JSON.parse(t)}catch(t){return _4.warn({err:t},`Corrupt tag snapshot; rebuilding from disk`),await this.discardCorruptSnapshot(e,`malformed`),!1}if(Uat(n))return!1;if(!Wat(n))return _4.warn({},`Incomplete tag snapshot; rebuilding from disk`),await this.discardCorruptSnapshot(e,`incomplete`),!1;this.state=v4(),this.fileMeta=new Map(Object.entries(n.files));for(let[e,t]of Object.entries(n.docs)){if(XW(e))continue;let n=new Set(t),r=new Set;for(let e of n)for(let t of dn(e))r.add(t);this.applyDocSnapshot(e,n,r)}return!0}async discardCorruptSnapshot(e,t){try{await VH(e,{force:!0})}catch(e){_4.warn({reason:t,err:e},`Failed to discard corrupt tag snapshot`)}}saveToDisk(){return this.enqueue(()=>this.saveOnce())}async saveOnce(){if(this.closed)return;let e=this.snapshotPath();if(!e)return;let t={version:2,docs:Object.fromEntries([...this.state.byDocLiteral.entries()].map(([e,t])=>[e,[...t].sort((e,t)=>e.localeCompare(t))])),files:Object.fromEntries(this.fileMeta)};await UH(V(e),{recursive:!0}),await Lx(e,JSON.stringify(t,null,2),{fs:tU})}reconcileWithDisk(){return this.enqueue(()=>B2(`tag`,`reconcile`,()=>this.reconcileOnce(),e=>({"index.added":e.added,"index.updated":e.updated,"index.deleted":e.deleted})))}async reconcileOnce(){if(this.closed||!G(this.contentDir))return{added:0,updated:0,deleted:0};let e=await this.listDocsWithPaths(),t=new Set(e.map(e=>e.docName)),n=new Map,r=0,i=0,a=[],o=await Promise.allSettled(e.map(async({docName:e,filePath:t})=>{let n=await ec(t);return{docName:e,filePath:t,meta:{mtimeMs:n.mtimeMs,size:n.size}}}));for(let e of o){if(e.status===`rejected`)continue;let{docName:t,filePath:r,meta:i}=e.value,o=this.fileMeta.get(t);if(o!==void 0&&o.mtimeMs===i.mtimeMs&&o.size===i.size){n.set(t,i);continue}a.push({docName:t,filePath:r,meta:i,isNew:o===void 0})}for(let e=0;e<a.length;e+=50){let t=a.slice(e,e+50),o=await Promise.allSettled(t.map(async({docName:e,meta:t,isNew:n,filePath:r})=>({docName:e,meta:t,isNew:n,markdown:await Xs(r,`utf-8`)})));for(let e of o){if(e.status===`rejected`){_4.warn({err:e.reason},`Failed to reconcile file`);continue}let{docName:t,meta:a,isNew:o,markdown:s}=e.value;this.updateDocumentFromMarkdown(t,s),n.set(t,a),o?r++:i++}}let s=0,c=new Set([...this.fileMeta.keys(),...this.state.byDoc.keys()]);for(let e of c)t.has(e)||(this.deleteDocument(e),s++);return this.fileMeta=n,{added:r,updated:i,deleted:s}}applyDocSnapshot(e,t,n){let r=this.state.byDoc.get(e)??new Set;for(let t of r){if(n.has(t))continue;let r=this.state.byTag.get(t);r&&(r.delete(e),r.size===0&&this.state.byTag.delete(t))}for(let t of n){let n=this.state.byTag.get(t);n||(n=new Set,this.state.byTag.set(t,n)),n.add(e)}n.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,n),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)&&(t.add(e),!0))}async walkContentDir(e,t){let n;try{n=await Zs(e,{withFileTypes:!0})}catch(t){_4.warn({dir:e,err:t},`Failed to read directory ${e}`);return}for(let r of n){let n=H(e,r.name);if(r.isDirectory()){let e=eG(U(this.contentDir,n));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(n,t);continue}if(!r.isFile()||!OW(r.name))continue;let i=eG(U(this.contentDir,n));this.contentFilter?.isExcluded(i)||t.push({docName:jW(i),filePath:n})}}};const y4=q(`derived-document-index`);function Jat(e){return typeof e==`string`&&Nc(e)}function b4(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}var Yat=class extends Error{constructor(){super(`Derived document index is closed`),this.name=`DerivedDocumentIndexClosedError`}};function x4(e){return e instanceof Yat}var Xat=class extends Error{constructor(){super(`Local-target index is not ready`),this.name=`LocalTargetIndexNotReadyError`}};function Zat(e){return e instanceof Xat}var Qat=class{testOnly;backlinkIndex;tagIndex;localTargetIndex;contentFilter;getGlobalSkillRoots;getLocalTargetInventory;signalChannel;onRecoveredFileTarget;startupAdmission=b4();readyBarrier=b4();tail=Promise.resolve();saveTimer=null;localTargetRebuildRetryTimer=null;localTargetFileExistenceTimer;localTargetRebuildRetryAttempt=0;graphFileTargetsSource=null;graphFileTargets=null;startupBranch=null;graphBuiltWithoutFileOracle=!1;saveTagsOnNextDebounce=!1;branchTransition=null;startupBegun=!1;startupBegunAt=0;startupSettled=!1;ready=!1;liveUpdateToken=0;lastSignaledLocalTargetGeneration=0;closed=!1;closePromise=null;constructor(e){this.backlinkIndex=new a4({projectDir:e.projectDir,contentDir:e.contentDir,contentFilter:e.contentFilter,getFileOracle:()=>this.graphFileOracle()}),this.tagIndex=new qat({projectDir:e.projectDir,contentDir:e.contentDir,contentFilter:e.contentFilter}),this.localTargetIndex=new yat({contentDir:e.contentDir,contentFilter:e.contentFilter}),this.contentFilter=e.contentFilter,this.getGlobalSkillRoots=e.getGlobalSkillRoots,this.getLocalTargetInventory=e.getLocalTargetInventory??(()=>({documentTargets:[],fileTargets:[],folderTargets:[]})),this.signalChannel=e.signalChannel,this.onRecoveredFileTarget=e.onRecoveredFileTarget,this.testOnly={resetDocumentForTest:e=>this.resetDocumentForTest(e),rescanBacklinksForTest:()=>this.rescanBacklinksForTest()},this.localTargetFileExistenceTimer=setInterval(()=>{this.closed||!this.startupSettled||!this.localTargetIndex.isReady()||this.runCommand(async()=>{let e=await this.localTargetIndex.reconcileDependentFileTargetsFromDisk(this.onRecoveredFileTarget);this.maybeSignalLocalTargets(),e>0&&this.signalChannel(`files`)}).catch(e=>{this.closed||y4.warn({err:e},`[local-target] dependent file-existence sweep failed`)})},5e3),this.localTargetFileExistenceTimer.unref?.()}beginStartup(e){if(this.assertOpen(),this.startupBegun)throw Error(`Derived document index startup has already begun`);this.startupBegun=!0,this.startupBegunAt=performance.now(),this.startupBranch=e,this.backlinkIndex.switchBranch(e);let t=Promise.withResolvers(),n=this.initializeBacklinks(e,t.resolve),r=this.warmTags();return this.tail=Promise.all([n.then(()=>void 0),r]).then(()=>void 0),this.startupAdmission.resolve(),{backlinksReady:n,offlineDeletionsReady:t.promise}}async settleStartupAfterWatcherSeed(){if(this.assertOpen(),!this.startupBegun)throw Error(`Derived document index startup has not begun`);if(this.startupSettled)throw Error(`Derived document index startup has already settled`);this.startupSettled=!0;try{return await this.enqueueInternal(async()=>{let e=!1;try{let e=await this.tagIndex.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&y4.info(e,`[tag-index] startup reconcile: offline changes applied`),await this.saveTagsLogOnly(`startup`)}catch(t){y4.error({err:t},`[tag-index] startup reconcile failed; tag index updates incrementally via watcher events`),e=!0}return await this.rebuildLocalTargets(`startup`)&&this.syncLocalTargetBaseline(),this.startupBranch!==null&&await this.reconcileGraphWithFileInventory(this.startupBranch),{tagIndexDegraded:e}})}finally{this.ready=!0,this.readyBarrier.resolve();let e=Math.round(performance.now()-this.startupBegunAt);(e>=1e4?y4.info:y4.debug).call(y4,{startupMs:e},`[derived-index] startup settled; deferred link checks resume`)}}async beginBranchSwitch(e){if(this.assertOpen(),this.branchTransition)throw Error(`Derived document index branch switch already active`);let t={branch:e,barrier:b4()};this.liveUpdateToken++,this.branchTransition=t,this.cancelScheduledSave();try{return await this.startupAdmission.promise,await this.readyBarrier.promise,this.assertOpen(),await this.enqueueInternal(async()=>{this.backlinkIndex.switchBranch(e)}),t}catch(e){throw this.releaseBranchTransition(t),e}}async settleBranchFromDisk(e){if(this.assertOpen(),this.branchTransition!==e)throw Error(`No derived document index branch switch is active`);try{await this.enqueueInternal(async()=>{let t=e.branch;if(await this.backlinkIndex.loadFromDisk(t)){let e=await this.backlinkIndex.reconcileWithDisk(t);(e.added>0||e.updated>0||e.deleted>0)&&y4.info(e,`[backlinks] branch-switch reconcile for ${t}`)}else await this.backlinkIndex.rebuildFromDisk(t);let n=!1,r;try{await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots(),t)}catch(e){n=!0,r=e}await this.saveBacklinksLogOnly(`branch-switch`,t);try{let e=await this.tagIndex.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&y4.info(e,`[tag-index] branch-switch reconcile for ${t}`)}catch(e){y4.warn({err:e,branch:t},`[tag-index] branch-switch reconcile failed; falling back to full rebuild`),await this.tagIndex.init()}if(await this.saveTagsLogOnly(`branch-switch`),await this.rebuildLocalTargets(`branch-switch`)&&this.syncLocalTargetBaseline(),n)throw r})}finally{this.releaseBranchTransition(e)}}abortBranchSwitch(e){e&&this.releaseBranchTransition(e)}captureLiveUpdateToken(){return this.closed?null:this.liveUpdateToken}recordLiveDocument(e,t,n){return this.closed||n!==this.liveUpdateToken?Promise.resolve():this.runCommand(async()=>{n===this.liveUpdateToken&&(this.updateBoth(e,t),this.signalAllRelations())})}recordDurableStore(e,t){return this.runCommand(async()=>{this.updateBacklinks(e,t),this.scheduleSave(!1)})}recordDiskUpsert(e,t){return this.runCommand(async()=>{this.updateBoth(e,t),this.reconcileLocalTargetInventory(),this.scheduleSave(),this.signalAllRelations()})}recordDiskDelete(e){return this.runCommand(async()=>{this.deleteBoth(e),this.reconcileLocalTargetInventory(),this.scheduleSave(),this.signalAllRelations()})}recordDiskRename(e,t,n){return this.runCommand(async()=>{this.renameBoth(e,t,n),this.reconcileLocalTargetInventory(),this.scheduleSave(),this.signalAllRelations()})}recordInventoryReconciled(){return this.runCommand(async()=>{this.reconcileLocalTargetInventory(),this.maybeSignalLocalTargets()})}recordFileTargetUpsert(e){return this.runCommand(async()=>{let t=this.reconcileLocalTargetInventory();(t===null||!t.fileTargets.includes(e))&&this.localTargetIndex.setFileTarget(e,!0),this.maybeSignalLocalTargets()})}recordFileTargetDelete(e){return this.runCommand(async()=>{let t=this.reconcileLocalTargetInventory();(t===null||t.fileTargets.includes(e))&&this.localTargetIndex.setFileTarget(e,!1),this.maybeSignalLocalTargets()})}recordDirectDocument(e,t){return this.recordDirectMutations([{kind:`upsert`,documentName:e,markdown:t}])}recordDirectDelete(e){return this.recordDirectMutations([{kind:`delete`,documentName:e}])}recordDirectRename(e,t,n){return this.recordDirectMutations([{kind:`rename`,oldDocumentName:e,newDocumentName:t,markdown:n}])}recordLinkRewrite(e,t){return this.runCommand(async()=>{this.updateBacklinks(e,t),this.scheduleSave(!1),this.signalBacklinks()})}recordDirectMutations(e){return e.length===0?Promise.resolve():this.runCommand(async()=>{let t=!1;for(let n of e)switch(n.kind){case`upsert`:this.updateBoth(n.documentName,n.markdown),t=!0;break;case`delete`:this.deleteBoth(n.documentName),t=!0;break;case`rename`:this.renameBoth(n.oldDocumentName,n.newDocumentName,n.markdown),t=!0;break;case`link-rewrite`:this.updateBacklinks(n.documentName,n.markdown)}t?(this.reconcileLocalTargetInventory(),await this.saveBothLogOnly(`direct-batch`),this.signalAllRelations()):(await this.saveBacklinksLogOnly(`direct-batch`),this.signalBacklinks())})}refreshGlobalSkillNodes(){return this.runCommand(async()=>{await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots()),this.reconcileLocalTargetInventory(),this.signalBacklinks()})}refreshContentScope(){return this.runCommand(async()=>{let e=this.backlinkIndex.getActiveBranch(),t=await this.backlinkIndex.reconcileWithDisk(e),n=!1,r;try{await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots(),e)}catch(e){n=!0,r=e}await this.tagIndex.reconcileWithDisk(),this.reconcileLocalTargetInventory();for(let{docName:e,filePath:n}of t.changedDocs)try{this.localTargetIndex.setSource(e,await Xs(n,`utf-8`))}catch{this.localTargetIndex.removeSource(e)}for(let e of t.deletedDocNames)this.localTargetIndex.removeSource(e);if(await this.saveBothLogOnly(`content-filter`,e),this.signalAllRelations(),n)throw r})}announceReadyViews(){this.assertOpen(),this.signalAllRelations()}isReady(){return this.ready&&!this.closed}getBacklinks(e){return this.runQuery(()=>this.backlinkIndex.getBacklinks(e))}getBacklinkCount(e){return this.runQuery(()=>this.backlinkIndex.getBacklinkCount(e))}getBacklinkCounts(e){return this.runQuery(()=>Object.fromEntries(e.map(e=>[e,this.backlinkIndex.getBacklinkCount(e)])))}getForwardLinkEntries(e){return this.runQuery(()=>this.backlinkIndex.getForwardLinkEntries(e))}getLinkGraphNeighborhood(e,t){return this.runQuery(()=>this.backlinkIndex.getLinkGraphNeighborhood(e,t))}getLinkGraph(){return this.runQuery(()=>this.backlinkIndex.getLinkGraph())}getHubs(e){return this.runQuery(()=>this.backlinkIndex.getHubs(e))}getOrphans(e,t){return this.runQuery(()=>this.backlinkIndex.getOrphans(e,t))}getDeadLinks(e,t){return this.runQuery(()=>this.backlinkIndex.getDeadLinks(e,t,void 0,this.getLocalTargetInventory()?.folderTargets))}getIndexedDocNames(){return this.runQuery(()=>this.backlinkIndex.getIndexedDocNames())}getRenameSourceInventory(){return this.runQuery(()=>this.backlinkIndex.getRenameSourceInventory())}getAllTags(){return this.runQuery(()=>this.tagIndex.getAllTags())}getDocsForTagWithMatches(e){return this.runQuery(()=>this.tagIndex.getDocsForTagWithMatches(e))}getLocalTargetAssessments(e){return this.runLocalTargetQuery(()=>this.localTargetIndex.getAssessments(e))}getLocalTargetAssessmentsForSources(e){return this.runLocalTargetQuery(()=>this.localTargetIndex.getAssessmentsForSources(e))}getLocalTargetGeneration(){return this.runLocalTargetQuery(()=>this.localTargetIndex.generation)}readLocalTargetGeneration(){return this.localTargetIndex.freshnessToken}getLocalTargetStats(){return this.runLocalTargetQuery(()=>this.localTargetIndex.getStats())}getLocalTargetDocumentDependents(e){return this.runLocalTargetQuery(()=>this.localTargetIndex.getDocumentDependents(e))}getLocalTargetFileDependents(e){return this.runLocalTargetQuery(()=>this.localTargetIndex.getFileDependents(e))}close(){if(this.closePromise)return this.closePromise;let e=this.cancelScheduledSave();return e!==null&&this.enqueueInternal(()=>this.saveScheduledCache(e,`close-flush`)),this.closed=!0,clearInterval(this.localTargetFileExistenceTimer),this.cancelLocalTargetRebuildRetry(),this.localTargetIndex.close(),this.startupAdmission.resolve(),this.readyBarrier.resolve(),this.releaseBranchTransition(this.branchTransition),this.closePromise=this.tail.then(()=>this.tagIndex.close()).then(()=>void 0,()=>void 0),this.closePromise}resetDocumentForTest(e){return this.runCommand(async()=>{this.deleteBoth(e),await this.saveBothLogOnly(`test-reset`),this.signalAllRelations()})}rescanBacklinksForTest(){return this.runCommand(async()=>{let e=this.backlinkIndex.getActiveBranch();await this.backlinkIndex.rebuildFromDisk(e),await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots(),e),this.reconcileLocalTargetInventory(),await this.saveBacklinksLogOnly(`test-rescan`,e),this.signalBacklinks()})}async initializeBacklinks(e,t){try{if(this.graphFileOracle(),await this.backlinkIndex.loadFromDisk(e)){let n=await this.backlinkIndex.reconcileWithDisk(e);t(n.deletedDocNames),(n.added>0||n.updated>0||n.deleted>0)&&y4.info({added:n.added,updated:n.updated,deleted:n.deleted},`[backlinks] startup reconcile`)}else t([]),await this.backlinkIndex.rebuildFromDisk(e);return await this.ingestGlobalSkillNodesLogOnly(e,`startup`),await this.saveBacklinksLogOnly(`startup`,e),{backlinkIndexDegraded:!1}}catch(n){return t([]),y4.error({err:n,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`),{backlinkIndexDegraded:!0}}}async warmTags(){try{await this.tagIndex.loadFromDisk()?await this.tagIndex.reconcileWithDisk():await this.tagIndex.init()}catch(e){y4.warn({err:e},`[derived-document-index] tag-index warm boot failed; continuing with stale or empty index`)}}updateBoth(e,t){this.updateBacklinks(e,t),this.isAdmitted(e)?this.tagIndex.updateDocumentFromMarkdown(e,t):this.tagIndex.deleteDocument(e)}updateBacklinks(e,t){this.isAdmitted(e)?(this.backlinkIndex.updateDocumentFromMarkdown(e,t),this.localTargetIndex.setSource(e,t)):(this.backlinkIndex.deleteDocument(e),this.localTargetIndex.removeSource(e))}deleteBoth(e){this.backlinkIndex.deleteDocument(e),this.tagIndex.deleteDocument(e),this.localTargetIndex.removeSource(e)}renameBoth(e,t,n){this.isAdmitted(t)?(this.backlinkIndex.renameDocument(e,t,n),this.tagIndex.renameDocument(e,t,n),this.localTargetIndex.renameSource(e,t,n)):(this.backlinkIndex.deleteDocument(e),this.backlinkIndex.deleteDocument(t),this.tagIndex.deleteDocument(e),this.tagIndex.deleteDocument(t),this.localTargetIndex.removeSource(e),this.localTargetIndex.removeSource(t))}isAdmitted(e){return XW(e)?!1:GW(e)?!0:!this.contentFilter.isExcluded(BW(e))}signalBacklinks(){this.signalChannel(`backlinks`),this.signalChannel(`graph`),this.maybeSignalLocalTargets()}signalAllRelations(){this.signalBacklinks(),this.signalChannel(`tags`)}maybeSignalLocalTargets(){let e=this.localTargetIndex.generation,t=e-this.lastSignaledLocalTargetGeneration;t!==0&&(Uit(`local-target`,`signal`,t),this.lastSignaledLocalTargetGeneration=e,this.signalChannel(`local-targets`))}graphFileOracle(){let e=this.getLocalTargetInventory();if(!e){this.graphBuiltWithoutFileOracle=!0;return}this.graphFileTargetsSource!==e.fileTargets&&(this.graphFileTargetsSource=e.fileTargets,this.graphFileTargets=ra(`file`,e.fileTargets));let t=this.graphFileTargets;return t?{hasFile:e=>t.resolve(e)!==void 0}:void 0}async reconcileGraphWithFileInventory(e){if(this.graphBuiltWithoutFileOracle&&this.graphFileOracle()){this.graphBuiltWithoutFileOracle=!1;try{await this.backlinkIndex.rebuildFromDisk(e),await this.saveBacklinksLogOnly(`file-inventory-reconcile`,e),this.signalChannel(`backlinks`),this.signalChannel(`graph`)}catch(t){this.graphBuiltWithoutFileOracle=!0,y4.warn({err:t,branch:e},`[backlinks] file-inventory reconciliation failed; graph retains its startup extraction`)}}}async rebuildLocalTargets(e){try{let t=this.getLocalTargetInventory();if(t===null)return this.localTargetIndex.markUnavailable(),y4.warn({reason:e},`[local-target] watcher inventory unavailable; index remains not ready`),!1;let n={documentTargets:new Set([...this.backlinkIndex.getIndexedDocNames(),...t.documentTargets]),fileTargets:t.fileTargets};return await this.localTargetIndex.rebuildFromDisk(n),this.localTargetRebuildRetryAttempt=0,this.cancelLocalTargetRebuildRetry(),!0}catch(t){return y4.warn({err:t,reason:e},`[local-target] rebuild failed; retaining the last complete snapshot and scheduling recovery`),this.scheduleLocalTargetRebuildRetry(e),!1}}reconcileLocalTargetInventory(){let e=this.getLocalTargetInventory();return e===null?(this.localTargetIndex.markUnavailable(),null):(this.localTargetIndex.reconcileDocumentTargets(new Set([...this.backlinkIndex.getIndexedDocNames(),...e.documentTargets])),this.localTargetIndex.reconcileFileTargets(e.fileTargets),this.localTargetIndex.reconcileFolderTargets(e.folderTargets),e)}syncLocalTargetBaseline(){let e=this.localTargetIndex.generation,t=e-this.lastSignaledLocalTargetGeneration;t>0&&Uit(`local-target`,`baseline`,t),this.lastSignaledLocalTargetGeneration=e}scheduleLocalTargetRebuildRetry(e){if(this.closed||this.localTargetRebuildRetryTimer!==null)return;let t=Math.min(1e3*2**this.localTargetRebuildRetryAttempt,3e4);this.localTargetRebuildRetryAttempt++,this.localTargetRebuildRetryTimer=setTimeout(()=>{this.localTargetRebuildRetryTimer=null,this.runCommand(async()=>{await this.rebuildLocalTargets(`retry:${e}`)&&this.maybeSignalLocalTargets()}).catch(t=>{this.closed||y4.warn({err:t,reason:e},`[local-target] recovery enqueue failed`)})},t),this.localTargetRebuildRetryTimer.unref?.()}cancelLocalTargetRebuildRetry(){this.localTargetRebuildRetryTimer!==null&&(clearTimeout(this.localTargetRebuildRetryTimer),this.localTargetRebuildRetryTimer=null)}scheduleSave(e=!0){let t=this.saveTagsOnNextDebounce||e;this.cancelScheduledSave(),this.saveTagsOnNextDebounce=t,this.saveTimer=setTimeout(()=>{this.saveTimer=null;let e=this.saveTagsOnNextDebounce;this.saveTagsOnNextDebounce=!1,this.enqueueInternal(()=>this.saveScheduledCache(e,`debounced`)).catch(e=>{y4.warn({err:e},`Failed to enqueue debounced derived-index cache save`)})},2e3)}cancelScheduledSave(){let e=this.saveTimer===null?null:this.saveTagsOnNextDebounce;return this.saveTimer!==null&&clearTimeout(this.saveTimer),this.saveTimer=null,this.saveTagsOnNextDebounce=!1,e}saveScheduledCache(e,t){return e?this.saveBothLogOnly(t):this.saveBacklinksLogOnly(`${t}-backlinks`)}releaseBranchTransition(e){let t=this.branchTransition;!e||t!==e||(this.branchTransition=null,t.barrier.resolve())}async saveBothLogOnly(e,t){await this.saveBacklinksLogOnly(e,t),await this.saveTagsLogOnly(e)}async saveBacklinksLogOnly(e,t){try{await this.backlinkIndex.saveToDisk(t)}catch(n){y4.warn({err:n,reason:e,branch:t},`Failed to persist backlink cache`)}}async saveTagsLogOnly(e){try{await this.tagIndex.saveToDisk()}catch(t){y4.warn({err:t,reason:e},`Failed to persist tag snapshot`)}}async ingestGlobalSkillNodesLogOnly(e,t){try{await this.backlinkIndex.ingestGlobalSkillBundles(this.getGlobalSkillRoots(),e)}catch(n){y4.warn({err:n,branch:e,reason:t},`Global skill bundle ingest failed`)}}async runCommand(e){return this.assertOpen(),await this.startupAdmission.promise,this.assertOpen(),this.enqueueAfterBranchAdmission(e)}async runQuery(e){return this.assertOpen(),await this.startupAdmission.promise,await this.readyBarrier.promise,this.assertOpen(),this.enqueueAfterBranchAdmission(e)}runLocalTargetQuery(e){return this.runQuery(()=>{if(!this.localTargetIndex.isReady())throw new Xat;return e()})}async enqueueAfterBranchAdmission(e){for(;;){let t=this.branchTransition;if(!t)return this.assertOpen(),this.enqueueInternal(()=>(this.assertOpen(),e()));await t.barrier.promise,this.assertOpen()}}enqueueInternal(e){let t=this.tail.then(e);return this.tail=t.then(()=>void 0,e=>{x4(e)?y4.debug({err:e},`Derived document index operation rejected after close`):y4.warn({err:e},`Derived document index operation failed; queue remains available`)}),t}assertOpen(){if(this.closed)throw new Yat}};function $at(e){throw Error(`[StorePublishOutcome] unhandled variant: ${JSON.stringify(e)}`)}function eot(e){throw Error(`[DeferredStoreWait] unhandled variant: ${JSON.stringify(e)}`)}const S4=`OK_DOC_REMOVED`,C4=2e4,w4=18e5;function tot(e){return e.reduce((e,t)=>Math.min(e,t.at+w4),1/0)}function T4(e){let t=[`{"version":1,"branches":{`];for(let[n,r]of Object.entries(Object.fromEntries(e))){t.length>1&&t.push(`,`),t.push(JSON.stringify(n),`:[`);for(let[e,n]of r.entries())e>0&&t.push(`,`),t.push(n);t.push(`]`)}return t.push(`}}`),t}function not(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&typeof e.then==`function`}function rot(e,t){let n;try{n=t instanceof Error?String(t.message):String(t)}catch{n=`unserializable rejection reason`}console.warn(JSON.stringify({event:`persistence-store-publish-async-rejected`,"doc.name":e.docName,generation:e.generation,error:n}))}function iot(e,t){return e?.docName===t?.docName&&e?.file===t?.file&&e?.diskHash===t?.diskHash&&e?.diskContent===t?.diskContent&&e?.retainedContent===t?.retainedContent&&e?.detectedAt===t?.detectedAt}var E4=class extends Error{kind;path;constructor(e,t,n){let r=n instanceof Error&&`code`in n&&typeof n.code==`string`?n.code:void 0,i=t===`unreadable`?r===`EACCES`||r===`EPERM`?`Check the snapshot and parent-directory permissions for the account running OpenKnowledge, then retry.`:r===`EISDIR`?`The snapshot path must be a regular file, not a directory. Preserve that directory and restore the snapshot file to this path.`:`Check the filesystem or mount and restore read access to this path, then retry.`:t===`incompatible`?`This build does not support the snapshot schema. Preserve the file and restore a compatible backup or contact support to identify a compatible build.`:`Restore this snapshot from a known-good backup, or contact support to recover its protected edits.`;super(`Cannot safely open this project: its stale-write recovery snapshot is ${t}${r?` [${r}]`:``} (${e}). The snapshot has been preserved because it may contain the only copy of protected edits. ${i} Run ${de()} bug-report from the project directory to collect diagnostics without starting the server. Do not delete it to bypass recovery.`,{cause:n}),this.name=`DocumentDurabilityStateError`,this.kind=t,this.path=e}};function D4(e,t,n){n===void 0?e.delete(t):e.set(t,n)}function aot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.hash==`string`&&typeof t.at==`number`}function oot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.file==`string`&&typeof t.diskHash==`string`&&typeof t.diskContent==`string`&&typeof t.detectedAt==`string`&&(t.retainedContent===void 0||typeof t.retainedContent==`string`)}function sot(e){if(!e||typeof e!=`object`)return null;let t=e;if(t.version!==1||!t.branches||typeof t.branches!=`object`||Array.isArray(t.branches))return null;let n=new Map;for(let[e,r]of Object.entries(t.branches)){if(!Array.isArray(r))return null;let t=[];for(let e of r){if(!e||typeof e!=`object`)return null;let n=e;if(typeof n.docName!=`string`||typeof n.acknowledgedContent!=`string`||!Array.isArray(n.displacedVersions)||!n.displacedVersions.every(aot)||n.staleExternalWrite!==void 0&&(!oot(n.staleExternalWrite)||n.staleExternalWrite.docName!==n.docName||n.staleExternalWrite.diskHash!==_Y(n.staleExternalWrite.diskContent)))return null;t.push({docName:n.docName,acknowledgedContent:n.acknowledgedContent,displacedVersions:n.displacedVersions,...n.staleExternalWrite?{staleExternalWrite:n.staleExternalWrite}:{}})}n.set(e,t)}return{version:1,branches:Object.fromEntries(n)}}var O4=class{reconciledBaseByBranch=new Map;displacedVersionsByBranch=new Map;staleExternalWritesByBranch=new Map;inFlightFlushByDoc=new Map;storeAttemptGenerations=new Map;publishedStoreGenerations=new Map;documentsWithPublishInFlight=new Set;agentWriteStores=new Set;refusedStoreDocNames=new Set;storeFailures=new Map;storeDivergences=new Set;staleExternalWriteFreezes=new Set;persistencePath;fileForDocName;onStaleExternalWriteChange;onStoreRefused;hasResolvedExtension;cachedDocumentsByBranch=new Map;lastPersistedParts=T4(new Map);nextDisplacedExpiryAt=1/0;activeBranch;batchInProgress=!1;writeAdmissionHolds=0;writeAdmissionWaiters=new Set;writeWaitDeadline=new mc;deferredStoreOutcomes=new Map;constructor(e=`main`,t={}){this.activeBranch=e,this.persistencePath=t.persistencePath,this.fileForDocName=t.fileForDocName??(e=>`${e}.md`),this.onStaleExternalWriteChange=t.onStaleExternalWriteChange,this.onStoreRefused=t.onStoreRefused,this.hasResolvedExtension=t.hasResolvedExtension,this.reconciledBaseByBranch.set(e,new Map),this.restore()}switchReconciledBaseScope(e){this.persist(),this.activeBranch=e,this.reconciledBaseByBranch.has(e)||this.reconciledBaseByBranch.set(e,new Map)}getActiveBranch(){return this.activeBranch}getReconciledBase(e){return this.reconciledBaseByBranch.get(this.activeBranch)?.get(e)}setReconciledBase(e,t){let n=this.reconciledBaseByBranch.get(this.activeBranch);if(n||(n=new Map,this.reconciledBaseByBranch.set(this.activeBranch,n)),!(n.get(e)===t&&Date.now()<this.nextDisplacedExpiryAt)){if(!this.isPersistedDocument(e)){n.set(e,t);return}this.mutateDocument(e,()=>n.set(e,t))}}recordSuccessfulStore(e,t,n){if(n===void 0){this.setReconciledBase(e,t);return}let r=Date.now(),i=_Y(n);this.mutateDocument(e,()=>{let n=this.reconciledBaseByBranch.get(this.activeBranch);n||(n=new Map,this.reconciledBaseByBranch.set(this.activeBranch,n));let a=this.displacedVersionsByBranch.get(this.activeBranch);a||(a=new Map,this.displacedVersionsByBranch.set(this.activeBranch,a));let o=(a.get(e)??[]).filter(e=>e.at>r-18e5&&e.hash!==i);o.push({hash:i,at:r}),n.set(e,t),a.set(e,o.slice(-8))})}deleteReconciledBase(e){this.refusedStoreDocNames.delete(e),this.storeFailures.delete(e);let t=this.isPersistedDocument(e);if(!t){this.reconciledBaseByBranch.get(this.activeBranch)?.delete(e),this.inFlightFlushByDoc.delete(e);return}this.mutateDocument(e,()=>{this.reconciledBaseByBranch.get(this.activeBranch)?.delete(e),this.inFlightFlushByDoc.delete(e),this.displacedVersionsByBranch.get(this.activeBranch)?.delete(e),this.staleExternalWritesByBranch.get(this.activeBranch)?.delete(e)},t)}freshDisplacedVersions(e){let t=this.displacedVersionsByBranch.get(this.activeBranch),n=t?.get(e);if(!t||!n)return[];let r=Date.now()-w4,i=n.filter(e=>e.at>r);return i.length===n.length?n:(this.mutateDocument(e,()=>{i.length===0?t.delete(e):t.set(e,i)}),i)}recordDisplacedVersion(e,t){let n=_Y(t),r=this.freshDisplacedVersions(e).filter(e=>e.hash!==n);r.push({hash:n,at:Date.now()});let i=this.displacedVersionsByBranch.get(this.activeBranch);i||(i=new Map,this.displacedVersionsByBranch.set(this.activeBranch,i)),this.mutateDocument(e,()=>i.set(e,r.slice(-8)))}clearDisplacedVersions(e){this.displacedVersionsByBranch.get(this.activeBranch)?.has(e)&&this.mutateDocument(e,()=>this.displacedVersionsByBranch.get(this.activeBranch)?.delete(e))}isDisplacedVersion(e,t){let n=this.freshDisplacedVersions(e);if(n.length===0)return!1;let r=_Y(t);return n.some(e=>e.hash===r)}recordStaleExternalWrite(e,t,n){let r=this.staleExternalWritesByBranch.get(this.activeBranch);r||(r=new Map,this.staleExternalWritesByBranch.set(this.activeBranch,r));let i=_Y(t),a=r.get(e);if(a?.diskHash===i&&(n===void 0||n===a.retainedContent))return a;let o=a?.diskHash!==i,s=n??a?.retainedContent,c={docName:e,file:this.fileForDocName(e),diskHash:i,diskContent:t,...s===void 0?{}:{retainedContent:s},detectedAt:a?.diskHash===i?a.detectedAt:new Date().toISOString()};return this.mutateDocument(e,()=>r.set(e,c)),o&&sXe(),c}staleExternalWriteMatches(e,t){let n=this.staleExternalWritesByBranch.get(this.activeBranch)?.get(e);return n!==void 0&&n.diskHash===_Y(t)}listStaleExternalWrites(){return[...this.staleExternalWritesByBranch.get(this.activeBranch)?.values()??[]].map(e=>this.withResolvedFile(e))}getStaleExternalWrite(e){let t=this.staleExternalWritesByBranch.get(this.activeBranch)?.get(e);return t===void 0?void 0:this.withResolvedFile(t)}withResolvedFile(e){if(this.hasResolvedExtension&&!this.hasResolvedExtension(e.docName))return e;let t=this.fileForDocName(e.docName);return t===e.file?e:{...e,file:t}}clearStaleExternalWrite(e){let t=this.staleExternalWritesByBranch.get(this.activeBranch);t?.get(e)&&this.mutateDocument(e,()=>t?.delete(e))}restoreStaleExternalWrite(e,t){let n=this.staleExternalWritesByBranch.get(t);n||(n=new Map,this.staleExternalWritesByBranch.set(t,n)),!n.has(e.docName)&&this.mutateDocument(e.docName,()=>n.set(e.docName,e))}mutateDocument(e,t,n=!0){let r=this.reconciledBaseByBranch.get(this.activeBranch)??new Map,i=this.displacedVersionsByBranch.get(this.activeBranch)??new Map,a=this.staleExternalWritesByBranch.get(this.activeBranch)??new Map,o=r.get(e),s=i.get(e),c=a.get(e),l=this.inFlightFlushByDoc.get(e),u;try{u=t(),n&&this.persist()}catch(t){throw D4(r,e,o),D4(i,e,s),D4(a,e,c),D4(this.inFlightFlushByDoc,e,l),this.reconciledBaseByBranch.set(this.activeBranch,r),this.displacedVersionsByBranch.set(this.activeBranch,i),this.staleExternalWritesByBranch.set(this.activeBranch,a),t}return c!==a.get(e)&&this.onStaleExternalWriteChange?.(),u}isPersistedDocument(e){return this.displacedVersionsByBranch.get(this.activeBranch)?.has(e)===!0||this.staleExternalWritesByBranch.get(this.activeBranch)?.has(e)===!0}restore(){if(!this.persistencePath)return;let e;try{e=K(this.persistencePath,`utf-8`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw new E4(this.persistencePath,`unreadable`,e)}let t;try{t=JSON.parse(e)}catch(e){throw new E4(this.persistencePath,`corrupt`,e)}if(t&&typeof t==`object`&&`version`in t&&t.version!==1)throw new E4(this.persistencePath,`incompatible`);let n=sot(t);if(!n)throw new E4(this.persistencePath,`corrupt`);let r=Date.now()-w4,i=new Map;for(let[e,t]of Object.entries(n.branches)){let n=new Map,a=new Map,o=new Map,s=new Map,c=[];for(let e of t){if(e.staleExternalWrite)try{this.fileForDocName(e.docName)}catch(e){throw new E4(this.persistencePath,`corrupt`,e)}let t=JSON.stringify(e);c.push(t);let i=tot(e.displacedVersions);this.nextDisplacedExpiryAt=Math.min(this.nextDisplacedExpiryAt,i);let l=e.displacedVersions.filter(e=>e.at>r);l.length===0&&!e.staleExternalWrite||(n.set(e.docName,e.acknowledgedContent),l.length>0&&a.set(e.docName,l),e.staleExternalWrite&&o.set(e.docName,e.staleExternalWrite),l.length===e.displacedVersions.length&&s.set(e.docName,{acknowledgedContent:e.acknowledgedContent,displacedVersions:a.get(e.docName),staleExternalWrite:e.staleExternalWrite?{...e.staleExternalWrite}:void 0,expiresAt:i,serialized:t}))}i.set(e,c),this.reconciledBaseByBranch.set(e,n),a.size>0&&this.displacedVersionsByBranch.set(e,a),o.size>0&&this.staleExternalWritesByBranch.set(e,o),s.size>0&&this.cachedDocumentsByBranch.set(e,s)}this.reconciledBaseByBranch.has(this.activeBranch)||this.reconciledBaseByBranch.set(this.activeBranch,new Map),this.lastPersistedParts=T4(i)}pruneExpiredDisplacedVersions(e){this.nextDisplacedExpiryAt=1/0;for(let[t,n]of this.displacedVersionsByBranch){for(let[t,r]of n){let i=r.filter(t=>t.at>e);i.length===0?n.delete(t):i.length!==r.length&&n.set(t,i);for(let e of i)this.nextDisplacedExpiryAt=Math.min(this.nextDisplacedExpiryAt,e.at+w4)}n.size===0&&this.displacedVersionsByBranch.delete(t)}}persist(){let e=Date.now()-w4;if(!this.persistencePath){this.pruneExpiredDisplacedVersions(e);return}let t=new Map,n=new Map,r=new Set([...this.displacedVersionsByBranch.keys(),...this.staleExternalWritesByBranch.keys()]);for(let i of r){let r=new Set([...this.displacedVersionsByBranch.get(i)?.keys()??[],...this.staleExternalWritesByBranch.get(i)?.keys()??[]]),a=[],o=new Map;for(let t of r){let n=this.reconciledBaseByBranch.get(i)?.get(t);if(n===void 0)continue;let r=this.displacedVersionsByBranch.get(i)?.get(t),s=this.staleExternalWritesByBranch.get(i)?.get(t),c=this.cachedDocumentsByBranch.get(i)?.get(t);if(c&&c.acknowledgedContent===n&&c.displacedVersions===r&&iot(c.staleExternalWrite,s)&&c.expiresAt>e+18e5){a.push(c.serialized),o.set(t,c);continue}let l=(r??[]).filter(t=>t.at>e);if(l.length===0&&!s)continue;let u={docName:t,acknowledgedContent:n,displacedVersions:l,...s?{staleExternalWrite:s}:{}},d=JSON.stringify(u);a.push(d),o.set(t,{acknowledgedContent:n,displacedVersions:r,staleExternalWrite:s?{...s}:void 0,expiresAt:tot(l),serialized:d})}a.length>0&&(t.set(i,a),n.set(i,o))}let i=T4(t);if(i.length===this.lastPersistedParts.length&&i.every((e,t)=>e===this.lastPersistedParts[t])){this.cachedDocumentsByBranch=n,this.pruneExpiredDisplacedVersions(e);return}let a=i.join(``);KH(V(this.persistencePath),{recursive:!0});let o=Fx(this.persistencePath);try{WH(o,a,{encoding:`utf-8`,mode:384,flag:`wx`}),qH(o,this.persistencePath),this.lastPersistedParts=i,this.cachedDocumentsByBranch=n}catch(e){try{G(o)&&XH(o)}catch(t){q(`document-durability-state`).warn({err:t,writeError:e instanceof Error?e.message:String(e),temporaryPath:o},`Unable to remove failed recovery snapshot temporary file`)}throw e}this.pruneExpiredDisplacedVersions(e)}freshInFlightFlushes(e){let t=this.inFlightFlushByDoc.get(e);if(!t)return[];let n=Date.now(),r=t.filter(e=>n-e.at<=6e4);return r.length===t.length?t:(SZe(t.length-r.length),r.length===0?this.inFlightFlushByDoc.delete(e):this.inFlightFlushByDoc.set(e,r),r)}beginInFlightFlush(e,t){let n=this.freshInFlightFlushes(e);n.push({value:t,at:Date.now()}),this.inFlightFlushByDoc.set(e,n)}peekInFlightFlush(e){let t=this.freshInFlightFlushes(e);return t[t.length-1]?.value}inFlightFlushCount(e){return this.freshInFlightFlushes(e).length}hasInFlightFlush(e,t){return this.freshInFlightFlushes(e).some(e=>e.value===t)}finishInFlightFlush(e,t){let n=this.freshInFlightFlushes(e);for(let r=n.length-1;r>=0;r--)if(n[r]?.value===t){n.splice(r,1),n.length===0&&this.inFlightFlushByDoc.delete(e);return}}beginStoreAttempt(e){let t=(this.storeAttemptGenerations.get(e)??0)+1;return this.storeAttemptGenerations.set(e,t),{docName:e,generation:t}}tryPublishStore(e,t){if(this.documentsWithPublishInFlight.has(e.docName))return`reentrant`;let n=this.publishedStoreGenerations.get(e.docName)??0;if(e.generation<=n)return`stale`;this.documentsWithPublishInFlight.add(e.docName);try{let n=t();if(not(n)){try{n.then(()=>{},t=>rot(e,t))}catch{}throw TypeError(`tryPublishStore: the publish callback must complete synchronously, but it returned a thenable (${e.docName} generation ${e.generation})`)}return this.publishedStoreGenerations.set(e.docName,e.generation),`published`}finally{this.documentsWithPublishInFlight.delete(e.docName)}}setBatchInProgress(e){this.batchInProgress=e}isBatchInProgress(){return this.batchInProgress}holdWriteAdmission(){this.writeAdmissionHolds++;let e=!1;return()=>{if(e||(e=!0,this.writeAdmissionHolds--,this.writeAdmissionHolds>0))return;let t=[...this.writeAdmissionWaiters];this.writeAdmissionWaiters.clear();for(let e of t)e()}}isWriteAdmissionHeld(){return this.writeAdmissionHolds>0}runWithinWriteWaitBudget(e,t=C4){return this.writeWaitDeadline.run(Date.now()+t,e)}remainingWriteWait(e){let t=this.writeWaitDeadline.getStore();return t===void 0?e:Math.max(0,Math.min(e,t-Date.now()))}async whenWriteAdmitted(e=C4){if(!this.isWriteAdmissionHeld())return!0;let t=this.remainingWriteWait(e);if(t===0)return!1;let n=()=>{},r=!1,i=setTimeout(()=>{r=!0,n()},t);try{for(;this.isWriteAdmissionHeld()&&!r;)await new Promise(e=>{n=e,this.writeAdmissionWaiters.add(e)}),this.writeAdmissionWaiters.delete(n);return!this.isWriteAdmissionHeld()}finally{clearTimeout(i)}}openDeferredStore(e){let{promise:t,resolve:n}=Promise.withResolvers();return this.deferredStoreOutcomes.set(e,t),{settle:r=>{this.deferredStoreOutcomes.get(e)===t&&this.deferredStoreOutcomes.delete(e),n(r)}}}async awaitDeferredStoreOutcome(e,t=C4){let n=this.deferredStoreOutcomes.get(e);if(n===void 0||!this.isWriteAdmissionHeld())return;let r={kind:`unsettled`},i=this.remainingWriteWait(t);if(i===0)return r;let a,o=new Promise(e=>{a=setTimeout(()=>e(r),i)});try{return await Promise.race([n,o])}finally{clearTimeout(a)}}markAgentWriteStore(e){this.agentWriteStores.add(e)}consumeAgentWriteStore(e){return this.agentWriteStores.delete(e)}markStoreRefused(e){this.refusedStoreDocNames.add(e),this.onStoreRefused?.(e)}clearStoreRefused(e){this.refusedStoreDocNames.delete(e)}isStoreRefused(e){return this.refusedStoreDocNames.has(e)}getRefusedStoreDocNames(){return[...this.refusedStoreDocNames]}recordStoreFailure(e,t){this.storeFailures.set(e,t)}clearStoreFailure(e){this.storeFailures.delete(e)}takeStoreFailure(e){let t=this.storeFailures.get(e)??null;return this.storeFailures.delete(e),t}recordStoreDivergence(e){this.storeDivergences.add(e)}takeStoreDivergence(e){return this.storeDivergences.delete(e)}recordStaleExternalWriteFreeze(e){this.staleExternalWriteFreezes.add(e)}takeStaleExternalWriteFreeze(e){return this.staleExternalWriteFreezes.delete(e)}};const k4=3000000000n,cot=()=>BigInt(Date.now())*1000000n,A4=e=>`${e.dev}:${e.ino}:${e.size}:${e.mtimeNs}:${e.ctimeNs}`,j4=(e,t)=>e.ctimeNs+k4>t||e.mtimeNs+k4>t&&e.mtimeNs<=t+k4,lot=/^[ -~]*$/,uot=new Map,M4=new Map;function dot(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function fot(e){let t=cot();try{let n=Ls(e,{bigint:!0});return{signature:A4(n),racy:j4(n,t)}}catch(e){if(e.code===`ENOENT`)return null;throw e}}function pot(e){let t=new Set;for(let n of e){let e=n;for(;e!==``&&!t.has(e);)t.add(e),e=dot(e)}return t}async function mot(e,t,n){let r=W(t),i=uot.get(r);i===void 0&&(i=W(r,(await e.raw(`rev-parse`,`--git-path`,`index`)).trim()),uot.set(r,i));let a=fot(i);if(a===null)return M4.delete(r),!1;let o=dot(n),s=M4.get(r),c=!a.racy&&lot.test(n);return c&&s?.indexSignature===a.signature&&s.scope===o?(s.listing??=pot(await aU(e,[`ls-files`,...o===``?[]:Bt([o])])),s.listing.has(n)):(c&&M4.set(r,{indexSignature:a.signature,scope:o,listing:void 0}),(await aU(e,[`ls-files`,...Bt([n])])).length>0)}function hot(e){let{assetService:t,log:n}=e,r={"missing-path":[400,`urn:ok:error:invalid-request`,`Missing asset path.`],"unsupported-type":[415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`],"not-found":[404,`urn:ok:error:asset-not-found`,`Asset not found.`],"invalid-path":[400,`urn:ok:error:invalid-request`,`Invalid asset path.`]},i=Z(me,async(e,i)=>{try{let a=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`),o=t.resolveServableAsset(a);if(!o.ok){let[e,t,n]=r[o.reason];X(i,e,t,n,{handler:`asset`,...o.cause===void 0?{}:{cause:o.cause}});return}let{asset:s}=o,c={"Content-Type":s.contentType,"Content-Length":String(s.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":s.disposition,"Cache-Control":`no-store`};s.csp!==null&&(c[`Content-Security-Policy`]=s.csp);let l=s.canonicalPath;i.writeHead(200,c);try{await hc(Es(l),i)}catch(e){let t=to.getActiveSpan(),r=rG(e),o=r===`ERR_STREAM_PREMATURE_CLOSE`||r===`ECONNRESET`||r===`EPIPE`;t?.setAttribute(Ny,o?`connection_closed`:`stream_failure`),t?.recordException(e instanceof Error?e:String(e)),t?.setStatus({code:ao.ERROR,message:`Asset transfer incomplete`}),n.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:a,err:e},`[asset] pipeline failed mid-stream`),i.destroyed||i.destroy(e instanceof Error?e:void 0)}}catch(e){X(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),a=1048576;return P$({"/api/asset":i,"/api/asset-text":Z(me,async(e,n)=>{try{let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`),o=t.resolveTextAsset(i);if(!o.ok){let[e,t,i]=r[o.reason];X(n,e,t,i,{handler:`asset-text`,...o.cause===void 0?{}:{cause:o.cause}});return}if(o.size>a){X(n,413,`urn:ok:error:payload-too-large`,`File exceeds the ${a}-byte text-viewer cap.`,{handler:`asset-text`});return}let s=(await Xs(o.canonicalPath)).toString(`utf-8`);n.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),n.end(s)}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0})})}const N4=`comments`,got={maxBytes:65536,timeoutMs:1e4},_ot={start:Fn().int().nonnegative().optional(),end:Fn().int().nonnegative().optional(),quote:R().min(1).optional(),prefix:R().max(1e3).optional(),suffix:R().max(1e3).optional()},vot=B({docName:R().min(1),..._ot,propertyKey:R().min(1).optional(),propertyPath:z(F([R(),Fn().int().nonnegative()])).optional(),body:R(),queue:Wa().optional(),summary:R().optional()}),P4=pr(),yot=ue(`action`,[B({action:P(`edit`),id:P4,body:R(),summary:R().optional()}),B({action:P(`resolve`),id:P4,summary:R().optional()}),B({action:P(`reopen`),id:P4,summary:R().optional()}),B({action:P(`replace`),id:P4,..._ot,summary:R().optional()}),B({action:P(`queue`),id:P4,summary:R().optional()}),B({action:P(`unqueue`),id:P4,summary:R().optional()}),B({action:P(`dispatch-prepare`),id:P4,summary:R().optional()}),B({action:P(`dispatch-complete`),id:P4,summary:R().optional()}),B({action:P(`dispatch-prepare-batch`),ids:z(P4).min(1).max(200),summary:R().optional()}),B({action:P(`dispatch-complete-batch`),ids:z(P4).min(1).max(200),summary:R().optional()})]);function bot(e){let{service:t,getPrincipal:n,onChanged:r}=e;async function i(e,n){let r=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??void 0;try{let e=await t.listThreads(r);Q(n,200,tt,{threads:e},{handler:N4})}catch(e){L4(n,e,`Failed to list comment threads.`)}}function a(e,t){let n=new URL(e.url??``,`http://localhost`).searchParams.get(`id`);return n?P4.safeParse(n).success?n:(F4(t,`id must be a comment thread UUID.`),null):(F4(t,`id query parameter is required.`),null)}async function o(e,n){let r=a(e,n);if(r!==null)try{let e=await t.readThread(r);Q(n,200,bi,e,{handler:N4})}catch(e){if(e instanceof k1)return I4(n,`Comment thread not found.`);L4(n,e,`Failed to read comment thread.`)}}async function s(e,i){let a=await xot(e,i,vot);if(!a)return;let o=y$(a,n);if(o.kind===`invalid-summary`)return F4(i,`Summary must be a string.`);let s=Sot(o);if(!s)return F4(i,`A principal or agent identity is required to comment.`);try{let e=await t.createThread({docName:a.docName,start:a.start,end:a.end,quote:a.quote,prefix:a.prefix,suffix:a.suffix,propertyKey:a.propertyKey,propertyPath:a.propertyPath,author:s,body:a.body,queue:a.queue});r?.(),Q(i,201,bi,e,{handler:N4})}catch(e){if(e instanceof O1)return I4(i,`Document not found.`);if(e instanceof j1)return F4(i,`The quoted passage is not in the document.`);if(e instanceof A1)return F4(i,`That property is not in the document: ${e.message}`);if(e instanceof RangeError||e instanceof Error&&/invalid selection|is required/.test(e.message))return F4(i,`Selection range is invalid for the document.`);L4(i,e,`Failed to create comment thread.`)}}async function c(e,i){let a=await xot(e,i,yot);if(!a)return;let o=y$(a,n);if(o.kind===`invalid-summary`)return F4(i,`Summary must be a string.`);try{switch(a.action){case`edit`:return Sot(o)?u(i,await t.editComment(a.id,a.body)):F4(i,`An identity is required to edit a comment.`);case`resolve`:return u(i,await t.resolve(a.id));case`reopen`:return u(i,await t.reopen(a.id));case`replace`:return u(i,await t.replaceAnchor(a.id,{start:a.start,end:a.end,quote:a.quote,prefix:a.prefix,suffix:a.suffix}));case`queue`:{let e=await t.queueForDispatch(a.id);return r?.(),Q(i,200,jte,e,{handler:N4})}case`unqueue`:return u(i,await t.unqueue(a.id));case`dispatch-prepare`:{let e=await t.prepareDispatch(a.id);return r?.(),Q(i,200,nie,e,{handler:N4})}case`dispatch-complete`:return u(i,await t.completeDispatch(a.id));case`dispatch-prepare-batch`:{let e=await t.prepareDispatchBatch(a.ids);return r?.(),Q(i,200,Ine,{results:e},{handler:N4})}case`dispatch-complete-batch`:{let e=await t.completeDispatchBatch(a.ids);return r?.(),Q(i,200,Pne,{results:e},{handler:N4})}}}catch(e){if(e instanceof k1)return I4(i,`Comment thread not found.`);if(e instanceof O1)return I4(i,`Document not found.`);if(e instanceof j1)return F4(i,`The quoted passage is not in the document.`);if(e instanceof A1)return F4(i,`That property is not in the document: ${e.message}`);if(e instanceof Error&&/invalid selection|is required/.test(e.message))return F4(i,`Selection range is invalid for the document.`);L4(i,e,`Failed to update comment thread.`)}}async function l(e,n){let i=a(e,n);if(i!==null)try{await t.delete(i),r?.(),Q(n,200,Xee,{threadId:i},{handler:N4})}catch(e){L4(n,e,`Failed to delete comment thread.`)}}function u(e,t){r?.(),Q(e,200,bi,t,{handler:N4})}return{list:i,read:o,create:s,mutate:c,remove:l}}async function xot(e,t,n){let r;try{r=await L$(e,got)}catch(e){return e instanceof R$?(z$(t,N4),null):(F4(t,`Request body could not be read.`),null)}let i;try{i=JSON.parse(r.toString(`utf8`)||`{}`)}catch{return F4(t,`Request body must be valid JSON.`),null}let a=n.safeParse(i);return a.success?a.data:(F4(t,`Request body is invalid.`),null)}function Sot(e){return e.kind===`agent`||e.kind===`principal`?e.writerId:null}function F4(e,t){X(e,400,`urn:ok:error:invalid-request`,t,{handler:N4})}function I4(e,t){X(e,404,`urn:ok:error:not-found`,t,{handler:N4})}function L4(e,t,n){X(e,500,`urn:ok:error:internal-server-error`,n,{handler:N4,cause:t})}function Cot(e){let{commentService:t,getPrincipal:n,signalChannel:r}=e,i=bot({service:t,getPrincipal:n,onChanged:()=>r?.(`comments`)});return P$({"/api/comments":i2({GET:i.list,POST:i.create},{handler:`comments`}),"/api/comment":i2({GET:i.read,POST:i.mutate,DELETE:i.remove},{handler:`comment`})},{mutating:[`/api/comments`,`/api/comment`]})}function wot(e,t,n){return e.filter(W8e).map(e=>{let r=B8e(e),i=r.at(-1)??null;return{value:e.slug,label:e.slug,description:null,group:null,source:`native-cli`,fingerprint:t,freshness:{kind:`cached`,at:n},selectability:`candidate`,context:i===null?null:{effectiveTokens:z8e(i,e),origin:`native-catalog`},contextChoices:r,setPhase:`launch-only`}})}function Tot(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function R4(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Eot(e){let t;try{t=JSON.parse(e)}catch{return[]}let n=Tot(t),r=Array.isArray(t)?t:n.models;return Array.isArray(r)?r.flatMap(e=>{let t=Tot(e),n=t.slug;return typeof n!=`string`||n===``?[]:[{slug:n,visibility:typeof t.visibility==`string`?t.visibility:null,contextWindow:R4(t.context_window),maxContextWindow:R4(t.max_context_window),effectivePercent:R4(t.effective_context_window_percent)}]}):[]}function Dot(e,t,n){let r={};for(let[e,n]of Object.entries(t))typeof n==`string`&&(r[e]=n);let i=n===`win32`,a=i?SQ(e,yQ(r)):e,o=i&&/\.(cmd|bat)$/i.test(a);return{...o?CQ(a,[`debug`,`models`]):{cmd:a,args:[`debug`,`models`]},wrap:o,env:r}}async function Oot(e,t=process.env,n=process.platform){let{cmd:r,args:i,wrap:a,env:o}=Dot(e,t,n);return new Promise(e=>{let t;try{t=ls(r,i,{env:o,stdio:[`ignore`,`pipe`,`ignore`],shell:!1,detached:n!==`win32`,windowsHide:!0,windowsVerbatimArguments:a})}catch(t){e(t.code===`ENOENT`?{outcome:`not-found`}:{outcome:`failed`});return}let s=()=>{DQ(t,{graceMs:1e3})},c=``,l=0,u=!1,d=t=>{u||(u=!0,clearTimeout(f),e(t))},f=setTimeout(()=>{s(),d({outcome:`failed`})},8e3);t.stdout?.on(`data`,e=>{if(l+=e.length,l>4194304){s(),d({outcome:`failed`});return}c+=e.toString(`utf8`)}),t.on(`error`,e=>{d(e.code===`ENOENT`?{outcome:`not-found`}:{outcome:`failed`})}),t.on(`close`,e=>{d(e===0?{outcome:`ok`,models:Eot(c)}:{outcome:`failed`})})})}let z4,B4;function kot(e=new Date().toISOString()){z4={startedAt:e},B4=performance.now()}function Aot(){if(B4!==void 0)return Math.round(performance.now()-B4)}function V4(e,t){z4&&(z4[e]=t)}function jot(e,t){z4&&(z4[e]=t)}function Mot(){return z4}function Not(e){let t=e.host;if(!t)return null;let n=e[`x-forwarded-proto`];return`${(Array.isArray(n)?n[0]:n)===`https`?`wss`:`ws`}://${t}/collab`}const Pot=q(`embeddings`);let Fot=null,Iot=null,Lot=null,Rot=null,zot=null;function Bot(){return Fot||=_H().createCounter(`ok.embeddings.tokens_total`,{description:`Embeddings tokens billed, by role. Bounded label: role ∈ {query, document}. Makes spend legible; never includes content.`}),Fot}function Vot(){return Iot||=_H().createCounter(`ok.embeddings.provider_errors_total`,{description:`Embeddings provider failures, by reason. Bounded label: reason ∈ {rate_limit, timeout, http_error, network, dims_mismatch, malformed_response}.`}),Iot}function Hot(){return Lot||=_H().createHistogram(`ok.embeddings.request_duration_ms`,{description:`Wall-clock duration of one embeddings API request. Bounded label: role.`,unit:`ms`}),Lot}function Uot(){return Rot||=_H().createCounter(`ok.search.semantic_query_total`,{description:`Semantic-requested searches, by outcome and caller surface. Bounded labels: outcome ∈ {applied, no_match, warming, incapable, provider_error}, source ∈ {omnibar, mcp, http}. The omnibar/mcp split separates interactive cost from agent cost.`}),Rot}function Wot(){return zot||=_H().createHistogram(`ok.search.semantic_query_embed_ms`,{description:`Wall-clock latency of the per-query embed on the semantic search path.`,unit:`ms`}),zot}function Got(e,t){t>0&&Bot().add(t,{role:e})}function Kot(e){Vot().add(1,{reason:e})}function qot(e,t){Hot().record(Math.max(0,t),{role:e})}function Jot(e){Uot().add(1,{outcome:e.outcome,source:e.source}),e.queryEmbedMs!==null&&Wot().record(Math.max(0,e.queryEmbedMs)),Pot.debug({outcome:e.outcome,source:e.source,capable:e.capable,embedded:e.embedded,total:e.total,coverage:e.total>0?e.embedded/e.total:0,queryEmbedMs:e.queryEmbedMs,vectorContributors:e.vectorContributors},`[search] semantic query`)}const Yot=q(`embeddings`),Xot=1536,Zot=`OK_EMBEDDINGS_API_KEY`;var H4=class extends Error{reason;status;constructor(e,t,n,r){super(t,r),this.reason=e,this.status=n,this.name=`EmbeddingProviderError`}},U4=class extends H4{name=`EmbeddingDimsMismatchError`;expected;got;constructor(e,t){super(`dims_mismatch`,`embeddings provider returned ${t}-dim vectors, expected ${e}`),this.expected=e,this.got=t}},W4=class extends H4{name=`MalformedEmbeddingResponseError`;constructor(e){super(`malformed_response`,e)}};function Qot(e,t){let n=0,r=Math.min(e.length,t.length);for(let i=0;i<r;i++)n+=e[i]*t[i];return n}function $ot(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];if(t=Math.sqrt(t),t>0)for(let n=0;n<e.length;n++)e[n]/=t;return e}const G4={maxBatchSize:96,maxBatchChars:Vte,docTimeoutMs:Ote,queryTimeoutMs:8e3,maxRetries:4,backoffBaseMs:500};function K4(e){try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${n}`}catch{return e.trim().replace(/\/+$/,``)}}function est(e){let t=pe(e);if(t===null)return;if(t===`invalid-url`)throw Error(`embeddings baseUrl is not a valid URL: ${e}`);let n=new URL(e);throw Error(`refusing to send the embeddings API key to a non-HTTPS endpoint (${n.protocol}//${n.host}); use https:// (http:// is allowed only for localhost)`)}const tst=new Set([408,409,429,500,502,503,504]);function q4(e,t={}){let n=t.fetchImpl??fetch,r=t.sleep??Ai,i=t.maxBatchSize??G4.maxBatchSize,a=t.maxBatchChars??G4.maxBatchChars,o=t.maxRetries??G4.maxRetries,s=t.backoffBaseMs??G4.backoffBaseMs,c=t.docTimeoutMs??G4.docTimeoutMs,l=t.queryTimeoutMs??G4.queryTimeoutMs;est(e.baseUrl);let u=e.dimensions??null,d=`${e.baseUrl.replace(/\/+$/,``)}/embeddings`;function f(e){let t=[],n=[],r=0;for(let o of e)n.length>0&&(n.length>=i||r+o.length>a)&&(t.push(n),n=[],r=0),n.push(o),r+=o.length;return n.length>0&&t.push(n),t}async function p(t,r,i,a){let o=new AbortController,s=setTimeout(()=>o.abort(),a),c=performance.now();try{let a=await n(d,{method:`POST`,headers:{"Content-Type":`application/json`,...e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}},body:t,signal:o.signal});if(qot(i,performance.now()-c),!a.ok){await a.text().catch(()=>``);let e=a.status===429?`rate_limit`:`http_error`,t=new H4(e,`embeddings request failed: HTTP ${a.status}`,a.status);return tst.has(a.status)?{kind:`retry`,reason:e,error:t}:{kind:`fatal`,reason:e,error:t}}let s;try{s=await a.json()}catch{throw new W4(`embeddings endpoint returned a non-JSON body — check the base URL`)}let l=h(s,r);return u??=l.dims,Got(i,s.usage?.total_tokens??0),{kind:`ok`,vectors:l.vectors}}catch(e){if(e instanceof U4)return{kind:`fatal`,reason:`dims_mismatch`,error:e};if(e instanceof W4)return{kind:`fatal`,reason:`malformed_response`,error:e};let t=e instanceof Error&&e.name===`AbortError`,n=e instanceof Error?e:Error(String(e));return{kind:`retry`,reason:t?`timeout`:`network`,error:n}}finally{clearTimeout(s)}}async function m(t,n){let i=n===`query`?l:c,a=n===`query`?`query`:`document`,u=JSON.stringify({model:e.model,input:t,encoding_format:`float`,...e.dimensions===void 0?{}:{dimensions:e.dimensions}}),d=0;for(;;){let e=await p(u,t.length,a,i);if(e.kind===`ok`)return e.vectors;if(Kot(e.reason),e.kind===`fatal`||d>=o)throw e.error instanceof H4?e.error:new H4(e.reason,e.error.message,void 0,{cause:e.error});d+=1;let n=s*2**(d-1);await r(Math.round(n/2+n/2*Math.random()))}}function h(e,t){let n=e.data;if(!Array.isArray(n)||n.length!==t)throw new W4(`embeddings response had ${n?.length??0} vectors, expected ${t}`);let r=[...n].sort((e,t)=>(e.index??0)-(t.index??0)),i=[],a=u;for(let e of r){let t=e.embedding;if(!Array.isArray(t))throw new W4(`embeddings response contained a non-array embedding (expected float vectors)`);if(a??=t.length,t.length!==a)throw new U4(a,t.length);i.push($ot(Float32Array.from(t)))}if(a===null)throw new W4(`embeddings response contained no vectors`);return{vectors:i,dims:a}}return{providerId:K4(e.baseUrl),modelId:e.model,get dims(){return u},pinDims(e){u??=e},async embed(e,{role:t}){if(e.length===0)return[];let n=[];for(let r of f(e))n.push(...await m(r,t));return n}}}function nst(e){return K4(e)===K4(Aa)}async function J4(e,t,n){let r=e?await e.resolveForProject(t,n).catch(e=>(Yot.warn({err:e},`[embeddings] failed to read the stored key — treating as unset`),null)):null;if(r?.key){let e=r.source===`file`?`file`:`project`;return{apiKey:r.key,keyless:!1,source:e}}if(nst(n)){let e=process.env[Zot];if(e)return{apiKey:e,keyless:!1,source:`env`}}return fie(n)?{apiKey:null,keyless:!0,source:`none`}:{apiKey:null,keyless:!1,source:`none`}}async function rst(e){let t=await J4(e.keyStore,e.projectDir,e.config.baseUrl);return t.apiKey?q4({...e.config,apiKey:t.apiKey},e.options):t.keyless?q4({...e.config},e.options):null}async function ist(e){let t;try{t=q4({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:e.apiKey},{fetchImpl:e.fetchImpl,maxRetries:0,queryTimeoutMs:e.timeoutMs??1e4})}catch{return{ok:!1,reason:`invalid_endpoint`}}try{let[e]=await t.embed([`OpenKnowledge embeddings connection test`],{role:`query`});return!e||e.length===0?{ok:!1,reason:`malformed_response`}:{ok:!0,dimensions:e.length}}catch(e){return e instanceof H4?{ok:!1,reason:e.reason,status:e.status}:{ok:!1,reason:`network`}}}const ast=K4(Aa),Y4=`OPENAI_API_KEY`,X4=`embeddings`,Z4=`embeddings_projects`;function Q4(e){try{return Ns.native(e)}catch{return W(e)}}function ost(e){return H(Mx(e??Hs()),te)}function sst(e){return e&&e.length>=8?e.slice(-4):null}function cst(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}var $4=class{backend=`file`;secretsFile;constructor(e){this.secretsFile=e??ost()}withLock(e){let t=`${this.secretsFile}.lock`,n=V(this.secretsFile);G(n)||KH(n,{recursive:!0,mode:448});let r=Date.now(),i=!1;for(;!i;)try{let e=js(t,`wx`,384);Bs(e,String(process.pid)),ws(e),i=!0}catch(e){if(e.code!==`EEXIST`){let t=e instanceof Error?e.message:`unknown error`;process.stderr.write(`[embeddings] could not acquire the secrets write-lock (${t}); proceeding without cross-process serialization.\n`);break}try{if(Date.now()-Ls(t).mtimeMs>1e4){Rs(t);continue}}catch{continue}if(Date.now()-r>2e3)break;cst(15)}try{return e()}finally{if(i)try{Rs(t)}catch{}}}tightenPermsIfLoose(){let e;try{e=Ls(this.secretsFile).mode&511}catch{return}if(e&63)try{Cs(this.secretsFile,384),process.stderr.write(`[embeddings] ${this.secretsFile} was readable beyond your user account (mode ${e.toString(8)}); tightened to 600. It stores an API key.\n`)}catch(t){let n=t instanceof Error?t.message:`unknown error`;process.stderr.write(`[embeddings] ${this.secretsFile} is readable beyond your user account (mode ${e.toString(8)}) and could not be tightened (${n}); your API key remains exposed — run: chmod 600 ${this.secretsFile}\n`)}}read(){if(!G(this.secretsFile))return{};this.tightenPermsIfLoose();try{return(0,Fc.parse)(K(this.secretsFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[embeddings] Failed to parse ${this.secretsFile}: ${t}. Starting with empty secrets.\n`),{}}}write(e){let t=V(this.secretsFile);G(t)||KH(t,{recursive:!0,mode:448});let n=`${this.secretsFile}.tmp`;WH(n,(0,Fc.stringify)(e),{mode:384}),Cs(n,384),qH(n,this.secretsFile),Cs(this.secretsFile,384)}writeOrUnlink(e){if(Object.keys(e).length===0){try{XH(this.secretsFile)}catch(e){if(e.code!==`ENOENT`){let t=e instanceof Error?e.message:`unknown error`;process.stderr.write(`[embeddings] could not remove ${this.secretsFile} (${t}); a cleared key may remain on disk — delete the file manually if needed.\n`)}}return}this.write(e)}readProjects(e){let t=e[Z4];return t&&typeof t==`object`?t:{}}legacyKey(e){let t=e[Y4]??e[X4];return typeof t==`string`&&t!==``?t:null}resolveForProject(e,t){let n=this.read(),r=K4(t),i=this.readProjects(n)[Q4(e)]?.[r];if(typeof i==`string`&&i!==``)return Promise.resolve({key:i,source:`project`});if(r===ast){let e=this.legacyKey(n);if(e)return Promise.resolve({key:e,source:`file`})}return Promise.resolve({key:null,source:null})}describeForProject(e,t){return this.resolveForProject(e,t).then(({key:e,source:t})=>({present:e!==null,hint:sst(e),source:t}))}getLegacyKey(){return Promise.resolve(this.legacyKey(this.read()))}setForProject(e,t,n){return this.withLock(()=>{let r=this.read(),i=this.readProjects(r),a=Q4(e);i[a]={...i[a],[K4(t)]:n},r[Z4]=i,this.write(r)}),Promise.resolve()}clearForProject(e,t){let n=this.withLock(()=>{let n=this.read(),r=this.readProjects(n),i=Q4(e),a=K4(t);return r[i]?.[a]!==void 0&&(delete r[i][a],Object.keys(r[i]).length===0&&delete r[i],Object.keys(r).length===0?delete n[Z4]:n[Z4]=r,this.writeOrUnlink(n),!0)});return Promise.resolve(n)}clearAllForProject(e){let t=this.withLock(()=>{let t=this.read(),n=this.readProjects(t),r=Q4(e);return n[r]!==void 0&&(delete n[r],Object.keys(n).length===0?delete t[Z4]:t[Z4]=n,this.writeOrUnlink(t),!0)});return Promise.resolve(t)}clearAll(){let e=this.withLock(()=>{let e=this.read(),t=e[Z4]!==void 0||e[Y4]!==void 0||e[X4]!==void 0;return delete e[Z4],delete e[Y4],delete e[X4],t&&this.writeOrUnlink(e),t});return Promise.resolve(e?{touched:[`file`]}:{touched:[]})}listProjects(){let e=this.readProjects(this.read()),t=Object.entries(e).map(([e,t])=>({projectKey:e,endpoints:Object.entries(t).map(([e,t])=>({endpoint:e,hint:sst(t)}))}));return Promise.resolve(t)}};function lst(e){return new $4(e)}function ust(e){return new $4(e)}async function dst(e,t,n){return new $4(n).describeForProject(e,t)}async function fst(e){return new $4(e).clearAll()}function pst(e,t){let n=jx({absPath:Vx(`project-local`,e,t?.configHomedirOverride),sideline:!1,warn:t?.onWarn??(()=>{})}).value.search?.semantic;return{enabled:n?.enabled===!0,baseUrl:n?.baseUrl??`https://api.openai.com/v1`,model:n?.model??`text-embedding-3-small`,dimensions:n?.dimensions??void 0,similarityFloor:n?.similarityFloor??void 0,maxBatchSize:n?.maxBatchSize??96,maxBatchChars:n?.maxBatchChars??96e3,docTimeoutMs:n?.docTimeoutMs??3e4}}function mst(e,t={}){let n=Math.max(1,t.targetChars??8e3),r=Math.max(0,Math.min(t.overlapChars??400,n-1)),i=t.maxChunks??80;if(e.trim().length===0)return[];if(e.length<=n)return[e.trim()];let a=[],o=0;for(;o<e.length&&a.length<i;){let t=Math.min(e.length,o+n);if(t<e.length){let r=Math.max(e.lastIndexOf(` `,t),e.lastIndexOf(`
1112
1112
  `,t));r>o+Math.floor(n/2)&&(t=r)}let i=e.slice(o,t).trim();if(i&&a.push(i),t>=e.length)break;let s=t-r;o=s>o?s:t}return a}const e3=q(`embeddings`);function hst(e,t){return e.identityDims===void 0?t===`auto`?`auto`:e.dims:e.identityDims}function gst(e){return ac(`sha256`).update(e,`utf-8`).digest(`hex`)}function _st(e){let t=0;for(let n of e)t+=n.length;let n=new Float32Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function vst(e,t){let n=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),r=new Float32Array(n);if(r.length%t!==0)throw Error(`vector blob length ${r.length} is not a multiple of dims ${t}`);let i=[];for(let e=0;e<r.length;e+=t)i.push(r.slice(e,e+t));return i}var yst=class{cacheDir;vecDir;manifestPath;providerId;modelId;identityDims;chunkConfigId;entries=new Map;vectorsByHash=new Map;persistedHashes=new Set;dirty=!1;pinnedDims;constructor(e){this.cacheDir=e.cacheDir,this.vecDir=e.cacheDir?H(e.cacheDir,`vec`):null,this.manifestPath=e.cacheDir?H(e.cacheDir,`manifest.json`):null,this.providerId=e.providerId,this.modelId=e.modelId,this.identityDims=e.identityDims,this.pinnedDims=e.identityDims===`auto`?null:e.identityDims,this.chunkConfigId=e.chunkConfigId}get dims(){return this.pinnedDims}matchesIdentity(e){return e.providerId===this.providerId&&e.modelId===this.modelId&&e.identityDims===this.identityDims&&e.chunkConfigId===this.chunkConfigId}pinDims(e){this.pinnedDims??=e}discard(){this.entries.clear(),this.vectorsByHash.clear(),this.persistedHashes.clear(),this.wipeDisk(),this.dirty=!1}async init(){if(!this.cacheDir||!this.manifestPath||!this.vecDir)return;let e=null;try{G(this.manifestPath)&&(e=JSON.parse(await Xs(this.manifestPath,`utf-8`)))}catch(t){e3.warn({err:t},`[embeddings] unreadable cache manifest — rebuilding`),e=null}if(!(e!==null&&e.schemaVersion===1&&this.matchesIdentity({providerId:e.providerId,modelId:e.modelId,identityDims:hst(e,this.identityDims),chunkConfigId:e.chunkConfigId}))){e!==null&&e3.info({hadModel:e.modelId,wantModel:this.modelId},`[embeddings] cache identity changed (provider/model/dims/chunking) — invalidating`),this.wipeDisk();return}if(!e)return;if(this.pinnedDims===null){if(!Number.isInteger(e.dims)||e.dims<=0)return;this.pinnedDims=e.dims}let t=this.pinnedDims;for(let[n,r]of Object.entries(e.entries))if(r?.contentHash&&(this.entries.set(n,{contentHash:r.contentHash,mtimeMs:r.mtimeMs??0}),!this.vectorsByHash.has(r.contentHash)))try{let e=H(this.vecDir,`${r.contentHash}.bin`);if(G(e)){let n=await Xs(e);this.vectorsByHash.set(r.contentHash,vst(n,t)),this.persistedHashes.add(r.contentHash)}}catch(e){e3.warn({hash:r.contentHash,err:e},`[embeddings] corrupt vector blob — will re-embed`)}}isFresh(e,t){let n=this.entries.get(e);return n!==void 0&&n.mtimeMs===t&&this.vectorsByHash.has(n.contentHash)}link(e,t,n){if(!this.vectorsByHash.has(t))return!1;let r=this.entries.get(e);return(!r||r.contentHash!==t||r.mtimeMs!==n)&&(this.dirty=!0),this.entries.set(e,{contentHash:t,mtimeMs:n}),!0}store(e,t,n,r){this.vectorsByHash.set(t,r),this.entries.set(e,{contentHash:t,mtimeMs:n}),this.dirty=!0}getVectors(e){let t=this.entries.get(e);if(t)return this.vectorsByHash.get(t.contentHash)}get embeddedCount(){let e=0;for(let t of this.entries.values()){let n=this.vectorsByHash.get(t.contentHash);n&&n.length>0&&(e+=1)}return e}retain(e){for(let t of this.entries.keys())e.has(t)||(this.entries.delete(t),this.dirty=!0);let t=new Set;for(let e of this.entries.values())t.add(e.contentHash);for(let e of this.vectorsByHash.keys())t.has(e)||this.vectorsByHash.delete(e)}clearMemory(){this.entries.clear(),this.vectorsByHash.clear(),this.persistedHashes.clear(),this.dirty=!1}async persist(){if(!this.cacheDir||!this.manifestPath||!this.vecDir||!this.dirty)return;let e=this.pinnedDims;if(e!==null)try{await UH(this.vecDir,{recursive:!0});let t=new Set;for(let e of this.entries.values())t.add(e.contentHash);for(let e of t){if(this.persistedHashes.has(e))continue;let t=this.vectorsByHash.get(e);t&&(await zH(H(this.vecDir,`${e}.bin`),_st(t)),this.persistedHashes.add(e))}let n={schemaVersion:1,providerId:this.providerId,modelId:this.modelId,dims:e,identityDims:this.identityDims,chunkConfigId:this.chunkConfigId,entries:Object.fromEntries(this.entries)},r=`${this.manifestPath}.tmp`;await zH(r,JSON.stringify(n)),await HH(r,this.manifestPath);for(let e of Ms(this.vecDir)){if(!e.endsWith(`.bin`))continue;let n=e.slice(0,-4);t.has(n)||(XH(H(this.vecDir,e)),this.persistedHashes.delete(n))}this.dirty=!1}catch(e){e3.warn({err:e},`[embeddings] failed to persist vector cache`)}}wipeDisk(){if(this.cacheDir)try{$H(this.cacheDir,{recursive:!0,force:!0})}catch(e){e3.warn({err:e},`[embeddings] failed to wipe stale cache`)}}};const t3=q(`embeddings`);function bst(e){return e instanceof Error?e.message:String(e)}var n3=class extends Error{name=`DimsMismatchSignal`;cause;constructor(e){super(e.message),this.cause=e}},xst=class{loadEmbedder;cacheDir;enabled;providerFingerprint;transportFingerprint;maxBatchSize;capable=!1;ready=!1;providerErrorReason=null;embedder=null;cache=null;warmPromise=null;warmGeneration=0;cacheInitChain=Promise.resolve();embedChain=Promise.resolve();queuedDocs=null;dimsDriftResets=0;constructor(e){this.loadEmbedder=e.loadEmbedder,this.cacheDir=e.cacheDir,this.enabled=e.enabled??!1,this.providerFingerprint=e.providerFingerprint??``,this.transportFingerprint=e.transportFingerprint??``,this.maxBatchSize=e.maxBatchSize??96}isEnabled(){return this.enabled}getStatus(){return{enabled:this.enabled,capable:this.capable,ready:this.ready,providerError:this.providerErrorReason!==null,providerErrorReason:this.providerErrorReason,embeddedCount:this.cache?.embeddedCount??0}}applyConfig(e){let t=e.providerFingerprint!==this.providerFingerprint,n=e.transportFingerprint!==this.transportFingerprint;this.providerFingerprint=e.providerFingerprint,this.transportFingerprint=e.transportFingerprint,this.maxBatchSize=e.maxBatchSize,t?(this.dimsDriftResets=0,this.resetWarm(`provider`)):n&&this.resetWarm(`transport`),e.enabled!==this.enabled&&(this.enabled=e.enabled,e.enabled||this.resetWarm(`disabled`))}resetWarm(e){let t=this.cache?.embeddedCount??0,n=e===`transport`||e===`credential`||e===`retry`;this.warmGeneration+=1,this.warmPromise=null,this.ready=!1,this.capable=!1,this.providerErrorReason=null,this.embedder=null,e===`disabled`&&this.cache?.clearMemory(),e===`dimensions`&&this.cache?.discard(),n||(this.cache=null),t3.info({reason:e,retainedInMemoryDocumentCount:n?t:0,unloadedInMemoryDocumentCount:n?0:t},`[embeddings] resetting embedder`)}reloadCredential(){this.resetWarm(`credential`)}reportPhaseFailure(e){this.providerErrorReason!==`dimensions`&&this.providerErrorReason!==`configured_dimensions`&&(this.providerErrorReason=e)}recoverFromDimsDrift(e,t,n){if(this.cache===e){if(e.identityDims!==`auto`){t3.error({expected:t.expected,got:t.got,phase:n,recovery:`configured_mismatch`},`[embeddings] provider ignored the configured vector size — check search.semantic.dimensions`),this.capable=!1,this.providerErrorReason=`configured_dimensions`,e.clearMemory();return}if(this.dimsDriftResets>=2){t3.error({expected:t.expected,got:t.got,phase:n,recovery:`drift_exhausted`,unloadedInMemoryDocumentCount:e.embeddedCount},`[embeddings] provider vector length keeps changing — disabling semantic search until restart`),this.capable=!1,this.providerErrorReason=`dimensions`,e.clearMemory();return}this.dimsDriftResets+=1,t3.warn({expected:t.expected,got:t.got,phase:n,recovery:`recovered`},`[embeddings] provider vector length changed — discarding cached vectors and re-embedding`),this.resetWarm(`dimensions`)}}async ensureWarm(){for(;this.enabled&&!this.ready;)this.warmPromise||=this.warm(this.warmGeneration),await this.warmPromise}async warm(e){try{let t=await this.loadEmbedder();if(e!==this.warmGeneration||!this.enabled)return;if(!t){this.capable=!1,this.ready=!0,t3.info({},`[embeddings] no embeddings key configured — semantic search degrades to lexical`);return}let n=t.dims??`auto`,r={cacheDir:this.cacheDir,providerId:t.providerId,modelId:t.modelId,identityDims:n,chunkConfigId:`c8000-o400-m80`},i=this.cache;if(!i?.matchesIdentity(r)){i=new yst(r);let t=i,n=this.cacheInitChain.then(async()=>{e!==this.warmGeneration||!this.enabled||await t.init()});this.cacheInitChain=n.catch(()=>{}),await n}if(e!==this.warmGeneration||!this.enabled)return;i.dims!==null&&t.pinDims?.(i.dims),this.embedder=t,this.cache=i,this.capable=!0,this.ready=!0}catch(t){if(e!==this.warmGeneration||!this.enabled)return;this.capable=!1,this.ready=!0,this.reportPhaseFailure(`warm`),t3.warn({err:t},`[embeddings] warm failed`)}}embedCorpus(e){return this.enabled?(this.providerErrorReason===`warm`&&this.ready&&!this.capable&&this.resetWarm(`retry`),this.queuedDocs=e,this.embedChain=this.embedChain.then(async()=>{let e=this.queuedDocs;if(e){this.queuedDocs=null;try{await this.runEmbedPass(e)}catch(e){this.reportPhaseFailure(`corpus`),t3.warn({err:e},`[embeddings] embed pass failed`)}}}),this.embedChain):Promise.resolve()}async runEmbedPass(e){for(;this.enabled&&!this.ready;)await this.ensureWarm();if(!this.enabled||!this.capable||!this.embedder||!this.cache)return;let t=this.cache,n=this.embedder,r=this.maxBatchSize,i=e.filter(e=>e.kind===`page`),a=new Set(i.map(e=>e.id)),o=[];for(let e of i){if(!this.enabled)return;let n=e.modifiedTs;if(t.isFresh(e.id,n))continue;let r=gst(e.content);t.link(e.id,r,n)||o.push({doc:e,contentHash:r,chunks:mst(e.content)})}let s=0,c=0,l=0,u=!1,d=(e,n)=>{let r=n[0]?.length;r!==void 0&&t.pinDims(r),t.store(e.doc.id,e.contentHash,e.doc.modifiedTs,n),c+=1},f=async e=>{let t=e.flatMap(e=>e.chunks);try{let r=t.length?await n.embed(t,{role:`document`}):[],i=0;for(let t of e)d(t,r.slice(i,i+t.chunks.length)),i+=t.chunks.length;return s=0,!0}catch(t){if(t instanceof U4)throw new n3(t);if(l+=1,e.length===1)return t3.warn({docId:e[0].doc.id,err:bst(t)},`[embeddings] failed to embed document`),s+=1,s<5;for(let t of e){if(!this.enabled)return!1;try{let e=t.chunks.length?await n.embed(t.chunks,{role:`document`}):[];d(t,e),s=0}catch(e){if(e instanceof U4)throw new n3(e);if(l+=1,t3.warn({docId:t.doc.id,err:bst(e)},`[embeddings] failed to embed document`),s+=1,s>=5)return!1}}return!0}},p=[],m=0;try{for(let e of o){if(!this.enabled)break;if(p.push(e),m+=Math.max(1,e.chunks.length),m>=r){let e=await f(p);if(p=[],m=0,!e){u=!0;break}}}p.length>0&&this.enabled&&(u=!await f(p))}catch(e){if(!(e instanceof n3))throw e;this.recoverFromDimsDrift(t,e.cause,`corpus`);return}if(!this.enabled||this.cache!==t){t3.info({reason:this.enabled?`cache-replaced`:`disabled`,completedDocumentCount:c,scheduledDocumentCount:o.length,corpusDocumentCount:a.size},`[embeddings] abandoning embed pass before persistence`);return}t.retain(a),await t.persist(),u||c===0&&l>=2?this.reportPhaseFailure(`corpus`):this.providerErrorReason===`corpus`&&(this.providerErrorReason=null)}async queryScores(e,t){if(!this.enabled||!this.capable||!this.ready)return null;let n=this.cache,r=this.embedder;if(!r||!n||n.embeddedCount===0)return null;let i=e.trim();if(!i)return null;let a;try{[a]=await r.embed([i],{role:`query`}),this.providerErrorReason===`query`&&(this.providerErrorReason=null)}catch(e){return e instanceof U4?this.recoverFromDimsDrift(n,e,`query`):(this.reportPhaseFailure(`query`),t3.warn({err:e,reason:e instanceof H4?e.reason:void 0},`[embeddings] query embed failed — degrading to lexical`)),null}if(!a)return null;let o=new Map;for(let e of t){let t=n.getVectors(e.id);if(!t||t.length===0)continue;let r=-1/0;for(let e of t){if(e.length!==a.length)continue;let t=Qot(a,e);t>r&&(r=t)}r>-1/0&&o.set(e.id,r)}return o}};const Sst=/^[A-Za-z0-9-]{8,64}$/;let r3=null;function Cst(e){return H(e??Hs(),`.ok`,vte)}function i3(e){if(e===void 0&&r3!==null)return r3;let t=Cst(e),n=null;try{let e=K(t,`utf-8`).trim();Sst.test(e)&&(n=e)}catch{}if(n===null){n=oc();try{ks(V(t),{recursive:!0}),zs(t,`${n}\n`,{encoding:`utf-8`,mode:384})}catch(e){q(`machine-id`).warn({path:t,err:e},`Failed to persist ${t} — using an ephemeral per-process id; lock ownership checks will fail closed (collision) instead of recognizing this machine: ${e instanceof Error?e.message:String(e)}`)}}return e===void 0&&(r3=n),n}const a3=q(`process-lock`);var o3=class extends Error{existing;lockPath;lockName;constructor(e,t,n){super(`OpenKnowledge ${n} already running at ${e.url??`port ${e.port}`} (pid ${e.pid}, started ${e.startedAt}). Stop it first or use a different directory. Lock: ${t}`),this.name=`ProcessLockCollisionError`,this.existing=e,this.lockPath=t,this.lockName=n}};function s3(e,t){return W(e,`${t}.lock`)}const c3=new Map;function wst(e){c3.set(e,(c3.get(e)??0)+1)}function Tst(e){let t=c3.get(e);return t===void 0||t<=1?(c3.delete(e),!0):(c3.set(e,t-1),!1)}function l3(e){return typeof e.machineId==`string`?e.machineId===i3():e.hostname===Us()}const u3=new Set;let Est=!1;function Dst(e){u3.add(e),!Est&&(Est=!0,process.on(`exit`,()=>{for(let e of u3)try{let t=JSON.parse(K(e,`utf-8`));if(t?.pid!==process.pid||typeof t.machineId==`string`&&t.machineId!==i3()||t.machineId===void 0&&typeof t.hostname==`string`&&t.hostname!==Us())continue;Rs(e)}catch{}}))}function Ost(e,t){try{let n=JSON.parse(K(e,`utf-8`));return n&&typeof n==`object`&&KU(n.pid)?n:(a3.warn({lockPath:e},`${t} Corrupt lock file at ${e} — replacing`),null)}catch{return a3.warn({lockPath:e},`${t} Corrupt lock file at ${e} — replacing`),null}}function kst(e){try{return wne()}catch(t){a3.warn({err:t},`${e} Not recording a channel: ${t instanceof Error?t.message:String(t)}`);return}}function Ast(e){return typeof e==`string`&&e.length>0?e:void 0}function jst(e){let{lockName:t,lockDir:n,metadata:r}=e,i=`[${t}-lock]`;ks(n,{recursive:!0});let a=s3(n,t),o={pid:process.pid,hostname:Us(),port:r.port,...r.url!==void 0&&{url:r.url},startedAt:new Date().toISOString(),worktreeRoot:r.worktreeRoot,machineId:i3(),...r.kind!==void 0&&{kind:r.kind},...r.parentPid!==void 0&&{parentPid:r.parentPid},...r.capabilities!==void 0&&{capabilities:r.capabilities},protocolVersion:r.protocolVersion??2,runtimeVersion:r.runtimeVersion??qZ,channel:kst(i)},s=JSON.stringify(o,null,2);for(let e=0;e<3;e++){if(!G(a))try{let e=js(a,`wx`,384);try{Bs(e,s)}finally{ws(e)}return wst(a),Dst(a),Mst({lockName:t,lockDir:n,lockPath:a})}catch(e){if(rG(e)!==`EEXIST`)throw e}let e=Ost(a,i);if(e){if(l3(e)&&e.pid===process.pid)return zs(a,s,{encoding:`utf-8`,mode:384}),wst(a),Dst(a),Mst({lockName:t,lockDir:n,lockPath:a});if(GU(e.pid))throw new o3(e,a,t);a3.warn({pid:e.pid,host:e.hostname},`${i} Stale lock detected (pid=${e.pid}, host=${e.hostname}) — replacing`)}try{Rs(a)}catch{}}throw Error(`${i} Failed to acquire ${a} after 3 attempts (concurrent acquire contention).`)}function Mst(e){let{lockName:t,lockDir:n,lockPath:r}=e;return{lockPath:r,release:()=>m3({lockName:t,lockDir:n}),updatePort:(e,r)=>f3({lockName:t,lockDir:n,port:e,url:r})}}function Nst(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`)return null;let n=t.hostname;return n===`localhost`||n===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)?t.origin:null}function d3(e,t){if(typeof e.url==`string`&&e.url.length>0){let t=Nst(e.url);if(t!==null)return t}if(e.port>0){let n=t?.fallbackHost??`localhost`;return`http://${n===`0.0.0.0`||n===`::`?`localhost`:n.includes(`:`)&&!n.startsWith(`[`)?`[${n}]`:n}:${e.port}`}return null}function f3(e){let{lockName:t,lockDir:n,port:r,url:i}=e,a=`[${t}-lock]`,o=s3(n,t);if(!G(o)){a3.warn({lockPath:o},`${a} Lock file missing at ${o} during port update — skipping`);return}let s;try{let e=JSON.parse(K(o,`utf-8`));if(!e||typeof e!=`object`||!KU(e.pid)){a3.warn({lockPath:o},`${a} Corrupt lock at ${o} during port update — skipping`);return}s=e}catch{a3.warn({lockPath:o},`${a} Unreadable lock at ${o} during port update — skipping`);return}if(s.pid===process.pid&&l3(s)){s.port=r,i===void 0?delete s.url:s.url=i;try{zs(o,JSON.stringify(s,null,2),{encoding:`utf-8`,mode:384})}catch(e){a3.warn({lockPath:o,err:e},`${a} Failed to update port in ${o}: ${e instanceof Error?e.message:String(e)}`)}}}function Pst(e){let{lockName:t,lockDir:n}=e,r=`[${t}-lock]`,i=s3(n,t);if((c3.get(i)??0)>1)return;let a;try{let e=JSON.parse(K(i,`utf-8`));if(!e||typeof e!=`object`||!KU(e.pid)){a3.warn({lockPath:i},`${r} Corrupt lock at ${i} during draining mark — skipping`);return}a=e}catch(e){rG(e)!==`ENOENT`&&a3.warn({lockPath:i,err:e},`${r} Unreadable lock at ${i} during draining mark — skipping: ${e instanceof Error?e.message:String(e)}`);return}if(a.pid===process.pid&&l3(a)&&a.draining!==!0){a.draining=!0;try{zs(i,JSON.stringify(a,null,2),{encoding:`utf-8`,mode:384})}catch(e){a3.warn({lockPath:i,err:e},`${r} Failed to mark ${i} draining: ${e instanceof Error?e.message:String(e)}`)}}}function p3(e){let{lockName:t,lockDir:n}=e,r=s3(n,t);if(!G(r))return null;let i;try{let e=JSON.parse(K(r,`utf-8`));if(!e||typeof e!=`object`||!KU(e.pid))return null;i={...e,channel:Ast(e.channel)}}catch{return null}if(!l3(i))return null;if(!GU(i.pid)){try{Rs(r)}catch{}return null}return i}function Fst(e){let{lockName:t,lockDir:n}=e,r=s3(n,t);if(!G(r))return{status:`absent`};let i;try{i=JSON.parse(K(r,`utf-8`))}catch{return{status:`incompatible`,reason:`corrupt`,raw:void 0}}if(!i||typeof i!=`object`)return{status:`incompatible`,reason:`corrupt`,raw:i};let a=i;if(!KU(a.pid)||typeof a.hostname!=`string`||typeof a.port!=`number`||typeof a.startedAt!=`string`||typeof a.worktreeRoot!=`string`)return{status:`incompatible`,reason:`corrupt`,raw:i};let o={pid:a.pid,hostname:a.hostname,port:a.port,url:typeof a.url==`string`?a.url:void 0,startedAt:a.startedAt,worktreeRoot:a.worktreeRoot,machineId:typeof a.machineId==`string`?a.machineId:void 0,draining:a.draining===!0||void 0,capabilities:Array.isArray(a.capabilities)&&a.capabilities.every(e=>typeof e==`string`)?a.capabilities:void 0,protocolVersion:typeof a.protocolVersion==`number`?a.protocolVersion:void 0,runtimeVersion:typeof a.runtimeVersion==`string`?a.runtimeVersion:void 0,channel:Ast(a.channel)};if(!l3(o))return{status:`stale`,lock:o};if(!GU(o.pid)){try{Rs(r)}catch{}return{status:`stale`,lock:o}}return o.protocolVersion===void 0||o.runtimeVersion===void 0?{status:`incompatible`,reason:`missing-fields`,raw:i}:{status:`live`,lock:o}}async function Ist(e){let{lockName:t,lockDir:n}=e,r=e.timeoutMs??1e4,i=e.pollIntervalMs??100,a=e.readLock??(()=>p3({lockName:t,lockDir:n})),o=e.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=a();if(s===null||s.draining!==!0)return`no-drain`;let c=Date.now()+r;for(;Date.now()<c;){await o(i);let e=a();if(e===null)return`released`;if(e.draining!==!0)return`no-drain`}return`timeout`}function m3(e){let{lockName:t,lockDir:n,deferUnlinkToExit:r=!1}=e,i=`[${t}-lock]`,a=s3(n,t);if(Tst(a)){if(r){Pst({lockName:t,lockDir:n});return}if(G(a))try{let e=JSON.parse(K(a,`utf-8`));if(!e||typeof e!=`object`||typeof e.pid!=`number`||e.pid!==process.pid||!l3(e))return;Rs(a),u3.delete(a)}catch(e){a3.warn({lockPath:a,err:e},`${i} Failed to release ${a}: ${e instanceof Error?e.message:String(e)}`)}}}var Lst=xb({ServerLockCollisionError:()=>h3,acquireServerLock:()=>g3,lockAdvertisesUi:()=>v3,markServerLockDraining:()=>b3,readServerLock:()=>_3,releaseServerLock:()=>y3,updateServerLockPort:()=>Rst,waitForServerLockDrain:()=>zst}),h3=class extends o3{constructor(e,t){super(e,t,`server`),this.name=`ServerLockCollisionError`}};function g3(e,t){try{return jst({lockName:`server`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof o3&&e.lockName===`server`?new h3(e.existing,e.lockPath):e}}function Rst(e,t,n){f3({lockName:`server`,lockDir:e,port:t,url:n})}function _3(e){return p3({lockName:`server`,lockDir:e})}function v3(e){return!Array.isArray(e.capabilities)||e.capabilities.includes(`ui`)}function y3(e,t){m3({lockName:`server`,lockDir:e,...t})}function b3(e){Pst({lockName:`server`,lockDir:e})}function zst(e,t){return Ist({lockName:`server`,lockDir:e,...t})}function Bst(e){let{contentDir:t,projectDir:n,ephemeral:r,log:i,ready:a,serverInstanceId:o,getDiskAckSVs:s,getCollabClientCount:c,getConfigDiagnostics:l,acpRegistry:u,loadAcpCustomAgents:d,acpHarnessAvailability:f,isRoutePeerAdmitted:p,isAllowedWorkspaceHostHeader:m,checkLocalOpSecurity:h,getPrincipal:g,semanticSearch:_,readSemanticProviderConfig:v,embeddingsSecretsFile:y,getFileIndex:x,shadowRef:S,getCurrentBranch:C,getReportedBranch:w,installedAgentsCache:T}=e,E=Z(me,async(e,t)=>{try{a&&await a.catch(e=>{i.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=w?.()??void 0,n=s?.(),r=Mot(),l=c?.();Q(t,200,Mte,{serverInstanceId:o,...e===void 0?{}:{currentBranch:e},...n===void 0?{}:{currentDiskAckSVs:n},...r===void 0?{}:{boot:r},...l===void 0?{}:{collabClients:l},runtimeVersion:qZ,protocolVersion:2},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0}),D=B({id:R(),name:R(),version:R(),description:R().optional(),license:R().optional(),iconUrl:R().optional(),website:R().optional(),source:ui([`registry`,`custom`]),supported:Wa(),featured:Wa(),harness:B({cli:ui([`claude`,`codex`,`cursor`,`gemini`,`opencode`,`pi`]),availability:ui([`present`,`not-found`,`unknown`]),credentials:ui([`present`,`unknown`])}).optional()}),O=B({agents:z(D),stale:Wa(),maxThreads:Fn()}),ee=B({agentId:R(),reason:R().nullable(),candidates:z(B({value:R(),label:R(),description:R().nullable(),group:R().nullable(),contextChoices:z(Fn()),context:B({effectiveTokens:Fn(),origin:R()}).nullable(),selectability:R(),setPhase:R()}))}),k=Z(me,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`agent`)??``,r=e=>Q(t,200,ee,{agentId:n,candidates:[],reason:e});if(n===``){X(t,400,`urn:ok:error:invalid-request`,`An agent id is required.`,{handler:`acp-models`});return}if(n!==`codex-acp`){r(`unsupported`);return}if((await f()).codex?.availability!==`present`){r(`unavailable`);return}let a=sQ(),o=await Oot(`codex`,a);if(o.outcome===`not-found`){let e=await nQ(i)();e!==null&&(o=await Oot(`codex`,mQ(a,e)))}if(o.outcome!==`ok`){i.warn({agentId:n,outcome:o.outcome},`[acp-models] codex catalog probe failed`),r(`unavailable`);return}let s=o.models;if(s.length===0){r(`unavailable`);return}Q(t,200,ee,{agentId:n,reason:null,candidates:wot(s,{harness:`codex`,cliVersion:null,adapterVersion:null,endpoint:null,account:null},Date.now()).map(e=>({value:e.value,label:e.label,description:e.description,group:e.group,contextChoices:[...e.contextChoices],context:e.context,selectability:e.selectability,setPhase:e.setPhase}))})},{handler:`acp-models`}),A=Z(me,async(e,t)=>{if(u===void 0){X(t,404,`urn:ok:error:not-found`,`ACP catalog unavailable.`,{handler:`acp-catalog`});return}try{let e=HV(),{agents:n,stale:r}=await u.getCatalog(),i=await d?.()??[],a=await f(),o=[...n.map(t=>{let n=het[t.id];return{id:t.id,name:t.name,version:t.version,...t.description===void 0?{}:{description:t.description},...t.license===void 0?{}:{license:t.license},...t.icon===void 0?{}:{iconUrl:t.icon},...t.website===void 0?{}:{website:t.website},source:`registry`,supported:t.distribution.npx!==void 0||t.distribution.uvx!==void 0||e!==null&&t.distribution.binary?.[e]!==void 0,featured:RV.includes(t.id),...n===void 0?{}:{harness:{cli:n,availability:a[n]?.availability??`unknown`,credentials:a[n]?.credentials??`unknown`}}}}),...i.map(e=>({id:e.id,name:e.name,version:`custom`,source:`custom`,supported:!0,featured:!1}))];Q(t,200,O,{agents:o,stale:r,maxThreads:8},{handler:`acp-catalog`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){X(t,502,`urn:ok:error:registry-unreachable`,`Agent registry unreachable.`,{handler:`acp-catalog`,cause:e})}},{handler:`acp-catalog`,method:`GET`,skipBodyParse:!0});async function te(e,t){if(!p(e.socket.remoteAddress)){X(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!m(e.headers.host)){X(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){X(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let n=g?.()??null;if(!n){X(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}Q(t,200,Lne,n,{handler:`principal`})}async function j(e,t){if(!p(e.socket.remoteAddress)){X(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!m(e.headers.host)){X(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){X(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let n=B7e.read();Q(t,200,ree,{entries:n,count:n.length,detection:K7e(n[0])},{handler:`embed-detect`})}async function M(e,n){if(!p(e.socket.remoteAddress)){X(n,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!m(e.headers.host)){X(n,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){X(n,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let r=W(t),a=r,o=!0;try{a=Ns(r)}catch(e){let t=rG(e);if(t===`ENOENT`)i.warn({path:r},`[workspace] contentDir does not exist; returning unresolved path`),o=!1;else{i.warn({path:r,err:e},`[workspace] realpath failed for contentDir`),X(n,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:t??void 0,cause:e});return}}Q(n,200,Nee,{contentDir:a,pathSeparator:vs,symlinkResolved:o},{handler:`workspace`})}async function ne(e,t){if(h(e,t,{handler:`installed-agents`}))try{await Ret(e,t,T.probeAll)}catch(n){t.headersSent||(i.error({err:n,requestId:Oq(e)},`[installed-agents] route wrapper failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let re=n?Vq(n):null;async function ie(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:Not(e.headers),previewUrl:null,port:re?_3(re)?.port??0:0,singleFile:r};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}Q(t,200,Wre,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}X(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function ae(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=l?.()??{diagnostics:[]};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}Q(t,200,b,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}X(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let N=Z(me,async(e,r)=>{try{let e=!1,i=!1,a=!1,o=!1,s=null,c=0;if(_){let t=_.getStatus();e=t.enabled,i=t.ready,a=t.capable,o=t.providerError,s=t.providerErrorReason,c=t.embeddedCount}let l=v?.()?.baseUrl??`https://api.openai.com/v1`,u=await J4(new $4(y),n??t,l),d=u.apiKey!==null,f=!d&&u.keyless,p=d?u.source:null,m=u.apiKey&&u.apiKey.length>=8?u.apiKey.slice(-4):null,h=0;for(let[e]of x())!UW(e)&&!WW(e)&&!cr(e)&&(h+=1);Q(r,200,Zn,{enabled:e,keyPresent:d,keyNotRequired:f,keySource:p,keyHint:m,ready:i,capable:a,providerError:o,providerErrorReason:s,embedded:c,total:h},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){X(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),oe=(e,t)=>{let n=V(e);for(;n!==t&&n.startsWith(`${t}${vs}`);){try{eU(n)}catch(e){i.debug({err:e},`[rescue] empty-directory prune stopped (non-critical)`);return}n=V(n)}},se={"/api/config":ie,"/api/config/diagnostics":ae,"/api/server-info":E,"/api/principal":te,"/api/workspace":M,"/api/semantic-status":N,"/api/acp/catalog":A,"/api/acp/models":k,"/api/installed-agents":ne,"/api/__embed-detect":j,"/api/rescue":Z(me,async(e,t)=>{try{if(!S?.current){Q(t,200,Wne,[],{handler:`rescue-list`,extraHeaders:{"Cache-Control":`no-store`}});return}let e=Date.now(),n=[],r=W(S.current.gitDir,`rescue`);if(G(r))try{let t=Ms(r,{encoding:`utf-8`,recursive:!0}).map(e=>e.replaceAll(vs,`/`)).filter(e=>OW(e)),a=Ns(r);for(let o of t){let t=W(r,o),s;try{s=Ns(t)}catch(e){i.warn({file:o,err:e},`[rescue] skipping unresolvable rescue entry`);continue}if(!tG(s,a)){i.warn({file:o,canonical:s},`[rescue] skipping rescue entry resolving outside the rescue directory`);continue}try{let t=Ls(s);if(!t.isFile())continue;if(e-t.mtimeMs>864e5){try{XH(s),oe(s,a)}catch(e){i.debug({err:e},`[rescue] cleanup failed (non-critical)`)}continue}n.push({docName:jW(o),timestamp:t.mtime.toISOString(),size:t.size,source:`flat`})}catch(e){i.warn({file:o,err:e},`[rescue] skipping uninspectable rescue entry`)}}}catch(e){i.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=C?.()??`main`,t=await SW(S.current,e);for(let e of t)n.push({...e,source:`timeline`})}catch(e){i.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}Q(t,200,Wne,n,{handler:`rescue-list`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0})};return{paths:Object.keys(se),table:{resolve(e){let t=se[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1}}}const Vst=q(`asset-references`),Hst=/<[\w:-]+\b[^>]*?\s+(?:href|src)\s*=\s*(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function Ust(e){return e.startsWith(`#`)||e.startsWith(`//`)||e.startsWith(`data:`)||/^[a-z][a-z0-9+.-]*:/i.test(e)}function Wst(e){let t=e.trim().replace(/^<(.+)>$/,`$1`),n=t.indexOf(`#`),r=n>=0?t.slice(0,n):t,i=r.indexOf(`?`);return i>=0?r.slice(0,i):r}function Gst(e){let t=Wst(e.href);if(!t||Ust(t))return!1;let n=e.literal?t:gte(t);return Jr.has(ms(n).slice(1).toLowerCase())}function Kst(e){return e?Qst(e).filter(Gst).map(e=>`${e.literal?`w`:`m`}\0${e.href}`).sort().join(``):``}function qst(e,t){return Kst(e)!==Kst(t)}function Jst(e){let t=ms(e).slice(1).toLowerCase();return Gt(t)}function Yst(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`?e.code:null}function Xst(e,t){let n=(e,n)=>{let r=`${n?`w`:`m`} ${e}`;t.has(r)||t.set(r,{href:e,literal:n})};for(let t of Z$e(e,{nestedBracketLabels:!0}))t.href&&n(t.href,!1);for(let t of X$e(e))n(t.target,!0);for(let t of e.matchAll(Hst)){let e=t[1]??t[2]??t[3]??t[4];e&&n(e,!1)}}function Zst(e,t){let n=e,r=``;for(;n.length>0;){if(t.inComment){let e=n.indexOf(`-->`);if(e===-1)return r;n=n.slice(e+3),t.inComment=!1;continue}let e=n.indexOf(`<!--`);if(e===-1)return r+n;r+=n.slice(0,e),n=n.slice(e+4),t.inComment=!0}return r}function Qst(e){let t=new Map,n=Vi(),r={inComment:!1};for(let i of e.replaceAll(`\r
1113
1113
  `,`
1114
1114
  `).replaceAll(`\r`,`
@@ -2057,7 +2057,7 @@ tags: [lore, history]
2057
2057
 
2058
2058
  ## Source
2059
2059
  `}}},m8=Object.keys(p8);function h8(e){return e&&p8[e]||p8[fpt]}function ppt(e){return typeof e==`string`&&m8.includes(e)}function g8(e){return ppt(e)?e:void 0}function mpt(e){let t=e.trim(),n=(/^([^.!?]+[.!?])/.exec(t)?.[1]??t).trim();return n.length<=140?n:`${n.slice(0,137)}…`}function hpt(){return m8.map(e=>{let t=p8[e];return{id:t.id,name:t.name,description:t.description,defaultSubfolder:t.defaultSubfolder,folders:t.folders.map(e=>({path:e.path,summary:e.uiSummary??mpt(e.description)})),entryCounts:gpt(t)}})}function gpt(e){let t=e.folders.length,n=0;for(let t of e.folders)n+=1+(t.extraTemplates?.length??0);return n+=e.rootFiles?Object.keys(e.rootFiles).length:0,{files:n,folders:t}}const _pt=`frontmatter.yml`;function vpt(e){let t=[];t.push(`title: ${_8(e.title)}`),t.push(`description: ${_8(e.description)}`),t.push(`tags:`);for(let n of e.tags)t.push(` - ${_8(n)}`);return`${t.join(`
2060
- `)}\n`}function _8(e){return e===``?`""`:/[:#\n"'\\]|^\s|\s$/.test(e)?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e}function ypt(e,t){if(t.rootFiles?.[e]!==void 0)return t.rootFiles[e];let n=/^(.+)\/\.ok\/frontmatter\.yml$/.exec(e);if(n){let e=t.folders.find(e=>e.path===n[1]);return e?vpt(e):void 0}let r=/^(.+)\/\.ok\/templates\/([^/]+)\.md$/.exec(e);if(r){let e=r[2]??``;return t.templates[e]}}async function bpt(e,t={}){let n=Date.now(),r=W(t.projectDir??process.cwd()),i=h8(t.packId??`knowledge-base`),a=0,o=[],s=[];for(let t of e.created)try{let e=spt(r,t.path);s.push({entry:t,absPath:e})}catch(e){o.push({path:typeof t.path==`string`?t.path:String(t.path),error:e instanceof f8||e instanceof Error?e.message:String(e)})}for(let{entry:e,absPath:t}of s.filter(e=>e.entry.kind===`folder`))try{ks(t,{recursive:!0}),a+=1}catch(t){o.push({path:e.path,error:t instanceof Error?t.message:String(t)})}for(let{entry:e,absPath:t}of s.filter(e=>e.entry.kind===`file`)){let n=e.template??e.path,r=ypt(n,i);if(r===void 0){o.push({path:e.path,error:`No content template registered for template id "${n}" in pack "${i.id}"`});continue}if(!G(t))try{WH(t,r,{encoding:`utf-8`,flag:`wx`}),a+=1}catch(t){o.push({path:e.path,error:t instanceof Error?t.message:String(t)})}}let c=await apt(r,i.id);if(!(`refusal`in u8(r))){let e=new Set(b0(r).map(e=>e.name));for(let{name:t}of l8(i.id)){let n=G(H(r,`.ok`,`skills`,t,`SKILL.md`));!e.has(t)&&!n&&o.push({path:t,error:`skill source could not be authored`})}}let l=[];try{l=dpt(r,i.requiredPlugins??[])}catch(e){o.push({path:`.ok/${mU}`,error:`could not enable required plugin(s): ${e instanceof Error?e.message:String(e)}`})}return{applied:a,errors:o,durationMs:Date.now()-n,packSkillsInstalled:c.editors,packSkillConflicts:c.conflicts,pluginsEnabled:l}}function xpt(e){return`${e}/.ok/frontmatter.yml`}function Spt(e,t){return`${e}/.ok/templates/${t}.md`}function Cpt(e,t){if(!e)return``;let n=e.trim();if(n===``||n===`.`||n===`./`)return``;if(n.startsWith(`/`))throw new f8(`rootDir must be relative to the project directory, got: ${e}`);let r=n.replace(/\\/g,`/`).replace(/^\.\//,``).replace(/\/+$/,``);if(r.split(`/`).some(e=>e===`..`))throw new f8(`rootDir must not contain '..' segments, got: ${e}`);return spt(t,r),r}function wpt(e,t){return e===``?t:`${e}/${t}`}async function Tpt(e={}){let t=W(e.projectDir??process.cwd());if(!e.skipPrerequisite&&!cG(t))throw new d8(`No ${en} found at ${t}. Run \`ok init\` first to scaffold the tool config.`);let n=Cpt(e.rootDir,t),r=h8(e.packId??`knowledge-base`),i=[],a=[],o=[];if(n!==``){let e=H(t,n);G(e)?a.push({path:n,reason:`already-exists`}):i.push({path:n,kind:`folder`})}for(let e of r.folders){let s=wpt(n,e.path),c=H(t,s);G(c)?a.push({path:s,reason:`already-exists`}):i.push({path:s,kind:`folder`});let l=`${s}/.ok`,u=H(t,l);G(u)?a.push({path:l,reason:`already-exists`}):i.push({path:l,kind:`folder`});let d=`${l}/${_pt}`,f=H(t,d);G(f)?a.push({path:d,reason:`already-exists`}):i.push({path:d,kind:`file`,template:xpt(e.path)});let p=`${l}/templates`,m=H(t,p);G(m)?a.push({path:p,reason:`already-exists`}):i.push({path:p,kind:`folder`});let h=[e.starterTemplate,...e.extraTemplates??[]];for(let n of h){let s=`${p}/${n}.md`,c=H(t,s);if(G(c)){a.push({path:s,reason:`already-exists`});continue}if(r.templates[n]===void 0){let t=n===e.starterTemplate;o.push(t?`No starter template body registered for "${n}" in pack "${r.id}". The folder will land without a pre-selected template.`:`No body registered for extra template "${n}" in pack "${r.id}". The folder will land without that optional variant.`);continue}i.push({path:s,kind:`file`,template:Spt(e.path,n)})}}if(r.rootFiles)for(let e of Object.keys(r.rootFiles)){let r=wpt(n,e),o=H(t,r);G(o)?a.push({path:r,reason:`already-exists`}):i.push({path:r,kind:`file`,template:e})}let s=l8(r.id),c=s.length>0?u8(t):null,l=c!==null&&`refusal`in c?c.refusal:void 0,u=s.length>0?b0(t):[],d=new Map(u.map(e=>[e.name,H(t,e.dir)])),f=s.length>0?n2(H(t,...y)):null,p=s.map(({name:e})=>{let n=H(t,`.ok`,`skills`,e),i=npt[e],a=i===void 0?null:d.get(i)??(G(H(t,`.ok`,`skills`,i,`SKILL.md`))?H(t,`.ok`,`skills`,i):null),o=d.get(e)??a??(G(H(n,`SKILL.md`))?n:null),s=d.has(e)||a===null?e:i,c=o!==null&&f!==null&&rpt(r.id,s,o,f)===`foreign`;return{name:e,pending:o===null&&l===void 0,...c?{conflict:!0}:{}}}),m=(r.requiredPlugins??[]).map(e=>({id:e,pending:!upt(t,e)}));return{created:i,skipped:a,warnings:o,...p.length>0?{packSkills:p}:{},...m.length>0?{requiredPlugins:m}:{},...p.length>0&&l!==void 0?{packSkillHomeRefusal:l}:{}}}const Ept=[`These are patterns to adapt to your domain, not a layout to copy verbatim.`,"To build a variant: create your own folders (via `write` or your editor) and reuse only the ideas that fit.","To adopt this pack as-is: re-run without `--dry-run`."].join(`
2060
+ `)}\n`}function _8(e){return e===``?`""`:/[:#\n"'\\]|^\s|\s$/.test(e)?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e}function ypt(e,t){if(t.rootFiles?.[e]!==void 0)return t.rootFiles[e];let n=/^(.+)\/\.ok\/frontmatter\.yml$/.exec(e);if(n){let e=t.folders.find(e=>e.path===n[1]);return e?vpt(e):void 0}let r=/^(.+)\/\.ok\/templates\/([^/]+)\.md$/.exec(e);if(r){let e=r[2]??``;return t.templates[e]}}async function bpt(e,t={}){let n=Date.now(),r=W(t.projectDir??process.cwd()),i=h8(t.packId??`knowledge-base`),a=0,o=[],s=[];for(let t of e.created)try{let e=spt(r,t.path);s.push({entry:t,absPath:e})}catch(e){o.push({path:typeof t.path==`string`?t.path:String(t.path),error:e instanceof f8||e instanceof Error?e.message:String(e)})}for(let{entry:e,absPath:t}of s.filter(e=>e.entry.kind===`folder`))try{ks(t,{recursive:!0}),a+=1}catch(t){o.push({path:e.path,error:t instanceof Error?t.message:String(t)})}for(let{entry:e,absPath:t}of s.filter(e=>e.entry.kind===`file`)){let n=e.template??e.path,r=ypt(n,i);if(r===void 0){o.push({path:e.path,error:`No content template registered for template id "${n}" in pack "${i.id}"`});continue}if(!G(t))try{WH(t,r,{encoding:`utf-8`,flag:`wx`}),a+=1}catch(t){o.push({path:e.path,error:t instanceof Error?t.message:String(t)})}}let c=await apt(r,i.id);if(!(`refusal`in u8(r))){let e=new Set(b0(r).map(e=>e.name));for(let{name:t}of l8(i.id)){let n=G(H(r,`.ok`,`skills`,t,`SKILL.md`));!e.has(t)&&!n&&o.push({path:t,error:`skill source could not be authored`})}}let l=[];try{l=dpt(r,i.requiredPlugins??[])}catch(e){o.push({path:`.ok/${mU}`,error:`could not enable required plugin(s): ${e instanceof Error?e.message:String(e)}`})}return{applied:a,errors:o,durationMs:Date.now()-n,packSkillsInstalled:c.editors,packSkillConflicts:c.conflicts,pluginsEnabled:l}}function xpt(e){return`${e}/.ok/frontmatter.yml`}function Spt(e,t){return`${e}/.ok/templates/${t}.md`}function Cpt(e,t){if(!e)return``;let n=e.trim();if(n===``||n===`.`||n===`./`)return``;if(n.startsWith(`/`))throw new f8(`rootDir must be relative to the project directory, got: ${e}`);let r=n.replace(/\\/g,`/`).replace(/^\.\//,``).replace(/\/+$/,``);if(r.split(`/`).some(e=>e===`..`))throw new f8(`rootDir must not contain '..' segments, got: ${e}`);return spt(t,r),r}function wpt(e,t){return e===``?t:`${e}/${t}`}async function Tpt(e={}){let t=W(e.projectDir??process.cwd());if(!e.skipPrerequisite&&!cG(t))throw new d8(`No ${en} found at ${t}. Run \`${de()} init\` first to scaffold the tool config.`);let n=Cpt(e.rootDir,t),r=h8(e.packId??`knowledge-base`),i=[],a=[],o=[];if(n!==``){let e=H(t,n);G(e)?a.push({path:n,reason:`already-exists`}):i.push({path:n,kind:`folder`})}for(let e of r.folders){let s=wpt(n,e.path),c=H(t,s);G(c)?a.push({path:s,reason:`already-exists`}):i.push({path:s,kind:`folder`});let l=`${s}/.ok`,u=H(t,l);G(u)?a.push({path:l,reason:`already-exists`}):i.push({path:l,kind:`folder`});let d=`${l}/${_pt}`,f=H(t,d);G(f)?a.push({path:d,reason:`already-exists`}):i.push({path:d,kind:`file`,template:xpt(e.path)});let p=`${l}/templates`,m=H(t,p);G(m)?a.push({path:p,reason:`already-exists`}):i.push({path:p,kind:`folder`});let h=[e.starterTemplate,...e.extraTemplates??[]];for(let n of h){let s=`${p}/${n}.md`,c=H(t,s);if(G(c)){a.push({path:s,reason:`already-exists`});continue}if(r.templates[n]===void 0){let t=n===e.starterTemplate;o.push(t?`No starter template body registered for "${n}" in pack "${r.id}". The folder will land without a pre-selected template.`:`No body registered for extra template "${n}" in pack "${r.id}". The folder will land without that optional variant.`);continue}i.push({path:s,kind:`file`,template:Spt(e.path,n)})}}if(r.rootFiles)for(let e of Object.keys(r.rootFiles)){let r=wpt(n,e),o=H(t,r);G(o)?a.push({path:r,reason:`already-exists`}):i.push({path:r,kind:`file`,template:e})}let s=l8(r.id),c=s.length>0?u8(t):null,l=c!==null&&`refusal`in c?c.refusal:void 0,u=s.length>0?b0(t):[],d=new Map(u.map(e=>[e.name,H(t,e.dir)])),f=s.length>0?n2(H(t,...y)):null,p=s.map(({name:e})=>{let n=H(t,`.ok`,`skills`,e),i=npt[e],a=i===void 0?null:d.get(i)??(G(H(t,`.ok`,`skills`,i,`SKILL.md`))?H(t,`.ok`,`skills`,i):null),o=d.get(e)??a??(G(H(n,`SKILL.md`))?n:null),s=d.has(e)||a===null?e:i,c=o!==null&&f!==null&&rpt(r.id,s,o,f)===`foreign`;return{name:e,pending:o===null&&l===void 0,...c?{conflict:!0}:{}}}),m=(r.requiredPlugins??[]).map(e=>({id:e,pending:!upt(t,e)}));return{created:i,skipped:a,warnings:o,...p.length>0?{packSkills:p}:{},...m.length>0?{requiredPlugins:m}:{},...p.length>0&&l!==void 0?{packSkillHomeRefusal:l}:{}}}const Ept=[`These are patterns to adapt to your domain, not a layout to copy verbatim.`,"To build a variant: create your own folders (via `write` or your editor) and reuse only the ideas that fit.","To adopt this pack as-is: re-run without `--dry-run`."].join(`
2061
2061
  `);function Dpt(e){return[e.starterTemplate,...e.extraTemplates??[]].join(`, `)}function Opt(e){let t=[`Pack: ${e.name} — ${e.description}`,``,Ept,``];t.push(`Layout & rationale:`);for(let n of e.folders)t.push(` ${n.path}/ — ${n.title}`),t.push(` why: ${n.description}`),t.push(` templates: ${Dpt(n)}`);let n=e.rootFiles?Object.keys(e.rootFiles):[];return n.length>0&&t.push(``,`Root files: ${n.join(`, `)}`),t.join(`
2062
2062
  `)}function kpt(e){let{contentDir:t,checkLocalOpSecurity:n}=e;async function r(e,r){if(!n(e,r,{handler:`seed-plan`}))return;if(e.method!==`GET`){X(r,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let i=new URL(e.url??`/`,`http://localhost`),a=i.searchParams.get(`rootDir`)??void 0,o=i.searchParams.get(`packId`),s=g8(o);if(o!==null&&o!==``&&s===void 0){X(r,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${o}" is not registered.`});return}try{let e=await Tpt({projectDir:t,rootDir:a,packId:s});Q(r,200,Vn,{plan:e},{handler:`seed-plan`})}catch(e){if(e instanceof d8){X(r,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof f8){X(r,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}X(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let i=Z(_e,async(e,n,r)=>{let i=r.plan;if(!i||typeof i!=`object`){X(n,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let a=i,o=r.packId,s=g8(o);if(typeof o==`string`&&o.length>0&&s===void 0){X(n,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${o}" is not registered.`});return}try{let e=await bpt(a,{projectDir:t,packId:s});Q(n,200,gie,{result:e},{handler:`seed-apply`})}catch(e){X(n,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)=>n(e,t,{handler:`seed-apply`})}),a=Z(aee,async(e,n,r)=>{let i=g8(r.packId);if(i===void 0){X(n,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-install-pack-skill`,detail:`Pack id "${r.packId}" is not registered.`});return}try{let e=await opt(t,i);Q(n,200,Be,e,{handler:`seed-install-pack-skill`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to install pack skill.`,{handler:`seed-install-pack-skill`,cause:e})}},{handler:`seed-install-pack-skill`,method:`POST`,preBodyGate:(e,t)=>n(e,t,{handler:`seed-install-pack-skill`})});async function o(e,t){if(n(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){X(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}Q(t,200,ke,{packs:hpt()},{handler:`seed-packs`})}}return P$({"/api/seed/plan":r,"/api/seed/apply":i,"/api/seed/install-pack-skill":a,"/api/seed/packs":o},{mutating:[`/api/seed/apply`,`/api/seed/install-pack-skill`]})}const v8=`share-construct-url`;function Apt(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 jpt(e,t,n,r,i){return`https://${e}/${t}/${n}/blob/${encodeURIComponent(r)}/${i.split(`/`).map(encodeURIComponent).join(`/`)}`}function Mpt(e,t,n,r,i){let a=`https://${e}/${t}/${n}/tree/${encodeURIComponent(r)}`;return i===``?a:`${a}/${i.split(`/`).map(encodeURIComponent).join(`/`)}`}function y8(e,t){let n=t?.branchExists,r=t?.kind,i=t?.freshness;q(`share`).info({action:`construct-url`,result:e,...n===void 0?{}:{branchExists:n},...r===void 0?{}:{kind:r},...i===void 0?{}:{freshness:i}},`share action`)}async function Npt(e,t,n,r){try{let{git:i}=sK(e,{timeoutMs:5e3,credentialConfig:[]}),a=`refs/remotes/origin/${t}`;await i.raw([`rev-parse`,`--verify`,a]);let o=Bt([n===``?`.`:n]),[s,c,l]=await Promise.all([i.raw([`cat-file`,`-e`,`${a}:${n}`]).then(()=>!0).catch(()=>!1),i.raw([`diff`,`--name-only`,a,...o]),i.raw([...nU,...o])]);return s?c.trim()!==``||l.trim()!==``?`stale`:`current`:r===`folder`&&c.trim()===``&&l.trim()===``?`empty`:`absent`}catch(e){let t=S6(e);q(`share`).warn({action:`freshness-probe-failed`,kind:r,error:t},`[share] freshness probe failed; omitting freshness`);return}}const b8=`share-target-status`;function Ppt(e,t){for(let n of e)if(n.from===t){if(n.status.startsWith(`R`))return{verdict:`renamed`,renamedTo:n.to};if(n.status===`D`)return{verdict:`deleted`}}return{verdict:`deleted`}}function Fpt(e,t){let n=t.endsWith(`/`)?t:`${t}/`,r=new Set;for(let t of e){if(!t.from.startsWith(n)||!t.status.startsWith(`R`))continue;let e=t.from.slice(n.length);t.to.endsWith(`/${e}`)?r.add(t.to.slice(0,t.to.length-e.length-1)):r.add(`\0ambiguous`)}let i=r.size===1?[...r][0]:void 0;return i!==void 0&&i!==`\0ambiguous`?{verdict:`renamed`,renamedTo:i}:{verdict:`deleted`}}async function Ipt(e,t,n,r,i){let a=q(`share`),o=e=>(a.info({action:`target-status`,verdict:e.verdict,kind:r},`target-status verdict`),e),{git:s}=sK(e,i.skipFetch?{credentialConfig:[]}:{timeoutMs:i.fetchTimeoutMs??15e3,credentialConfig:i.credentialConfig});if(!i.skipFetch)try{await s.raw([`fetch`,`origin`,t])}catch(e){return a.warn({action:`target-status`,kind:r,error:S6(e)},`target-status fetch failed`),o({verdict:`unknown`})}let c=`origin/${t}`;try{if(await s.raw([`cat-file`,`-e`,`${c}:${n}`]).then(()=>!0).catch(()=>!1)){let t=await s.raw([`cat-file`,`-e`,`HEAD:${n}`]).then(()=>!0).catch(()=>!1),r=G(H(e,n));return o(t&&!r?{verdict:`changed-locally`}:{verdict:`on-origin`})}let t=(await s.raw([`log`,`-1`,`--format=%H`,c,...Bt([n===``?`.`:n])])).trim();if(t===``)return o({verdict:`never-on-branch`});let i=await sU(s,[`diff-tree`,`-M`,`-r`,`--no-commit-id`,`--name-status`,`${t}^1`,t]),a=r===`folder`?Fpt(i,n):Ppt(i,n);return a.verdict===`renamed`&&!await s.raw([`cat-file`,`-e`,`${c}:${a.renamedTo}`]).then(()=>!0).catch(()=>!1)?o({verdict:`deleted`}):o(a)}catch(e){return a.warn({action:`target-status`,kind:r,error:S6(e)},`target-status detection failed`),o({verdict:`unknown`})}}function Lpt(e){let{projectDir:t,contentDir:n,log:r,checkLocalOpSecurity:i,localOpCliArgs:a,localOpGuard:o,getSyncEngine:s,resolveCredentialConfig:c,toGitRelativePath:l}=e,u=e.declaredGitHubHosts??G6(),d=Z(D,async(e,r,i)=>{try{if(!t){y8(`no-remote`,{kind:i.kind}),Q(r,200,Xi,{ok:!1,error:`no-remote`},{handler:v8});return}let e=i.kind===`doc`?i.docPath:i.folderPath;if(!Apt(e,i.kind)){y8(`invalid-path`,{kind:i.kind}),Q(r,200,Xi,{ok:!1,error:`invalid-path`},{handler:v8});return}let a=Vdt(t);if(a===null){if(q6(t,u).kind===`no-remote`){y8(`no-remote`,{kind:i.kind}),Q(r,200,Xi,{ok:!1,error:`no-remote`},{handler:v8});return}y8(`detached-head`,{kind:i.kind}),Q(r,200,Xi,{ok:!1,error:`detached-head`},{handler:v8});return}let o=q6(t,u);if(o.kind===`no-remote`){y8(`no-remote`,{kind:i.kind}),Q(r,200,Xi,{ok:!1,error:`no-remote`},{handler:v8});return}if(o.kind===`non-github`){y8(`non-github-remote`,{kind:i.kind}),Q(r,200,Xi,{ok:!1,error:`non-github-remote`},{handler:v8});return}if(!oft(t,a)){y8(`branch-not-on-origin`,{branchExists:!1,kind:i.kind}),Q(r,200,Xi,{ok:!1,error:`branch-not-on-origin`,branch:a},{handler:v8});return}let s=l(t,n);if(s===null)throw Error(`content dir is not contained within the project dir`);let c=s===``?e:e===``?s:`${s}/${e}`,d;d=i.kind===`doc`?jpt(o.host,o.owner,o.repo,a,c):Mpt(o.host,o.owner,o.repo,a,c);let f;try{let e=s===``?0:ln(Mpt(o.host,o.owner,o.repo,a,s)).targetSegments.length;f=`https://openknowledge.ai/d/${Dt(d,e)}`}catch(e){if(!(e instanceof Xe))throw e;y8(`unsupported-share-url`,{kind:i.kind}),Q(r,200,Xi,{ok:!1,error:`unsupported-share-url`},{handler:v8});return}let p=await Npt(t,a,c,i.kind);y8(`ok`,{branchExists:!0,kind:i.kind,freshness:p}),Q(r,200,Xi,{ok:!0,shareUrl:f,sharedUrl:d,branch:a,freshness:p},{handler:v8})}catch(e){X(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:v8,cause:e})}},{handler:v8,method:`POST`,preBodyGate:(e,t)=>i(e,t,{handler:v8})});function f(e,t,n){let r=e.split(`/`),i=t.split(`/`);if(n>=r.length||n>=i.length)return{verdict:`unknown`};for(let e=0;e<n;e+=1)if(r[e]!==i[e])return{verdict:`unknown`};return{verdict:`renamed`,renamedTo:i.slice(n).join(`/`)}}let p=Z(cn,async(e,n,r)=>{try{if(!t){X(n,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:b8});return}if(!Ylt(r.path,r.kind)){X(n,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:b8});return}let e=await Ipt(t,r.branch,r.path,r.kind,{credentialConfig:await c()}),i=e.verdict!==`renamed`||r.contentRootDepth===void 0?e:f(r.path,e.renamedTo,r.contentRootDepth);Q(n,200,_r,i,{handler:b8})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:b8,cause:e})}},{handler:b8,method:`POST`,preBodyGate:(e,t)=>i(e,t,{handler:b8})});async function m(e){let[t,...n]=a,i=[...n,...e];return await new Promise((e,n)=>{let a=ls(t,i,vG({..._G,env:{...process.env}})),o=!1,s=setTimeout(()=>{if(!o){o=!0;try{a.kill(`SIGKILL`)}catch{}a.stdout.destroy(),a.stderr.destroy(),n(Error(`share subprocess timed out after ${sft}ms`))}},sft);s.unref?.();let c=[],l=[];a.stdout.on(`data`,e=>c.push(e)),a.stderr.on(`data`,e=>l.push(e)),a.on(`close`,t=>{if(o)return;o=!0,clearTimeout(s);let n=Buffer.concat(c).toString(`utf-8`);if(t!==0){let e=$6(Buffer.concat(l).toString(`utf-8`)).slice(0,500);r.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:n,code:t})}),a.on(`error`,e=>{o||(o=!0,clearTimeout(s),n(e))})})}return P$({"/api/share/construct-url":d,"/api/share/target-status":p,"/api/share/publish/owners":Z(me,async(e,t)=>{if(!o.tryAcquire(`/api/share/publish/owners`)){X(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:J6,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await m([`share`,`owners`,`--json`]),n=uft(Z6(e));Q6(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),Q(t,200,Qn,n,{handler:J6})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:J6,cause:e})}finally{o.release(`/api/share/publish/owners`)}},{handler:J6,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>i(e,t,{handler:J6})}),"/api/share/publish/name-check":Z(me,async(e,t)=>{let n=nG(e),r=n.get(`owner`)??``,i=n.get(`name`)??``;if(!lft(r)||!cft(i)){X(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:Y6});return}if(!o.tryAcquire(`/api/share/publish/name-check`)){X(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:Y6,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await m([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=fft(Z6(e));Q6(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),Q(t,200,kn,n,{handler:Y6})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Y6,cause:e})}finally{o.release(`/api/share/publish/name-check`)}},{handler:Y6,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>i(e,t,{handler:Y6})}),"/api/share/publish":Z(Ye,async(e,n,i)=>{if(!t){Q6(`publish-create`,`no-project`),Q(n,200,Et,{ok:!1,error:`no-project`},{handler:X6});return}if(!lft(i.owner)||!cft(i.name)){X(n,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:X6});return}if(!o.tryAcquire(`/api/share/publish`)){X(n,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:X6,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,i.owner,`--name`,i.name,`--visibility`,i.visibility,`--project-dir`,t,`--json`];i.description!==void 0&&i.description.length>0&&e.push(`--description`,i.description);let{stdout:a}=await m(e),o=hft(Z6(a));Q6(`publish-create`,o.ok?`ok`:o.error),o.ok&&s?.()?.refreshRemote().catch(e=>{r.warn({err:e},`[share] post-publish refreshRemote failed`)}),Q(n,200,Et,o,{handler:X6})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:X6,cause:e})}finally{o.release(`/api/share/publish`)}},{handler:X6,method:`POST`,preBodyGate:(e,t)=>i(e,t,{handler:X6})})})}function Rpt(e){let{contentDir:t,projectDir:n,homeDirOverride:r,skillsHome:i,isSafeDocName:a,commentService:o,enumerateInstalledSkillsCached:s,checkLocalOpSecurity:c}=e,l=Z(me,async(e,a)=>{try{let e=wx(n??t),o=W(n??t),c=await S0(i),l=s({projectDir:e,...r===void 0?{}:{home:r}}),u=new Set(b0(t).map(e=>e.name)),d=new Set(c.map(e=>e.name)),f={...l,skills:l.skills.filter(t=>Lc(t.provenance,e)&&!(t.provenance.scope===`project`?u.has(t.name):d.has(t.name))).map(e=>Loe(e.provenance,e.home,o)?{...e,outsideProject:!0}:e)};Q(a,200,An,f,{handler:`skills-installed`})}catch(e){X(a,500,`urn:ok:error:internal-server-error`,`Failed to enumerate installed skills.`,{handler:`skills-installed`,cause:e})}},{handler:`skills-installed`,method:`GET`,skipBodyParse:!0}),u={"/api/comment-counts":Z(me,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`prefix`),i=n.searchParams.get(`docNames`);if(r===null&&i===null){X(t,400,`urn:ok:error:invalid-request`,`Missing docNames or prefix parameter.`,{handler:`comment-counts`});return}let s={};if(r!==null){let e=r.trim();if(e!==``&&!a(e)){X(t,400,`urn:ok:error:invalid-request`,`Invalid prefix parameter.`,{handler:`comment-counts`});return}s=Object.fromEntries(await o.countThreads({prefix:e}))}else{let e=(i??``).split(`,`).map(e=>e.trim()).filter(e=>e!==``&&a(e));s=Object.fromEntries(await o.countThreads({docNames:e}))}Q(t,200,Vre,{counts:s},{handler:`comment-counts`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to read comment counts.`,{handler:`comment-counts`,cause:e})}},{handler:`comment-counts`,method:`GET`,skipBodyParse:!0}),"/api/skills/installed":l,"/api/templates":Z(me,I$(async(e,n)=>{let r=await uct(W(t)),i=r.templates.map(e=>{let{scope:t,...n}=e;return n});Q(n,200,M,{templates:i,truncated:r.truncated},{handler:`templates-list`})},{handler:`templates-list`,title:`Failed to list templates.`}),{handler:`templates-list`,method:`GET`,skipBodyParse:!0}),"/api/skill/install-state":Z(me,I$(async(e,t)=>{let n=await o7e(Hs());Q(t,200,m,{...n},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>c(e,t,{handler:`skill-install-state`})})};return{paths:Object.keys(u),table:{resolve(e){let t=u[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1}}}const x8=new Map;function zpt(e){return e.kind===`git`?`git\n${e.url}\n${e.subpath??``}`:e.kind===`well-known`?`wk\n${e.origin}\n${e.skill}`:`local\n${e.path}`}function Bpt(e){for(let[t,n]of x8)n.expiresAt>e||(x8.delete(t),n.fetched.then(e=>e.cleanup()).catch(()=>{}))}async function Vpt(e){if(e.kind===`local`)return Ej(e);let t=Date.now();Bpt(t);let n=zpt(e),r=x8.get(n);if(!r){let i=Ej(e);r={fetched:i,expiresAt:t+3e4},x8.set(n,r);let a=r;i.catch(()=>{x8.get(n)===a&&x8.delete(n)})}let i=await r.fetched;return{dir:i.dir,ref:i.ref,cleanup:()=>{}}}const Hpt=q(`skills-leaderboard`),Upt=6e5;let S8=null;async function Wpt(e=24,t={}){let n=t.now??Date.now(),r=t.fetchImpl??fetch;if(S8&&n-S8.at<Upt)return S8.data.slice(0,e);try{let t=await r(`https://www.skills.sh/`,{headers:{"user-agent":`open-knowledge (+skills discovery)`,RSC:`1`},signal:AbortSignal.timeout(8e3),redirect:`manual`});if(!t.ok)throw Error(`HTTP ${t.status} ${t.statusText}`);let i=eIe(await t.text());if(i.length===0)throw Error(`parsed 0 skills (payload format may have changed)`);return S8={at:n,data:i},i.slice(0,e)}catch(t){return Hpt.warn({err:t},`skills.sh leaderboard fetch failed — Discover falls back to topics`),S8?.data.slice(0,e)??[]}}const Gpt=new Map;async function Kpt(e,t={}){let n=t.now??Date.now(),r=t.fetchImpl??fetch,i=Gpt.get(e);if(i&&n-i.at<Upt)return i.data;try{let t=await r(`https://www.skills.sh/${e}`,{headers:{"user-agent":`open-knowledge (+skills discovery)`},signal:AbortSignal.timeout(8e3),redirect:`manual`});if(!t.ok)throw Error(`HTTP ${t.status} ${t.statusText}`);let i=nIe(await t.text(),e);if(i.length===0)throw Error(`parsed 0 skills (page format may have changed)`);return Gpt.set(e,{at:n,data:i}),i}catch(t){return Hpt.warn({err:t,source:e},`skills.sh publisher page fetch failed — install counts unavailable`),i?.data??[]}}function qpt(e){let{log:t,skillsHome:n,projectDir:r,contentDir:i,resolveSkillDirForRead:a}=e;return{handleSkillsSearch:Z(me,async(e,n)=>{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`q`)?.trim()??``;if(r.length<2){X(n,400,`urn:ok:error:invalid-request`,`Search query must be at least 2 characters.`,{handler:`skills-search`});return}try{let e=await fetch(`https://skills.sh/api/search?q=${encodeURIComponent(r)}&limit=30`,{signal:AbortSignal.timeout(8e3)});if(e.ok){let t=Nj(await e.json());Q(n,200,$n,{results:t,backend:`skills.sh`,degraded:!1},{handler:`skills-search`});return}t.warn({status:e.status},`skills.sh search unavailable — falling back to GitHub topic search`)}catch(e){t.warn({err:e},`skills.sh search failed — falling back to GitHub topic search`)}try{let e=encodeURIComponent(`${r} topic:agent-skills`),i=await fetch(`https://api.github.com/search/repositories?q=${e}&per_page=30`,{signal:AbortSignal.timeout(8e3),headers:{Accept:`application/vnd.github+json`}});if(!i.ok){t.warn({status:i.status},`GitHub skill search fallback returned non-ok`),X(n,502,`urn:ok:error:internal-server-error`,`Skill discovery is temporarily unavailable.`,{handler:`skills-search`,detail:`GitHub fallback returned ${i.status}.`});return}let a=qPe(await i.json());Q(n,200,$n,{results:a,backend:`github-fallback`,degraded:!0},{handler:`skills-search`})}catch(e){X(n,502,`urn:ok:error:internal-server-error`,`Skill discovery is temporarily unavailable.`,{handler:`skills-search`,cause:e})}},{handler:`skills-search`,method:`GET`,skipBodyParse:!0}),handleSkillsPopular:Z(me,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=Number(n.searchParams.get(`limit`)),i=Number.isFinite(r)&&r>0?Math.min(Math.floor(r),60):24;try{let e=await Wpt(i);Q(t,200,$n,{results:e,backend:`skills.sh`,degraded:e.length===0},{handler:`skills-popular`})}catch(e){X(t,502,`urn:ok:error:internal-server-error`,`Popular skills are temporarily unavailable.`,{handler:`skills-popular`,cause:e})}},{handler:`skills-popular`,method:`GET`,skipBodyParse:!0}),handleSkillsPublisher:Z(me,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`source`)?.trim()??``;if(!/^[\w.-]+\/[\w.-]+$/.test(n)||n.includes(`..`)){X(t,400,`urn:ok:error:invalid-request`,`source must be owner/repo.`,{handler:`skills-publisher`});return}try{let e=await Kpt(n);Q(t,200,$n,{results:e,backend:`skills.sh`,degraded:e.length===0},{handler:`skills-publisher`})}catch(e){X(t,502,`urn:ok:error:internal-server-error`,`Publisher skills are temporarily unavailable.`,{handler:`skills-publisher`,cause:e})}},{handler:`skills-publisher`,method:`GET`,skipBodyParse:!0}),handleSkillsDetail:Z(me,async(e,n)=>{let r=new URL(e.url??``,`http://localhost`),i=r.searchParams.get(`source`)?.trim()??``,a=r.searchParams.get(`name`)?.trim()??``;if(!i||!a){X(n,400,`urn:ok:error:invalid-request`,`source and name are required.`,{handler:`skills-detail`});return}let o=Boe(i,a);if(!o){X(n,400,`urn:ok:error:invalid-request`,`Unrecognized skill source.`,{handler:`skills-detail`});return}let{skillsUrl:s,sourceKind:c,sourceUrl:l}=o,u={},d=!1;try{let e=await fetch(s,{signal:AbortSignal.timeout(8e3)});e.ok&&(d=!0,u=KPe(await e.text()))}catch(e){t.warn({err:e,skillsUrl:s},`skills.sh detail fetch failed — degrading to repo link`)}Q(n,200,kne,{title:u.title??a,description:u.description??``,image:u.image??null,skillsUrl:d?s:null,sourceKind:c,sourceUrl:l},{handler:`skills-detail`})},{handler:`skills-detail`,method:`GET`,skipBodyParse:!0}),handleSkillsPreview:Z(me,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`source`)?.trim()??``,i=n.searchParams.get(`name`)?.trim()??``;if(!r){X(t,400,`urn:ok:error:invalid-request`,`source is required.`,{handler:`skills-preview`});return}let a=null;try{a=await Fj(r,i||void 0)}catch(e){if(e instanceof xj){X(t,400,`urn:ok:error:invalid-request`,`Could not resolve source.`,{handler:`skills-preview`,cause:e});return}throw e}let o=a?.spec??wj(r);if(!o){X(t,400,`urn:ok:error:invalid-request`,`Unrecognized preview source.`,{handler:`skills-preview`,detail:`Expected owner/repo, a git URL, a website source, or a local path.`});return}if(!s2(t,o,`skills-preview`))try{let e=await Vpt(o),n=Mj(e.dir);if(n.length===0){X(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-preview`});return}let a=n[0];if(i){let e=n.find(e=>e.name===i)??n.find(e=>kj(e.dir)?.name===i);if(!e){X(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skills-preview`,detail:`"${i}" not among: ${n.map(e=>e.name).join(`, `)}.`});return}a=e}let s=Aj(a.dir);if(s){X(t,400,`urn:ok:error:invalid-request`,`Skill bundle is too large.`,{handler:`skills-preview`,detail:s});return}let c=jj(a.dir);if(!c){X(t,404,`urn:ok:error:not-found`,`SKILL.md unreadable in source.`,{handler:`skills-preview`});return}let l=MFe(r),u=NFe(e.dir);Q(t,200,Cne,{name:c.name,description:c.description,skillMd:c.skillMd,files:c.files.map(e=>({relPath:e.relPath,content:e.content})),plugin:l??void 0,pluginBundle:u??void 0},{handler:`skills-preview`})}catch(e){if(e instanceof xj){X(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-preview`,cause:e});return}X(t,502,`urn:ok:error:internal-server-error`,`Preview is unavailable.`,{handler:`skills-preview`,cause:e})}},{handler:`skills-preview`,method:`GET`,skipBodyParse:!0}),handleSkillsDiscover:Z(me,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`source`)?.trim()??``;if(!n){X(t,400,`urn:ok:error:invalid-request`,`source is required.`,{handler:`skills-discover`});return}let r=YPe(n);if(r){try{let e=await jPe(`https://${r.hostname}`);Q(t,200,O,{skills:e},{handler:`skills-discover`})}catch(e){if(e instanceof xj){X(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-discover`,cause:e});return}throw e}return}let i=wj(n);if(!i){X(t,400,`urn:ok:error:invalid-request`,`Unrecognized source.`,{handler:`skills-discover`,detail:`Expected owner/repo, a git URL, a website source, or a local path.`});return}if(!s2(t,i,`skills-discover`))try{let e=Mj((await Vpt(i)).dir).map(e=>{let t=kj(e.dir);return{name:t?.name??e.name,description:t?.description??null}});Q(t,200,O,{skills:e},{handler:`skills-discover`})}catch(e){if(e instanceof xj){X(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-discover`,cause:e});return}X(t,502,`urn:ok:error:internal-server-error`,`Discovery is unavailable.`,{handler:`skills-discover`,cause:e})}},{handler:`skills-discover`,method:`GET`,skipBodyParse:!0}),handleSkillsResolveRef:Z(me,async(e,o)=>{let s=new URL(e.url??``,`http://localhost`),c=s.searchParams.get(`ref`)?.trim()??``,l=s.searchParams.get(`from`)?.trim()??``,u=s.searchParams.get(`scope`)?.trim()===`global`?`global`:`project`;if(!c||!yi.test(c)||c.length>64){X(o,400,`urn:ok:error:invalid-request`,`A valid ref is required.`,{handler:`skills-resolve-ref`});return}try{let e=e=>Q(o,200,bn,e,{handler:`skills-resolve-ref`});for(let t of[u,u===`project`?`global`:`project`]){let r=a(t,c);if(r!==null){e({kind:`local`,scope:t,name:c,dir:U(t===`project`?i:n,r).split(vs).join(`/`)});return}}let s=u===`project`?r:n,d=l&&s?n2(H(s,...y)).skills[l]:void 0;if(d?.source){let n=(await Fj(d.source,c))?.spec??wj(d.source),r=n&&!(n.kind===`git`&&!j$(n.url));if(n&&r){let r;try{let t=await Ej(n);if(r=t.cleanup,Mj(t.dir).map(e=>kj(e.dir)?.name??e.name).includes(c)){e({kind:`import`,source:d.source,ref:c,via:`source`});return}}catch(e){t.debug({err:e,ref:c,from:l,source:d.source},`resolve-ref: source rung unreachable, falling through to publisher`)}finally{r?.()}}}if(d?.publisher)try{let t=await fetch(`https://skills.sh/api/search?q=${encodeURIComponent(c)}&limit=30`,{signal:AbortSignal.timeout(8e3)});if(t.ok){let n=Nj(await t.json()).filter(e=>e.name===c&&e.publisher===d.publisher);if(n.length===1){let t=n[0];if(t){e({kind:`import`,source:t.source,ref:c,via:`publisher`});return}}}}catch(e){t.debug({err:e,ref:c,publisher:d.publisher},`resolve-ref: skills.sh unavailable, no publisher resolution`)}e({kind:`none`})}catch(e){X(o,500,`urn:ok:error:internal-server-error`,`Could not resolve the reference.`,{handler:`skills-resolve-ref`,cause:e instanceof Error?e:Error(String(e))})}},{handler:`skills-resolve-ref`,method:`GET`,skipBodyParse:!0})}}function Jpt(e){let{handleSkillsSearch:t,handleSkillsPopular:n,handleSkillsPublisher:r,handleSkillsDetail:i,handleSkillsPreview:a,handleSkillsDiscover:o,handleSkillsResolveRef:s}=qpt(e);return P$({"/api/skills/search":t,"/api/skills/popular":n,"/api/skills/publisher":r,"/api/skills/detail":i,"/api/skills/preview":a,"/api/skills/discover":o,"/api/skills/resolve-ref":s},{mutating:[`/api/skills/preview`,`/api/skills/discover`,`/api/skills/resolve-ref`]})}function Ypt(e){let{projectDir:t,contentDir:n,getPrincipal:r,hocuspocus:i,log:a,checkLocalOpSecurity:o,getSyncEngine:s,conflicts:c,serializeDoc:l,setBatchInProgress:u}=e;function d(e){let t={file:e.file,detectedAt:e.detectedAt,conflict:e.kind,docName:c.docNameOf(e),conflictKind:e.kind===`reconcile`&&e.reason===`stale-external-write`?`stale-external-write`:`git`};switch(e.kind){case`merge-native`:return t;case`working-tree`:return{...t,theirsSha:e.theirsSha,...e.baseSha===void 0?{}:{baseSha:e.baseSha}};case`reconcile`:return{...t,reason:e.reason};default:return t}}async function f(e,t){if(o(e,t,{handler:`sync-status`})){if(e.method!==`GET`){X(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=s?.();if(!e){Q(t,200,ot,{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(),Q(t,200,ot,e.getStatus(),{handler:`sync-status`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let p=Z(Yt,async(e,t,n)=>{let r=s?.();if(!r){X(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;Q(t,202,Ere,{op:i},{handler:`sync-trigger`}),r.trigger(i).catch(e=>{a.error({err:e,op:i},`[sync] fire-and-forget trigger failed`)})},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>o(e,t,{handler:`sync-trigger`})?s?.()?!0:(X(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1}),m=Z(mee,async(e,t,n)=>{let r=s?.();if(!r){X(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-blocking`});return}if(r.getBlockingPaths().length===0){X(t,409,`urn:ok:error:no-blocking-changes`,`No local changes are blocking a merge.`,{handler:`sync-resolve-blocking`});return}try{let e=r.getBlockingPaths(),n=await r.commitBlockingPaths();Q(t,200,_t,{action:`commit`,paths:e,...n===null?{}:{commitSha:n}},{handler:`sync-resolve-blocking`}),r.trigger(`sync`).catch(e=>{a.error({err:e},`[sync] resolve-blocking follow-up sync failed`)})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-resolve-blocking`,cause:e})}},{handler:`sync-resolve-blocking`,method:`POST`,preBodyGate:(e,t)=>o(e,t,{handler:`sync-resolve-blocking`})});async function h(e,t){if(o(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){X(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{Q(t,200,N,{conflicts:c.list().map(d)},{handler:`sync-conflicts`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let g=Z(fee,async(e,i,a)=>{let{file:o,strategy:s,content:l}=a,d=y$(a,r),f;t&&(d.kind===`agent`||d.kind===`principal`)&&(f=qY(W(t,o),n),d9e(f,{writerId:d.writerId,displayName:d.displayName,colorSeed:d.colorSeed},Date.now(),3e3)),u?.(!0);try{await c.resolve(o,s,l),Q(i,200,See,{},{handler:`sync-resolve-conflict`})}catch(e){if(f&&p9e(f),e instanceof qK){X(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`sync-resolve-conflict`});return}if(e instanceof $q){X(i,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-resolve-conflict`,detail:`This file has no tracked conflict — it may have been resolved by another session, or the path may be stale. Refresh the conflict list in the OpenKnowledge app before retrying.`,extensions:{file:e.file}});return}if(e instanceof Qq){let t=c.findByFile(e.file),n=t===void 0?Jq:qq(t.kind,t.kind===`reconcile`?t.reason:void 0),r=e.refusal===`strategy-not-offered`;X(i,422,`urn:ok:error:unresolved-conflict-markers`,r?`Strategy not offered for this conflict.`:`Resolution still contains conflict markers.`,{handler:`sync-resolve-conflict`,detail:r?`Strategy "${s}" is not offered for this conflict. Pick one of the strategies listed in resolutionOptions.`:"The submitted content still contains a `<<<<<<< … >>>>>>>` block. Resolve every region, or take one side wholesale with a strategy listed in resolutionOptions.",extensions:{file:e.file,refusal:e.refusal,resolutionOptions:n}});return}X(i,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,extensions:{file:o,strategy:s}})}finally{u?.(!1)}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>o(e,t,{handler:`sync-resolve-conflict`})});async function _(e,n){if(!o(e,n,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){X(n,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!t){X(n,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=r.searchParams.get(`file`);if(!a){X(n,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(a.includes(`..`)||a.startsWith(`/`)){X(n,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let s=c.findByFile(a);if(s===void 0){X(n,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:a}});return}let u=s.kind===`reconcile`?s.reason:void 0,d=[...qq(s.kind,u)],f=c.docNameOf(s)??jW(a),p=i.documents.get(f),m=e=>{Q(n,200,Vie,{file:a,...e,conflict:s.kind,conflictKind:u===`stale-external-write`?`stale-external-write`:`git`,...u===void 0?{}:{reason:u},resolutionOptions:d},{handler:`sync-conflict-content`})},h=r.searchParams.get(`source`);switch(s.kind){case`reconcile`:{let e=h===`ytext`&&l?l(f):null;m({base:s.stages.base,ours:tY(s,e),theirs:s.stages.theirs,kind:`both-modified`});return}case`working-tree`:{let e=yj({baseDir:t,timeout:{block:15e3}});try{let n=async t=>{if(!t)return``;try{return await e.raw([`cat-file`,`blob`,t])}catch(e){throw console.warn(JSON.stringify({event:`conflict-content-readblob-failed`,file:a,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e}},r=await n(s.theirsSha),i=await n(s.baseSha),o=``,c=!1;if(p){let e=l?l(f):null;e!==null&&(o=e,c=!0)}else{eY(H(t,a),t,{allowShareableOkArtifact:zG});try{o=K(H(t,a),`utf-8`),c=!0}catch(e){if(rG(e)!==`ENOENT`)throw console.warn(JSON.stringify({event:`conflict-content-ours-read-failed`,file:a,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e;c=!1}}m({base:i,ours:o,theirs:r,kind:c?r.length===0?`modify-delete`:`both-modified`:`delete-modify`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}case`merge-native`:{let e=yj({baseDir:t,timeout:{block:15e3}}),r=async t=>{try{return{present:!0,content:await e.raw([`show`,`:${t}:${a}`])}}catch(e){let n=e instanceof Error?e.message:String(e);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:t,file:a,detail:n,handler:`sync-conflict-content`})),e;return{present:!1}}};try{let[e,t,n]=await Promise.all([r(1),r(2),r(3)]),i=e.present?e.content:``,a=n.present?n.content:``,o=t.present&&n.present?`both-modified`:!t.present&&n.present?`delete-modify`:t.present&&!n.present?`modify-delete`:`both-modified`,s=t.present?t.content:``;if(h===`ytext`&&p!==void 0&&o!==`delete-modify`){let e=l?l(f):null;e!==null&&!nJ(e)?s=e:e!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":f,handler:`sync-conflict-content`}))}m({base:i,ours:s,theirs:a,kind:o})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}default:X(n,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:Error(`unknown conflict kind: ${JSON.stringify(s)}`)});return}}return P$({"/api/sync/status":f,"/api/sync/trigger":p,"/api/sync/conflicts":h,"/api/sync/conflict-content":_,"/api/sync/resolve-conflict":g,"/api/sync/resolve-blocking":m},{mutating:[`/api/sync/trigger`,`/api/sync/resolve-conflict`,`/api/sync/resolve-blocking`]})}const Xpt={detached:!0,stdio:`ignore`,shell:!1};function Zpt(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function C8(e,t,n){return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,r(e))},o=setTimeout(()=>a({ok:!1,reason:`timeout`}),n);try{let n=ls(e,[...t],vG(Xpt));n.once(`error`,e=>{clearTimeout(o),a(Zpt(e))}),n.once(`spawn`,()=>{if(!i){try{n.unref()}catch{}clearTimeout(o),a({ok:!0})}})}catch(e){q(`spawn-detached`).warn({err:e},`synchronous spawn throw`),clearTimeout(o),a(Zpt(e))}})}const w8=`spawn-cursor`;function Qpt(e){throw Error(`Unhandled spawn-cursor outcome.reason: ${String(e)}`)}async function $pt(e,t,n){if(e.method!==`POST`){X(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:w8,extraHeaders:{Allow:`POST`}});return}let r;try{r=await L$(e,{maxBytes:4096,timeoutMs:5e3})}catch(e){if(e instanceof R$){z$(t,w8);return}if(e instanceof B$){X(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:w8,cause:e});return}if(e instanceof V$){X(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:w8,cause:e});return}X(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:w8,cause:e});return}let i;try{i=JSON.parse(r.toString(`utf-8`))}catch(e){X(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:w8,cause:e});return}let a=typeof i.path==`string`?i.path:``;if(!a){X(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:w8});return}if(!D8(a,n.contentDir,n.platform)){X(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:w8});return}let o=await(n.resolveCursorBinary??T8)(500);if(!o){X(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:w8});return}let s=E8(o,a,n.platform),c=await(n.spawnDetached??C8)(s.exec,s.args,2e3);if(c.ok){Q(t,200,we,{},{handler:w8});return}switch(c.reason){case`not-installed`:X(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:w8});return;case`timeout`:X(t,504,`urn:ok:error:cursor-spawn-timeout`,`Cursor spawn exceeded the deadline.`,{handler:w8});return;case`spawn-error`:X(t,502,`urn:ok:error:cursor-spawn-failed`,`Cursor spawn failed.`,{handler:w8});return;case`invalid-path`:X(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:w8});return;default:return Qpt(c.reason)}}const emt={darwin:[()=>`/Applications/Cursor.app/Contents/Resources/app/bin/cursor`,e=>`${e}/Applications/Cursor.app/Contents/Resources/app/bin/cursor`],win32:[e=>`${e}\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd`,()=>`C:\\Program Files\\Cursor\\resources\\app\\bin\\cursor.cmd`]};async function T8(e){let t=emt[process.platform];if(t&&t.length>0){let e=Hs();for(let n of t){let t=n(e);try{return await Ks(t,qs.X_OK),t}catch(e){let n=e?.code;n!==`ENOENT`&&n!==`EACCES`&&n!==`EPERM`&&q(`spawn-cursor`).warn({code:n,candidate:t},`unexpected fs.access error on bundle probe`)}}}return new Promise(t=>{let n=process.platform===`win32`?`where`:`which`;cs(n,[`cursor`],vG({timeout:e,encoding:`utf-8`}),(e,n)=>{if(e){t(null);return}let r=n.split(/\r?\n/)[0]?.trim();t(r&&r.length>0?r:null)})})}function E8(e,t,n){return n===`darwin`&&/\.app\/?$/.test(e)?{exec:`/usr/bin/open`,args:[`-a`,e.replace(/\/$/,``),t]}:n===`win32`&&/\.(cmd|bat)$/i.test(e)?{exec:process.env.ComSpec||`cmd.exe`,args:[`/d`,`/c`,e,t]}:{exec:e,args:[t]}}function D8(e,t,n){if(!e||typeof e!=`string`||e.includes(`\0`)||!t||typeof t!=`string`)return!1;if(n===`win32`){if(!/^([a-zA-Z]:[\\/]|\\\\)/.test(e)||!/^([a-zA-Z]:[\\/]|\\\\)/.test(t))return!1}else if(!e.startsWith(`/`)||!t.startsWith(`/`))return!1;let r=n===`win32`?ys:_s;try{let i=r.resolve(e),a=r.resolve(t);if(n===`win32`){let e=r.parse(i).root.toLowerCase(),t=r.parse(a).root.toLowerCase();if(!e||!t||e!==t)return!1}if(i===a)return!0;let o=r.relative(a,i);return o===``||o===`.`||!(o===`..`||o.startsWith(`..${r.sep}`)||n===`win32`&&(/^[a-zA-Z]:[\\/]/.test(o)||o.startsWith(`\\\\`))||n!==`win32`&&o.startsWith(`/`))}catch(e){return q(`spawn-cursor`).warn({err:e},`unexpected path-resolution error`),!1}}const tmt=q(`handoff-dispatch`),O8=`handoff`,k8=2e3,nmt={"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,probeScheme:`codex`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}},rmt=Object.keys(nmt),imt=B({target:ui(rmt),url:R().min(1).max(4096),workspacePath:R().optional()}),amt=B({}).loose();async function omt(e,t,n){if(e.method!==`POST`){X(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:O8,extraHeaders:{Allow:`POST`}});return}let r;try{r=await L$(e,{maxBytes:4096,timeoutMs:5e3})}catch(e){if(e instanceof R$){z$(t,O8);return}if(e instanceof B$){X(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:O8,cause:e});return}if(e instanceof V$){X(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:O8,cause:e});return}X(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:O8,cause:e});return}let i;try{i=JSON.parse(r.toString(`utf-8`))}catch(e){X(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:O8,cause:e});return}let a=imt.safeParse(i);if(!a.success){X(t,400,`urn:ok:error:invalid-request`,`Invalid request body.`,{handler:O8});return}let{target:o,url:s,workspacePath:c}=a.data,l=nmt[o];if(!s.startsWith(l.urlScheme)){X(t,400,`urn:ok:error:invalid-request`,`URL scheme must be ${l.urlScheme} for target ${o}.`,{handler:O8});return}let u=n.sleep??Ai,d=n.spawnDetached??C8,f=n.isSchemeRegistered??F1(n.platform);if(await iH({site:`deep-link`,agentId:hre(o)??o,mode:`external`,log:tmt,snapshot:n.hostSnapshot}),l.type===`app-bundle`){if(n.platform===`darwin`){l.quitFirst&&(await d(`/usr/bin/osascript`,[`-e`,`tell application "${l.appName}" to quit`],k8).catch(()=>void 0),await u(3e3));let e=await d(`/usr/bin/open`,[`-a`,l.appName],k8);if(!e.ok){A8(t,o,e.reason);return}await u(5e3)}else if(!await f(l.probeScheme)){X(t,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:O8,extensions:{target:o}});return}let e=smt(s,n.platform),r=await d(e.exec,e.args,k8);if(!r.ok){A8(t,o,r.reason);return}Q(t,200,amt,{},{handler:O8});return}if(!c){X(t,400,`urn:ok:error:invalid-request`,`workspacePath is required for cursor handoff.`,{handler:O8});return}if(!D8(c,n.contentDir,n.platform)){X(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:O8});return}let p=await(n.resolveCursorBinary??T8)(500);if(!p){X(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:O8,extensions:{target:`cursor`}});return}let m=E8(p,c,n.platform),h=await d(m.exec,m.args,k8);if(!h.ok){A8(t,o,h.reason);return}await u(1500);let g=smt(s,n.platform),_=await d(g.exec,g.args,k8);if(!_.ok){A8(t,o,_.reason);return}Q(t,200,amt,{},{handler:O8})}function smt(e,t){return t===`darwin`?{exec:`/usr/bin/open`,args:[e]}:t===`win32`?{exec:`rundll32.exe`,args:[`url.dll,FileProtocolHandler`,e]}:{exec:`xdg-open`,args:[e]}}function A8(e,t,n){switch(n){case`not-installed`:X(e,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:O8,extensions:{target:t}});return;case`timeout`:X(e,504,`urn:ok:error:handoff-spawn-timeout`,`Handoff spawn exceeded the deadline.`,{handler:O8,extensions:{target:t}});return;case`spawn-error`:X(e,502,`urn:ok:error:handoff-spawn-failed`,`Handoff spawn failed.`,{handler:O8,extensions:{target:t}});return;default:cmt(n)}}function cmt(e){throw Error(`Unhandled spawn reason: ${String(e)}`)}function lmt(e){let{contentDir:t,log:n,checkLocalOpSecurity:r,installedAgentsCache:i,agentIntegrations:a}=e;async function o(e,o){if(r(e,o,{handler:`handoff`}))try{await omt(e,o,{contentDir:t,platform:process.platform,isSchemeRegistered:i.probeWithCache,hostSnapshot:()=>u$({env:`local-web`,resolve:a?.probe})})}catch(t){o.headersSent||(n.error({err:t,requestId:Oq(e)},`[handoff] route wrapper failed`),X(o,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:t}))}}async function s(e,i){if(r(e,i,{handler:`spawn-cursor`}))try{await $pt(e,i,{contentDir:t,platform:process.platform})}catch(t){i.headersSent||(n.error({err:t,requestId:Oq(e)},`[spawn-cursor] route wrapper failed`),X(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:t}))}}return P$({"/api/spawn-cursor":s,"/api/handoff":o,"/api/client-logs":Z(ite,async(e,t,n)=>{try{let r=q(`renderer`),i=A7e(e)?.clientSurface,a=i===void 0?{}:{clientSurface:i};n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&r.warn({source:`renderer-console`,transport:`web`,...a,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let e of n.entries)try{r[e.level]({...e.fields,source:`renderer-console`,transport:`web`,...a,...e.sourceId?{sourceId:e.sourceId}:{},...e.lineNumber===void 0?{}:{lineNumber:e.lineNumber},...e.ts===void 0?{}:{clientTs:e.ts}},e.event??e.message)}catch{}Q(t,200,cre,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})})},{mutating:[`/api/client-logs`]})}const j8=q(`github-permissions`);function umt(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function dmt(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function M8(e){return e.status===429||e.status===403&&(e.headers.get(`x-ratelimit-remaining`)===`0`||e.headers.get(`retry-after`)!==null)}function fmt(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let n=t.push;return typeof n==`boolean`?n:null}async function pmt(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return j8.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let n=fmt(t);return n===null?(j8.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):n?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:case 429:return M8(e)?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return j8.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function mmt(e,t,n,r,i){let a=n(e,{login:t?.login});if(a.available&&a.token){if(t?.login!==void 0&&a.fallback===!0){let n=_mt(i,e);W6(n,t.login)||j8.warn({host:e,declaredLogin:t.login,declaredSource:t.source,resolvedLogin:n},`[permissions] declared GitHub account did not produce the gh token — probing as the active account`)}return{token:a.token,source:`gh`,resolvedLogin:a.resolvedLogin}}if(r)try{let t=await r.get(e);if(t?.token){let e=t.login===`unknown`?void 0:t.login;return{token:t.token,source:`token-store`,resolvedLogin:e}}}catch(t){j8.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}function hmt(e,t){let n=t.resolvedLogin??(t.tokenSource===`gh`?_mt(t.detectGhAccounts,t.host):void 0);return{...e,...n===void 0?{}:{resolvedLogin:n},...gmt(t.account,n)}}function gmt(e,t){return e?.login===void 0||W6(e.login,t)?{}:{declaredLogin:e.login,declaredSource:e.source}}function _mt(e,t){if(e)try{return e(t)?.find(e=>e.active)?.login}catch(e){j8.warn({err:e,host:t},`[permissions] detectGhAccounts failed — denial stays unnamed`);return}}async function vmt(e){let{owner:t,repo:n,host:r=`github.com`,transport:i=`https`,account:a,detectGh:o=()=>({available:!1}),detectGhAccounts:s,tokenStore:c,_fetchFn:l=fetch,_timeoutMs:u=5e3}=e,{token:d,source:f,resolvedLogin:p}=await mmt(r,a,o,c,s);if(f===`anonymous`)return i===`ssh`||i===`git`?(j8.info({host:r,transport:i},`[permissions] no credential resolved for ssh/git origin — abstaining (push auths with SSH keys, not tokens)`),{kind:`unknown`,error:`ssh-unverified`}):(j8.info({host:r},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`not-authenticated`,...gmt(a,void 0)});let m=`${umt(r)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}`;j8.info({host:r,tokenSource:f,tokenLen:d===void 0?0:d.length},`[permissions] probe starting`);let h=new AbortController,g=setTimeout(()=>h.abort(),u);try{let e=await l(m,{signal:h.signal,headers:dmt(d)}),t=await pmt(e,d!==void 0),n=t.kind===`denied`?hmt(t,{account:a,tokenSource:f,resolvedLogin:p,detectGhAccounts:s,host:r}):t;return j8.info({host:r,tokenSource:f,httpStatus:e.status,kind:n.kind,reason:n.kind===`denied`?n.reason:void 0,error:n.kind===`unknown`?n.error:void 0},`[permissions] probe classified`),n}catch(e){return h.signal.aborted?(j8.warn({host:r,timeoutMs:u},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(j8.warn({err:e,host:r},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(g)}}async function ymt(e){let t=performance.now(),n=await vmt(e);return Tmt(n,performance.now()-t),n}function bmt(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let xmt=null;function Smt(){return xmt||=_H().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,not-authenticated,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,ssh-unverified,none}.`}),xmt}let Cmt=null;function wmt(){return Cmt||=_H().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),Cmt}function Tmt(e,t){let n=bmt(e);Smt().add(1,n),wmt().record(t,{outcome:n.outcome})}const Emt=q(`github-reference`);function Dmt(e,t){let n=e.get(t);if(n===null||n.trim()===``)return null;let r=Number(n);return Number.isFinite(r)&&r>=0?r:null}function Omt(e,t){let n=Dmt(e,`retry-after`);if(n!==null)return t+Math.max(n,1)*1e3;let r=Dmt(e,`x-ratelimit-reset`);return e.get(`x-ratelimit-remaining`)===`0`&&r!==null&&r*1e3>t?r*1e3:t+6e4}function kmt(e){return e.status===200?!1:e.headers.get(`retry-after`)!==null||e.headers.get(`x-ratelimit-remaining`)!==`0`}const Amt=new Set([`RATE_LIMITED`,`RATE_LIMIT`]);function jmt(e){let t=P8(e)?.errors;return Array.isArray(t)&&t.some(e=>Amt.has(P8(e)?.type))}const Mmt={graphql:`[github-reference] GitHub rate-limited reference cards; no GraphQL requests to this host until the limit resets`,rest:`[github-reference] GitHub rate-limited reference cards; no REST requests to this host until the limit resets`,"graphql+rest":`[github-reference] GitHub rate-limited reference cards; no GraphQL or REST requests to this host until the limit resets`};var Nmt=class{until=new Map;holding(e,t){let n=this.until.get(e);return n===void 0?!1:n>t||(this.until.delete(e),!1)}hold(e,t,n){let r=Math.max(this.until.get(e)??0,Math.min(n+36e5,Omt(t,n)));return this.until.set(e,r),r}};const Pmt={ok:!1,reason:`not-found`},N8={ok:!1,reason:`unavailable`};function P8(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function F8(e){return typeof e==`string`?e:null}function I8(e){return F8(P8(e)?.login)}function Fmt(e){return`${e.host===`github.com`?`https://api.github.com`:`https://${e.host}/api/v3`}/repos/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function Imt(e){return e===`github.com`?`https://api.github.com/graphql`:`https://${e}/api/graphql`}function Lmt(e,t){let n={"User-Agent":`open-knowledge-server`,Accept:t};return e!==null&&(n.Authorization=`Bearer ${e}`),n}async function L8(e,t,n,r){let i=new AbortController,a=setTimeout(()=>i.abort(),r);try{let r=await n(e,{...t,signal:i.signal});return r.status===200?{status:200,headers:r.headers,body:await r.json()}:(await r.body?.cancel(),{status:r.status,headers:r.headers,body:null})}finally{clearTimeout(a)}}function Rmt(e,t){if(e?.toUpperCase()===`OPEN`)return`open`;let n=t?.toUpperCase();return n===`NOT_PLANNED`||n===`DUPLICATE`?`not-planned`:`completed`}function R8(e){let t=Tne.safeParse(e);return t.success?t.data:null}function zmt(e,t){let n=P8(t);if(n===null)return null;let r={repo:`${e.owner}/${e.repo}`,number:e.number,title:n.title,author:I8(n.author),createdAt:n.createdAt};if(n.__typename===`Issue`)return R8({...r,kind:`issue`,lifecycle:Rmt(F8(n.state),F8(n.stateReason))});if(n.__typename!==`PullRequest`)return null;let i=F8(n.state),a=i===`MERGED`?`merged`:i===`CLOSED`?`closed`:n.isDraft===!0?`draft`:`open`,o=P8(n.commits)?.nodes,s=Array.isArray(o)?P8(P8(o.at(-1))?.commit):null,c=P8(n.mergeQueueEntry);return R8({...r,kind:`pull`,lifecycle:a,additions:n.additions,deletions:n.deletions,...a===`open`?{status:{mergeQueue:c===null?null:{position:c.position,state:c.state},autoMerge:P8(n.autoMergeRequest)!==null,mergeState:n.mergeStateStatus,reviewDecision:n.reviewDecision,checks:P8(s?.statusCheckRollup)?.state??null}}:{}})}function Bmt(e,t,n){let r={repo:`${e.owner}/${e.repo}`,number:e.number},i=P8(n);if(i!==null){let e=i.merged===!0||F8(i.merged_at)!==null?`merged`:i.state===`closed`?`closed`:i.draft===!0?`draft`:`open`,t=F8(i.mergeable_state)?.toUpperCase()??null;return R8({...r,kind:`pull`,title:i.title,author:I8(i.user),createdAt:i.created_at,lifecycle:e,additions:i.additions,deletions:i.deletions,...e===`open`?{status:{mergeQueue:null,autoMerge:P8(i.auto_merge)!==null,mergeState:t,reviewDecision:null,checks:null}}:{}})}let a=P8(t);return a===null?null:R8({...r,kind:`issue`,title:a.title,author:I8(a.user),createdAt:a.created_at,lifecycle:Rmt(F8(a.state),F8(a.state_reason))})}async function Vmt(e,t,n,r,i){let a=await L8(Imt(e.host),{method:`POST`,headers:{...Lmt(t,`application/vnd.github.merge-info-preview+json`),"Content-Type":`application/json`},body:JSON.stringify({query:`query($owner: String!, $name: String!, $number: Int!) {
2063
2063
  repository(owner: $owner, name: $name) {
@@ -2107,14 +2107,14 @@ tags: [lore, history]
2107
2107
  `),s=n-a;return{text:`${o}\n<truncated: ${s} more lines — re-run with a more-specific query>`,truncated:!0,omittedLines:s}}function Xxt(e){let t=[];for(let n of e)if(n.command===`cat`)for(let e of n.args.slice(1))e.startsWith(`-`)||qxt.test(e)&&t.push(e);return t}function Zxt(e){for(let t=1;t<e.length;t++){let n=e[t],r=n.match(/^--lines=(\d+)$/);if(r)return Number(r[1]);if(n===`--lines`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}if(n===`-n`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}let i=n.match(/^-n(\d+)$/);if(i)return Number(i[1]);let a=n.match(/^-(\d+)$/);if(a)return Number(a[1])}return 10}function Qxt(e,t){if(e.length<2)return null;let n=e[e.length-1];if(n.command!==`head`&&n.command!==`tail`)return null;let r=Zxt(n.args),i=t.split(`
2108
2108
  `),a=i[i.length-1]===``?i.length-1:i.length;if(a<r)return null;let o=i.slice(0,a),s=new Set(o.map(e=>{let t=e.indexOf(`:`);return t>0?e.slice(0,t):e})).size,c=e.slice(0,-1).map(e=>e.command).join(` | `);return{banner:`Output hit \`${n.command} -${r}\` cap (${a} lines, ${s} unique file${s===1?``:`s`}). The \`${c}\` stage may have had more matches that never reached stdout. For existence checks across many files, prefer \`grep -rl PATTERN <dir>\` (list files only, no head). For enumeration, drop the \`| ${n.command}\` or widen the cap.`}}function $xt(e){return e.type===`directory`}function eSt(e){let t=[e.title?`**${e.title}** (${e.path}/)`:`**${e.path}/** (directory)`];if(e.description&&t.push(e.description),e.tags&&e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.templates_available&&e.templates_available.length>0){let n=e.templates_available.map(e=>e.description?`${e.name} — ${e.description} (${e.scope})`:`${e.name} (${e.scope})`).join(`, `);t.push(`templates: ${n}`)}e.schemas_applicable&&e.schemas_applicable.length>0&&t.push(`schemas: ${e.schemas_applicable.join(`, `)}`);let n=[];if(n.push(e.recursiveMdCount>e.directMdCount?`${e.directMdCount} md file${e.directMdCount===1?``:`s`} here (${e.recursiveMdCount} in tree)`:`${e.directMdCount} md file${e.directMdCount===1?``:`s`}`),e.childDirCount>0&&n.push(`${e.childDirCount} subdir${e.childDirCount===1?``:`s`}`),t.push(n.join(`, `)),e.mostRecentMd){let n=e.mostRecentMd.updatedAt?`, ${e.mostRecentMd.updatedAt.slice(0,10)}`:``;t.push(`most recent: ${e.mostRecentMd.title??e.mostRecentMd.path} (${e.mostRecentMd.path}${n})`)}if(e.commentCount!==void 0&&e.commentCount>0){let n=`⚠ ${e.commentCount} unresolved comment${e.commentCount===1?``:`s`} in tree`;if(e.commentedDocs&&e.commentedDocs.length>0){let t=e.commentedDocs.map(e=>`${e.docName} (${e.count})`).join(`, `),r=e.commentedDocs.reduce((e,t)=>e+t.count,0);n+=`: ${t}${r<e.commentCount?`, …`:``}`}t.push(n)}return e.truncated&&t.push(`scan truncated`),`- ${t.join(` — `)}`}function tSt(e){let t=[e.state===`orphaned`?`passage gone`:null,e.queued?`queued`:null].filter(e=>e!==null),n=t.length>0?` [${t.join(`, `)}]`:``;return e.quote===``?`"${e.body}"${n}`:`"${e.body}" on “${e.quote}”${n}`}function nSt(e){let t=[`**${e.title??e.path}** (${e.path})`];e.description&&t.push(e.description),e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.graphRole&&t.push(`graph: ${e.graphRole}`);let n=typeof e.frontmatter.status==`string`?e.frontmatter.status:null,r=typeof e.frontmatter.type==`string`?e.frontmatter.type:null;if(n&&t.push(`status: ${n}`),r&&t.push(`type: ${r}`),e.schemas_applicable&&e.schemas_applicable.length>0&&t.push(`schemas: ${e.schemas_applicable.join(`, `)}`),e.commentCount!==null&&e.commentCount>0){let n=`⚠ ${e.commentCount} unresolved comment${e.commentCount===1?``:`s`}`;if(e.comments&&e.comments.length>0){let t=e.comments.slice(0,3).map(tSt);n+=`: ${t.join(`; `)}${e.comments.length>3?`; …`:``}`}t.push(n)}if(e.backlinkCount!==null){let n=`backlinks: ${e.backlinkCount}`;if(e.backlinks&&e.backlinks.length>0){let t=e.backlinks.slice(0,5).map(e=>e.source);n+=` (${t.join(`, `)}${e.backlinks.length>5?`, …`:``})`}t.push(n)}if(e.forwardLinkCount!==null){let n=`forward links: ${e.forwardLinkCount}`;if(e.forwardLinks&&e.forwardLinks.length>0){let t=e.forwardLinks.slice(0,5).map(e=>e.kind===`doc`?e.docName:e.url);n+=` (${t.join(`, `)}${e.forwardLinks.length>5?`, …`:``})`}t.push(n)}if(e.history&&e.history.length>0){let n=e.history.map(e=>{let t=e.writerClassification===`agent`?`agent: ${e.writerName}`:e.writerClassification===`principal`?`human: ${e.writerName}`:`${e.writerClassification}: ${e.writerName}`;return`${e.hash.slice(0,7)} [${t}] ${e.message}`});t.push(`OK edits: ${n.join(` · `)}`)}if(e.projectHistory&&e.projectHistory.length>0){let n=e.projectHistory.map(e=>`${e.hash.slice(0,7)} ${e.authorName}: ${e.subject}`);t.push(`commits: ${n.join(` · `)}`)}return`- ${t.join(` — `)}`}function rSt(e,t,n,r){let i=null;for(let t=e.length-1;t>=0;t--){let n=e[t],r=n.command;if(r===`ls`||r===`cat`){i=n;break}if((r===`head`||r===`tail`)&&b7(n).length>0){i=n;break}}if(!i)return``;let a=b7(i);if(i.command===`ls`){let e=a[a.length-1];if(!e||e===`.`)return``;let n=e.replace(/\/+/g,`/`);if(n.startsWith(`./`)&&(n=n.slice(2)),n.endsWith(`/`)&&(n=n.slice(0,-1)),!n)return``;let i=r(n);return t.has(i)?`${i}/:\n`:``}let o=a.filter(e=>v7(e)&&n.has(r(e)));return o.length===1?`==> ${r(o[0])} <==\n`:``}function iSt(e){if(e.length===0)return``;let t=[``,`### Referenced files`,``];for(let n of e)t.push($xt(n)?eSt(n):nSt(n));return t.join(`
2109
2109
  `)}async function aSt(e,t){let n=[],r=[];return await Promise.all(t.map(async t=>{try{let i=await ec(W(e,t));i.isDirectory()?r.push(t):i.isFile()&&n.push(t)}catch(e){let n=e.code;n!==`ENOENT`&&n!==`ENOTDIR`&&k7.warn({path:t,code:n},`stat failed for a reported path; dropping it`);return}})),{files:n,dirs:r}}function A7(e,t){return U3(t,{enrichedPaths:[],error:{category:e,message:t}},!0)}function oSt(e,t){return e.map(e=>{let n=t(tbt(e.path));return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}})}function sSt(e){return e===null&&k7.warn({},`the engine refused a write without naming the file`),A7(`write_blocked`,`Write operation blocked: the command tried to write ${e===null?`a file`:`'${e}'`}. exec is read-only. For document changes, use the \`write\` or \`edit\` tool.`)}async function cSt(e,t){let n=await q3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return A7(`shell_construct_blocked`,`exec failed: ${n.error}`);let{cwd:r,executionCwd:i,config:a,url:o}=n,s=wt(hr(a.contentRules)),c=s.length>0?{contentDir:W(r,a.content.dir),frontmatterSchemas:s}:{},l=i===r?e=>e:e=>U(r,W(i,e)),u=lxt(e.command);if(`error`in u)return A7(u.error.category,u.error.message);let d=await mxt(u.stages,i);if(`error`in d)return A7(d.error.category,d.error.message);let f=Wbt(d.stages),p=Gbt(f),m=[...new Set(Uxt(u.stages).map(e=>M3(i,e)).filter(e=>e.ok).map(e=>e.rel))],h=await O7(i,m),g=Fxt(i),_=``,v=``;try{let e=await Ixt(g,p);if(e.exitCode!==0){let t=Nxt(e.stderr);if(t.blocked)return sSt(t.target)}_=e.stdout,v=e.stderr}catch(t){if(t instanceof Pxt)return A7(`output_overflow`,`Output exceeded 16 MB buffer. Narrow the command (e.g., add a more specific grep pattern, use head, restrict the path).`);let n=Nxt(t);return n.blocked?sSt(n.target):(k7.warn({err:t,command:e.command},`exec failed`),A7(`shell_construct_blocked`,`exec failed: ${t instanceof Error?t.message:String(t)}`))}let y=await O7(i,m),b=Gxt(h.snapshot,y.snapshot);if(b.changed.length>0)return k7.error({command:e.command,changed:b.changed},`files changed during exec`),A7(`security_invariant_violation`,`Security invariant violated: file(s) in the content directory were modified during a read-only exec call: ${b.changed.join(`, `)}. Either the read-only mount let a write through, or another writer (the live server, a human editor) touched these files at the same time. Logged.`);let x=h.truncated||y.truncated,S=Yxt(_),C=Mxt(_,f).filter(e=>M3(i,e).ok).map(l),{files:w,dirs:T}=await aSt(r,C),E=f.length===1&&f[0].command===`cat`&&w.length===1,D=await Promise.all(w.map(e=>Dlt(e,{projectDir:r,serverUrl:o,...c},{includeRichFields:E}).catch(()=>({path:e,tags:[],frontmatter:{},backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null,graphRole:null,commentCount:null,comments:null})))),O=await Promise.all(T.map(e=>jlt(e,1,{projectDir:r,serverUrl:o,...c}).catch(()=>({path:e,type:`directory`,directMdCount:0,recursiveMdCount:0,childDirCount:0,truncated:!1}))));if(!E&&o&&D.length>0){let e=D.map(e=>h6(e.path)),[t,n]=await Promise.all([blt(o,e).catch(()=>null),xlt(o,e).catch(()=>null)]);for(let e of D){let r=h6(e.path),i=t?.get(r);typeof i==`number`&&(e.backlinkCount=i);let a=n?.get(r);typeof a==`number`&&(e.commentCount=a)}}let ee=new Map(D.map(e=>[e.path,e])),k=new Map(O.map(e=>[e.path,e])),A=[];for(let e of C){let t=ee.get(e);if(t){A.push(t);continue}let n=k.get(e);n&&A.push(n)}let te=Xxt(f),j=[];te.length>0&&j.push(`File${te.length>1?`s`:``} ${te.join(`, `)} appear${te.length===1?`s`:``} to be binary (image/PDF/etc.) — exec returns text only (NG8). For binary retrieval, use native Read.`);let M=Qxt(f,_);M&&j.push(M.banner),v&&j.push(`stderr: ${v.trim()}`),x&&j.push(`Read-only mutation sweep was partial: the files in scope exceed the ${E7}-file cap, so only the first ${E7} were checked for unexpected writes. Narrow the command to a subdirectory for full sweep coverage.`);let ne=`${j.length>0?`${j.join(`
2110
- `)}\n\n`:``}${rSt(f,k,ee,l)+S.text}${iSt(A)}`,{resolve:re}=await a7({config:a,resolveCwd:async()=>r});return U3(ne,{enrichedPaths:oSt(A,re),stdoutTruncated:S.truncated,cwd:i,...j.length>0?{warnings:j}:{}})}function lSt(e,t){e.registerTool(`exec`,{description:Jxt,inputSchema:{command:R().describe(`Read-only bash command (allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut; pipes OK)`),cwd:R().optional().describe("Absolute host path to run the command from. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},outputSchema:H3({enrichedPaths:z3.describe("Per-referenced-file metadata: frontmatter, backlink/forward-link counts, unresolved comment threads (`commentCount`, plus `comments` on a single-file read), recent shadow-repo activity, and a route-only previewUrl. Directory entries carry a recursive `commentCount` + `commentedDocs`."),stdoutTruncated:Wa().optional().describe(`True when stdout was truncated by the soft cap.`),warnings:z(R()).optional().describe(`Tool-level warnings — head/tail truncation, binary detection, stderr, partial mutation-sweep coverage.`),cwd:R().optional().describe(`Absolute directory the command ran in.`),error:B({category:R(),message:R()}).optional().describe(`Present on failure — the error category + message.`)})},async e=>{try{return await cSt(e,t)}catch(e){return A7(`shell_construct_blocked`,`exec handler error: ${e instanceof Error?e.message:String(e)}`)}})}const uSt=[`Get the full browser URL for this project or a document/folder/skill, or an absolute markdown file outside the project. Opening is demand: auto-starts OK under the normal OK_MCP_AUTOSTART gate and waits briefly for UI; cold calls can take seconds. Other tools return route-only previewUrl paths; use this tool for an openable URL, never guess ports or hunt via ok ps/status.`,`Choose one: document (extension-less), folder (trailing-slash route), skill:{name,scope?} (project default), or file (absolute .md/.mdx in a loose-file/worktree session). file ignores cwd; other targets use current project. Omit targets for UI root.`,`When YOUR host opens URLs, navigate its embedded browser to url; Claude Code Desktop uses preview_start({url}) then navigate({url}). Only a stdio host without a browser tool should open the URL in the system browser. A CLI without a browser can use ok open <doc> for OK Desktop. This tool forces browser access even when Desktop is installed.`,`INSIDE OK's terminal/agent panel, use returned okOpenCommand instead; never paste url in the answer. If no UI is reachable, returns url:null, baseUrl:null, running:false, autoOpen plus state-specific recovery text (autostart disabled, no spawn authority or UI timeout). Follow it.`].join(`
2110
+ `)}\n\n`:``}${rSt(f,k,ee,l)+S.text}${iSt(A)}`,{resolve:re}=await a7({config:a,resolveCwd:async()=>r});return U3(ne,{enrichedPaths:oSt(A,re),stdoutTruncated:S.truncated,cwd:i,...j.length>0?{warnings:j}:{}})}function lSt(e,t){e.registerTool(`exec`,{description:Jxt,inputSchema:{command:R().describe(`Read-only bash command (allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut; pipes OK)`),cwd:R().optional().describe("Absolute host path to run the command from. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},outputSchema:H3({enrichedPaths:z3.describe("Per-referenced-file metadata: frontmatter, backlink/forward-link counts, unresolved comment threads (`commentCount`, plus `comments` on a single-file read), recent shadow-repo activity, and a route-only previewUrl. Directory entries carry a recursive `commentCount` + `commentedDocs`."),stdoutTruncated:Wa().optional().describe(`True when stdout was truncated by the soft cap.`),warnings:z(R()).optional().describe(`Tool-level warnings — head/tail truncation, binary detection, stderr, partial mutation-sweep coverage.`),cwd:R().optional().describe(`Absolute directory the command ran in.`),error:B({category:R(),message:R()}).optional().describe(`Present on failure — the error category + message.`)})},async e=>{try{return await cSt(e,t)}catch(e){return A7(`shell_construct_blocked`,`exec handler error: ${e instanceof Error?e.message:String(e)}`)}})}const uSt=[`Get the full browser URL for this project or a document/folder/skill, or an absolute markdown file outside the project. Opening is demand: auto-starts OK under the normal OK_MCP_AUTOSTART gate and waits briefly for UI; cold calls can take seconds. Other tools return route-only previewUrl paths; use this tool for an openable URL, never guess ports or hunt via the OpenKnowledge CLI's ps/status.`,`Choose one: document (extension-less), folder (trailing-slash route), skill:{name,scope?} (project default), or file (absolute .md/.mdx in a loose-file/worktree session). file ignores cwd; other targets use current project. Omit targets for UI root.`,`When YOUR host opens URLs, navigate its embedded browser to url; Claude Code Desktop uses preview_start({url}) then navigate({url}). Only a stdio host without a browser tool should open the URL in the system browser. A CLI without a browser can use the OpenKnowledge CLI's open <doc> for OK Desktop. This tool forces browser access even when Desktop is installed.`,`INSIDE OK's terminal/agent panel, use returned okOpenCommand instead; never paste url in the answer. If no UI is reachable, returns url:null, baseUrl:null, running:false, autoOpen plus state-specific recovery text (autostart disabled, no spawn authority or UI timeout). Follow it.`].join(`
2111
2111
  `),dSt={document:R().optional().describe(`Extension-less doc path to resolve a preview URL for (e.g. "specs/foo/SPEC"). Omit to get the UI root URL.`),folder:R().min(1).optional().describe('Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.'),skill:B({name:R().min(1).regex(yi,`Skill name must be lowercase letters, digits, and hyphens only.`).describe(`Skill name (the bundle-dir identity, wherever the skill lives).`),scope:ui(li).optional().describe("Skill scope; defaults to `project`.")}).optional().describe("Skill to resolve an editor preview URL for; returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`."),file:R().optional().describe("Absolute path to a single markdown file to open, including one OUTSIDE any Open Knowledge project. Resolves to the running single-file (or worktree) session whose content directory contains it and returns that session’s `url`. Mutually exclusive with `document` / `folder` / `skill`. When `file` is set, `cwd` is ignored."),cwd:R().optional().describe(P3)},fSt=H3({url:R().nullable().describe("Browser-reachable URL — the UI base joined with the doc route when `document` is given, else the UI root. `null` when no UI is running."),baseUrl:R().nullable().describe("Browser-reachable origin of the running UI (e.g. `http://localhost:5173`). `null` when no UI is running."),running:Wa().describe(`Whether a UI is running for the project.`),autoOpen:Wa().describe("User-scoped preview-auto-open preference (`appearance.preview.autoOpen`). When `true`, the agent should route the preview using capability-based routing (in-app browser if available, system browser as fallback). When `false`, the user is managing their own preview view (OK Desktop window, a browser tab they opened, etc.) — the agent must NOT open or refresh any preview UI, and should surface this URL only on direct user ask. Resolved fresh on every call; defaults to `true`."),okOpenCommand:R().nullable().optional().describe("Machine-readable form of the hosted-agent steer: when the calling agent runs inside an OpenKnowledge surface (the desktop app’s built-in terminal, or its in-app agent panel) AND a doc/folder/skill target was given, the exact OpenKnowledge CLI `open` command to run to bring it up for the user. Run it INSTEAD of navigating `url`, and do not paste `url` into your reply — the user is already in the app it points at. `null`/absent in every other context (navigate `url` per your host instead).")});function pSt(){return`The OK server is running but no preview UI is mounted (e.g. it was started with \`--only server\`). Restart it with plain \`${de()} start\` to serve the editor, or open the project in OK Electron.`}function mSt(){return`No OpenKnowledge server is running for this project. Start it with \`${de()} start\` (also starts the preview UI), or open the project in OK Electron.`}function hSt(){try{return jx({absPath:Vx(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value.appearance?.preview?.autoOpen??!0}catch(e){return process.stderr.write(`[preview-url] readUserAutoOpen failed: ${e instanceof Error?e.message:String(e)}\n`),!0}}function gSt(e){return`No Open Knowledge session is serving ${e} yet. On a host with a terminal, \`${de()} open ${e}\` starts one; otherwise open ${e} in the OK Desktop app. Then retry.`}function _St(e){try{let t=_3(e);return t===null||t.port<=0||!GU(t.pid)?!1:!v3(t)}catch(t){return process.stderr.write(`[preview-url] readServerLock failed at ${e} while checking ui capability: ${t instanceof Error?t.message:String(t)}\n`),!1}}function j7(e){try{let t=_3(e);return t!==null&&t.port>0&&GU(t.pid)}catch(t){return process.stderr.write(`[preview-url] readServerLock failed at ${e} while checking server liveness: ${t instanceof Error?t.message:String(t)}\n`),!1}}function vSt(e){return/^[A-Za-z0-9._/@%+-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function ySt(e,t){e.registerTool(`preview_url`,{description:uSt,inputSchema:dSt,outputSchema:fSt,annotations:{readOnlyHint:!1,idempotentHint:!0}},async e=>{if([e.document,e.folder,e.skill,e.file].filter(e=>e!=null).length>1)return{isError:!0,content:[{type:`text`,text:`Error: document, folder, skill, and file are mutually exclusive — pass at most one.`}]};if(e.file){if(!hs(e.file))return{isError:!0,content:[{type:`text`,text:`Error: file must be an absolute path (a loose file outside a project has no cwd to anchor a relative path).`}]};let n=(t.resolveUserAutoOpen??hSt)(),r=t.offCwdResolverDeps??Zvt(),i=await U5(e.file,r);if(i===null&&t.ensureSingleFileSession&&await t.ensureSingleFileSession(e.file).catch(t=>(process.stderr.write(`[preview-url] ensureSingleFileSession failed for ${e.file}: ${t instanceof Error?t.message:String(t)}\n`),!1))&&(i=await U5(e.file,r)),i!==null){let e=`${i.baseUrl}/#/${$5(i.docName)}`;return U3(`Preview URL: ${e}`,{url:e,baseUrl:i.baseUrl,running:!0,autoOpen:n})}return U3(gSt(e.file),{url:null,baseUrl:null,running:!1,autoOpen:n})}let n=await G3(t.resolveCwd,t.config,e.cwd);if(!n.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${n.error}`}]};let r=Hq(n.cwd),i={lockDir:r},a=n.config.appearance.preview.autoOpen,o=e.document?`#/${$5(e.document)}`:e.folder?`#/${Qyt(e.folder)}`:e.skill?`#/${e7(e.skill.scope??`project`,e.skill.name)}`:null,s=de(),c=e.document?`${s} open ${vSt(e.document)}`:e.folder?`${s} open ${vSt(e.folder)}`:e.skill?`${s} open ${e.skill.name} --skill${e.skill.scope===`global`?` --scope global`:``}`:null,l=t.isHostedAgent&&c?`You're running inside OpenKnowledge — run \`${c}\` to bring this up for the user. Don't navigate the URL below, open a browser, or paste the URL into your reply; it's for reference only.\n\n`:``,u=j7(r),d=!1;if(t.serverUrl!==void 0)try{await Ict(t.serverUrl,n.cwd)}catch(e){if(e instanceof ivt)d=!0;else return{isError:!0,content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}]}}let{baseUrl:f}=i7(i);if(f===null&&!u&&j7(r)&&(f=await ebt(i,{timeoutMs:t.uiBindWait?.timeoutMs??3e3,pollIntervalMs:t.uiBindWait?.pollIntervalMs??100})),f===null)return U3(`${l}${j7(r)?_St(r)?pSt():`The OK server is running but no UI has bound for this project yet. Retry in a few seconds, or open the project in OK Electron.`:`${mSt()}${d?` Auto-start is disabled (OK_MCP_AUTOSTART=0).`:``}`}`,{url:null,baseUrl:null,running:!1,autoOpen:a,okOpenCommand:t.isHostedAgent?c:null});let p=o?`${f}/${o}`:f;return U3(`${l}Preview URL: ${p}`,{url:p,baseUrl:f,running:!0,autoOpen:a,okOpenCommand:t.isHostedAgent?c:null})})}const bSt=B({version:R().describe("40-char commit SHA for this entry — pass to `restore_version({ document, version })`."),timestamp:R().describe(`ISO timestamp of the entry.`),author:R().describe(`Author display name.`),authorEmail:R().describe(`Author email.`),kind:ui([`checkpoint`,`wip`,`upstream`]).describe(`Entry kind: checkpoint / wip / upstream.`),message:R().describe(`Commit subject (the checkpoint summary, when one was set).`),contributors:z3.describe(`Per-contributor records parsed from the commit (writer id, name, docs, summaries).`),checkpoint:I().nullable().describe(`Checkpoint metadata when this entry is a checkpoint, else null.`)}),xSt=[`Read version history: pass exactly one document, folder or skill. Requires the Hocuspocus server. Returns shadow-repo entries newest first; version is a 40-char SHA for restore_version({document,version}) or restore_version({skill,version}).`,`document accepts optional .md/.mdx. folder lists attributed template/frontmatter activity; empty string is project root. skill is a project-scope name; global skills are unversioned. Optional branch (current default), limit (50 default, 200 max), offset (0), kind (checkpoint/upstream/wip), author and excludeAuthor (name/email).`].join(`
2112
2112
  `);function SSt(e,t){e.registerTool(`history`,{description:xSt,inputSchema:{document:R().optional().describe("Document name to query history for. Mutually exclusive with `folder`."),folder:R().optional().describe('Folder path to query the FOLDER timeline for — attributed activity over the folder\'s `.ok/` artifacts (templates + frontmatter): created / edited / renamed / moved / deleted, by whom, when. Mutually exclusive with `document`. Use `""` for the project root.'),skill:R().optional().describe("Skill name to query version history for. Mutually exclusive with `document` / `folder`."),branch:R().optional().describe(`Branch name (default: current branch)`),limit:Fn().int().min(1).max(200).optional().describe(`Maximum entries to return (default 50, max 200)`),offset:Fn().int().min(0).optional().describe(`Number of entries to skip for pagination (default 0)`),kind:ui([`checkpoint`,`upstream`,`wip`]).optional().describe("Filter by entry type (`checkpoint` / `upstream` / `wip`)."),author:R().optional().describe(`Filter to entries by this author name or email`),excludeAuthor:R().optional().describe(`Exclude entries by this author name or email`),cwd:R().optional().describe(P3)},outputSchema:H3({entries:z(bSt).describe("Timeline entries, newest first. Each carries a `version` for `restore_version`."),total:Fn().int().optional().describe(`Total entries available (pre-pagination).`),truncated:Wa().optional().describe(`Whether more entries exist beyond this returned page (the result was limit-capped).`),previewUrl:I3,previewUrlSource:L3})},async e=>{let n=await q3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return $(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return $(W3(),!0);if((e.document===void 0?0:1)+(e.folder===void 0?0:1)+(e.skill===void 0?0:1)!=1)return $("Error: pass EXACTLY ONE of `document`, `folder`, or `skill`.",!0);let a=e.folder!==void 0,o=new URLSearchParams,s=null;if(a)o.set(`folder`,e.folder??``);else if(e.skill!==void 0){let t=await t6(i,`/api/skills`,`skills`);if(`error`in t)return $(`Error: ${t.error}`,!0);let n=t.rows.find(t=>t.name===e.skill&&t.scope===`project`&&typeof t.path==`string`);if(!n)return $(`Error: No project skill named "${e.skill}". Global skills are unversioned.`,!0);let r=String(n.path).replace(/\/SKILL\.mdx?$/i,`/SKILL`);o.set(`docName`,r),s=r}else{let t=Y3(e.document);if(!t.ok)return $(t.error,!0);o.set(`docName`,t.docName),s=t.docName}e.branch&&o.set(`branch`,e.branch),e.limit!=null&&o.set(`limit`,String(e.limit)),e.offset!=null&&o.set(`offset`,String(e.offset)),e.kind&&o.set(`type`,e.kind),e.author&&o.set(`author`,e.author),e.excludeAuthor&&o.set(`excludeAuthor`,e.excludeAuthor);let c=await e6(i,`/api/history?${o.toString()}`);if(!c.ok)return $(`Error: ${c.error}`,!0);let{ok:l,...u}=c,d=(Array.isArray(u.entries)?u.entries:[]).map(e=>{let t=e;return{version:t.sha,timestamp:t.timestamp,author:t.author,authorEmail:t.authorEmail,kind:t.type,message:t.message,contributors:t.contributors,checkpoint:t.checkpoint??null}}),f=u.total,p=u.hasMore,m=s?await r7(s,{config:t.config,resolveCwd:t.resolveCwd},r):null,h={entries:d,...typeof f==`number`?{total:f}:{},...typeof p==`boolean`?{truncated:p}:{}};return U3(JSON.stringify(h,null,2),{...h,previewUrl:m?.url??null,...m?{previewUrlSource:m.source}:{}})})}const CSt=new Set([...fi,...La]),wSt=[`Import an external agentskills.io/skills.sh skill as managed content. Requires the Hocuspocus server. source accepts a full skills.sh page URL (including website catalogs), owner/repo[/subpath], git URL, or local/file:// path. skill picks one from a multi-skill source. scope: project (default, versioned/shared) or global (user-wide, unversioned).`,`Writes the .agents/skills/<name>/ hub with provenance in .ok/skills-lock.json. Scripts are NEVER executed. add selects editor locations; import always places the skill somewhere. Use install later to change placement/form/source. Name collisions use <name>-imported, never overwrite; identical content-hash re-import is a no-op.`].join(`
2113
2113
  `);function TSt(e,t){e.registerTool(`import`,{description:wSt,inputSchema:{source:R().min(1).describe("Full skills.sh skill-page URL (`https://www.skills.sh/<owner>/<repo>/<skill>`, or `https://www.skills.sh/site/<hostname>/<skill>` for a website catalog), `owner/repo[/subpath]`, a git URL, or a local / `file://` path."),skill:R().min(1).optional().describe(`Pick one skill from a multi-skill source.`),add:z(Ea).min(1).describe('REQUIRED — where the imported skill goes. Editor ids (`claude` … `pi`), `agents` (the vendor-neutral hub), or a custom root path (".team/skills"). Same vocabulary as `install`. A skill acquired and placed nowhere is not a state worth having, so this is not optional.'),mode:ui([`copy`,`link`]).optional().describe('The form for the locations in `add`. "link": a symlink to the source. "copy": an independent folder, refreshed on watcher/startup sync while unedited; hand edits fork it. Omit to follow the form the skill already uses.'),scope:u7.optional(),summary:F3,cwd:R().optional().describe(P3)},outputSchema:H3({name:R().optional().describe(`Managed skill name created or matched by the import.`),path:R().optional().describe("Project-relative path of the imported skill bundle (under `.agents/skills`)."),alreadyImported:Wa().optional().describe(`True when an identical content hash already existed and no files changed.`),collisionRenamedFrom:R().optional().describe("Original upstream skill name when a local collision forced an `-imported` rename."),warnings:z(R()).optional().describe(`Non-fatal warnings from BOTH steps: the acquire (skipped unsupported bundle files) first, then the placement \`add\` runs. ${Vct(`each step`)} One step sending an unreadable shape replaces only its own slice of this list; the other step's text still comes through.`),warningCodes:z(ui([...fi,...La])).optional().describe(`${Bct(`either step`)} Authoring codes (from the imported SKILL.md): ${l6} Placement codes: ${Hct}`)})},async e=>{let n=await K3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return n.result;let r=await r6(Z3(n.url,t.localApi),`/api/skill/import`,{source:e.source,...e.skill===void 0?{}:{skill:e.skill},install:!1,...Tj(e.source)===null?{}:{marketplace:!0},...e.scope===void 0?{}:{scope:e.scope},...e.summary===void 0?{}:{summary:e.summary},...N3(t.identityRef?.current)});if(!r.ok){let e=typeof r.detail==`string`?` (${r.detail})`:``;return $(`Error: ${r.error}${e}`,!0)}let i=typeof r.name==`string`?r.name:e.source,a=await r6(Z3(n.url,t.localApi),`/api/skill/install`,{...e.scope===void 0?{}:{scope:e.scope},name:i,add:e.add,...e.mode===void 0?{}:{mode:e.mode},...e.summary===void 0?{}:{summary:e.summary},...N3(t.identityRef?.current)});if(!a.ok)return $(`Imported "${i}", but placing it failed: ${a.error}. Run \`install\` to retry the placement.`,!0);let o=r.alreadyImported===!0,s=typeof r.collisionRenamedFrom==`string`?r.collisionRenamedFrom:void 0,c=o6(r.warnings,r.warningCodes,CSt),l=o6(a.warnings,a.warningCodes,CSt),u=[...c.warnings,...l.warnings];return U3([o?`Skill "${i}" was already imported (identical content); its placement was applied.`:`Imported "${i}"${s?` (renamed from "${s}" — the name was taken)`:``} into .agents/skills as content. Scripts shown, never run. Use \`install\` to change where it lives.`,...u].join(`
2114
2114
  `),{name:i,path:typeof r.path==`string`?r.path:void 0,alreadyImported:o,...s?{collisionRenamedFrom:s}:{},warnings:u,...c.warningCodes&&l.warningCodes?{warningCodes:[...c.warningCodes,...l.warningCodes]}:{}})})}const ESt=new Set(La),DSt=["Manage where a SKILL is available: `{name, add?, remove?, convert?, mode?, source?, scope?}` or `{skillFolders: {...}}` alone. Requires the Hocuspocus server. One real source folder plus managed copies/symlinks; the source still loads with no extra locations. Use delete to remove the skill everywhere.",`name is the bundle identity: lowercase letters/digits/hyphens, ≤64 chars. Locations: claude/cursor/codex/copilot/opencode/pi, agents (.agents/skills), or custom root containing '/' such as .team/skills. Custom roots are project-relative, home-relative at global scope. scope: project (default, shared via git) or global (user-wide).`,`add/remove change membership; omitting both installs to configured editors. remove cannot remove the source; folder aliases unfollow minus this skill and keep others. Differing copies are preserved; editor removal may succeed and leave them in place.`,`mode: link = live symlink for source updates (copy where the OS refuses symlinks); copy = separate folder, refreshed on watcher/startup sync while unedited. Hand-edited copies fork; differing copies are preserved and cannot be converted. Requires add or convert; affects named locations only, no skill-wide default. Omit mode on add to inherit form. convert requires mode and changes form without membership; name all locations for uniformity.`,`source moves the real folder; its old location becomes a symlink. Run alone, not with add/remove. Source SKILL.md with conflict markers, invalid/missing frontmatter, XML in name/description or reserved open-knowledge* names is refused before projection.`,`skillFolders runs alone without name. link: {action:'link', scope, root, target}; target required, merge then symlink root; equal entries deduplicate, differing skills abort, interrupted merges can rerun. unlink: {action:'unlink', scope, root, exclude?}; makes a real directory of per-skill symlinks, excluding named skills and retaining others. add-root: {action:'add-root', scope, root}; declares a custom root for install/link.`].join(`
2115
2115
  `);async function OSt(e,t,n){let r=await K3(e.resolveCwd,e.config,e.serverUrl,n);if(!r.ok)return r.result;let i=await i6(r.url,`/api/skill-targets`,{folderAction:t});if(!i.ok)return $(`Error: ${i.error}`,!0);let a=i.folder??{moved:[],dropped:[],linked:[]};return U3(t.action===`link`?`Linked ${t.root} → ${t.target}: moved ${a.moved?.length??0} skill(s), dropped ${a.dropped?.length??0} duplicate(s). Its agent now reads everything placed in ${t.target}.`:t.action===`unlink`?`Unlinked ${t.root} — it is a real directory again with per-skill symlinks (nothing stopped working).`:`Declared ${t.root} as a custom skills root — it is now an install and link target.`,{folder:{moved:a.moved??[],dropped:a.dropped??[],linked:a.linked??[]}})}function kSt(e,t){e.registerTool(`install`,{description:DSt,inputSchema:{name:R().optional().describe(`${l7} Required unless \`skillFolders\` is given.`),skillFolders:It.optional().describe("Folder-level skill-topology verb (link / unlink / add-root). Lives here rather than on `config` so that `config` stays a pure read and hosts can auto-approve it. Run alone, without `name`."),add:z(Ea).optional().describe('Locations to ADD the skill to — everything else untouched. Editor ids (`claude`…`pi`), `agents` (the hub), or a custom root path (".team/skills").'),remove:z(Ea).optional().describe("Locations to REMOVE the skill from; differing copies are preserved and may remain after success. An editor reading via a folder alias is unfollowed from the shared root minus this skill (it keeps the rest). The SOURCE cannot be removed — its folder IS the skill; use `source` to move it or `delete` to remove the skill."),convert:z(Ea).optional().describe("Existing locations to change the FORM of, leaving their membership alone. Requires `mode`. Pass every location to make them uniform. Lossless both ways; a differing copy is refused rather than overwritten."),mode:ui([`copy`,`link`]).optional().describe('Form for locations in `add` or `convert`. "link": live pointer to the source. "copy": independent folder, refreshed on watcher/startup sync while unedited; a hand edit forks it. Omit on `add` to inherit the existing form. Other locations stay unchanged; no skill-wide default. Requires `add` or `convert`; `mode` alone is refused.'),source:Ea.optional().describe(`Move the skill's REAL folder to this location (the old source becomes a symlink — never a removal). Run alone, not combined with add/remove.`),scope:u7.optional(),summary:F3,cwd:R().optional().describe(P3)},outputSchema:H3({name:R().optional().describe(`Managed skill name installed or uninstalled.`),hosts:z(R()).optional().describe("Every location holding the skill after the operation, SOURCE first (editor ids, `agents`, custom root paths). Never empty — the source folder is the skill."),sourceMovedTo:R().optional().describe("Set when `source` relocated the real folder — its new bundle dir."),converted:z(R()).optional().describe("Locations whose form `convert` changed. Membership is unchanged."),warningCodes:z(ui(La)).optional().describe(`${s6} ${Hct}`),scripts:Wa().optional().describe("true when the skill ships executable `scripts/` (projected, never auto-run)."),warnings:z(R()).optional().describe(`Non-fatal install/uninstall warnings from target projection. ${c6}`),folder:B({moved:z(R()).describe(`Skill bundles moved into the target root.`),dropped:z(R()).describe(`Same-content duplicates dropped during the merge.`),linked:z(R()).describe(`Folders now linked (or unlinked/declared).`)}).optional().describe("Present after a `skillFolders` verb: what the folder operation did.")})},async e=>{if(e.skillFolders!==void 0)return e.name===void 0?await OSt(t,e.skillFolders,e.cwd):$("Error: `skillFolders` operates on folders, not one skill — do not combine with `name`.",!0);if(e.name===void 0)return $("Error: `name` is required (or pass `skillFolders`).",!0);let n=d7(e.name);if(!n.ok)return $(`Error: ${n.error}`,!0);if(e.convert!==void 0&&e.mode===void 0)return $("Error: `convert` needs `mode` — the form to convert those locations to.",!0);if(e.mode!==void 0&&(e.add?.length??0)===0&&(e.convert?.length??0)===0)return $("Error: `mode` needs `add` or `convert` — name the locations whose form should change.",!0);let r=await K3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!r.ok)return r.result;for(let n of e.convert??[]){let i=await r6(Z3(r.url,t.localApi),`/api/skill/install`,{...e.scope===void 0?{}:{scope:e.scope},name:e.name,convert:{target:n,mode:e.mode},...e.summary===void 0?{}:{summary:e.summary},...N3(t.identityRef?.current)});if(!i.ok)return $(V3(i),!0)}if(e.convert!==void 0&&e.add===void 0&&e.remove===void 0&&e.source===void 0){let t=e.mode===`link`?`symlinks to the source`:`independent copies`;return U3(`Converted ${e.convert.length} location(s) of skill "${e.name}" to ${t}.`,{name:e.name,converted:[...e.convert]})}let i=await r6(Z3(r.url,t.localApi),`/api/skill/install`,{...e.scope===void 0?{}:{scope:e.scope},name:e.name,...e.add===void 0?{}:{add:e.add},...e.remove===void 0?{}:{remove:e.remove},...e.source===void 0?{}:{source:e.source},...e.summary===void 0?{}:{summary:e.summary},...N3(t.identityRef?.current)});if(!i.ok)return $(V3(i),!0);for(let n of e.mode===void 0?[]:e.add??[]){let i=await r6(Z3(r.url,t.localApi),`/api/skill/install`,{...e.scope===void 0?{}:{scope:e.scope},name:e.name,convert:{target:n,mode:e.mode},...N3(t.identityRef?.current)});if(!i.ok)return $(`Added ${e.add?.join(`, `)} to "${e.name}", but setting ${n} to ${e.mode} failed. ${V3(i)}`,!0)}let a=Array.isArray(i.hosts)?i.hosts:[],o=i.scripts===!0,s=o6(i.warnings,i.warningCodes,ESt),c=typeof i.sourceMovedTo==`string`?i.sourceMovedTo:void 0;return U3([c===void 0?`Skill "${e.name}" now lives at: ${a.join(`, `)||`(its source folder)`}.`:`Moved skill "${e.name}"'s source folder to ${c}; other locations now link to it.`,...s.warnings].join(`
2116
2116
  `),{name:e.name,hosts:a,scripts:o,warnings:s.warnings,...s.warningCodes?{warningCodes:s.warningCodes}:{},...c===void 0?{}:{sourceMovedTo:c}})})}const ASt=[`backlinks`,`forward`,`dead`,`orphans`,`hubs`,`suggest`],jSt=[`Read the wiki-link graph. Requires the Hocuspocus server. kind is one value or an array; results merge, failures go in errors. Use audit for validation.`,"`backlinks`/`forward`/`suggest` require document. suggest finds unlinked prose mentions; excerpt is normalized context, NOT edit-ready text. Re-read with exec, locate the real text using offset, then edit into a wiki-link.","`dead` lists raw unresolved internal targets; sourceDocuments optionally filters with OR semantics. Includes skill docs and lowercase log.md/log.mdx: inspect deliberately, never use as a repair queue or rewrite existing log entries to clear findings.","`orphans` finds disconnected pages; mode incoming/outgoing/both. `hubs` lists most-linked pages; limit defaults 20."].join(`
2117
- `);function MSt(e,t){e.registerTool(`links`,{description:jSt,inputSchema:{kind:F([ui(ASt),z(ui(ASt)).min(1)]).describe(`Link-graph view(s) to return — one kind, or an array to fetch several in one call (e.g. ["dead","orphans","hubs"] for a graph audit).`),document:R().optional().describe(`Target page (path, extension-less). Required for kind=backlinks|forward|suggest.`),sourceDocuments:z(R()).optional().describe(`Referring source docs to narrow the audit with OR semantics. Used by kind=dead.`),mode:ui(Mc).optional().describe(`Filter which type of graph disconnection to surface. Used by kind=orphans.`),limit:Fn().int().positive().max(100).optional().describe(`Maximum number of hubs to return (default 20, max 100). Used by kind=hubs.`),cwd:R().optional().describe(P3)},outputSchema:H3({backlinks:z3.optional().describe(`kind=backlinks: pages that link TO the target.`),forwardLinks:z3.optional().describe(`kind=forward: links FROM the target (doc + external).`),deadLinks:z3.optional().describe(`kind=dead: internal links whose target does not exist.`),orphans:z3.optional().describe(`kind=orphans: disconnected pages.`),hubs:z3.optional().describe(`kind=hubs: the most-linked pages.`),suggest:L(R(),I()).optional().describe("kind=suggest: `{ mentions: [{ source, excerpt, offset }], previewUrl }` — `excerpt` is a `…`-trimmed context snippet (re-read the doc for the real text before `edit`)."),errors:L(R(),R()).optional().describe("Per-kind failures on a multi-kind call: `{ kind: message }`."),cwd:R().describe(`Absolute directory the read ran against.`)})},async e=>{let n=await q3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return $(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return $(W3(),!0);let a=Array.isArray(e.kind)?[...new Set(e.kind)]:[e.kind],{resolve:o}=await a7(t,r),s=await Promise.all(a.map(n=>NSt(n,e,Z3(i,t.localApi),r,t,o))),c={},l={};if(a.forEach((e,t)=>{let n=s[t];n.ok?Object.assign(c,n.data):l[e]=n.error}),Object.keys(c).length===0){let e=a.length===1?l[a[0]]:`All requested link kinds failed: ${JSON.stringify(l)}`;return $(e.startsWith(`Error`)?e:`Error: ${e}`,!0)}let u={...c,...Object.keys(l).length>0?{errors:l}:{},cwd:r};return U3(JSON.stringify(u,null,2),u)})}function NSt(e,t,n,r,i,a){switch(e){case`backlinks`:return PSt(t,n,a);case`forward`:return FSt(t,n,a);case`dead`:return ISt(t,n,a);case`orphans`:return LSt(t,n,a);case`hubs`:return RSt(t,n,a);case`suggest`:return zSt(t,n,r,i)}}async function PSt(e,t,n){if(!e.document)return{ok:!1,error:"kind=backlinks requires `document`."};let r=Y3(e.document);if(!r.ok)return{ok:!1,error:r.error};let i=await e6(t,`/api/backlinks?docName=${encodeURIComponent(r.docName)}`);if(!i.ok)return{ok:!1,error:String(i.error)};let{ok:a,...o}=i;return{ok:!0,data:{backlinks:(o.backlinks??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function FSt(e,t,n){if(!e.document)return{ok:!1,error:"kind=forward requires `document`."};let r=Y3(e.document);if(!r.ok)return{ok:!1,error:r.error};let i=await e6(t,`/api/forward-links?docName=${encodeURIComponent(r.docName)}`);if(!i.ok)return{ok:!1,error:String(i.error)};let{ok:a,...o}=i;return{ok:!0,data:{forwardLinks:(o.forwardLinks??[]).map(e=>{let t=e.kind===`doc`&&typeof e.docName==`string`?e.docName:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function ISt(e,t,n){let r=new URLSearchParams;for(let t of e.sourceDocuments??[]){let e=Y3(t);if(!e.ok)return{ok:!1,error:e.error};r.append(`sourceDocName`,e.docName)}let i=r.toString(),a=await e6(t,`/api/dead-links${i?`?${i}`:``}`);if(!a.ok)return{ok:!1,error:String(a.error)};let{ok:o,...s}=a;return{ok:!0,data:{deadLinks:(s.deadLinks??[]).map(e=>{let t=typeof e.target==`string`?e.target:null,r=t?n(t):null,i=(e.sources??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}});return{...e,sources:i,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function LSt(e,t,n){let r=await e6(t,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!r.ok)return{ok:!1,error:String(r.error)};let{ok:i,...a}=r;return{ok:!0,data:{orphans:(a.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function RSt(e,t,n){let r=await e6(t,`/api/hubs${e.limit?`?limit=${encodeURIComponent(String(e.limit))}`:``}`);if(!r.ok)return{ok:!1,error:String(r.error)};let{ok:i,...a}=r;return{ok:!0,data:{hubs:(a.hubs??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function zSt(e,t,n,r){if(!e.document)return{ok:!1,error:"kind=suggest requires `document`."};let i=Y3(e.document);if(!i.ok)return{ok:!1,error:i.error};let a=await e6(t,`/api/suggest-links?docName=${encodeURIComponent(i.docName)}`);if(!a.ok)return{ok:!1,error:String(a.error)};let{ok:o,...s}=a,c=await r7(i.docName,{config:r.config,resolveCwd:r.resolveCwd},n);return{ok:!0,data:{suggest:{...s,previewUrl:c?.url??null,...c?{previewUrlSource:c.source}:{}}}}}const BSt=["Lint markdown and optionally auto-fix. Requires the Hocuspocus server. `document` selects one extension-less doc and overrides path. Otherwise scan all in-scope .md/.mdx; path narrows to file/folder. `fix: true` requires document and applies fixable rules through the live collaborative doc with attribution. Use edit/write for remaining findings; shell ok lint --fix is the unattributed headless/CI path.","ran lists selected `markdownlint`, `frontmatter` and document-level `okf` families. A family absent from `ran` was not checked. Project-tree OKF checks and link validation run only through audit.",`Findings carry source, code, message, 0-based LSP range and severity; only problematic files are listed. Counts reflect the full scan. Project output is capped at 10 files × 10 diagnostics each and project-wide at 10 warnings; omittedWarningCount reports dropped warnings. Narrow path reduces competing files; per-file caps still apply. Follow truncation recovery text.`,`Configure lint in Settings → Plugins and native .markdownlint.* rules.`].join(`
2117
+ `);function MSt(e,t){e.registerTool(`links`,{description:jSt,inputSchema:{kind:F([ui(ASt),z(ui(ASt)).min(1)]).describe(`Link-graph view(s) to return — one kind, or an array to fetch several in one call (e.g. ["dead","orphans","hubs"] for a graph audit).`),document:R().optional().describe(`Target page (path, extension-less). Required for kind=backlinks|forward|suggest.`),sourceDocuments:z(R()).optional().describe(`Referring source docs to narrow the audit with OR semantics. Used by kind=dead.`),mode:ui(Mc).optional().describe(`Filter which type of graph disconnection to surface. Used by kind=orphans.`),limit:Fn().int().positive().max(100).optional().describe(`Maximum number of hubs to return (default 20, max 100). Used by kind=hubs.`),cwd:R().optional().describe(P3)},outputSchema:H3({backlinks:z3.optional().describe(`kind=backlinks: pages that link TO the target.`),forwardLinks:z3.optional().describe(`kind=forward: links FROM the target (doc + external).`),deadLinks:z3.optional().describe(`kind=dead: internal links whose target does not exist.`),orphans:z3.optional().describe(`kind=orphans: disconnected pages.`),hubs:z3.optional().describe(`kind=hubs: the most-linked pages.`),suggest:L(R(),I()).optional().describe("kind=suggest: `{ mentions: [{ source, excerpt, offset }], previewUrl }` — `excerpt` is a `…`-trimmed context snippet (re-read the doc for the real text before `edit`)."),errors:L(R(),R()).optional().describe("Per-kind failures on a multi-kind call: `{ kind: message }`."),cwd:R().describe(`Absolute directory the read ran against.`)})},async e=>{let n=await q3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return $(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;if(!i)return $(W3(),!0);let a=Array.isArray(e.kind)?[...new Set(e.kind)]:[e.kind],{resolve:o}=await a7(t,r),s=await Promise.all(a.map(n=>NSt(n,e,Z3(i,t.localApi),r,t,o))),c={},l={};if(a.forEach((e,t)=>{let n=s[t];n.ok?Object.assign(c,n.data):l[e]=n.error}),Object.keys(c).length===0){let e=a.length===1?l[a[0]]:`All requested link kinds failed: ${JSON.stringify(l)}`;return $(e.startsWith(`Error`)?e:`Error: ${e}`,!0)}let u={...c,...Object.keys(l).length>0?{errors:l}:{},cwd:r};return U3(JSON.stringify(u,null,2),u)})}function NSt(e,t,n,r,i,a){switch(e){case`backlinks`:return PSt(t,n,a);case`forward`:return FSt(t,n,a);case`dead`:return ISt(t,n,a);case`orphans`:return LSt(t,n,a);case`hubs`:return RSt(t,n,a);case`suggest`:return zSt(t,n,r,i)}}async function PSt(e,t,n){if(!e.document)return{ok:!1,error:"kind=backlinks requires `document`."};let r=Y3(e.document);if(!r.ok)return{ok:!1,error:r.error};let i=await e6(t,`/api/backlinks?docName=${encodeURIComponent(r.docName)}`);if(!i.ok)return{ok:!1,error:String(i.error)};let{ok:a,...o}=i;return{ok:!0,data:{backlinks:(o.backlinks??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function FSt(e,t,n){if(!e.document)return{ok:!1,error:"kind=forward requires `document`."};let r=Y3(e.document);if(!r.ok)return{ok:!1,error:r.error};let i=await e6(t,`/api/forward-links?docName=${encodeURIComponent(r.docName)}`);if(!i.ok)return{ok:!1,error:String(i.error)};let{ok:a,...o}=i;return{ok:!0,data:{forwardLinks:(o.forwardLinks??[]).map(e=>{let t=e.kind===`doc`&&typeof e.docName==`string`?e.docName:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function ISt(e,t,n){let r=new URLSearchParams;for(let t of e.sourceDocuments??[]){let e=Y3(t);if(!e.ok)return{ok:!1,error:e.error};r.append(`sourceDocName`,e.docName)}let i=r.toString(),a=await e6(t,`/api/dead-links${i?`?${i}`:``}`);if(!a.ok)return{ok:!1,error:String(a.error)};let{ok:o,...s}=a;return{ok:!0,data:{deadLinks:(s.deadLinks??[]).map(e=>{let t=typeof e.target==`string`?e.target:null,r=t?n(t):null,i=(e.sources??[]).map(e=>{let t=typeof e.source==`string`?e.source:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}});return{...e,sources:i,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function LSt(e,t,n){let r=await e6(t,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!r.ok)return{ok:!1,error:String(r.error)};let{ok:i,...a}=r;return{ok:!0,data:{orphans:(a.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function RSt(e,t,n){let r=await e6(t,`/api/hubs${e.limit?`?limit=${encodeURIComponent(String(e.limit))}`:``}`);if(!r.ok)return{ok:!1,error:String(r.error)};let{ok:i,...a}=r;return{ok:!0,data:{hubs:(a.hubs??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,r=t?n(t):null;return{...e,previewUrl:r?.url??null,...r?{previewUrlSource:r.source}:{}}})}}}async function zSt(e,t,n,r){if(!e.document)return{ok:!1,error:"kind=suggest requires `document`."};let i=Y3(e.document);if(!i.ok)return{ok:!1,error:i.error};let a=await e6(t,`/api/suggest-links?docName=${encodeURIComponent(i.docName)}`);if(!a.ok)return{ok:!1,error:String(a.error)};let{ok:o,...s}=a,c=await r7(i.docName,{config:r.config,resolveCwd:r.resolveCwd},n);return{ok:!0,data:{suggest:{...s,previewUrl:c?.url??null,...c?{previewUrlSource:c.source}:{}}}}}const BSt=["Lint markdown and optionally auto-fix. Requires the Hocuspocus server. `document` selects one extension-less doc and overrides path. Otherwise scan all in-scope .md/.mdx; path narrows to file/folder. `fix: true` requires document and applies fixable rules through the live collaborative doc with attribution. Use edit/write for remaining findings; the OpenKnowledge CLI's lint --fix is the unattributed headless/CI path.","ran lists selected `markdownlint`, `frontmatter` and document-level `okf` families. A family absent from `ran` was not checked. Project-tree OKF checks and link validation run only through audit.",`Findings carry source, code, message, 0-based LSP range and severity; only problematic files are listed. Counts reflect the full scan. Project output is capped at 10 files × 10 diagnostics each and project-wide at 10 warnings; omittedWarningCount reports dropped warnings. Narrow path reduces competing files; per-file caps still apply. Follow truncation recovery text.`,`Configure lint in Settings → Plugins and native .markdownlint.* rules.`].join(`
2118
2118
  `);function VSt(e,t){if(e===0)return"None are auto-fixable — these need content edits via `edit`/`write`.";let n=t-e;return`${e} of ${t} are auto-fixable — pass \`fix: true\` to apply in place (attributed, live preview).${n>0?` The other ${n} need content edits via \`edit\`/\`write\`.`:``}`}function HSt(e,t){e.registerTool(`lint`,{description:BSt,inputSchema:{document:R().optional().describe(`Doc to lint (path, extension-less). Omit to audit the whole project.`),path:R().optional().describe("Audit scope when `document` is omitted: a folder or single file (content-dir-relative). Default: the whole project."),fix:Wa().optional().describe("Auto-fix fixable rules in `document` IN PLACE (attributed, live preview), then report what remains. Requires `document`."),cwd:R().optional().describe(P3)},outputSchema:H3({files:z3.optional().describe("Per-file diagnostics. For a single-doc lint, the one file (even if clean). Pre-fix, and so possibly an overstatement, when `diagnosticsArePreFix` is true."),fileCount:Fn().optional().describe(`Audit only: total in-scope documents scanned.`),errorCount:Fn().describe("Total error-severity violations. Pre-fix, and so possibly an overstatement, when `diagnosticsArePreFix` is true."),warningCount:Fn().describe("Total warning-severity violations. Pre-fix, and so possibly an overstatement, when `diagnosticsArePreFix` is true."),warnings:z(R()).optional().describe("Anything that made this run less than a full answer: unreadable files/dirs (audit), lint-config problems such as a broken frontmatter schema file, and selected lint plugins that threw. A source family named here is still listed in `ran`: it was selected, it just could not finish. In fix mode this array carries the plugin failures from BOTH lint passes, so a post-write re-lint failure can appear here as the failing plugin, but never as the `Re-lint after fix failed: ` entry an older server sends, which is filtered out. The prose explanation is in `reLintFailure.message`, its machine-readable discriminant in `reLintFailure.reason`, and `diagnosticsArePreFix` is the flag to branch on."),diagnosticsArePreFix:Wa().optional().describe("Fix mode only. Present and true when the server flags pre-fix diagnostics, supplies `reLintFailure`, or reports a legacy re-lint-failure warning; absent when none of those signals is present. The reported `files[].diagnostics` and their `errorCount`/`warningCount` describe the pre-fix set and may overstate what remains. Treat the fix as applied and re-run `lint` to confirm. A non-empty explanation, when available, is in `reLintFailure.message`, and `reLintFailure.reason` says which of the two failure shapes it was."),reLintFailure:tie.optional().describe("Fix mode only: why the post-write re-lint could not report. `reason` is the machine-readable discriminant — `re-lint-threw` when the re-lint pass itself threw, `source-went-blind` when a lint source that read the pre-fix text failed on the post-fix text — and `message` is the trimmed, non-empty prose, normalized from the server’s typed failure or a legacy prefixed warning. When present, `diagnosticsArePreFix` is true; that flag can also be present without a failure."),ran:z(R()).optional().describe("Lint source families selected for this run. A family absent from `ran` was not checked."),omittedWarningCount:Fn().optional().describe("Audit only: warnings omitted from `warnings` by the output cap."),omittedFileCount:Fn().optional().describe("Audit only: files with problems omitted from `files` by the output cap."),fixedCount:Fn().optional().describe("Fix mode only: the server-reported number of problems resolved by auto-fix, or 0 if omitted. When `diagnosticsArePreFix` is true, the post-fix result is unavailable; do not treat 0 as evidence that nothing was fixed."),cwd:R().describe(`Absolute directory the lint ran against.`)}),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0}},async e=>{let n=await q3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return $(`Error: ${n.error}`,!0);let{cwd:r,url:i}=n;return i?e.fix===!0?e.document===void 0?$("Error: `fix: true` requires `document` (fix one doc at a time). Omit `fix` to audit the whole project.",!0):USt(e.document,i,r,t.identityRef?.current):e.document===void 0?GSt(e.path,i,r):WSt(e.document,i,r):$(W3(),!0)})}async function USt(e,t,n,r){let i=Y3(e);if(!i.ok)return $(i.error,!0);let a=await r6(t,`/api/lint/fix`,{docName:i.docName,...N3(r)});if(!a.ok)return $(V3(a),!0);let{ok:o,...s}=a,c=s,l=c.file??i.docName,u=c.diagnostics??[],d=c.fixedCount??0,f=u.filter(e=>e.severity===`error`).length,p=u.length-f,m=typeof s.warning==`string`&&De(s.warning)?s.warning:void 0,h=[...c.warnings??[],...m===void 0?[]:[m]],g=h.find(De),_=h.filter(e=>!De(e)),v=c.diagnosticsArePreFix===!0||c.reLintFailure!==void 0||g!==void 0,y=typeof c.reLintFailure?.message==`string`?c.reLintFailure.message.trim():``,b=y?{reason:zn(c.reLintFailure?.reason)?c.reLintFailure.reason:`re-lint-threw`,message:y}:void 0,x=g?.slice(Fne.length).trim(),S=b??(x?{reason:`re-lint-threw`,message:x}:void 0),C=S?` (${S.message})`:``,w=Za(c.ran),T={files:[{file:l,diagnostics:u}],fixedCount:d,errorCount:f,warningCount:p,..._.length>0?{warnings:_}:{},...v?{diagnosticsArePreFix:!0}:{},...S?{reLintFailure:S}:{},...c.ran===void 0?{}:{ran:c.ran},cwd:n},E=v?`Applied auto-fixes to ${l}, but re-lint failed${C}; the fix landed — problems below are the pre-fix set, re-run \`lint\` to confirm.`:d>0?`Fixed ${d} problem${d===1?``:`s`} in ${l}.`:_.length>0?`No auto-fixable problems in ${l}, but the lint could not fully complete.`:`No auto-fixable problems in ${l}.`,D=u.map(d6),O=u6(`Lint`,_),ee=u.length>0&&!v?[`${u.length} problem${u.length===1?``:`s`} remain (${f6(f,p)}) — need content edits via \`edit\`/\`write\`.`]:[];return U3((u.length===0?[E,...w,...O]:[E,...D,...O,...ee,...w]).join(`
2119
2119
  `),T)}async function WSt(e,t,n){let r=Y3(e);if(!r.ok)return $(r.error,!0);let i=await e6(t,`/api/lint?doc=${encodeURIComponent(r.docName)}`);if(!i.ok)return $(`Error: ${String(i.error)}`,!0);let{ok:a,...o}=i,s=o,c=s.diagnostics??[],l=s.warnings??[],u=c.filter(e=>e.severity===`error`).length,d=c.length-u,f=Za(s.ran),p={file:s.file??r.docName,diagnostics:c},m={files:[p],errorCount:u,warningCount:d,...l.length>0?{warnings:l}:{},...s.ran===void 0?{}:{ran:s.ran},cwd:n},h=c.length>0?`${p.file}: ${f6(u,d)}`:l.length>0?`No problems found in ${p.file}, but the lint could not fully complete.`:`No problems in ${p.file}.`,g=c.map(d6),_=u6(`Lint`,l),v=c.filter(e=>(e.fixes?.length??0)>0).length,y=c.length>0?[VSt(v,c.length)]:[];return U3((c.length===0?[h,...f,..._]:[h,...g,..._,...y,...f]).join(`
2120
2120
  `),m)}async function GSt(e,t,n){let r=await e6(t,`/api/lint/audit${e?`?path=${encodeURIComponent(e)}`:``}`);if(!r.ok)return $(`Error: ${String(r.error)}`,!0);let{ok:i,...a}=r,o=a,s=o.files??[],c=o.fileCount??0,l=o.errorCount??0,u=o.warningCount??0,d=Za(o.ran,c),f=s.slice(0,10).map(e=>{let t=e.diagnostics??[],n=t.slice(0,10),r=t.length-n.length;return{...e,diagnostics:n,...r>0?{omittedDiagnosticCount:r}:{}}}),p=s.length-f.length,m=o.warnings??[],{shownWarnings:h,omittedWarningCount:g}=Wct(m),_={files:f,fileCount:c,errorCount:l,warningCount:u,...h.length>0?{warnings:h}:{},...g>0?{omittedWarningCount:g}:{},...o.ran===void 0?{}:{ran:o.ran},...p>0?{omittedFileCount:p}:{},cwd:n},v=e?` in ${e}`:``,y=u6(`Lint`,h,g);if(s.length===0)return U3([Gct(`Lint`,c,m,v),...d,...y].join(`
@@ -2157,7 +2157,7 @@ $$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-p
2157
2157
  `),{asset:{ok:!0,src:x,...S?{path:S}:{},...C?{deduped:C}:{}}})}async function $Ct(e,t,n,r,i){let a=r.identityRef?.current,o=e.description!==void 0,s=e.files??[];if(!o&&s.length===0)return $("Error: provide `description` (to author SKILL.md) and/or `files` (to write references/scripts) — a skill write with neither does nothing.",!0);if(e.body!==void 0&&!o)return $('Error: `body` updates SKILL.md, so it needs a `description` too. To write a reference, use `files: [{ path: "references/...", content }]` instead.',!0);let c=[];for(let e of s){let t=f7(e.path);if(!t.ok)return $(`Error: ${t.error}`,!0);c.push({...e,path:t.path})}let l=[],u=null;if(o&&(u=await pbt(n,{name:e.name,scope:e.scope,description:e.description,body:e.body,summary:t,identity:a,lockDir:i}),u.isError))return u;for(let r of c){let i=await hbt(n,{name:e.name,scope:e.scope,path:r.path,content:r.content,summary:t,identity:a}),o=i.structuredContent;if(i.isError)l.push({path:r.path,ok:!1,error:i.content[0]?.text??`write failed`});else{let e=o?.skill?.file??{};l.push({path:r.path,ok:!0,...typeof e.kind==`string`?{kind:e.kind}:{},...typeof e.created==`boolean`?{created:e.created}:{}})}}let d=l.filter(e=>e.ok).length,f=l.some(e=>!e.ok),p=u?.structuredContent??{},m=p.skill??{ok:!0},{text:h,...g}=p,_={...g,skill:{...m,...s.length>0?{files:l}:{}}},v=[];if(o&&u&&v.push(u.content[0]?.text??``),s.length>0){v.push(`${d}/${s.length} bundle file(s) written.`);for(let e of l)v.push(e.ok?` ${e.path} (${e.kind??`file`})`:` Failed ${e.path}: ${e.error}`)}return U3(v.filter(Boolean).join(`
2158
2158
  `),_,f)}async function ewt(e,t,n,r,i,a,o){let s=[];for(let a of e)s.push(await JCt(a,t,n,r,i));let c=s.map(e=>{if(!e.ok)return{docName:e.docName,ok:!1,error:e.error};let t=o7(e.docName,{lockDir:a}),n=Y5(e.raw.warnings),r=X5(e.raw.brokenLinks),i=Z5(e.raw.brokenLinkSuppression);return{docName:e.docName,ok:!0,position:e.position,...t?{previewUrl:t.url}:{},...n?{warnings:n}:{},...e.templateHint?{templateHint:e.templateHint}:{},brokenLinks:r,...i?{brokenLinkSuppression:i}:{}}}),l=c.filter(e=>e.ok).length,u=l===c.length,d=e.map((e,t)=>{let n=s[t];if(!n?.ok)return`Failed ${e.path}: ${n?.error??`unknown error`}`;if(HCt(n.position,e.content))return`No change to ${e.path} — empty ${n.position}, document unchanged.`;let r=c[t],i=[n.createdByPosition?VCt(n.docName,n.createdByPosition):`Wrote ${e.path} (${n.position}).`];if(r?.ok&&r.warnings&&i.push(...Fyt(r.warnings)),r?.ok){let e=Cyt(r.brokenLinks);e&&i.push(e),r.brokenLinkSuppression&&i.push(Qrt(r.brokenLinkSuppression))}return n.ok&&n.templateHint&&i.push(`ℹ ${n.templateHint.length} template${n.templateHint.length===1?``:`s`} available here (pass \`template\`).`),i.join(` `)}),f=e.flatMap((e,t)=>{let n=s[t];if(!n?.ok)return[];let r=BCt(n.position,e.content);return[...r?[r]:[],...n.extensionNote?[n.extensionNote]:[]].map(t=>`${e.path} — ${t}`)}),p=[`${l}/${c.length} written.`,...d,...f].join(`
2159
2159
  `),m={documents:c},h=s.find(e=>e.ok);return h&&h.raw.systemSubscriberCount===0&&(m.warning=n7(o7(h.docName,{lockDir:a}),o)),U3(p,m,!u)}async function twt(e,t,n,r,i,a,o){let s=await JCt(e,t,n,r,i);if(!s.ok)return $(`Error: ${s.error}`,!0);let c=s.raw,l=o7(s.docName,{lockDir:a}),u=(typeof c.systemSubscriberCount==`number`?c.systemSubscriberCount:void 0)===0,d=Array.isArray(c.hints)?c.hints:void 0,f=c.summary&&typeof c.summary==`object`?c.summary:void 0,p=typeof f?.hint==`string`?f.hint:void 0,m=Y5(c.warnings),h=X5(c.brokenLinks),g=Z5(c.brokenLinkSuppression),_=HCt(s.position,e.content),v=[s.createdByPosition?VCt(s.docName,s.createdByPosition):_??(s.fromTemplate===void 0?`Written successfully (${s.position}).`:`Written successfully (instantiated from template "${s.fromTemplate}").`)],y=BCt(s.position,e.content);if(y&&v.push(y),s.extensionNote&&v.push(s.extensionNote),u&&!l&&v.push(t7()),p&&v.push(p),d)for(let e of d)e.message&&v.push(e.message);m&&v.push(...Q5(m)),v.push(...Syt(h)),g&&v.push(Zrt(g)),s.templateHint&&v.push(YCt(s.templateHint));let b=v.join(`
2160
- `),x={brokenLinks:h};return g&&(x.brokenLinkSuppression=g),d&&(x.hints=d),f&&(x.summary=f),m&&(x.warnings=m),s.templateHint&&(x.templateHint=s.templateHint),U3(b,Pct(l,u?n7(l,o):void 0,x))}function nwt(e,t){let n={path:R().describe('Document path. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup". An optional `.md`/`.mdx` suffix selects the file format (default `.md`); prefer the `extension` field for that. The docName itself is always extension-less.'),content:R().optional().describe("The full Markdown body. C0 controls allow only TAB, LF and CR; remove others or use printable escapes. Mutually exclusive with `template`."),extension:sbt.optional(),template:R().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:s7.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:obt.optional()};e.registerTool(`write`,{description:zCt,inputSchema:{document:B(n).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:B({path:R().describe(`Folder path. Example: "meetings".`),frontmatter:s7.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:B({path:R().describe(lbt),content:R().describe("Starter content — the Markdown a new document becomes. A leading `---…---` frontmatter block here sets the STARTING PROPERTIES every doc created from this template gets (e.g. `type`, `status`, `tags`); the markdown below it is the body. The template's own picker identity (title/description) is the separate `frontmatter` field, NOT this block — it is stripped at instantiation and never copied onto created docs. (On disk this composes to one frontmatter block with the identity under a reserved `template:` key; you don't author that — just give the starter content here.) Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time. C0 controls allow only TAB, LF and CR; remove others or use printable escapes."),frontmatter:B({title:R().min(1).describe(`Required — the label shown when an agent picks this template.`),description:R().optional().describe(`Optional — shown beside the title in the template menu.`),tags:z(R()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),skill:B({name:R().describe(l7),description:R().optional().describe(`${ubt} Optional when writing ONLY \`files\` into an existing skill (omit to leave SKILL.md untouched).`),body:R().optional().describe("SKILL.md body (markdown guidance). Authored WITHOUT frontmatter — `name` + `description` are passed separately and composed server-side. Keep under ~500 lines; move depth into one-level-deep `references/`. C0 controls allow only TAB, LF and CR; remove others or use printable escapes."),files:z(B({path:R().describe(`Skill-relative path, e.g. "references/tiers.md" or "assets/logo.svg". Must stay inside the skill dir.`),content:R().describe(`Full text of the bundle file, including any frontmatter. For .md/.mdx paths, C0 controls allow only TAB, LF and CR; remove others or use printable escapes.`)})).optional().describe('Bundle files to write beside `SKILL.md`, as an ARRAY of `{ path, content }` (consistent with `documents`/`asset`). `path` is SKILL-RELATIVE and must stay inside the skill dir (e.g. "references/tiers.md", "scripts/run.sh", "assets/logo.svg") — no `../`, no absolute paths. `content` is the full text. Text only (no binary). Independent of `body`: write one reference without resending SKILL.md.'),scope:u7.optional()}).optional().describe('Create or overwrite an agent SKILL bundle (a NEW skill lands at the project\'s default skill home, e.g. `.agents/skills/<name>/`). SKILL.md is authored via `description`+`body`; bundle files via the `files` array — any skill-relative path that stays inside the skill dir (`references/**` and `scripts/**` are the conventional homes; `assets/` and per-harness dirs are accepted because published skills ship them). Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }'),asset:B({path:R().describe('Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png". A bare file name (no folder) goes to the attachment folder (`content.attachmentFolderPath`; by default the content root).'),content:R().optional().describe(`Base64 of the binary. Use for small files.`),source:R().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:z(B({...n,summary:F3})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:F3,cwd:R().optional().describe(P3)},outputSchema:H3({document:B({hints:z3.optional().describe(`Server-provided write hints, when any.`),...Nct}).optional().describe("Single-document write result. Always present on a successful single-doc write — it carries `brokenLinks` (possibly `[]`) plus any `brokenLinkSuppression`/`summary`/`hints`/`warnings`. Read `brokenLinkSuppression` and `warnings` before concluding anything from an empty `brokenLinks`: a suppression means a project policy withheld findings that are not yours to repair; a `link-check-deferred` warning means links were not checked yet."),folder:B({ok:Wa(),path:R(),frontmatterError:R().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:B({ok:Wa(),path:R(),created:Wa().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),skill:B({ok:Wa(),path:R().optional(),created:Wa().optional().describe(`true if created, false if an existing skill was overwritten.`),files:z3.optional().describe("Per-bundle-file results `{ path, kind, created, ok, error? }`."),warnings:z(R()).optional().describe(`Non-fatal authoring warnings for the SKILL.md that was written. ${c6}`),warningCodes:z(ui(fi)).optional().describe(`${s6} ${l6}`)}).optional().describe(`Skill-create result (SKILL.md and/or bundle files).`),asset:B({ok:Wa(),src:R().describe(`The reference src to embed in a doc.`),path:R().optional().describe("Content-root-relative path the server reports holding the asset (the existing file when `deduped`). Absent when the server reports none."),deduped:Wa().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:z3.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, brokenLinks, brokenLinkSuppression?, error? }`. `brokenLinks` (possibly `[]`) is present on each successful entry, same as a single-doc write — and, same as a single-doc write, an empty list means every link resolves only on entries carrying no `brokenLinkSuppression` and no `link-check-deferred` warning (links not checked yet because the server is still starting or busy)."),previewUrl:I3.optional(),previewUrlSource:L3,warning:kct})},async e=>{let n=await q3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return $(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n,o=Hq(r),s=Bq(i,r),c=i.appearance.preview.autoOpen;if(e.documents!==void 0){let n=p7(e,[`document`,`folder`,`template`,`skill`,`asset`,`documents`]);return n?$(`Error: ${n}`,!0):a?ewt(e.documents,r,s,a,t,o,c):$(W3(),!0)}let l=p7(e,[`document`,`folder`,`template`,`skill`,`asset`]);return l?$(`Error: ${l}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?e.skill===void 0?QCt(e.asset,r,a,t):$Ct(e.skill,e.summary,a,t,o):ZCt(e.template,e.summary,a,t):XCt(e.folder,e.summary,a,t):a?twt({...e.document,summary:e.summary},r,s,a,t,o,c):$(W3(),!0)})}function rwt(e,t){let n=t.logger,r=xyt(e,{logger:t.logger,identityRef:t.identityRef}),i=e=>async r=>{try{let i=await t.resolveCwd(r);return(G5()??n)?.debug(`tool cwd resolved`,{tool:e,cwd:i,...r?{explicit:r}:{}}),i}catch(t){throw(G5()??n)?.warn(`tool call failed`,{tool:e,err:t,...r?{explicit:r}:{}}),t}};lSt(r,{resolveCwd:i(`exec`),serverUrl:t.serverUrl,config:t.config}),vCt(r,{resolveCwd:i(`search`),config:t.config,serverUrl:t.serverUrl,localApi:t.localApi}),MSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`links`),localApi:t.localApi}),HSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`lint`),identityRef:t.identityRef}),Hyt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`audit`)}),nwt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`write`),identityRef:t.identityRef,localApi:t.localApi}),Vbt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`edit`),identityRef:t.identityRef}),Obt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`delete`),identityRef:t.identityRef,localApi:t.localApi}),$St(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`move`),identityRef:t.identityRef}),kSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`install`),identityRef:t.identityRef,localApi:t.localApi}),TSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`import`),identityRef:t.identityRef,localApi:t.localApi}),SSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`history`)}),RCt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`skills`)}),Gyt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`checkpoint`),identityRef:t.identityRef,localApi:t.localApi}),sCt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`restore_version`),identityRef:t.identityRef}),aCt(r,{resolveCwd:i(`palette`),config:t.config}),Xyt(r,{config:t.config,resolveCwd:i(`config`)}),ySt(r,{config:t.config,resolveCwd:i(`preview_url`),serverUrl:t.serverUrl,isHostedAgent:t.isHostedAgent,...t.serverUrl?{ensureSingleFileSession:eyt()}:{}}),ECt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`share_link`)})}function N7(e){return Array.isArray(e)?e[0]:e}function P7(e,t,n){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(n))}function iwt(e,t,n,r){let i=e.config,a=new BI({name:Ta,version:qZ});vvt(a);let o=n??oc(),s={current:{connectionId:o,displayName:o,colorSeed:o}};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=$4e(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:Ae(t),colorSeed:t}};let c=e.projectDir??e.contentDir;return rwt(a,{serverUrl:async()=>e.getServerUrl(),localApi:e.localApi,resolveCwd:async e=>{if(e===void 0)return c;let t=M3(c,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:i,identityRef:s,isHostedAgent:r}),_vt(a),{server:a,transport:t}}function awt(e){let t=new Map,n=e.sessionTtlMs??18e5,r=e.maxSessions??100;async function i(n,r){let i=t.get(n);if(!i)return;t.delete(n),i.ttlTimer!==void 0&&clearTimeout(i.ttlTimer);let a=await Promise.allSettled([i.server.close(),i.transport.close()]);for(let t of a)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:n,reason:r},`MCP HTTP session close failed`);e.log?.info?.({sessionId:n,reason:r},`MCP HTTP session closed`)}function a(t,r){r.ttlTimer!==void 0&&clearTimeout(r.ttlTimer),r.ttlTimer=setTimeout(()=>{i(t,`ttl-expired`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},n),r.ttlTimer.unref?.()}return{async handle(n,o){let s=N7(n.headers[`mcp-session-id`]);if(s){let e=t.get(s);if(!e){P7(o,404,`MCP session not found`);return}a(s,e),await e.transport.handleRequest(n,o);return}if(n.method!==`POST`){P7(o,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=r){e.log?.warn?.({activeSessions:t.size,maxSessions:r},`MCP HTTP session cap reached`),P7(o,503,`Too many active MCP sessions`);return}let c=N7(n.headers[Z4e]),l=YV(c)??void 0;c!==void 0&&l===void 0&&e.log?.warn?.({headerLength:c.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let u=N7(n.headers[Q4e])===`1`,d=new $Ue({sessionIdGenerator:()=>oc(),enableJsonResponse:!0,onsessioninitialized:async n=>{try{let r=iwt(e,d,l,u);await r.server.connect(d),t.set(n,r),a(n,r),e.log?.info?.({sessionId:n},`MCP HTTP session initialized`)}catch(r){throw t.delete(n),e.log?.error?.({err:r,sessionId:n},`MCP HTTP session initialization failed`),r}}});d.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},d.onclose=()=>{let t=d.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}i(t,`transport-closed`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await d.handleRequest(n,o)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>i(e,`handler-close`)))}}}const F7=1048576;function owt(e){if(!e)return null;try{return YV(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}function I7(e){return e===null||e.length===0||e.length>256||/[\u0000-\u001f\u007f]/.test(e)?null:e}function swt(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),n=I7(t.searchParams.get(`displayName`)),r=I7(t.searchParams.get(`clientName`)),i=I7(t.searchParams.get(`colorSeed`));return n===null||r===null||i===null?null:{displayName:n,clientName:r,colorSeed:i}}catch{return null}}function cwt(e){let{hocuspocus:t,log:n,sessionManager:r,agentFocusBroadcaster:i,agentPresenceBroadcaster:a,maintenanceCoordinator:o,acpThreadManager:s}=e,c=e.ingressPolicy??w$({}),l=e.keepaliveGraceMs??1e4,u=new fae.default({noServer:!0,maxPayload:F7}),d=new Map,f=new Set,p=new Set,m=!1,h;u.on(`error`,e=>n.error({err:e},`WebSocketServer error`));let g=e=>T$(e.socket.remoteAddress,c)&&E$(Array.isArray(e.headers.host)?e.headers.host[0]:e.headers.host,c),_=(e,t)=>{e.on(`error`,e=>{VU(e)||n.error({err:e},`${t} socket error`)}),p.add(e),e.once(`close`,()=>p.delete(e))},v=(e,t,r,i,a)=>{try{u.handleUpgrade(e,t,r,a)}catch(r){n.error({err:r,url:e.url},`[collab] ${i} handleUpgrade threw`);try{t.destroy()}catch{}}},y=(e,t,s)=>{if(!g(e)||e.headers.origin!==void 0&&!D$(e.headers.origin,c)){n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/keepalive upgrade refused`),t.destroy();return}_(t,`MCP keepalive`),v(e,t,s,`keepalive`,t=>{let s=owt(e.url);if(s){let e=d.get(s);e!==void 0&&(clearTimeout(e),d.delete(s),n.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&a){let t=swt(e.url);if(t)try{let e=Hn(t.clientName);a.setPresence(XV(s),{displayName:t.displayName,icon:e,color:Ha[e]??Ve(t.colorSeed),currentDoc:`(connected)`,mode:`idle`,ts:Date.now(),docTs:Date.now()})}catch(e){n.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let c=setInterval(()=>{try{t.ping()}catch{}},3e4);c.unref?.();let u=s?setInterval(()=>a?.bumpPresenceTs(XV(s)),3e3):null;u?.unref?.(),t.on(`close`,()=>{if(clearInterval(c),u!==null&&clearInterval(u),!s||m)return;let e=setTimeout(()=>{if(d.delete(s),m)return;let e=(async()=>{n.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await r?.closeAllForAgent(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{i?.clearFocus(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{a?.clearPresence(XV(s))}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await o?.onSessionClose()}catch(e){n.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();f.add(e),e.finally(()=>f.delete(e))},l);e.unref?.(),d.set(s,e),n.info({connectionId:s,graceMs:l},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{VU(e)||n.error({err:e},`MCP keepalive WS error`),t.terminate()})})};return{wss:u,handleUpgrade:(e,r,i)=>{if(!e.url?.startsWith(`/collab`))return!1;if(n.info({url:e.url,protocol:e.headers[`sec-websocket-protocol`]??`none`,host:e.headers.host??`none`,origin:e.headers.origin??`none`},`[collab] upgrade received`),k7e(e,{}),O$(e,c))return n.warn({url:e.url,host:e.headers.host},`[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL (or server.allowExternal + server.externalUrl in config)`),k$(n,`collab-upgrade`),r.destroy(),!0;if(e.url.startsWith(`/collab/thread`))return s==null||!g(e)||e.headers.origin!==void 0&&!D$(e.headers.origin,c)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/thread upgrade refused`),r.destroy(),!0):(_(r,`ACP thread`),v(e,r,i,`thread`,e=>G5e(e,s,n)),!0);if(e.url.startsWith(`/collab/keepalive`))return y(e,r,i),!0;let a=e.headers.origin!==void 0&&!D$(e.headers.origin,c),o=c.allowExternal;return a||o&&!g(e)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab upgrade refused`),r.destroy(),!0):(_(r,`Upgrade`),n.info({url:e.url},`[collab] handleUpgrade starting`),v(e,r,i,`collaboration`,r=>{let i=t.getConnectionsCount?.()??-1,a=t.handleConnection(r,e);n.info({url:e.url,connectionsBefore:i},`[collab] handshake complete`);let o=!1;r.on(`message`,e=>{if(!o){if(e.byteLength>F7){o=!0,BU(),n.warn({event:`collab-message-too-large`,bytes:e.byteLength,limit:F7},`Collab WebSocket message rejected before Yjs processing`),r.close(1009,`Message Too Big`);return}a.handleMessage(new Uint8Array(e))}}),r.on(`close`,(e,t)=>a.handleClose({code:e,reason:t.toString()})),r.on(`error`,e=>{e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`?(BU(),n.warn({event:`collab-message-too-large`,limit:F7},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`)):VU(e)||n.error({err:e},`WebSocket error`),r.terminate()})}),!0)},shutdown:()=>(h??=(async()=>{m=!0;for(let e of p)try{e.destroy()}catch{}p.clear();for(let e of d.values())clearTimeout(e);d.clear(),await Promise.allSettled(f)})(),h)}}function lwt({contentAssetMiddleware:e,reactShellMiddleware:t,ephemeral:n,ingressPolicy:r,log:i}){return(a,o)=>{let s=a.url?.split(`?`)[0];if(!R6(a,o,r,`mcp-mount`,i))return;let c=(e,t,n)=>{if(e===void 0){n();return}try{e(a,o,()=>{o.writableEnded||o.headersSent||n()})}catch(e){i.error({err:e},`Unhandled ${t} middleware error`),!o.writableEnded&&!o.headersSent?X(o,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):o.writableEnded||o.end()}},l=t=>{if(n===!0&&e!==void 0){if(!T$(a.socket.remoteAddress,r)){X(o,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!E$(a.headers.host,r)){X(o,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:C$});return}}c(e,`content-asset`,t)},u=e=>c(t,`react-shell`,e),d=()=>{o.writableEnded||o.headersSent||X(o,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`${t===void 0?"This server is running without the web UI. Restart it with plain `ok start` to serve the editor. ":``}No handler for ${s??`/`}`})};if(t!==void 0&&(s?.startsWith(`/assets/`)||s?.startsWith(`/excalidraw-assets/`))){u(()=>l(d));return}if(e!==void 0||t!==void 0){l(()=>u(d));return}X(o,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`This server is running without the web UI. Restart it with plain \`ok start\` to serve the editor. No handler for ${s??`/`}`})}}const uwt={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function dwt(e,t,n){return(r,i)=>{let a=r.headers.origin,o=Array.isArray(r.headers[`mcp-session-id`])?r.headers[`mcp-session-id`][0]:r.headers[`mcp-session-id`];if(!T$(r.socket.remoteAddress,t)){X(i,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`mcp`});return}if(!E$(r.headers.host,t)){X(i,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`,detail:C$});return}let s=E7e(a,r.method,t);if(!s.admitted){X(i,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`,detail:s.detail});return}if(a!==void 0&&i.setHeader(`Vary`,`Origin`),s.corsGrant){a!==void 0&&i.setHeader(`Access-Control-Allow-Origin`,a);for(let[e,t]of Object.entries(uwt))i.setHeader(e,t)}if(r.method===`OPTIONS`){i.writeHead(204),i.end();return}e.handle(r,i).catch(e=>{n.error({err:e,sessionId:o},`Unhandled MCP HTTP error`),!i.writableEnded&&!i.headersSent?X(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):i.writableEnded||i.end()})}}function fwt(e){let{httpServer:t,hocuspocus:n,mcpHttpHandler:r,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,contentAssetMiddleware:l,reactShellMiddleware:u,ephemeral:d}=e,f=e.ingressPolicy??w$({}),p=cwt({hocuspocus:n,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,keepaliveGraceMs:e.keepaliveGraceMs,acpThreadManager:e.acpThreadManager,ingressPolicy:f}),m=(e,t)=>{let r=e.url?.split(`?`)[0];R6(e,t,f,`mcp-mount`,i)&&n.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||X(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${r}`})}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()})},h=(e,t,n)=>{p.handleUpgrade(e,t,n)||(O$(e,f)&&(i.warn({url:e.url,host:e.headers.host},`[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL (or server.allowExternal + server.externalUrl in config)`),k$(i,`ws-upgrade`)),t.destroy())},{requestListener:g}=Kut({health:e.health,nativeApi:e.nativeApi,mcpDispatch:r===void 0?void 0:dwt(r,f,i),ingressPolicy:f,legacyDispatch:m,contentDispatch:lwt({contentAssetMiddleware:l,reactShellMiddleware:u,ephemeral:d,ingressPolicy:f,log:i}),log:i});t.on(`request`,g),t.on(`upgrade`,h);let _;return{wss:p.wss,shutdown:()=>(_??=(async()=>{t.off(`upgrade`,h),await p.shutdown()})(),_)}}function pwt(){return`OpenKnowledge config not found at .ok/config.yml. Run ${de()} init to scaffold OK in this directory.`}var mwt=class extends Error{kind;projectDir;constructor(e,t,n){super(pwt(),n),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};function hwt(e,t){return{crdt:{hocuspocus:e.hocuspocus,durabilityState:e.durabilityState,cc1Broadcaster:e.cc1Broadcaster,serverInstanceId:e.serverInstanceId},content:{contentDir:t.contentDir,projectDir:t.projectDir,contentFilter:e.contentFilter},indexes:{basenameIndex:e.basenameIndex,resolveEmbed:e.resolveEmbed},git:{get syncEngine(){return e.syncEngine}},agents:{sessionManager:e.sessionManager,agentFocusBroadcaster:e.agentFocusBroadcaster,agentPresenceBroadcaster:e.agentPresenceBroadcaster,acpRegistry:e.acpRegistry,acpPermissions:e.acpPermissions},background:{maintenanceCoordinator:e.maintenanceCoordinator},config:{getLinkPreviewsEnabled:e.getLinkPreviewsEnabled},ready:e.ready,get degraded(){return e.degraded},destroy:e.destroy}}const gwt=e=>{let t=rG(e);return t===`ENOENT`||t===`ENOTDIR`},_wt=(e,t)=>e.signature===t.signature&&(!e.racy||e.digest===t.digest),vwt=e=>e.racy?e:{...e,digest:void 0};async function ywt(e){let t;try{t=await ec(e,{bigint:!0})}catch(e){if(gwt(e))return;throw e}return t.isFile()?t:void 0}async function bwt(e){try{return ac(`sha256`).update(await Xs(e)).digest(`hex`)}catch(e){if(gwt(e))return;throw e}}async function xwt(e,t,n){let r=cot(),i=await ywt(e);if(i===void 0)return;if(!t?.racy&&!j4(i,r))return{size:i.size,signature:A4(i),racy:!1,digest:void 0};if(n())return;let a=await bwt(e);if(a===void 0||n())return;let o=await ywt(e);if(o!==void 0)return{size:o.size,signature:A4(o),racy:j4(o,r),digest:a}}async function L7({listPaths:e,onEvent:t,onError:n}){let r=q(`polled-path-watcher`),i=new Map,a=!1,o=(e,t)=>{if(!a)try{n(e,t)}catch(n){try{r.error({err:e,error:n,path:t},`onError threw while reporting a watcher error`)}catch{}}},s=async t=>{let n=new Set(await e());for(let e of i.keys())n.has(e)||i.delete(e);let r=new Map;return await Promise.all(Array.from(n,async e=>{let n;try{n=await xwt(e,t.get(e),()=>a)}catch(n){let a=rG(n);(!i.has(e)||i.get(e)!==a)&&(i.set(e,a),o(n,e));let s=t.get(e);s&&r.set(e,s);return}i.delete(e),n&&r.set(e,n)})),r},c=await s(new Map),l=new Map,u=e=>{for(let[n,r]of e){let e=c.get(n);e!==void 0&&_wt(e,r)?(l.delete(n),e.racy&&c.set(n,vwt(r))):l.get(n)===r.size?(l.delete(n),c.set(n,vwt(r)),t(e?`change`:`add`,n)):l.set(n,r.size)}for(let n of c.keys())e.has(n)||(c.delete(n),t(`unlink`,n));for(let t of l.keys())e.has(t)||l.delete(t)},d,f=async()=>{try{let e=await s(c);a||u(e)}catch(e){o(e)}},p=()=>{d=setTimeout(()=>{f().finally(()=>{a||p()})},200)};return p(),async()=>{a||(a=!0,clearTimeout(d))}}function R7(e,t){try{return K(e,`utf-8`)}catch(n){return rG(n)!==`ENOENT`&&t.warn({err:n,path:e},`config file baseline read failed; treating it as absent`),null}}async function Swt(e,t){let n=q(`config-file-watcher`),r=V(e);try{KH(r,{recursive:!0})}catch(e){rG(e)!==`EEXIST`&&n.warn({err:e,watchDir:r},`failed to create watch directory; watcher may be inert`)}let i=R7(e,n),a=(r,a=!0)=>{if(r!==e)return;let o;try{o=K(r,`utf-8`)}catch(e){if(rG(e)===`ENOENT`){a&&n.debug({path:r},`config file disappeared between event and read; dropping`);return}n.warn({err:e,path:r},`config file read failed; dropping event`);return}if(o!==i){i=o;try{t(o)}catch(e){n.warn({err:e,path:r},`config file change handler threw`)}}},o=t=>{t===e&&n.debug({path:t},`config file unlinked; Y.Text retained at current state`)},s=await L7({listPaths:async()=>[e],onEvent:(e,t)=>e===`unlink`?o(t):a(t),onError:(e,t)=>{n.warn({err:e,path:t},`[config-file-watcher] poll error`)}});return a(e,!1),Object.assign(()=>s(),{resync:()=>{i=R7(e,n)}})}async function Cwt(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let n=q(`config-file-watcher`),r=new Set(e),i=Array.from(new Set(Array.from(r,e=>V(e))));for(let e of i)try{KH(e,{recursive:!0})}catch(t){rG(t)!==`EEXIST`&&n.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let a=new Map,o=()=>{for(let e of r)a.set(e,R7(e,n))};o();let s=(e,i=!0)=>{if(!r.has(e))return;let o;try{o=K(e,`utf-8`)}catch(t){if(rG(t)===`ENOENT`){i&&n.debug({path:e},`config file disappeared between event and read; dropping`);return}n.warn({err:t,path:e},`config file read failed; dropping event`);return}if(o!==a.get(e)){a.set(e,o);try{t(e,o)}catch(t){n.warn({err:t,path:e},`config file change handler threw`)}}},c=e=>{r.has(e)&&n.debug({path:e},`config file unlinked; downstream state retained`)},l=await L7({listPaths:async()=>Array.from(r),onEvent:(e,t)=>e===`unlink`?c(t):s(t),onError:(e,t)=>{n.warn({err:e,path:t},`[config-file-watcher] poll error`)}});for(let e of r)s(e,!1);return Object.assign(()=>l(),{resync:o})}const z7=q(`config-persistence`);function B7(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let wwt=null;function Twt(){return wwt||=_H().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),wwt}function Ewt(e){if(pn(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)dne(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function V7(e,t){if(e===`__config__/project`)return Vx(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return Vx(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return Vx(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return W(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let H7=null;function Dwt(){return H7===null&&(H7=(0,Fc.stringify)(na.parse({}))),H7}function Owt(e){if(e.length===0)return{ok:!0};let t=e.split(`
2160
+ `),x={brokenLinks:h};return g&&(x.brokenLinkSuppression=g),d&&(x.hints=d),f&&(x.summary=f),m&&(x.warnings=m),s.templateHint&&(x.templateHint=s.templateHint),U3(b,Pct(l,u?n7(l,o):void 0,x))}function nwt(e,t){let n={path:R().describe('Document path. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup". An optional `.md`/`.mdx` suffix selects the file format (default `.md`); prefer the `extension` field for that. The docName itself is always extension-less.'),content:R().optional().describe("The full Markdown body. C0 controls allow only TAB, LF and CR; remove others or use printable escapes. Mutually exclusive with `template`."),extension:sbt.optional(),template:R().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:s7.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:obt.optional()};e.registerTool(`write`,{description:zCt,inputSchema:{document:B(n).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:B({path:R().describe(`Folder path. Example: "meetings".`),frontmatter:s7.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:B({path:R().describe(lbt),content:R().describe("Starter content — the Markdown a new document becomes. A leading `---…---` frontmatter block here sets the STARTING PROPERTIES every doc created from this template gets (e.g. `type`, `status`, `tags`); the markdown below it is the body. The template's own picker identity (title/description) is the separate `frontmatter` field, NOT this block — it is stripped at instantiation and never copied onto created docs. (On disk this composes to one frontmatter block with the identity under a reserved `template:` key; you don't author that — just give the starter content here.) Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time. C0 controls allow only TAB, LF and CR; remove others or use printable escapes."),frontmatter:B({title:R().min(1).describe(`Required — the label shown when an agent picks this template.`),description:R().optional().describe(`Optional — shown beside the title in the template menu.`),tags:z(R()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),skill:B({name:R().describe(l7),description:R().optional().describe(`${ubt} Optional when writing ONLY \`files\` into an existing skill (omit to leave SKILL.md untouched).`),body:R().optional().describe("SKILL.md body (markdown guidance). Authored WITHOUT frontmatter — `name` + `description` are passed separately and composed server-side. Keep under ~500 lines; move depth into one-level-deep `references/`. C0 controls allow only TAB, LF and CR; remove others or use printable escapes."),files:z(B({path:R().describe(`Skill-relative path, e.g. "references/tiers.md" or "assets/logo.svg". Must stay inside the skill dir.`),content:R().describe(`Full text of the bundle file, including any frontmatter. For .md/.mdx paths, C0 controls allow only TAB, LF and CR; remove others or use printable escapes.`)})).optional().describe('Bundle files to write beside `SKILL.md`, as an ARRAY of `{ path, content }` (consistent with `documents`/`asset`). `path` is SKILL-RELATIVE and must stay inside the skill dir (e.g. "references/tiers.md", "scripts/run.sh", "assets/logo.svg") — no `../`, no absolute paths. `content` is the full text. Text only (no binary). Independent of `body`: write one reference without resending SKILL.md.'),scope:u7.optional()}).optional().describe('Create or overwrite an agent SKILL bundle (a NEW skill lands at the project\'s default skill home, e.g. `.agents/skills/<name>/`). SKILL.md is authored via `description`+`body`; bundle files via the `files` array — any skill-relative path that stays inside the skill dir (`references/**` and `scripts/**` are the conventional homes; `assets/` and per-harness dirs are accepted because published skills ship them). Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }'),asset:B({path:R().describe('Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png". A bare file name (no folder) goes to the attachment folder (`content.attachmentFolderPath`; by default the content root).'),content:R().optional().describe(`Base64 of the binary. Use for small files.`),source:R().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:z(B({...n,summary:F3})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:F3,cwd:R().optional().describe(P3)},outputSchema:H3({document:B({hints:z3.optional().describe(`Server-provided write hints, when any.`),...Nct}).optional().describe("Single-document write result. Always present on a successful single-doc write — it carries `brokenLinks` (possibly `[]`) plus any `brokenLinkSuppression`/`summary`/`hints`/`warnings`. Read `brokenLinkSuppression` and `warnings` before concluding anything from an empty `brokenLinks`: a suppression means a project policy withheld findings that are not yours to repair; a `link-check-deferred` warning means links were not checked yet."),folder:B({ok:Wa(),path:R(),frontmatterError:R().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:B({ok:Wa(),path:R(),created:Wa().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),skill:B({ok:Wa(),path:R().optional(),created:Wa().optional().describe(`true if created, false if an existing skill was overwritten.`),files:z3.optional().describe("Per-bundle-file results `{ path, kind, created, ok, error? }`."),warnings:z(R()).optional().describe(`Non-fatal authoring warnings for the SKILL.md that was written. ${c6}`),warningCodes:z(ui(fi)).optional().describe(`${s6} ${l6}`)}).optional().describe(`Skill-create result (SKILL.md and/or bundle files).`),asset:B({ok:Wa(),src:R().describe(`The reference src to embed in a doc.`),path:R().optional().describe("Content-root-relative path the server reports holding the asset (the existing file when `deduped`). Absent when the server reports none."),deduped:Wa().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:z3.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, brokenLinks, brokenLinkSuppression?, error? }`. `brokenLinks` (possibly `[]`) is present on each successful entry, same as a single-doc write — and, same as a single-doc write, an empty list means every link resolves only on entries carrying no `brokenLinkSuppression` and no `link-check-deferred` warning (links not checked yet because the server is still starting or busy)."),previewUrl:I3.optional(),previewUrlSource:L3,warning:kct})},async e=>{let n=await q3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return $(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n,o=Hq(r),s=Bq(i,r),c=i.appearance.preview.autoOpen;if(e.documents!==void 0){let n=p7(e,[`document`,`folder`,`template`,`skill`,`asset`,`documents`]);return n?$(`Error: ${n}`,!0):a?ewt(e.documents,r,s,a,t,o,c):$(W3(),!0)}let l=p7(e,[`document`,`folder`,`template`,`skill`,`asset`]);return l?$(`Error: ${l}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?e.skill===void 0?QCt(e.asset,r,a,t):$Ct(e.skill,e.summary,a,t,o):ZCt(e.template,e.summary,a,t):XCt(e.folder,e.summary,a,t):a?twt({...e.document,summary:e.summary},r,s,a,t,o,c):$(W3(),!0)})}function rwt(e,t){let n=t.logger,r=xyt(e,{logger:t.logger,identityRef:t.identityRef}),i=e=>async r=>{try{let i=await t.resolveCwd(r);return(G5()??n)?.debug(`tool cwd resolved`,{tool:e,cwd:i,...r?{explicit:r}:{}}),i}catch(t){throw(G5()??n)?.warn(`tool call failed`,{tool:e,err:t,...r?{explicit:r}:{}}),t}};lSt(r,{resolveCwd:i(`exec`),serverUrl:t.serverUrl,config:t.config}),vCt(r,{resolveCwd:i(`search`),config:t.config,serverUrl:t.serverUrl,localApi:t.localApi}),MSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`links`),localApi:t.localApi}),HSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`lint`),identityRef:t.identityRef}),Hyt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`audit`)}),nwt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`write`),identityRef:t.identityRef,localApi:t.localApi}),Vbt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`edit`),identityRef:t.identityRef}),Obt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`delete`),identityRef:t.identityRef,localApi:t.localApi}),$St(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`move`),identityRef:t.identityRef}),kSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`install`),identityRef:t.identityRef,localApi:t.localApi}),TSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`import`),identityRef:t.identityRef,localApi:t.localApi}),SSt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`history`)}),RCt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`skills`)}),Gyt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`checkpoint`),identityRef:t.identityRef,localApi:t.localApi}),sCt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`restore_version`),identityRef:t.identityRef}),aCt(r,{resolveCwd:i(`palette`),config:t.config}),Xyt(r,{config:t.config,resolveCwd:i(`config`)}),ySt(r,{config:t.config,resolveCwd:i(`preview_url`),serverUrl:t.serverUrl,isHostedAgent:t.isHostedAgent,...t.serverUrl?{ensureSingleFileSession:eyt()}:{}}),ECt(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`share_link`)})}function N7(e){return Array.isArray(e)?e[0]:e}function P7(e,t,n){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(n))}function iwt(e,t,n,r){let i=e.config,a=new BI({name:Ta,version:qZ});vvt(a);let o=n??oc(),s={current:{connectionId:o,displayName:o,colorSeed:o}};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=$4e(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:Ae(t),colorSeed:t}};let c=e.projectDir??e.contentDir;return rwt(a,{serverUrl:async()=>e.getServerUrl(),localApi:e.localApi,resolveCwd:async e=>{if(e===void 0)return c;let t=M3(c,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:i,identityRef:s,isHostedAgent:r}),_vt(a),{server:a,transport:t}}function awt(e){let t=new Map,n=e.sessionTtlMs??18e5,r=e.maxSessions??100;async function i(n,r){let i=t.get(n);if(!i)return;t.delete(n),i.ttlTimer!==void 0&&clearTimeout(i.ttlTimer);let a=await Promise.allSettled([i.server.close(),i.transport.close()]);for(let t of a)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:n,reason:r},`MCP HTTP session close failed`);e.log?.info?.({sessionId:n,reason:r},`MCP HTTP session closed`)}function a(t,r){r.ttlTimer!==void 0&&clearTimeout(r.ttlTimer),r.ttlTimer=setTimeout(()=>{i(t,`ttl-expired`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},n),r.ttlTimer.unref?.()}return{async handle(n,o){let s=N7(n.headers[`mcp-session-id`]);if(s){let e=t.get(s);if(!e){P7(o,404,`MCP session not found`);return}a(s,e),await e.transport.handleRequest(n,o);return}if(n.method!==`POST`){P7(o,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=r){e.log?.warn?.({activeSessions:t.size,maxSessions:r},`MCP HTTP session cap reached`),P7(o,503,`Too many active MCP sessions`);return}let c=N7(n.headers[Z4e]),l=YV(c)??void 0;c!==void 0&&l===void 0&&e.log?.warn?.({headerLength:c.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let u=N7(n.headers[Q4e])===`1`,d=new $Ue({sessionIdGenerator:()=>oc(),enableJsonResponse:!0,onsessioninitialized:async n=>{try{let r=iwt(e,d,l,u);await r.server.connect(d),t.set(n,r),a(n,r),e.log?.info?.({sessionId:n},`MCP HTTP session initialized`)}catch(r){throw t.delete(n),e.log?.error?.({err:r,sessionId:n},`MCP HTTP session initialization failed`),r}}});d.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},d.onclose=()=>{let t=d.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}i(t,`transport-closed`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await d.handleRequest(n,o)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>i(e,`handler-close`)))}}}const F7=1048576;function owt(e){if(!e)return null;try{return YV(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}function I7(e){return e===null||e.length===0||e.length>256||/[\u0000-\u001f\u007f]/.test(e)?null:e}function swt(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),n=I7(t.searchParams.get(`displayName`)),r=I7(t.searchParams.get(`clientName`)),i=I7(t.searchParams.get(`colorSeed`));return n===null||r===null||i===null?null:{displayName:n,clientName:r,colorSeed:i}}catch{return null}}function cwt(e){let{hocuspocus:t,log:n,sessionManager:r,agentFocusBroadcaster:i,agentPresenceBroadcaster:a,maintenanceCoordinator:o,acpThreadManager:s}=e,c=e.ingressPolicy??w$({}),l=e.keepaliveGraceMs??1e4,u=new fae.default({noServer:!0,maxPayload:F7}),d=new Map,f=new Set,p=new Set,m=!1,h;u.on(`error`,e=>n.error({err:e},`WebSocketServer error`));let g=e=>T$(e.socket.remoteAddress,c)&&E$(Array.isArray(e.headers.host)?e.headers.host[0]:e.headers.host,c),_=(e,t)=>{e.on(`error`,e=>{VU(e)||n.error({err:e},`${t} socket error`)}),p.add(e),e.once(`close`,()=>p.delete(e))},v=(e,t,r,i,a)=>{try{u.handleUpgrade(e,t,r,a)}catch(r){n.error({err:r,url:e.url},`[collab] ${i} handleUpgrade threw`);try{t.destroy()}catch{}}},y=(e,t,s)=>{if(!g(e)||e.headers.origin!==void 0&&!D$(e.headers.origin,c)){n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/keepalive upgrade refused`),t.destroy();return}_(t,`MCP keepalive`),v(e,t,s,`keepalive`,t=>{let s=owt(e.url);if(s){let e=d.get(s);e!==void 0&&(clearTimeout(e),d.delete(s),n.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&a){let t=swt(e.url);if(t)try{let e=Hn(t.clientName);a.setPresence(XV(s),{displayName:t.displayName,icon:e,color:Ha[e]??Ve(t.colorSeed),currentDoc:`(connected)`,mode:`idle`,ts:Date.now(),docTs:Date.now()})}catch(e){n.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let c=setInterval(()=>{try{t.ping()}catch{}},3e4);c.unref?.();let u=s?setInterval(()=>a?.bumpPresenceTs(XV(s)),3e3):null;u?.unref?.(),t.on(`close`,()=>{if(clearInterval(c),u!==null&&clearInterval(u),!s||m)return;let e=setTimeout(()=>{if(d.delete(s),m)return;let e=(async()=>{n.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await r?.closeAllForAgent(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{i?.clearFocus(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{a?.clearPresence(XV(s))}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await o?.onSessionClose()}catch(e){n.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();f.add(e),e.finally(()=>f.delete(e))},l);e.unref?.(),d.set(s,e),n.info({connectionId:s,graceMs:l},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{VU(e)||n.error({err:e},`MCP keepalive WS error`),t.terminate()})})};return{wss:u,handleUpgrade:(e,r,i)=>{if(!e.url?.startsWith(`/collab`))return!1;if(n.info({url:e.url,protocol:e.headers[`sec-websocket-protocol`]??`none`,host:e.headers.host??`none`,origin:e.headers.origin??`none`},`[collab] upgrade received`),k7e(e,{}),O$(e,c))return n.warn({url:e.url,host:e.headers.host},`[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL (or server.allowExternal + server.externalUrl in config)`),k$(n,`collab-upgrade`),r.destroy(),!0;if(e.url.startsWith(`/collab/thread`))return s==null||!g(e)||e.headers.origin!==void 0&&!D$(e.headers.origin,c)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/thread upgrade refused`),r.destroy(),!0):(_(r,`ACP thread`),v(e,r,i,`thread`,e=>G5e(e,s,n)),!0);if(e.url.startsWith(`/collab/keepalive`))return y(e,r,i),!0;let a=e.headers.origin!==void 0&&!D$(e.headers.origin,c),o=c.allowExternal;return a||o&&!g(e)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab upgrade refused`),r.destroy(),!0):(_(r,`Upgrade`),n.info({url:e.url},`[collab] handleUpgrade starting`),v(e,r,i,`collaboration`,r=>{let i=t.getConnectionsCount?.()??-1,a=t.handleConnection(r,e);n.info({url:e.url,connectionsBefore:i},`[collab] handshake complete`);let o=!1;r.on(`message`,e=>{if(!o){if(e.byteLength>F7){o=!0,BU(),n.warn({event:`collab-message-too-large`,bytes:e.byteLength,limit:F7},`Collab WebSocket message rejected before Yjs processing`),r.close(1009,`Message Too Big`);return}a.handleMessage(new Uint8Array(e))}}),r.on(`close`,(e,t)=>a.handleClose({code:e,reason:t.toString()})),r.on(`error`,e=>{e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`?(BU(),n.warn({event:`collab-message-too-large`,limit:F7},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`)):VU(e)||n.error({err:e},`WebSocket error`),r.terminate()})}),!0)},shutdown:()=>(h??=(async()=>{m=!0;for(let e of p)try{e.destroy()}catch{}p.clear();for(let e of d.values())clearTimeout(e);d.clear(),await Promise.allSettled(f)})(),h)}}function lwt({contentAssetMiddleware:e,reactShellMiddleware:t,ephemeral:n,ingressPolicy:r,log:i}){return(a,o)=>{let s=a.url?.split(`?`)[0];if(!R6(a,o,r,`mcp-mount`,i))return;let c=(e,t,n)=>{if(e===void 0){n();return}try{e(a,o,()=>{o.writableEnded||o.headersSent||n()})}catch(e){i.error({err:e},`Unhandled ${t} middleware error`),!o.writableEnded&&!o.headersSent?X(o,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):o.writableEnded||o.end()}},l=t=>{if(n===!0&&e!==void 0){if(!T$(a.socket.remoteAddress,r)){X(o,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!E$(a.headers.host,r)){X(o,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:C$});return}}c(e,`content-asset`,t)},u=e=>c(t,`react-shell`,e),d=()=>{o.writableEnded||o.headersSent||X(o,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`${t===void 0?`This server is running without the web UI. Restart it with plain \`${de()} start\` to serve the editor. `:``}No handler for ${s??`/`}`})};if(t!==void 0&&(s?.startsWith(`/assets/`)||s?.startsWith(`/excalidraw-assets/`))){u(()=>l(d));return}if(e!==void 0||t!==void 0){l(()=>u(d));return}X(o,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`This server is running without the web UI. Restart it with plain \`${de()} start\` to serve the editor. No handler for ${s??`/`}`})}}const uwt={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function dwt(e,t,n){return(r,i)=>{let a=r.headers.origin,o=Array.isArray(r.headers[`mcp-session-id`])?r.headers[`mcp-session-id`][0]:r.headers[`mcp-session-id`];if(!T$(r.socket.remoteAddress,t)){X(i,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`mcp`});return}if(!E$(r.headers.host,t)){X(i,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`,detail:C$});return}let s=E7e(a,r.method,t);if(!s.admitted){X(i,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`,detail:s.detail});return}if(a!==void 0&&i.setHeader(`Vary`,`Origin`),s.corsGrant){a!==void 0&&i.setHeader(`Access-Control-Allow-Origin`,a);for(let[e,t]of Object.entries(uwt))i.setHeader(e,t)}if(r.method===`OPTIONS`){i.writeHead(204),i.end();return}e.handle(r,i).catch(e=>{n.error({err:e,sessionId:o},`Unhandled MCP HTTP error`),!i.writableEnded&&!i.headersSent?X(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):i.writableEnded||i.end()})}}function fwt(e){let{httpServer:t,hocuspocus:n,mcpHttpHandler:r,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,contentAssetMiddleware:l,reactShellMiddleware:u,ephemeral:d}=e,f=e.ingressPolicy??w$({}),p=cwt({hocuspocus:n,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,keepaliveGraceMs:e.keepaliveGraceMs,acpThreadManager:e.acpThreadManager,ingressPolicy:f}),m=(e,t)=>{let r=e.url?.split(`?`)[0];R6(e,t,f,`mcp-mount`,i)&&n.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||X(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${r}`})}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()})},h=(e,t,n)=>{p.handleUpgrade(e,t,n)||(O$(e,f)&&(i.warn({url:e.url,host:e.headers.host},`[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL (or server.allowExternal + server.externalUrl in config)`),k$(i,`ws-upgrade`)),t.destroy())},{requestListener:g}=Kut({health:e.health,nativeApi:e.nativeApi,mcpDispatch:r===void 0?void 0:dwt(r,f,i),ingressPolicy:f,legacyDispatch:m,contentDispatch:lwt({contentAssetMiddleware:l,reactShellMiddleware:u,ephemeral:d,ingressPolicy:f,log:i}),log:i});t.on(`request`,g),t.on(`upgrade`,h);let _;return{wss:p.wss,shutdown:()=>(_??=(async()=>{t.off(`upgrade`,h),await p.shutdown()})(),_)}}function pwt(){return`OpenKnowledge config not found at .ok/config.yml. Run ${de()} init to scaffold OK in this directory.`}var mwt=class extends Error{kind;projectDir;constructor(e,t,n){super(pwt(),n),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};function hwt(e,t){return{crdt:{hocuspocus:e.hocuspocus,durabilityState:e.durabilityState,cc1Broadcaster:e.cc1Broadcaster,serverInstanceId:e.serverInstanceId},content:{contentDir:t.contentDir,projectDir:t.projectDir,contentFilter:e.contentFilter},indexes:{basenameIndex:e.basenameIndex,resolveEmbed:e.resolveEmbed},git:{get syncEngine(){return e.syncEngine}},agents:{sessionManager:e.sessionManager,agentFocusBroadcaster:e.agentFocusBroadcaster,agentPresenceBroadcaster:e.agentPresenceBroadcaster,acpRegistry:e.acpRegistry,acpPermissions:e.acpPermissions},background:{maintenanceCoordinator:e.maintenanceCoordinator},config:{getLinkPreviewsEnabled:e.getLinkPreviewsEnabled},ready:e.ready,get degraded(){return e.degraded},destroy:e.destroy}}const gwt=e=>{let t=rG(e);return t===`ENOENT`||t===`ENOTDIR`},_wt=(e,t)=>e.signature===t.signature&&(!e.racy||e.digest===t.digest),vwt=e=>e.racy?e:{...e,digest:void 0};async function ywt(e){let t;try{t=await ec(e,{bigint:!0})}catch(e){if(gwt(e))return;throw e}return t.isFile()?t:void 0}async function bwt(e){try{return ac(`sha256`).update(await Xs(e)).digest(`hex`)}catch(e){if(gwt(e))return;throw e}}async function xwt(e,t,n){let r=cot(),i=await ywt(e);if(i===void 0)return;if(!t?.racy&&!j4(i,r))return{size:i.size,signature:A4(i),racy:!1,digest:void 0};if(n())return;let a=await bwt(e);if(a===void 0||n())return;let o=await ywt(e);if(o!==void 0)return{size:o.size,signature:A4(o),racy:j4(o,r),digest:a}}async function L7({listPaths:e,onEvent:t,onError:n}){let r=q(`polled-path-watcher`),i=new Map,a=!1,o=(e,t)=>{if(!a)try{n(e,t)}catch(n){try{r.error({err:e,error:n,path:t},`onError threw while reporting a watcher error`)}catch{}}},s=async t=>{let n=new Set(await e());for(let e of i.keys())n.has(e)||i.delete(e);let r=new Map;return await Promise.all(Array.from(n,async e=>{let n;try{n=await xwt(e,t.get(e),()=>a)}catch(n){let a=rG(n);(!i.has(e)||i.get(e)!==a)&&(i.set(e,a),o(n,e));let s=t.get(e);s&&r.set(e,s);return}i.delete(e),n&&r.set(e,n)})),r},c=await s(new Map),l=new Map,u=e=>{for(let[n,r]of e){let e=c.get(n);e!==void 0&&_wt(e,r)?(l.delete(n),e.racy&&c.set(n,vwt(r))):l.get(n)===r.size?(l.delete(n),c.set(n,vwt(r)),t(e?`change`:`add`,n)):l.set(n,r.size)}for(let n of c.keys())e.has(n)||(c.delete(n),t(`unlink`,n));for(let t of l.keys())e.has(t)||l.delete(t)},d,f=async()=>{try{let e=await s(c);a||u(e)}catch(e){o(e)}},p=()=>{d=setTimeout(()=>{f().finally(()=>{a||p()})},200)};return p(),async()=>{a||(a=!0,clearTimeout(d))}}function R7(e,t){try{return K(e,`utf-8`)}catch(n){return rG(n)!==`ENOENT`&&t.warn({err:n,path:e},`config file baseline read failed; treating it as absent`),null}}async function Swt(e,t){let n=q(`config-file-watcher`),r=V(e);try{KH(r,{recursive:!0})}catch(e){rG(e)!==`EEXIST`&&n.warn({err:e,watchDir:r},`failed to create watch directory; watcher may be inert`)}let i=R7(e,n),a=(r,a=!0)=>{if(r!==e)return;let o;try{o=K(r,`utf-8`)}catch(e){if(rG(e)===`ENOENT`){a&&n.debug({path:r},`config file disappeared between event and read; dropping`);return}n.warn({err:e,path:r},`config file read failed; dropping event`);return}if(o!==i){i=o;try{t(o)}catch(e){n.warn({err:e,path:r},`config file change handler threw`)}}},o=t=>{t===e&&n.debug({path:t},`config file unlinked; Y.Text retained at current state`)},s=await L7({listPaths:async()=>[e],onEvent:(e,t)=>e===`unlink`?o(t):a(t),onError:(e,t)=>{n.warn({err:e,path:t},`[config-file-watcher] poll error`)}});return a(e,!1),Object.assign(()=>s(),{resync:()=>{i=R7(e,n)}})}async function Cwt(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let n=q(`config-file-watcher`),r=new Set(e),i=Array.from(new Set(Array.from(r,e=>V(e))));for(let e of i)try{KH(e,{recursive:!0})}catch(t){rG(t)!==`EEXIST`&&n.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let a=new Map,o=()=>{for(let e of r)a.set(e,R7(e,n))};o();let s=(e,i=!0)=>{if(!r.has(e))return;let o;try{o=K(e,`utf-8`)}catch(t){if(rG(t)===`ENOENT`){i&&n.debug({path:e},`config file disappeared between event and read; dropping`);return}n.warn({err:t,path:e},`config file read failed; dropping event`);return}if(o!==a.get(e)){a.set(e,o);try{t(e,o)}catch(t){n.warn({err:t,path:e},`config file change handler threw`)}}},c=e=>{r.has(e)&&n.debug({path:e},`config file unlinked; downstream state retained`)},l=await L7({listPaths:async()=>Array.from(r),onEvent:(e,t)=>e===`unlink`?c(t):s(t),onError:(e,t)=>{n.warn({err:e,path:t},`[config-file-watcher] poll error`)}});for(let e of r)s(e,!1);return Object.assign(()=>l(),{resync:o})}const z7=q(`config-persistence`);function B7(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let wwt=null;function Twt(){return wwt||=_H().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),wwt}function Ewt(e){if(pn(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)dne(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function V7(e,t){if(e===`__config__/project`)return Vx(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return Vx(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return Vx(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return W(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let H7=null;function Dwt(){return H7===null&&(H7=(0,Fc.stringify)(na.parse({}))),H7}function Owt(e){if(e.length===0)return{ok:!0};let t=e.split(`
2161
2161
  `);for(let e=0;e<t.length;e++){let n=t[e]??``;if(n.length!==0&&/^\s+$/.test(n))return{ok:!1,error:{code:`OKIGNORE_INVALID`,detail:`Whitespace-only pattern is not allowed.`,lineNumber:e+1}}}return{ok:!0}}function U7(e,t){return e===`__config__/okignore`?Owt(t):Awt(t)}function kwt(e){return e===`__config__/okignore`?``:Dwt()}function Awt(e){let t=(0,Fc.parseDocument)(e);if(t.errors.length>0)return{ok:!1,error:{code:`YAML_PARSE`,detail:t.errors.map(e=>e.message).join(`; `)}};let n=t.toJSON()??{},r=na.safeParse(n);return r.success?{ok:!0}:{ok:!1,error:{code:`SCHEMA_INVALID`,issues:r.error.issues.map(e=>({path:e.path.map(e=>typeof e==`symbol`?String(e):e),message:e.message,issueCode:e.code}))}}}function jwt(e,t,n){let r=e.getText(`source`);if(r.length>0)return;let i=V7(t,n),a=``;if(G(i))try{a=K(i,`utf-8`)}catch(e){let t=e instanceof Error?e.message:String(e);z7.warn({path:i,err:e},`[config-persistence] Could not read ${i}: ${t}. Seeding with empty content.`),a=``}let o=U7(t,a);!o.ok&&a.length>0&&z7.warn({docName:t,path:i},`[config-persistence] loadConfigDoc seeding invalid content for ${t} into Y.Text — first mutation will revert to LKG`),e.transact(()=>{a.length>0&&r.insert(0,a)},S1),o.ok&&a.length>0?n.lkgCache.set(t,a):n.lkgCache.set(t,kwt(t))}async function Mwt(e,t){await UH(V(e),{recursive:!0});let n=Fx(e);try{await zH(n,t,`utf-8`),await HH(n,e)}catch(e){try{XH(n)}catch{}throw e}}async function Nwt(e,t,n,r){return ua(`config.persist`,{"config.scope":B7(t),"config.transport":`fs`},async i=>{let a=await Fwt(e,t,n,r);return i.setAttribute(`config.outcome`,Pwt(a)),a})}function Pwt(e){return e===`reverted`?`reverted`:e===`write-failed`?`rejected`:`success`}async function Fwt(e,t,n,r){if(r.ephemeral&&t===`__config__/okignore`||n===S1)return`no-op`;let i=e.getText(`source`),a=i.toString(),o=r.lkgCache.get(t);if(a.length===0&&(t!==`__config__/okignore`||o===void 0||o===``)||o!==void 0&&a===o)return`no-op`;let s=B7(t),c=xa(`config.validate`,{"config.scope":s,"config.validation.layer":`L3`},e=>{let n=U7(t,a);return e.setAttribute(`config.outcome`,n.ok?`success`:`rejected`),n.ok||Ewt(n.error),n});if(!c.ok)return await ua(`config.revert`,{"config.scope":s,"config.outcome":`reverted`},async()=>{let n=o??kwt(t);e.transact(()=>{i.length>0&&i.delete(0,i.length),i.insert(0,n)},S1),o===void 0&&r.lkgCache.set(t,n),t===`__config__/okignore`&&pn(c.error)&&Twt().add(1,{"error.code":c.error.code}),r.onConfigRejected?.(t,c.error)}),`reverted`;let l=V7(t,r);try{await UH(V(l),{recursive:!0})}catch(e){let n=e instanceof Error?e.message:String(e);return z7.warn({docName:t,path:l,err:e},`[config-persistence] could not create parent dir for ${l}: ${n}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not create parent directory for ${l}: ${n}`}),`write-failed`}try{return await zx(`${l}.lock`,async()=>{let n=null;try{n=K(l,`utf-8`)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);return z7.warn({docName:t,path:l,err:e},`[config-persistence] could not read config for reconciliation: ${n}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not read config for reconciliation at ${l}: ${n}`}),`write-failed`}}if(n!==null&&o!==void 0&&n!==o){if(U7(t,n).ok)return e.transact(()=>{i.length>0&&i.delete(0,i.length),i.insert(0,n)},det),r.lkgCache.set(t,n),z7.info({docName:t,path:l},`[config-persistence] reconciled: external writer landed; imported disk into Y.Text`),`reconciled`;z7.warn({docName:t,path:l},`[config-persistence] disk diverged from LKG but contains invalid content; proceeding with local write`)}try{await Mwt(l,a)}catch(e){let n=e instanceof Error?e.message:String(e);return z7.warn({docName:t,path:l,err:e},`[config-persistence] write-failed at ${l}: ${n}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Failed to persist config at ${l}: ${n}`}),`write-failed`}return r.lkgCache.set(t,a),`persisted`},{onWarn:(e,t)=>{z7.warn(t,`[config-persistence] ${e}`)}})}catch(e){if(e instanceof Rx)return z7.warn({docName:t,path:l,err:e},`[config-persistence] lock timeout at ${l}: ${e.message}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:e.message}),`write-failed`;throw e}}function Iwt(e,t,n){try{XH(V7(t,n))}catch(e){if(e.code!==`ENOENT`)throw e}if(n.lkgCache.delete(t),e===null)return;let r=e.getText(`source`);r.length>0&&e.transact(()=>{r.delete(0,r.length)},S1),jwt(e,t,n)}function Lwt(e,t,n){return n.lkgCache.get(e)===t}function W7(e,t,n,r){if(!e||Lwt(t,n,r))return`no-op`;let i=B7(t),a=xa(`config.validate`,{"config.scope":i,"config.validation.layer":`L3`},e=>{let r=U7(t,n);return e.setAttribute(`config.outcome`,r.ok?`success`:`rejected`),r.ok||Ewt(r.error),r});if(!a.ok)return t===`__config__/okignore`&&pn(a.error)&&Twt().add(1,{"error.code":a.error.code}),r.onConfigRejected?.(t,a.error),`rejected`;let o=e.getText(`source`);return e.transact(()=>{o.length>0&&o.delete(0,o.length),o.insert(0,n)},det),r.lkgCache.set(t,n),`applied`}const Rwt=`Other`,zwt=`Subdirectories`,G7=`Index`,Bwt=new Set([G7,Rwt,zwt]),Vwt={control:`generated index metadata contained a Cc control; replaced it with U+FFFD`,"parser-reservation":`generated index metadata contained a parser-reserved private-use code point; replaced it with U+FFFD`};function K7(e){return`${e.path}\0${e.field}`}var Hwt=class{contentDir;#e=new Map;constructor(e){this.contentDir=e}update(e,t,n){let r=K7(t),i=`${e}\0${r}`;if(!n){this.#e.delete(i);return}this.#e.has(i)||(this.#e.set(i,r),q(`generated-index`).warn({contentDir:this.contentDir,...t,kind:e},Vwt[e]))}retain(e){for(let[t,n]of this.#e)e.has(n)||this.#e.delete(t)}};function Uwt(e){return new Hwt(e)}function Wwt(e,t,n){if(!e)return;let r=new Set;for(let e of t)r.add(K7({path:e.path,field:`title`})),r.add(K7({path:e.path,field:`type`})),e.description!==void 0&&r.add(K7({path:e.path,field:`description`}));for(let e of n)r.add(K7({path:e.directory,field:`folder-label`}));e.retain(r)}function q7(e,t){let n=!1,r=!1,i=Array.from(Kwt(e),e=>/\p{Cc}/u.test(e)?(n=!0,`�`):Zre(e)?(r=!0,`�`):e).join(``);return t.kind===`attributed`&&t.warningScope&&(t.warningScope.update(`control`,t.source,n),t.warningScope.update(`parser-reservation`,t.source,r)),{visible:i,identity:i.normalize(`NFC`),source:i.replace(/[\u0021-\u002f\u003a-\u0040\u005b-\u0060\u007b-\u007e]/g,`\\$&`)}}function Gwt(e,t){let n=q7(e.type??``,{kind:`attributed`,source:{path:e.path,field:`type`},warningScope:t});return n.visible?n:q7(Rwt,{kind:`generator-owned`})}function Kwt(e){return e.replace(/\s+/g,` `).trim()}function J7(e,t){return e<t?-1:+(e>t)}function Y7(e){return Kwt(e).normalize(`NFC`).toLowerCase()}function qwt(e,t){return J7(Y7(e),Y7(t))||J7(e.normalize(`NFC`),t.normalize(`NFC`))}function Jwt(e,t){return(qwt(e,t)||J7(e,t))<0}function Ywt(e,t){return J7(Y7(e.title.visible),Y7(t.title.visible))||J7(e.path.replaceAll(`\\`,`/`).normalize(`NFC`),t.path.replaceAll(`\\`,`/`).normalize(`NFC`))}function Xwt(e,t){let n=`directory`in e?{path:e.directory,field:`folder-label`}:{path:e.path,field:`title`};return{path:`directory`in e?`${e.directory}/index.md`:e.path,title:q7(e.title,{kind:`attributed`,source:n,warningScope:t}),description:`description`in e&&e.description!==void 0?q7(e.description,{kind:`attributed`,source:{path:e.path,field:`description`},warningScope:t}):void 0}}function Zwt(e,t){let n=t.replaceAll(`\\`,`/`),r=e.replaceAll(`\\`,`/`).replace(/\/+$/,``);if(r===``)return n;let i=`${r}/`;return n.startsWith(i)?n.slice(i.length):n}function Qwt(e){let t=e.replaceAll(`\\`,`/`);return`./${Ga(t)}`}function $wt(e,t){let n=e.normalize(`NFC`);return t.resolve(n)===e?n:e}function eTt(e,t,n){let r=$wt(Zwt(t,e.path),n),i=`* [${e.title.source}](${Qwt(r)})`;return e.description?.source?`${i} - ${e.description.source}`:i}function tTt(e,t,n){return e.slice().sort(Ywt).map(e=>eTt(e,t,n)).join(`
2162
2162
  `)}function nTt(e,t){let n=t.directory??``,r=t.subdirectories??[],i=t.warningScope,a=q7(G7,{kind:`generator-owned`}).identity,o=new Map,s=ra(`document`),c=e=>{let t=e.identity,n=Bwt.has(e.visible),r=o.get(t);if(!r){let r={heading:e,pinned:n,links:[]};return o.set(t,r),r.links}return n&&!r.pinned?(r.heading=e,r.pinned=!0):!n&&!r.pinned&&Jwt(e.visible,r.heading.visible)&&(r.heading=e),r.links},l=e=>(s.add(Zwt(n,e.path)),e);for(let t of e)c(Gwt(t,i)).push(l(Xwt(t,i)));r.length>0&&c(q7(zwt,{kind:`generator-owned`})).push(...r.map(e=>l(Xwt(e,i))));let u=[...o].filter(([e])=>e!==a).sort(([,e],[,t])=>qwt(e.heading.visible,t.heading.visible)).map(([,{heading:e,links:t}])=>`## ${e.source}\n\n${tTt(t,n,s)}`),d=t.isRoot?`---
2163
2163
  okf_version: "0.2"