@inkeep/open-knowledge 0.86.19 → 0.86.20

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 (84) hide show
  1. package/dist/cli.mjs +6 -6
  2. package/dist/constants-BzjAJSFI.mjs +1 -0
  3. package/dist/{dist-CbA9Te53.mjs → dist-BGPdSmN8.mjs} +4 -4
  4. package/dist/{dist-dkuaYp-W.mjs → dist-DkXRAHZU.mjs} +1 -1
  5. package/dist/index.mjs +1 -1
  6. package/dist/{init-D1_2kwSe.mjs → init-C9OxriS2.mjs} +2 -2
  7. package/dist/init-D2N-G5vK.mjs +1 -0
  8. package/dist/{launch-json-removal-grbQuHRl.mjs → launch-json-removal-TnB13XlY.mjs} +1 -1
  9. package/dist/loader-BLBgSjXN.mjs +1 -0
  10. package/dist/{loader-CqCKhp-3.mjs → loader-BxttITBJ.mjs} +1 -1
  11. package/dist/{open-browser-foWNoVBg.mjs → open-browser-544981Pz.mjs} +1 -1
  12. package/dist/preview-CuM2TrBb.mjs +1 -0
  13. package/dist/{preview-Dw5ht4g5.mjs → preview-DWe9q5JX.mjs} +1 -1
  14. package/dist/public/assets/{AccountSection-DVxaHkM4.js → AccountSection-BSp2R9g2.js} +1 -1
  15. package/dist/public/assets/{ActivityModeContent-BIgcJK6a.js → ActivityModeContent-BCrd2UIn.js} +1 -1
  16. package/dist/public/assets/{AddPropertiesButton-D968tXQy.js → AddPropertiesButton-B3o6OXPY.js} +1 -1
  17. package/dist/public/assets/{AgentDiffPane-RE601rTO.js → AgentDiffPane-CCiGzoH0.js} +1 -1
  18. package/dist/public/assets/{AttachmentsSection-DL9nvFCk.js → AttachmentsSection-C93T5rSD.js} +1 -1
  19. package/dist/public/assets/{CodeMirrorPropInput-D-MXrjSu.js → CodeMirrorPropInput-B_DM6pT6.js} +1 -1
  20. package/dist/public/assets/{ContentRulesSection-DOLvfOER.js → ContentRulesSection-Cz52eO_M.js} +1 -1
  21. package/dist/public/assets/{DocumentContext-DoYFEoIV.js → DocumentContext-CUsoyl8q.js} +1 -1
  22. package/dist/public/assets/{EditorModeToggle-BrrBR82z.js → EditorModeToggle-C0F4UKng.js} +1 -1
  23. package/dist/public/assets/{ExcalidrawDocEditor-C9_cuBBc.js → ExcalidrawDocEditor-BmHDKLRi.js} +1 -1
  24. package/dist/public/assets/FeedbackForm-C_kFZsS6.js +1 -0
  25. package/dist/public/assets/{ImportSkillDialog-BbfUjEEz.js → ImportSkillDialog-Yk0VCFAg.js} +1 -1
  26. package/dist/public/assets/{LinkPreviewsSection-fEX_XthT.js → LinkPreviewsSection-CyeHW27a.js} +1 -1
  27. package/dist/public/assets/{LintConfigEditor-3qempgFs.js → LintConfigEditor-B5G61erT.js} +1 -1
  28. package/dist/public/assets/{LintingSection-C0-lVwWU.js → LintingSection-CWqDqFsH.js} +1 -1
  29. package/dist/public/assets/{ManagedArtifactProperties-BHAjmSMa.js → ManagedArtifactProperties-95igHuuE.js} +1 -1
  30. package/dist/public/assets/ManagedArtifactProperties-Dur9SWBZ.js +1 -0
  31. package/dist/public/assets/{MermaidDocEditor-DbH59fgw.js → MermaidDocEditor-9o9ig70y.js} +1 -1
  32. package/dist/public/assets/{NetworkAccessSection-Bbbze3FD.js → NetworkAccessSection-Bhn3U5nj.js} +1 -1
  33. package/dist/public/assets/{PropertyDisplayRow-DAkX7-35.js → PropertyDisplayRow-CnGuZCC-.js} +1 -1
  34. package/dist/public/assets/{PublishToGitHubDialog-C3q1CDqm.js → PublishToGitHubDialog-BL-xFCe9.js} +1 -1
  35. package/dist/public/assets/{SchemaConfigEditor-MCN2u6si.js → SchemaConfigEditor-CtSFO4xi.js} +1 -1
  36. package/dist/public/assets/{SearchSection-DCs9WFjN.js → SearchSection-Dm27Fcdx.js} +1 -1
  37. package/dist/public/assets/{SessionsHost-CIsRLSaE.js → SessionsHost-2l2jc9yc.js} +2 -2
  38. package/dist/public/assets/{SettingsDialogBody-BGgrDG7O.js → SettingsDialogBody-DbeBQ1Oq.js} +2 -2
  39. package/dist/public/assets/{ShareReceiveMissDialog-Bw61hL4X.js → ShareReceiveMissDialog-BX4bfEX5.js} +1 -1
  40. package/dist/public/assets/{SkillToolbarControls-BO0PKTq1.js → SkillToolbarControls-Ck9M1dZ4.js} +1 -1
  41. package/dist/public/assets/{SourceEditor-BBLTRJ7D.js → SourceEditor-DKvoc_-b.js} +1 -1
  42. package/dist/public/assets/{SyncSection-CRJzeX9p.js → SyncSection-0k1ctYue.js} +1 -1
  43. package/dist/public/assets/{SyncStatusBadge-D1OtRzRB.js → SyncStatusBadge--_KnEesK.js} +1 -1
  44. package/dist/public/assets/{TerminalSection-CC2YwJpV.js → TerminalSection-C4b-vw5j.js} +1 -1
  45. package/dist/public/assets/{TerminalWindowApp-DoI0jqQ1.js → TerminalWindowApp-Cd_-0tG1.js} +1 -1
  46. package/dist/public/assets/{TextDocEditor-BxVTOe7e.js → TextDocEditor-CAPsqB19.js} +1 -1
  47. package/dist/public/assets/{ThreadView-BHYoyM_O.js → ThreadView-CtAdbI1z.js} +1 -1
  48. package/dist/public/assets/{TimelineDiffPane-DO9irXKb.js → TimelineDiffPane-rJE9Dzwz.js} +1 -1
  49. package/dist/public/assets/{client-version-BVxzNu0e.js → client-version-Bdm4Iqzg.js} +1 -1
  50. package/dist/public/assets/{comment-chips-50INyshh.js → comment-chips-1P9YtXFI.js} +1 -1
  51. package/dist/public/assets/{config-provider-Bf-6EUb_.js → config-provider-BkMn6I7T.js} +1 -1
  52. package/dist/public/assets/{doc-undo-manager-CavX05dP.js → doc-undo-manager-C0GFkgEj.js} +1 -1
  53. package/dist/public/assets/{index-C10zpKkC.js → index-D3PM80wv.js} +7 -7
  54. package/dist/public/assets/{lint-plugins-C4Px2YBE.js → lint-plugins-CGH4gV3e.js} +1 -1
  55. package/dist/public/assets/{pending-receive-nav-store-BHYqINaL.js → pending-receive-nav-store-l2gpbd8l.js} +1 -1
  56. package/dist/public/assets/{preferred-session-events-DWIfqtIB.js → preferred-session-events-QaZHUEOT.js} +1 -1
  57. package/dist/public/assets/{progress-CgvUuzyt.js → progress-Cw8uW0-S.js} +1 -1
  58. package/dist/public/assets/{selection-context-C1ugIbCJ.js → selection-context-Bu02joOm.js} +1 -1
  59. package/dist/public/assets/{src-BjX-JGKc.js → src-o3k-itta.js} +1 -1
  60. package/dist/public/assets/{telemetry-impl-DsQovEi7.js → telemetry-impl-CEmk3C3S.js} +1 -1
  61. package/dist/public/assets/{telemetry-startup-Dgw1BcUL.js → telemetry-startup-Cn_nNKF1.js} +1 -1
  62. package/dist/public/assets/{typing-burst-detector-iy4OEiLk.js → typing-burst-detector-B-WMUzwR.js} +1 -1
  63. package/dist/public/assets/{use-activity-panel-BJDvDdvC.js → use-activity-panel-YGUNuYgi.js} +1 -1
  64. package/dist/public/assets/{use-open-skill-CFJ6fXda.js → use-open-skill-B2xp-vUC.js} +1 -1
  65. package/dist/public/assets/{use-terminal-enabled-jAihkkWu.js → use-terminal-enabled-Dv5wqPDz.js} +1 -1
  66. package/dist/public/assets/{use-timeline-entry-diff-dOfytDk7.js → use-timeline-entry-diff-D8jlzZSV.js} +1 -1
  67. package/dist/public/index.html +19 -19
  68. package/dist/{registry-probes-CPlsORK6.mjs → registry-probes-DbH8v0Qh.mjs} +1 -1
  69. package/dist/{removal-file-path-DXtxSsXI.mjs → removal-file-path-CcZ5OEOK.mjs} +1 -1
  70. package/dist/{repair-launch-json-HSjuiz_b.mjs → repair-launch-json-BUwLXR_B.mjs} +1 -1
  71. package/dist/{repair-mcp-configs-B3D0qm57.mjs → repair-mcp-configs-sprmmgpf.mjs} +1 -1
  72. package/dist/src-DZUzb-Pb.mjs +1 -0
  73. package/dist/{src-C9gZ883x.mjs → src-YGgHVdBT.mjs} +1 -1
  74. package/dist/start-BPYMRjEx.mjs +1 -0
  75. package/dist/{start-CRtnwn3L.mjs → start-D2XZWSXL.mjs} +3 -3
  76. package/package.json +4 -4
  77. package/dist/constants-BSsoisIb.mjs +0 -1
  78. package/dist/init-FqdPU1R4.mjs +0 -1
  79. package/dist/loader-DmXf4bJ0.mjs +0 -1
  80. package/dist/preview-CpjZq6qS.mjs +0 -1
  81. package/dist/public/assets/FeedbackForm-DL3ThcXe.js +0 -1
  82. package/dist/public/assets/ManagedArtifactProperties-CaWEt6SH.js +0 -1
  83. package/dist/src-CSHgb4Fd.mjs +0 -1
  84. package/dist/start-mTFQvqCW.mjs +0 -1
@@ -1066,9 +1066,9 @@ ${qYe.join(`
1066
1066
  `);try{i.stdin.end(`${u}\n`)}catch(e){clearTimeout(l),a1.warn({err:e},`[rename-log] WARN: batchResolveBlobOids stdin write failed: ${e.message}`),c(o())}})}function _1(e,t){let n=s1(e),r=tet(t);if(r.length===0){if(G(n))try{DG(n,``)}catch(e){a1.warn({err:e},`[rename-log] WARN: failed to truncate empty jsonl`)}return}let i=`${n}.tmp`;try{DG(i,r),AG(i,n)}catch(e){a1.warn({err:e},`[rename-log] WARN: atomic rewrite failed; index ahead of disk`);try{G(i)&&MG(i)}catch{}}}function det(e){let t=new Set;for(let n of e.byTo.values())n.commitSha===``&&t.add(n);return t}function fet(e,t,n,r,i){if(!/^[0-9a-f]{40}$/.test(n))return a1.warn({commitSha:n},`[rename-log] WARN: backfill rejected invalid commitSha: ${JSON.stringify(n)}`),{updated:0};let a=0;for(let e of i)e.commitSha===``&&e.actor.writerId===t&&r.byTo.get(e.to)===e&&(e.commitSha=n,a+=1);return a>0&&_1(e,r),{updated:a}}function pet(e,t){let n=[];for(let e of t.byTo.values())e.commitSha===``&&n.push(e);if(n.length===0)return{dropped:0};for(let e of n)X9e(t,e);return _1(e,t),o1().add(-n.length),a1.warn({orphans:n.length},`[rename-log] gc swept ${n.length} orphan entries (lazy-pop residue from mid-rename crash)`),{dropped:n.length}}async function v1(e,t,n){let r={scanned:0,dropped:0,retained:0,rebuilt:0};if(l1.has(e.gitDir))return{...r,skipped:!0};l1.add(e.gitDir);try{return await met(e,t,n,r)}finally{l1.delete(e.gitDir)}}async function met(e,t,n,r){let i=gK(e),a=[];for(let e of t.byTo.values())e.commitSha!==``&&a.push({entry:e,observedSha:e.commitSha});let o;try{o=(await i.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`,`refs/checkpoints/`)).split(`
1067
1067
  `).map(e=>e.trim()).filter(Boolean)}catch(e){return a1.warn({err:e},`[rename-log] WARN: gcRenameLog aborted — failed to enumerate refs`),r}let s=new Set;if(o.length>0){let t;try{t=await h1(e,o)}catch(e){return a1.warn({err:e},`[rename-log] WARN: gcRenameLog aborted — rev-list failed`),r}for(let e of t.split(`
1068
1068
  `)){let t=e.trim();t.length===40&&s.add(t)}}r.scanned=t.byTo.size;let c=[];for(let{entry:e,observedSha:n}of a)s.has(n)||t.byTo.get(e.to)===e&&e.commitSha===n&&c.push(e);for(let e of c)t.byTo.get(e.to)===e&&X9e(t,e);if(r.dropped=c.length,r.retained=t.byTo.size,n?.rebuild){let n;try{n=await i.raw(`log`,`--all`,`--grep=^rename: `,`--format=%H%x00%cI%x00%B%x1e`)}catch(e){a1.warn({err:e},`[rename-log] WARN: gcRenameLog rebuild: git log --grep failed; skipping reconstruction`),n=``}let a=await get(e,o);for(let e of n.split(``)){let n=e.trimStart();if(!n)continue;let i=n.split(`\0`),o=(i[0]??``).trim(),c=(i[1]??``).trim(),l=i[2]??``;if(o.length!==40||!s.has(o))continue;let u=LS(l),d=0;for(let e of u)d+=e.previous_paths?.length??0;if(d===0)continue;let f=d>1?`folder`:`file`,p=_et(a,o),m=het(o,``,``);for(let e of u)if(!(!e.previous_paths||e.previous_paths.length===0))for(let n of e.previous_paths)t.byTo.has(n.to)||(c1(t,{v:1,from:n.from,to:n.to,at:c||new Date(0).toISOString(),commitSha:o,branch:p,groupId:m,kind:f,actor:{writerId:e.writer_id,displayName:e.display_name}}),r.rebuilt+=1,r.retained+=1)}}return(r.dropped>0||r.rebuilt>0)&&_1(e.gitDir,t),r.dropped>0&&(a1.warn({dropped:r.dropped,retained:r.retained},`[rename-log] gc swept ${r.dropped} dead entries (${r.retained} live remain)`),W9e().add(r.dropped),o1().add(-r.dropped)),r.rebuilt>0&&o1().add(r.rebuilt),r}function het(e,t,n){let r=Tc(`sha256`);r.update(`${e}\0${t}\0${n}`);let i=r.digest(`hex`);return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20,32)}`}async function get(e,t){let n=new Map;for(let e of[...t].sort()){let t=/^refs\/(?:wip|checkpoints)\/([^/]+)\//.exec(e);if(!t?.[1])continue;let r=n.get(t[1])??[];r.push(e),n.set(t[1],r)}let r=new Map;for(let[t,i]of n){let n;try{n=await h1(e,i)}catch(e){a1.warn({branch:t,err:e},`[rename-log] WARN: gcRenameLog rebuild: rev-list failed for branch ${t}; reconstructed entries on this branch will fall back to 'main'`);continue}let a=new Set;for(let e of n.split(`
1069
- `)){let t=e.trim();t.length===40&&a.add(t)}r.set(t,a)}return r}function _et(e,t){for(let[n,r]of e)if(r.has(t))return n;return`main`}async function vet(e,t,n,r,i,a,o,s){let{chain:c}=net(t,r,i),l=await Promise.all(c.map(async t=>{if(t.renameCommit===null)return null;let n=await m1(e,t.renameCommit,r,s);return n.length===0?new Set:g1(e,n,r,o)})),u=[];for(let e=c.length-1;e>=0;e--){let t=c[e],r=l[e];if(!(r!==null&&!r.has(n)))for(let e of a(t.path))u.push({sha:n,path:e})}if(u.length===0)return null;let d=await cet(e,u);for(let e=0;e<u.length;e++)if(d[e])return u[e].path;return null}const yet=q(`history`);function bet(e){return{async saveCheckpoint(t,n){let r=n.explicitWriters,i=!1,a=e.getCurrentBranch?.()??`main`;if(r.length===0){if(n.agentWriter)r=[n.agentWriter];else{let e=(await _K(t,a)).filter(e=>!e.isPark);r=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[wK],i=!0}}let o=await jK(t,e.contentRoot??`.`,r,a,n.summary,i?{includeUpstream:!1}:void 0);yet.info({checkpointRef:o.checkpointRef},`checkpoint`);try{await v1(t,d1(t.gitDir))}catch(e){yet.warn({err:e},`[rename-log] post-saveVersion GC failed`)}return{checkpointRef:o.checkpointRef}}}}const xet=`urn:ok:error:too-many-agent-sessions`,Cet=`Too many agent sessions.`,wet=`The server is at its agent session limit, so this write was not applied and is safe to retry.`,Tet={committed:!1,retryAfterSeconds:10};function y1(e,t,n){X(e,503,xet,Cet,{handler:n,cause:t,detail:wet,extensions:{...Tet},extraHeaders:{"Retry-After":`10`}})}const Eet={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}};let Det=null;function b1(){return Det||=aG().createCounter(`ok.preview_attach.hint_emitted`,{description:`Count of preview-attach hints emitted on write-tool responses when no editor is attached to __system__. Covers both attach-preview-once (URL exists, no browser) and start-ui (no UI running anywhere) variants — the tool side disambiguates via the warning action; the metric name is retained as-is so existing dashboards keep working.`}),Det}let Oet=null;function ket(){return Oet||=aG().createCounter(`ok.frontmatter.agent_patch_fm_touch_total`,{description:"Count of agent-patch calls refused for touching the frontmatter region. Bounded labels: result ∈ {rejected, pre_deprecation_passthrough}, reason ∈ {intersect, promoted}. `intersect` is a find that MATCHED inside the existing frontmatter; `promoted` is a byte-0 replace that would CREATE frontmatter on a document that had none. They refuse for opposite reasons, so a spike in one says nothing about the other — the append/prepend surface separates the same pair via the `byte-0-promotion` class on `frontmatter-malformed-write-refused`."}),Oet}function Aet(e){let{conflicts:t,getLinkAdvisoryPolicy:n,respondStaleExternalWrite:r,requireNonEmptyDocName:i,resolveAlias:a,extractAgentIdentity:o,docNameExistsWithAnySupportedExtension:s,findMissingDocCandidates:c,contentDir:l,summaryResponseFields:u,sessionManager:d,durabilityState:p,hocuspocus:m,options:h,getBridgeLossReporter:g,agentPresenceBroadcaster:_,recordContentDivergenceGate:v,buildAgentActor:y,countNormalizedSummary:b,flushDiskAndDetectOutcome:x,respondPersistenceFailure:S,respondDiskDivergence:C,flushDocToDisk:w,agentFocusBroadcaster:T,onAgentWrite:E,computeOrphanHints:D,registerWrittenDocInFileIndex:O,prepareWriteLinkAdvisory:k,buildReconcileWarning:ee,computeLintViolations:A,log:j,flushDocToGit:M,commitOkArtifactWrite:N,isSafeDocName:te,shadowRef:ne,getPrincipal:P,contentRoot:re,safeDocPath:ie,getCurrentBranch:ae,docTreePathCandidates:oe,stripDefaultPathTruncation:se,renameAttributionCounter:ce}=e,le=bet({getCurrentBranch:ae,contentRoot:re});function ue(e){try{return m.documents.get(e)?.connections.size??0}catch{return 0}}function de(e,t,n){if(s(l,t)||(m.documents.get(t)?.getText(`source`).length??0)>0)return!1;let r=c(t);return X(e,404,`urn:ok:error:doc-not-found`,`No document at "${t}" (paths are relative to the content root). ${r.length===0?`edit only changes an existing document; use write({ document: { path, content } }) to create one.`:`Did you mean ${r.map(e=>`"${e}"`).join(` or `)}? Retry the edit at that path.`}`,{handler:n,extensions:{candidates:r,committed:!1}}),!0}function fe(){try{return m.documents.get(`__system__`)?.connections.size??0}catch{return 0}}return N$({"/api/agent-write-md":Z(f,async(e,c,f)=>{try{let e=n(),j=f.position??`append`,M=i(f.docName,c,`agent-write-md`);if(M===null)return;let N=UK(a(M)),{agentId:te,suppliedWriterId:ne,agentName:P,colorSeed:re,clientName:ie,clientVersion:ae,label:oe}=o(f);if(KK(N)||qK(N)){X(c,400,`urn:ok:error:reserved-doc-name`,`'${N}' is a reserved document name.`,{handler:`agent-write-md`});return}f.extension!==void 0&&!s(l,N)&&BK(N,f.extension);let se=_$(f.summary),{response:ce,stored:le}=u(se);await d.withSessions(async n=>{let i=await n(N,te,{displayName:P,colorSeed:re,clientName:ie}),a=r1(p,m,N,l,h.resolveEmbed,g?.(),t),o=h.resolveEmbed?{resolveEmbed:h.resolveEmbed,sourcePath:N}:void 0,s=await jZ(i.dc.document,f.markdown,j,o),u=new Date().toISOString(),d,M;try{let e=Yn(ie),t=eo[e]??ze(re??te);_?.setPresence(te,{displayName:P,icon:e,color:t,currentDoc:N,mode:`writing`,ts:Date.now()}),M=U$(i.dc.document.getText(`source`),te,i.origin,re,ie),NZ(i.dc.document,f.markdown,j),i.dc.document.transact(()=>{let e=FZ(i.dc.document);d=PZ(i.dc.document,f.markdown,j,o,s,MZ(i),ne);let t=Bc(e,FZ(i.dc.document))??void 0;i.dc.document.getMap(`agent-flash`).set(te,{agentId:te,timestamp:Date.now(),type:`insert`,description:`Added (${P}): ${f.markdown.trim().slice(0,50)}`,...t===void 0?{}:{changedBlocks:t}})},i.origin),d!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":N,position:j,intendedBytes:d.intendedBytes,actualBytes:d.actualBytes,byteDelta:d.byteDelta,"agent.id":te,"agent.client_name":ie})),v(`agent-write-md`,d),G$(N,te,P,re,void 0,y({clientName:ie,clientVersion:ae,label:oe}),le),nK(),b(se)}finally{M?.(),_?.touchMode(te,`idle`)}let de=await x(N);if(de?.kind===`failure`){S(c,de.failure,`agent-write-md`);return}if(de?.kind===`divergence`){C(c,`agent-write-md`);return}if(de?.kind===`stale-external-write`){r(c,`agent-write-md`,N);return}w(N,`agent-write-md`),T?.setFocus(te,{agentName:P,currentDoc:N,writeKind:`write`,ts:Date.now()}),E?.();let pe=await D(N),me=i.dc.document.getText(`source`).toString();O(N,me);let he=await V9e(me,N),ge=(await k([N]))(me,N,e.suppressLogLinkAdvisories),_e=ue(N),ve=fe();ve===0&&b1().add(1,{"shadow.writer":`agent`,"agent.type":qW(ie)});let ye=ee(a),be=d===void 0?void 0:MX(d),xe=[...be?[be]:[],...ye?[ye]:[],...he??[],...await A(i.dc.document.getText(`source`).toString(),N,e),...ge.warnings];Q(c,200,Dte,{timestamp:u,subscriberCount:_e,systemSubscriberCount:ve,...pe?{hints:pe}:{},...ce?{summary:ce}:{},...xe.length>0?{warnings:xe}:{},...ge.links},{handler:`agent-write-md`})})}catch(n){if(n instanceof BJ){VJ(c,n,`agent-write-md`,t.findByDocName(LK(n.file)));return}if(n instanceof MJ){o$e(c,n,`agent-write-md`);return}if(n instanceof NX){PX(c,n,`agent-write-md`);return}if(n instanceof LZ){y1(c,n,`agent-write-md`);return}j.error({err:n,requestId:DJ(e)},`[agent-write-md] handler failed`),X(c,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-md`,cause:n})}},{handler:`agent-write-md`,method:`POST`}),"/api/frontmatter-patch":Z(rre,async(e,s,c)=>{try{let e=n(),f=i(c.docName,s,`frontmatter-patch`);if(f===null)return;let v=a(f),{agentId:D,agentName:A,colorSeed:j,clientName:M,clientVersion:N,label:te}=o(c);if(KK(v)||qK(v)){X(s,400,`urn:ok:error:reserved-doc-name`,`'${v}' is a reserved document name.`,{handler:`frontmatter-patch`});return}if(de(s,v,`frontmatter-patch`))return;let ne=c.patch??{},P=Object.keys(ne),re=_$(c.summary),{response:ie,stored:ae}=u(re);await d.withSessions(async n=>{let i=await n(v,D,{displayName:A,colorSeed:j,clientName:M}),a=r1(p,m,v,l,h.resolveEmbed,g?.(),t),o=await z4e(i.dc.document,ne),c=new Date().toISOString(),u,d=!1,f=!1,oe=[];try{let e=Yn(M),t=eo[e]??ze(j??D);_?.setPresence(D,{displayName:A,icon:e,color:t,currentDoc:v,mode:`writing`,ts:Date.now()}),sG(`ok.frontmatter_patch`,{attributes:{"doc.name":v,"frontmatter_patch.keys":P.length}},()=>{i.dc.document.transact(()=>{let e=i.dc.document.getText(`source`).toString(),{fenced:t,body:n}=Ut(e),r=Ma(t,ne);if(!r.ok){u=r.error;return}for(let e of Object.keys(ne))oe.push(e);if(r.nextFenced!==t){let e=t===``&&n!==``&&!n.startsWith(`
1069
+ `)){let t=e.trim();t.length===40&&a.add(t)}r.set(t,a)}return r}function _et(e,t){for(let[n,r]of e)if(r.has(t))return n;return`main`}async function vet(e,t,n,r,i,a,o,s){let{chain:c}=net(t,r,i),l=await Promise.all(c.map(async t=>{if(t.renameCommit===null)return null;let n=await m1(e,t.renameCommit,r,s);return n.length===0?new Set:g1(e,n,r,o)})),u=[];for(let e=c.length-1;e>=0;e--){let t=c[e],r=l[e];if(!(r!==null&&!r.has(n)))for(let e of a(t.path))u.push({sha:n,path:e})}if(u.length===0)return null;let d=await cet(e,u);for(let e=0;e<u.length;e++)if(d[e])return u[e].path;return null}const yet=q(`history`);function bet(e){return{async saveCheckpoint(t,n){let r=n.explicitWriters,i=!1,a=e.getCurrentBranch?.()??`main`;if(r.length===0){if(n.agentWriter)r=[n.agentWriter];else{let e=(await _K(t,a)).filter(e=>!e.isPark);r=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[wK],i=!0}}let o=await jK(t,e.contentRoot??`.`,r,a,n.summary,i?{includeUpstream:!1}:void 0);yet.info({checkpointRef:o.checkpointRef},`checkpoint`);try{await v1(t,d1(t.gitDir))}catch(e){yet.warn({err:e},`[rename-log] post-saveVersion GC failed`)}return{checkpointRef:o.checkpointRef}}}}const xet=`urn:ok:error:too-many-agent-sessions`,Cet=`Too many agent sessions.`,wet=`The server is at its agent session limit, so this write was not applied and is safe to retry.`,Tet={committed:!1,retryAfterSeconds:10};function y1(e,t,n){X(e,503,xet,Cet,{handler:n,cause:t,detail:wet,extensions:{...Tet},extraHeaders:{"Retry-After":`10`}})}const Eet={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}};let Det=null;function b1(){return Det||=aG().createCounter(`ok.preview_attach.hint_emitted`,{description:`Count of preview-attach hints emitted on write-tool responses when no editor is attached to __system__. Covers both attach-preview-once (URL exists, no browser) and start-ui (no UI running anywhere) variants — the tool side disambiguates via the warning action; the metric name is retained as-is so existing dashboards keep working.`}),Det}let Oet=null;function ket(){return Oet||=aG().createCounter(`ok.frontmatter.agent_patch_fm_touch_total`,{description:"Count of agent-patch calls refused for touching the frontmatter region. Bounded labels: result ∈ {rejected, pre_deprecation_passthrough}, reason ∈ {intersect, promoted}. `intersect` is a find that MATCHED inside the existing frontmatter; `promoted` is a byte-0 replace that would CREATE frontmatter on a document that had none. They refuse for opposite reasons, so a spike in one says nothing about the other — the append/prepend surface separates the same pair via the `byte-0-promotion` class on `frontmatter-malformed-write-refused`."}),Oet}function Aet(e){let{conflicts:t,getLinkAdvisoryPolicy:n,respondStaleExternalWrite:r,requireNonEmptyDocName:i,resolveAlias:a,extractAgentIdentity:o,docNameExistsWithAnySupportedExtension:s,findMissingDocCandidates:c,contentDir:l,summaryResponseFields:u,sessionManager:d,durabilityState:p,hocuspocus:m,options:h,getBridgeLossReporter:g,agentPresenceBroadcaster:_,recordContentDivergenceGate:v,buildAgentActor:y,countNormalizedSummary:b,flushDiskAndDetectOutcome:x,respondPersistenceFailure:S,respondDiskDivergence:C,flushDocToDisk:w,agentFocusBroadcaster:T,onAgentWrite:E,computeOrphanHints:D,registerWrittenDocInFileIndex:O,prepareWriteLinkAdvisory:k,buildReconcileWarning:ee,computeLintViolations:A,log:j,flushDocToGit:M,flushGitCommit:N,commitOkArtifactWrite:te,isSafeDocName:ne,shadowRef:P,getPrincipal:re,contentRoot:ie,safeDocPath:ae,getCurrentBranch:oe,docTreePathCandidates:se,stripDefaultPathTruncation:ce,renameAttributionCounter:le}=e,ue=bet({getCurrentBranch:oe,contentRoot:ie});async function de(){await Promise.all([...m.documents.values()].filter(e=>!KK(e.name)&&!qK(e.name)).map(async e=>{await m.debouncer.executeNow(`onStoreDocument-${e.name}`),await e.saveMutex.waitForUnlock()})),await N?.()}function fe(e){try{return m.documents.get(e)?.connections.size??0}catch{return 0}}function pe(e,t,n){if(s(l,t)||(m.documents.get(t)?.getText(`source`).length??0)>0)return!1;let r=c(t);return X(e,404,`urn:ok:error:doc-not-found`,`No document at "${t}" (paths are relative to the content root). ${r.length===0?`edit only changes an existing document; use write({ document: { path, content } }) to create one.`:`Did you mean ${r.map(e=>`"${e}"`).join(` or `)}? Retry the edit at that path.`}`,{handler:n,extensions:{candidates:r,committed:!1}}),!0}function me(){try{return m.documents.get(`__system__`)?.connections.size??0}catch{return 0}}return N$({"/api/agent-write-md":Z(f,async(e,c,f)=>{try{let e=n(),j=f.position??`append`,M=i(f.docName,c,`agent-write-md`);if(M===null)return;let N=UK(a(M)),{agentId:te,suppliedWriterId:ne,agentName:P,colorSeed:re,clientName:ie,clientVersion:ae,label:oe}=o(f);if(KK(N)||qK(N)){X(c,400,`urn:ok:error:reserved-doc-name`,`'${N}' is a reserved document name.`,{handler:`agent-write-md`});return}f.extension!==void 0&&!s(l,N)&&BK(N,f.extension);let se=_$(f.summary),{response:ce,stored:le}=u(se);await d.withSessions(async n=>{let i=await n(N,te,{displayName:P,colorSeed:re,clientName:ie}),a=r1(p,m,N,l,h.resolveEmbed,g?.(),t),o=h.resolveEmbed?{resolveEmbed:h.resolveEmbed,sourcePath:N}:void 0,s=await jZ(i.dc.document,f.markdown,j,o),u=new Date().toISOString(),d,M;try{let e=Yn(ie),t=eo[e]??ze(re??te);_?.setPresence(te,{displayName:P,icon:e,color:t,currentDoc:N,mode:`writing`,ts:Date.now()}),M=U$(i.dc.document.getText(`source`),te,i.origin,re,ie),NZ(i.dc.document,f.markdown,j),i.dc.document.transact(()=>{let e=FZ(i.dc.document);d=PZ(i.dc.document,f.markdown,j,o,s,MZ(i),ne);let t=Bc(e,FZ(i.dc.document))??void 0;i.dc.document.getMap(`agent-flash`).set(te,{agentId:te,timestamp:Date.now(),type:`insert`,description:`Added (${P}): ${f.markdown.trim().slice(0,50)}`,...t===void 0?{}:{changedBlocks:t}})},i.origin),d!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":N,position:j,intendedBytes:d.intendedBytes,actualBytes:d.actualBytes,byteDelta:d.byteDelta,"agent.id":te,"agent.client_name":ie})),v(`agent-write-md`,d),G$(N,te,P,re,void 0,y({clientName:ie,clientVersion:ae,label:oe}),le),nK(),b(se)}finally{M?.(),_?.touchMode(te,`idle`)}let ue=await x(N);if(ue?.kind===`failure`){S(c,ue.failure,`agent-write-md`);return}if(ue?.kind===`divergence`){C(c,`agent-write-md`);return}if(ue?.kind===`stale-external-write`){r(c,`agent-write-md`,N);return}w(N,`agent-write-md`),T?.setFocus(te,{agentName:P,currentDoc:N,writeKind:`write`,ts:Date.now()}),E?.();let de=await D(N),pe=i.dc.document.getText(`source`).toString();O(N,pe);let he=await V9e(pe,N),ge=(await k([N]))(pe,N,e.suppressLogLinkAdvisories),_e=fe(N),ve=me();ve===0&&b1().add(1,{"shadow.writer":`agent`,"agent.type":qW(ie)});let ye=ee(a),be=d===void 0?void 0:MX(d),xe=[...be?[be]:[],...ye?[ye]:[],...he??[],...await A(i.dc.document.getText(`source`).toString(),N,e),...ge.warnings];Q(c,200,Dte,{timestamp:u,subscriberCount:_e,systemSubscriberCount:ve,...de?{hints:de}:{},...ce?{summary:ce}:{},...xe.length>0?{warnings:xe}:{},...ge.links},{handler:`agent-write-md`})})}catch(n){if(n instanceof BJ){VJ(c,n,`agent-write-md`,t.findByDocName(LK(n.file)));return}if(n instanceof MJ){o$e(c,n,`agent-write-md`);return}if(n instanceof NX){PX(c,n,`agent-write-md`);return}if(n instanceof LZ){y1(c,n,`agent-write-md`);return}j.error({err:n,requestId:DJ(e)},`[agent-write-md] handler failed`),X(c,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-md`,cause:n})}},{handler:`agent-write-md`,method:`POST`}),"/api/frontmatter-patch":Z(rre,async(e,s,c)=>{try{let e=n(),f=i(c.docName,s,`frontmatter-patch`);if(f===null)return;let v=a(f),{agentId:D,agentName:A,colorSeed:j,clientName:M,clientVersion:N,label:te}=o(c);if(KK(v)||qK(v)){X(s,400,`urn:ok:error:reserved-doc-name`,`'${v}' is a reserved document name.`,{handler:`frontmatter-patch`});return}if(pe(s,v,`frontmatter-patch`))return;let ne=c.patch??{},P=Object.keys(ne),re=_$(c.summary),{response:ie,stored:ae}=u(re);await d.withSessions(async n=>{let i=await n(v,D,{displayName:A,colorSeed:j,clientName:M}),a=r1(p,m,v,l,h.resolveEmbed,g?.(),t),o=await z4e(i.dc.document,ne),c=new Date().toISOString(),u,d=!1,f=!1,oe=[];try{let e=Yn(M),t=eo[e]??ze(j??D);_?.setPresence(D,{displayName:A,icon:e,color:t,currentDoc:v,mode:`writing`,ts:Date.now()}),sG(`ok.frontmatter_patch`,{attributes:{"doc.name":v,"frontmatter_patch.keys":P.length}},()=>{i.dc.document.transact(()=>{let e=i.dc.document.getText(`source`).toString(),{fenced:t,body:n}=Ut(e),r=Ma(t,ne);if(!r.ok){u=r.error;return}for(let e of Object.keys(ne))oe.push(e);if(r.nextFenced!==t){let e=t===``&&n!==``&&!n.startsWith(`
1070
1070
  `),a=he(r.nextFenced,(e?`
1071
- `:``)+n).md;dG(i.dc.document,a,`agent`,void 0,o),FX(`mcp-write`),f=!0}d=!0},i.origin)})}finally{_?.touchMode(D,`idle`)}if(u){let e;switch(u.kind){case`invalid_value`:e={[u.key]:u.reason};break;case`reserved_key`:e={[u.key]:`'${u.key}' is reserved`};break;case`unknown_key`:e={[u.key]:`'${u.key}' is not a recognized key`};break;case`duplicate_target`:e={[u.key]:`'${u.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${u.expected.join(`, `)}; got: ${u.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${u.bytes} > ${u.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${u.reason}`};break;case`invalid_path`:e={[u.path.map(String).join(`.`)||`__path__`]:u.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(u)})`}}X(s,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(d&&oe.length>0){if(G$(v,D,A,j,void 0,y({clientName:M,clientVersion:N,label:te}),ae),nK(),b(re),f){let e=await x(v);if(e?.kind===`failure`){S(s,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){C(s,`frontmatter-patch`);return}if(e?.kind===`stale-external-write`){r(s,`frontmatter-patch`,v);return}}w(v,`frontmatter-patch`)}T?.setFocus(D,{agentName:A,currentDoc:v,writeKind:`write`,ts:Date.now()}),E?.();let se=ue(v),ce=fe();ce===0&&b1().add(1,{"shadow.writer":`agent`,"agent.type":qW(M)});let le=ee(a);O(v,i.dc.document.getText(`source`).toString());let de=(await k([v]))(i.dc.document.getText(`source`).toString(),v,e.suppressLogLinkAdvisories),pe=[...le?[le]:[],...de.warnings];Q(s,200,Bre,{timestamp:c,subscriberCount:se,systemSubscriberCount:ce,appliedKeys:oe,...ie?{summary:ie}:{},...pe.length>0?{warnings:pe}:{},...de.links},{handler:`frontmatter-patch`})})}catch(t){if(t instanceof LZ){y1(s,t,`frontmatter-patch`);return}j.error({err:t,requestId:DJ(e)},`[frontmatter-patch] handler failed`),X(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:t})}},{handler:`frontmatter-patch`,method:`POST`}),"/api/agent-patch":Z(vre,async(e,s,c)=>{try{let e=n(),{find:f,replace:D,offset:j}=c,M=i(c.docName,s,`agent-patch`);if(M===null)return;let N=a(M),{agentId:te,suppliedWriterId:ne,agentName:P,colorSeed:re,clientName:ie,clientVersion:ae,label:oe}=o(c);if(KK(N)||qK(N)){X(s,400,`urn:ok:error:reserved-doc-name`,`'${N}' is a reserved document name.`,{handler:`agent-patch`});return}if(de(s,N,`agent-patch`))return;let se=_$(c.summary);await d.withSessions(async n=>{let i=await n(N,te,{displayName:P,colorSeed:re,clientName:ie}),a=r1(p,m,N,l,h.resolveEmbed,g?.(),t),o=h.resolveEmbed?{resolveEmbed:h.resolveEmbed,sourcePath:N}:void 0,c;{let e=i.dc.document.getText(`source`).toString(),{frontmatter:t,body:n}=Ba(e),r=Gi(t,n),a=j==null?r.indexOf(f):r.slice(j,j+f.length)===f?j:-1;if(a!==-1&&a>=t.length){let e=r.slice(0,a)+D+r.slice(a+f.length);c=await jZ(i.dc.document,Ba(e).body,`patch`,o)}}let d=new Date().toISOString(),M=!1,ce=!1,le=!1,de=!1,pe,me;try{let e=Yn(ie),t=eo[e]??ze(re??te);if(_?.setPresence(te,{displayName:P,icon:e,color:t,currentDoc:N,mode:`writing`,ts:Date.now()}),me=U$(i.dc.document.getText(`source`),te,i.origin,re,ie),i.dc.document.transact(()=>{let e=i.dc.document.getText(`source`).toString(),{frontmatter:t,body:n}=Ba(e),r=Gi(t,n),a=j==null?r.indexOf(f):r.slice(j,j+f.length)===f?j:-1;if(a===-1){j==null?M=!0:ce=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":N,findLength:f.length,replaceLength:D.length,hadOffset:j!=null})),kJe();return}if(a<t.length){le=!0;return}let s=r.slice(0,a)+D+r.slice(a+f.length);if(t===``&&Ba(s).frontmatter!==``){de=!0;return}let{body:l}=Ba(s),u=FZ(i.dc.document);pe=PZ(i.dc.document,l,`patch`,o,c,MZ(i),ne);let d=Bc(u,FZ(i.dc.document))??void 0;i.dc.document.getMap(`agent-flash`).set(te,{agentId:te,timestamp:Date.now(),type:`insert`,description:`Patched (${P}): ${f.slice(0,50)}`,...d===void 0?{}:{changedBlocks:d}})},i.origin),pe!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":N,position:`patch`,intendedBytes:pe.intendedBytes,actualBytes:pe.actualBytes,byteDelta:pe.byteDelta,"agent.id":te,"agent.client_name":ie})),!M&&!ce&&!le&&!de){let{stored:e}=u(se);G$(N,te,P,re,void 0,y({clientName:ie,clientVersion:ae,label:oe}),e),nK(),b(se),v(`agent-patch`,pe)}}finally{me?.(),_?.touchMode(te,`idle`)}if(ce){X(s,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(M){X(s,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(le){ket().add(1,{result:`rejected`,reason:`intersect`}),X(s,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(de){ket().add(1,{result:`rejected`,reason:`promoted`}),X(s,400,`urn:ok:error:frontmatter-edit-not-supported`,"This edit would turn the replacement text into the document's frontmatter: the document has no frontmatter, the match starts at byte 0, and `replace` opens a `---` fence pair — so the composed document would re-read that block as its YAML region. Use edit({ document: { path, frontmatter } }) to set frontmatter, or keep the `---` out of the first line (a leading blank line, or `***` / `___` for a thematic break).",{handler:`agent-patch`});return}let he=await x(N);if(he?.kind===`failure`){S(s,he.failure,`agent-patch`);return}if(he?.kind===`divergence`){C(s,`agent-patch`);return}if(he?.kind===`stale-external-write`){r(s,`agent-patch`,N);return}w(N,`agent-patch`),T?.setFocus(te,{agentName:P,currentDoc:N,writeKind:`edit`,ts:Date.now()}),E?.();let ge=ue(N),_e=fe();_e===0&&b1().add(1,{"shadow.writer":`agent`,"agent.type":qW(ie)});let{response:ve}=u(se),ye=i.dc.document.getText(`source`).toString();O(N,ye);let be=await V9e(ye,N),xe=(await k([N]))(ye,N,e.suppressLogLinkAdvisories),Se=ee(a),Ce=pe===void 0?void 0:MX(pe),we=[...Ce?[Ce]:[],...Se?[Se]:[],...be??[],...await A(i.dc.document.getText(`source`).toString(),N,e),...xe.warnings];Q(s,200,zt,{timestamp:d,subscriberCount:ge,systemSubscriberCount:_e,...ve?{summary:ve}:{},...we.length>0?{warnings:we}:{},...xe.links},{handler:`agent-patch`})})}catch(n){if(n instanceof BJ){VJ(s,n,`agent-patch`,t.findByDocName(LK(n.file)));return}if(n instanceof NX){PX(s,n,`agent-patch`);return}if(n instanceof LZ){y1(s,n,`agent-patch`);return}j.error({err:n,requestId:DJ(e)},`[agent-patch] handler failed`),X(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:n})}},{handler:`agent-patch`,method:`POST`}),"/api/agent-undo":Z(Nee,async(e,n,s)=>{try{let e=i(s.docName,n,`agent-undo`);if(e===null)return;let t=a(e),{agentId:c,agentName:l,colorSeed:u,clientName:f,clientVersion:p,label:m}=o(s);if(KK(t)||qK(t)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${t}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:g}=s,v,b;if(s.scope===`count`?(v=`count`,b=s.count):v=s.scope===`session`||s.scope===`file`?`session`:`last`,!d.hasSession(t,g)){X(n,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let w=await d.getSession(t,g),E=!1;try{let e=Yn(f),n=eo[e]??ze(u??c);_?.setPresence(c,{displayName:l,icon:e,color:n,currentDoc:t,mode:`writing`,ts:Date.now()}),E=G4e(w,v,h.resolveEmbed?{resolveEmbed:h.resolveEmbed,sourcePath:t}:void 0,b),E&&G$(t,g,l,u,void 0,y({clientName:f,clientVersion:p,label:m}))}finally{_?.touchMode(c,`idle`)}if(E){let e=await x(t);if(e?.kind===`failure`){S(n,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){C(n,`agent-undo`);return}if(e?.kind===`stale-external-write`){r(n,`agent-undo`,t);return}M(t,`agent-undo`)}T?.setFocus(g,{agentName:g,currentDoc:t,writeKind:`undo`,ts:Date.now()}),Q(n,200,Tee,{docName:t,scope:v,undone:E},{handler:`agent-undo`})}catch(r){if(r instanceof BJ){VJ(n,r,`agent-undo`,t.findByDocName(LK(r.file)));return}j.error({err:r,requestId:DJ(e)},`[agent-undo] handler failed`),X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:r})}},{handler:`agent-undo`,method:`POST`}),"/api/agent-activity":Z($a,async(e,t)=>{try{let n=WW(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(n===null){X(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}let r=e4e(d,n);Q(t,200,wte,r,{handler:`agent-activity`})}catch(n){j.error({err:n,requestId:DJ(e)},`[agent-activity] handler failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:n})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),"/api/agent-burst-diff":Z($a,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=WW(n.searchParams.get(`agentId`)),i=n.searchParams.get(`docName`),o=n.searchParams.get(`keptCount`);if(r===null){X(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!i||i.trim()===``){X(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!te(i)){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let s=a(i);if(KK(s)||qK(s)){X(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!o||Number.isNaN(Number(o))){X(t,400,`urn:ok:error:invalid-request`,`keptCount must be a number.`,{handler:`agent-burst-diff`});return}let c=Number(o);if(!Number.isInteger(c)||c<0){X(t,400,`urn:ok:error:invalid-request`,`keptCount must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let l=d.getLiveSession(s,r);if(!l){X(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let u=l.um;if(c>u.undoStack.length){X(t,404,`urn:ok:error:not-found`,`keptCount ${c} out of range (stack has ${u.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let f=l.dc.document.getText(`source`),{diff:p,before:m,after:h,properties:g}=Z2e(u.undoStack,c,f,s);Q(t,200,Ure,{diff:p,before:m,after:h,properties:g,generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(n){j.error({err:n,requestId:DJ(e)},`[agent-burst-diff] handler failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:n})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),"/api/save-version":Z(die,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=o(n),s=ne?.current;if(!s){X(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let c=/^[a-zA-Z0-9_-]+$/,l=[];if(Array.isArray(n.writers))try{l=n.writers.map(e=>{let t=e.id??`unknown`;if(!c.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){X(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let u=e===void 0?void 0:{id:r,name:a?`${i} (${a})`:i,email:`${r}@openknowledge.local`},d=_$(typeof n.summary==`string`?n.summary:void 0),f=await le.saveCheckpoint(s,{explicitWriters:l,agentWriter:u,summary:d.kind===`value`?d.value:void 0});Q(t,200,see,{checkpointRef:f.checkpointRef},{handler:`save-version`})}catch(n){j.error({err:n,requestId:DJ(e)},`[save-version] handler failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:n})}},{handler:`save-version`,method:`POST`}),"/api/rollback":Z(Vte,async(e,n,i)=>{let a=v$(i,P);if(a.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let o=t.findByDocName(i.docName);if(o!==void 0){VJ(n,new BJ({file:o.file}),`rollback`,o);return}let s=ne?.current;if(!s){X(n,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:c,commitSha:l}=i,d=re??`.`,f=ie(c,d);if(`error`in f){X(n,400,`urn:ok:error:invalid-request`,f.error,{handler:`rollback`});return}let p=gK(s),g=Date.now();try{await N(`rollback-read`);let e=d1(s.gitDir),t=p1(),i=await vet(s,c,l,ae?.()??`main`,e,e=>oe(e,d),t);if(i===null){X(n,404,`urn:ok:error:doc-not-found`,`Commit ${l.slice(0,7)} does not contain document ${c} at any known historical path.`,{handler:`rollback`});return}let o=await p.raw(`show`,`${l}:${i}`),f=new Date().toISOString();await OK(s,d,{action:`rollback`,context:{docName:c,targetSha:l}});let _=m.documents.get(c);if(!_){X(n,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let y=h.resolveEmbed?{resolveEmbed:h.resolveEmbed,sourcePath:c}:void 0,w=await JX(o,y),E;_.transact(()=>{fG(_,o,y,w),E=Z0e(_.getText(`source`).toString(),o,`rollback`)},Eet),E!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":c,position:`rollback`,intendedBytes:E.intendedBytes,actualBytes:E.actualBytes,byteDelta:E.byteDelta,"actor.kind":a.kind,...a.kind===`agent`||a.kind===`principal`?{"actor.writer_id":a.writerId}:{}})),v(`rollback`,E);let D;switch(a.kind){case`agent`:{let e=l.slice(0,8),t=a.summary.kind===`value`,n=t?a.summary:_$(`Restored to ${e}`),r=u(n);D=t||!r.response?r.response:se(r.response),G$(c,a.writerId,a.displayName,a.colorSeed,n_e(c,l),a.actor,r.stored),nK(),b(n,!t);break}case`principal`:{let e=u(a.summary);D=e.response,G$(c,a.writerId,a.displayName,a.colorSeed,n_e(c,l),a.actor,e.stored),b(a.summary,!1);break}case`anonymous`:j.debug({docName:c,commitSha:l.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(a.kind)}`)}ce().add(1,{kind:`rollback`,attribution_kind:a.kind});let O=await x(c);if(O?.kind===`failure`){S(n,O.failure,`rollback`);return}if(O?.kind===`divergence`){C(n,`rollback`);return}if(O?.kind===`stale-external-write`){r(n,`rollback`,c);return}M(c,`rollback`);let k=Date.now()-g;q(`rollback`).info({docName:c,from:l.slice(0,8),durationMs:k},`rollback`),a.kind===`agent`&&T?.setFocus(a.writerId,{agentName:a.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let ee=E===void 0?void 0:MX(E);Q(n,200,Xee,{restoredFrom:l,timestamp:f,...D?{summary:D}:{},...ee?{warnings:[ee]}:{}},{handler:`rollback`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`})},{mutating:[`/api/agent-write-md`,`/api/frontmatter-patch`,`/api/agent-patch`,`/api/agent-undo`,`/api/save-version`,`/api/rollback`]})}const x1={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},jet={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}},Met=[`document`,`server`];function Net(e){return Met.includes(e)}function Pet(e){let{agentPresence:t,resetSettingsForTest:n,settleDiskEvents:r,recentlyRemovedDocs:i,conflicts:a,durabilityState:o,resolveAlias:s,contentDir:c,log:l,sessionManager:u,hocuspocus:d,forceUnloadDocument:f,derivedDocumentIndex:p,contentFilter:m,bumpSkillsCatalogGen:h,signalChannel:g,flushGitCommit:_,rescanFiles:v}=e;async function y(e){let t=`onStoreDocument-${e}`;d.debouncer.isDebounced(t)&&await d.debouncer.executeNow(t);let n=d.documents.get(e);n&&await(f??d.unloadDocument.bind(d))(n),o.deleteReconciledBase(e),a.dissolveReconcile(e)}function b(e){return KK(e)||qK(e)}async function x(e){for(let t of d.documents.keys())t===e||b(t)||await y(t);for(let e of Object.keys(t?.getPresenceMap()??{}))t?.clearPresence(e);for(let[e]of i?.entries()??[])i?.delete(e)}function S(){let e=0;for(let t of d.documents.values())e+=t.getConnections().length;return{loadedDocuments:[...d.documents.keys()].filter(e=>!b(e)).sort(),clientConnections:e,agentSessions:u.liveSessionCount,agentPresence:Object.keys(t?.getPresenceMap()??{}).sort(),staleExternalWrites:o.listStaleExternalWrites().map(e=>e.docName).sort(),removedDocuments:(i?.entries()??[]).map(([e])=>e).sort()}}return N$({"/api/test-reset":Z($a,async(e,t)=>{try{let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`scope`)??`document`;if(!Net(a)){X(t,400,`urn:ok:error:invalid-request`,`scope must be one of ${Met.join(`, `)}.`,{handler:`test-reset`});return}if(a===`server`&&i.searchParams.has(`reset-okignore`)){X(t,400,`urn:ok:error:invalid-request`,`reset-okignore cannot be combined with scope=server: a server-scope reset always restores .okignore.`,{handler:`test-reset`});return}if(a===`server`&&n===void 0){X(t,400,`urn:ok:error:invalid-request`,`scope=server needs a server started with an isolated config home.`,{handler:`test-reset`});return}let o=UK(s(i.searchParams.get(`docName`)??`test-doc`)),f;try{f=fq(o,c)}catch(e){l.error({err:e,docName:o},`[test-reset] safeContentPath rejected docName`),X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}if(a===`server`)try{await r?.()}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`The server-scope reset did not run, because the file watcher could not settle.`,{handler:`test-reset`,detail:e instanceof Error?e.message:String(e),cause:e});return}if(await u.closeAll(a===`server`?void 0:o),d.closeConnections(a===`server`?void 0:o),await y(o),cc(f,``,`utf-8`),await p?.testOnly?.resetDocumentForTest(o),a===`server`&&(await x(o),n?.()),i.searchParams.get(`reset-okignore`)!==`false`)try{let e=W(c,`.okignore`),t=d.documents.get(xa);if(t){let e=t.getText(`source`);e.length>0&&t.transact(()=>{e.delete(0,e.length)},x1)}G(e)&&cc(e,``,`utf-8`),m&&(h(),await m.rebuildIgnorePatterns())}catch(e){l.warn({err:e},`[test-reset] okignore reset partial failure`)}g?.(`files`),Q(t,200,Jt,a===`server`?{scope:a,residue:S()}:{},{handler:`test-reset`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),"/api/test-flush-git":Z($a,async(e,t)=>{try{await _?.(),Q(t,200,Gr,{},{handler:`test-flush-git`})}catch(n){l.error({err:n,requestId:DJ(e)},`[test-flush-git] flush failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:n})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),"/api/test-rescan-backlinks":Z($a,async(e,t)=>{try{if(!p?.testOnly){X(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await p.testOnly.rescanBacklinksForTest(),Q(t,200,fee,{},{handler:`test-rescan-backlinks`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),"/api/test-rescan-files":Z($a,async(e,t)=>{try{if(!v){X(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await v(),g?.(`files`),Q(t,200,tt,{},{handler:`test-rescan-files`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0})},{mutating:[`/api/test-reset`,`/api/test-flush-git`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`]})}const Fet=Mne,Iet={claude:`claude`,codex:`codex`,cursor:`cursor-agent`,gemini:`gemini`,opencode:`opencode`,pi:`pi`,antigravity:`agy`,copilot:`copilot`,openclaw:`openclaw`,hermes:`hermes`},Let={codex:()=>H(process.env.CODEX_HOME??H(dc(),`.codex`),`auth.json`)};function Ret(e){let t=Let[e];if(t===void 0)return`unknown`;let n;try{return n=t(),G(n)?`present`:`unknown`}catch(t){return q(`acp-harness`).warn({cli:e,credentialPath:n,err:t},`harness credential probe failed; treating as unknown`),`unknown`}}async function zet(e,t,n=hQ){let r={cmd:Iet[e],args:[],env:aQ(),kind:`custom`,pathFromOverlay:!1};try{return await n(r),`present`}catch(i){if(!(i instanceof iQ)||i.code!==`command-not-found`)return q(`acp-harness`).warn({cli:e,err:i},`harness preflight failed before absence could be verified; availability unknown`),`unknown`;let a=null,o;try{a=await t()}catch(e){o=e}if(a===null)return q(`acp-harness`).warn({cli:e,err:o},`login-shell PATH capture failed; harness absence unverified — availability unknown`),`unknown`;try{return await n(E6e(r,a)),`present`}catch(t){return t instanceof iQ&&t.code===`command-not-found`?`not-found`:(q(`acp-harness`).warn({cli:e,err:t},`harness preflight on the login-shell PATH failed before absence could be verified; availability unknown`),`unknown`)}}}function Bet(e={}){let t=e.resolveLoginShellPath??eQ(q(`acp-harness`)),n=e.preflight??hQ,r=e.probe??(e=>zet(e,t,n)),i=e.credentials??Ret,a=e.now??Date.now,o=e.ttlMs??6e4,s=[...new Set(Object.values(Fet))].filter(e=>e!==void 0),c=null;return()=>{let e=a();if(c!==null&&c.expiresAt>e)return c.value;let t=Promise.all(s.map(async e=>{let t=`unknown`;try{t=i(e)}catch(t){q(`acp-harness`).warn({cli:e,err:t},`harness credential probe threw; treating as unknown`)}try{return[e,{availability:await r(e),credentials:t}]}catch(n){return q(`acp-harness`).warn({cli:e,err:n},`harness availability probe rejected; availability unknown`),[e,{availability:`unknown`,credentials:t}]}})).then(e=>Object.fromEntries(e));return c={expiresAt:e+o,value:t},t}}var Vet=class{threads=new Map;docToThreads=new Map;async build(e){this.threads.clear(),this.docToThreads.clear();for(let t of await e.scanCoverSheets())this.upsert(t)}upsert(e){let t=this.threads.get(e.threadId);t!==void 0&&t.docName!==e.docName&&this.detach(t.docName,e.threadId),this.threads.set(e.threadId,e);let n=this.docToThreads.get(e.docName);n||(n=new Set,this.docToThreads.set(e.docName,n)),n.add(e.threadId)}remove(e){let t=this.threads.get(e);t!==void 0&&(this.threads.delete(e),this.detach(t.docName,e))}renameDoc(e,t){let n=this.docToThreads.get(e);if(!n)return;this.docToThreads.delete(e);let r=this.docToThreads.get(t)??new Set;for(let e of n){r.add(e);let n=this.threads.get(e);n&&this.threads.set(e,{...n,docName:t})}this.docToThreads.set(t,r)}listForDoc(e){let t=[];for(let n of this.docToThreads.get(e)??[]){let e=this.threads.get(n);e&&t.push(e)}return t}listAll(){return[...this.threads.values()]}threadsForDoc(e){return[...this.docToThreads.get(e)??[]]}countsForDocs(e){let t=new Map;for(let n of e)t.set(n,this.countForDoc(n));return t}countsUnderPrefix(e){let t=e===``?``:e.endsWith(`/`)?e:`${e}/`,n=new Map;for(let e of this.docToThreads.keys()){if(!e.startsWith(t))continue;let r=this.countForDoc(e);r>0&&n.set(e,r)}return n}countForDoc(e){let t=0;for(let n of this.docToThreads.get(e)??[])this.threads.get(n)?.state!==`resolved`&&t++;return t}get size(){return this.threads.size}detach(e,t){let n=this.docToThreads.get(e);n&&(n.delete(t),n.size===0&&this.docToThreads.delete(e))}};function S1(e,t,n,r=32){if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n>e.length||t>=n)throw Error(`invalid selection range [${t}, ${n}) for body length ${e.length}`);let i=e.slice(t,n),a=e.slice(Math.max(0,t-r),t),o=e.slice(n,Math.min(e.length,n+r));if(Wet(e,i)>1){let s=r;for(;!Get(e,a,i,o)&&s<e.length;)s=Math.min(s*2,e.length),a=e.slice(Math.max(0,t-s),t),o=e.slice(n,Math.min(e.length,n+s))}return{exact:i,prefix:a,suffix:o,start:t,end:n}}function Het(e,t){return T1(e,t).map(e=>({start:e,end:e+t.length}))}function Uet(e,t,n,{contextIsMarkdown:r=!1}={}){let i=n.prefix??``,a=n.suffix??``,o=[],s=-1;for(let n of t){let t=Coe(e,n,{prefix:i,suffix:a},{syntaxIn:`haystack`,syntaxInContext:r});t>s?(s=t,o=[n]):t===s&&o.push(n)}return o}function C1(e,t){let{exact:n,prefix:r,suffix:i,start:a}=t,o=a+n.length;if(o<=e.length&&e.slice(a,o)===n)return{status:`anchored`,start:a,end:o};if(r!==``&&i!==``&&!e.includes(r+n+i)&&e.includes(r+i))return{status:`orphaned`};let s=T1(e,n);if(s.length===0)return w1(e,t);let c=woe(t,{syntaxInContext:!0}),l=t=>c===0||Coe(e,t,{prefix:r,suffix:i},{syntaxIn:`haystack`,syntaxInContext:!0})>=c;if(s.length===1){let r={start:s[0],end:s[0]+n.length};return l(r)?{status:`anchored`,start:r.start,end:r.end}:w1(e,t)}let u=Uet(e,s.map(e=>({start:e,end:e+n.length})),{prefix:r,suffix:i},{contextIsMarkdown:!0});if(!l(u[0]))return w1(e,t);if(u.length===1)return{status:`anchored`,start:u[0].start,end:u[0].end};let d=[],f=1/0;for(let e of u){let t=Math.abs(e.start-a);t<f?(f=t,d=[e]):t===f&&d.push(e)}return d.length===1?{status:`anchored`,start:d[0].start,end:d[0].end}:{status:`orphaned`}}function w1(e,t){let{prefix:n,suffix:r,exact:i}=t,a=n===``?[0]:T1(e,n).map(e=>e+n.length),o=r===``?[e.length]:T1(e,r);if(a.length!==1||o.length!==1)return{status:`orphaned`};let s=a[0],c=o[0];if(c<s||c===s)return{status:`orphaned`};let l=Toe(i.length);return c-s>l?{status:`orphaned`}:{status:`anchored`,start:s,end:c,rewritten:!0}}function Wet(e,t){if(t===``)return 0;let n=0,r=e.indexOf(t);for(;r!==-1;)n+=1,r=e.indexOf(t,r+1);return n}function T1(e,t){let n=[];if(t===``)return n;let r=e.indexOf(t);for(;r!==-1;)n.push(r),r=e.indexOf(t,r+1);return n}function Get(e,t,n,r){return Wet(e,t+n+r)===1}function E1(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];for(let e of n){if(r==null)return;if(typeof e==`number`){if(!Array.isArray(r)||e>=r.length)return;r=r[e];continue}if(typeof r!=`object`||Array.isArray(r))return;let t=r;if(!Object.hasOwn(t,e))return;r=t[e]}return r}function Ket(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):null}function qet(e,t){if(t===``)return!1;let n=e.indexOf(t);return n!==-1&&e.indexOf(t,n+1)!==-1}var D1=class extends Error{},O1=class extends Error{},k1=class extends Error{},A1=class extends Error{},Jet=class{store;index;getDocBody;getDocFrontmatter;now;newId;indexReady=null;constructor(e){this.store=e.store,this.index=e.index,this.getDocBody=e.getDocBody,this.getDocFrontmatter=e.getDocFrontmatter,this.now=e.now??Date.now,this.newId=e.newId??Ec}buildIndex(){return this.indexReady??=this.index.build(this.store),this.indexReady}async createThread(e){await this.buildIndex();let t=e.propertyKey,n,r;if(t===void 0){let t=await this.requireDocBody(e.docName),{start:i,end:a}=this.resolveRange(t,e);n={kind:`body`},r=S1(t,i,a)}else{let i=e.propertyPath??[];n={kind:`property`,key:t,path:i};let a=e.quote?.trim();if(a===void 0||a.length===0)await this.requirePropertyTarget(e.docName,t,i),r=null;else{let n=await this.requirePropertyText(e.docName,t,i),{start:a,end:o}=this.resolveRange(n,e);r=S1(n,a,o)}}let i=this.newId(),a=this.now(),o=await this.store.createThread({threadId:i,docName:e.docName,target:n,anchor:r,createdBy:e.author,createdAt:a,body:e.body});return this.index.upsert(o),e.queue===!0?this.mutate(i,{queued:!0}):o}async listThreads(e){return await this.buildIndex(),e===void 0?this.index.listAll():this.index.listForDoc(e)}async countThreads(e){return await this.buildIndex(),`prefix`in e?this.index.countsUnderPrefix(e.prefix):this.index.countsForDocs(e.docNames)}async readThread(e){return this.requireMeta(e)}async editComment(e,t){return this.mutate(e,{latestComment:t,updatedAt:this.now()})}async resolve(e){return this.mutate(e,{state:`resolved`})}async reopen(e){return await this.mutate(e,{state:`anchored`,queued:!0}),this.refindOnLoad(e)}async replaceAnchor(e,t){let n=await this.requireMeta(e);if(n.target.kind===`property`)throw new k1(n.target.key);let r=await this.requireDocBody(n.docName),{start:i,end:a}=this.resolveRange(r,t),o=S1(r,i,a);return this.mutate(e,{anchor:o,state:`anchored`})}async queueForDispatch(e,t){await this.mutate(e,{queued:!0});let n=await this.refindOnLoad(e,t);return{meta:n,orphaned:n.state===`orphaned`}}async prepareDispatch(e){let t=await this.getDocBody((await this.requireMeta(e)).docName),n=await this.queueForDispatch(e,t),{anchor:r,docName:i,target:a}=n.meta,o=await this.latestComment(e);return a.kind===`property`?{meta:n.meta,payload:{docName:i,instruction:o,property:j1(a.key,a.path),passage:r===null?null:{exact:r.exact,prefix:r.prefix,suffix:r.suffix},anchorLost:n.orphaned,passageRepeats:!1}}:{meta:n.meta,payload:{docName:i,instruction:o,property:null,passage:r===null?null:{exact:r.exact,prefix:r.prefix,suffix:r.suffix},anchorLost:n.orphaned,passageRepeats:r!==null&&t!==null&&qet(t,r.exact)}}}async completeDispatch(e){return this.mutate(e,{queued:!1,state:`resolved`})}async prepareDispatchBatch(e){let t=[];for(let n of e)try{let e=await this.prepareDispatch(n);t.push({threadId:n,ok:!0,...e})}catch(e){if(e instanceof O1){t.push({threadId:n,ok:!1,error:`not-found`});continue}throw e}return t}async completeDispatchBatch(e){let t=[];for(let n of e)try{t.push({threadId:n,ok:!0,meta:await this.completeDispatch(n)})}catch(e){if(e instanceof O1){t.push({threadId:n,ok:!1,error:`not-found`});continue}throw e}return t}async latestComment(e){return(await this.requireMeta(e)).latestComment.trim()}async unqueue(e){return this.mutate(e,{queued:!1})}async delete(e){await this.buildIndex(),await this.store.delete(e),this.index.remove(e)}async renameDoc(e,t){if(e===t)return;await this.buildIndex();let n=this.index.threadsForDoc(e);n.length!==0&&(this.index.renameDoc(e,t),await Promise.all(n.map(e=>this.store.update(e,{docName:t}))))}async deleteDoc(e){await this.buildIndex();let t=this.index.threadsForDoc(e);for(let e of t)await this.store.delete(e),this.index.remove(e);return t.length}async refindDoc(e){await this.buildIndex();let t=this.index.listForDoc(e).filter(e=>e.state!==`resolved`);if(t.length===0)return!1;let n=await this.getDocBody(e);if(n===null)return!1;let r=t.some(e=>e.target.kind===`property`)?await this.getDocFrontmatter(e):null,i=!1;for(let a of t){if(a.target.kind===`property`){let t=await this.refindProperty(e,a.target,a.anchor,r);if(t===null||t.state===a.state)continue;await this.mutate(a.threadId,{state:t.state}),i=!0;continue}if(a.anchor===null)continue;let t=C1(n,a.anchor);if(t.status===`orphaned`){if(a.state===`orphaned`)continue;await this.mutate(a.threadId,{state:`orphaned`}),i=!0;continue}let o=t.rewritten===!0?S1(n,t.start,t.end):void 0,s=a.state!==`anchored`;o===void 0&&!s||(await this.mutate(a.threadId,{...o?{anchor:o}:{},state:`anchored`}),(s||o!==void 0)&&(i=!0))}return i}async refindOnLoad(e,t){let n=await this.requireMeta(e);if(n.state===`resolved`)return n;if(n.target.kind===`property`){let t=await this.refindProperty(n.docName,n.target,n.anchor);return t===null||t.anchor===void 0&&t.state===n.state?n:this.mutate(e,{...t.anchor?{anchor:t.anchor}:{},state:t.state})}let r=t===void 0?await this.getDocBody(n.docName):t;if(r===null)return n;let i=n.anchor;if(i===null)return n;let a=C1(r,i);if(a.status===`orphaned`)return n.state===`orphaned`?n:this.mutate(e,{state:`orphaned`});let o=a.rewritten?S1(r,a.start,a.end):a.start!==i.start||a.end!==i.end?{...i,start:a.start,end:a.end}:void 0;return o===void 0&&n.state===`anchored`?n:this.mutate(e,{...o?{anchor:o}:{},state:`anchored`})}async mutate(e,t){let n=await this.store.update(e,t);if(!n)throw new O1(e);return this.index.upsert(n),n}resolveRange(e,t){if(t.start!==void 0&&t.end!==void 0)return{start:t.start,end:t.end};let n=t.quote?.trim();if(n===void 0||n.length===0)throw Error(`either start/end offsets or a non-empty quote is required`);let r=Het(e,n),i=r.length>0?r:boe(e,n,{syntaxIn:`haystack`});if(i.length===0)throw new A1(n);return i.length===1?i[0]:Uet(e,i,{prefix:t.prefix,suffix:t.suffix})[0]}async requireMeta(e){let t=await this.store.readMeta(e);if(!t)throw new O1(e);return t}async requireDocBody(e){let t=await this.getDocBody(e);if(t===null)throw new D1(e);return t}async requirePropertyText(e,t,n){let r=await this.getDocFrontmatter(e);if(r===null)throw new D1(e);let i=E1(r,t,n);if(i===void 0)throw new k1(j1(t,n));let a=Ket(i);if(a===null)throw new k1(j1(t,n));return a}async requirePropertyTarget(e,t,n){let r=await this.getDocFrontmatter(e);if(r===null)throw new D1(e);if(E1(r,t,n)===void 0)throw new k1(j1(t,n))}async refindProperty(e,t,n,r){let i=r===void 0?await this.getDocFrontmatter(e):r;if(i===null)return null;let a=E1(i,t.key,t.path);if(a===void 0)return{state:`orphaned`};if(n===null)return{state:`anchored`};let o=Ket(a);if(o===null)return{state:`orphaned`};let s=C1(o,n);return s.status===`orphaned`?{state:`orphaned`}:s.rewritten?{state:`anchored`,anchor:S1(o,s.start,s.end)}:s.start!==n.start||s.end!==n.end?{state:`anchored`,anchor:{...n,start:s.start,end:s.end}}:{state:`anchored`}}};function j1(e,t){let n=e;for(let e of t)n+=typeof e==`number`?`[${e}]`:`.${e}`;return n}var Yet=class{dir;log;writeQueues=new Map;dirReady=null;constructor(e,t){this.dir=H(e,`comments`),this.log=t}init(){return this.ensureDir()}ensureDir(){return this.dirReady??=EG(this.dir,{recursive:!0}).then(()=>void 0),this.dirReady}metaPath(e){return H(this.dir,`${e}.meta.json`)}enqueueResult(e,t){let n=(this.writeQueues.get(e)??Promise.resolve()).then(()=>t());return this.writeQueues.set(e,n.then(()=>void 0,()=>void 0)),n}async whenIdle(e){await(this.writeQueues.get(e)??Promise.resolve())}createThread(e){let t=va.parse({threadId:e.threadId,docName:e.docName,target:e.target,anchor:e.anchor,state:`anchored`,queued:!1,latestComment:e.body,createdBy:e.createdBy,createdAt:e.createdAt});return this.enqueueResult(e.threadId,async()=>(await this.ensureDir(),await this.write(t),t))}update(e,t){return this.enqueueResult(e,async()=>{await this.ensureDir();let n=await this.readMeta(e);if(!n)return null;let r=va.parse({...n,...Xet(t)});return await this.write(r),r})}write(e){return YS(this.metaPath(e.threadId),Zet(e),{fs:LG})}async readMeta(e){let t;try{t=await vc(this.metaPath(e),`utf8`)}catch{return null}let n=va.safeParse(Qet(t));return n.success?n.data:(this.log.warn({threadId:e},`[comments] skipping unreadable thread meta`),null)}async scanCoverSheets(){let e;try{e=await yc(this.dir)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(`.meta.json`))continue;let e=await this.readMeta(n.slice(0,-10));e&&t.push(e)}return t}async delete(e){await this.enqueueResult(e,async()=>{await wG(this.metaPath(e),{force:!0}),await wG(H(this.dir,`${e}.ndjson`),{force:!0})})}};function Xet(e){let{docName:t,anchor:n,state:r,queued:i,latestComment:a,updatedAt:o}=e;return{...t!==void 0&&{docName:t},...n!==void 0&&{anchor:n},...r!==void 0&&{state:r},...i!==void 0&&{queued:i},...a!==void 0&&{latestComment:a},...o!==void 0&&{updatedAt:o}}}function Zet(e){return`${JSON.stringify(e,null,1)}\n`}function Qet(e){try{return JSON.parse(e)}catch{return}}const M1=[`claude`,`codex`,`cursor`],N1=2e3,$et={claude:[`Claude`],codex:[`Codex`],cursor:[`Cursor`]};function ett(e){let t=new Map,n=e.now??Date.now,r=e.ttlMs??6e4;async function i(i){let a=t.get(i);if(a?.status===`resolved`&&a.expiresAt>n())return a.installed;if(a?.status===`inflight`)return a.promise;let o=(async()=>{try{let a=await e.probe(i);return t.set(i,{status:`resolved`,installed:a,expiresAt:n()+r}),a}catch{return t.set(i,{status:`resolved`,installed:!1,expiresAt:n()+r}),!1}})();return t.set(i,{status:`inflight`,promise:o}),o}async function a(){let e=await Promise.all(M1.map(async e=>[e,await i(e)]));return Object.fromEntries(e)}return{probeAll:a,probeWithCache:i}}function ttt(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return ntt(e)}catch{}let n=e.headers.origin;if(typeof n==`string`&&n.length>0)try{return ntt(new URL(n).hostname)}catch{return!1}return!0}function ntt(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function rtt(e,t,n){if(e.method!==`GET`){X(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{let r=ttt(e)?await n():Object.fromEntries(M1.map(e=>[e,!0]));Q(t,200,cn,r,{handler:`installed-agents`})}catch(e){q(`handoff`).error({err:e},`[installed-agents] handler failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function P1(e,t=Es){return n=>e===`darwin`?itt(n,t):e===`win32`?att(n,t):ott(n,t)}function itt(e,t){let n=$et[e];function r(e){return new Promise(n=>{t(`osascript`,[`-e`,`id of app "${e}"`],hq({timeout:N1,encoding:`utf-8`}),(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}return(async()=>{for(let e of n)if(await r(e))return!0;return!1})()}function att(e,t){return new Promise(n=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],hq({timeout:N1,encoding:`utf-8`}),e=>{n(!e)})})}function ott(e,t){return new Promise(n=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],hq({timeout:N1,encoding:`utf-8`}),(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}const stt=`skill-install-events.jsonl`;async function F1(e,t){let n=t?.homedir??(()=>process.env.HOME??``),r=t?.warn??((e,t)=>{q(`skills`).warn(e,t)}),i=n();if(!i){r({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let a=H(KS(i),stt),o=`${JSON.stringify(e)}\n`;try{await EG(V(a),{recursive:!0})}catch(e){r({event:`skill-install-events.mkdir-failed`,err:e},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await SG(a,o,{flag:`a`,encoding:`utf-8`})}catch(e){r({event:`skill-install-events.append-failed`,err:e},`[skill-install-events] append failed; telemetry skipped`)}}function ctt(){return Sa.parse({}).telemetry.skillInstallReports.enabled}function I1(e){let t=e??dc(),n;try{n=QS(`user`,t,t)}catch(e){return q(`skills`).warn({err:e},`could not resolve the user config path; not reporting`),{enabled:!1,home:t}}if(!G(n))return{enabled:ctt(),home:t};try{let e=(0,Wc.parse)(K(n,`utf-8`))?.telemetry?.skillInstallReports?.enabled;return{enabled:typeof e==`boolean`?e:ctt(),home:t}}catch(e){return q(`skills`).warn({err:e,path:n},`user config exists but could not be read; not reporting skill installs`),{enabled:!1,home:t}}}function L1(){let e=new Map;return(t,n)=>{let r=(e.get(t)??Promise.resolve()).then(n,n);return e.set(t,r.then(()=>void 0,()=>void 0)),r}}const ltt=[`.ok`,yr,Fte];function R1(e){return H(e,...ltt)}function utt(e){let t=e;for(;!G(t);){let e=V(t);if(e===t)return null;t=e}return t}function dtt(e){let t=e;for(;;)try{return oc(t),t}catch(e){let n=e.code;if(n!==`ENOENT`&&n!==`ENOTDIR`)throw e;let r=V(t);if(r===t)return null;t=r}}function ftt(e,t,n){if(t.length===0||t.includes(`\0`)||Ps(t)||t.split(/[/\\]/).some(e=>e===`..`))return null;let r=W(e),i=W(r,t);if(i===r||!i.startsWith(`${r}${Rs}`))return null;let a=nc(r),o=n(i);if(o===null)return null;let s=nc(o);return s!==a&&!s.startsWith(`${a}${Rs}`)?null:i}function ptt(e,t){return ftt(e,t,dtt)}function z1(e,t){try{return ftt(e,t,utt)}catch{return null}}function B1(){return{schema:1,skills:{}}}function mtt(e,t,n){if(!t||typeof t!=`object`)return!1;let r=t;return typeof r.path==`string`&&n(e,r.path)!==null&&(r.mode===`copy`||r.mode===`link`)&&(r.hash===void 0||typeof r.hash==`string`)}function htt(e){if(!e||typeof e!=`object`)return;let t=Object.entries(e).filter(e=>e[1]===`copy`||e[1]===`link`);return t.length>0?Object.fromEntries(t):void 0}function gtt(e){if(!e||typeof e!=`object`)return;let t=Object.entries(e).filter(e=>typeof e[1]==`string`&&e[1]!==``);return t.length>0?Object.fromEntries(t):void 0}function _tt(e,t,n){if(!t||typeof t!=`object`)return;let r=[];for(let[i,a]of Object.entries(t)){if(n(e,i)===null||!a||typeof a!=`object`)continue;let t=a;t.expect===`own`?r.push([i,{expect:`own`}]):t.expect===`link`&&typeof t.target==`string`&&n(e,t.target)!==null&&r.push([i,{expect:`link`,target:t.target}])}return r.length>0?Object.fromEntries(r):void 0}function V1(e,t,n=z1){let r={};if(t.skills&&typeof t.skills==`object`)for(let[i,a]of Object.entries(t.skills)){if(!Array.isArray(a))continue;let t=a.filter(t=>mtt(e,t,n));t.length>0&&(r[i]=t)}let i=Array.isArray(t.roots)?t.roots.filter(t=>typeof t==`string`&&n(e,t)!==null):[],a=htt(t.preferences),o=gtt(t.sources),s=_tt(e,t.folders,n);return{schema:1,skills:r,...a?{preferences:a}:{},...o?{sources:o}:{},...i.length>0?{roots:i}:{},...s?{folders:s}:{}}}function H1(e){let t=R1(e);if(!G(t))return B1();try{let n=JSON.parse(K(t,`utf-8`));return!n||typeof n!=`object`?B1():V1(e,n)}catch(e){return q(`skill-placements`).warn({err:e,path:t},`skill-placements.json is unreadable; continuing with an empty ledger (recorded placements for this project are lost)`),B1()}}function vtt(e,t){let n=R1(e);try{oc(n)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return{kind:`read`,store:B1()};throw e}let r=K(n,`utf-8`),i;try{i=JSON.parse(r)}catch(e){return q(`skill-placements`).warn({err:e,path:n},`skill-placements.json is not valid JSON; skill scans read no recorded roots or sources from it, and in-place skill refreshes keep the prior admission of the skills it decides`),{kind:`unparsable`,error:e}}return!i||typeof i!=`object`?{kind:`read`,store:B1()}:{kind:`read`,store:V1(e,i,t)}}function ytt(e){let t=R1(e);if(!G(t))return{ok:!0,store:B1()};let n;try{n=K(t,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?{ok:!0,store:B1()}:{ok:!1,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}let r;try{r=JSON.parse(n)}catch(e){return{ok:!1,reason:`it is not valid JSON`,cause:e}}if(typeof r!=`object`||!r||Array.isArray(r))return{ok:!1,reason:`its contents are not a placements ledger`};let i=r.schema;return i!==void 0&&i!==1?{ok:!1,reason:typeof i==`number`?`it declares schema ${i}, which this server does not understand (it writes schema 1)`:`it declares an unsupported schema value`}:{ok:!0,store:V1(e,r)}}const btt=L1();function U1(e,t){return btt(R1(e),async()=>{let n=ytt(e);if(!n.ok){let t=R1(e);throw q(`skill-placements`).error({path:t,reason:n.reason,err:n.cause},`refusing to rewrite skill-placements.json because it could not be read — rewriting it would replace every placement it records with this one`),Error(`Refusing to rewrite ${t}: ${n.reason}`)}let r=n.store;t(r),await xtt(e,r)})}async function xtt(e,t){let n=R1(e);await EG(V(n),{recursive:!0}),await YS(n,`${JSON.stringify(t,null,2)}\n`,{fs:LG})}function Stt(e,t,n){let r=new Set(t.roots??[]);for(let i of Object.values(t.skills))for(let t of i){let i=t.path.split(`/`).slice(0,-1).join(`/`);i!==``&&n(e,i)!==null&&r.add(i)}return[...r].sort()}function Ctt(e){return Stt(e,H1(e),z1)}function wtt(e){let t=[],n=(e,n)=>{try{return ptt(e,n)}catch(e){return t.push(e),null}},r;try{r=vtt(e,n)}catch(t){return q(`skill-placements`).warn({err:t,path:R1(e)},`skill-placements.json could not be read; skill scans read no recorded roots or sources from it, and in-place skill refreshes keep their prior admission`),{kind:`incomplete`,roots:[],sources:{},error:t}}if(r.kind===`unparsable`)return{kind:`unparsable`,roots:[],sources:{},error:r.error};let{store:i}=r,a=Stt(e,i,n),o=i.sources??{};return t.length===0?{kind:`complete`,roots:a,sources:o}:{kind:`incomplete`,roots:a,sources:o,error:t[0]}}const Ttt=new Set([400,404,410,422]),Ett=[`.local`,`.internal`,`.intranet`,`.corp`,`.home`,`.home.arpa`,`.lan`,`.private`,`.test`,`.invalid`,`.localhost`,`.localdomain`];function Dtt(e){let t=e.split(`/`);return t.length===1?/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(e)?!Ett.some(t=>e.toLowerCase().endsWith(t)):!1:t.length===2&&t.every(e=>/^[\w.-]+$/.test(e)&&e!==`.`&&e!==`..`)}function W1(e,t){if(e.scope===void 0)return`${e.source}#${t}`;let n=e.scope;try{n=nc(n)}catch{}return`${e.source}#${t}@${n}`}function Ott(e=process.env){return!!(e.DISABLE_TELEMETRY||e.DO_NOT_TRACK)}async function G1(e,t){let n=t.env??process.env;if(!t.enabled||Ott(n)||!Dtt(e.source.trim()))return[];let r=await S7e(t.home).catch(t=>(q(`skills`).warn({err:t,source:e.source},`could not read the install-report ledger; a duplicate report is possible`),new Set)),i=e.skills.filter(t=>!r.has(W1(e,t)));if(i.length===0)return[];let a=new URLSearchParams({event:`install`,source:e.source,skills:i.join(`,`)});e.agents&&e.agents.length>0&&a.set(`agents`,e.agents.join(`,`)),e.global&&a.set(`global`,`1`),e.version&&a.set(`v`,e.version);let o=t.fetchImpl??globalThis.fetch;if(!o)return[];try{await C7e(t.home,i.map(t=>W1(e,t)))}catch(t){return q(`skills`).warn({err:t,source:e.source,skills:i},`skill install report ledger write failed; not reporting this install`),[]}try{let n=await o(`https://add-skill.vercel.sh/t?${a.toString()}`,{signal:AbortSignal.timeout(3e3)});if(!n.ok&&Ttt.has(n.status))return q(`skills`).warn({status:n.status,source:e.source,skills:i},`skill install report rejected by the collector; releasing the claim to retry later`),await w7e(t.home,i.map(t=>W1(e,t))).catch(t=>{q(`skills`).warn({err:t,status:n.status,source:e.source,skills:i},`could not release the install-report claim; this install will not be retried`)}),[];n.ok||q(`skills`).warn({status:n.status,source:e.source,skills:i},`skill install report rejected with an ambiguous status; keeping the claim so a counted install cannot be double-reported`)}catch(t){q(`skills`).warn({err:t,source:e.source,skills:i},`skill install report could not be delivered; this install is not counted`)}return i}const K1=`.agents`;function ktt(e,t){return H(e,K1,`skills`,t)}function q1(e){return rte.filter(t=>G(H(e,t.hostDir)))}function Att(e){let t=q1(e).map(e=>({editor:e.editorId,skillsRoot:e.skillsRoot,custom:!1})),n=new Set(t.map(e=>e.skillsRoot)),r=Ctt(e).filter(t=>!n.has(t)&&G(H(e,t))).map(e=>({editor:e,skillsRoot:e,custom:!0}));return[...t,...r]}function jtt(e){return ra.filter(t=>{let n=Vi[t];return n!==null&&G(H(e,Qa(n)))})}async function Mtt(e,t){let n=q1(e).map(n=>H(e,n.skillsRoot,t));G(H(e,K1))&&n.push(ktt(e,t));for(let e of n)try{if((await Sc(e)).isDirectory())return!0}catch{}return!1}function Ntt(e,t,n){let r=[...t.map(e=>e.skillsRoot),`${K1}/skills`];for(let t of r){let r=H(e,t,`open-knowledge`);if(G(r))try{FG(r,{recursive:!0,force:!0}),n.info?.({event:`skill-install.legacy-removed`,path:r},"Removed pre-split `open-knowledge` user-global skill dir.")}catch(e){n.warn({event:`skill-install.legacy-remove-failed`,path:r,err:e},"Legacy `open-knowledge` skill removal failed; continuing with install.")}}}function Ptt(e,t){FG(t,{recursive:!0,force:!0}),kG(V(t),{recursive:!0}),jG(e,t,{recursive:!0})}function Ftt(e,t,n,r,i){let a=[],o=ktt(e,t),s=[...i?[o]:[],...r.map(n=>H(e,n.skillsRoot,t)).filter(e=>e!==o)];for(let e of s)try{Ptt(n,e),a.push({path:e,status:`written`})}catch(t){a.push({path:e,status:`failed`,error:t instanceof Error?t.message:String(t)})}return a}async function Itt(e={}){let t=e.home??dc(),n=e.logger??{warn:(e,t)=>q(`skills`).warn(e,t),info:(e,t)=>q(`skills`).info(e,t)},r=e.surface??`cli-npx-skills-add`,i=e.bundleId??`discovery`,a=RZ[i];if(!Ps(t))return n.warn({event:`skill-install.failed`,reason:`home-not-absolute`,home:t},`Skill install aborted — $HOME is not an absolute path.`),`failed`;let o=async(e,a,o)=>{await F1({ts:new Date().toISOString(),surface:r,target:`cli-hosts`,bundle:i,outcome:e,...a===void 0?{}:{version:a},...o===void 0?{}:{reason:o}},{homedir:()=>t,warn:n.warn})},s;try{s=await b7e(t,a,n)}catch(e){return n.warn({event:`skill-install.gate.decision-read-failed`,bundle:i,err:e},`Could not read the opt-out decision; skipping the install rather than risk reversing it.`),await o(`skip-current`,void 0,`decision-read-failed`),`skip-current`}if(s===!1)return n.info?.({event:`skill-install.declined`,bundle:i},`Bundle is opted out; skipping user-global skill install.`),await o(`skip-current`,void 0,`declined`),`skip-current`;let c;try{c=await g$()}catch(e){return n.warn({event:`skill-install.failed`,reason:`version-read-failed`,err:e},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await o(`failed`,void 0,`version-read-failed`),`failed`}let l=await m$(t,`cli-hosts`,n).catch(e=>(n.warn({event:`skill-install.gate.read-failed`,err:e},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(!e.force&&l!==null&&l===c){if(await Mtt(t,a))return n.info?.({event:`skill-install.skip-current`,version:c},`OpenKnowledge skill already installed at current version; skipping.`),await o(`skip-current`,c),`skip-current`;n.info?.({event:`skill-install.reinstall-missing`,version:c},`Sidecar matches current version but skill files are missing; reinstalling.`)}let u;try{u=WZ(i,{checkDesktop:!1})}catch(e){return n.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,err:e},`Skill install aborted — bundled SKILL.md asset not found.`),await o(`failed`,c,`bundled-asset-missing`),`failed`}let d=q1(t),f=G(H(t,K1));if(d.length===0&&!f)return n.info?.({event:`skill-install.no-hosts`,version:c},`No supported agent host detected; skipping user-global skill install.`),await o(`skip-current`,c,`no-hosts`),`no-hosts`;Ntt(t,d,n);let p=Ftt(t,a,u,d,f),m=p.filter(e=>e.status===`written`),h=p.filter(e=>e.status===`failed`);if(m.length===0)return n.warn({event:`skill-install.failed`,reason:`write-failed`,entries:h},`Skill install failed — every destination write errored.`),await o(`failed`,c,`write-failed`),`failed`;try{await h$(t,`cli-hosts`,c,r,n)}catch(e){return n.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,err:e},`Skill install succeeded but sidecar write failed.`),await o(`failed`,c,`sidecar-write-failed`),`failed`}return h.length>0&&n.warn({event:`skill-install.partial`,version:c,entries:h},`Some agent hosts could not be written; the remaining copies are installed.`),n.info?.({event:`skill-install.installed`,version:c,hosts:d.map(e=>e.editorId),paths:m.map(e=>e.path)},`OpenKnowledge skill installed to ${m.length} location(s): ${m.map(e=>e.path).join(`, `)}`),await o(`installed`,c),G1({source:Qe,skills:[a],agents:d.map(e=>e.editorId),global:!0,version:c},{home:t,enabled:I1(t).enabled}),`installed`}function Ltt(e){return H(e,`Downloads`,`openknowledge.skill`)}function Rtt(e,t,n){let r=hq({detached:!0,stdio:`ignore`});try{return t===`darwin`?(n(`open`,[e],r).unref(),{ok:!0}):t===`win32`?(n(`cmd`,[`/c`,`start`,`""`,e],r).unref(),{ok:!0}):t===`linux`?(n(`xdg-open`,[e],r).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function ztt(e={}){let t=e.home??dc(),n=W(e.out??Ltt(t)),r=e.platformName??pc(),i=e.spawnFn??Os,a=e.logger,o=async(e,n,r)=>{await F1({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...n===void 0?{}:{version:n},...r===void 0?{}:{reason:r}},{homedir:()=>t,warn:a?.warn})};if(!e.force){let e=null;try{e=await g$()}catch(e){a?.warn?.({event:`skill-install.gate.version-read-failed`,err:e},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let n=null,r=null;try{[n,r]=await Promise.all([m$(t,`claude-cowork`,a),y7e(t,`claude-cowork`,a)])}catch(e){a?.warn?.({event:`skill-install.gate.read-failed`,err:e},`Could not read claude-cowork install-state; rebuilding.`)}if(n!==null&&n===e)return a?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`OpenKnowledge skill already delivered at current version; skipping rebuild.`),await o(`skip-current`,e),{status:`skip-current`,skillVersion:e,...r===null?{}:{recordedAt:r}}}}try{await EG(V(n),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await o(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let s;try{s=await h3e({outputPath:n,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await o(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let c;try{c=await g$()}catch{c=void 0}let l={status:`built`,outputPath:s.outputPath,size:s.size,sha256:s.sha256,skillVersion:c};if(c)try{await h$(t,`claude-cowork`,c,`server-build-and-open`,a)}catch(e){a?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:c,err:e},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await o(`built`,c),l;let u=Rtt(s.outputPath,r,i);return u.ok?(await o(`installed`,c),G1({source:Qe,skills:[RZ.project],agents:[`claude-desktop`],global:!0,version:c},{home:t,enabled:I1(t).enabled}),{...l,status:`installed`}):(await o(`built`,c,`handoff-${u.reason}`),{...l,handoffError:{reason:u.reason,message:u.message}})}function Btt(e){let{checkLocalOpSecurity:t}=e;return N$({"/api/install-skill":Z(fie,async(e,t,n)=>{if(n.out!==void 0&&!M$(n.out)){X(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{let e=await ztt({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}});Q(t,200,Br,e,{handler:`install-skill`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,n)=>t(e,n,{handler:`install-skill`})})},{mutating:[`/api/install-skill`]})}const Vtt=1024,Htt=[`anthropic`,`claude`],J1=`SKILL.md`;function Utt(e){let t=n0(e.name);if(!t.ok)return{ok:!1,error:t.error};let n=Jtt(e.frontmatter,e.name);if(!n.ok)return{ok:!1,error:n.error};let r=`---\n${Xtt(e.frontmatter)}---\n${e.body}`,i=[],a=[],o=Htt.filter(t=>e.name.includes(t));o.length>0&&(i.push(`Skill name contains ${o.map(e=>`"${e}"`).join(`, `)} — Anthropic's authoring guidance discourages vendor words in skill names.`),a.push(`skill-name-vendor-word`));let s=e.body.split(`
1071
+ `:``)+n).md;dG(i.dc.document,a,`agent`,void 0,o),FX(`mcp-write`),f=!0}d=!0},i.origin)})}finally{_?.touchMode(D,`idle`)}if(u){let e;switch(u.kind){case`invalid_value`:e={[u.key]:u.reason};break;case`reserved_key`:e={[u.key]:`'${u.key}' is reserved`};break;case`unknown_key`:e={[u.key]:`'${u.key}' is not a recognized key`};break;case`duplicate_target`:e={[u.key]:`'${u.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${u.expected.join(`, `)}; got: ${u.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${u.bytes} > ${u.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${u.reason}`};break;case`invalid_path`:e={[u.path.map(String).join(`.`)||`__path__`]:u.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(u)})`}}X(s,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(d&&oe.length>0){if(G$(v,D,A,j,void 0,y({clientName:M,clientVersion:N,label:te}),ae),nK(),b(re),f){let e=await x(v);if(e?.kind===`failure`){S(s,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){C(s,`frontmatter-patch`);return}if(e?.kind===`stale-external-write`){r(s,`frontmatter-patch`,v);return}}w(v,`frontmatter-patch`)}T?.setFocus(D,{agentName:A,currentDoc:v,writeKind:`write`,ts:Date.now()}),E?.();let se=fe(v),ce=me();ce===0&&b1().add(1,{"shadow.writer":`agent`,"agent.type":qW(M)});let le=ee(a);O(v,i.dc.document.getText(`source`).toString());let ue=(await k([v]))(i.dc.document.getText(`source`).toString(),v,e.suppressLogLinkAdvisories),de=[...le?[le]:[],...ue.warnings];Q(s,200,Bre,{timestamp:c,subscriberCount:se,systemSubscriberCount:ce,appliedKeys:oe,...ie?{summary:ie}:{},...de.length>0?{warnings:de}:{},...ue.links},{handler:`frontmatter-patch`})})}catch(t){if(t instanceof LZ){y1(s,t,`frontmatter-patch`);return}j.error({err:t,requestId:DJ(e)},`[frontmatter-patch] handler failed`),X(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:t})}},{handler:`frontmatter-patch`,method:`POST`}),"/api/agent-patch":Z(vre,async(e,s,c)=>{try{let e=n(),{find:f,replace:D,offset:j}=c,M=i(c.docName,s,`agent-patch`);if(M===null)return;let N=a(M),{agentId:te,suppliedWriterId:ne,agentName:P,colorSeed:re,clientName:ie,clientVersion:ae,label:oe}=o(c);if(KK(N)||qK(N)){X(s,400,`urn:ok:error:reserved-doc-name`,`'${N}' is a reserved document name.`,{handler:`agent-patch`});return}if(pe(s,N,`agent-patch`))return;let se=_$(c.summary);await d.withSessions(async n=>{let i=await n(N,te,{displayName:P,colorSeed:re,clientName:ie}),a=r1(p,m,N,l,h.resolveEmbed,g?.(),t),o=h.resolveEmbed?{resolveEmbed:h.resolveEmbed,sourcePath:N}:void 0,c;{let e=i.dc.document.getText(`source`).toString(),{frontmatter:t,body:n}=Ba(e),r=Gi(t,n),a=j==null?r.indexOf(f):r.slice(j,j+f.length)===f?j:-1;if(a!==-1&&a>=t.length){let e=r.slice(0,a)+D+r.slice(a+f.length);c=await jZ(i.dc.document,Ba(e).body,`patch`,o)}}let d=new Date().toISOString(),M=!1,ce=!1,le=!1,ue=!1,de,pe;try{let e=Yn(ie),t=eo[e]??ze(re??te);if(_?.setPresence(te,{displayName:P,icon:e,color:t,currentDoc:N,mode:`writing`,ts:Date.now()}),pe=U$(i.dc.document.getText(`source`),te,i.origin,re,ie),i.dc.document.transact(()=>{let e=i.dc.document.getText(`source`).toString(),{frontmatter:t,body:n}=Ba(e),r=Gi(t,n),a=j==null?r.indexOf(f):r.slice(j,j+f.length)===f?j:-1;if(a===-1){j==null?M=!0:ce=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":N,findLength:f.length,replaceLength:D.length,hadOffset:j!=null})),kJe();return}if(a<t.length){le=!0;return}let s=r.slice(0,a)+D+r.slice(a+f.length);if(t===``&&Ba(s).frontmatter!==``){ue=!0;return}let{body:l}=Ba(s),u=FZ(i.dc.document);de=PZ(i.dc.document,l,`patch`,o,c,MZ(i),ne);let d=Bc(u,FZ(i.dc.document))??void 0;i.dc.document.getMap(`agent-flash`).set(te,{agentId:te,timestamp:Date.now(),type:`insert`,description:`Patched (${P}): ${f.slice(0,50)}`,...d===void 0?{}:{changedBlocks:d}})},i.origin),de!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":N,position:`patch`,intendedBytes:de.intendedBytes,actualBytes:de.actualBytes,byteDelta:de.byteDelta,"agent.id":te,"agent.client_name":ie})),!M&&!ce&&!le&&!ue){let{stored:e}=u(se);G$(N,te,P,re,void 0,y({clientName:ie,clientVersion:ae,label:oe}),e),nK(),b(se),v(`agent-patch`,de)}}finally{pe?.(),_?.touchMode(te,`idle`)}if(ce){X(s,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(M){X(s,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(le){ket().add(1,{result:`rejected`,reason:`intersect`}),X(s,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(ue){ket().add(1,{result:`rejected`,reason:`promoted`}),X(s,400,`urn:ok:error:frontmatter-edit-not-supported`,"This edit would turn the replacement text into the document's frontmatter: the document has no frontmatter, the match starts at byte 0, and `replace` opens a `---` fence pair — so the composed document would re-read that block as its YAML region. Use edit({ document: { path, frontmatter } }) to set frontmatter, or keep the `---` out of the first line (a leading blank line, or `***` / `___` for a thematic break).",{handler:`agent-patch`});return}let he=await x(N);if(he?.kind===`failure`){S(s,he.failure,`agent-patch`);return}if(he?.kind===`divergence`){C(s,`agent-patch`);return}if(he?.kind===`stale-external-write`){r(s,`agent-patch`,N);return}w(N,`agent-patch`),T?.setFocus(te,{agentName:P,currentDoc:N,writeKind:`edit`,ts:Date.now()}),E?.();let ge=fe(N),_e=me();_e===0&&b1().add(1,{"shadow.writer":`agent`,"agent.type":qW(ie)});let{response:ve}=u(se),ye=i.dc.document.getText(`source`).toString();O(N,ye);let be=await V9e(ye,N),xe=(await k([N]))(ye,N,e.suppressLogLinkAdvisories),Se=ee(a),Ce=de===void 0?void 0:MX(de),we=[...Ce?[Ce]:[],...Se?[Se]:[],...be??[],...await A(i.dc.document.getText(`source`).toString(),N,e),...xe.warnings];Q(s,200,zt,{timestamp:d,subscriberCount:ge,systemSubscriberCount:_e,...ve?{summary:ve}:{},...we.length>0?{warnings:we}:{},...xe.links},{handler:`agent-patch`})})}catch(n){if(n instanceof BJ){VJ(s,n,`agent-patch`,t.findByDocName(LK(n.file)));return}if(n instanceof NX){PX(s,n,`agent-patch`);return}if(n instanceof LZ){y1(s,n,`agent-patch`);return}j.error({err:n,requestId:DJ(e)},`[agent-patch] handler failed`),X(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:n})}},{handler:`agent-patch`,method:`POST`}),"/api/agent-undo":Z(Nee,async(e,n,s)=>{try{let e=i(s.docName,n,`agent-undo`);if(e===null)return;let t=a(e),{agentId:c,agentName:l,colorSeed:u,clientName:f,clientVersion:p,label:m}=o(s);if(KK(t)||qK(t)){X(n,400,`urn:ok:error:reserved-doc-name`,`'${t}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:g}=s,v,b;if(s.scope===`count`?(v=`count`,b=s.count):v=s.scope===`session`||s.scope===`file`?`session`:`last`,!d.hasSession(t,g)){X(n,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let w=await d.getSession(t,g),E=!1;try{let e=Yn(f),n=eo[e]??ze(u??c);_?.setPresence(c,{displayName:l,icon:e,color:n,currentDoc:t,mode:`writing`,ts:Date.now()}),E=G4e(w,v,h.resolveEmbed?{resolveEmbed:h.resolveEmbed,sourcePath:t}:void 0,b),E&&G$(t,g,l,u,void 0,y({clientName:f,clientVersion:p,label:m}))}finally{_?.touchMode(c,`idle`)}if(E){let e=await x(t);if(e?.kind===`failure`){S(n,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){C(n,`agent-undo`);return}if(e?.kind===`stale-external-write`){r(n,`agent-undo`,t);return}M(t,`agent-undo`)}T?.setFocus(g,{agentName:g,currentDoc:t,writeKind:`undo`,ts:Date.now()}),Q(n,200,Tee,{docName:t,scope:v,undone:E},{handler:`agent-undo`})}catch(r){if(r instanceof BJ){VJ(n,r,`agent-undo`,t.findByDocName(LK(r.file)));return}j.error({err:r,requestId:DJ(e)},`[agent-undo] handler failed`),X(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:r})}},{handler:`agent-undo`,method:`POST`}),"/api/agent-activity":Z($a,async(e,t)=>{try{let n=WW(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(n===null){X(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}let r=e4e(d,n);Q(t,200,wte,r,{handler:`agent-activity`})}catch(n){j.error({err:n,requestId:DJ(e)},`[agent-activity] handler failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:n})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),"/api/agent-burst-diff":Z($a,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=WW(n.searchParams.get(`agentId`)),i=n.searchParams.get(`docName`),o=n.searchParams.get(`keptCount`);if(r===null){X(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!i||i.trim()===``){X(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!ne(i)){X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let s=a(i);if(KK(s)||qK(s)){X(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!o||Number.isNaN(Number(o))){X(t,400,`urn:ok:error:invalid-request`,`keptCount must be a number.`,{handler:`agent-burst-diff`});return}let c=Number(o);if(!Number.isInteger(c)||c<0){X(t,400,`urn:ok:error:invalid-request`,`keptCount must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let l=d.getLiveSession(s,r);if(!l){X(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let u=l.um;if(c>u.undoStack.length){X(t,404,`urn:ok:error:not-found`,`keptCount ${c} out of range (stack has ${u.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let f=l.dc.document.getText(`source`),{diff:p,before:m,after:h,properties:g}=Z2e(u.undoStack,c,f,s);Q(t,200,Ure,{diff:p,before:m,after:h,properties:g,generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(n){j.error({err:n,requestId:DJ(e)},`[agent-burst-diff] handler failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:n})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),"/api/save-version":Z(die,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=o(n),s=P?.current;if(!s){X(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let c=/^[a-zA-Z0-9_-]+$/,l=[];if(Array.isArray(n.writers))try{l=n.writers.map(e=>{let t=e.id??`unknown`;if(!c.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){X(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let u=e===void 0?void 0:{id:r,name:a?`${i} (${a})`:i,email:`${r}@openknowledge.local`},d=_$(typeof n.summary==`string`?n.summary:void 0);await de();let f=await ue.saveCheckpoint(s,{explicitWriters:l,agentWriter:u,summary:d.kind===`value`?d.value:void 0});Q(t,200,see,{checkpointRef:f.checkpointRef},{handler:`save-version`})}catch(n){j.error({err:n,requestId:DJ(e)},`[save-version] handler failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:n})}},{handler:`save-version`,method:`POST`}),"/api/rollback":Z(Vte,async(e,n,i)=>{let a=v$(i,re);if(a.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let o=t.findByDocName(i.docName);if(o!==void 0){VJ(n,new BJ({file:o.file}),`rollback`,o);return}let s=P?.current;if(!s){X(n,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:c,commitSha:l}=i,d=ie??`.`,f=ae(c,d);if(`error`in f){X(n,400,`urn:ok:error:invalid-request`,f.error,{handler:`rollback`});return}let p=gK(s),g=Date.now();try{await te(`rollback-read`);let e=d1(s.gitDir),t=p1(),i=await vet(s,c,l,oe?.()??`main`,e,e=>se(e,d),t);if(i===null){X(n,404,`urn:ok:error:doc-not-found`,`Commit ${l.slice(0,7)} does not contain document ${c} at any known historical path.`,{handler:`rollback`});return}let o=await p.raw(`show`,`${l}:${i}`),f=new Date().toISOString();await OK(s,d,{action:`rollback`,context:{docName:c,targetSha:l}});let _=m.documents.get(c);if(!_){X(n,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let y=h.resolveEmbed?{resolveEmbed:h.resolveEmbed,sourcePath:c}:void 0,w=await JX(o,y),E;_.transact(()=>{fG(_,o,y,w),E=Z0e(_.getText(`source`).toString(),o,`rollback`)},Eet),E!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":c,position:`rollback`,intendedBytes:E.intendedBytes,actualBytes:E.actualBytes,byteDelta:E.byteDelta,"actor.kind":a.kind,...a.kind===`agent`||a.kind===`principal`?{"actor.writer_id":a.writerId}:{}})),v(`rollback`,E);let D;switch(a.kind){case`agent`:{let e=l.slice(0,8),t=a.summary.kind===`value`,n=t?a.summary:_$(`Restored to ${e}`),r=u(n);D=t||!r.response?r.response:ce(r.response),G$(c,a.writerId,a.displayName,a.colorSeed,n_e(c,l),a.actor,r.stored),nK(),b(n,!t);break}case`principal`:{let e=u(a.summary);D=e.response,G$(c,a.writerId,a.displayName,a.colorSeed,n_e(c,l),a.actor,e.stored),b(a.summary,!1);break}case`anonymous`:j.debug({docName:c,commitSha:l.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(a.kind)}`)}le().add(1,{kind:`rollback`,attribution_kind:a.kind});let O=await x(c);if(O?.kind===`failure`){S(n,O.failure,`rollback`);return}if(O?.kind===`divergence`){C(n,`rollback`);return}if(O?.kind===`stale-external-write`){r(n,`rollback`,c);return}M(c,`rollback`);let k=Date.now()-g;q(`rollback`).info({docName:c,from:l.slice(0,8),durationMs:k},`rollback`),a.kind===`agent`&&T?.setFocus(a.writerId,{agentName:a.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let ee=E===void 0?void 0:MX(E);Q(n,200,Xee,{restoredFrom:l,timestamp:f,...D?{summary:D}:{},...ee?{warnings:[ee]}:{}},{handler:`rollback`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`})},{mutating:[`/api/agent-write-md`,`/api/frontmatter-patch`,`/api/agent-patch`,`/api/agent-undo`,`/api/save-version`,`/api/rollback`]})}const x1={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},jet={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}},Met=[`document`,`server`];function Net(e){return Met.includes(e)}function Pet(e){let{agentPresence:t,resetSettingsForTest:n,settleDiskEvents:r,recentlyRemovedDocs:i,conflicts:a,durabilityState:o,resolveAlias:s,contentDir:c,log:l,sessionManager:u,hocuspocus:d,forceUnloadDocument:f,derivedDocumentIndex:p,contentFilter:m,bumpSkillsCatalogGen:h,signalChannel:g,flushGitCommit:_,rescanFiles:v}=e;async function y(e){let t=`onStoreDocument-${e}`;d.debouncer.isDebounced(t)&&await d.debouncer.executeNow(t);let n=d.documents.get(e);n&&await(f??d.unloadDocument.bind(d))(n),o.deleteReconciledBase(e),a.dissolveReconcile(e)}function b(e){return KK(e)||qK(e)}async function x(e){for(let t of d.documents.keys())t===e||b(t)||await y(t);for(let e of Object.keys(t?.getPresenceMap()??{}))t?.clearPresence(e);for(let[e]of i?.entries()??[])i?.delete(e)}function S(){let e=0;for(let t of d.documents.values())e+=t.getConnections().length;return{loadedDocuments:[...d.documents.keys()].filter(e=>!b(e)).sort(),clientConnections:e,agentSessions:u.liveSessionCount,agentPresence:Object.keys(t?.getPresenceMap()??{}).sort(),staleExternalWrites:o.listStaleExternalWrites().map(e=>e.docName).sort(),removedDocuments:(i?.entries()??[]).map(([e])=>e).sort()}}return N$({"/api/test-reset":Z($a,async(e,t)=>{try{let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`scope`)??`document`;if(!Net(a)){X(t,400,`urn:ok:error:invalid-request`,`scope must be one of ${Met.join(`, `)}.`,{handler:`test-reset`});return}if(a===`server`&&i.searchParams.has(`reset-okignore`)){X(t,400,`urn:ok:error:invalid-request`,`reset-okignore cannot be combined with scope=server: a server-scope reset always restores .okignore.`,{handler:`test-reset`});return}if(a===`server`&&n===void 0){X(t,400,`urn:ok:error:invalid-request`,`scope=server needs a server started with an isolated config home.`,{handler:`test-reset`});return}let o=UK(s(i.searchParams.get(`docName`)??`test-doc`)),f;try{f=fq(o,c)}catch(e){l.error({err:e,docName:o},`[test-reset] safeContentPath rejected docName`),X(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}if(a===`server`)try{await r?.()}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`The server-scope reset did not run, because the file watcher could not settle.`,{handler:`test-reset`,detail:e instanceof Error?e.message:String(e),cause:e});return}if(await u.closeAll(a===`server`?void 0:o),d.closeConnections(a===`server`?void 0:o),await y(o),cc(f,``,`utf-8`),await p?.testOnly?.resetDocumentForTest(o),a===`server`&&(await x(o),n?.()),i.searchParams.get(`reset-okignore`)!==`false`)try{let e=W(c,`.okignore`),t=d.documents.get(xa);if(t){let e=t.getText(`source`);e.length>0&&t.transact(()=>{e.delete(0,e.length)},x1)}G(e)&&cc(e,``,`utf-8`),m&&(h(),await m.rebuildIgnorePatterns())}catch(e){l.warn({err:e},`[test-reset] okignore reset partial failure`)}g?.(`files`),Q(t,200,Jt,a===`server`?{scope:a,residue:S()}:{},{handler:`test-reset`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),"/api/test-flush-git":Z($a,async(e,t)=>{try{await _?.(),Q(t,200,Gr,{},{handler:`test-flush-git`})}catch(n){l.error({err:n,requestId:DJ(e)},`[test-flush-git] flush failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:n})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),"/api/test-rescan-backlinks":Z($a,async(e,t)=>{try{if(!p?.testOnly){X(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await p.testOnly.rescanBacklinksForTest(),Q(t,200,fee,{},{handler:`test-rescan-backlinks`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),"/api/test-rescan-files":Z($a,async(e,t)=>{try{if(!v){X(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await v(),g?.(`files`),Q(t,200,tt,{},{handler:`test-rescan-files`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0})},{mutating:[`/api/test-reset`,`/api/test-flush-git`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`]})}const Fet=Mne,Iet={claude:`claude`,codex:`codex`,cursor:`cursor-agent`,gemini:`gemini`,opencode:`opencode`,pi:`pi`,antigravity:`agy`,copilot:`copilot`,openclaw:`openclaw`,hermes:`hermes`},Let={codex:()=>H(process.env.CODEX_HOME??H(dc(),`.codex`),`auth.json`)};function Ret(e){let t=Let[e];if(t===void 0)return`unknown`;let n;try{return n=t(),G(n)?`present`:`unknown`}catch(t){return q(`acp-harness`).warn({cli:e,credentialPath:n,err:t},`harness credential probe failed; treating as unknown`),`unknown`}}async function zet(e,t,n=hQ){let r={cmd:Iet[e],args:[],env:aQ(),kind:`custom`,pathFromOverlay:!1};try{return await n(r),`present`}catch(i){if(!(i instanceof iQ)||i.code!==`command-not-found`)return q(`acp-harness`).warn({cli:e,err:i},`harness preflight failed before absence could be verified; availability unknown`),`unknown`;let a=null,o;try{a=await t()}catch(e){o=e}if(a===null)return q(`acp-harness`).warn({cli:e,err:o},`login-shell PATH capture failed; harness absence unverified — availability unknown`),`unknown`;try{return await n(E6e(r,a)),`present`}catch(t){return t instanceof iQ&&t.code===`command-not-found`?`not-found`:(q(`acp-harness`).warn({cli:e,err:t},`harness preflight on the login-shell PATH failed before absence could be verified; availability unknown`),`unknown`)}}}function Bet(e={}){let t=e.resolveLoginShellPath??eQ(q(`acp-harness`)),n=e.preflight??hQ,r=e.probe??(e=>zet(e,t,n)),i=e.credentials??Ret,a=e.now??Date.now,o=e.ttlMs??6e4,s=[...new Set(Object.values(Fet))].filter(e=>e!==void 0),c=null;return()=>{let e=a();if(c!==null&&c.expiresAt>e)return c.value;let t=Promise.all(s.map(async e=>{let t=`unknown`;try{t=i(e)}catch(t){q(`acp-harness`).warn({cli:e,err:t},`harness credential probe threw; treating as unknown`)}try{return[e,{availability:await r(e),credentials:t}]}catch(n){return q(`acp-harness`).warn({cli:e,err:n},`harness availability probe rejected; availability unknown`),[e,{availability:`unknown`,credentials:t}]}})).then(e=>Object.fromEntries(e));return c={expiresAt:e+o,value:t},t}}var Vet=class{threads=new Map;docToThreads=new Map;async build(e){this.threads.clear(),this.docToThreads.clear();for(let t of await e.scanCoverSheets())this.upsert(t)}upsert(e){let t=this.threads.get(e.threadId);t!==void 0&&t.docName!==e.docName&&this.detach(t.docName,e.threadId),this.threads.set(e.threadId,e);let n=this.docToThreads.get(e.docName);n||(n=new Set,this.docToThreads.set(e.docName,n)),n.add(e.threadId)}remove(e){let t=this.threads.get(e);t!==void 0&&(this.threads.delete(e),this.detach(t.docName,e))}renameDoc(e,t){let n=this.docToThreads.get(e);if(!n)return;this.docToThreads.delete(e);let r=this.docToThreads.get(t)??new Set;for(let e of n){r.add(e);let n=this.threads.get(e);n&&this.threads.set(e,{...n,docName:t})}this.docToThreads.set(t,r)}listForDoc(e){let t=[];for(let n of this.docToThreads.get(e)??[]){let e=this.threads.get(n);e&&t.push(e)}return t}listAll(){return[...this.threads.values()]}threadsForDoc(e){return[...this.docToThreads.get(e)??[]]}countsForDocs(e){let t=new Map;for(let n of e)t.set(n,this.countForDoc(n));return t}countsUnderPrefix(e){let t=e===``?``:e.endsWith(`/`)?e:`${e}/`,n=new Map;for(let e of this.docToThreads.keys()){if(!e.startsWith(t))continue;let r=this.countForDoc(e);r>0&&n.set(e,r)}return n}countForDoc(e){let t=0;for(let n of this.docToThreads.get(e)??[])this.threads.get(n)?.state!==`resolved`&&t++;return t}get size(){return this.threads.size}detach(e,t){let n=this.docToThreads.get(e);n&&(n.delete(t),n.size===0&&this.docToThreads.delete(e))}};function S1(e,t,n,r=32){if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n>e.length||t>=n)throw Error(`invalid selection range [${t}, ${n}) for body length ${e.length}`);let i=e.slice(t,n),a=e.slice(Math.max(0,t-r),t),o=e.slice(n,Math.min(e.length,n+r));if(Wet(e,i)>1){let s=r;for(;!Get(e,a,i,o)&&s<e.length;)s=Math.min(s*2,e.length),a=e.slice(Math.max(0,t-s),t),o=e.slice(n,Math.min(e.length,n+s))}return{exact:i,prefix:a,suffix:o,start:t,end:n}}function Het(e,t){return T1(e,t).map(e=>({start:e,end:e+t.length}))}function Uet(e,t,n,{contextIsMarkdown:r=!1}={}){let i=n.prefix??``,a=n.suffix??``,o=[],s=-1;for(let n of t){let t=Coe(e,n,{prefix:i,suffix:a},{syntaxIn:`haystack`,syntaxInContext:r});t>s?(s=t,o=[n]):t===s&&o.push(n)}return o}function C1(e,t){let{exact:n,prefix:r,suffix:i,start:a}=t,o=a+n.length;if(o<=e.length&&e.slice(a,o)===n)return{status:`anchored`,start:a,end:o};if(r!==``&&i!==``&&!e.includes(r+n+i)&&e.includes(r+i))return{status:`orphaned`};let s=T1(e,n);if(s.length===0)return w1(e,t);let c=woe(t,{syntaxInContext:!0}),l=t=>c===0||Coe(e,t,{prefix:r,suffix:i},{syntaxIn:`haystack`,syntaxInContext:!0})>=c;if(s.length===1){let r={start:s[0],end:s[0]+n.length};return l(r)?{status:`anchored`,start:r.start,end:r.end}:w1(e,t)}let u=Uet(e,s.map(e=>({start:e,end:e+n.length})),{prefix:r,suffix:i},{contextIsMarkdown:!0});if(!l(u[0]))return w1(e,t);if(u.length===1)return{status:`anchored`,start:u[0].start,end:u[0].end};let d=[],f=1/0;for(let e of u){let t=Math.abs(e.start-a);t<f?(f=t,d=[e]):t===f&&d.push(e)}return d.length===1?{status:`anchored`,start:d[0].start,end:d[0].end}:{status:`orphaned`}}function w1(e,t){let{prefix:n,suffix:r,exact:i}=t,a=n===``?[0]:T1(e,n).map(e=>e+n.length),o=r===``?[e.length]:T1(e,r);if(a.length!==1||o.length!==1)return{status:`orphaned`};let s=a[0],c=o[0];if(c<s||c===s)return{status:`orphaned`};let l=Toe(i.length);return c-s>l?{status:`orphaned`}:{status:`anchored`,start:s,end:c,rewritten:!0}}function Wet(e,t){if(t===``)return 0;let n=0,r=e.indexOf(t);for(;r!==-1;)n+=1,r=e.indexOf(t,r+1);return n}function T1(e,t){let n=[];if(t===``)return n;let r=e.indexOf(t);for(;r!==-1;)n.push(r),r=e.indexOf(t,r+1);return n}function Get(e,t,n,r){return Wet(e,t+n+r)===1}function E1(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];for(let e of n){if(r==null)return;if(typeof e==`number`){if(!Array.isArray(r)||e>=r.length)return;r=r[e];continue}if(typeof r!=`object`||Array.isArray(r))return;let t=r;if(!Object.hasOwn(t,e))return;r=t[e]}return r}function Ket(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):null}function qet(e,t){if(t===``)return!1;let n=e.indexOf(t);return n!==-1&&e.indexOf(t,n+1)!==-1}var D1=class extends Error{},O1=class extends Error{},k1=class extends Error{},A1=class extends Error{},Jet=class{store;index;getDocBody;getDocFrontmatter;now;newId;indexReady=null;constructor(e){this.store=e.store,this.index=e.index,this.getDocBody=e.getDocBody,this.getDocFrontmatter=e.getDocFrontmatter,this.now=e.now??Date.now,this.newId=e.newId??Ec}buildIndex(){return this.indexReady??=this.index.build(this.store),this.indexReady}async createThread(e){await this.buildIndex();let t=e.propertyKey,n,r;if(t===void 0){let t=await this.requireDocBody(e.docName),{start:i,end:a}=this.resolveRange(t,e);n={kind:`body`},r=S1(t,i,a)}else{let i=e.propertyPath??[];n={kind:`property`,key:t,path:i};let a=e.quote?.trim();if(a===void 0||a.length===0)await this.requirePropertyTarget(e.docName,t,i),r=null;else{let n=await this.requirePropertyText(e.docName,t,i),{start:a,end:o}=this.resolveRange(n,e);r=S1(n,a,o)}}let i=this.newId(),a=this.now(),o=await this.store.createThread({threadId:i,docName:e.docName,target:n,anchor:r,createdBy:e.author,createdAt:a,body:e.body});return this.index.upsert(o),e.queue===!0?this.mutate(i,{queued:!0}):o}async listThreads(e){return await this.buildIndex(),e===void 0?this.index.listAll():this.index.listForDoc(e)}async countThreads(e){return await this.buildIndex(),`prefix`in e?this.index.countsUnderPrefix(e.prefix):this.index.countsForDocs(e.docNames)}async readThread(e){return this.requireMeta(e)}async editComment(e,t){return this.mutate(e,{latestComment:t,updatedAt:this.now()})}async resolve(e){return this.mutate(e,{state:`resolved`})}async reopen(e){return await this.mutate(e,{state:`anchored`,queued:!0}),this.refindOnLoad(e)}async replaceAnchor(e,t){let n=await this.requireMeta(e);if(n.target.kind===`property`)throw new k1(n.target.key);let r=await this.requireDocBody(n.docName),{start:i,end:a}=this.resolveRange(r,t),o=S1(r,i,a);return this.mutate(e,{anchor:o,state:`anchored`})}async queueForDispatch(e,t){await this.mutate(e,{queued:!0});let n=await this.refindOnLoad(e,t);return{meta:n,orphaned:n.state===`orphaned`}}async prepareDispatch(e){let t=await this.getDocBody((await this.requireMeta(e)).docName),n=await this.queueForDispatch(e,t),{anchor:r,docName:i,target:a}=n.meta,o=await this.latestComment(e);return a.kind===`property`?{meta:n.meta,payload:{docName:i,instruction:o,property:j1(a.key,a.path),passage:r===null?null:{exact:r.exact,prefix:r.prefix,suffix:r.suffix},anchorLost:n.orphaned,passageRepeats:!1}}:{meta:n.meta,payload:{docName:i,instruction:o,property:null,passage:r===null?null:{exact:r.exact,prefix:r.prefix,suffix:r.suffix},anchorLost:n.orphaned,passageRepeats:r!==null&&t!==null&&qet(t,r.exact)}}}async completeDispatch(e){return this.mutate(e,{queued:!1,state:`resolved`})}async prepareDispatchBatch(e){let t=[];for(let n of e)try{let e=await this.prepareDispatch(n);t.push({threadId:n,ok:!0,...e})}catch(e){if(e instanceof O1){t.push({threadId:n,ok:!1,error:`not-found`});continue}throw e}return t}async completeDispatchBatch(e){let t=[];for(let n of e)try{t.push({threadId:n,ok:!0,meta:await this.completeDispatch(n)})}catch(e){if(e instanceof O1){t.push({threadId:n,ok:!1,error:`not-found`});continue}throw e}return t}async latestComment(e){return(await this.requireMeta(e)).latestComment.trim()}async unqueue(e){return this.mutate(e,{queued:!1})}async delete(e){await this.buildIndex(),await this.store.delete(e),this.index.remove(e)}async renameDoc(e,t){if(e===t)return;await this.buildIndex();let n=this.index.threadsForDoc(e);n.length!==0&&(this.index.renameDoc(e,t),await Promise.all(n.map(e=>this.store.update(e,{docName:t}))))}async deleteDoc(e){await this.buildIndex();let t=this.index.threadsForDoc(e);for(let e of t)await this.store.delete(e),this.index.remove(e);return t.length}async refindDoc(e){await this.buildIndex();let t=this.index.listForDoc(e).filter(e=>e.state!==`resolved`);if(t.length===0)return!1;let n=await this.getDocBody(e);if(n===null)return!1;let r=t.some(e=>e.target.kind===`property`)?await this.getDocFrontmatter(e):null,i=!1;for(let a of t){if(a.target.kind===`property`){let t=await this.refindProperty(e,a.target,a.anchor,r);if(t===null||t.state===a.state)continue;await this.mutate(a.threadId,{state:t.state}),i=!0;continue}if(a.anchor===null)continue;let t=C1(n,a.anchor);if(t.status===`orphaned`){if(a.state===`orphaned`)continue;await this.mutate(a.threadId,{state:`orphaned`}),i=!0;continue}let o=t.rewritten===!0?S1(n,t.start,t.end):void 0,s=a.state!==`anchored`;o===void 0&&!s||(await this.mutate(a.threadId,{...o?{anchor:o}:{},state:`anchored`}),(s||o!==void 0)&&(i=!0))}return i}async refindOnLoad(e,t){let n=await this.requireMeta(e);if(n.state===`resolved`)return n;if(n.target.kind===`property`){let t=await this.refindProperty(n.docName,n.target,n.anchor);return t===null||t.anchor===void 0&&t.state===n.state?n:this.mutate(e,{...t.anchor?{anchor:t.anchor}:{},state:t.state})}let r=t===void 0?await this.getDocBody(n.docName):t;if(r===null)return n;let i=n.anchor;if(i===null)return n;let a=C1(r,i);if(a.status===`orphaned`)return n.state===`orphaned`?n:this.mutate(e,{state:`orphaned`});let o=a.rewritten?S1(r,a.start,a.end):a.start!==i.start||a.end!==i.end?{...i,start:a.start,end:a.end}:void 0;return o===void 0&&n.state===`anchored`?n:this.mutate(e,{...o?{anchor:o}:{},state:`anchored`})}async mutate(e,t){let n=await this.store.update(e,t);if(!n)throw new O1(e);return this.index.upsert(n),n}resolveRange(e,t){if(t.start!==void 0&&t.end!==void 0)return{start:t.start,end:t.end};let n=t.quote?.trim();if(n===void 0||n.length===0)throw Error(`either start/end offsets or a non-empty quote is required`);let r=Het(e,n),i=r.length>0?r:boe(e,n,{syntaxIn:`haystack`});if(i.length===0)throw new A1(n);return i.length===1?i[0]:Uet(e,i,{prefix:t.prefix,suffix:t.suffix})[0]}async requireMeta(e){let t=await this.store.readMeta(e);if(!t)throw new O1(e);return t}async requireDocBody(e){let t=await this.getDocBody(e);if(t===null)throw new D1(e);return t}async requirePropertyText(e,t,n){let r=await this.getDocFrontmatter(e);if(r===null)throw new D1(e);let i=E1(r,t,n);if(i===void 0)throw new k1(j1(t,n));let a=Ket(i);if(a===null)throw new k1(j1(t,n));return a}async requirePropertyTarget(e,t,n){let r=await this.getDocFrontmatter(e);if(r===null)throw new D1(e);if(E1(r,t,n)===void 0)throw new k1(j1(t,n))}async refindProperty(e,t,n,r){let i=r===void 0?await this.getDocFrontmatter(e):r;if(i===null)return null;let a=E1(i,t.key,t.path);if(a===void 0)return{state:`orphaned`};if(n===null)return{state:`anchored`};let o=Ket(a);if(o===null)return{state:`orphaned`};let s=C1(o,n);return s.status===`orphaned`?{state:`orphaned`}:s.rewritten?{state:`anchored`,anchor:S1(o,s.start,s.end)}:s.start!==n.start||s.end!==n.end?{state:`anchored`,anchor:{...n,start:s.start,end:s.end}}:{state:`anchored`}}};function j1(e,t){let n=e;for(let e of t)n+=typeof e==`number`?`[${e}]`:`.${e}`;return n}var Yet=class{dir;log;writeQueues=new Map;dirReady=null;constructor(e,t){this.dir=H(e,`comments`),this.log=t}init(){return this.ensureDir()}ensureDir(){return this.dirReady??=EG(this.dir,{recursive:!0}).then(()=>void 0),this.dirReady}metaPath(e){return H(this.dir,`${e}.meta.json`)}enqueueResult(e,t){let n=(this.writeQueues.get(e)??Promise.resolve()).then(()=>t());return this.writeQueues.set(e,n.then(()=>void 0,()=>void 0)),n}async whenIdle(e){await(this.writeQueues.get(e)??Promise.resolve())}createThread(e){let t=va.parse({threadId:e.threadId,docName:e.docName,target:e.target,anchor:e.anchor,state:`anchored`,queued:!1,latestComment:e.body,createdBy:e.createdBy,createdAt:e.createdAt});return this.enqueueResult(e.threadId,async()=>(await this.ensureDir(),await this.write(t),t))}update(e,t){return this.enqueueResult(e,async()=>{await this.ensureDir();let n=await this.readMeta(e);if(!n)return null;let r=va.parse({...n,...Xet(t)});return await this.write(r),r})}write(e){return YS(this.metaPath(e.threadId),Zet(e),{fs:LG})}async readMeta(e){let t;try{t=await vc(this.metaPath(e),`utf8`)}catch{return null}let n=va.safeParse(Qet(t));return n.success?n.data:(this.log.warn({threadId:e},`[comments] skipping unreadable thread meta`),null)}async scanCoverSheets(){let e;try{e=await yc(this.dir)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(`.meta.json`))continue;let e=await this.readMeta(n.slice(0,-10));e&&t.push(e)}return t}async delete(e){await this.enqueueResult(e,async()=>{await wG(this.metaPath(e),{force:!0}),await wG(H(this.dir,`${e}.ndjson`),{force:!0})})}};function Xet(e){let{docName:t,anchor:n,state:r,queued:i,latestComment:a,updatedAt:o}=e;return{...t!==void 0&&{docName:t},...n!==void 0&&{anchor:n},...r!==void 0&&{state:r},...i!==void 0&&{queued:i},...a!==void 0&&{latestComment:a},...o!==void 0&&{updatedAt:o}}}function Zet(e){return`${JSON.stringify(e,null,1)}\n`}function Qet(e){try{return JSON.parse(e)}catch{return}}const M1=[`claude`,`codex`,`cursor`],N1=2e3,$et={claude:[`Claude`],codex:[`Codex`],cursor:[`Cursor`]};function ett(e){let t=new Map,n=e.now??Date.now,r=e.ttlMs??6e4;async function i(i){let a=t.get(i);if(a?.status===`resolved`&&a.expiresAt>n())return a.installed;if(a?.status===`inflight`)return a.promise;let o=(async()=>{try{let a=await e.probe(i);return t.set(i,{status:`resolved`,installed:a,expiresAt:n()+r}),a}catch{return t.set(i,{status:`resolved`,installed:!1,expiresAt:n()+r}),!1}})();return t.set(i,{status:`inflight`,promise:o}),o}async function a(){let e=await Promise.all(M1.map(async e=>[e,await i(e)]));return Object.fromEntries(e)}return{probeAll:a,probeWithCache:i}}function ttt(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return ntt(e)}catch{}let n=e.headers.origin;if(typeof n==`string`&&n.length>0)try{return ntt(new URL(n).hostname)}catch{return!1}return!0}function ntt(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function rtt(e,t,n){if(e.method!==`GET`){X(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{let r=ttt(e)?await n():Object.fromEntries(M1.map(e=>[e,!0]));Q(t,200,cn,r,{handler:`installed-agents`})}catch(e){q(`handoff`).error({err:e},`[installed-agents] handler failed`),X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function P1(e,t=Es){return n=>e===`darwin`?itt(n,t):e===`win32`?att(n,t):ott(n,t)}function itt(e,t){let n=$et[e];function r(e){return new Promise(n=>{t(`osascript`,[`-e`,`id of app "${e}"`],hq({timeout:N1,encoding:`utf-8`}),(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}return(async()=>{for(let e of n)if(await r(e))return!0;return!1})()}function att(e,t){return new Promise(n=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],hq({timeout:N1,encoding:`utf-8`}),e=>{n(!e)})})}function ott(e,t){return new Promise(n=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],hq({timeout:N1,encoding:`utf-8`}),(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}const stt=`skill-install-events.jsonl`;async function F1(e,t){let n=t?.homedir??(()=>process.env.HOME??``),r=t?.warn??((e,t)=>{q(`skills`).warn(e,t)}),i=n();if(!i){r({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let a=H(KS(i),stt),o=`${JSON.stringify(e)}\n`;try{await EG(V(a),{recursive:!0})}catch(e){r({event:`skill-install-events.mkdir-failed`,err:e},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await SG(a,o,{flag:`a`,encoding:`utf-8`})}catch(e){r({event:`skill-install-events.append-failed`,err:e},`[skill-install-events] append failed; telemetry skipped`)}}function ctt(){return Sa.parse({}).telemetry.skillInstallReports.enabled}function I1(e){let t=e??dc(),n;try{n=QS(`user`,t,t)}catch(e){return q(`skills`).warn({err:e},`could not resolve the user config path; not reporting`),{enabled:!1,home:t}}if(!G(n))return{enabled:ctt(),home:t};try{let e=(0,Wc.parse)(K(n,`utf-8`))?.telemetry?.skillInstallReports?.enabled;return{enabled:typeof e==`boolean`?e:ctt(),home:t}}catch(e){return q(`skills`).warn({err:e,path:n},`user config exists but could not be read; not reporting skill installs`),{enabled:!1,home:t}}}function L1(){let e=new Map;return(t,n)=>{let r=(e.get(t)??Promise.resolve()).then(n,n);return e.set(t,r.then(()=>void 0,()=>void 0)),r}}const ltt=[`.ok`,yr,Fte];function R1(e){return H(e,...ltt)}function utt(e){let t=e;for(;!G(t);){let e=V(t);if(e===t)return null;t=e}return t}function dtt(e){let t=e;for(;;)try{return oc(t),t}catch(e){let n=e.code;if(n!==`ENOENT`&&n!==`ENOTDIR`)throw e;let r=V(t);if(r===t)return null;t=r}}function ftt(e,t,n){if(t.length===0||t.includes(`\0`)||Ps(t)||t.split(/[/\\]/).some(e=>e===`..`))return null;let r=W(e),i=W(r,t);if(i===r||!i.startsWith(`${r}${Rs}`))return null;let a=nc(r),o=n(i);if(o===null)return null;let s=nc(o);return s!==a&&!s.startsWith(`${a}${Rs}`)?null:i}function ptt(e,t){return ftt(e,t,dtt)}function z1(e,t){try{return ftt(e,t,utt)}catch{return null}}function B1(){return{schema:1,skills:{}}}function mtt(e,t,n){if(!t||typeof t!=`object`)return!1;let r=t;return typeof r.path==`string`&&n(e,r.path)!==null&&(r.mode===`copy`||r.mode===`link`)&&(r.hash===void 0||typeof r.hash==`string`)}function htt(e){if(!e||typeof e!=`object`)return;let t=Object.entries(e).filter(e=>e[1]===`copy`||e[1]===`link`);return t.length>0?Object.fromEntries(t):void 0}function gtt(e){if(!e||typeof e!=`object`)return;let t=Object.entries(e).filter(e=>typeof e[1]==`string`&&e[1]!==``);return t.length>0?Object.fromEntries(t):void 0}function _tt(e,t,n){if(!t||typeof t!=`object`)return;let r=[];for(let[i,a]of Object.entries(t)){if(n(e,i)===null||!a||typeof a!=`object`)continue;let t=a;t.expect===`own`?r.push([i,{expect:`own`}]):t.expect===`link`&&typeof t.target==`string`&&n(e,t.target)!==null&&r.push([i,{expect:`link`,target:t.target}])}return r.length>0?Object.fromEntries(r):void 0}function V1(e,t,n=z1){let r={};if(t.skills&&typeof t.skills==`object`)for(let[i,a]of Object.entries(t.skills)){if(!Array.isArray(a))continue;let t=a.filter(t=>mtt(e,t,n));t.length>0&&(r[i]=t)}let i=Array.isArray(t.roots)?t.roots.filter(t=>typeof t==`string`&&n(e,t)!==null):[],a=htt(t.preferences),o=gtt(t.sources),s=_tt(e,t.folders,n);return{schema:1,skills:r,...a?{preferences:a}:{},...o?{sources:o}:{},...i.length>0?{roots:i}:{},...s?{folders:s}:{}}}function H1(e){let t=R1(e);if(!G(t))return B1();try{let n=JSON.parse(K(t,`utf-8`));return!n||typeof n!=`object`?B1():V1(e,n)}catch(e){return q(`skill-placements`).warn({err:e,path:t},`skill-placements.json is unreadable; continuing with an empty ledger (recorded placements for this project are lost)`),B1()}}function vtt(e,t){let n=R1(e);try{oc(n)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return{kind:`read`,store:B1()};throw e}let r=K(n,`utf-8`),i;try{i=JSON.parse(r)}catch(e){return q(`skill-placements`).warn({err:e,path:n},`skill-placements.json is not valid JSON; skill scans read no recorded roots or sources from it, and in-place skill refreshes keep the prior admission of the skills it decides`),{kind:`unparsable`,error:e}}return!i||typeof i!=`object`?{kind:`read`,store:B1()}:{kind:`read`,store:V1(e,i,t)}}function ytt(e){let t=R1(e);if(!G(t))return{ok:!0,store:B1()};let n;try{n=K(t,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?{ok:!0,store:B1()}:{ok:!1,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}let r;try{r=JSON.parse(n)}catch(e){return{ok:!1,reason:`it is not valid JSON`,cause:e}}if(typeof r!=`object`||!r||Array.isArray(r))return{ok:!1,reason:`its contents are not a placements ledger`};let i=r.schema;return i!==void 0&&i!==1?{ok:!1,reason:typeof i==`number`?`it declares schema ${i}, which this server does not understand (it writes schema 1)`:`it declares an unsupported schema value`}:{ok:!0,store:V1(e,r)}}const btt=L1();function U1(e,t){return btt(R1(e),async()=>{let n=ytt(e);if(!n.ok){let t=R1(e);throw q(`skill-placements`).error({path:t,reason:n.reason,err:n.cause},`refusing to rewrite skill-placements.json because it could not be read — rewriting it would replace every placement it records with this one`),Error(`Refusing to rewrite ${t}: ${n.reason}`)}let r=n.store;t(r),await xtt(e,r)})}async function xtt(e,t){let n=R1(e);await EG(V(n),{recursive:!0}),await YS(n,`${JSON.stringify(t,null,2)}\n`,{fs:LG})}function Stt(e,t,n){let r=new Set(t.roots??[]);for(let i of Object.values(t.skills))for(let t of i){let i=t.path.split(`/`).slice(0,-1).join(`/`);i!==``&&n(e,i)!==null&&r.add(i)}return[...r].sort()}function Ctt(e){return Stt(e,H1(e),z1)}function wtt(e){let t=[],n=(e,n)=>{try{return ptt(e,n)}catch(e){return t.push(e),null}},r;try{r=vtt(e,n)}catch(t){return q(`skill-placements`).warn({err:t,path:R1(e)},`skill-placements.json could not be read; skill scans read no recorded roots or sources from it, and in-place skill refreshes keep their prior admission`),{kind:`incomplete`,roots:[],sources:{},error:t}}if(r.kind===`unparsable`)return{kind:`unparsable`,roots:[],sources:{},error:r.error};let{store:i}=r,a=Stt(e,i,n),o=i.sources??{};return t.length===0?{kind:`complete`,roots:a,sources:o}:{kind:`incomplete`,roots:a,sources:o,error:t[0]}}const Ttt=new Set([400,404,410,422]),Ett=[`.local`,`.internal`,`.intranet`,`.corp`,`.home`,`.home.arpa`,`.lan`,`.private`,`.test`,`.invalid`,`.localhost`,`.localdomain`];function Dtt(e){let t=e.split(`/`);return t.length===1?/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(e)?!Ett.some(t=>e.toLowerCase().endsWith(t)):!1:t.length===2&&t.every(e=>/^[\w.-]+$/.test(e)&&e!==`.`&&e!==`..`)}function W1(e,t){if(e.scope===void 0)return`${e.source}#${t}`;let n=e.scope;try{n=nc(n)}catch{}return`${e.source}#${t}@${n}`}function Ott(e=process.env){return!!(e.DISABLE_TELEMETRY||e.DO_NOT_TRACK)}async function G1(e,t){let n=t.env??process.env;if(!t.enabled||Ott(n)||!Dtt(e.source.trim()))return[];let r=await S7e(t.home).catch(t=>(q(`skills`).warn({err:t,source:e.source},`could not read the install-report ledger; a duplicate report is possible`),new Set)),i=e.skills.filter(t=>!r.has(W1(e,t)));if(i.length===0)return[];let a=new URLSearchParams({event:`install`,source:e.source,skills:i.join(`,`)});e.agents&&e.agents.length>0&&a.set(`agents`,e.agents.join(`,`)),e.global&&a.set(`global`,`1`),e.version&&a.set(`v`,e.version);let o=t.fetchImpl??globalThis.fetch;if(!o)return[];try{await C7e(t.home,i.map(t=>W1(e,t)))}catch(t){return q(`skills`).warn({err:t,source:e.source,skills:i},`skill install report ledger write failed; not reporting this install`),[]}try{let n=await o(`https://add-skill.vercel.sh/t?${a.toString()}`,{signal:AbortSignal.timeout(3e3)});if(!n.ok&&Ttt.has(n.status))return q(`skills`).warn({status:n.status,source:e.source,skills:i},`skill install report rejected by the collector; releasing the claim to retry later`),await w7e(t.home,i.map(t=>W1(e,t))).catch(t=>{q(`skills`).warn({err:t,status:n.status,source:e.source,skills:i},`could not release the install-report claim; this install will not be retried`)}),[];n.ok||q(`skills`).warn({status:n.status,source:e.source,skills:i},`skill install report rejected with an ambiguous status; keeping the claim so a counted install cannot be double-reported`)}catch(t){q(`skills`).warn({err:t,source:e.source,skills:i},`skill install report could not be delivered; this install is not counted`)}return i}const K1=`.agents`;function ktt(e,t){return H(e,K1,`skills`,t)}function q1(e){return rte.filter(t=>G(H(e,t.hostDir)))}function Att(e){let t=q1(e).map(e=>({editor:e.editorId,skillsRoot:e.skillsRoot,custom:!1})),n=new Set(t.map(e=>e.skillsRoot)),r=Ctt(e).filter(t=>!n.has(t)&&G(H(e,t))).map(e=>({editor:e,skillsRoot:e,custom:!0}));return[...t,...r]}function jtt(e){return ra.filter(t=>{let n=Vi[t];return n!==null&&G(H(e,Qa(n)))})}async function Mtt(e,t){let n=q1(e).map(n=>H(e,n.skillsRoot,t));G(H(e,K1))&&n.push(ktt(e,t));for(let e of n)try{if((await Sc(e)).isDirectory())return!0}catch{}return!1}function Ntt(e,t,n){let r=[...t.map(e=>e.skillsRoot),`${K1}/skills`];for(let t of r){let r=H(e,t,`open-knowledge`);if(G(r))try{FG(r,{recursive:!0,force:!0}),n.info?.({event:`skill-install.legacy-removed`,path:r},"Removed pre-split `open-knowledge` user-global skill dir.")}catch(e){n.warn({event:`skill-install.legacy-remove-failed`,path:r,err:e},"Legacy `open-knowledge` skill removal failed; continuing with install.")}}}function Ptt(e,t){FG(t,{recursive:!0,force:!0}),kG(V(t),{recursive:!0}),jG(e,t,{recursive:!0})}function Ftt(e,t,n,r,i){let a=[],o=ktt(e,t),s=[...i?[o]:[],...r.map(n=>H(e,n.skillsRoot,t)).filter(e=>e!==o)];for(let e of s)try{Ptt(n,e),a.push({path:e,status:`written`})}catch(t){a.push({path:e,status:`failed`,error:t instanceof Error?t.message:String(t)})}return a}async function Itt(e={}){let t=e.home??dc(),n=e.logger??{warn:(e,t)=>q(`skills`).warn(e,t),info:(e,t)=>q(`skills`).info(e,t)},r=e.surface??`cli-npx-skills-add`,i=e.bundleId??`discovery`,a=RZ[i];if(!Ps(t))return n.warn({event:`skill-install.failed`,reason:`home-not-absolute`,home:t},`Skill install aborted — $HOME is not an absolute path.`),`failed`;let o=async(e,a,o)=>{await F1({ts:new Date().toISOString(),surface:r,target:`cli-hosts`,bundle:i,outcome:e,...a===void 0?{}:{version:a},...o===void 0?{}:{reason:o}},{homedir:()=>t,warn:n.warn})},s;try{s=await b7e(t,a,n)}catch(e){return n.warn({event:`skill-install.gate.decision-read-failed`,bundle:i,err:e},`Could not read the opt-out decision; skipping the install rather than risk reversing it.`),await o(`skip-current`,void 0,`decision-read-failed`),`skip-current`}if(s===!1)return n.info?.({event:`skill-install.declined`,bundle:i},`Bundle is opted out; skipping user-global skill install.`),await o(`skip-current`,void 0,`declined`),`skip-current`;let c;try{c=await g$()}catch(e){return n.warn({event:`skill-install.failed`,reason:`version-read-failed`,err:e},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await o(`failed`,void 0,`version-read-failed`),`failed`}let l=await m$(t,`cli-hosts`,n).catch(e=>(n.warn({event:`skill-install.gate.read-failed`,err:e},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(!e.force&&l!==null&&l===c){if(await Mtt(t,a))return n.info?.({event:`skill-install.skip-current`,version:c},`OpenKnowledge skill already installed at current version; skipping.`),await o(`skip-current`,c),`skip-current`;n.info?.({event:`skill-install.reinstall-missing`,version:c},`Sidecar matches current version but skill files are missing; reinstalling.`)}let u;try{u=WZ(i,{checkDesktop:!1})}catch(e){return n.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,err:e},`Skill install aborted — bundled SKILL.md asset not found.`),await o(`failed`,c,`bundled-asset-missing`),`failed`}let d=q1(t),f=G(H(t,K1));if(d.length===0&&!f)return n.info?.({event:`skill-install.no-hosts`,version:c},`No supported agent host detected; skipping user-global skill install.`),await o(`skip-current`,c,`no-hosts`),`no-hosts`;Ntt(t,d,n);let p=Ftt(t,a,u,d,f),m=p.filter(e=>e.status===`written`),h=p.filter(e=>e.status===`failed`);if(m.length===0)return n.warn({event:`skill-install.failed`,reason:`write-failed`,entries:h},`Skill install failed — every destination write errored.`),await o(`failed`,c,`write-failed`),`failed`;try{await h$(t,`cli-hosts`,c,r,n)}catch(e){return n.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,err:e},`Skill install succeeded but sidecar write failed.`),await o(`failed`,c,`sidecar-write-failed`),`failed`}return h.length>0&&n.warn({event:`skill-install.partial`,version:c,entries:h},`Some agent hosts could not be written; the remaining copies are installed.`),n.info?.({event:`skill-install.installed`,version:c,hosts:d.map(e=>e.editorId),paths:m.map(e=>e.path)},`OpenKnowledge skill installed to ${m.length} location(s): ${m.map(e=>e.path).join(`, `)}`),await o(`installed`,c),G1({source:Qe,skills:[a],agents:d.map(e=>e.editorId),global:!0,version:c},{home:t,enabled:I1(t).enabled}),`installed`}function Ltt(e){return H(e,`Downloads`,`openknowledge.skill`)}function Rtt(e,t,n){let r=hq({detached:!0,stdio:`ignore`});try{return t===`darwin`?(n(`open`,[e],r).unref(),{ok:!0}):t===`win32`?(n(`cmd`,[`/c`,`start`,`""`,e],r).unref(),{ok:!0}):t===`linux`?(n(`xdg-open`,[e],r).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function ztt(e={}){let t=e.home??dc(),n=W(e.out??Ltt(t)),r=e.platformName??pc(),i=e.spawnFn??Os,a=e.logger,o=async(e,n,r)=>{await F1({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...n===void 0?{}:{version:n},...r===void 0?{}:{reason:r}},{homedir:()=>t,warn:a?.warn})};if(!e.force){let e=null;try{e=await g$()}catch(e){a?.warn?.({event:`skill-install.gate.version-read-failed`,err:e},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let n=null,r=null;try{[n,r]=await Promise.all([m$(t,`claude-cowork`,a),y7e(t,`claude-cowork`,a)])}catch(e){a?.warn?.({event:`skill-install.gate.read-failed`,err:e},`Could not read claude-cowork install-state; rebuilding.`)}if(n!==null&&n===e)return a?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`OpenKnowledge skill already delivered at current version; skipping rebuild.`),await o(`skip-current`,e),{status:`skip-current`,skillVersion:e,...r===null?{}:{recordedAt:r}}}}try{await EG(V(n),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await o(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let s;try{s=await h3e({outputPath:n,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await o(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let c;try{c=await g$()}catch{c=void 0}let l={status:`built`,outputPath:s.outputPath,size:s.size,sha256:s.sha256,skillVersion:c};if(c)try{await h$(t,`claude-cowork`,c,`server-build-and-open`,a)}catch(e){a?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:c,err:e},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await o(`built`,c),l;let u=Rtt(s.outputPath,r,i);return u.ok?(await o(`installed`,c),G1({source:Qe,skills:[RZ.project],agents:[`claude-desktop`],global:!0,version:c},{home:t,enabled:I1(t).enabled}),{...l,status:`installed`}):(await o(`built`,c,`handoff-${u.reason}`),{...l,handoffError:{reason:u.reason,message:u.message}})}function Btt(e){let{checkLocalOpSecurity:t}=e;return N$({"/api/install-skill":Z(fie,async(e,t,n)=>{if(n.out!==void 0&&!M$(n.out)){X(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{let e=await ztt({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}});Q(t,200,Br,e,{handler:`install-skill`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,n)=>t(e,n,{handler:`install-skill`})})},{mutating:[`/api/install-skill`]})}const Vtt=1024,Htt=[`anthropic`,`claude`],J1=`SKILL.md`;function Utt(e){let t=n0(e.name);if(!t.ok)return{ok:!1,error:t.error};let n=Jtt(e.frontmatter,e.name);if(!n.ok)return{ok:!1,error:n.error};let r=`---\n${Xtt(e.frontmatter)}---\n${e.body}`,i=[],a=[],o=Htt.filter(t=>e.name.includes(t));o.length>0&&(i.push(`Skill name contains ${o.map(e=>`"${e}"`).join(`, `)} — Anthropic's authoring guidance discourages vendor words in skill names.`),a.push(`skill-name-vendor-word`));let s=e.body.split(`
1072
1072
  `).length;return s>500&&(i.push(`SKILL.md body is ${s} lines — keep it under 500 for performance (every line is a recurring token cost). Move detail into one-level-deep references/.`),a.push(`skill-body-too-long`)),{ok:!0,content:r,warnings:i,warningCodes:a}}function Y1(e){let t=V(e),n=`${js(e)}${qS}`;try{for(let e of tc(t))e.startsWith(n)&&MG(H(t,e))}catch{}}function X1(e){let t=t0(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=Utt({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!n.ok)return{ok:!1,error:n.error};let{content:r,warnings:i,warningCodes:a}=n,{skillDir:o,filePath:s}=r0(e.skillsRoot,e.name);try{kG(o,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create skill directory at ${i0(e.skillsRoot,o)}: ${t.message}`}}}let c=!G(s);Y1(s);let l=JS(s);try{DG(l,r,`utf-8`),AG(l,s)}catch(t){try{MG(l)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill at ${i0(e.skillsRoot,s)}: ${t.message}`}}}return{ok:!0,path:i0(e.skillsRoot,s),created:c,warnings:i,warningCodes:a}}function Z1(e){let t=H(e.skillDir,J1),n;if(e.skillMd!==void 0)n=e.skillMd;else try{n=K(t,`utf-8`)}catch(e){return{ok:!1,stage:`read`,cause:e}}let{fenced:r,body:i}=Ut(n),a=Ma(r,{name:e.toName});if(!a.ok)return{ok:!1,stage:`patch`,error:a.error};Y1(t);let o=JS(t);try{DG(o,`${a.nextFenced}${i}`,`utf-8`),AG(o,t)}catch(e){try{MG(o)}catch{}return{ok:!1,stage:`write`,cause:e}}return{ok:!0}}function Q1(e,t){if(typeof t!=`string`||t.length===0||t.includes(`\0`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path.`}};let n=ga(t);if(n.length===0||n.some(e=>e===`..`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path: ${t}`}};if(n.length===1&&n[0]===J1)return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`SKILL.md is written through the skill write path, not as a bundle file.`}};let r=H(e,...n);return r!==e&&!r.startsWith(e+Rs)?{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Skill file escapes the skill dir: ${t}`}}:{ok:!0,abs:r}}function Wtt(e){let t=0,n=(r,i)=>{let a;try{a=tc(r,{withFileTypes:!0})}catch{return}for(let o of a){let a=i===``?o.name:`${i}/${o.name}`;xq(a)||(o.isDirectory()?n(H(r,o.name),a):o.isFile()&&(r!==e||o.name!==J1)&&t++)}};return n(e,``),t}function $1(e){let t=e.bytes??e.content??``,n=t0(e.skillsRoot);if(!n.ok)return{ok:!1,error:n.error};let r=n0(e.name);if(!r.ok)return{ok:!1,error:r.error};let{skillDir:i,filePath:a}=r0(e.skillsRoot,e.name);if(!G(a))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill "${e.name}" — create it (write its SKILL.md) before adding bundle files.`}};let o=Q1(i,e.relPath);if(!o.ok)return{ok:!1,error:o.error};let{abs:s}=o,c=typeof t==`string`?Buffer.byteLength(t,`utf-8`):t.length,l=e.limits?.maxFileBytes??262144,u=e.limits?.maxFiles??50;if(c>l)return{ok:!1,error:{code:`FILE_TOO_LARGE`,message:`Skill file ${e.relPath} is ${c} bytes — the per-file cap is ${l}.`}};let d=!G(s);if(d&&Wtt(i)>=u)return{ok:!1,error:{code:`TOO_MANY_FILES`,message:`Skill "${e.name}" already holds ${u} bundle files (the cap) — delete one before adding another.`}};try{kG(H(s,`..`),{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create directory for ${e.relPath}: ${t.message}`}}}Y1(s);let f=JS(s);try{typeof t==`string`?DG(f,t,`utf-8`):DG(f,t),AG(f,s)}catch(t){try{MG(f)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill file ${e.relPath}: ${t.message}`}}}return{ok:!0,path:i0(e.skillsRoot,s),created:d}}function Gtt(e){let t=t0(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=n0(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillDir:r}=r0(e.skillsRoot,e.name),i=Q1(r,e.relPath);if(!i.ok)return{ok:!1,error:i.error};let a=Q1(r,e.toRelPath);if(!a.ok)return{ok:!1,error:a.error};if(!G(i.abs))return{ok:!1,error:{code:`FILE_NOT_FOUND`,message:`No bundle file at ${e.relPath}.`}};if(G(a.abs))return{ok:!1,error:{code:`DEST_EXISTS`,message:`A bundle file already exists at ${e.toRelPath} — renames never overwrite.`}};try{kG(H(a.abs,`..`),{recursive:!0}),AG(i.abs,a.abs)}catch(t){return{ok:!1,error:{code:`RENAME_FAILED`,message:`Failed to rename ${e.relPath} -> ${e.toRelPath}: ${t.message}`}}}let o=H(i.abs,`..`);if(o!==r&&a0(o))try{IG(o)}catch{}return{ok:!0}}function Ktt(e){let t=t0(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=n0(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillDir:r}=r0(e.skillsRoot,e.name),i=Q1(r,e.relPath);if(!i.ok)return{ok:!1,error:i.error};let{abs:a}=i,o=G(a);if(o){try{oc(a).isDirectory()?FG(a,{recursive:!0,force:!0}):MG(a)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill file ${e.relPath}: ${t.message}`}}}let t=H(a,`..`);if(t!==r&&a0(t))try{IG(t)}catch{}}return{ok:!0,path:i0(e.skillsRoot,a),existed:o}}function e0(e){let t=t0(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=n0(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillsRoot:r}=t,{skillDir:i}=r0(e.skillsRoot,e.name),a=G(i);if(a)try{FG(i,{recursive:!0,force:!0})}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill at ${i0(e.skillsRoot,i)}: ${t.message}`}}}return Ytt(r),{ok:!0,path:i0(e.skillsRoot,i),existed:a}}async function qtt(e){let t=t0(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=n0(e.fromName);if(!n.ok)return{ok:!1,error:n.error};let r=n0(e.toName);if(!r.ok)return{ok:!1,error:r.error};let i=r0(e.skillsRoot,e.fromName),a=r0(e.skillsRoot,e.toName);if(i.skillDir===a.skillDir)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same skill.`}};if(!G(i.skillDir))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill at ${i0(e.skillsRoot,i.skillDir)}.`}};if(G(a.skillDir))return{ok:!1,error:{code:`SKILL_EXISTS`,message:`A skill already exists at ${i0(e.skillsRoot,a.skillDir)}.`}};let o;try{o=await e.relocate(i.skillDir,a.skillDir)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move skill: ${e.message}`}}}return{ok:!0,fromPath:i0(e.skillsRoot,i.skillDir),toPath:i0(e.skillsRoot,a.skillDir),committed:o}}function t0(e){return Ps(e)?{ok:!0,skillsRoot:e}:{ok:!1,error:{code:`BAD_SKILLS_ROOT`,message:`skillsRoot must be absolute`}}}function n0(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name is required.`}}:e.length>64?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must be ≤64 characters.`}}:no.test(e)?{ok:!0}:{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must match /^[a-z0-9-]+$/ (got: ${JSON.stringify(e)}). Lowercase letters, digits, hyphens — no slashes, dots, spaces, or uppercase.`}}}function Jtt(e,t){return!e||typeof e!=`object`?{ok:!1,error:{code:`BAD_FRONTMATTER`,message:`Skill frontmatter (name, description) is required.`}}:typeof e.name!=`string`||e.name.length===0?{ok:!1,error:{code:`SKILL_NAME_REQUIRED`,message:`Skill frontmatter.name is required.`}}:e.name===t?Ra(e.name)?{ok:!1,error:{code:`XML_TAG_IN_NAME`,message:"Skill frontmatter.name may not contain XML tags (`<...>`)."}}:typeof e.description==`string`?e.description.length>Vtt?{ok:!1,error:{code:`DESCRIPTION_TOO_LONG`,message:`Skill frontmatter.description must be ≤${Vtt} characters (got ${e.description.length}).`}}:Ra(e.description)?{ok:!1,error:{code:`XML_TAG_IN_DESCRIPTION`,message:"Skill frontmatter.description may not contain XML tags (`<...>`) — they break the Cowork parser and skill loader."}}:{ok:!0}:{ok:!1,error:{code:`SKILL_DESCRIPTION_REQUIRED`,message:`Skill frontmatter.description must be a string — it is the primary triggering surface (when to use the skill).`}}:{ok:!1,error:{code:`NAME_DIR_MISMATCH`,message:`Skill frontmatter.name (${JSON.stringify(e.name)}) must equal the skill directory name (${JSON.stringify(t)}).`}}}function r0(e,t){let n=H(e,t);return{skillDir:n,filePath:H(n,J1)}}function Ytt(e){if(G(e)&&a0(e))try{IG(e)}catch{}let t=Fs(H(e,`..`));if(t.endsWith(`${Rs}.ok`)&&G(t)&&a0(t))try{IG(t)}catch{}}function i0(e,t){let n=t.startsWith(e+Rs)?t.slice(e.length+1):t;return Fs(n).split(Rs).join(`/`)}function Xtt(e){return(0,Wc.stringify)({name:e.name,description:e.description,...e.metadata===void 0?{}:{metadata:e.metadata}})}function a0(e){try{return tc(e).length===0}catch{return!1}}const Ztt=new Map;function Qtt(e,t){Ztt.set(e,t)}function o0(e,t){let n=Ztt.get(e);if(n===void 0)return null;if(!no.test(e)||e.length>64)throw Error(`externalSkillAbsPath: invalid skill name ${JSON.stringify(e)}`);let r;if(t===null)r=W(n,`SKILL.md`);else{let e=t.split(`/`).filter(e=>e!==``&&e!==`.`);if(e.length===0||e.some(e=>e===`..`))throw Error(`externalSkillAbsPath: invalid bundle path ${JSON.stringify(t)}`);r=W(n,...e)}if(!r.startsWith(n+Rs))throw Error(`externalSkillAbsPath: path escape for ${JSON.stringify(e)}`);return r}function $tt(e){switch(e.kind){case`invalid_value`:return`${e.kind} (${e.key}: ${e.reason})`;case`reserved_key`:return`${e.kind} ('${e.key}' is reserved)`;case`unknown_key`:return`${e.kind} ('${e.key}' is not a recognized key)`;case`duplicate_target`:return`${e.kind} ('${e.key}' appears more than once)`;case`reorder_mismatch`:return`${e.kind} (expected: ${e.expected.join(`, `)}; got: ${e.got.join(`, `)})`;case`region_too_large`:return`${e.kind} (frontmatter region too large: ${e.bytes} > ${e.limit} bytes)`;case`parse_failed`:return`${e.kind} (frontmatter region unparseable: ${e.reason})`;case`invalid_path`:return`${e.kind} (${e.path.map(String).join(`.`)||`__path__`}: ${e.reason})`;default:return`unhandled frontmatter edit error (${String(e)})`}}function ent(e,t){return[...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({editor:e,root:t})),{editor:`agents`,root:t}]}const s0=ent(Vi,oi),c0=ent(Ji,oi);function l0(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`}function u0(e,t){let n=d0(e,t),r={},i;try{i=nc(e)}catch{return r}for(let{editor:t,root:a}of n){let n;try{n=nc(H(e,a))}catch{continue}if(n===H(i,a))continue;let o=U(i,n);o===``||o.startsWith(`..`)||Ps(o)||(r[t]=o.split(Rs).join(`/`))}return r}function tnt(e){return e===`project`?s0:c0}function nnt(e){let t=d0(e,`global`).map(t=>H(e,t.root)),n=H(e,`.ok`,ba);return t.includes(n)?t:[...t,n]}function d0(e,t){return rnt(t,Ctt(e))}function rnt(e,t){let n=tnt(e),r=new Set(n.map(e=>e.root));return[...n,...t.filter(e=>!r.has(e)).map(e=>({editor:e,root:e}))]}function f0(e){return new Set((e===`project`?s0:c0).map(e=>e.root))}function p0(e,t,n,r){return!f0(t).has(n)||G(H(e,Qa(n)))?!0:n===`.agents/skills`&&Nne.some(e=>e.scope===t&&G(H(r,e.dotDir)))}function int(e,t,n,r){let i=new Set([...d0(e,t).map(e=>e.root),qa]),a=[];for(let t of i){let i=H(e,t,n),o;try{o=Ys(i)}catch{continue}if(o.isSymbolicLink()){a.push(i);continue}iP(i)?.contentHash===r&&a.push(i)}return a}function ant(e,t){let n=new Map((t===`project`?s0:c0).map(e=>[e.editor,e.root])),r=new Set;for(let t of Object.keys(e)){let e=n.get(t);e===void 0?t.includes(`/`)&&r.add(t):r.add(e)}return r}function m0(e,t){let n=t===`project`?s0:c0;if(G(H(e,`.agents`)))return oi;let r=[...n].filter(e=>e.editor!==`agents`).sort((e,t)=>{let n=dP.indexOf(e.editor),r=dP.indexOf(t.editor);return(n===-1?dP.length:n)-(r===-1?dP.length:r)});for(let{root:t}of r)if(G(H(e,Qa(t))))return t;return null}function ont(e){return[...new Set((e===`project`?s0:c0).map(e=>`${Qa(e.root)}/`))]}function snt(e){try{if(!oc(H(e,`SKILL.md`)).isFile())return null}catch(e){if(l0(e))return null;throw e}let t=[],n=(e,r)=>{for(let i of tc(e,{withFileTypes:!0})){let a=H(e,i.name),o=r===``?i.name:`${r}/${i.name}`;if(i.isDirectory())QN.has(i.name)||n(a,o);else if(i.isFile()){let e=oc(a);t.push(`${o}:${e.size}:${e.mtimeMs}`)}}};return n(e,``),t.sort().join(`|`)}async function cnt(e){try{if(!(await Sc(H(e,`SKILL.md`))).isFile())return null}catch(e){if(l0(e))return null;throw e}let t=[],n=async(e,r)=>{for(let i of await yc(e,{withFileTypes:!0})){let a=H(e,i.name),o=r===``?i.name:`${r}/${i.name}`;if(i.isDirectory())QN.has(i.name)||await n(a,o);else if(i.isFile()){let e=await Sc(a);t.push(`${o}:${e.size}:${e.mtimeMs}`)}}};return await n(e,``),t.sort().join(`|`)}const h0=new Map;function lnt(e,t){let n=po(k(t.skillMd)??{});return{stamp:e,contentHash:t.contentHash,description:t.description,size:Ua(t),...n===void 0?{}:{pack:n}}}function unt(e){let t=snt(e);if(t===null)return null;let n=h0.get(e);if(n!==void 0&&n.stamp===t)return n;let r=iP(e);if(!r)return null;let i=lnt(t,r);return h0.set(e,i),i}function dnt(e){return unt(e)?.contentHash}const g0=new Map,fnt=new Map;function pnt(e,t){let n=g0.get(e);if(n!==void 0)return n;let r=(async()=>{let t=await cnt(e);if(t===null)return!0;if(h0.get(e)?.stamp===t)return!1;let n=await MMe(e);return n&&h0.set(e,lnt(t,n)),!1})().catch(e=>(mnt(t,e),!1)).then(t=>{fnt.set(e,t)}).finally(()=>g0.delete(e));return g0.set(e,r),r}function mnt(e,t){l0(t)||q(`in-place-skills`).warn({root:e,err:t},`[in-place-skills] skills not read ahead of the scan; the scan reads them synchronously`)}async function hnt(e){for(let{root:t}of _0(e,`global`).roots){let n=H(e,t),r;try{r=await yc(n)}catch(e){mnt(t,e);continue}for(let e of r)await pnt(H(n,e),t)}}function _0(e,t){let n=[],r={},i=[];try{let t=wtt(e);r=t.sources,i=t.roots,t.kind===`incomplete`&&n.push({scope:`scan`,error:t.error}),t.kind===`unparsable`&&n.push({scope:`ledger-parse`,error:t.error})}catch(e){n.push({scope:`scan`,error:e})}return{sourcePrefs:r,roots:rnt(t,i),failures:n}}function v0(e,t){let n=[],{sourcePrefs:r,roots:i,failures:a}=_0(e,t),o=e=>{a.push({scope:`scan`,error:e})},s=null;try{s=nc(e)}catch(e){l0(e)||o(e)}for(let{editor:c,root:l}of i){let i=H(e,l),u,d=!1;try{if(!oc(i).isDirectory())continue}catch(e){l0(e)||o(e);continue}try{d=s!==null&&nc(i)!==H(s,l),u=tc(i)}catch(e){o(e);continue}for(let e of u){let s=H(i,e);try{if(!oc(s).isDirectory())continue}catch(e){l0(e)||o(e);continue}let u;try{u=unt(s)}catch(t){a.push({scope:`bundle`,dir:`${l}/${e}`,error:t});continue}if(u)try{n.push({name:e,scope:t,editor:c,contentHash:u.contentHash,dir:`${l}/${e}`,description:u.description,size:u.size,...u.pack===void 0?{}:{pack:u.pack},viaLink:d||Ys(s).isSymbolicLink(),...d?{aliasRooted:!0}:{},...r[e]===c?{preferredSource:!0}:{}})}catch(e){o(e)}}}let{admittedDirs:c,canonicalDir:l}=PNe(n),u=new Set(l.values());return{skills:pP(n).filter(e=>c.has(e.canonical.dir)).filter(e=>u.has(e.canonical.dir)||!BZ(e.name)).sort((e,t)=>e.name.localeCompare(t.name)||Number(u.has(t.canonical.dir))-Number(u.has(e.canonical.dir))||e.contentHash.localeCompare(t.contentHash)).map(t=>{let r=null;try{r=nc(H(e,t.canonical.dir))}catch{r=null}let i=t=>{if(r===null)return!1;try{return nc(H(e,t))===r}catch{return!1}},a=t.copies.filter(e=>e.aliasRooted!==!0&&(e.viaLink||!i(e.dir))),o=BZ(t.canonical.name)?[]:n.filter(e=>e.name===t.canonical.name&&e.contentHash!==t.contentHash).map(e=>e.editor);return{name:t.canonical.name,description:t.canonical.description,dir:t.canonical.dir,hosts:[t.canonical.editor,...a.map(e=>e.editor)],linkedHosts:[t.canonical,...a].filter(e=>e.viaLink).map(e=>e.editor),conflictHosts:o,copyDirs:a.filter(e=>!e.viaLink).map(e=>e.dir),contentHash:t.contentHash,size:t.canonical.size,...t.canonical.pack===void 0?{}:{pack:t.canonical.pack}}}),occurrences:n,failures:a}}function gnt(e){return e.filter(e=>!t3e(e.name))}function y0(e){return gnt(v0(e,`project`).skills)}function b0(e){return v0(e,`global`).skills}async function x0(e){return vnt(e)&&await hnt(e),b0(e)}function _nt(e){let t=fnt.get(e);if(t===void 0)return!0;if(!t)return!1;try{return oc(H(e,`SKILL.md`)).isFile()}catch{return!1}}function vnt(e){for(let{root:t}of _0(e,`global`).roots){let n=H(e,t),r;try{r=tc(n)}catch{continue}if(r.some(e=>_nt(H(n,e))))return!0}return!1}const ynt=[...c0].sort((e,t)=>{let n=dP.indexOf(e.editor),r=dP.indexOf(t.editor);return(n===-1?dP.length:n)-(r===-1?dP.length:r)||e.editor.localeCompare(t.editor)});function S0(e,t){for(let{root:n}of ynt){let r=H(e,n,t);try{if(G(H(r,`SKILL.md`)))return r}catch{}}return null}function bnt(e){return new Set(d0(e,`project`).map(e=>e.root))}function C0(e){return e.slice(e.lastIndexOf(`/`)+1)}function xnt(e){return e.slice(0,e.lastIndexOf(`/`))}function Snt(e,t,n){let r=n.failures.some(e=>e.scope===`ledger-parse`),i=new Set(n.failures.flatMap(e=>e.scope===`bundle`?[e.dir]:[])),a=new Set(n.occurrences.map(e=>e.dir)),o=new Map;for(let{name:e}of n.occurrences)o.set(e,(o.get(e)??0)+1);let s=f0(`project`),c=e=>i.has(e)||r&&(!s.has(xnt(e))||a.has(e)&&(o.get(C0(e))??0)>=2),l=new Set([...e].filter(c).map(C0));return new Set([...[...e].filter(e=>l.has(C0(e))&&(c(e)||a.has(e))),...[...t].filter(e=>!l.has(C0(e)))])}function Cnt(e,t){let n=v0(e,`project`),r=new Set(gnt(n.skills).map(e=>e.dir)),[i]=n.failures;if(i===void 0)return r;if(t===void 0||n.failures.some(e=>e.scope===`scan`))throw i.error;return Snt(t,r,n)}const wnt=q(`installed-skills-marker`);function w0(e){return H(e,...Zee)}const Tnt=L1();function Ent(e,t){return Tnt(w0(e),t)}function T0(e){let t=w0(e);if(!G(t))return _();try{return Qr(K(t,`utf-8`))??_()}catch(e){return wnt.warn({err:e,path:t},`installed-skills marker unreadable`),_()}}function Dnt(e){let t=w0(e);if(!G(t))return{ok:!0,state:_()};let n;try{n=K(t,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?{ok:!0,state:_()}:{ok:!1,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}let r=Qr(n);return r===null?{ok:!1,reason:`its contents are not an installed-skills marker this server understands`}:{ok:!0,state:r}}function Ont(e){let t=Dnt(e);if(t.ok)return t.state;let n=w0(e);throw wnt.error({path:n,reason:t.reason,err:t.cause},`refusing to rewrite the installed-skills marker because it could not be read — rewriting it would replace every install it records with this one`),Error(`Refusing to rewrite ${n}: ${t.reason}`)}async function knt(e,t){let n=Yne.safeParse(t);if(!n.success)throw Error(`Refusing to write invalid installed-skills marker: ${n.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let r=w0(e);await EG(V(r),{recursive:!0}),await YS(r,`${JSON.stringify(n.data,null,2)}\n`,{fs:LG})}async function E0(e,t,n){return Ent(e,async()=>{let r=Ont(e);await knt(e,{...r,skills:{...r.skills,[t]:n}})})}async function D0(e,t){return Ent(e,async()=>{let n=Ont(e),r=n.skills[t]??null;if(r===null)return null;let{[t]:i,...a}=n.skills;return await knt(e,{...n,skills:a}),r})}function O0(e,t){return`${e}:${t}`}function Ant(e){return H(FJ(e),Ute)}function k0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function A0(e){return typeof e==`string`?e:``}const jnt=()=>({ok:!0,store:{schema:1,retained:{}}});function Mnt(e){let t=Ant(e);if(!G(t))return jnt();let n;try{n=K(t,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?jnt():{ok:!1,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}let r;try{r=JSON.parse(n)}catch{return{ok:!1,reason:`it is not valid JSON`}}if(!k0(r)||!k0(r.retained))return{ok:!1,reason:`its contents are not a retained-record ledger`};if(r.schema!==1)return{ok:!1,reason:typeof r.schema==`number`?`it declares schema ${r.schema}, which this server does not understand (it writes schema 1)`:`it declares a schema this server does not understand (it writes schema 1)`};let i={};for(let[e,t]of Object.entries(r.retained)){let n=k0(t)?t:{};i[e]={retainedAt:A0(n.retainedAt),from:A0(n.from),to:A0(n.to),sourceState:Xne(n.sourceState)?n.sourceState:`unknown`,reason:A0(n.reason),retainedContentHash:A0(n.retainedContentHash)}}return{ok:!0,store:{schema:1,retained:i}}}function j0(e,t,n){let r=Mnt(e);if(!r.ok)return{state:`unreadable`,reason:r.reason,...r.cause===void 0?{}:{cause:r.cause}};let i=r.store.retained[O0(t,n)];return i===void 0?{state:`none`}:{state:`record`,record:i}}const Nnt=L1();function Pnt(e,t){let n=Ant(e);return Nnt(n,async()=>{let r=Mnt(e);if(!r.ok)throw q(`skill-move-retained`).error({event:`skill-move-retained.unreadable`,path:n,reason:r.reason},`refusing to rewrite the retained-destination ledger because it could not be read — rewriting it would replace every record it holds with this one`),Error(`Refusing to rewrite ${n}: ${r.reason}`);t(r.store.retained)&&(await EG(V(n),{recursive:!0}),await YS(n,`${JSON.stringify(r.store,null,2)}\n`,{fs:LG}))})}function Fnt(e,t,n,r){return Pnt(e,e=>(e[O0(t,n)]=r,!0))}function Int(e,t,n){return Pnt(e,e=>{let r=O0(t,n);return r in e&&(delete e[r],!0)})}function M0(e){return(e===`.ok`||e.startsWith(`.ok/`))&&e!==`.ok/skills`}async function N0(e,t,n){await U1(e,e=>{e.sources={...e.sources,[t]:n}})}async function Lnt(e,t,n){await U1(e,e=>{e.folders={...e.folders,[t]:n}})}function Rnt(e){return H1(e).folders??{}}async function znt(e,t){await U1(e,e=>{let n=new Set(e.roots??[]);n.has(t)||(n.add(t),e.roots=[...n].sort())})}function Bnt(e,t){let n=H1(e).preferences?.[t];return n===`link`||n===`copy`?n:void 0}function P0(e){let t={};for(let[n,r]of Object.entries(H1(e).skills)){let i=r.filter(t=>{let n=z1(e,t.path);return n!==null&&G(H(n,`SKILL.md`))});i.length>0&&(t[n]=i)}return t}async function Vnt(e,t,n){await U1(e,e=>{let r=(e.skills[t]??[]).filter(e=>e.path!==n);e.skills={...e.skills},r.length>0?e.skills[t]=r:delete e.skills[t]})}async function Hnt(e,t){await U1(e,e=>{e.skills[t]!==void 0&&(e.skills={...e.skills},delete e.skills[t])})}async function F0(e,t,n){await U1(e,e=>{e.skills={...e.skills};let r=(e.skills[t]??[]).filter(e=>e.path!==n.path);r.push(n),e.skills[t]=r})}async function I0(e,t,n){let r=P0(e),i=n??y0(t);for(let t of i){let n=new Set((r[t.name]??[]).map(e=>e.path));for(let i of t.copyDirs){if(n.has(i)||z1(e,i)===null)continue;let a={path:i,mode:`copy`,hash:t.contentHash};await F0(e,t.name,a),r[t.name]=[...r[t.name]??[],a]}}if(Object.keys(r).length===0)return 0;let a=0;for(let n of i){let i=r[n.name];if(!i)continue;let o=z1(t,n.dir);if(o!==null)for(let t of i){if(t.mode!==`copy`||t.hash===void 0)continue;let r=z1(e,t.path);if(r===null||r===o)continue;let i=iP(r)?.contentHash;if(i!==void 0){if(i===n.contentHash){t.hash!==i&&await F0(e,n.name,{...t,hash:i});continue}i===t.hash&&(r=z1(e,t.path),r!==null&&(FG(r,{recursive:!0,force:!0}),jG(o,r,{recursive:!0,dereference:!0}),await F0(e,n.name,{...t,hash:n.contentHash}),a+=1))}}}return a}function Unt(e,t,n){let r;try{r=Ys(e)}catch{return{kind:`absent`}}if(r.isSymbolicLink())try{return nc(e)===nc(t)?{kind:`symlink`,resolution:`target`}:{kind:`symlink`,resolution:`elsewhere`}}catch{return{kind:`symlink`,resolution:`dangling`}}if(!r.isDirectory())return{kind:`other`};try{if(nc(e)===nc(t))return{kind:`dir`,identity:`is-target`}}catch{return{kind:`dir`,identity:`different`}}return iP(e)?.contentHash===n?{kind:`dir`,identity:`same-content`}:{kind:`dir`,identity:`different`}}function L0(e,t){let n=V0(t);return e.filter(e=>n.includes(e))}const Wnt=`open-knowledge`,Gnt=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Knt=[/^<{7} /m,/^={7}$/m,/^>{7} /m];function qnt(e){let t=e.match(Gnt);if(!t)return null;try{let e=(0,Wc.parse)(t[1]??``);return e&&typeof e==`object`&&!Array.isArray(e)?e:null}catch{return null}}function R0(e,t,n){let r=[],i=[],a=H(e,`SKILL.md`),o=G(H(e,`scripts`))&&oc(H(e,`scripts`)).isDirectory(),s=t.startsWith(Wnt)&&Gt[t]===void 0;if(!n?.allowReservedName&&s&&r.push(`"${t}" uses the reserved \`${Wnt}*\` prefix (reserved for OK's shipped skills) — choose another name.`),!G(a))return r.push(`No SKILL.md found at ${e}.`),{ok:r.length===0,errors:r,warnings:i,hasScripts:o};let c;try{c=K(a,`utf-8`)}catch(e){return r.push(`Cannot read SKILL.md: ${e.message}.`),{ok:!1,errors:r,warnings:i,hasScripts:o}}Knt.some(e=>e.test(c))&&r.push("SKILL.md contains git conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`). Resolve the conflict before installing.");let l=qnt(c);if(l===null)r.push("SKILL.md has no valid `---` frontmatter block (name + description required).");else{let e=l.name,n=l.description;typeof e!=`string`||e.length===0?r.push(`SKILL.md frontmatter.name is missing or empty.`):e!==t&&r.push(`SKILL.md frontmatter.name ("${e}") must equal the skill directory ("${t}").`),(typeof n!=`string`||n.length===0)&&i.push("This skill has no `description`. Add one so agents know when to use it."),(typeof e==`string`&&Ra(e)||typeof n==`string`&&Ra(n))&&r.push("SKILL.md name/description contains XML tags (`<...>`), which break the skill loader.")}return{ok:r.length===0,errors:r,warnings:i,hasScripts:o}}function Jnt(e){let t=vn();return ra.filter(n=>{let r=vie(n,t);return r!==null&&G(W(e,r))})}function z0(e,t){if(t&&t.length>0){let e=new Set(ra);return t.filter(t=>e.has(t))}return Jnt(e)}function B0(e){return e===`global`?Ji:Vi}function V0(e){return e===`global`?ao:ra}function H0(e,t,n,r=Vi){let i=r[t];return i===null?null:W(e,i,n)}function U0(e,t,n,r=Vi){return t===`agents`?W(e,oi,n):H0(e,t,n,r)}function W0(e,t){if(!G(t))return!1;try{let n=U(nc(e),nc(t));return n.startsWith(`..`)||Ps(n)}catch{return!0}}function Ynt(e,t){if(!G(e)||!G(t))return!1;try{return nc(e)===nc(t)}catch{return!1}}function Xnt(e){let t=e?.code;return t===`EPERM`||t===`EACCES`}function G0(e,t,n){try{return PG(e,t,`dir`),`link`}catch(e){if(!Xnt(e))throw e;return FG(t,{recursive:!0,force:!0}),jG(n,t,{recursive:!0,dereference:!0}),`copy`}}function Znt(e){return`This system does not allow creating symlinks, so ${e.join(`, `)} got a copy instead of a link. On Windows, creating symlinks needs administrator rights or Developer Mode.`}function K0(e,t,n){let r=W(n),i=U(W(e),r);return i!==``&&!i.startsWith(`..`)&&!Ps(i)?U(t,r):r}function q0(e,t,n,r,i=`symlink`,a=Vi){let o=[];for(let s of r){let r=H0(n,s,t,a);if(r===null)continue;let c=V(r);if(W0(n,c))continue;if(Ynt(c,V(e))){o.push(s);continue}let l=W(r)===W(e);if(!l&&G(r))try{l=nc(r)===nc(e)}catch{l=!1}if(l){o.push(s);continue}FG(r,{recursive:!0,force:!0}),kG(c,{recursive:!0}),i===`copy`?jG(e,r,{recursive:!0,dereference:!0}):G0(K0(n,c,e),r,e),o.push(s)}return o}function Qnt(e,t){if(!BZ(t))return!1;try{return!Ys(e).isSymbolicLink()&&G(H(e,`SKILL.md`))}catch{return!1}}function J0(e,t,n){let r=Unt(e,t,n);switch(r.kind){case`absent`:return`absent`;case`other`:return`different`;case`symlink`:return r.resolution===`target`?`link-to-canonical`:`link`;case`dir`:return r.identity===`is-target`?`canonical-dir`:r.identity===`same-content`?`same-copy`:`different`}}function Y0(e){let{canonicalAbs:t,canonicalHash:n,canonicalRootRel:r,name:i,cwd:a,targets:o}=e,s=e.roots??Vi,c=e.mode??`copy`,l=[],u=[],d=[],f=(e,n,r)=>{FG(e,{recursive:!0,force:!0}),kG(n,{recursive:!0}),c===`link`?G0(K0(a,n,t),e,t)===`copy`&&d.push(r):jG(t,e,{recursive:!0,dereference:!0})};for(let d of o){if(d===`agents`?r===`.agents/skills`:s[d]===r){let r=U0(a,d,i,s);if(r!==null&&!W0(a,V(r))){let i=J0(r,t,n);(c===`link`&&e.convertCopies===!0&&i===`same-copy`||c===`copy`&&e.convertLinks===!0&&i===`link-to-canonical`)&&f(r,V(r),d)}l.push(d);continue}let o=U0(a,d,i,s);if(o===null)continue;let p=V(o);if(!W0(a,p)){try{if(nc(p)!==H(nc(a),U(a,p)))continue}catch{}switch(J0(o,t,n)){case`canonical-dir`:l.push(d);break;case`link-to-canonical`:c===`copy`&&e.convertLinks===!0&&f(o,p,d),l.push(d);break;case`same-copy`:c===`link`&&e.convertCopies===!0&&f(o,p,d),l.push(d);break;case`different`:if(Qnt(o,i)){f(o,p,d),l.push(d);break}u.push(d);break;case`link`:case`absent`:f(o,p,d),l.push(d)}}}return{hosts:l,conflicted:u,linkFallbacks:d}}function X0(e){let{canonicalHash:t,name:n,cwd:r,newTarget:i}=e,a=e.roots??Vi,o;try{o=nc(e.canonicalAbs)}catch{return{ok:!1,reason:`target-unusable`}}try{if(Ys(o).isSymbolicLink()||!Ys(o).isDirectory())return{ok:!1,reason:`target-unusable`}}catch{return{ok:!1,reason:`target-unusable`}}let s=e.destDirAbs??U0(r,i,n,a);if(s===null)return{ok:!1,reason:`target-missing`};if(W(s)===o)return{ok:!0,newAbs:s};let c=V(s);if(W0(r,c))return{ok:!1,reason:`target-unusable`};switch(J0(s,o,t)){case`canonical-dir`:return{ok:!0,newAbs:s};case`different`:return{ok:!1,reason:`target-unusable`};case`same-copy`:try{if(Ys(s).isSymbolicLink()||!G(H(s,`SKILL.md`)))return{ok:!1,reason:`target-unusable`}}catch{return{ok:!1,reason:`target-unusable`}}FG(o,{recursive:!0,force:!0});break;case`link`:case`link-to-canonical`:FG(s,{recursive:!0,force:!0}),kG(c,{recursive:!0}),AG(o,s);break;case`absent`:kG(c,{recursive:!0}),AG(o,s)}return!G(H(s,`SKILL.md`))||Ys(s).isSymbolicLink()?{ok:!1,reason:`target-unusable`}:(e.leaveLinkBehind===!0&&!G(o)&&PG(K0(r,V(o),s),o,`dir`),Z0({name:n,cwd:r,roots:a,target:s,skip:[s,o],alsoClaim:[o,s]}),{ok:!0,newAbs:s})}function $nt(e){return[`agents`,...V0(e===Ji?`global`:`project`)]}function ert(e,t,n){return $nt(n).map(r=>U0(e,r,t,n)).filter(e=>e!==null)}function Z0(e){let{name:t,cwd:n,roots:r,target:i}=e,a=new Set((e.skip??[]).map(e=>W(e))),o=new Set((e.alsoClaim??[]).map(e=>W(e))),s=e.slots??ert(n,t,r);for(let e of s){if(a.has(W(e)))continue;try{if(!Ys(e).isSymbolicLink())continue}catch{continue}let t=null;try{t=nc(e)}catch{t=null}t!==null&&!o.has(t)||(FG(e,{recursive:!0,force:!0}),PG(K0(n,V(e),i),e,`dir`))}}function Q0(e){let{canonicalHash:t,name:n,cwd:r,targets:i}=e,a=e.roots??Vi,o;try{o=nc(e.canonicalAbs)}catch{return[]}let s=[];for(let e of i){let i=U0(r,e,n,a);if(i!==null&&!W0(r,V(i)))switch(J0(i,o,t)){case`same-copy`:case`link`:case`link-to-canonical`:FG(i,{recursive:!0,force:!0}),s.push(e);break;case`different`:Qnt(i,n)&&(FG(i,{recursive:!0,force:!0}),s.push(e))}}return s.length>0&&Z0({name:n,cwd:r,roots:a,target:o}),s}function $0(e,t,n,r=Vi){let i=[];for(let a of n){let n=H0(t,a,e,r);if(n===null)continue;let o=!1;try{Ys(n),o=!0}catch{o=!1}o&&(FG(n,{recursive:!0,force:!0}),i.push(a))}return i}function trt(e){try{return G(e)?e2(e).filter(e=>e!==`SKILL.md`):[]}catch{return[]}}function e2(e,t=``){let n=[];for(let r of tc(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;xq(i)||(r.isDirectory()?n.push(...e2(H(e,r.name),i)):r.isFile()&&n.push(i))}return n.sort()}function nrt(e){if(!G(e))return[];let t=[];for(let n of e2(e)){if(n===`SKILL.md`)continue;let r=null;try{let t=K(H(e,n));t.length<=262144&&!t.includes(0)&&(r=t.toString(`utf-8`))}catch(e){if(e?.code!==`ENOENT`)throw e;r=null}t.push({path:n,text:r})}return t}function rrt(e){let t=[];G(W(e,`SKILL.md`))&&t.push(`SKILL.md`);let n=W(e,`references`);if(!G(n))return t;let r=(e,n)=>{let i;try{i=tc(e,{withFileTypes:!0})}catch{return}for(let a of i){let i=n?`${n}/${a.name}`:a.name;a.isDirectory()?r(W(e,a.name),i):a.isFile()&&a.name.toLowerCase().endsWith(`.md`)&&t.push(`references/${i}`)}};return r(n,``),t}function irt(e){let{base:t,scope:n,fromName:r,toName:i}=e;if(r===i)return[];let a=q(`skill-ref-rename`),o;try{o=n===`project`?y0(t):b0(t)}catch(e){return a.warn({err:e,scope:n},`skill scan failed; refs to the old name are left as authored`),[]}let s=[];for(let e of o){let n=W(t,e.dir);for(let t of rrt(n)){let o=W(n,t),c;try{c=K(o,`utf-8`)}catch(e){a.warn({err:e,absPath:o},`unreadable skill markdown; skipped`);continue}let l=yee(c,r,i);if(l!==c){try{DG(o,l,`utf-8`)}catch(e){a.warn({err:e,absPath:o},`skill ref rewrite could not be written; skipped`);continue}s.push({dir:e.dir,rel:t,absPath:o,markdown:l})}}}return s}function t2(e){return G(e)?ee(K(e,`utf-8`))||(q(`skills-lock`).warn({lockPath:e},`skills-lock.json is unreadable; continuing with an empty lock (import provenance for this project is lost)`),rn()):rn()}function art(e){if(!G(e))return{ok:!0,lock:rn()};let t;try{t=K(e,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?{ok:!0,lock:rn()}:{ok:!1,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}let n=ee(t);return n===null?{ok:!1,reason:`its contents are not a skills lock this server understands`}:{ok:!0,lock:n}}const ort=L1();function n2(e,t){return ort(e,async()=>{let n=art(e);if(!n.ok)throw q(`skills-lock`).error({lockPath:e,reason:n.reason,err:n.cause},`refusing to rewrite skills-lock.json because it could not be read — rewriting it would replace every import it records with this one`),Error(`Refusing to rewrite ${e}: ${n.reason}`);let r=n.lock,i=t(r)??r;await EG(V(e),{recursive:!0}),await YS(e,`${JSON.stringify(i,null,2)}\n`,{fs:LG})})}function r2(e,t){let n=Object.keys(e).join(`, `);return async(r,i)=>{let a=r.method===void 0?void 0:e[r.method];if(a){await a(r,i);return}X(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:t.handler,extraHeaders:{Allow:n}})}}function srt(e){let{validateSkillName:t,parseSkillScope:n,skillsHome:r,projectDir:i,resolveBuiltinSkillDir:a,parseFrontmatterDoc:o,resolveSkillDirForRead:s,skillRelPath:c,derivedDocumentIndex:l,contentFilter:u,bumpSkillsCatalogGen:d,settleSkillCatalog:f,invalidateSkillCatalog:p,scheduleDeferredIgnoreRebuild:m,recordDerivedDocumentBestEffort:h,getPrincipal:g,rejectReservedBuiltinSkill:_,contentDir:v,attributeOkArtifactWrite:y,scheduleOkArtifactFlush:b,signalChannel:x,checkSkillDocConflictGate:S,extractAgentIdentity:C,sessionManager:w,flushDiskAndDetectOutcome:T,respondStaleExternalWrite:E,respondPersistenceFailure:D,respondDiskDivergence:O,okArtifactKey:k,resolveSkillsRoot:ee,extractActorIdentityFromQuery:A,captureAndCloseDocuments:j,log:M,commitOkArtifactWrite:N,skillInstallBase:te,uninstallSkillFromHostDirs:ne,renameTrackedPathInGit:re,renamePathOnDisk:ie,localSkillHash:ae,shadowHeadSha:oe,artifactWriterId:se,checkLocalOpSecurity:ce,effectiveSkillRoot:le}=e;function ue(e,t){let n=e===`project`?i:r;if(!n)return`symlink`;try{return t2(H(n,...Qn)).skills[t]===void 0?`symlink`:`copy`}catch{return`symlink`}}function de(e){let t=e===`project`?i:r;return t?H(t,...Qn):null}function fe(e,t,n,r={}){let i=de(e);return i?n2(i,e=>{let i=e.skills[t];if(!i)return e;let a={...e.skills};return delete a[t],a[n]={...i,...r},{...e,skills:a}}):Promise.resolve()}async function pe(e,t,n,r=n){let i=de(e),a=de(t);if(!i||!a)return!1;let o=t2(i).skills[n];if(!o)return!1;let s={...o};return t===`global`&&delete s.baselineRef,await n2(a,e=>({...e,skills:{...e.skills,[r]:s}})),await n2(i,e=>{let t={...e.skills};return delete t[n],{...e,skills:t}}),!0}function me(e,t,n){let r=de(e);return r?n2(r,e=>{let r=e.skills[t];return r?{...e,skills:{...e.skills,[t]:{...r,...n}}}:e}):Promise.resolve()}function he(e,t){let n=W(e,t,`references`);if(!G(n))return[];let r=[],i=(e,t)=>{for(let n of tc(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(W(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}async function ge(e,t,n){if(!l){q(`skill-move`).warn({fromName:t,toName:n},`no derived-document index available — skipping re-index of the moved skill (its old entries will be dropped with no replacement)`);return}let r=[],i=(e,t,n)=>{let i;try{i=K(n,`utf-8`)}catch(i){q(`skill-move`).warn({err:i,absFile:n,oldDocName:e,newDocName:t},`relocated skill file unreadable after move — dropping the old index entry with no replacement`),r.push({kind:`delete`,documentName:e});return}r.push({kind:`rename`,oldDocumentName:e,newDocumentName:t,markdown:i})},a=U(v,e).split(Rs).join(`/`),o=(e,t)=>`${a}/${e}/${t?t.replace(/\.mdx?$/i,``):`SKILL`}`;i(o(t),o(n),W(e,n,`SKILL.md`));for(let r of he(e,n))i(o(t,r),o(n,r),W(e,n,r));await l.recordDirectMutations(r)}async function _e(e,t){if(!l||e.length===0)return;let n=[];for(let r of e)r.dir.split(`/`).pop()!==t&&n.push({kind:`link-rewrite`,documentName:`${r.dir}/${r.rel.replace(/\.mdx?$/i,``)}`,markdown:r.markdown});n.length>0&&await l.recordDirectMutations(n)}let ve=Z($a,async(e,l)=>{try{let u=new URL(e.url??``,`http://localhost`),d=u.searchParams.get(`name`)??``;if(!t(d,l,`skill-get`))return;let f=n(u.searchParams.get(`scope`),l,`skill-get`);if(f===null)return;if(BZ(d)){let e=f===`global`?r:i,t=e?a(e,d,f,u.searchParams.get(`host`)??void 0):null;if(t){let{frontmatter:e,body:n}=o(await vc(t.skillMd,`utf-8`));Q(l,200,Eee,{skill:{name:d,scope:f,path:t.relPath,frontmatter:{name:typeof e.name==`string`?e.name:d,description:typeof e.description==`string`?e.description:``},body:n,files:nrt(t.dir),managed:!0}},{handler:`skill-get`});return}}let p=u.searchParams.get(`host`)??void 0,m=s(f,d,p);if(m===null){X(l,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:p===void 0?`Skill "${d}" not found in ${f} scope.`:`No skill "${d}" (${f}) in ${p}.`});return}let h=W(m,`SKILL.md`),{frontmatter:g,body:_}=o(await vc(h,`utf-8`));Q(l,200,Eee,{skill:{name:d,scope:f,path:c(h,f),frontmatter:{name:typeof g.name==`string`?g.name:d,description:typeof g.description==`string`?g.description:``},body:_,files:nrt(m)}},{handler:`skill-get`})}catch(e){X(l,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0});async function ye(e,t){!l||$K(e)||(u&&(d(),u.refreshInPlaceSkillDirs(),m()),h(e,t,`skill-put`))}let be=Z(Ire,async(e,n,i)=>{try{let e=v$(i,g);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!t(i.name,n,`skill-put`)||_(i.name,n,`skill-put`))return;let a=Utt({name:i.name,body:typeof i.body==`string`?i.body:``,frontmatter:{name:i.frontmatter.name,description:i.frontmatter.description}});if(!a.ok){X(n,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:a.error.code,cause:Error(a.error.message)});return}let o=i.scope===`project`?v:r,c=s(i.scope,i.name);if(c===null){let t=m0(o,i.scope);if(t===null){X(n,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-put`,detail:`NO_USABLE_SKILL_HOME`});return}let r=X1({skillsRoot:W(o,t),name:i.name,body:typeof i.body==`string`?i.body:``,frontmatter:{name:i.frontmatter.name,description:i.frontmatter.description}});if(!r.ok){X(n,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}i.scope===`project`&&(y(e,`${t}/${i.name}/SKILL`,`skill-create: ${t}/${i.name}/SKILL.md`),b(`skill-put`)),await ye(i.scope===`project`?`${t}/${i.name}/SKILL`:gn(`global`,i.name),a.content),x?.(`files`),Q(n,200,Ii,{path:`${t}/${i.name}/SKILL.md`,created:!0,warnings:r.warnings,warningCodes:r.warningCodes},{handler:`skill-put`});return}let l=U(o,c).split(Rs).join(`/`),u=`${l}/SKILL.md`,d=i.scope===`project`?`${l}/SKILL`:gn(i.scope,i.name);if(S(d,`skill-put`,n))return;let{agentId:f,agentName:p,colorSeed:m,clientName:h}=C(i),ee=await w.getSession(d,f,{displayName:p,colorSeed:m,clientName:h});ee.dc.document.transact(()=>{dG(ee.dc.document,a.content,`agent`)},ee.origin);let A=await T(d);if(A?.kind===`failure`){D(n,A.failure,`skill-put`);return}if(A?.kind===`divergence`){O(n,`skill-put`);return}if(A?.kind===`stale-external-write`){E(n,`skill-put`,d);return}i.scope===`project`&&(y(e,k(`skill`,``,i.name),`skill-edit: ${u}`),b(`skill-put`)),await ye(d,a.content),x?.(`files`),Q(n,200,Ii,{path:u,created:!1,warnings:a.warnings,warningCodes:a.warningCodes},{handler:`skill-put`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`});function xe(e,t){let n=e===`project`?v:r,i=(e===`project`?y0(v):b0(r)).find(e=>e.name===t);return i?Q0({canonicalAbs:W(n,i.dir),canonicalHash:i.contentHash,name:t,cwd:n,targets:i.hosts.filter(e=>zi(e)),roots:B0(e)}):[]}let Se=Z($a,async(e,r)=>{try{let i=new URL(e.url??``,`http://localhost`),a=i.searchParams.get(`name`)??``;if(!t(a,r,`skill-delete`))return;let o=n(i.searchParams.get(`scope`),r,`skill-delete`);if(o===null)return;let s=i.searchParams.get(`host`)??void 0,{root:c,dirRel:l,realDir:u}=le(o,a,s),f=s===void 0?te(o):void 0,p=f===void 0?{state:`none`}:j0(f,o,a),m=p.state===`record`&&p.record.sourceState!==`intact`&&p.record.retainedContentHash!==``&&u!==null?ke(u):void 0;if(s!==void 0&&u===null){X(r,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-delete`,detail:`No skill "${a}" (${o}) in ${s}.`});return}let h=A(i,g);if(h.kind===`invalid-summary`){X(r,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await j(o===`project`?[...new Set([`${l}/SKILL`,gn(o,a)])]:[gn(o,a,s)],`deleted-upstream`),s===void 0&&xe(o,a);let _=e0({skillsRoot:c,name:a}),v=ee(o);if(s===void 0&&_.ok&&v!==c&&G(W(v,a,`SKILL.md`))){let e=e0({skillsRoot:v,name:a});e.ok||M.warn({name:a,scope:o,detail:e.error.code},`[skill-delete] legacy store resident survived the delete`)}if(!_.ok){let e=_.error.code===`UNLINK_FAILED`?500:400;X(r,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:_.error.code,cause:Error(_.error.message)});return}_.existed&&(o===`project`&&(y(h,l,`skill-delete: ${l}`),d(),N(`skill-delete`)),x?.(`files`));let b=te(o),S=[];if(s===void 0&&b)try{await ne(b,a,o)}catch(t){M.error({requestId:DJ(e),handler:`skill-delete`,name:a,scope:o,err:t},`[skill-delete] skill content removed, but install bookkeeping could not be updated`),S.push(`The skill was deleted, but this server could not update its install records (${Me(t)}). A stale entry may remain until that file is repaired.`)}if(s===void 0){if(p.state===`record`&&p.record.sourceState!==`intact`){let t=p.record,n=t.retainedContentHash!==``&&m?.ok===!0&&t.retainedContentHash===m.hash,r=m!==void 0&&!m.ok&&m.kind!==`absent`,i=t.from===``?`an earlier move`:`a move of "${t.from}"`,s=t.retainedAt?` on ${t.retainedAt}`:``;(n||r)&&M.error({requestId:DJ(e),handler:`skill-delete`,name:a,scope:o,from:t.from,retainedAt:t.retainedAt,sourceState:t.sourceState,verified:n,...r&&m.kind===`read-error`?{err:m.cause}:{}},n?`[skill-delete] deleted a copy this server retained when an earlier move failed to remove its source; the source was never verified unchanged, so files that only existed here may now be gone`:`[skill-delete] deleted a directory carrying an unverified retained-copy record; this server could not read that directory before removing it, so it could not confirm whether it was the copy an earlier failed move retained`),n?S.push(`A recovery copy was deleted: ${i} failed to remove its source${s}, and this server kept this copy in case it held files that failed removal had already deleted. That source was never verified unchanged. Check the other location before relying on this deletion.`):r&&S.push(`A directory this server could not read was deleted: ${i} failed to remove its source${s}, and this server has a record of keeping a copy under this name in case it held files that failed removal had already deleted. It could not read the directory before removing it, so it could not confirm whether that was the copy it kept. Check the other location before assuming nothing was lost.`)}await je(f,o,a,{requestId:DJ(e),handler:`skill-delete`})}Q(r,200,Cr,{existed:_.existed,path:_.path,...S.length>0?{warnings:S}:{}},{handler:`skill-delete`})}catch(e){X(r,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),Ce=Z(Ere,async(e,n,a)=>{try{let l=v$(a,g);if(l.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!t(a.fromName,n,`skill-move`)||!t(a.toName,n,`skill-move`)||_(a.toName,n,`skill-move`))return;let{root:u,dirRel:d}=le(a.scope,a.fromName),f=s(a.scope,a.toName);if(f!==null){let t=te(a.scope),r=t===void 0?{state:`none`}:j0(t,a.scope,a.toName),i=ke(f),{verdict:o,detail:s}=Ae(le(a.scope,a.toName).dirRel,r,i);r.state===`record`&&o.kind===`plain-collision`&&await je(t,a.scope,a.toName,{requestId:DJ(e),handler:`skill-move`}),X(n,409,`urn:ok:error:doc-already-exists`,`A skill named "${a.toName}" already exists.`,{handler:`skill-move`,detail:s??`Delete or rename it first; this move will not overwrite it.`,...!i.ok&&i.kind===`read-error`?{cause:i.cause}:r.state===`unreadable`&&r.cause!==void 0?{cause:r.cause}:{}});return}let m=te(a.scope),h=m?T0(m).skills[a.fromName]:void 0,b=a.scope===`project`?v:r,S=(a.scope===`project`?y0(v):b0(r)).find(e=>e.name===a.fromName),C=S?V(S.dir):null,w=C===null?[]:Object.entries(u0(b,a.scope)).filter(([,e])=>e===C).map(([e])=>e),T=[...new Set([...h?L0(h.hosts,a.scope):[],...S?L0(S.hosts,a.scope):[],...L0(w,a.scope)])];await j(a.scope===`project`?[...new Set([`${d}/SKILL`,gn(a.scope,a.fromName)])]:[gn(a.scope,a.fromName)],`renamed`),xe(a.scope,a.fromName);let E=await qtt({skillsRoot:u,fromName:a.fromName,toName:a.toName,relocate:async(e,t)=>{let n=await re(i,e,t);return n||ie(e,t),n}});if(!E.ok){if(E.error.code===`SKILL_NOT_FOUND`){X(n,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:E.error.message});return}if(E.error.code===`SKILL_EXISTS`){X(n,409,`urn:ok:error:doc-already-exists`,E.error.message,{handler:`skill-move`,detail:E.error.code});return}let e=E.error.code===`MOVE_FAILED`?500:400;X(n,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:E.error.code,cause:Error(E.error.message)});return}let D=null,O=W(u,a.toName,`SKILL.md`),ee=``,A=``;try{let e=o(K(O,`utf-8`));ee=e.body,typeof e.frontmatter.description==`string`&&(A=e.frontmatter.description)}catch{}let ne=typeof a.body==`string`?a.body:ee,P=a.frontmatter===void 0?A:a.frontmatter.description,ce=X1({skillsRoot:u,name:a.toName,body:ne,frontmatter:{name:a.toName,description:P}});ce.ok||(D=ce.error);let de=[];if(!D)try{de=irt({base:a.scope===`project`?v:r,scope:a.scope,fromName:a.fromName,toName:a.toName})}catch(e){q(`skill-move`).warn({err:e,fromName:a.fromName,toName:a.toName},`skill-ref rewrite failed — rename succeeded, refs to the old name are left as authored`)}a.scope===`project`&&!D&&(p(),ge(u,a.fromName,a.toName).then(()=>_e(de,a.toName)).catch(()=>{}));let pe=c(W(u,a.fromName),a.scope),he=c(W(u,a.toName),a.scope),ve=ae(u,a.toName),ye=[],be=(e,t)=>{M.error({err:e,fromName:a.fromName,toName:a.toName,scope:a.scope},`skill renamed, but its bookkeeping could not be updated`),ye.push(`The skill was renamed to "${a.toName}", but this server could not update its ${t} (${Me(e)}). A stale entry may remain until that file is repaired.`)};try{await fe(a.scope,a.fromName,a.toName,{localHash:ve})}catch(e){be(e,`import records`)}if(a.scope===`project`&&(y(l,k(`skill`,``,a.toName),`skill-rename: ${pe} -> ${he}`,[{from:pe,to:he}]),(async()=>{try{await N(`skill-move`);let e=await oe(se(l),he);e!==void 0&&await me(`project`,a.toName,{baselineRef:e})}catch(e){q(`skill-move`).warn({err:e,toName:a.toName},`deferred shadow flush / revert-baseline failed — Revert stays unarmed until the next flush`)}})()),m){try{await D0(m,a.fromName)}catch(e){be(e,`install records`)}$0(a.fromName,m,T,B0(a.scope));let e=W(u,a.toName);if(T.length>0){let t=q0(e,a.toName,m,T,ue(a.scope,a.toName),B0(a.scope));try{await E0(m,a.toName,{...h,scope:a.scope,hosts:t,scripts:h?.scripts??R0(e,a.toName).hasScripts,installedAt:h?.installedAt??new Date().toISOString()})}catch(e){be(e,`install records`)}}}if(x?.(`files`),D){let e=D.code===`WRITE_ERROR`;X(n,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${a.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:D.code,cause:Error(D.message)});return}Q(n,200,ere,{from:pe,to:he,committed:E.committed,...ye.length>0?{warnings:ye}:{}},{handler:`skill-move`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),we=Z(ii,async(e,n,r)=>{let{name:i,home:a}=r;if(!t(i,n,`skill-edit-external`))return;let o;try{o=nc(a)}catch{X(n,404,`urn:ok:error:not-found`,`Skill directory not found.`,{handler:`skill-edit-external`,detail:`HOME_NOT_FOUND`});return}if(!oc(o).isDirectory()||!G(W(o,`SKILL.md`))){X(n,400,`urn:ok:error:invalid-request`,`Not a skill directory (no SKILL.md).`,{handler:`skill-edit-external`});return}Qtt(i,o),Q(n,200,_t,{docName:sie(i)},{handler:`skill-edit-external`})},{handler:`skill-edit-external`,method:`POST`,preBodyGate:(e,t)=>ce(e,t,{handler:`skill-edit-external`})}),Te={retained:void 0,"plain-collision":void 0,"stray-occupant":void 0,"ledger-unreadable":`unreadable`,"occupant-unverifiable":`occupant-unverifiable`,"retained-slot-unverifiable":`occupant-unverifiable`,"occupant-unreadable":`occupant-unverifiable`},Ee=null;function De(){return Ee||=aG().createCounter(`ok.skill_move_scope.outcome`,{description:"Count of cross-scope skill-move handler invocations by terminal outcome, one per invocation. Bounded labels: move_state ∈ SKILL_MOVE_STATE_CODES plus `success`; source_state ∈ SKILL_SOURCE_STATE_CODES plus `none`; retention_ledger ∈ SKILL_RETENTION_LEDGER_CODES plus `none`. Skill names, filesystem paths, droppedLocations, problem detail text, error messages and request IDs are never labels. Transport-level and schema-level rejections happen outside the handler and stay covered by ok.api.error."}),Ee}function Oe(e,t,n,r){De().add(1,{move_state:e,source_state:t??`none`,retention_ledger:n??`none`}),q(`skill-move-scope`)[r?.logLevel??((r?.status??200)>=500?`error`:`warn`)]({event:`skill-move-scope.outcome`,...r?.instance===void 0?{}:{instance:r.instance},...r?.requestId===void 0?{}:{requestId:r.requestId},handler:`skill-move-scope`,...r?.status===void 0?{}:{status:r.status},moveState:e,sourceState:t??null,retentionLedger:n??null,droppedLocationCount:r?.droppedLocationCount??0},r?.message??`cross-scope skill move did not complete`)}function ke(e){try{let t=iP(e);return t===null?G(e)?{ok:!1,kind:`no-manifest`,reason:`it has no readable SKILL.md`}:{ok:!1,kind:`absent`,reason:`it does not exist`}:{ok:!0,hash:t.contentHash}}catch(e){let t=e?.code;return{ok:!1,kind:`read-error`,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}}function Ae(e,t,n){let r=t.state===`record`?t.record:null,i=r!==null&&r.retainedContentHash!==``&&n.ok&&r.retainedContentHash===n.hash?r:null,a=r!==null&&r.from!==``?`a move of "${r.from}"`:`an earlier move`,o=r?.retainedAt?` on ${r.retainedAt}`:``;return i?.sourceState===`intact`?{verdict:{kind:`retained`,record:i},detail:`${e} is a copy this server retained${o} when ${a} failed to remove the source. That source was verified unchanged, so this copy is a redundant duplicate whose install records never transferred: remove it, then retry. This call wrote nothing.`}:i===null?t.state===`unreadable`?{verdict:{kind:`ledger-unreadable`},detail:`A directory already exists at ${e}, and this server could not read its retained-destination ledger (${t.reason}), so it cannot tell whether that directory is a copy an earlier failed move retained. Do NOT delete it before comparing it against the source. This call wrote nothing.`}:r!==null&&!n.ok&&n.kind===`no-manifest`?{verdict:{kind:`retained-slot-unverifiable`},detail:`A directory already exists at ${e} with no readable SKILL.md, and this server has a record of retaining a copy under this name${o} when ${a} failed to remove the source. Nothing in it could be matched against that record, so verify it against the source before assuming it is that copy.`}:r!==null&&!n.ok?{verdict:{kind:`occupant-unverifiable`},detail:`A directory already exists at ${e}, and this server has a record of retaining a copy under that name${o} from ${a}, but it could not read that directory to confirm the copy is the one it retained (${n.reason}). Do NOT delete it before comparing it against the source. This call wrote nothing.`}:!n.ok&&n.kind===`read-error`?{verdict:{kind:`occupant-unreadable`},detail:`A directory exists at ${e} and this server could not read it to determine whether it is a skill (${n.reason}). Verify it against the source before removing it; this move will not overwrite it. This call wrote nothing.`}:!n.ok&&n.kind===`no-manifest`?{verdict:{kind:`stray-occupant`},detail:`A directory exists at ${e} with no readable SKILL.md. Verify it against the source before removing it; this move will not overwrite it. This call wrote nothing.`}:{verdict:{kind:`plain-collision`},detail:void 0}:{verdict:{kind:`retained`,record:i},detail:`${e} is a copy this server retained${o} when ${a} failed to remove the source. Do NOT delete it before reconciling it against the source: it may hold the only copy of files that failed removal already deleted. Reconcile the two locations, then remove whichever copy is redundant. This call wrote nothing.`}}async function je(e,t,n,r){if(e!==void 0)try{await Int(e,t,n)}catch(e){q(`skill-move-scope`).warn({event:`skill-move-scope.retention-clear-failed`,scope:t,name:n,...r,err:e},`could not clear a retained-destination record — a later collision on this name may still report it as retained`)}}let Me=e=>e instanceof Error?e.message:String(e),Ne={"nothing-written":!1,"destination-removed":!0,"destination-stray":!0,"destination-retained":!0,"destination-retained-blocking":!1,"destination-unreadable":!0,"partially-applied":!0},Pe=Z(rne,async(e,n,a)=>{let o;try{o=v$(a,g)}catch(t){X(n,500,`urn:ok:error:internal-server-error`,`Failed to move skill across scopes.`,{handler:`skill-move-scope`,detail:`Could not resolve who is making the request. Nothing was written.`,extensions:{moveState:`nothing-written`,droppedLocations:[]},cause:t}),Oe(`nothing-written`,void 0,void 0,{requestId:DJ(e),status:400});return}let c=f,l=!1,u=!1,d=[],p=(t,r,i,a)=>{let o=`urn:uuid:${Ec()}`;Oe(a.moveState,a.sourceState,a.retentionLedger,{instance:o,requestId:DJ(e),status:t,droppedLocationCount:d.length,...a.logLevel===void 0?{}:{logLevel:a.logLevel}}),(u||Ne[a.moveState])&&c(),X(n,t,r,i,{instance:o,handler:`skill-move-scope`,...a.detail===void 0?{}:{detail:a.detail},extensions:{moveState:a.moveState,droppedLocations:d,...a.sourceState===void 0?{}:{sourceState:a.sourceState},...a.retentionLedger===void 0?{}:{retentionLedger:a.retentionLedger}},...a.cause===void 0?{}:{cause:a.cause},...a.logLevel?{logLevel:a.logLevel}:{}})};try{if(o.kind===`invalid-summary`){p(400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{moveState:`nothing-written`});return}let{name:f,fromScope:m,toScope:h}=a,g=a.toName??f,_={moveState:`nothing-written`,droppedLocations:[]};if(!t(f,n,`skill-move-scope`,_)){Oe(`nothing-written`,void 0,void 0,{requestId:DJ(e),status:400});return}if(!t(g,n,`skill-move-scope`,_)){Oe(`nothing-written`,void 0,void 0,{requestId:DJ(e),status:400});return}if(BZ(f)){p(400,`urn:ok:error:invalid-request`,`"${f}" is a built-in skill and always lives at its own scope.`,{moveState:`nothing-written`,detail:`BUILTIN_SCOPE_FIXED`});return}if(BZ(g)){p(400,`urn:ok:error:invalid-request`,`"${g}" is a built-in skill name and cannot be used as a destination name.`,{moveState:`nothing-written`,detail:`BUILTIN_SCOPE_FIXED`});return}if(m===h){p(400,`urn:ok:error:invalid-request`,`Source and destination scope are the same.`,{moveState:`nothing-written`});return}if(h===`project`&&!i){p(400,`urn:ok:error:invalid-request`,`Cannot move to project scope — no project root is resolved for this server.`,{moveState:`nothing-written`,detail:`NO_PROJECT_ROOT`});return}let{root:b,dirRel:x,realDir:S}=le(m,f),C=W(b,f),w=(()=>{try{return nc(C)}catch{return C}})(),T=h===`project`?v:r,E=m0(T,h);if(E===null){p(400,`urn:ok:error:invalid-request`,`No agent skill host is available in the destination scope.`,{moveState:`nothing-written`,detail:`NO_USABLE_SKILL_HOME`});return}let D=W(T,E),O=W(D,g),k=U(T,O).split(Rs).join(`/`);if(S===null||!G(C)){p(404,`urn:ok:error:not-found`,`Skill not found.`,{moveState:`nothing-written`,detail:`Skill "${f}" not found in ${m} scope.`});return}if(W(S)===W(O)||G(O)&&nc(S)===nc(O)){p(409,`urn:ok:error:doc-already-exists`,`The source and destination resolve to the same skill directory.`,{moveState:`nothing-written`,detail:`SAME_STORAGE`});return}if(s(h,g)!==null||G(O)){let t=te(h),n=t!==void 0&&G(O)?j0(t,h,g):{state:`none`},r=ke(O),{verdict:i,detail:a}=Ae(k,n,r);n.state===`record`&&i.kind===`plain-collision`&&await je(t,h,g,{requestId:DJ(e),handler:`skill-move-scope`,toDirRel:k});let o=Te[i.kind],s=i.kind===`retained`?{moveState:`destination-retained-blocking`,sourceState:i.record.sourceState}:{moveState:`nothing-written`,...o===void 0?{}:{retentionLedger:o}};p(409,`urn:ok:error:doc-already-exists`,`A ${h} skill named "${g}" already exists.`,{...s,detail:a??`Delete or rename it first; this move will not overwrite it.`,...!r.ok&&r.kind===`read-error`?{cause:r.cause}:n.state===`unreadable`&&n.cause!==void 0?{cause:n.cause}:{}});return}let ee=te(m),A=te(h),M=ee?T0(ee).skills[f]:void 0,P=m===`project`?v:r,re=(m===`project`?y0(v):b0(r)).find(e=>e.name===f),ie=re?V(re.dir):null,ce=ie===null?[]:Object.entries(u0(P,m)).filter(([,e])=>e===ie).map(([e])=>e),de=[...new Set([...M?L0(M.hosts,m):[],...re?L0(re.hosts,m):[],...L0(ce,m)])],fe=e=>e.filter(e=>L0([e],h).length===0),he=[...new Set([...fe(M?.hosts??[]),...fe(re?.hosts??[])])].sort();if(u=!0,await j([...new Set([...m===`project`?[`${x}/SKILL`]:[],gn(m,f),gn(h,g)])],`renamed`),l=!0,kG(D,{recursive:!0}),jG(w,O,{recursive:!0,dereference:!0}),g!==f){let e=(e,t,n,r)=>{let i=e0({skillsRoot:D,name:g});p(i.ok?e:500,i.ok&&e===400?`urn:ok:error:invalid-request`:`urn:ok:error:internal-server-error`,i.ok?`Failed to rename the copied skill; destination copy removed.`:`Failed to rename the copied skill; destination cleanup failed.`,{moveState:i.ok?`destination-removed`:`destination-stray`,detail:i.ok?`Rename failed (${t}). The source "${m}:${f}" was not removed.`:`Rename failed (${t}); destination cleanup failed (${i.error.code}). The source "${m}:${f}" was not removed. A partial copy may remain at "${h}:${g}" (${k}). Inspect the destination before retrying.`,cause:i.ok?n:Error(i.error.message,{cause:n}),...r?{logLevel:r}:{}})};try{let t=iP(O);if(t===null){e(400,`UNREADABLE_SKILL`,Error(`UNREADABLE_SKILL`),`error`);return}let n=Z1({skillDir:O,toName:g,skillMd:t.skillMd});if(!n.ok){if(n.stage===`patch`){let t=$tt(n.error);e(400,t,Error(t),`error`)}else e(500,`RENAME_FAILED`,n.cause);return}}catch(t){e(500,`RENAME_FAILED`,t);return}}if(!G(H(O,`SKILL.md`))){let e=e0({skillsRoot:D,name:g});p(500,`urn:ok:error:internal-server-error`,e.ok?`The copied skill is unreadable; destination copy removed.`:`The copied skill is unreadable; destination cleanup failed.`,{moveState:e.ok?`destination-removed`:`destination-stray`,detail:e.ok?`No readable SKILL.md at the destination copy (${k}); it was removed. The source "${m}:${f}" was not touched and is unchanged.`:`No readable SKILL.md at the destination copy (${k}); cleanup failed (${e.error.code}). The source "${m}:${f}" was not touched and is unchanged. A partial copy remains at "${h}:${g}". Inspect the destination before retrying.`,...e.ok?{}:{cause:Error(e.error.message)}});return}d=[...new Set(xe(m,f))].sort();let ge=e0({skillsRoot:b,name:f});if(ge.ok&&w!==C){let e=(()=>{try{return nc(P)}catch{return P}})(),t=U(e,w);t!==``&&!t.startsWith(`..`)&&!Ps(t)&&FG(w,{recursive:!0,force:!0})}if(!ge.ok){let t,n=(()=>{if(!re)return`unknown`;try{let e=iP(C);return e&&e.contentHash===re.contentHash?`intact`:`lossy`}catch(e){return t=e,`unknown`}})(),r=!1,i=ke(O);if(A!==void 0){let t=i.ok?void 0:Error(`the destination copy could not be hashed (${i.reason})`,{cause:i.kind===`read-error`?i.cause:void 0});if(i.ok)try{await Fnt(A,h,g,{retainedAt:new Date().toISOString(),from:`${m}:${f}`,to:`${h}:${g}`,sourceState:n,reason:ge.error.code,retainedContentHash:i.hash}),r=!0}catch(e){t=e}r||q(`skill-move-scope`).error({event:`skill-move-scope.retention-record-failed`,requestId:DJ(e),handler:`skill-move-scope`,toScope:h,toDirRel:k,sourceState:n,err:t},`could not record the retained destination copy — a retry will report an ordinary name collision instead of a retained copy`)}let a=r?``:i.ok?` This server could not record the retention, so a retry will not recognise ${k} as a copy it retained and will report an ordinary name collision instead.`:` This server could not read the destination copy at ${k} to confirm it is intact (${i.reason}), so do not rely on it for recovery until you have inspected it yourself. It was not recorded as a retained copy either, so a retry will report an ordinary name collision instead.`;p(500,`urn:ok:error:internal-server-error`,`Failed to move skill (source removal failed); destination copy retained for recovery.`,{moveState:`destination-retained`,sourceState:n,detail:n===`intact`?`Source removal failed (${ge.error.code}) without deleting anything. The source "${m}:${f}" is unchanged at its original scope, so no files were lost. The destination copy "${h}:${g}" at ${k} is a duplicate whose install records have not transferred; remove it before retrying.${a}`:n===`lossy`?`Source removal failed (${ge.error.code}). The source "${m}:${f}" may be partially removed. The destination copy "${h}:${g}" remains at ${k}; its install records have not transferred. Inspect both locations before retrying, and recover missing source files from the retained copy.${a}`:`Source removal failed (${ge.error.code}). The source "${m}:${f}" could not be verified against a known content hash, so whether any files were lost is unknown. The destination copy "${h}:${g}" remains at ${k}; its install records have not transferred. Compare both locations before removing either.${a}`,cause:t?Error(ge.error.message,{cause:t}):Error(ge.error.message)});return}await je(A,h,g,{requestId:DJ(e),handler:`skill-move-scope`,toDirRel:k});let _e=[],ve=!1;try{if(ve=await pe(m,h,f,g),ee&&await ne(ee,f,m,re?{purge:{contentHash:re.contentHash}}:{}),ee&&await Hnt(ee,f),A&&de.length>0){let e=q0(O,g,A,de,ue(h,g),B0(h));await E0(A,g,{...M,scope:h,hosts:e,scripts:M?.scripts??R0(O,g).hasScripts,installedAt:M?.installedAt??new Date().toISOString()})}ve&&await me(h,g,{localHash:ae(D,g)})}catch(t){q(`skill-move-scope`).error({err:t,name:f,toName:g,fromScope:m,toScope:h,requestId:DJ(e)},`skill moved across scopes, but its bookkeeping could not be updated`),_e.push(`The skill moved to ${h}, but this server could not update its install records (${Me(t)}). A stale entry may remain until that file is repaired.`)}if(!G(H(O,`SKILL.md`))){p(500,`urn:ok:error:internal-server-error`,`The source was removed, but the destination skill is unreadable.`,{moveState:`destination-unreadable`,detail:`Inspect "${h}:${g}" at ${k} before retrying. Restore the skill from a backup, or check the project Timeline / shadow-repo history for an earlier version if available.`});return}if(m===`project`||h===`project`){y(o,m===`project`?x:U(v,O).split(Rs).join(`/`),`skill-move-scope: ${m} -> ${h} ${f}${g===f?``:` -> ${g}`}`);let t=U(v,O).split(Rs).join(`/`),n=!!ve&&h===`project`,r=DJ(e);(async()=>{let e=await N(`skill-move-scope`);if(n){if(e!==`flushed`){q(`skill-move-scope`).warn({event:`skill-move-scope.revert-baseline-unset`,requestId:r,handler:`skill-move-scope`,toScope:h,toName:g,flush:e},`the deferred shadow flush did not complete, so this move did not establish or update its Revert baseline; any baseline an earlier write recorded is unchanged`);return}try{let n=await oe(se(o),t);if(n===void 0){q(`skill-move-scope`).warn({event:`skill-move-scope.revert-baseline-unset`,requestId:r,handler:`skill-move-scope`,toScope:h,toName:g,flush:e},`no shadow head was readable after the flush, so this move did not establish or update its Revert baseline; any baseline an earlier write recorded is unchanged`);return}await me(h,g,{baselineRef:n})}catch(e){q(`skill-move-scope`).warn({event:`skill-move-scope.baseline-update-failed`,requestId:r,handler:`skill-move-scope`,toScope:h,toName:g,err:e},`could not record the Revert baseline for the moved skill, so this move did not establish or update its baseline; any baseline an earlier write recorded is unchanged`)}}})()}c(),Oe(`success`,void 0,void 0,{requestId:DJ(e),status:200,droppedLocationCount:he.length,logLevel:`debug`,message:`cross-scope skill move completed`}),Q(n,200,Qee,{scope:h,path:k,droppedLocations:he,..._e.length>0?{warnings:_e}:{}},{handler:`skill-move-scope`})}catch(e){p(500,`urn:ok:error:internal-server-error`,l?`Failed to move skill across scopes; the move may be partially applied.`:`Failed to move skill across scopes; nothing was written.`,{moveState:l?`partially-applied`:`nothing-written`,detail:l?`Inspect the source "${a.fromScope}:${a.name}" and destination "${a.toScope}:${a.toName??a.name}" before retrying. Preserve any remaining copies and recover missing files from a backup or available project Timeline / shadow-repo history.`:`The failure happened before any file was copied, so no files were copied or removed for "${a.fromScope}:${a.name}" or "${a.toScope}:${a.toName??a.name}". Retrying is safe once the underlying error clears.`,cause:e})}},{handler:`skill-move-scope`,method:`POST`}),Fe=Z(Aie,async(e,n,i)=>{let a=f,o=!1,c=!1,l=!1;try{let e=v$(i,g);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-duplicate`});return}if(!t(i.name,n,`skill-duplicate`)||!t(i.toName,n,`skill-duplicate`)||_(i.toName,n,`skill-duplicate`))return;let u=s(i.scope,i.name);if(u===null||!G(H(u,`SKILL.md`))){X(n,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-duplicate`,detail:`SOURCE_NOT_FOUND`});return}let d=i.scope===`project`?v:r,f=m0(d,i.scope);if(f===null){X(n,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-duplicate`,detail:`NO_USABLE_SKILL_HOME`});return}let p=W(d,f),m=W(p,i.toName);if(s(i.scope,i.toName)!==null||G(m)){X(n,409,`urn:ok:error:doc-already-exists`,`A ${i.scope} skill named "${i.toName}" already exists.`,{handler:`skill-duplicate`});return}let h=iP(u);if(!h){X(n,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-duplicate`});return}let b=U(d,m).split(Rs).join(`/`);o=!0,kG(p,{recursive:!0}),c=!0,jG(u,m,{recursive:!0,dereference:!0}),l=!0;let x=(e,t,r,o)=>{let s=e0({skillsRoot:p,name:i.toName});a(),X(n,s.ok?e:500,s.ok&&e===400?`urn:ok:error:invalid-request`:`urn:ok:error:internal-server-error`,s.ok?`Failed to write duplicated skill; destination copy removed.`:`Failed to write duplicated skill; destination cleanup failed.`,{handler:`skill-duplicate`,detail:s.ok?`Duplicate failed (${t}). The source "${i.scope}:${i.name}" was not touched.`:`Duplicate failed (${t}); destination cleanup failed (${s.error.code}). The source "${i.scope}:${i.name}" was not touched. A partial copy may remain at "${i.scope}:${i.toName}" (${b}). Inspect the destination before retrying.`,cause:s.ok?r:Error(s.error.message,{cause:r}),...o?{logLevel:o}:{}})},S=Z1({skillDir:m,toName:i.toName,skillMd:h.skillMd});if(!S.ok){if(S.stage===`patch`){let e=$tt(S.error);x(400,e,Error(e),`error`)}else x(500,`WRITE_FAILED`,S.cause);return}if(i.scope===`project`){let t=U(v,m).split(Rs).join(`/`);y(e,k(`skill`,``,i.toName),`skill-duplicate: ${i.name} -> ${t}`),N(`skill-duplicate`)}a(),Q(n,200,P,{name:i.toName},{handler:`skill-duplicate`})}catch(e){o&&a(),X(n,500,`urn:ok:error:internal-server-error`,`Failed to duplicate skill.`,{handler:`skill-duplicate`,...l?{detail:`A complete copy was created at "${i.scope}:${i.toName}" and was left in place. Inspect it before retrying.`}:c?{detail:`A copy of "${i.scope}:${i.name}" was started at "${i.scope}:${i.toName}" and may be incomplete; it was left in place, and its SKILL.md may still carry the source's name. Inspect or remove it before retrying.`}:{},cause:e})}},{handler:`skill-duplicate`,method:`POST`});return N$({"/api/skill":r2({GET:ve,PUT:be,POST:Ce,DELETE:Se},{handler:`skill`}),"/api/skill/edit-external":we,"/api/skill/duplicate":Fe,"/api/skill/move-scope":Pe},{mutating:[`/api/skill`,`/api/skill/edit-external`,`/api/skill/duplicate`,`/api/skill/move-scope`]})}function crt(e){let t=[],n=e;for(;;){try{return H(nc.native(n),...t)}catch(e){let t=iq(e);if(t===`ELOOP`)return null;if(t!==`ENOENT`&&t!==`ENOTDIR`)throw e}try{if(Ys(n).isSymbolicLink())return null}catch{}let e=V(n);if(e===n)return null;t.unshift(js(n)),n=e}}function i2(e,t){if(!nq(t,e))return`escapes`;if(xq(U(e,t).split(Rs).join(`/`)))return`withheld`;let n=crt(e),r=crt(t);return n===null||r===null||!nq(r,n)?`escapes`:xq(U(n,r).split(Rs).join(`/`))?`withheld`:`admitted`}function a2(e,t,n,r,i){let a=i2(t,W(t,n));return a!==`admitted`&&(X(e,400,`urn:ok:error:invalid-request`,a===`withheld`?`Skill file path falls under an entry Open Knowledge withholds from skill bundles (.git, node_modules, OK and editor host dirs, OS artifact files).`:i,{handler:r,detail:n}),!0)}function lrt(e){let{validateSkillName:t,parseSkillScope:n,skillsHome:r,projectDir:i,resolveBuiltinSkillDir:a,resolveSkillDirForRead:o,resolveSkillsRoot:s,getPrincipal:c,rejectReservedBuiltinSkill:l,contentDir:u,checkSkillDocConflictGate:d,extractAgentIdentity:f,sessionManager:p,flushDiskAndDetectOutcome:m,respondStaleExternalWrite:h,respondPersistenceFailure:g,respondDiskDivergence:_,attributeOkArtifactWrite:v,okArtifactKey:b,commitOkArtifactWrite:x,signalChannel:S,extractActorIdentityFromQuery:C,captureAndCloseDocuments:w,derivedDocumentIndex:T,log:E,recordDerivedMutationsBestEffort:D}=e;function O(e){if(e.includes(`\0`))return null;let t=ga(e);return t.length<1||t.some(e=>e===`..`)||t.length===1&&t[0].toLowerCase()===`skill.md`?null:t[0]===`references`&&t.length>=2?`reference`:t[0]===`scripts`&&t.length>=2?`script`:`file`}function k(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function ee(e,t){let n=W(e,t),r=U(u,e).split(Rs).join(`/`),i;try{i=tc(n,{recursive:!0,encoding:`utf-8`})}catch{return[]}return i.filter(e=>/\.md$/i.test(e)).map(e=>`${r}/${t}/${e.split(Rs).join(`/`).replace(/\.md$/i,``)}`)}function A(e,t){let n=t.replace(/\.md$/i,``);return`${y(e).replace(/\/SKILL$/,``)}/${n}`}return N$({"/api/skill-file":r2({GET:Z($a,async(e,c)=>{try{let l=new URL(e.url??``,`http://localhost`),u=l.searchParams.get(`name`)??``;if(!t(u,c,`skill-file-get`))return;let d=n(l.searchParams.get(`scope`),c,`skill-file-get`);if(d===null)return;let f=l.searchParams.get(`path`)??``,p=BZ(u)?d===`global`?r:i:void 0,m=l.searchParams.get(`host`)??void 0,h=p?a(p,u,d,m):null;if(f===``||f.includes(`\0`)){X(c,400,`urn:ok:error:invalid-request`,`Invalid skill file path.`,{handler:`skill-file-get`});return}let g=(h&&f===`SKILL.md`?`reference`:O(f))??`reference`,_=m,v=p?h?.dir??null:o(d,u,_);if(v===null&&_!==void 0){X(c,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-get`,detail:`No skill "${u}" (${d}) in ${_}.`});return}let y=v??W(s(d),u),b=W(y,f),x=i2(y,b);if(x===`escapes`){X(c,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let S=b,C=f;if(x===`withheld`||!G(S)){let e=x===`withheld`?null:f.match(/^(.*)\.(?:md|mdx)$/),t=e?Bi.map(t=>`${e[1]}${t}`).find(e=>e!==f&&i2(y,W(y,e))===`admitted`&&G(W(y,e))):void 0;if(t===void 0){X(c,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${f} not found in skill "${u}" (${d}).`});return}C=t,S=W(y,t)}let w=await vc(S);if(w.includes(0)){X(c,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}Q(c,200,hee,{path:C.replace(/\\/g,`/`),kind:g,text:w.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){X(c,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:Z(at,async(e,n,i)=>{try{let e=v$(i,c);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!t(i.name,n,`skill-file-put`)||l(i.name,n,`skill-file-put`))return;let a=O(i.path);if(a===null){X(n,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must name a file inside the skill dir, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(i.content,`utf-8`)>262144){X(n,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let s=o(i.scope,i.name);if(s===null||!G(H(s,`SKILL.md`))){X(n,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${i.name}" before adding bundle files.`});return}let y=i.scope===`project`?u:r,C=U(y,s).split(Rs).join(`/`),w=i.path.replace(/\\/g,`/`);if(a2(n,s,w,`skill-file-put`,`Skill file path escapes the skill dir.`))return;let T=k(i.scope,a,w),E;if(T){let e=`${C}/${w.replace(/\.mdx?$/i,``)}`;if(d(e,`skill-file-put`,n))return;if(E=!G(W(s,w)),E&&Wtt(s)>=50){X(n,400,`urn:ok:error:invalid-request`,`Skill "${i.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:t,agentName:r,colorSeed:a,clientName:o}=f(i),c=await p.getSession(e,t,{displayName:r,colorSeed:a,clientName:o});c.dc.document.transact(()=>{dG(c.dc.document,i.content,`agent`)},c.origin);let l=await m(e);if(l?.kind===`failure`){g(n,l.failure,`skill-file-put`);return}if(l?.kind===`divergence`){_(n,`skill-file-put`);return}if(l?.kind===`stale-external-write`){h(n,`skill-file-put`,e);return}}else{let e=$1({skillsRoot:V(s),name:i.name,relPath:w,content:i.content});if(!e.ok){let t=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;X(n,t,t===500?`urn:ok:error:internal-server-error`:t===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,t===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}E=e.created}i.scope===`project`&&(v(e,b(`skill`,``,i.name),`${E?`skill-file-create`:`skill-file-edit`}: ${C}/${w}`),x(`skill-file-put`)),S?.(`files`),Q(n,200,Qt,{path:w,created:E,kind:a,content:T},{handler:`skill-file-put`})}catch(e){X(n,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:Z($a,async(e,r)=>{try{let i=new URL(e.url??``,`http://localhost`),a=i.searchParams,d=a.get(`name`)??``;if(!t(d,r,`skill-file-delete`)||l(d,r,`skill-file-delete`))return;let f=n(a.get(`scope`),r,`skill-file-delete`);if(f===null)return;let p=(a.get(`path`)??``).replace(/\\/g,`/`),m=O(p);if(m===null){X(r,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must name a file inside the skill dir).`,{handler:`skill-file-delete`});return}let h=C(i,c);if(h.kind===`invalid-summary`){X(r,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let g=o(f,d),_=g===null?s(f):V(g),y=g??H(_,d),T=W(y,p);if(a2(r,y,p,`skill-file-delete`,`Invalid skill file path (must name a file inside the skill dir).`))return;if(G(T)&&k(f,m,p)){let e=p.replace(/\.md$/i,``),t=g===null?A(d,p):`${U(u,g).split(Rs).join(`/`)}/${e}`;await w([t],`deleted-upstream`)}else if(f===`project`&&g!==null&&G(T)&&oc(T).isDirectory()){let e=ee(g,p);e.length>0&&await w(e,`deleted-upstream`)}let E=Ktt({skillsRoot:_,name:d,relPath:p});if(!E.ok){let e=E.error.code===`UNLINK_FAILED`?500:400;X(r,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:E.error.code,cause:Error(E.error.message)});return}E.existed&&f===`project`&&(v(h,b(`skill`,``,d),`skill-file-delete: ${g===null?`${d}/${p}`:`${U(u,g).split(Rs).join(`/`)}/${p}`}`),x(`skill-file-delete`)),E.existed&&S?.(`files`),Q(r,200,Jr,{path:p,existed:E.existed,kind:m},{handler:`skill-file-delete`})}catch(e){X(r,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),"/api/skill-file/rename":Z(yre,async(e,n,r)=>{try{if(!t(r.name,n,`skill-file-rename`)||l(r.name,n,`skill-file-rename`))return;let e=v$(r,c);if(e.kind===`invalid-summary`){X(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-rename`});return}let i=r.from.replace(/\\/g,`/`),a=r.to.replace(/\\/g,`/`),s=O(i),f=O(a);if(s===null||f===null){X(n,400,`urn:ok:error:invalid-request`,`Both paths must stay inside the skill dir.`,{handler:`skill-file-rename`,detail:s===null?i:a});return}let p=o(r.scope,r.name);if(p===null){X(n,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-rename`});return}let m=V(p);if([i,a].some(e=>a2(n,p,e,`skill-file-rename`,`Both paths must stay inside the skill dir.`)))return;let h=k(r.scope,s,i),g=k(r.scope,f,a),_=U(u,p).split(Rs).join(`/`),y=h?`${_}/${i.replace(/\.md$/i,``)}`:null,C=g?`${_}/${a.replace(/\.md$/i,``)}`:null;if(y!==null&&d(y,`skill-file-rename`,n))return;if(y!==null)await w([y],`deleted-upstream`);else if(r.scope===`project`){let e=W(p,i);if(G(e)&&oc(e).isDirectory()){let e=ee(p,i);e.length>0&&await w(e,`deleted-upstream`)}}let E=Gtt({skillsRoot:m,name:r.name,relPath:i,toRelPath:a});if(!E.ok){let e=E.error.code===`RENAME_FAILED`?500:400;X(n,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,E.error.message,{handler:`skill-file-rename`,detail:E.error.code});return}if(T){let e=[];if(y!==null&&C!==null)try{e.push({kind:`rename`,oldDocumentName:y,newDocumentName:C,markdown:K(W(m,r.name,a),`utf-8`)})}catch{e.push({kind:`delete`,documentName:y})}else if(y!==null)e.push({kind:`delete`,documentName:y});else if(C!==null)try{e.push({kind:`upsert`,documentName:C,markdown:K(W(m,r.name,a),`utf-8`)})}catch{}await D(e,`skill-file-rename`)}r.scope===`project`&&(v(e,b(`skill`,``,r.name),`skill-file-rename: ${r.name}/${i} -> ${a}`),x(`skill-file-rename`)),S?.(`files`),Q(n,200,Bt,{from:i,to:a,...y===null?{}:{fromDocName:y},...C===null?{}:{toDocName:C}},{handler:`skill-file-rename`})}catch(e){E.error({err:e},`[skill-file-rename] failed`),n.headersSent||X(n,500,`urn:ok:error:internal-server-error`,`Failed to rename skill file.`,{handler:`skill-file-rename`})}},{handler:`skill-file-rename`,method:`POST`})},{mutating:[`/api/skill-file`,`/api/skill-file/rename`]})}function urt(e,t){return(0,WNe.default)({headers:e.headers,defParamCharset:`utf8`,limits:t})}function drt(e){return e.kind===`git`&&!A$(e.url)}function o2(e,t,n){return t.kind===`git`&&drt(t)?(X(e,400,`urn:ok:error:url-not-allowed`,`Git URL protocol is not allowed.`,{handler:n,cause:Error(`url=${t.url}`)}),!0):!1}function frt(e){let{projectDir:t,getPrincipal:n,skillImportService:r,bumpSkillsCatalogGen:i,contentFilter:a,scheduleDeferredIgnoreRebuild:o,signalChannel:s,parseSkillScope:c}=e;function l(e){let t=/github\.com[/:]([\w.-]+)\//.exec(e);return t?t[1]:void 0}function u(e,t){if(t.ok){Q(e,200,pr,t.body,{handler:`skill-import`});return}X(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}let d=Z(Vee,async(e,c,d)=>{let f=()=>{};try{if(!t){X(c,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=v$(d,n);if(e.kind===`invalid-summary`){X(c,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let p=d.scope,m=null,h,g,_,v,y=d.source;{let e=d.source;try{let t=await uP(e,d.skill),n=t?.source??e;y=n;let r=d.skill??t?.skill,i=t?.spec??JN(n);if(!i){X(c,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(o2(c,i,`skill-import`))return;let a=await XN(i);f=a.cleanup,g=a.ref;let o=oP(a.dir);if(o.length===0){X(c,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skill-import`});return}let s=o[0];if(r){let e=o.find(e=>e.name===r)??o.find(e=>nP(e.dir)?.name===r)??o.find(e=>e.name===Gt[r]);if(!e){X(c,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skill-import`,detail:`--skill "${r}" not among: ${o.map(e=>e.name).join(`, `)}.`});return}s=e}else if(o.length>1){X(c,400,`urn:ok:error:invalid-request`,"Source has multiple skills; pass `skill` to choose one.",{handler:`skill-import`,detail:o.map(e=>e.name).join(`, `)});return}m=s.dir,v=s.name,h=e,_=t?.publisher??l(n)}catch(e){if(e instanceof BN){X(c,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!m){X(c,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let b=await r.runSkillImport({acquiredDir:m,scope:p,sourceLabel:h,ref:g,publisher:_,upstreamSkill:v,actor:e,skipProjection:d.install===!1});b.ok&&(d.marketplace===!0||Nt(y))&&G1({source:y,skills:[b.body.name]},I1()),i(),a?.refreshInPlaceSkillDirs(),o(),s?.(`files`),u(c,b)}catch(e){X(c,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{f()}},{handler:`skill-import`,method:`POST`}),f=Z(le,async(e,c,u)=>{let d=()=>{};try{if(!t){X(c,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=v$(u,n);if(e.kind===`invalid-summary`){X(c,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let f=u.source,p=null,m=null,h=[],g,_,v=f;try{let e=await uP(f,u.skills[0]),t=e?.source??f;v=t;let n=e?.spec??JN(t);if(!n){X(c,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(o2(c,n,`skills-import-bulk`))return;if(_=e?.publisher??l(t),n.kind===`well-known`)p=n,m=await KN(n.origin);else{let e=await XN(n);d=e.cleanup,g=e.ref,h=oP(e.dir)}}catch(e){if(e instanceof BN){X(c,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(p===null&&h.length===0){X(c,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let y=[];for(let t of new Set(u.skills)){let n,i,a=()=>{};if(p!==null)try{let e=await XN({...p,skill:t},m?{index:m}:{});n=e.dir,a=e.cleanup,i=t}catch(e){y.push({requested:t,status:e instanceof BN?`not-found`:`failed`,warnings:[],warningCodes:[],...e instanceof BN?{}:{error:String(e)}});continue}else{let e=h.find(e=>e.name===t)??h.find(e=>iP(e.dir)?.name===t)??h.find(e=>e.name===Gt[t]);if(!e){y.push({requested:t,status:`not-found`,warnings:[],warningCodes:[]});continue}n=e.dir,i=e.name}try{let a=await r.runSkillImport({acquiredDir:n,scope:u.scope,sourceLabel:f,ref:g,publisher:_,upstreamSkill:i,actor:e,skipProjection:u.install===!1});if(!a.ok){q(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),y.push({requested:t,status:`failed`,warnings:[],warningCodes:[],error:a.detail??a.title});continue}y.push({requested:t,status:a.body.alreadyImported?`already-imported`:`imported`,name:a.body.name,...a.body.collisionRenamedFrom===void 0?{}:{collisionRenamedFrom:a.body.collisionRenamedFrom},warnings:a.body.warnings,warningCodes:a.body.warningCodes})}catch(e){q(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),y.push({requested:t,status:`failed`,warnings:[],warningCodes:[],error:e instanceof Error?e.message:String(e)})}finally{a()}}if(u.marketplace===!0||Nt(v)){let e=y.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&G1({source:v,skills:e},I1())}i(),a?.refreshInPlaceSkillDirs(),o(),s?.(`files`),Q(c,200,cie,{results:y,imported:y.filter(e=>e.status===`imported`).length,alreadyImported:y.filter(e=>e.status===`already-imported`).length,failed:y.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){X(c,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{d()}},{handler:`skills-import-bulk`,method:`POST`}),p=8388608,m=33554432;function h(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=W(e,n);return r!==e&&!r.startsWith(e+Rs)?null:r}function g(e){return new Promise((t,n)=>{let r;try{r=urt(e,{files:200,fields:10,fieldSize:2048,fileSize:p})}catch(e){n(e);return}let i=[],a=0,o=null,s=t=>{o||(o=t,e.unpipe(r),e.destroy(),r.destroy(),n(t))};r.on(`file`,(e,t,n)=>{let r=[],c=!1;t.on(`data`,e=>{if(!o){if(a+=e.length,a>m){s(Error(`Upload too large.`));return}r.push(e)}}),t.on(`limit`,()=>{c=!0}),t.on(`end`,()=>{if(!o){if(c){o=Error(`File "${n.filename}" exceeds the per-file size limit.`);return}i.push({relPath:n.filename||`file`,data:Buffer.concat(r)})}})}),r.on(`error`,n),r.on(`close`,()=>o?n(o):t(i)),e.pipe(r)})}function _(e,t){return new Promise((n,r)=>{(0,UNe.fromBuffer)(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(e??Error(`Unreadable archive.`));return}let a=0,o=0,s=e=>{try{i.close()}catch{}r(e instanceof Error?e:Error(String(e)))};i.on(`entry`,e=>{if(++o>200){s(Error(`Archive has too many entries.`));return}let n=h(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){kG(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>p){s(Error(`Archive entry too large: ${e.fileName}`));return}i.openReadStream(e,(e,t)=>{if(e||!t){s(e??Error(`Could not read archive entry.`));return}let r=[];t.on(`data`,e=>{if(a+=e.length,a>m){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{kG(V(n),{recursive:!0}),DG(n,Buffer.concat(r))}catch(e){s(e instanceof Error?e:Error(String(e)));return}i.readEntry()})})}),i.on(`end`,()=>n()),i.on(`error`,s),i.readEntry()})})}async function v(e,i){let a=Zs(H(mc(),`ok-skill-upload-`)),o=()=>{try{FG(a,{recursive:!0,force:!0})}catch{}};try{if(!t){X(i,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){X(i,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let o=new URL(e.url??``,`http://localhost`),s=c(o.searchParams.get(`scope`),i,`skill-upload`);if(!s)return;let l=e=>o.searchParams.get(e)??void 0,d=v$({agentId:l(`agentId`),agentName:l(`agentName`),colorSeed:l(`colorSeed`),clientName:l(`clientName`),summary:l(`summary`)},n);if(d.kind===`invalid-summary`){X(i,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let f;try{f=await g(e)}catch(e){X(i,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(f.length===0){X(i,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let p=f.length===1?f[0]:null,m=p&&/\.(zip|skill)$/i.test(p.relPath)?p.relPath:null;if(p&&m)try{await _(p.data,a)}catch(e){X(i,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of f){let t=h(a,e.relPath);if(!t){X(i,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}kG(V(t),{recursive:!0}),DG(t,e.data)}let v=oP(a);if(v.length===0){X(i,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(v.length>1){X(i,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:v.map(e=>e.name).join(`, `)});return}let y=v[0];u(i,await r.runSkillImport({acquiredDir:y.dir,scope:s,sourceLabel:`upload:${m??y.name}`,upstreamSkill:y.name,actor:d}))}catch(e){X(i,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{o()}}return N$({"/api/skill/import":d,"/api/skills/import-bulk":f,"/api/skill-upload":v},{mutating:[`/api/skill/import`,`/api/skills/import-bulk`,`/api/skill-upload`]})}function prt(e){let{resolveSkillsRoot:t,validateSkillName:n,projectDir:r,skillInstallBase:i,contentDir:a,skillsHome:o,shippedBundleSkillMd:s,flushDiskAndDetectOutcome:c,respondStaleExternalWrite:l,respondPersistenceFailure:u,respondDiskDivergence:d,skillInstallOps:f,skillPlacementOps:m,signalChannel:h,bumpSkillsCatalogGen:g,contentFilter:_,scheduleDeferredIgnoreRebuild:v,effectiveInstallMode:y,log:b}=e;return N$({"/api/skill/install":Z(p,async(e,p,x)=>{try{let e=t(x.scope);if(!n(x.name,p,`skill-install`))return;if(x.scope===`project`&&!r){X(p,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let S=i(x.scope),C=W(e,x.name),w=x.scope===`project`?a:o,T=(x.scope===`project`?y0(a):b0(o)).find(e=>e.name===x.name),E=BZ(x.name)?s(x.name,x.scope):null,D=T?W(w,T.dir):G(C)||E===null?C:V(E);if(!G(D)){X(p,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${x.name}" not found in ${x.scope} scope — create it with write({ skill }) first.`});return}let O=x.scope===`project`?`${U(w,D).split(Rs).join(`/`)}/SKILL`:gn(x.scope,x.name),k=await c(O);if(k?.kind===`failure`){u(p,k.failure,`skill-install`);return}if(k?.kind===`divergence`){d(p,`skill-install`);return}if(k?.kind===`stale-external-write`){l(p,`skill-install`,O);return}let A=R0(D,x.name,{allowReservedName:BZ(x.name)});if(!A.ok){X(p,400,`urn:ok:error:invalid-request`,`Skill "${x.name}" cannot be installed: ${A.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(x.fork!==void 0){if(!T){X(p,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=f.resolveFork({scope:x.scope,name:x.name,fork:x.fork,inPlaceEntry:T});if(!e.ok)switch(e.kind){case`unknown-editor`:X(p,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:X(p,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:X(p,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return;case`invalid-new-name`:X(p,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:X(p,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:e.toName});return;default:throw Error(`Unhandled fork outcome: ${String(e.kind)}`)}h?.(`files`),g(),_?.refreshInPlaceSkillDirs(),v(),Q(p,200,Va,{name:x.name,hosts:T.hosts.filter(zi),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let j=x.setSource??x.source,M=x.linkMode??(x.mode===void 0?void 0:x.mode===`link`),N=x.targets,te=[],ne=[];if(x.add!==void 0||x.remove!==void 0){if(!T){X(p,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=await f.applyAddRemove({scope:x.scope,name:x.name,inPlaceEntry:T,...x.add===void 0?{}:{add:x.add},...x.remove===void 0?{}:{remove:x.remove}});if(!e.ok){e.kind===`remove-source`?X(p,400,`urn:ok:error:invalid-request`,`"${e.sourceId}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,{handler:`skill-install`,detail:`REMOVE_SOURCE`}):X(p,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}N=e.targets.filter(zi),te.push(...e.rootAdds),ne.push(...e.rootRemoves)}if(j&&!T){let e=await f.promoteStoreBackedSource({scope:x.scope,name:x.name,base:S,skillDir:D,newSource:j});if(!e.ok){X(p,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.kind===`source-occupied`?e.reason:e.target});return}h?.(`files`),g(),_?.refreshInPlaceSkillDirs(),v(),Q(p,200,Va,{name:x.name,hosts:e.hosts,scripts:A.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(x.place){let e=x.scope===`project`?r:o;if(!e){X(p,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let t=await m.place({placeBase:e,name:x.name,rawDir:x.place.dir,skillDir:D,mode:x.place.mode});if(!t.ok){t.kind===`invalid-path`?X(p,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):X(p,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}`alreadyAtSource`in t||h?.(`files`),g(),_?.refreshInPlaceSkillDirs(),v(),Q(p,200,Va,{name:x.name,hosts:T?[...T.hosts]:[],scripts:A.hasScripts,...`copiedInsteadOfLinked`in t&&t.copiedInsteadOfLinked?{warnings:[Znt([V(t.placedAt)])],warningCodes:[`links-not-permitted`]}:{warnings:[],warningCodes:[]},placedAt:t.placedAt},{handler:`skill-install`});return}if(x.unplace){let e=x.scope===`project`?r:o;if(!e){X(p,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let t=await m.unplace({placeBase:e,name:x.name,rawPath:x.unplace.path,skillDir:D});if(!t.ok)switch(t.kind){case`not-recorded`:X(p,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:t.path});return;case`unsafe-path`:X(p,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:X(p,409,`urn:ok:error:doc-already-exists`,`This copy differs from the current source and was preserved. Inspect both versions before removing it.`,{handler:`skill-install`,detail:t.path});return;case`canonical-dir`:X(p,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:t.path});return;default:throw Error(`Unhandled unplace outcome: ${String(t.kind)}`)}h?.(`files`),g(),_?.refreshInPlaceSkillDirs(),v(),Q(p,200,Va,{name:x.name,hosts:T?[...T.hosts]:[],scripts:A.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(x.convert){if(!T){X(p,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:t}=x.convert,n=x.scope===`project`?r:o,i=await m.convert({ledgerBase:n??S,scope:x.scope,name:x.name,target:e,mode:t,skillDir:D,canonicalHash:T.contentHash});if(!i.ok)switch(i.kind){case`invalid-location`:X(p,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:X(p,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return;case`forked`:X(p,409,`urn:ok:error:doc-already-exists`,`This copy differs from the current source and was preserved. Inspect both versions before replacing or converting it.`,{handler:`skill-install`,detail:e});return;case`not-installed`:X(p,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return;case`links-not-permitted`:X(p,403,`urn:ok:error:links-not-permitted`,`This system does not allow creating symlinks, so that location was left as a copy. On Windows, creating symlinks needs administrator rights or Developer Mode.`,{handler:`skill-install`,detail:e});return;default:throw Error(`Unhandled convert outcome: ${String(i.kind)}`)}h?.(`files`),Q(p,200,Va,{name:x.name,hosts:[...T.hosts],scripts:A.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let P=x.scope===`global`?N===void 0?q1(o).map(e=>e.editorId):ao.filter(e=>N?.some(t=>t===e)):N===void 0?z0(S):ra.filter(e=>N?.some(t=>t===e)),re=[],ie=[];if(P.length===0&&N===void 0&&(re.push(x.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),ie.push(`no-targets`)),A.hasScripts&&(re.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),ie.push(`scripts-present`)),A.warnings.length>0&&(re.push(A.warnings[0]),ie.push(`no-description`)),T){let e=T.dir.split(`/`).slice(0,-1).join(`/`),t=(N===void 0?x.scope===`global`&&G(H(o,`.agents`)):N.includes(`agents`))?[...P,`agents`]:[...P],n=x.scope===`project`?r:o,i=M===void 0?y(x.scope,x.name,T):M?`link`:`copy`;if(j){let e=await f.promoteInPlaceSource({scope:x.scope,name:x.name,base:S,...n?{prefBase:n}:{},skillDir:D,inPlaceEntry:T,newSource:j});if(!e.ok){e.kind===`invalid-target`?X(p,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:e.target}):X(p,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.reason});return}h?.(`files`),Q(p,200,Va,{name:x.name,hosts:e.hosts,scripts:A.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let a=await f.fanOutInPlace({scope:x.scope,name:x.name,base:S,...n?{prefBase:n}:{},skillDir:D,inPlaceEntry:T,canonicalRootRel:e,inPlaceTargets:t,setExact:N!==void 0,installMode:i,...M===void 0?{}:{linkModeReq:M},rootAdds:te,rootRemoves:ne});if(!a.ok){X(p,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:a.reason});return}re.push(...a.warnings),ie.push(...a.warningCodes),h?.(`files`),Q(p,200,Va,{name:x.name,hosts:a.hosts,scripts:A.hasScripts,warnings:re,warningCodes:ie,...a.sourceMovedTo===void 0?{}:{sourceMovedTo:a.sourceMovedTo}},{handler:`skill-install`});return}let ae=L0(T0(S).skills[x.name]?.hosts??[],x.scope).filter(e=>!P.includes(e));ae.length>0&&$0(x.name,S,ae,B0(x.scope));let oe=H(S,...Qn),se=G(oe)?K(oe,`utf-8`):null,ce=se===null?null:ee(se);se!==null&&ce===null&&b.warn({skill:x.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let le=ce?.skills[x.name]!==void 0,ue=M===void 0?le?`copy`:`symlink`:M?`symlink`:`copy`,de=q0(D,x.name,S,P,ue,B0(x.scope));de.length===0?await D0(S,x.name):await E0(S,x.name,{hosts:de,scope:x.scope,scripts:A.hasScripts,installedAt:new Date().toISOString(),projection:ue}),h?.(`files`),Q(p,200,Va,{name:x.name,hosts:de,scripts:A.hasScripts,warnings:re,warningCodes:ie},{handler:`skill-install`})}catch(e){X(p,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`})},{mutating:[`/api/skill/install`]})}const mrt=[`.ok`,`local`,`plugin-skill-baselines.json`];function hrt(e){return H(e,...mrt)}function grt(e){try{let t=hrt(e);if(!G(t))return{};let n=JSON.parse(K(t,`utf-8`));if(typeof n!=`object`||!n)return{};let r=Object.create(null);for(let[e,t]of Object.entries(n))typeof t==`object`&&t&&typeof t.local==`string`&&typeof t.upstream==`string`&&(r[e]={local:t.local,upstream:t.upstream});return r}catch{return{}}}function _rt(e,t,n){return e===void 0||e.upstream!==n?{modified:!1,next:{local:t,upstream:n}}:{modified:t!==e.local,next:e}}function vrt(e){let t=grt(e),n=!1;return{isModified(e,r,i,a){let o=`${e}:${r}`,{modified:s,next:c}=_rt(t[o],i,a),l=t[o];return(l===void 0||l.local!==c.local||l.upstream!==c.upstream)&&(t[o]=c,n=!0),s},flush(){if(n){n=!1;try{kG(H(e,`.ok`,`local`),{recursive:!0}),DG(hrt(e),`${JSON.stringify(t,null,2)}\n`)}catch{}}}}}function yrt(e){let{contentDir:t,projectDir:n,skillsHome:r,contentFilter:i,catalogCache:a,resolveSkillsRoot:o,resolveSkillsList:s,skillOriginFor:c,localSkillHash:l,effectiveInstallMode:u,pluginSelfIdentity:d,synthBuiltinLockEntry:f,synthPluginLockEntry:p,pluginUpstreamHash:m,builtinSkillListEntry:h,indexedSkillContentPath:g,healUnservableSkillAdmission:_}=e,v=RZ.project,y={lastKey:null};return N$({"/api/skills":Z($a,F$(async(e,b)=>{let x=await x0(r),S=(i?.peekFreshInPlaceSkillDirsFingerprint()??``)+``+(n?jtt(n).join(`,`):``)+``+q1(r).map(e=>e.editorId).join(`,`)+``+x.map(e=>e.dir).sort().join(`,`),C=a.readList(S);if(C!==null){Q(b,200,zr,C.body,{handler:`skills-list`});return}let w=o(`project`),T=s(w,`project`),E=s(o(`global`),`global`),D=n?jtt(n):[],O=q1(r).map(e=>e.editorId),k=n?p0(n,`project`,oi,r):!1,A=p0(r,`global`,oi,r),j=n?T0(n).skills:{},M=T0(r).skills,N=n?ee(G(H(n,...Qn))?K(H(n,...Qn),`utf-8`):``)??null:null,te=c,ne=(e,t,n)=>e.skills.map(e=>{let r=t[e.name]?.hosts??[],i=n?N?.skills[e.name]:void 0,a=i?te(i):void 0,o=i?.localHash!==void 0&&l(w,e.name)!==i.localHash,s=i?.baselineRef!==void 0;return{...e,installed:r.length>0,hosts:r,...a?{origin:a}:{},...o?{modified:!0}:{},...s?{revertable:!0}:{}}}),P=n?P0(n):{},re=(e,t,n)=>{let r=[];for(let i of t??[]){let t=W(e,i.path);if(n!==void 0&&t===W(n))continue;let a=!1;try{a=Ys(t).isSymbolicLink()}catch{continue}if((a?`link`:`copy`)!==i.mode){if(a&&n!==void 0)try{if(nc(t)===nc(n))continue}catch{}r.push(i.path)}}return{drift:r}},ie=n?u0(t,`project`):{},ae=ant(ie,`project`),oe=(e,t)=>[...t].some(t=>e===t||e.startsWith(`${t}/`)),se=VS(n??t),ce=vrt(t),le=f0(`project`),ue=f0(`global`),de=(e,t)=>(e??[]).filter(e=>![...t].some(t=>e.path===t||e.path.startsWith(`${t}/`))),fe=new Set,pe=kNe(t),me=e=>{let t=jNe(pe,e);return t?{name:t.name,marketplace:t.marketplace,provider:`claude`,...t.url?{url:t.url}:{}}:null},he=n?y0(t).map(e=>{let r=!fe.has(e.name);fe.add(e.name);let i=W(t,e.dir),a=r?d(e.name,se,i)??me(i):null,o=r&&a===null?N?.skills[e.name]??f(t,e.name,`project`)??p(e.name,se,i):void 0,s=o?te(o):void 0,c=o?.localHash===void 0?(()=>{if(!o||!r)return!1;let t=m(e.name,se);return t!==null&&ce.isModified(`project`,e.name,e.contentHash,t)})():e.contentHash!==o.localHash;return{name:e.name,...e.description?{description:e.description}:{},scope:`project`,path:`${e.dir}/SKILL.md`,absolutePath:W(t,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],size:e.size,installableEditors:D,hubOffered:k,...e.pack===void 0?{}:{pack:e.pack},...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(ie).length>0?{hostAliases:ie}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...a===null?{}:{plugin:a},...(()=>{let t=de(r?P[e.name]:void 0,ae).filter(e=>!oe(e.path,le));return t.length?{customPlacements:t.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...(()=>{let i=re(n,de(r?P[e.name]:void 0,ae),W(t,e.dir));return i.drift.length>0?{driftPaths:i.drift}:{}})(),...u(`project`,e.name,e)===`link`?{linkMode:!0}:{},...s?{origin:s}:{},...c?{modified:!0}:{},...o?.baselineRef===void 0?{}:{revertable:!0},...BZ(e.name)?{managed:!0}:{}}}):[],ge=P0(r),_e=t2(H(r,...Qn)),ve=u0(r,`global`),ye=ant(ve,`global`),be=new Set(x.map(e=>e.name));E.skills=E.skills.filter(e=>!be.has(e.name));let xe=new Set,Se=x.map(e=>{let t=!xe.has(e.name);xe.add(e.name);let n=t?ge[e.name]:void 0,i=S0(r,e.name),a=i!==null&&W(r,e.dir)!==W(i)?e.hosts[0]:void 0;return{name:e.name,...e.description?{description:e.description}:{},scope:`global`,path:`${e.dir}/SKILL.md`,absolutePath:W(r,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],...a===void 0?{}:{hostQualifier:a},size:e.size,installableEditors:O,hubOffered:A,...e.pack===void 0?{}:{pack:e.pack},...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(ve).length>0?{hostAliases:ve}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let t=re(r,de(n,ye),W(r,e.dir));return t.drift.length>0?{driftPaths:t.drift}:{}})(),...(()=>{let e=de(n,ye).filter(e=>!oe(e.path,ue));return e.length?{customPlacements:e.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...u(`global`,e.name,e)===`link`?{linkMode:!0}:{},...BZ(e.name)?{managed:!0}:{},...(()=>{if(!t)return{};let n=W(r,e.dir),i=d(e.name,se,n);if(i!==null)return{plugin:i};let a=_e.skills[e.name]??f(r,e.name,`global`)??p(e.name,se,n);if(!a)return{};let o=a.localHash===void 0?(()=>{let t=m(e.name,se);return t!==null&&ce.isModified(`global`,e.name,e.contentHash,t)})():e.contentHash!==a.localHash;return{origin:te(a),...o?{modified:!0}:{}}})()}}),Ce=new Set(he.map(e=>e.name)),we=n&&!T.skills.some(e=>e.name===v)&&!Ce.has(v)?h(n,v,`project`):null,Te=new Set(Se.map(e=>e.name)),Ee=UZ.map(e=>RZ[e]).filter(e=>!E.skills.some(t=>t.name===e)&&!Te.has(e)).map(e=>h(r,e,`global`)).filter(e=>e!==null),De=new Set(he.map(e=>e.name)),Oe=[...ne(T,j,!0).filter(e=>!De.has(e.name)),...he,...ne(E,M,!1),...Se,...we?[we]:[],...Ee];ce.flush();let ke={skills:Oe.map(e=>{let n=e.scope===`project`&&e.absolutePath?g(e.absolutePath,t):null,r=e.absolutePath?trt(V(e.absolutePath)):[],a=r.length>0?{...e,filePaths:r}:e,o=n===null||n===e.path?a:{...a,canonicalPath:n},s=n??e.path;return e.scope===`project`&&!Ps(s)&&i?.isPathIgnored(s)===!0?{...o,ignored:!0}:o}),truncated:T.truncated||E.truncated},Ae=await _(he.map(e=>e.path),i??null,y)?{...ke,skills:ke.skills.map(e=>{if(e.scope!==`project`)return e;let t=e.canonicalPath??e.path,n=!Ps(t)&&i?.isPathIgnored(t)===!0;if(n===(e.ignored===!0))return e;if(n)return{...e,ignored:!0};let{ignored:r,...a}=e;return a})}:ke;a.writeList(S,Ae),Q(b,200,zr,Ae,{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0})})}const brt=/[^\p{L}\p{N}\p{M}\p{Extended_Pictographic}.\-_ ]/gu,xrt=/[/\\\x00-\x1f\x7f]/g;function Srt(e){let t=e.replace(xrt,``);if(t=t.replace(brt,`_`),t=t.replace(/_+/g,`_`).replace(/\.{2,}/g,`.`),t=t.replace(/^[._]+/,``),t=t.replace(/\.+$/,``),t===``)return`upload`;let n=new TextEncoder;if(n.encode(t).length>255){let e=t.lastIndexOf(`.`),r=e>=0?t.slice(e):``,i=e>=0?t.slice(0,e):t;for(;n.encode(i+r).length>255&&i.length>0;)i=i.slice(0,-1);t=(i||`upload`)+r,n.encode(t).length>255&&(t=`upload`)}return t}const Crt=q(`skill-import`),wrt={maxFileBytes:Ve,maxFiles:512};function Trt(e){if(e.files.length>512)return`Skill has ${e.files.length} dependent files; the import cap is 512.`;let t=Buffer.byteLength(e.skillMd);for(let n of e.files){let e=n.bytes?.byteLength??Buffer.byteLength(n.content??``);if(e>16777216)return`${n.relPath} is ${e} bytes; the import per-file cap is ${Ve}.`;t+=e}return t>67108864?`Skill is ${t} bytes; the import bundle cap is ${xt}.`:null}function Ert(e){function t(e,t){return iP(W(e,t))?.contentHash}return{async runSkillImport(n){let{acquiredDir:r,scope:i,sourceLabel:a,ref:o,publisher:s,upstreamSkill:c,actor:l}=n;if(!e.projectDir)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`No project root resolved.`,detail:`NO_PROJECT_ROOT`};let u=rP(r);if(u)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:u};let d=iP(r);if(!d)return{ok:!1,status:422,urn:`urn:ok:error:invalid-request`,title:`Source has no readable skill.`};let f=Trt(d);if(f)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:f};let p=H(i===`project`?e.projectDir:e.skillsHome,...Qn),m=t2(p),h=i===`project`?e.contentDir:e.skillsHome,g=m0(h,i);if(g===null)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Open Knowledge only writes skills into an agent folder that already exists (${ont(i).join(`, `)}) and never creates one for you. Create the folder your agent uses, then import again.`,detail:`NO_USABLE_SKILL_HOME`};let _=W(h,g),v=vr(m,d.contentHash);if(v&&e.resolveSkillDirForRead(i,v)!==null)return{ok:!0,body:{name:v,path:`${v}/SKILL.md`,created:!1,alreadyImported:!0,provenance:{source:a,ref:o,contentHash:d.contentHash,publisher:s},warnings:[],warningCodes:[]}};let y=Srt(d.name),b=t=>e.resolveSkillDirForRead(i,t)!==null||G(W(_,t,`SKILL.md`)),x=b(y),S=y;if(x){S=`${y}-imported`;let e=2;for(;b(S);)S=`${y}-imported-${e}`,e+=1}let C=e.parseFrontmatterDoc(d.skillMd),w=C.body,T=po(C.frontmatter),E=X1({skillsRoot:_,name:S,body:w,frontmatter:{name:S,description:d.description,...T===void 0?{}:{metadata:{pack:T}}}});if(!E.ok)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Failed to write imported skill.`,detail:E.error.code,cause:Error(E.error.message)};let D=[...E.warnings];for(let e of d.files){let t=$1({skillsRoot:_,name:S,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:wrt});if(!t.ok){let n=e0({skillsRoot:_,name:S});return{ok:!1,status:n.ok?400:500,urn:n.ok?`urn:ok:error:invalid-request`:`urn:ok:error:internal-server-error`,title:`Failed to write the complete imported skill bundle.`,detail:`${e.relPath}: ${t.error.code}`,cause:Error(n.ok?t.error.message:`${t.error.message}; rollback: ${n.error.message}`)}}}i===`project`&&(e.attributeOkArtifactWrite(l,`${g}/${S}/SKILL`,`skill-import: ${a} -> ${g}/${S}/SKILL.md`),await e.commitOkArtifactWrite(`skill-import`));let O=t(_,S),k=NP(a),ee=i===`project`?await e.shadowHeadSha(e.artifactWriterId(l),`${g}/${S}`):void 0;if(await n2(p,e=>Ur(e,S,{source:a,...k?{pluginProvider:k.provider}:{},ref:o,contentHash:d.contentHash,files:d.files.map(e=>e.relPath),...O===void 0?{}:{localHash:O},...ee===void 0?{}:{baselineRef:ee},publisher:s,importedAt:new Date().toISOString(),...c===void 0?{}:{skill:c}})),n.skipProjection!==!0)try{let t=z0(h);if(t.length>0){let n=W(_,S),r=B0(i),a=t.filter(e=>{let t=H0(h,e,S,r);return t!==null&&t!==n&&G(t)}),o=a.filter(e=>{let t=H0(h,e,S,r);try{return t!==null&&Ys(t).isSymbolicLink()}catch{return!1}});Y0({canonicalAbs:n,canonicalHash:iP(n)?.contentHash??``,canonicalRootRel:g,name:S,cwd:h,targets:t,mode:e.effectiveInstallMode(i,S,{hosts:[`<source>`,...a],linkedHosts:o}),roots:B0(i)})}}catch(e){Crt.warn({err:e,skill:S},`post-import editor fan-out failed (import kept)`)}return e.signalFiles(),{ok:!0,body:{name:S,path:`${g}/${S}/SKILL.md`,created:E.created,alreadyImported:!1,...x?{collisionRenamedFrom:d.name}:{},provenance:{source:a,ref:o,contentHash:d.contentHash,publisher:s},warnings:D,warningCodes:E.warningCodes}}}}}function Drt(e,t){let{recordedSkill:n,localName:r,frontmatterNameOf:i}=t;return(n?e.find(e=>e.name===n):void 0)??e.find(e=>e.name===r)??e.find(e=>i(e.dir)===r)??e.find(e=>e.name===Gt[n??r])??(e.length===1?e[0]:void 0)}function Ort(e){let t=new Set(e.upstreamFiles),n=new Set(e.local?.files??[]),r=(e.entry.files??(e.entry.localHash!==void 0&&e.local?.contentHash===e.entry.localHash?[...n]:[])).filter(e=>!t.has(e)).filter(e=>n.has(e));return{upToDate:e.upstreamHash===e.entry.contentHash&&r.length===0,removedUpstream:r}}function krt(e,t){let n=new Map,r=[];for(let i of new Set(e)){let e=t(i);if(!e){r.push(i);continue}let a=n.get(e.source);a?a.push(i):n.set(e.source,[i])}return{bySource:[...n].map(([e,t])=>({source:e,names:t})),unrecorded:r}}function Art(e){return{async runSkillReimport(t){let{acquiredDir:n,name:r,scope:i,entry:a,lockPath:o,ref:s,actor:c}=t,l=i===`global`?e.skillsHome:e.contentDir,{root:u,dirRel:d,realDir:f}=e.effectiveSkillRoot(i,r),p=!d.startsWith(`${e.legacyStoreRoot}/`);if(f===null||!G(W(l,d,`SKILL.md`)))return{ok:!1,status:404,urn:`urn:ok:error:not-found`,title:`Skill is not installed.`,detail:`SKILL_ABSENT`};let m=rP(n);if(m)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:m};let h=iP(n);if(!h)return{ok:!1,status:422,urn:`urn:ok:error:invalid-request`,title:`Source has no readable skill.`};let g=Trt(h);if(g)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:g};let _=iP(W(u,r)),{upToDate:v,removedUpstream:y}=Ort({upstreamHash:h.contentHash,upstreamFiles:h.files.map(e=>e.relPath),entry:a,local:_?{contentHash:_.contentHash,files:_.files.map(e=>e.relPath)}:null});if(v)return{ok:!0,body:{name:r,updated:!1,source:a.source,warnings:[],warningCodes:[]}};let b=e.parseFrontmatterDoc(h.skillMd),x=b.body,S=po(b.frontmatter);if(t.dryRun){let t;if(i===`project`&&e.projectDir)try{let n=RN({baseDir:e.projectDir,timeout:{block:15e3}}),i=U(e.projectDir,W(u,r)).split(Rs).join(`/`);t=(await n.raw(`ls-files`,...Wt([i]))).trim().length>0}catch{t=void 0}return{ok:!0,body:{name:r,updated:!0,source:a.source,localBody:e.parseFrontmatterDoc(_?.skillMd??``).body,upstreamBody:x,...t===void 0?{}:{gitTracked:t},warnings:[],warningCodes:[]}}}if(i===`project`){let t=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${d}/${e.replace(/\.mdx?$/i,``)}`);t.length>0&&await e.captureAndCloseDocuments(t,`deleted-upstream`)}let C=X1({skillsRoot:u,name:r,body:x,frontmatter:{name:r,description:h.description,...S===void 0?{}:{metadata:{pack:S}}}});if(!C.ok)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Failed to write skill.`,detail:C.error.code,cause:Error(C.error.message)};let w=[...C.warnings];for(let e of h.files){let t=$1({skillsRoot:u,name:r,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:wrt});if(!t.ok)return{ok:!1,status:500,urn:`urn:ok:error:internal-server-error`,title:`Failed to write the complete refreshed skill bundle.`,detail:`${e.relPath}: ${t.error.code}`,cause:Error(t.error.message)}}for(let e of y){let t=Ktt({skillsRoot:u,name:r,relPath:e});if(!t.ok)return{ok:!1,status:500,urn:`urn:ok:error:internal-server-error`,title:`Failed to reconcile files removed upstream.`,detail:`${e}: ${t.error.code}`,cause:Error(t.error.message)}}i===`project`&&(e.attributeOkArtifactWrite(c,e.skillArtifactKey(r),`skill-reimport: ${a.source} -> ${d}`),await e.commitOkArtifactWrite(`skill-reimport`));let T=iP(W(u,r))?.contentHash,E=i===`project`?await e.shadowHeadSha(e.artifactWriterId(c),d):void 0;return await n2(o,e=>Ur(e,r,{...e.skills[r]??a,contentHash:h.contentHash,files:h.files.map(e=>e.relPath),...T===void 0?{}:{localHash:T},...E===void 0?{}:{baselineRef:E},ref:s,importedAt:new Date().toISOString()})),!p&&i===`project`&&await e.projectImportedSkillCopy({skillsRoot:u,name:r,scope:`project`,hasScripts:h.files.some(e=>e.relPath.startsWith(`scripts/`)),handler:`skill-reimport`}),e.signalFiles(),{ok:!0,body:{name:r,updated:!0,source:a.source,warnings:w,warningCodes:C.warningCodes}}}}}function jrt(e,t){let n=e===`.`?``:e.replace(/^\.\//,``);return n?`${n}/${t}`:t}function Mrt(e){return/not a valid object name|not a tree object|bad revision|unknown revision|invalid object name/i.test(e)}async function Nrt(e){let{shadow:t,contentDir:n,contentRoot:r,name:i,version:a}=e,o=e.skillDirRel??`.ok/skills/${i}`;if(!G(t.workTree)||!G(t.gitDir))return{ok:!1,code:`no-shadow`,error:`No shadow repo — nothing to restore from.`};let s=gK(t),c=[...new Set([o,`.ok/skills/${i}`])],l=[],u=jrt(r,o);try{for(let e of c){let t=jrt(r,e),n=await VG(s,[`ls-tree`,`-r`,`--name-only`,a,...Wt([t])]);if(n.length>0){l=n,u=t;break}}}catch(e){let t=e instanceof Error?e.message:String(e);return Mrt(t)?{ok:!1,code:`version-not-found`,error:`Version ${a.slice(0,8)} not found.`}:{ok:!1,code:`io-error`,error:`Failed to read version ${a.slice(0,8)}: ${t}`}}if(l.length===0)return{ok:!1,code:`skill-absent`,error:`Skill "${i}" did not exist at version ${a.slice(0,8)}.`};let d=W(n,o),f=d+Rs,p=[];for(let e of l){let t=e.slice(u.length).replace(/^\//,``),n=W(d,t);if(n!==d&&!n.startsWith(f))return{ok:!1,code:`path-escape`,error:`Refusing to restore path outside skill dir: ${t}`};try{p.push({rel:t,destAbs:n,content:await s.raw(`show`,`${a}:${e}`)})}catch(e){let n=e instanceof Error?e.message:String(e);return{ok:!1,code:`io-error`,error:`Failed reading ${t} at ${a.slice(0,8)}: ${n}`}}}FG(d,{recursive:!0,force:!0});let m=[];for(let{rel:e,destAbs:t,content:n}of p)kG(V(t),{recursive:!0}),DG(t,n,`utf-8`),m.push(e);return{ok:!0,restoredFiles:m}}function Prt(e){try{let t=K(H(e,`SKILL.md`),`utf-8`),n=/^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(t)?.[1];return n!==void 0&&/^[ \t]+pack:[ \t]*"?[a-z0-9-]+"?[ \t]*$/m.test(n)}catch{return!1}}function Frt(e){let{synthPluginLockEntry:t,synthBuiltinLockEntry:n,isValidSkillName:r,getPrincipal:i,validateSkillName:a,rejectReservedBuiltinSkill:o,shadowRef:s,contentDir:c,contentRoot:l,projectDir:u,skillsHome:d,projectSkillDirRel:f,attributeOkArtifactWrite:p,okArtifactKey:m,commitOkArtifactWrite:h,signalChannel:g,bumpSkillsCatalogGen:_,contentFilter:v,scheduleDeferredIgnoreRebuild:y,effectiveSkillRoot:b,skillReimportService:x,localSkillHash:S,resolveSkillsRoot:C,projectImportedSkillCopy:w}=e;function T(e,t,n){let[r,i]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[t.code];X(e,r,i,t.error,{handler:n,detail:t.code})}function E(e,t){if(t.ok){Q(e,200,Wa,t.body,{handler:`skill-reimport`});return}X(e,t.status,t.urn,t.title,{handler:`skill-reimport`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}function D(e,t,n){let r=e===`project`?c:d,i=(e===`project`?y0(c):b0(d)).find(e=>e.name===t);return i?W(r,i.dir):W(n,t)}function O(e,r,i,a){let o=a.skills[r];if(o)return o;let s=D(e,r,i);return ut(r,iP(s)?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:Prt(s)})??n(e===`global`?d:c,r,e)??t(r,VS(u??c),s)}return N$({"/api/skill/restore":Z(_te,async(e,t,n)=>{try{let e=v$(n,i);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!a(n.name,t,`skill-restore`)||o(n.name,t,`skill-restore`))return;if(n.scope===`global`){X(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=s?.current;if(!r){X(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let u=await Nrt({shadow:r,contentDir:c,contentRoot:l??`.`,name:n.name,version:n.version,skillDirRel:f(n.name)});if(!u.ok){T(t,u,`skill-restore`);return}let d=[],b=R0(W(c,f(n.name)),n.name);b.ok||d.push(`Restored, but the skill no longer validates: ${b.errors.join(` `)}`),p(e,m(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await h(`skill-restore`),g?.(`files`),_(),v?.refreshInPlaceSkillDirs(),y(),Q(t,200,jte,{name:n.name,version:n.version,restoredFiles:u.restoredFiles,warnings:d},{handler:`skill-restore`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),"/api/skill/reimport":Z(Tne,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!u){X(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=v$(n,i);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!a(n.name,t,`skill-reimport`))return;let o=n.scope===`global`?d:c,{root:s,dirRel:l,realDir:f}=b(n.scope,n.name);if(f===null||!G(W(o,l,`SKILL.md`))){X(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let p=H(n.scope===`global`?d:u,...Qn),m=O(n.scope,n.name,s,t2(p));if(!m){X(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await n2(p,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??m,autoUpdate:n.setAutoUpdate}}})),_(),v?.refreshInPlaceSkillDirs(),y(),Q(t,200,Wa,{name:n.name,updated:!1,source:m.source,warnings:[],warningCodes:[]},{handler:`skill-reimport`});return}let h,g=null;try{let e=m.skill??n.name,i=Gt[e],a=await uP(m.source,e).catch(async e=>{if(i===void 0)throw e;return uP(m.source,i)}),o=a?.source??PP(m.source,m.pluginProvider),s=a?.skill??m.skill,c=a?.spec??JN(o);if(!c){X(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:m.source});return}if(o2(t,c,`skill-reimport`))return;let l=await XN(c);r=l.cleanup,h=l.ref;let u=oP(l.dir),d=Drt(u,{...s===void 0?{}:{recordedSkill:s},localName:n.name,frontmatterNameOf:e=>iP(e)?.name});if(!d){X(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}g=d.dir}catch(e){if(e instanceof BN){X(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!g){X(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let S=await x.runSkillReimport({acquiredDir:g,name:n.name,scope:n.scope,entry:m,lockPath:p,ref:h,actor:e,...n.dryRun===void 0?{}:{dryRun:n.dryRun}});_(),v?.refreshInPlaceSkillDirs(),y(),E(t,S)}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),"/api/skills/reimport-bulk":Z(Ne,async(e,t,n)=>{try{if(n.scope===`project`&&!u){X(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-reimport-bulk`,detail:`NO_PROJECT_ROOT`});return}let a=v$(n,i);if(a.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-reimport-bulk`});return}let o=H(n.scope===`global`?d:u,...Qn),s=t2(o),c=[],{bySource:l,unrecorded:f}=krt([...new Set(n.names)].filter(e=>r(e)?!0:(c.push({requested:e,status:`failed`,warnings:[],error:`INVALID_NAME`,warningCodes:[]}),!1)),e=>O(n.scope,e,b(n.scope,e).root,s));for(let e of f)c.push({requested:e,status:`not-found`,warnings:[],warningCodes:[]});for(let t of l){let r=()=>{};try{let i,l=[];try{let e=t.names[0],n=await uP(t.source,e).catch(async n=>{let r=Gt[e];if(r===void 0)throw n;return uP(t.source,r)}),a=n?.source??PP(t.source,s.skills[t.names[0]]?.pluginProvider),o=n?.spec??JN(a);if(!o||drt(o)){for(let e of t.names)c.push({requested:e,status:`failed`,source:t.source,warnings:[],warningCodes:[],error:`INVALID_SOURCE`});continue}let u=await XN(o);r=u.cleanup,i=u.ref,l=oP(u.dir)}catch(n){q(`skills-reimport-bulk`).warn({source:t.source,err:n,requestId:DJ(e)},`bulk update: one source could not be fetched (rest continue)`);for(let e of t.names)c.push({requested:e,status:`failed`,source:t.source,warnings:[],warningCodes:[],error:n instanceof Error?n.message:String(n)});continue}for(let r of t.names){let t=O(n.scope,r,b(n.scope,r).root,s);if(!t){c.push({requested:r,status:`not-found`,warnings:[],warningCodes:[]});continue}let u=Drt(l,{...t.skill===void 0?{}:{recordedSkill:t.skill},localName:r,frontmatterNameOf:e=>iP(e)?.name});if(!u){c.push({requested:r,status:`not-found`,source:t.source,warnings:[],warningCodes:[]});continue}try{let s=await x.runSkillReimport({acquiredDir:u.dir,name:r,scope:n.scope,entry:t,lockPath:o,ref:i,actor:a});if(!s.ok){q(`skills-reimport-bulk`).warn({skill:r,err:s.cause,detail:s.detail,requestId:DJ(e)},`bulk update: one skill failed (rest continue)`),c.push({requested:r,status:`failed`,source:t.source,warnings:[],warningCodes:[],error:s.detail??s.title});continue}c.push({requested:r,status:s.body.updated?`updated`:`up-to-date`,source:s.body.source,warnings:s.body.warnings,warningCodes:s.body.warningCodes})}catch(n){q(`skills-reimport-bulk`).warn({skill:r,err:n,requestId:DJ(e)},`bulk update: one skill threw (rest continue)`),c.push({requested:r,status:`failed`,source:t.source,warnings:[],warningCodes:[],error:n instanceof Error?n.message:String(n)})}}}finally{r()}}Q(t,200,be,{results:c,updated:c.filter(e=>e.status===`updated`).length,upToDate:c.filter(e=>e.status===`up-to-date`).length,failed:c.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-reimport-bulk`});try{_(),v?.refreshInPlaceSkillDirs(),_(),await v?.rebuildIgnorePatterns()}catch(e){q(`skills-reimport-bulk`).warn({err:e},`bulk update: ignore-pattern rebuild failed after a reported success`)}}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to update skills.`,{handler:`skills-reimport-bulk`,cause:e})}},{handler:`skills-reimport-bulk`,method:`POST`}),"/api/skill/revert":Z(ore,async(e,t,n)=>{try{if(!u){X(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=v$(n,i);if(e.kind===`invalid-summary`){X(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!a(n.name,t,`skill-revert`)||o(n.name,t,`skill-revert`))return;if(n.scope===`global`){X(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=H(u,...Qn),d=t2(r).skills[n.name];if(!d?.baselineRef){X(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let _=s?.current;if(!_){X(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let v=await Nrt({shadow:_,contentDir:c,contentRoot:l??`.`,name:n.name,version:d.baselineRef,skillDirRel:f(n.name)});if(!v.ok){T(t,v,`skill-revert`);return}p(e,m(`skill`,``,n.name),`skill-revert: ${n.name} @ ${d.baselineRef.slice(0,8)}`),await h(`skill-revert`);let y=W(c,f(n.name),`..`),b=S(y,n.name);await n2(r,e=>Ur(e,n.name,{...e.skills[n.name]??d,...b===void 0?{}:{localHash:b}})),y===C(`project`)&&await w({skillsRoot:y,name:n.name,scope:`project`,hasScripts:v.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),g?.(`files`),Q(t,200,Pne,{name:n.name,baselineRef:d.baselineRef,restoredFiles:v.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`})},{mutating:[`/api/skill/restore`,`/api/skill/reimport`,`/api/skills/reimport-bulk`,`/api/skill/revert`]})}function Irt(e){let{contentDir:t,projectDir:n,contentFilter:r,validateSkillName:i,indexedSkillContentPath:a,bumpSkillsCatalogGen:o,signalChannel:s}=e;function c(e){return`!/${V(e).split(Rs).join(`/`)}/`}return N$({"/api/skill/track-in-git":Z(Eie,F$(async(e,l,u)=>{if(!i(u.name,l,`skill-track-in-git`))return;if(u.scope!==`project`){X(l,400,`urn:ok:error:invalid-request`,`Only project skills live in the repository; a global skill is outside any .gitignore.`,{handler:`skill-track-in-git`});return}if(!n){X(l,400,`urn:ok:error:invalid-request`,`No project directory.`,{handler:`skill-track-in-git`});return}let d=y0(t).find(e=>e.name===u.name)?.dir??`.ok/skills/${u.name}`,f=a(W(t,d,`SKILL.md`),t)??`${d}/SKILL.md`,p=V(f),m=f,h=c(p),g=`.gitignore`,_=W(t,g);if(r&&!r.isPathIgnored(m)){Q(l,200,ji,{line:h,gitignorePath:g,applied:!1,alreadyTracked:!0},{handler:`skill-track-in-git`});return}if(u.apply!==!0){Q(l,200,ji,{line:h,gitignorePath:g,applied:!1},{handler:`skill-track-in-git`});return}let v=G(_)?K(_,`utf-8`):null;if((v??``).split(`
1073
1073
  `).some(e=>e.trim()===h)){X(l,409,`urn:ok:error:invalid-request`,`"${h}" is already in ${g}, but ${m} is still ignored — another rule excludes it.`,{handler:`skill-track-in-git`});return}let y=`${v===null||v.endsWith(`
1074
1074
  `)||v===``?v??``:`${v}\n`}${h}\n`;if(cc(_,y,`utf-8`),o(),await r?.rebuildIgnorePatterns(),r?.isPathIgnored(m)){v===null?ic(_,{force:!0}):cc(_,v,`utf-8`),o(),await r.rebuildIgnorePatterns(),X(l,409,`urn:ok:error:invalid-request`,`Adding "${h}" did not make ${m} trackable — another .gitignore rule excludes a parent directory. ${g} was left unchanged.`,{handler:`skill-track-in-git`});return}s?.(`files`),Q(l,200,ji,{line:h,gitignorePath:g,applied:!0},{handler:`skill-track-in-git`})},{handler:`skill-track-in-git`,title:`Failed to update .gitignore.`}),{handler:`skill-track-in-git`,method:`POST`})},{mutating:[`/api/skill/track-in-git`]})}const Lrt=[`INDEX`,`README`,`REPORT`,`SPEC`];function Rrt(e,t){let n=[],r=new Set,i=t=>{!t||r.has(t)||t!==e&&(r.add(t),n.push(t))},a=Brt(t),o=Vrt(e);for(;;){for(let e of Lrt)if(i(s2(t,a,c2(o,e))),n.length>=3)return n;let e=o===``?null:Hrt(o);if(e&&(i(s2(t,a,c2(o,e))),n.length>=3))return n;if(o===``)break;o=Vrt(o)}return n}function zrt(e,t){let n=[],r=Brt(t),i=Hrt(e);for(let a of[...Lrt,i]){let i=s2(t,r,c2(e,a));if(i&&!n.includes(i)&&n.push(i),n.length>=3)return n}let a=`/${e.toLowerCase()}`,o=[...t.keys()].filter(e=>e.toLowerCase().endsWith(a)).sort((e,t)=>e.length-t.length||e.localeCompare(t));for(let e of o)if(n.includes(e)||n.push(e),n.length>=3)break;return n}function s2(e,t,n){return e.has(n)?n:t.get(n.toLowerCase())??null}function Brt(e){let t=new Map;for(let n of e.keys()){let e=n.toLowerCase();t.has(e)||t.set(e,n)}return t}function Vrt(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function Hrt(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function c2(e,t){return e===``?t:`${e}/${t}`}var l2=class{entries=new Map;maxEntries;maxBytes;byteCount=0;hits=0;misses=0;constructor(e={}){this.maxEntries=e.maxEntries??1e4,this.maxBytes=e.maxBytes??67108864}static fingerprintConfig(e){return Tc(`sha1`).update(JSON.stringify(e)).digest(`base64`)}static key(e){return[e.contentDir,e.docRelPath,e.mtimeMs,e.size,e.configFingerprint].join(`\0`)}get(e){let t=this.entries.get(e);return t===void 0?(this.misses+=1,null):(this.hits+=1,this.entries.delete(e),this.entries.set(e,t),JSON.parse(t.json))}set(e,t){let n=this.entries.get(e);n!==void 0&&(this.byteCount-=n.bytes,this.entries.delete(e));let r=JSON.stringify(t),i=Buffer.byteLength(r,`utf8`);this.entries.set(e,{json:r,bytes:i}),this.byteCount+=i,this.evictToBounds()}evictToBounds(){for(;(this.entries.size>this.maxEntries||this.byteCount>this.maxBytes)&&this.entries.size>1;){let e=this.entries.keys().next();if(e.done===!0)return;let t=this.entries.get(e.value);this.entries.delete(e.value),t!==void 0&&(this.byteCount-=t.bytes)}}stats(){return{hits:this.hits,misses:this.misses,entries:this.entries.size,bytes:this.byteCount}}clear(){this.entries.clear(),this.byteCount=0,this.hits=0,this.misses=0}};function Urt(e){return`Scope ${JSON.stringify(e)} was not found. Use an existing file or directory; a document stem without .md or .mdx resolves .mdx before .md. Explicit document extensions must exist as written.`}function u2(e,t){let n=W(t),r=W(n,e??``);if(!f2(n,!0)?.isDirectory())return{ok:!1,path:n,title:`Content directory ${JSON.stringify(n)} was not found. Set content.dir to an existing directory.`};let i=f2(r);if(i!==void 0){let e=i.isSymbolicLink()?f2(r,!0):i;if(e?.isFile())return{ok:!0,scope:{kind:`file`,path:r}};if(e?.isDirectory())return{ok:!0,scope:{kind:`dir`,path:r}}}else if(r!==n&&pq(r,n)&&!Bi.some(e=>r.toLowerCase().endsWith(e)))for(let e of Bi){let t=`${r}${e}`;if(f2(t,!0)?.isFile())return{ok:!0,scope:{kind:`file`,path:t}}}return{ok:!1,path:r,title:Urt(e??`.`)}}function d2(e){return e instanceof Error&&`code`in e&&(e.code===`ENOENT`||e.code===`ENOTDIR`||e.code===`ENAMETOOLONG`||e.code===`ELOOP`||e.code===`ERR_INVALID_ARG_VALUE`)}function f2(e,t=!1){try{return t?oc(e):Ys(e)}catch(e){if(d2(e))return;throw e}}function p2(e,t){let n=U(t,e);return n===``||!n.startsWith(`..`)&&!Ps(n)}function m2(e,t){let n=JS(e);try{DG(n,t,`utf-8`),AG(n,e)}catch(e){try{MG(n)}catch{}throw e}}function Wrt(e){let t=H(e,`.ok`,`schemas`),n;try{n=tc(t,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.toLowerCase().endsWith(`.json`)).map(e=>e.name).sort((e,t)=>e.localeCompare(t))}catch(e){let n=e.code;return n!==`ENOENT`&&n!==`ENOTDIR`&&q(`frontmatter-schemas`).warn({err:e,code:n,dir:t},`could not enumerate .ok/schemas; the schema picker will show an empty list`),{schemas:[],truncated:!1}}let r=n.length>500;return{schemas:n.slice(0,500).map(e=>`.ok/schemas/${e}`),truncated:r}}function h2(e){return e instanceof Error?e.message:String(e)}function Grt(e,t){let n=[];for(let r of e)if(r.enabled!==!1)for(let e of oee(r.appliesTo,t))n.push(`unmatched appliesTo glob ${JSON.stringify(e)} — matches no docs in this project (frontmatter mapping for ${r.file})`);return n}function Krt(e,t){let n=W(e,t);if(!p2(n,W(e)))return{problem:`frontmatter schema ${t}: resolves outside the project`};let r;try{r=nc(n)}catch(e){return{problem:`frontmatter schema ${t}: cannot read (${h2(e)})`}}let i;try{i=nc(e)}catch(e){return{problem:`frontmatter schema ${t}: cannot read (${h2(e)})`}}if(!p2(r,i))return{problem:`frontmatter schema ${t}: resolves outside the project`};let a;try{a=K(r,`utf-8`)}catch(e){return{problem:`frontmatter schema ${t}: cannot read (${h2(e)})`}}let o;try{o=JSON.parse(a)}catch(e){return{problem:`frontmatter schema ${t}: malformed JSON (${h2(e)})`}}if(typeof o!=`object`||!o||Array.isArray(o))return{problem:`frontmatter schema ${t}: not a JSON object`};let s=o;if(!nr(s)){let e=JSON.stringify(cr[Wre]);return{problem:`frontmatter schema ${t}: unsupported dialect ${JSON.stringify(s.$schema)} (supported: ${Yte.join(`, `)}; e.g. ${e})`}}let c=Ce(s);return c===null?{schema:s,key:r}:{problem:`frontmatter schema ${t}: does not compile (${c})`}}function qrt(e,t){let n=[],r=new Map,i=new Set,a=[];for(let o of t){let t=o.enabled===!1,s=Ni(o.appliesTo);for(let{pattern:e,detail:r}of s.invalidPatterns)t||n.push(`invalid appliesTo glob ${JSON.stringify(e)} — ${r} (frontmatter mapping for ${o.file})`);for(let{pattern:e,reason:r}of s.suspiciousPatterns){if(t)continue;let i=r===`trailing-slash`?`a trailing slash can never match (doc paths have no trailing slash)`:r===`leading-slash`?`a leading slash can never match (doc paths are relative)`:`doc paths are extension-less; drop the file extension`;n.push(`suspicious appliesTo glob ${JSON.stringify(e)} — ${i} (frontmatter mapping for ${o.file})`)}let c=r.get(o.file);c===void 0&&(c=Krt(e,o.file),r.set(o.file,c)),`problem`in c&&!t&&!i.has(o.file)&&(i.add(o.file),n.push(c.problem)),a.push(`problem`in c?{...o,key:o.file}:{...o,key:c.key,schema:c.schema})}return{entries:a,problems:n}}const Jrt=[`.markdownlint.jsonc`,`.markdownlint.json`,`.markdownlint.yaml`,`.markdownlint.yml`,`.markdownlint.cjs`,`.markdownlint.mjs`,`.markdownlintrc`];function g2(e){for(let t of Jrt){let n=H(e,t);if(G(n))return{name:t,path:n}}return null}function Yrt(e){let t=g2(e);return t?Qrt(t.path,t.name,e):null}function Xrt(e,t){let n=W(t),r=W(e);for(p2(r,n)||(r=n);;){let e=g2(r);if(e)return Qrt(e.path,U(n,e.path)||e.name,n);if(r===n)return null;let t=V(r);if(t===r)return null;r=t}}function Zrt(e){let t=g2(e);if(!t||/\.(cjs|mjs|js)$/.test(t.path))return null;let n=K(t.path,`utf-8`),r=$rt(n,t.name);if(`error`in r)return null;let{value:i}=r;return!i||typeof i!=`object`||Array.isArray(i)?null:{rules:i,name:t.name,path:t.path,raw:n}}function Qrt(e,t,n){let r=[],i=new Set,a=(e,t)=>{if(!p2(W(e),W(n)))return r.push(`refusing extends target outside the project: ${U(n,e)||e}`),null;let o;try{o=nc(e)}catch(t){return r.push(`cannot read ${U(n,e)||e}: ${_2(t)}`),null}if(!p2(o,nc(n)))return r.push(`refusing extends target outside the project: ${U(n,e)||e}`),null;if(i.has(o))return r.push(`extends cycle at ${U(n,e)||e}`),null;if(i.add(o),t>10)return r.push(`extends chain deeper than 10 levels`),null;if(/\.(cjs|mjs|js)$/.test(e))return r.push(`executable markdownlint config detected but not executed: ${U(n,e)||e} — use a JSON/JSONC/YAML config`),null;let s;try{s=K(o,`utf-8`)}catch(t){return r.push(`cannot read ${U(n,e)||e}: ${_2(t)}`),null}let c=$rt(s,e);if(`error`in c)return r.push(`malformed markdownlint config: ${U(n,e)||e} (${c.error})`),null;if(!c.value||typeof c.value!=`object`||Array.isArray(c.value))return r.push(`malformed markdownlint config: ${U(n,e)||e} (not an object)`),null;let{extends:l,$schema:u,...d}=c.value;if(l==null)return d;if(typeof l!=`string`||l===``)return r.push(`invalid extends value in ${U(n,e)||e}`),d;if(!l.startsWith(`.`)&&!Ps(l))return r.push(`package extends is not supported (${JSON.stringify(l)} in ${U(n,e)||e}) — use a relative file path`),d;let f=W(V(e),l),p=a(f,t+1);return p?{...p,...d}:d};return{rules:a(e,0),file:t,problems:r}}function _2(e){return(e instanceof Error?e.message:String(e)).split(`
@@ -2076,7 +2076,7 @@ tags: [lore, history]
2076
2076
  }
2077
2077
  }`,variables:{owner:e.owner,name:e.repo,number:e.number}})},n,r);if(a.status!==200)return M8(a)?(i(a),N8):`fallback`;let o=aht(a.body);if((o||a.headers.get(`x-ratelimit-remaining`)===`0`)&&i(a),o)return`fallback`;let s=P8(P8(a.body)?.data);if(s===null)return`fallback`;let c=P8(s.repository);if(c===null||c.issueOrPullRequest===null)return cht;let l=pht(e,c.issueOrPullRequest);return l===null?`fallback`:{ok:!0,preview:l}}async function ght(e,t,n,r,i){let a={headers:dht(t,`application/vnd.github+json`)},o=lht(e),s=e=>e.status===404||e.status===410?cht:(M8(e)&&i(e),N8),c=async()=>{let t=await L8(`${o}/pulls/${e.number}`,a,n,r);if(t.status!==200)return s(t);let i=mht(e,null,t.body);return i===null?N8:{ok:!0,preview:i}};if(e.kind===`pull`)return c();let l=await L8(`${o}/issues/${e.number}`,a,n,r);if(l.status!==200)return s(l);if(P8(P8(l.body)?.pull_request)!==null)return c();let u=mht(e,l.body,null);return u===null?N8:{ok:!0,preview:u}}async function _ht(e){let{target:t,token:n,rateLimits:r}=e,i=e.fetchFn??fetch,a=e.timeoutMs??5e3,o=e.now??Date.now,s=`graphql ${t.host}`,c=`rest ${n===null?`anonymous`:`signed-in`} ${t.host}`,l=e=>r?.holding(e,o())===!0,u=(e,i)=>{if(r===void 0)return;let a=rht(i)?n===null?[c]:[s,c]:[e===`graphql`?s:c],l=0;for(let e of a)l=Math.max(l,r.hold(e,i.headers,o()));let u=a.length>1?`graphql+rest`:e;eht.info({host:t.host,signedIn:n!==null,api:u,until:new Date(l).toISOString()},oht[u])};try{if(n!==null&&!l(s)){let e=await hht(t,n,i,a,e=>u(`graphql`,e));if(e!==`fallback`)return e}return l(c)?N8:await ght(t,n,i,a,e=>u(`rest`,e))}catch(e){let n=e instanceof Error&&e.name===`AbortError`?`timeout`:e instanceof SyntaxError?`bad-response`:`network`;return eht.warn({reason:n,host:t.host,repo:`${t.owner}/${t.repo}`,number:t.number,...n===`timeout`?{}:{err:e}},`[github-reference] GitHub request failed; the reference stays a plain link`),N8}}function vht(e){if(!e.ok)return e.reason===`not-found`?3e5:6e4;let t=e.preview.lifecycle;return t===`open`||t===`draft`?6e4:18e5}var yht=class{entries=new Map;inflight=new Map;now;constructor(e=Date.now){this.now=e}load(e,t){let n=this.entries.get(e);if(n!==void 0&&n.expiresAt>this.now())return this.entries.delete(e),this.entries.set(e,n),Promise.resolve(n.outcome);let r=this.inflight.get(e);if(r!==void 0)return r;let i=t().then(t=>(this.store(e,t),t)).finally(()=>{this.inflight.delete(e)});return this.inflight.set(e,i),i}store(e,t){for(this.entries.delete(e),this.entries.set(e,{outcome:t,expiresAt:this.now()+vht(t)});this.entries.size>256;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e)}}};const bht=/^\/([A-Za-z0-9][A-Za-z0-9-]{0,38})\/([A-Za-z0-9._-]{1,100})\/(pull|issues)\/(\d{1,10})(?:\/[^?#]*)?$/;function xht(e,t){let n;try{n=new URL(e)}catch{return null}if(n.protocol!==`https:`||n.username!==``||n.password!==``||n.port!==``)return null;let r=Di(n.hostname);if(!sa(r,t))return null;let i=bht.exec(n.pathname);if(i===null)return null;let[,a,o,s,c]=i;if(a===void 0||o===void 0||o===`.`||o===`..`)return null;let l=Number(c);return!Number.isSafeInteger(l)||l<1?null:{host:r,owner:a,repo:o,number:l,kind:s===`pull`?`pull`:`issues`}}function Sht(e){return`${e.host}/${e.owner}/${e.repo}#${e.number}`.toLowerCase()}function Cht(e,t={}){let n=t.ttlMs??6e4,r=t.fallbackTtlMs??5e3,i=t.now??Date.now,a=new Map,o=new Map;function s(e,t){return e.token==null?null:{token:e.token,host:t,...e.resolvedLogin?{login:e.resolvedLogin}:{}}}return{get(t,c){if(!e)return null;let l=`${t}\0${c??``}`,u=i(),d=a.get(l);if(d&&d.expiresAt>u)return s(d,t);let f=e(t,{login:c}),p=f.available&&f.token?f.token:null,m=f.available?f.resolvedLogin:void 0,h=!c||p!=null&&W6(m,c),g;if(h)o.delete(l),g=n;else{let e=o.get(l)??0;o.set(l,e+1),g=Math.min(r*2**e,n)}let _={token:p,resolvedLogin:m,expiresAt:u+g};return a.set(l,_),s(_,t)},invalidate(){a.clear(),o.clear()}}}const wht=q(`github-reference`);function Tht(e){return y$(e.socket?.remoteAddress)&&!x$(e)}function Eht(e,t){let n=Cht(e);return async e=>{let r=n.get(e);if(r!==null)return r.token;if(!t)return null;try{let n=await t.get(e);return n?.token?n.token:null}catch(t){return wht.warn({err:t,host:e},`[github-reference] token store lookup failed; reading anonymously`),null}}}const Dht={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `,copy:`©`,reg:`®`,trade:`™`,mdash:`—`,ndash:`–`,hellip:`…`,lsquo:`‘`,rsquo:`’`,ldquo:`“`,rdquo:`”`};function Oht(e){return!Number.isInteger(e)||e<0||e>1114111||e>=55296&&e<=57343?null:String.fromCodePoint(e)}function kht(e){return e.replace(/&(#[xX][0-9a-fA-F]+|#\d+|[a-zA-Z][a-zA-Z0-9]*);/g,(e,t)=>{if(t.startsWith(`#`)){let n=t[1]===`x`||t[1]===`X`;return Oht(Number.parseInt(t.slice(n?2:1),n?16:10))??e}return Dht[t.toLowerCase()]??e})}function Aht(e){return e===1564||e>=8203&&e<=8207||e===8232||e===8233||e>=8234&&e<=8238||e>=8288&&e<=8292||e>=8294&&e<=8297||e===65279}function jht(e){return e<=31||e>=127&&e<=159}function Mht(e){let t=``;for(let n of e){let e=n.codePointAt(0)??0;Aht(e)||(t+=jht(e)?` `:n)}return t}function Nht(e,t){let n=Array.from(e);return n.length<=t?e:`${n.slice(0,t-1).join(``).trimEnd()}…`}function z8(e,t){return Nht(Mht(kht(e)).replace(/\s+/g,` `).trim(),t)}function Pht(e){return e.trim().toLowerCase().split(/\s+/)}function Fht(e){return e.replace(/[A-Z]+/g,e=>e.toLowerCase())}function B8(e){return e===32||e===9||e===10||e===12||e===13}const Iht=new Set([`script`,`style`,`template`,`textarea`,`iframe`,`xmp`,`noembed`,`noframes`,`plaintext`]);function Lht(e,t){let n=t;for(;n<e.length;){let t=e.charCodeAt(n);if(!(t>=97&&t<=122||t>=48&&t<=57||t===45))break;n++}return{name:e.slice(t,n),end:n}}function V8(e,t,n,r){let i=t.length,a=n;for(;a<i;){let n=t.charCodeAt(a);if(B8(n)||n===47){a++;continue}if(n===62)return a+1;let o=a;for(;a<i&&(n=t.charCodeAt(a),!(B8(n)||n===61||n===62||n===47));)a++;let s=t.slice(o,a);for(;a<i&&B8(t.charCodeAt(a));)a++;let c=``;if(a<i&&t.charCodeAt(a)===61){for(a++;a<i&&B8(t.charCodeAt(a));)a++;if(a<i){let r=t.charCodeAt(a);if(r===34||r===39){a++;let n=t.indexOf(r===34?`"`:`'`,a);c=e.slice(a,n===-1?i:n),a=n===-1?i:n+1}else{let r=a;for(;a<i&&(n=t.charCodeAt(a),!(B8(n)||n===62));)a++;c=e.slice(r,a)}}}r&&s&&!r.has(s)&&r.set(s,c)}return i}function Rht(e,t,n){let r=`</${t}`,i=n;for(;i<e.length;){let t=e.indexOf(r,i);if(t===-1)return null;let n=t+r.length,a=n<e.length?e.charCodeAt(n):-1;if(a===62||a===47||a===-1||B8(a)){let r=e.indexOf(`>`,n);return{textEnd:t,end:r===-1?e.length:r+1}}i=t+1}return null}function zht(e){let t=``,n=new Map,r,i=-1;try{let a=Fht(e),o=a.length,s=0;for(;s<o;){let c=a.indexOf(`<`,s);if(c===-1)break;let l=c+1<o?a.charCodeAt(c+1):-1;if(l===33){if(a.startsWith(`<!--`,c)){let e=a.indexOf(`-->`,c+2);if(e===-1)break;s=e+3}else{let e=a.indexOf(`>`,c+2);if(e===-1)break;s=e+1}continue}if(l===63){let e=a.indexOf(`>`,c+2);if(e===-1)break;s=e+1;continue}if(l===47){let{name:e,end:t}=Lht(a,c+2);if(e===`head`){if(t<o){let e=a.indexOf(`>`,t);e!==-1&&(i=e+1)}break}let n=a.indexOf(`>`,t);if(n===-1)break;s=n+1;continue}if(!(l>=97&&l<=122)){s=c+1;continue}let{name:u,end:d}=Lht(a,c+1);if(u===`body`){if(d<o){let e=a.charCodeAt(d);(e===62||e===47||B8(e))&&(i=d+1)}break}if(u===`title`){let n=V8(e,a,d,null),r=Rht(a,`title`,n);if(r===null){t+=e.slice(n);break}t+=e.slice(n,r.textEnd),s=r.end;continue}if(Iht.has(u)){let t=Rht(a,u,V8(e,a,d,null));if(t===null)break;s=t.end;continue}if(u===`meta`){let t=new Map;s=V8(e,a,d,t);let r=t.get(`content`);if(r){let e=t.get(`property`),i=t.get(`name`);e?n.set(e.toLowerCase(),r):i&&n.set(i.toLowerCase(),r)}continue}if(u===`link`){let t=new Map;if(s=V8(e,a,d,t),r===void 0){let e=t.get(`href`),n=t.get(`rel`);e&&n&&Pht(n).includes(`icon`)&&(r=e)}continue}s=V8(e,a,d,null)}}catch{}return{rawTitle:t,metaContent:n,faviconHref:r,headEndOffset:i}}function Bht(e){let{rawTitle:t,metaContent:n,faviconHref:r}=zht(e),i=z8(n.get(`og:title`)??t,200),a=z8(n.get(`og:description`)??n.get(`description`)??``,500),o=z8(n.get(`og:site_name`)??``,100),s={};return i&&(s.title=i),a&&(s.description=a),o&&(s.siteName=o),r&&(s.faviconHref=r),s}function Vht(e){return zht(e).headEndOffset}function Hht(e){let t;try{t=new URL(e).hostname}catch{return e}return t.startsWith(`www.`)&&t.slice(4).includes(`.`)&&(t=t.slice(4)),t}function Uht(e){let t=e.length>=2&&e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e;try{if(NI.default.IPv4.isValid(t))return NI.default.IPv4.parse(t);if(NI.default.IPv6.isValid(t))return NI.default.IPv6.parse(t)}catch{return null}return null}function Wht(e){let t=Uht(e);return t!==null&&t.range()===`unicast`}function Ght(e){let t=Uht(e);return t===null?{kind:`hostname`}:{kind:`ip-literal`,allowed:t.range()===`unicast`,canonical:t.toString(),family:t.kind()===`ipv6`?6:4}}const Kht=q(`link-preview.guarded-fetch`),qht=async e=>(await Bae(e,{all:!0,family:0})).map(e=>({address:e.address,family:e.family===6?6:4}));function Jht(e,t){let n=e.port?`:${e.port}`:``;return`${e.protocol}//${t}${n}${e.pathname}${e.search}`}async function Yht(e,t,n){let r;try{r=new URL(e)}catch{return{ok:!1,reason:`fetch-error`}}if(r.protocol!==`http:`&&r.protocol!==`https:`)return{ok:!1,reason:`bad-scheme`};let i=Ght(r.hostname);if(i.kind===`ip-literal`){if(!i.allowed)return{ok:!1,reason:`private-ip`};let e=i.family===6?`[${i.canonical}]`:i.canonical;return{ok:!0,target:{requestUrl:Jht(r,e),pinnedAddress:void 0,serverName:void 0,logicalUrl:r.toString()}}}let a;try{a=await t(r.hostname)}catch{return{ok:!1,reason:`dns-failure`}}if(a.length===0)return{ok:!1,reason:`dns-failure`};for(let e of a)if(!n(e.address))return{ok:!1,reason:`private-ip`};let o=a[0];return{ok:!0,target:{requestUrl:Jht(r,r.hostname),pinnedAddress:{address:o.address,family:o.family===6||o.address.includes(`:`)?6:4},serverName:r.hostname,logicalUrl:r.toString()}}}function Xht(e){return(t,n,r)=>{n.all?r(null,[{address:e.address,family:e.family}]):r(null,e.address,e.family)}}function Zht(e){return e===301||e===302||e===303||e===307||e===308}function Qht(e){return e?(e.split(`;`,1)[0]??``).trim().toLowerCase():``}function H8(e,t){return t.aborted||e instanceof Error&&(e.name===`TimeoutError`||e.name===`AbortError`)?`timeout`:`fetch-error`}function U8(e){try{e.destroy()}catch{}}function $ht(e,t){return new Promise(n=>{let r=!1,i=e=>{r||(r=!0,n(e))},a=e.requestUrl.startsWith(`https:`),o={method:`GET`,agent:!1,signal:t,headers:{"User-Agent":`OpenKnowledge-LinkPreview/1.x`,Accept:`text/html`,"Accept-Encoding":`identity`}};e.pinnedAddress&&(o.lookup=Xht(e.pinnedAddress)),a&&e.serverName&&(o.servername=e.serverName);try{let n=(a?Vae:Rae)(e.requestUrl,o,e=>{e.on(`error`,()=>{}),i({ok:!0,response:e})});n.on(`error`,e=>i({ok:!1,reason:H8(e,t)})),n.end()}catch(e){i({ok:!1,reason:H8(e,t)})}})}function egt(e){return e===``||e===`identity`?`identity`:e===`gzip`||e===`x-gzip`?Uae():e===`deflate`?Wae():e===`br`?Hae():null}function tgt(){let e=``;return t=>{let n=e.length;e+=Buffer.from(t).toString(`latin1`);let r=Vht(e);return r===-1?-1:r-n}}function ngt(e,t,n,r){let i=egt((e.headers[`content-encoding`]??``).trim().toLowerCase());if(i===null)return U8(e),Promise.resolve({ok:!1,reason:`fetch-error`});let a=i===`identity`?e:e.pipe(i);return new Promise(i=>{let o=[],s=r?tgt():null,c=0,l=!1,u=()=>{n.removeEventListener(`abort`,f),U8(e),a!==e&&a.destroy()},d=e=>{l||(l=!0,u(),i(e))},f=()=>d({ok:!1,reason:`timeout`});n.addEventListener(`abort`,f,{once:!0}),a!==e&&e.on(`error`,e=>d({ok:!1,reason:H8(e,n)})),a.on(`data`,e=>{if(s){let n=s(e);if(n!==-1){if(c+n>t){d({ok:!1,reason:`oversized`});return}o.push(e.subarray(0,n)),d({ok:!0,body:new Uint8Array(Buffer.concat(o))});return}}if(c+=e.byteLength,c>t){d({ok:!1,reason:`oversized`});return}o.push(e)}),a.on(`end`,()=>d({ok:!0,body:new Uint8Array(Buffer.concat(o))})),a.on(`error`,e=>d({ok:!1,reason:H8(e,n)}))})}function W8(e){return Kht.debug({reason:e},`link-preview guarded fetch rejected`),{ok:!1,reason:e}}async function rgt(e,t={}){let n=t.allowContentType??(e=>e===`text/html`),r=t.maxBytes??524288,i=t.timeoutMs??5e3,a=t.maxRedirects??3,o=t.resolve??qht,s=t.isAddressAllowed??Wht,c=AbortSignal.timeout(i),l=e,u=0;for(;;){let e=await Yht(l,o,s);if(!e.ok)return W8(e.reason);let{target:t}=e,i=await $ht(t,c);if(!i.ok)return W8(i.reason);let d=i.response;if(Zht(d.statusCode??0)){let e=d.headers.location;if(U8(d),e===void 0)return W8(`fetch-error`);if(u>=a)return W8(`redirect-limit`);u+=1;try{l=new URL(e,t.logicalUrl).toString()}catch{return W8(`fetch-error`)}continue}let f=Qht(d.headers[`content-type`]);if(!n(f))return U8(d),W8(`non-html`);let p=await ngt(d,r,c,f===`text/html`);return p.ok?{ok:!0,body:p.body,contentType:f,finalUrl:t.logicalUrl}:W8(p.reason)}}function igt(e){let t=e;return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?`image/png`:t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?`image/jpeg`:t.length>=6&&t[0]===71&&t[1]===73&&t[2]===70&&t[3]===56&&(t[4]===55||t[4]===57)&&t[5]===97?`image/gif`:t.length>=2&&t[0]===66&&t[1]===77?`image/bmp`:t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?`image/webp`:t.length>=4&&t[0]===0&&t[1]===0&&t[2]===1&&t[3]===0?`image/x-icon`:null}function agt(e){return e.startsWith(`image/`)}function ogt(e,t){try{return new URL(e??`/favicon.ico`,t).toString()}catch{return null}}async function sgt(e,t){let n=await t(e,{allowContentType:agt,maxBytes:102400,timeoutMs:2500});if(!n.ok)return;let r=igt(n.body);if(r)return`data:${r};base64,${Buffer.from(n.body).toString(`base64`)}`}async function cgt(e){let t=Bht(e.html),n=ogt(t.faviconHref,e.finalUrl),r=n?await sgt(n,e.fetch??rgt):void 0;return{domain:Hht(e.requestUrl),...t.title===void 0?{}:{title:t.title},...t.description===void 0?{}:{description:t.description},...t.siteName===void 0?{}:{siteName:t.siteName},...r===void 0?{}:{faviconDataUri:r}}}const G8=q(`link-preview.cache`);function lgt(e){try{let t=new URL(e);return t.hash=``,t.username=``,t.password=``,t.toString()}catch{return null}}function K8(e){return Tc(`sha256`).update(e,`utf-8`).digest(`hex`)}var ugt=class{cacheDir;metaDir;manifestPath;maxEntries;successTtlMs;negativeTtlMs;now;entries=new Map;payloads=new Map;persistedKeys=new Set;inFlight=new Map;dirty=!1;persisting=!1;persistPending=!1;constructor(e){this.cacheDir=e.cacheDir,this.metaDir=e.cacheDir?H(e.cacheDir,`meta`):null,this.manifestPath=e.cacheDir?H(e.cacheDir,`manifest.json`):null,this.maxEntries=e.maxEntries??256,this.successTtlMs=e.successTtlMs??6048e5,this.negativeTtlMs=e.negativeTtlMs??36e5,this.now=e.now??Date.now}async init(){if(!this.cacheDir||!this.manifestPath||!this.metaDir)return;let e=null;try{G(this.manifestPath)&&(e=JSON.parse(await vc(this.manifestPath,`utf-8`)))}catch(e){G8.warn({err:e},`[link-preview] unreadable cache manifest — starting empty`);return}if(!e||e.schemaVersion!==1||!e.entries)return;let t=this.now();for(let[n,r]of Object.entries(e.entries))if(!(!r||r.status!==`ok`&&r.status!==`negative`)&&!(typeof r.expiresAt!=`number`||t>=r.expiresAt)){if(r.status===`ok`){let e=await this.readBlob(n);if(!e)continue;this.payloads.set(n,e),this.persistedKeys.add(n)}this.entries.set(n,r)}}async load(e,t){let n=lgt(e);if(n===null)return t();let r=this.getFresh(n);if(r)return r;let i=this.inFlight.get(n);if(i)return i;let a=(async()=>{let e=await t();return this.record(n,e),e})().finally(()=>{this.inFlight.delete(n)});return this.inFlight.set(n,a),a}getFresh(e){let t=this.entries.get(e);if(!t)return;if(this.now()>=t.expiresAt){this.drop(e),this.dirty=!0;return}if(this.entries.delete(e),this.entries.set(e,t),t.status===`negative`)return{ok:!1,reason:t.reason??`error`};let n=this.payloads.get(e);if(!n){this.drop(e),this.dirty=!0;return}return{ok:!0,metadata:n}}record(e,t){let n=this.now();this.persistedKeys.delete(e),this.entries.delete(e),this.payloads.delete(e),t.ok?(this.entries.set(e,{status:`ok`,fetchedAt:n,expiresAt:n+this.successTtlMs}),this.payloads.set(e,t.metadata)):this.entries.set(e,{status:`negative`,fetchedAt:n,expiresAt:n+this.negativeTtlMs,reason:t.reason}),this.dirty=!0,this.evict()}evict(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.drop(e),this.dirty=!0}}drop(e){this.entries.delete(e),this.payloads.delete(e),this.persistedKeys.delete(e)}async persist(){if(this.cacheDir){if(this.persisting){this.persistPending=!0;return}this.persisting=!0;try{do this.persistPending=!1,await this.writeToDisk();while(this.persistPending&&this.dirty)}finally{this.persisting=!1}}}async writeToDisk(){if(!(!this.cacheDir||!this.manifestPath||!this.metaDir)&&this.dirty)try{await EG(this.metaDir,{recursive:!0});let e=new Set;for(let[t,n]of this.entries){if(n.status!==`ok`||(e.add(K8(t)),this.persistedKeys.has(t)))continue;let r=this.payloads.get(t);r&&(await SG(H(this.metaDir,`${K8(t)}.json`),JSON.stringify(r)),this.persistedKeys.add(t))}let t={schemaVersion:1,entries:Object.fromEntries(this.entries)},n=`${this.manifestPath}.tmp`;await SG(n,JSON.stringify(t)),await TG(n,this.manifestPath);for(let t of tc(this.metaDir)){if(!t.endsWith(`.json`))continue;let n=t.slice(0,-5);e.has(n)||MG(H(this.metaDir,t))}this.dirty=!1}catch(e){G8.warn({err:e},`[link-preview] failed to persist cache`)}}clearMemory(){this.entries.clear(),this.payloads.clear(),this.persistedKeys.clear(),this.inFlight.clear(),this.dirty=!1}async wipe(){if(this.clearMemory(),this.cacheDir)try{FG(this.cacheDir,{recursive:!0,force:!0})}catch(e){G8.warn({err:e},`[link-preview] failed to wipe cache`)}}get size(){return this.entries.size}async readBlob(e){if(!this.metaDir)return null;let t=H(this.metaDir,`${K8(e)}.json`);try{if(!G(t))return null;let e=Oie.safeParse(JSON.parse(await vc(t,`utf-8`)));return e.success?e.data:null}catch(e){return G8.warn({err:e},`[link-preview] unreadable cache blob — treating as miss`),null}}};function dgt(e){if(!e||e===`null`)return!1;let t;try{t=new URL(e)}catch{return!1}if(t.protocol!==`http:`&&t.protocol!==`https:`)return!1;let n=t.hostname;return n===`localhost`||n===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)}function fgt(e){return dgt(e.origin)?g9e(e.contentType)?{ok:!0}:{ok:!1,reason:`content-type`}:{ok:!1,reason:`origin`}}let pgt=null,mgt=null,hgt=null,ggt=null,_gt=null,vgt=null;function ygt(){return pgt||=aG().createCounter(`ok.saved_themes.save_total`,{description:`Successful saved-theme file saves. Attribute-free to keep cardinality bounded.`}),pgt}function bgt(){return mgt||=aG().createCounter(`ok.saved_themes.delete_total`,{description:`Successful saved-theme file deletions. Attribute-free to keep cardinality bounded.`}),mgt}function xgt(){return _gt||=aG().createCounter(`ok.saved_themes.parse_failure_total`,{description:`Saved-theme scheme parse failures. Attribute-free to keep cardinality bounded.`}),_gt}function Sgt(){return hgt||=aG().createCounter(`ok.saved_themes.scan_total`,{description:`Saved-theme store scans. Attribute-free to keep cardinality bounded.`}),hgt}function Cgt(){return ggt||=aG().createCounter(`ok.saved_themes.parse_total`,{description:`Saved-theme scheme parse attempts. Attribute-free to keep cardinality bounded.`}),ggt}function wgt(){return vgt||=aG().createHistogram(`ok.saved_themes.usable_count`,{description:`Usable saved themes returned by a completed bounded scan. Attribute-free to keep cardinality bounded.`}),vgt}function Tgt(){ygt().add(1)}function Egt(){bgt().add(1)}function Dgt(){Sgt().add(1)}function Ogt(){Cgt().add(1)}function kgt(){xgt().add(1)}function Agt(e){wgt().record(e)}const q8=q(`saved-themes`),J8=[`.yaml`,`.yml`];function Y8(e){return W(KS(e??dc()),Kt)}function jgt(e={}){Dgt();let t=e.root??Y8(e.homedirOverride),n=e.cap??500,r=[],i=!1;try{let n=$s(t);try{let t=e.observationCap??2e3;for(;r.length<t;){let e=n.readSync();if(e===null)break;r.push(e)}i=n.readSync()!==null}finally{try{n.closeSync()}catch{}}}catch(e){return iq(e)===`ENOENT`?Agt(0):q8.warn({root:t,reason:e instanceof Error?e.message:String(e)},`failed to read saved-theme store at ${t} — treating as empty`),{entries:[],truncated:!1}}let a=r.filter(Mgt).map(e=>e.name).sort(),o=new Map;for(let e of a){let t=Ngt(e),n=o.get(t)??[];n.push(e),o.set(t,n)}let s=[...o.entries()].sort(([e],[t])=>e.localeCompare(t)),c=i||s.length>n;c&&q8.warn({root:t,cap:n,found:s.length,observationTruncated:i},`saved-theme store at ${t} exceeded a scan bound; the returned list is incomplete.`);let l=[];for(let[e,r]of s.slice(0,n)){let n=r[0];if(!n)continue;if(r.length>1){let t=er(e);l.push({ok:!1,filename:n,...t.ok?{id:t.id}:{},code:`duplicate-identity`,conflictingFilenames:r});continue}let i=Pgt(t,n);i&&l.push(i)}return Agt(l.filter(e=>e.ok).length),{entries:l,truncated:c}}function Mgt(e){if(e.name.startsWith(`.`))return!1;let t=e.name.toLowerCase();return J8.some(e=>t.endsWith(e))}function Ngt(e){let t=e.toLowerCase(),n=J8.find(e=>t.endsWith(e));return n?e.slice(0,-n.length):Is(e).name}function Pgt(e,t){let n=er(Is(t).name);if(!n.ok)return{ok:!1,filename:t,code:n.code};if(!J8.some(e=>t.endsWith(e)))return{ok:!1,filename:t,id:n.id,code:`unsupported-extension-case`};let r=H(e,t);try{let e=Ys(r);if(e.isSymbolicLink())return{ok:!1,filename:t,id:n.id,code:`symlink`};if(!e.isFile())return{ok:!1,filename:t,id:n.id,code:`not-regular-file`}}catch(r){return iq(r)===`ENOENT`?null:(q8.warn({root:e,filename:t,reason:r instanceof Error?r.message:String(r)},`failed to inspect saved theme ${t} — listed as unreadable`),{ok:!1,filename:t,id:n.id,code:`read-failed`})}let i;try{i=Qs(r,Ks.O_RDONLY|Ks.O_NOFOLLOW)}catch(r){let i=iq(r);return i===`ENOENT`?null:i===`ELOOP`?{ok:!1,filename:t,id:n.id,code:`symlink`}:(q8.warn({root:e,filename:t,reason:r instanceof Error?r.message:String(r)},`failed to open saved theme ${t} — listed as unreadable`),{ok:!1,filename:t,id:n.id,code:`read-failed`})}let a;try{let e=oae(i);if(!e.isFile())return{ok:!1,filename:t,id:n.id,code:`not-regular-file`};if(e.size>65536)return{ok:!1,filename:t,id:n.id,code:`file-too-large`};let r=Buffer.alloc(65537),o=0;for(;o<r.length;){let e=ec(i,r,o,r.length-o,null);if(e===0)break;o+=e}if(o>65536)return{ok:!1,filename:t,id:n.id,code:`file-too-large`};a=r.subarray(0,o).toString(`utf-8`)}catch(r){return q8.warn({root:e,filename:t,reason:r instanceof Error?r.message:String(r)},`failed to read saved theme ${t} — listed as unreadable`),{ok:!1,filename:t,id:n.id,code:`read-failed`}}finally{try{Gs(i)}catch{}}Ogt();let o=nee(a);return o.ok?{ok:!0,id:n.id,filename:t,scheme:o.scheme}:(kgt(),{ok:!1,filename:t,id:n.id,code:o.error.kind})}async function X8(e,t,n,r){let i=W(KS(t));await EG(i,{recursive:!0});let a=Tc(`sha256`).update(W(e)).digest(`hex`).slice(0,24);try{return await ZS(H(i,`saved-themes-${a}.lock`),n,{timeoutMs:r})}catch(e){if(e instanceof XS)return{ok:!1,code:`lock-timeout`};throw e}}function Fgt(e){try{return Ys(e).isFile()?`regular`:`unsafe`}catch(e){if(e.code===`ENOENT`)return`missing`;throw e}}function Z8(e,t){let n=[],r;try{r=$s(e)}catch(e){if(e.code===`ENOENT`)return{complete:!0,filenames:n};throw e}try{for(let e=0;e<2e3;e+=1){let e=r.readSync();if(e===null)return{complete:!0,filenames:n.sort()};let i=e.name.toLowerCase(),a=J8.find(e=>i.endsWith(e));a&&e.name.slice(0,-a.length)===t&&n.push(e.name)}return{complete:r.readSync()===null,filenames:n.sort()}}finally{try{r.closeSync()}catch{}}}async function Igt(e){let t=e.stem===void 0?Ge(e.name):(()=>{let t=er(e.stem);return t.ok?{...t,stem:e.stem}:t})();if(!t.ok)return{ok:!1,code:t.code};let n=e.homedirOverride??dc(),r=e.root??Y8(n);return X8(r,n,async()=>{let n=Z8(r,t.stem);if(!n.complete||n.filenames.length>0)return{ok:!1,code:`name-taken`};let i=`${t.stem}${e.extension??`.yaml`}`;return Fgt(H(r,i))===`missing`?(await EG(r,{recursive:!0}),await YS(H(r,i),sn(e.scheme),{fs:LG,sweepStaleTmps:!1}),Tgt(),{ok:!0,id:t.id,filename:i}):{ok:!1,code:`name-taken`}},e.lockTimeoutMs)}async function Lgt(e){let t=Tt(e.id);if(!t.ok)return{ok:!1,code:`invalid-id`};let n=e.homedirOverride??dc(),r=e.root??Y8(n);return X8(r,n,async()=>{let n=Z8(r,t.stem);if(!n.complete)return{ok:!1,code:`ambiguous-id`};let{filenames:i}=n;if(i.length===0)return{ok:!1,code:`not-found`};if(i.length>1)return{ok:!1,code:`ambiguous-id`};let a=i[0];return a?!J8.some(e=>a.endsWith(e))||Fgt(H(r,a))!==`regular`?{ok:!1,code:`unsafe-target`}:(await YS(H(r,a),sn(e.scheme),{fs:LG,sweepStaleTmps:!1}),{ok:!0,id:e.id,filename:a}):{ok:!1,code:`not-found`}},e.lockTimeoutMs)}async function Rgt(e){let t=Tt(e.id);if(!t.ok)return{ok:!1,code:`invalid-id`};let n=e.homedirOverride??dc(),r=e.root??Y8(n);return X8(r,n,async()=>{let e=Z8(r,t.stem);if(!e.complete)return{ok:!1,code:`ambiguous-id`};let{filenames:n}=e;if(n.length===0)return{ok:!0,existed:!1};if(n.length>1)return{ok:!1,code:`ambiguous-id`};let i=n[0];if(!i)return{ok:!0,existed:!1};let a=Pgt(r,i);return a===null?{ok:!0,existed:!1}:a.ok?(MG(H(r,i)),Egt(),{ok:!0,existed:!0,filename:i,scheme:a.scheme}):{ok:!1,code:`unusable-theme`}},e.lockTimeoutMs)}const zgt=new Set([`.DS_Store`,`.localized`,`Thumbs.db`,`.gitignore`,`.gitkeep`,`.gitattributes`]);function Bgt(e){let t=[],n=[],r=[];for(let i of tc(e,{withFileTypes:!0})){if(zgt.has(i.name))continue;if(i.name.startsWith(`.`)){r.push(i.name);continue}let a=H(e,i.name);if(G(H(a,`SKILL.md`))){t.push(i.name);continue}if(i.isSymbolicLink()&&!G(a)){r.push(i.name);continue}i.isDirectory()&&Vgt(a)||n.push(i.name)}return{bundles:t,strays:n,ignored:r}}function Vgt(e){try{return tc(e).length===0}catch{return!1}}function Hgt(e){let{base:t,folderRel:n,targetRootRel:r,mayCreate:i}=e,a=H(t,n),o=H(t,r),s=[r,n].filter(e=>!G(H(t,e))&&!i(e));if(s.length>0)return{kind:`not-permitted`,roots:s};let c;try{c=Ys(a)}catch{return{kind:`absent`}}if(c.isSymbolicLink()||!c.isDirectory())return{kind:`not-linkable`};try{if(nc(a)===nc(o))return{kind:`not-linkable`}}catch{}let{bundles:l,strays:u,ignored:d}=Bgt(a);if(u.length>0)return{kind:`stray-entries`,strays:u};let f=[],p=[],m=[],h=[],g=[],_=[];for(let e of l){let t=H(a,e),n=H(o,e);if(Ys(t).isSymbolicLink()){let r=nc(t),i=null,a=!1;try{a=Ys(n).isSymbolicLink(),i=nc(n)}catch{}i===r?m.push(e):i===null?(a&&h.push(e),_.push({name:e,target:r})):f.push(e);continue}let r=!1;try{r=Ys(n).isSymbolicLink()}catch{}if(r){h.push(e),G(n)&&g.push(e),p.push(e);continue}if(!G(n)){p.push(e);continue}let i=iP(t)?.contentHash,s=iP(n)?.contentHash;i!==void 0&&i===s?m.push(e):f.push(e)}return f.length>0?{kind:`conflicts`,conflicts:f}:{kind:`plan`,plan:{toMove:p,toDrop:m,destLinks:h,liveDestLinks:g,linkedBundlesToMove:_,removes:d}}}function Ugt(e){let{base:t,folderRel:n,targetRootRel:r,mayCreate:i}=e,a=H(t,n),o=H(t,r),s=Hgt({base:t,folderRel:n,targetRootRel:r,mayCreate:i});if(s.kind===`not-permitted`)return{ok:!1,reason:`not-permitted`,roots:s.roots};if(s.kind===`absent`)return kG(V(a),{recursive:!0}),kG(o,{recursive:!0}),PG(U(V(a),o),a,`dir`),{ok:!0,moved:[],dropped:[],linked:[n]};if(s.kind===`not-linkable`)return{ok:!1,reason:`not-linkable`};if(s.kind===`stray-entries`)return{ok:!1,reason:`stray-entries`,strays:s.strays};if(s.kind===`conflicts`)return{ok:!1,reason:`conflicts`,conflicts:s.conflicts};let{toMove:c,toDrop:l,destLinks:u,linkedBundlesToMove:d}=s.plan,f=[];try{kG(o,{recursive:!0});let e=nc(o);for(let e of u)FG(H(o,e),{force:!0});for(let{name:t,target:n}of d){let r=H(o,t);PG(U(e,n),r,`dir`),FG(H(a,t),{force:!0}),f.push(t)}for(let e of c)AG(H(a,e),H(o,e)),f.push(e);for(let e of l)FG(H(a,e),{recursive:!0,force:!0});FG(a,{recursive:!0,force:!0}),PG(U(V(a),o),a,`dir`)}catch(e){return{ok:!1,reason:`partial-move`,moved:f,error:e instanceof Error?e.message:String(e)}}return{ok:!0,moved:[...d.map(({name:e})=>e),...c],dropped:l,linked:[n]}}function Wgt(e){let{base:t,folderRel:n}=e,r=new Set(e.exclude??[]),i=H(t,n),a;try{a=Ys(i)}catch{return{ok:!1,reason:`not-linked`}}if(!a.isSymbolicLink())return{ok:!1,reason:`not-linked`};let o;try{o=nc(i)}catch{return FG(i,{force:!0}),kG(i,{recursive:!0}),{ok:!0,moved:[],dropped:[],linked:[]}}let{bundles:s}=Bgt(o);FG(i,{force:!0}),kG(i,{recursive:!0});let c=nc(i),l=[];for(let e of s)r.has(e)||(PG(U(c,H(o,e)),H(i,e),`dir`),l.push(e));return{ok:!0,moved:[],dropped:[],linked:l}}const Ggt=I({enabled:je(),active:je(),git:I({state:Or([`not-applicable`,`ready`,`missing`,`conflict`,`unavailable`]),ownership:Or([`open-knowledge`,`existing`]).optional()}),applied:je().optional(),reason:Or([`git-conflict`,`git-unavailable`,`config-write`]).optional()}),Kgt=I({enabled:je()}).strict();function qgt(e){return(t,n)=>{let r=fgt({origin:t.headers.origin,contentType:t.headers[`content-type`]});return r.ok?!0:(r.reason===`origin`?X(n,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:e}):R$(n,e),!1)}}function Jgt(e){let{contentDir:t,projectDir:n,skillsHome:r,homeDirOverride:i,savedThemeLockTimeoutMs:a,ephemeral:o,log:s,signalChannel:c,searchService:l,linkPreviewFetch:u,getLinkPreviewsEnabled:d,declaredGitHubHosts:f,resolveGitHubToken:p,githubReferenceFetch:m,getGeneratedIndexSettingsStatus:h,setGeneratedIndexEnabled:g}=e,_=Z($a,async(e,t)=>{try{let{entries:e,truncated:n}=jgt({homedirOverride:i});Q(t,200,une,{themes:e,truncated:n},{handler:`saved-themes-list`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to list saved themes.`,{handler:`saved-themes-list`,cause:e})}},{handler:`saved-themes-list`,method:`GET`,skipBodyParse:!0}),v=Z(we,async(e,t,n)=>{try{let e=await Igt({name:n.name,stem:n.stem,scheme:n.scheme,extension:n.extension,homedirOverride:i,lockTimeoutMs:a});if(!e.ok){if(e.code===`lock-timeout`){X(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-save`,detail:e.code,extraHeaders:{"Retry-After":`5`}});return}if(e.code===`name-taken`){X(t,409,`urn:ok:error:theme-name-taken`,`A saved theme with that name already exists.`,{handler:`saved-theme-save`,detail:n.name});return}X(t,400,`urn:ok:error:theme-name-invalid`,`That name cannot be used as a theme id.`,{handler:`saved-theme-save`,detail:e.code});return}Q(t,201,qn,{id:e.id,filename:e.filename},{handler:`saved-theme-save`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to save theme.`,{handler:`saved-theme-save`,cause:e})}},{handler:`saved-theme-save`,method:`POST`}),y=Z($a,async(e,t)=>{try{let n=rq(e).get(`id`)??``;if(n===``){X(t,400,`urn:ok:error:invalid-request`,`Missing theme id.`,{handler:`saved-theme-delete`});return}let r=await Rgt({id:n,homedirOverride:i,lockTimeoutMs:a});if(!r.ok){if(r.code===`lock-timeout`){X(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-delete`,detail:r.code,extraHeaders:{"Retry-After":`5`}});return}X(t,r.code===`invalid-id`?400:409,`urn:ok:error:invalid-request`,`Cannot delete saved theme.`,{handler:`saved-theme-delete`,detail:r.code});return}Q(t,200,Le,r.existed?{existed:!0,filename:r.filename,scheme:r.scheme}:{existed:!1},{handler:`saved-theme-delete`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to delete theme.`,{handler:`saved-theme-delete`,cause:e})}},{handler:`saved-theme-delete`,method:`DELETE`,skipBodyParse:!0}),b=r2({POST:v,PUT:Z(bne,async(e,t,n)=>{try{let e=await Lgt({id:n.id,scheme:n.scheme,homedirOverride:i,lockTimeoutMs:a});if(!e.ok){if(e.code===`lock-timeout`){X(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-update`,detail:e.code,extraHeaders:{"Retry-After":`5`}});return}if(e.code===`not-found`){X(t,404,`urn:ok:error:not-found`,`Saved theme not found.`,{handler:`saved-theme-update`});return}if(e.code===`ambiguous-id`||e.code===`unsafe-target`){X(t,409,`urn:ok:error:invalid-request`,e.code===`ambiguous-id`?`Multiple saved theme files claim that id.`:`The saved theme id conflicts with a file that cannot be safely updated.`,{handler:`saved-theme-update`,detail:e.code});return}X(t,400,`urn:ok:error:invalid-request`,`Not a saved theme id.`,{handler:`saved-theme-update`,detail:e.code});return}Q(t,200,T,{id:e.id,filename:e.filename},{handler:`saved-theme-update`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to update theme.`,{handler:`saved-theme-update`,cause:e})}},{handler:`saved-theme-update`,method:`PUT`}),DELETE:y},{handler:`saved-theme`}),x=r2({GET:Z($a,async(e,i)=>{try{let e=z0(n??``),a=(e,t)=>{let n=Rnt(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};Q(i,200,Lte,{targets:e,configured:!1,folders:[...n?jI(t,d0(t,`project`)).filter(e=>p0(t,`project`,e.root,r)).map(e=>({...MI(e),scope:`project`,...a(t,e)})):[],...jI(r,d0(r,`global`)).filter(e=>p0(r,`global`,e.root,r)).map(e=>({...MI(e),scope:`global`,...a(r,e)}))]},{handler:`skill-targets-get`})}catch(e){X(i,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:Z(Kee,async(e,i,a)=>{try{{let e=a.folderAction,o=e.scope===`project`?t:r;if(e.scope===`project`&&!n){X(i,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let t=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),r=t.split(`/`).filter(e=>e!==``&&e!==`.`);if(t===``||t.startsWith(`/`)||t.startsWith(`~`)||/^[A-Za-z]:/.test(t)||t.includes(`\0`)||r.length===0||r.some(e=>e===`..`)){X(i,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await znt(o,r.join(`/`)),c?.(`files`),Q(i,200,Ja,{targets:z0(n??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let s=new Set(d0(o,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),l=e.action===`link`?e.target??``:e.root;if(!s.has(e.root)||e.action===`link`&&(!s.has(l)||e.root===l)){X(i,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${l}`});return}let u=e=>{X(i,400,`urn:ok:error:invalid-request`,`That link would create a folder OpenKnowledge may not create on this machine: ${e.join(`, `)}.`,{handler:`skill-targets-put`,detail:e.join(`, `)})},d=t=>p0(o,e.scope,t,r)&&!(t===`.agents/skills`&&!G(H(o,t)));if(e.action===`link`&&e.preview){let t=Hgt({base:o,folderRel:e.root,targetRootRel:l,mayCreate:d});if(t.kind===`not-permitted`){u(t.roots);return}let r=t.kind===`plan`?t.plan:null;Q(i,200,Ja,{targets:z0(n??``),reprojected:[],bundleHosts:[],removedFrom:[],preview:{moves:r?[...r.linkedBundlesToMove.map(({name:e})=>e),...r.toMove]:[],drops:r?.toDrop??[],removes:r?.removes??[],replaces:r?.liveDestLinks??[],conflicts:t.kind===`conflicts`?t.conflicts:[],strays:t.kind===`stray-entries`?t.strays:[]}},{handler:`skill-targets-put`});return}let f=e.action===`link`?Ugt({base:o,folderRel:e.root,targetRootRel:l,mayCreate:d}):Wgt({base:o,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!f.ok&&f.reason===`not-permitted`){u(f.roots);return}if(!f.ok){X(i,409,`urn:ok:error:invalid-request`,f.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${f.conflicts.join(`, `)}. Resolve them first.`:f.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${f.strays.join(`, `)}.`:f.reason===`partial-move`?`The merge stopped partway (${f.moved.length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${f.error??``})`:f.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:f.reason});return}await Lnt(o,e.root,e.action===`link`?{expect:`link`,target:l}:{expect:`own`}),c?.(`files`),Q(i,200,Ja,{targets:z0(n??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:f.moved,dropped:f.dropped,linked:f.linked}},{handler:`skill-targets-put`});return}}catch(e){X(i,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`});function S(e){return e===`navigation`||e===`relevance`?e:void 0}function C(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function w(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let n=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return n.length>0?n:void 0}function E(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function D(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let O=r2({GET:Z($a,F$(async(e,t)=>{let n=rq(e),r=n.get(`limit`),i=n.get(`query`)??``,a=C(n.get(`intent`)),o=S(n.get(`ranking`)),s=w(n.get(`scope`)??n.get(`scopes`)),c=E(n.get(`semantic`)),u=D(n.get(`source`)),d=r===null?void 0:Number(r);if(i.length>200){X(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}let f=await l.buildSearchResponse({query:i,intent:a,ranking:o,scopes:s,limit:d,semanticParam:c,source:u});Q(t,200,rr,f,{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:Z(Cn,F$(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=C(n.intent),a=S(n.ranking),o=w(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=E(n.semantic),u=D(n.source);if(r.length>200){X(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}let d=await l.buildSearchResponse({query:r,intent:i,ranking:a,scopes:o,limit:s,semanticParam:c,source:u});Q(t,200,rr,d,{handler:`search-post`})},{handler:`search-post`,title:`Failed to search workspace.`}),{handler:`search-post`,method:`POST`})},{handler:`search`}),k=`link-preview`,ee=new ugt({cacheDir:o?null:W(n??t,`.ok`,`local`,`link-previews`)}),A=null,j=()=>(A??=ee.init(),A),M=u??rgt;async function N(e){let t=await M(e);return t.ok?{ok:!0,metadata:await cgt({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:M})}:{ok:!1,reason:t.reason}}let ne=()=>{try{return d?.()===!0}catch{return!1}},P=Z(te,async(e,t,n)=>{try{if(!ne()){s.debug({outcome:`disabled`},`[link-preview] request outcome`),Q(t,200,ni,{ok:!1,reason:`disabled`},{handler:k});return}await j();let e=!1,r=await ee.load(n.url,()=>(e=!0,N(n.url)));ee.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};s.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),Q(t,200,ni,i,{handler:k})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:k,cause:e})}},{handler:k,method:`POST`,preBodyGate:qgt(k)}),re=`github-reference`,ie=new yht,ae=new sht;return N$({"/api/search":O,"/api/link-preview":P,"/api/github-reference":Z(lne,async(e,t,n)=>{try{let r=ne()?xht(n.url,f):null;if(r===null){let e=ne()?`unsupported`:`disabled`;s.debug({outcome:e},`[github-reference] request outcome`),Q(t,200,xn,{ok:!1,reason:e},{handler:re});return}let i=Tht(e),a=`${i?`signed-in`:`anonymous`} ${Sht(r)}`,o=await ie.load(a,async()=>_ht({target:r,token:i?await p?.(r.host)??null:null,fetchFn:m,rateLimits:ae}));s.debug({outcome:o.ok?`ok`:o.reason},`[github-reference] request outcome`),Q(t,200,xn,o,{handler:re})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:re,cause:e})}},{handler:re,method:`POST`,preBodyGate:qgt(re)}),"/api/skill-targets":x,"/api/saved-themes":_,"/api/saved-theme":b,"/api/generated-index/settings":r2({GET:Z($a,async(e,t)=>{if(!h){X(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-get`});return}Q(t,200,Ggt,h(),{handler:`generated-index-settings-get`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-get`,method:`GET`,skipBodyParse:!0}),POST:Z(Kgt,async(e,t,n)=>{if(!g){X(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-set`});return}let r=await g(n.enabled);Q(t,200,Ggt,r,{handler:`generated-index-settings-set`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-set`,method:`POST`})},{handler:`generated-index-settings`})},{mutating:[`/api/skill-targets`,`/api/saved-theme`,`/api/generated-index/settings`]})}const Q8=q(`managed-rename`);function Ygt(e){return FJ(e)}function $8(e){return W(Ygt(e),`managed-rename.json`)}function Xgt(e){let t={version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:e.affectedDocs,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots};return e.pathSnapshots&&e.pathSnapshots.length>0&&(t.pathSnapshots=e.pathSnapshots),e.cleanupPaths&&e.cleanupPaths.length>0&&(t.cleanupPaths=e.cleanupPaths),t}function Zgt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function Qgt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.path==`string`&&typeof t.content==`string`}function $gt(e){return typeof e==`string`&&e.length>0}function e_t(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.from==`string`&&typeof t.to==`string`}function t_t(e){if(typeof e.fromPath!=`string`||e.fromPath.length===0)throw Error(`Managed rename journal v2 is missing fromPath`);if(typeof e.toPath!=`string`||e.toPath.length===0)throw Error(`Managed rename journal v2 is missing toPath`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v2 is missing createdAt`);let t=e.affectedDocs,n=e.pathSnapshots,r=e.cleanupPaths,i=Array.isArray(n)&&n.length>0,a=Array.isArray(r)&&r.length>0;if(!Array.isArray(t)||!t.every(e_t)||t.length===0&&!i&&!a)throw Error(`Managed rename journal v2 has invalid affectedDocs`);if(!Array.isArray(e.snapshots)||t.length>0&&e.snapshots.length===0||!e.snapshots.every(Zgt))throw Error(`Managed rename journal v2 has invalid snapshots`);if(n!==void 0&&(!Array.isArray(n)||!n.every(Qgt)))throw Error(`Managed rename journal v2 has invalid pathSnapshots`);if(r!==void 0&&(!Array.isArray(r)||!r.every($gt)))throw Error(`Managed rename journal v2 has invalid cleanupPaths`);for(let n of t)if(!e.snapshots.some(e=>e.docName===n.from))throw Error(`Managed rename journal v2 is missing snapshot for affected doc: ${n.from}`);return{version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:t,createdAt:e.createdAt,snapshots:e.snapshots,...i?{pathSnapshots:n}:{},...a?{cleanupPaths:r}:{}}}function n_t(e){if(typeof e.sourceDocName!=`string`||e.sourceDocName.length===0)throw Error(`Managed rename journal v1 is missing sourceDocName`);if(typeof e.destinationDocName!=`string`||e.destinationDocName.length===0)throw Error(`Managed rename journal v1 is missing destinationDocName`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v1 is missing createdAt`);if(!Array.isArray(e.snapshots)||e.snapshots.length===0||!e.snapshots.every(Zgt))throw Error(`Managed rename journal v1 has invalid snapshots`);if(!e.snapshots.some(t=>t.docName===e.sourceDocName))throw Error(`Managed rename journal v1 must include the source document snapshot`);return{version:1,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt,snapshots:e.snapshots}}function r_t(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version===2)return t_t(t);if(t.version===1)return n_t(t);throw Error(`Unsupported managed rename journal version: ${String(t.version)}`)}function i_t(e){let t=$8(e);if(!G(t))return null;try{let e=K(t,`utf-8`);return r_t(JSON.parse(e))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function a_t(e,t){let n=$8(e);kG(V(n),{recursive:!0});let r=`${n}.tmp`;DG(r,JSON.stringify(t,null,2),`utf-8`),AG(r,n)}function o_t(e){FG($8(e),{force:!0})}async function s_t(e,t,n){a_t(e,t);let r=await n();return o_t(e),r}function c_t(e){return[e.destinationDocName]}function l_t(e){return e.affectedDocs.map(e=>e.to)}function u_t(e,t){let n=W(e),r=W(n,t);if(t.includes(`\0`)||r===n||!r.startsWith(`${n}${Rs}`))throw Error(`Invalid recovery path: ${t}`);return r}function d_t(e,t){let n=W(t),r=`${n}${Rs}`,i=V(e);for(;i.startsWith(r)&&i!==n;){let e;try{e=tc(i)}catch(e){Q8.warn({path:i,err:e},`pruneEmptyAncestors: cannot read ${i}`);return}if(e.length>0)return;try{IG(i)}catch(e){Q8.warn({path:i,err:e},`pruneEmptyAncestors: cannot rmdir ${i}`);return}i=V(i)}}function f_t(e,t=e){let n=i_t(t);if(!n)return{recovered:!1,journal:null,restoredDocNames:[]};let r=new Set,i=new Set,a=[];for(let t of n.snapshots)try{let n=fq(t.docName,e);kG(V(n),{recursive:!0}),DG(n,t.content,`utf-8`),r.add(t.docName)}catch(e){a.push({docName:t.docName,cause:e}),Q8.warn({docName:t.docName,err:e},`Failed to restore ${t.docName}`)}if(a.length>0){let e=a.map(e=>e.docName).join(`, `);Q8.warn({failed:e},`Recovery incomplete; keeping journal for retry (${e})`);let t=a.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to restore: ${e}`)}if(n.version===2){let t=[];for(let r of n.pathSnapshots??[])try{let t=u_t(e,r.path);kG(V(t),{recursive:!0}),DG(t,r.content,`utf-8`),i.add(r.path)}catch(e){t.push({path:r.path,cause:e}),Q8.warn({path:r.path,err:e},`Failed to restore path ${r.path}`)}if(t.length>0){let e=t.map(e=>e.path).join(`, `);Q8.warn({failed:e},`Recovery incomplete; keeping journal for retry (${e})`);let n=t.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(n,`Managed rename recovery incomplete; failed to restore paths: ${e}`)}}let o=n.version===2?l_t(n):c_t(n),s=[];for(let t of o){if(r.has(t))continue;let n=fq(t,e);try{FG(n,{force:!0}),d_t(n,e)}catch(e){G(n)&&Q8.warn({destination:t},`Both source and destination files exist after partial recovery for ${t}`),Q8.warn({destination:t,err:e},`Recovery incomplete; failed to clean destination ${t}`),s.push({destination:t,cause:e})}}if(n.version===2)for(let t of n.cleanupPaths??[]){if(i.has(t))continue;let n=null;try{n=u_t(e,t),FG(n,{force:!0}),d_t(n,e)}catch(e){n&&G(n)&&Q8.warn({destination:t},`Both source and destination paths exist after partial recovery for ${t}`),Q8.warn({destination:t,err:e},`Recovery incomplete; failed to clean destination path ${t}`),s.push({destination:t,cause:e})}}if(s.length>0){let e=s.map(e=>e.destination).join(`, `),t=s.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to clean destinations: ${e}`)}return o_t(t),{recovered:!0,journal:n,restoredDocNames:[...r].sort((e,t)=>e.localeCompare(t))}}function e5(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function p_t(e,t){let n=Lt.has(e);return{disposition:t.has(e)||n?`inline`:`attachment`,csp:e===`svg`?`sandbox; default-src 'none'; style-src 'unsafe-inline'`:n?gre:null,sandboxedHtml:n}}Object.assign(DL,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`,toml:`application/toml`,lock:`text/plain`,"7z":`application/x-7z-compressed`,tar:`application/x-tar`,rar:`application/vnd.rar`,xls:`application/vnd.ms-excel`,ppt:`application/vnd.ms-powerpoint`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,pages:`application/vnd.apple.pages`,numbers:`application/vnd.apple.numbers`,key:`application/vnd.apple.keynote`,mobi:`application/x-mobipocket-ebook`});function m_t(e){return DL[Ns(e).slice(1).toLowerCase()]??null}function h_t(e){return m_t(e)!==null&&mt.has(Ns(e).slice(1).toLowerCase())}const g_t=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i;function __t(e,t,n){let r=t.trim();return r===``||r===`./`?W(n,V(e)):r===`/`?n:r.startsWith(`./`)?W(n,V(e),r.slice(2)):W(n,r)}function v_t(e,t){let n=Qs(e,`r`);try{let e=Buffer.alloc(t),r=ec(n,e,0,t,0);return e.subarray(0,r)}finally{Gs(n)}}const t5=1e3;async function y_t(e){let t=Tc(`sha256`);return await jc(qs(e),t),t.digest(`hex`)}async function b_t(e,t,n){let r;try{r=await yc(e)}catch{return null}let i=q(`upload`),a=0;for(let o of r){let r=Ns(o).slice(1).toLowerCase();if(!mt.has(r))continue;let s=W(e,o),c;try{c=await Sc(s)}catch{continue}if(!c.isFile()||c.size!==n)continue;if(a++,a>t5)return i.warn({event:`upload-dedup-skip`,reason:`scan-cap-exceeded`,destDir:e,scanned:t5,expectedSize:n},`[upload-dedup] candidate scan exceeded ${t5} same-size siblings — degrading to no-dedup for this upload`),null;let l;try{l=await y_t(s)}catch(e){let t=iq(e);t!==`ENOENT`&&i.warn({event:`upload-dedup-skip`,reason:`read-failed`,code:t,entry:o},`[upload-dedup] skipped candidate — read failed`);continue}if(l===t)return o}return null}function x_t(e){function t(t){let n=nc(e.contentDir),r=W(n,t),i;try{i=nc(r),e.assertContentPath?.(i)}catch(e){return{ok:!1,reason:`not-found`,cause:e}}if(!pq(i,n))return{ok:!1,reason:`invalid-path`};let a;try{a=oc(i)}catch(e){return{ok:!1,reason:`not-found`,cause:e}}if(!a.isFile())return{ok:!1,reason:`not-found`};let o=yct(n,i);return o===t.split(`\\`).join(`/`)?{ok:!0,canonicalPath:i,relativePath:o,size:a.size}:{ok:!1,reason:`invalid-path`}}function n(n){let r=t(n);if(r.ok||r.reason!==`not-found`)return r;let i=n.split(`\\`).join(`/`),a=e.resolveTrackedFile?.(i);if(a===void 0||a===i||e.isPathIgnored?.(a))return r;let o=t(a);return o.ok?o:r}async function r(t){let{tempPath:n,sha:r,byteLength:i,filename:a,parentDocName:o,placement:s}=t,c=()=>{if(G(n))try{sc(n)}catch{}},l=W(e.contentDir),u;try{u=s===`parent-dir`?`./`:e.getAttachmentFolderPath?.()??`./`}catch(e){return c(),{ok:!1,kind:`config-error`,cause:e}}if(!S(u))return c(),{ok:!1,kind:`invalid-attachment-folder`};let d=__t(o,cne(u),l);if(!pq(d,l))return c(),{ok:!1,kind:`path-escape`};try{sJ(d,l),e.assertContentPath?.(d)}catch(e){return c(),uJ(e)?{ok:!1,kind:`path-escape`}:{ok:!1,kind:`dest-validation-error`,cause:e,destDir:d}}if(h4(dJ(d,l,q(`upload`))))return c(),{ok:!1,kind:`reserved-destination`,destDir:d};try{kG(d,{recursive:!0})}catch(e){if(!fJ(e))return c(),{ok:!1,kind:`mkdir-failed`,reason:O3(e),cause:e}}try{let t=nc(d);e.assertContentPath?.(t);let n;try{n=nc(l)}catch{n=l}if(!pq(t,n))return c(),{ok:!1,kind:`path-escape`};if(h4(tq(U(n,t))))return c(),{ok:!1,kind:`reserved-destination`,destDir:d}}catch(e){if(iq(e)!==`ENOENT`)return c(),{ok:!1,kind:`path-escape`,cause:e}}let f=v_t(n,4100),p=await kIe(f),m=p?.mime,h=p?.ext;if(!m){let e=f.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(m=`image/svg+xml`,h=`svg`)}{let t=await b_t(d,r,i);if(t){try{e.assertContentPath?.(W(d,t))}catch(e){return c(),{ok:!1,kind:`dest-validation-error`,cause:e,destDir:d}}return c(),{ok:!0,src:t,path:tq(U(e.contentDir,W(d,t))),deduped:!0,mime:m??null}}}let g;if(!a||a===`upload`||g_t.test(a)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=a?Ns(a).slice(1):``,n=h??t??``;g=n===``?`pasted-${e}`:`pasted-${e}.${n}`}else g=Srt(a);try{e.assertContentPath?.(W(d,g));let t=Lct(n,d,g);return{ok:!0,src:t,path:tq(U(e.contentDir,W(d,t))),deduped:!1,mime:m??null}}catch(e){return c(),{ok:!1,kind:`write-failed`,reason:e instanceof E3?e.reason:`urn:ok:error:storage-error`,cause:e,filename:g}}}return{resolveServableAsset(t){if(!t||t.includes(`\0`))return{ok:!1,reason:`missing-path`};if(!h_t(t))return{ok:!1,reason:`unsupported-type`};let r=n(t);if(!r.ok)return r;if(e.isPathIgnored?.(r.relativePath))return{ok:!1,reason:`not-found`};let i=m_t(r.relativePath),a=Ns(r.relativePath).slice(1).toLowerCase();return!i||!mt.has(a)?{ok:!1,reason:`unsupported-type`}:{ok:!0,asset:{canonicalPath:r.canonicalPath,relativePath:r.relativePath,size:r.size,contentType:i,...p_t(a,nt)}}},resolveTextAsset(e){if(!e||e.includes(`\0`))return{ok:!1,reason:`missing-path`};let t=n(e);return t.ok?{ok:!0,canonicalPath:t.canonicalPath,size:t.size}:t},storeUpload:r}}const n5=q(`search`);let S_t=null;function r5(){return S_t||=aG().createCounter(`ok.search.corpus_update_total`,{description:`Count of workspace search corpus builds, by mode (cold | incremental | rebuild) and, for rebuilds, the bounded fallback reason.`}),S_t}let C_t=null;function w_t(){return C_t||=aG().createCounter(`ok.search.corpus_truncated_total`,{description:`Count of corpus builds whose name-only file tier was truncated at OK_SEARCH_MAX_ENTRIES.`}),C_t}const i5=new Map;function T_t(e){let t=new Map;for(let n of e){let e=n.path.split(`/`).filter(Boolean);e.pop();for(let r=1;r<=e.length;r++){let i=e.slice(0,r).join(`/`);t.set(i,Math.max(t.get(i)??0,n.modifiedTs))}}return[...t.entries()].map(([e,t])=>ie({kind:`folder`,path:e,modifiedTs:t}))}function E_t(e,t){let n=t.trim().toLowerCase();if(!n||!e)return;let r=e.toLowerCase().indexOf(n);if(r<0)return;let i=Math.max(0,r-80),a=Math.min(e.length,r+n.length+120),o=i>0?`…`:``,s=a<e.length?`…`:``;return`${o}${e.slice(i,a).replace(/\s+/g,` `).trim()}${s}`.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,`�`)}function D_t(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?E_t(e.document.content,t):void 0}}function O_t(e,t,n){let{resolved:r,members:i}=MY(e,t,n),a=i.filter(e=>e.role===`symlink`).map(e=>e.path).join(`\0`),o=r?i.map(e=>e.path).toSorted().join(`\0`):``;return`${n.modified}\0${n.size}\0${n.canonicalPath}\0${n.inode}\0${a}\0${o}`}function k_t(e,t,n){return MY(e,t,n).members.map(e=>e.path)}function A_t(e){let{contentDir:t,projectDir:n,getAllFilesIndex:r,getFileIndexGeneration:i,semanticSearch:a,getSemanticSimilarityFloor:o,ready:s}=e;async function c(e,t,n,r){let i=r.documents.filter(e=>!Vne(e.path)),s=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!a?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:s,capable:!1};a.embedCorpus(i);let c,l=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await a.queryScores(e,i);if(l=performance.now()-t,n&&n.size>0){let e=o?.();c=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let u=a.getStatus(),d=(Fi(u,`query`)?Wi(u):null)??(u.ready?u.capable?u.embeddedCount===0?`warming`:e.trim().length<3?`query_too_short`:`no_match`:`incapable`:`warming`);return{input:c,status:{capable:u.capable,applied:!1,outcome:d,providerErrorReason:u.providerErrorReason,coverage:{embedded:u.embeddedCount,total:s}},queryEmbedMs:l,pageTotal:s,capable:u.capable}}function l(){let n=[],r=new Set;for(let e of y0(t)){let i=W(t,e.dir,`SKILL.md`);try{let t=oc(i);n.push({name:e.name,absolutePath:i,docPath:`${e.dir}/SKILL`,mtimeMs:t.mtimeMs,size:t.size}),r.add(e.name)}catch{}}let i=e.getProjectSkillsRoot();if(!G(i))return n;let a;try{a=tc(i,{withFileTypes:!0})}catch{return n}for(let e of a.sort((e,t)=>e.name.localeCompare(t.name))){if(!e.isDirectory()||!no.test(e.name)||r.has(e.name))continue;let t=W(i,e.name,`SKILL.md`);try{let r=oc(t);n.push({name:e.name,absolutePath:t,docPath:`${qa}/${e.name}/SKILL`,mtimeMs:r.mtimeMs,size:r.size})}catch{}}return n}function u(){let t=[];for(let n of l()){let r=n.name,i=``;try{let{frontmatter:t,body:a}=e.parseFrontmatterDoc(K(n.absolutePath,`utf-8`));typeof t.name==`string`&&t.name&&(r=t.name),i=`${typeof t.description==`string`?t.description:``}\n\n${a}`.trim()}catch{}t.push(ie({kind:`page`,path:n.docPath,title:r,content:i,modifiedTs:n.mtimeMs}))}return t}let d=new Map;async function f(){let n=[],i=[],a=new Set;for(let[e,o]of r()){if(KK(e)||qK(e)||hne(e)?.kind===`skill`||e.startsWith(`.ok/skills/`))continue;if(o.kind===`file`){i.push(ie({kind:`file`,path:e,modifiedTs:Date.parse(o.modified),aliases:k_t(t,e,o)}));continue}a.add(e);let r=O_t(t,e,o),s=d.get(e);if(s&&s.key===r){n.push(s.doc);continue}let c=``,l=e,u=!1;try{c=await vc(o.canonicalPath,`utf-8`)}catch(t){u=!0,n5.warn({docName:e,err:t},`[search] Failed to read ${e}`)}if(!u)try{l=EY(c,e)}catch(t){n5.warn({docName:e,err:t},`[search] Failed to extract title for ${e}`)}let f=ie({kind:`page`,path:e,title:l,content:c,modifiedTs:Date.parse(o.modified),aliases:k_t(t,e,o)});u||d.set(e,{key:r,doc:f}),n.push(f)}for(let e of d.keys())a.has(e)||d.delete(e);let o=e.getSearchMaxEntries(),s=i,c=!1;return i.length>o&&(c=!0,s=[...i].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,o),n5.warn({dropped:i.length-s.length,retained:s.length,limit:o},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),w_t().add(1)),{documents:[...n,...u(),...s,...T_t([...n,...s])],truncated:c}}function p(){return l().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function m(){return i?`gen:${i()}|skills${p()}`:`${[...r()].filter(([e])=>!KK(e)&&!qK(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,n])=>`${e}\0${O_t(t,e,n)}`).join(``)}|skills${p()}`}let h=s===void 0;s?.then(()=>{h=!0},e=>{h=!0,n5.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function g(){return!h}async function _(){let e=`${t} ${n??``}`,r=m(),i=i5.get(e);if(i?.fingerprint===r&&i.corpus)return{corpus:i.corpus,truncated:i.truncated??!1};if(i?.fingerprint===r&&i.pending)return i.pending;let a=i?.corpus,o=i?.pending,s=(async()=>{let e=o?await o.then(e=>e.corpus,()=>void 0):a,{documents:t,truncated:n}=await f();if(!e)return r5().add(1,{mode:`cold`}),{corpus:Mie(t),truncated:n};let r=yt(e,t);if(r.rebuilt){r5().add(1,{mode:`rebuild`,reason:r.rebuildReason});let e=r.rebuildReason===`mutation-failed`?`warn`:`debug`;n5[e]({reason:r.rebuildReason,documents:t.length},`[search] corpus update fell back to a full index rebuild`)}else r5().add(1,{mode:`incremental`}),n5.debug({inserted:r.inserted,updated:r.updated,removed:r.removed},`[search] corpus updated incrementally`);return{corpus:r.corpus,truncated:n}})();i5.set(e,{fingerprint:r,pending:s});try{let t=await s;return i5.get(e)?.pending===s&&i5.set(e,{fingerprint:r,corpus:t.corpus,truncated:t.truncated}),t}catch(t){throw i5.get(e)?.pending===s&&i5.delete(e),t}}return{async buildSearchResponse(e){let t=performance.now();if(g())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await _(),i=await c(e.query,e.intent,e.semanticParam,n),a=lee(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>D_t(t,e.query)),o;if(i.status){let t=a.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),n=t>0,r=n?`applied`:i.status.outcome;o={...i.status,applied:n,outcome:r},pst({outcome:r,source:e.source,capable:i.capable,embedded:i.status.coverage.embedded,total:i.pageTotal,queryEmbedMs:i.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:a,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...o?{semantic:o}:{},...r?{truncated:!0}:{}}},prewarm(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{_().catch(e=>{n5.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}}}const a5=q(`skill-install`);function j_t(e){let t=t=>t===`project`?y0(e.contentDir):b0(e.skillsHome);return{resolveFork(n){let{scope:r,name:i,fork:a,inPlaceEntry:o}=n,s=r===`project`?e.contentDir:e.skillsHome,c=[],l=r===`project`?Vi:Ji,u=a.editor===`agents`?oi:l[a.editor]??null;if(u===null)return{ok:!1,kind:`unknown-editor`,editor:a.editor};let d=W(s,u,i),f=W(s,o.dir),p=iP(d);if(p===null||d===f)return{ok:!1,kind:`fork-absent`};if(p.contentHash===o.contentHash)return{ok:!1,kind:`not-a-fork`};let m=new Date().toISOString().replace(/[:.]/g,`-`),h=(t,n)=>{try{let r=W(KS(e.skillsHome),`edit-backups`,`forks`,`${i}-${n}-${m}`);kG(W(r,`..`),{recursive:!0}),jG(t,r,{recursive:!0})}catch(e){a5.warn({name:i,err:e},`[skill-fork] stash failed`)}};if(a.action===`align`)h(d,a.editor),FG(d,{recursive:!0,force:!0}),Y0({canonicalAbs:f,canonicalHash:o.contentHash,canonicalRootRel:V(o.dir),name:i,cwd:s,targets:[a.editor].filter(zi),roots:B0(r)});else if(a.action===`make-source`){let e=o.hosts.filter(zi);h(f,`source`),Q0({canonicalAbs:f,canonicalHash:o.contentHash,name:i,cwd:s,targets:e,roots:B0(r)}),FG(f,{recursive:!0,force:!0});let n=t(r).find(e=>e.name===i);n&&Y0({canonicalAbs:W(s,n.dir),canonicalHash:n.contentHash,canonicalRootRel:V(n.dir),name:i,cwd:s,targets:e,roots:B0(r)})}else{let e=a.toName;if(!no.test(e))return{ok:!1,kind:`invalid-new-name`,toName:e};if(t(r).some(t=>t.name===e))return{ok:!1,kind:`name-taken`,toName:e};let n=W(s,u,e);AG(d,n);let i=Z1({skillDir:n,toName:e});i.ok||(i.stage===`patch`?(a5.warn({name:e,reason:i.error.kind},`[skill-fork] frontmatter rename failed`),c.push(`Renamed the folder to "${e}", but its SKILL.md still declares the old name — edit the frontmatter to match.`)):(a5.warn({name:e,err:i.cause},`[skill-fork] frontmatter rename failed`),c.push(`Renamed the folder to "${e}", but its SKILL.md could not be updated — edit the frontmatter to match.`)))}return{ok:!0,warnings:c}},async applyAddRemove(t){let{scope:n,name:r,inPlaceEntry:i}=t,a=n===`project`?e.contentDir:e.skillsHome,o=[],s=[],c=e=>e.replace(/\\/g,`/`).replace(/^~\//,``),l=i.hosts[0];if(l!==void 0&&(t.remove??[]).some(e=>c(e)===l))return{ok:!1,kind:`remove-source`,sourceId:l};let u=new Set(i.hosts.filter(e=>zi(e)));for(let e of t.add??[])zi(e)?u.add(e):o.push(c(e));let d=u0(a,n),f=[],p=[];for(let e of t.add??[])if(zi(e)&&d[e]!==void 0&&!G(W(a,d[e],r,`SKILL.md`))){let t=e===`agents`?oi:B0(n)[e]??null;t!==null&&p.push(t)}for(let e of t.remove??[])if(zi(e)){if(!u.has(e)&&d[e]!==void 0&&G(W(a,d[e],r,`SKILL.md`))){let t=e===`agents`?oi:B0(n)[e]??null;t!==null&&f.push(t)}u.delete(e)}else s.push(c(e));for(let{subRoot:e,exclude:t}of[...p.map(e=>({subRoot:e,exclude:void 0})),...f.map(e=>({subRoot:e,exclude:[r]}))]){let n=Wgt({base:a,folderRel:e,...t===void 0?{}:{exclude:t}});if(n.ok&&await Lnt(a,e,{expect:`own`}),!n.ok)return{ok:!1,kind:`unfollow-failed`,subRoot:e,reason:n.reason}}return{ok:!0,targets:[...u],rootAdds:o,rootRemoves:s}},async promoteStoreBackedSource(n){let{scope:r,name:i,base:a,skillDir:o,newSource:s}=n,c=r===`project`?e.contentDir:e.skillsHome,l=X0({canonicalAbs:o,canonicalHash:iP(o)?.contentHash??``,name:i,cwd:c,newTarget:s,roots:B0(r)});if(!l.ok)return{ok:!1,kind:`source-occupied`,reason:l.reason};await D0(a,i),await N0(c,i,s);let u=t(r).find(e=>e.name===i);return{ok:!0,hosts:u?[...u.hosts]:[],sourceMovedTo:U(c,l.newAbs).split(Rs).join(`/`)}},async promoteInPlaceSource(n){let{scope:r,name:i,base:a,prefBase:o,skillDir:s,inPlaceEntry:c,newSource:l}=n,u=r===`project`?e.contentDir:e.skillsHome,d=o??a,f=c.hosts[0],p=zi(l),m;if(!p){let e=l.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),t=M0(e),n=W(a,e,i);if(e===``||t||!n.startsWith(W(a)+Rs))return{ok:!1,kind:`invalid-target`,target:l};m=n}let h;if(f!==void 0&&l!==f){let t=U(u,W(s)).split(Rs).join(`/`),n=X0({canonicalAbs:s,canonicalHash:c.contentHash,name:i,cwd:a,newTarget:p?l:`agents`,...m===void 0?{}:{destDirAbs:m},leaveLinkBehind:!0,roots:B0(r)});if(!n.ok)return{ok:!1,kind:`source-occupied`,reason:n.reason};h=U(u,n.newAbs).split(Rs).join(`/`);let o=W(u,t);if(e.effectiveInstallMode(r,i,{hosts:c.hosts,linkedHosts:c.linkedHosts??[]})===`copy`)try{Ys(o).isSymbolicLink()&&(FG(o,{recursive:!0,force:!0}),jG(n.newAbs,o,{recursive:!0,dereference:!0}))}catch{}let f=!1;try{f=Ys(o).isSymbolicLink()}catch{f=!0}await F0(d,i,f?{path:t,mode:`link`}:{path:t,mode:`copy`,hash:c.contentHash});let g=new Set(ert(a,i,B0(r)).map(e=>W(e)));Z0({name:i,cwd:a,roots:B0(r),target:n.newAbs,slots:(P0(d)[i]??[]).map(e=>W(d,e.path)).filter(e=>!g.has(e)),skip:[n.newAbs,W(s)],alsoClaim:[W(s),n.newAbs]}),await F0(d,i,{path:h,mode:`copy`}),await N0(d,i,l)}let g=t(r).find(e=>e.name===i);return{ok:!0,hosts:g?[...g.hosts]:[...c.hosts],...h===void 0?{}:{sourceMovedTo:h}}},async fanOutInPlace(n){let{scope:r,name:i,base:a,prefBase:o,inPlaceEntry:s,inPlaceTargets:c}=n,l=r===`project`?e.contentDir:e.skillsHome,u=o??a,{skillDir:d}=n,f=[],p=[],m=s.hosts.filter(e=>zi(e)),h=s.hosts[0],g;if(n.setExact&&h!==void 0&&!h.includes(`/`)&&c.length>0&&!c.includes(h)){let e=c[0],t=X0({canonicalAbs:d,canonicalHash:s.contentHash,name:i,cwd:a,newTarget:e,roots:B0(r)});if(!t.ok)return{ok:!1,kind:`source-occupied`,reason:t.reason};d=t.newAbs,g=U(l,t.newAbs).split(Rs).join(`/`),await F0(u,i,{path:g,mode:`copy`}),await N0(u,i,e)}let _=g?g.split(`/`).slice(0,-1).join(`/`):n.canonicalRootRel;Q0({canonicalAbs:d,canonicalHash:s.contentHash,name:i,cwd:a,targets:n.setExact?m.filter(e=>!c.includes(e)):[],roots:B0(r)});let v=Y0({canonicalAbs:d,canonicalHash:s.contentHash,canonicalRootRel:_,name:i,cwd:a,targets:c,mode:n.installMode,convertLinks:n.linkModeReq===!1,convertCopies:n.linkModeReq===!0,roots:B0(r)}),y=new Set(v.linkFallbacks);for(let e of v.conflicted)f.push(`A different skill named "${i}" already exists in the ${e} skills folder — left untouched.`),p.push(`name-conflict`);if(n.linkModeReq!==void 0&&o&&n.rootAdds.length>0){let e=new Set((P0(o)[i]??[]).map(e=>e.path));for(let t of n.rootAdds){if(!e.has(`${t}/${i}`))continue;let r=W(o,t,i);if(r===W(d))continue;let a=J0(r,W(d),s.contentHash);n.linkModeReq===!0&&a===`same-copy`?(FG(r,{recursive:!0,force:!0}),G0(U(V(r),W(d)),r,W(d))===`copy`&&y.add(t)):n.linkModeReq===!1&&a===`link-to-canonical`&&(FG(r,{recursive:!0,force:!0}),jG(W(d),r,{recursive:!0,dereference:!0}))}}for(let e of v.hosts){let t=e===`agents`?oi:B0(r)[e];if(t===null||t===n.canonicalRootRel)continue;let o=W(a,t,i),c=!1;try{c=Ys(o).isSymbolicLink()}catch{continue}if(c){n.installMode===`link`&&await F0(u,i,{path:`${t}/${i}`,mode:`link`});continue}let l=G(H(o,`SKILL.md`))?iP(o)?.contentHash:void 0;l!==void 0&&l===s.contentHash&&await F0(u,i,{path:`${t}/${i}`,mode:`copy`,hash:l})}if((n.rootAdds.length>0||n.rootRemoves.length>0)&&o){let e=W(d);for(let t of n.rootAdds){let r=M0(t),a=W(o,t),c=z1(o,`${t}/${i}`);if(t===``||r||c===null||c===e){f.push(`"${t}" is not a placeable custom root — skipped.`),p.push(`place-path-invalid`);continue}let l=J0(c,e,s.contentHash);if(l===`different`){f.push(`A different "${i}" already exists at ${t} — left untouched.`),p.push(`name-conflict`);continue}l===`absent`&&(kG(a,{recursive:!0}),n.installMode===`link`?G0(U(a,e),c,e)===`copy`&&y.add(t):jG(e,c,{recursive:!0,dereference:!0}));let u=Ys(c).isSymbolicLink()?`link`:`copy`;await F0(o,i,{path:`${t}/${i}`,mode:u,...u===`copy`?{hash:s.contentHash}:{}})}for(let t of n.rootRemoves){let n=`${t}/${i}`,r=P0(o)[i]?.find(e=>e.path===n),a=z1(o,n);if(a===null){f.push(`"${t}" is not a placeable custom root — skipped.`),p.push(`place-path-invalid`);continue}let c=J0(a,e,s.contentHash);if(c===`different`){f.push(`The copy at ${n} differs from the current source and was preserved. Inspect both versions before removing it.`),p.push(`place-fork-refused`);continue}c!==`absent`&&c!==`canonical-dir`&&FG(a,{recursive:!0,force:!0}),r&&await Vnt(o,i,n)}}y.size>0&&(f.push(Znt([...y])),p.push(`links-not-permitted`));let b=t(r).find(e=>e.name===i);return{ok:!0,hosts:b?[...b.hosts]:v.hosts,warnings:f,warningCodes:p,...g===void 0?{}:{sourceMovedTo:g}}}}}function M_t(){return{async place(e){let t=e.rawDir.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),n=W(e.placeBase,t),r=`${t}/${e.name}`,i=z1(e.placeBase,r),a=W(e.placeBase),o=M0(t);if(t===``||i===null||!i.startsWith(a+Rs)||o)return{ok:!1,kind:`invalid-path`};if(i===W(e.skillDir))return{ok:!0,alreadyAtSource:!0,placedAt:r};if(G(i))return{ok:!1,kind:`dest-exists`};kG(n,{recursive:!0});let s=e.mode;return e.mode===`link`?s=G0(U(n,W(e.skillDir)),i,W(e.skillDir)):jG(e.skillDir,i,{recursive:!0,dereference:!0}),await F0(e.placeBase,e.name,{path:r,mode:s,...s===`copy`?{hash:iP(e.skillDir)?.contentHash}:{}}),{ok:!0,placedAt:r,...e.mode===`link`&&s===`copy`?{copiedInsteadOfLinked:!0}:{}}},async unplace(e){let t=e.rawPath.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``);if(!P0(e.placeBase)[e.name]?.find(e=>e.path===t))return{ok:!1,kind:`not-recorded`,path:t};let n=z1(e.placeBase,t);if(n===null)return{ok:!1,kind:`unsafe-path`};let r=iP(e.skillDir)?.contentHash??``;switch(J0(n,W(e.skillDir),r)){case`different`:return{ok:!1,kind:`forked`,path:t};case`canonical-dir`:return{ok:!1,kind:`canonical-dir`,path:t};case`absent`:break;default:FG(n,{recursive:!0,force:!0})}return await Vnt(e.placeBase,e.name,t),{ok:!0}},async convert(e){let t=B0(e.scope),n=zi(e.target)?e.target===`agents`?oi:t[e.target]:e.target.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),r=n===null||n===``?null:z1(e.ledgerBase,`${n}/${e.name}`);if(n===null||n===``||r===null)return{ok:!1,kind:`invalid-location`};let i=W(e.skillDir),a=J0(r,i,e.canonicalHash);if(a===`canonical-dir`)return{ok:!1,kind:`canonical-dir`};if(a===`different`)return{ok:!1,kind:`forked`};if(a===`absent`)return{ok:!1,kind:`not-installed`};if(!(e.mode===`link`&&a===`link-to-canonical`||e.mode===`copy`&&a===`same-copy`)){let t=V(r);if(FG(r,{recursive:!0,force:!0}),kG(t,{recursive:!0}),e.mode===`link`){if(G0(U(t,i),r,i)===`copy`)return{ok:!1,kind:`links-not-permitted`}}else jG(i,r,{recursive:!0,dereference:!0})}return await F0(e.ledgerBase,e.name,{path:`${n}/${e.name}`,mode:e.mode,...e.mode===`copy`?{hash:e.canonicalHash}:{}}),{ok:!0}}}}const o5=q(`write-advisory`);let N_t=null;function P_t(){return N_t||=aG().createCounter(`ok.write_advisory.deferred`,{description:`Post-write advisories that depend on the derived document index and were omitted from a write response: reason=deadline when the index did not answer within the write-advisory deadline, reason=busy when an earlier advisory was still waiting past its deadline so this one was not started. The write itself was durable either way.`,unit:`{advisory}`}),N_t}const F_t=Symbol(`write-advisory-deadline`);function I_t(e={}){let t=e.deadlineMs??1500,n=0,r=0,i,a=0,o=0,s=0,c,l,u=()=>{let e=Date.now();c=e;let l=n>0,u={closings:a,busySkipped:o,closedMs:l?s+e-r:s};a=0,o=0,s=0,r=e,l?o5.warn({advisory:i,deadlineMs:t,...u},`[write-advisory] document index did not answer within the write-advisory deadline; skipping index-backed write advisories until it catches up`):o5.info(u,`[write-advisory] document index caught up; index-backed write advisories resumed`)},d=()=>{if(l!==void 0)return;let e=Date.now(),t=c===void 0?e:c+6e4;if(e>=t){u();return}l=setTimeout(()=>{l=void 0,u()},t-e),l.unref()},f=e=>{n+=1,!(n>1)&&(r=Date.now(),i=e,a+=1,d())},p=()=>{--n,!(n>0)&&(s+=Date.now()-r,d())},m=(e,t,n)=>(P_t().add(1,{advisory:e,reason:t}),n());return{async run(e,r,i){if(n>0)return o+=1,m(e,`busy`,i);let a=!1,s=!1,c=Promise.resolve().then(r),l=()=>{a=!0,s&&p()};c.then(l,l);let u,d=new Promise(e=>{u=setTimeout(()=>e(F_t),t)});try{let t=await Promise.race([c,d]);return t===F_t?(a||(s=!0,f(e)),c.catch(t=>{o5.warn({err:t,advisory:e},`[write-advisory] deferred advisory failed after its deadline`)}),m(e,`deadline`,i)):t}finally{clearTimeout(u)}}}}function L_t(e,t){let{reason:n,targetKind:r}=t,i=e.fileExists!==null&&e.fileExcluded!==null;switch(n){case`no-such-doc`:return e.folderExists!==null&&(!t.mayNameFile||i);case`no-such-file`:return i&&(!t.wikiAsset||e.resolveWikiFile!==null);case`excluded`:return i;case`unresolvable`:return r!==`file`||e.fileExists!==null;default:return n}}function R_t(e,t,n,r){let i=r.fileExists??void 0,a=r.fileExcluded??void 0,{folderExists:o,resolveWikiFile:s,resolveFileByBasename:c}=r,l=Li(`document`,n),u=Ia(ya(`folder`),l),d=e=>u.resolve(e)??(o?.(e)===!0?e:void 0),f=e=>d(e)!==void 0,p=Hit(e,t,{resolveDocument:e=>l.resolve(e),resolveFile:e=>i?.(e)?e:void 0,resolveFileByBasename:c,...a?{isExcludedFile:a}:{},...s?{resolveWikiFile:s}:{},resolveTolerantDocument:A2(l),resolveFolder:d}),m=new Set(p.filter(({occurrence:e})=>e.sourceForm===`markdown-inline`&&e.role===`link`).map(({occurrence:e})=>e.href)),h=Eat(e,t,l,i,f,a).filter(e=>e.sourceForm===`jsx`||e.href.startsWith(`[[`)||m.has(e.href)),g=new Set(h.map(e=>e.href)),_=h.filter(e=>L_t(r,{reason:e.reason,targetKind:null,wikiAsset:!1,mayNameFile:e.sourceForm!==`jsx`&&!e.href.startsWith(`[[`)})),v=new Set;for(let e of p){if(e.reason===null||!L_t(r,{reason:e.reason,targetKind:e.targetKind,wikiAsset:P2(e.occurrence)!==null,mayNameFile:!F2(e.occurrence.sourceForm)}))continue;let{href:t,role:n,sourceForm:i,range:a,reference:o}=e.occurrence;if(n===`link`&&i===`markdown-inline`&&g.has(t))continue;let s=Uit(e,e.reason);if(s===null)continue;let c=o?.definition.repairRange??a,l=`${c.start}:${c.end}`;v.has(l)||(v.add(l),_.push({href:t,resolvedTo:e.resolvedTarget,reason:e.reason,localTarget:s}))}return _}let z_t=null;function B_t(){return z_t||=aG().createCounter(`ok.rename.attribution_kind`,{description:`Count of rename and rollback handler dispatches by attribution kind (agent | principal | anonymous)`}),z_t}let V_t=null;function H_t(){return V_t||=aG().createCounter(`ok.agent_write.gate_fired_total`,{description:`Count of agent writes that ran the Site A content-divergence gate (denominator for the divergence rate). Bounded label: handler ∈ {agent-write-md, agent-write-batch, agent-patch, rollback}.`}),V_t}let U_t=null;function W_t(){return U_t||=aG().createCounter(`ok.agent_write.content_divergence_total`,{description:`Count of agent writes whose converged Y.Text diverged from the composed intent (numerator for the divergence rate). Bounded labels: handler ∈ {agent-write-md, agent-write-batch, agent-patch, rollback}, divergence_type.`}),U_t}function G_t(e,t){H_t().add(1,{handler:e}),t!==void 0&&W_t().add(1,{handler:e,divergence_type:t.divergenceType})}const s5={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},c5=q(`api`),K_t=e=>e instanceof Error&&e.message.startsWith(`Refusing to rewrite `)?e.message:void 0;function l5(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name.`};let n=t===`.`?``:t.replace(/^\.\//,``),r=k6(e);if(r.managed&&r.versioned)return{path:n?`${n}/${r.filePath}`:r.filePath};let i=VK(e);return{path:n?`${n}/${e}${i}`:`${e}${i}`}}function q_t(e,t){let n=l5(e,t);if(`error`in n)return[`${e}.md`];let r=AXe(n.path,e);return r?[n.path,r]:[n.path]}function J_t(e,t){let n=W(e,t);if(!nq(n,e))throw Error(`Invalid directory: ${t}`);return n}function Y_t(e,t){let n,r;try{n=nc(e),r=nc(t)}catch{return null}return nq(n,r)?U(r,n).split(Rs).join(`/`):null}async function X_t(e,t,n){if(!t)return!1;let r=[...e].sort().join(`\0`);if(r===n.lastKey||(n.lastKey=r,!e.some(e=>t.isExcluded(e))))return!1;try{return await t.rebuildIgnorePatterns(),!0}catch{return!1}}function u5(e){let t=Ns(e);return t?t.slice(1).toLowerCase():e.startsWith(`.`)&&e.length>1?e.slice(1).toLowerCase():`file`}const Z_t=5e4;function Q_t(){let e=process.env.OK_SHOWALL_MAX_ENTRIES;if(e===void 0)return Z_t;let t=Number(e);return Number.isInteger(t)&&t>0?t:Z_t}const $_t=5e4;function evt(){let e=process.env.OK_SEARCH_MAX_ENTRIES;if(e===void 0)return $_t;let t=Number(e);return Number.isInteger(t)&&t>0?t:$_t}let d5=0,f5=0;function tvt(){return{invocations:d5,aborts:f5}}function nvt(){d5=0,f5=0}async function*p5(e){let{contentDir:t,contentFilter:n,dirFilter:r,maxEntries:i,signal:a,showOk:o}=e,s=e.maxDepth??1/0,c={bypassFilters:!0,respectOkignore:!0,showOk:o};d5+=1;let l=0,u=!1,d=!1,f=e=>!r||e===r||e.startsWith(`${r}/`),p;try{p=await bc(t)}catch{p=t}let m=e=>nq(e,p),h=async(e,t,r)=>{let i=new Map;for(let t of e){if(!t.isFile()&&!t.isSymbolicLink()||!PK(t.name))continue;let e=LK(r?`${r}/${t.name}`:t.name);i.set(e,(i.get(e)??0)+1)}let a=new Set([...i].filter(([,e])=>e>1).map(([e])=>e));if(a.size===0)return new Map;let o=new Map;for(let i of e){if(!i.isFile()&&!i.isSymbolicLink()||!PK(i.name))continue;let e=r?`${r}/${i.name}`:i.name,s=LK(e);if(a.has(s)&&!n.isExcluded(e,c)&&f(e)){if(i.isSymbolicLink()){let e=H(t,i.name),n;try{n=await bc(e)}catch{continue}if(!m(n))continue;let r;try{r=await Sc(n)}catch{continue}if(!r.isFile())continue}else try{await Sc(H(t,i.name))}catch{continue}o.set(s,(o.get(s)??0)+1)}}return o},g=(e,t)=>{let n=LK(e);return(t.get(n)??0)>1?e:n};async function _(e,t){let r;try{r=await yc(e,{withFileTypes:!0})}catch(t){return c5.warn({dir:e,err:t},`[document-list][showAll] probe readdir failed for ${e}`),!1}for(let i of r){let r=t?`${t}/${i.name}`:i.name;if(i.isDirectory()){if(n.isDirExcluded(r,c))continue;try{let t=await bc(H(e,i.name));if(!m(t))continue}catch(t){c5.warn({path:`${e}/${i.name}`,err:t},`[document-list][showAll] probe realpath failed for ${e}/${i.name}`);continue}return!0}if(i.isFile()&&!n.isExcluded(r,c))return!0}return!1}async function*v(e,r,o){let p=[{absDir:e,relDir:r,depth:o}];for(let e=0;e<p.length;e++){if(a?.aborted){d=!0;return}let{absDir:r,relDir:o,depth:v}=p[e],y;try{y=await yc(r,{withFileTypes:!0})}catch(e){c5.warn({dir:r,err:e},`[document-list][showAll] readdir failed for ${r}`);continue}let b=await h(y,r,o);for(let e of y){if(a?.aborted){d=!0;return}if(l>=i){u=!0;return}let h=o?`${o}/${e.name}`:e.name;if(e.isDirectory()){if(n.isDirExcluded(h,c))continue;let t=H(r,e.name),i;try{i=await bc(t)}catch(e){c5.warn({path:t,err:e},`[document-list][showAll] realpath failed for ${t}`);continue}if(!m(i)){c5.warn({path:t,canonical:i},`[document-list][showAll] refusing symlink-escape ${t} -> ${i}`);continue}if(f(h)){let e=null;try{e=await Sc(t)}catch(e){c5.warn({path:t,err:e},`[document-list][showAll] stat failed for ${t}`)}l+=1;let n=v>=s?await _(t,h):void 0;yield{kind:`folder`,path:h,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null,...n===void 0?{}:{hasChildren:n}}}v<s&&p.push({absDir:t,relDir:h,depth:v+1});continue}if(e.isSymbolicLink()){let i=H(r,e.name),a;try{a=await bc(i)}catch(e){c5.warn({path:i,err:e},`[document-list][showAll] symlink realpath failed for ${i}`);continue}if(!m(a)){c5.warn({path:i,canonical:a},`[document-list][showAll] refusing symlink-escape ${i} -> ${a}`);continue}let o;try{o=await Sc(a)}catch(e){c5.warn({path:i,err:e},`[document-list][showAll] symlink target stat failed for ${i}`);continue}let s=tq(U(t,a));if(o.isDirectory()){if(n.isDirExcluded(h,c)||!f(h))continue;l+=1,yield{kind:`folder`,path:h,size:0,modified:o.mtime.toISOString(),docExt:`.md`,isSymlink:!0,canonicalDocName:s,targetPath:s,hasChildren:await _(a,h)};continue}if(!o.isFile()||n.isExcluded(h,c)||!f(h))continue;if(l+=1,PK(e.name))yield{kind:`document`,docName:g(h,b),docExt:Ns(e.name),size:o.size,modified:o.mtime.toISOString(),isSymlink:!0,canonicalDocName:s.replace(/\.(md|mdx)$/i,``),targetPath:s};else{let t=u5(e.name);yield{kind:`asset`,docName:h,docExt:t,path:h,assetExt:t,mediaKind:mi(t),referencedBy:[],size:o.size,modified:o.mtime.toISOString(),isSymlink:!0,canonicalDocName:null,targetPath:s}}continue}if(!e.isFile()||n.isExcluded(h,c)||!f(h))continue;let y=null;try{y=await Sc(H(r,e.name))}catch(t){c5.warn({path:`${r}/${e.name}`,err:t},`[document-list][showAll] stat failed for ${r}/${e.name}`);continue}if(PK(e.name)){let t=g(h,b),n=Ns(e.name);l+=1,yield{kind:`document`,docName:t,docExt:n,size:y.size,modified:y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null};continue}let x=u5(e.name),S=mi(x);l+=1,yield{kind:`asset`,docName:h,docExt:x,path:h,assetExt:x,mediaKind:S,referencedBy:[],size:y.size,modified:y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null}}}}return yield*v(r?H(t,r):t,r??``,1),d&&(f5+=1),{truncated:u}}async function rvt(e){let{documents:t,...n}=e,r=p5(n),i=await r.next();for(;!i.done;)t.push(i.value),i=await r.next();return i.value}function ivt(e,t,n){let r=[...e.keys()].filter(e=>t===`file`?e===n:e===n||e.startsWith(`${n}/`));return r.sort((e,t)=>e.localeCompare(t)),r}function avt(e,t,n,r){return t===`file`||e===n?r:`${r}${e.slice(n.length)}`}function m5(e,t,n){return e!==void 0&&e.length>0?e:(X(t,400,`urn:ok:error:invalid-request`,"`docName` must be a non-empty document name.",{handler:n}),null)}function h5(e,t,n){if(!e5(n))throw new lJ(`path must be a relative content path`);let r=W(e),i=t===`file`?WK(n):n,a=W(r,i);if(a!==r&&!a.startsWith(`${r}${Rs}`))throw new lJ(`path must not escape content directory`);return sJ(a,r),a}function g5(e){let t=e.lastIndexOf(`/`);return t===-1?{parent:``,basename:e}:{parent:e.slice(0,t),basename:e.slice(t+1)}}function ovt(e,t){return e?`${e}/${t}`:t}function svt(e,t){return t===1?`${e} copy`:`${e} copy ${t}`}function _5(e,t){return v5(e,t)!==null}function v5(e,t){if(PK(t))return G(W(e,t))?t:null;for(let n of Bi)if(G(W(e,`${t}${n}`)))return`${t}${n}`;return null}function cvt(e,t){if(!PK(t))return!1;let n=LK(t),r=Ns(t).toLowerCase();return Bi.some(t=>t.toLowerCase()!==r&&G(W(e,`${n}${t}`)))}function y5(e,t){let n=LK(t);return PK(t)&&cvt(e,t)?t:n}function lvt(e,t,n){if(!e5(t))throw new lJ(`path must be a relative content path`);let r=W(e),i=W(r,`${t}${n}`);if(i!==r&&!i.startsWith(`${r}${Rs}`))throw new lJ(`path must not escape content directory`);return sJ(i,r),i}function uvt(e,t){let{parent:n,basename:r}=g5(t);for(let t=1;t<=1e4;t+=1){let i=ovt(n,svt(r,t));if(!_5(e,i))return{docName:i,attempt:t}}throw new w3(t)}function dvt(e,t){let{parent:n,basename:r}=g5(t);for(let t=1;t<=1e4;t+=1){let i=ovt(n,svt(r,t)),a=h5(e,`folder`,i);if(!G(a))return{folderPath:i,attempt:t}}throw new w3(t)}function fvt(e,t){let n=h5(e,`folder`,t),r=[];function i(t,n){for(let a of tc(t,{withFileTypes:!0})){let o=W(t,a.name),s=n?`${n}/${a.name}`:a.name;if(a.isDirectory()){i(o,s);continue}!a.isFile()||!PK(s)||r.push({docName:y5(e,s),fullPath:o,content:K(o,`utf-8`)})}}return i(n,t),r.sort((e,t)=>e.docName.localeCompare(t.docName)),r}function pvt(e,t){let n=h5(e,`folder`,t),r=[t];function i(e,t){for(let n of tc(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let a=W(e,n.name),o=t?`${t}/${n.name}`:n.name;r.push(o),i(a,o)}}return i(n,t),r.sort((e,t)=>e.localeCompare(t)),r}function b5(e,t){let n=W(e),r=W(t);return r!==n&&!r.startsWith(`${n}${Rs}`)?null:U(n,r).split(Rs).join(`/`)}function x5(e,t){return e!==t&&e.toLowerCase()===t.toLowerCase()}function S5(e,t){return x5(W(e),W(t))}function mvt(e,t){if(!S5(e,t)||!G(e)||!G(t))return!1;try{let n=oc(e),r=oc(t);return n.dev===r.dev&&n.ino===r.ino}catch{return!1}}function hvt(e){let t=V(e);for(let e=0;e<10;e+=1){let e=W(t,`.ok-case-rename-${Ec()}`);if(!G(e))return e}throw Error(`Unable to allocate temporary path for case-only rename`)}function C5(e,t){return(G(e)?K(e,`utf-8`):null)!==t&&(DG(e,t,`utf-8`),!0)}function w5(e,t){if(kG(V(t),{recursive:!0}),!S5(e,t)){AG(e,t);return}let n=hvt(e);AG(e,n);try{AG(n,t)}catch(t){try{let t=G(n),r=G(e);t&&!r?AG(n,e):c5.warn({tempExists:t,sourceExists:r},`[renamePathOnDisk] skipped case-only rollback due to unexpected state`)}catch(e){c5.warn({err:e},`[renamePathOnDisk] failed to roll back temporary case-only rename`)}throw t}}async function T5(e,t,n){if(!e)return!1;let r=b5(e,t),i=b5(e,n);return!r||!i?!1:await Rq(async()=>{let a=RN({baseDir:e,timeout:{block:15e3}}),o;try{o=await Not(a,e,r)}catch(t){return c5.warn({err:t,projectDir:e,path:r},`[renameTrackedPathInGit] tracked-path lookup failed, falling back to fs rename`),!1}if(!o)return!1;Xs(V(n),{recursive:!0});let s=!1;try{if(S5(t,n)){let n=b5(e,hvt(t));if(!n)return!1;await a.raw(`mv`,`--`,r,n);try{await a.raw(`mv`,`--`,n,i)}catch(e){try{await a.raw(`mv`,`--`,n,r)}catch(e){c5.warn({err:e},`[renameTrackedPathInGit] case-only git rename failed and rollback also failed; git index and disk may have diverged`),s=!0}throw e}}else await a.raw(`mv`,`--`,r,i);return!0}catch(e){if(s)throw e;return c5.warn({err:e},`[renameTrackedPathInGit] git mv failed, falling back to fs rename`),!1}})}function gvt(e){let{body:t}=Ba(e),n=[],r=new Map,i=io();for(let e of t.split(`
2078
2078
  `)){if(i(e))continue;let t=Uoe(e,r);t&&n.push(t)}return n}function E5(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function _vt(e,t){let n=t();n instanceof Map&&EX(e,n)}function vvt(e){switch(e.removal?.kind){case`path-occupied`:return{type:`urn:ok:error:doc-removed`,title:`Edit applied in memory; disk write refused because the file now at this path is not loaded into the document.`,detail:`${e.message}. Retrying will not help until the server reloads this document from disk, for example after Open Knowledge restarts; tell the user instead of retrying.`};case`renamed`:return{type:`urn:ok:error:doc-removed`,title:`Edit applied in memory; disk write refused because the document was renamed.`,detail:`${e.message}. Retrying will not help: re-read the document at ${e.removal.renamedTo} and re-apply your change there.`};case void 0:return{type:`urn:ok:error:doc-removed`,title:`Edit applied in memory; disk write refused because the document is no longer on disk.`,detail:`${e.message}. Retrying will not help: re-create the document before writing this content again.`}}}function yvt(e){return{type:`urn:ok:error:path-escape`,title:`Edit applied in memory; disk write refused because the document path could not be resolved.`,detail:`${e.message}. Retrying will not help: the path has to be repaired on disk before this content can be written.`}}function bvt(e){return{type:`urn:ok:error:branch-switched`,title:`Edit not saved: the Git branch changed before it reached disk.`,detail:`${e.message}. The document now shows the checked-out branch. Re-read it, then repeat the edit if it is still needed.`}}function xvt(e){return{type:`urn:ok:error:store-refused`,title:`Edit applied in memory; disk write refused because the duplication baseline could not be read.`,detail:`${e.message}. The edit is applied in collaborative state and the document file on disk was not updated; a copy of the edited document is preserved in the server's recovery buffer unless that buffer is unavailable or unwritable. Retry the write once the filesystem fault is repaired.`}}function D5(e,t,n){if(t.code===`OK_STORE_REFUSED`){let{type:r,title:i,detail:a}=xvt(t);X(e,503,r,i,{handler:n,detail:a});return}if(t.code===`OK_DOC_REMOVED`){let{type:r,title:i,detail:a}=vvt(t);X(e,409,r,i,{handler:n,detail:a});return}if(t.code===`OK_STORE_DISCARDED`){let{type:r,title:i,detail:a}=bvt(t);X(e,409,r,i,{handler:n,detail:a});return}if(t.code===`OK_PATH_UNRESOLVABLE`){let{type:r,title:i,detail:a}=yvt(t);X(e,400,r,i,{handler:n,detail:a});return}let r=O3({code:t.code});X(e,D3(r),r,`Write applied in memory but failed to persist to disk (${t.code??`unknown error`}): ${t.message}. The content was NOT saved and will be lost if the server restarts.`,{handler:n})}function Svt(e){let{durabilityState:t}=e,n=!1,r=new Set;async function i(e,i){if(n)throw new wJ(i.startsWith(`/api/local-op/`));let a=t.runWithinWriteWaitBudget(e);r.add(a);try{await a}finally{r.delete(a)}}let a=e.assertContentSubtree,o=e.ingressPolicy??C$({}),c=(e,t,n)=>r9e(e,t,{...n,policy:o}),l=e=>T$(e,o),u=e=>w$(e,o),{hocuspocus:d,sessionManager:f,contentDir:p,getGeneratedIndexSettingsStatus:m,setGeneratedIndexEnabled:h,serverInstanceId:g,getFileIndex:_,getAttachmentFolderPath:v,getAllFilesIndex:y=_,mutateFileIndex:b=e=>_vt(e,y),getFileIndexGeneration:x,getFolderIndex:S,onReferencedAssetsCacheInvalidator:C,getAliasMap:w,getFolderAliasIndex:T,resolveTrackedFile:E,rescanFiles:D,localOpConcurrencyGuard:O,enableTestRoutes:ee=!1,shadowRef:A,flushGitCommit:j,flushContributors:M,getCurrentBranch:N,getReportedBranch:te,getDiskAckSVs:ne,getCollabClientCount:P,contentRoot:re,derivedDocumentIndex:ie,signalChannel:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se,onAgentWrite:ce,getSyncEngine:le,conflicts:ue,setBatchInProgress:de,localOpCliArgs:fe,authStreamHeartbeatMs:pe,projectDir:me,getBridgeLossReporter:he,getPrincipal:ge,homeDirOverride:_e,resetSettingsForTest:ve,settleDiskEventsForTest:ye,agentIntegrations:be,savedThemeLockTimeoutMs:xe,acpRegistry:Se,loadAcpCustomAgents:Ce,acpHarnessAvailability:we=Bet(),contentFilter:Te,installedAgentsProbe:Ee,forceUnloadDocument:De,onNamespaceCreateAccepted:Oe,captureNamespaceMove:ke,capturePublicationReceipt:Ae,onResidentAdopted:je,ready:Me,recentlyRemovedDocs:Ne,serializeDoc:Pe,evictManagedArtifactLkg:Fe,semanticSearch:Ie,getSemanticSimilarityFloor:Le,embeddingsSecretsFile:Re,readSemanticProviderConfig:Be,getLinterBaseConfig:Ve,getLinkAdvisoryPolicy:He,getProjectConfigEpoch:Ue,ephemeral:We=!1,linkPreviewFetch:Ge,getLinkPreviewsEnabled:Ke,resolveGitHubToken:Je,githubReferenceFetch:Ye,getConfigDiagnostics:Xe}=e,Ze=e.declaredGitHubHosts??G6(_e),$e=e.resolveSyncCredentialConfig??kft({projectDir:me??p,tokenStore:null,localOpCliArgs:fe,declaredGitHubHosts:Ze});function et(t,n,r){let i=h5(t,n,r);return e.assertContentPath?.(i),i}let tt=aot({homeDirOverride:_e,log:c5}),{bumpSkillsCatalogGen:nt,enumerateInstalledSkillsCached:rt,pluginSkillsByName:it}=tt,at=ae?e=>{e===`files`&&nt(),ae(e)}:void 0,ot=O??i9e(),st=Sct({hocuspocus:d,conflicts:ue,contentDir:p,isSafeDocName:E5,resolveAlias:wt,resolveContentEntryPath:et,resolveDocPath:ht,extractHeadings:gvt,getFileIndex:_,getFileIndexGeneration:x,log:c5,ready:Me,contentFilter:Te,safeSubdir:J_t,getShowAllMaxEntries:Q_t,streamShowAllEntries:p5,walkContentDirForShowAll:rvt,synthesizeShowAllAssetExt:u5,getAllFilesIndex:y,getFolderIndex:S,getFolderAliasIndex:T,onReferencedAssetsCacheInvalidator:C}),{invalidateReferencedAssetsCache:ct}=st;function lt(){let e=S?.();return e instanceof Map?e:null}function ut(e){let t=lt();if(t)try{let n=oc(e);QY(t,p,e,n,e)}catch(t){c5.warn({path:e,err:t},`folder index stat failed for ${e}`)}}function dt(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)ut(W(p,t.slice(0,e).join(`/`)))}function ft(e){let t=lt();t&&$Y(t,e)}function pt(e,t){let n=lt();if(!n)return;let r=[];for(let[i,a]of n.entries()){if(i!==e&&!i.startsWith(`${e}/`))continue;n.delete(i);let o=i.slice(e.length);r.push([`${t}${o}`,a])}if(r.length===0){let e=et(p,`folder`,t);G(e)&&ut(e);return}for(let[e,t]of r)n.set(e,{...t,modified:new Date().toISOString(),canonicalPath:W(p,e)})}let mt=ett({probe:Ee??P1(process.platform)});function ht(e){if(Rr(e))try{return A6(e,{projectDir:me??p,homedirOverride:_e})}catch{return null}if(!E5(e))return null;let t=W(p),n=WK(e),r=W(t,n);return nq(r,t)?r:null}let gt=new Jet({store:new Yet(W(p,`.ok`,yr),c5),index:new Vet,getDocBody:e=>{try{let t=d.documents.get(e);if(t)return Ba(t.getText(`source`).toString()).body}catch{}try{let t=ht(e);if(t&&G(t))return Ba(K(t,`utf-8`)).body}catch{}return null},getDocFrontmatter:e=>{try{let t=d.documents.get(e);if(t)return k(t.getText(`source`).toString())??{}}catch{}try{let t=ht(e);if(t&&G(t))return k(K(t,`utf-8`))??{}}catch{}return null}});e.commentDocHooksRef&&(e.commentDocHooksRef.current={changed:e=>{gt.refindDoc(e).then(e=>{e&&at?.(`comments`)}).catch(t=>{c5.warn({err:t,docName:e},`[comments] re-anchor after document change failed`)})},deleted:e=>{gt.deleteDoc(e).then(e=>{e>0&&at?.(`comments`)}).catch(t=>{c5.warn({err:t,docName:e},`[comments] cleanup after document delete failed`)})}});function _t(e){let t=ht(e);if(!t||!G(t))return e;try{return EY(K(t,`utf-8`),e)}catch{return e}}function vt(e,t){return t.has(e)?_t(e):e}let yt={cluster:void 0,category:void 0,tags:void 0};function bt(e){try{let t=d.documents.get(e);if(t){let e=Fee(t.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,n=typeof e.category==`string`?e.category:void 0,r;if(Array.isArray(e.tags)){let t=e.tags.filter(e=>typeof e==`string`);r=t.length>0?t:void 0}else typeof e.tags==`string`&&e.tags&&(r=[e.tags]);return{cluster:t,category:n,tags:r}}}}catch{}try{let t=ht(e);if(!t||!G(t))return yt;let n=K(t,`utf-8`),{frontmatter:r}=Ba(n);return r?z1e(r):yt}catch{return yt}}function xt(e,t){return t.has(e)?bt(e):yt}let St=I_t();async function Ct(e){if(ie?.isReady())try{let t=await St.run(`orphan-hints`,()=>ie.getBacklinks(e),()=>void 0);if(t===void 0||t.length>0)return;let n=performance.now(),r=Rrt(e,_()),i=performance.now()-n;return i>5&&c5.debug({docName:e,elapsedMs:i,candidateCount:r.length},`[orphan-hint] findHubCandidates slow`),r.length===0?void 0:[{type:`orphan`,parentCandidates:r,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${r.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){c5.warn({err:e},`[orphan-hint] computeOrphanHints failed`);return}}function wt(e){return w?.().get(e)??e}function Tt(e,t){let n=`onStoreDocument-${e}`;(d.debouncer.isDebounced(n)?d.debouncer.executeNow(n):Promise.resolve()).then(()=>j?.()).catch(e=>{c5.warn({err:e},`[${t}] post-write flush failed`)})}function Et(e,t){let n=`onStoreDocument-${e}`;d.debouncer.isDebounced(n)&&d.debouncer.executeNow(n).catch(e=>{c5.warn({err:e},`[${t}] post-write disk flush failed`)})}async function Dt(e){let n=`onStoreDocument-${e}`;d.debouncer.isDebounced(n)&&(t.markAgentWriteStore(e),await d.debouncer.executeNow(n));let r=Date.now(),i=await t.awaitDeferredStoreOutcome(e);switch(i?.kind){case void 0:case`completed`:break;case`discarded`:return{kind:`failure`,failure:{code:`OK_STORE_DISCARDED`,message:`A Git branch switch discarded the pending save of ${e}`}};case`failed`:return{kind:`failure`,failure:t.takeStoreFailure(e)??i.failure};case`unsettled`:{let t=Date.now()-r;console.warn(JSON.stringify({event:`agent-write-deferred-store-unsettled`,"doc.name":e,waitedMs:t,timestamp:new Date().toISOString()})),c5.warn({docName:e,waitedMs:t},`[agent-write] deferred store still pending after the wait; acknowledging before it reaches disk`);break}default:yot(i)}let a=t.takeStoreFailure(e);return a?{kind:`failure`,failure:a}:t.takeStaleExternalWriteFreeze(e)?{kind:`stale-external-write`}:t.takeStoreDivergence(e)?{kind:`divergence`}:null}function Ot(e,t){X(e,409,`urn:ok:error:disk-divergence`,`The document changed on disk after your edit was prepared; your edit was NOT applied, to avoid overwriting the newer on-disk content. Re-read the document and retry.`,{handler:t})}function kt(e){return{type:`urn:ok:error:stale-external-write`,title:`Edit retained; disk write blocked by a stale external-write conflict.`,detail:`An older version was restored on disk. Your edit was applied and is retained in memory and in the recovery snapshot, but its Markdown disk write was skipped. Do not repeat this edit: ask the user to resolve the conflict in the OpenKnowledge app, then re-read the document before making further changes.`,file:t.getStaleExternalWrite(e)?.file??U(me??p,fq(e,p)).replaceAll(`\\`,`/`),resolutionOptions:zJ}}function At(e,t,n){let{type:r,title:i,detail:a,...o}=kt(n);X(e,409,r,i,{handler:t,detail:a,extensions:o})}function jt(e){if(e.reconciled)return{kind:`disk-edit-reconciled`,intendedBytes:e.baseBytes,actualBytes:e.diskBytes,byteDelta:e.diskBytes-e.baseBytes,...e.mergeOutcome?{mergeOutcome:e.mergeOutcome}:{},hint:e.mergeOutcome===`merged`?'An out-of-band edit was three-way merged into this document before your edit was applied on top; the merge may have interleaved content blocks. Re-read it (e.g. `exec("cat <path>")`) and review the combined result carefully before continuing.':'An out-of-band edit was reconciled into this document before your edit was applied on top; the document now reflects that edit plus yours. Re-read it (e.g. `exec("cat <path>")`) to see the combined result before continuing.'}}function Mt(e){if(!Te)return!1;let t=WK(e);return Te.isExcluded(t)}function Nt(){return ie?.isReady()??!0}let Pt=async e=>{if(!Nt())return Cit;let t;try{t=await St.run(`link-check`,Ft,()=>null)}catch(e){return c5.warn({err:e},`[link-check] write link advisory failed post-write; skipping link checks`),wit}if(t===null)return wit;for(let n of e)t.add(n);let n={fileExists:Ut(),folderExists:Ht(),fileExcluded:Jt(),resolveWikiFile:Kt(),resolveFileByBasename:qt()};return(e,r,i)=>({links:Tit(R_t(e,r,t,n),r,i),warnings:[]})};async function Ft(){let e=new Set;for(let[t,n]of _()){e.add(t);for(let t of n.aliases)e.add(t)}try{for(let t of[`project`,`global`]){let n=W(t===`global`?Wn:p,`.ok`,ba);for(let r of ur(n,t).skills)e.add(`${Ai}${t}/${r.name}`)}}catch(e){c5.warn({err:e},`[collectAdmittedDocNames] managed-artifact enumeration failed`)}for(let t of await ie?.getIndexedDocNames()??[])e.has(t)||Mt(t)||e.add(t);return e}async function It(e,t){if(!(!ie||e.length===0))try{await ie.recordDirectMutations(e)}catch(n){zt(n,{count:e.length,reason:t},`[derived-index] failed to project durable document mutations`)}}async function Lt(e,t,n){if(ie)try{await ie.recordDirectDocument(e,t)}catch(t){zt(t,{documentName:e,reason:n},`[derived-index] failed to project durable document`)}}async function Rt(e,t,n){if(ie)try{await ie.recordLinkRewrite(e,t)}catch(t){zt(t,{documentName:e,reason:n},`[derived-index] failed to project link rewrite`)}}function zt(e,t,n){if(b4(e)){c5.debug({err:e,...t},`[derived-index] coordinator closed; skipping durable projection`);return}c5.warn({err:e,...t},n)}function Bt(e,t,n){if(b4(t)){X(e,503,`urn:ok:error:derived-index-unavailable`,`Derived index is shutting down.`,{handler:n.handler,cause:t,logLevel:`debug`});return}X(e,500,`urn:ok:error:internal-server-error`,n.failureTitle,{handler:n.handler,cause:t})}async function Vt(e,t){await It([...e].map(e=>({kind:`delete`,documentName:e})),t)}function Ht(){let e=S?.();if(!e)return()=>!1;let t=Li(`folder`,e.keys());return e=>t.resolve(e)!==void 0}function Ut(e=y()){return Kat(m4(e,T?.()??new Map,p).fileTargets,p,Te)}function Gt(){return m4(y(),T?.()??new Map,p,S?.())}function Kt(){let e;return t=>(e??=oa(Gt().fileTargets),e(t))}function qt(){let e;return(t,n)=>(e??=Gat(Gt().fileTargets),e(t,n))}function Jt(){return e=>o4(p,Te,e)}function Yt(e,t){Mt(e)||b?.({kind:_().has(e)?`update`:`create`,path:et(p,`file`,e),docName:e,content:t})}function Xt(){let e=Promise.resolve();return async function(t){let n=e,r=()=>{};e=new Promise(e=>{r=e}),await n;try{return await t()}finally{r()}}}let Zt=Xt(),Qt=e=>e.endsWith(`.`)?e:`${e}.`;function $t(e){return e instanceof Error?e instanceof fY?{status:404,type:`urn:ok:error:doc-not-found`,error:Qt(e.message)}:e instanceof pY?{status:409,type:`urn:ok:error:doc-already-exists`,error:Qt(e.message)}:e instanceof mY||e instanceof hY?{status:400,type:`urn:ok:error:invalid-request`,error:Qt(e.message)}:e instanceof gY?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Qt(e.message)}:e instanceof C1e||e instanceof S1e?{status:404,type:`urn:ok:error:doc-not-found`,error:Qt(e.message)}:uJ(e)?{status:400,type:`urn:ok:error:path-escape`,error:Qt(e.message)}:e instanceof _Y?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:Qt(e.message)}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}}async function en(e,n){let r=new Map;for(let t of e){let e=d.documents.get(t);e&&r.set(t,e.getText(`source`).toString())}for(let t of e){let e=d.documents.get(t);e&&e.getMap(`lifecycle`).set(`status`,n)}for(let t of e)await f.closeAllForDoc(t).catch(e=>{c5.warn({docName:t,err:e},`[file-ops] Failed to close agent session for ${t}`)});for(let n of e){let e=d.documents.get(n);t.deleteReconciledBase(n),Fe?.(n),e&&(d.closeConnections(n),await(De??d.unloadDocument.bind(d))(e))}return r}function tn(n,r){let i=d.documents.get(n);N9e(t,d,n,r,e.resolveEmbed,void 0,he?.())===`revived`&&i&&je?.(i,n)}function nn(e,t){for(let{fromDocName:n,toDocName:r}of e){let e=fq(r,p),i=t.get(n);typeof i==`string`&&C5(e,i);let a=typeof i==`string`?i:G(e)?K(e,`utf-8`):null;typeof a==`string`&&(LY(e,kY(a)),tn(r,a))}}function rn(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let r=fq(e,p);if(!G(r))throw new S1e(e);return{docName:e,content:K(r,`utf-8`)}})}function an(e){let t=d.documents.get(e);if(t)return t.getText(`source`).toString();let n=et(p,`file`,e);return G(n)?K(n,`utf-8`):null}function F(e,n,r){let i=r?Ae?.(r,e):void 0,a=et(p,`file`,e);kG(V(a),{recursive:!0});let o=C5(a,n);LY(a,kY(n)),t.setReconciledBase(e,n),o&&i?.(),b?.({kind:`update`,path:a,docName:e,content:n})}function on(e,t,n){let r=d.documents.get(e);if(!r)throw Error(`Document is not loaded: ${e}`);let i={markdown:``,rewrites:0};return r.transact(()=>{i=cn(r.getText(`source`).toString(),e,n.renames.get(e)??e,t,n),i.rewrites!==0&&dG(r,i.markdown,`managed-rename`,!1)},s5),i}function sn(e,t,n){let r=e,i=0;for(let{fromPath:e,toPath:a}of n){let n=v1e(r,t,e,a);r=n.markdown,i+=n.rewrites}return{markdown:r,rewrites:i}}function cn(e,t,n,r,i){let a=T1e(e,t,i),o=sn(a.markdown,n,r);return{markdown:o.markdown,rewrites:o.markdown===e?0:a.rewrites+o.rewrites}}function ln(e,t){let n=d.documents.get(e);if(!n)throw Error(`Document is not loaded: ${e}`);let r={markdown:``,rewrites:0};return n.transact(()=>{r=sn(n.getText(`source`).toString(),e,t),r.rewrites!==0&&dG(n,r.markdown,`managed-rename`,!1)},s5),r}function un(e){let t=[];if(e.length===0)return t;let n=[..._().keys()].sort((e,t)=>e.localeCompare(t));for(let r of n){let n=an(r);if(typeof n!=`string`)continue;let i=sn(n,r,e);i.rewrites!==0&&t.push({docName:r,markdown:i.markdown,rewrites:i.rewrites})}return t}function dn(e){for(let t of e){let e=ue.findByDocName(t);if(e!==void 0)throw new BJ({file:e.file})}}async function fn(e,t){let n=[],r=[];for(let i of e){let e=d.documents.get(i.docName),a=e?ln(i.docName,t):i;a.rewrites!==0&&(F(i.docName,a.markdown,e),r.push({kind:`link-rewrite`,documentName:i.docName,markdown:a.markdown}),n.push({docName:i.docName,rewrites:a.rewrites}))}return{rewrittenDocs:n,derivedMutations:r}}let pn=e=>oot(e,{contentDir:p,contentFilter:Te,docNameForPath:e=>y5(p,e)});function mn(e,t,n){let r=[];function i(e){for(let a of tc(e,{withFileTypes:!0})){let o=W(e,a.name),s=U(p,o).split(Rs).join(`/`);if(!h4(s)){if(a.isDirectory()){if(Te?.isDirExcluded(s))continue;i(o);continue}!a.isFile()||PK(s)||Te?.isExcluded(s)||(s===t?r.push({fromPath:s,toPath:n}):s.startsWith(`${t}/`)&&r.push({fromPath:s,toPath:`${n}${s.slice(t.length)}`}))}}}return i(e),r.sort((e,t)=>e.fromPath.localeCompare(t.fromPath)),r}async function hn(e,t){return Zt(async()=>oG(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async n=>{if(!ie)throw new _Y;let r=Ns(t)?t:`${t}${Ns(e)}`;if(h4(e)||h4(r))throw new gY(`.ok and .git are reserved directories.`);if(Te?.isPathIgnored(r))throw new hY(`Destination asset is excluded by the project content config.`);let i=et(p,`folder`,e),a=et(p,`folder`,r);if(i===a)return{renamedAssets:[],rewrittenDocs:[]};if(x5(e,r))throw new hY(`Case-only renames are not supported.`);if(!G(i))throw new fY(`asset`,`Asset does not exist.`);if(G(a))throw new pY;if(!oc(i).isFile())throw new mY(`asset`,`Source path is not an asset file.`);let o=[{fromPath:e,toPath:r}],s=un(o);n.setAttribute(`rename.rewrite_candidates`,s.length),dn(s.map(e=>e.docName)),await T5(me,i,a)||w5(i,a);let{rewrittenDocs:c,derivedMutations:l}=await fn(s,o);return await It(l,`asset-rename`),at?.(`files`),c.sort((e,t)=>e.docName.localeCompare(t.docName)),n.setAttribute(`rename.rewrite_count`,c.length),{renamedAssets:o,rewrittenDocs:c}}))}async function gn(e,n){return Zt(async()=>oG(`rename.executeDocumentToFileRewrites`,{attributes:{"rename.kind":`asset`,"rename.transition":`document-to-file`}},async r=>{if(!ie)throw new _Y;if(!PK(e)||PK(n))throw new hY(`Document-to-file rename requires a markdown source and non-markdown destination.`);let i=LK(e);if(KK(i)||qK(i))throw new gY(`Reserved document names cannot be renamed.`);if(h4(e)||h4(n))throw new gY(`.ok and .git are reserved directories.`);if(Te?.isPathIgnored(n))throw new hY(`Destination file is excluded by the project content config.`);let a=et(p,`folder`,e),o=et(p,`folder`,n);if(a===o)return{renamedAssets:[],rewrittenDocs:[]};if(x5(e,n))throw new hY(`Case-only renames are not supported.`);if(!G(a))throw new fY(`file`);if(G(o))throw new pY;if(!oc(a).isFile())throw new mY(`file`,`Source path is not a document file.`);let s=ue.findByDocName(i);if(s!==void 0)throw new BJ({file:s.file});let c=[{fromPath:e,toPath:n}],l=un(c).filter(e=>e.docName!==i);r.setAttribute(`rename.rewrite_candidates`,l.length),dn(l.map(e=>e.docName)),r1(t,d,i,p,void 0,he?.(),ue),Ne&&!KK(i)&&!qK(i)&&Ne.setDeleted(i);let u=(await en([i],`renamed`)).get(i),f=typeof u==`string`?u:K(a,`utf-8`),m=Xgt({fromPath:e,toPath:n,affectedDocs:[{from:i,to:i}],snapshots:[{docName:i,content:f}],cleanupPaths:[n]}),h=[];return await s_t(me??p,m,async()=>{C5(a,f),LY(a,kY(f)),await T5(me,a,o)||w5(a,o),GK(i),b?.({kind:`delete`,path:a,docName:i});let e=oc(o);b?.({kind:`file-create`,path:o,relativePath:n,size:e.size,modifiedTs:e.mtimeMs,inode:e.ino});let t=await fn(l,c);h=t.rewrittenDocs,await It([{kind:`delete`,documentName:i},...t.derivedMutations],`document-to-file-rename`),at?.(`files`)}),h.sort((e,t)=>e.docName.localeCompare(t.docName)),r.setAttribute(`rename.rewrite_count`,h.length),{renamedAssets:c,rewrittenDocs:h}}))}async function _n(e,n,r,i){return Zt(async()=>oG(`rename.executeRewrites`,{attributes:{"rename.kind":r}},async o=>{if(!ie)throw new _Y;let s=et(p,r,e),c=et(p,r,n);if(s===c)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!G(s))throw new fY(r);if(G(c)&&!mvt(s,c))throw new pY;let l=oc(s);if(r===`file`&&!l.isFile()||r===`folder`&&!l.isDirectory())throw new mY(r);r===`folder`&&(dq(s,p),a?.(s));let u=r===`folder`?mn(s,e,n):[];o.setAttribute(`rename.affected_assets`,u.length);let f=(r===`file`?[y5(p,e)]:pn(s)).map(t=>({from:t,to:r===`file`?y5(p,n):avt(t,r,e,n)}));if(o.setAttribute(`rename.affected_docs`,f.length),f.length===0){let t=un(u);dn(t.map(e=>e.docName)),r===`folder`&&(await T5(me,s,c)||w5(s,c),pt(e,n),at?.(`files`));let{rewrittenDocs:i,derivedMutations:a}=await fn(t,u);return await It(a,`asset-only-folder-rename`),i.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:[],renamedAssets:u,rewrittenDocs:i}}let m=w1e(f),h=f1e(new Set([..._().keys(),...await ie.getIndexedDocNames(),...m.keys()]),m),g=f.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),v=new Set;for(let{from:e}of f)for(let t of await ie.getBacklinks(e))m.has(t.source)||v.add(t.source);let y=new Map,x=new Set,S=await ie.getRenameSourceInventory(),C=new Set(S.map(({docName:e})=>e)),w=new Set(d.documents.keys());for(let e of h.before.pages)C.has(e)||w.add(e);let T=[];for(let{docName:e,wikiTargets:t,indexedMtimeMs:n}of S)t.some(t=>m1e(t,e,h)!==null)&&w.add(e),w.has(e)||T.push({docName:e,indexedMtimeMs:n});for(let e=0;e<T.length;e+=128){let t=T.slice(e,e+128),n=await Promise.allSettled(t.map(async({docName:e,indexedMtimeMs:t})=>{try{let n=et(p,`file`,e);return t===(await Sc(n)).mtimeMs?null:e}catch(t){if(d2(t))return null;let n=t instanceof Error&&`code`in t?t.code:`unknown`;throw Error(`Rename discovery could not check ${e} (${n})`,{cause:t})}}));for(let e of n){if(e.status===`rejected`)throw e.reason;e.value&&w.add(e.value)}}for(let e of w){if(m.has(e)||eq(e)||Mt(e))continue;let n;try{n=et(p,`file`,e)}catch(e){if(d2(e))continue;throw e}if(!G(n))continue;r1(t,d,e,p,void 0,he?.(),ue);let r=an(e);typeof r==`string`&&h1e(Ba(r).body,e,h).rewrites>0&&(v.add(e),y.set(e,r),x.add(e))}let E=[...v].sort((e,t)=>e.localeCompare(t)),D=new Set,O=[];for(let e of[...m.keys(),...E]){if(y.has(e))continue;if(!m.has(e)){let t=et(p,`file`,e);if(!G(t)){O.push(e);continue}}r1(t,d,e,p,void 0,he?.(),ue);let n=an(e);typeof n==`string`?(y.set(e,n),m.has(e)||x.add(e)):m.has(e)||O.push(e)}if(u.length>0){let e=[..._().keys()].sort((e,t)=>e.localeCompare(t));for(let t of e){let e=y.get(t)??an(t);typeof e==`string`&&cn(e,t,m.get(t)??t,u,h).rewrites!==0&&(y.has(t)||y.set(t,e),D.add(t),m.has(t)||x.add(t))}}dn(D);for(let{from:e}of f)if(typeof y.get(e)!=`string`)throw new C1e(e);let k=Xgt({fromPath:e,toPath:n,affectedDocs:[...f],snapshots:rn([...y.keys()],y)}),ee=[],j=[...x].sort((e,t)=>e.localeCompare(t)),M=[];return await s_t(me??p,k,async()=>{for(let e of O)M.push({kind:`delete`,documentName:e});for(let e of j){let t=d.documents.get(e),n=t?on(e,u,h):cn(y.get(e)??``,e,e,u,h);n.rewrites>0&&(F(e,n.markdown,t),ee.push({docName:e,rewrites:n.rewrites})),M.push({kind:`link-rewrite`,documentName:e,markdown:n.markdown})}if(Ne)for(let{from:e,to:t}of f)KK(e)||qK(e)||(Ne.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let a=et(p,r,e),o=et(p,r,n),s=f.map(({to:e})=>ke?.(e));await T5(me,a,o)||w5(a,o);for(let e of s)e?.();r===`folder`&&pt(e,n);let c=await en([...m.keys()],`renamed`);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(A?.current){let e=A.current,t=f.filter(({from:e,to:t})=>LK(e)!==LK(t));t.length>0&&sG(`rename.appendLog`,{attributes:{"rename.kind":r}},n=>{let a=Ec(),o=new Date().toISOString(),s=N?.()??`main`,c=d1(e.gitDir),l=i?.actor?{writerId:i.actor.writerId,displayName:i.actor.displayName}:{writerId:wK.id,displayName:wK.name},u=0;for(let{from:n,to:d}of t){let t={v:1,from:n,to:d,at:o,commitSha:``,branch:s,groupId:a,kind:r,actor:l};Q9e(e.gitDir,t,c,e),u+=1,i?.actor?G$(d,i.actor.writerId,i.actor.displayName,i.actor.colorSeed,zS(n,d),i.actor.actorMetadata,void 0,[{from:n,to:d}]):G$(d,wK.id,wK.name,wK.id,zS(n,d),void 0,void 0,[{from:n,to:d}])}n.setAttribute(`rename.entries_appended`,u)})}let l=r===`file`&&PK(n)?Ns(n):null;for(let{from:e,to:t}of f){let n=PK(e)?Ns(e):VK(e);GK(e),BK(t,l??n)}let g=[...f].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:n}of g){let r=et(p,`file`,e),i=et(p,`file`,n),a=cn(c.get(e)??y.get(e)??K(i,`utf-8`),e,n,u,h);nn([{fromDocName:e,toDocName:n}],new Map([[e,a.markdown]])),t.setReconciledBase(n,a.markdown),b?.({kind:`rename`,oldPath:r,newPath:i,oldDocName:e,newDocName:n,content:a.markdown}),M.push({kind:`rename`,oldDocumentName:e,newDocumentName:n,markdown:a.markdown});try{await gt.renameDoc(e,n)}catch(t){c5.warn({err:t,fromDocName:e,toDocName:n},`[comments] cover-sheet rename failed; index updated, disk self-corrects at boot`)}a.rewrites>0&&ee.push({docName:n,rewrites:a.rewrites})}if(await It(M,`document-rename`),process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-journal-clear`)throw Error(`OK_TEST_RENAME_FAULT=pre-journal-clear`)}),at?.(`files`),ee.sort((e,t)=>e.docName.localeCompare(t.docName)),o.setAttribute(`rename.rewrite_count`,ee.length),{renamed:g,renamedAssets:u,rewrittenDocs:ee}}))}function vn(e){let t=mqe(e),n=t.suppliedWriterId??`claude-1`;return{rawAgentId:t.rawAgentId,suppliedWriterId:t.suppliedWriterId,agentId:n,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??n,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function yn(e){return{principalId:ge?.()?.id,agentType:qW(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function bn(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function xn(e){return{value:e.value}}function Sn(e,t=!1){e.kind===`value`&&(gJe(),e.truncatedFrom!==void 0&&!t&&_Je())}function Cn(e,t,n,r){if(n.length!==0)switch(e.kind){case`agent`:{let r=e.summary.kind===`value`,i=r?e.summary:_$(t),a=bn(i),o=r||!a.response?a.response:xn(a.response);for(let t=0;t<n.length;t++){let{docName:r,subject:i}=n[t];G$(r,e.writerId,e.displayName,e.colorSeed,i,e.actor,t===0?a.stored:void 0)}nK(),Sn(i,!r);for(let{docName:e}of n)Tt(e,`rename-path`);return o}case`principal`:{let t=bn(e.summary);for(let r=0;r<n.length;r++){let{docName:i,subject:a}=n[r];G$(i,e.writerId,e.displayName,e.colorSeed,a,e.actor,r===0?t.stored:void 0)}Sn(e.summary,!1);for(let{docName:e}of n)Tt(e,`rename-path`);return t.response}case`anonymous`:r.onAnonymous?.();return;default:{let t=e;throw Error(`Unhandled actor kind in ${r.context}: ${String(t.kind)}`)}}}function wn(e,t,n){let r=t.replace(/\/$/,``),i=r===``?``:`${r}/`;return e===`template`?`${i}.ok/templates/${n}`:e===`skill`?`${Zn(String(n))}/SKILL`:e===`folder-frontmatter`?`${i}.ok/frontmatter`:r===``?`.`:r}function Tn(e,t,n,r){if(e.kind!==`agent`&&e.kind!==`principal`)return;let i=bn(e.summary);G$(t,e.writerId,e.displayName,e.colorSeed,n,e.actor,i.stored,r)}let En=null;function Dn(){Te&&(En!==null&&clearTimeout(En),En=setTimeout(()=>{En=null,Te?.rebuildIgnorePatterns().catch(()=>{})},12e4))}function On(){nt(),Te?.refreshInPlaceSkillDirs(),Dn()}function kn(){On(),at?.(`files`)}let An=Promise.resolve();function jn(e){nt(),An=An.then(async()=>{await Mn(e)}).catch(()=>{})}async function Mn(e){if(!M)return`unavailable`;try{return await M(),`flushed`}catch(t){return c5.warn({context:e,err:t},`[${e}] flushContributors failed; attribution stays queued for the next flush`),`failed`}}let Nn=Z(Gre,async(n,r,i)=>{try{let n=m5(i.docName,r,`agent-write`);if(n===null)return;let a=wt(n),{agentId:o,suppliedWriterId:s,agentName:c,colorSeed:l,clientName:u,clientVersion:m,label:h}=vn(i);if(KK(a)||qK(a)){X(r,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`agent-write`});return}let g=_$(i.summary),_=await f.getSession(a,o,{displayName:c,colorSeed:l,clientName:u}),v=r1(t,d,a,p,e.resolveEmbed,he?.(),ue),y=new Date().toISOString(),b=typeof i.content==`string`?i.content:`Hello from the agent! ${y}`,{response:x,stored:S}=bn(g),C;try{let t=Yn(u),n=eo[t]??ze(l??o);se?.setPresence(o,{displayName:c,icon:t,color:n,currentDoc:a,mode:`writing`,ts:Date.now()}),C=U$(_.dc.document.getText(`source`),o,_.origin,l,u),NZ(_.dc.document,`${b}\n`,`append`),_.dc.document.transact(()=>{let t=FZ(_.dc.document);PZ(_.dc.document,`${b}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:a}:void 0,void 0,MZ(_),s);let n=Bc(t,FZ(_.dc.document))??void 0;_.dc.document.getMap(`agent-flash`).set(o,{agentId:o,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${b.slice(0,50)}`,...n===void 0?{}:{changedBlocks:n}})},_.origin),G$(a,o,c,l,void 0,yn({clientName:u,clientVersion:m,label:h}),S),nK(),Sn(g)}finally{C?.(),se?.touchMode(o,`idle`)}let w=await Dt(a);if(w?.kind===`failure`){D5(r,w.failure,`agent-write`);return}if(w?.kind===`divergence`){Ot(r,`agent-write`);return}if(w?.kind===`stale-external-write`){At(r,`agent-write`,a);return}Et(a,`agent-write`),ce?.();let T=jt(v);Q(r,200,qne,{timestamp:y,...x?{summary:x}:{},...T?{warnings:[T]}:{}},{handler:`agent-write`})}catch(e){if(e instanceof BJ){VJ(r,e,`agent-write`,ue.findByDocName(LK(e.file)));return}if(e instanceof NX){PX(r,e,`agent-write`);return}if(e instanceof LZ){y1(r,e,`agent-write`);return}c5.error({err:e,requestId:DJ(n)},`[agent-write] handler failed`),X(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),Pn=Z(Bee,async(n,r,i)=>{try{let a=He(),{agentId:o,suppliedWriterId:s,agentName:c,colorSeed:l,clientName:u,clientVersion:m,label:h}=vn(i),g=new Date().toISOString(),_=(e,t,n,r,i)=>({status:`error`,docName:e,error:{type:t,title:n,...r===void 0?{}:{detail:r},...i}}),v=(e,t)=>{if(t instanceof MJ)return NJ(t,`agent-write-batch`),_(e,jJ,r$e,a$e,{retryAfterSeconds:3});if(t instanceof BJ){console.warn(JSON.stringify({event:`doc-in-conflict-write-refused`,handler:`agent-write-batch`,"doc.name":e}));let{detail:t,...n}=h$e(ue.findByDocName(e));return{status:`error`,docName:e,error:{type:`urn:ok:error:doc-in-conflict`,title:`Document is in conflict.`,detail:t,...n}}}return t instanceof NX?(t2e(t,`agent-write-batch`),_(e,`urn:ok:error:frontmatter-malformed`,`Frontmatter YAML is malformed.`,e2e(t))):t instanceof LZ?_(e,xet,Cet,wet,Tet):(c5.error({err:t,docName:e,requestId:DJ(n)},`[agent-write-batch] entry failed`),_(e,`urn:ok:error:internal-server-error`,`Internal server error.`))},y=Array(i.docs.length),b=[];try{let n=Yn(u),r=eo[n]??ze(l??o);se?.setPresence(o,{displayName:c,icon:n,color:r,currentDoc:wt(i.docs[0].docName),mode:`writing`,ts:Date.now()}),await f.withSessions(async n=>{for(let r=0;r<i.docs.length;r++){let a=i.docs[r],f=wt(a.docName);if(KK(f)||qK(f)){y[r]=_(f,`urn:ok:error:reserved-doc-name`,`'${f}' is a reserved document name.`);continue}try{a.extension!==void 0&&!_5(p,f)&&BK(f,a.extension);let i=_$(a.summary),{response:g,stored:_}=bn(i),v=await n(f,o,{displayName:c,colorSeed:l,clientName:u}),y=r1(t,d,f,p,e.resolveEmbed,he?.(),ue),x=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:f}:void 0,S=await jZ(v.dc.document,a.markdown,a.position??`append`,x),C,w=U$(v.dc.document.getText(`source`),o,v.origin,l,u);NZ(v.dc.document,a.markdown,a.position??`append`);try{v.dc.document.transact(()=>{let e=FZ(v.dc.document);C=PZ(v.dc.document,a.markdown,a.position??`append`,x,S,MZ(v),s);let t=Bc(e,FZ(v.dc.document))??void 0;v.dc.document.getMap(`agent-flash`).set(o,{agentId:o,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${a.markdown.trim().slice(0,50)}`,...t===void 0?{}:{changedBlocks:t}})},v.origin)}finally{w()}G_t(`agent-write-batch`,C),G$(f,o,c,l,void 0,yn({clientName:u,clientVersion:m,label:h}),_),nK(),Sn(i);let T=jt(y),E=[...C===void 0?[]:[MX(C)],...T?[T]:[]];b.push({index:r,docName:f,session:v,summaryResponse:g,warnings:E})}catch(e){y[r]=v(f,e)}}let r=new Map;for(let e of b){if(r.has(e.docName))continue;let t=await Dt(e.docName);if(t?.kind===`failure`){if(t.failure.code===`OK_DOC_REMOVED`)r.set(e.docName,vvt(t.failure));else if(t.failure.code===`OK_PATH_UNRESOLVABLE`)r.set(e.docName,yvt(t.failure));else if(t.failure.code===`OK_STORE_REFUSED`)r.set(e.docName,xvt(t.failure));else if(t.failure.code===`OK_STORE_DISCARDED`)r.set(e.docName,bvt(t.failure));else{let n=O3({code:t.failure.code});r.set(e.docName,{type:n,title:`Write applied in memory but failed to persist to disk.`,detail:`${t.failure.code??`unknown error`}: ${t.failure.message}. The content was NOT saved and will be lost if the server restarts.`})}}else t?.kind===`divergence`?r.set(e.docName,{type:`urn:ok:error:disk-divergence`,title:`The document changed on disk after your edit was prepared; your edit was NOT applied. Re-read the document and retry.`}):t?.kind===`stale-external-write`?r.set(e.docName,kt(e.docName)):r.set(e.docName,void 0)}let f=await Pt(b.filter(e=>r.get(e.docName)===void 0).map(e=>e.docName)),g;for(let e of b){let t=r.get(e.docName);if(t!==void 0){y[e.index]={status:`error`,docName:e.docName,error:t};continue}let n=e.session.dc.document.getText(`source`).toString();Yt(e.docName,n);let i=f(n,e.docName,a.suppressLogLinkAdvisories),o=[...e.warnings,...i.warnings];y[e.index]={status:`written`,docName:e.docName,...e.summaryResponse?{summary:e.summaryResponse}:{},...o.length>0?{warnings:o}:{},...i.links},g=e.docName}g!==void 0&&(oe?.setFocus(o,{agentName:c,currentDoc:g,writeKind:`write`,ts:Date.now()}),ce?.())})}finally{se?.touchMode(o,`idle`)}let x=y.map((e,t)=>e??_(i.docs[t].docName,`urn:ok:error:internal-server-error`,`Internal server error.`)),S=x.filter(e=>e.status===`written`).length;Q(r,200,eee,{timestamp:g,results:x,written:S,failed:x.length-S},{handler:`agent-write-batch`})}catch(e){c5.error({err:e,requestId:DJ(n)},`[agent-write-batch] handler failed`),X(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-batch`,cause:e})}},{handler:`agent-write-batch`,method:`POST`}),Fn=M_t(),In=x_t({contentDir:p,assertContentPath:e.assertContentPath,isPathIgnored:e=>Te?.isPathIgnored(e)??!1,getAttachmentFolderPath:v,resolveTrackedFile:E}),Ln=Nct({assertContentSubtree:a,contentDir:p,resolveContentEntryPath:et,docNameForPath:e=>y5(p,e),docNameToRelativePath:WK,listManagedDocNamesUnderFolder:e=>pn(e),listAffectedDocNames:(e,t,n)=>ivt(e,t,n),getFileIndex:_,conflictFileForDocName:e=>ue.findByDocName(e)?.file??null,captureAndCloseDocuments:en,markRecentlyRemoved:Ne?e=>Ne.setDeleted(e):void 0,mutateFileIndexDelete:b?({path:e,docName:t})=>b({kind:`delete`,path:e,docName:t}):void 0,removeFolderIndexEntries:ft,upsertFolderIndexPathSegments:dt,deleteDerivedDocumentsBestEffort:Vt,invalidateReferencedAssetsCache:ct,signalFiles:()=>at?.(`files`),nextAvailableDuplicateDocName:e=>uvt(p,e),nextAvailableDuplicateFolderPath:e=>dvt(p,e),resolveDuplicateDocPath:(t,n)=>{let r=lvt(p,t,n);return e.assertContentPath?.(r),r},collectMarkdownCopies:e=>fvt(p,e),collectFolderPaths:e=>pvt(p,e),contentFilter:Te??void 0,unmarkRecentlyRemoved:Ne?e=>Ne.delete(e):void 0,mutateFileIndexCreate:b?({path:e,docName:t,content:n})=>{Oe?.(t),b({kind:`create`,path:e,docName:t,content:n})}:void 0,recordDerivedDocumentBestEffort:Lt,recordDerivedMutationsBestEffort:It});function Rn(e,t,n,r,i){let a=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(a.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return X(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let o=W(p),s=a===``?o:W(o,a);if(s!==o&&!s.startsWith(`${o}${Rs}`))return X(t,400,`urn:ok:error:path-escape`,`Path escapes content directory.`,{handler:r}),null;let c=W(s,`.ok`);if(cJ(c).kind===`symlink`)return X(t,400,`urn:ok:error:symlink-refused`,`${a||`.`}/.ok is a symlink — refusing to operate through it. Replace the symlink with a real file or directory and retry.`,{handler:r,detail:a||`.`}),null;let l=W(s,`.ok`,`templates`);if(i===`ok-and-templates`&&cJ(l).kind===`symlink`)return X(t,400,`urn:ok:error:symlink-refused`,`${a||`.`}/.ok/templates is a symlink — refusing to operate through it. Replace the symlink with a real file or directory and retry.`,{handler:r,detail:a||`.`}),null;try{sJ(c,o),i===`ok-and-templates`&&sJ(l,o)}catch(e){return uJ(e)?(X(t,400,`urn:ok:error:path-escape`,`Path escapes content directory.`,{handler:r,cause:e}),null):(X(t,500,`urn:ok:error:internal-server-error`,`Failed to validate path.`,{handler:r,cause:e}),null)}return{folderRel:a,resolvedContentDir:o}}function zn(e,t,n){let r=ue.findByDocName(e);return r!==void 0&&(VJ(n,new BJ({file:r.file}),t,r),!0)}let Bn=e=>{let{body:t}=Ba(e);return{frontmatter:k(e)??{},body:t}};function Vn(e){return!!e&&e.length<=64&&no.test(e)}function Hn(e,t,n,r){return Vn(e)?!0:(X(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n,...r?{extensions:r}:{}}),!1)}function Un(e,t,n){let r=Kte.safeParse(e??`project`);return r.success?r.data:(X(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let Wn=_e??dc(),Gn=j_t({contentDir:p,skillsHome:Wn,effectiveInstallMode:Xn});function Kn(e){return W(e===`global`?Wn:p,`.ok`,ba)}function qn(e,t,n){let r=W(Kn(e),t);if(e===`global`){if(n!==void 0){let e=b0(Wn).find(e=>e.name===t&&e.hosts.includes(n));return e?W(Wn,e.dir):null}let e=S0(Wn,t);return e===null?G(H(r,`SKILL.md`))?r:null:e}let i=y0(p).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?W(p,i.dir):n===void 0&&G(H(r,`SKILL.md`))?r:null}function Jn(e,t){let n=e.searchParams;return v$({agentId:n.get(`agentId`)??void 0,agentName:n.get(`agentName`)??void 0,colorSeed:n.get(`colorSeed`)??void 0,clientName:n.get(`clientName`)??void 0,clientVersion:n.get(`clientVersion`)??void 0,label:n.get(`label`)??void 0,summary:n.get(`summary`)??void 0},t)}function Xn(e,t,n){let r=e===`project`?me:Wn;return(r?Bnt(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function Zn(e){let t=qn(`project`,e);return t?U(p,t).split(Rs).join(`/`):`${qa}/${e}`}function Qn(e,t,n,r){let i=[],a=null,o=B0(n),s=[...V0(n).map(e=>({id:e,root:o[e]??``})),{id:`agents`,root:oi}];for(let{id:n,root:o}of s){if(!o)continue;let s=W(e,...o.split(`/`),t);G(W(s,`SKILL.md`))&&(i.push(n),(r===void 0?a===null:n===r)&&(a=s))}if(a===null)return null;let c=W(a,`SKILL.md`);return{dir:a,skillMd:c,hosts:i,relPath:U(e,c).split(/[\\/]/).filter(Boolean).join(`/`)}}function I(e){let t=lNe(e.source,e.pluginProvider);return{source:e.source,...e.publisher===void 0?{}:{publisher:e.publisher},...e.skill===void 0?{}:{skill:e.skill},...t?{marketplaceUrl:t}:{},importedAt:e.importedAt,...e.autoUpdate===void 0?{}:{autoUpdate:e.autoUpdate}}}function $n(e,t,n){if(!BZ(t))return null;let r=Qn(e,t,n);if(!r)return null;let i=iP(r.dir)?.contentHash??``,a;try{a=oc(r.skillMd).mtime.toISOString()}catch{a=new Date(0).toISOString()}return{source:Qe,skill:t,contentHash:i,autoUpdate:!1,importedAt:a}}function er(e,t){return it(t).get(e)?.contentHash??null}function tr(e,t,n){let r=it(t).get(e);if(!r)return null;try{if(nc(n)!==nc(r.home))return null}catch{return null}return{name:r.plugin,marketplace:r.marketplace,provider:r.provider,...r.repositoryUrl?{url:r.repositoryUrl}:{}}}function nr(e,t,n){let r=it(t).get(e);if(!r)return null;if(n!==void 0)try{if(nc(n)===nc(r.home))return null}catch{}let i;try{i=oc(H(r.home,`SKILL.md`)).mtime.toISOString()}catch(e){c5.warn({err:e,home:r.home},`plugin bundle unreadable; origin dated epoch`),i=new Date(0).toISOString()}return{source:r.home,skill:e,contentHash:r.contentHash,autoUpdate:!1,importedAt:i}}function rr(e,t){let n=VZ.find(t=>RZ[t]===e);if(n===void 0||t!==void 0&&HZ[n]!==(t===`global`?`user`:`project`))return null;try{let e=WZ(n,{checkDesktop:!0}),t=W(e,`SKILL.md`);return G(t)?t:null}catch(t){return c5.warn({name:e,err:t},`[skills] bundle asset dir unresolved for built-in ${e}`),null}}function ir(e,t,n){let r=Qn(e,t,n),i=r?.skillMd??rr(t);if(i===null)return null;let a;try{let{frontmatter:e}=Bn(K(i,`utf-8`));typeof e.description==`string`&&(a=e.description)}catch{}let o=$n(e,t,n),s=iP(V(i));return{name:t,...a===void 0?{}:{description:a},scope:n,path:r?.relPath??i,absolutePath:i,installed:(r?.hosts.length??0)>0,hosts:r?.hosts??[],managed:!0,...s?{size:Ua(s)}:{},...o?{origin:I(o)}:{}}}function ar(e,t,n){return BZ(e)?(X(t,400,`urn:ok:error:reserved-doc-name`,`"${e}" is one of OpenKnowledge's runtime skills — its content is read-only in-app (updates arrive via reimport). Duplicate it under a new name to make your own version.`,{handler:n}),!0):!1}function or(e,t){return U(t===`global`?Wn:p,e).split(/[\\/]/).filter(Boolean).join(`/`)}function sr(e){return e===`global`?Wn:me}function cr(e,t,n,r){let i=n===`project`?p:Wn;if(r.purge!==void 0){$0(t,e,V0(n),B0(n));for(let e of int(i,n,t,r.purge.contentHash))FG(e,{recursive:!0,force:!0});return}if(!G(W(Kn(n),t,`SKILL.md`))){let r=(n===`project`?y0(p):b0(Wn)).find(e=>e.name===t);if(r){let i=n===`project`?p:Wn,a=W(i,r.dir),o=W(i,`.agents`,`skills`),s=H(o,t);if(G(o)&&!G(H(s,`SKILL.md`))){let e=!1;try{e=nc(a)===nc(s)}catch{e=!1}e||jG(a,s,{recursive:!0,dereference:!0})}Q0({canonicalAbs:G(H(s,`SKILL.md`))?s:a,canonicalHash:r.contentHash,name:t,cwd:e,targets:[...V0(n)],roots:B0(n)});return}}$0(t,e,V0(n),B0(n))}async function lr(e,t,n,r={}){return cr(e,t,n,r),await D0(e,t)!==null}function ur(e,t){let n=[];if(!G(e))return{skills:n,truncated:!1};let r;try{r=tc(e,{withFileTypes:!0})}catch(r){return q(`skills`).warn({err:r,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:n,truncated:!1}}let i=!1;for(let a of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!a.isDirectory()||!no.test(a.name))continue;if(n.length>=500){i=!0;break}let r=W(e,a.name,`SKILL.md`);if(!G(r))continue;let o;try{let{frontmatter:e}=Bn(K(r,`utf-8`));typeof e.description==`string`&&(o=e.description)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:or(r,t),absolutePath:r})}return{skills:n,truncated:i}}function dr(e,t,n){let r=e===`project`?p:Wn,i=qn(e,t,n);return{root:i===null?Kn(e):V(i),dirRel:i===null?`.ok/skills/${t}`:U(r,i).split(Rs).join(`/`),realDir:i}}function fr(e,t){return iP(W(e,t))?.contentHash}async function pr(e,t){let n=A?.current;if(!(!n||!e))try{let r=gK(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
2079
- `).filter(Boolean).find(t=>t.endsWith(`/${e}`));if(t)return(await r.raw(`rev-parse`,t)).trim()},a=async(e,t)=>(await r.raw(`ls-tree`,`-r`,`--name-only`,e,...Wt([t]))).trim().length>0,o=await i();return o!==void 0&&t!==void 0&&!await a(o,t)&&(await Mn(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let mr=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function hr(e){try{let t=sr(e.scope);if(!t)return;let n=z0(t);if(n.length===0)return;let r=q0(W(e.skillsRoot,e.name),e.name,t,n,`copy`,B0(e.scope));if(r.length===0)return;await E0(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){c5.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}let gr=Ert({contentDir:p,skillsHome:Wn,...me===void 0?{}:{projectDir:me},resolveSkillDirForRead:qn,parseFrontmatterDoc:Bn,attributeOkArtifactWrite:Tn,commitOkArtifactWrite:Mn,shadowHeadSha:pr,artifactWriterId:mr,effectiveInstallMode:Xn,signalFiles:()=>at?.(`files`)}),_r=Art({contentDir:p,skillsHome:Wn,...me===void 0?{}:{projectDir:me},legacyStoreRoot:qa,effectiveSkillRoot:dr,parseFrontmatterDoc:Bn,attributeOkArtifactWrite:Tn,commitOkArtifactWrite:Mn,shadowHeadSha:pr,artifactWriterId:mr,skillArtifactKey:e=>wn(`skill`,``,e),captureAndCloseDocuments:en,projectImportedSkillCopy:hr,signalFiles:()=>at?.(`files`)}),vr=Z(yie,async(e,t,n)=>{try{if(!Hn(n.name,t,`skill-uninstall`))return;let e=sr(n.scope);if(!e){X(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await lr(e,n.name,n.scope);at?.(`files`),Q(t,200,ree,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,...K_t(e)===void 0?{}:{detail:K_t(e)},cause:e})}},{handler:`skill-uninstall`,method:`POST`}),L=A_t({contentDir:p,projectDir:me,getAllFilesIndex:y,getFileIndexGeneration:x,getSearchMaxEntries:evt,semanticSearch:Ie,getSemanticSimilarityFloor:Le,ready:Me,getProjectSkillsRoot:()=>Kn(`project`),parseFrontmatterDoc:Bn});L.prewarm();let br=0;function tee(){br+=1,at?.(`lint-config`)}let nee=()=>oit({lintConfigEpoch:br,projectConfigEpoch:Ue(),activeBranch:t.getActiveBranch(),localTargetGeneration:ie?.readLocalTargetGeneration?.()??0});async function xr(e,t,n){let r=Ve?.()??s;try{let i=x2(p,r,{docName:t,projectDir:me??p,onProblem:e=>c5.warn({problem:e,docName:t},`[lint] native config problem`)}),a=await qe(e,i,t),o=[];if(ie?.isReady()&&n.links!==`off`&&!$K(t)){let i=ie;o=await St.run(`lint-links`,async()=>{await Rt(t,e,`lint-validation`);let a=Zat({projectDir:me??p,contentDir:p,baseConfig:r,derivedDocumentIndex:i,linkPolicy:n,admittedDocNames:Ft,docFilePathFor:e=>v5(p,e),localTargetInventory:Gt}).find(e=>e.id===`links`);return a?(await a.run({targetPath:v5(p,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics):[]},()=>[])}return[...a,...o].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return c5.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Sr(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=C2({projectDir:me??p,contentDir:p});return Grt(t.schemas,n)}let Cr={"/api/skill/uninstall":vr,"/api/agent-write":Nn,"/api/agent-write-batch":Pn},wr=new Set([`/api/agent-write`,`/api/agent-write-batch`,`/api/test-reset`,`/api/test-flush-git`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`,`/api/skill/uninstall`]),Tr={resolve(e){let t=Cr[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:{template:`/api/*`}},isMutating:e=>wr.has(e)},Er=m9e({log:c5,policy:o,ephemeral:We,table:Tr,dispatchMutation:i}),Dr=Gdt({hocuspocus:d,derivedDocumentIndex:ie,getFileIndex:_,isSafeDocName:E5,readPageTitleForDocName:_t,readPageTitleForLinkedDocName:vt,readFrontmatterMetadataForLinkedDocName:xt,collectAdmittedDocNames:Ft,resolveAlias:wt,respondToDerivedIndexQueryFailure:Bt}),Or=Cpt({hocuspocus:d,agentPresenceBroadcaster:se,isAllowedWorkspaceHostHeader:l,log:c5}),kr=act({contentDir:p,projectDir:me,ephemeral:We,log:c5,ready:Me,serverInstanceId:g,getDiskAckSVs:ne,getCollabClientCount:P,getConfigDiagnostics:Xe,acpRegistry:Se,loadAcpCustomAgents:Ce,acpHarnessAvailability:we,isRoutePeerAdmitted:u,isAllowedWorkspaceHostHeader:l,checkLocalOpSecurity:c,getPrincipal:ge,semanticSearch:Ie,readSemanticProviderConfig:Be,embeddingsSecretsFile:Re,getFileIndex:_,shadowRef:A,getCurrentBranch:N,getReportedBranch:te,installedAgentsCache:mt}),Ar=Kdt({hocuspocus:d,contentDir:p,projectDir:me,contentFilter:Te,isSafeDocName:E5,resolveDocFilePath:v5,isValidRelativeContentPath:e5,streamShowAllEntries:p5,getLinterBaseConfig:Ve,getLinkAdvisoryPolicy:He,derivedDocumentIndex:ie,collectAdmittedDocNames:Ft,unmatchedGlobProblems:Sr,readAuditGeneration:nee,localTargetInventory:Gt}),jr=aft({conflicts:ue,contentDir:p,projectDir:me,signalLintConfigChanged:tee,getLinterBaseConfig:Ve,unmatchedGlobProblems:Sr,signalChannel:at,requireNonEmptyDocName:m5,resolveAlias:wt,getPrincipal:ge,resolveDocFilePath:v5,summaryResponseFields:bn,sessionManager:f,options:e,agentPresenceBroadcaster:se,buildAgentActor:yn,flushDiskAndDetectOutcome:Dt,respondPersistenceFailure:D5,respondDiskDivergence:Ot,respondStaleExternalWrite:At,flushDocToDisk:Et,log:c5}),Mr=ldt({contentRoot:re,log:c5,shadowRef:A,flushGitCommit:j,commitOkArtifactWrite:Mn,getCurrentBranch:N,validateFolderRel:Rn,safeDocPath:l5,docTreePathCandidates:q_t}),Nr=lrt({validateSkillName:Hn,parseSkillScope:Un,skillsHome:Wn,projectDir:me,resolveBuiltinSkillDir:Qn,resolveSkillDirForRead:qn,resolveSkillsRoot:Kn,getPrincipal:ge,rejectReservedBuiltinSkill:ar,contentDir:p,checkSkillDocConflictGate:zn,extractAgentIdentity:vn,sessionManager:f,flushDiskAndDetectOutcome:Dt,respondStaleExternalWrite:At,respondPersistenceFailure:D5,respondDiskDivergence:Ot,attributeOkArtifactWrite:Tn,okArtifactKey:wn,commitOkArtifactWrite:Mn,signalChannel:at,extractActorIdentityFromQuery:Jn,captureAndCloseDocuments:en,derivedDocumentIndex:ie,log:c5,recordDerivedMutationsBestEffort:It}),Pr=frt({projectDir:me,getPrincipal:ge,skillImportService:gr,bumpSkillsCatalogGen:nt,contentFilter:Te,scheduleDeferredIgnoreRebuild:Dn,signalChannel:at,parseSkillScope:Un}),Fr=srt({validateSkillName:Hn,parseSkillScope:Un,skillsHome:Wn,projectDir:me,resolveBuiltinSkillDir:Qn,parseFrontmatterDoc:Bn,resolveSkillDirForRead:qn,skillRelPath:or,derivedDocumentIndex:ie,contentFilter:Te,bumpSkillsCatalogGen:nt,settleSkillCatalog:kn,invalidateSkillCatalog:On,scheduleDeferredIgnoreRebuild:Dn,recordDerivedDocumentBestEffort:Lt,getPrincipal:ge,rejectReservedBuiltinSkill:ar,contentDir:p,attributeOkArtifactWrite:Tn,scheduleOkArtifactFlush:jn,signalChannel:at,checkSkillDocConflictGate:zn,extractAgentIdentity:vn,sessionManager:f,flushDiskAndDetectOutcome:Dt,respondStaleExternalWrite:At,respondPersistenceFailure:D5,respondDiskDivergence:Ot,okArtifactKey:wn,resolveSkillsRoot:Kn,extractActorIdentityFromQuery:Jn,captureAndCloseDocuments:en,log:c5,commitOkArtifactWrite:Mn,skillInstallBase:sr,uninstallSkillFromHostDirs:lr,renameTrackedPathInGit:T5,renamePathOnDisk:w5,localSkillHash:fr,shadowHeadSha:pr,artifactWriterId:mr,checkLocalOpSecurity:c,effectiveSkillRoot:dr}),Ir=yrt({contentDir:p,projectDir:me,skillsHome:Wn,contentFilter:Te,catalogCache:tt,resolveSkillsRoot:Kn,resolveSkillsList:ur,skillOriginFor:I,localSkillHash:fr,effectiveInstallMode:Xn,pluginSelfIdentity:tr,synthBuiltinLockEntry:$n,synthPluginLockEntry:nr,pluginUpstreamHash:er,builtinSkillListEntry:ir,indexedSkillContentPath:Y_t,healUnservableSkillAdmission:X_t}),Lr=fmt({contentDir:p,projectDir:me,homeDirOverride:_e,skillsHome:Wn,isSafeDocName:E5,commentService:gt,enumerateInstalledSkillsCached:rt,checkLocalOpSecurity:c}),R=Smt({log:c5,skillsHome:Wn,projectDir:me,contentDir:p,resolveSkillDirForRead:qn}),zr=Jgt({contentDir:p,projectDir:me,skillsHome:Wn,homeDirOverride:_e,savedThemeLockTimeoutMs:xe,ephemeral:We,log:c5,signalChannel:at,searchService:L,linkPreviewFetch:Ge,getLinkPreviewsEnabled:Ke,declaredGitHubHosts:Ze,resolveGitHubToken:Je,githubReferenceFetch:Ye,getGeneratedIndexSettingsStatus:m,setGeneratedIndexEnabled:h}),iee=Hot({commentService:gt,getPrincipal:ge,signalChannel:at}),aee=Cmt({projectDir:me,contentDir:p,getPrincipal:ge,hocuspocus:d,log:c5,checkLocalOpSecurity:c,getSyncEngine:le,conflicts:ue,serializeDoc:Pe,setBatchInProgress:de}),oee=dmt({declaredGitHubHosts:Ze,projectDir:me,contentDir:p,log:c5,checkLocalOpSecurity:c,localOpCliArgs:fe,localOpGuard:ot,getSyncEngine:le,resolveCredentialConfig:$e,toGitRelativePath:b5}),see=Dut({projectDir:me,contentDir:p,contentFilter:Te,getFileIndex:_,checkLocalOpSecurity:c,getSyncEngine:le,getPrincipal:ge,resolveCredentialConfig:$e}),Br=Spt({declaredGitHubHosts:Ze,projectDir:me,contentDir:p,log:c5,checkLocalOpSecurity:c,localOpCliArgs:fe,localOpGuard:ot,getSyncEngine:le,authStreamHeartbeatMs:pe,embeddingsSecretsFile:Re,readSemanticProviderConfig:Be,semanticSearch:Ie}),Vr=Hct({contentDir:p,projectDir:me,log:c5,getPrincipal:ge,contentFilter:Te,signalChannel:at,conflicts:ue,commitOkArtifactWrite:Mn,fileOpsService:Ln,assetService:In,extractAgentIdentity:vn,recordDerivedDocumentBestEffort:Lt,invalidateReferencedAssetsCache:ct,listManagedDocNamesUnderFolderFromDisk:pn,resolveContentEntryPath:et,docNameForFileOperationPath:y5,withPeriod:Qt,toManagedRenamePublicError:$t,attributeRenameWriteToActor:Cn,renameAttributionCounter:B_t,_performAssetRename:hn,_performDocumentToFileRename:gn,_performManagedRenameForDocs:_n,isValidRelativeContentPath:e5}),Hr=rmt({contentDir:p,checkLocalOpSecurity:c}),Ur=Lmt({contentDir:p,log:c5,checkLocalOpSecurity:c,installedAgentsCache:mt,agentIntegrations:be}),Wr=fut({contentDir:p,projectDir:me,ephemeral:We,log:c5,hocuspocus:d,sessionManager:f,getPrincipal:ge,signalChannel:at,conflicts:ue,recentlyRemovedDocs:Ne,isSafeDocName:E5,resolveAlias:wt,resolveContentEntryPath:et,validateFolderRel:Rn,extractAgentIdentity:vn,extractActorIdentityFromQuery:Jn,okArtifactKey:wn,attributeOkArtifactWrite:Tn,scheduleOkArtifactFlush:jn,flushDiskAndDetectOutcome:Dt,respondPersistenceFailure:D5,respondDiskDivergence:Ot,respondStaleExternalWrite:At,registerWrittenDocInFileIndex:Yt,captureAndCloseDocuments:en,captureNamespaceMove:ke,renameTrackedPathInGit:T5,renamePathOnDisk:w5,splitContentPath:g5,mutateFileIndex:b}),Gr=Pot({assetService:In,log:c5}),Kr=y9e({log:c5,checkLocalOpSecurity:c,getPrincipal:ge,homeDirOverride:_e,projectDir:me,agentIntegrations:be}),qr=Btt({checkLocalOpSecurity:c}),Jr=prt({resolveSkillsRoot:Kn,validateSkillName:Hn,projectDir:me,skillInstallBase:sr,contentDir:p,skillsHome:Wn,shippedBundleSkillMd:rr,flushDiskAndDetectOutcome:Dt,respondStaleExternalWrite:At,respondPersistenceFailure:D5,respondDiskDivergence:Ot,skillInstallOps:Gn,skillPlacementOps:Fn,signalChannel:at,bumpSkillsCatalogGen:nt,contentFilter:Te,scheduleDeferredIgnoreRebuild:Dn,effectiveInstallMode:Xn,log:c5}),Yr=Frt({synthPluginLockEntry:nr,synthBuiltinLockEntry:$n,isValidSkillName:Vn,getPrincipal:ge,validateSkillName:Hn,rejectReservedBuiltinSkill:ar,shadowRef:A,contentDir:p,contentRoot:re,projectDir:me,skillsHome:Wn,projectSkillDirRel:Zn,attributeOkArtifactWrite:Tn,okArtifactKey:wn,commitOkArtifactWrite:Mn,signalChannel:at,bumpSkillsCatalogGen:nt,contentFilter:Te,scheduleDeferredIgnoreRebuild:Dn,effectiveSkillRoot:dr,skillReimportService:_r,localSkillHash:fr,resolveSkillsRoot:Kn,projectImportedSkillCopy:hr}),Xr=Irt({contentDir:p,projectDir:me,contentFilter:Te,validateSkillName:Hn,indexedSkillContentPath:Y_t,bumpSkillsCatalogGen:nt,signalChannel:at}),Zr=Aet({conflicts:ue,getLinkAdvisoryPolicy:He,respondStaleExternalWrite:At,requireNonEmptyDocName:m5,resolveAlias:wt,extractAgentIdentity:vn,docNameExistsWithAnySupportedExtension:_5,findMissingDocCandidates:e=>zrt(e,_()),contentDir:p,summaryResponseFields:bn,sessionManager:f,durabilityState:t,hocuspocus:d,options:e,getBridgeLossReporter:he,agentPresenceBroadcaster:se,recordContentDivergenceGate:G_t,buildAgentActor:yn,countNormalizedSummary:Sn,flushDiskAndDetectOutcome:Dt,respondPersistenceFailure:D5,respondDiskDivergence:Ot,flushDocToDisk:Et,agentFocusBroadcaster:oe,onAgentWrite:ce,computeOrphanHints:Ct,registerWrittenDocInFileIndex:Yt,prepareWriteLinkAdvisory:Pt,buildReconcileWarning:jt,computeLintViolations:xr,log:c5,flushDocToGit:Tt,commitOkArtifactWrite:Mn,isSafeDocName:E5,shadowRef:A,getPrincipal:ge,contentRoot:re,safeDocPath:l5,getCurrentBranch:N,docTreePathCandidates:q_t,stripDefaultPathTruncation:xn,renameAttributionCounter:B_t}),Qr=Pet({agentPresence:se,resetSettingsForTest:ve,settleDiskEvents:ye,recentlyRemovedDocs:Ne,conflicts:ue,durabilityState:t,resolveAlias:wt,contentDir:p,log:c5,sessionManager:f,hocuspocus:d,forceUnloadDocument:De,derivedDocumentIndex:ie,contentFilter:Te,bumpSkillsCatalogGen:nt,signalChannel:at,flushGitCommit:async()=>{await An,await j?.()},rescanFiles:D}),$r=[Gr,Kr,Zr,...ee?[Qr]:[],Xr,Yr,Jr,qr,Pr,Nr,Dr,Or,st,kr,Ar,jr,Mr,Fr,Ir,Lr,R,zr,iee,aee,oee,see,Br,Vr,Hr,Ur,Wr],ei=$r.flatMap(e=>[...e.paths]);udt(ei,Cr);let z=$r.map(e=>m9e({log:c5,policy:o,ephemeral:We,table:e.table,dispatchMutation:i})),ti={paths:ei,dispatch:async(e,t)=>{for(let n of z)if(await n(e,t))return!0;return!1}},ni=new Set([`/api/search`,`/api/delete-path`,`/api/create-folder`,`/api/save-version`,`/api/skill/import`,`/api/skill/install`,`/api/upload`,`/api/orphans`,`/api/hubs`,`/api/backlinks`,`/api/forward-links`,`/api/dead-links`,`/api/suggest-links`]),ri=$r.map(e=>e.table),ii=e=>{for(let t of ri){let n=t.resolve(e)?.dispatch;if(n!==void 0)return t.isMutating(e)?(t,r)=>i(()=>n(t,r),e):n}};for(let e of ni)if(Cr[e]===void 0&&ii(e)===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);return{priority:100,async onRequest({request:e,response:t}){await Er(e,t)},nativeApi:ti,localApi:cft({resolve:e=>{if(!ni.has(e))return;let t=Cr[e];return t===void 0?ii(e):Tr.isMutating(e)?(n,r)=>i(()=>t(n,r),e):t}}),shutdownLocalOps:async()=>{n=!0;let e=(await Promise.allSettled([...r,Br.shutdown()])).at(-1);if(e?.status===`rejected`)throw e.reason}}}function O5(e){let t=e;if(t.length>1){let e=t.indexOf(`#`,1);e!==-1&&(t=t.slice(0,e));let n=t.indexOf(`?`,1);n!==-1&&(t=t.slice(0,n))}if(!t.includes(`%`))return t;try{return decodeURI(t)}catch{return t}}function Cvt(e,t){let n;try{n=encodeURI(e)}catch{return null}let r=t.indexOf(`?`),i=`/${n}${r===-1?``:t.slice(r)}`;return O5(i)===`/${e}`?i:null}function wvt(e,t){let n=W(e),r=Fs(H(`${n}${Rs}`,O5(t)));if(!r.startsWith(`${n}${Rs}`))return!1;try{let e=nc(n),t=nc(r);return oc(t).isFile()&&pq(t,e)&&!aJ(H(e,U(n,r)),t,e)}catch{return!1}}function Tvt(e){let{contentDir:t,contentFilter:n,contentSirv:r,inlineExtensions:i,assetExtensions:a,blocklistExtensions:o,ingressPolicy:s,resolveTrackedFile:c}=e,l=e=>Ns(e).slice(1).toLowerCase(),u=(e,r)=>{let i=c?.(e);if(i===void 0||i===e)return null;let o=l(i);if(n.isPathIgnored(i)||!a.has(o))return null;let s=Cvt(i,r);return s!==null&&wvt(t,s)?{url:s,ext:o}:null};return(e,c,d)=>{let f=e.url??``,p;try{p=decodeURIComponent(f.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return d()}let m=O5(f)===`/${p}`&&e5(p),h=l(p),g=h===`md`||h===`mdx`;if(!p||n.isPathIgnored(p)||!g&&!a.has(h))return d();let _=e.socket?.remoteAddress;if(_!==void 0&&!w$(_,s)){X(c,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!T$(e.headers.host,s)){X(c,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:S$});return}let v=m&&wvt(t,f),y=!m||v||g?null:u(p,f),b=y?.ext??h;c.setHeader(`X-Content-Type-Options`,`nosniff`);let x=p_t(b,i);g||c.setHeader(`Content-Disposition`,x.disposition),x.csp!==null&&c.setHeader(`Content-Security-Policy`,x.csp),x.sandboxedHtml&&c.setHeader(`Cache-Control`,`no-store`);let S=()=>{if(c.headersSent)return;e.url=f;let t=Lt.has(b);if(!t&&(a.has(b)||o.has(b))){c.statusCode=404,c.end();return}t&&(c.removeHeader(`Content-Security-Policy`),c.removeHeader(`Content-Disposition`),c.removeHeader(`X-Content-Type-Options`),c.removeHeader(`Cache-Control`)),d()};if(!v&&y===null){S();return}y!==null&&(e.url=y.url),r(e,c,S)}}function k5(e){let t=e?.code;return typeof t==`string`?t:void 0}function Evt(e){let t;try{t=tc(e.contentDir,{withFileTypes:!0})}catch(t){let n=k5(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&IK(n.name,mt)&&e.basenameIndex.add(n.name)}async function A5(e){let t=oq(e.contentDir,{root:`content`,component:`asset-walk`}),n=new Set;async function r(i){let a;try{a=await yc(i,{withFileTypes:!0})}catch(t){let n=k5(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=H(i,o.name),s=tq(U(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await gc(a)}catch(t){let n=k5(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await bc(a)}catch(t){let n=k5(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!nq(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Sc(i)}catch(t){let n=k5(t);n!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,n,i);continue}if(n.has(o.ino))continue;n.add(o.ino),o.isDirectory()?await r(i):o.isFile()&&IK(a,Yt)&&!e.contentFilter?.isPathIgnored(s)&&e.basenameIndex.add(s);continue}if(c.isDirectory()){if(n.has(c.ino))continue;n.add(c.ino),await r(a);continue}c.isFile()&&IK(a,Yt)&&!e.contentFilter?.isPathIgnored(s)&&e.basenameIndex.add(s)}}await r(t)}const Dvt=I({principalId:L().optional(),tabSessionId:L().optional(),expectedServerInstanceId:L().optional(),expectedBranch:L().optional(),expectedDocLineageEpoch:L().optional(),clientProtocolVersion:On().optional(),clientRuntimeVersion:L().optional(),clientKind:L().optional()}).loose(),Ovt=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function kvt(e){return Ovt.includes(e)}function Avt(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function jvt(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!kvt(n))return{kind:null,payload:void 0};if(t===-1)return{kind:n,payload:void 0};let r=e.slice(t+1);return{kind:n,payload:r.length>0?r:void 0}}var j5=class extends Error{kind;payload;reason;constructor(e,t,n){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof n==`string`&&n.length>0?n:void 0,this.reason=Avt(e,this.payload)}};function M5(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=Dvt.safeParse(t);return n.success?n.data:void 0}var Mvt=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};function Nvt(e,t){let n=e instanceof Error?{name:e.name,message:e.message,stack:e.stack??null}:{name:`NonError`,message:String(e),stack:null};return{timestamp:new Date().toISOString(),origin:t,error:n,pid:process.pid,uptimeSec:Math.round(process.uptime()*1e3)/1e3}}function Pvt(e,t){let n=FJ(e);try{Xs(n,{recursive:!0}),cc(H(n,c),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=CS(e);Xs(V(n),{recursive:!0});let r={level:60,time:Date.parse(t.timestamp),name:`crash`,origin:t.origin,err:t.error,pid:t.pid,uptimeSec:t.uptimeSec,msg:`fatal ${t.origin} — process crashing`};cc(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const N5=new Map;let Fvt=!1;function Ivt(e,t){try{let n=Nvt(e,t);for(let e of N5.keys())Pvt(e,n)}catch{}}function Lvt(e){N5.set(e,(N5.get(e)??0)+1),Fvt||(Fvt=!0,process.on(`uncaughtExceptionMonitor`,Ivt));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=N5.get(e)??0;n<=1?N5.delete(e):N5.set(e,n-1)}}}function P5(e,t){let n=0,r=!1,i=new Set;t&&i.add(t);let a=e=>{for(let t of i)t(e)},o=(e,t)=>{e.url?.startsWith(`/collab`)&&(n++,a(n),t.once(`close`,()=>{n--,n<0&&(n=0),a(n)}))};return e.on(`upgrade`,o),{getCount:()=>n,subscribe:e=>(i.add(e),()=>i.delete(e)),detach:()=>{r||(r=!0,e.off(`upgrade`,o))}}}function Rvt(e){let t=e.scheduler??Hr,n=e.warnBeforeMs??3e5,r=null,i=null,a=!1,o=!1;function s(){r!==null&&(t.clearTimeout(r),r=null),i!==null&&(t.clearTimeout(i),i=null)}function c(){s(),!(o||a)&&d.getCount()===0&&(n>0&&n<e.thresholdMs&&(i=t.setTimeout(()=>{i=null,d.getCount()===0&&!a&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),r=t.setTimeout(()=>{if(r=null,!(o||a)&&d.getCount()===0){a=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let l=e=>{e===0?c():s()},u=e.counter===void 0,d=e.counter??P5(e.httpServer),f=d.subscribe(l);return c(),{detach:()=>{o||(o=!0,f(),u&&d.detach(),s())}}}function F5(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zvt(e){if(!G(e))return{};let t;try{let n=K(e,`utf-8`);t=(0,Wc.parse)(n)}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!F5(t))return{};let n=t.telemetry;if(!F5(n))return{};let r=n.localSink;return F5(r)?r:{}}function Bvt(e){return typeof e==`boolean`?e:void 0}function Vvt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Hvt(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function I5(e){if(F5(e))return Vvt(e.maxBytes)}function Uvt(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=zvt(QS(`project`,e.projectDir)),n=zvt(QS(`project-local`,e.projectDir));if((Bvt(n.enabled)??Bvt(t.enabled)??!0)===!1)return null;let r=I5(n.spans)??I5(t.spans)??52428800,i=I5(n.logs)??I5(t.logs)??26214400,a=Hvt(n.attributeDenylist)??Hvt(t.attributeDenylist)??to;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}const L5=`https://json-schema.org/draft/2020-12/schema`,Wvt=`tools/list`;function Gvt(e){let t=e;if(t.__jsonSchemaDialectInstalled===!0)return;let n=e.server._requestHandlers?.get(Wvt);if(typeof n!=`function`){console.warn(`[json-schema-dialect] No ${Wvt} handler found. Either the SDK internals changed, or this ran before tools were registered. Tool schemas will keep the SDK's draft-07 dialect.`);return}e.server.setRequestHandler(iB,async(e,t)=>{let r=await n(e,t);for(let e of r.tools??[])e.inputSchema&&(e.inputSchema.$schema=L5),e.outputSchema&&(e.outputSchema.$schema=L5);return r}),t.__jsonSchemaDialectInstalled=!0}function Kvt(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let n=t.validateToolInput;if(typeof n!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,r){if(!e.inputSchema||!qvt(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=Ki(i.error);throw new hB(hz.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function qvt(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const R5=2e3,Jvt=2e3,Yvt=[`-iTCP`,`-sTCP:LISTEN`,`-nP`],Xvt=[/^open-knowledge-server(?:\s|$)/,/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function Zvt(e){return Xvt.some(t=>t.test(e))}function Qvt(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(`--ok-lock-dir-b64=`));if(t==null)return null;let n=t.slice(18);if(!n)return null;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);return Ps(e)?e:null}catch{return null}}function $vt(e){let t=e.indexOf(`--ok-project-path=`);if(t===-1)return null;let n=t+18,r=e.slice(n),i=r.search(/\s--/),a=(i===-1?r:r.slice(0,i)).trim();return a&&Ps(a)?a:null}function eyt(e){let t=[];for(let n of e.split(`
2079
+ `).filter(Boolean).find(t=>t.endsWith(`/${e}`));if(t)return(await r.raw(`rev-parse`,t)).trim()},a=async(e,t)=>(await r.raw(`ls-tree`,`-r`,`--name-only`,e,...Wt([t]))).trim().length>0,o=await i();return o!==void 0&&t!==void 0&&!await a(o,t)&&(await Mn(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let mr=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function hr(e){try{let t=sr(e.scope);if(!t)return;let n=z0(t);if(n.length===0)return;let r=q0(W(e.skillsRoot,e.name),e.name,t,n,`copy`,B0(e.scope));if(r.length===0)return;await E0(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){c5.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}let gr=Ert({contentDir:p,skillsHome:Wn,...me===void 0?{}:{projectDir:me},resolveSkillDirForRead:qn,parseFrontmatterDoc:Bn,attributeOkArtifactWrite:Tn,commitOkArtifactWrite:Mn,shadowHeadSha:pr,artifactWriterId:mr,effectiveInstallMode:Xn,signalFiles:()=>at?.(`files`)}),_r=Art({contentDir:p,skillsHome:Wn,...me===void 0?{}:{projectDir:me},legacyStoreRoot:qa,effectiveSkillRoot:dr,parseFrontmatterDoc:Bn,attributeOkArtifactWrite:Tn,commitOkArtifactWrite:Mn,shadowHeadSha:pr,artifactWriterId:mr,skillArtifactKey:e=>wn(`skill`,``,e),captureAndCloseDocuments:en,projectImportedSkillCopy:hr,signalFiles:()=>at?.(`files`)}),vr=Z(yie,async(e,t,n)=>{try{if(!Hn(n.name,t,`skill-uninstall`))return;let e=sr(n.scope);if(!e){X(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await lr(e,n.name,n.scope);at?.(`files`),Q(t,200,ree,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){X(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,...K_t(e)===void 0?{}:{detail:K_t(e)},cause:e})}},{handler:`skill-uninstall`,method:`POST`}),L=A_t({contentDir:p,projectDir:me,getAllFilesIndex:y,getFileIndexGeneration:x,getSearchMaxEntries:evt,semanticSearch:Ie,getSemanticSimilarityFloor:Le,ready:Me,getProjectSkillsRoot:()=>Kn(`project`),parseFrontmatterDoc:Bn});L.prewarm();let br=0;function tee(){br+=1,at?.(`lint-config`)}let nee=()=>oit({lintConfigEpoch:br,projectConfigEpoch:Ue(),activeBranch:t.getActiveBranch(),localTargetGeneration:ie?.readLocalTargetGeneration?.()??0});async function xr(e,t,n){let r=Ve?.()??s;try{let i=x2(p,r,{docName:t,projectDir:me??p,onProblem:e=>c5.warn({problem:e,docName:t},`[lint] native config problem`)}),a=await qe(e,i,t),o=[];if(ie?.isReady()&&n.links!==`off`&&!$K(t)){let i=ie;o=await St.run(`lint-links`,async()=>{await Rt(t,e,`lint-validation`);let a=Zat({projectDir:me??p,contentDir:p,baseConfig:r,derivedDocumentIndex:i,linkPolicy:n,admittedDocNames:Ft,docFilePathFor:e=>v5(p,e),localTargetInventory:Gt}).find(e=>e.id===`links`);return a?(await a.run({targetPath:v5(p,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics):[]},()=>[])}return[...a,...o].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return c5.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Sr(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=C2({projectDir:me??p,contentDir:p});return Grt(t.schemas,n)}let Cr={"/api/skill/uninstall":vr,"/api/agent-write":Nn,"/api/agent-write-batch":Pn},wr=new Set([`/api/agent-write`,`/api/agent-write-batch`,`/api/test-reset`,`/api/test-flush-git`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`,`/api/skill/uninstall`]),Tr={resolve(e){let t=Cr[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:{template:`/api/*`}},isMutating:e=>wr.has(e)},Er=m9e({log:c5,policy:o,ephemeral:We,table:Tr,dispatchMutation:i}),Dr=Gdt({hocuspocus:d,derivedDocumentIndex:ie,getFileIndex:_,isSafeDocName:E5,readPageTitleForDocName:_t,readPageTitleForLinkedDocName:vt,readFrontmatterMetadataForLinkedDocName:xt,collectAdmittedDocNames:Ft,resolveAlias:wt,respondToDerivedIndexQueryFailure:Bt}),Or=Cpt({hocuspocus:d,agentPresenceBroadcaster:se,isAllowedWorkspaceHostHeader:l,log:c5}),kr=act({contentDir:p,projectDir:me,ephemeral:We,log:c5,ready:Me,serverInstanceId:g,getDiskAckSVs:ne,getCollabClientCount:P,getConfigDiagnostics:Xe,acpRegistry:Se,loadAcpCustomAgents:Ce,acpHarnessAvailability:we,isRoutePeerAdmitted:u,isAllowedWorkspaceHostHeader:l,checkLocalOpSecurity:c,getPrincipal:ge,semanticSearch:Ie,readSemanticProviderConfig:Be,embeddingsSecretsFile:Re,getFileIndex:_,shadowRef:A,getCurrentBranch:N,getReportedBranch:te,installedAgentsCache:mt}),Ar=Kdt({hocuspocus:d,contentDir:p,projectDir:me,contentFilter:Te,isSafeDocName:E5,resolveDocFilePath:v5,isValidRelativeContentPath:e5,streamShowAllEntries:p5,getLinterBaseConfig:Ve,getLinkAdvisoryPolicy:He,derivedDocumentIndex:ie,collectAdmittedDocNames:Ft,unmatchedGlobProblems:Sr,readAuditGeneration:nee,localTargetInventory:Gt}),jr=aft({conflicts:ue,contentDir:p,projectDir:me,signalLintConfigChanged:tee,getLinterBaseConfig:Ve,unmatchedGlobProblems:Sr,signalChannel:at,requireNonEmptyDocName:m5,resolveAlias:wt,getPrincipal:ge,resolveDocFilePath:v5,summaryResponseFields:bn,sessionManager:f,options:e,agentPresenceBroadcaster:se,buildAgentActor:yn,flushDiskAndDetectOutcome:Dt,respondPersistenceFailure:D5,respondDiskDivergence:Ot,respondStaleExternalWrite:At,flushDocToDisk:Et,log:c5}),Mr=ldt({contentRoot:re,log:c5,shadowRef:A,flushGitCommit:j,commitOkArtifactWrite:Mn,getCurrentBranch:N,validateFolderRel:Rn,safeDocPath:l5,docTreePathCandidates:q_t}),Nr=lrt({validateSkillName:Hn,parseSkillScope:Un,skillsHome:Wn,projectDir:me,resolveBuiltinSkillDir:Qn,resolveSkillDirForRead:qn,resolveSkillsRoot:Kn,getPrincipal:ge,rejectReservedBuiltinSkill:ar,contentDir:p,checkSkillDocConflictGate:zn,extractAgentIdentity:vn,sessionManager:f,flushDiskAndDetectOutcome:Dt,respondStaleExternalWrite:At,respondPersistenceFailure:D5,respondDiskDivergence:Ot,attributeOkArtifactWrite:Tn,okArtifactKey:wn,commitOkArtifactWrite:Mn,signalChannel:at,extractActorIdentityFromQuery:Jn,captureAndCloseDocuments:en,derivedDocumentIndex:ie,log:c5,recordDerivedMutationsBestEffort:It}),Pr=frt({projectDir:me,getPrincipal:ge,skillImportService:gr,bumpSkillsCatalogGen:nt,contentFilter:Te,scheduleDeferredIgnoreRebuild:Dn,signalChannel:at,parseSkillScope:Un}),Fr=srt({validateSkillName:Hn,parseSkillScope:Un,skillsHome:Wn,projectDir:me,resolveBuiltinSkillDir:Qn,parseFrontmatterDoc:Bn,resolveSkillDirForRead:qn,skillRelPath:or,derivedDocumentIndex:ie,contentFilter:Te,bumpSkillsCatalogGen:nt,settleSkillCatalog:kn,invalidateSkillCatalog:On,scheduleDeferredIgnoreRebuild:Dn,recordDerivedDocumentBestEffort:Lt,getPrincipal:ge,rejectReservedBuiltinSkill:ar,contentDir:p,attributeOkArtifactWrite:Tn,scheduleOkArtifactFlush:jn,signalChannel:at,checkSkillDocConflictGate:zn,extractAgentIdentity:vn,sessionManager:f,flushDiskAndDetectOutcome:Dt,respondStaleExternalWrite:At,respondPersistenceFailure:D5,respondDiskDivergence:Ot,okArtifactKey:wn,resolveSkillsRoot:Kn,extractActorIdentityFromQuery:Jn,captureAndCloseDocuments:en,log:c5,commitOkArtifactWrite:Mn,skillInstallBase:sr,uninstallSkillFromHostDirs:lr,renameTrackedPathInGit:T5,renamePathOnDisk:w5,localSkillHash:fr,shadowHeadSha:pr,artifactWriterId:mr,checkLocalOpSecurity:c,effectiveSkillRoot:dr}),Ir=yrt({contentDir:p,projectDir:me,skillsHome:Wn,contentFilter:Te,catalogCache:tt,resolveSkillsRoot:Kn,resolveSkillsList:ur,skillOriginFor:I,localSkillHash:fr,effectiveInstallMode:Xn,pluginSelfIdentity:tr,synthBuiltinLockEntry:$n,synthPluginLockEntry:nr,pluginUpstreamHash:er,builtinSkillListEntry:ir,indexedSkillContentPath:Y_t,healUnservableSkillAdmission:X_t}),Lr=fmt({contentDir:p,projectDir:me,homeDirOverride:_e,skillsHome:Wn,isSafeDocName:E5,commentService:gt,enumerateInstalledSkillsCached:rt,checkLocalOpSecurity:c}),R=Smt({log:c5,skillsHome:Wn,projectDir:me,contentDir:p,resolveSkillDirForRead:qn}),zr=Jgt({contentDir:p,projectDir:me,skillsHome:Wn,homeDirOverride:_e,savedThemeLockTimeoutMs:xe,ephemeral:We,log:c5,signalChannel:at,searchService:L,linkPreviewFetch:Ge,getLinkPreviewsEnabled:Ke,declaredGitHubHosts:Ze,resolveGitHubToken:Je,githubReferenceFetch:Ye,getGeneratedIndexSettingsStatus:m,setGeneratedIndexEnabled:h}),iee=Hot({commentService:gt,getPrincipal:ge,signalChannel:at}),aee=Cmt({projectDir:me,contentDir:p,getPrincipal:ge,hocuspocus:d,log:c5,checkLocalOpSecurity:c,getSyncEngine:le,conflicts:ue,serializeDoc:Pe,setBatchInProgress:de}),oee=dmt({declaredGitHubHosts:Ze,projectDir:me,contentDir:p,log:c5,checkLocalOpSecurity:c,localOpCliArgs:fe,localOpGuard:ot,getSyncEngine:le,resolveCredentialConfig:$e,toGitRelativePath:b5}),see=Dut({projectDir:me,contentDir:p,contentFilter:Te,getFileIndex:_,checkLocalOpSecurity:c,getSyncEngine:le,getPrincipal:ge,resolveCredentialConfig:$e}),Br=Spt({declaredGitHubHosts:Ze,projectDir:me,contentDir:p,log:c5,checkLocalOpSecurity:c,localOpCliArgs:fe,localOpGuard:ot,getSyncEngine:le,authStreamHeartbeatMs:pe,embeddingsSecretsFile:Re,readSemanticProviderConfig:Be,semanticSearch:Ie}),Vr=Hct({contentDir:p,projectDir:me,log:c5,getPrincipal:ge,contentFilter:Te,signalChannel:at,conflicts:ue,commitOkArtifactWrite:Mn,fileOpsService:Ln,assetService:In,extractAgentIdentity:vn,recordDerivedDocumentBestEffort:Lt,invalidateReferencedAssetsCache:ct,listManagedDocNamesUnderFolderFromDisk:pn,resolveContentEntryPath:et,docNameForFileOperationPath:y5,withPeriod:Qt,toManagedRenamePublicError:$t,attributeRenameWriteToActor:Cn,renameAttributionCounter:B_t,_performAssetRename:hn,_performDocumentToFileRename:gn,_performManagedRenameForDocs:_n,isValidRelativeContentPath:e5}),Hr=rmt({contentDir:p,checkLocalOpSecurity:c}),Ur=Lmt({contentDir:p,log:c5,checkLocalOpSecurity:c,installedAgentsCache:mt,agentIntegrations:be}),Wr=fut({contentDir:p,projectDir:me,ephemeral:We,log:c5,hocuspocus:d,sessionManager:f,getPrincipal:ge,signalChannel:at,conflicts:ue,recentlyRemovedDocs:Ne,isSafeDocName:E5,resolveAlias:wt,resolveContentEntryPath:et,validateFolderRel:Rn,extractAgentIdentity:vn,extractActorIdentityFromQuery:Jn,okArtifactKey:wn,attributeOkArtifactWrite:Tn,scheduleOkArtifactFlush:jn,flushDiskAndDetectOutcome:Dt,respondPersistenceFailure:D5,respondDiskDivergence:Ot,respondStaleExternalWrite:At,registerWrittenDocInFileIndex:Yt,captureAndCloseDocuments:en,captureNamespaceMove:ke,renameTrackedPathInGit:T5,renamePathOnDisk:w5,splitContentPath:g5,mutateFileIndex:b}),Gr=Pot({assetService:In,log:c5}),Kr=y9e({log:c5,checkLocalOpSecurity:c,getPrincipal:ge,homeDirOverride:_e,projectDir:me,agentIntegrations:be}),qr=Btt({checkLocalOpSecurity:c}),Jr=prt({resolveSkillsRoot:Kn,validateSkillName:Hn,projectDir:me,skillInstallBase:sr,contentDir:p,skillsHome:Wn,shippedBundleSkillMd:rr,flushDiskAndDetectOutcome:Dt,respondStaleExternalWrite:At,respondPersistenceFailure:D5,respondDiskDivergence:Ot,skillInstallOps:Gn,skillPlacementOps:Fn,signalChannel:at,bumpSkillsCatalogGen:nt,contentFilter:Te,scheduleDeferredIgnoreRebuild:Dn,effectiveInstallMode:Xn,log:c5}),Yr=Frt({synthPluginLockEntry:nr,synthBuiltinLockEntry:$n,isValidSkillName:Vn,getPrincipal:ge,validateSkillName:Hn,rejectReservedBuiltinSkill:ar,shadowRef:A,contentDir:p,contentRoot:re,projectDir:me,skillsHome:Wn,projectSkillDirRel:Zn,attributeOkArtifactWrite:Tn,okArtifactKey:wn,commitOkArtifactWrite:Mn,signalChannel:at,bumpSkillsCatalogGen:nt,contentFilter:Te,scheduleDeferredIgnoreRebuild:Dn,effectiveSkillRoot:dr,skillReimportService:_r,localSkillHash:fr,resolveSkillsRoot:Kn,projectImportedSkillCopy:hr}),Xr=Irt({contentDir:p,projectDir:me,contentFilter:Te,validateSkillName:Hn,indexedSkillContentPath:Y_t,bumpSkillsCatalogGen:nt,signalChannel:at}),Zr=Aet({conflicts:ue,getLinkAdvisoryPolicy:He,respondStaleExternalWrite:At,requireNonEmptyDocName:m5,resolveAlias:wt,extractAgentIdentity:vn,docNameExistsWithAnySupportedExtension:_5,findMissingDocCandidates:e=>zrt(e,_()),contentDir:p,summaryResponseFields:bn,sessionManager:f,durabilityState:t,hocuspocus:d,options:e,getBridgeLossReporter:he,agentPresenceBroadcaster:se,recordContentDivergenceGate:G_t,buildAgentActor:yn,countNormalizedSummary:Sn,flushDiskAndDetectOutcome:Dt,respondPersistenceFailure:D5,respondDiskDivergence:Ot,flushDocToDisk:Et,agentFocusBroadcaster:oe,onAgentWrite:ce,computeOrphanHints:Ct,registerWrittenDocInFileIndex:Yt,prepareWriteLinkAdvisory:Pt,buildReconcileWarning:jt,computeLintViolations:xr,log:c5,flushDocToGit:Tt,flushGitCommit:j,commitOkArtifactWrite:Mn,isSafeDocName:E5,shadowRef:A,getPrincipal:ge,contentRoot:re,safeDocPath:l5,getCurrentBranch:N,docTreePathCandidates:q_t,stripDefaultPathTruncation:xn,renameAttributionCounter:B_t}),Qr=Pet({agentPresence:se,resetSettingsForTest:ve,settleDiskEvents:ye,recentlyRemovedDocs:Ne,conflicts:ue,durabilityState:t,resolveAlias:wt,contentDir:p,log:c5,sessionManager:f,hocuspocus:d,forceUnloadDocument:De,derivedDocumentIndex:ie,contentFilter:Te,bumpSkillsCatalogGen:nt,signalChannel:at,flushGitCommit:async()=>{await An,await j?.()},rescanFiles:D}),$r=[Gr,Kr,Zr,...ee?[Qr]:[],Xr,Yr,Jr,qr,Pr,Nr,Dr,Or,st,kr,Ar,jr,Mr,Fr,Ir,Lr,R,zr,iee,aee,oee,see,Br,Vr,Hr,Ur,Wr],ei=$r.flatMap(e=>[...e.paths]);udt(ei,Cr);let z=$r.map(e=>m9e({log:c5,policy:o,ephemeral:We,table:e.table,dispatchMutation:i})),ti={paths:ei,dispatch:async(e,t)=>{for(let n of z)if(await n(e,t))return!0;return!1}},ni=new Set([`/api/search`,`/api/delete-path`,`/api/create-folder`,`/api/save-version`,`/api/skill/import`,`/api/skill/install`,`/api/upload`,`/api/orphans`,`/api/hubs`,`/api/backlinks`,`/api/forward-links`,`/api/dead-links`,`/api/suggest-links`]),ri=$r.map(e=>e.table),ii=e=>{for(let t of ri){let n=t.resolve(e)?.dispatch;if(n!==void 0)return t.isMutating(e)?(t,r)=>i(()=>n(t,r),e):n}};for(let e of ni)if(Cr[e]===void 0&&ii(e)===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);return{priority:100,async onRequest({request:e,response:t}){await Er(e,t)},nativeApi:ti,localApi:cft({resolve:e=>{if(!ni.has(e))return;let t=Cr[e];return t===void 0?ii(e):Tr.isMutating(e)?(n,r)=>i(()=>t(n,r),e):t}}),shutdownLocalOps:async()=>{n=!0;let e=(await Promise.allSettled([...r,Br.shutdown()])).at(-1);if(e?.status===`rejected`)throw e.reason}}}function O5(e){let t=e;if(t.length>1){let e=t.indexOf(`#`,1);e!==-1&&(t=t.slice(0,e));let n=t.indexOf(`?`,1);n!==-1&&(t=t.slice(0,n))}if(!t.includes(`%`))return t;try{return decodeURI(t)}catch{return t}}function Cvt(e,t){let n;try{n=encodeURI(e)}catch{return null}let r=t.indexOf(`?`),i=`/${n}${r===-1?``:t.slice(r)}`;return O5(i)===`/${e}`?i:null}function wvt(e,t){let n=W(e),r=Fs(H(`${n}${Rs}`,O5(t)));if(!r.startsWith(`${n}${Rs}`))return!1;try{let e=nc(n),t=nc(r);return oc(t).isFile()&&pq(t,e)&&!aJ(H(e,U(n,r)),t,e)}catch{return!1}}function Tvt(e){let{contentDir:t,contentFilter:n,contentSirv:r,inlineExtensions:i,assetExtensions:a,blocklistExtensions:o,ingressPolicy:s,resolveTrackedFile:c}=e,l=e=>Ns(e).slice(1).toLowerCase(),u=(e,r)=>{let i=c?.(e);if(i===void 0||i===e)return null;let o=l(i);if(n.isPathIgnored(i)||!a.has(o))return null;let s=Cvt(i,r);return s!==null&&wvt(t,s)?{url:s,ext:o}:null};return(e,c,d)=>{let f=e.url??``,p;try{p=decodeURIComponent(f.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return d()}let m=O5(f)===`/${p}`&&e5(p),h=l(p),g=h===`md`||h===`mdx`;if(!p||n.isPathIgnored(p)||!g&&!a.has(h))return d();let _=e.socket?.remoteAddress;if(_!==void 0&&!w$(_,s)){X(c,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!T$(e.headers.host,s)){X(c,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:S$});return}let v=m&&wvt(t,f),y=!m||v||g?null:u(p,f),b=y?.ext??h;c.setHeader(`X-Content-Type-Options`,`nosniff`);let x=p_t(b,i);g||c.setHeader(`Content-Disposition`,x.disposition),x.csp!==null&&c.setHeader(`Content-Security-Policy`,x.csp),x.sandboxedHtml&&c.setHeader(`Cache-Control`,`no-store`);let S=()=>{if(c.headersSent)return;e.url=f;let t=Lt.has(b);if(!t&&(a.has(b)||o.has(b))){c.statusCode=404,c.end();return}t&&(c.removeHeader(`Content-Security-Policy`),c.removeHeader(`Content-Disposition`),c.removeHeader(`X-Content-Type-Options`),c.removeHeader(`Cache-Control`)),d()};if(!v&&y===null){S();return}y!==null&&(e.url=y.url),r(e,c,S)}}function k5(e){let t=e?.code;return typeof t==`string`?t:void 0}function Evt(e){let t;try{t=tc(e.contentDir,{withFileTypes:!0})}catch(t){let n=k5(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&IK(n.name,mt)&&e.basenameIndex.add(n.name)}async function A5(e){let t=oq(e.contentDir,{root:`content`,component:`asset-walk`}),n=new Set;async function r(i){let a;try{a=await yc(i,{withFileTypes:!0})}catch(t){let n=k5(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=H(i,o.name),s=tq(U(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await gc(a)}catch(t){let n=k5(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await bc(a)}catch(t){let n=k5(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!nq(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Sc(i)}catch(t){let n=k5(t);n!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,n,i);continue}if(n.has(o.ino))continue;n.add(o.ino),o.isDirectory()?await r(i):o.isFile()&&IK(a,Yt)&&!e.contentFilter?.isPathIgnored(s)&&e.basenameIndex.add(s);continue}if(c.isDirectory()){if(n.has(c.ino))continue;n.add(c.ino),await r(a);continue}c.isFile()&&IK(a,Yt)&&!e.contentFilter?.isPathIgnored(s)&&e.basenameIndex.add(s)}}await r(t)}const Dvt=I({principalId:L().optional(),tabSessionId:L().optional(),expectedServerInstanceId:L().optional(),expectedBranch:L().optional(),expectedDocLineageEpoch:L().optional(),clientProtocolVersion:On().optional(),clientRuntimeVersion:L().optional(),clientKind:L().optional()}).loose(),Ovt=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function kvt(e){return Ovt.includes(e)}function Avt(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function jvt(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!kvt(n))return{kind:null,payload:void 0};if(t===-1)return{kind:n,payload:void 0};let r=e.slice(t+1);return{kind:n,payload:r.length>0?r:void 0}}var j5=class extends Error{kind;payload;reason;constructor(e,t,n){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof n==`string`&&n.length>0?n:void 0,this.reason=Avt(e,this.payload)}};function M5(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=Dvt.safeParse(t);return n.success?n.data:void 0}var Mvt=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};function Nvt(e,t){let n=e instanceof Error?{name:e.name,message:e.message,stack:e.stack??null}:{name:`NonError`,message:String(e),stack:null};return{timestamp:new Date().toISOString(),origin:t,error:n,pid:process.pid,uptimeSec:Math.round(process.uptime()*1e3)/1e3}}function Pvt(e,t){let n=FJ(e);try{Xs(n,{recursive:!0}),cc(H(n,c),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=CS(e);Xs(V(n),{recursive:!0});let r={level:60,time:Date.parse(t.timestamp),name:`crash`,origin:t.origin,err:t.error,pid:t.pid,uptimeSec:t.uptimeSec,msg:`fatal ${t.origin} — process crashing`};cc(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const N5=new Map;let Fvt=!1;function Ivt(e,t){try{let n=Nvt(e,t);for(let e of N5.keys())Pvt(e,n)}catch{}}function Lvt(e){N5.set(e,(N5.get(e)??0)+1),Fvt||(Fvt=!0,process.on(`uncaughtExceptionMonitor`,Ivt));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=N5.get(e)??0;n<=1?N5.delete(e):N5.set(e,n-1)}}}function P5(e,t){let n=0,r=!1,i=new Set;t&&i.add(t);let a=e=>{for(let t of i)t(e)},o=(e,t)=>{e.url?.startsWith(`/collab`)&&(n++,a(n),t.once(`close`,()=>{n--,n<0&&(n=0),a(n)}))};return e.on(`upgrade`,o),{getCount:()=>n,subscribe:e=>(i.add(e),()=>i.delete(e)),detach:()=>{r||(r=!0,e.off(`upgrade`,o))}}}function Rvt(e){let t=e.scheduler??Hr,n=e.warnBeforeMs??3e5,r=null,i=null,a=!1,o=!1;function s(){r!==null&&(t.clearTimeout(r),r=null),i!==null&&(t.clearTimeout(i),i=null)}function c(){s(),!(o||a)&&d.getCount()===0&&(n>0&&n<e.thresholdMs&&(i=t.setTimeout(()=>{i=null,d.getCount()===0&&!a&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),r=t.setTimeout(()=>{if(r=null,!(o||a)&&d.getCount()===0){a=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let l=e=>{e===0?c():s()},u=e.counter===void 0,d=e.counter??P5(e.httpServer),f=d.subscribe(l);return c(),{detach:()=>{o||(o=!0,f(),u&&d.detach(),s())}}}function F5(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zvt(e){if(!G(e))return{};let t;try{let n=K(e,`utf-8`);t=(0,Wc.parse)(n)}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!F5(t))return{};let n=t.telemetry;if(!F5(n))return{};let r=n.localSink;return F5(r)?r:{}}function Bvt(e){return typeof e==`boolean`?e:void 0}function Vvt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Hvt(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function I5(e){if(F5(e))return Vvt(e.maxBytes)}function Uvt(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=zvt(QS(`project`,e.projectDir)),n=zvt(QS(`project-local`,e.projectDir));if((Bvt(n.enabled)??Bvt(t.enabled)??!0)===!1)return null;let r=I5(n.spans)??I5(t.spans)??52428800,i=I5(n.logs)??I5(t.logs)??26214400,a=Hvt(n.attributeDenylist)??Hvt(t.attributeDenylist)??to;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}const L5=`https://json-schema.org/draft/2020-12/schema`,Wvt=`tools/list`;function Gvt(e){let t=e;if(t.__jsonSchemaDialectInstalled===!0)return;let n=e.server._requestHandlers?.get(Wvt);if(typeof n!=`function`){console.warn(`[json-schema-dialect] No ${Wvt} handler found. Either the SDK internals changed, or this ran before tools were registered. Tool schemas will keep the SDK's draft-07 dialect.`);return}e.server.setRequestHandler(iB,async(e,t)=>{let r=await n(e,t);for(let e of r.tools??[])e.inputSchema&&(e.inputSchema.$schema=L5),e.outputSchema&&(e.outputSchema.$schema=L5);return r}),t.__jsonSchemaDialectInstalled=!0}function Kvt(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let n=t.validateToolInput;if(typeof n!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,r){if(!e.inputSchema||!qvt(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=Ki(i.error);throw new hB(hz.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function qvt(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const R5=2e3,Jvt=2e3,Yvt=[`-iTCP`,`-sTCP:LISTEN`,`-nP`],Xvt=[/^open-knowledge-server(?:\s|$)/,/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function Zvt(e){return Xvt.some(t=>t.test(e))}function Qvt(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(`--ok-lock-dir-b64=`));if(t==null)return null;let n=t.slice(18);if(!n)return null;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);return Ps(e)?e:null}catch{return null}}function $vt(e){let t=e.indexOf(`--ok-project-path=`);if(t===-1)return null;let n=t+18,r=e.slice(n),i=r.search(/\s--/),a=(i===-1?r:r.slice(0,i)).trim();return a&&Ps(a)?a:null}function eyt(e){let t=[];for(let n of e.split(`
2080
2080
  `)){let e=n.trim();if(!e)continue;let r=e.indexOf(` `);if(r===-1)continue;let i=e.slice(0,r),a=e.slice(r+1),o=Number.parseInt(i,10);!Number.isNaN(o)&&Zvt(a)&&t.push({pid:o,command:a})}return t}function tyt(e,t,n){return new Promise((r,i)=>{let a=Os(e,t,hq({...mq,timeout:R5,env:{...process.env,LC_CTYPE:process.env.LC_ALL||process.env.LC_CTYPE,LC_ALL:void 0,LC_MESSAGES:`C`}})),o=!1,s=!1,c=``;a.once(`error`,i);let l=(e,t)=>{let n=``;e.once(`error`,i),e.setEncoding(`utf8`),e.on(`data`,e=>{n+=e;let r=n.indexOf(`
2081
2081
  `);for(;r!==-1;)t(n.slice(0,r)),n=n.slice(r+1),r=n.indexOf(`
2082
2082
  `)}),e.once(`end`,()=>{n&&t(n)})};l(a.stdout,e=>{o=!0,n(e)}),l(a.stderr,e=>{s=!0,c||=e.trim()}),a.once(`close`,(e,t)=>{r({code:e,signal:t,timedOut:a.killed,hasStdout:o,hasStderr:s,diagnostic:c})})})}function z5(e){if(!(e instanceof Error))return String(e);let t=e.code;return t?`${t}: ${e.message}`:e.message}function nyt(e){let t=e.signal?`signal ${e.signal}`:`exit status ${e.code}`;return`${e.timedOut?`timed out after ${R5} ms (${t})`:t}${e.diagnostic?`: ${e.diagnostic}`:``}`}var ryt=class extends Error{result;constructor(e){super(nyt(e)),this.result=e}};async function iyt(e){let t=[],n=!0,r=await tyt(`ps`,e,e=>{if(n){n=!1;return}let r=e.trim(),i=r.indexOf(` `);if(i===-1)return;let a=Number.parseInt(r.slice(0,i),10),o=r.slice(i+1).trim();!Number.isNaN(a)&&Zvt(o)&&t.push({pid:a,command:o})});if(r.code!==0||r.signal)throw new ryt(r);if(n)throw Error(`no process table returned`);return t}async function ayt(e=!1){let t=[],n=process.platform===`darwin`||process.platform===`linux`;if(!n){let e=ks(`pgrep`,[`-a`,`-f`,`cli\\.mjs|open-knowledge|Open ?Knowledge(\\.app| Helper)|--ok-lock-dir-b64=|--ok-project-path=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`],hq({encoding:`utf-8`,timeout:R5}));if(!e.error&&(e.status===0||e.status===1)){let n=e.stdout??``,r=eyt(n);if(r.length>0||n.trim()===``)return r;t.push(`pgrep: no command rows returned`)}else t.push(`pgrep: ${e.error?z5(e.error):`exit status ${e.status}`}`)}let r=process.platform===`linux`?[[`-ww`,`-A`,`-o`,`pid,cmdline`],[`-ww`,`-A`,`-o`,`pid,args`],[`-A`,`-o`,`pid,args`]]:n?[[`-ww`,`-A`,`-o`,`pid,args`]]:[[`-axo`,`pid,command`]];for(let e of r)try{return await iyt(e)}catch(n){if(t.push(`ps (${e.join(` `)}): ${z5(n)}`),!(n instanceof ryt&&n.result.code===1&&!n.result.signal&&!n.result.hasStdout))break}if(e)throw Error(`Could not enumerate processes: ${t.join(`; `)}`);return[]}function oyt(e){let t=e.trim().split(/\s+/).filter(Boolean);for(let e of t){if(e.startsWith(`@`))continue;let t=js(e);if(t===`open-knowledge`||t===`ok`||e.endsWith(`/packages/cli/src/cli.ts`)||e.endsWith(`/packages/cli/dist/cli.mjs`)||t===`cli.mjs`||t===`cli.ts`)return e}return null}function syt(e){let t=ks(`ps`,[`-p`,String(e),`-o`,`command=`],hq({encoding:`utf-8`,timeout:R5}));return t.error!=null||!t.stdout?null:t.stdout.trim()||null}function cyt(e){let t=ks(`ps`,[`-p`,String(e),`-o`,`%cpu=,%mem=`],hq({encoding:`utf-8`,timeout:R5}));if(t.error!=null||!t.stdout)return null;let[n,r]=t.stdout.trim().split(/\s+/),i=Number.parseFloat(n??``),a=Number.parseFloat(r??``);return Number.isNaN(i)||Number.isNaN(a)?null:{cpuPercent:i,memPercent:a}}function lyt(e){return`[process-scan] could not read the state of process ${e.pid} (${e.reason}); treating it as not defunct\n`}function uyt(e,t,n){let r={pid:e,reason:t};return n.onProbeFailure?n.onProbeFailure(r):process.stderr.write(lyt(r)),{status:`unreadable`,reason:t}}function B5(e,t={}){if(process.platform!==`darwin`&&process.platform!==`linux`)return{status:`unreadable`,reason:`no process-state query on ${process.platform}`};try{return Ds(`ps`,[`-p`,String(e),`-o`,`stat=`],hq({encoding:`utf8`,...mq,timeout:R5,env:{...process.env,LC_ALL:`C`}})).trim().startsWith(`Z`)?{status:`defunct`}:{status:`running`}}catch(n){if(!(n instanceof Error))return uyt(e,String(n),t);let r=n,i=String(r.stderr??``);return typeof r.status==`number`&&i.trim()===``?{status:`gone`}:uyt(e,(i.split(`
@@ -2193,7 +2193,7 @@ ${uEt}
2193
2193
  `)){let t=e.indexOf(`:`);if(t<0)continue;let r=e.slice(0,t).trim(),i=Number.parseInt(e.slice(t+1).trim(),10);r&&n.set(r,Number.isFinite(i)?i:0)}return{looseObjects:n.get(`count`)??0,looseKiB:n.get(`size`)??0,packfiles:n.get(`packs`)??0,packedObjects:n.get(`in-pack`)??0}}function PEt(e){return G(W(e.gitDir,`gc.log`))}async function u9(e,t){let n=gK(e),r=t?`refs/wip/${t}/`:`refs/wip/`;try{return(await n.raw(`for-each-ref`,`--format=%(refname)`,r)).trim().split(`
2194
2194
  `).filter(Boolean).length}catch{return 0}}async function FEt(e,t){let n=gK(e),r;try{r=(await n.raw(`for-each-ref`,`--format=%(refname)%00%(committerdate:unix)%00%(contents:subject)`,`refs/wip/`)).trim().split(`
2195
2195
  `).filter(Boolean)}catch{return 0}let i=0;for(let e of r){let[n=``,r=``,a=``]=e.split(`\0`);if(a.startsWith(`park:`))continue;let o=n.split(`/`).slice(3).join(`/`);if(!o||BS(o).classification!==`agent`)continue;let s=Number.parseInt(r,10);Number.isFinite(s)&&s*1e3<t&&(i+=1)}return i}const d9=q(`shadow-maintenance`),IEt=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),LEt=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})();function f9(){return process.env.OK_SHADOW_MAINTENANCE_DISABLED===`1`}function REt(e){return e===`boot`?`boot`:e===`session-close`?`session-close`:e===`ttl`?`ttl`:`dead-chain`}var zEt=class{running=!1;destroyed=!1;flushCommitCounter=0;lastConsolidationAt=0;lastGcLatch=!1;deps;constructor(e){this.deps=e}get isRunning(){return this.running}destroy(){this.destroyed=!0}noteFlushCommit(){f9()||this.destroyed||(this.flushCommitCounter+=1,this.flushCommitCounter>=200&&(this.flushCommitCounter=0,this.runScheduledMaintenance(`flush-counter`)))}async runBootMaintenance(){f9()||this.destroyed||await this.runScheduledMaintenance(`boot`)}async onSessionClose(){await this.runScheduledMaintenance(`session-close`)}async runScheduledMaintenance(e){if(!(f9()||this.destroyed)&&!this.running){this.running=!0;try{if(await this.consolidateInner(e),this.destroyed||(await this.reapInner(e),this.destroyed))return;await this.gcInner(e)}finally{this.running=!1}}}async runReap(e){if(!(f9()||this.destroyed)&&!this.running){this.running=!0;try{await this.reapInner(e)}finally{this.running=!1}}}async reapInner(e){if(!this.deps.projectGitDir)return;let t=this.deps.getShadow();if(!t)return;let n=performance.now();try{await TEt(t,this.deps.projectGitDir,void 0,this.deps.contentRoot??`.`),c9(`reap`,`ok`,performance.now()-n)}catch(t){c9(`reap`,`error`,performance.now()-n),d9.warn({trigger:e,err:t},`[shadow-maintenance] reap failed; retrying next trigger`)}}async consolidateDeadChains(e){if(f9()||this.destroyed)return{consolidated:!1,skipped:`disabled`};if(this.running)return{consolidated:!1,skipped:`busy`};this.running=!0;try{return await this.consolidateInner(e)}finally{this.running=!1}}async consolidateInner(e){let{getCurrentBranch:t,isWriterLive:n}=this.deps;if(!t||!n)return{consolidated:!1,skipped:`unconfigured`};if(Date.now()-this.lastConsolidationAt<LEt)return{consolidated:!1,skipped:`spacing`};let r=this.deps.getShadow();if(!r)return{consolidated:!1,skipped:`no-shadow`};try{let i=t()??`main`,a=await this.findDeadAgentChains(r,i,n);if(a.length<IEt)return{consolidated:!1,skipped:`below-threshold`,deadChains:a.length};let o=await u9(r,i);await jK(r,this.deps.contentRoot??``,a,i,void 0,{checkpointKind:{foldedRefs:a.length,trigger:REt(e)},timeoutMs:fK}),this.lastConsolidationAt=Date.now();let s=await u9(r,i);return NEt(REt(e)),d9.info({trigger:e,branch:i,foldedChains:a.length,widthBefore:o,widthAfter:s},`[shadow-maintenance] auto-consolidation folded dead agent chains`),{consolidated:!0,deadChains:a.length,widthBefore:o,widthAfter:s}}catch(t){return d9.warn({trigger:e,err:t},`[shadow-maintenance] consolidation failed; retrying next trigger`),{consolidated:!1,skipped:`error`}}}async findDeadAgentChains(e,t,n){return(await _K(e,t)).filter(e=>e.classification===`agent`&&!e.isPark&&!n(e.writerId)).map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`}))}async runGc(e){if(f9())return{ran:!1,skipped:`disabled`};if(this.destroyed)return{ran:!1,skipped:`no-shadow`};if(this.running)return c9(`gc`,`skipped`,0),{ran:!1,skipped:`busy`};this.running=!0;try{return await this.gcInner(e)}finally{this.running=!1}}async gcInner(e){let t=this.deps.getShadow();return t?lK(t).withExclusive(()=>this.gcRun(e,t)):{ran:!1,skipped:`no-shadow`}}async gcRun(e,t){let n=performance.now();try{let r=await l9(t);await gK(t,{timeoutMs:fK}).raw(`gc`,`--auto`);let i=await l9(t),a=PEt(t),o=performance.now()-n;return c9(`gc`,`ok`,o),a&&(this.lastGcLatch||MEt(),d9.warn({trigger:e,looseObjects:i.looseObjects},`[shadow-maintenance] gc.log latch present — auto-gc disabled until it self-expires (~1 day); retrying next trigger`)),this.lastGcLatch=a,d9.info({trigger:e,looseBefore:r.looseObjects,looseAfter:i.looseObjects,packfiles:i.packfiles,durationMs:Math.round(o)},`[shadow-maintenance] gc complete`),{ran:!0,looseBefore:r.looseObjects,looseAfter:i.looseObjects,packfilesAfter:i.packfiles,latch:a,durationMs:o}}catch(t){return c9(`gc`,`error`,performance.now()-n),d9.warn({trigger:e,err:t},`[shadow-maintenance] gc failed; retrying next trigger`),{ran:!1,skipped:`error`}}}};function BEt(e){return new zEt(e)}async function VEt(e,t,n){let r=q(`managed-artifact-watcher`),i=Array.from(new Set(e));for(let e of i)try{kG(e,{recursive:!0})}catch(t){iq(t)!==`EEXIST`&&r.warn({err:t,dir:e},`failed to create watch root; watcher may be inert`)}let a=new Map,o=e=>{let n;try{n=K(e,`utf-8`)}catch(t){if(iq(t)===`ENOENT`){r.debug({path:e},`managed-artifact leaf disappeared between event and read; dropping`);return}r.warn({err:t,path:e},`managed-artifact leaf read failed; dropping event`);return}if(n!==a.get(e)){a.set(e,n);try{t(e,n)}catch(t){r.warn({err:t,path:e},`managed-artifact change handler threw`)}}},s=e=>{if(a.delete(e),r.debug({path:e},`managed-artifact leaf unlinked; live doc retained at current state`),n)try{n(e)}catch(t){r.warn({err:t,path:e},`managed-artifact unlink handler threw`)}},c=new Map,l=new Map,u=async e=>{let t;try{t=await yc(e)}catch(t){let n=iq(t);return n===`ENOENT`?(l.delete(e),c.set(e,[]),[]):((!l.has(e)||l.get(e)!==n)&&(l.set(e,n),r.warn({err:t,root:e},`failed to list watch root; keeping its previous listing`)),c.get(e)??[])}l.delete(e);let n=[H(e,`SKILL.md`),...t.map(t=>H(e,t,`SKILL.md`))];return c.set(e,n),n};return I7({listPaths:async()=>(await Promise.all(i.map(u))).flat(),onEvent:(e,t)=>e===`unlink`?s(t):o(t),onError:(e,t)=>{r.warn({err:e,path:t},`[managed-artifact-watcher] poll error`)}})}const p9=q(`mermaid-persistence`),HEt={source:`local`,skipStoreHooks:!0,context:{origin:`mermaid-source`}};function UEt(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let n=W(t,WK(e));if(!nq(n,t))throw Error(`Invalid document name: ${e}`);return n}function WEt(e,t,n){let r=e.getText(`source`);e.transact(()=>{r.length>0&&r.delete(0,r.length),t.length>0&&r.insert(0,t),n&&e.getMap(`lifecycle`).set(Vc,crypto.randomUUID())},HEt)}function GEt(e,t,n){if(e.getText(`source`).length>0)return;let r=UEt(t,n.contentDir);if(n.assertContentPath?.(r),!G(r))return;let i;try{sJ(r,n.contentDir),i=K(r,`utf-8`)}catch(e){p9.warn({documentName:t,err:e},`load: could not read; seeding empty`);return}WEt(e,i,!0),n.lkgCache.set(t,i)}async function KEt(e,t,n,r){if(n===HEt)return`no-op`;let i=e.getText(`source`).toString(),a=r.lkgCache.get(t);if(i===a)return`no-op`;let o=UEt(t,r.contentDir);try{if(sJ(o,r.contentDir),r.assertContentPath?.(o),await EG(W(o,`..`),{recursive:!0}),G(o)){let n=null;try{n=K(o,`utf-8`)}catch(e){e.code!==`ENOENT`&&p9.warn({documentName:t,err:e},`store: pre-write disk read failed (non-ENOENT); proceeding to write`),n=null}if(n!==null&&n!==a&&n!==i)return WEt(e,n,!1),r.lkgCache.set(t,n),`reconciled`}return await YS(o,i,{fs:GQe(e=>{sJ(e,r.contentDir),r.assertContentPath?.(e)})}),r.lkgCache.set(t,i),`persisted`}catch(e){return p9.warn({documentName:t,err:e},`store: write failed`),`write-failed`}}function qEt(e){let{body:t}=Ba(e);return jt(t).trim()}function JEt(e){return e===` `||e===`
2196
- `||e===` `||e===`\r`}function YEt(e,t){let n=qEt(t);if(n.length===0)return{kind:`allow`,reason:`empty-base`};let r=qEt(e);if(r===n)return{kind:`allow`,reason:`identical`};if(r.length<n.length*2)return{kind:`allow`,reason:`too-short`};let i=0,a=0;for(;i<r.length;){if(r.slice(i,i+n.length)!==n)return{kind:`allow`,reason:`not-integer-multiple`};for(i+=n.length,a++;i<r.length&&JEt(r[i]??``);)i++}return a>=2?{kind:`block`,reason:`structural-duplication`,copies:a}:{kind:`allow`,reason:`single-copy`}}const m9=q(`persistence`);var XEt=class extends Error{docName;size;limit;constructor(e,t,n=Eoe){super(`Document "${e}" is ${_i(t)}; OpenKnowledge opens documents up to ${_i(n)}.`),this.name=`DocumentOpenSizeLimitError`,this.docName=e,this.size=t,this.limit=n}};function ZEt(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(n.source===`local`){let e=n.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?SK:e.origin===`upstream-import`||e.origin===`git-upstream`?CK:wK}if(n.source===`connection`){let e=n.connection?.context;if(typeof e?.principalId==`string`){let n=e.principalId,r=t?.();return r&&r.id===n&&r.display_name&&r.display_email?{id:r.id,name:r.display_name,email:r.display_email}:{id:n,name:`Local User`,email:`${n}@openknowledge.local`}}return wK}return null}var QEt=class extends Error{constructor(e){super(e),this.name=`DuplicationBaselineUnavailableError`}};const $Et=new Set([`EACCES`,`EBADF`,`EBUSY`,`EEXIST`,`EISDIR`,`ELOOP`,`EMFILE`,`ENFILE`,`ENOENT`,`ENOSPC`,`ENOTDIR`,`EPERM`,`EROFS`,`ETXTBSY`,`EXDEV`]);function eDt(e){if(typeof e!=`object`||!e)return`unknown`;if(e instanceof QEt)return`duplication-baseline-unavailable`;let t=e,n=typeof t.message==`string`?t.message:``;return n.startsWith(`symlink-escape:`)?`disk-write`:typeof t.code==`string`&&$Et.has(t.code)?n.includes(`rename`)?`traced-rename`:`disk-write`:e instanceof ta?`serialize`:`unknown`}function tDt(e){return{sv:NT(e),json:VD(e.getXmlFragment(`default`),wa).toJSON()}}function nDt(e){let{frontmatter:t,body:n}=Ba(e);return jt(Gi(t,n))}function rDt(e){let t=e.getConnectionsCount;if(typeof t!=`function`)return 0;try{let n=t.call(e);return typeof n==`number`&&Number.isFinite(n)?n:0}catch{return 0}}const iDt=new Set([`ENOENT`,`ENOTDIR`]);function aDt(e){let t=iq(e);return t!==void 0&&iDt.has(t)?{onDisk:!1}:{error:e}}function oDt(e){try{let t=Ys(e,{throwIfNoEntry:!1});if(t===void 0)return{onDisk:!1};if(!t.isSymbolicLink())return{onDisk:!0}}catch(e){return aDt(e)}try{return nc(e),{onDisk:!0}}catch(e){return aDt(e)}}function h9(e){let t;try{let n=e?.code;typeof n==`string`&&(t=n)}catch{}let n=`unknown store error`;try{n=e instanceof Error?e.message:String(e)}catch{}return{code:t,message:n}}function sDt(e){let t=e?.durabilityState??new D4,n=oq(W(e?.contentDir??process.cwd()),{root:`content`,component:`persistence`}),r=oq(W(e?.projectDir??process.cwd()),{root:`project`,component:`persistence`}),i=e?.shadowRef,a=e?.contentRoot||tq(U(r,n))||`.`,o=e?.derivedDocumentIndex,s=e?.getPrincipal,c=e?.onAgentCommit,l=e?.onFlushCommit,u=e?.onDiskFlush,d=e?.onConfigPersisted,f=e?.onManagedSkillPersisted,p=e?.mdManager??La,m=e?.ephemeral??!1,h=(t,n)=>{let r=e?.lifecycleOf?.(t,n);if(r===void 0){let e=t.getMap(`lifecycle`).get(`status`);return LJ(e)?e:null}return r===null?null:r.status},g={projectDir:r,contentDir:n,lkgCache:new Map,homedirOverride:e?.configHomedirOverride,onConfigRejected:e?.onConfigRejected,ephemeral:m},_=new Map,v={projectDir:r,homedirOverride:e?.configHomedirOverride,lkgCache:_,setReconciledBase:(e,n)=>t.setReconciledBase(e,n),getReconciledBase:e=>t.getReconciledBase(e),beforeReconcileDivergence:(e,t,n,r)=>Ce(e,t,n,r)},y=new Map,b={assertContentPath:e?.assertContentPath,contentDir:n,lkgCache:y},x=new Set,S=new Set,C=new Set,w=e?.applyDiskContentToDoc??J$,T=null,E=new Map,D=new Map,O=e?.gitEnabled??!0,k=e?.commitDebounceMs??15e3,ee=e?.wipRef??`refs/wip/main`,A=e?.getCurrentBranch,j=null,M=0,N=null,te=!1,ne=null,P=new Map;async function re(){De();let e=Date.now();return oG(`persistence.commitToWipRef`,void 0,async()=>await ie()).finally(()=>{Ee?.record((Date.now()-e)/1e3)})}async function ie(){let e=i?.current;if(e){let t=C9e(),n=det(d1(e.gitDir)),r=A?.()??`main`;if(t.size===0){let t={v:1,writer_id:wK.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:wK.name,color_seed:wK.id,docs:[]},i=`${e_e([])}\n\n${IS(t)}`;try{let t=await yK(e,wK,a,i,r);M=0,m9.info({sha:t.slice(0,8),writer:wK.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${wK.id}`);try{fet(e.gitDir,wK.id,t,d1(e.gitDir),n)}catch(e){m9.warn({err:e},`[rename-log] service-writer backfill failed`)}}catch(e){M++,ZG(),m9.error({err:e,attempt:M},`[persistence] Shadow commit failed (attempt ${M})`),M>=3&&m9.error({err:e,attempt:M},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let i;try{i=await xK(e,a)}catch(e){w9e(t),M++,ZG(),m9.error({err:e,attempt:M},`[persistence] Shadow WIP tree build failed (attempt ${M})`);return}let o=!1;for(let[a,s]of t){let t={id:a,name:s.displayName,email:`${a}@openknowledge.local`},u=[...s.docs],d=s.actor,f=[...s.summaries],p=[...s.previousPaths],m={v:1,writer_id:a,principal:d?.principalId??null,agent_session:a.startsWith(`agent-`)?a.slice(6):null,agent_type:d?.agentType??null,client_name:d?.clientName??null,client_version:d?.clientVersion??null,label:d?.label??null,display_name:s.displayName,color_seed:s.colorSeed,docs:u,...f.length>0?{summaries:f}:{},...p.length>0?{previous_paths:p}:{}},h=`${c_e(s.subjectOverride??e_e(u),f)}\n\n${IS(m)}`;try{let s=await sXe(e,t,i,h,r);o=!0;try{l?.()}catch(e){m9.warn({err:e},`[persistence] onFlushCommit callback failed (non-fatal)`)}m9.info({sha:s.slice(0,8),writer:a,tree:i.slice(0,8)},`[persistence] Shadow WIP commit: ${s.slice(0,8)} on refs/wip/${a}`);try{fet(e.gitDir,a,s,d1(e.gitDir),n)}catch(e){m9.warn({err:e},`[rename-log] backfill failed; will retry next commit`)}a.startsWith(`agent-`)&&c?.()}catch(e){E9e(a,s),uJe(),m9.error({err:e,writer:a},`[persistence] Per-writer shadow commit failed for ${a}`)}}o?M=0:(M++,ZG(),M>=3&&m9.error({attempt:M},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=gK({gitDir:W(r,`.git`),workTree:r}),n=W(r,`.git/index-wip`),o={GIT_INDEX_FILE:n};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(o).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?m9.info({},`[persistence] Empty repo — starting with empty index`):m9.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(o).raw(`add`,...Wt([a]));let e=(await t.env(o).raw(`write-tree`)).trim(),n=null;try{n=(await t.raw(`rev-parse`,ee)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let r=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];n&&r.push(`-p`,n);let i=(await t.raw(...r)).trim();await t.raw(`update-ref`,ee,i),M=0,m9.info({sha:i.slice(0,8),wipRef:ee},`[persistence] Git commit: ${i.slice(0,8)} on ${ee}`)}catch(e){M++,ZG(),m9.error({err:e,attempt:M},`[persistence] Git commit failed (attempt ${M})`),M>=3&&m9.error({err:e,attempt:M},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{MG(n)}catch{}}}function ae(e){if(e<=0)return k;let t=2**Math.min(e,5),n=Math.random()*.25*k;return k*t+n}function oe(){O&&(t.isBatchInProgress()||(j&&clearTimeout(j),j=setTimeout(()=>{if(j=null,N){te=!0;return}N=re().finally(()=>{N=null,te&&(te=!1,oe())})},ae(M))))}async function se(){j&&(clearTimeout(j),j=null,N||=re().finally(()=>{N=null,te&&(te=!1,oe())})),N&&await N}function ce(t,n){try{let{frontmatter:r,body:i}=Ba(t),a=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:n}:void 0,o=p.parseWithFallback(i,a),s=p.serialize(o);return jt(Gi(r,s))}catch(e){return m9.debug({err:e,documentName:n},`[g8] ephemeral canonical baseline failed; falling through to write`),null}}function le(t,n,r){e?.getLossRing?.()?.record({event:`repair-rebuild`,docName:r,writerId:null,direction:`b`,site:ue,connections:rDt(t)});try{let i=t.getXmlFragment(`default`),a=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:r}:void 0,o=La.parseWithFallback(n,a),s=wa.nodeFromJSON(o);t.transact(()=>{zD(t,i,s,{mapping:new Map,isOMark:new Map})},CZ)}catch(e){dYe(),m9.warn({err:e,documentName:r},`[persistence] reconcileFragmentNow failed for ${r}`)}}let ue=`persistence-prewrite`,de=`persistence-duplication-reset`,fe=`persistence-divergence-realign`,pe=`managed-artifact-reconcile`,me=new WeakMap;function he(t,n){KJe(),e?.getLossRing?.()?.record({event:`persistence-hold`,docName:t,writerId:null,direction:`b`,site:ue,lostLen:n.reduce((e,t)=>e+t.length,0)})}function ge(t,n,r,o,s){if(qJe(),me.get(t)===r){YJe();return}me.set(t,r);let c=Er(r,o,``),l=c.reduce((e,t)=>e+t.length,0),u=e?.getLossRing?.(),d=i?.current;if(!d){u?.record({event:hG,docName:n,writerId:null,direction:`b`,site:ue,lostLen:l,witnessAvailable:s});return}let f=A?.()??`main`;queueMicrotask(()=>{kK(d,a,{kind:`persistence-reconcile-loss`,docName:n,contents:r,label:`Before persistence fragment rebuild @ ${new Date().toISOString()}`,branch:f,metadata:{atRiskLines:c.length,witnessAvailable:s}}).then(e=>{JJe(),u?.record({event:hG,docName:n,writerId:null,direction:`b`,site:ue,lostLen:l,witnessAvailable:s,checkpointSha:e}),console.warn(JSON.stringify({event:`persistence-reconcile-loss-checkpoint-created`,docName:n,sha:e,kind:`persistence-reconcile-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{me.get(t)===r&&me.delete(t);let i=e instanceof Error?e:Error(String(e));m9.warn({documentName:n,err:i},`[persistence] reconcile-loss checkpoint write failed`),u?.record({event:hG,docName:n,writerId:null,direction:`b`,site:ue,lostLen:l,witnessAvailable:s})})})}let _e=new WeakMap;function ve(e){let t=fq(e,n);if(!G(t))return{kind:`missing`};let r=null;try{r=aq(t)}catch(t){return m9.warn({err:t,documentName:e},`[persistence] Tripwire baseline read failed (realpath) for ${e}`),{kind:`unavailable`,reason:`read-failed`}}if(!pq(r,n)||aJ(t,r,n))return m9.warn({docName:e,originalPath:t,canonical:r,contentDir:n},`[persistence] symlink-escape on tripwire reset: ${t} → ${r}, skipping tripwire baseline read`),{kind:`unavailable`,reason:`escape`};try{return{kind:`ok`,content:K(r,`utf-8`)}}catch(t){return m9.warn({err:t,documentName:e,canonical:r},`[persistence] Tripwire baseline read failed (readFileSync) for ${e}`),{kind:`unavailable`,reason:`read-failed`}}}function ye(t,n,r,o,s){XJe();let c=e?.getLossRing?.(),l=i?.current;if(!l){c?.record({event:hG,docName:n,writerId:null,direction:`b`,site:de,lostLen:r.length});return}if(_e.get(t)===r){QJe();return}_e.set(t,r);let u=A?.()??`main`;queueMicrotask(()=>{kK(l,a,{kind:`persistence-duplication-reset`,docName:n,contents:r,label:`Before duplication reset @ ${new Date().toISOString()}`,branch:u,metadata:{copies:o,fragmentChildren:s}}).then(e=>{ZJe(),c?.record({event:hG,docName:n,writerId:null,direction:`b`,site:de,lostLen:r.length,checkpointSha:e}),console.warn(JSON.stringify({event:`persistence-duplication-reset-checkpoint-created`,docName:n,sha:e,kind:`persistence-duplication-reset`,timestamp:new Date().toISOString()}))}).catch(e=>{_e.get(t)===r&&_e.delete(t);let i=e instanceof Error?e:Error(String(e));m9.warn({documentName:n,err:i},`[persistence] duplication-reset checkpoint write failed`)})})}let be=new WeakMap;function xe(t,n,r,o){nYe();let s=e?.getLossRing?.(),c=i?.current;if(!c){s?.record({event:hG,docName:n,writerId:null,direction:`b`,site:fe,lostLen:r.length});return}if(be.get(t)===r){iYe();return}be.set(t,r);let l=A?.()??`main`;queueMicrotask(()=>{kK(c,a,{kind:`persistence-divergence-realign`,docName:n,contents:r,label:`Before divergence realign @ ${new Date().toISOString()}`,branch:l,metadata:{diskBytes:o.length,discardedBytes:r.length}}).then(e=>{rYe(),s?.record({event:hG,docName:n,writerId:null,direction:`b`,site:fe,lostLen:r.length,checkpointSha:e}),console.warn(JSON.stringify({event:`persistence-divergence-realign-checkpoint-created`,docName:n,sha:e,kind:`persistence-divergence-realign`,timestamp:new Date().toISOString()}))}).catch(e=>{be.get(t)===r&&be.delete(t);let i=e instanceof Error?e:Error(String(e));m9.warn({documentName:n,err:i},`[persistence] divergence-realign checkpoint write failed`)})})}let Se=new WeakMap;function Ce(t,n,r,o){let s=e?.getLossRing?.(),c={baselineFullMd:o,report:e=>{try{let t=MK(e);if(t.length===0)return;s?.record({event:pG,docName:n,writerId:SK.id,direction:`b`,site:pe,lostLen:t.reduce((e,t)=>e+t.length,0),digest:tn(t.join(`
2196
+ `||e===` `||e===`\r`}function YEt(e,t){let n=qEt(t);if(n.length===0)return{kind:`allow`,reason:`empty-base`};let r=qEt(e);if(r===n)return{kind:`allow`,reason:`identical`};if(r.length<n.length*2)return{kind:`allow`,reason:`too-short`};let i=0,a=0;for(;i<r.length;){if(r.slice(i,i+n.length)!==n)return{kind:`allow`,reason:`not-integer-multiple`};for(i+=n.length,a++;i<r.length&&JEt(r[i]??``);)i++}return a>=2?{kind:`block`,reason:`structural-duplication`,copies:a}:{kind:`allow`,reason:`single-copy`}}const m9=q(`persistence`);var XEt=class extends Error{docName;size;limit;constructor(e,t,n=Eoe){super(`Document "${e}" is ${_i(t)}; OpenKnowledge opens documents up to ${_i(n)}.`),this.name=`DocumentOpenSizeLimitError`,this.docName=e,this.size=t,this.limit=n}};function ZEt(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(n.source===`local`){let e=n.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?SK:e.origin===`upstream-import`||e.origin===`git-upstream`?CK:wK}if(n.source===`connection`){let e=n.connection?.context;if(typeof e?.principalId==`string`){let n=e.principalId,r=t?.();return r&&r.id===n&&r.display_name&&r.display_email?{id:r.id,name:r.display_name,email:r.display_email}:{id:n,name:`Local User`,email:`${n}@openknowledge.local`}}return wK}return null}var QEt=class extends Error{constructor(e){super(e),this.name=`DuplicationBaselineUnavailableError`}};const $Et=new Set([`EACCES`,`EBADF`,`EBUSY`,`EEXIST`,`EISDIR`,`ELOOP`,`EMFILE`,`ENFILE`,`ENOENT`,`ENOSPC`,`ENOTDIR`,`EPERM`,`EROFS`,`ETXTBSY`,`EXDEV`]);function eDt(e){if(typeof e!=`object`||!e)return`unknown`;if(e instanceof QEt)return`duplication-baseline-unavailable`;let t=e,n=typeof t.message==`string`?t.message:``;return n.startsWith(`symlink-escape:`)?`disk-write`:typeof t.code==`string`&&$Et.has(t.code)?n.includes(`rename`)?`traced-rename`:`disk-write`:e instanceof ta?`serialize`:`unknown`}function tDt(e){return{sv:NT(e),json:VD(e.getXmlFragment(`default`),wa).toJSON()}}function nDt(e){let{frontmatter:t,body:n}=Ba(e);return jt(Gi(t,n))}function rDt(e){let t=e.getConnectionsCount;if(typeof t!=`function`)return 0;try{let n=t.call(e);return typeof n==`number`&&Number.isFinite(n)?n:0}catch{return 0}}const iDt=new Set([`ENOENT`,`ENOTDIR`]);function aDt(e){let t=iq(e);return t!==void 0&&iDt.has(t)?{onDisk:!1}:{error:e}}function oDt(e){try{let t=Ys(e,{throwIfNoEntry:!1});if(t===void 0)return{onDisk:!1};if(!t.isSymbolicLink())return{onDisk:!0}}catch(e){return aDt(e)}try{return nc(e),{onDisk:!0}}catch(e){return aDt(e)}}function h9(e){let t;try{let n=e?.code;typeof n==`string`&&(t=n)}catch{}let n=`unknown store error`;try{n=e instanceof Error?e.message:String(e)}catch{}return{code:t,message:n}}function sDt(e){let t=e?.durabilityState??new D4,n=oq(W(e?.contentDir??process.cwd()),{root:`content`,component:`persistence`}),r=oq(W(e?.projectDir??process.cwd()),{root:`project`,component:`persistence`}),i=e?.shadowRef,a=e?.contentRoot||tq(U(r,n))||`.`,o=e?.derivedDocumentIndex,s=e?.getPrincipal,c=e?.onAgentCommit,l=e?.onFlushCommit,u=e?.onDiskFlush,d=e?.onConfigPersisted,f=e?.onManagedSkillPersisted,p=e?.mdManager??La,m=e?.ephemeral??!1,h=(t,n)=>{let r=e?.lifecycleOf?.(t,n);if(r===void 0){let e=t.getMap(`lifecycle`).get(`status`);return LJ(e)?e:null}return r===null?null:r.status},g={projectDir:r,contentDir:n,lkgCache:new Map,homedirOverride:e?.configHomedirOverride,onConfigRejected:e?.onConfigRejected,ephemeral:m},_=new Map,v={projectDir:r,homedirOverride:e?.configHomedirOverride,lkgCache:_,setReconciledBase:(e,n)=>t.setReconciledBase(e,n),getReconciledBase:e=>t.getReconciledBase(e),beforeReconcileDivergence:(e,t,n,r)=>Ce(e,t,n,r)},y=new Map,b={assertContentPath:e?.assertContentPath,contentDir:n,lkgCache:y},x=new Set,S=new Set,C=new Set,w=e?.applyDiskContentToDoc??J$,T=null,E=new Map,D=new Map,O=e?.gitEnabled??!0,k=e?.commitDebounceMs??15e3,ee=e?.wipRef??`refs/wip/main`,A=e?.getCurrentBranch,j=null,M=0,N=null,te=!1,ne=null,P=new Map;async function re(){De();let e=Date.now();return oG(`persistence.commitToWipRef`,void 0,async()=>await ie()).finally(()=>{Ee?.record((Date.now()-e)/1e3)})}async function ie(){let e=i?.current;if(e){let t=C9e(),n=det(d1(e.gitDir)),r=A?.()??`main`;if(t.size===0){let t={v:1,writer_id:wK.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:wK.name,color_seed:wK.id,docs:[]},i=`${e_e([])}\n\n${IS(t)}`;try{let t=await yK(e,wK,a,i,r);M=0,m9.info({sha:t.slice(0,8),writer:wK.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${wK.id}`);try{fet(e.gitDir,wK.id,t,d1(e.gitDir),n)}catch(e){m9.warn({err:e},`[rename-log] service-writer backfill failed`)}}catch(e){M++,ZG(),m9.error({err:e,attempt:M},`[persistence] Shadow commit failed (attempt ${M})`),M>=3&&m9.error({err:e,attempt:M},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let i;try{i=await xK(e,a)}catch(e){w9e(t),M++,ZG(),m9.error({err:e,attempt:M},`[persistence] Shadow WIP tree build failed (attempt ${M})`);return}let o=!1;for(let[a,s]of t){let t={id:a,name:s.displayName,email:`${a}@openknowledge.local`},u=[...s.docs],d=s.actor,f=[...s.summaries],p=[...s.previousPaths],m={v:1,writer_id:a,principal:d?.principalId??null,agent_session:a.startsWith(`agent-`)?a.slice(6):null,agent_type:d?.agentType??null,client_name:d?.clientName??null,client_version:d?.clientVersion??null,label:d?.label??null,display_name:s.displayName,color_seed:s.colorSeed,docs:u,...f.length>0?{summaries:f}:{},...p.length>0?{previous_paths:p}:{}},h=`${c_e(s.subjectOverride??e_e(u),f)}\n\n${IS(m)}`;try{let s=await sXe(e,t,i,h,r);o=!0;try{l?.()}catch(e){m9.warn({err:e},`[persistence] onFlushCommit callback failed (non-fatal)`)}m9.info({sha:s.slice(0,8),writer:a,tree:i.slice(0,8)},`[persistence] Shadow WIP commit: ${s.slice(0,8)} on refs/wip/${a}`);try{fet(e.gitDir,a,s,d1(e.gitDir),n)}catch(e){m9.warn({err:e},`[rename-log] backfill failed; will retry next commit`)}a.startsWith(`agent-`)&&c?.()}catch(e){E9e(a,s),uJe(),m9.error({err:e,writer:a},`[persistence] Per-writer shadow commit failed for ${a}`)}}o?M=0:(M++,ZG(),M>=3&&m9.error({attempt:M},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=gK({gitDir:W(r,`.git`),workTree:r}),n=W(r,`.git/index-wip`),o={GIT_INDEX_FILE:n};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(o).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?m9.info({},`[persistence] Empty repo — starting with empty index`):m9.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(o).raw(`add`,...Wt([a]));let e=(await t.env(o).raw(`write-tree`)).trim(),n=null;try{n=(await t.raw(`rev-parse`,ee)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let r=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];n&&r.push(`-p`,n);let i=(await t.raw(...r)).trim();await t.raw(`update-ref`,ee,i),M=0,m9.info({sha:i.slice(0,8),wipRef:ee},`[persistence] Git commit: ${i.slice(0,8)} on ${ee}`)}catch(e){M++,ZG(),m9.error({err:e,attempt:M},`[persistence] Git commit failed (attempt ${M})`),M>=3&&m9.error({err:e,attempt:M},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{MG(n)}catch{}}}function ae(e){if(e<=0)return k;let t=2**Math.min(e,5),n=Math.random()*.25*k;return k*t+n}function oe(){O&&(t.isBatchInProgress()||(j&&clearTimeout(j),j=setTimeout(()=>{if(j=null,N){te=!0;return}N=re().finally(()=>{N=null,te&&(te=!1,oe())})},ae(M))))}async function se(){if(N&&(j||te))return te=!0,await N,se();j&&(clearTimeout(j),j=null,N=re().finally(()=>{N=null,te&&(te=!1,oe())})),N&&await N}function ce(t,n){try{let{frontmatter:r,body:i}=Ba(t),a=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:n}:void 0,o=p.parseWithFallback(i,a),s=p.serialize(o);return jt(Gi(r,s))}catch(e){return m9.debug({err:e,documentName:n},`[g8] ephemeral canonical baseline failed; falling through to write`),null}}function le(t,n,r){e?.getLossRing?.()?.record({event:`repair-rebuild`,docName:r,writerId:null,direction:`b`,site:ue,connections:rDt(t)});try{let i=t.getXmlFragment(`default`),a=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:r}:void 0,o=La.parseWithFallback(n,a),s=wa.nodeFromJSON(o);t.transact(()=>{zD(t,i,s,{mapping:new Map,isOMark:new Map})},CZ)}catch(e){dYe(),m9.warn({err:e,documentName:r},`[persistence] reconcileFragmentNow failed for ${r}`)}}let ue=`persistence-prewrite`,de=`persistence-duplication-reset`,fe=`persistence-divergence-realign`,pe=`managed-artifact-reconcile`,me=new WeakMap;function he(t,n){KJe(),e?.getLossRing?.()?.record({event:`persistence-hold`,docName:t,writerId:null,direction:`b`,site:ue,lostLen:n.reduce((e,t)=>e+t.length,0)})}function ge(t,n,r,o,s){if(qJe(),me.get(t)===r){YJe();return}me.set(t,r);let c=Er(r,o,``),l=c.reduce((e,t)=>e+t.length,0),u=e?.getLossRing?.(),d=i?.current;if(!d){u?.record({event:hG,docName:n,writerId:null,direction:`b`,site:ue,lostLen:l,witnessAvailable:s});return}let f=A?.()??`main`;queueMicrotask(()=>{kK(d,a,{kind:`persistence-reconcile-loss`,docName:n,contents:r,label:`Before persistence fragment rebuild @ ${new Date().toISOString()}`,branch:f,metadata:{atRiskLines:c.length,witnessAvailable:s}}).then(e=>{JJe(),u?.record({event:hG,docName:n,writerId:null,direction:`b`,site:ue,lostLen:l,witnessAvailable:s,checkpointSha:e}),console.warn(JSON.stringify({event:`persistence-reconcile-loss-checkpoint-created`,docName:n,sha:e,kind:`persistence-reconcile-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{me.get(t)===r&&me.delete(t);let i=e instanceof Error?e:Error(String(e));m9.warn({documentName:n,err:i},`[persistence] reconcile-loss checkpoint write failed`),u?.record({event:hG,docName:n,writerId:null,direction:`b`,site:ue,lostLen:l,witnessAvailable:s})})})}let _e=new WeakMap;function ve(e){let t=fq(e,n);if(!G(t))return{kind:`missing`};let r=null;try{r=aq(t)}catch(t){return m9.warn({err:t,documentName:e},`[persistence] Tripwire baseline read failed (realpath) for ${e}`),{kind:`unavailable`,reason:`read-failed`}}if(!pq(r,n)||aJ(t,r,n))return m9.warn({docName:e,originalPath:t,canonical:r,contentDir:n},`[persistence] symlink-escape on tripwire reset: ${t} → ${r}, skipping tripwire baseline read`),{kind:`unavailable`,reason:`escape`};try{return{kind:`ok`,content:K(r,`utf-8`)}}catch(t){return m9.warn({err:t,documentName:e,canonical:r},`[persistence] Tripwire baseline read failed (readFileSync) for ${e}`),{kind:`unavailable`,reason:`read-failed`}}}function ye(t,n,r,o,s){XJe();let c=e?.getLossRing?.(),l=i?.current;if(!l){c?.record({event:hG,docName:n,writerId:null,direction:`b`,site:de,lostLen:r.length});return}if(_e.get(t)===r){QJe();return}_e.set(t,r);let u=A?.()??`main`;queueMicrotask(()=>{kK(l,a,{kind:`persistence-duplication-reset`,docName:n,contents:r,label:`Before duplication reset @ ${new Date().toISOString()}`,branch:u,metadata:{copies:o,fragmentChildren:s}}).then(e=>{ZJe(),c?.record({event:hG,docName:n,writerId:null,direction:`b`,site:de,lostLen:r.length,checkpointSha:e}),console.warn(JSON.stringify({event:`persistence-duplication-reset-checkpoint-created`,docName:n,sha:e,kind:`persistence-duplication-reset`,timestamp:new Date().toISOString()}))}).catch(e=>{_e.get(t)===r&&_e.delete(t);let i=e instanceof Error?e:Error(String(e));m9.warn({documentName:n,err:i},`[persistence] duplication-reset checkpoint write failed`)})})}let be=new WeakMap;function xe(t,n,r,o){nYe();let s=e?.getLossRing?.(),c=i?.current;if(!c){s?.record({event:hG,docName:n,writerId:null,direction:`b`,site:fe,lostLen:r.length});return}if(be.get(t)===r){iYe();return}be.set(t,r);let l=A?.()??`main`;queueMicrotask(()=>{kK(c,a,{kind:`persistence-divergence-realign`,docName:n,contents:r,label:`Before divergence realign @ ${new Date().toISOString()}`,branch:l,metadata:{diskBytes:o.length,discardedBytes:r.length}}).then(e=>{rYe(),s?.record({event:hG,docName:n,writerId:null,direction:`b`,site:fe,lostLen:r.length,checkpointSha:e}),console.warn(JSON.stringify({event:`persistence-divergence-realign-checkpoint-created`,docName:n,sha:e,kind:`persistence-divergence-realign`,timestamp:new Date().toISOString()}))}).catch(e=>{be.get(t)===r&&be.delete(t);let i=e instanceof Error?e:Error(String(e));m9.warn({documentName:n,err:i},`[persistence] divergence-realign checkpoint write failed`)})})}let Se=new WeakMap;function Ce(t,n,r,o){let s=e?.getLossRing?.(),c={baselineFullMd:o,report:e=>{try{let t=MK(e);if(t.length===0)return;s?.record({event:pG,docName:n,writerId:SK.id,direction:`b`,site:pe,lostLen:t.reduce((e,t)=>e+t.length,0),digest:tn(t.join(`
2197
2197
  `))})}catch(e){m9.warn({documentName:n,err:e},`[persistence] managed-artifact reconcile loss detection failed`)}}},l=k6(n),u=i?.current;if(!u||!l.managed||!l.versioned)return s?.record({event:hG,docName:n,writerId:null,direction:`b`,site:pe,lostLen:r.length}),c;if(Se.get(t)===r)return sYe(),c;Se.set(t,r);let d=A?.()??`main`,f=l.docKey;return queueMicrotask(()=>{kK(u,a,{kind:`managed-artifact-reconcile`,docName:f,contents:r,label:`Before artifact reconcile @ ${new Date().toISOString()}`,branch:d,metadata:{diskBytes:o.length,discardedBytes:r.length}}).then(e=>{oYe(),s?.record({event:hG,docName:n,writerId:null,direction:`b`,site:pe,lostLen:r.length,checkpointSha:e}),console.warn(JSON.stringify({event:`managed-artifact-reconcile-checkpoint-created`,docName:n,sha:e,kind:`managed-artifact-reconcile`,timestamp:new Date().toISOString()}))}).catch(e=>{Se.get(t)===r&&Se.delete(t);let i=e instanceof Error?e:Error(String(e));m9.warn({documentName:n,err:i},`[persistence] managed-artifact reconcile checkpoint write failed`)})}),c}let we=null,Te=null,Ee=null;function De(){if(we)return;let e=aG();we=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),Te=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),Ee=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}let Oe=new WeakSet;function ke(e,n,r,i=!1){if(E.delete(e),typeof n==`object`&&n&&Oe.add(n),!r)return;let a=iq(n),o=i||a===`ELOOP`;t.recordStoreFailure(e,o?{code:`OK_PATH_UNRESOLVABLE`,message:`the path for ${e} could not be resolved inside the content directory${a===void 0?``:` (${a})`}`}:h9(n))}function Ae(n,r,i,a,o){iJe(),console.warn(JSON.stringify({event:`persistence-store-removed-doc`,"doc.name":n,reason:o?.status??(e?.isRecentlyRemoved?.(n)?`recently-removed`:`file-absent`),baseBytes:r?.length??null,candidateBytes:i.length})),a&&t.recordStoreFailure(n,o?.removal?.kind===`path-occupied`?{code:x4,message:`${n} was ${o.status===`renamed`?`renamed`:`deleted`} on disk and the file now at its path has not been loaded into it, so the store was refused rather than overwriting that file`,removal:o.removal}:o?.removal?.kind===`renamed`?{code:x4,message:`${n} was renamed to ${o.removal.renamedTo} on disk, so the store was refused rather than recreating the file under its old name`,removal:o.removal}:{code:x4,message:`${n} is no longer on disk, so the store was refused rather than recreating the removed file`}),E.delete(n)}function je(e){try{return G(fq(e,n))}catch{return!1}}function Me(e,t,n){if(je(t))return{kind:`path-occupied`};let r=e.getMap(`lifecycle`).get(`newPath`);return n===`renamed`&&typeof r==`string`&&r!==``?{kind:`renamed`,renamedTo:r}:void 0}function Ne(e,t){return t!==void 0||C.has(e)}function Pe(e,t,n,r,i){let a=oDt(t);if(`error`in a)throw ke(e,a.error,i),m9.error({err:a.error,documentName:e,path:t},`[persistence] Could not determine whether ${t} still exists; store abandoned`),a.error;return a.onDisk?`on-disk`:(Ae(e,n,r,i),`refused`)}async function Fe({document:r,documentName:i,lastTransactionOrigin:a}){De();let c=Date.now(),l;return oG(`persistence.onStoreDocument`,{attributes:{"doc.name":i}},async()=>{let c=h(r,i);if(LJ(c)||D.delete(i),c!==null){if(m9.info({documentName:i,lifecycleStatus:c},`[persistence] Skipped store for ${i}: lifecycle=${c}`),LJ(c)){let e=t.consumeAgentWriteStore(i),n=t.getReconciledBase(i),a=r.getText(`source`).toString(),o=n??D.get(i);o===void 0&&D.set(i,a),(e||o!==void 0&&a!==o)&&Ae(i,n,a,e,{status:c,removal:Me(r,i,c)})}E.delete(i),x.delete(i);return}if(!C2e(r)){let e=E.get(i)??0;if(e<8){let t=XX(r);console.warn(JSON.stringify({event:`persistence-skip-non-quiescent`,"doc.name":i,wallClockMsSinceLastTransaction:t??null,deferCount:e})),wJe(),E.set(i,e+1);return}console.warn(JSON.stringify({event:`persistence-force-flush-during-burst`,"doc.name":i,wallClockMsSinceLastTransaction:XX(r)??null,deferCount:e})),TJe()}let d=t.consumeAgentWriteStore(i),{sv:f,json:g}=tDt(r),_=r.getText(`source`).toString(),v;try{v=e?.capturePublicationReceipt?.(r,i,f)}catch(e){m9.warn({err:e,documentName:i},`[persistence] capturePublicationReceipt callback failed`)}let y=t.beginStoreAttempt(i),{frontmatter:b,body:T}=Ba(_),O=Gi(b,T),k,ee=null;try{let t=p.serialize(g);ee=Gi(b,t),k=F2e(O,ee,{site:`persistence`,docName:i,suppressDevThrow:!0,canonicalizeBody:P2e(p,{resolveEmbed:e?.resolveEmbed,resolveSize:e?.resolveSize,docName:i})})}catch(e){bYe(),console.warn(JSON.stringify({event:`persistence-sanity-check-serialize-failed`,"doc.name":i,"error.type":e instanceof Error?e.constructor.name:typeof e,timestamp:new Date().toISOString()})),m9.warn({err:e,documentName:i},`[persistence] Sanity-check serialize failed for ${i}; proceeding with ytext bytes`),ee=null,k=!1}if(!k){let e=ee===null?void 0:D4e(r);ee!==null&&e!==void 0&&En(ee,O,e)?he(i,Er(ee,O,e)):(ee!==null&&ge(r,i,ee,O,e!==void 0),le(r,T,i))}let A=t.getReconciledBase(i),j=nDt(_),M=A!==void 0&&(d?O===A:j===jt(A)&&!fo(A,O));if(!M&&!d&&m&&A!==void 0){let e=ce(A,i);e!==null&&j===e&&(M=!0)}if(M){K$()>0&&oe(),t.clearStoreRefused(i),E.delete(i);return}if(A===void 0&&jt(O)===``){m9.warn({documentName:i},`[persistence] Skipped phantom write for ${i}: empty Y.Doc with no reconciled base`),E.delete(i);return}let N=ZEt(a,s);N&&N.id!==wK.id&&(D9e(N.id)||G$(i,N.id,N.name,N.id));let te;if(A===void 0){let e=ve(i);if(e.kind===`unavailable`){m9.warn({documentName:i,reason:e.reason},`[persistence] Tripwire baseline unavailable for ${i}; refusing store (fail-closed)`),tYe(),t.markStoreRefused(i);let n=new QEt(`duplication tripwire baseline unavailable for ${i}; store refused (fail-closed)`);switch(e.reason){case`escape`:ke(i,n,d,!0);break;case`read-failed`:d&&t.recordStoreFailure(i,{code:`OK_STORE_REFUSED`,message:n.message});break;default:{let t=e.reason;throw Error(`unhandled tripwire baseline failure reason: ${String(t)}`)}}throw n}e.kind===`missing`&&Ne(i,void 0)&&(eYe(),m9.warn({documentName:i},`[persistence] Tripwire has no baseline for ${i}: acknowledged base absent and file missing from disk; duplication check skipped`)),te=e.kind===`ok`?e.content:``}else te=A;{let t=YEt(O,te);if(t.kind===`block`&&S.has(i))$Je(),console.warn(JSON.stringify({event:`ok-persistence-duplication-spared`,"doc.name":i,candidateBytes:O.length,baseBytes:te.length,fragmentChildren:r.getXmlFragment(`default`).length,copies:t.copies,reason:t.reason}));else if(t.kind===`block`){if(x.has(i)){m9.warn({documentName:i},`[persistence] Tripwire breaker active — skipping duplicate store for ${i}`);return}let n=r.getXmlFragment(`default`).length;console.warn(JSON.stringify({event:`ok-persistence-duplication-blocked`,"doc.name":i,candidateBytes:O.length,baseBytes:te.length,fragmentChildren:n,copies:t.copies,reason:t.reason}));try{let a;if(A===void 0)a=te;else{let e=ve(i);a=e.kind===`ok`?e.content:A}ye(r,i,O,t.copies,n);let o=e?.getLossRing?.(),s={baselineFullMd:a,report:e=>{try{let t=MK(e);if(t.length===0)return;o?.record({event:pG,docName:i,writerId:SK.id,direction:`b`,site:de,lostLen:t.reduce((e,t)=>e+t.length,0),digest:tn(t.join(`
2198
2198
  `))})}catch(e){m9.warn({documentName:i,err:e},`[persistence] duplication-reset loss detection failed`)}}};r.transact(()=>{w(r,a,void 0,void 0,void 0,s)},q$),x.delete(i)}catch(e){x.add(i),m9.error({err:e,documentName:i},`[persistence] Tripwire reset failed for ${i}`)}E.delete(i);return}}l=jt(O),t.beginInFlightFlush(i,l);let ne;try{ne=fq(i,n),e?.assertContentPath?.(ne)}catch(e){if(e instanceof cq&&O===A){E.delete(i);return}throw ke(i,e,d),e}if(Ne(i,A)&&Pe(i,ne,A,O,d)===`refused`)return;await EG(V(ne),{recursive:!0});let P;try{P=await bc(ne)}catch(e){let t=iq(e);if(t===`ENOENT`){let e=!1;try{e=Ys(ne).isSymbolicLink()}catch(e){iq(e)!==`ENOENT`&&m9.warn({err:e,path:ne},`[persistence] lstat failed during broken-symlink check`)}e&&m9.warn({docName:i,reason:`broken-symlink`},`[persistence] broken-symlink fallback`),P=ne}else if(t===`ELOOP`)throw ke(i,e,d),m9.error({docName:i,path:ne,err:e},`[persistence] Symlink cycle at ${ne}`),Error(`Symlink cycle detected at ${ne}`);else throw ke(i,e,d),m9.error({docName:i,path:ne,err:e},`[persistence] Could not canonicalize ${ne}; store abandoned`),e}let re=P===ne?H(await bc(V(ne)),js(ne)):P,ie=!pq(re,n);if(ie||aJ(ne,re,n)){let e=`symlink-escape: ${ne} resolves to ${re} ${ie?`outside ${n}`:`inside private repository state`}`;m9.error({docName:i,originalPath:ne,canonical:re,contentDir:n},`[persistence] ${e}`);let t=Error(e);throw ke(i,t,d,!0),t}process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_DIVERGENCE===i&&await SG(P,`# NATIVE
2199
2199