@inkeep/open-knowledge 0.89.16 → 0.89.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/{cli-CQkMRa_G.mjs → cli-BuQzGzPO.mjs} +6 -6
  2. package/dist/cli.mjs +1 -1
  3. package/dist/constants-CE9Qkysz.mjs +1 -0
  4. package/dist/{dist-VzybC7-z.mjs → dist-BhC8nyIm.mjs} +4 -4
  5. package/dist/{dist-XwWqDkPC.mjs → dist-DHvKP_UT.mjs} +1 -1
  6. package/dist/index.mjs +1 -1
  7. package/dist/{init-DxC7Z5jW.mjs → init-CU_jp_VB.mjs} +2 -2
  8. package/dist/init-eLCLtu2C.mjs +1 -0
  9. package/dist/{launch-json-removal-C4bbs15k.mjs → launch-json-removal-6cuQ1qAw.mjs} +1 -1
  10. package/dist/loader-BFxyjO1X.mjs +1 -0
  11. package/dist/{loader-DNgqcHab.mjs → loader-DJZ7f8R6.mjs} +1 -1
  12. package/dist/{open-browser-BwRWmdWX.mjs → open-browser-CNemiJ5U.mjs} +1 -1
  13. package/dist/{preview-Dc0X6Mps.mjs → preview-BMDRXphT.mjs} +1 -1
  14. package/dist/preview-LjPDAgOZ.mjs +1 -0
  15. package/dist/public/assets/{AccountSection-CHozMHJY.js → AccountSection-CSvFA64l.js} +1 -1
  16. package/dist/public/assets/{ActivityModeContent-Bw_hkygk.js → ActivityModeContent-BeEHBujL.js} +1 -1
  17. package/dist/public/assets/{AddPropertiesButton-9WrUWSLv.js → AddPropertiesButton-CJJZzi_g.js} +1 -1
  18. package/dist/public/assets/{AgentDiffPane-C2XL5nKB.js → AgentDiffPane-AGmYrPS3.js} +1 -1
  19. package/dist/public/assets/{AttachmentsSection-DWPHcd9u.js → AttachmentsSection-dXC9U2jw.js} +1 -1
  20. package/dist/public/assets/{CodeMirrorPropInput-iuiSyr3U.js → CodeMirrorPropInput-DAPLoZsd.js} +1 -1
  21. package/dist/public/assets/{ContentRulesSection-CwTZfbU3.js → ContentRulesSection-Bl1nh_sg.js} +1 -1
  22. package/dist/public/assets/{DocumentContext-BrnilHCw.js → DocumentContext-C_V62Jnz.js} +1 -1
  23. package/dist/public/assets/{EditorModeToggle-BrJG24F9.js → EditorModeToggle-DFyNQqUw.js} +1 -1
  24. package/dist/public/assets/{ExcalidrawDocEditor-CrYSDJZa.js → ExcalidrawDocEditor-DjOv760p.js} +1 -1
  25. package/dist/public/assets/FeedbackForm-CSIICpjH.js +1 -0
  26. package/dist/public/assets/{ImportSkillDialog-C4yTUhzn.js → ImportSkillDialog-DGQSJIwL.js} +1 -1
  27. package/dist/public/assets/{LinkPreviewsSection-CPvt0_-V.js → LinkPreviewsSection-CT2-cY__.js} +1 -1
  28. package/dist/public/assets/{LintConfigEditor-CC-Njmt9.js → LintConfigEditor-BBMzeoSt.js} +1 -1
  29. package/dist/public/assets/{LintingSection-xx3jA9SB.js → LintingSection-DpgcbxBR.js} +1 -1
  30. package/dist/public/assets/ManagedArtifactProperties-Bx7dDQoA.js +1 -0
  31. package/dist/public/assets/{ManagedArtifactProperties-BXmH0rEd.js → ManagedArtifactProperties-kQXjpIek.js} +1 -1
  32. package/dist/public/assets/{Mermaid-CxlXMgBe.js → Mermaid-5SzEY_c6.js} +1 -1
  33. package/dist/public/assets/{MermaidDocEditor-CkUJSsuM.js → MermaidDocEditor-BauRjGLU.js} +1 -1
  34. package/dist/public/assets/{NetworkAccessSection-oUWWcJ3Q.js → NetworkAccessSection-DKPVtzCG.js} +1 -1
  35. package/dist/public/assets/{PropertyDisplayRow-C0wuxgaH.js → PropertyDisplayRow-BOU1XGil.js} +1 -1
  36. package/dist/public/assets/{PublishToGitHubDialog-BEsivwEf.js → PublishToGitHubDialog-CieaXg02.js} +1 -1
  37. package/dist/public/assets/{SchemaConfigEditor--0BzIDWv.js → SchemaConfigEditor-WHLnmGK8.js} +1 -1
  38. package/dist/public/assets/{SearchSection-CF4k2wpH.js → SearchSection-0gpn6Onk.js} +1 -1
  39. package/dist/public/assets/{SessionsHost-BY4avwao.js → SessionsHost-BqLElsPY.js} +2 -2
  40. package/dist/public/assets/{SettingsDialogBody-CxRuss5s.js → SettingsDialogBody-DDeCs2NP.js} +2 -2
  41. package/dist/public/assets/{ShareReceiveMissDialog-Jq675FPR.js → ShareReceiveMissDialog-DGHgw82u.js} +1 -1
  42. package/dist/public/assets/{SkillToolbarControls-DhO_7oFo.js → SkillToolbarControls-C6dQzTma.js} +1 -1
  43. package/dist/public/assets/{SourceEditor-HXBorBmQ.js → SourceEditor-B7nftbLi.js} +1 -1
  44. package/dist/public/assets/{SyncSection-ChOLwD4e.js → SyncSection-CFryevN1.js} +1 -1
  45. package/dist/public/assets/{SyncStatusBadge-60UuFcNQ.js → SyncStatusBadge-C1Jq0M-R.js} +1 -1
  46. package/dist/public/assets/{TerminalSection-ByS602GJ.js → TerminalSection-UODLjZM2.js} +1 -1
  47. package/dist/public/assets/{TerminalWindowApp-Bxe9lzty.js → TerminalWindowApp-Dg30Z9c_.js} +1 -1
  48. package/dist/public/assets/{TextDocEditor-BDu9Effd.js → TextDocEditor-C2pokr8q.js} +1 -1
  49. package/dist/public/assets/{ThreadView-D5pjOz6L.js → ThreadView-C3hih8Rs.js} +1 -1
  50. package/dist/public/assets/{TimelineDiffPane-C-HSZdUG.js → TimelineDiffPane-CrEUxGVZ.js} +1 -1
  51. package/dist/public/assets/{client-version-ZLuTUjxc.js → client-version-De5YUqCd.js} +1 -1
  52. package/dist/public/assets/{comment-chips-BLsxfsLU.js → comment-chips-XqE0meDC.js} +1 -1
  53. package/dist/public/assets/{config-provider--IjNiNEd.js → config-provider-B6Wc7odC.js} +1 -1
  54. package/dist/public/assets/{doc-undo-manager-BOSHctpN.js → doc-undo-manager-6aAAQ0l7.js} +1 -1
  55. package/dist/public/assets/{index-Rxt0MBvP.js → index-BHWPWHsX.js} +7 -7
  56. package/dist/public/assets/{lint-plugins-Do5gb9Bk.js → lint-plugins-BFM5fljk.js} +1 -1
  57. package/dist/public/assets/{pending-receive-nav-store-Dnu1-hGT.js → pending-receive-nav-store-CCFpDHhx.js} +1 -1
  58. package/dist/public/assets/{preferred-session-events-CWLHrXw_.js → preferred-session-events-BMs4wNq0.js} +1 -1
  59. package/dist/public/assets/{progress-BAVBxTN5.js → progress-BMFHTFAw.js} +1 -1
  60. package/dist/public/assets/{selection-context-SccCWsCG.js → selection-context-DogBIk_C.js} +1 -1
  61. package/dist/public/assets/{src-kn1hzJnb.js → src-Cgonq5HK.js} +1 -1
  62. package/dist/public/assets/{telemetry-impl-CVjfXtzn.js → telemetry-impl-B3B_Enx9.js} +1 -1
  63. package/dist/public/assets/{telemetry-startup-CPR-WILZ.js → telemetry-startup-COYoUaQM.js} +1 -1
  64. package/dist/public/assets/{typing-burst-detector-N41zR1Kr.js → typing-burst-detector-enojAr6V.js} +1 -1
  65. package/dist/public/assets/{use-activity-panel-4zj_H6cX.js → use-activity-panel-CP-4J86g.js} +1 -1
  66. package/dist/public/assets/{use-open-skill-BrvZzCof.js → use-open-skill-BHHips6e.js} +1 -1
  67. package/dist/public/assets/{use-terminal-enabled-D765hI7G.js → use-terminal-enabled-dlq3SEnX.js} +1 -1
  68. package/dist/public/assets/{use-timeline-entry-diff-DcqLjPgg.js → use-timeline-entry-diff-BE0aOIwR.js} +1 -1
  69. package/dist/public/index.html +20 -20
  70. package/dist/{registry-probes-GHqZp3df.mjs → registry-probes-B9h_KTDL.mjs} +1 -1
  71. package/dist/{removal-file-path-DTC03c-g.mjs → removal-file-path-BLhGZEoh.mjs} +1 -1
  72. package/dist/{repair-launch-json-BUIARjhY.mjs → repair-launch-json-E1w7BNDN.mjs} +1 -1
  73. package/dist/{repair-mcp-configs-BC23zYr3.mjs → repair-mcp-configs-BjDiEP7H.mjs} +1 -1
  74. package/dist/{src--0CO9dvR.mjs → src-CCfDOZtl.mjs} +1 -1
  75. package/dist/src-CO8aR5aE.mjs +1 -0
  76. package/dist/start-BjF0FeQP.mjs +1 -0
  77. package/dist/{start-BNfLccBi.mjs → start-DUun3ILD.mjs} +3 -3
  78. package/package.json +4 -4
  79. package/dist/constants-B7eEU3pc.mjs +0 -1
  80. package/dist/init-iUNp8cG7.mjs +0 -1
  81. package/dist/loader-DhJH1rjM.mjs +0 -1
  82. package/dist/preview-DfML4H1c.mjs +0 -1
  83. package/dist/public/assets/FeedbackForm-BvJ6Jio_.js +0 -1
  84. package/dist/public/assets/ManagedArtifactProperties-BzD5Fcqc.js +0 -1
  85. package/dist/src-CO_Gro2O.mjs +0 -1
  86. package/dist/start-TZp1iXmk.mjs +0 -1
@@ -1174,7 +1174,7 @@ ${yet(e).join(`
1174
1174
  `)){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&&mct(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){b$.warn({err:e},`[rename-log] WARN: gcRenameLog rebuild: git log --grep failed; skipping reconstruction`),n=``}let a=await Ict(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=Cx(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=Lct(a,o),m=Fct(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)||(C$(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)&&M$(e.gitDir,t),r.dropped>0&&(b$.warn({dropped:r.dropped,retained:r.retained},`[rename-log] gc swept ${r.dropped} dead entries (${r.retained} live remain)`),cct().add(r.dropped),x$().add(-r.dropped)),r.rebuilt>0&&x$().add(r.rebuilt),r}function Fct(e,t,n){let r=Mc(`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 Ict(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 A$(e,i)}catch(e){b$.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(`
1175
1175
  `)){let t=e.trim();t.length===40&&a.add(t)}r.set(t,a)}return r}function Lct(e,t){for(let[n,r]of e)if(r.has(t))return n;return`main`}async function Rct(e,t,n,r,i,a,o,s){let{chain:c}=Sct(t,r,i),l=await Promise.all(c.map(async t=>{if(t.renameCommit===null)return null;let n=await k$(e,t.renameCommit,r,s,t.anchors);return n.length===0?new Set:j$(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 kct(e,u);for(let e=0;e<u.length;e++)if(d[e])return u[e].path;return null}const zct=Y(`history`);function Bct(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 bJ(t,a)).filter(e=>!e.isPark);r=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[DJ],i=!0}}let o=await PJ(t,e.contentRoot??`.`,r,a,n.summary,i?{includeUpstream:!1}:void 0);zct.info({checkpointRef:o.checkpointRef},`checkpoint`);try{await N$(t,E$(t.gitDir))}catch(e){zct.warn({err:e},`[rename-log] post-saveVersion GC failed`)}return{checkpointRef:o.checkpointRef}}}}const Vct=`urn:ok:error:too-many-agent-sessions`,Hct=`Too many agent sessions.`,Uct=`The server is at its agent session limit, so this write was not applied and is safe to retry.`,Wct={committed:!1,retryAfterSeconds:10};function P$(e,t,n){Q(e,503,Vct,Hct,{handler:n,cause:t,detail:Uct,extensions:{...Wct,...yG[`urn:ok:error:too-many-agent-sessions`]},extraHeaders:{"Retry-After":`10`}})}function F$(e,t,n,r){Q(e,409,`urn:ok:error:both-kept`,`Edit saved; both versions of a block changed here and outside were kept.`,{handler:t,detail:`Your write landed and is saved to the file; do not retry it. Where a block was changed both here and outside, both versions are in the document, the version here first and the outside version directly under it. Re-read the document and, if your task calls for it, remove the duplicate with an ordinary edit.`,extensions:{...n,...r},logLevel:`debug`})}const Gct={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}};let Kct=null;function I$(){return Kct||=aH().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.`}),Kct}let qct=null;function Jct(){return qct||=aH().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`."}),qct}const Yct={handler:`agent-write-md`,preWriteMerge:!0,callerReadsWriteReport:!0},L$={handler:`acp-document-write`,preWriteMerge:!1,callerReadsWriteReport:!1},Xct=H({docName:V().min(1),file:V().min(1),markdown:V(),extension:Ri(wr).optional(),agentId:V().optional(),agentName:V().optional(),clientName:V().optional()}).strict(),Zct=H({...cie,timestamp:V().min(1)}).strict();function Qct(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:f,hocuspocus:p,options:m,getBridgeLossReporter:h,mergeHistory:g,agentPresenceBroadcaster:_,recordContentDivergenceGate:v,buildAgentActor:y,countNormalizedSummary:b,flushDiskAndDetectOutcome:x,respondPersistenceFailure:S,flushDocToDisk:C,agentFocusBroadcaster:w,onAgentWrite:T,computeOrphanHints:E,registerWrittenDocInFileIndex:D,prepareWriteLinkAdvisory:O,buildReconcileWarning:k,computeLintViolations:A,log:j,flushDocToGit:M,flushGitCommit:N,commitOkArtifactWrite:P,isSafeDocName:ee,shadowRef:te,getPrincipal:F,contentRoot:I,safeDocPath:ne,getCurrentBranch:re,docTreePathCandidates:ie,stripDefaultPathTruncation:ae,renameAttributionCounter:oe}=e,se=Bct({getCurrentBranch:re,contentRoot:I});async function ce(){await Promise.all([...p.documents.values()].filter(e=>!_W(e.name)&&!vW(e.name)).map(async e=>{await p.debouncer.executeNow(`onStoreDocument-${e.name}`),await e.saveMutex.waitForUnlock()})),await N?.()}function le(e){try{return p.documents.get(e)?.connections.size??0}catch{return 0}}function ue(e,t,n){if(s(l,t)||(p.documents.get(t)?.getText(`source`).length??0)>0)return!1;let r=c(t);return Q(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,...yG[`urn:ok:error:doc-not-found`]}}),!0}function fe(){try{return p.documents.get(`__system__`)?.connections.size??0}catch{return 0}}let pe=ZQ(_te,(e,t,n)=>he(e,t,n,Yct),{handler:`agent-write-md`,method:`POST`});function me(e,t){return e!==t&&e!==UU(t)?!1:Ute(e).ok?!0:m.contentFilter!==void 0&&!m.contentFilter.isExcluded(t)}async function he(e,c,M,N){try{let e=n(),j=M.position??`append`,P=i(M.docName,c,N.handler);if(P===null)return;let ee=YU(a(P)),{agentId:te,suppliedWriterId:F,agentName:I,colorSeed:ne,clientName:re,clientVersion:ie,label:ae}=o(M);if(_W(ee)||vW(ee)){Q(c,400,`urn:ok:error:reserved-doc-name`,`'${ee}' is a reserved document name.`,{handler:N.handler,extensions:{...yG[`urn:ok:error:reserved-doc-name`]}});return}M.extension!==void 0&&!s(l,ee)&&KU(ee,M.extension);let oe=EQ(M.summary),{response:se,stored:ce}=u(oe);await d.withSessions(async n=>{let i=await n(ee,te,{displayName:I,colorSeed:ne,clientName:re}),a=N.preWriteMerge?await v$(f,p,ee,l,m.resolveEmbed,h?.(),t,g):g$,o=m.resolveEmbed?{resolveEmbed:m.resolveEmbed,sourcePath:ee}:void 0,s=await fQ(i.dc.document,M.markdown,j,o),u=new Date().toISOString(),d,P,L,ue=``;try{let e=ar(re),t=lo[e]??rt(ne??te);_?.setPresence(te,{displayName:I,icon:e,color:t,currentDoc:ee,mode:`writing`,ts:Date.now()}),P=$Q(i.dc.document.getText(`source`),te,i.origin,ne,re),mQ(i.dc.document,M.markdown,j),i.dc.document.transact(()=>{let e=gQ(i.dc.document);d=hQ(i.dc.document,M.markdown,j,o,s,pQ(i),F);let t=Xc(e,gQ(i.dc.document))??void 0;i.dc.document.getMap(`agent-flash`).set(te,{agentId:te,timestamp:Date.now(),type:`insert`,description:`Added (${I}): ${M.markdown.trim().slice(0,50)}`,...t===void 0?{}:{changedBlocks:t}})},i.origin),L=$W(i.dc.document),f.markAgentWriteStore(ee),ue=i.dc.document.getText(`source`).toString(),d!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":ee,position:j,intendedBytes:d.intendedBytes,actualBytes:d.actualBytes,byteDelta:d.byteDelta,"agent.id":te,"agent.client_name":re})),v(N.handler,d),t$(ee,te,I,ne,void 0,y({clientName:re,clientVersion:ie,label:ae}),ce),N.callerReadsWriteReport&&(aW(),b(oe))}finally{P?.(),_?.touchMode(te,`idle`)}let de=await x(ee,L);if(de?.kind===`failure`){S(c,de.failure,N.handler);return}if(de?.kind===`stale-external-write`){r(c,N.handler,ee);return}C(ee,N.handler),w?.setFocus(te,{agentName:I,currentDoc:ee,writeKind:`write`,ts:Date.now()}),T?.(),ue=p.documents.get(ee)?.getText(`source`).toString()??ue;let pe=SG(a,de,d!==void 0);if(!N.callerReadsWriteReport){if(D(ee,ue),pe.outcome===`both-kept`){F$(c,N.handler,{timestamp:u},pe);return}$(c,200,Zct,{timestamp:u,...pe},{handler:N.handler});return}let me=await E(ee);D(ee,ue);let he=await act(ue,ee),ge=(await O([ee]))(ue,ee,e.suppressLogLinkAdvisories),_e=le(ee),ve=fe();ve===0&&I$().add(1,{"shadow.writer":`agent`,"agent.type":AU(re)});let ye=k(a),be=d===void 0?void 0:pZ(d),xe=[...be?[be]:[],...ye?[ye]:[],...he??[],...await A(ue,ee,e),...ge.warnings],Se={timestamp:u,subscriberCount:_e,systemSubscriberCount:ve,...me?{hints:me}:{},...se?{summary:se}:{},...xe.length>0?{warnings:xe}:{},...ge.links};if(pe.outcome===`both-kept`){F$(c,N.handler,Se,pe);return}$(c,200,Lne,{...Se,...pe},{handler:N.handler})})}catch(n){if(n instanceof UJ){WJ(c,n,N.handler,t.findByDocName(UU(n.file)));return}if(n instanceof qK){s5e(c,n,N.handler);return}if(n instanceof mZ){hZ(c,n,N.handler);return}if(n instanceof vQ){P$(c,n,N.handler);return}j.error({err:n,requestId:HK(e)},`[${N.handler}] handler failed`),Q(c,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:N.handler,cause:n})}}let ge=ZQ(Xct,async(e,t,n)=>{if(!me(n.docName,n.file)){Q(t,400,`urn:ok:error:invalid-request`,`'${n.file}' is not a document OpenKnowledge keeps for the in-app agent.`,{handler:L$.handler,detail:`The path is excluded from the project content, so there is no document to write it through. Nothing was written.`,extensions:{outcome:`refused`,saved:!1,nextStep:`none`}});return}let{file:r,...i}=n;await he(e,t,{...i,position:`replace`},L$)},{handler:L$.handler,method:`POST`,maxBodyBytes:1/0});return{...HQ({"/api/agent-write-md":pe,"/api/frontmatter-patch":ZQ(ine,async(e,s,c)=>{try{let e=n(),v=i(c.docName,s,`frontmatter-patch`);if(v===null)return;let E=a(v),{agentId:A,agentName:j,colorSeed:M,clientName:N,clientVersion:P,label:ee}=o(c);if(_W(E)||vW(E)){Q(s,400,`urn:ok:error:reserved-doc-name`,`'${E}' is a reserved document name.`,{handler:`frontmatter-patch`,extensions:{...yG[`urn:ok:error:reserved-doc-name`]}});return}if(ue(s,E,`frontmatter-patch`))return;let te=c.patch??{},F=Object.keys(te),I=EQ(c.summary),{response:ne,stored:re}=u(I);await d.withSessions(async n=>{let i=await n(E,A,{displayName:j,colorSeed:M,clientName:N}),a=await v$(f,p,E,l,m.resolveEmbed,h?.(),t,g),o=await _ot(i.dc.document,te),c=new Date().toISOString(),u,d=!1,v=!1,ie=null,ae=[];try{let e=ar(N),t=lo[e]??rt(M??A);_?.setPresence(A,{displayName:j,icon:e,color:t,currentDoc:E,mode:`writing`,ts:Date.now()}),sH(`ok.frontmatter_patch`,{attributes:{"doc.name":E,"frontmatter_patch.keys":F.length}},()=>{i.dc.document.transact(()=>{let e=i.dc.document.getText(`source`).toString(),{fenced:t,body:n}=It(e),r=vi(t,te);if(!r.ok){u=r.error;return}for(let e of Object.keys(te))ae.push(e);if(r.nextFenced!==t){let e=t===``&&n!==``&&!n.startsWith(`
1176
1176
  `),a=Zte(r.nextFenced,(e?`
1177
- `:``)+n).md;kq(i.dc.document,a,`agent`,void 0,o),gZ(`mcp-write`),v=!0}d=!0},i.origin),v&&f.markAgentWriteStore(E)})}finally{_?.touchMode(A,`idle`)}let oe=i.dc.document.getText(`source`).toString();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)})`}}Q(s,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e,...yG[`urn:ok:error:invalid-frontmatter-patch`]}});return}if(d&&ae.length>0){if(t$(E,A,j,M,void 0,y({clientName:N,clientVersion:P,label:ee}),re),aW(),b(I),v){ie=await x(E);let e=ie;if(e?.kind===`failure`){S(s,e.failure,`frontmatter-patch`);return}if(e?.kind===`stale-external-write`){r(s,`frontmatter-patch`,E);return}}C(E,`frontmatter-patch`)}w?.setFocus(A,{agentName:j,currentDoc:E,writeKind:`write`,ts:Date.now()}),T?.();let se=le(E),ce=fe();ce===0&&I$().add(1,{"shadow.writer":`agent`,"agent.type":AU(N)});let L=k(a);oe=p.documents.get(E)?.getText(`source`).toString()??oe,D(E,oe);let ue=(await O([E]))(oe,E,e.suppressLogLinkAdvisories),de=[...L?[L]:[],...ue.warnings],pe={timestamp:c,subscriberCount:se,systemSubscriberCount:ce,appliedKeys:ae,...ne?{summary:ne}:{},...de.length>0?{warnings:de}:{},...ue.links},me=SG(a,ie);if(me.outcome===`both-kept`){F$(s,`frontmatter-patch`,pe,me);return}$(s,200,Xte,{...pe,...me},{handler:`frontmatter-patch`})})}catch(t){if(t instanceof vQ){P$(s,t,`frontmatter-patch`);return}j.error({err:t,requestId:HK(e)},`[frontmatter-patch] handler failed`),Q(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:t})}},{handler:`frontmatter-patch`,method:`POST`}),"/api/agent-patch":ZQ(nre,async(e,s,c)=>{try{let e=n(),{find:E,replace:j,offset:M}=c,N=i(c.docName,s,`agent-patch`);if(N===null)return;let P=a(N),{agentId:ee,suppliedWriterId:te,agentName:F,colorSeed:I,clientName:ne,clientVersion:re,label:ie}=o(c);if(_W(P)||vW(P)){Q(s,400,`urn:ok:error:reserved-doc-name`,`'${P}' is a reserved document name.`,{handler:`agent-patch`,extensions:{...yG[`urn:ok:error:reserved-doc-name`]}});return}if(ue(s,P,`agent-patch`))return;let ae=EQ(c.summary);await d.withSessions(async n=>{let i=await n(P,ee,{displayName:F,colorSeed:I,clientName:ne}),a=await v$(f,p,P,l,m.resolveEmbed,h?.(),t,g),o=m.resolveEmbed?{resolveEmbed:m.resolveEmbed,sourcePath:P}:void 0,c;{let e=i.dc.document.getText(`source`).toString(),{frontmatter:t,body:n}=an(e),r=Pa(t,n),a=M==null?r.indexOf(E):r.slice(M,M+E.length)===E?M:-1;if(a!==-1&&a>=t.length){let e=r.slice(0,a)+j+r.slice(a+E.length);c=await fQ(i.dc.document,an(e).body,`patch`,o)}}let d=new Date().toISOString(),N=!1,oe=!1,se=!1,ce=!1,L,ue;try{let e=ar(ne),t=lo[e]??rt(I??ee);if(_?.setPresence(ee,{displayName:F,icon:e,color:t,currentDoc:P,mode:`writing`,ts:Date.now()}),ue=$Q(i.dc.document.getText(`source`),ee,i.origin,I,ne),i.dc.document.transact(()=>{let e=i.dc.document.getText(`source`).toString(),{frontmatter:t,body:n}=an(e),r=Pa(t,n),a=M==null?r.indexOf(E):r.slice(M,M+E.length)===E?M:-1;if(a===-1){M==null?N=!0:oe=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":P,findLength:E.length,replaceLength:j.length,hadOffset:M!=null})),R0e();return}if(a<t.length){se=!0;return}let s=r.slice(0,a)+j+r.slice(a+E.length);if(t===``&&an(s).frontmatter!==``){ce=!0;return}let{body:l}=an(s),u=gQ(i.dc.document);L=hQ(i.dc.document,l,`patch`,o,c,pQ(i),te);let d=Xc(u,gQ(i.dc.document))??void 0;i.dc.document.getMap(`agent-flash`).set(ee,{agentId:ee,timestamp:Date.now(),type:`insert`,description:`Patched (${F}): ${E.slice(0,50)}`,...d===void 0?{}:{changedBlocks:d}})},i.origin),f.markAgentWriteStore(P),L!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":P,position:`patch`,intendedBytes:L.intendedBytes,actualBytes:L.actualBytes,byteDelta:L.byteDelta,"agent.id":ee,"agent.client_name":ne})),!N&&!oe&&!se&&!ce){let{stored:e}=u(ae);t$(P,ee,F,I,void 0,y({clientName:ne,clientVersion:re,label:ie}),e),aW(),b(ae),v(`agent-patch`,L)}}finally{ue?.(),_?.touchMode(ee,`idle`)}if(oe){Q(s,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`,extensions:{...yG[`urn:ok:error:stale-target`]}});return}if(N){Q(s,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`,extensions:{...yG[`urn:ok:error:target-not-found`]}});return}if(se){Jct().add(1,{result:`rejected`,reason:`intersect`}),Q(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`,extensions:{...yG[`urn:ok:error:frontmatter-edit-not-supported`]}});return}if(ce){Jct().add(1,{result:`rejected`,reason:`promoted`}),Q(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`,extensions:{...yG[`urn:ok:error:frontmatter-edit-not-supported`]}});return}let de=i.dc.document.getText(`source`).toString(),pe=await x(P);if(pe?.kind===`failure`){S(s,pe.failure,`agent-patch`);return}if(pe?.kind===`stale-external-write`){r(s,`agent-patch`,P);return}C(P,`agent-patch`),w?.setFocus(ee,{agentName:F,currentDoc:P,writeKind:`edit`,ts:Date.now()}),T?.();let me=le(P),he=fe();he===0&&I$().add(1,{"shadow.writer":`agent`,"agent.type":AU(ne)});let{response:ge}=u(ae);de=p.documents.get(P)?.getText(`source`).toString()??de,D(P,de);let _e=await act(de,P),ve=(await O([P]))(de,P,e.suppressLogLinkAdvisories),ye=k(a),be=L===void 0?void 0:pZ(L),xe=[...be?[be]:[],...ye?[ye]:[],..._e??[],...await A(de,P,e),...ve.warnings],Se={timestamp:d,subscriberCount:me,systemSubscriberCount:he,...ge?{summary:ge}:{},...xe.length>0?{warnings:xe}:{},...ve.links},Ce=SG(a,pe,L!==void 0);if(Ce.outcome===`both-kept`){F$(s,`agent-patch`,Se,Ce);return}$(s,200,Nre,{...Se,...Ce},{handler:`agent-patch`})})}catch(n){if(n instanceof UJ){WJ(s,n,`agent-patch`,t.findByDocName(UU(n.file)));return}if(n instanceof mZ){hZ(s,n,`agent-patch`);return}if(n instanceof vQ){P$(s,n,`agent-patch`);return}j.error({err:n,requestId:HK(e)},`[agent-patch] handler failed`),Q(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:n})}},{handler:`agent-patch`,method:`POST`}),"/api/agent-undo":ZQ(fne,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:p,clientVersion:h,label:g}=o(s);if(_W(t)||vW(t)){Q(n,400,`urn:ok:error:reserved-doc-name`,`'${t}' is a reserved document name.`,{handler:`agent-undo`,extensions:{...yG[`urn:ok:error:reserved-doc-name`]}});return}let{connectionId:v}=s,b,C;if(s.scope===`count`?(b=`count`,C=s.count):b=s.scope===`session`||s.scope===`file`?`session`:`last`,!d.hasSession(t,v)){Q(n,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let T=await d.getSession(t,v),E=!1;try{let e=ar(p),n=lo[e]??rt(u??c);_?.setPresence(c,{displayName:l,icon:e,color:n,currentDoc:t,mode:`writing`,ts:Date.now()}),E=Cot(T,b,m.resolveEmbed?{resolveEmbed:m.resolveEmbed,sourcePath:t}:void 0,C),E&&(f.markAgentWriteStore(t),t$(t,v,l,u,void 0,y({clientName:p,clientVersion:h,label:g})))}finally{_?.touchMode(c,`idle`)}let D=null;if(E){D=await x(t);let e=D;if(e?.kind===`failure`&&!xG(e.failure)){S(n,e.failure,`agent-undo`);return}if(e?.kind===`stale-external-write`){r(n,`agent-undo`,t);return}M(t,`agent-undo`)}w?.setFocus(v,{agentName:v,currentDoc:t,writeKind:`undo`,ts:Date.now()}),$(n,200,$ee,{docName:t,scope:b,undone:E,...SG(void 0,D)},{handler:`agent-undo`})}catch(r){if(r instanceof UJ){WJ(n,r,`agent-undo`,t.findByDocName(UU(r.file)));return}j.error({err:r,requestId:HK(e)},`[agent-undo] handler failed`),Q(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:r})}},{handler:`agent-undo`,method:`POST`}),"/api/agent-activity":ZQ(L,async(e,t)=>{try{let n=DU(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(n===null){Q(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}let r=Mat(d,n);$(t,200,Ate,r,{handler:`agent-activity`})}catch(n){j.error({err:n,requestId:HK(e)},`[agent-activity] handler failed`),Q(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":ZQ(L,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=DU(n.searchParams.get(`agentId`)),i=n.searchParams.get(`docName`),o=n.searchParams.get(`keptCount`);if(r===null){Q(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!i||i.trim()===``){Q(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!ee(i)){Q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let s=a(i);if(_W(s)||vW(s)){Q(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))){Q(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){Q(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){Q(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){Q(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}=kat(u.undoStack,c,f,s);$(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:HK(e)},`[agent-burst-diff] handler failed`),Q(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":ZQ(de,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=o(n),s=te?.current;if(!s){Q(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){Q(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=EQ(typeof n.summary==`string`?n.summary:void 0);await ce();let f=await se.saveCheckpoint(s,{explicitWriters:l,agentWriter:u,summary:d.kind===`value`?d.value:void 0});$(t,200,bne,{checkpointRef:f.checkpointRef},{handler:`save-version`})}catch(n){j.error({err:n,requestId:HK(e)},`[save-version] handler failed`),Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:n})}},{handler:`save-version`,method:`POST`}),"/api/rollback":ZQ(qr,async(e,n,i)=>{let a=DQ(i,F);if(a.kind===`invalid-summary`){Q(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){WJ(n,new UJ({file:o.file}),`rollback`,o);return}let s=te?.current;if(!s){Q(n,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:c,commitSha:l}=i,d=I??`.`,h=ne(c,d);if(`error`in h){Q(n,400,`urn:ok:error:invalid-request`,h.error,{handler:`rollback`});return}let g=yJ(s),_=Date.now();try{await P(`rollback-read`);let e=E$(s.gitDir),t=O$(),i=await Rct(s,c,l,re?.()??`main`,e,e=>ie(e,d),t);if(i===null){Q(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`,extensions:{...yG[`urn:ok:error:doc-not-found`]}});return}let o=await g.raw(`show`,`${l}:${i}`),h=new Date().toISOString();await jJ(s,d,{action:`rollback`,context:{docName:c,targetSha:l}});let y=p.documents.get(c);if(!y){Q(n,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let C=m.resolveEmbed?{resolveEmbed:m.resolveEmbed,sourcePath:c}:void 0,T=await kZ(o,C),E;y.transact(()=>{Aq(y,o,C,T),E=kit(y.getText(`source`).toString(),o,`rollback`)},Gct),f.markAgentWriteStore(c),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:EQ(`Restored to ${e}`),r=u(n);D=t||!r.response?r.response:ae(r.response),t$(c,a.writerId,a.displayName,a.colorSeed,Dye(c,l),a.actor,r.stored),aW(),b(n,!t);break}case`principal`:{let e=u(a.summary);D=e.response,t$(c,a.writerId,a.displayName,a.colorSeed,Dye(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)}`)}oe().add(1,{kind:`rollback`,attribution_kind:a.kind});let O=await x(c);if(O?.kind===`failure`&&!xG(O.failure)){S(n,O.failure,`rollback`);return}if(O?.kind===`stale-external-write`){r(n,`rollback`,c);return}M(c,`rollback`);let k=Date.now()-_;Y(`rollback`).info({docName:c,from:l.slice(0,8),durationMs:k},`rollback`),a.kind===`agent`&&w?.setFocus(a.writerId,{agentName:a.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let A=E===void 0?void 0:pZ(E);$(n,200,Ne,{...SG(void 0,O,E!==void 0),restoredFrom:l,timestamp:h,...D?{summary:D}:{},...A?{warnings:[A]}:{}},{handler:`rollback`})}catch(e){Q(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`]}),acpDocumentWrite:ge}}const R$={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},$ct={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}},elt=[`document`,`server`,`presence`],tlt=[`docName`,`reset-okignore`];function nlt(e){return elt.includes(e)}function rlt(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 _W(e)||vW(e)}function x(){for(let e of Object.keys(t?.getPresenceMap()??{}))t?.clearPresence(e)}async function S(e){for(let t of d.documents.keys())t===e||b(t)||await y(t);x();for(let[e]of i?.entries()??[])i?.delete(e)}function C(){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 HQ({"/api/test-reset":ZQ(L,async(e,t)=>{try{let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`scope`)??`document`;if(!nlt(a)){Q(t,400,`urn:ok:error:invalid-request`,`scope must be one of ${elt.join(`, `)}.`,{handler:`test-reset`});return}if(a===`presence`){let e=tlt.find(e=>i.searchParams.has(e));if(e!==void 0){Q(t,400,`urn:ok:error:invalid-request`,`${e} cannot be combined with scope=presence: a presence-scope reset clears agent presence only.`,{handler:`test-reset`});return}x(),$(t,200,Cr,{scope:a},{handler:`test-reset`});return}if(a===`server`&&i.searchParams.has(`reset-okignore`)){Q(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){Q(t,400,`urn:ok:error:invalid-request`,`scope=server needs a server started with an isolated config home.`,{handler:`test-reset`});return}let o=YU(s(i.searchParams.get(`docName`)??`test-doc`)),f;try{f=AG(o,c)}catch(e){l.error({err:e,docName:o},`[test-reset] safeContentPath rejected docName`),Q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}if(a===`server`)try{await r?.()}catch(e){Q(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),mc(f,``,`utf-8`),await p?.testOnly?.resetDocumentForTest(o),a===`server`&&(await S(o),n?.()),i.searchParams.get(`reset-okignore`)!==`false`)try{let e=K(c,`.okignore`),t=d.documents.get($r);if(t){let e=t.getText(`source`);e.length>0&&t.transact(()=>{e.delete(0,e.length)},R$)}q(e)&&mc(e,``,`utf-8`),m&&(h(),await m.rebuildIgnorePatterns())}catch(e){l.warn({err:e},`[test-reset] okignore reset partial failure`)}g?.(`files`),$(t,200,Cr,a===`server`?{scope:a,residue:C()}:{},{handler:`test-reset`})}catch(e){Q(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":ZQ(L,async(e,t)=>{try{await _?.(),$(t,200,Eee,{},{handler:`test-flush-git`})}catch(n){l.error({err:n,requestId:HK(e)},`[test-flush-git] flush failed`),Q(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":ZQ(L,async(e,t)=>{try{if(!p?.testOnly){Q(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await p.testOnly.rescanBacklinksForTest(),$(t,200,yee,{},{handler:`test-rescan-backlinks`})}catch(e){Q(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":ZQ(L,async(e,t)=>{try{if(!v){Q(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await v(),g?.(`files`),$(t,200,jee,{},{handler:`test-rescan-files`})}catch(e){Q(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 ilt=dte,alt={claude:`claude`,codex:`codex`,cursor:`cursor-agent`,gemini:`gemini`,opencode:`opencode`,pi:`pi`,antigravity:`agy`,copilot:`copilot`,openclaw:`openclaw`,hermes:`hermes`},olt={codex:()=>W(process.env.CODEX_HOME??W(_c(),`.codex`),`auth.json`)};function slt(e){let t=olt[e];if(t===void 0)return`unknown`;let n;try{return n=t(),q(n)?`present`:`unknown`}catch(t){return Y(`acp-harness`).warn({cli:e,credentialPath:n,err:t},`harness credential probe failed; treating as unknown`),`unknown`}}async function clt(e,t,n=oU){let r={cmd:alt[e],args:[],env:YH(),kind:`custom`,pathFromOverlay:!1};try{return await n(r),`present`}catch(i){if(!(i instanceof qH)||i.code!==`command-not-found`)return Y(`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 Y(`acp-harness`).warn({cli:e,err:o},`login-shell PATH capture failed; harness absence unverified — availability unknown`),`unknown`;try{return await n(NQe(r,a)),`present`}catch(t){return t instanceof qH&&t.code===`command-not-found`?`not-found`:(Y(`acp-harness`).warn({cli:e,err:t},`harness preflight on the login-shell PATH failed before absence could be verified; availability unknown`),`unknown`)}}}function llt(e={}){let t=e.resolveLoginShellPath??UH(Y(`acp-harness`)),n=e.preflight??oU,r=e.probe??(e=>clt(e,t,n)),i=e.credentials??slt,a=e.now??Date.now,o=e.ttlMs??6e4,s=[...new Set(Object.values(ilt))].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){Y(`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 Y(`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 ult=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 z$(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(plt(e,i)>1){let s=r;for(;!mlt(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 dlt(e,t){return H$(e,t).map(e=>({start:e,end:e+t.length}))}function flt(e,t,n,{contextIsMarkdown:r=!1}={}){let i=n.prefix??``,a=n.suffix??``,o=[],s=-1;for(let n of t){let t=Goe(e,n,{prefix:i,suffix:a},{syntaxIn:`haystack`,syntaxInContext:r});t>s?(s=t,o=[n]):t===s&&o.push(n)}return o}function B$(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=H$(e,n);if(s.length===0)return V$(e,t);let c=Koe(t,{syntaxInContext:!0}),l=t=>c===0||Goe(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}:V$(e,t)}let u=flt(e,s.map(e=>({start:e,end:e+n.length})),{prefix:r,suffix:i},{contextIsMarkdown:!0});if(!l(u[0]))return V$(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 V$(e,t){let{prefix:n,suffix:r,exact:i}=t,a=n===``?[0]:H$(e,n).map(e=>e+n.length),o=r===``?[e.length]:H$(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=qoe(i.length);return c-s>l?{status:`orphaned`}:{status:`anchored`,start:s,end:c,rewritten:!0}}function plt(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 H$(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 mlt(e,t,n,r){return plt(e,t+n+r)===1}function U$(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 hlt(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):null}function glt(e,t){if(t===``)return!1;let n=e.indexOf(t);return n!==-1&&e.indexOf(t,n+1)!==-1}var W$=class extends Error{},G$=class extends Error{},K$=class extends Error{},q$=class extends Error{},_lt=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??Nc}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=z$(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=z$(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 K$(n.target.key);let r=await this.requireDocBody(n.docName),{start:i,end:a}=this.resolveRange(r,t),o=z$(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:J$(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&&glt(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 G$){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 G$){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=B$(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?z$(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=B$(r,i);if(a.status===`orphaned`)return n.state===`orphaned`?n:this.mutate(e,{state:`orphaned`});let o=a.rewritten?z$(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 G$(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=dlt(e,n),i=r.length>0?r:Hoe(e,n,{syntaxIn:`haystack`});if(i.length===0)throw new q$(n);return i.length===1?i[0]:flt(e,i,{prefix:t.prefix,suffix:t.suffix})[0]}async requireMeta(e){let t=await this.store.readMeta(e);if(!t)throw new G$(e);return t}async requireDocBody(e){let t=await this.getDocBody(e);if(t===null)throw new W$(e);return t}async requirePropertyText(e,t,n){let r=await this.getDocFrontmatter(e);if(r===null)throw new W$(e);let i=U$(r,t,n);if(i===void 0)throw new K$(J$(t,n));let a=hlt(i);if(a===null)throw new K$(J$(t,n));return a}async requirePropertyTarget(e,t,n){let r=await this.getDocFrontmatter(e);if(r===null)throw new W$(e);if(U$(r,t,n)===void 0)throw new K$(J$(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=U$(i,t.key,t.path);if(a===void 0)return{state:`orphaned`};if(n===null)return{state:`anchored`};let o=hlt(a);if(o===null)return{state:`orphaned`};let s=B$(o,n);return s.status===`orphaned`?{state:`orphaned`}:s.rewritten?{state:`anchored`,anchor:z$(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 J$(e,t){let n=e;for(let e of t)n+=typeof e==`number`?`[${e}]`:`.${e}`;return n}var vlt=class{dir;log;writeQueues=new Map;dirReady=null;constructor(e,t){this.dir=W(e,`comments`),this.log=t}init(){return this.ensureDir()}ensureDir(){return this.dirReady??=yH(this.dir,{recursive:!0}).then(()=>void 0),this.dirReady}metaPath(e){return W(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=ga.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=ga.parse({...n,...ylt(t)});return await this.write(r),r})}write(e){return Fs(this.metaPath(e.threadId),blt(e),{fs:MH})}async readMeta(e){let t;try{t=await wc(this.metaPath(e),`utf8`)}catch{return null}let n=ga.safeParse(xlt(t));return n.success?n.data:(this.log.warn({threadId:e},`[comments] skipping unreadable thread meta`),null)}async scanCoverSheets(){let e;try{e=await Tc(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 _H(this.metaPath(e),{force:!0}),await _H(W(this.dir,`${e}.ndjson`),{force:!0})})}};function ylt(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 blt(e){return`${JSON.stringify(e,null,1)}\n`}function xlt(e){try{return JSON.parse(e)}catch{return}}const Y$=[`claude`,`codex`,`cursor`],X$=2e3,Slt={claude:[`Claude`],codex:[`Codex`],cursor:[`Cursor`]};function Clt(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(Y$.map(async e=>[e,await i(e)]));return Object.fromEntries(e)}return{probeAll:a,probeWithCache:i}}function wlt(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return Tlt(e)}catch{}let n=e.headers.origin;if(typeof n==`string`&&n.length>0)try{return Tlt(new URL(n).hostname)}catch{return!1}return!0}function Tlt(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function Elt(e,t,n){if(e.method!==`GET`){Q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{let r=wlt(e)?await n():Object.fromEntries(Y$.map(e=>[e,!0]));$(t,200,fi,r,{handler:`installed-agents`})}catch(e){Y(`handoff`).error({err:e},`[installed-agents] handler failed`),Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function Z$(e,t=Ic){return n=>e===`darwin`?Dlt(n,t):e===`win32`?Olt(n,t):klt(n,t)}function Dlt(e,t){let n=Slt[e];function r(e){return new Promise(n=>{t(`osascript`,[`-e`,`id of app "${e}"`],DW({timeout:X$,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 Olt(e,t){return new Promise(n=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],DW({timeout:X$,encoding:`utf-8`}),e=>{n(!e)})})}function klt(e,t){return new Promise(n=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],DW({timeout:X$,encoding:`utf-8`}),(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}const Alt=`skill-install-events.jsonl`;async function Q$(e,t){let n=t?.homedir??(()=>process.env.HOME??``),r=t?.warn??((e,t)=>{Y(`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=W(Ls(i),Alt),o=`${JSON.stringify(e)}\n`;try{await yH(U(a),{recursive:!0})}catch(e){r({event:`skill-install-events.mkdir-failed`,err:e},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await hH(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 jlt(){return Ca.parse({}).telemetry.skillInstallReports.enabled}function $$(e){let t=e??_c(),n;try{n=yl(`user`,t,t)}catch(e){return Y(`skills`).warn({err:e},`could not resolve the user config path; not reporting`),{enabled:!1,home:t}}if(!q(n))return{enabled:jlt(),home:t};try{let e=(0,nl.parse)(J(n,`utf-8`))?.telemetry?.skillInstallReports?.enabled;return{enabled:typeof e==`boolean`?e:jlt(),home:t}}catch(e){return Y(`skills`).warn({err:e,path:n},`user config exists but could not be read; not reporting skill installs`),{enabled:!1,home:t}}}function e1(){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 Mlt=[`.ok`,T,Vte];function t1(e){return W(e,...Mlt)}function Nlt(e){let t=e;for(;!q(t);){let e=U(t);if(e===t)return null;t=e}return t}function Plt(e){let t=e;for(;;)try{return fc(t),t}catch(e){let n=e.code;if(n!==`ENOENT`&&n!==`ENOTDIR`)throw e;let r=U(t);if(r===t)return null;t=r}}function Flt(e,t,n){if(t.length===0||t.includes(`\0`)||Gs(t)||t.split(/[/\\]/).some(e=>e===`..`))return null;let r=K(e),i=K(r,t);if(i===r||!i.startsWith(`${r}${Js}`))return null;let a=cc(r),o=n(i);if(o===null)return null;let s=cc(o);return s!==a&&!s.startsWith(`${a}${Js}`)?null:i}function Ilt(e,t){return Flt(e,t,Plt)}function n1(e,t){try{return Flt(e,t,Nlt)}catch{return null}}function r1(){return{schema:1,skills:{}}}function Llt(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 Rlt(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 zlt(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 Blt(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 i1(e,t,n=n1){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=>Llt(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=Rlt(t.preferences),o=zlt(t.sources),s=Blt(e,t.folders,n);return{schema:1,skills:r,...a?{preferences:a}:{},...o?{sources:o}:{},...i.length>0?{roots:i}:{},...s?{folders:s}:{}}}function a1(e){let t=t1(e);if(!q(t))return r1();try{let n=JSON.parse(J(t,`utf-8`));return!n||typeof n!=`object`?r1():i1(e,n)}catch(e){return Y(`skill-placements`).warn({err:e,path:t},`skill-placements.json is unreadable; continuing with an empty ledger (recorded placements for this project are lost)`),r1()}}function Vlt(e,t){let n=t1(e);try{fc(n)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return{kind:`read`,store:r1()};throw e}let r=J(n,`utf-8`),i;try{i=JSON.parse(r)}catch(e){return Y(`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:r1()}:{kind:`read`,store:i1(e,i,t)}}function Hlt(e){let t=t1(e);if(!q(t))return{ok:!0,store:r1()};let n;try{n=J(t,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?{ok:!0,store:r1()}:{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:i1(e,r)}}const Ult=e1();function o1(e,t){return Ult(t1(e),async()=>{let n=Hlt(e);if(!n.ok){let t=t1(e);throw Y(`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 Wlt(e,r)})}async function Wlt(e,t){let n=t1(e);await yH(U(n),{recursive:!0}),await Fs(n,`${JSON.stringify(t,null,2)}\n`,{fs:MH})}function Glt(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 Klt(e){return Glt(e,a1(e),n1)}function qlt(e){let t=[],n=(e,n)=>{try{return Ilt(e,n)}catch(e){return t.push(e),null}},r;try{r=Vlt(e,n)}catch(t){return Y(`skill-placements`).warn({err:t,path:t1(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=Glt(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 Jlt=new Set([400,404,410,422]),Ylt=[`.local`,`.internal`,`.intranet`,`.corp`,`.home`,`.home.arpa`,`.lan`,`.private`,`.test`,`.invalid`,`.localhost`,`.localdomain`];function Xlt(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)?!Ylt.some(t=>e.toLowerCase().endsWith(t)):!1:t.length===2&&t.every(e=>/^[\w.-]+$/.test(e)&&e!==`.`&&e!==`..`)}function s1(e,t){if(e.scope===void 0)return`${e.source}#${t}`;let n=e.scope;try{n=cc(n)}catch{}return`${e.source}#${t}@${n}`}function Zlt(e=process.env){return!!(e.DISABLE_TELEMETRY||e.DO_NOT_TRACK)}async function c1(e,t){let n=t.env??process.env;if(!t.enabled||Zlt(n)||!Xlt(e.source.trim()))return[];let r=await Lot(t.home).catch(t=>(Y(`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(s1(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 Rot(t.home,i.map(t=>s1(e,t)))}catch(t){return Y(`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&&Jlt.has(n.status))return Y(`skills`).warn({status:n.status,source:e.source,skills:i},`skill install report rejected by the collector; releasing the claim to retry later`),await zot(t.home,i.map(t=>s1(e,t))).catch(t=>{Y(`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||Y(`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){Y(`skills`).warn({err:t,source:e.source,skills:i},`skill install report could not be delivered; this install is not counted`)}return i}const l1=`.agents`;function Qlt(e,t){return W(e,l1,`skills`,t)}function u1(e){return Ire.filter(t=>q(W(e,t.hostDir)))}function $lt(e){let t=u1(e).map(e=>({editor:e.editorId,skillsRoot:e.skillsRoot,custom:!1})),n=new Set(t.map(e=>e.skillsRoot)),r=Klt(e).filter(t=>!n.has(t)&&q(W(e,t))).map(e=>({editor:e,skillsRoot:e,custom:!0}));return[...t,...r]}function eut(e){return Sa.filter(t=>{let n=Sr[t];return n!==null&&q(W(e,Zi(n)))})}async function tut(e,t){let n=u1(e).map(n=>W(e,n.skillsRoot,t));q(W(e,l1))&&n.push(Qlt(e,t));for(let e of n)try{if((await Dc(e)).isDirectory())return!0}catch{}return!1}function nut(e,t,n){let r=[...t.map(e=>e.skillsRoot),`${l1}/skills`];for(let t of r){let r=W(e,t,`open-knowledge`);if(q(r))try{AH(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 rut(e,t){AH(t,{recursive:!0,force:!0}),SH(U(t),{recursive:!0}),wH(e,t,{recursive:!0})}function iut(e,t,n,r,i){let a=[],o=Qlt(e,t),s=[...i?[o]:[],...r.map(n=>W(e,n.skillsRoot,t)).filter(e=>e!==o)];for(let e of s)try{rut(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 aut(e={}){let t=e.home??_c(),n=e.logger??{warn:(e,t)=>Y(`skills`).warn(e,t),info:(e,t)=>Y(`skills`).info(e,t)},r=e.surface??`cli-npx-skills-add`,i=e.bundleId??`discovery`,a=NU[i];if(!Gs(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 Q$({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 Fot(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 TQ()}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 CQ(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 tut(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=zU(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=u1(t),f=q(W(t,l1));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`;nut(t,d,n);let p=iut(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 wQ(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),c1({source:Ci,skills:[a],agents:d.map(e=>e.editorId),global:!0,version:c},{home:t,enabled:$$(t).enabled}),`installed`}function out(e){return W(e,`Downloads`,`openknowledge.skill`)}function sut(e,t){if(t===`darwin`)return{command:`open`,args:[e]};if(t===`win32`)return{command:`cmd`,args:[`/c`,`start`,`""`,e]};if(t===`linux`)return{command:`xdg-open`,args:[e]}}function cut(e,t){let n=t instanceof Error?t.message:String(t);return{ok:!1,reason:`spawn-error`,message:qW(t)===`ENOENT`?`No system file opener (${e}) was found: ${n}`:n}}function lut(e,t,n){let r=sut(e,t);if(r===void 0)return Promise.resolve({ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`});let i=DW({detached:!0,stdio:`ignore`});return new Promise(e=>{let t;try{t=n(r.command,r.args,i)}catch(t){e(cut(r.command,t));return}t.on(`error`,t=>e(cut(r.command,t))),t.once(`spawn`,()=>{t.unref(),e({ok:!0})})})}async function uut(e={}){let t=e.home??_c(),n=K(e.out??out(t)),r=e.platformName??yc(),i=e.spawnFn??Rc,a=e.logger,o=async(e,n,r)=>{await Q$({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 TQ()}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([CQ(t,`claude-cowork`,a),Pot(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 yH(U(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 Y1e({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 TQ()}catch{c=void 0}let l={status:`built`,outputPath:s.outputPath,size:s.size,sha256:s.sha256,skillVersion:c};if(c)try{await wQ(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=await lut(s.outputPath,r,i);return u.ok?(await o(`installed`,c),c1({source:Ci,skills:[NU.project],agents:[`claude-desktop`],global:!0,version:c},{home:t,enabled:$$(t).enabled}),{...l,status:`installed`}):(await o(`built`,c,`handoff-${u.reason}`),{...l,handoffError:{reason:u.reason,message:u.message}})}function dut(e){let{checkLocalOpSecurity:t}=e;return HQ({"/api/install-skill":ZQ(Wt,async(e,t,n)=>{if(n.out!==void 0&&!VQ(n.out)){Q(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{let e=await uut({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}});$(t,200,En,e,{handler:`install-skill`})}catch(e){Q(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 fut=1024,put=[`anthropic`,`claude`],d1=`SKILL.md`;function mut(e){let t=x1(e.name);if(!t.ok)return{ok:!1,error:t.error};let n=yut(e.frontmatter,e.name);if(!n.ok)return{ok:!1,error:n.error};let r=`---\n${xut(e.frontmatter)}---\n${e.body}`,i=[],a=[],o=put.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(`
1177
+ `:``)+n).md;kq(i.dc.document,a,`agent`,void 0,o),gZ(`mcp-write`),v=!0}d=!0},i.origin),v&&f.markAgentWriteStore(E)})}finally{_?.touchMode(A,`idle`)}let oe=i.dc.document.getText(`source`).toString();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)})`}}Q(s,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e,...yG[`urn:ok:error:invalid-frontmatter-patch`]}});return}if(d&&ae.length>0){if(t$(E,A,j,M,void 0,y({clientName:N,clientVersion:P,label:ee}),re),aW(),b(I),v){ie=await x(E);let e=ie;if(e?.kind===`failure`){S(s,e.failure,`frontmatter-patch`);return}if(e?.kind===`stale-external-write`){r(s,`frontmatter-patch`,E);return}}C(E,`frontmatter-patch`)}w?.setFocus(A,{agentName:j,currentDoc:E,writeKind:`write`,ts:Date.now()}),T?.();let se=le(E),ce=fe();ce===0&&I$().add(1,{"shadow.writer":`agent`,"agent.type":AU(N)});let L=k(a);oe=p.documents.get(E)?.getText(`source`).toString()??oe,D(E,oe);let ue=(await O([E]))(oe,E,e.suppressLogLinkAdvisories),de=[...L?[L]:[],...ue.warnings],pe={timestamp:c,subscriberCount:se,systemSubscriberCount:ce,appliedKeys:ae,...ne?{summary:ne}:{},...de.length>0?{warnings:de}:{},...ue.links},me=SG(a,ie);if(me.outcome===`both-kept`){F$(s,`frontmatter-patch`,pe,me);return}$(s,200,Xte,{...pe,...me},{handler:`frontmatter-patch`})})}catch(t){if(t instanceof vQ){P$(s,t,`frontmatter-patch`);return}j.error({err:t,requestId:HK(e)},`[frontmatter-patch] handler failed`),Q(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:t})}},{handler:`frontmatter-patch`,method:`POST`}),"/api/agent-patch":ZQ(nre,async(e,s,c)=>{try{let e=n(),{find:E,replace:j,offset:M}=c,N=i(c.docName,s,`agent-patch`);if(N===null)return;let P=a(N),{agentId:ee,suppliedWriterId:te,agentName:F,colorSeed:I,clientName:ne,clientVersion:re,label:ie}=o(c);if(_W(P)||vW(P)){Q(s,400,`urn:ok:error:reserved-doc-name`,`'${P}' is a reserved document name.`,{handler:`agent-patch`,extensions:{...yG[`urn:ok:error:reserved-doc-name`]}});return}if(ue(s,P,`agent-patch`))return;let ae=EQ(c.summary);await d.withSessions(async n=>{let i=await n(P,ee,{displayName:F,colorSeed:I,clientName:ne}),a=await v$(f,p,P,l,m.resolveEmbed,h?.(),t,g),o=m.resolveEmbed?{resolveEmbed:m.resolveEmbed,sourcePath:P}:void 0,c;{let e=i.dc.document.getText(`source`).toString(),{frontmatter:t,body:n}=an(e),r=Pa(t,n),a=M==null?r.indexOf(E):r.slice(M,M+E.length)===E?M:-1;if(a!==-1&&a>=t.length){let e=r.slice(0,a)+j+r.slice(a+E.length);c=await fQ(i.dc.document,an(e).body,`patch`,o)}}let d=new Date().toISOString(),N=!1,oe=!1,se=!1,ce=!1,L,ue;try{let e=ar(ne),t=lo[e]??rt(I??ee);if(_?.setPresence(ee,{displayName:F,icon:e,color:t,currentDoc:P,mode:`writing`,ts:Date.now()}),ue=$Q(i.dc.document.getText(`source`),ee,i.origin,I,ne),i.dc.document.transact(()=>{let e=i.dc.document.getText(`source`).toString(),{frontmatter:t,body:n}=an(e),r=Pa(t,n),a=M==null?r.indexOf(E):r.slice(M,M+E.length)===E?M:-1;if(a===-1){M==null?N=!0:oe=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":P,findLength:E.length,replaceLength:j.length,hadOffset:M!=null})),R0e();return}if(a<t.length){se=!0;return}let s=r.slice(0,a)+j+r.slice(a+E.length);if(t===``&&an(s).frontmatter!==``){ce=!0;return}let{body:l}=an(s),u=gQ(i.dc.document);L=hQ(i.dc.document,l,`patch`,o,c,pQ(i),te);let d=Xc(u,gQ(i.dc.document))??void 0;i.dc.document.getMap(`agent-flash`).set(ee,{agentId:ee,timestamp:Date.now(),type:`insert`,description:`Patched (${F}): ${E.slice(0,50)}`,...d===void 0?{}:{changedBlocks:d}})},i.origin),f.markAgentWriteStore(P),L!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":P,position:`patch`,intendedBytes:L.intendedBytes,actualBytes:L.actualBytes,byteDelta:L.byteDelta,"agent.id":ee,"agent.client_name":ne})),!N&&!oe&&!se&&!ce){let{stored:e}=u(ae);t$(P,ee,F,I,void 0,y({clientName:ne,clientVersion:re,label:ie}),e),aW(),b(ae),v(`agent-patch`,L)}}finally{ue?.(),_?.touchMode(ee,`idle`)}if(oe){Q(s,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`,extensions:{...yG[`urn:ok:error:stale-target`]}});return}if(N){Q(s,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`,extensions:{...yG[`urn:ok:error:target-not-found`]}});return}if(se){Jct().add(1,{result:`rejected`,reason:`intersect`}),Q(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`,extensions:{...yG[`urn:ok:error:frontmatter-edit-not-supported`]}});return}if(ce){Jct().add(1,{result:`rejected`,reason:`promoted`}),Q(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`,extensions:{...yG[`urn:ok:error:frontmatter-edit-not-supported`]}});return}let de=i.dc.document.getText(`source`).toString(),pe=await x(P);if(pe?.kind===`failure`){S(s,pe.failure,`agent-patch`);return}if(pe?.kind===`stale-external-write`){r(s,`agent-patch`,P);return}C(P,`agent-patch`),w?.setFocus(ee,{agentName:F,currentDoc:P,writeKind:`edit`,ts:Date.now()}),T?.();let me=le(P),he=fe();he===0&&I$().add(1,{"shadow.writer":`agent`,"agent.type":AU(ne)});let{response:ge}=u(ae);de=p.documents.get(P)?.getText(`source`).toString()??de,D(P,de);let _e=await act(de,P),ve=(await O([P]))(de,P,e.suppressLogLinkAdvisories),ye=k(a),be=L===void 0?void 0:pZ(L),xe=[...be?[be]:[],...ye?[ye]:[],..._e??[],...await A(de,P,e),...ve.warnings],Se={timestamp:d,subscriberCount:me,systemSubscriberCount:he,...ge?{summary:ge}:{},...xe.length>0?{warnings:xe}:{},...ve.links},Ce=SG(a,pe,L!==void 0);if(Ce.outcome===`both-kept`){F$(s,`agent-patch`,Se,Ce);return}$(s,200,Nre,{...Se,...Ce},{handler:`agent-patch`})})}catch(n){if(n instanceof UJ){WJ(s,n,`agent-patch`,t.findByDocName(UU(n.file)));return}if(n instanceof mZ){hZ(s,n,`agent-patch`);return}if(n instanceof vQ){P$(s,n,`agent-patch`);return}j.error({err:n,requestId:HK(e)},`[agent-patch] handler failed`),Q(s,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:n})}},{handler:`agent-patch`,method:`POST`}),"/api/agent-undo":ZQ(fne,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:p,clientVersion:h,label:g}=o(s);if(_W(t)||vW(t)){Q(n,400,`urn:ok:error:reserved-doc-name`,`'${t}' is a reserved document name.`,{handler:`agent-undo`,extensions:{...yG[`urn:ok:error:reserved-doc-name`]}});return}let{connectionId:v}=s,b,C;if(s.scope===`count`?(b=`count`,C=s.count):b=s.scope===`session`||s.scope===`file`?`session`:`last`,!d.hasSession(t,v)){Q(n,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let T=await d.getSession(t,v),E=!1;try{let e=ar(p),n=lo[e]??rt(u??c);_?.setPresence(c,{displayName:l,icon:e,color:n,currentDoc:t,mode:`writing`,ts:Date.now()}),E=Cot(T,b,m.resolveEmbed?{resolveEmbed:m.resolveEmbed,sourcePath:t}:void 0,C),E&&(f.markAgentWriteStore(t),t$(t,v,l,u,void 0,y({clientName:p,clientVersion:h,label:g})))}finally{_?.touchMode(c,`idle`)}let D=null;if(E){D=await x(t);let e=D;if(e?.kind===`failure`&&!xG(e.failure)){S(n,e.failure,`agent-undo`);return}if(e?.kind===`stale-external-write`){r(n,`agent-undo`,t);return}M(t,`agent-undo`)}w?.setFocus(v,{agentName:v,currentDoc:t,writeKind:`undo`,ts:Date.now()}),$(n,200,$ee,{docName:t,scope:b,undone:E,...SG(void 0,D)},{handler:`agent-undo`})}catch(r){if(r instanceof UJ){WJ(n,r,`agent-undo`,t.findByDocName(UU(r.file)));return}j.error({err:r,requestId:HK(e)},`[agent-undo] handler failed`),Q(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:r})}},{handler:`agent-undo`,method:`POST`}),"/api/agent-activity":ZQ(L,async(e,t)=>{try{let n=DU(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(n===null){Q(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}let r=Mat(d,n);$(t,200,Ate,r,{handler:`agent-activity`})}catch(n){j.error({err:n,requestId:HK(e)},`[agent-activity] handler failed`),Q(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":ZQ(L,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=DU(n.searchParams.get(`agentId`)),i=n.searchParams.get(`docName`),o=n.searchParams.get(`keptCount`);if(r===null){Q(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!i||i.trim()===``){Q(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!ee(i)){Q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let s=a(i);if(_W(s)||vW(s)){Q(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))){Q(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){Q(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){Q(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){Q(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}=kat(u.undoStack,c,f,s);$(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:HK(e)},`[agent-burst-diff] handler failed`),Q(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":ZQ(de,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=o(n),s=te?.current;if(!s){Q(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){Q(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=EQ(typeof n.summary==`string`?n.summary:void 0);await ce();let f=await se.saveCheckpoint(s,{explicitWriters:l,agentWriter:u,summary:d.kind===`value`?d.value:void 0});$(t,200,bne,{checkpointRef:f.checkpointRef},{handler:`save-version`})}catch(n){j.error({err:n,requestId:HK(e)},`[save-version] handler failed`),Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:n})}},{handler:`save-version`,method:`POST`}),"/api/rollback":ZQ(qr,async(e,n,i)=>{let a=DQ(i,F);if(a.kind===`invalid-summary`){Q(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){WJ(n,new UJ({file:o.file}),`rollback`,o);return}let s=te?.current;if(!s){Q(n,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:c,commitSha:l}=i,d=I??`.`,h=ne(c,d);if(`error`in h){Q(n,400,`urn:ok:error:invalid-request`,h.error,{handler:`rollback`});return}let g=yJ(s),_=Date.now();try{await P(`rollback-read`);let e=E$(s.gitDir),t=O$(),i=await Rct(s,c,l,re?.()??`main`,e,e=>ie(e,d),t);if(i===null){Q(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`,extensions:{...yG[`urn:ok:error:doc-not-found`]}});return}let o=await g.raw(`show`,`${l}:${i}`),h=new Date().toISOString();await jJ(s,d,{action:`rollback`,context:{docName:c,targetSha:l}});let y=p.documents.get(c);if(!y){Q(n,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let C=m.resolveEmbed?{resolveEmbed:m.resolveEmbed,sourcePath:c}:void 0,T=await kZ(o,C),E;y.transact(()=>{Aq(y,o,C,T),E=kit(y.getText(`source`).toString(),o,`rollback`)},Gct),f.markAgentWriteStore(c),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:EQ(`Restored to ${e}`),r=u(n);D=t||!r.response?r.response:ae(r.response),t$(c,a.writerId,a.displayName,a.colorSeed,Dye(c,l),a.actor,r.stored),aW(),b(n,!t);break}case`principal`:{let e=u(a.summary);D=e.response,t$(c,a.writerId,a.displayName,a.colorSeed,Dye(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)}`)}oe().add(1,{kind:`rollback`,attribution_kind:a.kind});let O=await x(c);if(O?.kind===`failure`&&!xG(O.failure)){S(n,O.failure,`rollback`);return}if(O?.kind===`stale-external-write`){r(n,`rollback`,c);return}M(c,`rollback`);let k=Date.now()-_;Y(`rollback`).info({docName:c,from:l.slice(0,8),durationMs:k},`rollback`),a.kind===`agent`&&w?.setFocus(a.writerId,{agentName:a.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let A=E===void 0?void 0:pZ(E);$(n,200,Ne,{...SG(void 0,O,E!==void 0),restoredFrom:l,timestamp:h,...D?{summary:D}:{},...A?{warnings:[A]}:{}},{handler:`rollback`})}catch(e){Q(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`]}),acpDocumentWrite:ge}}const R$={source:`local`,skipStoreHooks:!0,context:{origin:`config-validation-revert`}},$ct={source:`local`,skipStoreHooks:!0,context:{origin:`config-file-watcher`}},elt=[`document`,`server`,`presence`],tlt=[`docName`,`reset-okignore`];function nlt(e){return elt.includes(e)}function rlt(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 _W(e)||vW(e)}function x(){for(let e of Object.keys(t?.getPresenceMap()??{}))t?.clearPresence(e)}async function S(e){for(let t of d.documents.keys())t===e||b(t)||await y(t);x();for(let[e]of i?.entries()??[])i?.delete(e)}function C(){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 HQ({"/api/test-reset":ZQ(L,async(e,t)=>{try{let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`scope`)??`document`;if(!nlt(a)){Q(t,400,`urn:ok:error:invalid-request`,`scope must be one of ${elt.join(`, `)}.`,{handler:`test-reset`});return}if(a===`presence`){let e=tlt.find(e=>i.searchParams.has(e));if(e!==void 0){Q(t,400,`urn:ok:error:invalid-request`,`${e} cannot be combined with scope=presence: a presence-scope reset clears agent presence only.`,{handler:`test-reset`});return}x(),$(t,200,Cr,{scope:a},{handler:`test-reset`});return}if(a===`server`&&i.searchParams.has(`reset-okignore`)){Q(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){Q(t,400,`urn:ok:error:invalid-request`,`scope=server needs a server started with an isolated config home.`,{handler:`test-reset`});return}let o=YU(s(i.searchParams.get(`docName`)??`test-doc`)),f;try{f=AG(o,c)}catch(e){l.error({err:e,docName:o},`[test-reset] safeContentPath rejected docName`),Q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}if(a===`server`)try{await r?.()}catch(e){Q(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),mc(f,``,`utf-8`),await p?.testOnly?.resetDocumentForTest(o),a===`server`&&(await S(o),n?.()),i.searchParams.get(`reset-okignore`)!==`false`)try{let e=K(c,`.okignore`),t=d.documents.get($r);if(t){let e=t.getText(`source`);e.length>0&&t.transact(()=>{e.delete(0,e.length)},R$)}q(e)&&mc(e,``,`utf-8`),m&&(h(),await m.rebuildIgnorePatterns())}catch(e){l.warn({err:e},`[test-reset] okignore reset partial failure`)}g?.(`files`),$(t,200,Cr,a===`server`?{scope:a,residue:C()}:{},{handler:`test-reset`})}catch(e){Q(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":ZQ(L,async(e,t)=>{try{await _?.(),$(t,200,Eee,{},{handler:`test-flush-git`})}catch(n){l.error({err:n,requestId:HK(e)},`[test-flush-git] flush failed`),Q(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":ZQ(L,async(e,t)=>{try{if(!p?.testOnly){Q(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await p.testOnly.rescanBacklinksForTest(),$(t,200,yee,{},{handler:`test-rescan-backlinks`})}catch(e){Q(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":ZQ(L,async(e,t)=>{try{if(!v){Q(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await v(),g?.(`files`),$(t,200,jee,{},{handler:`test-rescan-files`})}catch(e){Q(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 ilt=dte,alt={claude:`claude`,codex:`codex`,cursor:`cursor-agent`,gemini:`gemini`,opencode:`opencode`,pi:`pi`,antigravity:`agy`,copilot:`copilot`,openclaw:`openclaw`,hermes:`hermes`},olt={codex:()=>W(process.env.CODEX_HOME??W(_c(),`.codex`),`auth.json`)};function slt(e){let t=olt[e];if(t===void 0)return`unknown`;let n;try{return n=t(),q(n)?`present`:`unknown`}catch(t){return Y(`acp-harness`).warn({cli:e,credentialPath:n,err:t},`harness credential probe failed; treating as unknown`),`unknown`}}async function clt(e,t,n=oU){let r={cmd:alt[e],args:[],env:YH(),kind:`custom`,pathFromOverlay:!1};try{return await n(r),`present`}catch(i){if(!(i instanceof qH)||i.code!==`command-not-found`)return Y(`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 Y(`acp-harness`).warn({cli:e,err:o},`login-shell PATH capture failed; harness absence unverified — availability unknown`),`unknown`;try{return await n(NQe(r,a)),`present`}catch(t){return t instanceof qH&&t.code===`command-not-found`?`not-found`:(Y(`acp-harness`).warn({cli:e,err:t},`harness preflight on the login-shell PATH failed before absence could be verified; availability unknown`),`unknown`)}}}function llt(e={}){let t=e.resolveLoginShellPath??UH(Y(`acp-harness`)),n=e.preflight??oU,r=e.probe??(e=>clt(e,t,n)),i=e.credentials??slt,a=e.now??Date.now,o=e.ttlMs??6e4,s=[...new Set(Object.values(ilt))].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){Y(`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 Y(`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 ult=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 z$(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(plt(e,i)>1){let s=r;for(;!mlt(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 dlt(e,t){return H$(e,t).map(e=>({start:e,end:e+t.length}))}function flt(e,t,n,{contextIsMarkdown:r=!1}={}){let i=n.prefix??``,a=n.suffix??``,o=[],s=-1;for(let n of t){let t=Goe(e,n,{prefix:i,suffix:a},{syntaxIn:`haystack`,syntaxInContext:r});t>s?(s=t,o=[n]):t===s&&o.push(n)}return o}function B$(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=H$(e,n);if(s.length===0)return V$(e,t);let c=Koe(t,{syntaxInContext:!0}),l=t=>c===0||Goe(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}:V$(e,t)}let u=flt(e,s.map(e=>({start:e,end:e+n.length})),{prefix:r,suffix:i},{contextIsMarkdown:!0});if(!l(u[0]))return V$(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 V$(e,t){let{prefix:n,suffix:r,exact:i}=t,a=n===``?[0]:H$(e,n).map(e=>e+n.length),o=r===``?[e.length]:H$(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=qoe(i.length);return c-s>l?{status:`orphaned`}:{status:`anchored`,start:s,end:c,rewritten:!0}}function plt(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 H$(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 mlt(e,t,n,r){return plt(e,t+n+r)===1}function U$(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 hlt(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):null}function glt(e,t){if(t===``)return!1;let n=e.indexOf(t);return n!==-1&&e.indexOf(t,n+1)!==-1}var W$=class extends Error{},G$=class extends Error{},K$=class extends Error{},q$=class extends Error{},_lt=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??Nc}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=z$(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=z$(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 K$(n.target.key);let r=await this.requireDocBody(n.docName),{start:i,end:a}=this.resolveRange(r,t),o=z$(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:J$(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&&glt(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 G$){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 G$){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 0;await this.buildIndex();let n=this.index.threadsForDoc(e);if(n.length===0)return 0;this.index.renameDoc(e,t);let r=await Promise.allSettled(n.map(e=>this.moveThread(e,t))),i=r.flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(i.length>0)throw AggregateError(i,`Moving comment threads from ${e} to ${t} failed`);return r.filter(e=>e.status===`fulfilled`&&e.value).length}async moveThread(e,t){let n;try{n=await this.store.update(e,{docName:t})}catch(t){throw this.reindex(e,await this.store.readMeta(e)),t}return this.reindex(e,n),n!==null}reindex(e,t){t===null?this.index.remove(e):this.index.upsert(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=B$(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?z$(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=B$(r,i);if(a.status===`orphaned`)return n.state===`orphaned`?n:this.mutate(e,{state:`orphaned`});let o=a.rewritten?z$(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 G$(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=dlt(e,n),i=r.length>0?r:Hoe(e,n,{syntaxIn:`haystack`});if(i.length===0)throw new q$(n);return i.length===1?i[0]:flt(e,i,{prefix:t.prefix,suffix:t.suffix})[0]}async requireMeta(e){let t=await this.store.readMeta(e);if(!t)throw new G$(e);return t}async requireDocBody(e){let t=await this.getDocBody(e);if(t===null)throw new W$(e);return t}async requirePropertyText(e,t,n){let r=await this.getDocFrontmatter(e);if(r===null)throw new W$(e);let i=U$(r,t,n);if(i===void 0)throw new K$(J$(t,n));let a=hlt(i);if(a===null)throw new K$(J$(t,n));return a}async requirePropertyTarget(e,t,n){let r=await this.getDocFrontmatter(e);if(r===null)throw new W$(e);if(U$(r,t,n)===void 0)throw new K$(J$(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=U$(i,t.key,t.path);if(a===void 0)return{state:`orphaned`};if(n===null)return{state:`anchored`};let o=hlt(a);if(o===null)return{state:`orphaned`};let s=B$(o,n);return s.status===`orphaned`?{state:`orphaned`}:s.rewritten?{state:`anchored`,anchor:z$(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 J$(e,t){let n=e;for(let e of t)n+=typeof e==`number`?`[${e}]`:`.${e}`;return n}var vlt=class{dir;log;writeQueues=new Map;dirReady=null;constructor(e,t){this.dir=W(e,`comments`),this.log=t}init(){return this.ensureDir()}ensureDir(){return this.dirReady??=yH(this.dir,{recursive:!0}).then(()=>void 0),this.dirReady}metaPath(e){return W(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=ga.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=ga.parse({...n,...ylt(t)});return await this.write(r),r})}write(e){return Fs(this.metaPath(e.threadId),blt(e),{fs:MH})}async readMeta(e){let t;try{t=await wc(this.metaPath(e),`utf8`)}catch{return null}let n=ga.safeParse(xlt(t));return n.success?n.data:(this.log.warn({threadId:e},`[comments] skipping unreadable thread meta`),null)}async scanCoverSheets(){let e;try{e=await Tc(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 _H(this.metaPath(e),{force:!0}),await _H(W(this.dir,`${e}.ndjson`),{force:!0})})}};function ylt(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 blt(e){return`${JSON.stringify(e,null,1)}\n`}function xlt(e){try{return JSON.parse(e)}catch{return}}const Y$=[`claude`,`codex`,`cursor`],X$=2e3,Slt={claude:[`Claude`],codex:[`Codex`],cursor:[`Cursor`]};function Clt(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(Y$.map(async e=>[e,await i(e)]));return Object.fromEntries(e)}return{probeAll:a,probeWithCache:i}}function wlt(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return Tlt(e)}catch{}let n=e.headers.origin;if(typeof n==`string`&&n.length>0)try{return Tlt(new URL(n).hostname)}catch{return!1}return!0}function Tlt(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function Elt(e,t,n){if(e.method!==`GET`){Q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{let r=wlt(e)?await n():Object.fromEntries(Y$.map(e=>[e,!0]));$(t,200,fi,r,{handler:`installed-agents`})}catch(e){Y(`handoff`).error({err:e},`[installed-agents] handler failed`),Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function Z$(e,t=Ic){return n=>e===`darwin`?Dlt(n,t):e===`win32`?Olt(n,t):klt(n,t)}function Dlt(e,t){let n=Slt[e];function r(e){return new Promise(n=>{t(`osascript`,[`-e`,`id of app "${e}"`],DW({timeout:X$,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 Olt(e,t){return new Promise(n=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],DW({timeout:X$,encoding:`utf-8`}),e=>{n(!e)})})}function klt(e,t){return new Promise(n=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],DW({timeout:X$,encoding:`utf-8`}),(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}const Alt=`skill-install-events.jsonl`;async function Q$(e,t){let n=t?.homedir??(()=>process.env.HOME??``),r=t?.warn??((e,t)=>{Y(`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=W(Ls(i),Alt),o=`${JSON.stringify(e)}\n`;try{await yH(U(a),{recursive:!0})}catch(e){r({event:`skill-install-events.mkdir-failed`,err:e},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await hH(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 jlt(){return Ca.parse({}).telemetry.skillInstallReports.enabled}function $$(e){let t=e??_c(),n;try{n=yl(`user`,t,t)}catch(e){return Y(`skills`).warn({err:e},`could not resolve the user config path; not reporting`),{enabled:!1,home:t}}if(!q(n))return{enabled:jlt(),home:t};try{let e=(0,nl.parse)(J(n,`utf-8`))?.telemetry?.skillInstallReports?.enabled;return{enabled:typeof e==`boolean`?e:jlt(),home:t}}catch(e){return Y(`skills`).warn({err:e,path:n},`user config exists but could not be read; not reporting skill installs`),{enabled:!1,home:t}}}function e1(){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 Mlt=[`.ok`,T,Vte];function t1(e){return W(e,...Mlt)}function Nlt(e){let t=e;for(;!q(t);){let e=U(t);if(e===t)return null;t=e}return t}function Plt(e){let t=e;for(;;)try{return fc(t),t}catch(e){let n=e.code;if(n!==`ENOENT`&&n!==`ENOTDIR`)throw e;let r=U(t);if(r===t)return null;t=r}}function Flt(e,t,n){if(t.length===0||t.includes(`\0`)||Gs(t)||t.split(/[/\\]/).some(e=>e===`..`))return null;let r=K(e),i=K(r,t);if(i===r||!i.startsWith(`${r}${Js}`))return null;let a=cc(r),o=n(i);if(o===null)return null;let s=cc(o);return s!==a&&!s.startsWith(`${a}${Js}`)?null:i}function Ilt(e,t){return Flt(e,t,Plt)}function n1(e,t){try{return Flt(e,t,Nlt)}catch{return null}}function r1(){return{schema:1,skills:{}}}function Llt(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 Rlt(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 zlt(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 Blt(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 i1(e,t,n=n1){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=>Llt(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=Rlt(t.preferences),o=zlt(t.sources),s=Blt(e,t.folders,n);return{schema:1,skills:r,...a?{preferences:a}:{},...o?{sources:o}:{},...i.length>0?{roots:i}:{},...s?{folders:s}:{}}}function a1(e){let t=t1(e);if(!q(t))return r1();try{let n=JSON.parse(J(t,`utf-8`));return!n||typeof n!=`object`?r1():i1(e,n)}catch(e){return Y(`skill-placements`).warn({err:e,path:t},`skill-placements.json is unreadable; continuing with an empty ledger (recorded placements for this project are lost)`),r1()}}function Vlt(e,t){let n=t1(e);try{fc(n)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return{kind:`read`,store:r1()};throw e}let r=J(n,`utf-8`),i;try{i=JSON.parse(r)}catch(e){return Y(`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:r1()}:{kind:`read`,store:i1(e,i,t)}}function Hlt(e){let t=t1(e);if(!q(t))return{ok:!0,store:r1()};let n;try{n=J(t,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?{ok:!0,store:r1()}:{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:i1(e,r)}}const Ult=e1();function o1(e,t){return Ult(t1(e),async()=>{let n=Hlt(e);if(!n.ok){let t=t1(e);throw Y(`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 Wlt(e,r)})}async function Wlt(e,t){let n=t1(e);await yH(U(n),{recursive:!0}),await Fs(n,`${JSON.stringify(t,null,2)}\n`,{fs:MH})}function Glt(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 Klt(e){return Glt(e,a1(e),n1)}function qlt(e){let t=[],n=(e,n)=>{try{return Ilt(e,n)}catch(e){return t.push(e),null}},r;try{r=Vlt(e,n)}catch(t){return Y(`skill-placements`).warn({err:t,path:t1(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=Glt(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 Jlt=new Set([400,404,410,422]),Ylt=[`.local`,`.internal`,`.intranet`,`.corp`,`.home`,`.home.arpa`,`.lan`,`.private`,`.test`,`.invalid`,`.localhost`,`.localdomain`];function Xlt(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)?!Ylt.some(t=>e.toLowerCase().endsWith(t)):!1:t.length===2&&t.every(e=>/^[\w.-]+$/.test(e)&&e!==`.`&&e!==`..`)}function s1(e,t){if(e.scope===void 0)return`${e.source}#${t}`;let n=e.scope;try{n=cc(n)}catch{}return`${e.source}#${t}@${n}`}function Zlt(e=process.env){return!!(e.DISABLE_TELEMETRY||e.DO_NOT_TRACK)}async function c1(e,t){let n=t.env??process.env;if(!t.enabled||Zlt(n)||!Xlt(e.source.trim()))return[];let r=await Lot(t.home).catch(t=>(Y(`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(s1(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 Rot(t.home,i.map(t=>s1(e,t)))}catch(t){return Y(`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&&Jlt.has(n.status))return Y(`skills`).warn({status:n.status,source:e.source,skills:i},`skill install report rejected by the collector; releasing the claim to retry later`),await zot(t.home,i.map(t=>s1(e,t))).catch(t=>{Y(`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||Y(`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){Y(`skills`).warn({err:t,source:e.source,skills:i},`skill install report could not be delivered; this install is not counted`)}return i}const l1=`.agents`;function Qlt(e,t){return W(e,l1,`skills`,t)}function u1(e){return Ire.filter(t=>q(W(e,t.hostDir)))}function $lt(e){let t=u1(e).map(e=>({editor:e.editorId,skillsRoot:e.skillsRoot,custom:!1})),n=new Set(t.map(e=>e.skillsRoot)),r=Klt(e).filter(t=>!n.has(t)&&q(W(e,t))).map(e=>({editor:e,skillsRoot:e,custom:!0}));return[...t,...r]}function eut(e){return Sa.filter(t=>{let n=Sr[t];return n!==null&&q(W(e,Zi(n)))})}async function tut(e,t){let n=u1(e).map(n=>W(e,n.skillsRoot,t));q(W(e,l1))&&n.push(Qlt(e,t));for(let e of n)try{if((await Dc(e)).isDirectory())return!0}catch{}return!1}function nut(e,t,n){let r=[...t.map(e=>e.skillsRoot),`${l1}/skills`];for(let t of r){let r=W(e,t,`open-knowledge`);if(q(r))try{AH(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 rut(e,t){AH(t,{recursive:!0,force:!0}),SH(U(t),{recursive:!0}),wH(e,t,{recursive:!0})}function iut(e,t,n,r,i){let a=[],o=Qlt(e,t),s=[...i?[o]:[],...r.map(n=>W(e,n.skillsRoot,t)).filter(e=>e!==o)];for(let e of s)try{rut(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 aut(e={}){let t=e.home??_c(),n=e.logger??{warn:(e,t)=>Y(`skills`).warn(e,t),info:(e,t)=>Y(`skills`).info(e,t)},r=e.surface??`cli-npx-skills-add`,i=e.bundleId??`discovery`,a=NU[i];if(!Gs(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 Q$({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 Fot(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 TQ()}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 CQ(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 tut(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=zU(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=u1(t),f=q(W(t,l1));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`;nut(t,d,n);let p=iut(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 wQ(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),c1({source:Ci,skills:[a],agents:d.map(e=>e.editorId),global:!0,version:c},{home:t,enabled:$$(t).enabled}),`installed`}function out(e){return W(e,`Downloads`,`openknowledge.skill`)}function sut(e,t){if(t===`darwin`)return{command:`open`,args:[e]};if(t===`win32`)return{command:`cmd`,args:[`/c`,`start`,`""`,e]};if(t===`linux`)return{command:`xdg-open`,args:[e]}}function cut(e,t){let n=t instanceof Error?t.message:String(t);return{ok:!1,reason:`spawn-error`,message:qW(t)===`ENOENT`?`No system file opener (${e}) was found: ${n}`:n}}function lut(e,t,n){let r=sut(e,t);if(r===void 0)return Promise.resolve({ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`});let i=DW({detached:!0,stdio:`ignore`});return new Promise(e=>{let t;try{t=n(r.command,r.args,i)}catch(t){e(cut(r.command,t));return}t.on(`error`,t=>e(cut(r.command,t))),t.once(`spawn`,()=>{t.unref(),e({ok:!0})})})}async function uut(e={}){let t=e.home??_c(),n=K(e.out??out(t)),r=e.platformName??yc(),i=e.spawnFn??Rc,a=e.logger,o=async(e,n,r)=>{await Q$({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 TQ()}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([CQ(t,`claude-cowork`,a),Pot(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 yH(U(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 Y1e({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 TQ()}catch{c=void 0}let l={status:`built`,outputPath:s.outputPath,size:s.size,sha256:s.sha256,skillVersion:c};if(c)try{await wQ(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=await lut(s.outputPath,r,i);return u.ok?(await o(`installed`,c),c1({source:Ci,skills:[NU.project],agents:[`claude-desktop`],global:!0,version:c},{home:t,enabled:$$(t).enabled}),{...l,status:`installed`}):(await o(`built`,c,`handoff-${u.reason}`),{...l,handoffError:{reason:u.reason,message:u.message}})}function dut(e){let{checkLocalOpSecurity:t}=e;return HQ({"/api/install-skill":ZQ(Wt,async(e,t,n)=>{if(n.out!==void 0&&!VQ(n.out)){Q(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{let e=await uut({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}});$(t,200,En,e,{handler:`install-skill`})}catch(e){Q(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 fut=1024,put=[`anthropic`,`claude`],d1=`SKILL.md`;function mut(e){let t=x1(e.name);if(!t.ok)return{ok:!1,error:t.error};let n=yut(e.frontmatter,e.name);if(!n.ok)return{ok:!1,error:n.error};let r=`---\n${xut(e.frontmatter)}---\n${e.body}`,i=[],a=[],o=put.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(`
1178
1178
  `).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 f1(e){let t=U(e),n=`${Hs(e)}${mae}`;try{for(let e of sc(t))e.startsWith(n)&&EH(W(t,e))}catch{}}function p1(e){let t=b1(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=mut({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}=S1(e.skillsRoot,e.name),c=g1(e.boundary,o,s);if(!c.ok)return c;try{SH(o,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create skill directory at ${C1(e.skillsRoot,o)}: ${t.message}`}}}let l=!q(s);f1(s);let u=Ms(s);try{bH(u,r,{encoding:`utf-8`,flag:`wx`}),CH(u,s)}catch(t){try{EH(u)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill at ${C1(e.skillsRoot,s)}: ${t.message}`}}}return{ok:!0,path:C1(e.skillsRoot,s),created:l,warnings:i,warningCodes:a}}function m1(e){let t=W(e.skillDir,d1),n;if(e.skillMd!==void 0)n=e.skillMd;else try{n=J(t,`utf-8`)}catch(e){return{ok:!1,stage:`read`,cause:e}}let{fenced:r,body:i}=It(n),a=vi(r,{name:e.toName});if(!a.ok)return{ok:!1,stage:`patch`,error:a.error};f1(t);let o=Ms(t);try{bH(o,`${a.nextFenced}${i}`,`utf-8`),CH(o,t)}catch(e){try{EH(o)}catch{}return{ok:!1,stage:`write`,cause:e}}return{ok:!0}}function h1(e){return e===`SKILL_PATH_CHECK_FAILED`?500:400}function g1(e,t,n){if(!Gs(e)||!YW(t,e)||!YW(n,t))return{ok:!1,error:{code:`SKILL_PATH_OUTSIDE_HOME`,message:`Skill ${G(e,t)} must stay inside its project or home directory.`}};let r=t,i=`resolve the project or home directory`;try{let a=CG(e);i=`resolve skill directory ${G(e,t)}`;let{ancestor:o,missingSegments:s}=wG(t),c=W(o,...s),l=cK(G(e,t).split(Js).join(`/`),G(a,c).split(Js).join(`/`));if(!YW(c,a)||l)return{ok:!1,error:{code:l?`SKILL_PATH_PRIVATE_STATE`:`SKILL_PATH_OUTSIDE_HOME`,message:`Skill ${G(e,t)} resolves ${l?`into private repository state`:`outside its project or home directory`}; replace the link with an authorized skill directory.`}};for(let e of G(t,n).split(Js)){r=W(r,e),i=`inspect skill path ${G(t,r)}`;let n=nc(r,{throwIfNoEntry:!1});if(n===void 0)break;if(n.isSymbolicLink())return{ok:!1,error:{code:`SKILL_SYMLINK_REFUSED`,message:`Skill path ${G(t,r)} is a symlink; replace it with a real file or directory before changing it.`}}}}catch(e){return{ok:!1,error:{code:`SKILL_PATH_CHECK_FAILED`,message:`Could not ${i} (${qW(e)??`unknown error`}).`,cause:e}}}return{ok:!0}}function _1(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=aa(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]===d1)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=W(e,...n);return r!==e&&!r.startsWith(e+Js)?{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Skill file escapes the skill dir: ${t}`}}:{ok:!0,abs:r}}function hut(e){let t=0,n=(r,i)=>{let a;try{a=sc(r,{withFileTypes:!0})}catch{return}for(let o of a){let a=i===``?o.name:`${i}/${o.name}`;zG(a)||(o.isDirectory()?n(W(r,o.name),a):o.isFile()&&(r!==e||o.name!==d1)&&t++)}};return n(e,``),t}function v1(e){let t=e.bytes??e.content??``,n=b1(e.skillsRoot);if(!n.ok)return{ok:!1,error:n.error};let r=x1(e.name);if(!r.ok)return{ok:!1,error:r.error};let{skillDir:i,filePath:a}=S1(e.skillsRoot,e.name);if(!q(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=_1(i,e.relPath);if(!o.ok)return{ok:!1,error:o.error};let{abs:s}=o,c=g1(e.boundary,i,s);if(!c.ok)return c;let l=typeof t==`string`?Buffer.byteLength(t,`utf-8`):t.length,u=e.limits?.maxFileBytes??262144,d=e.limits?.maxFiles??50;if(l>u)return{ok:!1,error:{code:`FILE_TOO_LARGE`,message:`Skill file ${e.relPath} is ${l} bytes — the per-file cap is ${u}.`}};let f=!q(s);if(f&&hut(i)>=d)return{ok:!1,error:{code:`TOO_MANY_FILES`,message:`Skill "${e.name}" already holds ${d} bundle files (the cap) — delete one before adding another.`}};try{SH(W(s,`..`),{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create directory for ${e.relPath}: ${t.message}`}}}f1(s);let p=Ms(s);try{bH(p,t,{encoding:`utf-8`,flag:`wx`}),CH(p,s)}catch(t){try{EH(p)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill file ${e.relPath}: ${t.message}`}}}return{ok:!0,path:C1(e.skillsRoot,s),created:f}}function gut(e){let t=b1(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=x1(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillDir:r}=S1(e.skillsRoot,e.name),i=_1(r,e.relPath);if(!i.ok)return{ok:!1,error:i.error};let a=_1(r,e.toRelPath);if(!a.ok)return{ok:!1,error:a.error};for(let t of[i.abs,a.abs]){let n=g1(e.boundary,r,t);if(!n.ok)return n}if(!q(i.abs))return{ok:!1,error:{code:`FILE_NOT_FOUND`,message:`No bundle file at ${e.relPath}.`}};if(q(a.abs))return{ok:!1,error:{code:`DEST_EXISTS`,message:`A bundle file already exists at ${e.toRelPath} — renames never overwrite.`}};try{SH(W(a.abs,`..`),{recursive:!0}),CH(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=W(i.abs,`..`);if(o!==r&&w1(o))try{jH(o)}catch{}return{ok:!0}}function _ut(e){let t=b1(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=x1(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillDir:r}=S1(e.skillsRoot,e.name),i=_1(r,e.relPath);if(!i.ok)return{ok:!1,error:i.error};let{abs:a}=i,o=g1(e.boundary,r,a);if(!o.ok)return o;let s=q(a);if(s){try{fc(a).isDirectory()?AH(a,{recursive:!0,force:!0}):EH(a)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill file ${e.relPath}: ${t.message}`}}}let t=W(a,`..`);if(t!==r&&w1(t))try{jH(t)}catch{}}return{ok:!0,path:C1(e.skillsRoot,a),existed:s}}function y1(e){let t=b1(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=x1(e.name);if(!n.ok)return{ok:!1,error:n.error};let{skillsRoot:r}=t,{skillDir:i}=S1(e.skillsRoot,e.name),a=q(i);if(a)try{AH(i,{recursive:!0,force:!0})}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill at ${C1(e.skillsRoot,i)}: ${t.message}`}}}return but(r),{ok:!0,path:C1(e.skillsRoot,i),existed:a}}async function vut(e){let t=b1(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let n=x1(e.fromName);if(!n.ok)return{ok:!1,error:n.error};let r=x1(e.toName);if(!r.ok)return{ok:!1,error:r.error};let i=S1(e.skillsRoot,e.fromName),a=S1(e.skillsRoot,e.toName);if(i.skillDir===a.skillDir)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same skill.`}};if(!q(i.skillDir))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill at ${C1(e.skillsRoot,i.skillDir)}.`}};if(q(a.skillDir))return{ok:!1,error:{code:`SKILL_EXISTS`,message:`A skill already exists at ${C1(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:C1(e.skillsRoot,i.skillDir),toPath:C1(e.skillsRoot,a.skillDir),committed:o}}function b1(e){return Gs(e)?{ok:!0,skillsRoot:e}:{ok:!1,error:{code:`BAD_SKILLS_ROOT`,message:`skillsRoot must be absolute`}}}function x1(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.`}}:We.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 yut(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?za(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>fut?{ok:!1,error:{code:`DESCRIPTION_TOO_LONG`,message:`Skill frontmatter.description must be ≤${fut} characters (got ${e.description.length}).`}}:za(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 S1(e,t){let n=W(e,t);return{skillDir:n,filePath:W(n,d1)}}function but(e){if(q(e)&&w1(e))try{jH(e)}catch{}let t=Ks(W(e,`..`));if(t.endsWith(`${Js}.ok`)&&q(t)&&w1(t))try{jH(t)}catch{}}function C1(e,t){let n=t.startsWith(e+Js)?t.slice(e.length+1):t;return Ks(n).split(Js).join(`/`)}function xut(e){return(0,nl.stringify)({name:e.name,description:e.description,...e.metadata===void 0?{}:{metadata:e.metadata}})}function w1(e){try{return sc(e).length===0}catch{return!1}}const Sut=new Map;function Cut(e,t){Sut.set(e,t)}function T1(e,t){let n=Sut.get(e);if(n===void 0)return null;if(!We.test(e)||e.length>64)throw Error(`externalSkillAbsPath: invalid skill name ${JSON.stringify(e)}`);let r;if(t===null)r=K(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=K(n,...e)}if(!r.startsWith(n+Js))throw Error(`externalSkillAbsPath: path escape for ${JSON.stringify(e)}`);return r}function wut(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 Tut(e,t){return[...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({editor:e,root:t})),{editor:`agents`,root:t}]}const E1=Tut(Sr,Oi),D1=Tut(M,Oi);function O1(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`}function k1(e,t){let n=A1(e,t),r={},i;try{i=cc(e)}catch{return r}for(let{editor:t,root:a}of n){let n;try{n=cc(W(e,a))}catch{continue}if(n===W(i,a))continue;let o=G(i,n);o===``||o.startsWith(`..`)||Gs(o)||(r[t]=o.split(Js).join(`/`))}return r}function Eut(e){return e===`project`?E1:D1}function Dut(e){let t=A1(e,`global`).map(t=>W(e,t.root)),n=W(e,`.ok`,ya);return t.includes(n)?t:[...t,n]}function A1(e,t){return Out(t,Klt(e))}function Out(e,t){let n=Eut(e),r=new Set(n.map(e=>e.root));return[...n,...t.filter(e=>!r.has(e)).map(e=>({editor:e,root:e}))]}function j1(e){return new Set((e===`project`?E1:D1).map(e=>e.root))}function M1(e,t,n,r){return!j1(t).has(n)||q(W(e,Zi(n)))?!0:n===`.agents/skills`&&Ja.some(e=>e.scope===t&&q(W(r,e.dotDir)))}function kut(e,t,n,r){let i=new Set([...A1(e,t).map(e=>e.root),pa]),a=[];for(let t of i){let i=W(e,t,n),o;try{o=nc(i)}catch{continue}if(o.isSymbolicLink()){a.push(i);continue}uO(i)?.contentHash===r&&a.push(i)}return a}function Aut(e,t){let n=new Map((t===`project`?E1:D1).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 N1(e,t){let n=t===`project`?E1:D1;if(q(W(e,`.agents`)))return Oi;let r=[...n].filter(e=>e.editor!==`agents`).sort((e,t)=>{let n=vO.indexOf(e.editor),r=vO.indexOf(t.editor);return(n===-1?vO.length:n)-(r===-1?vO.length:r)});for(let{root:t}of r)if(q(W(e,Zi(t))))return t;return null}function jut(e){return[...new Set((e===`project`?E1:D1).map(e=>`${Zi(e.root)}/`))]}function Mut(e){try{if(!fc(W(e,`SKILL.md`)).isFile())return null}catch(e){if(O1(e))return null;throw e}let t=[],n=(e,r)=>{for(let i of sc(e,{withFileTypes:!0})){let a=W(e,i.name),o=r===``?i.name:`${r}/${i.name}`;if(i.isDirectory())iO.has(i.name)||n(a,o);else if(i.isFile()){let e=fc(a);t.push(`${o}:${e.size}:${e.mtimeMs}`)}}};return n(e,``),t.sort().join(`|`)}async function Nut(e){try{if(!(await Dc(W(e,`SKILL.md`))).isFile())return null}catch(e){if(O1(e))return null;throw e}let t=[],n=async(e,r)=>{for(let i of await Tc(e,{withFileTypes:!0})){let a=W(e,i.name),o=r===``?i.name:`${r}/${i.name}`;if(i.isDirectory())iO.has(i.name)||await n(a,o);else if(i.isFile()){let e=await Dc(a);t.push(`${o}:${e.size}:${e.mtimeMs}`)}}};return await n(e,``),t.sort().join(`|`)}const P1=new Map;function Put(e,t){let n=yi(he(t.skillMd)??{});return{stamp:e,contentHash:t.contentHash,description:t.description,size:Hte(t),...n===void 0?{}:{pack:n}}}function Fut(e){let t=Mut(e);if(t===null)return null;let n=P1.get(e);if(n!==void 0&&n.stamp===t)return n;let r=uO(e);if(!r)return null;let i=Put(t,r);return P1.set(e,i),i}function Iut(e){return Fut(e)?.contentHash}const F1=new Map,Lut=new Map;function Rut(e,t){let n=F1.get(e);if(n!==void 0)return n;let r=(async()=>{let t=await Nut(e);if(t===null)return!0;if(P1.get(e)?.stamp===t)return!1;let n=await fMe(e);return n&&P1.set(e,Put(t,n)),!1})().catch(e=>(zut(t,e),!1)).then(t=>{Lut.set(e,t)}).finally(()=>F1.delete(e));return F1.set(e,r),r}function zut(e,t){O1(t)||Y(`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 But(e){for(let{root:t}of I1(e,`global`).roots){let n=W(e,t),r;try{r=await Tc(n)}catch(e){zut(t,e);continue}for(let e of r)await Rut(W(n,e),t)}}function I1(e,t){let n=[],r={},i=[];try{let t=qlt(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:Out(t,i),failures:n}}function L1(e,t){let n=[],{sourcePrefs:r,roots:i,failures:a}=I1(e,t),o=e=>{a.push({scope:`scan`,error:e})},s=null;try{s=cc(e)}catch(e){O1(e)||o(e)}for(let{editor:c,root:l}of i){let i=W(e,l),u,d=!1;try{if(!fc(i).isDirectory())continue}catch(e){O1(e)||o(e);continue}try{d=s!==null&&cc(i)!==W(s,l),u=sc(i)}catch(e){o(e);continue}for(let e of u){let s=W(i,e);try{if(!fc(s).isDirectory())continue}catch(e){O1(e)||o(e);continue}let u;try{u=Fut(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||nc(s).isSymbolicLink(),...d?{aliasRooted:!0}:{},...r[e]===c?{preferredSource:!0}:{}})}catch(e){o(e)}}}let{admittedDirs:c,canonicalDir:l}=mNe(n),u=new Set(l.values());return{skills:bO(n).filter(e=>c.has(e.canonical.dir)).filter(e=>u.has(e.canonical.dir)||!FU(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=cc(W(e,t.canonical.dir))}catch{r=null}let i=t=>{if(r===null)return!1;try{return cc(W(e,t))===r}catch{return!1}},a=t.copies.filter(e=>e.aliasRooted!==!0&&(e.viaLink||!i(e.dir))),o=FU(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 Vut(e){return e.filter(e=>!F1e(e.name))}function R1(e){return Vut(L1(e,`project`).skills)}function z1(e){return L1(e,`global`).skills}async function B1(e){return Uut(e)&&await But(e),z1(e)}function Hut(e){let t=Lut.get(e);if(t===void 0)return!0;if(!t)return!1;try{return fc(W(e,`SKILL.md`)).isFile()}catch{return!1}}function Uut(e){for(let{root:t}of I1(e,`global`).roots){let n=W(e,t),r;try{r=sc(n)}catch{continue}if(r.some(e=>Hut(W(n,e))))return!0}return!1}const Wut=[...D1].sort((e,t)=>{let n=vO.indexOf(e.editor),r=vO.indexOf(t.editor);return(n===-1?vO.length:n)-(r===-1?vO.length:r)||e.editor.localeCompare(t.editor)});function V1(e,t){for(let{root:n}of Wut){let r=W(e,n,t);try{if(q(W(r,`SKILL.md`)))return r}catch{}}return null}function Gut(e){return new Set(A1(e,`project`).map(e=>e.root))}function H1(e){return e.slice(e.lastIndexOf(`/`)+1)}function Kut(e){return e.slice(0,e.lastIndexOf(`/`))}function qut(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=j1(`project`),c=e=>i.has(e)||r&&(!s.has(Kut(e))||a.has(e)&&(o.get(H1(e))??0)>=2),l=new Set([...e].filter(c).map(H1));return new Set([...[...e].filter(e=>l.has(H1(e))&&(c(e)||a.has(e))),...[...t].filter(e=>!l.has(H1(e)))])}function Jut(e,t){let n=L1(e,`project`),r=new Set(Vut(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 qut(t,r,n)}const Yut=Y(`installed-skills-marker`);function U1(e){return W(e,...Wee)}const Xut=e1();function Zut(e,t){return Xut(U1(e),t)}function W1(e){let t=U1(e);if(!q(t))return ie();try{return gi(J(t,`utf-8`))??ie()}catch(e){return Yut.warn({err:e,path:t},`installed-skills marker unreadable`),ie()}}function Qut(e){let t=U1(e);if(!q(t))return{ok:!0,state:ie()};let n;try{n=J(t,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?{ok:!0,state:ie()}:{ok:!1,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}let r=gi(n);return r===null?{ok:!1,reason:`its contents are not an installed-skills marker this server understands`}:{ok:!0,state:r}}function $ut(e){let t=Qut(e);if(t.ok)return t.state;let n=U1(e);throw Yut.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 edt(e,t){let n=are.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=U1(e);await yH(U(r),{recursive:!0}),await Fs(r,`${JSON.stringify(n.data,null,2)}\n`,{fs:MH})}async function G1(e,t,n){return Zut(e,async()=>{let r=$ut(e);await edt(e,{...r,skills:{...r.skills,[t]:n}})})}async function K1(e,t){return Zut(e,async()=>{let n=$ut(e),r=n.skills[t]??null;if(r===null)return null;let{[t]:i,...a}=n.skills;return await edt(e,{...n,skills:a}),r})}function q1(e,t){return`${e}:${t}`}function tdt(e){return W(RJ(e),Qte)}function J1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Y1(e){return typeof e==`string`?e:``}const ndt=()=>({ok:!0,store:{schema:1,retained:{}}});function rdt(e){let t=tdt(e);if(!q(t))return ndt();let n;try{n=J(t,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?ndt():{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(!J1(r)||!J1(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=J1(t)?t:{};i[e]={retainedAt:Y1(n.retainedAt),from:Y1(n.from),to:Y1(n.to),sourceState:Pte(n.sourceState)?n.sourceState:`unknown`,reason:Y1(n.reason),retainedContentHash:Y1(n.retainedContentHash)}}return{ok:!0,store:{schema:1,retained:i}}}function X1(e,t,n){let r=rdt(e);if(!r.ok)return{state:`unreadable`,reason:r.reason,...r.cause===void 0?{}:{cause:r.cause}};let i=r.store.retained[q1(t,n)];return i===void 0?{state:`none`}:{state:`record`,record:i}}const idt=e1();function adt(e,t){let n=tdt(e);return idt(n,async()=>{let r=rdt(e);if(!r.ok)throw Y(`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 yH(U(n),{recursive:!0}),await Fs(n,`${JSON.stringify(r.store,null,2)}\n`,{fs:MH}))})}function odt(e,t,n,r){return adt(e,e=>(e[q1(t,n)]=r,!0))}function sdt(e,t,n){return adt(e,e=>{let r=q1(t,n);return r in e&&(delete e[r],!0)})}function Z1(e){return(e===`.ok`||e.startsWith(`.ok/`))&&e!==`.ok/skills`}async function Q1(e,t,n){await o1(e,e=>{e.sources={...e.sources,[t]:n}})}async function cdt(e,t,n){await o1(e,e=>{e.folders={...e.folders,[t]:n}})}function ldt(e){return a1(e).folders??{}}async function udt(e,t){await o1(e,e=>{let n=new Set(e.roots??[]);n.has(t)||(n.add(t),e.roots=[...n].sort())})}function ddt(e,t){let n=a1(e).preferences?.[t];return n===`link`||n===`copy`?n:void 0}function $1(e){let t={};for(let[n,r]of Object.entries(a1(e).skills)){let i=r.filter(t=>{let n=n1(e,t.path);return n!==null&&q(W(n,`SKILL.md`))});i.length>0&&(t[n]=i)}return t}async function fdt(e,t,n){await o1(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 pdt(e,t){await o1(e,e=>{e.skills[t]!==void 0&&(e.skills={...e.skills},delete e.skills[t])})}async function e0(e,t,n){await o1(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 t0(e,t,n){let r=$1(e),i=n??R1(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)||n1(e,i)===null)continue;let a={path:i,mode:`copy`,hash:t.contentHash};await e0(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=n1(t,n.dir);if(o!==null)for(let t of i){if(t.mode!==`copy`||t.hash===void 0)continue;let r=n1(e,t.path);if(r===null||r===o)continue;let i=uO(r)?.contentHash;if(i!==void 0){if(i===n.contentHash){t.hash!==i&&await e0(e,n.name,{...t,hash:i});continue}i===t.hash&&(r=n1(e,t.path),r!==null&&(AH(r,{recursive:!0,force:!0}),wH(o,r,{recursive:!0,dereference:!0}),await e0(e,n.name,{...t,hash:n.contentHash}),a+=1))}}}return a}function mdt(e,t,n){let r;try{r=nc(e)}catch{return{kind:`absent`}}if(r.isSymbolicLink())try{return cc(e)===cc(t)?{kind:`symlink`,resolution:`target`}:{kind:`symlink`,resolution:`elsewhere`}}catch{return{kind:`symlink`,resolution:`dangling`}}if(!r.isDirectory())return{kind:`other`};try{if(cc(e)===cc(t))return{kind:`dir`,identity:`is-target`}}catch{return{kind:`dir`,identity:`different`}}return uO(e)?.contentHash===n?{kind:`dir`,identity:`same-content`}:{kind:`dir`,identity:`different`}}function n0(e,t){let n=o0(t);return e.filter(e=>n.includes(e))}const hdt=`open-knowledge`,gdt=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,_dt=[/^<{7} /m,/^={7}$/m,/^>{7} /m];function vdt(e){let t=e.match(gdt);if(!t)return null;try{let e=(0,nl.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=W(e,`SKILL.md`),o=q(W(e,`scripts`))&&fc(W(e,`scripts`)).isDirectory(),s=t.startsWith(hdt)&&Ni[t]===void 0;if(!n?.allowReservedName&&s&&r.push(`"${t}" uses the reserved \`${hdt}*\` prefix (reserved for OK's shipped skills) — choose another name.`),!q(a))return r.push(`No SKILL.md found at ${e}.`),{ok:r.length===0,errors:r,warnings:i,hasScripts:o};let c;try{c=J(a,`utf-8`)}catch(e){return r.push(`Cannot read SKILL.md: ${e.message}.`),{ok:!1,errors:r,warnings:i,hasScripts:o}}_dt.some(e=>e.test(c))&&r.push("SKILL.md contains git conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`). Resolve the conflict before installing.");let l=vdt(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`&&za(e)||typeof n==`string`&&za(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 ydt(e){let t=b();return Sa.filter(n=>{let r=fte(n,t);return r!==null&&q(K(e,r))})}function i0(e,t){if(t&&t.length>0){let e=new Set(Sa);return t.filter(t=>e.has(t))}return ydt(e)}function a0(e){return e===`global`?M:Sr}function o0(e){return e===`global`?lre:Sa}function s0(e,t,n,r=Sr){let i=r[t];return i===null?null:K(e,i,n)}function c0(e,t,n,r=Sr){return t===`agents`?K(e,Oi,n):s0(e,t,n,r)}function l0(e,t){if(!q(t))return!1;try{let n=G(cc(e),cc(t));return n.startsWith(`..`)||Gs(n)}catch{return!0}}function bdt(e,t){if(!q(e)||!q(t))return!1;try{return cc(e)===cc(t)}catch{return!1}}function xdt(e){let t=e?.code;return t===`EPERM`||t===`EACCES`}function u0(e,t,n){try{return kH(e,t,`dir`),`link`}catch(e){if(!xdt(e))throw e;return AH(t,{recursive:!0,force:!0}),wH(n,t,{recursive:!0,dereference:!0}),`copy`}}function Sdt(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 d0(e,t,n){let r=K(n),i=G(K(e),r);return i!==``&&!i.startsWith(`..`)&&!Gs(i)?G(t,r):r}function f0(e,t,n,r,i=`symlink`,a=Sr){let o=[];for(let s of r){let r=s0(n,s,t,a);if(r===null)continue;let c=U(r);if(l0(n,c))continue;if(bdt(c,U(e))){o.push(s);continue}let l=K(r)===K(e);if(!l&&q(r))try{l=cc(r)===cc(e)}catch{l=!1}if(l){o.push(s);continue}AH(r,{recursive:!0,force:!0}),SH(c,{recursive:!0}),i===`copy`?wH(e,r,{recursive:!0,dereference:!0}):u0(d0(n,c,e),r,e),o.push(s)}return o}function Cdt(e,t){if(!FU(t))return!1;try{return!nc(e).isSymbolicLink()&&q(W(e,`SKILL.md`))}catch{return!1}}function p0(e,t,n){let r=mdt(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 m0(e){let{canonicalAbs:t,canonicalHash:n,canonicalRootRel:r,name:i,cwd:a,targets:o}=e,s=e.roots??Sr,c=e.mode??`copy`,l=[],u=[],d=[],f=(e,n,r)=>{AH(e,{recursive:!0,force:!0}),SH(n,{recursive:!0}),c===`link`?u0(d0(a,n,t),e,t)===`copy`&&d.push(r):wH(t,e,{recursive:!0,dereference:!0})};for(let d of o){if(d===`agents`?r===`.agents/skills`:s[d]===r){let r=c0(a,d,i,s);if(r!==null&&!l0(a,U(r))){let i=p0(r,t,n);(c===`link`&&e.convertCopies===!0&&i===`same-copy`||c===`copy`&&e.convertLinks===!0&&i===`link-to-canonical`)&&f(r,U(r),d)}l.push(d);continue}let o=c0(a,d,i,s);if(o===null)continue;let p=U(o);if(!l0(a,p)){try{if(cc(p)!==W(cc(a),G(a,p)))continue}catch{}switch(p0(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(Cdt(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 h0(e){let{canonicalHash:t,name:n,cwd:r,newTarget:i}=e,a=e.roots??Sr,o;try{o=cc(e.canonicalAbs)}catch{return{ok:!1,reason:`target-unusable`}}try{if(nc(o).isSymbolicLink()||!nc(o).isDirectory())return{ok:!1,reason:`target-unusable`}}catch{return{ok:!1,reason:`target-unusable`}}let s=e.destDirAbs??c0(r,i,n,a);if(s===null)return{ok:!1,reason:`target-missing`};if(K(s)===o)return{ok:!0,newAbs:s};let c=U(s);if(l0(r,c))return{ok:!1,reason:`target-unusable`};switch(p0(s,o,t)){case`canonical-dir`:return{ok:!0,newAbs:s};case`different`:return{ok:!1,reason:`target-unusable`};case`same-copy`:try{if(nc(s).isSymbolicLink()||!q(W(s,`SKILL.md`)))return{ok:!1,reason:`target-unusable`}}catch{return{ok:!1,reason:`target-unusable`}}AH(o,{recursive:!0,force:!0});break;case`link`:case`link-to-canonical`:AH(s,{recursive:!0,force:!0}),SH(c,{recursive:!0}),CH(o,s);break;case`absent`:SH(c,{recursive:!0}),CH(o,s)}return!q(W(s,`SKILL.md`))||nc(s).isSymbolicLink()?{ok:!1,reason:`target-unusable`}:(e.leaveLinkBehind===!0&&!q(o)&&kH(d0(r,U(o),s),o,`dir`),g0({name:n,cwd:r,roots:a,target:s,skip:[s,o],alsoClaim:[o,s]}),{ok:!0,newAbs:s})}function wdt(e){return[`agents`,...o0(e===M?`global`:`project`)]}function Tdt(e,t,n){return wdt(n).map(r=>c0(e,r,t,n)).filter(e=>e!==null)}function g0(e){let{name:t,cwd:n,roots:r,target:i}=e,a=new Set((e.skip??[]).map(e=>K(e))),o=new Set((e.alsoClaim??[]).map(e=>K(e))),s=e.slots??Tdt(n,t,r);for(let e of s){if(a.has(K(e)))continue;try{if(!nc(e).isSymbolicLink())continue}catch{continue}let t=null;try{t=cc(e)}catch{t=null}t!==null&&!o.has(t)||(AH(e,{recursive:!0,force:!0}),kH(d0(n,U(e),i),e,`dir`))}}function _0(e){let{canonicalHash:t,name:n,cwd:r,targets:i}=e,a=e.roots??Sr,o;try{o=cc(e.canonicalAbs)}catch{return[]}let s=[];for(let e of i){let i=c0(r,e,n,a);if(i!==null&&!l0(r,U(i)))switch(p0(i,o,t)){case`same-copy`:case`link`:case`link-to-canonical`:AH(i,{recursive:!0,force:!0}),s.push(e);break;case`different`:Cdt(i,n)&&(AH(i,{recursive:!0,force:!0}),s.push(e))}}return s.length>0&&g0({name:n,cwd:r,roots:a,target:o}),s}function v0(e,t,n,r=Sr){let i=[];for(let a of n){let n=s0(t,a,e,r);if(n===null)continue;let o=!1;try{nc(n),o=!0}catch{o=!1}o&&(AH(n,{recursive:!0,force:!0}),i.push(a))}return i}function Edt(e){try{return q(e)?y0(e).filter(e=>e!==`SKILL.md`):[]}catch{return[]}}function y0(e,t=``){let n=[];for(let r of sc(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;zG(i)||(r.isDirectory()?n.push(...y0(W(e,r.name),i)):r.isFile()&&n.push(i))}return n.sort()}function Ddt(e){if(!q(e))return[];let t=[];for(let n of y0(e)){if(n===`SKILL.md`)continue;let r=null;try{let t=J(W(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 Odt(e){let t=[];q(K(e,`SKILL.md`))&&t.push(`SKILL.md`);let n=K(e,`references`);if(!q(n))return t;let r=(e,n)=>{let i;try{i=sc(e,{withFileTypes:!0})}catch{return}for(let a of i){let i=n?`${n}/${a.name}`:a.name;a.isDirectory()?r(K(e,a.name),i):a.isFile()&&a.name.toLowerCase().endsWith(`.md`)&&t.push(`references/${i}`)}};return r(n,``),t}function kdt(e){let{base:t,scope:n,fromName:r,toName:i}=e;if(r===i)return[];let a=Y(`skill-ref-rename`),o;try{o=n===`project`?R1(t):z1(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=K(t,e.dir);for(let t of Odt(n)){let o=K(n,t),c;try{c=J(o,`utf-8`)}catch(e){a.warn({err:e,absPath:o},`unreadable skill markdown; skipped`);continue}let l=Wre(c,r,i);if(l!==c){try{bH(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 b0(e){return q(e)?gt(J(e,`utf-8`))||(Y(`skills-lock`).warn({lockPath:e},`skills-lock.json is unreadable; continuing with an empty lock (import provenance for this project is lost)`),Dt()):Dt()}function Adt(e){if(!q(e))return{ok:!0,lock:Dt()};let t;try{t=J(e,`utf-8`)}catch(e){let t=e?.code;return t===`ENOENT`?{ok:!0,lock:Dt()}:{ok:!1,reason:t?`it could not be read (${t})`:`it could not be read`,cause:e}}let n=gt(t);return n===null?{ok:!1,reason:`its contents are not a skills lock this server understands`}:{ok:!0,lock:n}}const jdt=e1();function x0(e,t){return jdt(e,async()=>{let n=Adt(e);if(!n.ok)throw Y(`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 yH(U(e),{recursive:!0}),await Fs(e,`${JSON.stringify(i,null,2)}\n`,{fs:MH})})}function S0(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}Q(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:t.handler,extraHeaders:{Allow:n}})}}function Mdt(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,markAgentWriteStore:E,respondStaleExternalWrite:D,respondPersistenceFailure:O,okArtifactKey:k,resolveSkillsRoot:A,extractActorIdentityFromQuery:j,captureAndCloseDocuments:M,log:N,commitOkArtifactWrite:P,skillInstallBase:ee,uninstallSkillFromHostDirs:te,renameTrackedPathInGit:F,renamePathOnDisk:I,localSkillHash:ne,shadowHeadSha:re,artifactWriterId:ie,checkLocalOpSecurity:ae,effectiveSkillRoot:oe}=e;function se(e,t){let n=e===`project`?i:r;if(!n)return`symlink`;try{return b0(W(n,...yo)).skills[t]===void 0?`symlink`:`copy`}catch{return`symlink`}}function ce(e){let t=e===`project`?i:r;return t?W(t,...yo):null}function le(e,t,n,r={}){let i=ce(e);return i?x0(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 ue(e,t,n,r=n){let i=ce(e),a=ce(t);if(!i||!a)return!1;let o=b0(i).skills[n];if(!o)return!1;let s={...o};return t===`global`&&delete s.baselineRef,await x0(a,e=>({...e,skills:{...e.skills,[r]:s}})),await x0(i,e=>{let t={...e.skills};return delete t[n],{...e,skills:t}}),!0}function de(e,t,n){let r=ce(e);return r?x0(r,e=>{let r=e.skills[t];return r?{...e,skills:{...e.skills,[t]:{...r,...n}}}:e}):Promise.resolve()}function fe(e,t){let n=K(e,t,`references`);if(!q(n))return[];let r=[],i=(e,t)=>{for(let n of sc(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(K(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}async function pe(e,t,n){if(!l){Y(`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=J(n,`utf-8`)}catch(i){Y(`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=G(v,e).split(Js).join(`/`),o=(e,t)=>`${a}/${e}/${t?t.replace(/\.mdx?$/i,``):`SKILL`}`;i(o(t),o(n),K(e,n,`SKILL.md`));for(let r of fe(e,n))i(o(t,r),o(n,r),K(e,n,r));await l.recordDirectMutations(r)}async function me(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 he=ZQ(L,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(FU(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 wc(t.skillMd,`utf-8`));$(l,200,Zne,{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:Ddt(t.dir),managed:!0}},{handler:`skill-get`});return}}let p=u.searchParams.get(`host`)??void 0,m=s(f,d,p);if(m===null){Q(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=K(m,`SKILL.md`),{frontmatter:g,body:_}=o(await wc(h,`utf-8`));$(l,200,Zne,{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:Ddt(m)}},{handler:`skill-get`})}catch(e){Q(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 ge(e,t){!l||wW(e)||(u&&(d(),u.refreshInPlaceSkillDirs(),m()),h(e,t,`skill-put`))}let _e=ZQ(_re,async(e,n,i)=>{try{let e=DQ(i,g);if(e.kind===`invalid-summary`){Q(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=mut({name:i.name,body:typeof i.body==`string`?i.body:``,frontmatter:{name:i.frontmatter.name,description:i.frontmatter.description}});if(!a.ok){Q(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=N1(o,i.scope);if(t===null){Q(n,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-put`,detail:`NO_USABLE_SKILL_HOME`});return}let r=p1({boundary:o,skillsRoot:K(o,t),name:i.name,body:typeof i.body==`string`?i.body:``,frontmatter:{name:i.frontmatter.name,description:i.frontmatter.description}});if(!r.ok){let e=h1(r.error.code);Q(n,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,r.error.message,{handler:`skill-put`,detail:r.error.code,cause:r.error.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 ge(i.scope===`project`?`${t}/${i.name}/SKILL`:ui(`global`,i.name),a.content),x?.(`files`),$(n,200,Vne,{...SG(void 0,null),path:`${t}/${i.name}/SKILL.md`,created:!0,warnings:r.warnings,warningCodes:r.warningCodes},{handler:`skill-put`});return}let l=G(o,c).split(Js).join(`/`),u=`${l}/SKILL.md`,d=i.scope===`project`?`${l}/SKILL`:ui(i.scope,i.name);if(S(d,`skill-put`,n))return;let{agentId:f,agentName:p,colorSeed:m,clientName:h}=C(i),A=await w.getSession(d,f,{displayName:p,colorSeed:m,clientName:h});A.dc.document.transact(()=>{kq(A.dc.document,a.content,`agent`)},A.origin),E(d);let j=await T(d);if(j?.kind===`failure`&&!xG(j.failure)){O(n,j.failure,`skill-put`);return}if(j?.kind===`stale-external-write`){D(n,`skill-put`,d);return}i.scope===`project`&&(y(e,k(`skill`,``,i.name),`skill-edit: ${u}`),b(`skill-put`)),await ge(d,a.content),x?.(`files`),$(n,200,Vne,{...SG(void 0,j),path:u,created:!1,warnings:a.warnings,warningCodes:a.warningCodes},{handler:`skill-put`})}catch(e){Q(n,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`});function ve(e,t){let n=e===`project`?v:r,i=(e===`project`?R1(v):z1(r)).find(e=>e.name===t);return i?_0({canonicalAbs:K(n,i.dir),canonicalHash:i.contentHash,name:t,cwd:n,targets:i.hosts.filter(e=>Ii(e)),roots:a0(e)}):[]}let ye=ZQ(L,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}=oe(o,a,s),f=s===void 0?ee(o):void 0,p=f===void 0?{state:`none`}:X1(f,o,a),m=p.state===`record`&&p.record.sourceState!==`intact`&&p.record.retainedContentHash!==``&&u!==null?Ee(u):void 0;if(s!==void 0&&u===null){Q(r,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-delete`,detail:`No skill "${a}" (${o}) in ${s}.`});return}let h=j(i,g);if(h.kind===`invalid-summary`){Q(r,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await M(o===`project`?[...new Set([`${l}/SKILL`,ui(o,a)])]:[ui(o,a,s)],`deleted-upstream`),s===void 0&&ve(o,a);let _=y1({skillsRoot:c,name:a}),v=A(o);if(s===void 0&&_.ok&&v!==c&&q(K(v,a,`SKILL.md`))){let e=y1({skillsRoot:v,name:a});e.ok||N.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;Q(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(),P(`skill-delete`)),x?.(`files`));let b=ee(o),S=[];if(s===void 0&&b)try{await te(b,a,o)}catch(t){N.error({requestId:HK(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 (${ke(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)&&N.error({requestId:HK(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 Oe(f,o,a,{requestId:HK(e),handler:`skill-delete`})}$(r,200,gee,{existed:_.existed,path:_.path,...S.length>0?{warnings:S}:{}},{handler:`skill-delete`})}catch(e){Q(r,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),be=ZQ(Nne,async(e,n,a)=>{try{let l=DQ(a,g);if(l.kind===`invalid-summary`){Q(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}=oe(a.scope,a.fromName),f=a.scope===`project`?v:r,m=K(u,a.fromName),h=g1(f,m,K(m,`SKILL.md`));if(!h.ok){let e=h1(h.error.code);Q(n,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,h.error.message,{handler:`skill-move`,detail:h.error.code,cause:h.error.cause});return}let b=s(a.scope,a.toName);if(b!==null){let t=ee(a.scope),r=t===void 0?{state:`none`}:X1(t,a.scope,a.toName),i=Ee(b),{verdict:o,detail:s}=De(oe(a.scope,a.toName).dirRel,r,i);r.state===`record`&&o.kind===`plain-collision`&&await Oe(t,a.scope,a.toName,{requestId:HK(e),handler:`skill-move`}),Q(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 S=ee(a.scope),C=S?W1(S).skills[a.fromName]:void 0,w=(a.scope===`project`?R1(v):z1(r)).find(e=>e.name===a.fromName),T=w?U(w.dir):null,E=T===null?[]:Object.entries(k1(f,a.scope)).filter(([,e])=>e===T).map(([e])=>e),D=[...new Set([...C?n0(C.hosts,a.scope):[],...w?n0(w.hosts,a.scope):[],...n0(E,a.scope)])];await M(a.scope===`project`?[...new Set([`${d}/SKILL`,ui(a.scope,a.fromName)])]:[ui(a.scope,a.fromName)],`renamed`),ve(a.scope,a.fromName);let O=await vut({skillsRoot:u,fromName:a.fromName,toName:a.toName,relocate:async(e,t)=>{let n=await F(i,e,t);return n||I(e,t),n}});if(!O.ok){if(O.error.code===`SKILL_NOT_FOUND`){Q(n,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:O.error.message});return}if(O.error.code===`SKILL_EXISTS`){Q(n,409,`urn:ok:error:doc-already-exists`,O.error.message,{handler:`skill-move`,detail:O.error.code});return}let e=O.error.code===`MOVE_FAILED`?500:400;Q(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:O.error.code,cause:Error(O.error.message)});return}let A=null,j=K(u,a.toName,`SKILL.md`),te=``,ae=``;try{let e=o(J(j,`utf-8`));te=e.body,typeof e.frontmatter.description==`string`&&(ae=e.frontmatter.description)}catch{}let ce=typeof a.body==`string`?a.body:te,L=a.frontmatter===void 0?ae:a.frontmatter.description,ue=p1({boundary:f,skillsRoot:u,name:a.toName,body:ce,frontmatter:{name:a.toName,description:L}});ue.ok||(A=ue.error);let fe=[];if(!A)try{fe=kdt({base:a.scope===`project`?v:r,scope:a.scope,fromName:a.fromName,toName:a.toName})}catch(e){Y(`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`&&!A&&(p(),pe(u,a.fromName,a.toName).then(()=>me(fe,a.toName)).catch(()=>{}));let he=c(K(u,a.fromName),a.scope),ge=c(K(u,a.toName),a.scope),_e=ne(u,a.toName),ye=[],be=(e,t)=>{N.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} (${ke(e)}). A stale entry may remain until that file is repaired.`)};try{await le(a.scope,a.fromName,a.toName,{localHash:_e})}catch(e){be(e,`import records`)}if(a.scope===`project`&&(y(l,k(`skill`,``,a.toName),`skill-rename: ${he} -> ${ge}`,[{from:he,to:ge}]),(async()=>{try{await P(`skill-move`);let e=await re(ie(l),ge);e!==void 0&&await de(`project`,a.toName,{baselineRef:e})}catch(e){Y(`skill-move`).warn({err:e,toName:a.toName},`deferred shadow flush / revert-baseline failed — Revert stays unarmed until the next flush`)}})()),S){try{await K1(S,a.fromName)}catch(e){be(e,`install records`)}v0(a.fromName,S,D,a0(a.scope));let e=K(u,a.toName);if(D.length>0){let t=f0(e,a.toName,S,D,se(a.scope,a.toName),a0(a.scope));try{await G1(S,a.toName,{...C,scope:a.scope,hosts:t,scripts:C?.scripts??r0(e,a.toName).hasScripts,installedAt:C?.installedAt??new Date().toISOString()})}catch(e){be(e,`install records`)}}}if(x?.(`files`),A){let e=A.code===`WRITE_ERROR`?500:h1(A.code);Q(n,e,e===500?`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:A.code,cause:A.cause??Error(A.message)});return}$(n,200,Ite,{from:he,to:ge,committed:O.committed,...ye.length>0?{warnings:ye}:{}},{handler:`skill-move`})}catch(e){Q(n,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),xe=ZQ(Tre,async(e,n,r)=>{let{name:i,home:a}=r;if(!t(i,n,`skill-edit-external`))return;let o;try{o=cc(a)}catch{Q(n,404,`urn:ok:error:not-found`,`Skill directory not found.`,{handler:`skill-edit-external`,detail:`HOME_NOT_FOUND`});return}if(!fc(o).isDirectory()||!q(K(o,`SKILL.md`))){Q(n,400,`urn:ok:error:invalid-request`,`Not a skill directory (no SKILL.md).`,{handler:`skill-edit-external`});return}Cut(i,o),$(n,200,tn,{docName:ot(i)},{handler:`skill-edit-external`})},{handler:`skill-edit-external`,method:`POST`,preBodyGate:(e,t)=>ae(e,t,{handler:`skill-edit-external`})}),Se={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`},Ce=null;function we(){return Ce||=aH().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."}),Ce}function Te(e,t,n,r){we().add(1,{move_state:e,source_state:t??`none`,retention_ledger:n??`none`}),Y(`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 Ee(e){try{let t=uO(e);return t===null?q(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 De(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 Oe(e,t,n,r){if(e!==void 0)try{await sdt(e,t,n)}catch(e){Y(`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 ke=e=>e instanceof Error?e.message:String(e),Ae={"nothing-written":!1,"destination-removed":!0,"destination-stray":!0,"destination-retained":!0,"destination-retained-blocking":!1,"destination-unreadable":!0,"partially-applied":!0},je=ZQ(Xre,async(e,n,a)=>{let o;try{o=DQ(a,g)}catch(t){Q(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}),Te(`nothing-written`,void 0,void 0,{requestId:HK(e),status:400});return}let c=f,l=!1,u=!1,d=[],p=(t,r,i,a)=>{let o=`urn:uuid:${Nc()}`;Te(a.moveState,a.sourceState,a.retentionLedger,{instance:o,requestId:HK(e),status:t,droppedLocationCount:d.length,...a.logLevel===void 0?{}:{logLevel:a.logLevel}}),(u||Ae[a.moveState])&&c(),Q(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`,_)){Te(`nothing-written`,void 0,void 0,{requestId:HK(e),status:400});return}if(!t(g,n,`skill-move-scope`,_)){Te(`nothing-written`,void 0,void 0,{requestId:HK(e),status:400});return}if(FU(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(FU(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}=oe(m,f),C=K(b,f),w=(()=>{try{return cc(C)}catch{return C}})(),T=h===`project`?v:r,E=N1(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=K(T,E),O=K(D,g),k=G(T,O).split(Js).join(`/`);if(S===null||!q(C)){p(404,`urn:ok:error:not-found`,`Skill not found.`,{moveState:`nothing-written`,detail:`Skill "${f}" not found in ${m} scope.`});return}if(K(S)===K(O)||q(O)&&cc(S)===cc(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||q(O)){let t=ee(h),n=t!==void 0&&q(O)?X1(t,h,g):{state:`none`},r=Ee(O),{verdict:i,detail:a}=De(k,n,r);n.state===`record`&&i.kind===`plain-collision`&&await Oe(t,h,g,{requestId:HK(e),handler:`skill-move-scope`,toDirRel:k});let o=Se[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 A=ee(m),j=ee(h),N=A?W1(A).skills[f]:void 0,F=m===`project`?v:r,I=(m===`project`?R1(v):z1(r)).find(e=>e.name===f),ae=I?U(I.dir):null,ce=ae===null?[]:Object.entries(k1(F,m)).filter(([,e])=>e===ae).map(([e])=>e),le=[...new Set([...N?n0(N.hosts,m):[],...I?n0(I.hosts,m):[],...n0(ce,m)])],L=e=>e.filter(e=>n0([e],h).length===0),fe=[...new Set([...L(N?.hosts??[]),...L(I?.hosts??[])])].sort();if(u=!0,await M([...new Set([...m===`project`?[`${x}/SKILL`]:[],ui(m,f),ui(h,g)])],`renamed`),l=!0,SH(D,{recursive:!0}),wH(w,O,{recursive:!0,dereference:!0}),g!==f){let e=(e,t,n,r)=>{let i=y1({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=uO(O);if(t===null){e(400,`UNREADABLE_SKILL`,Error(`UNREADABLE_SKILL`),`error`);return}let n=m1({skillDir:O,toName:g,skillMd:t.skillMd});if(!n.ok){if(n.stage===`patch`){let t=wut(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(!q(W(O,`SKILL.md`))){let e=y1({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(ve(m,f))].sort();let pe=y1({skillsRoot:b,name:f});if(pe.ok&&w!==C){let e=(()=>{try{return cc(F)}catch{return F}})(),t=G(e,w);t!==``&&!t.startsWith(`..`)&&!Gs(t)&&AH(w,{recursive:!0,force:!0})}if(!pe.ok){let t,n=(()=>{if(!I)return`unknown`;try{let e=uO(C);return e&&e.contentHash===I.contentHash?`intact`:`lossy`}catch(e){return t=e,`unknown`}})(),r=!1,i=Ee(O);if(j!==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 odt(j,h,g,{retainedAt:new Date().toISOString(),from:`${m}:${f}`,to:`${h}:${g}`,sourceState:n,reason:pe.error.code,retainedContentHash:i.hash}),r=!0}catch(e){t=e}r||Y(`skill-move-scope`).error({event:`skill-move-scope.retention-record-failed`,requestId:HK(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 (${pe.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 (${pe.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 (${pe.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(pe.error.message,{cause:t}):Error(pe.error.message)});return}await Oe(j,h,g,{requestId:HK(e),handler:`skill-move-scope`,toDirRel:k});let me=[],he=!1;try{if(he=await ue(m,h,f,g),A&&await te(A,f,m,I?{purge:{contentHash:I.contentHash}}:{}),A&&await pdt(A,f),j&&le.length>0){let e=f0(O,g,j,le,se(h,g),a0(h));await G1(j,g,{...N,scope:h,hosts:e,scripts:N?.scripts??r0(O,g).hasScripts,installedAt:N?.installedAt??new Date().toISOString()})}he&&await de(h,g,{localHash:ne(D,g)})}catch(t){Y(`skill-move-scope`).error({err:t,name:f,toName:g,fromScope:m,toScope:h,requestId:HK(e)},`skill moved across scopes, but its bookkeeping could not be updated`),me.push(`The skill moved to ${h}, but this server could not update its install records (${ke(t)}). A stale entry may remain until that file is repaired.`)}if(!q(W(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:G(v,O).split(Js).join(`/`),`skill-move-scope: ${m} -> ${h} ${f}${g===f?``:` -> ${g}`}`);let t=G(v,O).split(Js).join(`/`),n=!!he&&h===`project`,r=HK(e);(async()=>{let e=await P(`skill-move-scope`);if(n){if(e!==`flushed`){Y(`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 re(ie(o),t);if(n===void 0){Y(`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 de(h,g,{baselineRef:n})}catch(e){Y(`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(),Te(`success`,void 0,void 0,{requestId:HK(e),status:200,droppedLocationCount:fe.length,logLevel:`debug`,message:`cross-scope skill move completed`}),$(n,200,bte,{scope:h,path:k,droppedLocations:fe,...me.length>0?{warnings:me}:{}},{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`}),Me=ZQ(St,async(e,n,i)=>{let a=f,o=!1,c=!1,l=!1;try{let e=DQ(i,g);if(e.kind===`invalid-summary`){Q(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||!q(W(u,`SKILL.md`))){Q(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=N1(d,i.scope);if(f===null){Q(n,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-duplicate`,detail:`NO_USABLE_SKILL_HOME`});return}let p=K(d,f),m=K(p,i.toName);if(s(i.scope,i.toName)!==null||q(m)){Q(n,409,`urn:ok:error:doc-already-exists`,`A ${i.scope} skill named "${i.toName}" already exists.`,{handler:`skill-duplicate`});return}let h=uO(u);if(!h){Q(n,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-duplicate`});return}let b=G(d,m).split(Js).join(`/`);o=!0,SH(p,{recursive:!0}),c=!0,wH(u,m,{recursive:!0,dereference:!0}),l=!0;let x=(e,t,r,o)=>{let s=y1({skillsRoot:p,name:i.toName});a(),Q(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=m1({skillDir:m,toName:i.toName,skillMd:h.skillMd});if(!S.ok){if(S.stage===`patch`){let e=wut(S.error);x(400,e,Error(e),`error`)}else x(500,`WRITE_FAILED`,S.cause);return}if(i.scope===`project`){let t=G(v,m).split(Js).join(`/`);y(e,k(`skill`,``,i.toName),`skill-duplicate: ${i.name} -> ${t}`),P(`skill-duplicate`)}a(),$(n,200,mn,{name:i.toName},{handler:`skill-duplicate`})}catch(e){o&&a(),Q(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 HQ({"/api/skill":S0({GET:he,PUT:_e,POST:be,DELETE:ye},{handler:`skill`}),"/api/skill/edit-external":xe,"/api/skill/duplicate":Me,"/api/skill/move-scope":je},{mutating:[`/api/skill`,`/api/skill/edit-external`,`/api/skill/duplicate`,`/api/skill/move-scope`]})}function Ndt(e){let t=[],n=e;for(;;){try{return W(cc.native(n),...t)}catch(e){let t=qW(e);if(t===`ELOOP`)return null;if(t!==`ENOENT`&&t!==`ENOTDIR`)throw e}try{if(nc(n).isSymbolicLink())return null}catch{}let e=U(n);if(e===n)return null;t.unshift(Hs(n)),n=e}}function C0(e,t){if(!YW(t,e))return`escapes`;if(zG(G(e,t).split(Js).join(`/`)))return`withheld`;let n=Ndt(e),r=Ndt(t);return n===null||r===null||!YW(r,n)?`escapes`:zG(G(n,r).split(Js).join(`/`))?`withheld`:`admitted`}function w0(e,t,n,r,i,a){let o=C0(n,K(n,r));if(o===`admitted`){let a=g1(t,n,K(n,r));if(a.ok)return!1;let o=h1(a.error.code);return Q(e,o,o===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,a.error.message,{handler:i,detail:`${r}: ${a.error.code}`,cause:a.error.cause}),!0}return Q(e,400,`urn:ok:error:invalid-request`,o===`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).`:a,{handler:i,detail:r}),!0}function Pdt(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,markAgentWriteStore:h,respondStaleExternalWrite:g,respondPersistenceFailure:_,attributeOkArtifactWrite:v,okArtifactKey:y,commitOkArtifactWrite:b,signalChannel:x,extractActorIdentityFromQuery:S,captureAndCloseDocuments:C,derivedDocumentIndex:w,log:T,recordDerivedMutationsBestEffort:E}=e;function D(e){if(e.includes(`\0`))return null;let t=aa(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 O(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function k(e,t){let n=K(e,t),r=G(u,e).split(Js).join(`/`),i;try{i=sc(n,{recursive:!0,encoding:`utf-8`})}catch{return[]}return i.filter(e=>/\.md$/i.test(e)).map(e=>`${r}/${t}/${e.split(Js).join(`/`).replace(/\.md$/i,``)}`)}function A(e,t){let n=t.replace(/\.md$/i,``);return`${iee(e).replace(/\/SKILL$/,``)}/${n}`}return HQ({"/api/skill-file":S0({GET:ZQ(L,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=FU(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`)){Q(c,400,`urn:ok:error:invalid-request`,`Invalid skill file path.`,{handler:`skill-file-get`});return}let g=(h&&f===`SKILL.md`?`reference`:D(f))??`reference`,_=m,v=p?h?.dir??null:o(d,u,_);if(v===null&&_!==void 0){Q(c,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-get`,detail:`No skill "${u}" (${d}) in ${_}.`});return}let y=v??K(s(d),u),b=K(y,f),x=C0(y,b);if(x===`escapes`){Q(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`||!q(S)){let e=x===`withheld`?null:f.match(/^(.*)\.(?:md|mdx)$/),t=e?wr.map(t=>`${e[1]}${t}`).find(e=>e!==f&&C0(y,K(y,e))===`admitted`&&q(K(y,e))):void 0;if(t===void 0){Q(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=K(y,t)}let w=await wc(S);if(w.includes(0)){Q(c,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}$(c,200,xee,{path:C.replace(/\\/g,`/`),kind:g,text:w.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){Q(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:ZQ(Pee,async(e,n,i)=>{try{let e=DQ(i,c);if(e.kind===`invalid-summary`){Q(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=D(i.path);if(a===null){Q(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){Q(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||!q(W(s,`SKILL.md`))){Q(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 S=i.scope===`project`?u:r,C=G(S,s).split(Js).join(`/`),w=i.path.replace(/\\/g,`/`);if(w0(n,S,s,w,`skill-file-put`,`Skill file path escapes the skill dir.`))return;let T=O(i.scope,a,w),E=null,k;if(T){let e=`${C}/${w.replace(/\.mdx?$/i,``)}`;if(d(e,`skill-file-put`,n))return;if(k=!q(K(s,w)),k&&hut(s)>=50){Q(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(()=>{kq(c.dc.document,i.content,`agent`)},c.origin),h(e);let l=await m(e);if(E=l,l?.kind===`failure`&&!xG(l.failure)){_(n,l.failure,`skill-file-put`);return}if(l?.kind===`stale-external-write`){g(n,`skill-file-put`,e);return}}else{let e=v1({boundary:S,skillsRoot:U(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:h1(e.error.code);Q(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}k=e.created}i.scope===`project`&&(v(e,y(`skill`,``,i.name),`${k?`skill-file-create`:`skill-file-edit`}: ${C}/${w}`),b(`skill-file-put`)),x?.(`files`),$(n,200,Dr,{...SG(void 0,E),path:w,created:k,kind:a,content:T},{handler:`skill-file-put`})}catch(e){Q(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:ZQ(L,async(e,i)=>{try{let a=new URL(e.url??``,`http://localhost`),d=a.searchParams,f=d.get(`name`)??``;if(!t(f,i,`skill-file-delete`)||l(f,i,`skill-file-delete`))return;let p=n(d.get(`scope`),i,`skill-file-delete`);if(p===null)return;let m=(d.get(`path`)??``).replace(/\\/g,`/`),h=D(m);if(h===null){Q(i,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must name a file inside the skill dir).`,{handler:`skill-file-delete`});return}let g=S(a,c);if(g.kind===`invalid-summary`){Q(i,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let _=o(p,f),w=_===null?s(p):U(_),T=p===`project`?u:r,E=_??W(w,f),j=K(E,m);if(w0(i,T,E,m,`skill-file-delete`,`Invalid skill file path (must name a file inside the skill dir).`))return;if(q(j)&&O(p,h,m)){let e=m.replace(/\.md$/i,``),t=_===null?A(f,m):`${G(u,_).split(Js).join(`/`)}/${e}`;await C([t],`deleted-upstream`)}else if(p===`project`&&_!==null&&q(j)&&fc(j).isDirectory()){let e=k(_,m);e.length>0&&await C(e,`deleted-upstream`)}let M=_ut({boundary:T,skillsRoot:w,name:f,relPath:m});if(!M.ok){let e=M.error.code===`UNLINK_FAILED`?500:h1(M.error.code);Q(i,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:M.error.code,cause:Error(M.error.message)});return}M.existed&&p===`project`&&(v(g,y(`skill`,``,f),`skill-file-delete: ${_===null?`${f}/${m}`:`${G(u,_).split(Js).join(`/`)}/${m}`}`),b(`skill-file-delete`)),M.existed&&x?.(`files`),$(i,200,Oee,{path:m,existed:M.existed,kind:h},{handler:`skill-file-delete`})}catch(e){Q(i,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":ZQ(F,async(e,n,i)=>{try{if(!t(i.name,n,`skill-file-rename`)||l(i.name,n,`skill-file-rename`))return;let e=DQ(i,c);if(e.kind===`invalid-summary`){Q(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-rename`});return}let a=i.from.replace(/\\/g,`/`),s=i.to.replace(/\\/g,`/`),f=D(a),p=D(s);if(f===null||p===null){Q(n,400,`urn:ok:error:invalid-request`,`Both paths must stay inside the skill dir.`,{handler:`skill-file-rename`,detail:f===null?a:s});return}let m=o(i.scope,i.name);if(m===null){Q(n,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-rename`});return}let h=U(m),g=i.scope===`project`?u:r;if([a,s].some(e=>w0(n,g,m,e,`skill-file-rename`,`Both paths must stay inside the skill dir.`)))return;let _=O(i.scope,f,a),S=O(i.scope,p,s),T=G(u,m).split(Js).join(`/`),A=_?`${T}/${a.replace(/\.md$/i,``)}`:null,j=S?`${T}/${s.replace(/\.md$/i,``)}`:null;if(A!==null&&d(A,`skill-file-rename`,n))return;if(A!==null)await C([A],`deleted-upstream`);else if(i.scope===`project`){let e=K(m,a);if(q(e)&&fc(e).isDirectory()){let e=k(m,a);e.length>0&&await C(e,`deleted-upstream`)}}let M=gut({boundary:g,skillsRoot:h,name:i.name,relPath:a,toRelPath:s});if(!M.ok){let e=M.error.code===`RENAME_FAILED`?500:h1(M.error.code);Q(n,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,M.error.message,{handler:`skill-file-rename`,detail:M.error.code});return}if(w){let e=[];if(A!==null&&j!==null)try{e.push({kind:`rename`,oldDocumentName:A,newDocumentName:j,markdown:J(K(h,i.name,s),`utf-8`)})}catch{e.push({kind:`delete`,documentName:A})}else if(A!==null)e.push({kind:`delete`,documentName:A});else if(j!==null)try{e.push({kind:`upsert`,documentName:j,markdown:J(K(h,i.name,s),`utf-8`)})}catch{}await E(e,`skill-file-rename`)}i.scope===`project`&&(v(e,y(`skill`,``,i.name),`skill-file-rename: ${i.name}/${a} -> ${s}`),b(`skill-file-rename`)),x?.(`files`),$(n,200,Ote,{from:a,to:s,...A===null?{}:{fromDocName:A},...j===null?{}:{toDocName:j}},{handler:`skill-file-rename`})}catch(e){T.error({err:e},`[skill-file-rename] failed`),n.headersSent||Q(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 Fdt(e,t){return(0,MLe.default)({headers:e.headers,defParamCharset:`utf8`,limits:t})}function Idt(e){return e.kind===`git`&&!zQ(e.url)}function T0(e,t,n){return t.kind===`git`&&Idt(t)?(Q(e,400,`urn:ok:error:url-not-allowed`,`Git URL protocol is not allowed.`,{handler:n,cause:Error(`url=${t.url}`)}),!0):!1}const Ldt=/[^\p{L}\p{N}\p{M}\p{Extended_Pictographic}.\-_ ]/gu,Rdt=/[/\\\x00-\x1f\x7f]/g;function zdt(e){let t=e.replace(Rdt,``);if(t=t.replace(Ldt,`_`),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 Bdt=Y(`skill-import`),Vdt={maxFileBytes:ge,maxFiles:512};function Hdt(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 ${ge}.`;t+=e}return t>67108864?`Skill is ${t} bytes; the import bundle cap is ${_i}.`:null}function Udt(e){function t(e,t){return uO(K(e,t))?.contentHash}return{async runSkillImport(n){let{acquiredDir:r,scope:i,sourceLabel:a,ref:o,publisher:s,upstreamSkill:c,subpath:l,actor:u}=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 d=lO(r);if(d)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:d};let f=uO(r);if(!f)return{ok:!1,status:422,urn:`urn:ok:error:invalid-request`,title:`Source has no readable skill.`};let p=Hdt(f);if(p)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:p};let m=W(i===`project`?e.projectDir:e.skillsHome,...yo),h=b0(m),g=i===`project`?e.contentDir:e.skillsHome,_=N1(g,i);if(_===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 (${jut(i).join(`, `)}) and never creates one for you. Create the folder your agent uses, then import again.`,detail:`NO_USABLE_SKILL_HOME`};let v=K(g,_),y=li(h,f.contentHash);if(y&&e.resolveSkillDirForRead(i,y)!==null)return{ok:!0,body:{name:y,path:`${y}/SKILL.md`,created:!1,alreadyImported:!0,provenance:{source:a,ref:o,contentHash:f.contentHash,publisher:s},warnings:[],warningCodes:[]}};let b=zdt(f.name),x=t=>e.resolveSkillDirForRead(i,t)!==null||q(K(v,t,`SKILL.md`)),S=x(b),C=b;if(S){C=`${b}-imported`;let e=2;for(;x(C);)C=`${b}-imported-${e}`,e+=1}let w=e.parseFrontmatterDoc(f.skillMd),T=w.body,E=yi(w.frontmatter),D=p1({boundary:g,skillsRoot:v,name:C,body:T,frontmatter:{name:C,description:f.description,...E===void 0?{}:{metadata:{pack:E}}}});if(!D.ok){let e=h1(D.error.code);return{ok:!1,status:e,urn:e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,title:D.error.message,detail:D.error.code,cause:D.error.cause??Error(D.error.message)}}let O=[...D.warnings];for(let e of f.files){let t=v1({boundary:g,skillsRoot:v,name:C,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:Vdt});if(!t.ok){let n=y1({skillsRoot:v,name:C}),r=n.ok?h1(t.error.code):500;return{ok:!1,status:r,urn:r===400?`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(u,`${_}/${C}/SKILL`,`skill-import: ${a} -> ${_}/${C}/SKILL.md`),await e.commitOkArtifactWrite(`skill-import`));let k=t(v,C),A=BO(a),j=i===`project`?await e.shadowHeadSha(e.artifactWriterId(u),`${_}/${C}`):void 0;if(await x0(m,e=>Jt(e,C,{source:a,...A?{pluginProvider:A.provider}:{},ref:o,contentHash:f.contentHash,files:f.files.map(e=>e.relPath),...k===void 0?{}:{localHash:k},...j===void 0?{}:{baselineRef:j},publisher:s,importedAt:new Date().toISOString(),...c===void 0?{}:{skill:c},...l===void 0?{}:{subpath:l}})),n.skipProjection!==!0)try{let t=i0(g);if(t.length>0){let n=K(v,C),r=a0(i),a=t.filter(e=>{let t=s0(g,e,C,r);return t!==null&&t!==n&&q(t)}),o=a.filter(e=>{let t=s0(g,e,C,r);try{return t!==null&&nc(t).isSymbolicLink()}catch{return!1}});m0({canonicalAbs:n,canonicalHash:uO(n)?.contentHash??``,canonicalRootRel:_,name:C,cwd:g,targets:t,mode:e.effectiveInstallMode(i,C,{hosts:[`<source>`,...a],linkedHosts:o}),roots:a0(i)})}}catch(e){Bdt.warn({err:e,skill:C},`post-import editor fan-out failed (import kept)`)}return e.signalFiles(),{ok:!0,body:{name:C,path:`${_}/${C}/SKILL.md`,created:D.created,alreadyImported:!1,...S?{collisionRenamedFrom:f.name}:{},provenance:{source:a,ref:o,contentHash:f.contentHash,publisher:s},warnings:O,warningCodes:D.warningCodes}}}}}function Wdt(e,t){if(t===void 0)return e;let{subpath:n,...r}=e;return t.kind===`set`?{...r,subpath:t.subpath}:r}function Gdt(e,t){return Kdt(e,t)[0]}function Kdt(e,t){let{recordedSkill:n,localName:r,frontmatterNameOf:i}=t,a=Ni[n??r],o=[e=>n!==void 0&&n!==``&&e.name===n,e=>e.name===r,e=>i(e.dir)===r,e=>a!==void 0&&e.name===a];for(let t of o){let n=e.filter(t);if(n.length>0)return n}return e.length===1?[...e]:[]}function qdt(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 Jdt(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 Ydt(e){return{async runSkillReimport(t){let{acquiredDir:n,name:r,scope:i,entry:a,lockPath:o,ref:s,folder:c,actor:l}=t,u=i===`global`?e.skillsHome:e.contentDir,{root:d,dirRel:f,realDir:p}=e.effectiveSkillRoot(i,r),m=!f.startsWith(`${e.legacyStoreRoot}/`);if(p===null||!q(K(u,f,`SKILL.md`)))return{ok:!1,status:404,urn:`urn:ok:error:not-found`,title:`Skill is not installed.`,detail:`SKILL_ABSENT`};let h=lO(n);if(h)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:h};let g=uO(n);if(!g)return{ok:!1,status:422,urn:`urn:ok:error:invalid-request`,title:`Source has no readable skill.`};let _=Hdt(g);if(_)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:_};let v=uO(K(d,r)),{upToDate:y,removedUpstream:b}=qdt({upstreamHash:g.contentHash,upstreamFiles:g.files.map(e=>e.relPath),entry:a,local:v?{contentHash:v.contentHash,files:v.files.map(e=>e.relPath)}:null});if(y)return{ok:!0,body:{name:r,updated:!1,source:a.source,warnings:[],warningCodes:[]}};let x=e.parseFrontmatterDoc(g.skillMd),S=x.body,C=yi(x.frontmatter),w=K(d,r);for(let e of[`SKILL.md`,...g.files.map(e=>e.relPath),...b]){let t=g1(u,w,K(w,e));if(!t.ok){let n=h1(t.error.code);return{ok:!1,status:n,urn:n===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,title:t.error.message,detail:`${e}: ${t.error.code}`,cause:t.error.cause??Error(t.error.message)}}}if(t.dryRun){let t;if(i===`project`&&e.projectDir)try{let n=kN({baseDir:e.projectDir,timeout:{block:15e3}}),i=G(e.projectDir,K(d,r)).split(Js).join(`/`);t=(await n.raw(`ls-files`,...on([i]))).trim().length>0}catch{t=void 0}return{ok:!0,body:{name:r,updated:!0,source:a.source,localBody:e.parseFrontmatterDoc(v?.skillMd??``).body,upstreamBody:S,...t===void 0?{}:{gitTracked:t},warnings:[],warningCodes:[]}}}if(i===`project`){let t=b.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${f}/${e.replace(/\.mdx?$/i,``)}`);t.length>0&&await e.captureAndCloseDocuments(t,`deleted-upstream`)}let T=p1({boundary:u,skillsRoot:d,name:r,body:S,frontmatter:{name:r,description:g.description,...C===void 0?{}:{metadata:{pack:C}}}});if(!T.ok){let e=h1(T.error.code);return{ok:!1,status:e,urn:e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,title:T.error.message,detail:T.error.code,cause:T.error.cause??Error(T.error.message)}}let E=[...T.warnings];for(let e of g.files){let t=v1({boundary:u,skillsRoot:d,name:r,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:Vdt});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 b){let t=_ut({boundary:u,skillsRoot:d,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(l,e.skillArtifactKey(r),`skill-reimport: ${a.source} -> ${f}`),await e.commitOkArtifactWrite(`skill-reimport`));let D=uO(K(d,r))?.contentHash,O=i===`project`?await e.shadowHeadSha(e.artifactWriterId(l),f):void 0;return await x0(o,e=>Jt(e,r,{...Wdt(e.skills[r]??a,c),contentHash:g.contentHash,files:g.files.map(e=>e.relPath),...D===void 0?{}:{localHash:D},...O===void 0?{}:{baselineRef:O},ref:s,importedAt:new Date().toISOString()})),!m&&i===`project`&&await e.projectImportedSkillCopy({skillsRoot:d,name:r,scope:`project`,hasScripts:g.files.some(e=>e.relPath.startsWith(`scripts/`)),handler:`skill-reimport`}),e.signalFiles(),{ok:!0,body:{name:r,updated:!0,source:a.source,warnings:E,warningCodes:T.warningCodes}}}}}function Xdt(e){return e.kind===`git`&&!e.subpath}function E0(e,t){return G(e,t).split(Js).join(`/`)}function Zdt(e){if(!(e===void 0||/^[A-Za-z]:/.test(e)))return e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`&&!/[\\\0\r\n]/.test(e))?e:void 0}async function D0(e,t){if(!e.fetchFolders||t.length===0)return{dirs:[...t],ref:e.ref,cleanup:()=>{}};let n=t.map(t=>E0(e.dir,t)),r=await e.fetchFolders([...new Set(n)]);return{dirs:n.map(e=>W(r.dir,e)),ref:r.ref,cleanup:r.cleanup}}function O0(e){return{...e.recordedSkill===void 0?{}:{recordedSkill:e.recordedSkill},localName:e.name,frontmatterNameOf:e=>uO(e)?.name}}async function Qdt(e,t){let n=Zdt(t.entry.subpath);if(n===void 0)return;let r;try{r=await KD({...e,subpath:n})}catch(e){if(e instanceof MD)return;throw e}try{let e=pO(r.dir),n=Gdt(e,O0(t));if(!n){r.cleanup();return}return{dirs:e,picks:new Map([[t.name,{dir:n.dir}]]),ref:r.ref,cleanup:r.cleanup}}catch(e){throw r.cleanup(),e}}async function $dt(e,t){if(e.kind!==`git`||e.subpath){let n=await KD(e);try{let e=pO(n.dir),r=new Map;for(let n of t){let t=Gdt(e,O0(n));t&&r.set(n.name,{dir:t.dir})}return{dirs:e,picks:r,ref:n.ref,cleanup:n.cleanup}}catch(e){throw n.cleanup(),e}}let n=t.length===1?t[0]:void 0,r=n?await Qdt(e,n):void 0;if(r)return r;let i=await qD(e);try{let e=pO(i.dir),n=[];for(let r of t){let t=Zdt(r.entry.subpath);if(t!==void 0&&q(W(i.dir,t,`SKILL.md`))){n.push({name:r.name,dir:W(i.dir,t)});continue}let a=Kdt(e,O0(r)),o=a[0];if(!o)continue;let s=E0(i.dir,o.dir),c=a.length===1&&s!==``?{kind:`set`,subpath:s}:r.entry.subpath===void 0?void 0:{kind:`clear`};n.push({name:r.name,dir:o.dir,...c?{folder:c}:{}})}let r=await D0(i,n.map(e=>e.dir));return{dirs:e,picks:new Map(n.map((e,t)=>[e.name,{dir:r.dirs[t],...e.folder?{folder:e.folder}:{}}])),ref:r.ref,cleanup:()=>{r.cleanup(),i.cleanup()}}}catch(e){throw i.cleanup(),e}}function eft(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){$(e,200,lne,t.body,{handler:`skill-import`});return}Q(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=ZQ(Are,async(e,c,d)=>{let f=()=>{};try{if(!t){Q(c,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=DQ(d,n);if(e.kind===`invalid-summary`){Q(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,b=d.source;{let e=d.source;try{let t=await _O(e,d.skill),n=t?.source??e;b=n;let r=d.skill??t?.skill,i=t?.spec??WD(n);if(!i){Q(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(T0(c,i,`skill-import`))return;let a=await qD(i);f=a.cleanup,g=a.ref;let o=pO(a.dir);if(o.length===0){Q(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=>cO(e.dir)?.name===r)??o.find(e=>e.name===Ni[r]);if(!e){Q(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){Q(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}let u=E0(a.dir,s.dir),p=await D0(a,[s.dir]),x=f;f=()=>{p.cleanup(),x()},g=p.ref,m=p.dirs[0]??s.dir,Xdt(i)&&u!==``&&(y=u),v=s.name,h=e,_=t?.publisher??l(n)}catch(e){if(e instanceof AD){Q(c,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!m){Q(c,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let x=await r.runSkillImport({acquiredDir:m,scope:p,sourceLabel:h,ref:g,publisher:_,upstreamSkill:v,...y===void 0?{}:{subpath:y},actor:e,skipProjection:d.install===!1});x.ok&&(d.marketplace===!0||A(b))&&c1({source:b,skills:[x.body.name]},$$()),i(),a?.refreshInPlaceSkillDirs(),o(),s?.(`files`),u(c,x)}catch(e){Q(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=ZQ(wne,async(e,c,u)=>{let d=()=>{};try{if(!t){Q(c,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=DQ(u,n);if(e.kind===`invalid-summary`){Q(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,y=new Map,b=e=>h.find(t=>t.name===e)??h.find(t=>uO(t.dir)?.name===e)??h.find(t=>t.name===Ni[e]);try{let e=await _O(f,u.skills[0]),t=e?.source??f;v=t;let n=e?.spec??WD(t);if(!n){Q(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(T0(c,n,`skills-import-bulk`))return;if(_=e?.publisher??l(t),n.kind===`well-known`)p=n,m=await VD(n.origin);else{let e=await qD(n);d=e.cleanup,g=e.ref,h=pO(e.dir);let t=[...new Set(u.skills)].flatMap(e=>{let t=b(e);return t?[t.dir]:[]}),r=await D0(e,t);d=()=>{r.cleanup(),e.cleanup()},g=r.ref,t.forEach((t,i)=>{let a=E0(e.dir,t);y.set(t,{dir:r.dirs[i]??t,...Xdt(n)&&a!==``?{subpath:a}:{}})})}}catch(e){if(e instanceof AD){Q(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){Q(c,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let x=[];for(let t of new Set(u.skills)){let n,i,a,o=()=>{};if(p!==null)try{let e=await KD({...p,skill:t},m?{index:m}:{});n=e.dir,o=e.cleanup,i=t}catch(e){let n=e instanceof AD&&!(e instanceof jD);x.push({requested:t,status:n?`not-found`:`failed`,warnings:[],warningCodes:[],...n?{}:{error:e instanceof jD?e.message:String(e)}});continue}else{let e=b(t);if(!e){x.push({requested:t,status:`not-found`,warnings:[],warningCodes:[]});continue}let r=y.get(e.dir);n=r?.dir??e.dir,a=r?.subpath,i=e.name}try{let o=await r.runSkillImport({acquiredDir:n,scope:u.scope,sourceLabel:f,ref:g,publisher:_,upstreamSkill:i,...a===void 0?{}:{subpath:a},actor:e,skipProjection:u.install===!1});if(!o.ok){Y(`skills-import-bulk`).warn({skill:t,err:o.cause,detail:o.detail},`bulk import: one skill failed (rest continue)`),x.push({requested:t,status:`failed`,warnings:[],warningCodes:[],error:o.detail?`${o.title} (${o.detail})`:o.title});continue}x.push({requested:t,status:o.body.alreadyImported?`already-imported`:`imported`,name:o.body.name,...o.body.collisionRenamedFrom===void 0?{}:{collisionRenamedFrom:o.body.collisionRenamedFrom},warnings:o.body.warnings,warningCodes:o.body.warningCodes})}catch(e){Y(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),x.push({requested:t,status:`failed`,warnings:[],warningCodes:[],error:e instanceof Error?e.message:String(e)})}finally{o()}}if(u.marketplace===!0||A(v)){let e=x.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&c1({source:v,skills:e},$$())}i(),a?.refreshInPlaceSkillDirs(),o(),s?.(`files`),$(c,200,ce,{results:x,imported:x.filter(e=>e.status===`imported`).length,alreadyImported:x.filter(e=>e.status===`already-imported`).length,failed:x.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){Q(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=K(e,n);return r!==e&&!r.startsWith(e+Js)?null:r}function g(e){return new Promise((t,n)=>{let r;try{r=Fdt(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,jLe.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(`/`)){SH(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{SH(U(n),{recursive:!0}),bH(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=ic(W(bc(),`ok-skill-upload-`)),o=()=>{try{AH(a,{recursive:!0,force:!0})}catch{}};try{if(!t){Q(i,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){Q(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=DQ({agentId:l(`agentId`),agentName:l(`agentName`),colorSeed:l(`colorSeed`),clientName:l(`clientName`),summary:l(`summary`)},n);if(d.kind===`invalid-summary`){Q(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){Q(i,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(f.length===0){Q(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){Q(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){Q(i,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}SH(U(t),{recursive:!0}),bH(t,e.data)}let v=pO(a);if(v.length===0){Q(i,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(v.length>1){Q(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){Q(i,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{o()}}return HQ({"/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 tft(e){let{resolveSkillsRoot:t,validateSkillName:n,projectDir:r,skillInstallBase:i,contentDir:a,skillsHome:o,shippedBundleSkillMd:s,flushDiskAndDetectOutcome:c,respondStaleExternalWrite:l,respondPersistenceFailure:u,skillInstallOps:d,skillPlacementOps:f,signalChannel:p,bumpSkillsCatalogGen:m,contentFilter:h,scheduleDeferredIgnoreRebuild:g,effectiveInstallMode:_,log:v}=e;return HQ({"/api/skill/install":ZQ(Jee,async(e,y,b)=>{try{let e=t(b.scope);if(!n(b.name,y,`skill-install`))return;if(b.scope===`project`&&!r){Q(y,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 x=i(b.scope),S=K(e,b.name),C=b.scope===`project`?a:o,w=(b.scope===`project`?R1(a):z1(o)).find(e=>e.name===b.name),T=FU(b.name)?s(b.name,b.scope):null,E=w?K(C,w.dir):q(S)||T===null?S:U(T);if(!q(E)){Q(y,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${b.name}" not found in ${b.scope} scope — create it with write({ skill }) first.`});return}let D=b.scope===`project`?`${G(C,E).split(Js).join(`/`)}/SKILL`:ui(b.scope,b.name),O=await c(D);if(O?.kind===`failure`&&!xG(O.failure)){u(y,O.failure,`skill-install`);return}if(O?.kind===`stale-external-write`){l(y,`skill-install`,D);return}let k=r0(E,b.name,{allowReservedName:FU(b.name)});if(!k.ok){Q(y,400,`urn:ok:error:invalid-request`,`Skill "${b.name}" cannot be installed: ${k.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(b.fork!==void 0){if(!w){Q(y,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=d.resolveFork({scope:b.scope,name:b.name,fork:b.fork,inPlaceEntry:w});if(!e.ok)switch(e.kind){case`unknown-editor`:Q(y,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:Q(y,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:Q(y,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`:Q(y,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:Q(y,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)}`)}p?.(`files`),m(),h?.refreshInPlaceSkillDirs(),g(),$(y,200,Va,{name:b.name,hosts:w.hosts.filter(Ii),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let A=b.setSource??b.source,j=b.linkMode??(b.mode===void 0?void 0:b.mode===`link`),M=b.targets,N=[],P=[];if(b.add!==void 0||b.remove!==void 0){if(!w){Q(y,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 d.applyAddRemove({scope:b.scope,name:b.name,inPlaceEntry:w,...b.add===void 0?{}:{add:b.add},...b.remove===void 0?{}:{remove:b.remove}});if(!e.ok){e.kind===`remove-source`?Q(y,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`}):Q(y,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}M=e.targets.filter(Ii),N.push(...e.rootAdds),P.push(...e.rootRemoves)}if(A&&!w){let e=await d.promoteStoreBackedSource({scope:b.scope,name:b.name,base:x,skillDir:E,newSource:A});if(!e.ok){Q(y,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}p?.(`files`),m(),h?.refreshInPlaceSkillDirs(),g(),$(y,200,Va,{name:b.name,hosts:e.hosts,scripts:k.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(b.place){let e=b.scope===`project`?r:o;if(!e){Q(y,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 f.place({placeBase:e,name:b.name,rawDir:b.place.dir,skillDir:E,mode:b.place.mode});if(!t.ok){t.kind===`invalid-path`?Q(y,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):Q(y,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||p?.(`files`),m(),h?.refreshInPlaceSkillDirs(),g(),$(y,200,Va,{name:b.name,hosts:w?[...w.hosts]:[],scripts:k.hasScripts,...`copiedInsteadOfLinked`in t&&t.copiedInsteadOfLinked?{warnings:[Sdt([U(t.placedAt)])],warningCodes:[`links-not-permitted`]}:{warnings:[],warningCodes:[]},placedAt:t.placedAt},{handler:`skill-install`});return}if(b.unplace){let e=b.scope===`project`?r:o;if(!e){Q(y,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 f.unplace({placeBase:e,name:b.name,rawPath:b.unplace.path,skillDir:E});if(!t.ok)switch(t.kind){case`not-recorded`:Q(y,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:t.path});return;case`unsafe-path`:Q(y,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:Q(y,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`:Q(y,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)}`)}p?.(`files`),m(),h?.refreshInPlaceSkillDirs(),g(),$(y,200,Va,{name:b.name,hosts:w?[...w.hosts]:[],scripts:k.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(b.convert){if(!w){Q(y,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}=b.convert,n=b.scope===`project`?r:o,i=await f.convert({ledgerBase:n??x,scope:b.scope,name:b.name,target:e,mode:t,skillDir:E,canonicalHash:w.contentHash});if(!i.ok)switch(i.kind){case`invalid-location`:Q(y,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:Q(y,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`:Q(y,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`:Q(y,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return;case`links-not-permitted`:Q(y,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)}`)}p?.(`files`),$(y,200,Va,{name:b.name,hosts:[...w.hosts],scripts:k.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let ee=b.scope===`global`?M===void 0?u1(o).map(e=>e.editorId):lre.filter(e=>M?.some(t=>t===e)):M===void 0?i0(x):Sa.filter(e=>M?.some(t=>t===e)),te=[],F=[];if(ee.length===0&&M===void 0&&(te.push(b.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`."),F.push(`no-targets`)),k.hasScripts&&(te.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."),F.push(`scripts-present`)),k.warnings.length>0&&(te.push(k.warnings[0]),F.push(`no-description`)),w){let e=w.dir.split(`/`).slice(0,-1).join(`/`),t=(M===void 0?b.scope===`global`&&q(W(o,`.agents`)):M.includes(`agents`))?[...ee,`agents`]:[...ee],n=b.scope===`project`?r:o,i=j===void 0?_(b.scope,b.name,w):j?`link`:`copy`;if(A){let e=await d.promoteInPlaceSource({scope:b.scope,name:b.name,base:x,...n?{prefBase:n}:{},skillDir:E,inPlaceEntry:w,newSource:A});if(!e.ok){e.kind===`invalid-target`?Q(y,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}):Q(y,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}p?.(`files`),$(y,200,Va,{name:b.name,hosts:e.hosts,scripts:k.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let a=await d.fanOutInPlace({scope:b.scope,name:b.name,base:x,...n?{prefBase:n}:{},skillDir:E,inPlaceEntry:w,canonicalRootRel:e,inPlaceTargets:t,setExact:M!==void 0,installMode:i,...j===void 0?{}:{linkModeReq:j},rootAdds:N,rootRemoves:P});if(!a.ok){Q(y,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}te.push(...a.warnings),F.push(...a.warningCodes),p?.(`files`),$(y,200,Va,{name:b.name,hosts:a.hosts,scripts:k.hasScripts,warnings:te,warningCodes:F,...a.sourceMovedTo===void 0?{}:{sourceMovedTo:a.sourceMovedTo}},{handler:`skill-install`});return}let I=n0(W1(x).skills[b.name]?.hosts??[],b.scope).filter(e=>!ee.includes(e));I.length>0&&v0(b.name,x,I,a0(b.scope));let ne=W(x,...yo),re=q(ne)?J(ne,`utf-8`):null,ie=re===null?null:gt(re);re!==null&&ie===null&&v.warn({skill:b.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let ae=ie?.skills[b.name]!==void 0,oe=j===void 0?ae?`copy`:`symlink`:j?`symlink`:`copy`,se=f0(E,b.name,x,ee,oe,a0(b.scope));se.length===0?await K1(x,b.name):await G1(x,b.name,{hosts:se,scope:b.scope,scripts:k.hasScripts,installedAt:new Date().toISOString(),projection:oe}),p?.(`files`),$(y,200,Va,{name:b.name,hosts:se,scripts:k.hasScripts,warnings:te,warningCodes:F},{handler:`skill-install`})}catch(e){Q(y,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 nft=[`.ok`,`local`,`plugin-skill-baselines.json`];function rft(e){return W(e,...nft)}function ift(e){try{let t=rft(e);if(!q(t))return{};let n=JSON.parse(J(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 aft(e,t,n){return e===void 0||e.upstream!==n?{modified:!1,next:{local:t,upstream:n}}:{modified:t!==e.local,next:e}}function oft(e){let t=ift(e),n=!1;return{isModified(e,r,i,a){let o=`${e}:${r}`,{modified:s,next:c}=aft(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{SH(W(e,`.ok`,`local`),{recursive:!0}),bH(rft(e),`${JSON.stringify(t,null,2)}\n`)}catch{}}}}}function sft(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=NU.project,y={lastKey:null};return HQ({"/api/skills":ZQ(L,WQ(async(e,b)=>{let x=await B1(r),S=(i?.peekFreshInPlaceSkillDirsFingerprint()??``)+``+(n?eut(n).join(`,`):``)+``+u1(r).map(e=>e.editorId).join(`,`)+``+x.map(e=>e.dir).sort().join(`,`),C=a.readList(S);if(C!==null){$(b,200,gne,C.body,{handler:`skills-list`});return}let w=o(`project`),T=s(w,`project`),E=s(o(`global`),`global`),D=n?eut(n):[],O=u1(r).map(e=>e.editorId),k=n?M1(n,`project`,Oi,r):!1,A=M1(r,`global`,Oi,r),j=n?W1(n).skills:{},M=W1(r).skills,N=n?gt(q(W(n,...yo))?J(W(n,...yo),`utf-8`):``)??null:null,P=c,ee=(e,t,n)=>e.skills.map(e=>{let r=t[e.name]?.hosts??[],i=n?N?.skills[e.name]:void 0,a=i?P(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}:{}}}),te=n?$1(n):{},F=(e,t,n)=>{let r=[];for(let i of t??[]){let t=K(e,i.path);if(n!==void 0&&t===K(n))continue;let a=!1;try{a=nc(t).isSymbolicLink()}catch{continue}if((a?`link`:`copy`)!==i.mode){if(a&&n!==void 0)try{if(cc(t)===cc(n))continue}catch{}r.push(i.path)}}return{drift:r}},I=n?k1(t,`project`):{},ne=Aut(I,`project`),re=(e,t)=>[...t].some(t=>e===t||e.startsWith(`${t}/`)),ie=Ex(n??t),ae=oft(t),oe=j1(`project`),se=j1(`global`),ce=(e,t)=>(e??[]).filter(e=>![...t].some(t=>e.path===t||e.path.startsWith(`${t}/`))),le=new Set,L=lNe(t),ue=e=>{let t=dNe(L,e);return t?{name:t.name,marketplace:t.marketplace,provider:`claude`,...t.url?{url:t.url}:{}}:null},de=n?R1(t).map(e=>{let r=!le.has(e.name);le.add(e.name);let i=K(t,e.dir),a=r?d(e.name,ie,i)??ue(i):null,o=r&&a===null?N?.skills[e.name]??f(t,e.name,`project`)??p(e.name,ie,i):void 0,s=o?P(o):void 0,c=o?.localHash===void 0?(()=>{if(!o||!r)return!1;let t=m(e.name,ie);return t!==null&&ae.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:K(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(I).length>0?{hostAliases:I}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...a===null?{}:{plugin:a},...(()=>{let t=ce(r?te[e.name]:void 0,ne).filter(e=>!re(e.path,oe));return t.length?{customPlacements:t.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...(()=>{let i=F(n,ce(r?te[e.name]:void 0,ne),K(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},...FU(e.name)?{managed:!0}:{}}}):[],fe=$1(r),pe=b0(W(r,...yo)),me=k1(r,`global`),he=Aut(me,`global`),ge=new Set(x.map(e=>e.name));E.skills=E.skills.filter(e=>!ge.has(e.name));let _e=new Set,ve=x.map(e=>{let t=!_e.has(e.name);_e.add(e.name);let n=t?fe[e.name]:void 0,i=V1(r,e.name),a=i!==null&&K(r,e.dir)!==K(i)?e.hosts[0]:void 0;return{name:e.name,...e.description?{description:e.description}:{},scope:`global`,path:`${e.dir}/SKILL.md`,absolutePath:K(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(me).length>0?{hostAliases:me}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let t=F(r,ce(n,he),K(r,e.dir));return t.drift.length>0?{driftPaths:t.drift}:{}})(),...(()=>{let e=ce(n,he).filter(e=>!re(e.path,se));return e.length?{customPlacements:e.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...u(`global`,e.name,e)===`link`?{linkMode:!0}:{},...FU(e.name)?{managed:!0}:{},...(()=>{if(!t)return{};let n=K(r,e.dir),i=d(e.name,ie,n);if(i!==null)return{plugin:i};let a=pe.skills[e.name]??f(r,e.name,`global`)??p(e.name,ie,n);if(!a)return{};let o=a.localHash===void 0?(()=>{let t=m(e.name,ie);return t!==null&&ae.isModified(`global`,e.name,e.contentHash,t)})():e.contentHash!==a.localHash;return{origin:P(a),...o?{modified:!0}:{}}})()}}),ye=new Set(de.map(e=>e.name)),be=n&&!T.skills.some(e=>e.name===v)&&!ye.has(v)?h(n,v,`project`):null,xe=new Set(ve.map(e=>e.name)),Se=RU.map(e=>NU[e]).filter(e=>!E.skills.some(t=>t.name===e)&&!xe.has(e)).map(e=>h(r,e,`global`)).filter(e=>e!==null),Ce=new Set(de.map(e=>e.name)),we=[...ee(T,j,!0).filter(e=>!Ce.has(e.name)),...de,...ee(E,M,!1),...ve,...be?[be]:[],...Se];ae.flush();let Te={skills:we.map(e=>{let n=e.scope===`project`&&e.absolutePath?g(e.absolutePath,t):null,r=e.absolutePath?Edt(U(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`&&!Gs(s)&&i?.isPathIgnored(s)===!0?{...o,ignored:!0}:o}),truncated:T.truncated||E.truncated},Ee=await _(de.map(e=>e.path),i??null,y)?{...Te,skills:Te.skills.map(e=>{if(e.scope!==`project`)return e;let t=e.canonicalPath??e.path,n=!Gs(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})}:Te;a.writeList(S,Ee),$(b,200,gne,Ee,{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0})})}function cft(e,t){let n=e===`.`?``:e.replace(/^\.\//,``);return n?`${n}/${t}`:t}function lft(e){return/not a valid object name|not a tree object|bad revision|unknown revision|invalid object name/i.test(e)}async function uft(e){let{shadow:t,contentDir:n,contentRoot:r,name:i,version:a}=e,o=e.skillDirRel??`.ok/skills/${i}`;if(!q(t.workTree)||!q(t.gitDir))return{ok:!1,code:`no-shadow`,error:`No shadow repo — nothing to restore from.`};let s=yJ(t),c=[...new Set([o,`.ok/skills/${i}`])],l=[],u=cft(r,o);try{for(let e of c){let t=cft(r,e),n=await zq(s,[`ls-tree`,`-r`,`--name-only`,a,...on([t])]);if(n.length>0){l=n,u=t;break}}}catch(e){let t=e instanceof Error?e.message:String(e);return lft(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=K(n,o),f=d+Js,p=[];for(let e of l){let t=e.slice(u.length).replace(/^\//,``),n=K(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}`}}}AH(d,{recursive:!0,force:!0});let m=[];for(let{rel:e,destAbs:t,content:n}of p)SH(U(t),{recursive:!0}),bH(t,n,`utf-8`),m.push(e);return{ok:!0,restoredFiles:m}}function dft(e){try{let t=J(W(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 fft(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];Q(e,r,i,t.error,{handler:n,detail:t.code})}function E(e,t){if(t.ok){$(e,200,Gte,t.body,{handler:`skill-reimport`});return}Q(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`?R1(c):z1(d)).find(e=>e.name===t);return i?K(r,i.dir):K(n,t)}function O(e,r,i,a){let o=a.skills[r];if(o)return o;let s=D(e,r,i);return xre(r,uO(s)?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:dft(s)})??n(e===`global`?d:c,r,e)??t(r,Ex(u??c),s)}return HQ({"/api/skill/restore":ZQ(Ree,async(e,t,n)=>{try{let e=DQ(n,i);if(e.kind===`invalid-summary`){Q(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`){Q(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){Q(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 uft({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(K(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(),$(t,200,rie,{name:n.name,version:n.version,restoredFiles:u.restoredFiles,warnings:d},{handler:`skill-restore`})}catch(e){Q(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":ZQ(ene,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!u){Q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=DQ(n,i);if(e.kind===`invalid-summary`){Q(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||!q(K(o,l,`SKILL.md`))){Q(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let p=W(n.scope===`global`?d:u,...yo),m=O(n.scope,n.name,s,b0(p));if(!m){Q(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 x0(p,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??m,autoUpdate:n.setAutoUpdate}}})),_(),v?.refreshInPlaceSkillDirs(),y(),$(t,200,Gte,{name:n.name,updated:!1,source:m.source,warnings:[],warningCodes:[]},{handler:`skill-reimport`});return}let h,g=null,S;try{let e=m.skill??n.name,i=Ni[e],a=await _O(m.source,e).catch(async e=>{if(i===void 0)throw e;return _O(m.source,i)}),o=a?.source??VO(m.source,m.pluginProvider),s=a?.skill??m.skill,c=a?.spec??WD(o);if(!c){Q(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(T0(t,c,`skill-reimport`))return;let l=await $dt(c,[{name:n.name,entry:m,...s===void 0?{}:{recordedSkill:s}}]);r=l.cleanup,h=l.ref;let u=l.picks.get(n.name);if(!u){Q(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:l.dirs.map(e=>e.name).join(`, `)});return}g=u.dir,S=u.folder}catch(e){if(e instanceof AD){Q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!g){Q(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let C=await x.runSkillReimport({acquiredDir:g,name:n.name,scope:n.scope,entry:m,lockPath:p,ref:h,...S?{folder:S}:{},actor:e,...n.dryRun===void 0?{}:{dryRun:n.dryRun}});_(),v?.refreshInPlaceSkillDirs(),y(),E(t,C)}catch(e){Q(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":ZQ(Mn,async(e,t,n)=>{try{if(n.scope===`project`&&!u){Q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-reimport-bulk`,detail:`NO_PROJECT_ROOT`});return}let a=DQ(n,i);if(a.kind===`invalid-summary`){Q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-reimport-bulk`});return}let o=W(n.scope===`global`?d:u,...yo),s=b0(o),c=[],{bySource:l,unrecorded:f}=Jdt([...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;try{let e=t.names[0],a=await _O(t.source,e).catch(async n=>{let r=Ni[e];if(r===void 0)throw n;return _O(t.source,r)}),o=a?.source??VO(t.source,s.skills[t.names[0]]?.pluginProvider),l=a?.spec??WD(o);if(!l||Idt(l)){for(let e of t.names)c.push({requested:e,status:`failed`,source:t.source,warnings:[],warningCodes:[],error:`INVALID_SOURCE`});continue}i=await $dt(l,t.names.flatMap(e=>{let t=O(n.scope,e,b(n.scope,e).root,s);return t?[{name:e,entry:t,...t.skill===void 0?{}:{recordedSkill:t.skill}}]:[]})),r=i.cleanup}catch(n){Y(`skills-reimport-bulk`).warn({source:t.source,err:n,requestId:HK(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 l=i.picks.get(r);if(!l){c.push({requested:r,status:`not-found`,source:t.source,warnings:[],warningCodes:[]});continue}try{let s=await x.runSkillReimport({acquiredDir:l.dir,name:r,scope:n.scope,entry:t,lockPath:o,ref:i.ref,...l.folder?{folder:l.folder}:{},actor:a});if(!s.ok){Y(`skills-reimport-bulk`).warn({skill:r,err:s.cause,detail:s.detail,requestId:HK(e)},`bulk update: one skill failed (rest continue)`),c.push({requested:r,status:`failed`,source:t.source,warnings:[],warningCodes:[],error:s.detail?`${s.title} (${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){Y(`skills-reimport-bulk`).warn({skill:r,err:n,requestId:HK(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()}}$(t,200,Hn,{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){Y(`skills-reimport-bulk`).warn({err:e},`bulk update: ignore-pattern rebuild failed after a reported success`)}}catch(e){Q(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":ZQ(wie,async(e,t,n)=>{try{if(!u){Q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=DQ(n,i);if(e.kind===`invalid-summary`){Q(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`){Q(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=W(u,...yo),d=b0(r).skills[n.name];if(!d?.baselineRef){Q(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(!_){Q(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 uft({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=K(c,f(n.name),`..`),b=S(y,n.name);await x0(r,e=>Jt(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`),$(t,200,rte,{name:n.name,baselineRef:d.baselineRef,restoredFiles:v.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){Q(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 pft(e){let{contentDir:t,projectDir:n,contentFilter:r,validateSkillName:i,indexedSkillContentPath:a,bumpSkillsCatalogGen:o,signalChannel:s}=e;function c(e){return`!/${U(e).split(Js).join(`/`)}/`}return HQ({"/api/skill/track-in-git":ZQ(ti,WQ(async(e,l,u)=>{if(!i(u.name,l,`skill-track-in-git`))return;if(u.scope!==`project`){Q(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){Q(l,400,`urn:ok:error:invalid-request`,`No project directory.`,{handler:`skill-track-in-git`});return}let d=R1(t).find(e=>e.name===u.name)?.dir??`.ok/skills/${u.name}`,f=a(K(t,d,`SKILL.md`),t)??`${d}/SKILL.md`,p=U(f),m=f,h=c(p),g=`.gitignore`,_=K(t,g);if(r&&!r.isPathIgnored(m)){$(l,200,Ze,{line:h,gitignorePath:g,applied:!1,alreadyTracked:!0},{handler:`skill-track-in-git`});return}if(u.apply!==!0){$(l,200,Ze,{line:h,gitignorePath:g,applied:!1},{handler:`skill-track-in-git`});return}let v=q(_)?J(_,`utf-8`):null;if((v??``).split(`
1179
1179
  `).some(e=>e.trim()===h)){Q(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(`
1180
1180
  `)||v===``?v??``:`${v}\n`}${h}\n`;if(mc(_,y,`utf-8`),o(),await r?.rebuildIgnorePatterns(),r?.isPathIgnored(m)){v===null?uc(_,{force:!0}):mc(_,v,`utf-8`),o(),await r.rebuildIgnorePatterns(),Q(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`),$(l,200,Ze,{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 mft=[`INDEX`,`README`,`REPORT`,`SPEC`];function hft(e,t){let n=[],r=new Set,i=t=>{!t||r.has(t)||t!==e&&(r.add(t),n.push(t))},a=_ft(t),o=vft(e);for(;;){for(let e of mft)if(i(k0(t,a,A0(o,e))),n.length>=3)return n;let e=o===``?null:yft(o);if(e&&(i(k0(t,a,A0(o,e))),n.length>=3))return n;if(o===``)break;o=vft(o)}return n}function gft(e,t){let n=[],r=_ft(t),i=yft(e);for(let a of[...mft,i]){let i=k0(t,r,A0(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 k0(e,t,n){return e.has(n)?n:t.get(n.toLowerCase())??null}function _ft(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 vft(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function yft(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function A0(e,t){return e===``?t:`${e}/${t}`}var j0=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 Mc(`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 bft(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 M0(e,t){let n=K(t),r=K(n,e??``);if(!P0(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=P0(r);if(i!==void 0){let e=i.isSymbolicLink()?P0(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&&jG(r,n)&&!wr.some(e=>r.toLowerCase().endsWith(e)))for(let e of wr){let t=`${r}${e}`;if(P0(t,!0)?.isFile())return{ok:!0,scope:{kind:`file`,path:t}}}return{ok:!1,path:r,title:bft(e??`.`)}}function N0(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 P0(e,t=!1){try{return t?fc(e):nc(e)}catch(e){if(N0(e))return;throw e}}function F0(e,t){let n=G(t,e);return n===``||!n.startsWith(`..`)&&!Gs(n)}function I0(e,t){let n=Ms(e);try{bH(n,t,`utf-8`),CH(n,e)}catch(e){try{EH(n)}catch{}throw e}}function xft(e){let t=W(e,`.ok`,`schemas`),n;try{n=sc(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`&&Y(`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 L0(e){return e instanceof Error?e.message:String(e)}function Sft(e,t){let n=[];for(let r of e)if(r.enabled!==!1)for(let e of ue(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 Cft(e,t){let n=K(e,t);if(!F0(n,K(e)))return{problem:`frontmatter schema ${t}: resolves outside the project`};let r;try{r=cc(n)}catch(e){return{problem:`frontmatter schema ${t}: cannot read (${L0(e)})`}}let i;try{i=cc(e)}catch(e){return{problem:`frontmatter schema ${t}: cannot read (${L0(e)})`}}if(!F0(r,i))return{problem:`frontmatter schema ${t}: resolves outside the project`};let a;try{a=J(r,`utf-8`)}catch(e){return{problem:`frontmatter schema ${t}: cannot read (${L0(e)})`}}let o;try{o=JSON.parse(a)}catch(e){return{problem:`frontmatter schema ${t}: malformed JSON (${L0(e)})`}}if(typeof o!=`object`||!o||Array.isArray(o))return{problem:`frontmatter schema ${t}: not a JSON object`};let s=o;if(!Mie(s)){let e=JSON.stringify(Mre[fre]);return{problem:`frontmatter schema ${t}: unsupported dialect ${JSON.stringify(s.$schema)} (supported: ${ote.join(`, `)}; e.g. ${e})`}}let c=Fn(s);return c===null?{schema:s,key:r}:{problem:`frontmatter schema ${t}: does not compile (${c})`}}function wft(e,t){let n=[],r=new Map,i=new Set,a=[];for(let o of t){let t=o.enabled===!1,s=ii(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=Cft(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 Tft=[`.markdownlint.jsonc`,`.markdownlint.json`,`.markdownlint.yaml`,`.markdownlint.yml`,`.markdownlint.cjs`,`.markdownlint.mjs`,`.markdownlintrc`];function R0(e){for(let t of Tft){let n=W(e,t);if(q(n))return{name:t,path:n}}return null}function Eft(e){let t=R0(e);return t?kft(t.path,t.name,e):null}function Dft(e,t){let n=K(t),r=K(e);for(F0(r,n)||(r=n);;){let e=R0(r);if(e)return kft(e.path,G(n,e.path)||e.name,n);if(r===n)return null;let t=U(r);if(t===r)return null;r=t}}function Oft(e){let t=R0(e);if(!t||/\.(cjs|mjs|js)$/.test(t.path))return null;let n=J(t.path,`utf-8`),r=Aft(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 kft(e,t,n){let r=[],i=new Set,a=(e,t)=>{if(!F0(K(e),K(n)))return r.push(`refusing extends target outside the project: ${G(n,e)||e}`),null;let o;try{o=cc(e)}catch(t){return r.push(`cannot read ${G(n,e)||e}: ${z0(t)}`),null}if(!F0(o,cc(n)))return r.push(`refusing extends target outside the project: ${G(n,e)||e}`),null;if(i.has(o))return r.push(`extends cycle at ${G(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: ${G(n,e)||e} — use a JSON/JSONC/YAML config`),null;let s;try{s=J(o,`utf-8`)}catch(t){return r.push(`cannot read ${G(n,e)||e}: ${z0(t)}`),null}let c=Aft(s,e);if(`error`in c)return r.push(`malformed markdownlint config: ${G(n,e)||e} (${c.error})`),null;if(!c.value||typeof c.value!=`object`||Array.isArray(c.value))return r.push(`malformed markdownlint config: ${G(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 ${G(n,e)||e}`),d;if(!l.startsWith(`.`)&&!Gs(l))return r.push(`package extends is not supported (${JSON.stringify(l)} in ${G(n,e)||e}) — use a relative file path`),d;let f=K(U(e),l),p=a(f,t+1);return p?{...p,...d}:d};return{rules:a(e,0),file:t,problems:r}}function z0(e){return(e instanceof Error?e.message:String(e)).split(`
@@ -2181,7 +2181,7 @@ tags: [lore, history]
2181
2181
  }
2182
2182
  }
2183
2183
  }`,variables:{owner:e.owner,name:e.repo,number:e.number}})},n,r);if(a.status!==200)return f8(a)?(i(a),p8):`fallback`;let o=Dwt(a.body);if((o||a.headers.get(`x-ratelimit-remaining`)===`0`)&&i(a),o)return`fallback`;let s=m8(m8(a.body)?.data);if(s===null)return`fallback`;let c=m8(s.repository);if(c===null||c.issueOrPullRequest===null)return Awt;let l=Fwt(e,c.issueOrPullRequest);return l===null?`fallback`:{ok:!0,preview:l}}async function Rwt(e,t,n,r,i){let a={headers:Nwt(t,`application/vnd.github+json`)},o=jwt(e),s=e=>e.status===404||e.status===410?Awt:(f8(e)&&i(e),p8),c=async()=>{let t=await _8(`${o}/pulls/${e.number}`,a,n,r);if(t.status!==200)return s(t);let i=Iwt(e,null,t.body);return i===null?p8:{ok:!0,preview:i}};if(e.kind===`pull`)return c();let l=await _8(`${o}/issues/${e.number}`,a,n,r);if(l.status!==200)return s(l);if(m8(m8(l.body)?.pull_request)!==null)return c();let u=Iwt(e,l.body,null);return u===null?p8:{ok:!0,preview:u}}async function zwt(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=Twt(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;Swt.info({host:t.host,signedIn:n!==null,api:u,until:new Date(l).toISOString()},Owt[u])};try{if(n!==null&&!l(s)){let e=await Lwt(t,n,i,a,e=>u(`graphql`,e));if(e!==`fallback`)return e}return l(c)?p8:await Rwt(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 Swt.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`),p8}}function Bwt(e){if(!e.ok)return e.reason===`not-found`?3e5:6e4;let t=e.preview.lifecycle;return t===`open`||t===`draft`?6e4:18e5}var Vwt=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()+Bwt(t)});this.entries.size>256;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e)}}};const Hwt=/^\/([A-Za-z0-9][A-Za-z0-9-]{0,38})\/([A-Za-z0-9._-]{1,100})\/(pull|issues)\/(\d{1,10})(?:\/[^?#]*)?$/;function Uwt(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=m(n.hostname);if(!O(r,t))return null;let i=Hwt.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 Wwt(e){return`${e.host}/${e.owner}/${e.repo}#${e.number}`.toLowerCase()}function Gwt(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&&C6(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 Kwt=Y(`github-reference`);function qwt(e){return OQ(e.socket?.remoteAddress)&&!AQ(e)}function Jwt(e,t){let n=Gwt(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 Kwt.warn({err:t,host:e},`[github-reference] token store lookup failed; reading anonymously`),null}}}const Ywt={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `,copy:`©`,reg:`®`,trade:`™`,mdash:`—`,ndash:`–`,hellip:`…`,lsquo:`‘`,rsquo:`’`,ldquo:`“`,rdquo:`”`};function Xwt(e){return!Number.isInteger(e)||e<0||e>1114111||e>=55296&&e<=57343?null:String.fromCodePoint(e)}function Zwt(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 Xwt(Number.parseInt(t.slice(n?2:1),n?16:10))??e}return Ywt[t.toLowerCase()]??e})}function Qwt(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 $wt(e){return e<=31||e>=127&&e<=159}function eTt(e){let t=``;for(let n of e){let e=n.codePointAt(0)??0;Qwt(e)||(t+=$wt(e)?` `:n)}return t}function tTt(e,t){let n=Array.from(e);return n.length<=t?e:`${n.slice(0,t-1).join(``).trimEnd()}…`}function y8(e,t){return tTt(eTt(Zwt(e)).replace(/\s+/g,` `).trim(),t)}function nTt(e){return e.trim().toLowerCase().split(/\s+/)}function rTt(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 iTt=new Set([`script`,`style`,`template`,`textarea`,`iframe`,`xmp`,`noembed`,`noframes`,`plaintext`]);function aTt(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 x8(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 oTt(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 sTt(e){let t=``,n=new Map,r,i=-1;try{let a=rTt(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}=aTt(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}=aTt(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=x8(e,a,d,null),r=oTt(a,`title`,n);if(r===null){t+=e.slice(n);break}t+=e.slice(n,r.textEnd),s=r.end;continue}if(iTt.has(u)){let t=oTt(a,u,x8(e,a,d,null));if(t===null)break;s=t.end;continue}if(u===`meta`){let t=new Map;s=x8(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=x8(e,a,d,t),r===void 0){let e=t.get(`href`),n=t.get(`rel`);e&&n&&nTt(n).includes(`icon`)&&(r=e)}continue}s=x8(e,a,d,null)}}catch{}return{rawTitle:t,metaContent:n,faviconHref:r,headEndOffset:i}}function cTt(e){let{rawTitle:t,metaContent:n,faviconHref:r}=sTt(e),i=y8(n.get(`og:title`)??t,200),a=y8(n.get(`og:description`)??n.get(`description`)??``,500),o=y8(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 lTt(e){return sTt(e).headEndOffset}function uTt(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}const dTt=Y(`link-preview.guarded-fetch`),fTt=async e=>(await hoe(e,{all:!0,family:0})).map(e=>({address:e.address,family:e.family===6?6:4}));function pTt(e,t){let n=e.port?`:${e.port}`:``;return`${e.protocol}//${t}${n}${e.pathname}${e.search}`}async function mTt(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=Use(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:pTt(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:pTt(r,r.hostname),pinnedAddress:{address:o.address,family:o.family===6||o.address.includes(`:`)?6:4},serverName:r.hostname,logicalUrl:r.toString()}}}function hTt(e){return(t,n,r)=>{n.all?r(null,[{address:e.address,family:e.family}]):r(null,e.address,e.family)}}function gTt(e){return e===301||e===302||e===303||e===307||e===308}function _Tt(e){return e?(e.split(`;`,1)[0]??``).trim().toLowerCase():``}function S8(e,t){return t.aborted||e instanceof Error&&(e.name===`TimeoutError`||e.name===`AbortError`)?`timeout`:`fetch-error`}function C8(e){try{e.destroy()}catch{}}function vTt(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=hTt(e.pinnedAddress)),a&&e.serverName&&(o.servername=e.serverName);try{let n=(a?goe:loe)(e.requestUrl,o,e=>{e.on(`error`,()=>{}),i({ok:!0,response:e})});n.on(`error`,e=>i({ok:!1,reason:S8(e,t)})),n.end()}catch(e){i({ok:!1,reason:S8(e,t)})}})}function yTt(e){return e===``||e===`identity`?`identity`:e===`gzip`||e===`x-gzip`?ioe():e===`deflate`?aoe():e===`br`?roe():null}function bTt(){let e=``;return t=>{let n=e.length;e+=Buffer.from(t).toString(`latin1`);let r=lTt(e);return r===-1?-1:r-n}}function xTt(e,t,n,r){let i=yTt((e.headers[`content-encoding`]??``).trim().toLowerCase());if(i===null)return C8(e),Promise.resolve({ok:!1,reason:`fetch-error`});let a=i===`identity`?e:e.pipe(i);return new Promise(i=>{let o=[],s=r?bTt():null,c=0,l=!1,u=()=>{n.removeEventListener(`abort`,f),C8(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:S8(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:S8(e,n)}))})}function w8(e){return dTt.debug({reason:e},`link-preview guarded fetch rejected`),{ok:!1,reason:e}}async function STt(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??fTt,s=t.isAddressAllowed??Hse,c=AbortSignal.timeout(i),l=e,u=0;for(;;){let e=await mTt(l,o,s);if(!e.ok)return w8(e.reason);let{target:t}=e,i=await vTt(t,c);if(!i.ok)return w8(i.reason);let d=i.response;if(gTt(d.statusCode??0)){let e=d.headers.location;if(C8(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=_Tt(d.headers[`content-type`]);if(!n(f))return C8(d),w8(`non-html`);let p=await xTt(d,r,c,f===`text/html`);return p.ok?{ok:!0,body:p.body,contentType:f,finalUrl:t.logicalUrl}:w8(p.reason)}}function CTt(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 wTt(e){return e.startsWith(`image/`)}function TTt(e,t){try{return new URL(e??`/favicon.ico`,t).toString()}catch{return null}}async function ETt(e,t){let n=await t(e,{allowContentType:wTt,maxBytes:102400,timeoutMs:2500});if(!n.ok)return;let r=CTt(n.body);if(r)return`data:${r};base64,${Buffer.from(n.body).toString(`base64`)}`}async function DTt(e){let t=cTt(e.html),n=TTt(t.faviconHref,e.finalUrl),r=n?await ETt(n,e.fetch??STt):void 0;return{domain:uTt(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 T8=Y(`link-preview.cache`);function OTt(e){try{let t=new URL(e);return t.hash=``,t.username=``,t.password=``,t.toString()}catch{return null}}function E8(e){return Mc(`sha256`).update(e,`utf-8`).digest(`hex`)}var kTt=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?W(e.cacheDir,`meta`):null,this.manifestPath=e.cacheDir?W(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{q(this.manifestPath)&&(e=JSON.parse(await wc(this.manifestPath,`utf-8`)))}catch(e){T8.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=OTt(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 yH(this.metaDir,{recursive:!0});let e=new Set;for(let[t,n]of this.entries){if(n.status!==`ok`||(e.add(E8(t)),this.persistedKeys.has(t)))continue;let r=this.payloads.get(t);r&&(await hH(W(this.metaDir,`${E8(t)}.json`),JSON.stringify(r)),this.persistedKeys.add(t))}let t={schemaVersion:1,entries:Object.fromEntries(this.entries)},n=`${this.manifestPath}.tmp`;await hH(n,JSON.stringify(t)),await vH(n,this.manifestPath);for(let t of sc(this.metaDir)){if(!t.endsWith(`.json`))continue;let n=t.slice(0,-5);e.has(n)||EH(W(this.metaDir,t))}this.dirty=!1}catch(e){T8.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{AH(this.cacheDir,{recursive:!0,force:!0})}catch(e){T8.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=W(this.metaDir,`${E8(e)}.json`);try{if(!q(t))return null;let e=bt.safeParse(JSON.parse(await wc(t,`utf-8`)));return e.success?e.data:null}catch(e){return T8.warn({err:e},`[link-preview] unreadable cache blob — treating as miss`),null}}};function ATt(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 jTt(e){return ATt(e.origin)?jst(e.contentType)?{ok:!0}:{ok:!1,reason:`content-type`}:{ok:!1,reason:`origin`}}let MTt=null,NTt=null,PTt=null,FTt=null,ITt=null,LTt=null;function RTt(){return MTt||=aH().createCounter(`ok.saved_themes.save_total`,{description:`Successful saved-theme file saves. Attribute-free to keep cardinality bounded.`}),MTt}function zTt(){return NTt||=aH().createCounter(`ok.saved_themes.delete_total`,{description:`Successful saved-theme file deletions. Attribute-free to keep cardinality bounded.`}),NTt}function BTt(){return ITt||=aH().createCounter(`ok.saved_themes.parse_failure_total`,{description:`Saved-theme scheme parse failures. Attribute-free to keep cardinality bounded.`}),ITt}function VTt(){return PTt||=aH().createCounter(`ok.saved_themes.scan_total`,{description:`Saved-theme store scans. Attribute-free to keep cardinality bounded.`}),PTt}function HTt(){return FTt||=aH().createCounter(`ok.saved_themes.parse_total`,{description:`Saved-theme scheme parse attempts. Attribute-free to keep cardinality bounded.`}),FTt}function UTt(){return LTt||=aH().createHistogram(`ok.saved_themes.usable_count`,{description:`Usable saved themes returned by a completed bounded scan. Attribute-free to keep cardinality bounded.`}),LTt}function WTt(){RTt().add(1)}function GTt(){zTt().add(1)}function KTt(){VTt().add(1)}function qTt(){HTt().add(1)}function JTt(){BTt().add(1)}function YTt(e){UTt().record(e)}const D8=Y(`saved-themes`),O8=[`.yaml`,`.yml`];function k8(e){return K(Ls(e??_c()),x)}function XTt(e={}){KTt();let t=e.root??k8(e.homedirOverride),n=e.cap??500,r=[],i=!1;try{let n=Dae(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 qW(e)===`ENOENT`?YTt(0):D8.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(ZTt).map(e=>e.name).sort(),o=new Map;for(let e of a){let t=QTt(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&&D8.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=Nn(e);l.push({ok:!1,filename:n,...t.ok?{id:t.id}:{},code:`duplicate-identity`,conflictingFilenames:r});continue}let i=$Tt(t,n);i&&l.push(i)}return YTt(l.filter(e=>e.ok).length),{entries:l,truncated:c}}function ZTt(e){if(e.name.startsWith(`.`))return!1;let t=e.name.toLowerCase();return O8.some(e=>t.endsWith(e))}function QTt(e){let t=e.toLowerCase(),n=O8.find(e=>t.endsWith(e));return n?e.slice(0,-n.length):bae(e).name}function $Tt(e,t){let n=Nn(bae(t).name);if(!n.ok)return{ok:!1,filename:t,code:n.code};if(!O8.some(e=>t.endsWith(e)))return{ok:!1,filename:t,id:n.id,code:`unsupported-extension-case`};let r=W(e,t);try{let e=nc(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 qW(r)===`ENOENT`?null:(D8.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=ac(r,$s.O_RDONLY|$s.O_NOFOLLOW)}catch(r){let i=qW(r);return i===`ENOENT`?null:i===`ELOOP`?{ok:!1,filename:t,id:n.id,code:`symlink`}:(D8.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=tc(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=oc(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 D8.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{Qs(i)}catch{}}qTt();let o=Bt(a);return o.ok?{ok:!0,id:n.id,filename:t,scheme:o.scheme}:(JTt(),{ok:!1,filename:t,id:n.id,code:o.error.kind})}async function A8(e,t,n,r){let i=K(Ls(t));await yH(i,{recursive:!0});let a=Mc(`sha256`).update(K(e)).digest(`hex`).slice(0,24);try{return await vl(W(i,`saved-themes-${a}.lock`),n,{timeoutMs:r})}catch(e){if(e instanceof _l)return{ok:!1,code:`lock-timeout`};throw e}}function eEt(e){try{return nc(e).isFile()?`regular`:`unsafe`}catch(e){if(e.code===`ENOENT`)return`missing`;throw e}}function j8(e,t){let n=[],r;try{r=Dae(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=O8.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 tEt(e){let t=e.stem===void 0?Un(e.name):(()=>{let t=Nn(e.stem);return t.ok?{...t,stem:e.stem}:t})();if(!t.ok)return{ok:!1,code:t.code};let n=e.homedirOverride??_c(),r=e.root??k8(n);return A8(r,n,async()=>{let n=j8(r,t.stem);if(!n.complete||n.filenames.length>0)return{ok:!1,code:`name-taken`};let i=`${t.stem}${e.extension??`.yaml`}`;return eEt(W(r,i))===`missing`?(await yH(r,{recursive:!0}),await Fs(W(r,i),lt(e.scheme),{fs:MH,sweepStaleTmps:!1}),WTt(),{ok:!0,id:t.id,filename:i}):{ok:!1,code:`name-taken`}},e.lockTimeoutMs)}async function nEt(e){let t=fr(e.id);if(!t.ok)return{ok:!1,code:`invalid-id`};let n=e.homedirOverride??_c(),r=e.root??k8(n);return A8(r,n,async()=>{let n=j8(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?!O8.some(e=>a.endsWith(e))||eEt(W(r,a))!==`regular`?{ok:!1,code:`unsafe-target`}:(await Fs(W(r,a),lt(e.scheme),{fs:MH,sweepStaleTmps:!1}),{ok:!0,id:e.id,filename:a}):{ok:!1,code:`not-found`}},e.lockTimeoutMs)}async function rEt(e){let t=fr(e.id);if(!t.ok)return{ok:!1,code:`invalid-id`};let n=e.homedirOverride??_c(),r=e.root??k8(n);return A8(r,n,async()=>{let e=j8(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=$Tt(r,i);return a===null?{ok:!0,existed:!1}:a.ok?(EH(W(r,i)),GTt(),{ok:!0,existed:!0,filename:i,scheme:a.scheme}):{ok:!1,code:`unusable-theme`}},e.lockTimeoutMs)}const iEt=new Set([`.DS_Store`,`.localized`,`Thumbs.db`,`.gitignore`,`.gitkeep`,`.gitattributes`]);function aEt(e){let t=[],n=[],r=[];for(let i of sc(e,{withFileTypes:!0})){if(iEt.has(i.name))continue;if(i.name.startsWith(`.`)){r.push(i.name);continue}let a=W(e,i.name);if(q(W(a,`SKILL.md`))){t.push(i.name);continue}if(i.isSymbolicLink()&&!q(a)){r.push(i.name);continue}i.isDirectory()&&oEt(a)||n.push(i.name)}return{bundles:t,strays:n,ignored:r}}function oEt(e){try{return sc(e).length===0}catch{return!1}}function sEt(e){let{base:t,folderRel:n,targetRootRel:r,mayCreate:i}=e,a=W(t,n),o=W(t,r),s=[r,n].filter(e=>!q(W(t,e))&&!i(e));if(s.length>0)return{kind:`not-permitted`,roots:s};let c;try{c=nc(a)}catch{return{kind:`absent`}}if(c.isSymbolicLink()||!c.isDirectory())return{kind:`not-linkable`};try{if(cc(a)===cc(o))return{kind:`not-linkable`}}catch{}let{bundles:l,strays:u,ignored:d}=aEt(a);if(u.length>0)return{kind:`stray-entries`,strays:u};let f=[],p=[],m=[],h=[],g=[],_=[];for(let e of l){let t=W(a,e),n=W(o,e);if(nc(t).isSymbolicLink()){let r=cc(t),i=null,a=!1;try{a=nc(n).isSymbolicLink(),i=cc(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=nc(n).isSymbolicLink()}catch{}if(r){h.push(e),q(n)&&g.push(e),p.push(e);continue}if(!q(n)){p.push(e);continue}let i=uO(t)?.contentHash,s=uO(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 cEt(e){let{base:t,folderRel:n,targetRootRel:r,mayCreate:i}=e,a=W(t,n),o=W(t,r),s=sEt({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 SH(U(a),{recursive:!0}),SH(o,{recursive:!0}),kH(G(U(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{SH(o,{recursive:!0});let e=cc(o);for(let e of u)AH(W(o,e),{force:!0});for(let{name:t,target:n}of d){let r=W(o,t);kH(G(e,n),r,`dir`),AH(W(a,t),{force:!0}),f.push(t)}for(let e of c)CH(W(a,e),W(o,e)),f.push(e);for(let e of l)AH(W(a,e),{recursive:!0,force:!0});AH(a,{recursive:!0,force:!0}),kH(G(U(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 lEt(e){let{base:t,folderRel:n}=e,r=new Set(e.exclude??[]),i=W(t,n),a;try{a=nc(i)}catch{return{ok:!1,reason:`not-linked`}}if(!a.isSymbolicLink())return{ok:!1,reason:`not-linked`};let o;try{o=cc(i)}catch{return AH(i,{force:!0}),SH(i,{recursive:!0}),{ok:!0,moved:[],dropped:[],linked:[]}}let{bundles:s}=aEt(o);AH(i,{force:!0}),SH(i,{recursive:!0});let c=cc(i),l=[];for(let e of s)r.has(e)||(kH(G(c,W(o,e)),W(i,e),`dir`),l.push(e));return{ok:!0,moved:[],dropped:[],linked:l}}const uEt=H({enabled:uo(),active:uo(),git:H({state:Ri([`not-applicable`,`ready`,`missing`,`conflict`,`unavailable`]),ownership:Ri([`open-knowledge`,`existing`]).optional()}),applied:uo().optional(),reason:Ri([`git-conflict`,`git-unavailable`,`config-write`]).optional()}),dEt=H({enabled:uo()}).strict();function fEt(e){return(t,n)=>{let r=jTt({origin:t.headers.origin,contentType:t.headers[`content-type`]});return r.ok?!0:(r.reason===`origin`?Q(n,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:e}):qQ(n,e),!1)}}function pEt(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,_=ZQ(L,async(e,t)=>{try{let{entries:e,truncated:n}=XTt({homedirOverride:i});$(t,200,Tn,{themes:e,truncated:n},{handler:`saved-themes-list`})}catch(e){Q(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=ZQ(Kn,async(e,t,n)=>{try{let e=await tEt({name:n.name,stem:n.stem,scheme:n.scheme,extension:n.extension,homedirOverride:i,lockTimeoutMs:a});if(!e.ok){if(e.code===`lock-timeout`){Q(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`){Q(t,409,`urn:ok:error:theme-name-taken`,`A saved theme with that name already exists.`,{handler:`saved-theme-save`,detail:n.name});return}Q(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}$(t,201,hr,{id:e.id,filename:e.filename},{handler:`saved-theme-save`})}catch(e){Q(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=ZQ(L,async(e,t)=>{try{let n=KW(e).get(`id`)??``;if(n===``){Q(t,400,`urn:ok:error:invalid-request`,`Missing theme id.`,{handler:`saved-theme-delete`});return}let r=await rEt({id:n,homedirOverride:i,lockTimeoutMs:a});if(!r.ok){if(r.code===`lock-timeout`){Q(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-delete`,detail:r.code,extraHeaders:{"Retry-After":`5`}});return}Q(t,r.code===`invalid-id`?400:409,`urn:ok:error:invalid-request`,`Cannot delete saved theme.`,{handler:`saved-theme-delete`,detail:r.code});return}$(t,200,In,r.existed?{existed:!0,filename:r.filename,scheme:r.scheme}:{existed:!1},{handler:`saved-theme-delete`})}catch(e){Q(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=S0({POST:v,PUT:ZQ(ft,async(e,t,n)=>{try{let e=await nEt({id:n.id,scheme:n.scheme,homedirOverride:i,lockTimeoutMs:a});if(!e.ok){if(e.code===`lock-timeout`){Q(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`){Q(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`){Q(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}Q(t,400,`urn:ok:error:invalid-request`,`Not a saved theme id.`,{handler:`saved-theme-update`,detail:e.code});return}$(t,200,Ut,{id:e.id,filename:e.filename},{handler:`saved-theme-update`})}catch(e){Q(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=S0({GET:ZQ(L,async(e,i)=>{try{let e=i0(n??``),a=(e,t)=>{let n=ldt(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`}};$(i,200,Ur,{targets:e,configured:!1,folders:[...n?MI(t,A1(t,`project`)).filter(e=>M1(t,`project`,e.root,r)).map(e=>({...NI(e),scope:`project`,...a(t,e)})):[],...MI(r,A1(r,`global`)).filter(e=>M1(r,`global`,e.root,r)).map(e=>({...NI(e),scope:`global`,...a(r,e)}))]},{handler:`skill-targets-get`})}catch(e){Q(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:ZQ(ke,async(e,i,a)=>{try{{let e=a.folderAction,o=e.scope===`project`?t:r;if(e.scope===`project`&&!n){Q(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===`..`)){Q(i,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await udt(o,r.join(`/`)),c?.(`files`),$(i,200,ao,{targets:i0(n??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let s=new Set(A1(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)){Q(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=>{Q(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=>M1(o,e.scope,t,r)&&!(t===`.agents/skills`&&!q(W(o,t)));if(e.action===`link`&&e.preview){let t=sEt({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;$(i,200,ao,{targets:i0(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`?cEt({base:o,folderRel:e.root,targetRootRel:l,mayCreate:d}):lEt({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){Q(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 cdt(o,e.root,e.action===`link`?{expect:`link`,target:l}:{expect:`own`}),c?.(`files`),$(i,200,ao,{targets:i0(n??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:f.moved,dropped:f.dropped,linked:f.linked}},{handler:`skill-targets-put`});return}}catch(e){Q(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 T(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function E(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let D=S0({GET:ZQ(L,WQ(async(e,t)=>{let n=KW(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=T(n.get(`semantic`)),u=E(n.get(`source`)),d=r===null?void 0:Number(r);if(i.length>200){Q(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});$(t,200,Ce,f,{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:ZQ(Lr,WQ(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=T(n.semantic),u=E(n.source);if(r.length>200){Q(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});$(t,200,Ce,d,{handler:`search-post`})},{handler:`search-post`,title:`Failed to search workspace.`}),{handler:`search-post`,method:`POST`})},{handler:`search`}),O=`link-preview`,k=new kTt({cacheDir:o?null:K(n??t,`.ok`,`local`,`link-previews`)}),A=null,j=()=>(A??=k.init(),A),M=u??STt;async function N(e){let t=await M(e);return t.ok?{ok:!0,metadata:await DTt({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:M})}:{ok:!1,reason:t.reason}}let P=()=>{try{return d?.()===!0}catch{return!1}},ee=ZQ(fn,async(e,t,n)=>{try{if(!P()){s.debug({outcome:`disabled`},`[link-preview] request outcome`),$(t,200,ja,{ok:!1,reason:`disabled`},{handler:O});return}await j();let e=!1,r=await k.load(n.url,()=>(e=!0,N(n.url)));k.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`),$(t,200,ja,i,{handler:O})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:O,cause:e})}},{handler:O,method:`POST`,preBodyGate:fEt(O)}),te=`github-reference`,F=new Vwt,I=new kwt;return HQ({"/api/search":D,"/api/link-preview":ee,"/api/github-reference":ZQ(Cn,async(e,t,n)=>{try{let r=P()?Uwt(n.url,f):null;if(r===null){let e=P()?`unsupported`:`disabled`;s.debug({outcome:e},`[github-reference] request outcome`),$(t,200,Fr,{ok:!1,reason:e},{handler:te});return}let i=qwt(e),a=`${i?`signed-in`:`anonymous`} ${Wwt(r)}`,o=await F.load(a,async()=>zwt({target:r,token:i?await p?.(r.host)??null:null,fetchFn:m,rateLimits:I}));s.debug({outcome:o.ok?`ok`:o.reason},`[github-reference] request outcome`),$(t,200,Fr,o,{handler:te})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:te,cause:e})}},{handler:te,method:`POST`,preBodyGate:fEt(te)}),"/api/skill-targets":x,"/api/saved-themes":_,"/api/saved-theme":b,"/api/generated-index/settings":S0({GET:ZQ(L,async(e,t)=>{if(!h){Q(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-get`});return}$(t,200,uEt,h(),{handler:`generated-index-settings-get`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-get`,method:`GET`,skipBodyParse:!0}),POST:ZQ(dEt,async(e,t,n)=>{if(!g){Q(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-set`});return}let r=await g(n.enabled);$(t,200,uEt,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 M8=Y(`managed-rename`);function mEt(e){return RJ(e)}function N8(e){return K(mEt(e),`managed-rename.json`)}function hEt(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 gEt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function _Et(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.path==`string`&&typeof t.content==`string`}function vEt(e){return typeof e==`string`&&e.length>0}function yEt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.from==`string`&&typeof t.to==`string`}function bEt(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(yEt)||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(gEt))throw Error(`Managed rename journal v2 has invalid snapshots`);if(n!==void 0&&(!Array.isArray(n)||!n.every(_Et)))throw Error(`Managed rename journal v2 has invalid pathSnapshots`);if(r!==void 0&&(!Array.isArray(r)||!r.every(vEt)))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 xEt(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(gEt))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 SEt(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version===2)return bEt(t);if(t.version===1)return xEt(t);throw Error(`Unsupported managed rename journal version: ${String(t.version)}`)}function CEt(e){let t=N8(e);if(!q(t))return null;try{let e=J(t,`utf-8`);return SEt(JSON.parse(e))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function wEt(e,t){let n=N8(e);SH(U(n),{recursive:!0});let r=`${n}.tmp`;bH(r,JSON.stringify(t,null,2),`utf-8`),CH(r,n)}function TEt(e){AH(N8(e),{force:!0})}async function EEt(e,t,n){wEt(e,t);let r=await n();return TEt(e),r}function DEt(e){return[e.destinationDocName]}function OEt(e){return e.affectedDocs.map(e=>e.to)}function kEt(e,t){let n=K(e),r=K(n,t);if(t.includes(`\0`)||r===n||!r.startsWith(`${n}${Js}`))throw Error(`Invalid recovery path: ${t}`);return r}function AEt(e,t){let n=K(t),r=`${n}${Js}`,i=U(e);for(;i.startsWith(r)&&i!==n;){let e;try{e=sc(i)}catch(e){M8.warn({path:i,err:e},`pruneEmptyAncestors: cannot read ${i}`);return}if(e.length>0)return;try{jH(i)}catch(e){M8.warn({path:i,err:e},`pruneEmptyAncestors: cannot rmdir ${i}`);return}i=U(i)}}function jEt(e,t=e){let n=CEt(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=AG(t.docName,e);SH(U(n),{recursive:!0}),bH(n,t.content,`utf-8`),r.add(t.docName)}catch(e){a.push({docName:t.docName,cause:e}),M8.warn({docName:t.docName,err:e},`Failed to restore ${t.docName}`)}if(a.length>0){let e=a.map(e=>e.docName).join(`, `);M8.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=kEt(e,r.path);SH(U(t),{recursive:!0}),bH(t,r.content,`utf-8`),i.add(r.path)}catch(e){t.push({path:r.path,cause:e}),M8.warn({path:r.path,err:e},`Failed to restore path ${r.path}`)}if(t.length>0){let e=t.map(e=>e.path).join(`, `);M8.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?OEt(n):DEt(n),s=[];for(let t of o){if(r.has(t))continue;let n=AG(t,e);try{AH(n,{force:!0}),AEt(n,e)}catch(e){q(n)&&M8.warn({destination:t},`Both source and destination files exist after partial recovery for ${t}`),M8.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=kEt(e,t),AH(n,{force:!0}),AEt(n,e)}catch(e){n&&q(n)&&M8.warn({destination:t},`Both source and destination paths exist after partial recovery for ${t}`),M8.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 TEt(t),{recovered:!0,journal:n,restoredDocNames:[...r].sort((e,t)=>e.localeCompare(t))}}const P8=Y(`reconcile`),F8={ours:`Version here`,theirs:`Outside version`};function MEt(e,t){return e===`config`?t===`ours`?`outside-settings-applied`:`outside-settings-invalid`:`no-merge-engine`}const NEt={"external-change-both-kept":{created:o0e,failed:s0e},"external-change-kept-live":{created:o0e,failed:s0e},"external-change-no-engine":{created:T2e,failed:E2e}};function PEt(e){let t=e.writeCheckpoint??MJ,n=(n,r)=>t(n,e.contentRoot,r).then(e=>(NEt[r.kind].created(),P8.info({docName:r.docName,kind:r.kind,side:r.metadata.side,sha:e},`[reconcile] history entry saved (${r.kind}, ${r.metadata.side}): ${r.docName}`),e),e=>(NEt[r.kind].failed(),P8.error({err:e,docName:r.docName,kind:r.kind,side:r.metadata.side},`[reconcile] history entry write failed (${r.kind}, ${r.metadata.side}): ${r.docName}`),null)),r=(e,t)=>{c0e(),P8.info({docName:e,kind:t},`[reconcile] history entry not saved for ${e} (${t}): the shadow repo is unavailable`)},i=async(t,i,a)=>{let o=e.getShadow();return o?n(o,{kind:`external-change-no-engine`,docName:t,contents:i.bytes,label:`${F8[i.side]} moved to history (no merge for ${a}) @ ${new Date().toISOString()}`,branch:e.getBranch()??`main`,metadata:{side:i.side,fileType:a}}):(r(t,`external-change-no-engine`),null)},a=(t,n,r,i)=>{e.notices?.record(t,e.getBranch()??`main`,{kind:`moved-to-backup`,side:n,reason:r,backup:i.display})};return{bothKept(t,i,a){let o=KJ(a),s=e.getBranch()??`main`,c=e.notices?.record(t,s,{kind:`both-kept`,kept:o})??null,l=e.getShadow();if(!l){r(t,`external-change-both-kept`);return}let u=new Date().toISOString();for(let r of[`ours`,`theirs`]){let a={kind:`external-change-both-kept`,docName:t,contents:i[r],label:`${F8[r]} before both versions were kept @ ${u}`,branch:s,metadata:{side:r,keptBlocks:o.duplicated}};queueMicrotask(()=>{n(l,a).then(n=>{n!==null&&c!==null&&e.notices?.attachEntry(t,c,n)})})}},async keptLive(t,i,a){let o=e.getShadow();if(!o)return r(t,`external-change-kept-live`),!1;let s=e.getBranch()??`main`,c=await n(o,{kind:`external-change-kept-live`,docName:t,contents:i.bytes,label:`${F8[i.side]} moved to history (${a}) @ ${new Date().toISOString()}`,branch:s,metadata:{side:i.side,reason:a}});return c!==null&&(e.notices?.record(t,s,{kind:`moved-to-history`,side:i.side,reason:a,entry:c}),!0)},saveNoEngine:i,noticeNoEngine:(t,n,r,i)=>{let o=MEt(r,n);if(i.where===`backup`){a(t,n,o,i.backup);return}e.notices?.record(t,e.getBranch()??`main`,{kind:`moved-to-history`,side:n,reason:o,entry:i.entry})},noticeBackup:a,noticeHeld(t,n){e.notices?.record(t,e.getBranch()??`main`,{kind:`save-held`,cause:n})},clearHeld(t){e.notices?.withdrawHeld(t,e.getBranch()??`main`)}}}async function FEt(e,t,n,r,i,a,o){let s=e===null?null:await e.saveNoEngine(r,i,a);if(s!==null)return{where:`history`,entry:s};let c=await Eyt(t,n,r,i.bytes,o);return c===null?null:{where:`backup`,backup:c}}function I8(e){for(let{from:t,to:n,toFile:r}of e.moves)t!==n&&e.notices?.rename(t,n,e.branch,r);let t=e.shadow;if(!t)return 0;let n=e.moves.filter(({from:e,to:t})=>UU(e)!==UU(t));if(n.length===0)return 0;let r=Nc(),i=new Date().toISOString(),a=E$(t.gitDir);for(let{from:o,to:s}of n)vct(t.gitDir,{v:1,from:o,to:s,at:i,commitSha:``,branch:e.branch,groupId:r,kind:e.kind,actor:{writerId:e.writer.writerId,displayName:e.writer.displayName},...e.anchors&&e.anchors.length>0?{anchors:[...e.anchors]}:{}},a,t),t$(s,e.writer.writerId,e.writer.displayName,e.writer.colorSeed,kye(o,s),e.writer.actor,void 0,[{from:o,to:s}]);return n.length}const L8=Y(`search`);let IEt=null;function R8(){return IEt||=aH().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.`}),IEt}let LEt=null;function REt(){return LEt||=aH().createCounter(`ok.search.corpus_truncated_total`,{description:`Count of corpus builds whose name-only file tier was truncated at OK_SEARCH_MAX_ENTRIES.`}),LEt}const z8=new Map;function zEt(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])=>Te({kind:`folder`,path:e,modifiedTs:t}))}function BEt(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 VEt(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`?BEt(e.document.content,t):void 0}}function HEt(e,t,n){let{resolved:r,members:i}=eX(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 UEt(e,t,n){return eX(e,t,n).members.map(e=>e.path)}function WEt(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=>!zne(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=(Rne(u,`query`)?ore(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 R1(t)){let i=K(t,e.dir,`SKILL.md`);try{let t=fc(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(!q(i))return n;let a;try{a=sc(i,{withFileTypes:!0})}catch{return n}for(let e of a.sort((e,t)=>e.name.localeCompare(t.name))){if(!e.isDirectory()||!We.test(e.name)||r.has(e.name))continue;let t=K(i,e.name,`SKILL.md`);try{let r=fc(t);n.push({name:e.name,absolutePath:t,docPath:`${pa}/${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(J(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(Te({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(_W(e)||vW(e)||_e(e)?.kind===`skill`||e.startsWith(`.ok/skills/`))continue;if(o.kind===`file`){i.push(Te({kind:`file`,path:e,modifiedTs:Date.parse(o.modified),aliases:UEt(t,e,o)}));continue}a.add(e);let r=HEt(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 wc(o.canonicalPath,`utf-8`)}catch(t){u=!0,L8.warn({docName:e,err:t},`[search] Failed to read ${e}`)}if(!u)try{l=zY(c,e)}catch(t){L8.warn({docName:e,err:t},`[search] Failed to extract title for ${e}`)}let f=Te({kind:`page`,path:e,title:l,content:c,modifiedTs:Date.parse(o.modified),aliases:UEt(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),L8.warn({dropped:i.length-s.length,retained:s.length,limit:o},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),REt().add(1)),{documents:[...n,...u(),...s,...zEt([...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])=>!_W(e)&&!vW(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,n])=>`${e}\0${HEt(t,e,n)}`).join(``)}|skills${p()}`}let h=s===void 0;s?.then(()=>{h=!0},e=>{h=!0,L8.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=z8.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 R8().add(1,{mode:`cold`}),{corpus:Fie(t),truncated:n};let r=Ft(e,t);if(r.rebuilt){R8().add(1,{mode:`rebuild`,reason:r.rebuildReason});let e=r.rebuildReason===`mutation-failed`?`warn`:`debug`;L8[e]({reason:r.rebuildReason,documents:t.length},`[search] corpus update fell back to a full index rebuild`)}else R8().add(1,{mode:`incremental`}),L8.debug({inserted:r.inserted,updated:r.updated,removed:r.removed},`[search] corpus updated incrementally`);return{corpus:r.corpus,truncated:n}})();z8.set(e,{fingerprint:r,pending:s});try{let t=await s;return z8.get(e)?.pending===s&&z8.set(e,{fingerprint:r,corpus:t.corpus,truncated:t.truncated}),t}catch(t){throw z8.get(e)?.pending===s&&z8.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=dee(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>VEt(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},zht({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=>{L8.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}}}const B8=Y(`skill-install`);function GEt(e){let t=t=>t===`project`?R1(e.contentDir):z1(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`?Sr:M,u=a.editor===`agents`?Oi:l[a.editor]??null;if(u===null)return{ok:!1,kind:`unknown-editor`,editor:a.editor};let d=K(s,u,i),f=K(s,o.dir),p=uO(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=K(Ls(e.skillsHome),`edit-backups`,`forks`,`${i}-${n}-${m}`);SH(K(r,`..`),{recursive:!0}),wH(t,r,{recursive:!0})}catch(e){B8.warn({name:i,err:e},`[skill-fork] stash failed`)}};if(a.action===`align`)h(d,a.editor),AH(d,{recursive:!0,force:!0}),m0({canonicalAbs:f,canonicalHash:o.contentHash,canonicalRootRel:U(o.dir),name:i,cwd:s,targets:[a.editor].filter(Ii),roots:a0(r)});else if(a.action===`make-source`){let e=o.hosts.filter(Ii);h(f,`source`),_0({canonicalAbs:f,canonicalHash:o.contentHash,name:i,cwd:s,targets:e,roots:a0(r)}),AH(f,{recursive:!0,force:!0});let n=t(r).find(e=>e.name===i);n&&m0({canonicalAbs:K(s,n.dir),canonicalHash:n.contentHash,canonicalRootRel:U(n.dir),name:i,cwd:s,targets:e,roots:a0(r)})}else{let e=a.toName;if(!We.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=K(s,u,e);CH(d,n);let i=m1({skillDir:n,toName:e});i.ok||(i.stage===`patch`?(B8.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.`)):(B8.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=>Ii(e)));for(let e of t.add??[])Ii(e)?u.add(e):o.push(c(e));let d=k1(a,n),f=[],p=[];for(let e of t.add??[])if(Ii(e)&&d[e]!==void 0&&!q(K(a,d[e],r,`SKILL.md`))){let t=e===`agents`?Oi:a0(n)[e]??null;t!==null&&p.push(t)}for(let e of t.remove??[])if(Ii(e)){if(!u.has(e)&&d[e]!==void 0&&q(K(a,d[e],r,`SKILL.md`))){let t=e===`agents`?Oi:a0(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=lEt({base:a,folderRel:e,...t===void 0?{}:{exclude:t}});if(n.ok&&await cdt(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=h0({canonicalAbs:o,canonicalHash:uO(o)?.contentHash??``,name:i,cwd:c,newTarget:s,roots:a0(r)});if(!l.ok)return{ok:!1,kind:`source-occupied`,reason:l.reason};await K1(a,i),await Q1(c,i,s);let u=t(r).find(e=>e.name===i);return{ok:!0,hosts:u?[...u.hosts]:[],sourceMovedTo:G(c,l.newAbs).split(Js).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=Ii(l),m;if(!p){let e=l.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),t=Z1(e),n=K(a,e,i);if(e===``||t||!n.startsWith(K(a)+Js))return{ok:!1,kind:`invalid-target`,target:l};m=n}let h;if(f!==void 0&&l!==f){let t=G(u,K(s)).split(Js).join(`/`),n=h0({canonicalAbs:s,canonicalHash:c.contentHash,name:i,cwd:a,newTarget:p?l:`agents`,...m===void 0?{}:{destDirAbs:m},leaveLinkBehind:!0,roots:a0(r)});if(!n.ok)return{ok:!1,kind:`source-occupied`,reason:n.reason};h=G(u,n.newAbs).split(Js).join(`/`);let o=K(u,t);if(e.effectiveInstallMode(r,i,{hosts:c.hosts,linkedHosts:c.linkedHosts??[]})===`copy`)try{nc(o).isSymbolicLink()&&(AH(o,{recursive:!0,force:!0}),wH(n.newAbs,o,{recursive:!0,dereference:!0}))}catch{}let f=!1;try{f=nc(o).isSymbolicLink()}catch{f=!0}await e0(d,i,f?{path:t,mode:`link`}:{path:t,mode:`copy`,hash:c.contentHash});let g=new Set(Tdt(a,i,a0(r)).map(e=>K(e)));g0({name:i,cwd:a,roots:a0(r),target:n.newAbs,slots:($1(d)[i]??[]).map(e=>K(d,e.path)).filter(e=>!g.has(e)),skip:[n.newAbs,K(s)],alsoClaim:[K(s),n.newAbs]}),await e0(d,i,{path:h,mode:`copy`}),await Q1(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=>Ii(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=h0({canonicalAbs:d,canonicalHash:s.contentHash,name:i,cwd:a,newTarget:e,roots:a0(r)});if(!t.ok)return{ok:!1,kind:`source-occupied`,reason:t.reason};d=t.newAbs,g=G(l,t.newAbs).split(Js).join(`/`),await e0(u,i,{path:g,mode:`copy`}),await Q1(u,i,e)}let _=g?g.split(`/`).slice(0,-1).join(`/`):n.canonicalRootRel;_0({canonicalAbs:d,canonicalHash:s.contentHash,name:i,cwd:a,targets:n.setExact?m.filter(e=>!c.includes(e)):[],roots:a0(r)});let v=m0({canonicalAbs:d,canonicalHash:s.contentHash,canonicalRootRel:_,name:i,cwd:a,targets:c,mode:n.installMode,convertLinks:n.linkModeReq===!1,convertCopies:n.linkModeReq===!0,roots:a0(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(($1(o)[i]??[]).map(e=>e.path));for(let t of n.rootAdds){if(!e.has(`${t}/${i}`))continue;let r=K(o,t,i);if(r===K(d))continue;let a=p0(r,K(d),s.contentHash);n.linkModeReq===!0&&a===`same-copy`?(AH(r,{recursive:!0,force:!0}),u0(G(U(r),K(d)),r,K(d))===`copy`&&y.add(t)):n.linkModeReq===!1&&a===`link-to-canonical`&&(AH(r,{recursive:!0,force:!0}),wH(K(d),r,{recursive:!0,dereference:!0}))}}for(let e of v.hosts){let t=e===`agents`?Oi:a0(r)[e];if(t===null||t===n.canonicalRootRel)continue;let o=K(a,t,i),c=!1;try{c=nc(o).isSymbolicLink()}catch{continue}if(c){n.installMode===`link`&&await e0(u,i,{path:`${t}/${i}`,mode:`link`});continue}let l=q(W(o,`SKILL.md`))?uO(o)?.contentHash:void 0;l!==void 0&&l===s.contentHash&&await e0(u,i,{path:`${t}/${i}`,mode:`copy`,hash:l})}if((n.rootAdds.length>0||n.rootRemoves.length>0)&&o){let e=K(d);for(let t of n.rootAdds){let r=Z1(t),a=K(o,t),c=n1(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=p0(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`&&(SH(a,{recursive:!0}),n.installMode===`link`?u0(G(a,e),c,e)===`copy`&&y.add(t):wH(e,c,{recursive:!0,dereference:!0}));let u=nc(c).isSymbolicLink()?`link`:`copy`;await e0(o,i,{path:`${t}/${i}`,mode:u,...u===`copy`?{hash:s.contentHash}:{}})}for(let t of n.rootRemoves){let n=`${t}/${i}`,r=$1(o)[i]?.find(e=>e.path===n),a=n1(o,n);if(a===null){f.push(`"${t}" is not a placeable custom root — skipped.`),p.push(`place-path-invalid`);continue}let c=p0(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`&&AH(a,{recursive:!0,force:!0}),r&&await fdt(o,i,n)}}y.size>0&&(f.push(Sdt([...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 KEt(){return{async place(e){let t=e.rawDir.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),n=K(e.placeBase,t),r=`${t}/${e.name}`,i=n1(e.placeBase,r),a=K(e.placeBase),o=Z1(t);if(t===``||i===null||!i.startsWith(a+Js)||o)return{ok:!1,kind:`invalid-path`};if(i===K(e.skillDir))return{ok:!0,alreadyAtSource:!0,placedAt:r};if(q(i))return{ok:!1,kind:`dest-exists`};SH(n,{recursive:!0});let s=e.mode;return e.mode===`link`?s=u0(G(n,K(e.skillDir)),i,K(e.skillDir)):wH(e.skillDir,i,{recursive:!0,dereference:!0}),await e0(e.placeBase,e.name,{path:r,mode:s,...s===`copy`?{hash:uO(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(!$1(e.placeBase)[e.name]?.find(e=>e.path===t))return{ok:!1,kind:`not-recorded`,path:t};let n=n1(e.placeBase,t);if(n===null)return{ok:!1,kind:`unsafe-path`};let r=uO(e.skillDir)?.contentHash??``;switch(p0(n,K(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:AH(n,{recursive:!0,force:!0})}return await fdt(e.placeBase,e.name,t),{ok:!0}},async convert(e){let t=a0(e.scope),n=Ii(e.target)?e.target===`agents`?Oi:t[e.target]:e.target.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),r=n===null||n===``?null:n1(e.ledgerBase,`${n}/${e.name}`);if(n===null||n===``||r===null)return{ok:!1,kind:`invalid-location`};let i=K(e.skillDir),a=p0(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=U(r);if(AH(r,{recursive:!0,force:!0}),SH(t,{recursive:!0}),e.mode===`link`){if(u0(G(t,i),r,i)===`copy`)return{ok:!1,kind:`links-not-permitted`}}else wH(i,r,{recursive:!0,dereference:!0})}return await e0(e.ledgerBase,e.name,{path:`${n}/${e.name}`,mode:e.mode,...e.mode===`copy`?{hash:e.canonicalHash}:{}}),{ok:!0}}}}const V8=Y(`write-advisory`);let qEt=null;function JEt(){return qEt||=aH().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}`}),qEt}const YEt=Symbol(`write-advisory-deadline`);function XEt(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?V8.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`):V8.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)=>(JEt().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(YEt),t)});try{let t=await Promise.race([c,d]);return t===YEt?(a||(s=!0,f(e)),c.catch(t=>{V8.warn({err:t,advisory:e},`[write-advisory] deferred advisory failed after its deadline`)}),m(e,`deadline`,i)):t}finally{clearTimeout(u)}}}}function ZEt(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 QEt(e,t,n,r){let i=r.fileExists??void 0,a=r.fileExcluded??void 0,{folderExists:o,resolveWikiFile:s,resolveFileByBasename:c}=r,l=Ji(`document`,n),u=Ga(_a(`folder`),l),d=e=>u.resolve(e)??(o?.(e)===!0?e:void 0),f=e=>d(e)!==void 0,p=ypt(e,t,{resolveDocument:e=>l.resolve(e),resolveFile:e=>i?.(e)?e:void 0,resolveFileByBasename:c,...a?{isExcludedFile:a}:{},...s?{resolveWikiFile:s}:{},resolveTolerantDocument:Q0(l),resolveFolder:d}),m=new Set(p.filter(({occurrence:e})=>e.sourceForm===`markdown-inline`&&e.role===`link`).map(({occurrence:e})=>e.href)),h=rmt(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=>ZEt(r,{reason:e.reason,targetKind:null,wikiAsset:!1,mayNameFile:e.sourceForm!==`jsx`&&!e.href.startsWith(`[[`)})),v=new Set;for(let e of p){let t=e.reason;if(t===null&&e.targetKind===`file`&&e.occurrence.role===`image`&&e.resolvedTarget!==null&&r.imagePathExcluded?.(e.resolvedTarget)===!0&&(t=`no-such-file`),t===null||!ZEt(r,{reason:t,targetKind:e.targetKind,wikiAsset:n2(e.occurrence)!==null,mayNameFile:!r2(e.occurrence.sourceForm)}))continue;let{href:n,role:i,sourceForm:a,range:o,reference:s}=e.occurrence;if(i===`link`&&a===`markdown-inline`&&g.has(n))continue;let c=bpt(e,t);if(c===null)continue;let l=s?.definition.repairRange??o,u=`${l.start}:${l.end}`;v.has(u)||(v.add(u),_.push({href:n,resolvedTo:e.resolvedTarget,reason:t,localTarget:c}))}return _}let $Et=null;function eDt(){return $Et||=aH().createCounter(`ok.rename.attribution_kind`,{description:`Count of rename and rollback handler dispatches by attribution kind (agent | principal | anonymous)`}),$Et}let tDt=null;function nDt(){return tDt||=aH().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, acp-document-write, agent-write-batch, agent-patch, rollback}.`}),tDt}let rDt=null;function iDt(){return rDt||=aH().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, acp-document-write, agent-write-batch, agent-patch, rollback}, divergence_type.`}),rDt}function aDt(e,t){nDt().add(1,{handler:e}),t!==void 0&&iDt().add(1,{handler:e,divergence_type:t.divergenceType})}const H8={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},U8=Y(`api`),oDt=e=>e instanceof Error&&e.message.startsWith(`Refusing to rewrite `)?e.message:void 0;function W8(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name.`};let n=t===`.`?``:t.replace(/^\.\//,``),r=a6(e);if(r.managed&&r.versioned)return{path:n?`${n}/${r.filePath}`:r.filePath};let i=qU(e);return{path:n?`${n}/${e}${i}`:`${e}${i}`}}function sDt(e,t){let n=W8(e,t);if(`error`in n)return[`${e}.md`];let r=$1e(n.path,e);return r?[n.path,r]:[n.path]}function cDt(e,t){let n=K(e,t);if(!YW(n,e))throw Error(`Invalid directory: ${t}`);return n}function lDt(e,t){let n,r;try{n=cc(e),r=cc(t)}catch{return null}return YW(n,r)?G(r,n).split(Js).join(`/`):null}async function uDt(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 G8(e){let t=Ws(e);return t?t.slice(1).toLowerCase():e.startsWith(`.`)&&e.length>1?e.slice(1).toLowerCase():`file`}const dDt=5e4;function fDt(){let e=process.env.OK_SHOWALL_MAX_ENTRIES;if(e===void 0)return dDt;let t=Number(e);return Number.isInteger(t)&&t>0?t:dDt}const pDt=5e4;function mDt(){let e=process.env.OK_SEARCH_MAX_ENTRIES;if(e===void 0)return pDt;let t=Number(e);return Number.isInteger(t)&&t>0?t:pDt}let K8=0,q8=0;function hDt(){return{invocations:K8,aborts:q8}}function gDt(){K8=0,q8=0}async function*J8(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};K8+=1;let l=0,u=!1,d=!1,f=e=>!r||e===r||e.startsWith(`${r}/`),p;try{p=await Ec(t)}catch{p=t}let m=e=>YW(e,p),h=async(e,t,r)=>{let i=new Map;for(let t of e){if(!t.isFile()&&!t.isSymbolicLink()||!BU(t.name))continue;let e=UU(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()||!BU(i.name))continue;let e=r?`${r}/${i.name}`:i.name,s=UU(e);if(a.has(s)&&!n.isExcluded(e,c)&&f(e)){if(i.isSymbolicLink()){let e=W(t,i.name),n;try{n=await Ec(e)}catch{continue}if(!m(n))continue;let r;try{r=await Dc(n)}catch{continue}if(!r.isFile())continue}else try{await Dc(W(t,i.name))}catch{continue}o.set(s,(o.get(s)??0)+1)}}return o},g=(e,t)=>{let n=UU(e);return(t.get(n)??0)>1?e:n};async function _(e,t){let r;try{r=await Tc(e,{withFileTypes:!0})}catch(t){return U8.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 Ec(W(e,i.name));if(!m(t))continue}catch(t){U8.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 Tc(r,{withFileTypes:!0})}catch(e){U8.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=W(r,e.name),i;try{i=await Ec(t)}catch(e){U8.warn({path:t,err:e},`[document-list][showAll] realpath failed for ${t}`);continue}if(!m(i)){U8.warn({path:t,canonical:i},`[document-list][showAll] refusing symlink-escape ${t} -> ${i}`);continue}if(f(h)){let e=null;try{e=await Dc(t)}catch(e){U8.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=W(r,e.name),a;try{a=await Ec(i)}catch(e){U8.warn({path:i,err:e},`[document-list][showAll] symlink realpath failed for ${i}`);continue}if(!m(a)){U8.warn({path:i,canonical:a},`[document-list][showAll] refusing symlink-escape ${i} -> ${a}`);continue}let o;try{o=await Dc(a)}catch(e){U8.warn({path:i,err:e},`[document-list][showAll] symlink target stat failed for ${i}`);continue}let s=JW(G(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,BU(e.name))yield{kind:`document`,docName:g(h,b),docExt:Ws(e.name),size:o.size,modified:o.mtime.toISOString(),isSymlink:!0,canonicalDocName:s.replace(/\.(md|mdx)$/i,``),targetPath:s};else{let t=G8(e.name);yield{kind:`asset`,docName:h,docExt:t,path:h,assetExt:t,mediaKind:Ti(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 Dc(W(r,e.name))}catch(t){U8.warn({path:`${r}/${e.name}`,err:t},`[document-list][showAll] stat failed for ${r}/${e.name}`);continue}if(BU(e.name)){let t=g(h,b),n=Ws(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=G8(e.name),S=Ti(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?W(t,r):t,r??``,1),d&&(q8+=1),{truncated:u}}async function _Dt(e){let{documents:t,...n}=e,r=J8(n),i=await r.next();for(;!i.done;)t.push(i.value),i=await r.next();return i.value}function vDt(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 yDt(e,t,n,r){return t===`file`||e===n?r:`${r}${e.slice(n.length)}`}function Y8(e,t,n){return e!==void 0&&e.length>0?e:(Q(t,400,`urn:ok:error:invalid-request`,"`docName` must be a non-empty document name.",{handler:n}),null)}function X8(e,t,n){if(!L4(n))throw new xK(`path must be a relative content path`);let r=K(e),i=t===`file`?XU(n):n,a=K(r,i);if(a!==r&&!a.startsWith(`${r}${Js}`))throw new xK(`path must not escape content directory`);return yK(a,r),a}function Z8(e){let t=e.lastIndexOf(`/`);return t===-1?{parent:``,basename:e}:{parent:e.slice(0,t),basename:e.slice(t+1)}}function bDt(e,t){return e?`${e}/${t}`:t}function xDt(e,t){return t===1?`${e} copy`:`${e} copy ${t}`}function Q8(e,t){return $8(e,t)!==null}function $8(e,t){if(BU(t))return q(K(e,t))?t:null;for(let n of wr)if(q(K(e,`${t}${n}`)))return`${t}${n}`;return null}function SDt(e,t){if(!BU(t))return!1;let n=UU(t),r=Ws(t).toLowerCase();return wr.some(t=>t.toLowerCase()!==r&&q(K(e,`${n}${t}`)))}function e5(e,t){let n=UU(t);return BU(t)&&SDt(e,t)?t:n}function CDt(e,t,n){if(!L4(t))throw new xK(`path must be a relative content path`);let r=K(e),i=K(r,`${t}${n}`);if(i!==r&&!i.startsWith(`${r}${Js}`))throw new xK(`path must not escape content directory`);return yK(i,r),i}function wDt(e,t){let{parent:n,basename:r}=Z8(t);for(let t=1;t<=1e4;t+=1){let i=bDt(n,xDt(r,t));if(!Q8(e,i))return{docName:i,attempt:t}}throw new J4(t)}function TDt(e,t){let{parent:n,basename:r}=Z8(t);for(let t=1;t<=1e4;t+=1){let i=bDt(n,xDt(r,t)),a=X8(e,`folder`,i);if(!q(a))return{folderPath:i,attempt:t}}throw new J4(t)}function EDt(e,t){let n=X8(e,`folder`,t),r=[];function i(t,n){for(let a of sc(t,{withFileTypes:!0})){let o=K(t,a.name),s=n?`${n}/${a.name}`:a.name;if(a.isDirectory()){i(o,s);continue}!a.isFile()||!BU(s)||r.push({docName:e5(e,s),fullPath:o,content:J(o,`utf-8`)})}}return i(n,t),r.sort((e,t)=>e.docName.localeCompare(t.docName)),r}function DDt(e,t){let n=X8(e,`folder`,t),r=[t];function i(e,t){for(let n of sc(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let a=K(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 t5(e,t){let n=K(e),r=K(t);return r!==n&&!r.startsWith(`${n}${Js}`)?null:G(n,r).split(Js).join(`/`)}function n5(e,t){return e!==t&&e.toLowerCase()===t.toLowerCase()}function r5(e,t){return n5(K(e),K(t))}function ODt(e,t){if(!r5(e,t)||!q(e)||!q(t))return!1;try{let n=fc(e,{bigint:!0}),r=fc(t,{bigint:!0});return Sl(n)===Sl(r)}catch{return!1}}function kDt(e){let t=U(e);for(let e=0;e<10;e+=1){let e=K(t,`.ok-case-rename-${Nc()}`);if(!q(e))return e}throw Error(`Unable to allocate temporary path for case-only rename`)}function i5(e,t){return(q(e)?J(e,`utf-8`):null)!==t&&(bH(e,t,`utf-8`),!0)}function a5(e,t){if(SH(U(t),{recursive:!0}),!r5(e,t)){CH(e,t);return}let n=kDt(e);CH(e,n);try{CH(n,t)}catch(t){try{let t=q(n),r=q(e);t&&!r?CH(n,e):U8.warn({tempExists:t,sourceExists:r},`[renamePathOnDisk] skipped case-only rollback due to unexpected state`)}catch(e){U8.warn({err:e},`[renamePathOnDisk] failed to roll back temporary case-only rename`)}throw t}}async function o5(e,t,n){if(!e)return!1;let r=t5(e,t),i=t5(e,n);return!r||!i?!1:await nK(async()=>{let a=kN({baseDir:e,timeout:{block:15e3}}),o;try{o=await nht(a,e,r)}catch(t){return U8.warn({err:t,projectDir:e,path:r},`[renameTrackedPathInGit] tracked-path lookup failed, falling back to fs rename`),!1}if(!o)return!1;rc(U(n),{recursive:!0});let s=!1;try{if(r5(t,n)){let n=t5(e,kDt(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){U8.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 U8.warn({err:e},`[renameTrackedPathInGit] git mv failed, falling back to fs rename`),!1}})}function ADt(e){let{body:t}=an(e),n=[],r=new Map,i=no();for(let e of t.split(`
2184
- `)){if(i(e))continue;let t=vse(e,r);t&&n.push(t)}return n}function s5(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function jDt(e,t){let n=t();n instanceof Map&&oZ(e,n)}function MDt(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`deleted-outside`:return{type:`urn:ok:error:doc-removed`,title:`Edit not saved to disk: the document was deleted outside the app, and the edit went to its history.`,detail:`${e.message}. Retrying will not help: the document is closed. Its history (the timeline) has the edit; tell the user the file was deleted, and do not re-create the document on your own.`};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: tell the user the file is no longer on disk.`}}}function NDt(e){let t=e.removal?.kind===`renamed`?e.removal.renamedTo:`its new name`;return{type:`urn:ok:error:doc-moved`,title:`Edit kept: the document was moved outside the app, and the edit moved with it.`,detail:`${e.message}. Do not repeat the edit: it is in ${t}, which saves it under that name. Re-read ${t} to confirm.`}}function PDt(e){let t=e.removal?.kind===`renamed`?e.removal.renamedTo:void 0;return{type:`urn:ok:error:server-stopped`,title:`Edit not saved to disk: the server stopped before the edit reached disk.`,detail:t===void 0?`${e.message}. After OpenKnowledge restarts, the edit is in the document's history (the timeline); tell the user.`:`${e.message}. After OpenKnowledge restarts, re-read the document at ${t} to see whether it holds the edit, and re-apply the edit there if it is missing. Do not re-create the document under its old name.`}}function FDt(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: tell the user the path has to be repaired on disk before this content can be written.`}}const IDt={"legacy-name":`Write the skill or template by its file path instead; that write is saved to the file.`,unresolvable:`Retrying will not help until the path resolves again. Tell the user which document it is.`,"container-gone":`OpenKnowledge does not re-create a skill folder that was deleted or moved. Tell the user which skill it is.`,"intake-landed":`Re-read the document, which now holds the outside change, and re-apply the edit if it is still missing.`};function LDt(e){let t=e.dropped===void 0?IDt.unresolvable:IDt[e.dropped];return{type:`urn:ok:error:write-dropped`,title:`Edit not saved: OpenKnowledge did not write this document's file.`,detail:`${e.message}. The edit is only in the open document. ${t}`}}function RDt(e){return{type:`urn:ok:error:write-replaced`,title:`Edit not saved: the file on disk replaced the document, and the edit went to its history.`,detail:`${e.message}. OpenKnowledge had no agreed version of the file to merge the edit with, so it took the file in as it is and saved the document as it was, this edit included, to the document's history (the timeline). Re-read the document, and re-apply the edit if it is still needed.`}}function zDt(e,t){switch(t.kind){case`branch-switch`:return{code:iG,message:`A Git branch switch discarded the pending save of ${e}`};case`renamed-outside`:return{code:eG,message:`${e} was moved outside the app to ${t.to}, and its open document followed`,removal:{kind:`renamed`,renamedTo:t.to,...t.carry?{carry:t.carry}:{}}};case`deleted-outside`:return{code:eG,message:`${e} was deleted outside the app before the edit reached disk`,removal:{kind:`deleted-outside`}};case`shutdown`:return{code:oG,message:`The server stopped while the file of ${e} was missing`};default:throw Error(`unhandled discard cause: ${JSON.stringify(t)}`)}}function BDt(e){return{type:`urn:ok:error:branch-switched`,title:`Edit kept in the open document: the Git branch changed before it reached disk.`,detail:`${e.message}. The edit stays in the open document, merged with the checked-out branch's version of the file, and is saved with the document's next save; do not repeat the edit. Re-read the document to confirm it.`}}const VDt={"pending-unreadable":{retryWhen:`next-save`,sentence:`A later save writes it once the file can be read again: the next edit to this document, or the idle save within a few minutes.`},"pending-exhausted":{retryWhen:`next-save`,sentence:`A later save writes it once the file stops changing: the next edit to this document, or the idle save within a few minutes.`},"pending-base-moved":{retryWhen:`next-save`,sentence:`A later save writes it once the outside changes have been taken in: the next edit to this document, or the idle save within a few minutes.`},"pending-intake-failed":{retryWhen:`next-save`,sentence:`A later save merges the outside change and writes it: the next edit to this document, or the idle save within a few minutes.`},"pending-intake-failed-no-base":{retryWhen:`next-save`,sentence:`A later save merges the outside change and writes it: the next edit to this document, or the idle save within a few minutes.`},"pending-no-intake":{retryWhen:`next-edit`,sentence:`The next edit to this document tries the save again.`},"pending-conflict":{retryWhen:`conflict-resolved`,sentence:`It is saved once the user has dealt with the file in the OpenKnowledge app; tell the user which file it is.`},"pending-no-history-or-backup":{retryWhen:`next-save`,sentence:`The file is not written over until its outside version is saved to the document history or the backup folder; a later save tries again: the next edit to this document, or the idle save within a few minutes.`},"pending-not-utf8":{retryWhen:void 0,sentence:`OpenKnowledge does not write over it, and no save runs until someone saves the file as text again. Tell the user which file it is.`},"pending-unsettled":{retryWhen:`next-save`,sentence:`The save was still running when the write stopped waiting for it, and it finishes on its own.`},"pending-rename":{retryWhen:`next-save`,sentence:`The edit goes with the document to its new name, or to its history if the move cannot carry it. Do not repeat this write, and do not re-create the document under its old name: re-read it at its new name.`}};function HDt(e,t,n){if(n)return`${e.message}. This edit is in the document but is not saved to the file, and no save runs on its own: OpenKnowledge has no agreed version of the file to merge it with. Any further write to this document, yours included, replaces the document with the file on disk and moves this edit, that write and any typing since to the document history (timeline). Do not write to this document again; tell the user that its file changed outside OpenKnowledge.`;let{sentence:r}=VDt[t];return t===`pending-rename`?`${e.message}. ${r}`:X3e(t)?`${e.message}. The edit is kept in the document. ${r} Do not repeat this write.`:`${e.message}. The edit is kept in the document. ${r} Do not repeat this write: re-read the document before editing it further.`}function UDt(e){let t=e.held?.reason??`pending-unreadable`,n=e.held?.noBase===!0,r=n?`replaced-on-next-edit`:VDt[t].retryWhen;return{type:`urn:ok:error:save-held`,title:`Edit applied in memory; its save to disk is held.`,detail:HDt(e,t,n),reason:t,...r===void 0?{}:{retryWhen:r},...e.held?.causeCode===void 0?{}:{causeCode:e.held.causeCode}}}function WDt(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. Do not repeat the write now: once the filesystem fault is repaired, re-read the document and repeat the edit only if it is missing.`}}function GDt(e){let t=bG(e),n=(e,n)=>({status:e,problem:{...n,...t}});switch(e.code){case nG:return n(503,WDt(e));case rG:return n(503,UDt(e));case eG:return n(409,MDt(e));case iG:return n(409,BDt(e));case aG:return n(409,NDt(e));case oG:return n(503,PDt(e));case tG:return n(400,FDt(e));case sG:return n(409,RDt(e));case cG:return n(409,LDt(e));default:return}}function KDt(e){let{outcome:t,saved:n,nextStep:r,...i}=e;return i}function qDt(e){let t=GDt(e);return t?KDt(t.problem):{type:W4({code:e.code}),title:`Write applied in memory but failed to persist to disk.`,detail:`${e.code??`unknown error`}: ${e.message}. The content was NOT saved and will be lost if the server restarts.`}}function c5(e,t,n){let r=GDt(t);if(r){let{type:t,title:i,detail:a,...o}=r.problem;Q(e,r.status,t,i,{handler:n,...a===void 0?{}:{detail:a},extensions:o});return}let i=W4({code:t.code});Q(e,U4(i),i,`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,extensions:{...bG(t)}})}function JDt(e){return e instanceof Qa||e instanceof va||e instanceof Error&&e.name===`BridgeMergeContentLossError`}function YDt(e,t,n,r,i,a,o){let s=Jst(e,t,n,r,i,a,o),c=t.documents.get(n);if(s===`revived`)return c;if(s===`failed`||!c||TW(n)||c.getText(`source`).toString()===r)return;let l=Y(`reconcile`);try{s$(e,t,n,r,i,a,o)}catch(e){if(JDt(e))throw e;l.error({err:o$(e),docName:n},`[reconcile] could not adopt moved content into ${n}`);return}return l.info({docName:n,replacedInMemoryContent:!0},`[reconcile] adopted moved content into ${n}: its open editor now shows the moved page`),c}function XDt(e){let{durabilityState:t}=e,n=!1,r=new Set;async function i(e,i){if(n)throw new zK(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??MQ({}),s=(e,t,n)=>vst(e,t,{...n,policy:o}),c=e=>PQ(e,o),l=e=>NQ(e,o),{hocuspocus:u,sessionManager:d,contentDir:f,getGeneratedIndexSettingsStatus:p,setGeneratedIndexEnabled:m,serverInstanceId:h,getFileIndex:g,getAttachmentFolderPath:_,getAllFilesIndex:v=g,mutateFileIndex:y=e=>jDt(e,v),getFileIndexGeneration:b,getFolderIndex:x,onReferencedAssetsCacheInvalidator:S,getAliasMap:C,getFolderAliasIndex:w,resolveTrackedFile:E,rescanFiles:D,localOpConcurrencyGuard:O,enableTestRoutes:k=!1,shadowRef:A,flushGitCommit:j,flushContributors:M,getCurrentBranch:N,getReportedBranch:P,getDiskAckSVs:ee,getCollabClientCount:te,contentRoot:F,derivedDocumentIndex:I,signalChannel:ne,agentFocusBroadcaster:re,agentPresenceBroadcaster:ie,onAgentWrite:ae,getSyncEngine:oe,conflicts:se,setBatchInProgress:ce,localOpCliArgs:le,authStreamHeartbeatMs:L,projectDir:ue,getBridgeLossReporter:de,getPrincipal:fe,homeDirOverride:pe,resetSettingsForTest:me,settleDiskEventsForTest:ge,agentIntegrations:_e,savedThemeLockTimeoutMs:ve,acpRegistry:ye,loadAcpCustomAgents:be,acpHarnessAvailability:xe=llt(),contentFilter:Ce,installedAgentsProbe:we,forceUnloadDocument:Te,onNamespaceCreateAccepted:Ee,captureNamespaceMove:De,capturePublicationReceipt:Oe,onResidentAdopted:ke,ready:Ae,recentlyRemovedDocs:je,serializeDoc:Me,evictManagedArtifactLkg:Ne,semanticSearch:Pe,getSemanticSimilarityFloor:Fe,embeddingsSecretsFile:Ie,readSemanticProviderConfig:Le,getLinterBaseConfig:Re,getLinkAdvisoryPolicy:ze,getProjectConfigEpoch:Ve,ephemeral:He=!1,linkPreviewFetch:Ue,getLinkPreviewsEnabled:Ge,resolveGitHubToken:Ke,githubReferenceFetch:qe,getConfigDiagnostics:Je}=e,Ye=e.docNotices,Xe=e.declaredGitHubHosts??w6(pe),R=e.resolveSyncCredentialConfig??Vxt({projectDir:ue??f,tokenStore:null,localOpCliArgs:le,declaredGitHubHosts:Xe});function Ze(t,n,r){let i=X8(t,n,r);return e.assertContentPath?.(i),i}let Qe=Imt({homeDirOverride:pe,log:U8}),{bumpSkillsCatalogGen:$e,enumerateInstalledSkillsCached:et,pluginSkillsByName:tt}=Qe,nt=ne?e=>{e===`files`&&$e(),ne(e)}:void 0,it=O??yst(),at=o_t({hocuspocus:u,conflicts:se,contentDir:f,isSafeDocName:s5,resolveAlias:St,resolveContentEntryPath:Ze,resolveDocPath:pt,extractHeadings:ADt,getFileIndex:g,getFileIndexGeneration:b,log:U8,ready:Ae,contentFilter:Ce,safeSubdir:cDt,getShowAllMaxEntries:fDt,streamShowAllEntries:J8,walkContentDirForShowAll:_Dt,synthesizeShowAllAssetExt:G8,getAllFilesIndex:v,getFolderIndex:x,getFolderAliasIndex:w,onReferencedAssetsCacheInvalidator:S}),{invalidateReferencedAssetsCache:ot}=at;function st(){let e=x?.();return e instanceof Map?e:null}function ct(e){let t=st();if(t)try{let n=fc(e,{bigint:!0});SX(t,f,e,n,e)}catch(t){U8.warn({path:e,err:t},`folder index stat failed for ${e}`)}}function lt(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)ct(K(f,t.slice(0,e).join(`/`)))}function ut(e){let t=st();t&&CX(t,e)}function dt(e,t){let n=st();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=Ze(f,`folder`,t);q(e)&&ct(e);return}for(let[e,t]of r)n.set(e,{...t,modified:new Date().toISOString(),canonicalPath:K(f,e)})}let ft=Clt({probe:we??Z$(process.platform)});function pt(e){if(Rt(e))try{return o6(e,{projectDir:ue??f,homedirOverride:pe})}catch{return null}if(!s5(e))return null;let t=K(f),n=XU(e),r=K(t,n);return YW(r,t)?r:null}let mt=new _lt({store:new vlt(K(f,`.ok`,T),U8),index:new ult,getDocBody:e=>{try{let t=u.documents.get(e);if(t)return an(t.getText(`source`).toString()).body}catch{}try{let t=pt(e);if(t&&q(t))return an(J(t,`utf-8`)).body}catch{}return null},getDocFrontmatter:e=>{try{let t=u.documents.get(e);if(t)return he(t.getText(`source`).toString())??{}}catch{}try{let t=pt(e);if(t&&q(t))return he(J(t,`utf-8`))??{}}catch{}return null}});e.commentDocHooksRef&&(e.commentDocHooksRef.current={changed:e=>{mt.refindDoc(e).then(e=>{e&&nt?.(`comments`)}).catch(t=>{U8.warn({err:t,docName:e},`[comments] re-anchor after document change failed`)})},deleted:e=>{mt.deleteDoc(e).then(e=>{e>0&&nt?.(`comments`)}).catch(t=>{U8.warn({err:t,docName:e},`[comments] cleanup after document delete failed`)})}});function ht(e){let t=pt(e);if(!t||!q(t))return e;try{return zY(J(t,`utf-8`),e)}catch{return e}}function gt(e,t){return t.has(e)?ht(e):e}let _t={cluster:void 0,category:void 0,tags:void 0};function vt(e){try{let t=u.documents.get(e);if(t){let e=ree(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=pt(e);if(!t||!q(t))return _t;let n=J(t,`utf-8`),{frontmatter:r}=an(n);return r?Knt(r):_t}catch{return _t}}function yt(e,t){return t.has(e)?vt(e):_t}let bt=XEt();async function xt(e){if(I?.isReady())try{let t=await bt.run(`orphan-hints`,()=>I.getBacklinks(e),()=>void 0);if(t===void 0||t.length>0)return;let n=performance.now(),r=hft(e,g()),i=performance.now()-n;return i>5&&U8.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){U8.warn({err:e},`[orphan-hint] computeOrphanHints failed`);return}}function St(e){return C?.().get(e)??e}function Ct(e,t){let n=`onStoreDocument-${e}`;(u.debouncer.isDebounced(n)?u.debouncer.executeNow(n):Promise.resolve()).then(()=>j?.()).catch(e=>{U8.warn({err:e},`[${t}] post-write flush failed`)})}function wt(e,t){let n=`onStoreDocument-${e}`;u.debouncer.isDebounced(n)&&u.debouncer.executeNow(n).catch(e=>{U8.warn({err:e},`[${t}] post-write disk flush failed`)})}function Tt(e,t,n){return{kind:`failure`,failure:{code:rG,message:`${e} ${n}`,held:{reason:t}}}}async function Et(e,n,r){if(n.code!==`OK_DOC_REMOVED`||n.removal?.kind!==`renamed`)return{kind:`failure`,failure:n};let i=await t.awaitRenameCarry(e,n.removal.carry),a=n.removal.renamedTo;switch(i.kind){case`unsettled`:return Tt(e,`pending-rename`,`was still being moved outside the app to ${a} when the write stopped waiting`);case`stopped`:return{kind:`failure`,failure:{code:oG,message:`The server stopped while ${e} was being moved outside the app to ${a}`,removal:{kind:`renamed`,renamedTo:a}}};case`settled`:return{kind:`failure`,failure:P3e(r,i.carried)?{...n,code:aG}:n};default:throw Error(`unhandled rename carry answer: ${JSON.stringify(i)}`)}}function Dt(e){let t=u.documents.get(e);return t?$W(t):void 0}async function Ot(e){let t=u.documents.get(e);t!==void 0&&await u.storeDocumentHooks(t,{instance:u,clientsCount:t.getConnectionsCount(),document:t,documentName:e,lastContext:{},lastTransactionOrigin:null},!0)}async function kt(e,n=Dt(e)){let r=`onStoreDocument-${e}`;u.debouncer.isDebounced(r)?(t.markAgentWriteStore(e),await u.debouncer.executeNow(r)):u.debouncer.isCurrentlyExecuting(r)&&(t.markAgentWriteStore(e),await Ot(e));let i=Date.now(),a=await t.awaitDeferredStoreOutcome(e),o,s=!1;switch(a?.kind){case void 0:case`completed`:break;case`discarded`:o=zDt(e,a.cause);break;case`failed`:o=t.takeStoreFailure(e)??a.failure;break;case`unsettled`:{s=!0;let t=Date.now()-i;console.warn(JSON.stringify({event:`agent-write-deferred-store-unsettled`,"doc.name":e,waitedMs:t,timestamp:new Date().toISOString()})),U8.warn({docName:e,waitedMs:t},`[agent-write] deferred store still pending after the wait; answering that the save is held`);break}default:L3e(a)}o??=t.takeStoreFailure(e)??void 0;let c=t.readStoreIntake(e,n);return t.consumeAgentWriteStore(e),o?Et(e,o,n):t.takeStaleExternalWriteFreeze(e)?{kind:`stale-external-write`}:s?Tt(e,`pending-unsettled`,`was still being saved when the write stopped waiting`):c===`disk-replaced`?{kind:`failure`,failure:{code:sG,message:`${e} changed on disk, and its file replaced the document`}}:c===void 0?null:{kind:`taken-in`,merge:c}}function At(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??G(ue??f,AG(e,f)).replaceAll(`\\`,`/`),resolutionOptions:HJ,...yG[`urn:ok:error:stale-external-write`]}}function jt(e,t,n){let{type:r,title:i,detail:a,...o}=At(n);Q(e,409,r,i,{handler:t,detail:a,extensions:o})}let Mt=PEt({getShadow:()=>A?.current,contentRoot:F??``,getBranch:()=>N?.()??null,writeCheckpoint:e.mergeHistoryWriter,notices:e.docNotices});function Nt(e){if(!Ce)return!1;let t=XU(e);return Ce.isExcluded(t)}function Pt(){return I?.isReady()??!0}let Ft=async e=>{if(!Pt())return ept;let t;try{t=await bt.run(`link-check`,It,()=>null)}catch(e){return U8.warn({err:e},`[link-check] write link advisory failed post-write; skipping link checks`),tpt}if(t===null)return tpt;for(let n of e)t.add(n);let n={fileExists:Wt(),folderExists:Ut(),fileExcluded:Jt(),imagePathExcluded:Ce?.isPathIgnored??null,resolveWikiFile:Kt(),resolveFileByBasename:qt()};return(e,r,i)=>({links:npt(QEt(e,r,t,n),r,i),warnings:[]})};async function It(){let e=new Set;for(let[t,n]of g()){e.add(t);for(let t of n.aliases)e.add(t)}try{for(let t of[`project`,`global`]){let n=K(t===`global`?Gn:f,`.ok`,ya);for(let r of pr(n,t).skills)e.add(`${da}${t}/${r.name}`)}}catch(e){U8.warn({err:e},`[collectAdmittedDocNames] managed-artifact enumeration failed`)}for(let t of await I?.getIndexedDocNames()??[])e.has(t)||Nt(t)||e.add(t);return e}async function Lt(e,t){if(!(!I||e.length===0))try{await I.recordDirectMutations(e)}catch(n){Bt(n,{count:e.length,reason:t},`[derived-index] failed to project durable document mutations`)}}async function z(e,t,n){if(I)try{await I.recordDirectDocument(e,t)}catch(t){Bt(t,{documentName:e,reason:n},`[derived-index] failed to project durable document`)}}async function zt(e,t,n){if(I)try{await I.recordLinkRewrite(e,t)}catch(t){Bt(t,{documentName:e,reason:n},`[derived-index] failed to project link rewrite`)}}function Bt(e,t,n){if(V2(e)){U8.debug({err:e,...t},`[derived-index] coordinator closed; skipping durable projection`);return}U8.warn({err:e,...t},n)}function Vt(e,t,n){if(V2(t)){Q(e,503,`urn:ok:error:derived-index-unavailable`,`Derived index is shutting down.`,{handler:n.handler,cause:t,logLevel:`debug`});return}Q(e,500,`urn:ok:error:internal-server-error`,n.failureTitle,{handler:n.handler,cause:t})}async function Ht(e,t){await Lt([...e].map(e=>({kind:`delete`,documentName:e})),t)}function Ut(){let e=x?.();if(!e)return()=>!1;let t=Ji(`folder`,e.keys());return e=>t.resolve(e)!==void 0}function Wt(e=v()){return Cmt(I2(e,w?.()??new Map,f).fileTargets,f,Ce)}function Gt(){return I2(v(),w?.()??new Map,f,x?.())}function Kt(){let e;return t=>(e??=la(Gt().fileTargets),e(t))}function qt(){let e;return(t,n)=>(e??=Smt(Gt().fileTargets),e(t,n))}function Jt(){return e=>O2(f,Ce,e)}function Yt(e,t){Nt(e)||y?.({kind:g().has(e)?`update`:`create`,path:Ze(f,`file`,e),docName:e,content:t})}function Xt(){let e=Promise.resolve();return async function(t){let n=e,{promise:r,resolve:i}=Promise.withResolvers();e=r,await n;try{return await t()}finally{i()}}}let Zt=Xt(),Qt=e=>e.endsWith(`.`)?e:`${e}.`;function $t(e){return e instanceof Error?e instanceof TY?{status:404,type:`urn:ok:error:doc-not-found`,error:Qt(e.message)}:e instanceof EY?{status:409,type:`urn:ok:error:doc-already-exists`,error:Qt(e.message)}:e instanceof DY||e instanceof OY?{status:400,type:`urn:ok:error:invalid-request`,error:Qt(e.message)}:e instanceof kY?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Qt(e.message)}:e instanceof Ant||e instanceof knt?{status:404,type:`urn:ok:error:doc-not-found`,error:Qt(e.message)}:SK(e)?{status:400,type:`urn:ok:error:path-escape`,error:Qt(e.message)}:e instanceof AY?{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=u.documents.get(t);e&&r.set(t,e.getText(`source`).toString())}for(let t of e){let e=u.documents.get(t);e&&e.getMap(`lifecycle`).set(`status`,n)}for(let t of e)await d.closeAllForDoc(t).catch(e=>{U8.warn({docName:t,err:e},`[file-ops] Failed to close agent session for ${t}`)});for(let n of e){let e=u.documents.get(n);t.deleteReconciledBase(n),Ne?.(n),e&&(u.closeConnections(n),await(Te??u.unloadDocument.bind(u))(e))}return r}function tn(n,r){let i=YDt(t,u,n,r,e.resolveEmbed,void 0,de?.());i&&ke?.(i,n)}function nn(e,t){for(let{fromDocName:n,toDocName:r}of e){let e=AG(r,f),i=t.get(n);typeof i==`string`&&i5(e,i);let a=typeof i==`string`?i:q(e)?J(e,`utf-8`):null;typeof a==`string`&&(oX(e,XW(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=AG(e,f);if(!q(r))throw new knt(e);return{docName:e,content:J(r,`utf-8`)}})}function sn(e){let t=u.documents.get(e);if(t)return t.getText(`source`).toString();let n=Ze(f,`file`,e);return q(n)?J(n,`utf-8`):null}function cn(e,n,r){let i=r?Oe?.(r,e):void 0,a=Ze(f,`file`,e);SH(U(a),{recursive:!0});let o=i5(a,n);oX(a,XW(n)),t.setReconciledBase(e,n),o&&i?.(),y?.({kind:`update`,path:a,docName:e,content:n})}function ln(e,t,n){let r=u.documents.get(e);if(!r)throw Error(`Document is not loaded: ${e}`);let i={markdown:``,rewrites:0};return r.transact(()=>{i=dn(r.getText(`source`).toString(),e,n.renames.get(e)??e,t,n),i.rewrites!==0&&kq(r,i.markdown,`managed-rename`,!1)},H8),i}function un(e,t,n){let r=e,i=0;for(let{fromPath:e,toPath:a}of n){let n=Tnt(r,t,e,a);r=n.markdown,i+=n.rewrites}return{markdown:r,rewrites:i}}function dn(e,t,n,r,i){let a=Mnt(e,t,i),o=un(a.markdown,n,r);return{markdown:o.markdown,rewrites:o.markdown===e?0:a.rewrites+o.rewrites}}function fn(e,t){let n=u.documents.get(e);if(!n)throw Error(`Document is not loaded: ${e}`);let r={markdown:``,rewrites:0};return n.transact(()=>{r=un(n.getText(`source`).toString(),e,t),r.rewrites!==0&&kq(n,r.markdown,`managed-rename`,!1)},H8),r}function pn(e){let t=[];if(e.length===0)return t;let n=[...g().keys()].sort((e,t)=>e.localeCompare(t));for(let r of n){let n=sn(r);if(typeof n!=`string`)continue;let i=un(n,r,e);i.rewrites!==0&&t.push({docName:r,markdown:i.markdown,rewrites:i.rewrites})}return t}function mn(e){for(let t of e){let e=se.findByDocName(t);if(e!==void 0)throw new UJ({file:e.file})}}async function hn(e,t){let n=[],r=[];for(let i of e){let e=u.documents.get(i.docName),a=e?fn(i.docName,t):i;a.rewrites!==0&&(cn(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 gn=e=>Lmt(e,{contentDir:f,contentFilter:Ce,docNameForPath:e=>e5(f,e)});function _n(e,t,n){let r=[];function i(e){for(let a of sc(e,{withFileTypes:!0})){let o=K(e,a.name),s=G(f,o).split(Js).join(`/`);if(!L2(s)){if(a.isDirectory()){if(Ce?.isDirExcluded(s))continue;i(o);continue}!a.isFile()||BU(s)||Ce?.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 vn(e,t){return Zt(async()=>oH(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async n=>{if(!I)throw new AY;let r=Ws(t)?t:`${t}${Ws(e)}`;if(L2(e)||L2(r))throw new kY(`.ok and .git are reserved directories.`);if(Ce?.isPathIgnored(r))throw new OY(`Destination asset is excluded by the project content config.`);let i=Ze(f,`folder`,e),a=Ze(f,`folder`,r);if(i===a)return{renamedAssets:[],rewrittenDocs:[]};if(n5(e,r))throw new OY(`Case-only renames are not supported.`);if(!q(i))throw new TY(`asset`,`Asset does not exist.`);if(q(a))throw new EY;if(!fc(i).isFile())throw new DY(`asset`,`Source path is not an asset file.`);let o=[{fromPath:e,toPath:r}],s=pn(o);n.setAttribute(`rename.rewrite_candidates`,s.length),mn(s.map(e=>e.docName)),await o5(ue,i,a)||a5(i,a);let{rewrittenDocs:c,derivedMutations:l}=await hn(s,o);return await Lt(l,`asset-rename`),nt?.(`files`),c.sort((e,t)=>e.docName.localeCompare(t.docName)),n.setAttribute(`rename.rewrite_count`,c.length),{renamedAssets:o,rewrittenDocs:c}}))}async function yn(e,n){return Zt(async()=>oH(`rename.executeDocumentToFileRewrites`,{attributes:{"rename.kind":`asset`,"rename.transition":`document-to-file`}},async r=>{if(!I)throw new AY;if(!BU(e)||BU(n))throw new OY(`Document-to-file rename requires a markdown source and non-markdown destination.`);let i=UU(e);if(_W(i)||vW(i))throw new kY(`Reserved document names cannot be renamed.`);if(L2(e)||L2(n))throw new kY(`.ok and .git are reserved directories.`);if(Ce?.isPathIgnored(n))throw new OY(`Destination file is excluded by the project content config.`);let a=Ze(f,`folder`,e),o=Ze(f,`folder`,n);if(a===o)return{renamedAssets:[],rewrittenDocs:[]};if(n5(e,n))throw new OY(`Case-only renames are not supported.`);if(!q(a))throw new TY(`file`);if(q(o))throw new EY;if(!fc(a).isFile())throw new DY(`file`,`Source path is not a document file.`);let s=se.findByDocName(i);if(s!==void 0)throw new UJ({file:s.file});let c=[{fromPath:e,toPath:n}],l=pn(c).filter(e=>e.docName!==i);r.setAttribute(`rename.rewrite_candidates`,l.length),mn(l.map(e=>e.docName)),await v$(t,u,i,f,void 0,de?.(),se,Mt),je&&!_W(i)&&!vW(i)&&je.setDeleted(i);let d=(await en([i],`renamed`)).get(i),p=typeof d==`string`?d:J(a,`utf-8`),m=hEt({fromPath:e,toPath:n,affectedDocs:[{from:i,to:i}],snapshots:[{docName:i,content:p}],cleanupPaths:[n]}),h=[];return await EEt(ue??f,m,async()=>{i5(a,p),oX(a,XW(p)),await o5(ue,a,o)||a5(a,o),ZU(i),y?.({kind:`delete`,path:a,docName:i});let e=fc(o,{bigint:!0});y?.({kind:`file-create`,path:o,relativePath:n,size:Number(e.size),modifiedTs:Cl(e),inode:Sl(e)});let t=await hn(l,c);h=t.rewrittenDocs,await Lt([{kind:`delete`,documentName:i},...t.derivedMutations],`document-to-file-rename`),nt?.(`files`)}),h.sort((e,t)=>e.docName.localeCompare(t.docName)),r.setAttribute(`rename.rewrite_count`,h.length),{renamedAssets:c,rewrittenDocs:h}}))}async function bn(e,n,r,i){return Zt(async()=>oH(`rename.executeRewrites`,{attributes:{"rename.kind":r}},async o=>{if(!I)throw new AY;let s=Ze(f,r,e),c=Ze(f,r,n);if(s===c)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!q(s))throw new TY(r);if(q(c)&&!ODt(s,c))throw new EY;let l=fc(s);if(r===`file`&&!l.isFile()||r===`folder`&&!l.isDirectory())throw new DY(r);r===`folder`&&(kG(s,f),a?.(s));let d=r===`folder`?_n(s,e,n):[];o.setAttribute(`rename.affected_assets`,d.length);let p=(r===`file`?[e5(f,e)]:gn(s)).map(t=>({from:t,to:r===`file`?e5(f,n):yDt(t,r,e,n)}));if(o.setAttribute(`rename.affected_docs`,p.length),p.length===0){let t=pn(d);mn(t.map(e=>e.docName)),r===`folder`&&(await o5(ue,s,c)||a5(s,c),dt(e,n),nt?.(`files`));let{rewrittenDocs:i,derivedMutations:a}=await hn(t,d);return await Lt(a,`asset-only-folder-rename`),i.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:[],renamedAssets:d,rewrittenDocs:i}}let m=jnt(p),h=ynt(new Set([...g().keys(),...await I.getIndexedDocNames(),...m.keys()]),m),_=p.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),v=new Set;for(let{from:e}of p)for(let t of await I.getBacklinks(e))m.has(t.source)||v.add(t.source);let b=new Map,x=new Set,S=await I.getRenameSourceInventory(),C=new Set(S.map(({docName:e})=>e)),w=new Set(u.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=>xnt(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=Ze(f,`file`,e);return t===(await Dc(n)).mtimeMs?null:e}catch(t){if(N0(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)||TW(e)||Nt(e))continue;let n;try{n=Ze(f,`file`,e)}catch(e){if(N0(e))continue;throw e}if(!q(n))continue;await v$(t,u,e,f,void 0,de?.(),se,Mt);let r=sn(e);typeof r==`string`&&Snt(an(r).body,e,h).rewrites>0&&(v.add(e),b.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(b.has(e))continue;if(!m.has(e)){let t=Ze(f,`file`,e);if(!q(t)){O.push(e);continue}}await v$(t,u,e,f,void 0,de?.(),se,Mt);let n=sn(e);typeof n==`string`?(b.set(e,n),m.has(e)||x.add(e)):m.has(e)||O.push(e)}if(d.length>0){let e=[...g().keys()].sort((e,t)=>e.localeCompare(t));for(let t of e){let e=b.get(t)??sn(t);typeof e==`string`&&dn(e,t,m.get(t)??t,d,h).rewrites!==0&&(b.has(t)||b.set(t,e),D.add(t),m.has(t)||x.add(t))}}mn(D);for(let{from:e}of p)if(typeof b.get(e)!=`string`)throw new Ant(e);let k=hEt({fromPath:e,toPath:n,affectedDocs:[...p],snapshots:rn([...b.keys()],b)}),j=[],M=[...x].sort((e,t)=>e.localeCompare(t)),P=[];return await EEt(ue??f,k,async()=>{for(let e of O)P.push({kind:`delete`,documentName:e});for(let e of M){let t=u.documents.get(e),n=t?ln(e,d,h):dn(b.get(e)??``,e,e,d,h);n.rewrites>0&&(cn(e,n.markdown,t),j.push({docName:e,rewrites:n.rewrites})),P.push({kind:`link-rewrite`,documentName:e,markdown:n.markdown})}if(je)for(let{from:e,to:t}of p)_W(e)||vW(e)||(je.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let a=Ze(f,r,e),o=Ze(f,r,n),s=p.map(({to:e})=>De?.(e));await o5(ue,a,o)||a5(a,o);for(let e of s)e?.();r===`folder`&&dt(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`);sH(`rename.appendLog`,{attributes:{"rename.kind":r}},e=>{let t=i?.actor,n=I8({moves:p,kind:r,branch:N?.()??`main`,writer:t?{writerId:t.writerId,displayName:t.displayName,colorSeed:t.colorSeed,actor:t.actorMetadata}:{writerId:DJ.id,displayName:DJ.name,colorSeed:DJ.id},shadow:A?.current,notices:Ye});e.setAttribute(`rename.entries_appended`,n)});let l=r===`file`&&BU(n)?Ws(n):null;for(let{from:e,to:t}of p){let n=BU(e)?Ws(e):qU(e);ZU(e),KU(t,l??n)}let g=[...p].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:n}of g){let r=Ze(f,`file`,e),i=Ze(f,`file`,n),a=dn(c.get(e)??b.get(e)??J(i,`utf-8`),e,n,d,h);t.setReconciledBase(n,a.markdown),nn([{fromDocName:e,toDocName:n}],new Map([[e,a.markdown]])),y?.({kind:`rename`,oldPath:r,newPath:i,oldDocName:e,newDocName:n,content:a.markdown}),P.push({kind:`rename`,oldDocumentName:e,newDocumentName:n,markdown:a.markdown});try{await mt.renameDoc(e,n)}catch(t){U8.warn({err:t,fromDocName:e,toDocName:n},`[comments] cover-sheet rename failed; index updated, disk self-corrects at boot`)}a.rewrites>0&&j.push({docName:n,rewrites:a.rewrites})}if(await Lt(P,`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`)}),nt?.(`files`),j.sort((e,t)=>e.docName.localeCompare(t.docName)),o.setAttribute(`rename.rewrite_count`,j.length),{renamed:_,renamedAssets:d,rewrittenDocs:j}}))}function xn(e){let t=N1e(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 Sn(e){return{principalId:fe?.()?.id,agentType:AU(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Cn(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 wn(e){return{value:e.value}}function Tn(e,t=!1){e.kind===`value`&&(T0e(),e.truncatedFrom!==void 0&&!t&&E0e())}function En(e,t,n,r){if(n.length!==0)switch(e.kind){case`agent`:{let r=e.summary.kind===`value`,i=r?e.summary:EQ(t),a=Cn(i),o=r||!a.response?a.response:wn(a.response);for(let t=0;t<n.length;t++){let{docName:r,subject:i}=n[t];t$(r,e.writerId,e.displayName,e.colorSeed,i,e.actor,t===0?a.stored:void 0)}aW(),Tn(i,!r);for(let{docName:e}of n)Ct(e,`rename-path`);return o}case`principal`:{let t=Cn(e.summary);for(let r=0;r<n.length;r++){let{docName:i,subject:a}=n[r];t$(i,e.writerId,e.displayName,e.colorSeed,a,e.actor,r===0?t.stored:void 0)}Tn(e.summary,!1);for(let{docName:e}of n)Ct(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 Dn(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 On(e,t,n,r){if(e.kind!==`agent`&&e.kind!==`principal`)return;let i=Cn(e.summary);t$(t,e.writerId,e.displayName,e.colorSeed,n,e.actor,i.stored,r)}let kn=null;function An(){Ce&&(kn!==null&&clearTimeout(kn),kn=setTimeout(()=>{kn=null,Ce?.rebuildIgnorePatterns().catch(()=>{})},12e4))}function jn(){$e(),Ce?.refreshInPlaceSkillDirs(),An()}function B(){jn(),nt?.(`files`)}let Mn=Promise.resolve();function Nn(e){$e(),Mn=Mn.then(async()=>{await Pn(e)}).catch(()=>{})}async function Pn(e){if(!M)return`unavailable`;try{return await M(),`flushed`}catch(t){return U8.warn({context:e,err:t},`[${e}] flushContributors failed; attribution stays queued for the next flush`),`failed`}}let Fn=ZQ(eie,async(n,r,i)=>{try{let n=Y8(i.docName,r,`agent-write`);if(n===null)return;let a=St(n),{agentId:o,suppliedWriterId:s,agentName:c,colorSeed:l,clientName:p,clientVersion:m,label:h}=xn(i);if(_W(a)||vW(a)){Q(r,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`agent-write`,extensions:{...yG[`urn:ok:error:reserved-doc-name`]}});return}let g=EQ(i.summary),_=await d.getSession(a,o,{displayName:c,colorSeed:l,clientName:p}),v=await v$(t,u,a,f,e.resolveEmbed,de?.(),se,Mt),y=new Date().toISOString(),b=typeof i.content==`string`?i.content:`Hello from the agent! ${y}`,{response:x,stored:S}=Cn(g),C,w;try{let n=ar(p),r=lo[n]??rt(l??o);ie?.setPresence(o,{displayName:c,icon:n,color:r,currentDoc:a,mode:`writing`,ts:Date.now()}),C=$Q(_.dc.document.getText(`source`),o,_.origin,l,p),mQ(_.dc.document,`${b}\n`,`append`),_.dc.document.transact(()=>{let t=gQ(_.dc.document);hQ(_.dc.document,`${b}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:a}:void 0,void 0,pQ(_),s);let n=Xc(t,gQ(_.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),w=$W(_.dc.document),t.markAgentWriteStore(a),t$(a,o,c,l,void 0,Sn({clientName:p,clientVersion:m,label:h}),S),aW(),Tn(g)}finally{C?.(),ie?.touchMode(o,`idle`)}let T=await kt(a,w);if(T?.kind===`failure`){c5(r,T.failure,`agent-write`);return}if(T?.kind===`stale-external-write`){jt(r,`agent-write`,a);return}wt(a,`agent-write`),ae?.();let E=h$(v),D={timestamp:y,...x?{summary:x}:{},...E?{warnings:[E]}:{}},O=SG(v,T);if(O.outcome===`both-kept`){F$(r,`agent-write`,D,O);return}$(r,200,Cte,{...D,...O},{handler:`agent-write`})}catch(e){if(e instanceof UJ){WJ(r,e,`agent-write`,se.findByDocName(UU(e.file)));return}if(e instanceof mZ){hZ(r,e,`agent-write`);return}if(e instanceof vQ){P$(r,e,`agent-write`);return}U8.error({err:e,requestId:HK(n)},`[agent-write] handler failed`),Q(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),In=ZQ(mre,async(n,r,i)=>{try{let a=ze(),{agentId:o,suppliedWriterId:s,agentName:c,colorSeed:l,clientName:p,clientVersion:m,label:h}=xn(i),g=new Date().toISOString(),_=(e,t,n,r,i,a)=>({status:`error`,docName:e,error:{type:t,title:n,...r===void 0?{}:{detail:r},...i},...a}),v=(e,t)=>{if(t instanceof qK)return o5e(t,`agent-write-batch`),_(e,KK,r5e,a5e,{retryAfterSeconds:3},yG[`urn:ok:error:concurrent-overwrite-refused`]);if(t instanceof UJ){console.warn(JSON.stringify({event:`doc-in-conflict-write-refused`,handler:`agent-write-batch`,"doc.name":e}));let{detail:t,...n}=ott(se.findByDocName(e));return{status:`error`,docName:e,error:{type:`urn:ok:error:doc-in-conflict`,title:`Document is in conflict.`,detail:t,...n},...yG[`urn:ok:error:doc-in-conflict`]}}return t instanceof mZ?(Nit(t,`agent-write-batch`),_(e,`urn:ok:error:frontmatter-malformed`,`Frontmatter YAML is malformed.`,Mit(t),void 0,yG[`urn:ok:error:frontmatter-malformed`])):t instanceof vQ?_(e,Vct,Hct,Uct,Wct,yG[`urn:ok:error:too-many-agent-sessions`]):(U8.error({err:t,docName:e,requestId:HK(n)},`[agent-write-batch] entry failed`),_(e,`urn:ok:error:internal-server-error`,`Internal server error.`))},y=Array(i.docs.length),b=[],x=new Map,S=new Map;try{let n=ar(p),r=lo[n]??rt(l??o);ie?.setPresence(o,{displayName:c,icon:n,color:r,currentDoc:St(i.docs[0].docName),mode:`writing`,ts:Date.now()}),await d.withSessions(async n=>{for(let r=0;r<i.docs.length;r++){let a=i.docs[r],d=St(a.docName);if(_W(d)||vW(d)){y[r]=_(d,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,void 0,void 0,yG[`urn:ok:error:reserved-doc-name`]);continue}try{a.extension!==void 0&&!Q8(f,d)&&KU(d,a.extension);let i=EQ(a.summary),{response:g,stored:_}=Cn(i),v=await n(d,o,{displayName:c,colorSeed:l,clientName:p}),y=await v$(t,u,d,f,e.resolveEmbed,de?.(),se,Mt),C=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:d}:void 0,w=await fQ(v.dc.document,a.markdown,a.position??`append`,C),T,E=$Q(v.dc.document.getText(`source`),o,v.origin,l,p);mQ(v.dc.document,a.markdown,a.position??`append`);try{v.dc.document.transact(()=>{let e=gQ(v.dc.document);T=hQ(v.dc.document,a.markdown,a.position??`append`,C,w,pQ(v),s);let t=Xc(e,gQ(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),x.set(d,$W(v.dc.document)),S.set(d,v.dc.document.getText(`source`).toString()),t.markAgentWriteStore(d)}finally{E()}aDt(`agent-write-batch`,T),t$(d,o,c,l,void 0,Sn({clientName:p,clientVersion:m,label:h}),_),aW(),Tn(i);let D=h$(y),O=[...T===void 0?[]:[pZ(T)],...D?[D]:[]];b.push({index:r,docName:d,reconcile:y,summaryResponse:g,warnings:O,diverged:T!==void 0})}catch(e){y[r]=v(d,e)}}let r=new Map,d=new Map;for(let e of b){if(r.has(e.docName))continue;let t=await kt(e.docName,x.get(e.docName));d.set(e.docName,t),t?.kind===`failure`?r.set(e.docName,qDt(t.failure)):t?.kind===`stale-external-write`?r.set(e.docName,KDt(At(e.docName))):r.set(e.docName,void 0)}let g=await Ft(b.filter(e=>r.get(e.docName)===void 0).map(e=>e.docName)),C;for(let e of b){let t=r.get(e.docName),n=d.get(e.docName)??null;if(t!==void 0){y[e.index]={status:`error`,docName:e.docName,error:t,...n?.kind===`failure`?bG(n.failure):yG[`urn:ok:error:stale-external-write`]};continue}let i=u.documents.get(e.docName)?.getText(`source`).toString()??S.get(e.docName)??``;Yt(e.docName,i);let o=g(i,e.docName,a.suppressLogLinkAdvisories),s=[...e.warnings,...o.warnings];y[e.index]={status:`written`,docName:e.docName,...SG(e.reconcile,n,e.diverged),...e.summaryResponse?{summary:e.summaryResponse}:{},...s.length>0?{warnings:s}:{},...o.links},C=e.docName}C!==void 0&&(re?.setFocus(o,{agentName:c,currentDoc:C,writeKind:`write`,ts:Date.now()}),ae?.())})}finally{ie?.touchMode(o,`idle`)}let C=y.map((e,t)=>e??_(i.docs[t].docName,`urn:ok:error:internal-server-error`,`Internal server error.`)),w=C.filter(e=>e.status===`written`).length;$(r,200,Rre,{timestamp:g,results:C,written:w,failed:C.length-w},{handler:`agent-write-batch`})}catch(e){U8.error({err:e,requestId:HK(n)},`[agent-write-batch] handler failed`),Q(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-batch`,cause:e})}},{handler:`agent-write-batch`,method:`POST`}),Ln=KEt(),Rn=j_t({contentDir:f,assertContentPath:e.assertContentPath,isPathIgnored:e=>Ce?.isPathIgnored(e)??!1,getAttachmentFolderPath:_,resolveTrackedFile:E}),zn=M_t({assertContentSubtree:a,contentDir:f,resolveContentEntryPath:Ze,docNameForPath:e=>e5(f,e),docNameToRelativePath:XU,listManagedDocNamesUnderFolder:e=>gn(e),listAffectedDocNames:(e,t,n)=>vDt(e,t,n),getFileIndex:g,conflictFileForDocName:e=>se.findByDocName(e)?.file??null,captureAndCloseDocuments:en,markRecentlyRemoved:je?e=>je.setDeleted(e):void 0,mutateFileIndexDelete:y?({path:e,docName:t})=>y({kind:`delete`,path:e,docName:t}):void 0,removeFolderIndexEntries:ut,upsertFolderIndexPathSegments:lt,deleteDerivedDocumentsBestEffort:Ht,invalidateReferencedAssetsCache:ot,signalFiles:()=>nt?.(`files`),nextAvailableDuplicateDocName:e=>wDt(f,e),nextAvailableDuplicateFolderPath:e=>TDt(f,e),resolveDuplicateDocPath:(t,n)=>{let r=CDt(f,t,n);return e.assertContentPath?.(r),r},collectMarkdownCopies:e=>EDt(f,e),collectFolderPaths:e=>DDt(f,e),contentFilter:Ce??void 0,unmarkRecentlyRemoved:je?e=>je.delete(e):void 0,mutateFileIndexCreate:y?({path:e,docName:t,content:n})=>{Ee?.(t),y({kind:`create`,path:e,docName:t,content:n})}:void 0,recordDerivedDocumentBestEffort:z,recordDerivedMutationsBestEffort:Lt});function Bn(e,t,n,r,i){let a=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(a.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return Q(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let o=K(f),s=a===``?o:K(o,a);if(s!==o&&!s.startsWith(`${o}${Js}`))return Q(t,400,`urn:ok:error:path-escape`,`Path escapes content directory.`,{handler:r}),null;let c=K(s,`.ok`);if(bK(c).kind===`symlink`)return Q(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=K(s,`.ok`,`templates`);if(i===`ok-and-templates`&&bK(l).kind===`symlink`)return Q(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{yK(c,o),i===`ok-and-templates`&&yK(l,o)}catch(e){return SK(e)?(Q(t,400,`urn:ok:error:path-escape`,`Path escapes content directory.`,{handler:r,cause:e}),null):(Q(t,500,`urn:ok:error:internal-server-error`,`Failed to validate path.`,{handler:r,cause:e}),null)}return{folderRel:G(o,s).split(Js).join(`/`),resolvedContentDir:o}}function Vn(e,t,n){let r=se.findByDocName(e);return r!==void 0&&(WJ(n,new UJ({file:r.file}),t,r),!0)}let V=e=>{let{body:t}=an(e);return{frontmatter:he(e)??{},body:t}};function Hn(e){return!!e&&e.length<=64&&We.test(e)}function Un(e,t,n,r){return Hn(e)?!0:(Q(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 Wn(e,t,n){let r=_ie.safeParse(e??`project`);return r.success?r.data:(Q(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let Gn=pe??_c(),Kn=GEt({contentDir:f,skillsHome:Gn,effectiveInstallMode:Xn});function qn(e){return K(e===`global`?Gn:f,`.ok`,ya)}function Jn(e,t,n){let r=K(qn(e),t);if(e===`global`){if(n!==void 0){let e=z1(Gn).find(e=>e.name===t&&e.hosts.includes(n));return e?K(Gn,e.dir):null}let e=V1(Gn,t);return e===null?q(W(r,`SKILL.md`))?r:null:e}let i=R1(f).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?K(f,i.dir):n===void 0&&q(W(r,`SKILL.md`))?r:null}function Yn(e,t){let n=e.searchParams;return DQ({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`?ue:Gn;return(r?ddt(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function Zn(e){let t=Jn(`project`,e);return t?G(f,t).split(Js).join(`/`):`${pa}/${e}`}function Qn(e,t,n,r){let i=[],a=null,o=a0(n),s=[...o0(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=K(e,...o.split(`/`),t);q(K(s,`SKILL.md`))&&(i.push(n),(r===void 0?a===null:n===r)&&(a=s))}if(a===null)return null;let c=K(a,`SKILL.md`);return{dir:a,skillMd:c,hosts:i,relPath:G(e,c).split(/[\\/]/).filter(Boolean).join(`/`)}}function er(e){let t=UMe(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 tr(e,t,n){if(!FU(t))return null;let r=Qn(e,t,n);if(!r)return null;let i=uO(r.dir)?.contentHash??``,a;try{a=fc(r.skillMd).mtime.toISOString()}catch{a=new Date(0).toISOString()}return{source:Ci,skill:t,contentHash:i,autoUpdate:!1,importedAt:a}}function nr(e,t){return tt(t).get(e)?.contentHash??null}function rr(e,t,n){let r=tt(t).get(e);if(!r)return null;try{if(cc(n)!==cc(r.home))return null}catch{return null}return{name:r.plugin,marketplace:r.marketplace,provider:r.provider,...r.repositoryUrl?{url:r.repositoryUrl}:{}}}function ir(e,t,n){let r=tt(t).get(e);if(!r)return null;if(n!==void 0)try{if(cc(n)===cc(r.home))return null}catch{}let i;try{i=fc(W(r.home,`SKILL.md`)).mtime.toISOString()}catch(e){U8.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 or(e,t){let n=IU.find(t=>NU[t]===e);if(n===void 0||t!==void 0&&LU[n]!==(t===`global`?`user`:`project`))return null;try{let e=zU(n,{checkDesktop:!0}),t=K(e,`SKILL.md`);return q(t)?t:null}catch(t){return U8.warn({name:e,err:t},`[skills] bundle asset dir unresolved for built-in ${e}`),null}}function sr(e,t,n){let r=Qn(e,t,n),i=r?.skillMd??or(t);if(i===null)return null;let a;try{let{frontmatter:e}=V(J(i,`utf-8`));typeof e.description==`string`&&(a=e.description)}catch{}let o=tr(e,t,n),s=uO(U(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:Hte(s)}:{},...o?{origin:er(o)}:{}}}function cr(e,t,n){return FU(e)?(Q(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 lr(e,t){return G(t===`global`?Gn:f,e).split(/[\\/]/).filter(Boolean).join(`/`)}function ur(e){return e===`global`?Gn:ue}function dr(e,t,n,r){let i=n===`project`?f:Gn;if(r.purge!==void 0){v0(t,e,o0(n),a0(n));for(let e of kut(i,n,t,r.purge.contentHash))AH(e,{recursive:!0,force:!0});return}if(!q(K(qn(n),t,`SKILL.md`))){let r=(n===`project`?R1(f):z1(Gn)).find(e=>e.name===t);if(r){let i=n===`project`?f:Gn,a=K(i,r.dir),o=K(i,`.agents`,`skills`),s=W(o,t);if(q(o)&&!q(W(s,`SKILL.md`))){let e=!1;try{e=cc(a)===cc(s)}catch{e=!1}e||wH(a,s,{recursive:!0,dereference:!0})}_0({canonicalAbs:q(W(s,`SKILL.md`))?s:a,canonicalHash:r.contentHash,name:t,cwd:e,targets:[...o0(n)],roots:a0(n)});return}}v0(t,e,o0(n),a0(n))}async function fr(e,t,n,r={}){return dr(e,t,n,r),await K1(e,t)!==null}function pr(e,t){let n=[];if(!q(e))return{skills:n,truncated:!1};let r;try{r=sc(e,{withFileTypes:!0})}catch(r){return Y(`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()||!We.test(a.name))continue;if(n.length>=500){i=!0;break}let r=K(e,a.name,`SKILL.md`);if(!q(r))continue;let o;try{let{frontmatter:e}=V(J(r,`utf-8`));typeof e.description==`string`&&(o=e.description)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:lr(r,t),absolutePath:r})}return{skills:n,truncated:i}}function mr(e,t,n){let r=e===`project`?f:Gn,i=Jn(e,t,n);return{root:i===null?qn(e):U(i),dirRel:i===null?`.ok/skills/${t}`:G(r,i).split(Js).join(`/`),realDir:i}}function hr(e,t){return uO(K(e,t))?.contentHash}async function gr(e,t){let n=A?.current;if(!(!n||!e))try{let r=yJ(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
2184
+ `)){if(i(e))continue;let t=vse(e,r);t&&n.push(t)}return n}function s5(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function jDt(e,t){let n=t();n instanceof Map&&oZ(e,n)}function MDt(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`deleted-outside`:return{type:`urn:ok:error:doc-removed`,title:`Edit not saved to disk: the document was deleted outside the app, and the edit went to its history.`,detail:`${e.message}. Retrying will not help: the document is closed. Its history (the timeline) has the edit; tell the user the file was deleted, and do not re-create the document on your own.`};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: tell the user the file is no longer on disk.`}}}function NDt(e){let t=e.removal?.kind===`renamed`?e.removal.renamedTo:`its new name`;return{type:`urn:ok:error:doc-moved`,title:`Edit kept: the document was moved outside the app, and the edit moved with it.`,detail:`${e.message}. Do not repeat the edit: it is in ${t}, which saves it under that name. Re-read ${t} to confirm.`}}function PDt(e){let t=e.removal?.kind===`renamed`?e.removal.renamedTo:void 0;return{type:`urn:ok:error:server-stopped`,title:`Edit not saved to disk: the server stopped before the edit reached disk.`,detail:t===void 0?`${e.message}. After OpenKnowledge restarts, the edit is in the document's history (the timeline); tell the user.`:`${e.message}. After OpenKnowledge restarts, re-read the document at ${t} to see whether it holds the edit, and re-apply the edit there if it is missing. Do not re-create the document under its old name.`}}function FDt(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: tell the user the path has to be repaired on disk before this content can be written.`}}const IDt={"legacy-name":`Write the skill or template by its file path instead; that write is saved to the file.`,unresolvable:`Retrying will not help until the path resolves again. Tell the user which document it is.`,"container-gone":`OpenKnowledge does not re-create a skill folder that was deleted or moved. Tell the user which skill it is.`,"intake-landed":`Re-read the document, which now holds the outside change, and re-apply the edit if it is still missing.`};function LDt(e){let t=e.dropped===void 0?IDt.unresolvable:IDt[e.dropped];return{type:`urn:ok:error:write-dropped`,title:`Edit not saved: OpenKnowledge did not write this document's file.`,detail:`${e.message}. The edit is only in the open document. ${t}`}}function RDt(e){return{type:`urn:ok:error:write-replaced`,title:`Edit not saved: the file on disk replaced the document, and the edit went to its history.`,detail:`${e.message}. OpenKnowledge had no agreed version of the file to merge the edit with, so it took the file in as it is and saved the document as it was, this edit included, to the document's history (the timeline). Re-read the document, and re-apply the edit if it is still needed.`}}function zDt(e,t){switch(t.kind){case`branch-switch`:return{code:iG,message:`A Git branch switch discarded the pending save of ${e}`};case`renamed-outside`:return{code:eG,message:`${e} was moved outside the app to ${t.to}, and its open document followed`,removal:{kind:`renamed`,renamedTo:t.to,...t.carry?{carry:t.carry}:{}}};case`deleted-outside`:return{code:eG,message:`${e} was deleted outside the app before the edit reached disk`,removal:{kind:`deleted-outside`}};case`shutdown`:return{code:oG,message:`The server stopped while the file of ${e} was missing`};default:throw Error(`unhandled discard cause: ${JSON.stringify(t)}`)}}function BDt(e){return{type:`urn:ok:error:branch-switched`,title:`Edit kept in the open document: the Git branch changed before it reached disk.`,detail:`${e.message}. The edit stays in the open document, merged with the checked-out branch's version of the file, and is saved with the document's next save; do not repeat the edit. Re-read the document to confirm it.`}}const VDt={"pending-unreadable":{retryWhen:`next-save`,sentence:`A later save writes it once the file can be read again: the next edit to this document, or the idle save within a few minutes.`},"pending-exhausted":{retryWhen:`next-save`,sentence:`A later save writes it once the file stops changing: the next edit to this document, or the idle save within a few minutes.`},"pending-base-moved":{retryWhen:`next-save`,sentence:`A later save writes it once the outside changes have been taken in: the next edit to this document, or the idle save within a few minutes.`},"pending-intake-failed":{retryWhen:`next-save`,sentence:`A later save merges the outside change and writes it: the next edit to this document, or the idle save within a few minutes.`},"pending-intake-failed-no-base":{retryWhen:`next-save`,sentence:`A later save merges the outside change and writes it: the next edit to this document, or the idle save within a few minutes.`},"pending-no-intake":{retryWhen:`next-edit`,sentence:`The next edit to this document tries the save again.`},"pending-conflict":{retryWhen:`conflict-resolved`,sentence:`It is saved once the user has dealt with the file in the OpenKnowledge app; tell the user which file it is.`},"pending-no-history-or-backup":{retryWhen:`next-save`,sentence:`The file is not written over until its outside version is saved to the document history or the backup folder; a later save tries again: the next edit to this document, or the idle save within a few minutes.`},"pending-not-utf8":{retryWhen:void 0,sentence:`OpenKnowledge does not write over it, and no save runs until someone saves the file as text again. Tell the user which file it is.`},"pending-unsettled":{retryWhen:`next-save`,sentence:`The save was still running when the write stopped waiting for it, and it finishes on its own.`},"pending-rename":{retryWhen:`next-save`,sentence:`The edit goes with the document to its new name, or to its history if the move cannot carry it. Do not repeat this write, and do not re-create the document under its old name: re-read it at its new name.`}};function HDt(e,t,n){if(n)return`${e.message}. This edit is in the document but is not saved to the file, and no save runs on its own: OpenKnowledge has no agreed version of the file to merge it with. Any further write to this document, yours included, replaces the document with the file on disk and moves this edit, that write and any typing since to the document history (timeline). Do not write to this document again; tell the user that its file changed outside OpenKnowledge.`;let{sentence:r}=VDt[t];return t===`pending-rename`?`${e.message}. ${r}`:X3e(t)?`${e.message}. The edit is kept in the document. ${r} Do not repeat this write.`:`${e.message}. The edit is kept in the document. ${r} Do not repeat this write: re-read the document before editing it further.`}function UDt(e){let t=e.held?.reason??`pending-unreadable`,n=e.held?.noBase===!0,r=n?`replaced-on-next-edit`:VDt[t].retryWhen;return{type:`urn:ok:error:save-held`,title:`Edit applied in memory; its save to disk is held.`,detail:HDt(e,t,n),reason:t,...r===void 0?{}:{retryWhen:r},...e.held?.causeCode===void 0?{}:{causeCode:e.held.causeCode}}}function WDt(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. Do not repeat the write now: once the filesystem fault is repaired, re-read the document and repeat the edit only if it is missing.`}}function GDt(e){let t=bG(e),n=(e,n)=>({status:e,problem:{...n,...t}});switch(e.code){case nG:return n(503,WDt(e));case rG:return n(503,UDt(e));case eG:return n(409,MDt(e));case iG:return n(409,BDt(e));case aG:return n(409,NDt(e));case oG:return n(503,PDt(e));case tG:return n(400,FDt(e));case sG:return n(409,RDt(e));case cG:return n(409,LDt(e));default:return}}function KDt(e){let{outcome:t,saved:n,nextStep:r,...i}=e;return i}function qDt(e){let t=GDt(e);return t?KDt(t.problem):{type:W4({code:e.code}),title:`Write applied in memory but failed to persist to disk.`,detail:`${e.code??`unknown error`}: ${e.message}. The content was NOT saved and will be lost if the server restarts.`}}function c5(e,t,n){let r=GDt(t);if(r){let{type:t,title:i,detail:a,...o}=r.problem;Q(e,r.status,t,i,{handler:n,...a===void 0?{}:{detail:a},extensions:o});return}let i=W4({code:t.code});Q(e,U4(i),i,`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,extensions:{...bG(t)}})}function JDt(e){return e instanceof Qa||e instanceof va||e instanceof Error&&e.name===`BridgeMergeContentLossError`}function YDt(e,t,n,r,i,a,o){let s=Jst(e,t,n,r,i,a,o),c=t.documents.get(n);if(s===`revived`)return c;if(s===`failed`||!c||TW(n)||c.getText(`source`).toString()===r)return;let l=Y(`reconcile`);try{s$(e,t,n,r,i,a,o)}catch(e){if(JDt(e))throw e;l.error({err:o$(e),docName:n},`[reconcile] could not adopt moved content into ${n}`);return}return l.info({docName:n,replacedInMemoryContent:!0},`[reconcile] adopted moved content into ${n}: its open editor now shows the moved page`),c}function XDt(e){let{durabilityState:t}=e,n=!1,r=new Set;async function i(e,i){if(n)throw new zK(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??MQ({}),s=(e,t,n)=>vst(e,t,{...n,policy:o}),c=e=>PQ(e,o),l=e=>NQ(e,o),{hocuspocus:u,sessionManager:d,contentDir:f,getGeneratedIndexSettingsStatus:p,setGeneratedIndexEnabled:m,serverInstanceId:h,getFileIndex:g,getAttachmentFolderPath:_,getAllFilesIndex:v=g,mutateFileIndex:y=e=>jDt(e,v),getFileIndexGeneration:b,getFolderIndex:x,onReferencedAssetsCacheInvalidator:S,getAliasMap:C,getFolderAliasIndex:w,resolveTrackedFile:E,rescanFiles:D,localOpConcurrencyGuard:O,enableTestRoutes:k=!1,shadowRef:A,flushGitCommit:j,flushContributors:M,getCurrentBranch:N,getReportedBranch:P,getDiskAckSVs:ee,getCollabClientCount:te,contentRoot:F,derivedDocumentIndex:I,signalChannel:ne,agentFocusBroadcaster:re,agentPresenceBroadcaster:ie,onAgentWrite:ae,getSyncEngine:oe,conflicts:se,setBatchInProgress:ce,localOpCliArgs:le,authStreamHeartbeatMs:L,projectDir:ue,getBridgeLossReporter:de,getPrincipal:fe,homeDirOverride:pe,resetSettingsForTest:me,settleDiskEventsForTest:ge,agentIntegrations:_e,savedThemeLockTimeoutMs:ve,acpRegistry:ye,loadAcpCustomAgents:be,acpHarnessAvailability:xe=llt(),contentFilter:Ce,installedAgentsProbe:we,forceUnloadDocument:Te,onNamespaceCreateAccepted:Ee,captureNamespaceMove:De,capturePublicationReceipt:Oe,onResidentAdopted:ke,ready:Ae,recentlyRemovedDocs:je,serializeDoc:Me,evictManagedArtifactLkg:Ne,semanticSearch:Pe,getSemanticSimilarityFloor:Fe,embeddingsSecretsFile:Ie,readSemanticProviderConfig:Le,getLinterBaseConfig:Re,getLinkAdvisoryPolicy:ze,getProjectConfigEpoch:Ve,ephemeral:He=!1,linkPreviewFetch:Ue,getLinkPreviewsEnabled:Ge,resolveGitHubToken:Ke,githubReferenceFetch:qe,getConfigDiagnostics:Je}=e,Ye=e.docNotices,Xe=e.declaredGitHubHosts??w6(pe),R=e.resolveSyncCredentialConfig??Vxt({projectDir:ue??f,tokenStore:null,localOpCliArgs:le,declaredGitHubHosts:Xe});function Ze(t,n,r){let i=X8(t,n,r);return e.assertContentPath?.(i),i}let Qe=Imt({homeDirOverride:pe,log:U8}),{bumpSkillsCatalogGen:$e,enumerateInstalledSkillsCached:et,pluginSkillsByName:tt}=Qe,nt=ne?e=>{e===`files`&&$e(),ne(e)}:void 0,it=O??yst(),at=o_t({hocuspocus:u,conflicts:se,contentDir:f,isSafeDocName:s5,resolveAlias:St,resolveContentEntryPath:Ze,resolveDocPath:pt,extractHeadings:ADt,getFileIndex:g,getFileIndexGeneration:b,log:U8,ready:Ae,contentFilter:Ce,safeSubdir:cDt,getShowAllMaxEntries:fDt,streamShowAllEntries:J8,walkContentDirForShowAll:_Dt,synthesizeShowAllAssetExt:G8,getAllFilesIndex:v,getFolderIndex:x,getFolderAliasIndex:w,onReferencedAssetsCacheInvalidator:S}),{invalidateReferencedAssetsCache:ot}=at;function st(){let e=x?.();return e instanceof Map?e:null}function ct(e){let t=st();if(t)try{let n=fc(e,{bigint:!0});SX(t,f,e,n,e)}catch(t){U8.warn({path:e,err:t},`folder index stat failed for ${e}`)}}function lt(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)ct(K(f,t.slice(0,e).join(`/`)))}function ut(e){let t=st();t&&CX(t,e)}function dt(e,t){let n=st();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=Ze(f,`folder`,t);q(e)&&ct(e);return}for(let[e,t]of r)n.set(e,{...t,modified:new Date().toISOString(),canonicalPath:K(f,e)})}let ft=Clt({probe:we??Z$(process.platform)});function pt(e){if(Rt(e))try{return o6(e,{projectDir:ue??f,homedirOverride:pe})}catch{return null}if(!s5(e))return null;let t=K(f),n=XU(e),r=K(t,n);return YW(r,t)?r:null}let mt=new _lt({store:new vlt(K(f,`.ok`,T),U8),index:new ult,getDocBody:e=>{try{let t=u.documents.get(e);if(t)return an(t.getText(`source`).toString()).body}catch{}try{let t=pt(e);if(t&&q(t))return an(J(t,`utf-8`)).body}catch{}return null},getDocFrontmatter:e=>{try{let t=u.documents.get(e);if(t)return he(t.getText(`source`).toString())??{}}catch{}try{let t=pt(e);if(t&&q(t))return he(J(t,`utf-8`))??{}}catch{}return null}});e.commentDocHooksRef&&(e.commentDocHooksRef.current={changed:e=>{mt.refindDoc(e).then(e=>{e&&nt?.(`comments`)}).catch(t=>{U8.warn({err:t,docName:e},`[comments] re-anchor after document change failed`)})},deleted:e=>{mt.deleteDoc(e).then(e=>{e>0&&nt?.(`comments`)}).catch(t=>{U8.warn({err:t,docName:e},`[comments] cleanup after document delete failed`)})},renamed:async(e,t)=>{try{await mt.renameDoc(e,t)>0&&nt?.(`comments`)}catch(n){nt?.(`comments`),U8.warn({err:n,fromDocName:e,toDocName:t},`[comments] update after document rename failed`)}}});function ht(e){let t=pt(e);if(!t||!q(t))return e;try{return zY(J(t,`utf-8`),e)}catch{return e}}function gt(e,t){return t.has(e)?ht(e):e}let _t={cluster:void 0,category:void 0,tags:void 0};function vt(e){try{let t=u.documents.get(e);if(t){let e=ree(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=pt(e);if(!t||!q(t))return _t;let n=J(t,`utf-8`),{frontmatter:r}=an(n);return r?Knt(r):_t}catch{return _t}}function yt(e,t){return t.has(e)?vt(e):_t}let bt=XEt();async function xt(e){if(I?.isReady())try{let t=await bt.run(`orphan-hints`,()=>I.getBacklinks(e),()=>void 0);if(t===void 0||t.length>0)return;let n=performance.now(),r=hft(e,g()),i=performance.now()-n;return i>5&&U8.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){U8.warn({err:e},`[orphan-hint] computeOrphanHints failed`);return}}function St(e){return C?.().get(e)??e}function Ct(e,t){let n=`onStoreDocument-${e}`;(u.debouncer.isDebounced(n)?u.debouncer.executeNow(n):Promise.resolve()).then(()=>j?.()).catch(e=>{U8.warn({err:e},`[${t}] post-write flush failed`)})}function wt(e,t){let n=`onStoreDocument-${e}`;u.debouncer.isDebounced(n)&&u.debouncer.executeNow(n).catch(e=>{U8.warn({err:e},`[${t}] post-write disk flush failed`)})}function Tt(e,t,n){return{kind:`failure`,failure:{code:rG,message:`${e} ${n}`,held:{reason:t}}}}async function Et(e,n,r){if(n.code!==`OK_DOC_REMOVED`||n.removal?.kind!==`renamed`)return{kind:`failure`,failure:n};let i=await t.awaitRenameCarry(e,n.removal.carry),a=n.removal.renamedTo;switch(i.kind){case`unsettled`:return Tt(e,`pending-rename`,`was still being moved outside the app to ${a} when the write stopped waiting`);case`stopped`:return{kind:`failure`,failure:{code:oG,message:`The server stopped while ${e} was being moved outside the app to ${a}`,removal:{kind:`renamed`,renamedTo:a}}};case`settled`:return{kind:`failure`,failure:P3e(r,i.carried)?{...n,code:aG}:n};default:throw Error(`unhandled rename carry answer: ${JSON.stringify(i)}`)}}function Dt(e){let t=u.documents.get(e);return t?$W(t):void 0}async function Ot(e){let t=u.documents.get(e);t!==void 0&&await u.storeDocumentHooks(t,{instance:u,clientsCount:t.getConnectionsCount(),document:t,documentName:e,lastContext:{},lastTransactionOrigin:null},!0)}async function kt(e,n=Dt(e)){let r=`onStoreDocument-${e}`;u.debouncer.isDebounced(r)?(t.markAgentWriteStore(e),await u.debouncer.executeNow(r)):u.debouncer.isCurrentlyExecuting(r)&&(t.markAgentWriteStore(e),await Ot(e));let i=Date.now(),a=await t.awaitDeferredStoreOutcome(e),o,s=!1;switch(a?.kind){case void 0:case`completed`:break;case`discarded`:o=zDt(e,a.cause);break;case`failed`:o=t.takeStoreFailure(e)??a.failure;break;case`unsettled`:{s=!0;let t=Date.now()-i;console.warn(JSON.stringify({event:`agent-write-deferred-store-unsettled`,"doc.name":e,waitedMs:t,timestamp:new Date().toISOString()})),U8.warn({docName:e,waitedMs:t},`[agent-write] deferred store still pending after the wait; answering that the save is held`);break}default:L3e(a)}o??=t.takeStoreFailure(e)??void 0;let c=t.readStoreIntake(e,n);return t.consumeAgentWriteStore(e),o?Et(e,o,n):t.takeStaleExternalWriteFreeze(e)?{kind:`stale-external-write`}:s?Tt(e,`pending-unsettled`,`was still being saved when the write stopped waiting`):c===`disk-replaced`?{kind:`failure`,failure:{code:sG,message:`${e} changed on disk, and its file replaced the document`}}:c===void 0?null:{kind:`taken-in`,merge:c}}function At(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??G(ue??f,AG(e,f)).replaceAll(`\\`,`/`),resolutionOptions:HJ,...yG[`urn:ok:error:stale-external-write`]}}function jt(e,t,n){let{type:r,title:i,detail:a,...o}=At(n);Q(e,409,r,i,{handler:t,detail:a,extensions:o})}let Mt=PEt({getShadow:()=>A?.current,contentRoot:F??``,getBranch:()=>N?.()??null,writeCheckpoint:e.mergeHistoryWriter,notices:e.docNotices});function Nt(e){if(!Ce)return!1;let t=XU(e);return Ce.isExcluded(t)}function Pt(){return I?.isReady()??!0}let Ft=async e=>{if(!Pt())return ept;let t;try{t=await bt.run(`link-check`,It,()=>null)}catch(e){return U8.warn({err:e},`[link-check] write link advisory failed post-write; skipping link checks`),tpt}if(t===null)return tpt;for(let n of e)t.add(n);let n={fileExists:Wt(),folderExists:Ut(),fileExcluded:Jt(),imagePathExcluded:Ce?.isPathIgnored??null,resolveWikiFile:Kt(),resolveFileByBasename:qt()};return(e,r,i)=>({links:npt(QEt(e,r,t,n),r,i),warnings:[]})};async function It(){let e=new Set;for(let[t,n]of g()){e.add(t);for(let t of n.aliases)e.add(t)}try{for(let t of[`project`,`global`]){let n=K(t===`global`?Gn:f,`.ok`,ya);for(let r of pr(n,t).skills)e.add(`${da}${t}/${r.name}`)}}catch(e){U8.warn({err:e},`[collectAdmittedDocNames] managed-artifact enumeration failed`)}for(let t of await I?.getIndexedDocNames()??[])e.has(t)||Nt(t)||e.add(t);return e}async function Lt(e,t){if(!(!I||e.length===0))try{await I.recordDirectMutations(e)}catch(n){Bt(n,{count:e.length,reason:t},`[derived-index] failed to project durable document mutations`)}}async function z(e,t,n){if(I)try{await I.recordDirectDocument(e,t)}catch(t){Bt(t,{documentName:e,reason:n},`[derived-index] failed to project durable document`)}}async function zt(e,t,n){if(I)try{await I.recordLinkRewrite(e,t)}catch(t){Bt(t,{documentName:e,reason:n},`[derived-index] failed to project link rewrite`)}}function Bt(e,t,n){if(V2(e)){U8.debug({err:e,...t},`[derived-index] coordinator closed; skipping durable projection`);return}U8.warn({err:e,...t},n)}function Vt(e,t,n){if(V2(t)){Q(e,503,`urn:ok:error:derived-index-unavailable`,`Derived index is shutting down.`,{handler:n.handler,cause:t,logLevel:`debug`});return}Q(e,500,`urn:ok:error:internal-server-error`,n.failureTitle,{handler:n.handler,cause:t})}async function Ht(e,t){await Lt([...e].map(e=>({kind:`delete`,documentName:e})),t)}function Ut(){let e=x?.();if(!e)return()=>!1;let t=Ji(`folder`,e.keys());return e=>t.resolve(e)!==void 0}function Wt(e=v()){return Cmt(I2(e,w?.()??new Map,f).fileTargets,f,Ce)}function Gt(){return I2(v(),w?.()??new Map,f,x?.())}function Kt(){let e;return t=>(e??=la(Gt().fileTargets),e(t))}function qt(){let e;return(t,n)=>(e??=Smt(Gt().fileTargets),e(t,n))}function Jt(){return e=>O2(f,Ce,e)}function Yt(e,t){Nt(e)||y?.({kind:g().has(e)?`update`:`create`,path:Ze(f,`file`,e),docName:e,content:t})}function Xt(){let e=Promise.resolve();return async function(t){let n=e,{promise:r,resolve:i}=Promise.withResolvers();e=r,await n;try{return await t()}finally{i()}}}let Zt=Xt(),Qt=e=>e.endsWith(`.`)?e:`${e}.`;function $t(e){return e instanceof Error?e instanceof TY?{status:404,type:`urn:ok:error:doc-not-found`,error:Qt(e.message)}:e instanceof EY?{status:409,type:`urn:ok:error:doc-already-exists`,error:Qt(e.message)}:e instanceof DY||e instanceof OY?{status:400,type:`urn:ok:error:invalid-request`,error:Qt(e.message)}:e instanceof kY?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Qt(e.message)}:e instanceof Ant||e instanceof knt?{status:404,type:`urn:ok:error:doc-not-found`,error:Qt(e.message)}:SK(e)?{status:400,type:`urn:ok:error:path-escape`,error:Qt(e.message)}:e instanceof AY?{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=u.documents.get(t);e&&r.set(t,e.getText(`source`).toString())}for(let t of e){let e=u.documents.get(t);e&&e.getMap(`lifecycle`).set(`status`,n)}for(let t of e)await d.closeAllForDoc(t).catch(e=>{U8.warn({docName:t,err:e},`[file-ops] Failed to close agent session for ${t}`)});for(let n of e){let e=u.documents.get(n);t.deleteReconciledBase(n),Ne?.(n),e&&(u.closeConnections(n),await(Te??u.unloadDocument.bind(u))(e))}return r}function tn(n,r){let i=YDt(t,u,n,r,e.resolveEmbed,void 0,de?.());i&&ke?.(i,n)}function nn(e,t){for(let{fromDocName:n,toDocName:r}of e){let e=AG(r,f),i=t.get(n);typeof i==`string`&&i5(e,i);let a=typeof i==`string`?i:q(e)?J(e,`utf-8`):null;typeof a==`string`&&(oX(e,XW(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=AG(e,f);if(!q(r))throw new knt(e);return{docName:e,content:J(r,`utf-8`)}})}function sn(e){let t=u.documents.get(e);if(t)return t.getText(`source`).toString();let n=Ze(f,`file`,e);return q(n)?J(n,`utf-8`):null}function cn(e,n,r){let i=r?Oe?.(r,e):void 0,a=Ze(f,`file`,e);SH(U(a),{recursive:!0});let o=i5(a,n);oX(a,XW(n)),t.setReconciledBase(e,n),o&&i?.(),y?.({kind:`update`,path:a,docName:e,content:n})}function ln(e,t,n){let r=u.documents.get(e);if(!r)throw Error(`Document is not loaded: ${e}`);let i={markdown:``,rewrites:0};return r.transact(()=>{i=dn(r.getText(`source`).toString(),e,n.renames.get(e)??e,t,n),i.rewrites!==0&&kq(r,i.markdown,`managed-rename`,!1)},H8),i}function un(e,t,n){let r=e,i=0;for(let{fromPath:e,toPath:a}of n){let n=Tnt(r,t,e,a);r=n.markdown,i+=n.rewrites}return{markdown:r,rewrites:i}}function dn(e,t,n,r,i){let a=Mnt(e,t,i),o=un(a.markdown,n,r);return{markdown:o.markdown,rewrites:o.markdown===e?0:a.rewrites+o.rewrites}}function fn(e,t){let n=u.documents.get(e);if(!n)throw Error(`Document is not loaded: ${e}`);let r={markdown:``,rewrites:0};return n.transact(()=>{r=un(n.getText(`source`).toString(),e,t),r.rewrites!==0&&kq(n,r.markdown,`managed-rename`,!1)},H8),r}function pn(e){let t=[];if(e.length===0)return t;let n=[...g().keys()].sort((e,t)=>e.localeCompare(t));for(let r of n){let n=sn(r);if(typeof n!=`string`)continue;let i=un(n,r,e);i.rewrites!==0&&t.push({docName:r,markdown:i.markdown,rewrites:i.rewrites})}return t}function mn(e){for(let t of e){let e=se.findByDocName(t);if(e!==void 0)throw new UJ({file:e.file})}}async function hn(e,t){let n=[],r=[];for(let i of e){let e=u.documents.get(i.docName),a=e?fn(i.docName,t):i;a.rewrites!==0&&(cn(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 gn=e=>Lmt(e,{contentDir:f,contentFilter:Ce,docNameForPath:e=>e5(f,e)});function _n(e,t,n){let r=[];function i(e){for(let a of sc(e,{withFileTypes:!0})){let o=K(e,a.name),s=G(f,o).split(Js).join(`/`);if(!L2(s)){if(a.isDirectory()){if(Ce?.isDirExcluded(s))continue;i(o);continue}!a.isFile()||BU(s)||Ce?.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 vn(e,t){return Zt(async()=>oH(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async n=>{if(!I)throw new AY;let r=Ws(t)?t:`${t}${Ws(e)}`;if(L2(e)||L2(r))throw new kY(`.ok and .git are reserved directories.`);if(Ce?.isPathIgnored(r))throw new OY(`Destination asset is excluded by the project content config.`);let i=Ze(f,`folder`,e),a=Ze(f,`folder`,r);if(i===a)return{renamedAssets:[],rewrittenDocs:[]};if(n5(e,r))throw new OY(`Case-only renames are not supported.`);if(!q(i))throw new TY(`asset`,`Asset does not exist.`);if(q(a))throw new EY;if(!fc(i).isFile())throw new DY(`asset`,`Source path is not an asset file.`);let o=[{fromPath:e,toPath:r}],s=pn(o);n.setAttribute(`rename.rewrite_candidates`,s.length),mn(s.map(e=>e.docName)),await o5(ue,i,a)||a5(i,a);let{rewrittenDocs:c,derivedMutations:l}=await hn(s,o);return await Lt(l,`asset-rename`),nt?.(`files`),c.sort((e,t)=>e.docName.localeCompare(t.docName)),n.setAttribute(`rename.rewrite_count`,c.length),{renamedAssets:o,rewrittenDocs:c}}))}async function yn(e,n){return Zt(async()=>oH(`rename.executeDocumentToFileRewrites`,{attributes:{"rename.kind":`asset`,"rename.transition":`document-to-file`}},async r=>{if(!I)throw new AY;if(!BU(e)||BU(n))throw new OY(`Document-to-file rename requires a markdown source and non-markdown destination.`);let i=UU(e);if(_W(i)||vW(i))throw new kY(`Reserved document names cannot be renamed.`);if(L2(e)||L2(n))throw new kY(`.ok and .git are reserved directories.`);if(Ce?.isPathIgnored(n))throw new OY(`Destination file is excluded by the project content config.`);let a=Ze(f,`folder`,e),o=Ze(f,`folder`,n);if(a===o)return{renamedAssets:[],rewrittenDocs:[]};if(n5(e,n))throw new OY(`Case-only renames are not supported.`);if(!q(a))throw new TY(`file`);if(q(o))throw new EY;if(!fc(a).isFile())throw new DY(`file`,`Source path is not a document file.`);let s=se.findByDocName(i);if(s!==void 0)throw new UJ({file:s.file});let c=[{fromPath:e,toPath:n}],l=pn(c).filter(e=>e.docName!==i);r.setAttribute(`rename.rewrite_candidates`,l.length),mn(l.map(e=>e.docName)),await v$(t,u,i,f,void 0,de?.(),se,Mt),je&&!_W(i)&&!vW(i)&&je.setDeleted(i);let d=(await en([i],`renamed`)).get(i),p=typeof d==`string`?d:J(a,`utf-8`),m=hEt({fromPath:e,toPath:n,affectedDocs:[{from:i,to:i}],snapshots:[{docName:i,content:p}],cleanupPaths:[n]}),h=[];return await EEt(ue??f,m,async()=>{i5(a,p),oX(a,XW(p)),await o5(ue,a,o)||a5(a,o),ZU(i),y?.({kind:`delete`,path:a,docName:i});let e=fc(o,{bigint:!0});y?.({kind:`file-create`,path:o,relativePath:n,size:Number(e.size),modifiedTs:Cl(e),inode:Sl(e)});let t=await hn(l,c);h=t.rewrittenDocs,await Lt([{kind:`delete`,documentName:i},...t.derivedMutations],`document-to-file-rename`),nt?.(`files`)}),h.sort((e,t)=>e.docName.localeCompare(t.docName)),r.setAttribute(`rename.rewrite_count`,h.length),{renamedAssets:c,rewrittenDocs:h}}))}async function bn(e,n,r,i){return Zt(async()=>oH(`rename.executeRewrites`,{attributes:{"rename.kind":r}},async o=>{if(!I)throw new AY;let s=Ze(f,r,e),c=Ze(f,r,n);if(s===c)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!q(s))throw new TY(r);if(q(c)&&!ODt(s,c))throw new EY;let l=fc(s);if(r===`file`&&!l.isFile()||r===`folder`&&!l.isDirectory())throw new DY(r);r===`folder`&&(kG(s,f),a?.(s));let d=r===`folder`?_n(s,e,n):[];o.setAttribute(`rename.affected_assets`,d.length);let p=(r===`file`?[e5(f,e)]:gn(s)).map(t=>({from:t,to:r===`file`?e5(f,n):yDt(t,r,e,n)}));if(o.setAttribute(`rename.affected_docs`,p.length),p.length===0){let t=pn(d);mn(t.map(e=>e.docName)),r===`folder`&&(await o5(ue,s,c)||a5(s,c),dt(e,n),nt?.(`files`));let{rewrittenDocs:i,derivedMutations:a}=await hn(t,d);return await Lt(a,`asset-only-folder-rename`),i.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:[],renamedAssets:d,rewrittenDocs:i}}let m=jnt(p),h=ynt(new Set([...g().keys(),...await I.getIndexedDocNames(),...m.keys()]),m),_=p.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),v=new Set;for(let{from:e}of p)for(let t of await I.getBacklinks(e))m.has(t.source)||v.add(t.source);let b=new Map,x=new Set,S=await I.getRenameSourceInventory(),C=new Set(S.map(({docName:e})=>e)),w=new Set(u.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=>xnt(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=Ze(f,`file`,e);return t===(await Dc(n)).mtimeMs?null:e}catch(t){if(N0(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)||TW(e)||Nt(e))continue;let n;try{n=Ze(f,`file`,e)}catch(e){if(N0(e))continue;throw e}if(!q(n))continue;await v$(t,u,e,f,void 0,de?.(),se,Mt);let r=sn(e);typeof r==`string`&&Snt(an(r).body,e,h).rewrites>0&&(v.add(e),b.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(b.has(e))continue;if(!m.has(e)){let t=Ze(f,`file`,e);if(!q(t)){O.push(e);continue}}await v$(t,u,e,f,void 0,de?.(),se,Mt);let n=sn(e);typeof n==`string`?(b.set(e,n),m.has(e)||x.add(e)):m.has(e)||O.push(e)}if(d.length>0){let e=[...g().keys()].sort((e,t)=>e.localeCompare(t));for(let t of e){let e=b.get(t)??sn(t);typeof e==`string`&&dn(e,t,m.get(t)??t,d,h).rewrites!==0&&(b.has(t)||b.set(t,e),D.add(t),m.has(t)||x.add(t))}}mn(D);for(let{from:e}of p)if(typeof b.get(e)!=`string`)throw new Ant(e);let k=hEt({fromPath:e,toPath:n,affectedDocs:[...p],snapshots:rn([...b.keys()],b)}),j=[],M=[...x].sort((e,t)=>e.localeCompare(t)),P=[];return await EEt(ue??f,k,async()=>{for(let e of O)P.push({kind:`delete`,documentName:e});for(let e of M){let t=u.documents.get(e),n=t?ln(e,d,h):dn(b.get(e)??``,e,e,d,h);n.rewrites>0&&(cn(e,n.markdown,t),j.push({docName:e,rewrites:n.rewrites})),P.push({kind:`link-rewrite`,documentName:e,markdown:n.markdown})}if(je)for(let{from:e,to:t}of p)_W(e)||vW(e)||(je.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let a=Ze(f,r,e),o=Ze(f,r,n),s=p.map(({to:e})=>De?.(e));await o5(ue,a,o)||a5(a,o);for(let e of s)e?.();r===`folder`&&dt(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`);sH(`rename.appendLog`,{attributes:{"rename.kind":r}},e=>{let t=i?.actor,n=I8({moves:p,kind:r,branch:N?.()??`main`,writer:t?{writerId:t.writerId,displayName:t.displayName,colorSeed:t.colorSeed,actor:t.actorMetadata}:{writerId:DJ.id,displayName:DJ.name,colorSeed:DJ.id},shadow:A?.current,notices:Ye});e.setAttribute(`rename.entries_appended`,n)});let l=r===`file`&&BU(n)?Ws(n):null;for(let{from:e,to:t}of p){let n=BU(e)?Ws(e):qU(e);ZU(e),KU(t,l??n)}let g=[...p].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:n}of g){let r=Ze(f,`file`,e),i=Ze(f,`file`,n),a=dn(c.get(e)??b.get(e)??J(i,`utf-8`),e,n,d,h);t.setReconciledBase(n,a.markdown),nn([{fromDocName:e,toDocName:n}],new Map([[e,a.markdown]])),y?.({kind:`rename`,oldPath:r,newPath:i,oldDocName:e,newDocName:n,content:a.markdown}),P.push({kind:`rename`,oldDocumentName:e,newDocumentName:n,markdown:a.markdown});try{await mt.renameDoc(e,n)}catch(t){U8.warn({err:t,fromDocName:e,toDocName:n},`[comments] cover-sheet rename failed`)}a.rewrites>0&&j.push({docName:n,rewrites:a.rewrites})}if(await Lt(P,`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`)}),nt?.(`files`),j.sort((e,t)=>e.docName.localeCompare(t.docName)),o.setAttribute(`rename.rewrite_count`,j.length),{renamed:_,renamedAssets:d,rewrittenDocs:j}}))}function xn(e){let t=N1e(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 Sn(e){return{principalId:fe?.()?.id,agentType:AU(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Cn(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 wn(e){return{value:e.value}}function Tn(e,t=!1){e.kind===`value`&&(T0e(),e.truncatedFrom!==void 0&&!t&&E0e())}function En(e,t,n,r){if(n.length!==0)switch(e.kind){case`agent`:{let r=e.summary.kind===`value`,i=r?e.summary:EQ(t),a=Cn(i),o=r||!a.response?a.response:wn(a.response);for(let t=0;t<n.length;t++){let{docName:r,subject:i}=n[t];t$(r,e.writerId,e.displayName,e.colorSeed,i,e.actor,t===0?a.stored:void 0)}aW(),Tn(i,!r);for(let{docName:e}of n)Ct(e,`rename-path`);return o}case`principal`:{let t=Cn(e.summary);for(let r=0;r<n.length;r++){let{docName:i,subject:a}=n[r];t$(i,e.writerId,e.displayName,e.colorSeed,a,e.actor,r===0?t.stored:void 0)}Tn(e.summary,!1);for(let{docName:e}of n)Ct(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 Dn(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 On(e,t,n,r){if(e.kind!==`agent`&&e.kind!==`principal`)return;let i=Cn(e.summary);t$(t,e.writerId,e.displayName,e.colorSeed,n,e.actor,i.stored,r)}let kn=null;function An(){Ce&&(kn!==null&&clearTimeout(kn),kn=setTimeout(()=>{kn=null,Ce?.rebuildIgnorePatterns().catch(()=>{})},12e4))}function jn(){$e(),Ce?.refreshInPlaceSkillDirs(),An()}function B(){jn(),nt?.(`files`)}let Mn=Promise.resolve();function Nn(e){$e(),Mn=Mn.then(async()=>{await Pn(e)}).catch(()=>{})}async function Pn(e){if(!M)return`unavailable`;try{return await M(),`flushed`}catch(t){return U8.warn({context:e,err:t},`[${e}] flushContributors failed; attribution stays queued for the next flush`),`failed`}}let Fn=ZQ(eie,async(n,r,i)=>{try{let n=Y8(i.docName,r,`agent-write`);if(n===null)return;let a=St(n),{agentId:o,suppliedWriterId:s,agentName:c,colorSeed:l,clientName:p,clientVersion:m,label:h}=xn(i);if(_W(a)||vW(a)){Q(r,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`agent-write`,extensions:{...yG[`urn:ok:error:reserved-doc-name`]}});return}let g=EQ(i.summary),_=await d.getSession(a,o,{displayName:c,colorSeed:l,clientName:p}),v=await v$(t,u,a,f,e.resolveEmbed,de?.(),se,Mt),y=new Date().toISOString(),b=typeof i.content==`string`?i.content:`Hello from the agent! ${y}`,{response:x,stored:S}=Cn(g),C,w;try{let n=ar(p),r=lo[n]??rt(l??o);ie?.setPresence(o,{displayName:c,icon:n,color:r,currentDoc:a,mode:`writing`,ts:Date.now()}),C=$Q(_.dc.document.getText(`source`),o,_.origin,l,p),mQ(_.dc.document,`${b}\n`,`append`),_.dc.document.transact(()=>{let t=gQ(_.dc.document);hQ(_.dc.document,`${b}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:a}:void 0,void 0,pQ(_),s);let n=Xc(t,gQ(_.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),w=$W(_.dc.document),t.markAgentWriteStore(a),t$(a,o,c,l,void 0,Sn({clientName:p,clientVersion:m,label:h}),S),aW(),Tn(g)}finally{C?.(),ie?.touchMode(o,`idle`)}let T=await kt(a,w);if(T?.kind===`failure`){c5(r,T.failure,`agent-write`);return}if(T?.kind===`stale-external-write`){jt(r,`agent-write`,a);return}wt(a,`agent-write`),ae?.();let E=h$(v),D={timestamp:y,...x?{summary:x}:{},...E?{warnings:[E]}:{}},O=SG(v,T);if(O.outcome===`both-kept`){F$(r,`agent-write`,D,O);return}$(r,200,Cte,{...D,...O},{handler:`agent-write`})}catch(e){if(e instanceof UJ){WJ(r,e,`agent-write`,se.findByDocName(UU(e.file)));return}if(e instanceof mZ){hZ(r,e,`agent-write`);return}if(e instanceof vQ){P$(r,e,`agent-write`);return}U8.error({err:e,requestId:HK(n)},`[agent-write] handler failed`),Q(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),In=ZQ(mre,async(n,r,i)=>{try{let a=ze(),{agentId:o,suppliedWriterId:s,agentName:c,colorSeed:l,clientName:p,clientVersion:m,label:h}=xn(i),g=new Date().toISOString(),_=(e,t,n,r,i,a)=>({status:`error`,docName:e,error:{type:t,title:n,...r===void 0?{}:{detail:r},...i},...a}),v=(e,t)=>{if(t instanceof qK)return o5e(t,`agent-write-batch`),_(e,KK,r5e,a5e,{retryAfterSeconds:3},yG[`urn:ok:error:concurrent-overwrite-refused`]);if(t instanceof UJ){console.warn(JSON.stringify({event:`doc-in-conflict-write-refused`,handler:`agent-write-batch`,"doc.name":e}));let{detail:t,...n}=ott(se.findByDocName(e));return{status:`error`,docName:e,error:{type:`urn:ok:error:doc-in-conflict`,title:`Document is in conflict.`,detail:t,...n},...yG[`urn:ok:error:doc-in-conflict`]}}return t instanceof mZ?(Nit(t,`agent-write-batch`),_(e,`urn:ok:error:frontmatter-malformed`,`Frontmatter YAML is malformed.`,Mit(t),void 0,yG[`urn:ok:error:frontmatter-malformed`])):t instanceof vQ?_(e,Vct,Hct,Uct,Wct,yG[`urn:ok:error:too-many-agent-sessions`]):(U8.error({err:t,docName:e,requestId:HK(n)},`[agent-write-batch] entry failed`),_(e,`urn:ok:error:internal-server-error`,`Internal server error.`))},y=Array(i.docs.length),b=[],x=new Map,S=new Map;try{let n=ar(p),r=lo[n]??rt(l??o);ie?.setPresence(o,{displayName:c,icon:n,color:r,currentDoc:St(i.docs[0].docName),mode:`writing`,ts:Date.now()}),await d.withSessions(async n=>{for(let r=0;r<i.docs.length;r++){let a=i.docs[r],d=St(a.docName);if(_W(d)||vW(d)){y[r]=_(d,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,void 0,void 0,yG[`urn:ok:error:reserved-doc-name`]);continue}try{a.extension!==void 0&&!Q8(f,d)&&KU(d,a.extension);let i=EQ(a.summary),{response:g,stored:_}=Cn(i),v=await n(d,o,{displayName:c,colorSeed:l,clientName:p}),y=await v$(t,u,d,f,e.resolveEmbed,de?.(),se,Mt),C=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:d}:void 0,w=await fQ(v.dc.document,a.markdown,a.position??`append`,C),T,E=$Q(v.dc.document.getText(`source`),o,v.origin,l,p);mQ(v.dc.document,a.markdown,a.position??`append`);try{v.dc.document.transact(()=>{let e=gQ(v.dc.document);T=hQ(v.dc.document,a.markdown,a.position??`append`,C,w,pQ(v),s);let t=Xc(e,gQ(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),x.set(d,$W(v.dc.document)),S.set(d,v.dc.document.getText(`source`).toString()),t.markAgentWriteStore(d)}finally{E()}aDt(`agent-write-batch`,T),t$(d,o,c,l,void 0,Sn({clientName:p,clientVersion:m,label:h}),_),aW(),Tn(i);let D=h$(y),O=[...T===void 0?[]:[pZ(T)],...D?[D]:[]];b.push({index:r,docName:d,reconcile:y,summaryResponse:g,warnings:O,diverged:T!==void 0})}catch(e){y[r]=v(d,e)}}let r=new Map,d=new Map;for(let e of b){if(r.has(e.docName))continue;let t=await kt(e.docName,x.get(e.docName));d.set(e.docName,t),t?.kind===`failure`?r.set(e.docName,qDt(t.failure)):t?.kind===`stale-external-write`?r.set(e.docName,KDt(At(e.docName))):r.set(e.docName,void 0)}let g=await Ft(b.filter(e=>r.get(e.docName)===void 0).map(e=>e.docName)),C;for(let e of b){let t=r.get(e.docName),n=d.get(e.docName)??null;if(t!==void 0){y[e.index]={status:`error`,docName:e.docName,error:t,...n?.kind===`failure`?bG(n.failure):yG[`urn:ok:error:stale-external-write`]};continue}let i=u.documents.get(e.docName)?.getText(`source`).toString()??S.get(e.docName)??``;Yt(e.docName,i);let o=g(i,e.docName,a.suppressLogLinkAdvisories),s=[...e.warnings,...o.warnings];y[e.index]={status:`written`,docName:e.docName,...SG(e.reconcile,n,e.diverged),...e.summaryResponse?{summary:e.summaryResponse}:{},...s.length>0?{warnings:s}:{},...o.links},C=e.docName}C!==void 0&&(re?.setFocus(o,{agentName:c,currentDoc:C,writeKind:`write`,ts:Date.now()}),ae?.())})}finally{ie?.touchMode(o,`idle`)}let C=y.map((e,t)=>e??_(i.docs[t].docName,`urn:ok:error:internal-server-error`,`Internal server error.`)),w=C.filter(e=>e.status===`written`).length;$(r,200,Rre,{timestamp:g,results:C,written:w,failed:C.length-w},{handler:`agent-write-batch`})}catch(e){U8.error({err:e,requestId:HK(n)},`[agent-write-batch] handler failed`),Q(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-batch`,cause:e})}},{handler:`agent-write-batch`,method:`POST`}),Ln=KEt(),Rn=j_t({contentDir:f,assertContentPath:e.assertContentPath,isPathIgnored:e=>Ce?.isPathIgnored(e)??!1,getAttachmentFolderPath:_,resolveTrackedFile:E}),zn=M_t({assertContentSubtree:a,contentDir:f,resolveContentEntryPath:Ze,docNameForPath:e=>e5(f,e),docNameToRelativePath:XU,listManagedDocNamesUnderFolder:e=>gn(e),listAffectedDocNames:(e,t,n)=>vDt(e,t,n),getFileIndex:g,conflictFileForDocName:e=>se.findByDocName(e)?.file??null,captureAndCloseDocuments:en,markRecentlyRemoved:je?e=>je.setDeleted(e):void 0,mutateFileIndexDelete:y?({path:e,docName:t})=>y({kind:`delete`,path:e,docName:t}):void 0,removeFolderIndexEntries:ut,upsertFolderIndexPathSegments:lt,deleteDerivedDocumentsBestEffort:Ht,invalidateReferencedAssetsCache:ot,signalFiles:()=>nt?.(`files`),nextAvailableDuplicateDocName:e=>wDt(f,e),nextAvailableDuplicateFolderPath:e=>TDt(f,e),resolveDuplicateDocPath:(t,n)=>{let r=CDt(f,t,n);return e.assertContentPath?.(r),r},collectMarkdownCopies:e=>EDt(f,e),collectFolderPaths:e=>DDt(f,e),contentFilter:Ce??void 0,unmarkRecentlyRemoved:je?e=>je.delete(e):void 0,mutateFileIndexCreate:y?({path:e,docName:t,content:n})=>{Ee?.(t),y({kind:`create`,path:e,docName:t,content:n})}:void 0,recordDerivedDocumentBestEffort:z,recordDerivedMutationsBestEffort:Lt});function Bn(e,t,n,r,i){let a=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(a.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return Q(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let o=K(f),s=a===``?o:K(o,a);if(s!==o&&!s.startsWith(`${o}${Js}`))return Q(t,400,`urn:ok:error:path-escape`,`Path escapes content directory.`,{handler:r}),null;let c=K(s,`.ok`);if(bK(c).kind===`symlink`)return Q(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=K(s,`.ok`,`templates`);if(i===`ok-and-templates`&&bK(l).kind===`symlink`)return Q(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{yK(c,o),i===`ok-and-templates`&&yK(l,o)}catch(e){return SK(e)?(Q(t,400,`urn:ok:error:path-escape`,`Path escapes content directory.`,{handler:r,cause:e}),null):(Q(t,500,`urn:ok:error:internal-server-error`,`Failed to validate path.`,{handler:r,cause:e}),null)}return{folderRel:G(o,s).split(Js).join(`/`),resolvedContentDir:o}}function Vn(e,t,n){let r=se.findByDocName(e);return r!==void 0&&(WJ(n,new UJ({file:r.file}),t,r),!0)}let V=e=>{let{body:t}=an(e);return{frontmatter:he(e)??{},body:t}};function Hn(e){return!!e&&e.length<=64&&We.test(e)}function Un(e,t,n,r){return Hn(e)?!0:(Q(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 Wn(e,t,n){let r=_ie.safeParse(e??`project`);return r.success?r.data:(Q(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let Gn=pe??_c(),Kn=GEt({contentDir:f,skillsHome:Gn,effectiveInstallMode:Xn});function qn(e){return K(e===`global`?Gn:f,`.ok`,ya)}function Jn(e,t,n){let r=K(qn(e),t);if(e===`global`){if(n!==void 0){let e=z1(Gn).find(e=>e.name===t&&e.hosts.includes(n));return e?K(Gn,e.dir):null}let e=V1(Gn,t);return e===null?q(W(r,`SKILL.md`))?r:null:e}let i=R1(f).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?K(f,i.dir):n===void 0&&q(W(r,`SKILL.md`))?r:null}function Yn(e,t){let n=e.searchParams;return DQ({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`?ue:Gn;return(r?ddt(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function Zn(e){let t=Jn(`project`,e);return t?G(f,t).split(Js).join(`/`):`${pa}/${e}`}function Qn(e,t,n,r){let i=[],a=null,o=a0(n),s=[...o0(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=K(e,...o.split(`/`),t);q(K(s,`SKILL.md`))&&(i.push(n),(r===void 0?a===null:n===r)&&(a=s))}if(a===null)return null;let c=K(a,`SKILL.md`);return{dir:a,skillMd:c,hosts:i,relPath:G(e,c).split(/[\\/]/).filter(Boolean).join(`/`)}}function er(e){let t=UMe(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 tr(e,t,n){if(!FU(t))return null;let r=Qn(e,t,n);if(!r)return null;let i=uO(r.dir)?.contentHash??``,a;try{a=fc(r.skillMd).mtime.toISOString()}catch{a=new Date(0).toISOString()}return{source:Ci,skill:t,contentHash:i,autoUpdate:!1,importedAt:a}}function nr(e,t){return tt(t).get(e)?.contentHash??null}function rr(e,t,n){let r=tt(t).get(e);if(!r)return null;try{if(cc(n)!==cc(r.home))return null}catch{return null}return{name:r.plugin,marketplace:r.marketplace,provider:r.provider,...r.repositoryUrl?{url:r.repositoryUrl}:{}}}function ir(e,t,n){let r=tt(t).get(e);if(!r)return null;if(n!==void 0)try{if(cc(n)===cc(r.home))return null}catch{}let i;try{i=fc(W(r.home,`SKILL.md`)).mtime.toISOString()}catch(e){U8.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 or(e,t){let n=IU.find(t=>NU[t]===e);if(n===void 0||t!==void 0&&LU[n]!==(t===`global`?`user`:`project`))return null;try{let e=zU(n,{checkDesktop:!0}),t=K(e,`SKILL.md`);return q(t)?t:null}catch(t){return U8.warn({name:e,err:t},`[skills] bundle asset dir unresolved for built-in ${e}`),null}}function sr(e,t,n){let r=Qn(e,t,n),i=r?.skillMd??or(t);if(i===null)return null;let a;try{let{frontmatter:e}=V(J(i,`utf-8`));typeof e.description==`string`&&(a=e.description)}catch{}let o=tr(e,t,n),s=uO(U(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:Hte(s)}:{},...o?{origin:er(o)}:{}}}function cr(e,t,n){return FU(e)?(Q(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 lr(e,t){return G(t===`global`?Gn:f,e).split(/[\\/]/).filter(Boolean).join(`/`)}function ur(e){return e===`global`?Gn:ue}function dr(e,t,n,r){let i=n===`project`?f:Gn;if(r.purge!==void 0){v0(t,e,o0(n),a0(n));for(let e of kut(i,n,t,r.purge.contentHash))AH(e,{recursive:!0,force:!0});return}if(!q(K(qn(n),t,`SKILL.md`))){let r=(n===`project`?R1(f):z1(Gn)).find(e=>e.name===t);if(r){let i=n===`project`?f:Gn,a=K(i,r.dir),o=K(i,`.agents`,`skills`),s=W(o,t);if(q(o)&&!q(W(s,`SKILL.md`))){let e=!1;try{e=cc(a)===cc(s)}catch{e=!1}e||wH(a,s,{recursive:!0,dereference:!0})}_0({canonicalAbs:q(W(s,`SKILL.md`))?s:a,canonicalHash:r.contentHash,name:t,cwd:e,targets:[...o0(n)],roots:a0(n)});return}}v0(t,e,o0(n),a0(n))}async function fr(e,t,n,r={}){return dr(e,t,n,r),await K1(e,t)!==null}function pr(e,t){let n=[];if(!q(e))return{skills:n,truncated:!1};let r;try{r=sc(e,{withFileTypes:!0})}catch(r){return Y(`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()||!We.test(a.name))continue;if(n.length>=500){i=!0;break}let r=K(e,a.name,`SKILL.md`);if(!q(r))continue;let o;try{let{frontmatter:e}=V(J(r,`utf-8`));typeof e.description==`string`&&(o=e.description)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:lr(r,t),absolutePath:r})}return{skills:n,truncated:i}}function mr(e,t,n){let r=e===`project`?f:Gn,i=Jn(e,t,n);return{root:i===null?qn(e):U(i),dirRel:i===null?`.ok/skills/${t}`:G(r,i).split(Js).join(`/`),realDir:i}}function hr(e,t){return uO(K(e,t))?.contentHash}async function gr(e,t){let n=A?.current;if(!(!n||!e))try{let r=yJ(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
2185
2185
  `).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,...on([t]))).trim().length>0,o=await i();return o!==void 0&&t!==void 0&&!await a(o,t)&&(await Pn(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let _r=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function vr(e){try{let t=ur(e.scope);if(!t)return;let n=i0(t);if(n.length===0)return;let r=f0(K(e.skillsRoot,e.name),e.name,t,n,`copy`,a0(e.scope));if(r.length===0)return;await G1(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){U8.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}let yr=Udt({contentDir:f,skillsHome:Gn,...ue===void 0?{}:{projectDir:ue},resolveSkillDirForRead:Jn,parseFrontmatterDoc:V,attributeOkArtifactWrite:On,commitOkArtifactWrite:Pn,shadowHeadSha:gr,artifactWriterId:_r,effectiveInstallMode:Xn,signalFiles:()=>nt?.(`files`)}),br=Ydt({contentDir:f,skillsHome:Gn,...ue===void 0?{}:{projectDir:ue},legacyStoreRoot:pa,effectiveSkillRoot:mr,parseFrontmatterDoc:V,attributeOkArtifactWrite:On,commitOkArtifactWrite:Pn,shadowHeadSha:gr,artifactWriterId:_r,skillArtifactKey:e=>Dn(`skill`,``,e),captureAndCloseDocuments:en,projectImportedSkillCopy:vr,signalFiles:()=>nt?.(`files`)}),xr=ZQ(Be,async(e,t,n)=>{try{if(!Un(n.name,t,`skill-uninstall`))return;let e=ur(n.scope);if(!e){Q(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 fr(e,n.name,n.scope);nt?.(`files`),$(t,200,$n,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){Q(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,...oDt(e)===void 0?{}:{detail:oDt(e)},cause:e})}},{handler:`skill-uninstall`,method:`POST`}),Sr=WEt({contentDir:f,projectDir:ue,getAllFilesIndex:v,getFileIndexGeneration:b,getSearchMaxEntries:mDt,semanticSearch:Pe,getSemanticSimilarityFloor:Fe,ready:Ae,getProjectSkillsRoot:()=>qn(`project`),parseFrontmatterDoc:V});Sr.prewarm();let Cr=0;function wr(){Cr+=1,nt?.(`lint-config`)}let Tr=()=>Lft({lintConfigEpoch:Cr,projectConfigEpoch:Ve(),activeBranch:t.getActiveBranch(),localTargetGeneration:I?.readLocalTargetGeneration?.()??0});async function Er(e,t,n){let r=Re?.()??ca;try{let i=U0(f,r,{docName:t,projectDir:ue??f,onProblem:e=>U8.warn({problem:e,docName:t},`[lint] native config problem`)}),a=await Se(e,i,t),o=[];if(I?.isReady()&&n.links!==`off`&&!wW(t)){let i=I;o=await bt.run(`lint-links`,async()=>{await zt(t,e,`lint-validation`);let a=Omt({projectDir:ue??f,contentDir:f,baseConfig:r,derivedDocumentIndex:i,linkPolicy:n,admittedDocNames:It,docFilePathFor:e=>$8(f,e),localTargetInventory:Gt}).find(e=>e.id===`links`);return a?(await a.run({targetPath:$8(f,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 U8.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Dr(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=G0({projectDir:ue??f,contentDir:f});return Sft(t.schemas,n)}let Or={"/api/skill/uninstall":xr,"/api/agent-write":Fn,"/api/agent-write-batch":In},kr=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`]),Ar={resolve(e){let t=Or[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:{template:`/api/*`}},isMutating:e=>kr.has(e)},jr=kst({log:U8,policy:o,ephemeral:He,table:Ar,dispatchMutation:i}),Mr=rxt({hocuspocus:u,derivedDocumentIndex:I,getFileIndex:g,isSafeDocName:s5,readPageTitleForDocName:ht,readPageTitleForLinkedDocName:gt,readFrontmatterMetadataForLinkedDocName:yt,collectAdmittedDocNames:It,resolveAlias:St,respondToDerivedIndexQueryFailure:Vt}),Nr=LSt({hocuspocus:u,agentPresenceBroadcaster:ie,isAllowedWorkspaceHostHeader:c,log:U8}),Pr=Vgt({contentDir:f,projectDir:ue,ephemeral:He,log:U8,ready:Ae,serverInstanceId:h,getDiskAckSVs:ee,getCollabClientCount:te,getConfigDiagnostics:Je,acpRegistry:ye,loadAcpCustomAgents:be,acpHarnessAvailability:xe,isRoutePeerAdmitted:l,isAllowedWorkspaceHostHeader:c,checkLocalOpSecurity:s,getPrincipal:fe,semanticSearch:Pe,readSemanticProviderConfig:Le,embeddingsSecretsFile:Ie,getFileIndex:g,shadowRef:A,getCurrentBranch:N,getReportedBranch:P,installedAgentsCache:ft}),Fr=ixt({hocuspocus:u,contentDir:f,projectDir:ue,contentFilter:Ce,isSafeDocName:s5,resolveDocFilePath:$8,isValidRelativeContentPath:L4,streamShowAllEntries:J8,getLinterBaseConfig:Re,getLinkAdvisoryPolicy:ze,derivedDocumentIndex:I,collectAdmittedDocNames:It,unmatchedGlobProblems:Dr,readAuditGeneration:Tr,localTargetInventory:Gt}),Ir=_xt({conflicts:se,contentDir:f,projectDir:ue,signalLintConfigChanged:wr,getLinterBaseConfig:Re,unmatchedGlobProblems:Dr,signalChannel:nt,requireNonEmptyDocName:Y8,resolveAlias:St,getPrincipal:fe,resolveDocFilePath:$8,summaryResponseFields:Cn,sessionManager:d,options:e,agentPresenceBroadcaster:ie,buildAgentActor:Sn,flushDiskAndDetectOutcome:kt,markAgentWriteStore:e=>t.markAgentWriteStore(e),respondPersistenceFailure:c5,respondStaleExternalWrite:jt,flushDocToDisk:wt,log:U8}),Lr=xbt({contentRoot:F,log:U8,shadowRef:A,flushGitCommit:j,commitOkArtifactWrite:Pn,getCurrentBranch:N,validateFolderRel:Bn,safeDocPath:W8,docTreePathCandidates:sDt}),Rr=Pdt({validateSkillName:Un,parseSkillScope:Wn,skillsHome:Gn,projectDir:ue,resolveBuiltinSkillDir:Qn,resolveSkillDirForRead:Jn,resolveSkillsRoot:qn,getPrincipal:fe,rejectReservedBuiltinSkill:cr,contentDir:f,checkSkillDocConflictGate:Vn,extractAgentIdentity:xn,sessionManager:d,flushDiskAndDetectOutcome:kt,markAgentWriteStore:e=>t.markAgentWriteStore(e),respondStaleExternalWrite:jt,respondPersistenceFailure:c5,attributeOkArtifactWrite:On,okArtifactKey:Dn,commitOkArtifactWrite:Pn,signalChannel:nt,extractActorIdentityFromQuery:Yn,captureAndCloseDocuments:en,derivedDocumentIndex:I,log:U8,recordDerivedMutationsBestEffort:Lt}),zr=eft({projectDir:ue,getPrincipal:fe,skillImportService:yr,bumpSkillsCatalogGen:$e,contentFilter:Ce,scheduleDeferredIgnoreRebuild:An,signalChannel:nt,parseSkillScope:Wn}),Br=Mdt({validateSkillName:Un,parseSkillScope:Wn,skillsHome:Gn,projectDir:ue,resolveBuiltinSkillDir:Qn,parseFrontmatterDoc:V,resolveSkillDirForRead:Jn,skillRelPath:lr,derivedDocumentIndex:I,contentFilter:Ce,bumpSkillsCatalogGen:$e,settleSkillCatalog:B,invalidateSkillCatalog:jn,scheduleDeferredIgnoreRebuild:An,recordDerivedDocumentBestEffort:z,getPrincipal:fe,rejectReservedBuiltinSkill:cr,contentDir:f,attributeOkArtifactWrite:On,scheduleOkArtifactFlush:Nn,signalChannel:nt,checkSkillDocConflictGate:Vn,extractAgentIdentity:xn,sessionManager:d,flushDiskAndDetectOutcome:kt,markAgentWriteStore:e=>t.markAgentWriteStore(e),respondStaleExternalWrite:jt,respondPersistenceFailure:c5,okArtifactKey:Dn,resolveSkillsRoot:qn,extractActorIdentityFromQuery:Yn,captureAndCloseDocuments:en,log:U8,commitOkArtifactWrite:Pn,skillInstallBase:ur,uninstallSkillFromHostDirs:fr,renameTrackedPathInGit:o5,renamePathOnDisk:a5,localSkillHash:hr,shadowHeadSha:gr,artifactWriterId:_r,checkLocalOpSecurity:s,effectiveSkillRoot:mr}),Vr=sft({contentDir:f,projectDir:ue,skillsHome:Gn,contentFilter:Ce,catalogCache:Qe,resolveSkillsRoot:qn,resolveSkillsList:pr,skillOriginFor:er,localSkillHash:hr,effectiveInstallMode:Xn,pluginSelfIdentity:rr,synthBuiltinLockEntry:tr,synthPluginLockEntry:ir,pluginUpstreamHash:nr,builtinSkillListEntry:sr,indexedSkillContentPath:lDt,healUnservableSkillAdmission:uDt}),Hr=ECt({contentDir:f,projectDir:ue,homeDirOverride:pe,skillsHome:Gn,isSafeDocName:s5,commentService:mt,enumerateInstalledSkillsCached:et,checkLocalOpSecurity:s}),Ur=RCt({log:U8,skillsHome:Gn,projectDir:ue,contentDir:f,resolveSkillDirForRead:Jn}),Wr=pEt({contentDir:f,projectDir:ue,skillsHome:Gn,homeDirOverride:pe,savedThemeLockTimeoutMs:ve,ephemeral:He,log:U8,signalChannel:nt,searchService:Sr,linkPreviewFetch:Ue,getLinkPreviewsEnabled:Ge,declaredGitHubHosts:Xe,resolveGitHubToken:Ke,githubReferenceFetch:qe,getGeneratedIndexSettingsStatus:p,setGeneratedIndexEnabled:m}),Gr=dht({commentService:mt,getPrincipal:fe,signalChannel:nt}),Kr=Hgt({docNotices:e.docNotices??null,getBranch:()=>N?.()??`main`,checkLocalOpSecurity:s}),qr=zCt({projectDir:ue,contentDir:f,getPrincipal:fe,hocuspocus:u,log:U8,checkLocalOpSecurity:s,getSyncEngine:oe,conflicts:se,serializeDoc:Me,setBatchInProgress:ce}),Jr=TCt({declaredGitHubHosts:Xe,projectDir:ue,contentDir:f,log:U8,checkLocalOpSecurity:s,localOpCliArgs:le,localOpGuard:it,getSyncEngine:oe,resolveCredentialConfig:R,toGitRelativePath:t5}),Yr=byt({projectDir:ue,contentDir:f,contentFilter:Ce,getFileIndex:g,checkLocalOpSecurity:s,getSyncEngine:oe,getPrincipal:fe,resolveCredentialConfig:R}),Xr=ISt({declaredGitHubHosts:Xe,projectDir:ue,contentDir:f,log:U8,checkLocalOpSecurity:s,localOpCliArgs:le,localOpGuard:it,getSyncEngine:oe,authStreamHeartbeatMs:L,embeddingsSecretsFile:Ie,readSemanticProviderConfig:Le,semanticSearch:Pe}),Zr=I_t({contentDir:f,projectDir:ue,log:U8,getPrincipal:fe,contentFilter:Ce,signalChannel:nt,conflicts:se,commitOkArtifactWrite:Pn,fileOpsService:zn,assetService:Rn,extractAgentIdentity:xn,recordDerivedDocumentBestEffort:z,invalidateReferencedAssetsCache:ot,listManagedDocNamesUnderFolderFromDisk:gn,resolveContentEntryPath:Ze,docNameForFileOperationPath:e5,withPeriod:Qt,toManagedRenamePublicError:$t,attributeRenameWriteToActor:En,renameAttributionCounter:eDt,_performAssetRename:vn,_performDocumentToFileRename:yn,_performManagedRenameForDocs:bn,isValidRelativeContentPath:L4}),Qr=_Ct({contentDir:f,checkLocalOpSecurity:s}),$r=awt({contentDir:f,log:U8,checkLocalOpSecurity:s,installedAgentsCache:ft,agentIntegrations:_e}),ei=ayt({contentDir:f,projectDir:ue,ephemeral:He,log:U8,hocuspocus:u,sessionManager:d,getPrincipal:fe,signalChannel:nt,conflicts:se,recentlyRemovedDocs:je,isSafeDocName:s5,resolveAlias:St,resolveContentEntryPath:Ze,validateFolderRel:Bn,extractAgentIdentity:xn,extractActorIdentityFromQuery:Yn,okArtifactKey:Dn,attributeOkArtifactWrite:On,scheduleOkArtifactFlush:Nn,flushDiskAndDetectOutcome:kt,markAgentWriteStore:e=>t.markAgentWriteStore(e),respondPersistenceFailure:c5,respondStaleExternalWrite:jt,registerWrittenDocInFileIndex:Yt,captureAndCloseDocuments:en,captureNamespaceMove:De,renameTrackedPathInGit:o5,renamePathOnDisk:a5,splitContentPath:Z8,mutateFileIndex:y}),ti=rht({assetService:Rn,log:U8}),ni=Pst({log:U8,checkLocalOpSecurity:s,getPrincipal:fe,homeDirOverride:pe,projectDir:ue,agentIntegrations:_e}),ri=dut({checkLocalOpSecurity:s}),ii=Ugt({refreshDocumentsFromDisk:e.refreshDocumentsFromDisk}),ai=tft({resolveSkillsRoot:qn,validateSkillName:Un,projectDir:ue,skillInstallBase:ur,contentDir:f,skillsHome:Gn,shippedBundleSkillMd:or,flushDiskAndDetectOutcome:kt,respondStaleExternalWrite:jt,respondPersistenceFailure:c5,skillInstallOps:Kn,skillPlacementOps:Ln,signalChannel:nt,bumpSkillsCatalogGen:$e,contentFilter:Ce,scheduleDeferredIgnoreRebuild:An,effectiveInstallMode:Xn,log:U8}),oi=fft({synthPluginLockEntry:ir,synthBuiltinLockEntry:tr,isValidSkillName:Hn,getPrincipal:fe,validateSkillName:Un,rejectReservedBuiltinSkill:cr,shadowRef:A,contentDir:f,contentRoot:F,projectDir:ue,skillsHome:Gn,projectSkillDirRel:Zn,attributeOkArtifactWrite:On,okArtifactKey:Dn,commitOkArtifactWrite:Pn,signalChannel:nt,bumpSkillsCatalogGen:$e,contentFilter:Ce,scheduleDeferredIgnoreRebuild:An,effectiveSkillRoot:mr,skillReimportService:br,localSkillHash:hr,resolveSkillsRoot:qn,projectImportedSkillCopy:vr}),si=pft({contentDir:f,projectDir:ue,contentFilter:Ce,validateSkillName:Un,indexedSkillContentPath:lDt,bumpSkillsCatalogGen:$e,signalChannel:nt}),ci=Qct({conflicts:se,getLinkAdvisoryPolicy:ze,respondStaleExternalWrite:jt,requireNonEmptyDocName:Y8,resolveAlias:St,extractAgentIdentity:xn,docNameExistsWithAnySupportedExtension:Q8,findMissingDocCandidates:e=>gft(e,g()),contentDir:f,summaryResponseFields:Cn,sessionManager:d,durabilityState:t,hocuspocus:u,options:e,getBridgeLossReporter:de,mergeHistory:Mt,agentPresenceBroadcaster:ie,recordContentDivergenceGate:aDt,buildAgentActor:Sn,countNormalizedSummary:Tn,flushDiskAndDetectOutcome:kt,respondPersistenceFailure:c5,flushDocToDisk:wt,agentFocusBroadcaster:re,onAgentWrite:ae,computeOrphanHints:xt,registerWrittenDocInFileIndex:Yt,prepareWriteLinkAdvisory:Ft,buildReconcileWarning:h$,computeLintViolations:Er,log:U8,flushDocToGit:Ct,flushGitCommit:j,commitOkArtifactWrite:Pn,isSafeDocName:s5,shadowRef:A,getPrincipal:fe,contentRoot:F,safeDocPath:W8,getCurrentBranch:N,docTreePathCandidates:sDt,stripDefaultPathTruncation:wn,renameAttributionCounter:eDt}),li=rlt({agentPresence:ie,resetSettingsForTest:me,settleDiskEvents:ge,recentlyRemovedDocs:je,conflicts:se,durabilityState:t,resolveAlias:St,contentDir:f,log:U8,sessionManager:d,hocuspocus:u,forceUnloadDocument:Te,derivedDocumentIndex:I,contentFilter:Ce,bumpSkillsCatalogGen:$e,signalChannel:nt,flushGitCommit:async()=>{await Mn,await j?.()},rescanFiles:D}),ui=[ti,ni,ci,...k?[li]:[],si,oi,ai,ri,zr,Rr,Mr,Nr,at,ii,Pr,Fr,Ir,Lr,Br,Vr,Hr,Ur,Wr,Gr,qr,Kr,Jr,Yr,Xr,Zr,Qr,$r,ei],di=ui.flatMap(e=>[...e.paths]);Sbt(di,Or);let eee=ui.map(e=>kst({log:U8,policy:o,ephemeral:He,table:e.table,dispatchMutation:i})),tee={paths:di,dispatch:async(e,t)=>{for(let n of eee)if(await n(e,t))return!0;return!1}},fi=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`]),pi=ui.map(e=>e.table),mi=e=>{for(let t of pi){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 fi)if(Or[e]===void 0&&mi(e)===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);let hi=new Map([[JK,ci.acpDocumentWrite]]);return{priority:100,async onRequest({request:e,response:t}){await jr(e,t)},nativeApi:tee,localApi:bxt({resolve:e=>{let t=hi.get(e);if(t!==void 0)return(n,r)=>i(async()=>t(n,r),e);if(!fi.has(e))return;let n=Or[e];return n===void 0?mi(e):Ar.isMutating(e)?(t,r)=>i(()=>n(t,r),e):n}}),shutdownLocalOps:async()=>{n=!0;let e=(await Promise.allSettled([...r,Xr.shutdown()])).at(-1);if(e?.status===`rejected`)throw e.reason}}}function l5(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 ZDt(e,t){let n;try{n=encodeURI(e)}catch{return null}let r=t.indexOf(`?`),i=`/${n}${r===-1?``:t.slice(r)}`;return l5(i)===`/${e}`?i:null}function QDt(e,t){let n=K(e),r=Ks(W(`${n}${Js}`,l5(t)));if(!r.startsWith(`${n}${Js}`))return!1;try{let e=cc(n),t=cc(r);return fc(t).isFile()&&jG(t,e)&&!_K(W(e,G(n,r)),t,e)}catch{return!1}}function $Dt(e){let{contentDir:t,contentFilter:n,contentSirv:r,inlineExtensions:i,assetExtensions:a,blocklistExtensions:o,ingressPolicy:s,resolveTrackedFile:c}=e,l=e=>Ws(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=ZDt(i,r);return s!==null&&QDt(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=l5(f)===`/${p}`&&L4(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&&!NQ(_,s)){Q(c,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!PQ(e.headers.host,s)){Q(c,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:jQ});return}let v=m&&QDt(t,f),y=!m||v||g?null:u(p,f),b=y?.ext??h;c.setHeader(`X-Content-Type-Options`,`nosniff`);let x=S_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=Aa.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 u5(e){let t=e?.code;return typeof t==`string`?t:void 0}function eOt(e){let t;try{t=sc(e.contentDir,{withFileTypes:!0})}catch(t){let n=u5(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&HU(n.name,be)&&e.basenameIndex.add(n.name)}async function d5(e){let t=TG(e.contentDir,{root:`content`,component:`asset-walk`}),n=new Set;async function r(i){let a;try{a=await Tc(i,{withFileTypes:!0})}catch(t){let n=u5(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=W(i,o.name),s=JW(G(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await Sc(a,{bigint:!0})}catch(t){let n=u5(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Ec(a)}catch(t){let n=u5(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!YW(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Dc(i,{bigint:!0})}catch(t){let n=u5(t);n!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,n,i);continue}if(n.has(Sl(o)))continue;n.add(Sl(o)),o.isDirectory()?await r(i):o.isFile()&&HU(a,yt)&&!e.contentFilter?.isPathIgnored(s)&&e.basenameIndex.add(s);continue}if(c.isDirectory()){if(n.has(Sl(c)))continue;n.add(Sl(c)),await r(a);continue}c.isFile()&&HU(a,yt)&&!e.contentFilter?.isPathIgnored(s)&&e.basenameIndex.add(s)}}await r(t)}const tOt=H({principalId:V().optional(),tabSessionId:V().optional(),expectedServerInstanceId:V().optional(),expectedBranch:V().optional(),expectedDocLineageEpoch:V().optional(),clientProtocolVersion:Qn().optional(),clientRuntimeVersion:V().optional(),clientKind:V().optional()}).loose(),nOt=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function rOt(e){return nOt.includes(e)}function iOt(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function aOt(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!rOt(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 f5=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=iOt(e,this.payload)}};function p5(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=tOt.safeParse(t);return n.success?n.data:void 0}var oOt=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};function sOt(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 cOt(e,t){let n=RJ(e);try{rc(n,{recursive:!0}),mc(W(n,nse),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=lx(e);rc(U(n),{recursive:!0,mode:448});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`};mc(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const m5=new Map;let lOt=!1;function uOt(e,t){try{let n=sOt(e,t);for(let e of m5.keys())cOt(e,n)}catch{}}function dOt(e){m5.set(e,(m5.get(e)??0)+1),lOt||(lOt=!0,process.on(`uncaughtExceptionMonitor`,uOt));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=m5.get(e)??0;n<=1?m5.delete(e):m5.set(e,n-1)}}}function fOt(e){let t=$se(e,({err:e,root:t,file:n},r)=>Y(`shell-csp`).warn({err:e,root:t,file:n},r));return(e,n,r,i)=>{let a=t({file:i,stats:r});a!==void 0&&e.setHeader(`Content-Security-Policy`,a)}}function h5(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 pOt(e){let t=e.scheduler??lie,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??h5(e.httpServer),f=d.subscribe(l);return c(),{detach:()=>{o||(o=!0,f(),u&&d.detach(),s())}}}function g5(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mOt(e){if(!q(e))return{};let t;try{let n=J(e,`utf-8`);t=(0,nl.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(!g5(t))return{};let n=t.telemetry;if(!g5(n))return{};let r=n.localSink;return g5(r)?r:{}}function hOt(e){return typeof e==`boolean`?e:void 0}function gOt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function _Ot(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function _5(e){if(g5(e))return gOt(e.maxBytes)}function vOt(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=mOt(yl(`project`,e.projectDir)),n=mOt(yl(`project-local`,e.projectDir));if((hOt(n.enabled)??hOt(t.enabled)??!0)===!1)return null;let r=_5(n.spans)??_5(t.spans)??52428800,i=_5(n.logs)??_5(t.logs)??26214400,a=_Ot(n.attributeDenylist)??_Ot(t.attributeDenylist)??Ea;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}const v5=`https://json-schema.org/draft/2020-12/schema`,yOt=`tools/list`,bOt=[`items`,`contains`,`not`,`propertyNames`,`if`,`then`,`else`,`additionalProperties`,`unevaluatedProperties`,`additionalItems`,`unevaluatedItems`,`contentSchema`],xOt=[`allOf`,`anyOf`,`oneOf`,`prefixItems`,`items`],SOt=[`properties`,`patternProperties`,`dependentSchemas`,`$defs`,`definitions`];function COt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function y5(e){if(!COt(e))return;let{type:t}=e;Array.isArray(t)&&t.length>1&&e.anyOf===void 0&&(delete e.type,e.anyOf=t.map(e=>({type:e})));for(let t of bOt)y5(e[t]);for(let t of xOt){let n=e[t];if(Array.isArray(n))for(let e of n)y5(e)}for(let t of SOt){let n=e[t];if(COt(n))for(let e of Object.values(n))y5(e)}}function wOt(e){let t=e;if(t.__jsonSchemaDialectInstalled===!0)return;let n=e.server._requestHandlers?.get(yOt);if(typeof n!=`function`){console.warn(`[json-schema-dialect] No ${yOt} 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(ez,async(e,t)=>{let r=await n(e,t);for(let e of r.tools??[])e.inputSchema&&(y5(e.inputSchema),e.inputSchema.$schema=v5),e.outputSchema&&(y5(e.outputSchema),e.outputSchema.$schema=v5);return r}),t.__jsonSchemaDialectInstalled=!0}function TOt(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||!EOt(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=ln(i.error);throw new cz(vR.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function EOt(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const b5=2e3,DOt=2e3,OOt=[`-iTCP`,`-sTCP:LISTEN`,`-nP`],kOt=[/^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 AOt(e){return kOt.some(t=>t.test(e))}function jOt(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 Gs(e)?e:null}catch{return null}}function MOt(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&&Gs(a)?a:null}function NOt(e){let t=[];for(let n of e.split(`
2186
2186
  `)){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)&&AOt(a)&&t.push({pid:o,command:a})}return t}function POt(e,t,n){return new Promise((r,i)=>{let a=Rc(e,t,DW({...EW,timeout:b5,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(`
2187
2187
  `);for(;r!==-1;)t(n.slice(0,r)),n=n.slice(r+1),r=n.indexOf(`
@@ -2214,7 +2214,7 @@ tags: [lore, history]
2214
2214
  `);function uMt(e){let t=e.split(`
2215
2215
  `),n=t[t.length-1]===``?t.length-1:t.length;if(n<=500&&e.length<=sMt)return{text:e,truncated:!1,omittedLines:0};let r=Math.min(n,500),i=0,a=0;for(let e=0;e<r;e++){let n=t[e];if(i+=n.length+1,i>sMt)break;a++}let o=t.slice(0,a).join(`
2216
2216
  `),s=n-a;return{text:`${o}\n<truncated: ${s} more lines — re-run with a more-specific query>`,truncated:!0,omittedLines:s}}function dMt(e){let t=[];for(let n of e)if(n.command===`cat`)for(let e of n.args.slice(1))e.startsWith(`-`)||cMt.test(e)&&t.push(e);return t}function fMt(e){for(let t=1;t<e.length;t++){let n=e[t],r=n.match(/^--lines=(\d+)$/);if(r)return Number(r[1]);if(n===`--lines`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}if(n===`-n`&&t+1<e.length){let n=Number(e[t+1]);if(Number.isFinite(n))return n}let i=n.match(/^-n(\d+)$/);if(i)return Number(i[1]);let a=n.match(/^-(\d+)$/);if(a)return Number(a[1])}return 10}function pMt(e,t){if(e.length<2)return null;let n=e[e.length-1];if(n.command!==`head`&&n.command!==`tail`)return null;let r=fMt(n.args),i=t.split(`
2217
- `),a=i[i.length-1]===``?i.length-1:i.length;if(a<r)return null;let o=i.slice(0,a),s=new Set(o.map(e=>{let t=e.indexOf(`:`);return t>0?e.slice(0,t):e})).size,c=e.slice(0,-1).map(e=>e.command).join(` | `);return{banner:`Output hit \`${n.command} -${r}\` cap (${a} lines, ${s} unique file${s===1?``:`s`}). The \`${c}\` stage may have had more matches that never reached stdout. For existence checks across many files, prefer \`grep -rl PATTERN <dir>\` (list files only, no head). For enumeration, drop the \`| ${n.command}\` or widen the cap.`}}function mMt(e){return e.type===`directory`}function hMt(e){let t=[e.title?`**${e.title}** (${e.path}/)`:`**${e.path}/** (directory)`];if(e.description&&t.push(e.description),e.tags&&e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.templates_available&&e.templates_available.length>0){let n=e.templates_available.map(e=>e.description?`${e.name} — ${e.description} (${e.scope})`:`${e.name} (${e.scope})`).join(`, `);t.push(`templates: ${n}`)}e.schemas_applicable&&e.schemas_applicable.length>0&&t.push(`schemas: ${e.schemas_applicable.join(`, `)}`);let n=[];if(n.push(e.recursiveMdCount>e.directMdCount?`${e.directMdCount} md file${e.directMdCount===1?``:`s`} here (${e.recursiveMdCount} in tree)`:`${e.directMdCount} md file${e.directMdCount===1?``:`s`}`),e.childDirCount>0&&n.push(`${e.childDirCount} subdir${e.childDirCount===1?``:`s`}`),t.push(n.join(`, `)),e.mostRecentMd){let n=e.mostRecentMd.updatedAt?`, ${e.mostRecentMd.updatedAt.slice(0,10)}`:``;t.push(`most recent: ${e.mostRecentMd.title??e.mostRecentMd.path} (${e.mostRecentMd.path}${n})`)}if(e.commentCount!==void 0&&e.commentCount>0){let n=`⚠ ${e.commentCount} unresolved comment${e.commentCount===1?``:`s`} in tree`;if(e.commentedDocs&&e.commentedDocs.length>0){let t=e.commentedDocs.map(e=>`${e.docName} (${e.count})`).join(`, `),r=e.commentedDocs.reduce((e,t)=>e+t.count,0);n+=`: ${t}${r<e.commentCount?`, …`:``}`}t.push(n)}return e.truncated&&t.push(`scan truncated`),`- ${t.join(` — `)}`}function gMt(e){let t=[e.state===`orphaned`?`passage gone`:null,e.queued?`queued`:null].filter(e=>e!==null),n=t.length>0?` [${t.join(`, `)}]`:``;return e.quote===``?`"${e.body}"${n}`:`"${e.body}" on “${e.quote}”${n}`}function _Mt(e){let t=[`**${e.title??e.path}** (${e.path})`];e.description&&t.push(e.description),e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.graphRole&&t.push(`graph: ${e.graphRole}`);let n=typeof e.frontmatter.status==`string`?e.frontmatter.status:null,r=typeof e.frontmatter.type==`string`?e.frontmatter.type:null;if(n&&t.push(`status: ${n}`),r&&t.push(`type: ${r}`),e.schemas_applicable&&e.schemas_applicable.length>0&&t.push(`schemas: ${e.schemas_applicable.join(`, `)}`),e.commentCount!==null&&e.commentCount>0){let n=`⚠ ${e.commentCount} unresolved comment${e.commentCount===1?``:`s`}`;if(e.comments&&e.comments.length>0){let t=e.comments.slice(0,3).map(gMt);n+=`: ${t.join(`; `)}${e.comments.length>3?`; …`:``}`}t.push(n)}if(e.backlinkCount!==null){let n=`backlinks: ${e.backlinkCount}`;if(e.backlinks&&e.backlinks.length>0){let t=e.backlinks.slice(0,5).map(e=>e.source);n+=` (${t.join(`, `)}${e.backlinks.length>5?`, …`:``})`}t.push(n)}if(e.forwardLinkCount!==null){let n=`forward links: ${e.forwardLinkCount}`;if(e.forwardLinks&&e.forwardLinks.length>0){let t=e.forwardLinks.slice(0,5).map(e=>e.kind===`doc`?e.docName:e.url);n+=` (${t.join(`, `)}${e.forwardLinks.length>5?`, …`:``})`}t.push(n)}if(e.history&&e.history.length>0){let n=e.history.map(e=>{let t=e.writerClassification===`agent`?`agent: ${e.writerName}`:e.writerClassification===`principal`?`human: ${e.writerName}`:`${e.writerClassification}: ${e.writerName}`;return`${e.hash.slice(0,7)} [${t}] ${e.message}`});t.push(`OK edits: ${n.join(` · `)}`)}if(e.projectHistory&&e.projectHistory.length>0){let n=e.projectHistory.map(e=>`${e.hash.slice(0,7)} ${e.authorName}: ${e.subject}`);t.push(`commits: ${n.join(` · `)}`)}return`- ${t.join(` — `)}`}function vMt(e,t,n,r){let i=null;for(let t=e.length-1;t>=0;t--){let n=e[t],r=n.command;if(r===`ls`||r===`cat`){i=n;break}if((r===`head`||r===`tail`)&&p7(n).length>0){i=n;break}}if(!i)return``;let a=p7(i);if(i.command===`ls`){let e=a[a.length-1];if(!e||e===`.`)return``;let n=e.replace(/\/+/g,`/`);if(n.startsWith(`./`)&&(n=n.slice(2)),n.endsWith(`/`)&&(n=n.slice(0,-1)),!n)return``;let i=r(n);return t.has(i)?`${i}/:\n`:``}let o=a.filter(e=>d7(e)&&n.has(r(e)));return o.length===1?`==> ${r(o[0])} <==\n`:``}function yMt(e){if(e.length===0)return``;let t=[``,`### Referenced files`,``];for(let n of e)t.push(mMt(n)?hMt(n):_Mt(n));return t.join(`
2217
+ `),a=i[i.length-1]===``?i.length-1:i.length;if(a<r)return null;let o=i.slice(0,a),s=new Set(o.map(e=>{let t=e.indexOf(`:`);return t>0?e.slice(0,t):e})).size,c=e.slice(0,-1).map(e=>e.command).join(` | `);return{banner:`Output hit \`${n.command} -${r}\` cap (${a} lines, ${s} unique file${s===1?``:`s`}). The \`${c}\` stage may have had more matches that never reached stdout. For existence checks across many files, prefer \`grep -rl PATTERN <dir>\` (list files only, no head). For enumeration, drop the \`| ${n.command}\` or widen the cap.`}}function mMt(e){return e.type===`directory`}function hMt(e){let t=[e.title?`**${e.title}** (${e.path}/)`:`**${e.path}/** (directory)`];if(e.description&&t.push(e.description),e.tags&&e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.templates_available&&e.templates_available.length>0){let n=e.templates_available.map(e=>e.description?`${e.name} — ${e.description} (${e.scope})`:`${e.name} (${e.scope})`).join(`, `);t.push(`templates: ${n}`)}e.schemas_applicable&&e.schemas_applicable.length>0&&t.push(`schemas: ${e.schemas_applicable.join(`, `)}`);let n=[];if(n.push(e.recursiveMdCount>e.directMdCount?`${e.directMdCount} md file${e.directMdCount===1?``:`s`} here (${e.recursiveMdCount} in tree)`:`${e.directMdCount} md file${e.directMdCount===1?``:`s`}`),e.childDirCount>0&&n.push(`${e.childDirCount} subdir${e.childDirCount===1?``:`s`}`),t.push(n.join(`, `)),e.mostRecentMd){let n=e.mostRecentMd.updatedAt?`, ${e.mostRecentMd.updatedAt.slice(0,10)}`:``;t.push(`most recent: ${e.mostRecentMd.title??e.mostRecentMd.path} (${e.mostRecentMd.path}${n})`)}if(e.commentCount!==void 0&&e.commentCount>0){let n=`⚠ ${e.commentCount} unresolved comment${e.commentCount===1?``:`s`} in tree`;if(e.commentedDocs&&e.commentedDocs.length>0){let t=e.commentedDocs.map(e=>`${e.docName} (${e.count})`).join(`, `),r=e.commentedDocs.reduce((e,t)=>e+t.count,0);n+=`: ${t}${r<e.commentCount?`, …`:``}`}t.push(n)}return e.truncated&&t.push(`scan truncated`),`- ${t.join(` — `)}`}function gMt(e){let t=[e.state===`orphaned`?`passage gone`:null,e.queued?`queued`:null].filter(e=>e!==null),n=t.length>0?` [${t.join(`, `)}]`:``;return e.quote===``?`"${e.body}"${n}`:`"${e.body}" on “${e.quote}”${n}`}function _Mt(e){let t=[`**${e.title??e.path}** (${e.path})`];e.description&&t.push(e.description),e.tags.length>0&&t.push(`tags: ${e.tags.join(`, `)}`),e.graphRole&&t.push(`graph: ${e.graphRole}`);let n=typeof e.frontmatter.status==`string`?e.frontmatter.status:null,r=typeof e.frontmatter.type==`string`?e.frontmatter.type:null;if(n&&t.push(`status: ${n}`),r&&t.push(`type: ${r}`),e.schemas_applicable&&e.schemas_applicable.length>0&&t.push(`schemas: ${e.schemas_applicable.join(`, `)}`),e.commentCount!==null&&e.commentCount>0){let n=`⚠ ${e.commentCount} unresolved comment${e.commentCount===1?``:`s`}`;if(e.comments&&e.comments.length>0){let t=e.comments.slice(0,3).map(gMt),r=e.comments.length-t.length;n+=`: ${t.join(`; `)}${r>0?`; … ${r} more. See \`enrichedPaths[].comments\` for this file or open the document in Open Knowledge and select Comments → This doc.`:``}`}t.push(n)}if(e.backlinkCount!==null){let n=`backlinks: ${e.backlinkCount}`;if(e.backlinks&&e.backlinks.length>0){let t=e.backlinks.slice(0,5).map(e=>e.source);n+=` (${t.join(`, `)}${e.backlinks.length>5?`, …`:``})`}t.push(n)}if(e.forwardLinkCount!==null){let n=`forward links: ${e.forwardLinkCount}`;if(e.forwardLinks&&e.forwardLinks.length>0){let t=e.forwardLinks.slice(0,5).map(e=>e.kind===`doc`?e.docName:e.url);n+=` (${t.join(`, `)}${e.forwardLinks.length>5?`, …`:``})`}t.push(n)}if(e.history&&e.history.length>0){let n=e.history.map(e=>{let t=e.writerClassification===`agent`?`agent: ${e.writerName}`:e.writerClassification===`principal`?`human: ${e.writerName}`:`${e.writerClassification}: ${e.writerName}`;return`${e.hash.slice(0,7)} [${t}] ${e.message}`});t.push(`OK edits: ${n.join(` · `)}`)}if(e.projectHistory&&e.projectHistory.length>0){let n=e.projectHistory.map(e=>`${e.hash.slice(0,7)} ${e.authorName}: ${e.subject}`);t.push(`commits: ${n.join(` · `)}`)}return`- ${t.join(` — `)}`}function vMt(e,t,n,r){let i=null;for(let t=e.length-1;t>=0;t--){let n=e[t],r=n.command;if(r===`ls`||r===`cat`){i=n;break}if((r===`head`||r===`tail`)&&p7(n).length>0){i=n;break}}if(!i)return``;let a=p7(i);if(i.command===`ls`){let e=a[a.length-1];if(!e||e===`.`)return``;let n=e.replace(/\/+/g,`/`);if(n.startsWith(`./`)&&(n=n.slice(2)),n.endsWith(`/`)&&(n=n.slice(0,-1)),!n)return``;let i=r(n);return t.has(i)?`${i}/:\n`:``}let o=a.filter(e=>d7(e)&&n.has(r(e)));return o.length===1?`==> ${r(o[0])} <==\n`:``}function yMt(e){if(e.length===0)return``;let t=[``,`### Referenced files`,``];for(let n of e)t.push(mMt(n)?hMt(n):_Mt(n));return t.join(`
2218
2218
  `)}async function bMt(e,t){let n=[],r=[];return await Promise.all(t.map(async t=>{try{let i=await Dc(K(e,t));i.isDirectory()?r.push(t):i.isFile()&&n.push(t)}catch(e){let n=e.code;n!==`ENOENT`&&n!==`ENOTDIR`&&x7.warn({path:t,code:n},`stat failed for a reported path; dropping it`);return}})),{files:n,dirs:r}}function S7(e,t){return c3(t,{enrichedPaths:[],error:{category:e,message:t}},!0)}function xMt(e,t){return e.map(e=>{let n=t(uAt(e.path));return{...e,previewUrl:n?.url??null,...n?{previewUrlSource:n.source}:{}}})}function SMt(e){return e===null&&x7.warn({},`the engine refused a write without naming the file`),S7(`write_blocked`,`Write operation blocked: the command tried to write ${e===null?`a file`:`'${e}'`}. exec is read-only. For document changes, use the \`write\` or \`edit\` tool.`)}async function CMt(e,t){let n=await f3(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return S7(`shell_construct_blocked`,`exec failed: ${n.error}`);let{cwd:r,executionCwd:i,config:a,url:o}=n,s=xt(Ma(a.contentRules)),c=s.length>0?{contentDir:K(r,a.content.dir),frontmatterSchemas:s}:{},l=i===r?e=>e:e=>G(r,K(i,e)),u=Cjt(e.command);if(`error`in u)return S7(u.error.category,u.error.message);let d=await Ojt(u.stages,i);if(`error`in d)return S7(d.error.category,d.error.message);let f=ijt(d.stages),p=ajt(f),m=[...new Set(rMt(u.stages).map(e=>X4(i,e)).filter(e=>e.ok).map(e=>e.rel))],h=await aMt(i,m),g=Yjt(i),_=``,v=``;try{let e=await Xjt(g,p);if(e.exitCode!==0){let t=qjt(e.stderr);if(t.blocked)return SMt(t.target)}_=e.stdout,v=e.stderr}catch(t){if(t instanceof Jjt)return S7(`output_overflow`,`Output exceeded 16 MB buffer. Narrow the command (e.g., add a more specific grep pattern, use head, restrict the path).`);let n=qjt(t);return n.blocked?SMt(n.target):(x7.warn({err:t,command:e.command},`exec failed`),S7(`shell_construct_blocked`,`exec failed: ${t instanceof Error?t.message:String(t)}`))}let y=await aMt(i,m),b=oMt(h.snapshot,y.snapshot);if(b.changed.length>0)return x7.error({command:e.command,changed:b.changed},`files changed during exec`),S7(`security_invariant_violation`,`Security invariant violated: file(s) in the content directory were modified during a read-only exec call: ${b.changed.join(`, `)}. Either the read-only mount let a write through, or another writer (the live server, a human editor) touched these files at the same time. Logged.`);let x=h.truncated||y.truncated,S=uMt(_),C=Kjt(_,f).filter(e=>X4(i,e).ok).map(l),{files:w,dirs:T}=await bMt(r,C),E=f.length===1&&f[0].command===`cat`&&w.length===1,D=await Promise.all(w.map(e=>zvt(e,{projectDir:r,serverUrl:o,...c},{includeRichFields:E}).catch(()=>({path:e,tags:[],frontmatter:{},backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null,graphRole:null,commentCount:null,comments:null})))),O=await Promise.all(T.map(e=>Uvt(e,1,{projectDir:r,serverUrl:o,...c}).catch(()=>({path:e,type:`directory`,directMdCount:0,recursiveMdCount:0,childDirCount:0,truncated:!1}))));if(!E&&o&&D.length>0){let e=D.map(e=>P3(e.path)),[t,n]=await Promise.all([Mvt(o,e).catch(()=>null),Nvt(o,e).catch(()=>null)]);for(let e of D){let r=P3(e.path),i=t?.get(r);typeof i==`number`&&(e.backlinkCount=i);let a=n?.get(r);typeof a==`number`&&(e.commentCount=a)}}let k=new Map(D.map(e=>[e.path,e])),A=new Map(O.map(e=>[e.path,e])),j=[];for(let e of C){let t=k.get(e);if(t){j.push(t);continue}let n=A.get(e);n&&j.push(n)}let M=dMt(f),N=[];M.length>0&&N.push(`File${M.length>1?`s`:``} ${M.join(`, `)} appear${M.length===1?`s`:``} to be binary (image/PDF/etc.) — exec returns text only (NG8). For binary retrieval, use native Read.`);let P=pMt(f,_);P&&N.push(P.banner),v&&N.push(`stderr: ${v.trim()}`),x&&N.push(`Read-only mutation sweep was partial: the files in scope exceed the ${y7}-file cap, so only the first ${y7} were checked for unexpected writes. Narrow the command to a subdirectory for full sweep coverage.`);let ee=`${N.length>0?`${N.join(`
2219
2219
  `)}\n\n`:``}${vMt(f,A,k,l)+S.text}${yMt(j)}`,{resolve:te}=await V5({config:a,resolveCwd:async()=>r});return c3(ee,{enrichedPaths:xMt(j,te),stdoutTruncated:S.truncated,cwd:i,...N.length>0?{warnings:N}:{}})}function wMt(e,t){e.registerTool(`exec`,{description:lMt,inputSchema:{command:V().describe(`Read-only bash command (allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut; pipes OK)`),cwd:V().optional().describe("Absolute host path to run the command from. Defaults only when the MCP client advertises exactly one root; otherwise pass `cwd` explicitly.")},outputSchema:s3({enrichedPaths:r3.describe("Per-referenced-file metadata: frontmatter, backlink/forward-link counts, unresolved comment threads (`commentCount`, plus `comments` on a single-file read), recent shadow-repo activity, and a route-only previewUrl. Directory entries carry a recursive `commentCount` + `commentedDocs`."),stdoutTruncated:uo().optional().describe(`True when stdout was truncated by the soft cap.`),warnings:Ui(V()).optional().describe(`Tool-level warnings — head/tail truncation, binary detection, stderr, partial mutation-sweep coverage.`),cwd:V().optional().describe(`Absolute directory the command ran in.`),error:H({category:V(),message:V()}).optional().describe(`Present on failure — the error category + message.`)})},async e=>{try{return await CMt(e,t)}catch(e){return S7(`shell_construct_blocked`,`exec handler error: ${e instanceof Error?e.message:String(e)}`)}})}const TMt=[`Get the full browser URL for this project or a document/folder/skill, or an absolute markdown file outside the project. Opening is demand: auto-starts OK under the normal OK_MCP_AUTOSTART gate and waits briefly for UI; cold calls can take seconds. Other tools return route-only previewUrl paths; use this tool for an openable URL, never guess ports or hunt via the OpenKnowledge CLI's ps/status.`,`Choose one: document (extension-less), folder (trailing-slash route), skill:{name,scope?} (project default), or file (absolute .md/.mdx in a loose-file/worktree session). file ignores cwd; other targets use current project. Omit targets for UI root.`,`When YOUR host opens URLs, navigate its embedded browser to url; Claude Code Desktop uses preview_start({url}) then navigate({url}). Only a stdio host without a browser tool should open the URL in the system browser. A CLI without a browser can use the OpenKnowledge CLI's open <doc> for OK Desktop. This tool forces browser access even when Desktop is installed.`,`INSIDE OK's terminal/agent panel, use returned okOpenCommand instead; never paste url in the answer. If no UI is reachable, returns url:null, baseUrl:null, running:false, autoOpen plus state-specific recovery text (autostart disabled, no spawn authority or UI timeout). Follow it.`].join(`
2220
2220
  `),EMt={document:V().optional().describe(`Extension-less doc path to resolve a preview URL for (e.g. "specs/foo/SPEC"). Omit to get the UI root URL.`),folder:V().min(1).optional().describe('Folder path to resolve a folder-route preview URL for (e.g. "specs/foo"); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.'),skill:H({name:V().min(1).regex(We,`Skill name must be lowercase letters, digits, and hyphens only.`).describe(`Skill name (the bundle-dir identity, wherever the skill lives).`),scope:Ri(Vn).optional().describe("Skill scope; defaults to `project`.")}).optional().describe("Skill to resolve an editor preview URL for; returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`."),file:V().optional().describe("Absolute path to a single markdown file to open, including one OUTSIDE any Open Knowledge project. Resolves to the running single-file (or worktree) session whose content directory contains it and returns that session’s `url`. Mutually exclusive with `document` / `folder` / `skill`. When `file` is set, `cwd` is ignored."),cwd:V().optional().describe(Q4)},DMt=s3({url:V().nullable().describe("Browser-reachable URL — the UI base joined with the doc route when `document` is given, else the UI root. `null` when no UI is running."),baseUrl:V().nullable().describe("Browser-reachable origin of the running UI (e.g. `http://localhost:5173`). `null` when no UI is running."),running:uo().describe(`Whether a UI is running for the project.`),autoOpen:uo().describe("User-scoped preview-auto-open preference (`appearance.preview.autoOpen`). When `true`, the agent should route the preview using capability-based routing (in-app browser if available, system browser as fallback). When `false`, the user is managing their own preview view (OK Desktop window, a browser tab they opened, etc.) — the agent must NOT open or refresh any preview UI, and should surface this URL only on direct user ask. Resolved fresh on every call; defaults to `true`."),okOpenCommand:V().nullable().optional().describe("Machine-readable form of the hosted-agent steer: when the calling agent runs inside an OpenKnowledge surface (the desktop app’s built-in terminal, or its in-app agent panel) AND a doc/folder/skill target was given, the exact OpenKnowledge CLI `open` command to run to bring it up for the user. Run it INSTEAD of navigating `url`, and do not paste `url` into your reply — the user is already in the app it points at. `null`/absent in every other context (navigate `url` per your host instead).")});function OMt(){return`The OK server is running but no preview UI is mounted (e.g. it was started with \`--only server\`). Restart it with plain \`${d()} start\` to serve the editor, or open the project in OK Electron.`}function kMt(){return`No OpenKnowledge server is running for this project. Start it with \`${d()} start\` (also starts the preview UI), or open the project in OK Electron.`}function AMt(){try{return gl({absPath:yl(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value.appearance?.preview?.autoOpen??!0}catch(e){return process.stderr.write(`[preview-url] readUserAutoOpen failed: ${e instanceof Error?e.message:String(e)}\n`),!0}}function jMt(e){return`No Open Knowledge session is serving ${e} yet. On a host with a terminal, \`${d()} open ${e}\` starts one; otherwise open ${e} in the OK Desktop app. Then retry.`}function MMt(e){try{let t=N4(e);return t===null||t.port<=0||!Kq(t.pid)?!1:!P4(t)}catch(t){return process.stderr.write(`[preview-url] readServerLock failed at ${e} while checking ui capability: ${t instanceof Error?t.message:String(t)}\n`),!1}}function C7(e){try{let t=N4(e);return t!==null&&t.port>0&&Kq(t.pid)}catch(t){return process.stderr.write(`[preview-url] readServerLock failed at ${e} while checking server liveness: ${t instanceof Error?t.message:String(t)}\n`),!1}}function NMt(e){return/^[A-Za-z0-9._/@%+-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function PMt(e,t){e.registerTool(`preview_url`,{description:TMt,inputSchema:EMt,outputSchema:DMt,annotations:{readOnlyHint:!1,idempotentHint:!0}},async e=>{if([e.document,e.folder,e.skill,e.file].filter(e=>e!=null).length>1)return{isError:!0,content:[{type:`text`,text:`Error: document, folder, skill, and file are mutually exclusive — pass at most one.`}]};if(e.file){if(!Gs(e.file))return{isError:!0,content:[{type:`text`,text:`Error: file must be an absolute path (a loose file outside a project has no cwd to anchor a relative path).`}]};let n=(t.resolveUserAutoOpen??AMt)(),r=t.offCwdResolverDeps??ikt(),i=await T5(e.file,r);if(i===null&&t.ensureSingleFileSession&&await t.ensureSingleFileSession(e.file).catch(t=>(process.stderr.write(`[preview-url] ensureSingleFileSession failed for ${e.file}: ${t instanceof Error?t.message:String(t)}\n`),!1))&&(i=await T5(e.file,r)),i!==null){let e=`${i.baseUrl}/#/${F5(i.docName)}`;return c3(`Preview URL: ${e}`,{url:e,baseUrl:i.baseUrl,running:!0,autoOpen:n})}return c3(jMt(e.file),{url:null,baseUrl:null,running:!1,autoOpen:n})}let n=await u3(t.resolveCwd,t.config,e.cwd);if(!n.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${n.error}`}]};let r=zJ(n.cwd),i={lockDir:r},a=n.config.appearance.preview.autoOpen,o=e.document?`#/${F5(e.document)}`:e.folder?`#/${sAt(e.folder)}`:e.skill?`#/${I5(e.skill.scope??`project`,e.skill.name)}`:null,s=d(),c=e.document?`${s} open ${NMt(e.document)}`:e.folder?`${s} open ${NMt(e.folder)}`:e.skill?`${s} open ${e.skill.name} --skill${e.skill.scope===`global`?` --scope global`:``}`:null,l=t.isHostedAgent&&c?`You're running inside OpenKnowledge — run \`${c}\` to bring this up for the user. Don't navigate the URL below, open a browser, or paste the URL into your reply; it's for reference only.\n\n`:``,u=C7(r),f=!1;if(t.serverUrl!==void 0)try{await J_t(t.serverUrl,n.cwd)}catch(e){if(e instanceof oOt)f=!0;else return{isError:!0,content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}]}}let{baseUrl:p}=B5(i);if(p===null&&!u&&C7(r)&&(p=await lAt(i,{timeoutMs:t.uiBindWait?.timeoutMs??3e3,pollIntervalMs:t.uiBindWait?.pollIntervalMs??100})),p===null)return c3(`${l}${C7(r)?MMt(r)?OMt():`The OK server is running but no UI has bound for this project yet. Retry in a few seconds, or open the project in OK Electron.`:`${kMt()}${f?` Auto-start is disabled (OK_MCP_AUTOSTART=0).`:``}`}`,{url:null,baseUrl:null,running:!1,autoOpen:a,okOpenCommand:t.isHostedAgent?c:null});let m=o?`${p}/${o}`:p;return c3(`${l}Preview URL: ${m}`,{url:m,baseUrl:p,running:!0,autoOpen:a,okOpenCommand:t.isHostedAgent?c:null})})}const FMt=H({version:V().describe("40-char commit SHA for this entry — pass to `restore_version({ document, version })`."),timestamp:V().describe(`ISO timestamp of the entry.`),author:V().describe(`Author display name.`),authorEmail:V().describe(`Author email.`),kind:Ri([`checkpoint`,`wip`,`upstream`]).describe(`Entry kind: checkpoint / wip / upstream.`),message:V().describe(`Commit subject (the checkpoint summary, when one was set).`),contributors:r3.describe(`Per-contributor records parsed from the commit (writer id, name, docs, summaries).`),checkpoint:z().nullable().describe(`Checkpoint metadata when this entry is a checkpoint, else null.`)}),IMt=[`Read version history: pass exactly one document, folder or skill. Requires the Hocuspocus server. Returns shadow-repo entries newest first; version is a 40-char SHA for restore_version({document,version}) or restore_version({skill,version}).`,`document accepts optional .md/.mdx. folder lists attributed template/frontmatter activity; empty string is project root. skill is a project-scope name; global skills are unversioned. Optional branch (current default), limit (50 default, 200 max), offset (0), kind (checkpoint/upstream/wip), author and excludeAuthor (name/email).`].join(`
@@ -2320,7 +2320,7 @@ restat-race-injected
2320
2320
  `)){let e=n.startsWith(`credential.username `)?n.slice(20).trim():void 0;e&&(t=e)}return t}function IRt(e,t={}){let n=Fxt(e);if(!n)return{source:`active`};let r=n.host;if(n.login)return{host:r,login:n.login,source:`remote-url`};if(n.transport!==`https`)return{host:r,source:`active`};let i=(t._readCredentialUrlMatch??NRt)(PRt(e),t.cwd??process.cwd()),a=i?Mxt(FRt(i)):void 0;return a?{host:r,login:a,source:`credential-config`}:{host:r,source:`active`}}function LRt(e={}){let t=e.ttlMs??6e4,n=e.now??Date.now,r;return{resolve(i){let a=T6(i);if(!a)return{source:`active`};let o=n();if(r&&r.projectDir===i&&r.url===a&&r.expiresAt>o)return r.account;let s=IRt(a,{cwd:i,_readCredentialUrlMatch:e._readCredentialUrlMatch});return r={projectDir:i,url:a,account:s,expiresAt:o+t},s},invalidate(){r=void 0}}}function RRt(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}const A9=Y(`sync-engine`),zRt=new Set(vRt),j9=/^[0-9a-f]{40}$/i,BRt=Bc(Ic);var M9=class extends Error{constructor(){super(`Sync paused while a Git operation is in progress or the index has unresolved conflicts`),this.name=`GitOperationInProgressError`}},VRt=class extends Error{constructor(e,t){super(`Shareable .ok subtree "${e}" could not be fully enumerated; sync staging aborted`,{cause:t}),this.name=`ShareableOkEnumerationError`}};function HRt(e){let{exitCode:t,stderr:n}=e,r=n??``;return t===128||/^fatal:/m.test(r)&&/not possible to fast-forward/i.test(r)?`divergence`:/^error:/m.test(r)&&/would be overwritten by merge/i.test(r)?`overlay-overlap`:`unknown`}function URt(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason,...e.resolvedLogin===void 0?{}:{resolvedLogin:e.resolvedLogin},...e.declaredLogin===void 0?{}:{declaredLogin:e.declaredLogin},...e.declaredSource===void 0?{}:{declaredSource:e.declaredSource}}:{checkStatus:`unknown`,unknownError:e.error}}function WRt(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason&&e.resolvedLogin===t.resolvedLogin&&e.declaredLogin===t.declaredLogin&&e.declaredSource===t.declaredSource:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}const GRt={syncScope:{pathBase:`content`}},N9={syncScope:{pathBase:`project`}},KRt=/(^|[/\\])index\.lock\b/i,qRt=new Set(gse);function JRt(e){return qRt.has(e)}const YRt=new Set([`diverged-local-commits`,`external-changes-pending`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`]),XRt=[`no-push-permission`,`auth-error`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`],ZRt=new Set(XRt),QRt=new Set([...XRt,`external-changes-pending`]);function P9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function $Rt(e){return new Promise(t=>{setTimeout(t,e)})}function F9(e){let t=Xve(e);if(t.kind!==`repository`)return!1;let n=t.repository.readHead();return n.kind===`branch`&&t.repository.readRef(n.ref).kind===`absent`}function ezt(e){return e.class===`network`&&e.subclass!==`429`&&e.subclass!==`5xx`}function tzt(e){return e>=8?36e5:e>=5?9e5:e>=3?3e5:0}const nzt=12e4;var rzt=class{declaredGitHubHosts;state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;rootOkOutsideContentWalk;pullIntervalSeconds;pushIntervalSeconds;mode;credentialConfig;resolveCredentialConfig;cc1Broadcaster;onStateChange;setBatchInProgress;onAutoDisable;checkpointBeforeStrandedConversion;checkpointBeforeOverlayRestore;beforeRealIndexResetRetry;mcpTomlEditor;detectGh;detectGhAccounts;ghTokenSource;ghAccountResolver;declaredAccountWarnKey;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;get lastRunUtc(){return this.lastPullOkUtc===null?this.lastPushOkUtc:this.lastPushOkUtc===null||this.lastPullOkUtc>this.lastPushOkUtc?this.lastPullOkUtc:this.lastPushOkUtc}lastPullOkUtc=null;lastPushOkUtc=null;pushCycleLanded=!1;fetchOnlyInFlight=!1;lastFetchUtc=null;lastPushedSha=null;lastPullUtc=null;lastPullOutcome=null;consecutivePullFailures=0;consecutivePushFailures=0;pushStreakIsConnectivity=!1;consecutiveContentions=0;ahead=0;behind=0;get conflictCount(){let e=0;for(let t of this.conflicts.list())att(t)&&e++;return e}pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;indexLockHitThisCycle=!1;lastLockNoticeKind;restingIndexLockPause;blockingPaths=[];loggedSymlinkRefusal;refusedSymlinkPaths=[];currentBranch=`main`;cycleInFlight=null;hasRemote=!1;identityUnresolved=!1;statePath;conflicts;unsubscribeConflicts=null;constructor(e){this.projectDir=e.projectDir,this.declaredGitHubHosts=e.declaredGitHubHosts??w6(),this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.rootOkOutsideContentWalk=JW(G(this.contentDir,W(this.projectDir,`.ok`))).startsWith(`..`),this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.mode=e.mode??(e.syncEnabled===!0?`full`:`off`),this.credentialConfig=e.credentialConfig??[],this.resolveCredentialConfig=e.resolveCredentialConfig,this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.checkpointBeforeStrandedConversion=e.checkpointBeforeStrandedConversion,this.checkpointBeforeOverlayRestore=e.checkpointBeforeOverlayRestore,this.beforeRealIndexResetRetry=e._beforeRealIndexResetRetry,this.mcpTomlEditor=e.mcpTomlEditor,this.detectGh=e.detectGh,this.detectGhAccounts=e.detectGhAccounts,this.ghTokenSource=Gwt(e.detectGh),this.ghAccountResolver=LRt({_readCredentialUrlMatch:e._readCredentialUrlMatch}),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??hwt,this.statePath=K(RJ(this.projectDir),`sync-state.json`),this.conflicts=e.conflicts}syncGhTarget(){let e=this.ghAccountResolver.resolve(this.projectDir);return{account:e,host:e.host??`github.com`}}resolveRelayGhToken(){let{account:e,host:t}=this.syncGhTarget(),n=this.ghTokenSource.get(t,e.login);return this.noteDeclaredAccountOutcome(e,t,n),n}noteDeclaredAccountOutcome(e,t,n){let r=e.login,i=n===null?void 0:n.login??this.activeGhLogin(t);if(!(r!==void 0&&(n===null||!C6(i,r)))){this.declaredAccountWarnKey=void 0;return}let a=`${t}\0${r}\0${e.source}\0${n===null?`none`:`fallback`}`;a!==this.declaredAccountWarnKey&&(n===null?A9.warn({host:t,declaredLogin:r,declaredSource:e.source},`[sync] declared GitHub account produced no gh token — git runs with no relayed credential`):A9.warn({host:t,declaredLogin:r,declaredSource:e.source,resolvedLogin:i},`[sync] declared GitHub account did not produce the gh token — using the active account`)),this.declaredAccountWarnKey=a}parkedOnAmbiguousNotFound(){return(this.state===`auth-error`||this.pausedReason===`auth-error`)&&(this.pushErrorCode===`auth-not-found-as-identity`||this.pullErrorCode===`auth-not-found-as-identity`)}activeGhLogin(e){if(this.detectGhAccounts)try{return this.detectGhAccounts(e)?.find(e=>e.active)?.login}catch(t){A9.warn({err:t,host:e},`[sync] detectGhAccounts failed — fallback identity stays unnamed`);return}}gitHandle(e){return rK(this.projectDir,{credentialConfig:this.credentialConfig,gitIndexFile:e,ghToken:this.resolveRelayGhToken()??void 0,timeoutMs:12e4})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflicts.setBranch(e))}catch{}}catch(e){A9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),A9.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){A9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=_x(this.projectDir),n=t?W(t,`MERGE_HEAD`):null,r=n!==null&&q(n);await this.conflicts.pruneMergeNativeAgainstGit();let i=()=>this.conflicts.list().some(e=>e.kind===`merge-native`);if(r&&!i()){A9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){A9.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.subscribeToConflicts(),i()){this.transitionTo(`conflict`),A9.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let a=RRt(this.lastFetchUtc,this.pullIntervalSeconds),o=RRt(this.lastPushOkUtc,this.pushIntervalSeconds);this.schedulePull(a>0?a:void 0),this.schedulePush(o>0?o:void 0),A9.info({branch:this.currentBranch,pullDelayMs:a,pushDelayMs:o},`[sync] started`)}stop(){this.unsubscribeConflicts?.(),this.unsubscribeConflicts=null,this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}setIntervals(e,t){let n=this.pullIntervalSeconds!==e,r=this.pushIntervalSeconds!==t;!n&&!r||(A9.info({pullFrom:this.pullIntervalSeconds,pullTo:e,pushFrom:this.pushIntervalSeconds,pushTo:t},`[sync] cycle intervals changed`),this.pullIntervalSeconds=e,this.pushIntervalSeconds=t,n&&this.pullTimer!==null&&this.schedulePull(),r&&this.pushTimer!==null&&this.schedulePush())}async setMode(e,t=`config`){if(this.mode===e)return;let n=this.mode;if(this.mode=e,A9.info({from:n,to:e,source:t},`[sync] mode changed`),e===`off`){this.cancelScheduledCycles(),await this.drainInFlightCycles(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}e===`follow`&&(await this.drainInFlightCycles(),this.cancelScheduledCycles(),await this.convertStrandedCommitsToOverlay()),this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(0),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}async setEnabled(e){await this.setMode(e?`full`:`off`)}cancelScheduledCycles(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null)}async drainInFlightCycles(){let e=Date.now();for(;this.cycleInFlight!==null;){if(Date.now()-e>3e4){A9.warn({cycleInFlight:this.cycleInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await Vc(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||F9(this.projectDir)?0:this.unpushedCommitCount(this.gitHandle())}async unpushedCommitCount(e){try{let t=await e.git.status();if(t.tracking)return t.ahead}catch{}try{let t=(await e.git.raw([`rev-list`,`--count`,`origin/${this.currentBranch}..HEAD`])).trim(),n=Number.parseInt(t,10);return Number.isFinite(n)?n:0}catch{return 0}}async convertStrandedCommitsToOverlay(){if(!this.hasRemote||F9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){A9.warn({err:e},`[sync] pull-only: could not probe stranded commits — skipping conversion`);return}if(t!==0){try{await this.checkpointBeforeStrandedConversion?.({branch:this.currentBranch,ahead:t})}catch(e){A9.warn({err:e},`[sync] pull-only: stranded-commit checkpoint failed — proceeding`)}try{let n=(await e.git.raw([`merge-base`,`HEAD`,`origin/${this.currentBranch}`])).trim();this.setBatchInProgress?.(!0);try{await nK(()=>e.git.raw([`reset`,`--mixed`,n]))}finally{this.setBatchInProgress?.(!1)}let r=await e.git.status();this.ahead=r.ahead,this.behind=r.behind,this.pausedReason=void 0,A9.info({ahead:t,behind:this.behind},`[sync] pull-only: folded stranded local commits into a working-tree overlay`)}catch(e){this.pausedReason=`diverged-local-commits`,A9.warn({err:e},`[sync] pull-only: stranded-commit conversion failed — leaving branch as-is`)}}}getCredentialConfig(){return this.credentialConfig}async refreshCredentialConfig(){if(this.resolveCredentialConfig)try{this.credentialConfig=await this.resolveCredentialConfig()}catch(e){A9.warn({err:e},`[sync] credential config refresh failed — keeping the previous chain`)}}async notifyCredentialsChanged(){if(await this.refreshCredentialConfig(),this.mode!==`off`&&(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.state===`auth-error`||this.pausedReason===`auth-error`)){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(0),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){if(e===`fetch`){await this.fetchOnly();return}if(this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.consecutiveContentions=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`||this.pausedReason===`git-index-locked`||this.pausedReason===`no-commits-yet`)&&(this.pausedReason=void 0,this.clearPullError()),this.parkedOnAmbiguousNotFound()&&(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()),this.probePushPermissionInternal(`refresh`),e===`pull`){await this.pullOnce();return}if(e===`push`){await this.pushOnce();return}this.state===`dormant`||this.state===`conflict`||this.state===`auth-error`?A9.warn({op:e,state:this.state,mode:this.mode,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):A9.info({op:e,state:this.state},`[sync] trigger(${e}) running`),await this.pushOnce(),await this.pullOnce(`sync`)}async pushOnce(){if(this.mode===`full`){await this.runPushCycle();return}await this.runOneShotPush()}async runOneShotPush(){if(this.cycleInFlight!==null){A9.info({cycleInFlight:this.cycleInFlight},`[sync] one-shot push refused — a cycle is already in flight`);return}if(this.state===`conflict`||this.state===`auth-error`){A9.info({state:this.state},`[sync] one-shot push refused — state=${this.state}`);return}if(this.conflictCount>0){A9.info({conflictCount:this.conflictCount},`[sync] one-shot push refused — unresolved conflicts hold the tree`);return}if(!this.hasRemote){A9.info({hasRemote:!1},`[sync] one-shot push refused — no remote`);return}if(F9(this.projectDir)){this.noteUnbornHeadRefusal();return}this.clearUnbornHeadPause();let e=this.state;this.cycleInFlight=`push`,this.beginIndexLockWatch(`push`);try{await this.doPushCycle(1)}finally{this.cycleInFlight=null,this.settleIndexLockPause(`push`),this.pushCycleLanded&&this.markRun();let t=this.currentState();t!==`conflict`&&t!==`auth-error`&&this.transitionTo(e),this.cc1Broadcaster?.signal(`sync-status`)}}async fetchOnly(){if(!this.hasRemote||F9(this.projectDir)||this.cycleInFlight!==null||this.fetchOnlyInFlight)return!1;this.fetchOnlyInFlight=!0,await this.refreshCredentialConfig();let e=this.gitHandle();try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.scheduleSaveState()}catch(e){return A9.debug({err:e},`[sync] panel-open fetch failed — counts left as they were`),!1}finally{this.fetchOnlyInFlight=!1}return await this.refreshDivergenceCounts(e),this.cc1Broadcaster?.signal(`sync-status`),!0}async refreshDivergenceCounts(e){try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch(e){A9.debug({err:e},`[sync] divergence-count refresh failed — keeping previous counts`)}}async pullOnce(e=`explicit`){let t=this.mode,n=await this.runOneShotPull(e);return A9.info({mode:t,outcome:n},`[sync] one-shot pull complete`),n}async runOneShotPull(e){if(this.cycleInFlight!==null)return A9.info({cycleInFlight:this.cycleInFlight},`[sync] one-shot pull refused — a cycle is already in flight`),this.recordPullOutcome(`refused`);if(this.state===`conflict`)return A9.info({state:this.state},`[sync] one-shot pull refused — the conflict resolver holds the tree`),this.recordPullOutcome(`refused`);if(!this.hasRemote||F9(this.projectDir))return A9.info({hasRemote:this.hasRemote},`[sync] one-shot pull refused — no remote, or no commits yet`),this.recordPullOutcome(`refused`);this.clearUnbornHeadPause();let t=this.mode,n=this.state,r=this.pausedReason;this.cycleInFlight=`pull`,this.beginIndexLockWatch(`pull`);try{return this.recordPullOutcome(await this.doPullCycle(e))}finally{this.cycleInFlight=null,this.settleIndexLockPause(`pull`),t===`off`?(YRt.has(this.pausedReason)||YRt.has(r)||(this.pausedReason=r),this.transitionTo(n)):this.schedulePull()}}recordPullOutcome(e){return this.lastPullUtc=new Date().toISOString(),this.lastPullOutcome=e,(e===`succeeded`||e===`up-to-date`||e===`conflict`)&&(this.lastPullOkUtc=new Date().toISOString(),this.saveStateNow()),this.cc1Broadcaster?.signal(`sync-status`),e}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastRunUtc:this.lastRunUtc,lastPullOkUtc:this.lastPullOkUtc,lastPushOkUtc:this.lastPushOkUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,lastPullUtc:this.lastPullUtc,lastPullOutcome:this.lastPullOutcome,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutivePullFailures,consecutivePushFailures:this.consecutivePushFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.mode!==`off`,syncMode:this.mode,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?Uxt(this.projectDir,this.declaredGitHubHosts):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.blockingPathsForStatus().length>0?{blockingPaths:this.blockingPathsForStatus()}:{},...this.pausedReason===`unsafe-incoming-symlinks`&&this.refusedSymlinkPaths.length>0?{refusedSymlinkPaths:this.refusedSymlinkPaths.slice(0,50)}:{},...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}blockingPathsForStatus(){return this.pausedReason===`external-changes-pending`?this.blockingPaths.slice(0,50):[]}getBlockingPaths(){return this.pausedReason===`external-changes-pending`?[...this.blockingPaths]:[]}async commitBlockingPaths(){let e=this.getBlockingPaths();if(e.length===0)return null;let t=this.gitHandle();return nK(async()=>{await this.applyCommitIdentity(t);try{if(await t.git.raw([`add`,...on(e)]),(await zq(t.git,[`diff`,`--cached`,`--name-only`,...on(e)])).length===0)return null;await t.git.raw([`commit`,`-m`,`Commit local changes before syncing`,...on(e)])}catch(n){throw await t.git.raw([`reset`,...on(e)]).catch(t=>{A9.warn({resetErr:t,files:e.length},`[sync] blocking-path index reset failed; paths may remain staged`)}),A9.error({err:n,files:e.length},`[sync] commit of blocking paths failed`),n}let n=(await t.git.revparse(`HEAD`)).trim();return this.clearBlockingPause(),A9.info({files:e.length},`[sync] committed overlapping paths at user request`),n})}clearBlockingPause(){this.blockingPaths=[],this.pausedReason=void 0,this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await wxt(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async applyCommitIdentity(e){let t=await wxt(this.projectDir),n=t===null;this.identityUnresolved!==n&&(this.identityUnresolved=n,this.cc1Broadcaster?.signal(`sync-status`));let r=t?.name??`OpenKnowledge`,i=t?.email??`sync@open-knowledge.local`;U6e(e,{GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i})}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=E6(this.projectDir,this.declaredGitHubHosts);if(t.kind!==`ok`){let n={checkStatus:`unknown`},r=this.pushPermission;return this.pushPermission=n,this.pausedReason===`no-push-permission`?(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),A9.info({caller:e,originKind:t.kind},`[sync] push-permission pause cleared — origin is no longer a GitHub host`),this.cc1Broadcaster?.signal(`sync-status`)):WRt(r,n)||this.cc1Broadcaster?.signal(`sync-status`),n}this.pushPermissionProbeInFlight=!0,A9.info({caller:e,host:t.host,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let{account:n}=this.syncGhTarget(),r;try{r=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,transport:t.transport,account:n,detectGh:this.detectGh,detectGhAccounts:this.detectGhAccounts,tokenStore:this.tokenStore})}catch(t){A9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),r={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let i=URt(r),a=this.pushPermission;this.pushPermission=i;let o=!1;return i.checkStatus===`denied`&&this.mode===`full`&&this.parkedOnAmbiguousNotFound()&&A9.info({reason:i.deniedReason,caller:e},`[sync] probe denial not applied — repository-not-found park is the more specific diagnosis`),i.checkStatus===`denied`&&this.mode===`full`&&!this.parkedOnAmbiguousNotFound()?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),o=!0,A9.info({reason:i.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):i.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),o=!0,A9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!o&&!WRt(a,i)&&this.cc1Broadcaster?.signal(`sync-status`),i}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,A9.info({mode:this.mode},`[sync] remote detected post-boot — re-evaluating state`),this.mode===`off`?this.transitionTo(`disabled`):(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()))}async probeRemote(){if(!q(W(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return A9.warn({err:e},`[sync] remote detection failed`),!1}}subscribeToConflicts(){this.unsubscribeConflicts===null&&(this.unsubscribeConflicts=this.conflicts.subscribe(()=>{let e=this.conflicts.list().some(e=>e.kind===`merge-native`);if(e&&this.state!==`conflict`){this.transitionTo(`conflict`),this.scheduleSaveState();return}!e&&this.state===`conflict`&&(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush(),this.scheduleSaveState())}))}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflicts.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush(0)))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{A9.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){if(this.mode!==`full`)return;this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??this.effectivePushDelayMs();this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{A9.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=tzt(this.consecutivePullFailures),t=e>0?e/1e3:0;return P9(Math.max(t,this.pullIntervalSeconds))}effectivePushDelayMs(){let e=tzt(this.consecutivePushFailures),t=e>0?e/1e3:0;return P9(Math.max(t,this.pushIntervalSeconds))}logContention(){let e={consecutiveContentions:this.consecutiveContentions,consecutivePushFailures:this.consecutivePushFailures,releasedConnectivityStreak:this.pushStreakIsConnectivity};this.consecutiveContentions>=3?A9.warn(e,`[sync] push repeatedly losing to remote contention — not backing off by design`):A9.info(e,`[sync] push still rejected after retry (contention) — scheduling next push at base cadence`)}bumpFailureCount(e,t=!1){e===`push`?(this.consecutiveContentions=0,this.consecutivePushFailures++,this.pushStreakIsConnectivity=(this.consecutivePushFailures===1||this.pushStreakIsConnectivity)&&t):this.consecutivePullFailures++}async runPullCycle(){if(this.cycleInFlight!==null){this.cycleInFlight===`push`&&this.pullTimer===null&&this.schedulePull();return}if(this.state!==`dormant`&&this.state!==`disabled`&&this.state!==`auth-error`){if(this.state===`conflict`){this.schedulePull();return}if(F9(this.projectDir)){this.schedulePull();return}this.clearUnbornHeadPause(),this.cycleInFlight=`pull`,this.beginIndexLockWatch(`pull`);try{this.recordPullOutcome(await this.doPullCycle(this.mode===`full`?`sync`:`explicit`))}finally{this.cycleInFlight=null,this.settleIndexLockPause(`pull`),this.schedulePull()}}}async doPullCycle(e){if(this.pausedReason===`git-operation-in-progress`)try{await this.assertNoGitOperationInProgress()}catch(e){return e instanceof M9?(this.handleGitOperationRefusal(e,`pull`),`refused`):(this.handleError(T9(e instanceof Error?e:Error(String(e))),`pull`),`error`)}await this.refreshCredentialConfig();let t=this.gitHandle(),n;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!e||e===`HEAD`)return this.transitionTo(`disabled`),this.pausedReason=`detached-head`,A9.warn({},`[sync] detached HEAD — pausing sync`),`refused`;n=e,this.currentBranch=n}catch(e){return this.handleError(T9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.transitionTo(`fetching`);try{await t.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutivePullFailures=0,this.clearPullError(),this.consecutivePushFailures>0&&this.pushStreakIsConnectivity&&(A9.info({cleared:this.consecutivePushFailures},`[sync] fetch succeeded — releasing connectivity-class push backoff`),this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.schedulePush())}catch(e){let t=T9(e instanceof Error?e:Error(String(e)));return this.handleError(t,`pull`),`error`}await this.refreshDivergenceCounts(t);let r=``;if(this.behind>0&&(e===`explicit`?this.ahead===0:this.conflictCount===0))try{r=await this.validateIncomingSymlinks(t,n)}catch(e){return e instanceof dK?(this.handleIncomingSymlinkRefusal(e,`pull`),`refused`):(this.handleError(T9(e instanceof Error?e:Error(String(e))),`pull`),`error`)}else this.behind===0&&this.clearIncomingSymlinkPause();if(this.behind>0&&e===`explicit`){let e=await this.doPullCycleB1(t,n,r);return this.scheduleSaveState(),e}if(this.behind>0&&this.conflictCount===0){this.pausedReason===`diverged-local-commits`&&(this.pausedReason=void 0),this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);let e=!0,i=!0;try{await this.commitDirtyContentFilesToHead(t,`pull`),await this.validateIncomingSymlinks(t,n,r);let a=await this.prepareForMerge(t,n,r);if(!a.proceed)return`refused`;try{await this.applyCommitIdentity(t),await this.mergeIncomingCommit(t,n,r),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.pausedReason===`external-changes-pending`&&this.clearBlockingPause(),this.transitionTo(`idle`)}finally{a.needsStashPop&&(e=await this.popPreMergeStash(t)),i=this.restoreReconciledMcpOverlays(a.reconciled)}if(!e)throw Error(`failed to replay pre-merge working-tree state`);if(!i)throw Error(`failed to restore reconciled MCP overlays`);return await this.persistReconciledMcpEntries(a.reconciled),this.scheduleSaveState(),`succeeded`}catch(t){if(t instanceof M9)return this.handleGitOperationRefusal(t,`pull`),`refused`;if(t instanceof dK)return this.handleIncomingSymlinkRefusal(t,`pull`),`refused`;if(t instanceof pK&&e&&i)return A9.info({branch:n,incoming:r,ref:t.ref},`[sync] incoming commit moved after inspection; re-inspecting next cycle`),this.transitionTo(`idle`),`refused`;let a=t instanceof pK?Error(e?`failed to restore reconciled MCP overlays`:`failed to replay pre-merge working-tree state`):t,o=T9(a instanceof Error?a:Error(String(a)));return o.class===`semantic`&&o.subclass===`merge-conflict`?(await this.handleMergeConflict(),this.state===`conflict`?`conflict`:this.pullError?`error`:`succeeded`):(this.handleError(o,`pull`),`error`)}finally{this.setBatchInProgress?.(!1)}}return this.transitionTo(`idle`),this.scheduleSaveState(),this.behind===0?`up-to-date`:`conflict`}async doPullCycleB1(e,t,n){if(this.transitionTo(`pulling`),this.ahead>0)return this.clearPullError(),this.pausedReason=`diverged-local-commits`,this.transitionTo(`idle`),A9.warn({ahead:this.ahead,behind:this.behind},`[sync] pull-only: local history diverged — not fast-forwardable, skipping cycle`),`refused`;let r,i;try{r=(await e.git.revparse([`HEAD`])).trim();let t=await zq(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await zq(e.git,[`diff`,`--name-only`,`HEAD..${n}`]));i=t.filter(e=>a.has(e))}catch(e){return this.handleError(T9(e instanceof Error?e:Error(String(e))),`pull`),`error`}let a=new Map;for(let e of this.conflicts.list())e.kind===`working-tree`&&a.set(e.file,e);let o;try{o=await this.planOverlapReconciliation(e,n,r,i,a)}catch(e){return this.handleError(T9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.setBatchInProgress?.(!0);try{if(i.length>0){try{await this.checkpointBeforeOverlayRestore?.({branch:t,paths:i.length})}catch(e){A9.warn({err:e,paths:i.length},`[sync] pull-only: overlay checkpoint failed before restore — proceeding`)}try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,...on(i)])}catch(e){return A9.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError(T9(e instanceof Error?e:Error(String(e))),`pull`),`error`}}let r=await this.fastForwardOnly(e,n);if(!r.ok){try{this.applyOverlayPlan(o.mineRestore,o.deletions)}catch(e){return A9.error({err:e,refusal:r.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError(T9(e instanceof Error?e:Error(String(e))),`pull`),`error`}return r.timedOut?(A9.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(T9(Error(`git merge --ff-only timed out after ${nzt}ms`)),`pull`),`error`):(r.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),A9.warn({refusal:r.refusal,stderr:r.stderr.slice(0,200)},`[sync] pull-only: fast-forward refused — skipping cycle`),`refused`)}try{this.applyOverlayPlan(o.writes,o.deletions)}catch(e){return A9.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError(T9(e instanceof Error?e:Error(String(e))),`pull`),`error`}for(let e of o.upserts)this.conflicts.raise(e);for(let e of o.dissolved)this.conflicts.dissolveWorkingTree(e);this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.clearPullError(),this.pausedReason=void 0,this.blockingPaths=[],this.transitionTo(`idle`);let a=await this.countStandingOverlay(e);return A9.info({created:o.newConflicts.length,autoCombined:o.autoCombined.length,autoDissolved:o.dissolved.length,autoRestored:o.autoRestored.length,overlayStock:a},`[sync] pull-only: fast-forwarded to origin tip`),o.newConflicts.length>0?`conflict`:`succeeded`}finally{this.setBatchInProgress?.(!1)}}async fastForwardOnly(e,t){try{return await BRt(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,t],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:nzt}),{ok:!0}}catch(e){let t=e,n=t.killed===!0||t.signal===`SIGTERM`,r=typeof t.code==`number`?t.code:null,i=typeof t.stderr==`string`?t.stderr:e instanceof Error?e.message:String(e);return{ok:!1,refusal:HRt({exitCode:r,stderr:i}),stderr:i,exitCode:r,timedOut:n}}}async planOverlapReconciliation(e,t,n,r,i){let a=[],o=[],s=[],c=[],l=[],u=[],d=[],f=[];for(let p of r){let r=i.get(p),m=r!==void 0;if(!q(W(this.projectDir,p))){try{await e.git.revparse([`${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),A9.warn({err:e,path:p},`[sync] pull-only: unexpected error probing origin for a deleted overlay — deferring reconcile`);continue}s.push(p),m&&l.push(p);continue}if(!this.isContentConflictPath(p)){s.push(p);continue}f.push(p),m&&l.push(p);continue}let h;try{h=J(W(this.projectDir,p))}catch{continue}o.push({path:p,bytes:h});let g=h.toString(`utf-8`),_=null;try{_=await e.git.raw([`show`,`${t}:${p}`])}catch(e){this.classifyRefReadFailure(e)===`error`&&A9.warn({err:e,path:p},`[sync] pull-only: unexpected error reading origin blob — keeping overlay, deferring reconcile`),_=null}if(_!==null&&_===g){m&&l.push(p);continue}if(_!==null&&zRt.has(p)){let t=await this.readMcpGitBlob(e,n,p),r=jRt({target:p,layers:{base:t,head:t,index:await this.readMcpGitBlob(e,``,p),worktree:g,incoming:_},tomlEditor:this.mcpTomlEditor});if(r.kind===`resolved`){r.raw!==_&&a.push({path:p,bytes:Buffer.from(r.raw,`utf8`)}),A9.info({event:`mcp-config-reconcile`,target:p,outcome:`auto-resolved`},`[sync] pull-only: auto-resolved OpenKnowledge MCP entry overlap`);continue}r.kind===`declined`&&A9.warn({event:`mcp-config-reconcile`,target:p,outcome:`declined`,reason:r.reason},`[sync] pull-only: declined OpenKnowledge MCP entry reconciliation`)}if(_===null||!this.isContentConflictPath(p)){a.push({path:p,bytes:h});continue}let v=m?r.baseSha:await this.gitBlobSha(e,`${n}:${p}`),y=v?await this.gitBlobContent(e,v):``,b=On(y,g,_);if(b.clean){a.push({path:p,bytes:Buffer.from(b.merged,`utf-8`)}),d.push(p),m&&l.push(p);continue}a.push({path:p,bytes:h});let x=await this.gitBlobSha(e,`${t}:${p}`);if(x===void 0){A9.warn({path:p},`[sync] pull-only: could not pin origin blob for a collision — keeping overlay, deferring`);continue}c.push({kind:`working-tree`,file:p,theirsSha:x,...v===void 0?{}:{baseSha:v}}),m||u.push(p)}return{writes:a,mineRestore:o,deletions:s,upserts:c,dissolved:l,newConflicts:u,autoCombined:d,autoRestored:f}}applyOverlayPlan(e,t){let n={allowShareableOkArtifact:KG};for(let{path:t,bytes:r}of e)bH(MY(W(this.projectDir,t),this.projectDir,n),r);for(let e of t){let t=W(this.projectDir,e);MY(t,this.projectDir,n);try{EH(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=W(this.projectDir,e),n=JW(G(this.contentDir,t));return!n.startsWith(`..`)&&BU(n)&&!this.contentFilter.isExcluded(n)}async gitBlobSha(e,t){try{return(await e.git.revparse([t])).trim()}catch{return}}classifyRefReadFailure(e){let t=e instanceof Error?e.message:String(e);return/does not exist in|exists on disk, but not in/i.test(t)?`absent`:`error`}async gitBlobContent(e,t){return e.git.raw([`cat-file`,`blob`,t])}async countStandingOverlay(e){try{return(await zq(e.git,[`diff-index`,`--name-only`,`HEAD`])).filter(e=>this.isContentConflictPath(e)).length}catch{return null}}async runPushCycle(){if(this.mode===`full`&&this.state!==`dormant`&&this.state!==`disabled`&&this.state!==`conflict`&&this.state!==`auth-error`){if(this.conflictCount>0){this.schedulePush();return}if(F9(this.projectDir)){this.hasRemote&&this.noteUnbornHeadRefusal(),this.schedulePush();return}if(this.clearUnbornHeadPause(),this.cycleInFlight!==null){this.cycleInFlight===`pull`&&this.pushTimer===null&&this.schedulePush();return}if(this.pausedReason===`unsafe-incoming-symlinks`){this.schedulePush();return}this.cycleInFlight=`push`,this.beginIndexLockWatch(`push`);try{await this.doPushCycle(1)}finally{this.cycleInFlight=null,this.settleIndexLockPause(`push`),this.pushCycleLanded&&this.markRun(),this.schedulePush()}}}async doPushCycle(e=0){this.pushCycleLanded=!1,await this.refreshCredentialConfig();let t=W(bc(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),n=null;try{let e=this.gatherContentFilesSync(),r=await this.snapshotPromisedPaths(),i=new Set;await nK(async()=>{await this.assertNoGitOperationInProgress(),this.transitionTo(`pushing`);try{let r=this.gitHandle(t);if(F9(this.projectDir)){A9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let a;try{a=(await r.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){A9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(T9(e instanceof Error?e:Error(String(e))),`push`);return}await r.git.raw([`read-tree`,a]);let o=await this.listHeadContentPaths(r,a),s=await this.stageContentFiles(r,e),c=new Set(s.map(e=>e.projectRelPath)),l=[...o].filter(e=>!c.has(e));await this.removePathsFromIndex(r,l);let u=(await r.git.raw([`write-tree`])).trim(),d=``;try{d=(await r.git.raw([`rev-parse`,`${a}^{tree}`])).trim()}catch{}if(d&&d===u){let t=null;try{t=(await r.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(t===a){A9.info({contentFileCount:e.length,headSha:a},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=a,this.lastSyncUtc=new Date().toISOString(),this.pushCycleLanded=!0,this.consecutivePushFailures=0,this.consecutiveContentions=0,this.pushStreakIsConnectivity=!1,this.clearPushError(),this.transitionTo(`idle`);return}A9.info({headSha:a,upstreamSha:t},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let i=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),i=!0}catch{}i?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=a;return}let f=[],p=[];try{let t=await zq(r.git,[`diff-tree`,`--name-only`,`-r`,a,u]);if(t.length>0){let n=new Map(e.map(e=>[e.projectRelPath,e.contentRelPath]));for(let e of t){f.push(e);let t=n.get(e)??JW(G(this.contentDir,W(this.projectDir,e)));t&&!t.startsWith(`..`)&&p.push(t)}}}catch{f=e.map(e=>e.projectRelPath).concat(l),p=e.map(e=>e.contentRelPath)}let m=this.buildCommitMessage(p);await this.applyCommitIdentity(r);let h=(await r.git.raw([`commit-tree`,u,`-p`,a,`-m`,m])).trim();if(!h||!j9.test(h)){A9.warn({raw:h},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await r.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,h,a]),await this.resetRealIndexForPaths(f,`push`);for(let e of f)i.add(e);let g=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),g=!0}catch{}g?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=h}finally{await this.healStaleRealIndex(r,i)}}),n&&(this.lastPushedSha=n,this.lastSyncUtc=new Date().toISOString(),this.pushCycleLanded=!0,this.ahead=0,this.consecutivePushFailures=0,this.consecutiveContentions=0,this.pushStreakIsConnectivity=!1,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){if(t instanceof M9){this.handleGitOperationRefusal(t,`push`);return}let n=t instanceof Error?t:Error(String(t));n instanceof VRt&&A9.warn({err:n},`[sync] push cycle: staging error detail`);let r=T9(n);if(r.class===`semantic`&&r.subclass===`non-fast-forward`){if(e>0){A9.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);let t=`fetch`,n=!0,r=!0;try{await e.git.fetch(`origin`);let i=await this.validateIncomingSymlinks(e,this.currentBranch);t=`push`,await this.commitDirtyContentFilesToHead(e,`push`),t=`fetch`,await this.validateIncomingSymlinks(e,this.currentBranch,i),t=`push`;let a=await this.prepareForMerge(e,this.currentBranch,i);if(!a.proceed){this.setBatchInProgress?.(!1);return}try{await this.applyCommitIdentity(e),t=`merge`,await this.mergeIncomingCommit(e,this.currentBranch,i),t=`push`}finally{a.needsStashPop&&(n=await this.popPreMergeStash(e)),r=this.restoreReconciledMcpOverlays(a.reconciled)}if(!n)throw Error(`failed to replay pre-merge working-tree state`);if(!r)throw Error(`failed to restore reconciled MCP overlays`);await this.persistReconciledMcpEntries(a.reconciled)}catch(e){if(e instanceof M9){this.handleGitOperationRefusal(e,`push`);return}if(e instanceof dK){this.handleIncomingSymlinkRefusal(e,`push`);return}if(e instanceof pK&&n&&r){A9.info({ref:e.ref},`[sync] push retry: incoming commit moved after inspection; re-inspecting next cycle`),this.state===`pushing`&&this.transitionTo(`idle`),this.scheduleSaveState();return}let i=e instanceof pK?Error(n?`failed to restore reconciled MCP overlays`:`failed to replay pre-merge working-tree state`):e,a=T9(i instanceof Error?i:Error(String(i)));if(a.class===`semantic`&&a.subclass===`merge-conflict`)await this.handleMergeConflict();else{let n=t===`merge`||t===`fetch`?`pull`:`push`;A9.warn({err:e,stage:t},`[sync] push retry error detail`),this.handleError(a,n)}this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}this.consecutiveContentions++,this.logContention(),this.pushStreakIsConnectivity&&(this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.clearPushError()),this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(r,`push`)}finally{try{pc(t)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e,t){if(await this.assertNoGitOperationInProgress(),(await e.git.status()).files.length===0)return null;let n=(await e.git.revparse(`HEAD`)).trim(),r=this.gatherContentFilesSync(),i=await this.listHeadContentPaths(e,n);if(r.length===0&&i.size===0)return null;let a=W(bc(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),o=this.gitHandle(a);try{await o.git.raw([`read-tree`,n]);let a=await this.stageContentFiles(o,r),s=new Set(a.map(e=>e.projectRelPath)),c=[...i].filter(e=>!s.has(e));await this.removePathsFromIndex(o,c);let l=(await o.git.raw([`write-tree`])).trim();if(l===(await o.git.raw([`rev-parse`,`${n}^{tree}`])).trim())return null;let u=[];try{u=await zq(o.git,[`diff-tree`,`--name-only`,`-r`,n,l])}catch{u=r.map(e=>e.projectRelPath).concat(c)}await this.applyCommitIdentity(o);let d=(await o.git.raw([`commit-tree`,l,`-p`,n,`-m`,`Auto-save: interim before merge`])).trim();return!d||!j9.test(d)?(A9.warn({raw:d},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,d,n]),await this.resetRealIndexForPaths(u,t,e),d)}finally{try{pc(a)}catch{}}}async readMcpGitBlob(e,t,n){try{return await e.git.raw([`cat-file`,`-e`,`${t}:${n}`]),await e.git.raw([`show`,`${t}:${n}`])}catch{return null}}async planTrackedMcpOverlap(e,t,n){let r;try{r=(await e.git.raw([`merge-base`,`HEAD`,t])).trim()}catch(e){return A9.warn({err:e,incomingCommit:t,path:n},`[sync] MCP reconciliation merge-base unavailable — declining`),{kind:`declined`,reason:`merge-base-unavailable`}}let[i,a,o,s]=await Promise.all([this.readMcpGitBlob(e,r,n),this.readMcpGitBlob(e,`HEAD`,n),this.readMcpGitBlob(e,``,n),this.readMcpGitBlob(e,t,n)]),c=null;try{c=J(W(this.projectDir,n),`utf8`)}catch{}return jRt({target:n,layers:{base:i,head:a,index:o,worktree:c,incoming:s},tomlEditor:this.mcpTomlEditor})}async prepareForMerge(e,t,n){let r=[],i;try{i=await zq(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return A9.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1,reconciled:r}}if(i.length===0)return{proceed:!0,needsStashPop:!1,reconciled:r};let a;try{a=new Set(await zq(e.git,[`diff`,`--name-only`,`HEAD..${n}`]))}catch(e){return A9.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1,reconciled:r}}let o=i.filter(e=>a.has(e)),s=zRt,c=o.filter(e=>s.has(e));if(c.length>0){let t=await Promise.all(c.map(async t=>({path:t,plan:await this.planTrackedMcpOverlap(e,n,t)}))),i=t.find(({plan:e})=>e.kind===`declined`),a=o.some(e=>!s.has(e));if(!i&&!a){for(let{path:e,plan:n}of t)n.kind===`resolved`&&(r.push({path:e,raw:n.raw,winnerEntry:n.winnerEntry}),A9.info({event:`mcp-config-reconcile`,target:e,outcome:`auto-resolved`},`[sync] auto-resolved OpenKnowledge MCP entry overlap`));o=o.filter(e=>!s.has(e))}else i?A9.warn({event:`mcp-config-reconcile`,target:i.path,outcome:`declined`,reason:i.plan.kind===`declined`?i.plan.reason:void 0},`[sync] declined OpenKnowledge MCP entry reconciliation`):a&&A9.info({event:`mcp-config-reconcile`,targets:c,outcome:`suppressed`,reason:`other-blocking-path`},`[sync] suppressed MCP entry reconciliation because another path blocks the merge`)}if(o.length>0){let e=o.slice(0,3).join(`, `),t=o.length>3?`, +${o.length-3} more`:``;return this.blockingPaths=o,this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutivePullFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),A9.warn({files:o},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1,reconciled:[]}}if(r.length>0)try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,...on(r.map(e=>e.path))])}catch(e){return A9.warn({err:e},`[sync] could not isolate reconciled MCP paths from pre-merge stash`),this.pullError=`Sync paused — OpenKnowledge could not safely isolate local MCP launcher changes before merging.`,this.pausedReason=`external-changes-pending`,this.blockingPaths=[],this.transitionTo(`idle`),this.scheduleSaveState(),{proceed:!1,needsStashPop:!1,reconciled:[]}}let l=new Set(r.map(e=>e.path));if(i.every(e=>l.has(e)))return{proceed:!0,needsStashPop:!1,reconciled:r};let u=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,u])}catch(e){return A9.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1,reconciled:r}}return{proceed:!0,needsStashPop:!0,reconciled:r}}restoreReconciledMcpOverlays(e){let t=!0;for(let n of e)try{let e=MY(W(this.projectDir,n.path),this.projectDir),t=null;try{t=J(e,`utf8`)}catch(e){A9.warn({err:e,path:n.path},`[sync] could not read MCP config before restoring reconciled overlay`)}t!==n.raw&&bH(e,n.raw,`utf8`)}catch(e){t=!1,A9.warn({err:e,path:n.path},`[sync] could not restore reconciled MCP overlay`)}return t}async popPreMergeStash(e){try{return await e.git.raw([`stash`,`pop`]),!0}catch(e){return A9.warn({err:e},`[sync] stash pop failed — stash remains on stack`),!1}}async assertNoGitOperationInProgress(){if(this.hasGitOperationInProgress()||(await zq(this.gitHandle().git,[`diff`,`--name-only`,`--diff-filter=U`])).length>0||this.hasGitOperationInProgress())throw new M9;this.pausedReason===`git-operation-in-progress`&&(this.pausedReason=void 0,this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}handleGitOperationRefusal(e,t){this.state===`conflict`||this.conflictCount>0?this.transitionTo(`conflict`):(this.pausedReason=`git-operation-in-progress`,t===`push`?this.clearPushError():this.clearPullError(),(this.state===`pushing`||this.state===`pulling`||this.state===`fetching`)&&this.transitionTo(`idle`)),A9.error({event:`git-operation-refusal`,err:e,op:t,branch:this.currentBranch},`[sync] cycle refused because a Git operation holds the tree — finish or abort it to resume sync`),this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}async validateIncomingSymlinks(e,t,n){let r=`refs/remotes/origin/${t}`,i=n;try{i??=await uK(e.git,r),await fK(e.git,i,`merge`,e.env)}catch(e){let n=e instanceof dK?e.unsafe.slice(0,50):null,a=n===null?void 0:JSON.stringify([i,n]);throw n!==null&&a!==this.loggedSymlinkRefusal&&(this.loggedSymlinkRefusal=a,A9.warn({event:`unsafe-incoming-symlinks`,branch:t,incoming:i,links:n},`[sync] refusing incoming changes with unsafe symlinks until they are fixed`)),n===null&&A9.warn({err:e,branch:t,trackingRef:r,incoming:i},`[sync] incoming symlink inspection failed`),e}return this.clearIncomingSymlinkPause(),i}handleIncomingSymlinkRefusal(e,t){this.pausedReason=`unsafe-incoming-symlinks`,this.refusedSymlinkPaths=e.displayPaths(),t===`push`?this.clearPushError():this.clearPullError(),(this.state===`pushing`||this.state===`pulling`||this.state===`fetching`)&&this.transitionTo(`idle`),this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}clearIncomingSymlinkPause(){this.loggedSymlinkRefusal=void 0,this.pausedReason===`unsafe-incoming-symlinks`&&(this.pausedReason=void 0,this.refusedSymlinkPaths=[],this.cc1Broadcaster?.signal(`sync-status`))}async mergeIncomingCommit(e,t,n){let r=`origin/${t}`;try{await E8e(e.git,{name:r,trackingRef:`refs/remotes/${r}`,commit:n})}catch(e){throw e instanceof w8e&&A9.warn({event:`incoming-ref-shadowed`,shadowedName:e.shadowedName,incoming:n},`[sync] another ref shadows the incoming branch name; delete it locally and on the remote`),e}await e.git.merge([r])}hasGitOperationInProgress(){let e=_x(this.projectDir);return!e||[`MERGE_HEAD`,`CHERRY_PICK_HEAD`,`REVERT_HEAD`,`rebase-merge`,`rebase-apply`].some(t=>q(W(e,t)))}async persistReconciledMcpEntries(e){if(e.length!==0){if(this.hasGitOperationInProgress())throw new M9;await nK(async()=>{let t=W(bc(),`ok-mcp-sync-idx-${process.pid}-${Date.now()}.idx`),n=[];try{let r=this.gitHandle(),i=this.gitHandle(t),a=(await i.git.revparse(`HEAD`)).trim(),o=(await i.git.revparse([`--abbrev-ref`,`HEAD`])).trim();if(o===`HEAD`)throw Error(`refusing MCP entry commit on detached HEAD`);await i.git.raw([`read-tree`,a]);let s=[];for(let r=0;r<e.length;r++){let o=e[r];if(!o)continue;let c=await this.readMcpGitBlob(i,a,o.path);if(c===null)throw Error(`tracked MCP path disappeared: ${o.path}`);let l=ORt({target:o.path,raw:c,entry:o.winnerEntry,tomlEditor:this.mcpTomlEditor});if(l===null)throw Error(`cannot edit tracked MCP path: ${o.path}`);let u=(await i.git.raw([`ls-tree`,a,...on([o.path])])).match(/^(100644|100755)\s/)?.[1];if(!u)throw Error(`unsafe tracked MCP mode: ${o.path}`);let d=`${t}.commit-${r}`;n.push(d),mc(d,l,`utf8`);let f=(await i.git.raw([`hash-object`,`-w`,d])).trim();await i.git.raw([`update-index`,`--add`,`--cacheinfo`,`${u},${f},${o.path}`]);let p=kRt({target:o.path,raw:l,tomlEditor:this.mcpTomlEditor}),m=kRt({target:o.path,raw:o.raw,tomlEditor:this.mcpTomlEditor}),h=p!==null&&p===m?l:o.raw,g=`${t}.replay-${r}`;n.push(g),mc(g,h,`utf8`);let _=(await i.git.raw([`hash-object`,`-w`,g])).trim();s.push({path:o.path,mode:u,blobSha:_,raw:h})}let c=(await i.git.raw([`write-tree`])).trim();if(c===(await i.git.raw([`rev-parse`,`${a}^{tree}`])).trim())return;await this.applyCommitIdentity(i);let l=(await i.git.raw([`commit-tree`,c,`-p`,a,`-m`,`Update OpenKnowledge MCP launcher`])).trim();if(!j9.test(l))throw Error(`commit-tree returned an invalid SHA`);try{await i.git.raw([`update-ref`,`refs/heads/${o}`,l,a])}catch(e){A9.info({event:`mcp-config-reconcile`,outcome:`ref-race`,branch:o,err:e},`[sync] skipped MCP launcher commit because the branch moved`);return}try{for(let e of s){await r.git.raw([`update-index`,`--add`,`--cacheinfo`,`${e.mode},${e.blobSha},${e.path}`]);let t=MY(W(this.projectDir,e.path),this.projectDir);J(t,`utf8`)!==e.raw&&bH(t,e.raw,`utf8`)}}catch(t){A9.warn({event:`mcp-config-reconcile`,outcome:`overlay-replay-failed`,err:t},`[sync] MCP overlay replay failed; resetting the affected index entries`),await this.resetRealIndexForPaths(s.map(e=>e.path),`mcp-reconcile`),this.restoreReconciledMcpOverlays(e)}A9.info({event:`mcp-config-reconcile`,outcome:`persisted-entry-commit`},`[sync] persisted OpenKnowledge MCP launcher entry commit`)}finally{for(let e of n)try{pc(e)}catch{}try{pc(t)}catch{}}})}}async stageContentFiles(e,t){if(t.length===0)return t;let n=new Set,r=!0;for(let i=0;i<t.length;i+=100){let a=t.slice(i,i+100).map(e=>e.projectRelPath);try{let t=await zq(e.git,[`ls-files`,`--others`,`--ignored`,`--exclude-standard`,...on(a)]);for(let e of t)n.add(e)}catch(e){r=!1,A9.warn({err:e},`[sync] ignored-path probe failed — staging unfiltered without -f`)}}n.size>0&&A9.info({count:n.size,sample:[...n].slice(0,5)},`[sync] skipping gitignored untracked path(s) — in content scope but excluded from git`);let i=[...n].filter(e=>e.endsWith(`/`)),a=e=>n.has(e)||i.some(t=>e.startsWith(t)),o=r?t.filter(e=>!a(e.projectRelPath)):t,s=e=>e.startsWith(`.ok/`)||e.includes(`/.ok/`),c=r?o.filter(e=>s(e.projectRelPath)):[],l=r?o.filter(e=>!s(e.projectRelPath)):o;for(let[t,n]of[[[`add`],l],[[`add`,`-f`],c]])for(let r=0;r<n.length;r+=100){let i=n.slice(r,r+100).map(e=>e.projectRelPath);await e.git.raw([...t,...on(i)])}return o}gatherContentFilesSync(){let e=[],t=(e,t)=>{throw new VRt(JW(G(this.projectDir,t))||`.`,e)},n=(r,i,a,o)=>{let s;try{s=sc(r,{withFileTypes:!0})}catch(e){o?.(e,r);return}for(let c of s){let s=W(r,c.name);if(c.isDirectory()){let e=JW(G(i,s));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e,a))continue;let r=e.split(`/`).some(e=>e.toLowerCase()===`.ok`);n(s,i,a,o??(r?t:void 0))}else if(c.isFile()||c.isSymbolicLink()){let t=JW(G(i,s));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t,a)){let t=JW(G(this.contentDir,s)),n=JW(G(this.projectDir,s));e.push({contentRelPath:t,projectRelPath:n})}}}};if(q(this.contentDir)&&n(this.contentDir,this.contentDir,GRt),this.rootOkOutsideContentWalk){let e=W(this.projectDir,`.ok`);q(e)&&!this.contentFilter.isDirExcluded(`.ok`,N9)&&n(e,this.projectDir,N9,t)}return e}isSyncScopedPath(e){let t=W(this.projectDir,e),n=JW(G(this.contentDir,t)),r=!n.startsWith(`..`)&&!this.contentFilter.isExcluded(n,GRt),i=this.rootOkOutsideContentWalk&&e.startsWith(`.ok/`)&&!this.contentFilter.isExcluded(e,N9);return r||i}async listHeadContentPaths(e,t){let n=new Set;try{let r=await zq(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r)this.isSyncScopedPath(e)&&n.add(e)}catch{}return n}async removePathsFromIndex(e,t){if(t.length===0)return;let n=[...new Set(t)];for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100);await e.git.raw([`rm`,`--cached`,...on(r)])}}async snapshotPromisedPaths(){let e,t;try{let{git:n}=this.gitHandle();e=await h9e(n,Iq),t=new Set(await zq(n,[`diff`,`--name-only`,`--diff-filter=U`]))}catch(e){return A9.warn({event:`snapshot-read-failed`,err:e,branch:this.currentBranch},`[sync] could not read the real index before the push cycle — skipping stale-index self-heal`),[]}let n=[];for(let r of e)if(!t.has(r.path)&&this.isSyncScopedPath(r.path)&&(n.push(r.path),n.length===100))break;return n}async healStaleRealIndex(e,t){let n=new Set(e.filter(e=>!t.has(e)));if(n.size===0)return;if(this.hasGitOperationInProgress()){A9.warn({event:`self-heal-skipped-git-operation`,branch:this.currentBranch,pathCount:n.size,paths:[...n].slice(0,20)},`[sync] self-heal skipped — a Git operation now holds the tree, so the promised paths stay listed until it ends`);return}let r=this.gitHandle(),i,a;try{i=(await Bq(r.git,[`diff-index`,`--cached`,`--name-status`,`HEAD`])).flatMap(e=>e.status[0]===`R`||e.status[0]===`C`?[e.from,e.to]:[e.to]),a=await zq(r.git,[`diff`,`--name-only`,`HEAD`])}catch(e){A9.error({event:`self-heal-skipped`,branch:this.currentBranch,pathCount:n.size,paths:[...n].slice(0,20),err:e},`[sync] self-heal could not compare the real index against HEAD — the promised paths stay listed in the real index`);return}let o=new Set(a),s=[...new Set(i.filter(e=>n.has(e)&&!o.has(e)))];s.length!==0&&(await this.resetRealIndexForPaths(s,`push`,r),A9.warn({event:`self-heal-applied`,branch:this.currentBranch,pathCount:s.length,paths:s.slice(0,20)},`[sync] self-heal cleared stale real-index entries left behind by an earlier push cycle`))}async resetRealIndexForPaths(e,t,n){if(e.length===0)return;let r=n??this.gitHandle(),i=[...new Set(e)];for(let e=0;e<i.length;e+=100){let n=i.slice(e,e+100);await this.resetRealIndexBatch(r,n,t)}}async resetRealIndexBatch(e,t,n){let r;try{await e.git.raw([`reset`,`HEAD`,...on(t)]);return}catch(e){r=e}let i=T9(r),a=r,o=!1;if(i.class===`local`&&i.subclass===`index-lock`){await this.beforeRealIndexResetRetry?.(),await $Rt(P9(.05));try{await e.git.raw([`reset`,`HEAD`,...on(t)]),o=!0}catch(e){a=e,i=T9(e)}}let s={event:`stale-index-reset`,outcome:o?`recovered-on-retry`:`failed`,op:n,branch:this.currentBranch,pathCount:t.length,paths:t.slice(0,20),errorClass:i.class,errorSubclass:i.subclass,err:a};o?A9.warn(s,`[sync] stale-index reset needed a second attempt — it succeeded, so the panel listing is current`):A9.error(s,`[sync] stale-index reset failed — the panel listing may stay stale`),!o&&i.class===`local`&&i.subclass===`index-lock`&&this.noteIndexLockEncountered(n,i)}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=this.gitHandle(),t=[];try{t=await zq(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){A9.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){A9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t)this.isContentConflictPath(e)?n.push(e):r.push(e);let i=[],a=JW(G(this.projectDir,yl(`project`,this.projectDir)));for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,...on([t])]),await e.git.raw([`add`,...on([t])]),t.toLowerCase()===a.toLowerCase()?A9.warn({file:t},`[sync] auto-resolved .ok/config.yml conflict with theirs: local project config edits were overwritten by the remote version`):A9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){A9.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),i.push({file:t,err:e})}if(i.length>0){let t=i.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){A9.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let n=t.slice(0,3).join(`, `),r=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${n}${r}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutivePullFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),A9.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(n.length>0){for(let e of n)this.conflicts.raise({kind:`merge-native`,file:e});this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),A9.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await this.applyCommitIdentity(e),await e.git.raw([`commit`,`--no-edit`]);let n=_x(this.projectDir);t=n===null||!q(W(n,`MERGE_HEAD`))}catch(e){A9.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),A9.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){A9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullError=`Sync paused — could not finalize the merge. Retry sync to try again.`,this.transitionTo(`idle`),A9.warn({},`[sync] could not finalize merge after auto-resolving conflicts — merge aborted`)}}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){if(e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),A9.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`)this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`;else if(e.class===`semantic`&&e.subclass===`protected-branch`)this.mode=`off`,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`);else if(e.class===`local`&&e.subclass===`index-lock`)this.bumpFailureCount(t),(this.state===`pushing`||this.state===`pulling`||this.state===`fetching`)&&this.transitionTo(`idle`),this.noteIndexLockEncountered(t,e);else if(e.class===`local`&&e.subclass===`dirty-tree`){if(this.state===`conflict`||this.conflictCount>0){this.transitionTo(`conflict`);return}this.bumpFailureCount(t),this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)}else e.retryable?(this.bumpFailureCount(t,ezt(e)),this.transitionTo(`offline`)):(this.bumpFailureCount(t),this.transitionTo(`idle`))}otherLegInFlight(e){return this.cycleInFlight!==null&&this.cycleInFlight!==e}beginIndexLockWatch(e){if(this.otherLegInFlight(e))return;let t=this.pausedReason===`git-index-locked`;this.indexLockHitThisCycle=!1,t||(this.lastLockNoticeKind=void 0),this.restingIndexLockPause=t?void 0:this.pausedReason}holdsIndexLock(e){return KRt.test(`${e.message}\n${e.rawStderr??``}`)}noteIndexLockEncountered(e,t){let n=this.holdsIndexLock(t),r=n?`index-locked`:`git-lock-held`;if(this.lastLockNoticeKind!==r){this.lastLockNoticeKind=r;let i={event:r,op:e,branch:this.currentBranch,errorClass:t.class,errorSubclass:t.subclass};n?A9.error(i,`[sync] index locked — another program is holding .git/index.lock, so sync cannot update it`):A9.error(i,`[sync] a git lock file blocked the operation — the held lock is not .git/index.lock, so the listing is not paused on it`)}n&&(this.indexLockHitThisCycle=!0,this.pausedReason!==`git-index-locked`&&(this.pausedReason=`git-index-locked`,this.cc1Broadcaster?.signal(`sync-status`)))}noteUnbornHeadRefusal(){this.pausedReason!==`no-commits-yet`&&A9.error({event:`unborn-head-refusal`,branch:this.currentBranch},`[sync] push refused — this repository has no commits yet, so there is nothing to send`),this.pausedReason=`no-commits-yet`,this.cc1Broadcaster?.signal(`sync-status`)}clearUnbornHeadPause(){this.pausedReason===`no-commits-yet`&&(this.pausedReason=void 0,this.cc1Broadcaster?.signal(`sync-status`))}settleIndexLockPause(e){this.otherLegInFlight(e)||this.indexLockHitThisCycle||this.pausedReason===`git-index-locked`&&(this.pausedReason=this.restingIndexLockPause,this.cc1Broadcaster?.signal(`sync-status`))}currentState(){return this.state}markRun(){this.lastPushOkUtc=new Date().toISOString(),this.saveStateNow(),this.cc1Broadcaster?.signal(`sync-status`)}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,A9.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null);try{let e=ZRt.has(this.pausedReason)?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastPullOkUtc:this.lastPullOkUtc,lastPushOkUtc:this.lastPushOkUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutivePullFailures,consecutivePushFailures:this.consecutivePushFailures,pushStreakIsConnectivity:this.pushStreakIsConnectivity,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0},n=`${this.statePath}.tmp`;bH(n,JSON.stringify(t,null,2),`utf-8`),CH(n,this.statePath)}catch(e){A9.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(q(this.statePath))try{let e=J(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastPullOkUtc=t.lastPullOkUtc??null,this.lastPushOkUtc=t.lastPushOkUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutivePullFailures=t.consecutiveFailures??0,this.consecutivePushFailures=t.consecutivePushFailures??0,this.pushStreakIsConnectivity=t.pushStreakIsConnectivity??!1;let n=typeof t.pausedReason==`string`?t.pausedReason:void 0,r=n!==void 0&&JRt(n)?n:void 0;n!==void 0&&r===void 0&&n.length>0&&A9.warn({event:`paused-reason-unrecognized`,pausedReason:n},`[sync] persisted pause reason is not one this build knows — dropping it and continuing without a pause`),this.pausedReason=QRt.has(r)?void 0:r}catch(e){A9.warn({err:e},`[sync] failed to load sync state`)}}};const izt=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function azt(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(_W(e)||vW(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&izt.test(n)&&(r[`mount.id`]=n);try{let e=()=>{sH(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),wo.with(Oo.extract(wo.active(),r),e)}else e()}catch(e){Y(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let I9=!1;function ozt(){if(I9)return;let e=doe;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){I9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),I9=!0}catch(e){Y(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const szt=XW(``),czt=1e4,L9=3e4;function lzt(e,t){let n=e.filter(t);return n.length===1?n[0]:void 0}function uzt(e){let t=new Set;for(let n of e.split(`
2321
2321
  `)){let e=n.trim();e!==``&&t.add(e)}return t}function dzt(e,t){let n=uzt(e),r=uzt(t),i=0;for(let e of n)r.has(e)&&i++;return i>0&&i>=Math.max(n.size,r.size)*.5}function fzt(e,t){return e.size!==void 0&&e.modified!==void 0&&t.size===e.size&&t.modified===e.modified}function pzt(e,t,n){return e.identity===void 0||t.identity!==e.identity?!1:fzt(e,t)?!0:e.text!==void 0&&n!==void 0&&dzt(e.text,n)}var mzt=class{pending=new Map;recentCreates=new Map;get size(){return this.pending.size}hold(e){this.pending.set(e.docName,e)}has(e){return this.pending.has(e)}release(e){let t=this.pending.get(e);return this.pending.delete(e),t}all(){return[...this.pending.values()]}matchCreate(e){let t=this.pending.get(e.docName);if(t)return{vanished:t,by:`same-name`};for(let t of this.pending.values())if(pzt(t,e,e.content))return{vanished:t,by:`identity`};if(e.hash===szt)return;let n=lzt([...this.pending.values()],t=>t.hashes.has(e.hash));return n?{vanished:n,by:`hash`}:void 0}dueAfter(e){return this.all().filter(t=>t.afterPass<e)}heldBefore(e){return this.all().filter(t=>t.heldAt<=e)}rememberCreate(e){this.forgetCreatesBefore(e.at-czt),this.recentCreates.delete(e.docName),this.recentCreates.set(e.docName,e);for(let e of this.recentCreates.keys()){if(this.recentCreates.size<=256)break;this.recentCreates.delete(e)}}forgetCreatesBefore(e){for(let[t,n]of this.recentCreates)n.at<e&&this.recentCreates.delete(t)}matchRecentCreate(e,t,n){this.forgetCreatesBefore(t-czt);let r=[...this.recentCreates.values()].filter(t=>t.docName!==e.docName),i;for(let t of r)if(e.identity!==void 0&&t.identity===e.identity&&pzt(e,t,fzt(e,t)?void 0:n(t))){i={create:t,by:`identity`};break}if(!i){let t=lzt(r.filter(e=>e.hash!==szt),t=>e.hashes.has(t.hash));t&&(i={create:t,by:`hash`})}return i&&this.recentCreates.delete(i.create.docName),i}clear(){this.pending.clear(),this.recentCreates.clear()}};function hzt(e,t){let n=!0,r={async afterUnloadDocument(){n&&t()}};return e.configuration.extensions.unshift(r),()=>{n=!1;let t=e.configuration.extensions,i=t.indexOf(r);i!==-1&&t.splice(i,1)}}const gzt=5e3,_zt=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),vzt=(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function yzt(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=zc(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],DW({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return Y(`upstream-attribution`).warn({err:e,oldHead:n,newHead:r},`git log spawn threw; upstream docs keep file-system attribution`),i}if(a.error||a.status!==0||typeof a.stdout!=`string`)return Y(`upstream-attribution`).warn({err:a.error,status:a.status,signal:a.signal,stderr:typeof a.stderr==`string`?a.stderr.slice(0,500):void 0,oldHead:n,newHead:r},`git log failed; upstream docs keep file-system attribution`),i;let o=null;for(let n of a.stdout.split(`
2322
2322
  `)){let r=n.trim();if(r===``)continue;if(r.startsWith(`C\0`)){let[,e,t]=r.split(`\0`);o=e&&t?{name:e,email:t}:null;continue}if(!o||!r.endsWith(`.md`)&&!r.endsWith(`.mdx`))continue;let a=K(e,r);if(!jG(a,t))continue;let s=bX(a,t);i.has(s)||q(a)&&i.set(s,o)}return i}function bzt(e){ozt();let t=e.ingressPolicy??MQ({}),{contentDir:n,projectDir:r=n,quiet:i=!0,debounce:a=2e3,maxDebounce:o=1e4,gitEnabled:s=!0,commitDebounceMs:c=3e4,wipRef:l=`refs/wip/main`,configHomedirOverride:u,enableTestRoutes:d=!1,shadowRepo:f,contentRoot:p,destroyTimeoutMs:m=1e4,localOpCliArgs:h,authStreamHeartbeatMs:g,skipStateManifestCheck:_=!1,singleDocRelPath:v,ephemeral:y=!1}=e,b=TG(n,{root:`content`,component:`server-factory`}),x=w6(u),S=Vxt({projectDir:r,tokenStore:e.tokenStore,localOpCliArgs:h,declaredGitHubHosts:x}),C=Y(`server`),w=null,T=()=>w?.getLastKnownBranch()??null,E=()=>w?w.getLastKnownBranch():r9(r).branch,D=yFt(K(n)),O=null,k=r9(r).branch??`main`,A=new N3e({path:W(RJ(r),`receipts.jsonl`)}),j=j3e(n),M=new mG(k,{persistencePath:W(RJ(r),`stale-external-writes.json`),receipts:A,onStaleExternalWriteChange:()=>{O?.signal(`sync-status`),le()},onStoreRefused:e=>{oi(e,`refused-store-mark`)===`lost`&&C.warn({docName:e},`[rescue] refused-store content for ${e} was not durably buffered at refusal time`)},fileForDocName:e=>G(r,AG(e,n)).replaceAll(`\\`,`/`),hasResolvedExtension:JU}),N=()=>M.getActiveBranch(),ee=e=>M.getReconciledBase(e),te=(e,t)=>M.setReconciledBase(e,t),F=e=>M.deleteReconciledBase(e),I=e=>M.switchReconciledBaseScope(e),ne=new mzt,re=e=>M.holdBatch(e),ie=e=>M.releaseBatch(e),ae=async()=>{try{await qr()}finally{Jr()}await Ke.flushDeferredStores(`within-branch`)},oe=e=>t=>{if(t){re(e);return}ie(e)&&ae().catch(t=>{C.error({err:t,owner:e},`[batch] draining after the batch failed`)})},se=()=>M.isBatchInProgress(),ce=new Dit({projectDir:r,contentDir:n,assertResolutionPath:Ae,branch:k,signal:{signal:e=>O?.signal(e)},io:{gitRaw:async e=>rK(r,{credentialConfig:[],timeoutMs:3e4}).git.raw(e),writeProjectFileUntracked:(e,t)=>{Ae(e),bH(e,t,`utf-8`)},unlinkProjectFileUndeclared:e=>{Ae(e),EH(e)},deleteResolvedContent:(e,t)=>{De(t);let n=mrt(t);try{EH(t)}catch(e){throw hrt(n),e}He.decrementMdDir(U(e)),_n.current?.deleted(e)},applyResolvedContent:async(e,t,n)=>{De(t);let r=!q(t);oX(t,XW(n)),await Fs(t,n,{fs:ke}),r&&He.incrementMdDir(U(e)),Je.documents.get(e)&&Bn(e,n),te(e,n),await Ue.recordDiskUpsert(e,n)},readLiveContent:e=>zn(e),finalizeReconcileResolution:async(e,t,n)=>{let r;if(e.reason===`stale-external-write`){let i=M.getStaleExternalWrite(n);i&&(r={conflict:i,branch:M.getActiveBranch()}),t===`mine`||t===`content`?M.recordDisplacedVersion(n,e.stages.theirs):M.clearDisplacedVersions(n),M.clearStaleExternalWrite(n)}if(t===`delete`&&Sn(n)){C.debug({docName:n,source:`resolve-delete`,bindingRecreated:!0},`[reconcile] delete skipped: ${n} (binding recreated)`);return}let i=Je.documents.get(n),a=i?.getMap(`lifecycle`);if(t===`delete`){let e=jn(n);try{let t=e.residentCurrent()&&i?Pr(n,w?.getLastKnownBranch()??`main`,`delete`,!0):!1;if(e.namespaceCurrent()&&(_n.current?.deleted(n),await Ue.recordDiskDelete(n)),!e.namespaceCurrent()&&!e.residentCurrent()){C.debug({docName:n,source:`resolve-delete`,namespaceCurrent:!1,residentCurrent:!1},`[reconcile] delete skipped: ${n} (stale removal)`);return}C.info({docName:n,isDirty:t,source:`resolve-delete`},`[reconcile] delete: ${n} (dirty=${t})`);let o=a?{status:a.get(`status`),reason:a.get(`reason`),detectedAt:a.get(`detectedAt`)}:void 0;if(i&&e.residentCurrent()){a?.set(`status`,`deleted-upstream`),a?.delete(`reason`),a?.delete(`detectedAt`);try{Je.closeConnections(n),await ft(i,e.residentCurrent)}catch(t){if(e.residentCurrent()&&a&&o)for(let[e,t]of Object.entries(o))t===void 0?a.delete(e):a.set(e,t);if(e.namespaceCurrent()&&r)try{M.restoreStaleExternalWrite(r.conflict,r.branch)}catch(e){C.error({err:e,docName:n},`[reconcile] stale-external-write rollback failed for ${n}; the retry may not find the conflict`)}throw t}}if(!e.namespaceCurrent()){C.debug({docName:n,source:`resolve-delete`,namespaceCurrent:!1,residentCurrent:e.residentCurrent()},`[reconcile] delete: ${n} not recorded as removed (stale removal)`);return}F(n),Mn(n),tn(n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:n,kind:`deleted`,source:`resolve-delete`}))}finally{e.dispose()}}else a?.get(`reason`)===e.reason&&(a.delete(`status`),a.delete(`reason`),a.delete(`detectedAt`));Et(`files`)}}});function le(){for(let e of M.listStaleExternalWrites()){let t=ee(e.docName)??e.diskContent;ce.raise({kind:`reconcile`,file:e.file,reason:`stale-external-write`,detectedAt:e.detectedAt,stages:{base:t,ours:e.retainedContent??t,theirs:e.diskContent}})}}le();function L(e){let t=gl({absPath:yl(`project`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project config`)});if(!t.valid){let n=Yt(t.error)&&t.error.code===`SCHEMA_INVALID`?t.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(n.length>0)throw new w_t(n.map(e=>e.message));if(e?.requireValid)throw Error(`Project config is invalid`,{cause:t.error});C.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return t.value.content.attachmentFolderPath??`./{{filename}}.assets`}function ue(){let e=gl({absPath:yl(`project-local`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project-local config`)}),t=Kre(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||C.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let n=gl({absPath:yl(`project`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project config`)});return n.valid||C.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:P(n.value.autoSync?.default)??`off`,source:`committed-default`}}function de(){let e=gl({absPath:yl(`project-local`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project-local config`)});return Nte(e.value.autoSync)}function fe(){let e=gl({absPath:yl(`project`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules,t=e?Ma(e):ca;return EIt(r,t.plugins.okf),t}function pe(){let e=gl({absPath:yl(`project`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project config for link validation`)});return{links:e.value.validation?.links??`warning`,suppressLogLinkAdvisories:e.value.validation?.suppressLogLinkAdvisories??!0}}function me(){return sgt(r,{configHomedirOverride:u,onWarn:e=>C.warn({message:e},`[config] could not read project-local config`)})}function he(){let e=gl({absPath:yl(`project-local`,r,u),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function ge(){return tce({cwd:r,homedirOverride:u,warn:e=>C.debug({message:e},`[config] diagnostics read`)})}function _e(e){let t={user:Zn,project:Xe,"project-local":Re};for(let n of ge().diagnostics)if(e===void 0||t[n.scope]===e){if(n.code===`VALUE_FALLBACK`){for(let e of n.issues)C.warn({code:n.code,scope:n.scope,file:n.file,path:e.path.join(`.`),line:e.line,column:e.column},`[config] ${e.path.join(`.`)}: ${e.message}`);continue}n.code===`REMOVED_KEY`&&C.warn({scope:n.scope,file:n.file,path:n.path.join(`.`)},`[config] ${n.path.join(`.`)} is no longer read and was ignored. ${n.redirect}`)}}function ve(e){return`${r4(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function ye(e){return`${e.maxBatchSize}|${e.maxBatchChars}|${e.docTimeoutMs}`}let be,xe=0;function Se(e,t){let i;if(e===`__config__/project`||e===`__local__/project`){let t=ue();i=t.mode,ei?.setMode(t.mode,t.source).catch(n=>{C.warn({err:n,mode:t.mode,docName:e},`[sync] failed to apply autoSync mode from config`)});let n=de();ei?.setIntervals(n.pullIntervalSeconds,n.pushIntervalSeconds)}let a=me();if(st.applyConfig({enabled:a.enabled,providerFingerprint:ve(a),transportFingerprint:ye(a),maxBatchSize:a.maxBatchSize}),e===`__config__/project`){xe+=1;try{let e=L({requireValid:!0});He?.setAttachmentFolderPath(e),be!==void 0&&e!==be&&C.warn({previous:be,next:e},`[content-filter] attachment folder changed — files under the previous folder no longer sync`),be=e}catch(e){C.warn({err:e},`[content-filter] project config invalid — keeping previous attachment admission`)}O?.signal(`lint-config`),(t??fe().plugins.okf?.generate?.index===!0)||qFt({projectDir:r,contentDir:n,generatedDocNames:cn(),enabled:!1}).then(e=>{e.ok||C.warn({state:e.status.state},`[index] could not remove Open Knowledge generated-index Git attributes`)}),nn()}C.info({docName:e,autoSyncMode:i,semanticEnabled:a.enabled},`[config] applied persisted config to in-process consumers`)}tH();let Ce=Nc(),we=!1,Te=!1,Ee=K8e(n,v),De=e=>{if(we)throw new zK(!1);Y8e(Ee,e)},Oe=e=>{De(e),X8e(Ee,e)},ke=G8e(De);function Ae(e){MY(e,r,{allowShareableOkArtifact:KG});let t=BK(e),n=JW(G(BK(r),t));Ee.kind===`tree`&&!FK({kind:`tree`,path:Ee.path,excluded:[]},t)&&KG(n)||De(t)}let je=RJ(r),Me=new C1e({localDir:je,log:Y(`acp-registry`),fetchImpl:e.acpRegistryFetchImpl}),Ne=new f1e(je,Y(`acp-permissions`)),Pe;try{Pe=W8e({scope:Ee,projectDir:BK(r),serverInstanceId:Ce,registryPath:e.authorityRegistryPath})}catch(e){if(e instanceof kK&&e.existing.projectDir===BK(r)){let t=N4(je);if(t?.pid===e.existing.pid)throw new j4(t,W(je,`server.lock`))}throw e}Ee=Pe.scope;let Fe=!1;try{M4(je,{port:0,worktreeRoot:r,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),Fe=!0,_||eRt({lockDir:je,shadowRepoDir:vx(r)})}catch(e){Fe&&F4(je);try{Pe.release()}catch(e){C.error({err:e},`[server] startup authority release failed`)}throw e}let Ie=Xn(),Le=bmt(()=>F2(Yr,n)),ze=xmt(()=>F2(Yr,n)),Be=(e,t)=>{let n=_pt(e);return n===null||!n.includes(`/`)?Ie.resolveEmbed(e,t):ze(n)??null},Ve=(e,t)=>{let r=Be(e,t);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=K(n,r);if(!YW(i,K(n)))return null;try{let e=fc(i);return e.isFile()?e.size:null}catch{return null}},He,Ue,We,Ge,Ke,qe,Je,Ye,R,Ze,Qe,$e,et=null,tt=null,nt=null,rt=null,it=null,at=null,ot=me(),st=new hgt({loadEmbedder:()=>{let t=me(),n={keyStore:e.embeddingsKeyStore??null,projectDir:r,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions},options:{maxBatchSize:t.maxBatchSize,maxBatchChars:t.maxBatchChars,docTimeoutMs:t.docTimeoutMs}};return(e.embedderLoader??Jht)(n)},cacheDir:W(RJ(r),`embeddings`),enabled:ot.enabled,providerFingerprint:ve(ot),transportFingerprint:ye(ot),maxBatchSize:ot.maxBatchSize}),ct=null,lt=new Map,ut=!1,dt=[],ft,pt,{promise:mt,resolve:ht,reject:gt}=Promise.withResolvers(),_t=!1;mt.then(()=>{_t=!0},()=>{});let vt=e=>q3(e,r,u??_c()),yt=()=>!0,bt=new fIt({projectDir:r,contentDir:n,getShadow:()=>We?.current,isReady:()=>_t,signal:()=>O?.signal(`sync-status`),isHeld:e=>ne.has(e),isSaveHeld:e=>yt(e),resolveFile:e=>{let t;try{if(vW(e))t=P7(e,Ke.configPersistenceCtx);else if(yW(e))t=o6(e,Ke.managedArtifactCtx);else return null}catch(t){return C.debug({err:t,docName:e},`[doc-notices] no file to name for a notice outside the content folder`),null}return{abs:t,display:vt(t)}}}),xt=PEt({getShadow:()=>We?.current,contentRoot:p??``,getBranch:T,writeCheckpoint:e.mergeHistoryWriter,notices:bt}),St=Promise.withResolvers(),{promise:Ct,resolve:wt}=Promise.withResolvers();async function Tt(){let e,t=Symbol(`branch-scope-gate-timeout`),n=new Promise(n=>{e=setTimeout(()=>n(t),1e4),e.unref?.()});try{if(await Promise.race([Ct,n])!==t)return N()}finally{e&&clearTimeout(e)}try{return r9(r).branch??null}catch(e){return C.warn({err:e},`[auth] branch scope gate expired and HEAD is unreadable — skipping the branch claim check`),null}}function Et(e){O?.signal(e)}let Dt,Ot,kt,At=!1,jt=!1,Mt=new AbortController,Nt=new Set,Pt=!1,Ft=!1,It=!1,Lt=0,{promise:Rt,resolve:z}=Promise.withResolvers();function zt(e){It||(It=!0,z(e))}function Bt(){return Pt||Nt.size>0}function Vt(){jt||!At||(Dt!==void 0&&clearTimeout(Dt),Dt=setTimeout(()=>{Dt=void 0,Zt()},500),Dt.unref?.())}function Ht(){if(jt){zt({status:`cancelled`,indexCount:0});return}Pt=!0,Ft=!0,Ot=setImmediate(()=>{Ot=void 0,Zt()})}let Ut,Wt,Gt=!1,Kt=null;async function qt(){let e=We.current;if(!e||Gt)return;let t=performance.now();C.info({gitDir:e.gitDir},`[shadow-housekeeping] deferred boot housekeeping started`);try{await Tet(e)}catch(e){C.warn({err:e},`failed to write gc config (non-fatal)`)}if(!Gt){if(Kt)try{let t=Number.parseInt(process.env.OK_BOOT_RENAME_GC_RETRY_INTERVAL_MS??``,10)||1e3,n=!1;for(let r=0;r<30;r++){if(!(await N$(e,Kt,{rebuild:!0})).skipped){n=!0;break}if(r===29)break;if(await new Promise(e=>{setTimeout(e,t).unref?.()}),Gt)return}n||C.warn({gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild retry budget exhausted (persistent GC contention); rebuild deferred to next boot`)}catch(t){C.warn({err:t,gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild failed; index loaded without GC`)}if(!Gt){try{await Ge?.runBootMaintenance()}catch(e){C.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}C.info({gitDir:e.gitDir,durationMs:Math.round(performance.now()-t)},`[shadow-housekeeping] deferred boot housekeeping complete`)}}}function Jt(){Gt||(Ut=setImmediate(()=>{Ut=void 0,Wt=qt().catch(e=>{C.error({err:e},`[shadow-housekeeping] unexpected uncaught failure`)})}))}async function Xt(){if(Gt=!0,Ut!==void 0&&(clearImmediate(Ut),Ut=void 0),!Wt)return;let e,t=new Promise(t=>{e=setTimeout(()=>t(`timeout`),m)});try{if(await Promise.race([Wt,t])===`timeout`)throw Error(`shadow housekeeping drain timed out after ${m}ms — abandoning in-flight housekeeping`)}finally{e!==void 0&&clearTimeout(e)}}function Zt(){if(jt||!At||!Bt())return;if(kt!==void 0){e.generatedIndexTestHooks?.onKickWhileInFlight?.();return}if(M.isBatchInProgress()){Vt();return}let t=Pt,n=new Set(Nt),r=Ft;Pt=!1,Nt.clear(),Ft=!1;let i=t?{fullSweep:!0}:{fullSweep:!1,directories:n};kt=(async()=>{let e=await fn(i,Mt.signal);if(e.status===`deferred`){Pt=!0,r&&(Lt+=e.indexCount,Ft=!0);return}r&&(Lt+=e.indexCount,e.status===`completed`&&Bt()?Ft=!0:zt({...e,indexCount:Lt}))})().catch(e=>{C.warn({err:e},`[index] index regeneration coordinator failed`),r&&zt({status:`failed`,indexCount:0})}).finally(()=>{if(kt=void 0,jt){r&&zt({status:`cancelled`,indexCount:0});return}Bt()&&Dt===void 0?Vt():!Bt()&&Dt===void 0&&e.generatedIndexTestHooks?.onIdle?.()})}async function Qt(){if(!jt){let e=kt;jt=!0,Mt.abort(),Dt!==void 0&&(clearTimeout(Dt),Dt=void 0),Ot!==void 0&&(clearImmediate(Ot),Ot=void 0),Nt.clear(),Pt=!1,Ft=!1,e===void 0&&zt({status:`cancelled`,indexCount:0})}await kt}function $t(e){jt||ZFt(e)||(Nt.add(X7(e)),Vt())}function en(e){if(!jt){for(let t of XFt(e))Nt.add(t);Vt()}}function tn(e){let t=Yr?.getFileIndex();if(!t){$t(e);return}let n=X7(e);if(Z7(t.keys()).has(n)){$t(e);return}en(X7(n))}function nn(){jt||(Pt=!0,Vt())}function rn(e){let t=Yr?.getFileIndex().get(e);if(t)return{title:t.title,description:t.description,type:t.type}}let an=!1,on={origin:vzt,writer:Fet,isConflict:e=>ce.has(e),getDocument:e=>Je.documents.get(e),writeDisk:async(e,t)=>{De(e),SH(U(e),{recursive:!0}),await Fs(e,t,{fs:ke})},registerWrite:(e,t)=>oX(e,XW(t)),noteFileIndex:e=>Yr?.mutateFileIndex({kind:e.kind,path:e.absPath,docName:e.docName,content:e.markdown}),signalFiles:()=>Et(`files`),attribute:async(e,t)=>{t$(e,t.id,t.name,t.id),an=!0}};function sn(e){return e===``?J7:`${e}/${J7}`}function cn(){return[...Yr?Z7(Yr.getFileIndex().keys()):new Set([``])].map(sn)}function ln(e){let t=fe().plugins.okf?.generate?.index===!0,n=e.state===`ready`||e.state===`not-applicable`;return{enabled:t,active:t&&n,git:e.state===`ready`?{state:e.state,ownership:e.ownership}:{state:e.state}}}function un(){return ln(UFt({projectDir:r,contentDir:n,generatedDocNames:cn()}))}async function dn(e){let t=await qFt({projectDir:r,contentDir:n,generatedDocNames:cn(),enabled:e});if(!t.ok)return{...un(),applied:!1,reason:t.status.state===`conflict`?`git-conflict`:`git-unavailable`};let i=await xl({cwd:r,scope:`project`,patch:{contentRules:{okf:{generate:{index:e}}}}});if(!i.ok){try{await t.rollback()}catch(e){C.error({err:e},`[index] could not roll back generated-index Git attributes`)}return{...un(),applied:!1,reason:`config-write`}}try{let e=J(i.path,`utf-8`);await L7(Je.documents.get(`__config__/project`)??null,Xe,e,Ke.configPersistenceCtx)}catch(e){C.warn({err:e},`[index] generated-index settings reflection deferred to config watcher`)}return Se(Xe,e),_e(Xe),{...un(),applied:!0}}async function fn(t,i){let a=0,o=t.fullSweep?performance.now():void 0,s=()=>fe().plugins.okf?.generate?.index!==!0;try{if(i.aborted)return{status:`cancelled`,indexCount:0};if(s())return{status:`disabled`,indexCount:0};let c=Yr?.getFileIndex();if(!c)return{status:`failed`,indexCount:0};try{if(await e.generatedIndexTestHooks?.beforePlan?.({fullSweep:t.fullSweep,signal:i}),i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};if(M.isBatchInProgress())return{status:`deferred`,indexCount:a};let o=tIt({docs:c,docExtension:qU,currentMarkdownFor:()=>null,warningScope:D}),l=UFt({projectDir:r,contentDir:n,generatedDocNames:o.map(({directory:e})=>sn(e))});if(l.state!==`ready`&&l.state!==`not-applicable`)return C.warn({state:l.state},`[index] generated index regeneration paused by Git attributes`),{status:`blocked`,indexCount:a};for(let{directory:r,markdown:c}of o){if(!t.fullSweep&&!t.directories.has(r))continue;if(i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};if(M.isBatchInProgress())return{status:`deferred`,indexCount:a};if(await e.generatedIndexTestHooks?.beforeDecision?.({directory:r,fullSweep:t.fullSweep,signal:i}),i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};let o=sn(r),l=K(n,`${o}.md`);De(l);let u;try{u=J(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&C.warn({err:e,path:uH(l)},`[index] could not read the existing generated index; treating it as absent`),u=null}a+=1;let d=await NFt({docName:o,absPath:l,markdown:c,currentMarkdown:u},on);d===`blocked-conflict`?C.warn({event:`generated-index-regeneration`,outcome:`blocked`,directory:r,reason:`conflict`},`[index] generated index regeneration blocked by active conflict`):C.info({event:`generated-index-regeneration`,outcome:d===`unchanged`?`unchanged`:`written`,directory:r},`[index] generated index regeneration completed`),await e.generatedIndexTestHooks?.afterWrite?.({docName:o,fullSweep:t.fullSweep,signal:i}),!t.fullSweep&&r!==``&&u===null&&en(X7(r))}}finally{an&&=(await Ke.waitForPendingCommits(),await Ke.flushContributors(),!1),o!==void 0&&(Z2(`generatedIndexSweepMs`,Math.round((performance.now()-o)*100)/100),yht(`generatedIndexCount`,a))}return{status:`completed`,indexCount:a}}catch(e){return C.warn({err:e},`[index] index regeneration failed`),{status:`failed`,indexCount:a}}}let pn=null,mn=!1,hn=()=>{try{qLt(r,gn.entries())}catch(e){C.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},gn=new RLt(void 0,{onEviction:()=>U2e(),onSizeChange:e=>W2e(e),onMutate:()=>{!mn||pn!==null||(pn=setTimeout(()=>{pn=null,hn()},2e3))}});for(let[e,t]of KLt(r))CW(e)||s5(e)&&([`.md`,`.mdx`].some(t=>{let r=K(n,`${e}${t}`);return YW(r,K(n))&&q(r)})||gn.restore(e,t));mn=!0;let _n={current:null},vn=new WeakMap,yn=new Map,bn=K(n);function xn(e){if(!s5(e))return null;let t=XU(e),n=K(bn,t);return YW(n,bn)?n:null}function Sn(e){let t=Yr?.getFileIndex().get(e)?.canonicalPath??xn(e);return t!==null&&RX(e,t,n,He)}function Cn(e){let t=vn.get(e);return t||(t={source:e.getText(`source`).toString(),mutation:void 0,adoption:void 0,pendingRetirement:!1},vn.set(e,t)),t}function wn(e){for(let t of yn.get(e)??[])t.namespaceAllowed=!1}function Tn(e,t){if(Te||e.isDestroyed||Je.documents.get(t)!==e)return;let n=Cn(e);n.pendingRetirement=!1,n.adoption={};for(let e of yn.get(t)??[])e.namespaceAllowed=!1,e.residentAllowed=!1}function En(e){vn.set(e,{source:e.getText(`source`).toString(),mutation:void 0,adoption:void 0,pendingRetirement:!0})}function Dn(e){if(Te)return;wn(e);let t=Je.documents.get(e);t&&En(t),_n.current?.deleted(e)}function On(e){let t=Je.documents.get(e),n=t?Cn(t):void 0,r=n?.adoption;return()=>{Te||(wn(e),t&&Je.documents.get(e)===t&&vn.get(t)===n&&n?.adoption===r&&En(t))}}function kn(e,t){let n=vn.get(e)?.mutation;if(n)return()=>{vn.get(e)===n.occurrence&&Tn(e,t)}}function An(e,t){Sn(e)&&Tn(t,e)}function jn(e,t){let n=Je.documents.get(e),r=()=>(t?.()??!0)&&!Sn(e),i=!Te&&r(),a={namespaceAllowed:i,residentAllowed:!Te&&n!==void 0&&(i||Cn(n).pendingRetirement)},o=yn.get(e)??new Set;return Te||(o.add(a),yn.set(e,o)),{document:n,namespaceCurrent:()=>(a.namespaceAllowed&&!r()&&(a.namespaceAllowed=!1),a.namespaceAllowed),residentCurrent:()=>(a.residentAllowed&&(n===void 0||n.isDestroyed||Je.documents.get(e)!==n)&&(a.residentAllowed=!1),a.residentAllowed),dispose:()=>{a.namespaceAllowed=!1,a.residentAllowed=!1,o.delete(a),o.size===0&&yn.delete(e)}}}let B=(e,t)=>{CW(e)||gn.setRenamed(e,t)},Mn=e=>{if(!CW(e)){if(gn.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}gn.setDeleted(e)}},Nn=e=>{CW(e)||gn.delete(e)};try{let m=oee;try{m=L()}catch(e){C.warn({err:e},`[content-filter] invalid attachment folder at boot — using default attachment placement`)}be=m,He=QG({projectDir:r,contentDir:n,isContentScopeExcluded:e=>{if(Ee.kind!==`tree`)return!1;try{let t=BK(e);return Ee.excluded.some(e=>FK({kind:`tree`,path:e,excluded:[]},t))}catch(t){let n=qW(t);if(!(t instanceof mK)&&n!==`EACCES`&&n!==`EPERM`)throw t;return C.warn({path:uH(e),code:n},`[content-filter] scope path could not be inspected`),!0}},singleDocRelPath:v,attachmentFolderPath:m,inPlaceSkillDirs:new Set(R1(n).map(e=>e.dir)),rescanInPlaceSkillDirs:e=>Jut(n,e),skillRootPaths:Gut(n),onAfterRebuild:()=>{Ue.refreshContentScope().catch(e=>{Y(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),bit(Yr).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?Y(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):Y(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{Y(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),Ue=new Xmt({projectDir:r,contentDir:n,contentFilter:He,getGlobalSkillRoots:()=>Uyt(Ke.managedArtifactCtx),signalChannel:Et,getLocalTargetInventory:()=>F2(Yr,b),onRecoveredFileTarget:(e,t)=>{Yr&&BLt({watcher:Yr,contentDir:n,relativePath:e,exists:t,invalidateReferencedAssetsCache:it})}}),We={current:f},Ge=s?ZIt({getShadow:()=>We.current??null,getCurrentBranch:T,contentRoot:p??``,projectGitDir:_x(r)??void 0,isWriterLive:e=>{if(!rt&&!Ye)return Y(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(rt?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of Ye?.sessionsForConnection(t)??[])return!0;return!1}}):void 0;let _=null;Ke=ALt({contentDir:n,assertContentPath:De,projectDir:r,conflicts:ce,lifecycleOf:(e,t)=>ce.lifecycleOf(e,t),gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:We,ephemeral:y,contentRoot:p,derivedDocumentIndex:Ue,configHomedirOverride:u,getCurrentBranch:T,resolveEmbed:Be,resolveSize:Ve,getPrincipal:()=>ct,onAgentCommit:()=>O?.signal(`session-activity`),onFlushCommit:()=>Ge?.noteFlushCommit(),capturePublicationReceipt:kn,onDiskFlush:(e,t,n,r)=>{O?.emitDiskAck(e,t),!CW(e)&&(nIt(r,n,e)&&$t(e),Xgt(r,n)&&(it?.(),Et(`files`)))},onConfigRejected:(e,t)=>O?.emitConfigValidationRejected(e,t),onConfigPersisted:e=>{Se(e),_e(e)},onManagedSkillPersisted:e=>{let t=bo(e);t?.kind===`skill`&&t.scope===`global`&&(_!==null&&clearTimeout(_),_=setTimeout(()=>{_=null;let e=u??_c();B1(e).then(t=>t0(e,e,t)).then(e=>{e>0&&C.info({refreshed:e},`[in-place-skills] post-edit copy re-sync`)}).catch(e=>C.warn({err:e},`[in-place-skills] post-edit copy re-sync failed`))},2e3),_.unref?.())},isRecentlyRemoved:e=>gn.has(e),mdManager:e.mdManager,getLossRing:()=>qe,mergeHistory:xt,ingestDiskAtStore:async(e,t,n)=>{let r;try{r=await Vr({kind:`update`,path:t,docName:e,content:n})}catch(e){return{kind:`failed`,error:e}}switch(r.kind){case`applied`:return r.merge===void 0?{kind:`taken-in`}:{kind:`taken-in`,merge:r.merge};case`nothing-to-take`:return{kind:`taken-in`};case`conflict`:return{kind:`conflict`};case`failed`:return{kind:`failed`,error:r.error};default:return zr(r)}},durabilityState:M}),yt=e=>Ke.hasHeldSave(e),Je=new ZXe({quiet:i,debounce:a,maxDebounce:o,extensions:[Ke.extension]});let w=Je.hooks.bind(Je);Je.hooks=(e,t,n)=>{if((e===`afterLoadDocument`||e===`onChange`)&&`document`in t&&!CW(t.document.name)){let n=t.document,r=Cn(n);e===`onChange`&&r.mutation===void 0&&n.getText(`source`).toString()!==r.source&&(r.source=void 0,r.mutation={occurrence:r})}return e===`connected`&&`connection`in t&&t.connection&&!CW(t.documentName)&&An(t.documentName,t.connection.document),w(e,t,n)};let D=Je.openDirectConnection.bind(Je);function k(e){if(Te)throw new zK(!1);if(CW(e)){if(v!==void 0&&e!==`__system__`&&!vW(e))throw new RK;return}if(v!==void 0&&YU(e)!==YU(UU(v)))throw new RK;if(we)throw new zK(!1);J8e(Ee,AG(e,n))}Je.openDirectConnection=(async(e,t)=>{let n=YU(e);return k(n),D(n,t)});let A=Je;dt.push(Bat(()=>A.documents.size),Vat(()=>Ke.getQueueDepths()),Uat(()=>{let e=0;for(let t of A.documents.values())e+=t.directConnectionsCount;return{websocket:A.getConnectionsCount()-e,direct:e}})),Gat(),y||(at=jLt({getLoadedDocuments:()=>A.documents,lifecycleOf:(e,t)=>ce.lifecycleOf(e,t),forceStore:(e,t)=>Ke.forceStore(e,t),isHeldSaveDue:e=>Ke.isHeldSaveDue(e),retryHeldSave:(e,t)=>Ke.retryHeldSave(e,t),getBase:e=>M.getReconciledBase(e),isBatchActive:()=>M.isBatchInProgress(),hasInFlight:e=>M.inFlightFlushCount(e)>0,readDiskBytes:e=>{let t=AG(e,n),r,i;try{r=cc(t),i=fc(r).size}catch(t){let n=qW(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new y9(`symlink cycle at content path: ${e}`):t}if(vK(t,r,n))throw new y9(`symlink-escape: ${t} resolves outside the content dir or into private state`);if(i>524288)throw new y9(`document exceeds the open byte limit: ${e}`);try{return J(r,`utf-8`)}catch(e){if(qW(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs})),pt=Je.shouldUnloadDocument.bind(Je),Je.shouldUnloadDocument=e=>{let t=lt.get(e);if(t)return[...t].some(e=>e());if(ut&&!CW(e.name)&&M.isStoreRefused(e.name))return!1;if(ut&&pt(e))return!0;let n=e.name;return CW(n)||ee(n)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:pt(e)},ft=async(e,t)=>{let n=()=>Je.documents.get(e.name)===e&&(t?.()??!0),r=lt.get(e)??new Set;r.add(n),lt.set(e,r);try{await Je.unloadDocument(e)}finally{r.delete(n),r.size===0&&lt.delete(e)}},O=new y4e(Je),nt=new Y7e(Je),rt=new Z7e(Je),Ye=new jot(Je,{...e.agentSessionOptions,assertDocumentScope:k,awaitWriteAdmission:()=>M.whenWriteAdmitted()});let j=Ye;dt.push(Wat(()=>({active:j.liveSessionCount,limit:j.sessionLimit})));let N=MIt({derivedDocumentIndex:Ue,onDocumentSettled:e=>_n.current?.changed(e)});Je.configuration.extensions.push(N);function P(e,t,n={}){C.warn({reason:e,docName:t,...n},`[auth-rejection] ${e}`)}Je.configuration.extensions.push({__kind:`principal-auth`,async beforeHandleMessage(e){k(e.documentName)},async onAuthenticate(e){k(e.documentName);let t=e.token,n=p5(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==Ce)throw P(`server-instance-mismatch`,e.documentName,{claimedServerInstanceId:r,currentServerInstanceId:Ce}),new f5(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${Ce}`);let i=n?.expectedBranch;if(typeof i==`string`&&i.length>0){let t=await Tt();if(t!==null&&i!==t)throw P(`branch-mismatch`,e.documentName,{claimedBranch:i,currentBranch:t}),new f5(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${t}`)}if(!n)return;let a=e.context;typeof n.principalId==`string`&&(ct&&n.principalId===ct.id?a.principalId=ct.id:ct?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:ct.id})):a.principalId=n.principalId),typeof n.tabSessionId==`string`&&(a.tabSessionId=n.tabSessionId),a.kind=`human`}}),Je.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!vW(e.documentName)&&!yW(e.documentName))return;let n=e.request,r=n.socket?.remoteAddress;if(r!==void 0&&!NQ(r,t))throw P(`config-doc-admission-denied`,e.documentName,{check:`peer`}),Error(`config-doc admission requires loopback peer (peer=${r}, doc=${e.documentName})`);let i=e.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0;if(!PQ(a,t))throw P(`config-doc-admission-denied`,e.documentName,{check:`host`}),Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${e.documentName})`)}}),Je.configuration.extensions.push(LLt(e=>P(`config-doc-admission-denied`,Zn,{check:`private-skill-trust`,rejectionClass:e}))),Je.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){if(!CW(e.documentName)){let t=xn(e.documentName);if(t!==null&&!q(t))try{await Promise.race([St.promise,mt])}catch(t){throw C.error({err:t,docName:e.documentName},`[removal-guard] missing-document admission refused after startup failure`),t}}await HLt(e.documentName,{recentlyRemovedDocs:gn,resolveFilePath:xn,fileExists:q})}}),Je.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=p5(e.token);iIt(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Je.documents.get(e)})}}),Je.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new MV(e.update);if(t.readVarString(),t.readVarUint()===RV.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${lr} rejected — server-only channel`)}}),Je.configuration.extensions.push({async afterUnloadDocument({documentName:e}){M.endRenameCarry(e)}});let te=XDt({mergeHistoryWriter:e.mergeHistoryWriter,docNotices:bt,declaredGitHubHosts:x,resolveSyncCredentialConfig:S,hocuspocus:Je,durabilityState:M,ingressPolicy:t,sessionManager:Ye,commentDocHooksRef:_n,onNamespaceCreateAccepted:Dn,capturePublicationReceipt:kn,captureNamespaceMove:On,onResidentAdopted:Tn,contentDir:n,assertContentPath:De,assertContentSubtree:Oe,getGeneratedIndexSettingsStatus:un,setGeneratedIndexEnabled:dn,contentFilter:He,serverInstanceId:Ce,getFileIndex:()=>Yr?Yr.getFileIndex():new Map,getAttachmentFolderPath:L,getAllFilesIndex:()=>Yr?Yr.getAllFilesIndex():new Map,getFileIndexGeneration:()=>Yr?.getFileIndexGeneration()??0,mutateFileIndex:e=>{let t=e.kind===`update`?rn(e.docName):void 0;switch(Yr?.mutateFileIndex(e),e.kind){case`update`:rIt(t,e.content,e.docName)&&$t(e.docName);break;case`create`:Vn(e.docName,e.content),$t(e.docName);break;case`conflict`:$t(e.docName);break;case`delete`:_n.current?.deleted(e.docName),tn(e.docName);break;case`rename`:tn(e.oldDocName),$t(e.newDocName);break;case`folder-create`:case`folder-delete`:en(e.relativePath);break;case`asset-create`:case`asset-delete`:case`file-create`:case`file-update`:case`file-delete`:break;default:$Y(e)}},getFolderIndex:()=>Yr?Yr.getFolderIndex():new Map,getAliasMap:()=>Yr?Yr.getAliasMap():new Map,getFolderAliasIndex:()=>Yr?Yr.getFolderAliasIndex():new Map,resolveTrackedFile:Le,rescanFiles:()=>Yr?.rescanFromDisk(),settleDiskEventsForTest:async()=>{await Yr?.settle()},enableTestRoutes:d,shadowRef:We,flushGitCommit:()=>Ke.flushPendingGitCommit(),flushContributors:()=>Ke.flushContributors(),getCurrentBranch:T,getReportedBranch:E,getDiskAckSVs:()=>O?.getLatestDiskAckSVsAsBase64()??{},getCollabClientCount:e.getCollabClientCount,contentRoot:p,derivedDocumentIndex:Ue,signalChannel:Et,agentFocusBroadcaster:nt,agentPresenceBroadcaster:rt,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>ei,conflicts:ce,setBatchInProgress:oe(`conflict-resolve`),refreshDocumentsFromDisk:Qr,localOpCliArgs:h,authStreamHeartbeatMs:g,projectDir:r,resolveEmbed:Be,getBridgeLossReporter:()=>$e,getPrincipal:()=>ct,agentIntegrations:e.agentIntegrations,acpRegistry:Me,loadAcpCustomAgents:()=>TU(je,Y(`acp-registry`)),homeDirOverride:u,resetSettingsForTest:u===void 0?void 0:()=>{for(let e of ro)dFt(Je.documents.get(e)??null,e,Ke.configPersistenceCtx),Ln.get(e)?.(),Se(e)},forceUnloadDocument:ft,ready:mt,recentlyRemovedDocs:gn,serializeDoc:zn,evictManagedArtifactLkg:e=>{Ke.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:st,getSemanticSimilarityFloor:()=>me().similarityFloor,getLinterBaseConfig:()=>fe(),getLinkAdvisoryPolicy:pe,getProjectConfigEpoch:()=>xe,getLinkPreviewsEnabled:he,resolveGitHubToken:Jwt(e.detectGh,e.tokenStore),getConfigDiagnostics:ge,embeddingsSecretsFile:p4(u),readSemanticProviderConfig:me,ephemeral:y,onReferencedAssetsCacheInvalidator:e=>{it=e}});Je.configuration.extensions.push(te),Je.configuration.extensions.push(hIt({clock:e.watcherClock??qY(),refresh:Qr})),R=te.nativeApi,Ze=te.localApi,Qe=te.shutdownLocalOps;let F=gl({absPath:yl(`project`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project config for bridge guards`)}),I=F.value.bridge.deferGuard.enabled,ne=F.value.bridge.fixedPoint.enabled,re=F.value.bridge.preDrain.enabled;qe=F.value.lossCapture.enabled?new s9e({projectDir:r,maxBytes:F.value.lossCapture.maxBytes}):void 0,F.value.bridge.lossDetector.enabled&&($e=Xet({shadow:()=>We.current,ring:qe,getBranch:()=>T()??`main`,contentRoot:p??``}),Ye.attachBridgeLossReporter($e)),Je.configuration.extensions.push(JLt({mdManager:qa,schema:xa,shadowRef:We,contentRoot:p,getCurrentBranch:T,resolveEmbed:Be,resolveSize:Ve,deferGuardEnabled:I,lossDetectorEnabled:F.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:ne,preDrainEnabled:re,lossRing:qe})),Je.configuration.extensions.push(azt()),Je.configuration.extensions.push({async afterLoadDocument({document:e}){Cit(e,ce)}})}catch(e){for(let e of dt.splice(0))e();at?.dispose(),at=null,we=!0,F4(je);try{Pe.release()}catch(e){C.error({err:e},`[server] construction authority release failed`)}throw e}let Pn=null,Fn=new Map,In=[],Ln=new Map;function Rn(e,t){let n=K(e,`rescue`),r=XU(t),i=K(n,r);return YW(i,n)?i:null}function zn(e){let t=Je.documents.get(e);return t?_$(t):null}let Bn=(e,t)=>{let n=Je.documents.get(e);s$(M,Je,e,t,Be,Ve,$e),n&&Sn(e)&&Tn(n,e)},Vn=(e,t)=>{let n=Jst(M,Je,e,t,Be,Ve,$e),r=Je.documents.get(e);return n===`revived`&&r&&Sn(e)&&Tn(r,e),n},V=(e,t)=>{let n=YDt(M,Je,e,t,Be,Ve,$e);n&&An(e,n)},Hn=(e,t)=>{let n=0;for(let[r]of Je.documents){if(CW(r))continue;let i=Je.documents.get(r);if(!i)continue;let a=i.getText(`source`).toString();if(a.includes(e))try{i.transact(()=>{i$(i,a,Be,r)},r$),n++}catch(e){C.error({originalError:o$(e),docName:r,...t},t.reason===`asset-event`?`[asset-event] failed to re-render ${r} for asset basename ${t.assetBasename}`:`[basename-index] failed to refresh loaded startup embeds in ${r}`)}}return n},Un=e=>{e&&Hn(`[[${e}]]`,{reason:`asset-event`,assetBasename:e})},Wn=()=>{try{let e=Hn(`![[`,{reason:`startup`});C.debug({documentCount:e},`[basename-index] refreshed loaded startup embeds`)}catch(e){C.warn({err:e},`[basename-index] loaded startup embed refresh failed`)}},Gn=null,Kn=e=>{e&&(Gn===null&&(Gn=new Set,setImmediate(()=>{let e=Gn;if(Gn=null,e)try{for(let t of e)Un(t)}catch(t){C.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Gn.add(e))};function qn(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return $Y(e)}}let Jn={delete:`external-change-rescue`,rename:`external-change-rescue`,"branch-switch":`external-change-rescue`,"disk-update":`external-change-rescue-disk-update`},Yn=(e,t,n,r,i=``,a=!1)=>{if(!We.current){let t=a?r===`delete`?` — the delete that follows destroys the document content`:` — the overwrite that follows replaces the document content`:``;return C.warn({docName:e,site:r},`[reconcile] rescue checkpoint not minted for ${e} (${r}) — shadow repo unavailable${t}`),$U(),!1}let o=We.current;return queueMicrotask(()=>{MJ(o,p??``,{kind:Jn[r],docName:e,contents:t,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:i}}).then(()=>{h0e(),C.info({docName:e,site:r},`[reconcile] rescue checkpoint saved (${r}): ${e}`)}).catch(t=>{g0e();let n=a?r===`delete`?` — the delete that follows destroys the document content`:` — the overwrite that follows replaces the document content`:``;C.error({docName:e,site:r,err:t},`[reconcile] rescue checkpoint write failed (${r}): ${e}${n}`)})}),!0},Qn=new WeakSet,$n=e.watcherClock??qY(),er=null,tr=!1,nr=e=>{ne.hold(e),M.holdStores(e.docName)},rr=new Set,ir=new Map,ar=e=>{ne.release(e),ir.delete(e),rr.delete(e),M.releaseStores(e)},or=null,sr=0;function cr(){sr+=1,$n.clearTimeout(or),or=null}function ur(e){cr(),dr(e,sr,1).catch(t=>{C.error({err:t,branch:e},`[branch-switch] the follow-up re-checks stopped`)})}async function dr(e,t,n){if(!Yr||t!==sr)return;let r;try{r=await Yr.recheck(`full`)}catch(t){C.warn({err:t,branch:e,attempt:n},`[branch-switch] follow-up re-check ${n} after switching to ${e} failed`)}if(t!==sr||r?.status===`closed`)return;if(r?.status===`completed`&&!r.partial){C.info({branch:e,attempt:n},`[branch-switch] follow-up re-check ${n} observed the whole tree after switching to ${e}`);return}s4e();let i={branch:e,attempt:n,status:r?.status??`failed`,partial:r?.partial===!0};if(n>=3){C.warn(i,`[branch-switch] ${n} follow-up re-checks after switching to ${e} did not observe the whole tree; open documents may keep text from the previous branch until a later re-check observes it`);return}C.warn(i,`[branch-switch] follow-up re-check ${n} after switching to ${e} did not observe the whole tree; trying again in ${gzt/1e3} s`),or=$n.setTimeout(()=>{or=null,dr(e,t,n+1).catch(t=>{C.error({err:t,branch:e},`[branch-switch] the follow-up re-checks stopped`)})},gzt),or.unref()}let fr=()=>{er||tr||ne.size===0||(er=$n.setTimeout(()=>{er=null,pr().catch(e=>{C.error({err:e},`[reconcile] the re-check loop for vanished documents failed`)})},1e3),er.unref())};async function pr(){if(!Yr)return;tr=!0;let e;try{e=await Yr.recheck(`metadata`)}catch(e){C.warn({err:e},`[reconcile] the re-check for vanished documents failed`)}finally{tr=!1}try{ne.size>0&&(e?.status!==`completed`||e.partial)&&C.info({status:e?.status??`failed`,partial:e?.partial===!0},`[reconcile] the re-check for ${ne.size} vanished document(s) did not observe the whole tree; trying again`),await Er()}finally{fr()}}function mr(e){try{return nc(e),!0}catch(t){let n=qW(t);return n===`ENOENT`||n===`ENOTDIR`?!1:(C.warn({err:t,path:e},`[reconcile] could not tell whether a vanished file is gone`),!0)}}function hr(e,t){let r=e=>{let t=qW(e);return t===`ENOENT`||t===`ENOTDIR`?{kind:`absent`}:{kind:`unreadable`,code:t??`unknown`}};try{nc(t),xae(t,$s.R_OK)}catch(e){let t=r(e);if(t.kind===`absent`||qW(e)!==`ELOOP`)return t}if(!RX(e,t,n,He))return{kind:`refused`};try{return{kind:`present`,path:t,content:J(t,`utf-8`)}}catch(e){return r(e)}}function gr(e){let t=Yr?.getFileIndex().get(e.docName)?.canonicalPath??xn(e.docName)??e.path;return hr(e.docName,t)}async function _r(e){if(!Yr||mr(e.path))return!1;let t=Art(e),n=ee(e.docName),r=new Set;t.lastHash!==void 0&&r.add(t.lastHash),n!==void 0&&r.add(XW(n));let i={docName:e.docName,path:e.path,identity:t.identity,size:t.size,modified:t.modified,hashes:r,text:n??zn(e.docName)??void 0},a=ne.matchRecentCreate(i,$n.now(),e=>{let t=hr(e.docName,e.path);return t.kind===`present`?t.content:void 0});if(a){let t=hr(a.create.docName,a.create.path);if(t.kind===`present`)return mW(a.by===`identity`?`paired-identity`:`paired-hash`),await Ur({kind:`rename`,oldPath:e.path,newPath:a.create.path,oldDocName:e.docName,newDocName:a.create.docName,content:t.content}),!0;C.info({docName:e.docName,create:a.create.docName,probe:t.kind},`[reconcile] ${e.docName}: a recent create could not be read; holding the document instead`)}return nr({...i,afterPass:Yr.recoveryPassesStarted(),heldAt:$n.now()}),mW(`pending`),C.info({docName:e.docName},`[reconcile] ${e.docName}: its file vanished; it stays open until a re-check of the whole tree, in case it was moved`),fr(),!0}let vr=()=>{se()||Ke.flushDeferredStores(`within-branch`).catch(e=>{C.error({err:e},`[persistence] deferred store drain failed after a vanished file resolved`)})};async function yr(e,t){ar(e.docName);try{mW(`recreated`),C.info({docName:e.docName},`[reconcile] ${e.docName}: its file is back; taking it in as an update`),await Gr({kind:`update`,path:t.path,docName:e.docName,content:t.content})}finally{vr()}}async function br(e,t){Ke.discardDeferredStore(e.docName,{kind:`deleted-outside`}),ar(e.docName),mW(t);let n={kind:`delete`,path:e.path,docName:e.docName};Qn.add(n),await Gr(n)}function xr(e,t){rr.has(e.docName)||(rr.add(e.docName),C.warn({docName:e.docName,code:t},`[reconcile] ${e.docName}: a file is at its path but cannot be read (${t}); it stays held until it can be read or the hold limit passes`))}function Sr(e,t,n,r){let i=ne.has(e.docName),a=r===void 0?``:` (attempt ${r} of 3 past the hold limit)`;C.error({err:n,docName:e.docName,action:t.action,stillHeld:i,overdueAttempt:r},i?`[reconcile] ${e.docName}: ${t.action} failed with an internal error${a}; it is still held`:`[reconcile] ${e.docName}: ${t.action} failed with an internal error${a}; its hold had already ended`)}function Cr(e,t){ar(e.docName),vr(),C.error({docName:e.docName,attempts:t},`[reconcile] ${e.docName}: ended its hold after ${t} failed attempts past the hold limit; its deferred saves were released to run as normal saves`)}async function wr(e,t){if(t)for(let t of ne.dueAfter(e)){let e={action:`checking its path`};try{await Tr(t,e)}catch(n){Sr(t,e,n)}}}async function Tr(e,t){let n=gr(e);switch(n.kind){case`present`:t.action=`taking its returned file in`,await yr(e,n);return;case`unreadable`:xr(e,n.code);return;case`absent`:case`refused`:t.action=`applying the delete`,C.info({docName:e.docName,probe:n.kind},`[reconcile] ${e.docName}: no move found after a re-check of the whole tree; the delete stands`),await br(e,`deleted`);return;default:throw Error(`unhandled file probe: ${JSON.stringify(n)}`)}}async function Er(){for(let e of ne.heldBefore($n.now()-L9)){let t={action:`resolving its hold at the limit`};try{await Dr(e,t)}catch(n){if(!ne.has(e.docName)){Sr(e,t,n);continue}let r=(ir.get(e.docName)??0)+1;ir.set(e.docName,r),Sr(e,t,n,r),r>=3&&Cr(e,r)}}}async function Dr(e,t){let n=`${L9/1e3} s`,r;try{r=gr(e)}catch(t){C.error({err:t,docName:e.docName,limitMs:L9},`[reconcile] ${e.docName}: checking its path at the hold limit failed with an internal error; the delete stands as at any hold limit`)}switch(r?.kind){case void 0:break;case`present`:t.action=`taking its returned file in`,await yr(e,r);return;case`absent`:C.warn({docName:e.docName,probe:r.kind,limitMs:L9},`[reconcile] ${e.docName}: its file is gone and no re-check observed the whole tree within ${n}; the delete stands and unsaved typing is in its history`);break;case`unreadable`:C.warn({docName:e.docName,probe:r.kind,code:r.code,limitMs:L9},`[reconcile] ${e.docName}: a file at its path still cannot be read (${r.code}) after ${n}; the hold ends, the document closes and unsaved typing is in its history`);break;case`refused`:C.warn({docName:e.docName,probe:r.kind,limitMs:L9},`[reconcile] ${e.docName}: the entry at its path is still not an admitted Markdown file after ${n}; the hold ends, the document closes and unsaved typing is in its history`);break;default:throw Error(`unhandled file probe: ${JSON.stringify(r)}`)}t.action=`applying the delete at the hold limit`,await br(e,`unconfirmed`)}function Or(e,t,n){let r=T()??`main`,i={from:e,to:t,toFile:`${t}${Ws(n)}`},a={writerId:TJ.id,displayName:TJ.name,colorSeed:TJ.id};I8({moves:[i],kind:`file`,branch:r,writer:a,shadow:void 0,notices:bt});let o=We.current;o&&Ar(o,r,i,a)}async function kr(e,t){try{return(await yJ(e).raw(`for-each-ref`,`--sort=-committerdate`,`--format=%(objectname)`,`refs/wip/${t}/`)).split(`
2323
- `).map(e=>e.trim()).filter(e=>/^[0-9a-f]{40}$/.test(e))}catch(e){return C.warn({err:e,branch:t},`[reconcile] rename: could not read the writers' history heads; the move is recorded without them`),[]}}async function Ar(e,t,n,r){let i=await kr(e,t),a;try{a=I8({moves:[n],kind:`file`,branch:t,writer:r,shadow:e,notices:void 0,anchors:i})}catch(e){a4e(),C.warn({err:e,oldDocName:n.from,newDocName:n.to},`[reconcile] rename: could not write the rename-log entry for ${n.from} -> ${n.to}; history before the move will not show under the new name`);return}if(a===0)return;let o;try{await Ke.flushContributors()}catch(e){o=e}let s=E$(e.gitDir).byTo.get(n.to);if(s!==void 0&&s.commitSha===``){o4e(),C.warn({err:o,oldDocName:n.from,newDocName:n.to},`[reconcile] rename: wrote the rename-log entry for ${n.from} -> ${n.to}, but no commit claimed it yet; a later commit by the file-system writer claims it, and the next start drops it if none does`);return}o!==void 0&&C.warn({err:o,oldDocName:n.from,newDocName:n.to},`[reconcile] rename: the commit after recording the move failed`)}async function jr(e,t,n,r,i){let a;try{return a=await Je.openDirectConnection(e),Bn(e,r),te(e,n),i!==n&&await Ur({kind:`update`,path:t,docName:e,content:i}),C.info({newDocName:e},`[reconcile] rename: unsaved typing carried into ${e}`),!0}catch(t){return C.error({err:t,newDocName:e},`[reconcile] rename: could not carry unsaved typing into ${e}; it is in the rename checkpoint`),!1}finally{await a?.disconnect()}}function Nr(e){for(let[t,r]of Je.documents)if(!CW(t)&&r.getMap(`lifecycle`).get(`status`)===void 0)try{let i=AG(t,n);if(!q(i)||!vK(i,cc(i),n))continue;Pr(t,e,`branch-switch`),r.getMap(`lifecycle`).set(`status`,`deleted-upstream`),C.warn({docName:t,branch:e},`[branch-switch] tombstone: ${t} resolves outside the content dir or into private state on ${e}`)}catch(e){C.error({err:e,docName:t},`[branch-switch] could not check where ${t} resolves`)}}let Pr=(e,t,n,r=!1)=>{let i=ee(e),a=zn(e)??``,o=i===void 0?a!==``:a!==i;return o&&(Yn(e,a,t,n,``,r),o)};function Fr(e){ce.dissolveReconcile(e),ce.dissolveWorkingTree(ce.fileOf(e))}let Ir=(e,t,n,r)=>{(t.kind===`merged`||t.kind===`both-kept`)&&t.dedupSkipped&&(t0e(),C.warn({docName:e,oursLen:n.length,theirsLen:r.length,newLen:t.newContent.length},`[reconcile] ${e} insert-group dedup skipped (LCS cell cap); union emitted with possible same-block duplication`))},Lr=async(e,t,n)=>{let r=n===void 0;P2e();let i=zn(e)??``,a=T()??`main`,o=XW(t).slice(0,6),s=i!==``&&i!==t,c=s?oi(e,`disk-authoritative-ingest`):`not-needed`;s&&Yn(e,i,a,`disk-update`,o,!0);let l=XW(i).slice(0,6),u=r?`absent`:`blockless`,d,f=!1;try{Bn(e,t),Fr(e),f=!0}catch(s){d=s,F2e(),C.error({err:s,docName:e},`[reconcile] failed to apply disk-authoritative ingest to Y.Doc for ${e}`),Yn(e,t,a,`disk-update`,o,!0),Fr(e);let f;try{f=zn(e)??void 0}catch(t){C.error({err:t,docName:e},`[reconcile] unable to read ${e} back after a failed disk-authoritative ingest; treating the live content as lost`)}f===t?te(e,t):M.restoreReconciledBase(e,n),c===`lost`&&f!==i&&(I2e(),C.warn({docName:e,baseAbsent:r,reason:`no-base`,ours:l,theirs:o,result:`clean-unrescued`,rescue:c,applyFailed:!0},`[reconcile] ${e} base=${u} reason=no-base result=clean-unrescued ours=${l} theirs=${o} rescue=${c} applyFailed=true`))}if(f){let n=c===`lost`?`clean-unrescued`:`clean`;return c===`lost`&&I2e(),(c===`lost`?C.warn.bind(C):C.info.bind(C))({docName:e,baseAbsent:r,reason:`no-base`,ours:l,theirs:o,result:n,rescue:c},`[reconcile] ${e} base=${u} reason=no-base result=${n} ours=${l} theirs=${o} rescue=${c}`),await Rr(e,t),s?{kind:`applied`,merge:`disk-replaced`}:{kind:`applied`}}return{kind:`failed`,error:d}},Rr=async(e,t)=>{try{await Ue.recordDiskUpsert(e,t)}catch(t){C.warn({err:t,docName:e},`[reconcile] ${e}: the derived index could not record the disk version`)}};function zr(e){throw Error(`unhandled disk intake outcome: ${e.kind}`)}function Br(e){throw Error(`unhandled reconcile outcome: ${e.kind}`)}async function Vr(e){let{docName:t,content:n}=e;if(Nn(t),rIt(e.previousIndexedFields,n,t)&&$t(t),ce.findByDocName(t)?.kind===`merge-native`)try{await ce.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e,docName:t},`[reconcile] conflict prune against git failed`)}let r=Je.documents.get(t);if(!r)return p$(M,void 0,t,n,ce)||M.refreshReceiptWithoutBase(t,n),await Ue.recordDiskUpsert(t,n),{kind:`nothing-to-take`};if(Vn(t,n)!==`not-frozen`)return await Ue.recordDiskUpsert(t,n),{kind:`nothing-to-take`};let i=XW(n),a=Lyt({receiptHash:M.getReceipt(t)?.hash,eventHash:i,isRecentOwnWrite:M.isRecentOwnWrite(t,i),readDiskHash:()=>{try{return XW(J(e.path,`utf-8`))}catch{return null}}}),o=Ryt(a);if(o!==null&&M.getStaleExternalWrite(t)===void 0)return f2e(o),C.debug({docName:t,receiptIntake:a},`[reconcile] ${t}: the disk bytes match its receipt (${a}); nothing to take in`),ce.dissolveReconcile(t),await Rr(t,n),{kind:`nothing-to-take`};let s=ee(t),c=zn(t)??s??``;if(p$(M,r,t,n,ce,c))return await Rr(t,n),{kind:`conflict`};if(s===void 0)return Lr(t,n,void 0);let l=$J({docName:t,base:s,ours:c,theirs:n}),u=XW(s).slice(0,6),d=XW(c).slice(0,6),f=XW(n).slice(0,6),p=c.length,m=n.length,h=l.kind===`clean`||l.kind===`merged`||l.kind===`both-kept`?l.newContent.length:void 0,g=h===void 0?void 0:h-Math.max(p,m),_=h===void 0?``:` newLen=${h} delta=${g}`;switch(C.info({docName:t,base:u,ours:d,theirs:f,result:l.kind,oursLen:p,theirsLen:m,...h===void 0?{}:{newLen:h,delta:g}},`[reconcile] ${t} base=${u} ours=${d} theirs=${f} result=${l.kind} oursLen=${p} theirsLen=${m}${_}`),Ir(t,l,c,n),l.kind){case`noop`:return ce.dissolveReconcile(t),await Rr(t,n),{kind:`nothing-to-take`};case`clean`:try{Bn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),te(t,s),ce.dissolveReconcile(t),{kind:`failed`,error:e}}return te(t,l.newContent),QU(),ce.dissolveReconcile(t),await Rr(t,n),{kind:`applied`,merge:`clean`};case`merged`:try{Bn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),te(t,s),ce.dissolveReconcile(t),{kind:`failed`,error:e}}return te(t,n),QU(),ce.dissolveReconcile(t),await Rr(t,n),{kind:`applied`,merge:`merged`};case`both-kept`:try{Bn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply both-kept content to Y.Doc for ${t}; raising the conflict`),te(t,s),e0e(),ce.raise({kind:`reconcile`,file:ce.fileOf(t),reason:`merged-with-markers`,stages:{base:s,ours:c,theirs:n}}),{kind:`failed`,error:e}}return xt.bothKept(t,{ours:c,theirs:n},l.kept),te(t,n),QU(),d$(t,l.kept,`watcher`),ce.dissolveReconcile(t),await Rr(t,n),{kind:`applied`,merge:`both-kept`};case`refused`:return l.reason===`no-base`?Lr(t,n,s):(u$(t,l,`watcher`),(l.reason===`check-failed`||l.reason===`too-large`)&&await xt.keptLive(t,{side:`theirs`,bytes:n},l.reason)?(te(t,n),f$(t,l.reason,`watcher`),ce.dissolveReconcile(t),await Rr(t,n),{kind:`applied`,merge:`kept-live`}):(e0e(),ce.raise({kind:`reconcile`,file:ce.fileOf(t),reason:Xst(l.reason),stages:{base:s,ours:c,theirs:n}}),{kind:`conflict`}));default:return Br(l)}}let Hr=new Map;async function Ur(e,t=e.kind===`delete`||e.kind===`rename`?Hr.get(e)??jn(e.kind===`delete`?e.docName:e.oldDocName,LX(e)):void 0){try{switch(e.kind){case`create`:{let t=Art(e),n=XW(e.content),r=ne.matchCreate({docName:e.docName,identity:t.identity,size:t.size,modified:t.modified,hash:n,content:e.content});if(r){if(ar(r.vanished.docName),r.by===`same-name`){mW(`recreated`),C.info({docName:e.docName},`[reconcile] ${e.docName}: its file came back; taking it in as an update`),await Ur({kind:`update`,path:e.path,docName:e.docName,content:e.content}),vr();break}let t=M.beginRenameCarry(r.vanished.docName);try{Ke.discardDeferredStore(r.vanished.docName,{kind:`renamed-outside`,to:e.docName,carry:t}),mW(r.by===`identity`?`paired-identity`:`paired-hash`),await Ur({kind:`rename`,oldPath:r.vanished.path,newPath:e.path,oldDocName:r.vanished.docName,newDocName:e.docName,content:e.content})}finally{M.abandonRenameCarry(r.vanished.docName)}break}ne.rememberCreate({docName:e.docName,path:e.path,identity:t.identity,size:t.size,modified:t.modified,hash:n,at:$n.now()}),C.info({docName:e.docName},`[reconcile] create: ${e.docName}`),Vn(e.docName,e.content),await Ue.recordDiskUpsert(e.docName,e.content),Et(`files`),$t(e.docName),Nn(e.docName);break}case`update`:await Vr(e);break;case`delete`:{let{docName:n}=e,r=t??jn(n,LX(e));Hr.delete(e);try{let t=r.namespaceCurrent(),i=r.residentCurrent();if(!t&&!i){C.debug({docName:n,source:`watcher-delete`,namespaceCurrent:t,residentCurrent:i},`[reconcile] delete skipped: ${n} (stale removal)`);return}if(t&&i&&r.document&&!Qn.has(e)&&await _r(e))return;t&&(Fr(n),_n.current?.deleted(n));let{document:a}=r,o=i&&a?Pr(n,T()??`main`,`delete`,!0):!1;if(i&&(a?.getMap(`lifecycle`).set(`status`,`deleted-upstream`),M.endRenameCarry(n)),t&&F(n),t&&await Ue.recordDiskDelete(n),!r.namespaceCurrent()&&!r.residentCurrent()){C.debug({docName:n,source:`watcher-delete`,namespaceCurrent:!1,residentCurrent:!1},`[reconcile] delete skipped: ${n} (stale removal)`);return}if(C.info({docName:n,isDirty:o,source:`watcher-delete`},`[reconcile] delete: ${n} (dirty=${o})`),r.residentCurrent()&&a&&(Je.closeConnections(n),await ft(a,r.residentCurrent)),!r.namespaceCurrent()){C.debug({docName:n,source:`watcher-delete`,namespaceCurrent:!1,residentCurrent:r.residentCurrent()},`[reconcile] delete: ${n} not recorded as removed (stale removal)`);return}Et(`files`),Mn(n),tn(n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:n,kind:`deleted`,source:`watcher-delete`}))}finally{r.dispose()}break}case`rename`:{let{oldDocName:n,newDocName:r,content:i}=e,a=t??jn(n,LX(e));Hr.delete(e),M.beginRenameCarry(n);let o=null,s=!1,c;try{let t=a.document,l=a.residentCurrent()&&t?t:null,u=l?zn(n):null,d=l?$W(l):null,f=ee(n),p=e=>{let t=e.getMap(`lifecycle`);t.set(`status`,`renamed`),t.set(`newPath`,r)},m=a.residentCurrent()&&t?Pr(n,T()??`main`,`rename`):!1;a.residentCurrent()&&t&&p(t),a.namespaceCurrent()&&(Fr(n),F(n),Ke.forgetObservedFile(n),B(n,r)),te(r,i),C.info({oldDocName:n,newDocName:r,isDirty:m},`[reconcile] rename: ${n} → ${r} (dirty=${m})`),Et(`files`),Nn(r);try{a.namespaceCurrent()?await Ue.recordDiskRename(n,r,i):await Ue.recordDiskUpsert(r,i)}catch(e){C.error({oldDocName:n,newDocName:r,err:e},`[reconcile] rename: index update failed for ${n} → ${r}; completing client teardown anyway`)}let h=a.namespaceCurrent()?Je.documents.get(n):void 0,g=h===t?void 0:h;g&&p(g);try{V(r,i)}catch(e){c={error:e}}$t(r),a.namespaceCurrent()&&Or(n,r,e.newPath),u!==null&&f!==void 0&&(u===f||await jr(r,e.newPath,f,u,i))&&(o=d);let _=a.residentCurrent()&&t?t:g;if(s=!!_,_){let e=_.getConnectionsCount();Je.closeConnections(n),await Ye.closeAllForDoc(n),e>0&&C.info({oldDocName:n,newDocName:r,closedConnections:e},`[reconcile] rename: closed ${e} connection(s) on ${n}`)}if(a.namespaceCurrent()?(console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:n,to:r,kind:`renamed`,source:`watcher-rename`})),tn(n)):C.debug({docName:n,newDocName:r,source:`watcher-rename`,namespaceCurrent:!1,residentCurrent:a.residentCurrent()},`[reconcile] rename: ${n} not recorded as removed (stale removal)`),c)throw c.error}finally{M.settleRenameCarry(n,o),s||M.endRenameCarry(n),a.dispose()}break}case`conflict`:{let{docName:t}=e;if(!Je.documents.get(t))return;let n=ee(t)??``,r=zn(t);r===null?C.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):te(t,r),ce.raise({kind:`reconcile`,file:ce.fileOf(t),reason:`disk-markers`,stages:{base:n,ours:r??n,theirs:e.content}}),C.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:Ie.add(e.relativePath),Et(`files`),Kn(Hs(e.relativePath));break;case`asset-delete`:Ie.remove(e.relativePath),Et(`files`),Kn(Hs(e.relativePath));break;case`folder-create`:case`folder-delete`:Et(`files`),en(e.relativePath);break;case`file-create`:case`file-update`:await Ue.recordFileTargetUpsert(e.relativePath),it?.(),Et(`files`),await Zr(e.relativePath);break;case`file-delete`:await Ue.recordFileTargetDelete(e.relativePath),it?.(),Et(`files`);break;default:$Y(e)}}catch(t){let n=qn(e);C.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let Wr=[];async function Gr(e){if(!Te){if((e.kind===`delete`||e.kind===`rename`)&&!Hr.has(e)&&Hr.set(e,jn(e.kind===`delete`?e.docName:e.oldDocName,LX(e))),se()||Kr!==null){Wr.push(e);return}await Ur(e)}}let Kr=null;function qr(){if(Kr)return Kr;if(Wr.length===0)return Promise.resolve();let e=Promise.withResolvers();return Kr=e.promise,(async()=>{try{for(;Wr.length>0;){let e=Wr.splice(0,Wr.length);for(let t of e)await Ur(t)}e.resolve()}catch(t){e.reject(t)}finally{Kr=null}})(),e.promise}function Jr(){for(let e of Hr.values())e.dispose();Hr.clear()}let Yr=null;function Xr(e){return bW(e)||xW(e)||SW(e)}async function Zr(e){if(!Xr(e))return!1;let t=Je.documents.get(e);return t?await sLt(t,e,Ke.mermaidPersistenceCtx)!==`unchanged`:!1}async function Qr(e,t){if(!Yr)return{checked:0,found:0};let r=Yr.getAliasMap(),i=Yr.getFileIndex(),a=[],o={checked:0,found:0};for(let s of new Set(e)){let e=r.get(s)??s;if(CW(e))continue;if(Xr(e)){o.checked++,await Zr(e)&&o.found++;continue}let c=i.get(e)?.canonicalPath;if(c!==void 0){a.push(c);continue}try{a.push(AG(e,n))}catch(e){C.debug({err:e,trigger:t},`[reconcile] skipped a re-read for a name outside the content tree`)}}let s=a.length===0?{checked:0,found:0}:await Yr.recheckPaths(a),c={checked:s.checked+o.checked,found:s.found+o.found},l={trigger:t,...c};return c.found>0?C.info(l,`[reconcile] re-read on ${t} found outside changes`):C.debug(l,`[reconcile] re-read on ${t} found nothing new`),c}let ei=null,ti=null,ni=!1,ri=null;function ii(e,t){let n=ri;if(n===null||n.authorityGateReached){C.error({err:t,watched:e},`[server] late watcher release failed after shutdown`);return}n.phaseErrors.push({phase:`watcher-unsubscribe`,error:t instanceof Error?t.message:String(t)}),C.error({err:t,watched:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}async function ai(e,t,n){if(ni)return;let r=await e();if(ni){try{await r.unsubscribe()}catch(e){ii(n,e)}return}t(r)}let oi=(e,t)=>{let n=We.current;if(!n)return C.warn({docName:e,context:t},`[rescue] shadow repo unavailable — cannot buffer ${e} (${t})`),$U(),`lost`;try{let r=TW(e)?Je.documents.get(e)?.getText(`source`).toString()??null:zn(e);if(r===null)return C.warn({docName:e,context:t},`[rescue] skipping ${e} — document dropped from map mid-rescue (${t})`),$U(),`lost`;let i=Rn(n.gitDir,e);return i?(SH(U(i),{recursive:!0}),bH(i,r,`utf-8`),h0e(),C.info({docName:e,context:t},`[rescue] rescue buffer saved (${t}): ${e}`),`rescued`):(C.warn({docName:e,gitDir:n.gitDir,context:t},`[rescue] path-traversal guard rejected docName: ${e} (${t})`),$U(),`lost`)}catch(n){return C.error({err:n,docName:e,context:t},`[rescue] failed to write rescue buffer for ${e} (${t})`),$U(),`lost`}};async function si(e){if(Je.documents.size===0)return;let t=!1,n=Date.now()+e,r,i=Promise.withResolvers(),a=hzt(Je,()=>{t||(n=Date.now()+e,r&&(clearTimeout(r.id),r.id=setTimeout(r.expire,Math.max(n-Date.now(),250))))}),o={async afterUnloadDocument({instance:e}){!t&&e.getDocumentsCount()===0&&(t=!0,i.resolve())}};Je.configuration.extensions.push(o);try{let o=Array.from(Je.documents.keys());Je.closeConnections(),Je.flushPendingStores();for(let e of Je.documents.values())e.getConnectionsCount()===0&&Je.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});for(;Date.now()<n-250&&Array.from(Je.documents.values()).some(e=>e.getConnectionsCount()===0&&!pt(e));)await new Promise(e=>setTimeout(e,25));for(let e of M.getRefusedStoreDocNames()){if(CW(e))continue;let t=Je.documents.get(e);if(!t||!pt(t))continue;if(n-Date.now()<50){C.warn({docName:e},`[rescue] refused-store pass out of budget before ${e}; leaving it and any remaining refused docs to the flush timeout path`);break}if(oi(e,`refused-store-shutdown`)!==`rescued`){C.warn({docName:e},`[rescue] refused-store doc rescue failed; leaving ${e} to the flush timeout path`);continue}let r=!1,i=!1,a=ft(t).then(()=>{r=!0}).catch(t=>{i=!0,r=!0,C.warn({docName:e,err:t},`[rescue] refused-store doc unload failed at shutdown: ${e}`)}),o=0;do{let e=Math.max(n-Date.now(),50);o+=e;let t;try{await Promise.race([a,new Promise(n=>{t=setTimeout(n,e)})])}finally{t!==void 0&&clearTimeout(t)}}while(!r&&Date.now()<n);if(!r){C.warn({docName:e,unloadDeadline:o},`[rescue] refused-store doc unload did not finish before the flush deadline; leaving ${e} to the flush timeout path`),a.then(()=>{i||C.info({docName:e},`[rescue] refused-store doc unload completed after the flush deadline: ${e}`)});continue}i||C.info({docName:e},`[rescue] refused-store doc rescued and unloaded at shutdown: ${e}`)}let s=new Promise((i,s)=>{let c=()=>{if(t)return;t=!0,a();let n=Array.from(Je.documents.keys()),r=[],i=[];if(We.current)for(let e of n)CW(e)||(oi(e,`flush-timeout`)===`rescued`?r.push(e):i.push(e));else{C.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`);for(let e of n)CW(e)||(i.push(e),$U())}let c=r.length>0||i.length>0?` — rescued [${r.join(`, `)}]${i.length>0?`, lost [${i.join(`, `)}]`:``}`:``;s(Error(`flushAllStoresAndWait timeout: no document retired for ${e}ms — ${n.length}/${o.length} docs did not unload: [${n.join(`, `)}]${c}`))};r={id:setTimeout(c,Math.max(n-Date.now(),250)),expire:c}});await Promise.race([i.promise,s])}finally{t=!0,a();let e=Je.configuration.extensions,n=e.indexOf(o);n!==-1&&e.splice(n,1),r&&clearTimeout(r.id)}}async function ci(){return ti||(ni=!0,ti=(async()=>{let e=Date.now(),t=[],n={phaseErrors:t,authorityGateReached:!1};ri=n;let i=Math.min(m,2e3),a=Date.now()+i,o=()=>Math.max(1,a-Date.now()),s=async(e,t)=>{let n;try{return await Promise.race([e,new Promise((e,r)=>{n=setTimeout(()=>r(Error(`${t} did not retire before the pre-flush deadline`)),o())})])}finally{clearTimeout(n)}};ut=!0;let c=Promise.allSettled([Qe()]),l;try{[l]=await s(c,`mutation-drain`)}catch(e){t.push({phase:`mutation-drain`,error:String(e)}),C.error({err:e},`[server] shutdown mutation drain failed`)}$n.clearTimeout(er),er=null,cr();for(let e of ne.all())Ke.discardDeferredStore(e.docName,{kind:`shutdown`}),Pr(e.docName,T()??`main`,`delete`,!0),mW(`shutdown`),M.releaseStores(e.docName);ne.clear(),M.endAllRenameCarries(),rr.clear(),ir.clear(),Te=!0,Jr();for(let e of yn.values())for(let t of e)t.namespaceAllowed=!1,t.residentAllowed=!1;yn.clear(),vn=new WeakMap;try{await s(Qt(),`generated-index`)}catch(e){C.warn({err:e},`[index] generated index shutdown drain failed`),t.push({phase:`generated-index-drain`,error:String(e)})}for(let e of dt.splice(0))e();try{await s(Promise.resolve(at?.dispose()),`staleness-watchdog`)}catch(e){C.warn({err:e},`[server] staleness watchdog drain failed during destroy`),t.push({phase:`staleness-watchdog-drain`,error:String(e)})}at=null;try{I4(je)}catch(e){C.warn({err:e},`[server] failed to mark server.lock draining`)}Ge?.destroy();try{await s(Xt(),`shadow-housekeeping`)}catch(e){C.warn({err:e},`[shadow-housekeeping] shutdown drain failed`),t.push({phase:`shadow-housekeeping-drain`,error:String(e)})}if(pn!==null&&(clearTimeout(pn),pn=null),mn)try{qLt(r,gn.entries())}catch(e){C.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let u,d=await Promise.race([mt.then(()=>`completed`,e=>(C.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{u=setTimeout(()=>e(`timeout`),o())})]);u!==void 0&&clearTimeout(u),d===`timeout`&&(C.warn({},`[server] init did not complete before the pre-flush deadline`),t.push({phase:`initialization-drain`,error:`Initialization remains pending`}));let f;try{await Promise.race([Promise.allSettled(Je.loadingDocuments.values()),new Promise((e,t)=>{f=setTimeout(()=>t(Error(`Pending document loads did not retire`)),o())})])}catch(e){t.push({phase:`document-load-drain`,error:String(e)}),C.error({err:e},`[server] shutdown document load drain failed`)}finally{clearTimeout(f)}let p=Je.documents.size,h=async(e,t)=>{if(e!==null)try{await e.unsubscribe()}catch(e){ii(t,e)}};try{try{et&&=(clearTimeout(et),null),tt&&=(clearTimeout(tt),null),await h(w,`head`),w=null,await h(Yr,`content`),Yr=null;for(let{docName:e,cleanup:t}of In)try{await t()}catch(t){C.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}In.length=0,Ln.clear();try{O?.destroy(),rt?.destroy(),Pn&&=(await Pn.disconnect(),null);for(let[e,t]of Fn)try{await t.disconnect()}catch(t){C.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Fn.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await Ye.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Jit()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await si(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([Ue.close(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`derived index close did not settle within ${i}ms`)),i)})])}catch(e){t.push({phase:`derived-index-close`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown derived-index close failed`)}finally{e!==void 0&&clearTimeout(e)}let n;try{await Promise.race([(async()=>{await Ke.flushPendingGitCommit(),await Ke.waitForPendingCommits()})(),new Promise((e,t)=>{n=setTimeout(()=>t(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{n!==void 0&&clearTimeout(n)}try{ei&&=(await ei.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(We.current){let e;try{await Promise.race([fJ(We.current).drain(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`shadow mutator drain timeout`)),m)})])}catch(e){t.push({phase:`shadow-mutator-drain`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-5 shadow mutator drain failed`)}finally{e!==void 0&&clearTimeout(e)}try{let e=(await kN({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&mc(K(We.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{Eet(We.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}if(l?.status===`rejected`){let e=l.reason,n=e instanceof AggregateError?e.errors:[e];t.push({phase:`local-op-subprocess-shutdown`,error:n.map(e=>e instanceof Error?e.message:String(e)).join(`; `)}),C.error({err:e},`[server] shutdown local-op subprocess drain failed`)}let i=Date.now()-e;if(n.authorityGateReached=!0,t.length===0){we=!0;try{Pe.release()}catch(e){t.push({phase:`authority-release`,error:String(e)}),C.error({err:e},`[server] shutdown authority release failed`)}C.info({documentCount:p,durationMs:i},`[server] shutdown flushed ${p} documents in ${i}ms`)}else C.warn({documentCount:p,durationMs:i,phaseErrors:t},`[server] shutdown flushed ${p} documents in ${i}ms with ${t.length} phase error(s)`)}}finally{try{F4(je,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await rH()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}ri===n&&(ri=null)}if(l?.status===`rejected`)throw l.reason})(),ti)}let li=[];async function ui(){try{ct=await NLt(r),C.info({principalId:ct.id},`[server] principal loaded`)}catch(e){C.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!We.current)try{We.current=await xJ(r,{deferGcConfig:!0}),C.info({gitDir:We.current.gitDir},`[server] history repo initialized at ${We.current.gitDir}`),xet(We.current)&&!li.includes(`shadow-excludes`)&&li.push(`shadow-excludes`)}catch(e){C.error({err:e},`[server] history repo init failed`),li.push(`shadow-repo`)}if(We.current)try{let e=hct(We.current.gitDir);Nct(We.current.gitDir,e),bct(We.current.gitDir,e),Kt=e,C.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){C.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(We.current)try{await yJ(We.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){C.warn({},`[server] history repo appears corrupted — reinitializing`);try{We.current=await xJ(r,{deferGcConfig:!0}),xet(We.current)&&!li.includes(`shadow-excludes`)&&li.push(`shadow-excludes`)}catch(e){C.error({err:e},`[server] history repo reinit failed`),We.current=void 0,li.includes(`shadow-repo`)||li.push(`shadow-repo`)}}else C.error({err:e},`[server] history repo check failed (transient?)`)}if(We.current&&ti===null){let e=We.current,t=JW(G(r,n))||`.`;tt=setTimeout(()=>{tt=null,wJ(e,t).catch(e=>{C.debug({err:e},`[shadow] fan-out index warm-up failed (non-fatal)`)})},3e3),tt.unref?.()}if(We.current)try{let e=K(We.current.gitDir,`last-known-head`),t=null;try{t=J(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await kN({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await kN({baseDir:r,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}C.info({lastKnownHead:t,currentHead:n,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=import`);try{await kJ(We.current,p??``,t,n,e),f0e()}catch(e){C.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else C.info({currentHead:n},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=noop`);try{mc(e,n,`utf-8`)}catch(e){C.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){C.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=jEt(n,r);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;C.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){C.error({err:e},`[server] managed rename recovery failed`),li.push(`managed-rename-recovery`)}try{let e=x_t(r);(e.deleted>0||e.errors>0)&&C.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){C.error({err:e},`[server] upload-tempfile sweep failed`),li.push(`upload-tempfile-sweep`)}try{Pn=await Je.openDirectConnection(lr),O?.emitServerInfo(Ce,E()??void 0)}catch(e){C.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),li.push(`cc1-push`)}let t=y?[]:ro;for(let e of t)try{let t=await Je.openDirectConnection(e);Fn.set(e,t)}catch(t){C.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),li.push(`config-doc:${e}`)}let i=new Map([[Xe,yl(`project`,r)],[Re,yl(`project-local`,r)],[Zn,yl(`user`,r,u)]]);for(let e of t){let t=i.get(e);if(t)try{C.info({docName:e,path:t},`[config-file-watcher] starting`);let n=async t=>{let n=Je.documents.get(e),r=fFt(e,t,Ke.configPersistenceCtx);C.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let i=await L7(n??null,e,t,Ke.configPersistenceCtx);C.info({docName:e,outcome:i,isEcho:r},`[config-file-watcher] applyExternalConfigChange outcome`),Se(e),r||_e(e)},r=await UPt(t,t=>{n(t).catch(t=>{C.warn({err:t,docName:e},`[config-file-watcher] change handler failed`)})});In.push({docName:e,cleanup:r}),Ln.set(e,r.resync),C.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){C.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),li.push(`config-file-watcher:${e}`)}}if(!y){let e=null,t=t=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,Ue.refreshGlobalSkillNodes().catch(e=>{C.warn({err:e,docName:t},`[backlinks] global skill bundle re-ingest failed`)})},300)},n=async(e,n)=>{let r=qyt(e,Ke.managedArtifactCtx);if(!r)return;let i=await $yt(Je.documents.get(r)??null,r,n,Ke.managedArtifactCtx);C.info({docName:r,outcome:i},`[managed-artifact-watcher] external change`),Et(`files`),Mr(r)&&t(r)},r=e=>{let n=qyt(e,Ke.managedArtifactCtx);Et(`files`),n&&Mr(n)&&t(n)};try{let e=Uyt(Ke.managedArtifactCtx),t=await QIt(e,n,r);In.push({docName:`__skill-files__`,cleanup:t}),C.info({roots:e},`[managed-artifact-watcher] skills started`)}catch(e){C.warn({err:e},`[managed-artifact-watcher] skills failed to start`),li.push(`managed-artifact-watcher:skills`)}try{let e=yQ(i6(Ke.managedArtifactCtx)),t=await UPt(e,()=>{Et(`files`)});In.push({docName:`__skill-state__`,cleanup:t}),C.info({path:e},`[skill-state-watcher] started`)}catch(e){C.warn({err:e},`[skill-state-watcher] failed to start`),li.push(`skill-state-watcher`)}}try{let e=K(n,`.okignore`),t=K(r,`.gitignore`),i=null;try{let e=zc(`git`,[`rev-parse`,`--git-common-dir`],DW({cwd:r,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=K(r,e.stdout.trim()),n=W(t,`info`,`exclude`);q(U(n))&&(i=n)}}catch{}let a=i?[e,t,i]:[e,t],o=C;o.info({okignorePath:e,gitignorePath:t,gitInfoExcludePath:i,ephemeral:y},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=y?null:await WPt(a,(t,n)=>{(async()=>{if(t===e)try{let e=await L7(Je.documents.get(`__config__/okignore`)??null,$r,n,Ke.configPersistenceCtx);o.info({docName:$r,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:G(r,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await He.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:G(r,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),O?.signal(`files`);else{let e=G(r,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),O?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:G(r,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(In.push({docName:`__ignore-files__`,cleanup:s}),Ln.set($r,s.resync),o.info({okignorePath:e,gitignorePath:t},`[ignore-watcher] multi-path watcher started`))}catch(e){C.warn({err:e,projectDir:r,contentDir:n},`[ignore-watcher] failed to start multi-path watcher`),li.push(`ignore-files-watcher`)}let a=r9(r).branch??`main`;I(a),wt();let o=Ue.beginStartup(a),s=!1,c=performance.now();try{await oH(`ok.boot.indexes`,void 0,async()=>{let t=await o.offlineDeletionsReady,i=0;for(let e of t)CW(e)||gn.peek(e)?.kind!==`renamed`&&(gn.setDeleted(e),i++);i>0&&C.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`),St.resolve();let{backlinkIndexDegraded:a}=await o.backlinksReady;a&&li.push(`backlink-index`);let c=performance.now(),l=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,d=He?new Set(R1(n).map(e=>e.dir)):new Set,f=e=>{e.some(e=>l.test(G(b,e).split(Js).join(`/`)))&&(et&&clearTimeout(et),et=setTimeout(()=>{et=null;try{t0(r,n).then(e=>{e>0&&(C.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),O?.signal(`files`))}).catch(e=>C.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=Jut(n,d);if(!(e.size!==d.size||[...e].some(e=>!d.has(e))))return;d=e,He.rebuildIgnorePatterns().then(t=>{t.ok?(C.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),O?.signal(`files`)):C.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>C.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){C.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};await ai(()=>oH(`ok.boot.seed-walk`,void 0,async()=>vit(b,Gr,He,{onRawBatch:f,onRecoveryComplete:()=>Ue.recordInventoryReconciled(),onRecoveryPassCompleted:(e,t)=>wr(e,t),nativeBackend:e.watcherBackend,clock:e.watcherClock,freshnessIntervalMs:e.freshnessIntervalMs===void 0?5e3:e.freshnessIntervalMs})),e=>{Yr=e},`content`),t0(r,n).then(e=>{e>0&&C.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>C.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=u??_c();B1(e).then(t=>t0(e,e,t)).then(e=>{e>0&&C.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>C.warn({err:e},`[in-place-skills] global copy re-sync failed`))}Z2(`seedWalkMs`,Math.round(performance.now()-c));{let e=K(n),t=0;for(let[n]of gn.entries()){if(!s5(n))continue;let r=K(e,`${n}${qU(n)}`);YW(r,e)&&q(r)&&(gn.delete(n),t++)}t>0&&C.info({count:t},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let p=await Ue.settleStartupAfterWatcherSeed();s=!0,p.tagIndexDegraded&&li.push(`tag-index`);let m=0;try{v===void 0?await d5({contentDir:n,contentFilter:He,basenameIndex:Ie,onSkip:(e,t,n)=>{m++,C.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):eOt({contentDir:n,basenameIndex:Ie,onSkip:(e,t,n)=>{m++,C.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),m>0&&(C.warn({count:m},`[basename-index] startup seed completed with ${m} skipped entries — embeds under inaccessible subtrees will not resolve`),li.push(`basename-index-partial`))}catch(e){C.error({err:e},`[basename-index] startup seed failed`),li.push(`basename-index`)}})}catch(e){if(C.error({err:e},`[server] disk bridge watcher failed to start`),li.push(`file-watcher`),!s){let e=await Ue.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&li.push(`tag-index`)}}finally{Z2(`indexesMs`,Math.round(performance.now()-c)),Yr&&yht(`fileCount`,Yr.getFileIndex().size),Wn()}let l=()=>{};try{await ai(()=>bIt(r,async({trigger:e})=>{if(C.info({trigger:e},`[batch] begin trigger=${e}`),d0e(),Je.flushPendingStores(),await Ke.flushPendingGitCommit(),re(`head-watcher`),l(),l=M.holdWriteAdmission(),We.current){let e=N(),t=r9(r).branch??e,n=[],i=0;for(let[e,t]of Je.documents){if(CW(e))continue;let r=null;if(t.transact(()=>{r=zn(e)},_zt),r===null)continue;let a=ee(e);if(a===void 0){i++;continue}n.push({docName:e,markdown:r,diskSnapshot:a})}if(i>0&&C.warn({count:i,branch:e},`[history] skipped parking ${i} doc(s) with no reconciled base; their content was not parked to the shadow history`),n.length>0)try{let r=await Het(We.current,e,DJ.id,n,t);r&&(v0e(),C.info({count:n.length,branch:e,sha:r.slice(0,8)},`[history] parked ${n.length} docs on ${e} → ${r.slice(0,8)}`))}catch(e){C.error({err:e},`[shadow] park failed`)}}},async e=>{let t=Wr.length,i=e.newBranch??`main`;if(C.info({kind:e.batchKind,headMoved:e.headMoved,docs:t,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${t}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){try{try{await qr()}finally{Jr()}if(e.headMoved&&e.newHead){let t=yzt(r,K(n),e.oldHead,e.newHead);if(t.size>0){Lst(t.keys());for(let[e,n]of t)t$(e,rye(n.email),n.name,n.email,Eye(e));await Ke.flushContributors()}}}finally{try{ie(`head-watcher`)&&await ae()}finally{l()}}try{await ce.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e},`[head-watcher] conflict prune against git failed`)}}else{_0e(),cr();let t=!1,r=!1,a;try{I(i),ce.setBranch(i),le(),a=await Ue.beginBranchSwitch(i),He.rebuildDirCount();try{let e=0;Ie.clear(),await d5({contentDir:n,contentFilter:He,basenameIndex:Ie,onSkip:(t,n,r)=>{e++,C.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(C.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),li.includes(`basename-index-partial`)||li.push(`basename-index-partial`))}catch(e){C.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}try{await Ue.settleBranchFromDisk(a)}catch(e){Ue.abortBranchSwitch(a),C.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}try{await qr();let e=await Yr?.recheck(`full`);e&&(e.status!==`completed`||e.partial)&&(r=!0,s4e(),C.warn({branch:i,status:e.status,partial:e.partial===!0},`[branch-switch] the re-check after switching to ${i} did not observe the whole tree; another one runs once the switch ends`)),await qr()}finally{Jr()}if(Nr(i),C.info({branch:i,docCount:Je.documents.size},`[branch-switch] loaded branch ${i} (${Je.documents.size} docs)`),e.oldBranch?.startsWith(`detached-`)&&We.current)try{let t=yJ(We.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await fJ(We.current).withMutator(async()=>{for(let e of n.split(`
2323
+ `).map(e=>e.trim()).filter(e=>/^[0-9a-f]{40}$/.test(e))}catch(e){return C.warn({err:e,branch:t},`[reconcile] rename: could not read the writers' history heads; the move is recorded without them`),[]}}async function Ar(e,t,n,r){let i=await kr(e,t),a;try{a=I8({moves:[n],kind:`file`,branch:t,writer:r,shadow:e,notices:void 0,anchors:i})}catch(e){a4e(),C.warn({err:e,oldDocName:n.from,newDocName:n.to},`[reconcile] rename: could not write the rename-log entry for ${n.from} -> ${n.to}; history before the move will not show under the new name`);return}if(a===0)return;let o;try{await Ke.flushContributors()}catch(e){o=e}let s=E$(e.gitDir).byTo.get(n.to);if(s!==void 0&&s.commitSha===``){o4e(),C.warn({err:o,oldDocName:n.from,newDocName:n.to},`[reconcile] rename: wrote the rename-log entry for ${n.from} -> ${n.to}, but no commit claimed it yet; a later commit by the file-system writer claims it, and the next start drops it if none does`);return}o!==void 0&&C.warn({err:o,oldDocName:n.from,newDocName:n.to},`[reconcile] rename: the commit after recording the move failed`)}async function jr(e,t,n,r,i){let a;try{return a=await Je.openDirectConnection(e),Bn(e,r),te(e,n),i!==n&&await Ur({kind:`update`,path:t,docName:e,content:i}),C.info({newDocName:e},`[reconcile] rename: unsaved typing carried into ${e}`),!0}catch(t){return C.error({err:t,newDocName:e},`[reconcile] rename: could not carry unsaved typing into ${e}; it is in the rename checkpoint`),!1}finally{await a?.disconnect()}}function Nr(e){for(let[t,r]of Je.documents)if(!CW(t)&&r.getMap(`lifecycle`).get(`status`)===void 0)try{let i=AG(t,n);if(!q(i)||!vK(i,cc(i),n))continue;Pr(t,e,`branch-switch`),r.getMap(`lifecycle`).set(`status`,`deleted-upstream`),C.warn({docName:t,branch:e},`[branch-switch] tombstone: ${t} resolves outside the content dir or into private state on ${e}`)}catch(e){C.error({err:e,docName:t},`[branch-switch] could not check where ${t} resolves`)}}let Pr=(e,t,n,r=!1)=>{let i=ee(e),a=zn(e)??``,o=i===void 0?a!==``:a!==i;return o&&(Yn(e,a,t,n,``,r),o)};function Fr(e){ce.dissolveReconcile(e),ce.dissolveWorkingTree(ce.fileOf(e))}let Ir=(e,t,n,r)=>{(t.kind===`merged`||t.kind===`both-kept`)&&t.dedupSkipped&&(t0e(),C.warn({docName:e,oursLen:n.length,theirsLen:r.length,newLen:t.newContent.length},`[reconcile] ${e} insert-group dedup skipped (LCS cell cap); union emitted with possible same-block duplication`))},Lr=async(e,t,n)=>{let r=n===void 0;P2e();let i=zn(e)??``,a=T()??`main`,o=XW(t).slice(0,6),s=i!==``&&i!==t,c=s?oi(e,`disk-authoritative-ingest`):`not-needed`;s&&Yn(e,i,a,`disk-update`,o,!0);let l=XW(i).slice(0,6),u=r?`absent`:`blockless`,d,f=!1;try{Bn(e,t),Fr(e),f=!0}catch(s){d=s,F2e(),C.error({err:s,docName:e},`[reconcile] failed to apply disk-authoritative ingest to Y.Doc for ${e}`),Yn(e,t,a,`disk-update`,o,!0),Fr(e);let f;try{f=zn(e)??void 0}catch(t){C.error({err:t,docName:e},`[reconcile] unable to read ${e} back after a failed disk-authoritative ingest; treating the live content as lost`)}f===t?te(e,t):M.restoreReconciledBase(e,n),c===`lost`&&f!==i&&(I2e(),C.warn({docName:e,baseAbsent:r,reason:`no-base`,ours:l,theirs:o,result:`clean-unrescued`,rescue:c,applyFailed:!0},`[reconcile] ${e} base=${u} reason=no-base result=clean-unrescued ours=${l} theirs=${o} rescue=${c} applyFailed=true`))}if(f){let n=c===`lost`?`clean-unrescued`:`clean`;return c===`lost`&&I2e(),(c===`lost`?C.warn.bind(C):C.info.bind(C))({docName:e,baseAbsent:r,reason:`no-base`,ours:l,theirs:o,result:n,rescue:c},`[reconcile] ${e} base=${u} reason=no-base result=${n} ours=${l} theirs=${o} rescue=${c}`),await Rr(e,t),s?{kind:`applied`,merge:`disk-replaced`}:{kind:`applied`}}return{kind:`failed`,error:d}},Rr=async(e,t)=>{try{await Ue.recordDiskUpsert(e,t)}catch(t){C.warn({err:t,docName:e},`[reconcile] ${e}: the derived index could not record the disk version`)}};function zr(e){throw Error(`unhandled disk intake outcome: ${e.kind}`)}function Br(e){throw Error(`unhandled reconcile outcome: ${e.kind}`)}async function Vr(e){let{docName:t,content:n}=e;if(Nn(t),rIt(e.previousIndexedFields,n,t)&&$t(t),ce.findByDocName(t)?.kind===`merge-native`)try{await ce.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e,docName:t},`[reconcile] conflict prune against git failed`)}let r=Je.documents.get(t);if(!r)return p$(M,void 0,t,n,ce)||M.refreshReceiptWithoutBase(t,n),await Ue.recordDiskUpsert(t,n),{kind:`nothing-to-take`};if(Vn(t,n)!==`not-frozen`)return await Ue.recordDiskUpsert(t,n),{kind:`nothing-to-take`};let i=XW(n),a=Lyt({receiptHash:M.getReceipt(t)?.hash,eventHash:i,isRecentOwnWrite:M.isRecentOwnWrite(t,i),readDiskHash:()=>{try{return XW(J(e.path,`utf-8`))}catch{return null}}}),o=Ryt(a);if(o!==null&&M.getStaleExternalWrite(t)===void 0)return f2e(o),C.debug({docName:t,receiptIntake:a},`[reconcile] ${t}: the disk bytes match its receipt (${a}); nothing to take in`),ce.dissolveReconcile(t),await Rr(t,n),{kind:`nothing-to-take`};let s=ee(t),c=zn(t)??s??``;if(p$(M,r,t,n,ce,c))return await Rr(t,n),{kind:`conflict`};if(s===void 0)return Lr(t,n,void 0);let l=$J({docName:t,base:s,ours:c,theirs:n}),u=XW(s).slice(0,6),d=XW(c).slice(0,6),f=XW(n).slice(0,6),p=c.length,m=n.length,h=l.kind===`clean`||l.kind===`merged`||l.kind===`both-kept`?l.newContent.length:void 0,g=h===void 0?void 0:h-Math.max(p,m),_=h===void 0?``:` newLen=${h} delta=${g}`;switch(C.info({docName:t,base:u,ours:d,theirs:f,result:l.kind,oursLen:p,theirsLen:m,...h===void 0?{}:{newLen:h,delta:g}},`[reconcile] ${t} base=${u} ours=${d} theirs=${f} result=${l.kind} oursLen=${p} theirsLen=${m}${_}`),Ir(t,l,c,n),l.kind){case`noop`:return ce.dissolveReconcile(t),await Rr(t,n),{kind:`nothing-to-take`};case`clean`:try{Bn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),te(t,s),ce.dissolveReconcile(t),{kind:`failed`,error:e}}return te(t,l.newContent),QU(),ce.dissolveReconcile(t),await Rr(t,n),{kind:`applied`,merge:`clean`};case`merged`:try{Bn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),te(t,s),ce.dissolveReconcile(t),{kind:`failed`,error:e}}return te(t,n),QU(),ce.dissolveReconcile(t),await Rr(t,n),{kind:`applied`,merge:`merged`};case`both-kept`:try{Bn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply both-kept content to Y.Doc for ${t}; raising the conflict`),te(t,s),e0e(),ce.raise({kind:`reconcile`,file:ce.fileOf(t),reason:`merged-with-markers`,stages:{base:s,ours:c,theirs:n}}),{kind:`failed`,error:e}}return xt.bothKept(t,{ours:c,theirs:n},l.kept),te(t,n),QU(),d$(t,l.kept,`watcher`),ce.dissolveReconcile(t),await Rr(t,n),{kind:`applied`,merge:`both-kept`};case`refused`:return l.reason===`no-base`?Lr(t,n,s):(u$(t,l,`watcher`),(l.reason===`check-failed`||l.reason===`too-large`)&&await xt.keptLive(t,{side:`theirs`,bytes:n},l.reason)?(te(t,n),f$(t,l.reason,`watcher`),ce.dissolveReconcile(t),await Rr(t,n),{kind:`applied`,merge:`kept-live`}):(e0e(),ce.raise({kind:`reconcile`,file:ce.fileOf(t),reason:Xst(l.reason),stages:{base:s,ours:c,theirs:n}}),{kind:`conflict`}));default:return Br(l)}}let Hr=new Map;async function Ur(e,t=e.kind===`delete`||e.kind===`rename`?Hr.get(e)??jn(e.kind===`delete`?e.docName:e.oldDocName,LX(e)):void 0){try{switch(e.kind){case`create`:{let t=Art(e),n=XW(e.content),r=ne.matchCreate({docName:e.docName,identity:t.identity,size:t.size,modified:t.modified,hash:n,content:e.content});if(r){if(ar(r.vanished.docName),r.by===`same-name`){mW(`recreated`),C.info({docName:e.docName},`[reconcile] ${e.docName}: its file came back; taking it in as an update`),await Ur({kind:`update`,path:e.path,docName:e.docName,content:e.content}),vr();break}let t=M.beginRenameCarry(r.vanished.docName);try{Ke.discardDeferredStore(r.vanished.docName,{kind:`renamed-outside`,to:e.docName,carry:t}),mW(r.by===`identity`?`paired-identity`:`paired-hash`),await Ur({kind:`rename`,oldPath:r.vanished.path,newPath:e.path,oldDocName:r.vanished.docName,newDocName:e.docName,content:e.content})}finally{M.abandonRenameCarry(r.vanished.docName)}break}ne.rememberCreate({docName:e.docName,path:e.path,identity:t.identity,size:t.size,modified:t.modified,hash:n,at:$n.now()}),C.info({docName:e.docName},`[reconcile] create: ${e.docName}`),Vn(e.docName,e.content),await Ue.recordDiskUpsert(e.docName,e.content),Et(`files`),$t(e.docName),Nn(e.docName);break}case`update`:await Vr(e);break;case`delete`:{let{docName:n}=e,r=t??jn(n,LX(e));Hr.delete(e);try{let t=r.namespaceCurrent(),i=r.residentCurrent();if(!t&&!i){C.debug({docName:n,source:`watcher-delete`,namespaceCurrent:t,residentCurrent:i},`[reconcile] delete skipped: ${n} (stale removal)`);return}if(t&&i&&r.document&&!Qn.has(e)&&await _r(e))return;t&&(Fr(n),_n.current?.deleted(n));let{document:a}=r,o=i&&a?Pr(n,T()??`main`,`delete`,!0):!1;if(i&&(a?.getMap(`lifecycle`).set(`status`,`deleted-upstream`),M.endRenameCarry(n)),t&&F(n),t&&await Ue.recordDiskDelete(n),!r.namespaceCurrent()&&!r.residentCurrent()){C.debug({docName:n,source:`watcher-delete`,namespaceCurrent:!1,residentCurrent:!1},`[reconcile] delete skipped: ${n} (stale removal)`);return}if(C.info({docName:n,isDirty:o,source:`watcher-delete`},`[reconcile] delete: ${n} (dirty=${o})`),r.residentCurrent()&&a&&(Je.closeConnections(n),await ft(a,r.residentCurrent)),!r.namespaceCurrent()){C.debug({docName:n,source:`watcher-delete`,namespaceCurrent:!1,residentCurrent:r.residentCurrent()},`[reconcile] delete: ${n} not recorded as removed (stale removal)`);return}Et(`files`),Mn(n),tn(n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:n,kind:`deleted`,source:`watcher-delete`}))}finally{r.dispose()}break}case`rename`:{let{oldDocName:n,newDocName:r,content:i}=e,a=t??jn(n,LX(e));Hr.delete(e),M.beginRenameCarry(n);let o=null,s=!1,c;try{let t=a.document,l=a.residentCurrent()&&t?t:null,u=l?zn(n):null,d=l?$W(l):null,f=ee(n),p=e=>{let t=e.getMap(`lifecycle`);t.set(`status`,`renamed`),t.set(`newPath`,r)},m=a.residentCurrent()&&t?Pr(n,T()??`main`,`rename`):!1;a.residentCurrent()&&t&&p(t),a.namespaceCurrent()&&(Fr(n),F(n),Ke.forgetObservedFile(n),B(n,r)),te(r,i),C.info({oldDocName:n,newDocName:r,isDirty:m},`[reconcile] rename: ${n} → ${r} (dirty=${m})`),Et(`files`),Nn(r),a.namespaceCurrent()&&await _n.current?.renamed(n,r);try{a.namespaceCurrent()?await Ue.recordDiskRename(n,r,i):await Ue.recordDiskUpsert(r,i)}catch(e){C.error({oldDocName:n,newDocName:r,err:e},`[reconcile] rename: index update failed for ${n} → ${r}; completing client teardown anyway`)}let h=a.namespaceCurrent()?Je.documents.get(n):void 0,g=h===t?void 0:h;g&&p(g);try{V(r,i)}catch(e){c={error:e}}$t(r),a.namespaceCurrent()&&Or(n,r,e.newPath),u!==null&&f!==void 0&&(u===f||await jr(r,e.newPath,f,u,i))&&(o=d);let _=a.residentCurrent()&&t?t:g;if(s=!!_,_){let e=_.getConnectionsCount();Je.closeConnections(n),await Ye.closeAllForDoc(n),e>0&&C.info({oldDocName:n,newDocName:r,closedConnections:e},`[reconcile] rename: closed ${e} connection(s) on ${n}`)}if(a.namespaceCurrent()?(console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:n,to:r,kind:`renamed`,source:`watcher-rename`})),tn(n)):C.debug({docName:n,newDocName:r,source:`watcher-rename`,namespaceCurrent:!1,residentCurrent:a.residentCurrent()},`[reconcile] rename: ${n} not recorded as removed (stale removal)`),c)throw c.error}finally{M.settleRenameCarry(n,o),s||M.endRenameCarry(n),a.dispose()}break}case`conflict`:{let{docName:t}=e;if(!Je.documents.get(t))return;let n=ee(t)??``,r=zn(t);r===null?C.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):te(t,r),ce.raise({kind:`reconcile`,file:ce.fileOf(t),reason:`disk-markers`,stages:{base:n,ours:r??n,theirs:e.content}}),C.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:Ie.add(e.relativePath),Et(`files`),Kn(Hs(e.relativePath));break;case`asset-delete`:Ie.remove(e.relativePath),Et(`files`),Kn(Hs(e.relativePath));break;case`folder-create`:case`folder-delete`:Et(`files`),en(e.relativePath);break;case`file-create`:case`file-update`:await Ue.recordFileTargetUpsert(e.relativePath),it?.(),Et(`files`),await Zr(e.relativePath);break;case`file-delete`:await Ue.recordFileTargetDelete(e.relativePath),it?.(),Et(`files`);break;default:$Y(e)}}catch(t){let n=qn(e);C.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let Wr=[];async function Gr(e){if(!Te){if((e.kind===`delete`||e.kind===`rename`)&&!Hr.has(e)&&Hr.set(e,jn(e.kind===`delete`?e.docName:e.oldDocName,LX(e))),se()||Kr!==null){Wr.push(e);return}await Ur(e)}}let Kr=null;function qr(){if(Kr)return Kr;if(Wr.length===0)return Promise.resolve();let e=Promise.withResolvers();return Kr=e.promise,(async()=>{try{for(;Wr.length>0;){let e=Wr.splice(0,Wr.length);for(let t of e)await Ur(t)}e.resolve()}catch(t){e.reject(t)}finally{Kr=null}})(),e.promise}function Jr(){for(let e of Hr.values())e.dispose();Hr.clear()}let Yr=null;function Xr(e){return bW(e)||xW(e)||SW(e)}async function Zr(e){if(!Xr(e))return!1;let t=Je.documents.get(e);return t?await sLt(t,e,Ke.mermaidPersistenceCtx)!==`unchanged`:!1}async function Qr(e,t){if(!Yr)return{checked:0,found:0};let r=Yr.getAliasMap(),i=Yr.getFileIndex(),a=[],o={checked:0,found:0};for(let s of new Set(e)){let e=r.get(s)??s;if(CW(e))continue;if(Xr(e)){o.checked++,await Zr(e)&&o.found++;continue}let c=i.get(e)?.canonicalPath;if(c!==void 0){a.push(c);continue}try{a.push(AG(e,n))}catch(e){C.debug({err:e,trigger:t},`[reconcile] skipped a re-read for a name outside the content tree`)}}let s=a.length===0?{checked:0,found:0}:await Yr.recheckPaths(a),c={checked:s.checked+o.checked,found:s.found+o.found},l={trigger:t,...c};return c.found>0?C.info(l,`[reconcile] re-read on ${t} found outside changes`):C.debug(l,`[reconcile] re-read on ${t} found nothing new`),c}let ei=null,ti=null,ni=!1,ri=null;function ii(e,t){let n=ri;if(n===null||n.authorityGateReached){C.error({err:t,watched:e},`[server] late watcher release failed after shutdown`);return}n.phaseErrors.push({phase:`watcher-unsubscribe`,error:t instanceof Error?t.message:String(t)}),C.error({err:t,watched:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}async function ai(e,t,n){if(ni)return;let r=await e();if(ni){try{await r.unsubscribe()}catch(e){ii(n,e)}return}t(r)}let oi=(e,t)=>{let n=We.current;if(!n)return C.warn({docName:e,context:t},`[rescue] shadow repo unavailable — cannot buffer ${e} (${t})`),$U(),`lost`;try{let r=TW(e)?Je.documents.get(e)?.getText(`source`).toString()??null:zn(e);if(r===null)return C.warn({docName:e,context:t},`[rescue] skipping ${e} — document dropped from map mid-rescue (${t})`),$U(),`lost`;let i=Rn(n.gitDir,e);return i?(SH(U(i),{recursive:!0}),bH(i,r,`utf-8`),h0e(),C.info({docName:e,context:t},`[rescue] rescue buffer saved (${t}): ${e}`),`rescued`):(C.warn({docName:e,gitDir:n.gitDir,context:t},`[rescue] path-traversal guard rejected docName: ${e} (${t})`),$U(),`lost`)}catch(n){return C.error({err:n,docName:e,context:t},`[rescue] failed to write rescue buffer for ${e} (${t})`),$U(),`lost`}};async function si(e){if(Je.documents.size===0)return;let t=!1,n=Date.now()+e,r,i=Promise.withResolvers(),a=hzt(Je,()=>{t||(n=Date.now()+e,r&&(clearTimeout(r.id),r.id=setTimeout(r.expire,Math.max(n-Date.now(),250))))}),o={async afterUnloadDocument({instance:e}){!t&&e.getDocumentsCount()===0&&(t=!0,i.resolve())}};Je.configuration.extensions.push(o);try{let o=Array.from(Je.documents.keys());Je.closeConnections(),Je.flushPendingStores();for(let e of Je.documents.values())e.getConnectionsCount()===0&&Je.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});for(;Date.now()<n-250&&Array.from(Je.documents.values()).some(e=>e.getConnectionsCount()===0&&!pt(e));)await new Promise(e=>setTimeout(e,25));for(let e of M.getRefusedStoreDocNames()){if(CW(e))continue;let t=Je.documents.get(e);if(!t||!pt(t))continue;if(n-Date.now()<50){C.warn({docName:e},`[rescue] refused-store pass out of budget before ${e}; leaving it and any remaining refused docs to the flush timeout path`);break}if(oi(e,`refused-store-shutdown`)!==`rescued`){C.warn({docName:e},`[rescue] refused-store doc rescue failed; leaving ${e} to the flush timeout path`);continue}let r=!1,i=!1,a=ft(t).then(()=>{r=!0}).catch(t=>{i=!0,r=!0,C.warn({docName:e,err:t},`[rescue] refused-store doc unload failed at shutdown: ${e}`)}),o=0;do{let e=Math.max(n-Date.now(),50);o+=e;let t;try{await Promise.race([a,new Promise(n=>{t=setTimeout(n,e)})])}finally{t!==void 0&&clearTimeout(t)}}while(!r&&Date.now()<n);if(!r){C.warn({docName:e,unloadDeadline:o},`[rescue] refused-store doc unload did not finish before the flush deadline; leaving ${e} to the flush timeout path`),a.then(()=>{i||C.info({docName:e},`[rescue] refused-store doc unload completed after the flush deadline: ${e}`)});continue}i||C.info({docName:e},`[rescue] refused-store doc rescued and unloaded at shutdown: ${e}`)}let s=new Promise((i,s)=>{let c=()=>{if(t)return;t=!0,a();let n=Array.from(Je.documents.keys()),r=[],i=[];if(We.current)for(let e of n)CW(e)||(oi(e,`flush-timeout`)===`rescued`?r.push(e):i.push(e));else{C.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`);for(let e of n)CW(e)||(i.push(e),$U())}let c=r.length>0||i.length>0?` — rescued [${r.join(`, `)}]${i.length>0?`, lost [${i.join(`, `)}]`:``}`:``;s(Error(`flushAllStoresAndWait timeout: no document retired for ${e}ms — ${n.length}/${o.length} docs did not unload: [${n.join(`, `)}]${c}`))};r={id:setTimeout(c,Math.max(n-Date.now(),250)),expire:c}});await Promise.race([i.promise,s])}finally{t=!0,a();let e=Je.configuration.extensions,n=e.indexOf(o);n!==-1&&e.splice(n,1),r&&clearTimeout(r.id)}}async function ci(){return ti||(ni=!0,ti=(async()=>{let e=Date.now(),t=[],n={phaseErrors:t,authorityGateReached:!1};ri=n;let i=Math.min(m,2e3),a=Date.now()+i,o=()=>Math.max(1,a-Date.now()),s=async(e,t)=>{let n;try{return await Promise.race([e,new Promise((e,r)=>{n=setTimeout(()=>r(Error(`${t} did not retire before the pre-flush deadline`)),o())})])}finally{clearTimeout(n)}};ut=!0;let c=Promise.allSettled([Qe()]),l;try{[l]=await s(c,`mutation-drain`)}catch(e){t.push({phase:`mutation-drain`,error:String(e)}),C.error({err:e},`[server] shutdown mutation drain failed`)}$n.clearTimeout(er),er=null,cr();for(let e of ne.all())Ke.discardDeferredStore(e.docName,{kind:`shutdown`}),Pr(e.docName,T()??`main`,`delete`,!0),mW(`shutdown`),M.releaseStores(e.docName);ne.clear(),M.endAllRenameCarries(),rr.clear(),ir.clear(),Te=!0,Jr();for(let e of yn.values())for(let t of e)t.namespaceAllowed=!1,t.residentAllowed=!1;yn.clear(),vn=new WeakMap;try{await s(Qt(),`generated-index`)}catch(e){C.warn({err:e},`[index] generated index shutdown drain failed`),t.push({phase:`generated-index-drain`,error:String(e)})}for(let e of dt.splice(0))e();try{await s(Promise.resolve(at?.dispose()),`staleness-watchdog`)}catch(e){C.warn({err:e},`[server] staleness watchdog drain failed during destroy`),t.push({phase:`staleness-watchdog-drain`,error:String(e)})}at=null;try{I4(je)}catch(e){C.warn({err:e},`[server] failed to mark server.lock draining`)}Ge?.destroy();try{await s(Xt(),`shadow-housekeeping`)}catch(e){C.warn({err:e},`[shadow-housekeeping] shutdown drain failed`),t.push({phase:`shadow-housekeeping-drain`,error:String(e)})}if(pn!==null&&(clearTimeout(pn),pn=null),mn)try{qLt(r,gn.entries())}catch(e){C.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let u,d=await Promise.race([mt.then(()=>`completed`,e=>(C.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{u=setTimeout(()=>e(`timeout`),o())})]);u!==void 0&&clearTimeout(u),d===`timeout`&&(C.warn({},`[server] init did not complete before the pre-flush deadline`),t.push({phase:`initialization-drain`,error:`Initialization remains pending`}));let f;try{await Promise.race([Promise.allSettled(Je.loadingDocuments.values()),new Promise((e,t)=>{f=setTimeout(()=>t(Error(`Pending document loads did not retire`)),o())})])}catch(e){t.push({phase:`document-load-drain`,error:String(e)}),C.error({err:e},`[server] shutdown document load drain failed`)}finally{clearTimeout(f)}let p=Je.documents.size,h=async(e,t)=>{if(e!==null)try{await e.unsubscribe()}catch(e){ii(t,e)}};try{try{et&&=(clearTimeout(et),null),tt&&=(clearTimeout(tt),null),await h(w,`head`),w=null,await h(Yr,`content`),Yr=null;for(let{docName:e,cleanup:t}of In)try{await t()}catch(t){C.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}In.length=0,Ln.clear();try{O?.destroy(),rt?.destroy(),Pn&&=(await Pn.disconnect(),null);for(let[e,t]of Fn)try{await t.disconnect()}catch(t){C.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Fn.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await Ye.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Jit()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await si(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([Ue.close(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`derived index close did not settle within ${i}ms`)),i)})])}catch(e){t.push({phase:`derived-index-close`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown derived-index close failed`)}finally{e!==void 0&&clearTimeout(e)}let n;try{await Promise.race([(async()=>{await Ke.flushPendingGitCommit(),await Ke.waitForPendingCommits()})(),new Promise((e,t)=>{n=setTimeout(()=>t(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{n!==void 0&&clearTimeout(n)}try{ei&&=(await ei.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(We.current){let e;try{await Promise.race([fJ(We.current).drain(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`shadow mutator drain timeout`)),m)})])}catch(e){t.push({phase:`shadow-mutator-drain`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-5 shadow mutator drain failed`)}finally{e!==void 0&&clearTimeout(e)}try{let e=(await kN({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&mc(K(We.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{Eet(We.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}if(l?.status===`rejected`){let e=l.reason,n=e instanceof AggregateError?e.errors:[e];t.push({phase:`local-op-subprocess-shutdown`,error:n.map(e=>e instanceof Error?e.message:String(e)).join(`; `)}),C.error({err:e},`[server] shutdown local-op subprocess drain failed`)}let i=Date.now()-e;if(n.authorityGateReached=!0,t.length===0){we=!0;try{Pe.release()}catch(e){t.push({phase:`authority-release`,error:String(e)}),C.error({err:e},`[server] shutdown authority release failed`)}C.info({documentCount:p,durationMs:i},`[server] shutdown flushed ${p} documents in ${i}ms`)}else C.warn({documentCount:p,durationMs:i,phaseErrors:t},`[server] shutdown flushed ${p} documents in ${i}ms with ${t.length} phase error(s)`)}}finally{try{F4(je,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await rH()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}ri===n&&(ri=null)}if(l?.status===`rejected`)throw l.reason})(),ti)}let li=[];async function ui(){try{ct=await NLt(r),C.info({principalId:ct.id},`[server] principal loaded`)}catch(e){C.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!We.current)try{We.current=await xJ(r,{deferGcConfig:!0}),C.info({gitDir:We.current.gitDir},`[server] history repo initialized at ${We.current.gitDir}`),xet(We.current)&&!li.includes(`shadow-excludes`)&&li.push(`shadow-excludes`)}catch(e){C.error({err:e},`[server] history repo init failed`),li.push(`shadow-repo`)}if(We.current)try{let e=hct(We.current.gitDir);Nct(We.current.gitDir,e),bct(We.current.gitDir,e),Kt=e,C.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){C.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(We.current)try{await yJ(We.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){C.warn({},`[server] history repo appears corrupted — reinitializing`);try{We.current=await xJ(r,{deferGcConfig:!0}),xet(We.current)&&!li.includes(`shadow-excludes`)&&li.push(`shadow-excludes`)}catch(e){C.error({err:e},`[server] history repo reinit failed`),We.current=void 0,li.includes(`shadow-repo`)||li.push(`shadow-repo`)}}else C.error({err:e},`[server] history repo check failed (transient?)`)}if(We.current&&ti===null){let e=We.current,t=JW(G(r,n))||`.`;tt=setTimeout(()=>{tt=null,wJ(e,t).catch(e=>{C.debug({err:e},`[shadow] fan-out index warm-up failed (non-fatal)`)})},3e3),tt.unref?.()}if(We.current)try{let e=K(We.current.gitDir,`last-known-head`),t=null;try{t=J(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await kN({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await kN({baseDir:r,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}C.info({lastKnownHead:t,currentHead:n,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=import`);try{await kJ(We.current,p??``,t,n,e),f0e()}catch(e){C.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else C.info({currentHead:n},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=noop`);try{mc(e,n,`utf-8`)}catch(e){C.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){C.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=jEt(n,r);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;C.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){C.error({err:e},`[server] managed rename recovery failed`),li.push(`managed-rename-recovery`)}try{let e=x_t(r);(e.deleted>0||e.errors>0)&&C.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){C.error({err:e},`[server] upload-tempfile sweep failed`),li.push(`upload-tempfile-sweep`)}try{Pn=await Je.openDirectConnection(lr),O?.emitServerInfo(Ce,E()??void 0)}catch(e){C.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),li.push(`cc1-push`)}let t=y?[]:ro;for(let e of t)try{let t=await Je.openDirectConnection(e);Fn.set(e,t)}catch(t){C.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),li.push(`config-doc:${e}`)}let i=new Map([[Xe,yl(`project`,r)],[Re,yl(`project-local`,r)],[Zn,yl(`user`,r,u)]]);for(let e of t){let t=i.get(e);if(t)try{C.info({docName:e,path:t},`[config-file-watcher] starting`);let n=async t=>{let n=Je.documents.get(e),r=fFt(e,t,Ke.configPersistenceCtx);C.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let i=await L7(n??null,e,t,Ke.configPersistenceCtx);C.info({docName:e,outcome:i,isEcho:r},`[config-file-watcher] applyExternalConfigChange outcome`),Se(e),r||_e(e)},r=await UPt(t,t=>{n(t).catch(t=>{C.warn({err:t,docName:e},`[config-file-watcher] change handler failed`)})});In.push({docName:e,cleanup:r}),Ln.set(e,r.resync),C.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){C.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),li.push(`config-file-watcher:${e}`)}}if(!y){let e=null,t=t=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,Ue.refreshGlobalSkillNodes().catch(e=>{C.warn({err:e,docName:t},`[backlinks] global skill bundle re-ingest failed`)})},300)},n=async(e,n)=>{let r=qyt(e,Ke.managedArtifactCtx);if(!r)return;let i=await $yt(Je.documents.get(r)??null,r,n,Ke.managedArtifactCtx);C.info({docName:r,outcome:i},`[managed-artifact-watcher] external change`),Et(`files`),Mr(r)&&t(r)},r=e=>{let n=qyt(e,Ke.managedArtifactCtx);Et(`files`),n&&Mr(n)&&t(n)};try{let e=Uyt(Ke.managedArtifactCtx),t=await QIt(e,n,r);In.push({docName:`__skill-files__`,cleanup:t}),C.info({roots:e},`[managed-artifact-watcher] skills started`)}catch(e){C.warn({err:e},`[managed-artifact-watcher] skills failed to start`),li.push(`managed-artifact-watcher:skills`)}try{let e=yQ(i6(Ke.managedArtifactCtx)),t=await UPt(e,()=>{Et(`files`)});In.push({docName:`__skill-state__`,cleanup:t}),C.info({path:e},`[skill-state-watcher] started`)}catch(e){C.warn({err:e},`[skill-state-watcher] failed to start`),li.push(`skill-state-watcher`)}}try{let e=K(n,`.okignore`),t=K(r,`.gitignore`),i=null;try{let e=zc(`git`,[`rev-parse`,`--git-common-dir`],DW({cwd:r,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=K(r,e.stdout.trim()),n=W(t,`info`,`exclude`);q(U(n))&&(i=n)}}catch{}let a=i?[e,t,i]:[e,t],o=C;o.info({okignorePath:e,gitignorePath:t,gitInfoExcludePath:i,ephemeral:y},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=y?null:await WPt(a,(t,n)=>{(async()=>{if(t===e)try{let e=await L7(Je.documents.get(`__config__/okignore`)??null,$r,n,Ke.configPersistenceCtx);o.info({docName:$r,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:G(r,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await He.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:G(r,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),O?.signal(`files`);else{let e=G(r,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),O?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:G(r,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(In.push({docName:`__ignore-files__`,cleanup:s}),Ln.set($r,s.resync),o.info({okignorePath:e,gitignorePath:t},`[ignore-watcher] multi-path watcher started`))}catch(e){C.warn({err:e,projectDir:r,contentDir:n},`[ignore-watcher] failed to start multi-path watcher`),li.push(`ignore-files-watcher`)}let a=r9(r).branch??`main`;I(a),wt();let o=Ue.beginStartup(a),s=!1,c=performance.now();try{await oH(`ok.boot.indexes`,void 0,async()=>{let t=await o.offlineDeletionsReady,i=0;for(let e of t)CW(e)||gn.peek(e)?.kind!==`renamed`&&(gn.setDeleted(e),i++);i>0&&C.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`),St.resolve();let{backlinkIndexDegraded:a}=await o.backlinksReady;a&&li.push(`backlink-index`);let c=performance.now(),l=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,d=He?new Set(R1(n).map(e=>e.dir)):new Set,f=e=>{e.some(e=>l.test(G(b,e).split(Js).join(`/`)))&&(et&&clearTimeout(et),et=setTimeout(()=>{et=null;try{t0(r,n).then(e=>{e>0&&(C.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),O?.signal(`files`))}).catch(e=>C.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=Jut(n,d);if(!(e.size!==d.size||[...e].some(e=>!d.has(e))))return;d=e,He.rebuildIgnorePatterns().then(t=>{t.ok?(C.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),O?.signal(`files`)):C.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>C.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){C.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};await ai(()=>oH(`ok.boot.seed-walk`,void 0,async()=>vit(b,Gr,He,{onRawBatch:f,onRecoveryComplete:()=>Ue.recordInventoryReconciled(),onRecoveryPassCompleted:(e,t)=>wr(e,t),nativeBackend:e.watcherBackend,clock:e.watcherClock,freshnessIntervalMs:e.freshnessIntervalMs===void 0?5e3:e.freshnessIntervalMs})),e=>{Yr=e},`content`),t0(r,n).then(e=>{e>0&&C.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>C.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=u??_c();B1(e).then(t=>t0(e,e,t)).then(e=>{e>0&&C.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>C.warn({err:e},`[in-place-skills] global copy re-sync failed`))}Z2(`seedWalkMs`,Math.round(performance.now()-c));{let e=K(n),t=0;for(let[n]of gn.entries()){if(!s5(n))continue;let r=K(e,`${n}${qU(n)}`);YW(r,e)&&q(r)&&(gn.delete(n),t++)}t>0&&C.info({count:t},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let p=await Ue.settleStartupAfterWatcherSeed();s=!0,p.tagIndexDegraded&&li.push(`tag-index`);let m=0;try{v===void 0?await d5({contentDir:n,contentFilter:He,basenameIndex:Ie,onSkip:(e,t,n)=>{m++,C.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):eOt({contentDir:n,basenameIndex:Ie,onSkip:(e,t,n)=>{m++,C.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),m>0&&(C.warn({count:m},`[basename-index] startup seed completed with ${m} skipped entries — embeds under inaccessible subtrees will not resolve`),li.push(`basename-index-partial`))}catch(e){C.error({err:e},`[basename-index] startup seed failed`),li.push(`basename-index`)}})}catch(e){if(C.error({err:e},`[server] disk bridge watcher failed to start`),li.push(`file-watcher`),!s){let e=await Ue.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&li.push(`tag-index`)}}finally{Z2(`indexesMs`,Math.round(performance.now()-c)),Yr&&yht(`fileCount`,Yr.getFileIndex().size),Wn()}let l=()=>{};try{await ai(()=>bIt(r,async({trigger:e})=>{if(C.info({trigger:e},`[batch] begin trigger=${e}`),d0e(),Je.flushPendingStores(),await Ke.flushPendingGitCommit(),re(`head-watcher`),l(),l=M.holdWriteAdmission(),We.current){let e=N(),t=r9(r).branch??e,n=[],i=0;for(let[e,t]of Je.documents){if(CW(e))continue;let r=null;if(t.transact(()=>{r=zn(e)},_zt),r===null)continue;let a=ee(e);if(a===void 0){i++;continue}n.push({docName:e,markdown:r,diskSnapshot:a})}if(i>0&&C.warn({count:i,branch:e},`[history] skipped parking ${i} doc(s) with no reconciled base; their content was not parked to the shadow history`),n.length>0)try{let r=await Het(We.current,e,DJ.id,n,t);r&&(v0e(),C.info({count:n.length,branch:e,sha:r.slice(0,8)},`[history] parked ${n.length} docs on ${e} → ${r.slice(0,8)}`))}catch(e){C.error({err:e},`[shadow] park failed`)}}},async e=>{let t=Wr.length,i=e.newBranch??`main`;if(C.info({kind:e.batchKind,headMoved:e.headMoved,docs:t,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${t}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){try{try{await qr()}finally{Jr()}if(e.headMoved&&e.newHead){let t=yzt(r,K(n),e.oldHead,e.newHead);if(t.size>0){Lst(t.keys());for(let[e,n]of t)t$(e,rye(n.email),n.name,n.email,Eye(e));await Ke.flushContributors()}}}finally{try{ie(`head-watcher`)&&await ae()}finally{l()}}try{await ce.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e},`[head-watcher] conflict prune against git failed`)}}else{_0e(),cr();let t=!1,r=!1,a;try{I(i),ce.setBranch(i),le(),a=await Ue.beginBranchSwitch(i),He.rebuildDirCount();try{let e=0;Ie.clear(),await d5({contentDir:n,contentFilter:He,basenameIndex:Ie,onSkip:(t,n,r)=>{e++,C.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(C.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),li.includes(`basename-index-partial`)||li.push(`basename-index-partial`))}catch(e){C.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}try{await Ue.settleBranchFromDisk(a)}catch(e){Ue.abortBranchSwitch(a),C.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}try{await qr();let e=await Yr?.recheck(`full`);e&&(e.status!==`completed`||e.partial)&&(r=!0,s4e(),C.warn({branch:i,status:e.status,partial:e.partial===!0},`[branch-switch] the re-check after switching to ${i} did not observe the whole tree; another one runs once the switch ends`)),await qr()}finally{Jr()}if(Nr(i),C.info({branch:i,docCount:Je.documents.size},`[branch-switch] loaded branch ${i} (${Je.documents.size} docs)`),e.oldBranch?.startsWith(`detached-`)&&We.current)try{let t=yJ(We.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await fJ(We.current).withMutator(async()=>{for(let e of n.split(`
2324
2324
  `))e&&await t.raw(`update-ref`,`-d`,e)}),C.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){C.error({err:e},`[branch-switch] detached cleanup failed`)}t=!0,ie(`head-watcher`)&&await ae(),O?.emitBranchSwitched(i),r&&ur(i)}finally{try{Ue.abortBranchSwitch(a),!t&&ie(`head-watcher`)&&await ae()}finally{l()}}}if(e.headMoved&&e.newHead&&We.current&&t>0){let t=p??`.`;try{let n=await kJ(We.current,t,e.oldHead,e.newHead,i);f0e(),C.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){C.error({err:e},`[shadow] upstream-import failed`)}}},{nativeBackend:e.watcherBackend,clock:e.watcherClock,onGaveUp:()=>{li.includes(`head-watcher`)||li.push(`head-watcher`)},onBack:()=>{let e=li.indexOf(`head-watcher`);e!==-1&&li.splice(e,1)}}),e=>{w=e},`head`)}catch(e){C.error({err:e},`[server] HEAD watcher failed to start`),li.push(`head-watcher`)}ce.subscribe(e=>{if(e.type!==`raised`||e.conflict.kind===`reconcile`)return;let t=e.docName;if(t===null||!Je.documents.get(t))return;let n=zn(t);n===null?C.warn({docName:t,file:e.conflict.file},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):te(t,n)});try{await ce.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e},`[conflicts] boot prune of merge-native entries failed`)}let d=await S(),f=ue(),m=de();f.mode!==`off`&&C.info({mode:f.mode,source:f.source},`[sync] mode active at boot`);try{ei=new rzt({declaredGitHubHosts:x,projectDir:r,contentDir:n,contentFilter:He,contentRoot:p,mcpTomlEditor:e.mcpTomlEditor,mode:f.mode,pullIntervalSeconds:e.pullIntervalSeconds??m.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds??m.pushIntervalSeconds,credentialConfig:d,resolveCredentialConfig:S,cc1Broadcaster:O,conflicts:ce,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:oe(`sync-engine`),onStateChange:e=>{C.info({state:e},`[sync] state → ${e}`)},checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=We.current;n&&await jJ(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=We.current;n&&await jJ(n,p??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{C.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await xl({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||C.error({result:t,reason:e,humanError:Sre(t.error),configPath:yl(`project-local`,r)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await ei.start()}catch(e){C.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ei=null}Et(`files`),Ue.announceReadyViews();let h=vht();h!==void 0&&Z2(`readyMs`,h),_e()}return ui().then(()=>{At=!0,ht(),setImmediate(()=>{let e=A.pruneGone(j);e>0&&C.info({pruned:e},`[disk-receipts] dropped ${e} receipt(s) whose file is gone`)}).unref(),Ht(),Jt()},e=>{jt=!0,Mt.abort(),zt({status:`failed`,indexCount:0}),Ue.close(),wt(),gt(e)}),{hocuspocus:Je,durabilityState:M,sessionManager:Ye,nativeApi:R,localApi:Ze,cc1Broadcaster:O,agentFocusBroadcaster:nt,agentPresenceBroadcaster:rt,maintenanceCoordinator:Ge,contentFilter:He,basenameIndex:Ie,serverInstanceId:Ce,destroy:ci,ready:mt,generatedIndexSweepReady:Rt,degraded:li,lockDir:je,get syncEngine(){return ei},conflicts:ce,getLinkPreviewsEnabled:he,resolveEmbed:Be,resolveTrackedFile:Le,acpRegistry:Me,acpPermissions:Ne,recheckDisk:()=>Yr?Yr.recheck():Promise.reject(Error(`the file watcher is not running, so there is nothing to re-check`))}}function R9(e){return e/1048576}function xzt(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:R9(e.rss),heapTotalMb:R9(e.heapTotal),heapUsedMb:R9(e.heapUsed),externalMb:R9(e.external),arrayBuffersMb:R9(e.arrayBuffers)}}}let z9=null,B9=null,V9=null;const Szt=1e6;let H9=null,U9=null;nH(()=>{z9=null,B9=null,V9=null,H9?.disable(),H9=null,U9=null});function Czt(){if(z9)return;let e=aH().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss, external, array_buffers}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=xzt();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),z9=e}function wzt(){if(!B9){let e=aH().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!H9){H9=eoe({resolution:20}),H9.enable();return}e.observe(H9.percentile(50)/Szt,{stat:`p50`}),e.observe(H9.percentile(99)/Szt,{stat:`p99`}),H9.reset()}),B9=e}if(!V9){let e=aH().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=U9;if(U9={cpu:t,hrtimeNs:n},!r)return;let i=Number(n-r.hrtimeNs)/1e3;i<=0||(e.observe((t.user-r.cpu.user)/i,{mode:`user`}),e.observe((t.system-r.cpu.system)/i,{mode:`system`}))}),V9=e}}const Tzt=Y(`skill-migrate`);function Ezt(e){return[{host:`agents`,root:Oi},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=vO.indexOf(e.host),r=vO.indexOf(t.host);return(n===-1?vO.length:n)-(r===-1?vO.length:r)||e.host.localeCompare(t.host)})}const Dzt=Ezt(Sr),Ozt=Ezt(M);function kzt(e,t){return q(K(e,Zi(t)))}function Azt(e,t){SH(U(t),{recursive:!0});try{CH(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;wH(e,t,{recursive:!0}),AH(e,{recursive:!0,force:!0})}}function jzt(e,t,n){let r=mdt(e,t,n);switch(r.kind){case`absent`:return{kind:`absent`};case`other`:return{kind:`occupied`,by:`different`};case`symlink`:return r.resolution===`target`?{kind:`store-link`}:{kind:`occupied`,by:`foreign-link`};case`dir`:return r.identity===`different`?{kind:`occupied`,by:`different`}:{kind:`same-copy`}}}function Mzt(e,t){let n;try{n=cc(K(e,`.ok`,`skills`))}catch{n=K(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!cc(K(e,t.dir)).startsWith(n+Js)}catch{return!0}}).map(e=>e.name))}async function Nzt(e){let{projectDir:t,skillsRoot:n}=e,r,i=async t=>(r??=e.inPlaceNames?.()??Promise.resolve(new Set),(await r).has(t)),a=e.hostRoots??Dzt,o={migrated:[],skipped:[]};if(!q(n))return o;let s;try{s=sc(n)}catch{return o}let c=G(t,n).split(Js).join(`/`),l=new Set;for(let[e,n]of Object.entries($1(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===c&&l.add(e);for(let e of s)try{if(!We.test(e)||PU.has(e))continue;if(await i(e)){o.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(l.has(e)){o.skipped.push({name:e,reason:`recorded-placement`});continue}let r=K(n,e);if(!q(W(r,`SKILL.md`)))continue;let s=uO(r)?.contentHash;if(s===void 0)continue;let c=cc(r),u=a.map(({host:n,root:r})=>{let i=K(t,r);return{host:n,root:r,path:W(i,e),escapes:l0(t,i),state:jzt(W(i,e),c,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>kzt(t,e.root));if(!d){o.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){o.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?AH(r,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&AH(d.path,{recursive:!0,force:!0}),Azt(r,d.path));for(let e of u)e!==d&&e.state.kind===`store-link`&&(AH(e.path,{recursive:!0,force:!0}),wH(d.path,e.path,{recursive:!0}));await K1(t,e),o.migrated.push({name:e,to:`${d.root}/${e}`}),Tzt.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){o.skipped.push({name:e,reason:`error`}),Tzt.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return o}let W9=null,G9=!1;function Pzt(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function Fzt(e){if(!Pzt())return;let t=RJ(e);W9=new sx({currentPath:K(t,`tolerance-telemetry.jsonl`),previousPath:K(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),Yn(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};W9?.append(`${JSON.stringify(t)}\n`).catch(e=>{G9||(G9=!0,Y(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function K9(){Yn(null),await W9?.drain(),W9=null,G9=!1}function Izt(e){let t=K(e,T);if(!(()=>{if(!q(t))return!0;try{return sc(t).length===0}catch{return!0}})())return[];let n=[];for(let t of y)q(K(e,t))&&n.push(t);for(let t of S){let r=K(e,t);try{q(r)&&fc(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function Lzt(e){let t=gx(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const q9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function Rzt(e){_ht();let t=e.projectDir??e.contentDir,n=Tl(t),r=vOt({projectDir:t});if(r){PPt(t,{authorityRegistryPath:e.authorityRegistryPath});let n=r.telemetry.attributeDenylist,i=[];for(let e of n){i.push(e);for(let t=1;t<=5;t++)i.push(`${`*.`.repeat(t)}${e}`)}dx.configure({pinoConfig:{fileSink:r.logs,redactPaths:i}})}tH({localSink:r?.telemetry}),Fzt(t),Czt(),wzt();let{kind:i,gitdir:a}=Lzt(e.projectDir??e.contentDir),o={"ok.worktree.kind":i};a!==null&&(o[`ok.worktree.gitdir`]=uH(a));let s=dOt(t),c=process.env.OK_STARTUP_TRACEPARENT,l=()=>oH(`ok.boot`,{attributes:o},async()=>zzt(e,n)),u=()=>{if(c)try{let e=Oo.extract(wo.active(),{traceparent:c});return wo.with(e,l)}catch(e){Y(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return l()},d;try{d=await u()}catch(e){throw s.uninstall(),e}let f=d.destroy;return d.destroy=async(e,t)=>{try{await f(e,t)}finally{s.uninstall()}},d}async function zzt(e,t){let n=e.skipAutoInit??!1,r=e.log??Y(`boot`),i=e.serverRuntime??{...yr(e.config),allowExternal:!1},a=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((wee(i)||!jr(a))&&!i.allowExternal)throw new nst(`refusing to start: the server would bind a non-loopback address (${(jr(a)?i.bind:a).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let o=MQ({serverRuntime:i});i.allowExternal&&!i.loopbackOnly&&i.externalUrl===void 0&&(o.bindLiterals.length===0?r.warn({bind:i.bind},`[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.externalUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.externalUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.`):r.info({bind:i.bind},`[ingress] server.allowExternal is set with no server.externalUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.externalUrl to admit a hostname.`));let s=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,c=e.lockKind??s??`interactive`,{createServer:l}=await import(`node:http`),{markServerLockDraining:u,releaseServerLock:f,updateServerLockPort:p}=await Promise.resolve().then(()=>Rgt),m=!1;if(!n&&e.autoInitFn)try{m=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let h=e.projectDir??e.contentDir,g=K(h,`.ok`),_=K(g,`config.yml`);if(!q(_))throw new kPt(q(g)?`config`:`okdir`,h);let v=K(g,`.gitignore`);q(v)||Y(`boot`).warn({path:v},`Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run \`${d()} init\` to add the recommended ignore entries.`);let y=e.gitPreflight??jW;try{e.gitEnabled!==!1&&y()}catch(e){if(e instanceof OW||e instanceof kW||e instanceof AW){let t=I6(e);L6(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:t.reason,detectedVersion:t.detectedVersion},t.logMessage),process.stderr.write(`${e.message}\n`)}throw await rH(),await Promise.race([K9(),new Promise(e=>setTimeout(e,q9))]),e}let b=Izt(g);b.length>0&&Y(`boot`).warn({files:b},`Found legacy runtime files at .ok/${b.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${T}/.`);let x=null,S=bzt({authorityRegistryPath:e.authorityRegistryPath,getCollabClientCount:()=>x?.getCount()??0,acpRegistryFetchImpl:e.acpRegistryFetchImpl,contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:o,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,mcpTomlEditor:e.mcpTomlEditor,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:c,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,agentIntegrations:e.agentIntegrations,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral,configHomedirOverride:e.configHomedirOverride,watcherBackend:e.watcherBackend,watcherClock:e.watcherClock,freshnessIntervalMs:e.freshnessIntervalMs}),{hocuspocus:C,destroy:w,ready:E,degraded:D,lockDir:O,sessionManager:k,agentFocusBroadcaster:A,agentPresenceBroadcaster:j,maintenanceCoordinator:M}=S,N=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),P=e.port??0,ee=()=>`http://${N}:${P}`,te=e.ephemeral?void 0:bPt({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>ee(),localApi:S.localApi,log:r}),F=l();F.headersTimeout=3e4,F.requestTimeout=6e4;let I=e.serveContentAssets===!1?void 0:$Dt({contentDir:e.contentDir,contentFilter:S.contentFilter,contentSirv:LI(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:xi,assetExtensions:be,blocklistExtensions:tee,ingressPolicy:o,resolveTrackedFile:S.resolveTrackedFile}),ne=e.reactShellDistDir?LI(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0,setHeaders:fOt(e.reactShellDistDir)}):void 0,re=e.ephemeral?null:new P7e({contentDir:e.contentDir,localDir:O,globalDir:Ls(),registry:S.acpRegistry,permissions:S.acpPermissions,sessionManager:k,agentPresenceBroadcaster:j,localApi:S.localApi,isExcludedPath:e=>S.contentFilter.isExcluded(e),isIgnoredPath:e=>S.contentFilter.isPathIgnored(e),getLoadedDocText:e=>C.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>ee(),getMcpStdioCommand:()=>N7e(e.localOpCliArgs,P,{log:r}),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,probePiAcpBridge:e.probePiAcpBridge,ensurePiAcpBridge:e.ensurePiAcpBridge,terminalAuthAvailable:e.terminalAuthAvailable===!0,hostSnapshot:()=>Tq({env:`local-web`,resolve:e.agentIntegrations?.probe}),autoApproveOkTools:()=>o1e(e.projectDir??e.contentDir,e.configHomedirOverride,r),agentBrowserTools:()=>s1e(e.projectDir??e.contentDir,e.configHomedirOverride,r),log:r});re!==null&&await re.init();let ie=`pending`;E.then(()=>{ie=`ready`},()=>{ie=`failed`});let ae=DPt({httpServer:F,hocuspocus:C,nativeApi:S.nativeApi,mcpHttpHandler:te,ingressPolicy:o,health:{readiness:()=>ie,degraded:()=>D},log:r,sessionManager:k,agentFocusBroadcaster:A,agentPresenceBroadcaster:j,maintenanceCoordinator:M,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:I,reactShellMiddleware:ne,ephemeral:e.ephemeral,acpThreadManager:re}),oe=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)};x=h5(F);let se=null,ce=[...new Set(a)],le=ce[0],L=async()=>{await w().catch(e=>{r.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),f(O)},ue=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await ue(F,e.port??0,le??`127.0.0.1`)}catch(e){throw await L(),e}let de=F.address(),fe=typeof de==`object`&&de?de.port:e.port??0,pe=[];for(let e of ce.slice(1)){let t=l();t.headersTimeout=F.headersTimeout,t.requestTimeout=F.requestTimeout;for(let e of F.listeners(`request`))t.on(`request`,e);for(let e of F.listeners(`upgrade`))t.on(`upgrade`,e);try{await ue(t,fe,e)}catch(t){r.error({err:t,failedAddress:e,port:fe,alreadyBound:pe.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...pe,F])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&r.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await L(),t}pe.push(t)}let me=vht();me!==void 0&&Z2(`httpListenMs`,me);let he=F.address(),ge=typeof he==`object`&&he?he.port:e.port??0;P=ge;let _e=ee();p(O,ge,_e),r.info({event:`server-listening`,pid:process.pid,port:ge,addresses:ce,url:_e,lockDir:O},`[boot] listening on ${_e}`);let ve=!1,ye=async(e,t,n)=>{let r,i,a=!1,o=Promise.withResolvers(),s=()=>{a||(a=!0,o.reject(Error(n?`${e} timed out: no document retired for ${q9}ms`:`${e} timed out after ${q9}ms`)))},c=()=>{r=setTimeout(s,q9),r.unref?.()};try{n&&(i=hzt(n,()=>{a||(r!==void 0&&clearTimeout(r),c())}),c());let e=t();n||c(),await Promise.race([e,o.promise])}finally{a=!0,i?.(),r!==void 0&&clearTimeout(r)}};oe=async(e=`unspecified`,n={})=>{if(ve)return;ve=!0;try{let e=nc(t);if(e.isDirectory()&&!e.isSymbolicLink()){let e=new Date;pH(t,e,e)}}catch{}r.info({reason:e,signal:n.signal??null,pid:process.pid,lockDir:O},`[server] shutdown initiated (${e})`),ie=`draining`;let i=[],a=async(e,t,n)=>{try{await ye(e,t,n)}catch(t){i.push(t),r.warn({err:t,step:e},`bootServer destroy step failed`)}};try{u(O)}catch(e){r.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{x?.detach()}catch(e){r.warn({err:e,step:`collabClientCounter.detach`},`bootServer destroy step failed`)}try{se?.detach()}catch(e){i.push(e),r.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(re!==null&&await a(`acpThreads.destroy`,()=>re.destroy()),await a(`secondaryListeners.close`,async()=>{for(let e of pe)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&r.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await a(`mount.shutdown`,()=>ae.shutdown()),te!==void 0&&await a(`mcpHttpHandler.close`,()=>te.close()),await a(`mount.wss.close`,()=>new Promise((e,t)=>{ae.wss.close(n=>n?t(n):e())})),await a(`httpServer.closeAllConnections`,async()=>{F.closeAllConnections?.()}),await a(`httpServer.close`,()=>new Promise((e,t)=>{F.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await a(`destroyHocuspocus`,()=>w(),C),await a(`shutdownTelemetry`,()=>rH()),await a(`teardownToleranceTelemetry`,()=>K9()),await a(`flushLogFileSinks`,()=>dx.flushAllFileSinks()),i.length>0)throw AggregateError(i,`bootServer destroy completed with errors`)};try{let t=await Nzt({projectDir:h,skillsRoot:K(e.contentDir,`.ok`,ya),inPlaceNames:async()=>Mzt(e.contentDir,R1(e.contentDir))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=_c(),t=await Nzt({projectDir:e,skillsRoot:K(e,`.ok`,ya),hostRoots:Ozt,inPlaceNames:async()=>Mzt(e,await B1(e))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}if(e.idleShutdownMs!==null){let t=e.idleShutdownMs??18e5,n=e.idleShutdownHandler??(e=>async()=>{await e()});se=pOt({httpServer:F,counter:x,thresholdMs:t,log:r,onShutdown:n(async()=>{await oe(`idle-shutdown`)})})}return{httpServer:F,destroy:oe,lockDir:O,contentDir:e.contentDir,port:ge,ready:E,generatedIndexSweepReady:S.generatedIndexSweepReady,degraded:D,didAutoInit:m,serverInstance:S,runtime:IPt(S,{contentDir:e.contentDir,projectDir:h}),acpThreadManager:re}}const Bzt=Ca;function Vzt(e={}){let t=e.home??_c(),n=e.platformName??process.platform,r=e.env??process.env;if(n===`darwin`)return q(W(t,`Library`,`Application Support`,`Claude`));if(n===`win32`){let e=r.APPDATA??W(t,`AppData`,`Roaming`);return q(W(e,`Claude`))}return!1}function Hzt(e){let t=K(e),n=0;for(;n<30;){let e=!1;try{e=q(K(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=U(t);if(r===t)return null;t=r,n+=1}return null}const J9=Bc(Ic),Y9=Y(`project-git`);var X9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function Uzt(e,t){try{return await J9(e,[`var`,`GIT_COMMITTER_IDENT`],DW({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function Wzt(e,t){try{let{stdout:n}=await J9(e,[`for-each-ref`,`--count=1`,`refs/`],DW({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return Y9.warn({path:t,stderr:Kzt(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function Gzt(e){let t=K(e,`packed-refs`);if(q(t))try{if(J(t,`utf-8`).split(`
2325
2325
  `).some(e=>e.trim()!==``&&!e.startsWith(`#`)))return!0}catch{return!0}try{return sc(K(e,`refs/heads`)).length>0}catch{return!1}}function Kzt(e){let t=typeof e==`object`&&e?e:null,n=t?.stderr;return n==null?String(t?.message??e):Buffer.isBuffer(n)?n.toString(`utf-8`):String(n)}async function qzt(e,t){if(await Wzt(e,t))return;let n=[`commit`,`--allow-empty`,`--no-verify`,`--no-gpg-sign`,`-m`,`Initial commit`],r=await Uzt(e,t),i=r?n:[`-c`,`user.name=Open Knowledge`,`-c`,`user.email=noreply@openknowledge.local`,...n];try{await J9(e,i,DW({cwd:t,encoding:`utf-8`})),r||Y9.info({path:t},`created initial commit with fallback identity (git identity unset)`)}catch(e){Y9.warn({path:t,stderr:Kzt(e)},`could not create initial commit`)}}async function Jzt(e,t){try{let{stdout:n}=await J9(e,[`rev-parse`,`--is-inside-work-tree`],DW({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function Yzt(e){let t=K(e);Hq(t);let n=K(t,`.git`),r=K(n,`HEAD`),i=!1,a=!1;if(q(n)){if(!fc(n).isDirectory())return{didInit:!1};if(q(r)){if(Gzt(n))return{didInit:!1};a=!0}else Y9.info({},`detected partial .git/ — running git init to repair`),i=!0}let o;try{o=jW()}catch(e){if(e instanceof OW||e instanceof kW||e instanceof AW){let t=I6(e);L6(e),Y9.warn({event:`git_preflight_fail`,platform:e.platform,reason:t.reason,detectedVersion:t.detectedVersion},t.logMessage)}else Y9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`);throw e}let s=o.resolvedPath;if(a)return await qzt(s,t),{didInit:!1};if(!i&&await Jzt(s,t))return{didInit:!1};let c=``;try{let{stdout:e}=await J9(s,[`config`,`--default`,`main`,`--get`,`init.defaultBranch`],DW({cwd:t,encoding:`utf-8`}));c=(await J9(s,[`init`,`--initial-branch=${e.trim()}`,t],DW({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new X9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!q(r))throw new X9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,c);return await qzt(s,t),i?(Y9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(Y9.info({path:t},`initialized .git/`),{didInit:!0})}async function Xzt(e,t){let n;try{n=Rs(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=U(n),r=0;r<32;r+=1){let n=W(t,`package.json`);if(q(n))try{let t=JSON.parse(await wc(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=U(t);if(r===t)return;t=r}}const Zzt=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function Z9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of Zzt)t=t.replace(e,n);return t}function Q9(e,t=0,n=new WeakSet){if(t>=5)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > 5; truncated`};if(typeof e==`object`&&e){if(n.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};n.add(e)}if(e instanceof Error)return{name:e.name,message:Z9(e.message)??``,stack:Z9(e.stack),code:e.code,cause:e.cause===void 0?void 0:Q9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:Z9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:Z9(String(r.message??``))??``,stack:Z9(r.stack),code:r.code,cause:r.cause===void 0?void 0:Q9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var Qzt=class extends Error{filePath;constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},$zt=class extends Error{filePath;constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},$9=class extends Error{projectRoot;constructor(e,t){super(`Cannot open with --project ${e}: ${t}`),this.projectRoot=e,this.name=`SingleFileProjectOverrideError`}},eBt=class extends Error{filePath;constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function tBt(e,t={}){if(!BU(e))throw new eBt(e);let n;try{n=cc(K(e))}catch(t){throw t.code===`ENOENT`?new Qzt(e):t}if(!fc(n).isFile())throw new $zt(e);let r=U(n);if(t.projectRoot!==void 0){let e=K(t.projectRoot);if(!Ps(e))throw new $9(e,`no .ok/config.yml there, so it is not an OpenKnowledge project root`);let r=nBt(e),i=G(r,n);if(i.startsWith(`..`)||Gs(i))throw new $9(e,`${n} is not inside that project's content directory`);return{mode:`project`,projectRoot:e,docName:UU(i.split(Js).join(`/`)),canonicalFilePath:n}}let i=_ae(r);if(i){let e=i.rootPath,t=nBt(e);return{mode:`project`,projectRoot:e,docName:UU(G(t,n).split(Js).join(`/`)),canonicalFilePath:n}}let a=Hs(n);return{mode:`ephemeral`,canonicalFilePath:n,contentDir:r,singleDocRelPath:a,docName:UU(a)}}function nBt(e){let t=gl({absPath:yl(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`;return K(e,t)}const rBt=`ok-ephemeral-`;function iBt(e,t){let n=K(e,`.ok`);return rc(n,{recursive:!0}),mc(K(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(t)}\n`,`utf-8`),mc(K(n,`.gitignore`),`local/
2326
2326
  `,`utf-8`),e}function aBt(e){return iBt(ic(K(bc(),rBt)),e)}const oBt=`server-base`;export{Dot as $,AG as $a,E6 as $i,agt as $n,vR as $o,tCt as $r,Hq as $t,Q2 as A,zU as Aa,DPt as Ai,qJ as An,AH as Ao,iH as Ar,dce as As,eBt as At,kW as B,Dft as Ba,pCt as Bi,L6e as Bn,CSt as Bo,Fzt as Br,Zoe as Bs,zW as Bt,NJ as C,MX as Ca,D4 as Ci,Tq as Cn,T4 as Co,Bet as Cr,dx as Cs,G6 as Ct,fG as D,g4e as Da,igt as Di,IW as Dn,SH as Do,Yq as Dr,Fve as Ds,j4 as Dt,mG as E,c1 as Ea,I9e as Ei,Net as En,yH as Eo,RJ as Er,Pve as Es,AK as Et,m4 as F,o4 as Fa,MW as Fi,s9 as Fn,ozt as Fo,c4e as Fr,vl as Fs,RU as Ft,_9e as G,zst as Ga,rJ as Gi,bPt as Gn,sH as Go,$ot as Gr,ese as Gs,cCt as Gt,nOt as H,Xzt as Ha,tBt as Hi,aBt as Hn,Bgt as Ho,TOt as Hr,nse as Hs,M4 as Ht,v9e as I,IRt as Ia,p5 as Ii,XDt as In,jX as Io,rW as Ir,Pse as Is,dK as It,kIt as J,_St as Ja,Vot as Ji,$Ot as Jn,N9e as Jo,dZ as Jr,Zc as Js,jW as Jt,Y$ as K,wnt as Ka,VOt as Ki,Z$ as Kn,Iot as Ko,vW as Kr,$c as Ks,S8e as Kt,ySt as L,Rxt as La,xPt as Li,$Dt as Ln,O4 as Lo,M9e as Lr,xl as Ls,hDt as Lt,p1e as M,a8 as Ma,MU as Mi,n$ as Mn,EH as Mo,WCt as Mr,sce as Ms,S9 as Mt,TJ as N,o8 as Na,S9e as Ni,o9 as Nn,hH as No,AQ as Nr,gl as Ns,oBt as Nt,Hht as O,M0 as Oa,I4 as Oi,V0 as On,vH as Oo,aH as Or,Sl as Os,$zt as Ot,r$ as P,U0 as Pa,aOt as Pi,KIt as Pn,bH as Po,GIt as Pr,yl as Ps,Umt as Pt,b7e as Q,dkt as Qa,Ixt as Qi,GK as Qn,fWe as Qo,PQ as Qr,C8e as Qt,EJ as R,zJ as Ra,iJ as Ri,CPt as Rn,zgt as Ro,xJ as Rr,il as Rs,gDt as Rt,Dit as S,F4 as Sa,P4 as Si,X6 as Sn,OU as So,gCt as Sr,Jve as Ss,G6e as St,eCt as T,O9e as Ta,Nxt as Ti,SJ as Tn,OH as To,ust as Tr,Bve as Ts,kK as Tt,f5 as U,$$ as Ua,FPt as Ui,Yst as Un,DW as Uo,aut as Ur,tse as Us,hQ as Ut,AW as V,Y6 as Va,PPt as Vi,h4 as Vn,J1e as Vo,wOt as Vr,tl as Vs,Mgt as Vt,tOt as W,B5 as Wa,BOt as Wi,MIt as Wn,oH as Wo,Qot as Wr,el as Ws,s$ as Wt,fU as X,TSt as Xa,Fot as Xi,JLt as Xn,wQ as Xo,rOt as Xr,Coe as Xs,E8e as Xt,ggt as Y,gSt as Ya,aet as Yi,bzt as Yn,C9 as Yo,b9e as Yr,voe as Ys,fK as Yt,H8 as Z,dSt as Za,w6 as Zi,$7e as Zn,iX as Zo,y9e as Zr,$Y as Zt,vot as _,M6 as _a,TX as _i,Vq as _n,VJ as _o,Hzt as _r,vx as _s,q6 as _t,C1e as a,r9 as aa,BW as ai,Cit as an,PJ as ao,Eft as ar,MI as as,iQ as at,GCt as b,oX as ba,TU as bi,lJ as bn,Rst as bo,iOt as br,qve as bs,H4e as bt,Z7e as c,TQ as ca,s8 as ci,w9e as cn,iBt as co,sAt as cr,mP as cs,b4 as ct,oOt as d,Pot as da,CW as di,N7e as dn,hot as do,Q as dr,wN as ds,Gct as dt,Oft as ea,wW as ei,sJ as en,cDt as eo,Vzt as er,xR as es,R4e as et,IU as f,CQ as fa,zX as fi,Y1e as fn,yJ as fo,_rt as fr,kN as fs,j9e as ft,y4e as g,Q9e as ga,qq as gi,f4 as gn,vit as go,O4e as gr,Ex as gs,aCt as gt,E2 as h,Q$ as ha,Pzt as hi,L1e as hn,dtt as ho,w2 as hr,yx as hs,Alt as ht,f1e as i,S5 as ia,yW as ii,bft as in,MJ as io,QOt as ir,_R as is,kPt as it,nst as j,LJ as ja,uH as ji,XW as jn,jH as jo,hW as jr,uce as js,$9 as jt,rBt as k,$lt as ka,OPt as ki,H0 as kn,CH as ko,h4e as kr,Tl as ks,Qzt as kt,vQ as l,Bot as la,NQ as li,CMt as ln,Q9 as lo,I5 as lr,uP as ls,bgt as lt,NU as m,t$ as ma,_W as mi,wJ as mn,r8 as mo,zOt as mr,bx as ms,DJ as mt,E1e as n,Igt as na,KOt as ni,h5 as nn,C6 as no,XLt as nr,wVe as ns,b4e as nt,P7e as o,sgt as oa,FQ as oi,Rzt as on,ekt as oo,L6 as or,hP as os,A9e as ot,LU as p,$J as pa,Zlt as pi,oCt as pn,rH as po,ADt as pr,WO as ps,LW as pt,v5 as q,Cnt as qa,s1e as qi,ALt as qn,gxt as qo,WOt as qr,Yoe as qs,eRt as qt,got as r,nJ as ra,OQ as ri,pOt as rn,B4e as ro,u1 as rr,hR as rs,ukt as rt,Y7e as s,N4 as sa,aQ as si,uut as sn,d5 as so,F5 as sr,pP as ss,I1e as st,D1e as t,k4 as ta,aJ as ti,q7e as tn,jJ as to,x4e as tr,nR as ts,Oot as tt,jot as u,$Lt as ua,Kq as ui,MQ as un,cH as uo,Yzt as ur,dP as us,X9 as ut,Uq as v,vPt as va,Ret as vi,Prt as vn,XV as vo,R0 as vr,fx as vs,J6 as vt,Vht as w,E4 as wa,x4 as wi,kJ as wn,xH as wo,D5 as wr,lx as ws,K6 as wt,Bzt as x,A4 as xa,NLt as xi,ogt as xn,K9 as xo,Bst as xr,Y as xs,K6e as xt,ctt as y,W9e as ya,rCt as yi,dH as yn,n5e as yo,Yft as yr,ux as ys,YLt as yt,OW as z,B0 as za,bX as zi,QG as zn,DU as zo,tH as zr,sse as zs,Y4e as zt};