@inkeep/open-knowledge 0.28.0-beta.6 → 0.28.0-beta.8
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.
- package/dist/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +1 -1
- package/dist/cli.mjs +7 -7
- package/dist/constants-Z9iTGlVY.mjs +2 -0
- package/dist/{dist-Dub-ig7i.mjs → dist-CD7iLv1c.mjs} +20 -20
- package/dist/{dist-BVj_KrOm.mjs → dist-D0fMk7yr.mjs} +1 -1
- package/dist/{gh-detect-DSpFEO46.mjs → gh-detect-Bc-KSyh6.mjs} +2 -2
- package/dist/index.d.mts +4 -3
- package/dist/index.mjs +1 -1
- package/dist/init-79Qb-xiL.mjs +1 -0
- package/dist/{init-BtskSwnA.mjs → init-Ci768cUc.mjs} +8 -8
- package/dist/{loader-BTCOlsDj.mjs → loader-CUdbH5wE.mjs} +2 -2
- package/dist/loader-Hx3ppSIp.mjs +1 -0
- package/dist/preview-CmJ-n5_k.mjs +1 -0
- package/dist/{preview-QT2ENrpW.mjs → preview-Ty-nKYZm.mjs} +2 -2
- package/dist/{repair-launch-json-Ci_j-i_T.mjs → repair-launch-json-Bvn_t98K.mjs} +2 -2
- package/dist/{repair-mcp-configs-DVTatP1p.mjs → repair-mcp-configs-TvlevgIB.mjs} +2 -2
- package/dist/repair-skills-Bv8iL5x_.mjs +1 -0
- package/dist/repair-skills-v6Mlols4.mjs +3 -0
- package/dist/{src-D6ofvaU_.mjs → src-BDsw_Ypd.mjs} +3 -3
- package/dist/{start-an3G7EhI.mjs → start-6yv8Ce7C.mjs} +2 -2
- package/dist/start-B5ydqSJZ.mjs +1 -0
- package/dist/write-project-skill-Pt6mb0Oq.mjs +36 -0
- package/package.json +1 -1
- package/dist/constants-B7J2lQgj.mjs +0 -2
- package/dist/init-D9TQvDdj.mjs +0 -1
- package/dist/loader-DFKzDb0I.mjs +0 -1
- package/dist/preview-VkwB6YTL.mjs +0 -1
- package/dist/repair-skills-BgmvshxL.mjs +0 -1
- package/dist/repair-skills-CAbhMzu9.mjs +0 -3
- package/dist/start-D1SMidps.mjs +0 -1
- package/dist/write-project-skill-k_Wu1Uka.mjs +0 -36
|
@@ -779,13 +779,13 @@ caused by: `+S(E,t)):w},w=e=>S(e,new Set),E=(e,t,S)=>{if(!s(e))return``;let w=S?
|
|
|
779
779
|
`).filter(e=>e.length>0)}catch{return 0}let g=[],S={server:0,"human-":0,upstream:0};for(let e of s){let t=e.split(`/`);if(t.length<4)continue;let s=t.slice(3).join(`/`);parseWriterId(s).classification===`unknown`&&(s===`server`?(g.push(e),S.server++):s.startsWith(`human-`)?(g.push(e),S[`human-`]++):s===`upstream`&&(g.push(e),S.upstream++))}if(g.length===0)return 0;for(let e of g)try{await t.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[shadow-migration] failed to delete legacy ref ${e}:`,t)}let w=g.length;return incrementShadowMigrationLegacyRefsDeleted(w),console.warn(`[shadow-migration] deleted ${w} legacy refs: server=${S.server} human-=${S[`human-`]} upstream=${S.upstream}`),w}async function commitWip(e,t,s,g,S=`main`,w){return withSpan(`shadow.commitWip`,{attributes:{"shadow.writer":t.id,"shadow.branch":S}},async()=>commitWipInner(e,t,s,g,S,w?.date))}async function commitWipInner(e,t,s,g,S=`main`,w){let E=resolve(e.gitDir,`index-wip-${t.id}`),D=`refs/wip/${S}/${t.id}`,O=shadowGit(e),k=s||`.`;try{try{let t=(await O.raw(`rev-parse`,`${D}^{tree}`)).trim();await O.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`read-tree`,t)}catch(e){let t=e instanceof Error?e.message:String(e);if(!(t.includes(`unknown revision`)||t.includes(`bad revision`)))throw console.error(`[shadow-repo] Unexpected error seeding index for ${D}:`,e),e}await O.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:E}).raw(`add`,k);let s=(await O.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`write-tree`)).trim(),S=null;try{S=(await O.raw(`rev-parse`,D)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${D}:`,e),e}let j=[`commit-tree`,s,`-m`,g];S&&j.push(`-p`,S);let F={GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`};w&&(F.GIT_AUTHOR_DATE=w,F.GIT_COMMITTER_DATE=w);let L=(await O.env(F).raw(...j)).trim();return await O.raw(`update-ref`,D,L),L}finally{try{rmSync(E)}catch{}}}function sweepOrphanedTmpIndexFiles(e){let t=0;try{for(let s of readdirSync(e.gitDir))if(s.startsWith(`index-wip-fanout-`))try{rmSync(resolve(e.gitDir,s)),t++}catch{}}catch{}return t}async function buildWipTree(e,t){let s=resolve(e.gitDir,`index-wip-fanout-${randomUUID()}`),g=shadowGit(e),S=t||`.`;try{return await g.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:s}).raw(`add`,S),(await g.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:s}).raw(`write-tree`)).trim()}finally{try{rmSync(s)}catch{}}}async function commitWipFromTree(e,t,s,g,S=`main`){return withSpan(`shadow.commitWipFromTree`,{attributes:{"shadow.writer":t.id,"shadow.branch":S,"shadow.tree":s.slice(0,8)}},async()=>commitWipFromTreeInner(e,t,s,g,S))}async function commitWipFromTreeInner(e,t,s,g,S=`main`){let w=`refs/wip/${S}/${t.id}`,E=shadowGit(e),D=null;try{D=(await E.raw(`rev-parse`,w)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${w}:`,e),e}let O=[`commit-tree`,s,`-m`,g];D&&O.push(`-p`,D);let k=(await E.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...O)).trim();return await E.raw(`update-ref`,w,k),k}const FILE_SYSTEM_WRITER={id:`file-system`,name:`File System`,email:`file-system@openknowledge.local`},GIT_UPSTREAM_WRITER={id:`git-upstream`,name:`Git (upstream)`,email:`git@openknowledge.local`},SERVICE_WRITER={id:`openknowledge-service`,name:`OpenKnowledge (service)`,email:`service@openknowledge.local`},UPSTREAM_WRITER=GIT_UPSTREAM_WRITER;async function commitUpstreamImport(e,t,s,g,S=`main`){return withSpan(`shadow.commitUpstreamImport`,{attributes:{"shadow.branch":S,"shadow.new_head":g.slice(0,8)}},async()=>commitUpstreamImportInner(e,t,s,g,S))}async function commitUpstreamImportInner(e,t,s,g,S=`main`){return commitWip(e,UPSTREAM_WRITER,t,`${formatImportSubject(s,g)}\n\n${formatOkActor({v:1,writer_id:UPSTREAM_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:UPSTREAM_WRITER.name,color_seed:UPSTREAM_WRITER.id,docs:[]})}`,S)}const SAFETY_WRITER=SERVICE_WRITER;async function safetyCheckpoint(e,t,s,g=`main`){return commitWip(e,SAFETY_WRITER,t,`${formatCheckpointSubject(`pre-${s.action}`)}\n\n${formatOkActor({v:1,writer_id:SAFETY_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SAFETY_WRITER.name,color_seed:SAFETY_WRITER.id,docs:[]})}`,g)}async function saveInMemoryCheckpoint(e,t,s){let g=s.branch??`main`,S=shadowGit(e),w=randomUUID(),E=resolve(e.gitDir,`index-checkpoint-${w}`),D=resolve(e.gitDir,`tmp-checkpoint-blob-${w}`),O=t?`${t.replace(/\/$/,``)}/${s.docName}`:s.docName,k=Buffer.byteLength(s.contents,`utf-8`),j;switch(s.kind){case`bridge-merge-loss`:j={kind:`bridge-merge-loss`,docName:s.docName,size:k,metadata:s.metadata};break;case`producer-guard-loss`:j={kind:`producer-guard-loss`,docName:s.docName,size:k,metadata:s.metadata};break;case`external-change-rescue`:j={kind:`external-change-rescue`,docName:s.docName,size:k,metadata:s.metadata};break}let F=formatCheckpointBodyLine(j),L=`checkpoint: ${s.label}\n\n${F}`;try{tracedWriteFileSync(D,s.contents,`utf-8`);let t=(await S.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`hash-object`,`-w`,D)).trim();await S.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${t},${O}`);let w=(await S.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`write-tree`)).trim(),k=(await S.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(`commit-tree`,w,`-m`,L)).trim();return await S.raw(`update-ref`,`refs/checkpoints/${g}/${k}`,k),k}finally{try{rmSync(E)}catch{}try{rmSync(D)}catch{}}}async function listRescueCheckpoints(e,t=`main`){let s=shadowGit(e),g;try{g=await s.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch{return[]}let S=g.trim().split(`
|
|
780
780
|
`).filter(e=>e.length===40);if(S.length===0)return[];let w;try{w=await s.raw(`log`,`--no-walk`,`--author-date-order`,`--format=%H%x00%aI%x00%s%x00%B%x1e`,...S)}catch{return[]}let E=[];for(let e of w.split(``)){let t=e.trimStart();if(!t)continue;let[g=``,S=``,w=``,D=``]=t.split(`\0`),O=parseCheckpoint(D);if(O?.kind!==`external-change-rescue`)continue;let k=O.docName??``,j=O.size??0;if(!k)try{let e=(await listTreeLongEntries(s,[`ls-tree`,`-r`,`--long`,g]))[0];e&&(j===0&&(j=e.size),k=e.path.replace(/\.mdx?$/,``).split(`/`).slice(-1)[0]??``)}catch{}k&&E.push({docName:k,timestamp:S,size:j,sha:g,label:w.replace(/^checkpoint:\s*/,``),incomingDiskSha:O.metadata.incomingDiskSha})}return E}const DEFAULT_CHECKPOINT_RETENTION={maxBridgeMergeLoss:50,maxProducerGuardLoss:50,maxExternalChangeRescue:50,maxAutoConsolidation:2,ttlMs:720*60*60*1e3};async function gcCheckpointRefs(e,t=`main`,s=DEFAULT_CHECKPOINT_RETENTION){let g={scanned:0,deletedBridgeMergeLoss:0,deletedProducerGuardLoss:0,deletedExternalChangeRescue:0,deletedAutoConsolidation:0,retained:0},S=shadowGit(e),w;try{w=await S.raw(`for-each-ref`,`--format=%(objectname) %(refname)`,`refs/checkpoints/${t}/`)}catch{return g}let E=w.trim().split(`
|
|
781
781
|
`).map(e=>e.trim()).filter(Boolean);if(E.length===0)return g;let D=new Map,O=[];for(let e of E){let t=e.indexOf(` `);if(t<0)continue;let s=e.slice(0,t),g=e.slice(t+1);s.length===40&&(D.set(s,g),O.push(s))}if(g.scanned=O.length,O.length===0)return g;let k;try{k=await S.raw(`log`,`--no-walk`,`--author-date-order`,`--format=%H%x00%aI%x00%B%x1e`,...O)}catch{return g}let j=[];for(let e of k.split(``)){let t=e.trimStart();if(!t)continue;let[s=``,g=``,S=``]=t.split(`\0`);if(!s)continue;let w=parseCheckpoint(S)?.kind??null,E=Date.parse(g);j.push({sha:s,timestamp:Number.isFinite(E)?E:0,kind:w})}let F={"bridge-merge-loss":[],"producer-guard-loss":[],"external-change-rescue":[],"auto-consolidation":[]},L=0;for(let e of j){if(e.kind===null){L++;continue}F[e.kind].push(e)}let B=Date.now(),H=[],q=(e,t,S,w=!0)=>{e.sort((e,t)=>t.timestamp-e.timestamp);for(let E=0;E<e.length;E++){let O=e[E];if(!O)continue;let k=E>=t,j=w&&s.ttlMs>0&&O.timestamp>0&&B-O.timestamp>s.ttlMs;if(k||j){let e=D.get(O.sha);e&&(H.push(e),g[S]++)}}};q(F[`bridge-merge-loss`],s.maxBridgeMergeLoss,`deletedBridgeMergeLoss`),q(F[`producer-guard-loss`],s.maxProducerGuardLoss,`deletedProducerGuardLoss`),q(F[`external-change-rescue`],s.maxExternalChangeRescue,`deletedExternalChangeRescue`),q(F[`auto-consolidation`],s.maxAutoConsolidation,`deletedAutoConsolidation`,!1);for(let e of H)try{await S.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[checkpoint-gc] failed to delete`,e,t)}return g.retained=L+(g.scanned-H.length-L),g}async function parkBranch(e,t,s,g,S){return g.length===0?null:withSpan(`shadow.parkBranch`,{attributes:{"shadow.branch":t,"shadow.new_branch":S??``,"shadow.doc_count":g.length}},async()=>parkBranchInner(e,t,s,g,S))}async function parkBranchInner(e,t,s,g,S){let w=shadowGit(e),E=resolve(e.gitDir,`index-park-${t.replace(/\//g,`-`)}`),D=`refs/wip/${t}/${s}`,O=resolve(e.gitDir,`tmp-park-blob`);try{for(let t of g){tracedWriteFileSync(O,t.markdown,`utf-8`);let s=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`hash-object`,`-w`,O)).trim();await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${s},${t.docName}`),tracedWriteFileSync(O,t.diskSnapshot,`utf-8`);let g=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`hash-object`,`-w`,O)).trim();await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${g},.park-base/${t.docName}`)}let s=(await w.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:E}).raw(`write-tree`)).trim(),k=null;try{k=(await w.raw(`rev-parse`,D)).trim()}catch{}let j={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:g.map(e=>e.docName)},F=[`commit-tree`,s,`-m`,`${formatParkSubject(t,S??t)}\n\n${formatOkActor(j)}`];k&&F.push(`-p`,k);let L=(await w.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...F)).trim();return await w.raw(`update-ref`,D,L),L}finally{try{rmSync(E)}catch{}try{rmSync(O)}catch{}}}async function readParkedState(e,t,s,g){let S=shadowGit(e),w=`refs/wip/${t}/${s}`,E;try{E=(await S.raw(`rev-parse`,w)).trim()}catch{return null}try{return(await S.raw(`log`,`-1`,`--format=%s`,E)).trim().startsWith(`park:`)?{markdown:(await S.raw(`show`,`${E}:${g}`)).trim(),diskSnapshot:(await S.raw(`show`,`${E}:.park-base/${g}`)).trim()}:null}catch(e){throw console.error(`[shadow] Failed to read parked state for ${g} from ${w}:`,e),e}}async function saveVersion(e,t,s,g=`main`,S,w){return withSpan(`shadow.saveVersion`,{attributes:{"shadow.branch":g,"shadow.writer_count":s.length,"shadow.checkpoint_kind":w?.checkpointKind?`auto-consolidation`:`user`}},async()=>saveVersionInner(e,t,s,g,S,w))}async function saveVersionInner(e,t,s,g=`main`,S,w){let E=shadowGit(e,w?.timeoutMs?{timeoutMs:w.timeoutMs}:void 0),D=t||`.`,O=resolve(e.gitDir,`index-checkpoint-${randomUUID()}`);try{await E.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:O}).raw(`add`,D);let t=(await E.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:O}).raw(`write-tree`)).trim(),k=w?.includeUpstream===!1?s:[...s,GIT_UPSTREAM_WRITER],j=[],F=new Map;for(let e of k)try{let t=(await E.raw(`rev-parse`,`refs/wip/${g}/${e.id}`)).trim();j.push(t),F.set(e.id,t)}catch{}let L=[...new Set(j)];try{let e=(await E.raw(`for-each-ref`,`--sort=-creatordate`,`--count=1`,`--format=%(objectname)`,`refs/checkpoints/${g}/`)).trim();e&&!L.includes(e)&&L.push(e)}catch{}let B={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},H=`${formatCheckpointSubject(S?.trim()?S.trim():`Checkpoint version`)}\n\n${formatOkActor(B)}`;w?.checkpointKind&&(H+=`\n${formatCheckpointBodyLine({kind:`auto-consolidation`,docName:null,size:null,metadata:{foldedRefs:w.checkpointKind.foldedRefs,trigger:w.checkpointKind.trigger}})}`);let q=[`commit-tree`,t,`-m`,H];for(let e of L)q.push(`-p`,e);let ee={GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`};w?.date&&(ee.GIT_AUTHOR_DATE=w.date,ee.GIT_COMMITTER_DATE=w.date);let J=(await E.env(ee).raw(...q)).trim(),Y=`refs/checkpoints/${g}/${J}`;return await E.raw(`update-ref`,Y,J),await resetFoldedWipRefs(E,g,k,F),{checkpointRef:Y}}finally{try{rmSync(O)}catch{}}}async function resetFoldedWipRefs(e,t,s,g){for(let S of s){let s=`refs/wip/${t}/${S.id}`,w=g.get(S.id);if(w!==void 0)try{await e.raw(`update-ref`,`-d`,s,w)}catch{}}}const FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function applyDiskContentToDoc(e,t,s,g,S){composeAndWriteRawBody(e,t,`file-watcher`,s&&g?{resolveEmbed:s,resolveSize:S,sourcePath:g}:void 0)}function applyExternalChange(e,t,s,g,S){if(isSystemDoc(t)||isConfigDoc(t))return;let w=e.documents.get(t);if(!w)return;let E=w.getText(`source`).toString(),D=E===s,O=stripFrontmatter(E).frontmatter,{frontmatter:k}=stripFrontmatter(s);try{w.transact(()=>{applyDiskContentToDoc(w,s,g,t,S)},FILE_WATCHER_ORIGIN)}catch(e){throw setReconciledBase(t,w.getText(`source`).toString()),e}O!==k&&recordFrontmatterEditSurface(`file-watcher`),D||recordContributor(t,FILE_SYSTEM_WRITER.id,FILE_SYSTEM_WRITER.name,FILE_SYSTEM_WRITER.id,formatReconcileSubject(t)),setReconciledBase(t,s)}function createExternalChangeHandler(e,t,s){return async(g,S)=>{try{applyExternalChange(e,g,S,t,s),getLogger(`file-watcher`).info({docName:g},`applied external change`)}catch(e){if(e instanceof BridgeInvariantViolationError||e instanceof BridgeMergeContentLossError)throw e;incrementExternalChangeHandlerErrors(),console.error(`[file-watcher] Failed to apply external change for ${g}:`,e)}}}const NOT_RECONCILED={reconciled:!1,baseBytes:0,diskBytes:0};function serializeYDocSource(e){let{frontmatter:t,body:s}=stripFrontmatter(e.getText(`source`).toString());return prependFrontmatter(t,s)}function reconcileDiskBeforeAgentWrite(e,t,s,g){if(isSystemDoc(t)||isConfigDoc(t))return NOT_RECONCILED;let S=e.documents.get(t);if(S&&isDocInConflict(S))return NOT_RECONCILED;let w=getReconciledBase(t);if(w===void 0)return NOT_RECONCILED;let E;try{let e=safeContentPath(t,s);if(!existsSync(e))return NOT_RECONCILED;E=realpathSync(e)}catch{return NOT_RECONCILED}if(!isWithinContentDir(E,s))return getLogger(`reconcile`).warn({docName:t,canonical:E,contentDir:s},`[reconcile] symlink-escape on disk read for ${t}; skipping reconcile`),NOT_RECONCILED;let D;try{D=readFileSync(E,`utf-8`)}catch(e){let s=e?.code;return s!==`ENOENT`&&getLogger(`reconcile`).warn({docName:t,canonical:E,code:s},`[reconcile] disk read failed for ${t} (${s??`unknown`}); skipping reconcile`),NOT_RECONCILED}if(normalizeBridge(D)===normalizeBridge(w))return NOT_RECONCILED;let O=peekInFlightFlush(t);if(O!==void 0){if(normalizeBridge(D)===O)return incrementReconcileOwnFlushSkips(),getLogger(`reconcile`).debug({docName:t,diskBytes:D.length},`[reconcile] disk matches own in-flight flush for ${t}; skipping reconcile`),NOT_RECONCILED;incrementReconcileInFlightFallthroughs(),getLogger(`reconcile`).warn({docName:t,diskBytes:D.length},`[reconcile] in-flight flush present but disk differs from snapshot for ${t}; falling through to merge`)}if(!S)return NOT_RECONCILED;let k=reconcile({docName:t,base:w,ours:serializeYDocSource(S),theirs:D});switch(getLogger(`reconcile`).info({docName:t,result:k.kind,baseBytes:w.length,diskBytes:D.length},`[reconcile] before-agent-write ${t} result=${k.kind}`),k.kind){case`noop`:return NOT_RECONCILED;case`conflicts`:case`refused`:{let e=S.getMap(`lifecycle`);return e.set(`status`,`conflict`),e.set(`reason`,k.kind===`refused`?k.reason:`reconcile-conflicts`),NOT_RECONCILED}case`clean`:case`merged`:return applyExternalChange(e,t,k.kind===`clean`?D:k.newContent,g),k.kind===`merged`&&setReconciledBase(t,D),{reconciled:!0,baseBytes:Buffer.byteLength(w,`utf8`),diskBytes:Buffer.byteLength(D,`utf8`),mergeOutcome:k.kind}}}function splitFrontmatterLines(e){return e?unwrapFrontmatterFences(e).split(/\r?\n/):[]}function normalizeFrontmatterScalar(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function extractFrontmatterScalar(e,t){let s=`${t}:`;for(let t of splitFrontmatterLines(e))if(t.startsWith(s))return normalizeFrontmatterScalar(t.slice(s.length))||null;return null}function parseInlineAliases(e){let t=[],s=``,g=null;for(let S of e){if(g){s+=S,S===g&&(g=null);continue}if(S===`"`||S===`'`){g=S,s+=S;continue}if(S===`,`){let e=normalizeFrontmatterScalar(s);e&&t.push(e),s=``;continue}s+=S}let S=normalizeFrontmatterScalar(s);return S&&t.push(S),t}function dedupeExact(e){let t=[],s=new Set;for(let g of e)!g||s.has(g)||(s.add(g),t.push(g));return t}function extractPageAliases(e){let{frontmatter:t}=stripFrontmatter(e);if(!t)return[];let s=splitFrontmatterLines(t);for(let e=0;e<s.length;e+=1){let t=s[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let g=t[1]?.trim()??``;if(g){if(g.startsWith(`[`)&&g.endsWith(`]`))return dedupeExact(parseInlineAliases(g.slice(1,-1)));let e=normalizeFrontmatterScalar(g);return e?[e]:[]}let S=[];for(let t=e+1;t<s.length;t+=1){let e=s[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&S.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return dedupeExact(S)}return[]}function extractPageTitle(e,t){let{frontmatter:s,body:g}=stripFrontmatter(e),S=extractFrontmatterScalar(s,`title`);if(S)return S;let w=g.match(/^# (.+)$/m);return w?w[1].trim():t}const ICON_VALUE_LENGTH_CAP=2048;function extractPageIcon(e){let{frontmatter:t}=stripFrontmatter(e),s=extractFrontmatterScalar(t,`icon`);if(!(!s||s.length>ICON_VALUE_LENGTH_CAP))return s}function parseFrontmatterMetadata(e){return e?.trim()?{cluster:extractFrontmatterScalar(e,`cluster`)??void 0,category:extractFrontmatterScalar(e,`category`)??void 0,tags:extractFrontmatterArray(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function extractFrontmatterArray(e,t){let s=`${t}:`,g=splitFrontmatterLines(e);for(let e=0;e<g.length;e+=1){let t=g[e];if(!t?.startsWith(s))continue;let S=t.slice(s.length).trim();if(S){if(S.startsWith(`[`)&&S.endsWith(`]`)){let e=parseInlineAliases(S.slice(1,-1));return e.length>0?e:void 0}let e=normalizeFrontmatterScalar(S);return e?[e]:void 0}let w=[];for(let t=e+1;t<g.length;t+=1){let e=g[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&w.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return w.length>0?w:void 0}}function extractPageIdentity(e,t){let s=extractPageTitle(e,t),g=extractPageAliases(e),S=dedupeExact([s,...g]),w=[],E=new Set;for(let e of S){let t=toWikiLinkSlug(e);!t||E.has(t)||(E.add(t),w.push(t))}return{docName:t,title:s,aliases:g,matchLabels:S,normalizedMatchLabels:w}}function toPosix(e){return e.replace(/\\/g,`/`)}function isWithinDir(e,t){let s=toPosix(e),g=toPosix(t);return s===g||s.startsWith(`${g}/`)}function assertNeverDiskEvent(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}function derivePageMeta(e,t){return{title:extractPageTitle(e,t),icon:extractPageIcon(e)}}function markdownIndexView(e){let t=new Map;for(let[s,g]of e)g.kind===`markdown`&&t.set(s,g);return t}const writeTracker=new Map,WRITE_TRACKER_TTL_MS=1e4;function registerWrite(e,t){let s=writeTracker.get(e)??[];s.push({hash:t,timestamp:Date.now()}),writeTracker.set(e,s)}function evictStaleTrackerEntries(){let e=Date.now();for(let[t,s]of writeTracker){let g=s.filter(t=>e-t.timestamp<=WRITE_TRACKER_TTL_MS);g.length===0?writeTracker.delete(t):g.length!==s.length&&writeTracker.set(t,g)}}function contentHash(e){return createHash(`sha256`).update(e).digest(`hex`)}function eventEscapesContentDir(e,t){let s;try{s=lstatSync(e)}catch(t){let s=t.code;return s===`ENOENT`?!1:(console.warn(`[file-watcher] lstat failed for escape check on ${e} (${s}), dropping event`),!0)}if(!s.isSymbolicLink())return!1;let g;try{g=realpathSync(e)}catch(t){let s=t.code;return s!==`ENOENT`&&s!==`ELOOP`&&console.warn(`[file-watcher] realpath failed for escape check on ${e} (${s}), dropping event`),!0}return!isWithinContentDir(g,t)}function pathToDocName(e,t){return stripDocExtension(toPosix(relative(t,e)))}function contentRelativePath(e,t){let s=relative(e,t).replaceAll(`\\`,`/`);return!s||s===`.`||s===`..`||s.startsWith(`../`)?null:s}function upsertFolderIndexEntry(e,t,s,g,S=s){let w=contentRelativePath(t,s);return w?(e.set(w,{size:0,modified:g.mtime.toISOString(),canonicalPath:S,inode:Number(g.ino)}),w):null}function removeFolderIndexEntries(e,t){let s=!1;for(let g of e.keys())(g===t||g.startsWith(`${t}/`))&&(e.delete(g),s=!0);return s}function extractDocExtension(e){let t=extname(e);if(t===``)return null;let s=t.toLowerCase();return s===`.mdx`||s===`.md`?t:null}const lastKnownHash=new Map;function updateLastKnownHash(e,t){lastKnownHash.set(e,t)}function removeLastKnownHash(e){let t=lastKnownHash.get(e);return lastKnownHash.delete(e),t}async function classifyEvents(e,t,s,g){let S=[],w=[],E=[];for(let g of e)if(isSupportedDocFile(g.path)){if(s){let e=toPosix(relative(t,g.path));if(s.isExcluded(e))continue}switch(g.type){case`delete`:S.push(g);break;case`create`:lastKnownHash.has(g.path)?E.push(g):w.push(g);break;case`update`:E.push(g);break}}let D=new Map,O=new Map;for(let e of w)try{D.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of E)try{O.set(e.path,await readFile$1(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function k(e){let s=pathToDocName(e,t);if(!g)return s;let S=null;try{S=lstatSync(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),g.has(s)&&g.delete(s),s}if(!S.isSymbolicLink())return g.has(s)&&g.delete(s),s;let w;try{w=realpathSync(e)}catch(t){let S=t.code;return S!==`ENOENT`&&S!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),g.delete(s),s}if(!isWithinContentDir(w,t))return g.delete(s),s;let E=pathToDocName(w,t);return E===s?s:(g.set(s,E),E)}let j=[],F=new Set,L=new Set;for(let e of S){let t=removeLastKnownHash(e.path);if(t)for(let s of w){if(F.has(s.path))continue;let g=D.get(s.path);if(g===void 0)continue;let S=contentHash(g);if(S===t){F.add(s.path),L.add(e.path),updateLastKnownHash(s.path,S),j.push({kind:`rename`,oldPath:e.path,newPath:s.path,oldDocName:k(e.path),newDocName:k(s.path),content:g});break}}}for(let e of S)L.has(e.path)||(removeLastKnownHash(e.path),j.push({kind:`delete`,path:e.path,docName:k(e.path)}));for(let e of w){if(F.has(e.path))continue;let t=D.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`create`,path:e.path,docName:k(e.path),content:t})}for(let e of E){let t=O.get(e.path);if(t===void 0)continue;let s=contentHash(t);updateLastKnownHash(e.path,s),containsConflictMarkers(t)?j.push({kind:`conflict`,path:e.path,docName:k(e.path),content:t}):j.push({kind:`update`,path:e.path,docName:k(e.path),content:t})}return j}function isSelfWrite(e,t){let s=writeTracker.get(e);if(!s)return!1;let g=s.findIndex(e=>e.hash===t);return g<0?!1:(s.splice(g,1),s.length===0&&writeTracker.delete(e),!0)}async function seedLastKnownHashes(e,t,s,g,S,w,E,D){let O=D??new Set;try{let D=await readdir(e,{withFileTypes:!0});for(let k of D){let D=join(e,k.name),j;try{j=await lstat(D)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${D}, skipping:`,e);continue}if(j.isSymbolicLink()){let e;try{e=await realpath(D)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${D}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${D}:`,e);continue}if(!isWithinContentDir(e,t)){console.warn(`[file-watcher] Symlink escape: ${D} → ${e}, skipping`);continue}try{let j=await stat$1(e);if(O.has(j.ino)){if(j.isFile()&&isSupportedDocFile(k.name)){let s=pathToDocName(D,t),S=pathToDocName(e,t);w.set(s,S);let E=g.get(S);E&&!E.aliases.includes(s)&&E.aliases.push(s)}else if(j.isDirectory()){let g=contentRelativePath(t,D);(!s||g&&!s.isDirExcluded(g))&&E.set(pathToDocName(D,t),pathToDocName(e,t))}continue}if(O.add(j.ino),j.isDirectory()){let k=contentRelativePath(t,D);if(s&&(!k||s.isDirExcluded(k)))continue;E.set(pathToDocName(D,t),pathToDocName(e,t)),await seedLastKnownHashes(e,t,s,g,S,w,E,O)}else if(j.isFile()&&isSupportedDocFile(k.name)){if(s){let g=toPosix(relative(t,e));if(s.isExcluded(g))continue}let S=pathToDocName(D,t),E=pathToDocName(e,t);w.set(S,E);try{let t=await readFile$1(e,`utf-8`),s=contentHash(t);lastKnownHash.set(e,s);let w=extractDocExtension(e);if(w){let e=registerDocExtension(E,w);if(e.shadowed&&(console.warn(`[file-watcher] docName "${E}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(E,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:e,inode:j.ino,aliases:[S],kind:`markdown`,...derivePageMeta(t,E)})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}else if(j.isFile()){if(s){let g=toPosix(relative(t,e));if(s.isPathIgnored(g))continue}let S=pathToDocName(D,t);if(isSystemDoc(S)||isConfigDoc(S))continue;g.set(S,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:e,inode:j.ino,aliases:[],kind:`file`})}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(j.isDirectory()){let e=contentRelativePath(t,D);if(s&&(!e||s.isDirExcluded(e)))continue;upsertFolderIndexEntry(S,t,D,j),await seedLastKnownHashes(D,t,s,g,S,w,E,O)}else if(j.isFile()&&isSupportedDocFile(k.name)){if(O.has(j.ino))continue;if(O.add(j.ino),s){let e=toPosix(relative(t,D));if(s.isExcluded(e))continue}try{let e=await readFile$1(D,`utf-8`);lastKnownHash.set(D,contentHash(e));let s=pathToDocName(D,t),S=extractDocExtension(D);if(S){let e=registerDocExtension(s,S);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}g.set(s,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:D,inode:j.ino,aliases:[],kind:`markdown`,...derivePageMeta(e,s)})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${D}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${D}:`,e)}}else if(j.isFile()){if(O.has(j.ino))continue;if(O.add(j.ino),s){let e=toPosix(relative(t,D));if(s.isPathIgnored(e))continue}let e=pathToDocName(D,t);if(isSystemDoc(e)||isConfigDoc(e))continue;g.set(e,{size:j.size,modified:j.mtime.toISOString(),canonicalPath:D,inode:j.ino,aliases:[],kind:`file`})}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function updateFileIndex(e,t){if(!(e.kind===`asset-create`||e.kind===`asset-delete`||e.kind===`folder-create`||e.kind===`folder-delete`)){if(e.kind===`file-create`||e.kind===`file-update`||e.kind===`file-delete`){let s=e.relativePath;if(isSystemDoc(s)||isConfigDoc(s))return;if(e.kind===`file-delete`){let e=t.get(s);e&&e.kind===`file`&&t.delete(s);return}let g=t.get(s);if(g&&g.kind===`markdown`)return;t.set(s,{size:e.size,modified:new Date(e.modifiedTs).toISOString(),canonicalPath:g?.canonicalPath??e.path,inode:e.inode||g?.inode||0,aliases:g?.aliases??[],kind:`file`});return}if(!isReservedForUserTree(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let s=e.docName,g=t.get(s),S=extractDocExtension(e.path);S&®isterDocExtension(s,S),t.set(s,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:g?.canonicalPath??e.path,inode:g?.inode??0,aliases:g?.aliases??[],kind:`markdown`,...derivePageMeta(e.content,s)});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),forgetDocExtension(e.docName);else for(let[,s]of t){let t=s.aliases.indexOf(e.docName);if(t!==-1){s.aliases.splice(t,1);break}}break;case`rename`:{let s=t.get(e.oldDocName);t.delete(e.oldDocName),forgetDocExtension(e.oldDocName);let g=extractDocExtension(e.newPath);g&®isterDocExtension(e.newDocName,g),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:s?.canonicalPath??e.newPath,inode:s?.inode??0,aliases:s?.aliases??[],kind:`markdown`,...derivePageMeta(e.content,e.newDocName)});break}default:assertNeverDiskEvent(e)}}}function updateFolderIndexFromRawEvents(e,t,s,g){let S=[];for(let w of e){let e=contentRelativePath(t,w.path);if(!e)continue;if(w.type===`delete`){removeFolderIndexEntries(g,e)&&S.push({kind:`folder-delete`,path:w.path,relativePath:e});continue}let E;try{E=lstatSync(w.path)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder lstat failed for ${w.path} (${t})`);continue}let D=null,O=w.path;if(E.isDirectory())D=E;else if(E.isSymbolicLink())try{if(O=realpathSync(w.path),!isWithinContentDir(O,t))continue;let e=statSync(O);e.isDirectory()&&(D=e)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder symlink resolve failed for ${w.path} (${t})`),D=null}if(!D||s?.isDirExcluded(e))continue;let k=g.has(e);upsertFolderIndexEntry(g,t,w.path,D,O),k||(S.push({kind:`folder-create`,path:w.path,relativePath:e}),scanForUntrackedSubfolders(O,t,s,g,S))}return S}function scanForUntrackedSubfolders(e,t,s,g,S){let w=[e];for(;w.length>0;){let e=w.shift();if(e===void 0)continue;let E;try{E=readdirSync(e,{withFileTypes:!0})}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] folder rescan readdir failed for ${e} (${s})`);continue}for(let D of E){if(!D.isDirectory())continue;let E=join(e,D.name),O=contentRelativePath(t,E);if(!O||s?.isDirExcluded(O))continue;let k;try{k=lstatSync(E)}catch(e){let t=e.code;t!==`ENOENT`&&console.warn(`[file-watcher] folder rescan lstat failed for ${E} (${t})`);continue}k.isDirectory()&&(g.has(O)||(upsertFolderIndexEntry(g,t,E,k),S.push({kind:`folder-create`,path:E,relativePath:O})),w.push(E))}}}async function handleRawEvents(e,t,s,g,S,w,E){let D=e.filter(e=>eventEscapesContentDir(e.path,t)?(console.warn(`[file-watcher] Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),O=D.filter(e=>isSupportedDocFile(e.path)),k=D.filter(e=>isSupportedAssetFile(e.path,LINKABLE_ASSET_EXTENSIONS)),j=D.filter(e=>!isSupportedDocFile(e.path)),F=updateFolderIndexFromRawEvents(D,t,s,S);if(O.length===0&&k.length===0&&F.length===0&&j.length===0)return;let L=O.length>0?await classifyEvents(O,t,s,E):[];for(let e of L){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let s=contentHash(e.content),g=e.path;try{g=realpathSync(e.path)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${s})`)}t=isSelfWrite(g,s)}else if(e.kind===`rename`){let s=contentHash(e.content),g=e.newPath;try{g=realpathSync(e.newPath)}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${s})`)}t=isSelfWrite(g,s)}if(updateFileIndex(e,g),s&&!t)switch(e.kind){case`create`:s.incrementMdDir(dirname(e.docName));break;case`delete`:s.decrementMdDir(dirname(e.docName));break;case`rename`:s.decrementMdDir(dirname(e.oldDocName)),s.incrementMdDir(dirname(e.newDocName));break;case`update`:case`conflict`:break;default:assertNeverDiskEvent(e)}if(t){getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!0});continue}getLogger(`file-watcher`).debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1});let S=e.kind===`rename`?e.newPath:e.path;await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(S),"disk.path.role":classifyFsPath(S)}},async()=>w(e))}for(let e of F)getLogger(`file-watcher`).debug({kind:e.kind,path:e.path},`[file-watcher] Dispatching: ${e.kind}`),_fileWatcherEventsCounter().add(1,{"disk.kind":e.kind,self:!1}),await withSpan(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":normalizeFsPath(e.path),"disk.path.role":classifyFsPath(e.path)}},async()=>w(e));for(let e of k){if(s){let g=toPosix(relative(t,e.path));if(s.isExcluded(g))continue}let g=toPosix(relative(t,e.path));await w(e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:g}:{kind:`asset-create`,path:e.path,relativePath:g})}for(let e of j){let S=toPosix(relative(t,e.path));if(s?.isPathIgnored(S)||isSystemDoc(S)||isConfigDoc(S))continue;if(e.type===`delete`){let t={kind:`file-delete`,path:e.path,relativePath:S};updateFileIndex(t,g),await w(t);continue}let E;try{E=lstatSync(e.path),E.isSymbolicLink()&&(E=statSync(e.path))}catch(t){let s=t.code;s!==`ENOENT`&&console.warn(`[file-watcher] file-event lstat failed for ${e.path} (${s})`);continue}if(!E.isFile())continue;let D=e.type===`create`?{kind:`file-create`,path:e.path,relativePath:S,size:E.size,modifiedTs:E.mtime.getTime(),inode:Number(E.ino)}:{kind:`file-update`,path:e.path,relativePath:S,size:E.size,modifiedTs:E.mtime.getTime(),inode:Number(E.ino)};updateFileIndex(D,g),await w(D)}}let _fwEventsCounterCache=null;function _fileWatcherEventsCounter(){return _fwEventsCounterCache||=getMeter().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),_fwEventsCounterCache}async function startParcelWatcher(e,t,s,g,S,w,E){let D;try{D=await import(`@parcel/watcher`)}catch(e){return getLogger(`file-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[file-watcher] @parcel/watcher import failed; falling back to chokidar`),null}try{let O=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await D.subscribe(e,async(D,O)=>{if(D){console.error(`[file-watcher]`,D);return}try{await handleRawEvents(O.map(e=>({type:e.type,path:e.path})),e,t,s,g,S,w),E()}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},O)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function startChokidarWatcher(e,t,s,g,S,w,E){let{watch:D}=await import(`./chokidar-D1eNAlbX.mjs`),O=D(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(s,g)=>{let S=toPosix(relative(e,s));return S===``||S===`.`?!1:g?.isDirectory()?t.isDirExcluded(S):t.isExcluded(S)}:void 0});O.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let k=50,j=[],F=null;function L(D,O){j.push({type:D,path:O}),F||=setTimeout(()=>{let D=j;j=[],F=null,handleRawEvents(D,e,t,s,g,S,w).then(E).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return O.on(`add`,e=>L(`create`,e)),O.on(`change`,e=>L(`update`,e)),O.on(`unlink`,e=>L(`delete`,e)),O.on(`addDir`,e=>L(`create`,e)),O.on(`unlinkDir`,e=>L(`delete`,e)),{unsubscribe:()=>(F&&(clearTimeout(F),F=null,j=[]),O.close())}}async function startWatcher(e,t,s){let g;try{g=realpathSync(e)}catch{g=e}let S=new Map,w=new Map,E=new Map,D=new Map,O=0,k=null,j=-1,F=()=>{O++};await seedLastKnownHashes(g,g,s,S,w,E,D),F();let L=setInterval(evictStaleTrackerEntries,WRITE_TRACKER_TTL_MS),B,H;try{let e=await startParcelWatcher(g,s,S,w,t,E,F);e?(B=e,H=`parcel`):(B=await startChokidarWatcher(g,s,S,w,t,E,F),H=`chokidar`)}catch(e){throw clearInterval(L),e}let q=B.unsubscribe.bind(B);return getLogger(`file-watcher`).info({contentDir:g,backend:H},`watching for external .md changes`),{async unsubscribe(){return clearInterval(L),writeTracker.clear(),lastKnownHash.clear(),q()},getFileIndex(){return k&&j===O?k:(k=markdownIndexView(S),j=O,k)},getAllFilesIndex(){return S},getFileIndexGeneration(){return O},getFolderIndex(){return w},getAliasMap(){return E},getFolderAliasIndex(){return D},mutateFileIndex(e){updateFileIndex(e,S),F()},pruneFileIndexNowExcluded(){if(!s)return 0;let e=0;for(let[t,w]of S){let E=toPosix(relative(g,w.canonicalPath));(w.kind===`file`?s.isPathIgnored(E):s.isExcluded(E))&&(S.delete(t),e++)}return e>0&&F(),e},pruneFolderIndexNowExcluded(){if(!s)return 0;let e=0;for(let t of w.keys())s.isDirExcluded(t)&&(w.delete(t),e++);return e},async rescanFromDisk(){await seedLastKnownHashes(g,g,s,S,w,E,D),F()}}}async function reconcileFileIndexAfterFilterRebuild(e){if(!e)return{prunedFiles:0,prunedFolders:0};let t=e.pruneFileIndexNowExcluded(),s=e.pruneFolderIndexNowExcluded();return await e.rescanFromDisk(),{prunedFiles:t,prunedFolders:s}}const log$17=getLogger(`managed-artifact-persistence`);function homeFor(e){return e.homedirOverride??homedir()}function managedArtifactContributorAttribution(e){let t=parseManagedArtifactName(e);if(t===null)return null;if(t.kind===`skill`)return t.scope===`project`?{docKey:`${SKILL_CONTENT_ROOT}/${t.name}`,subject:`skill-edit: ${t.name}/SKILL.md`}:null;let s=t.folder.replace(/\/$/,``),g=`${s?`${s}/`:``}.ok/templates/${t.name}`;return{docKey:g,subject:`template-edit: ${g}.md`}}function managedArtifactTimelinePaths(e){let t=parseManagedArtifactName(e);if(!t)return{managed:!1};let s=managedArtifactContributorAttribution(e);if(!s)return{managed:!0,versioned:!1};let g=t.kind===`skill`?`${s.docKey}/SKILL.md`:`${s.docKey}.md`;return{managed:!0,versioned:!0,docKey:s.docKey,filePath:g}}function managedArtifactSkillsRoots(e){return[resolve(homeFor(e),`.ok`,`skills`)]}function managedArtifactAbsPath(e,t){let s=parseManagedArtifactName(e);if(s===null)throw Error(`managedArtifactAbsPath: not a managed-artifact doc name: ${e}`);if(s.kind===`template`)return templateAbsPath(s.folder,s.name,t,e);if(!SKILL_NAME_REGEX.test(s.name)||s.name.length>64)throw Error(`managedArtifactAbsPath: invalid skill name: ${JSON.stringify(s.name)}`);let g=resolve(s.scope===`global`?homeFor(t):t.projectDir,`.ok`,`skills`),S=resolve(g,s.name,`SKILL.md`);if(!S.startsWith(g+sep))throw Error(`managedArtifactAbsPath: path escape for ${e}`);return S}function normalizeTemplateFolder(e){return e.replace(/^\/+/,``).replace(/\/+$/,``)}function templateAbsPath(e,t,s,g){if(!TEMPLATE_NAME_REGEX.test(t)||t.length>64)throw Error(`managedArtifactAbsPath: invalid template name: ${JSON.stringify(t)}`);let S=normalizeTemplateFolder(e);if(S.split(`/`).includes(`..`))throw Error(`managedArtifactAbsPath: template folder escape for ${g}`);let w=resolve(s.projectDir),E=S?resolve(w,S):w;if(E!==w&&!E.startsWith(w+sep))throw Error(`managedArtifactAbsPath: template folder escape for ${g}`);let D=resolve(E,`.ok`,`templates`),O=resolve(D,`${t}.md`);if(!O.startsWith(D+sep))throw Error(`managedArtifactAbsPath: path escape for ${g}`);return O}function managedArtifactDocNameForPath(e,t){let s=resolve(e);if(s.endsWith(`${sep}SKILL.md`)){let e=[[resolve(homeFor(t),`.ok`,`skills`),`global`]];for(let[t,g]of e){if(!s.startsWith(t+sep))continue;let e=s.slice(t.length+1).split(sep);if(e.length!==2||e[1]!==`SKILL.md`)continue;let S=e[0];if(!(!SKILL_NAME_REGEX.test(S)||S.length>64))return`${MANAGED_ARTIFACT_PREFIX_SKILL}${g}/${S}`}return null}if(s.endsWith(`.md`)){let e=resolve(t.projectDir);if(s!==e&&!s.startsWith(e+sep))return null;let g=s===e?``:s.slice(e.length+1),S=`.ok${sep}templates${sep}`,w=g.indexOf(S);if(w<0||w>0&&g[w-1]!==sep)return null;let E=g.slice(w+S.length);if(E.includes(sep)||!E.endsWith(`.md`))return null;let D=E.slice(0,-3);if(!TEMPLATE_NAME_REGEX.test(D)||D.length>64)return null;let O=w===0?``:g.slice(0,w-1),k=O?O.split(sep).map(e=>encodeURIComponent(e)).join(`/`):``;return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${k?`${k}/`:``}${encodeURIComponent(D)}`}return null}function loadManagedArtifactDoc(e,t,s){let g=parseManagedArtifactName(t);if(g?.kind===`skill`&&g.scope===`project`||e.getXmlFragment(`default`).length>0)return;let S=managedArtifactAbsPath(t,s);if(!existsSync(S))return;let w;try{w=readFileSync(S,`utf-8`)}catch(e){log$17.warn({documentName:t,err:e.message},`load: could not read; seeding empty`);return}e.transact(()=>{applyDiskContentToDoc(e,w,void 0,t),e.getMap(`lifecycle`).set(LINEAGE_EPOCH_KEY,crypto.randomUUID())},FILE_WATCHER_ORIGIN),s.setReconciledBase(t,w),s.lkgCache.set(t,w)}async function storeManagedArtifactDoc(e,t,s,g){let S=parseManagedArtifactName(t);if(S?.kind===`skill`&&S.scope===`project`||s===FILE_WATCHER_ORIGIN)return`no-op`;let w=e.getText(`source`).toString(),E=g.lkgCache.get(t);if(w===E)return`no-op`;let D=managedArtifactAbsPath(t,g);try{return await tracedMkdir(resolve(D,`..`),{recursive:!0}),await withFileLock(`${D}.lock`,async()=>{if(existsSync(D)){let s=null;try{s=readFileSync(D,`utf-8`)}catch(e){e.code!==`ENOENT`&&log$17.warn({documentName:t,err:e.message},`store: pre-write disk read failed (non-ENOENT); proceeding to write`),s=null}if(s!==null&&s!==E&&s!==w)return e.transact(()=>{applyDiskContentToDoc(e,s,void 0,t)},FILE_WATCHER_ORIGIN),g.setReconciledBase(t,s),g.lkgCache.set(t,s),`reconciled`}return await atomicWriteFile(D,w,{fs:tracedAtomicFs}),g.lkgCache.set(t,w),g.setReconciledBase(t,w),`persisted`})}catch(e){return e instanceof FileLockTimeoutError?(log$17.warn({documentName:t},`store: file lock timeout; skipping write`),`write-failed`):(log$17.warn({documentName:t,err:e.message},`store: write failed`),`write-failed`)}}function applyExternalManagedArtifactChange(e,t,s,g){if(!e)return`no-op`;let S=g.lkgCache.get(t);return S!==void 0&&S===s?`no-op`:(e.transact(()=>{applyDiskContentToDoc(e,s,void 0,t)},FILE_WATCHER_ORIGIN),g.setReconciledBase(t,s),g.lkgCache.set(t,s),`applied`)}function normalizeBody(e){let{body:t}=stripFrontmatter(e);return normalizeBridge(t).trim()}function isWhitespace(e){return e===` `||e===`
|
|
782
|
-
`||e===` `||e===`\r`}function classifyDuplication(e,t){let s=normalizeBody(t);if(s.length===0)return{kind:`allow`,reason:`empty-base`};let g=normalizeBody(e);if(g===s)return{kind:`allow`,reason:`identical`};if(g.length<s.length*2)return{kind:`allow`,reason:`too-short`};let S=0,w=0;for(;S<g.length;){if(g.slice(S,S+s.length)!==s)return{kind:`allow`,reason:`not-integer-multiple`};for(S+=s.length,w++;S<g.length&&isWhitespace(g[S]??``);)S++}return w>=2?{kind:`block`,reason:`structural-duplication`,copies:w}:{kind:`allow`,reason:`single-copy`}}let _liveEntriesGauge=null;function liveEntriesGauge(){return _liveEntriesGauge||=getMeter().createUpDownCounter(`rename.log_entries_total`,{description:`Live rename-log entry count after each append / GC pass`}),_liveEntriesGauge}let _gcDroppedCounter=null;function gcDroppedCounter(){return _gcDroppedCounter||=getMeter().createCounter(`rename.log_gc_dropped_total`,{description:`Cumulative count of rename-log entries dropped by reachability GC`}),_gcDroppedCounter}const RENAME_LOG_HARD_CAP_BYTES=5*1024*1024,RENAME_LOG_MAX_LINE_BYTES=4*1024,RENAME_LOG_FILENAME=`renames.jsonl`;function createEmptyIndex(){return{byTo:new Map,byFrom:new Map}}function renameLogPath(e){return resolve(e,RENAME_LOG_FILENAME)}function validateEntry(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||typeof t.from!=`string`||t.from.length===0||typeof t.to!=`string`||t.to.length===0||t.from===t.to||typeof t.at!=`string`||t.at.length===0||typeof t.commitSha!=`string`||t.commitSha!==``&&!/^[0-9a-f]{40}$/.test(t.commitSha)||typeof t.branch!=`string`||t.branch.length===0||typeof t.groupId!=`string`||t.groupId.length===0||t.kind!==`file`&&t.kind!==`folder`||t.actor===null||typeof t.actor!=`object`)return null;let s=t.actor;return typeof s.writerId!=`string`||s.writerId.length===0||typeof s.displayName!=`string`?null:{v:1,from:t.from,to:t.to,at:t.at,commitSha:t.commitSha,branch:t.branch,groupId:t.groupId,kind:t.kind,actor:{writerId:s.writerId,displayName:s.displayName}}}function removeFromByFrom(e,t){let s=e.byFrom.get(t.from);if(!s)return;let g=s.filter(e=>e!==t);g.length===0?e.byFrom.delete(t.from):e.byFrom.set(t.from,g)}function indexRemove(e,t){e.byTo.delete(t.to),removeFromByFrom(e,t)}function indexInsert(e,t){let s=e.byTo.get(t.to);s&&removeFromByFrom(e,s),e.byTo.set(t.to,t);let g=e.byFrom.get(t.from);g?g.push(t):e.byFrom.set(t.from,[t])}function loadRenameLogIndex(e){let t=createEmptyIndex(),s=renameLogPath(e);if(!existsSync(s))return t;let g;try{g=readFileSync(s,`utf-8`)}catch(e){return console.warn(`[rename-log] WARN: failed to read ${s}, treating as empty:`,e),t}if(g.length===0)return t;let S=g.split(`
|
|
782
|
+
`||e===` `||e===`\r`}function classifyDuplication(e,t){let s=normalizeBody(t);if(s.length===0)return{kind:`allow`,reason:`empty-base`};let g=normalizeBody(e);if(g===s)return{kind:`allow`,reason:`identical`};if(g.length<s.length*2)return{kind:`allow`,reason:`too-short`};let S=0,w=0;for(;S<g.length;){if(g.slice(S,S+s.length)!==s)return{kind:`allow`,reason:`not-integer-multiple`};for(S+=s.length,w++;S<g.length&&isWhitespace(g[S]??``);)S++}return w>=2?{kind:`block`,reason:`structural-duplication`,copies:w}:{kind:`allow`,reason:`single-copy`}}function withHiddenWindowsConsole(e){return{...e,windowsHide:!0}}let _liveEntriesGauge=null;function liveEntriesGauge(){return _liveEntriesGauge||=getMeter().createUpDownCounter(`rename.log_entries_total`,{description:`Live rename-log entry count after each append / GC pass`}),_liveEntriesGauge}let _gcDroppedCounter=null;function gcDroppedCounter(){return _gcDroppedCounter||=getMeter().createCounter(`rename.log_gc_dropped_total`,{description:`Cumulative count of rename-log entries dropped by reachability GC`}),_gcDroppedCounter}const RENAME_LOG_HARD_CAP_BYTES=5*1024*1024,RENAME_LOG_MAX_LINE_BYTES=4*1024,RENAME_LOG_FILENAME=`renames.jsonl`;function createEmptyIndex(){return{byTo:new Map,byFrom:new Map}}function renameLogPath(e){return resolve(e,RENAME_LOG_FILENAME)}function validateEntry(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||typeof t.from!=`string`||t.from.length===0||typeof t.to!=`string`||t.to.length===0||t.from===t.to||typeof t.at!=`string`||t.at.length===0||typeof t.commitSha!=`string`||t.commitSha!==``&&!/^[0-9a-f]{40}$/.test(t.commitSha)||typeof t.branch!=`string`||t.branch.length===0||typeof t.groupId!=`string`||t.groupId.length===0||t.kind!==`file`&&t.kind!==`folder`||t.actor===null||typeof t.actor!=`object`)return null;let s=t.actor;return typeof s.writerId!=`string`||s.writerId.length===0||typeof s.displayName!=`string`?null:{v:1,from:t.from,to:t.to,at:t.at,commitSha:t.commitSha,branch:t.branch,groupId:t.groupId,kind:t.kind,actor:{writerId:s.writerId,displayName:s.displayName}}}function removeFromByFrom(e,t){let s=e.byFrom.get(t.from);if(!s)return;let g=s.filter(e=>e!==t);g.length===0?e.byFrom.delete(t.from):e.byFrom.set(t.from,g)}function indexRemove(e,t){e.byTo.delete(t.to),removeFromByFrom(e,t)}function indexInsert(e,t){let s=e.byTo.get(t.to);s&&removeFromByFrom(e,s),e.byTo.set(t.to,t);let g=e.byFrom.get(t.from);g?g.push(t):e.byFrom.set(t.from,[t])}function loadRenameLogIndex(e){let t=createEmptyIndex(),s=renameLogPath(e);if(!existsSync(s))return t;let g;try{g=readFileSync(s,`utf-8`)}catch(e){return console.warn(`[rename-log] WARN: failed to read ${s}, treating as empty:`,e),t}if(g.length===0)return t;let S=g.split(`
|
|
783
783
|
`),w=S[S.length-1];w!==``&&console.warn(`[rename-log] WARN: trailing line missing newline (${w.length} bytes); dropped`);let E=S.slice(0,-1);for(let e=0;e<E.length;e++){let s=E[e];if(s.length===0)continue;let g;try{g=JSON.parse(s)}catch(t){let g=s.slice(0,80),S=t.message;console.warn(`[rename-log] WARN: corrupt entry at line ${e+1} skipped (${S}): ${g}${s.length>80?`…`:``}`);continue}let S=validateEntry(g);if(!S){console.warn(`[rename-log] WARN: corrupt entry at line ${e+1} skipped`);continue}indexInsert(t,S)}return t.byTo.size>0&&liveEntriesGauge().add(t.byTo.size),t}function appendRenameLogEntry(e,t,s,g){let S=validateEntry(t);if(!S)throw Error(`[rename-log] refusing to append malformed entry`);let w=`${JSON.stringify(S)}\n`;if(Buffer.byteLength(w,`utf-8`)>RENAME_LOG_MAX_LINE_BYTES)throw Error(`[rename-log] entry exceeds max line size (${RENAME_LOG_MAX_LINE_BYTES} bytes)`);let E=renameLogPath(e),D=!1;if(existsSync(E))try{let e=statSync(E).size;e>5242880&&(D=!0,console.warn(`[rename-log] WARN: file size ${e} exceeds hard cap ${RENAME_LOG_HARD_CAP_BYTES}; forcing GC sweep`))}catch{}tracedAppendFileSync(E,w,{flag:`a`}),indexInsert(s,S),liveEntriesGauge().add(1),D&&g&&scheduleHardCapGc(g,s)}const gcPending=new Set;function scheduleHardCapGc(e,t){queueMicrotask(()=>{gcRenameLog(e,t).catch(e=>{console.warn(`[rename-log] WARN: hard-cap forced GC failed:`,e)})})}let _moduleIndex=null;function setRenameLogIndex(e,t){_moduleIndex={shadowDir:e,index:t}}function getOrLoadRenameLogIndex(e){if(_moduleIndex&&_moduleIndex.shadowDir===e)return _moduleIndex.index;let t=loadRenameLogIndex(e);return _moduleIndex={shadowDir:e,index:t},t}function serializeIndexToString(e){let t=[];for(let s of e.byTo.values())t.push(JSON.stringify(s));return t.length>0?`${t.join(`
|
|
784
784
|
`)}\n`:``}function parseGitTimeoutMs(){let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4}function expandPredecessors(e,t,s){let g=[],S=new Set,w=e,E=0;for(;;){if(g.length>=100){console.warn(`[rename-log] WARN: predecessor chain depth exceeded 100 while expanding "${e}"; truncating`);break}if(S.has(w)){console.warn(`[rename-log] WARN: cycle detected at "${w}" while expanding predecessors of "${e}"; truncating`);break}S.add(w);let D=s.byTo.get(w);if(!D||D.branch!==t)break;if(D.commitSha===``){E+=1;break}g.push({path:D.from,renameCommit:D.commitSha}),w=D.from}return g.reverse(),g.push({path:e,renameCommit:null}),{chain:g,skipped:E}}function createAncestorShaSetCache(){return new Map}function createSeedsCache(){return new Map}async function buildSeeds(e,t,s,g){return withSpan(`rename.buildSeeds`,void 0,async S=>{if(g){let e=g.get(`${s}:${t}`);if(e)return S.setAttribute(`rename.seeds_count`,e.length),S.setAttribute(`rename.cache_hit`,!0),e}let w=shadowGit(e),E;try{E=(await w.raw(`show`,`-s`,`--format=%aI`,t)).trim()}catch(e){return console.warn(`[rename-log] WARN: buildSeeds: git show failed for rename commit ${t}; falling back to single-seed:`,e),S.setAttribute(`rename.seeds_count`,1),[t]}if(!E)return S.setAttribute(`rename.seeds_count`,1),[t];let D;try{D=await w.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(creatordate:iso8601-strict) %(objectname)`,`refs/checkpoints/${s}/`)}catch(e){return console.warn(`[rename-log] WARN: buildSeeds: for-each-ref failed for branch ${s}; falling back to single-seed:`,e),S.setAttribute(`rename.seeds_count`,1),[t]}let O=[t];for(let e of D.split(`
|
|
785
|
-
`)){let s=e.trim();if(!s)continue;let g=s.lastIndexOf(` `);if(g<0)continue;let S=s.slice(0,g),w=s.slice(g+1);w.length===40&&w!==t&&S<E&&O.push(w)}return S.setAttribute(`rename.seeds_count`,O.length),g&&g.set(`${s}:${t}`,O),O})}const REV_LIST_STDIN_THRESHOLD_BYTES=100*1024;async function revListReachable(e,t){if(t.length===0)return``;if(t.reduce((e,t)=>e+t.length+1,0)<REV_LIST_STDIN_THRESHOLD_BYTES)return shadowGit(e).raw(`rev-list`,...t);let s=parseGitTimeoutMs();return new Promise((g,S)=>{let w=spawn(`git`,[`rev-list`,`--stdin`],{env:{...process.env,GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree}
|
|
786
|
-
`)}\n`)}catch(e){if(O)return;O=!0,clearTimeout(k),S(e)}})}async function logSeededReachable(e,t,s,g){if(s.length===0)return``;if(s.reduce((e,t)=>e+t.length+1,0)<REV_LIST_STDIN_THRESHOLD_BYTES){let S=[...t,...s,...g?[`--`,g]:[]];return shadowGit(e).raw(`log`,...S)}let S=parseGitTimeoutMs();return new Promise((w,E)=>{let D=spawn(`git`,[`log`,`--stdin`,...t,...g?[`--`,g]:[]],{env:{...process.env,GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree}
|
|
785
|
+
`)){let s=e.trim();if(!s)continue;let g=s.lastIndexOf(` `);if(g<0)continue;let S=s.slice(0,g),w=s.slice(g+1);w.length===40&&w!==t&&S<E&&O.push(w)}return S.setAttribute(`rename.seeds_count`,O.length),g&&g.set(`${s}:${t}`,O),O})}const REV_LIST_STDIN_THRESHOLD_BYTES=100*1024,GIT_STDIN_STDIO_OPTIONS={stdio:[`pipe`,`pipe`,`pipe`]},GIT_BATCH_CHECK_STDIO_OPTIONS={stdio:[`pipe`,`pipe`,`ignore`]};async function revListReachable(e,t){if(t.length===0)return``;if(t.reduce((e,t)=>e+t.length+1,0)<REV_LIST_STDIN_THRESHOLD_BYTES)return shadowGit(e).raw(`rev-list`,...t);let s=parseGitTimeoutMs();return new Promise((g,S)=>{let w=spawn(`git`,[`rev-list`,`--stdin`],withHiddenWindowsConsole({...GIT_STDIN_STDIO_OPTIONS,env:{...process.env,GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree}})),E=[],D=[];w.stdout.on(`data`,e=>E.push(e)),w.stderr.on(`data`,e=>D.push(e));let O=!1,k=setTimeout(()=>{if(!O){O=!0;try{w.kill(`SIGKILL`)}catch{}S(Error(`git rev-list --stdin timed out after ${s}ms`))}},s);w.on(`error`,e=>{O||(O=!0,clearTimeout(k),S(e))}),w.on(`close`,e=>{if(!O){if(O=!0,clearTimeout(k),e!==0){let t=Buffer.concat(D).toString(`utf-8`).trim();S(Error(`git rev-list --stdin exited ${e}: ${t}`));return}g(Buffer.concat(E).toString(`utf-8`))}});try{w.stdin.end(`${t.join(`
|
|
786
|
+
`)}\n`)}catch(e){if(O)return;O=!0,clearTimeout(k),S(e)}})}async function logSeededReachable(e,t,s,g){if(s.length===0)return``;if(s.reduce((e,t)=>e+t.length+1,0)<REV_LIST_STDIN_THRESHOLD_BYTES){let S=[...t,...s,...g?[`--`,g]:[]];return shadowGit(e).raw(`log`,...S)}let S=parseGitTimeoutMs();return new Promise((w,E)=>{let D=spawn(`git`,[`log`,`--stdin`,...t,...g?[`--`,g]:[]],withHiddenWindowsConsole({...GIT_STDIN_STDIO_OPTIONS,env:{...process.env,GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree}})),O=[],k=[];D.stdout.on(`data`,e=>O.push(e)),D.stderr.on(`data`,e=>k.push(e));let j=!1,F=setTimeout(()=>{if(!j){j=!0;try{D.kill(`SIGKILL`)}catch{}E(Error(`git log --stdin timed out after ${S}ms`))}},S);D.on(`error`,e=>{j||(j=!0,clearTimeout(F),E(e))}),D.on(`close`,e=>{if(!j){if(j=!0,clearTimeout(F),e!==0){let t=Buffer.concat(k).toString(`utf-8`).trim();E(Error(`git log --stdin exited ${e}: ${t}`));return}w(Buffer.concat(O).toString(`utf-8`))}});try{D.stdin.end(`${s.join(`
|
|
787
787
|
`)}\n`)}catch(e){if(j)return;j=!0,clearTimeout(F),E(e)}})}async function buildAncestorShaSet(e,t,s,g){return withSpan(`rename.buildAncestorShaSet`,void 0,async S=>{if(t.length===0)return S.setAttribute(`rename.ancestor_shas_count`,0),new Set;let w=`${s}:${[...t].sort().join(`,`)}`;if(g){let e=g.get(w);if(e)return S.setAttribute(`rename.ancestor_shas_count`,e.size),S.setAttribute(`rename.cache_hit`,!0),e}let E;try{E=await revListReachable(e,t)}catch(e){return console.warn(`[rename-log] WARN: buildAncestorShaSet: rev-list failed (${t.length} seeds); falling back to empty set:`,e),S.setAttribute(`rename.ancestor_shas_count`,0),new Set}let D=new Set;for(let e of E.split(`
|
|
788
|
-
`)){let t=e.trim();t.length===40&&D.add(t)}return g&&g.set(w,D),S.setAttribute(`rename.ancestor_shas_count`,D.size),D})}function batchCheckExistence(e,t){if(t.length===0)return Promise.resolve([]);let s=parseGitTimeoutMs();return new Promise(g=>{let S=spawn(`git`,[`cat-file`,`--batch-check`,`--buffer`],{env:{...process.env,GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree}
|
|
788
|
+
`)){let t=e.trim();t.length===40&&D.add(t)}return g&&g.set(w,D),S.setAttribute(`rename.ancestor_shas_count`,D.size),D})}function batchCheckExistence(e,t){if(t.length===0)return Promise.resolve([]);let s=parseGitTimeoutMs();return new Promise(g=>{let S=spawn(`git`,[`cat-file`,`--batch-check`,`--buffer`],withHiddenWindowsConsole({...GIT_BATCH_CHECK_STDIO_OPTIONS,env:{...process.env,GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree}})),w=[];S.stdout.on(`data`,e=>w.push(e));let E=()=>t.map(()=>!1),D=!1,O=e=>{D||(D=!0,g(e))},k=setTimeout(()=>{console.warn(`[rename-log] WARN: batchCheckExistence timed out after ${s}ms (${t.length} probes); returning all-false`);try{S.kill(`SIGKILL`)}catch{}O(E())},s);S.on(`error`,e=>{clearTimeout(k),console.warn(`[rename-log] WARN: batchCheckExistence spawn error: ${e.message}`),O(E())}),S.on(`close`,(e,s)=>{if(clearTimeout(k),e!==null&&e!==0||s&&!D){console.warn(`[rename-log] WARN: batchCheckExistence exited code=${e} signal=${s??`none`}; returning all-false`),O(E());return}let g=Buffer.concat(w).toString(`utf-8`).split(`
|
|
789
789
|
`).filter(e=>e.length>0);O(t.map((e,t)=>{let s=g[t];return s?!s.endsWith(` missing`):!1}))});let j=t.map(e=>`${e.sha}:${e.path}`).join(`
|
|
790
790
|
`);try{S.stdin.end(`${j}\n`)}catch(e){clearTimeout(k),console.warn(`[rename-log] WARN: batchCheckExistence stdin write failed: ${e.message}`),O(E())}})}function rewriteJsonlAtomically(e,t){let s=renameLogPath(e),g=serializeIndexToString(t);if(g.length===0){if(existsSync(s))try{tracedWriteFileSync(s,``)}catch(e){console.warn(`[rename-log] WARN: failed to truncate empty jsonl:`,e)}return}let S=`${s}.tmp`;try{tracedWriteFileSync(S,g),tracedRenameSync(S,s)}catch(e){console.warn(`[rename-log] WARN: atomic rewrite failed; index ahead of disk:`,e);try{existsSync(S)&&tracedUnlinkSync(S)}catch{}}}function backfillRenameLogCommitSha(e,t,s,g){if(!/^[0-9a-f]{40}$/.test(s))return console.warn(`[rename-log] WARN: backfill rejected invalid commitSha: ${JSON.stringify(s)}`),{updated:0};let S=0;for(let e of g.byTo.values())e.commitSha===``&&e.actor.writerId===t&&(e.commitSha=s,S+=1);return S>0&&rewriteJsonlAtomically(e,g),{updated:S}}function sweepLazyPopOrphans(e,t){let s=[];for(let e of t.byTo.values())e.commitSha===``&&s.push(e);if(s.length===0)return{dropped:0};for(let e of s)indexRemove(t,e);return rewriteJsonlAtomically(e,t),liveEntriesGauge().add(-s.length),console.warn(`[rename-log] gc swept ${s.length} orphan entries (lazy-pop residue from mid-rename crash)`),{dropped:s.length}}async function gcRenameLog(e,t,s){let g={scanned:0,dropped:0,retained:0,rebuilt:0};if(gcPending.has(e.gitDir))return g;gcPending.add(e.gitDir);try{return await gcRenameLogInner(e,t,s,g)}finally{gcPending.delete(e.gitDir)}}async function gcRenameLogInner(e,t,s,g){let S=shadowGit(e),w=[];for(let e of t.byTo.values())e.commitSha!==``&&w.push({entry:e,observedSha:e.commitSha});let E;try{E=(await S.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`,`refs/checkpoints/`)).split(`
|
|
791
791
|
`).map(e=>e.trim()).filter(Boolean)}catch(e){return console.warn(`[rename-log] WARN: gcRenameLog aborted — failed to enumerate refs:`,e),g}let D=new Set;if(E.length>0){let t;try{t=await revListReachable(e,E)}catch(e){return console.warn(`[rename-log] WARN: gcRenameLog aborted — rev-list failed:`,e),g}for(let e of t.split(`
|
|
@@ -822,13 +822,13 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
|
|
|
822
822
|
`)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let s=e.indexOf(`|`,t+1);if(s<0)continue;let g=e.indexOf(`|`,s+1);g<0||w.push({hash:e.slice(0,t),date:e.slice(t+1,s),authorName:e.slice(s+1,g),subject:e.slice(g+1)})}return{commits:w,source:`git`}}const GIT_TIMEOUT_MS$1=5e3;async function currentProjectBranch(e){try{let t=(await esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS$1}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function openShadowGit(e,t){return esm_default({baseDir:t,timeout:{block:GIT_TIMEOUT_MS$1}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function writerIdFromRef(e,t){let s=getWipRefPattern(t);return e.startsWith(s)?e.slice(s.length):e}async function logOnRef(e,t,s,g,S){let w=``;try{w=await e.raw(`log`,t,`-${Math.max(1,S*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,s)}catch{return[]}let E=writerIdFromRef(t,g),D=parseWriterId(E),O=[];for(let e of w.split(``)){let t=e.trimStart();if(!t)continue;let[s=``,S=``,w=``,k=``,j=``]=t.split(`\0`),F=s.trim();F.length===40&&O.push({hash:F,date:S,writerName:w,message:k,contributors:readContributors(j),writerId:E,isAgent:D.isAgent,writerClassification:D.classification,branch:g})}return O}async function checkpointAncestryFallback(e,t,s,g,S){let w=``;try{w=(await e.raw(`for-each-ref`,`--sort=-creatordate`,`--count=1`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)).trim()}catch{return[]}if(!w)return[];let E=``;try{E=await e.raw(`log`,w,`-${Math.max(g*3,20)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,s)}catch{return[]}let D=[];for(let e of E.split(``)){if(D.length>=g)break;let s=e.trimStart();if(!s)continue;let[w=``,E=``,O=``,k=``,j=``]=s.split(`\0`),F=w.trim();if(F.length!==40||S.has(F)||k.startsWith(`checkpoint:`)||k.startsWith(`park:`)||k.startsWith(`import:`)||k.startsWith(`upstream:`))continue;let L=parseOkActor(j),B=L?.writer_id??``,H=parseWriterId(B);S.add(F),D.push({hash:F,date:E,writerName:L?.display_name??O,message:k,contributors:readContributors(j),writerId:B,isAgent:H.isAgent,writerClassification:H.classification,branch:t})}return D}async function readShadowLog(e,t,s=5){let g=getShadowRepoPath(e);if(!g)return{commits:[],source:`shadow-repo-absent`};let S=await currentProjectBranch(e);if(!S)return{commits:[],source:`shadow-repo`};let w=openShadowGit(g,resolve(e)),E=``;try{E=await w.raw(`for-each-ref`,getWipRefPattern(S),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let D=E.split(`
|
|
823
823
|
`).map(e=>e.trim()).filter(Boolean),O=(D.length===0?[]:await Promise.all(D.map(e=>logOnRef(w,e,t,S,s)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,s);if(O.length<s){let e=new Set(O.map(e=>e.hash)),g=await checkpointAncestryFallback(w,S,t,s-O.length,e);g.length>0&&(O=[...O,...g].sort((e,t)=>t.date.localeCompare(e.date)).slice(0,s))}return{commits:O,source:`shadow-repo`}}function resolveTemplatesAvailable(e,t,s={}){let g=normalizeFolderPath(t),S=g===``?[]:g.split(`/`),w=new Set,E=[];collectFromFolder(e,g,`local`,w,E);for(let t=S.length-1;t>=1;t--)collectFromFolder(e,S.slice(0,t).join(`/`),`inherited`,w,E);return S.length>0&&collectFromFolder(e,``,`inherited`,w,E),E}function resolveProjectTemplates(e){let t=[],s=new Map,g=e=>{let t=s.get(e);return t||(t=new Set,s.set(e,t)),t},S=0,w=!1,E=[``];for(;E.length>0;){let s=E.shift()??``;if(S++>=PROJECT_TEMPLATE_SCAN_CAP){w=!0,console.warn(`[ok-templates] project scan hit the ${PROJECT_TEMPLATE_SCAN_CAP}-directory cap at ${e}; deeper templates were not enumerated. Queue depth at break: ${E.length}.`);break}collectFromFolder(e,s,`local`,g(s),t);let D=s?join(e,s):e,O;try{O=readdirSync(D).sort()}catch(e){if(e?.code!==`ENOENT`&&!templateMetaWarnedPaths.has(D)){templateMetaWarnedPaths.add(D);let t=e instanceof Error?e.message:String(e);console.warn(`[ok-templates] failed to read directory ${D} during project scan — skipped. Reason: ${t}`)}continue}for(let e of O){if(PROJECT_TEMPLATE_DIR_SKIP.has(e)||e.startsWith(`.`))continue;let t=join(D,e),g;try{g=statSync(t)}catch{continue}if(!g.isDirectory())continue;let S=s?posix.join(s,e):e;E.push(S)}}return{templates:t,truncated:w}}const PROJECT_TEMPLATE_SCAN_CAP=2e3,PROJECT_TEMPLATE_DIR_SKIP=new Set([`node_modules`,`dist`,`build`]);function collectFromFolder(e,t,s,g,S){let w=t?join(e,t,`.ok`,`templates`):join(e,`.ok`,`templates`);if(!existsSync(w))return;let E;try{E=readdirSync(w)}catch{return}for(let e of E){if(!e.endsWith(`.md`))continue;let E=e.slice(0,-3);if(g.has(E))continue;let D=join(w,e),O;try{O=statSync(D)}catch{continue}if(!O.isFile())continue;let k=readTemplateMeta(D),j={name:E,path:t?posix.join(t,`.ok`,`templates`,e):posix.join(`.ok`,`templates`,e),source_folder:t,scope:s};k.title!==void 0&&(j.title=k.title),k.description!==void 0&&(j.description=k.description),g.add(E),S.push(j)}}function normalizeFolderPath(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const templateMetaWarnedPaths=new Set;function readTemplateMeta(e){let t;try{t=readFileSync(e,`utf-8`)}catch(t){if(t?.code!==`ENOENT`&&!templateMetaWarnedPaths.has(e)){templateMetaWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-templates] failed to read template at ${e} — metadata skipped. Reason: ${s}`)}return{}}let{identity:s}=parseTemplateFile(t);typeof s.title!=`string`&&!templateMetaWarnedPaths.has(e)&&(templateMetaWarnedPaths.add(e),console.warn(`[ok-templates] template at ${e} has no title — YAML may be malformed or the title is missing.`));let g={};return typeof s.title==`string`&&(g.title=s.title),typeof s.description==`string`&&(g.description=s.description),g}function parseFrontmatterRaw(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return null;try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));if(typeof e==`object`&&e&&!Array.isArray(e))return e}catch{}return null}const DIRECTORY_SCAN_CAP=1e3,DIR_SKIP=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),WIKI_EXT_RE=/\.(md|mdx)$/i,HUB_MIN_INBOUND=5;function computeGraphRole(e,t){if(e===null||t===null)return null;let s=e,g=t;return s===0&&g===0?`orphan`:s>=HUB_MIN_INBOUND?`hub`:s>0&&g>0?`connector`:`leaf`}function pathToDocName$1(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const fmReadWarnedPaths=new Set;async function readFrontmatter(e){try{return parseFrontmatterRaw(await readFile$1(e,`utf-8`))??{}}catch(t){if(t?.code!==`ENOENT`&&!fmReadWarnedPaths.has(e)){fmReadWarnedPaths.add(e);let s=t instanceof Error?t.message:String(t);console.warn(`[ok-enrich] failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${s}`)}return null}}async function fetchBacklinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.backlinks??s.results??s.links;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e,s=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;s&&S.push({source:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}const BACKLINK_COUNT_CHUNK=100;async function fetchBacklinkCountsBatch(e,t){if(!e||t.length===0)return null;let s=[...new Set(t)],g=[];for(let e=0;e<s.length;e+=BACKLINK_COUNT_CHUNK)g.push(s.slice(e,e+BACKLINK_COUNT_CHUNK));let S=await Promise.all(g.map(async t=>{let s=await httpGet(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return s.ok?s.counts??{}:null})),w=new Map,E=!1;for(let e of S)if(e){E=!0;for(let[t,s]of Object.entries(e))typeof s==`number`&&Number.isFinite(s)&&w.set(t,s)}return E?w:null}async function fetchForwardLinks(e,t){if(!e)return null;let s=await httpGet(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!s.ok)return null;let g=s.forwardLinks??s.links??s.results;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){S.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let s=typeof t.docName==`string`?t.docName:void 0;s&&S.push({kind:`doc`,docName:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}function liftOwnFrontmatter(e){let t=e??{};return{title:typeof t.title==`string`?t.title:void 0,description:typeof t.description==`string`?t.description:void 0,tags:Array.isArray(t.tags)?t.tags.filter(e=>typeof e==`string`):[],frontmatter:t}}async function enrichPath(e,t,s={}){let g=resolveWithinRoot(t.projectDir,e);if(!g.ok)throw Error(`enrichPath: ${g.reason}`);let S=g.rel,w=g.abs,E=t.historyDepth??5,D=s.includeRichFields===!0,O=readFrontmatter(w);if(!D){let e=liftOwnFrontmatter(await O);return{path:S,title:e.title,description:e.description,tags:e.tags,frontmatter:e.frontmatter,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null,graphRole:null}}let[k,j,F,L,B]=await Promise.all([O,fetchBacklinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),fetchForwardLinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),readShadowLog(t.projectDir,S,E).catch(()=>({commits:[],source:`shadow-repo`})),readProjectGitLog(t.projectDir,S,E).catch(()=>({commits:[],source:`git`}))]),H=liftOwnFrontmatter(k);return{path:S,title:H.title,description:H.description,tags:H.tags,frontmatter:H.frontmatter,backlinkCount:j?.length??null,backlinks:j,forwardLinkCount:F?.length??null,forwardLinks:F,history:L.commits,historySource:L.source,projectHistory:B.commits,projectHistorySource:B.source,graphRole:computeGraphRole(j?.length??null,F?.length??null)}}async function scanDirectory(e,t){let s={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},g=0,S=[{path:e,depth:0}];for(;S.length>0;){let e=S.shift();if(!e)break;if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}let w;try{w=await readdir(e.path,{withFileTypes:!0})}catch{continue}for(let E of w){if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}g++;let w=E.name;if(E.isDirectory()){if(DIR_SKIP.has(w)||w.startsWith(`.`))continue;e.depth===0&&s.childDirCount++,S.push({path:`${e.path}/${w}`,depth:e.depth+1})}else if(E.isFile()&&WIKI_EXT_RE.test(w)){s.recursiveMdCount++,e.depth===0&&s.directMdCount++;let g=`${e.path}/${w}`;try{let e=await stat$1(g);(!s.mostRecent||e.mtimeMs>s.mostRecent.mtimeMs)&&(s.mostRecent={absPath:g,relPath:relative(t,g).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return s}async function enrichDirectory(e,t){let s=resolveWithinRoot(t.projectDir,e);if(!s.ok)throw Error(`enrichDirectory: ${s.reason}`);let g=s.rel,S=s.abs,w=await scanDirectory(S,t.projectDir),E;if(w.mostRecent){let e=await readFrontmatter(w.mostRecent.absPath),t=typeof e?.title==`string`?e.title:void 0;E={path:w.mostRecent.relPath,title:t??basename(w.mostRecent.relPath),updatedAt:new Date(w.mostRecent.mtimeMs).toISOString()}}let D={path:g,type:`directory`,directMdCount:w.directMdCount,recursiveMdCount:w.recursiveMdCount,childDirCount:w.childDirCount,mostRecentMd:E,truncated:w.truncated},O=readFolderFrontmatter(t.projectDir,g);O.title!==void 0&&(D.title=O.title),O.description!==void 0&&(D.description=O.description),(O.tags?.length??0)>0&&(D.tags=O.tags);let k=resolveTemplatesAvailable(t.projectDir,g);return k.length>0&&(D.templates_available=k),D}async function enrichDirectoryRecursive(e,t,s){let g=await enrichDirectory(e,s);if(t<=1)return g;let S=g.path,w=resolve(s.projectDir,S),E;try{E=await readdir(w,{withFileTypes:!0})}catch{return g}let D=[];for(let e of E){if(!e.isDirectory()||RECURSIVE_LISTING_SKIP_DIRS.has(e.name)||e.name.startsWith(`.`))continue;let g=await enrichDirectoryRecursive(S?`${S}/${e.name}`:e.name,t-1,s);D.push(g)}return D.length>0&&(g.subfolders=D),g}const RECURSIVE_LISTING_SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function mergePatch(e,t){let s={...e};for(let[e,g]of Object.entries(t))if(g!==void 0){if(isEmpty$2(g)){delete s[e];continue}s[e]=g}return s}function isEmpty$2(e){return isFrontmatterValueEmpty(e)}function applyFolderFrontmatterPatch(e){if(!isAbsolute(e.anchorDir))return{ok:!1,error:{code:`BAD_CONTENT_DIR`,message:`anchorDir must be absolute`}};let t=resolve(e.anchorDir),s=e.folderRel.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(s.split(`/`).some(e=>e===`..`))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Folder path escapes the content directory: ${e.folderRel}`}};let g=s===``?t:resolve(t,s);if(g!==t&&!g.startsWith(t+sep))return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder escapes the content directory: ${g}`}};let S=join(g,`.ok`),w=join(S,`frontmatter.yml`);try{let s=readExistingFrontmatter(w),g=Object.keys(e.patch).length===0?{}:mergePatch(s,e.patch);if(Object.keys(g).length===0)return existsSync(w)?(unlinkSync(w),autoCleanOkDir(S),{ok:!0,path:relPathOf$2(t,w),action:`deleted`}):{ok:!0,path:relPathOf$2(t,w),action:`noop`};mkdirSync(S,{recursive:!0});let E=(0,import_dist$1.stringify)(g),D=`${w}.tmp.${process.pid}.${Date.now()}`;return writeFileSync(D,E,`utf-8`),renameSync(D,w),{ok:!0,path:relPathOf$2(t,w),action:`written`}}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write folder frontmatter for "${s||`.`}": ${e.message}`}}}}function readExistingFrontmatter(e){if(!existsSync(e))return{};let t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`));return typeof t!=`object`||!t||Array.isArray(t)?{}:{...t}}function autoCleanOkDir(e){if(!existsSync(e))return;let t;try{t=readdirSync(e)}catch{return}if(t.length===0)try{rmdirSync(e)}catch{}}function relPathOf$2(e,t){return t.startsWith(e+sep)?t.slice(e.length+1).split(sep).join(`/`):t}const NAME_MAX=64,DESCRIPTION_MAX=1024,RESERVED_NAME_WORDS=[`anthropic`,`claude`],BODY_SOFT_MAX_LINES=500,SKILL_FILE=`SKILL.md`;function composeSkillContent(e){let t=validateName(e.name);if(!t.ok)return{ok:!1,error:t.error};let s=validateFrontmatter(e.frontmatter,e.name);if(!s.ok)return{ok:!1,error:s.error};let g=`---\n${serializeFrontmatter(e.frontmatter)}---\n${e.body}`,S=[],w=e.body.split(`
|
|
824
824
|
`).length;return w>BODY_SOFT_MAX_LINES&&S.push(`SKILL.md body is ${w} lines — keep it under ${BODY_SOFT_MAX_LINES} for performance (every line is a recurring token cost). Move detail into one-level-deep references/.`),{ok:!0,content:g,warnings:S}}function applySkillWrite(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=composeSkillContent({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!s.ok)return{ok:!1,error:s.error};let{content:g,warnings:S}=s,{skillDir:w,filePath:E}=skillPaths(e.skillsRoot,e.name);try{mkdirSync(w,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create skill directory at ${relPathOf$1(e.skillsRoot,w)}: ${t.message}`}}}let D=!existsSync(E),O=`${E}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(O,g,`utf-8`),renameSync(O,E)}catch(t){try{unlinkSync(O)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill at ${relPathOf$1(e.skillsRoot,E)}: ${t.message}`}}}return{ok:!0,path:relPathOf$1(e.skillsRoot,E),created:D,warnings:S}}const BUNDLE_FILE_MAX_BYTES=256*1024;function resolveBundleFileAbs(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 s=t.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);if(s.length<2||s.some(e=>e===`..`))return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Invalid skill file path: ${t}`}};if(s[0]!==`references`&&s[0]!==`scripts`)return{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Skill file must be under references/ or scripts/: ${t}`}};let g=join(e,...s);return g!==e&&!g.startsWith(e+sep)?{ok:!1,error:{code:`BAD_FILE_PATH`,message:`Skill file escapes the skill dir: ${t}`}}:{ok:!0,abs:g}}function countBundleFiles(e){let t=0,s=g=>{let S;try{S=readdirSync(g)}catch{return}for(let w of S){let S=join(g,w),E;try{E=statSync(S).isDirectory()}catch{continue}E?s(S):g===e&&w===SKILL_FILE||t++}};return s(e),t}function applySkillBundleFileWrite(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.name);if(!s.ok)return{ok:!1,error:s.error};let{skillDir:g,filePath:S}=skillPaths(e.skillsRoot,e.name);if(!existsSync(S))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill "${e.name}" — create it (write its SKILL.md) before adding bundle files.`}};let w=resolveBundleFileAbs(g,e.relPath);if(!w.ok)return{ok:!1,error:w.error};let{abs:E}=w,D=Buffer.byteLength(e.content,`utf-8`);if(D>262144)return{ok:!1,error:{code:`FILE_TOO_LARGE`,message:`Skill file ${e.relPath} is ${D} bytes — the per-file cap is ${BUNDLE_FILE_MAX_BYTES}.`}};let O=!existsSync(E);if(O&&countBundleFiles(g)>=50)return{ok:!1,error:{code:`TOO_MANY_FILES`,message:`Skill "${e.name}" already holds 50 bundle files (the cap) — delete one before adding another.`}};try{mkdirSync(join(E,`..`),{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create directory for ${e.relPath}: ${t.message}`}}}let k=`${E}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(k,e.content,`utf-8`),renameSync(k,E)}catch(t){try{unlinkSync(k)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write skill file ${e.relPath}: ${t.message}`}}}return{ok:!0,path:relPathOf$1(e.skillsRoot,E),created:O}}function applySkillBundleFileDelete(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.name);if(!s.ok)return{ok:!1,error:s.error};let{skillDir:g}=skillPaths(e.skillsRoot,e.name),S=resolveBundleFileAbs(g,e.relPath);if(!S.ok)return{ok:!1,error:S.error};let{abs:w}=S,E=existsSync(w);if(E){try{unlinkSync(w)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill file ${e.relPath}: ${t.message}`}}}let t=join(w,`..`);if(t!==g&&isEmpty$1(t))try{rmdirSync(t)}catch{}}return{ok:!0,path:relPathOf$1(e.skillsRoot,w),existed:E}}function applySkillDelete(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.name);if(!s.ok)return{ok:!1,error:s.error};let{skillsRoot:g}=t,{skillDir:S}=skillPaths(e.skillsRoot,e.name),w=existsSync(S);if(w)try{rmSync(S,{recursive:!0,force:!0})}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete skill at ${relPathOf$1(e.skillsRoot,S)}: ${t.message}`}}}return cleanEmptyDirs(g),{ok:!0,path:relPathOf$1(e.skillsRoot,S),existed:w}}async function applySkillMove(e){let t=validateBase(e.skillsRoot);if(!t.ok)return{ok:!1,error:t.error};let s=validateName(e.fromName);if(!s.ok)return{ok:!1,error:s.error};let g=validateName(e.toName);if(!g.ok)return{ok:!1,error:g.error};let S=skillPaths(e.skillsRoot,e.fromName),w=skillPaths(e.skillsRoot,e.toName);if(S.skillDir===w.skillDir)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same skill.`}};if(!existsSync(S.skillDir))return{ok:!1,error:{code:`SKILL_NOT_FOUND`,message:`No skill at ${relPathOf$1(e.skillsRoot,S.skillDir)}.`}};if(existsSync(w.skillDir))return{ok:!1,error:{code:`SKILL_EXISTS`,message:`A skill already exists at ${relPathOf$1(e.skillsRoot,w.skillDir)}.`}};let E;try{E=await e.relocate(S.skillDir,w.skillDir)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move skill: ${e.message}`}}}return{ok:!0,fromPath:relPathOf$1(e.skillsRoot,S.skillDir),toPath:relPathOf$1(e.skillsRoot,w.skillDir),committed:E}}function validateBase(e){return isAbsolute(e)?{ok:!0,skillsRoot:e}:{ok:!1,error:{code:`BAD_SKILLS_ROOT`,message:`skillsRoot must be absolute`}}}function validateName(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name is required.`}}:e.length>NAME_MAX?{ok:!1,error:{code:`BAD_NAME`,message:`Skill name must be ≤${NAME_MAX} characters.`}}:SKILL_NAME_REGEX.test(e)?RESERVED_NAME_WORDS.some(t=>e.includes(t))?{ok:!1,error:{code:`RESERVED_NAME`,message:`Skill name may not contain reserved words (${RESERVED_NAME_WORDS.join(`, `)}).`}}:{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 validateFrontmatter(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?containsXmlTag(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===0?{ok:!1,error:{code:`SKILL_DESCRIPTION_REQUIRED`,message:`Skill frontmatter.description is required — it is the primary triggering surface (when to use the skill).`}}:e.description.length>DESCRIPTION_MAX?{ok:!1,error:{code:`DESCRIPTION_TOO_LONG`,message:`Skill frontmatter.description must be ≤${DESCRIPTION_MAX} characters (got ${e.description.length}).`}}:containsXmlTag(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:`NAME_DIR_MISMATCH`,message:`Skill frontmatter.name (${JSON.stringify(e.name)}) must equal the skill directory name (${JSON.stringify(t)}).`}}}function skillPaths(e,t){let s=join(e,t);return{skillDir:s,filePath:join(s,SKILL_FILE)}}function cleanEmptyDirs(e){if(existsSync(e)&&isEmpty$1(e))try{rmdirSync(e)}catch{}let t=normalize(join(e,`..`));if(t.endsWith(`${sep}.ok`)&&existsSync(t)&&isEmpty$1(t))try{rmdirSync(t)}catch{}}function relPathOf$1(e,t){return normalize(t.startsWith(e+sep)?t.slice(e.length+1):t).split(sep).join(`/`)}function serializeFrontmatter(e){return(0,import_dist$1.stringify)({name:e.name,description:e.description})}function isEmpty$1(e){try{return readdirSync(e).length===0}catch{return!1}}const SUBSTITUTION_ALLOWLIST=[`date`,`user`],TOKEN_PATTERN=/\{\{([^{}\n]+?)\}\}/g;function validateSubstitution(e){let t=[];for(let s of e.matchAll(TOKEN_PATTERN)){let e=(s[1]??``).trim();isAllowedToken(e)||t.push({token:e,offset:s.index??0})}return t}function applySubstitution(e,t){return e.replace(TOKEN_PATTERN,(e,s)=>{let g=s.trim();return isAllowedToken(g)?t[g]:e})}function isAllowedToken(e){return SUBSTITUTION_ALLOWLIST.includes(e)}function todayIsoUtc(e=new Date){return`${e.getUTCFullYear().toString().padStart(4,`0`)}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}const NAME_RE=TEMPLATE_NAME_REGEX;function composeTemplateContent(e){if(!NAME_RE.test(e.name))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(e.name)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let t=validateTitle(e.frontmatter.title);if(!t.ok)return{ok:!1,error:t.error};let s=validateSubstitutionAllowlist(e.body);if(!s.ok)return{ok:!1,error:s.error};let g=validateNoReservedDocKey(e.body);if(!g.ok)return{ok:!1,error:g.error};let S={};e.frontmatter.title!==void 0&&(S.title=e.frontmatter.title),e.frontmatter.description!==void 0&&(S.description=e.frontmatter.description),Array.isArray(e.frontmatter.tags)&&e.frontmatter.tags.length>0&&(S.tags=e.frontmatter.tags);let w=composeTemplateFile(S,e.body),E=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&E.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,content:w,warnings:E}}function applyTemplateWrite(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let s=composeTemplateContent({name:e.name,body:e.body,frontmatter:e.frontmatter});if(!s.ok)return{ok:!1,error:s.error};let{content:g,warnings:S}=s,{templatesDir:w,filePath:E}=templatePaths(e.projectDir,t.folderRel,e.name);try{mkdirSync(w,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${relPathOf(e.projectDir,w)}: ${t.message}`}}}let D=!existsSync(E),O=`${E}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(O,g,`utf-8`),renameSync(O,E)}catch(t){try{unlinkSync(O)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${relPathOf(e.projectDir,E)}: ${t.message}`}}}return{ok:!0,path:relPathOf(e.projectDir,E),created:D,warnings:S}}function applyTemplateDelete(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let{templatesDir:s,okDir:g,filePath:S}=templatePaths(e.projectDir,t.folderRel,e.name),w=existsSync(S);if(w)try{unlinkSync(S)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete template at ${relPathOf(e.projectDir,S)}: ${t.message}`}}}return{ok:!0,path:relPathOf(e.projectDir,S),existed:w,cleanedEmpty:cleanEmptyOkDirs(s,g)}}function cleanEmptyOkDirs(e,t){let s=!1,g=!1;if(existsSync(e)&&isEmpty(e))try{rmdirSync(e),s=!0}catch{}if(existsSync(t)&&isEmpty(t))try{rmdirSync(t),g=!0}catch{}return{templatesDir:s,okDir:g}}async function applyTemplateMove(e){let t=validateInputs(e.projectDir,e.fromFolder,e.fromName);if(!t.ok)return{ok:!1,error:t.error};let s=validateInputs(e.projectDir,e.toFolder,e.toName);if(!s.ok)return{ok:!1,error:s.error};let g=templatePaths(e.projectDir,t.folderRel,e.fromName),S=templatePaths(e.projectDir,s.folderRel,e.toName);if(g.filePath===S.filePath)return{ok:!1,error:{code:`NOOP`,message:`Source and destination are the same template.`}};if(!existsSync(g.filePath))return{ok:!1,error:{code:`TEMPLATE_NOT_FOUND`,message:`No template at ${relPathOf(e.projectDir,g.filePath)}.`}};if(existsSync(S.filePath))return{ok:!1,error:{code:`TEMPLATE_EXISTS`,message:`A template already exists at ${relPathOf(e.projectDir,S.filePath)}.`}};try{mkdirSync(S.templatesDir,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create destination template directory at ${relPathOf(e.projectDir,S.templatesDir)}: ${t.message}`}}}let w;try{w=await e.relocate(g.filePath,S.filePath)}catch(e){return{ok:!1,error:{code:`MOVE_FAILED`,message:`Failed to move template: ${e.message}`}}}let E=cleanEmptyOkDirs(g.templatesDir,g.okDir);return{ok:!0,fromPath:relPathOf(e.projectDir,g.filePath),toPath:relPathOf(e.projectDir,S.filePath),committed:w,cleanedEmpty:E}}function validateInputs(e,t,s){if(!isAbsolute(e))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};if(!NAME_RE.test(s))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(s)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let g=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``);if(g.includes(`..`))return{ok:!1,error:{code:`PATH_TRAVERSAL`,message:`Folder path may not contain "..": ${JSON.stringify(t)}`}};let S=g?resolve(e,g):e,w=resolve(e);return!S.startsWith(w+sep)&&S!==w?{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder path escapes projectDir: ${S}`}}:{ok:!0,folderRel:g}}function validateTitle(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`TEMPLATE_TITLE_REQUIRED`,message:"Template frontmatter.title is required. `title` is the menu surface — agents pick templates by name+title; a title-less template is effectively invisible. Set a non-empty `title` and retry."}}:{ok:!0}}function validateSubstitutionAllowlist(e){let t=validateSubstitution(e);return t.length===0?{ok:!0}:{ok:!1,error:{code:`TEMPLATE_UNKNOWN_VARIABLE`,message:`Template body contains unknown substitution token(s): ${t.map(e=>`\`{{${e.token}}}\` at offset ${e.offset}`).join(`, `)}. v1 allowlist: \`{{date}}\`, \`{{user}}\`. Remove or rename the offending tokens and retry.`}}}function templatePaths(e,t,s){let g=t?join(e,t,`.ok`):join(e,`.ok`),S=join(g,`templates`);return{okDir:g,templatesDir:S,filePath:join(S,`${s}.md`)}}function relPathOf(e,t){return normalize(t.startsWith(e+sep)?t.slice(e.length+1):t).split(sep).join(`/`)}function validateNoReservedDocKey(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return{ok:!0};let s=unwrapFrontmatterFences(t);return RegExp(`^template:`,`m`).test(s)?{ok:!1,error:{code:`TEMPLATE_RESERVED_KEY`,message:`Template starter content may not declare a top-level \`${TEMPLATE_IDENTITY_KEY}:\` frontmatter key — it is reserved for the template's identity.`}}:{ok:!0}}function isEmpty(e){try{return readdirSync(e).length===0}catch{return!1}}var RingBuffer=class{capacity;store;writeIndex=0;filled=!1;constructor(e){if(!Number.isInteger(e)||e<=0)throw RangeError(`RingBuffer capacity must be a positive integer, got ${e}`);this.capacity=e,this.store=Array(e)}push(e){this.store[this.writeIndex]=e,this.writeIndex=(this.writeIndex+1)%this.capacity,this.writeIndex===0&&(this.filled=!0)}read(){let e=[],t=this.filled?this.capacity:this.writeIndex;for(let s=1;s<=t;s++){let t=(this.writeIndex-s+this.capacity)%this.capacity,g=this.store[t];g!==void 0&&e.push(g)}return e}get size(){return this.filled?this.capacity:this.writeIndex}};const embedProbeRing=new RingBuffer(256);function recordEmbedProbe(e){embedProbeRing.push(e)}const CURSOR_UA_RE=UA_PATTERNS.cursor,CODEX_UA_RE=UA_PATTERNS.codex,CLAUDE_UA_RE=UA_PATTERNS[`claude-desktop`],CURSOR_REFERER_STRATEGY_LITERAL=`?strategy=C_iframe`,EMPTY_DETECTION={app:null,signals_fired:[]};function deriveDetection(e){if(!e)return{...EMPTY_DETECTION};let t=[],s=e.ua,g=e.referer,S=!!s&&CURSOR_UA_RE.test(s),w=!!g&&g.includes(CURSOR_REFERER_STRATEGY_LITERAL);if(S&&t.push(`cursor_ua_regex`),w&&t.push(`cursor_referer_strategy_iframe`),S||w)return{app:`cursor`,signals_fired:t};let E=!!s&&CODEX_UA_RE.test(s);if(E&&t.push(`codex_ua_regex`),E)return{app:`codex`,signals_fired:t};let D=!!s&&CLAUDE_UA_RE.test(s);return D&&t.push(`claude_ua_regex`),D?{app:`claude`,signals_fired:t}:{...EMPTY_DETECTION}}const log$15=getLogger(`embeddings`);let _tokens=null,_errors=null,_requestDuration=null,_queryTotal=null,_queryEmbedDuration=null;function tokensCounter(){return _tokens||=getMeter().createCounter(`ok.embeddings.tokens_total`,{description:`Embeddings tokens billed, by role. Bounded label: role ∈ {query, document}. Makes spend legible; never includes content.`}),_tokens}function errorsCounter(){return _errors||=getMeter().createCounter(`ok.embeddings.provider_errors_total`,{description:`Embeddings provider failures, by reason. Bounded label: reason ∈ {rate_limit, timeout, http_error, network, dims_mismatch, malformed_response}.`}),_errors}function requestDurationHist(){return _requestDuration||=getMeter().createHistogram(`ok.embeddings.request_duration_ms`,{description:`Wall-clock duration of one embeddings API request. Bounded label: role.`,unit:`ms`}),_requestDuration}function queryTotalCounter(){return _queryTotal||=getMeter().createCounter(`ok.search.semantic_query_total`,{description:`Semantic-requested searches, by outcome and caller surface. Bounded labels: outcome ∈ {applied, no_match, warming, incapable, provider_error}, source ∈ {omnibar, mcp, http}. The omnibar/mcp split separates interactive cost from agent cost.`}),_queryTotal}function queryEmbedDurationHist(){return _queryEmbedDuration||=getMeter().createHistogram(`ok.search.semantic_query_embed_ms`,{description:`Wall-clock latency of the per-query embed on the semantic search path.`,unit:`ms`}),_queryEmbedDuration}function recordEmbeddingTokens(e,t){t>0&&tokensCounter().add(t,{role:e})}function recordEmbeddingProviderError(e){errorsCounter().add(1,{reason:e})}function recordEmbeddingRequestDuration(e,t){requestDurationHist().record(Math.max(0,t),{role:e})}function recordSemanticQuery(e){queryTotalCounter().add(1,{outcome:e.outcome,source:e.source}),e.queryEmbedMs!==null&&queryEmbedDurationHist().record(Math.max(0,e.queryEmbedMs)),log$15.debug({outcome:e.outcome,source:e.source,capable:e.capable,embedded:e.embedded,total:e.total,coverage:e.total>0?e.embedded/e.total:0,queryEmbedMs:e.queryEmbedMs,vectorContributors:e.vectorContributors},`[search] semantic query`)}const DEFAULT_EMBEDDINGS_DIMENSIONS=1536,EMBEDDINGS_API_KEY_ENV=`OK_EMBEDDINGS_API_KEY`;var EmbeddingDimsMismatchError=class extends Error{name=`EmbeddingDimsMismatchError`;constructor(e,t){super(`embeddings provider returned ${t}-dim vectors, expected ${e}. Set search.semantic.dimensions to ${t} (or point at the right model).`),this.expected=e,this.got=t}},MalformedEmbeddingResponseError=class extends Error{name=`MalformedEmbeddingResponseError`;constructor(e,t){super(`embeddings response had ${t} vectors, expected ${e}`)}};function cosineSimilarity(e,t){let s=0,g=Math.min(e.length,t.length);for(let S=0;S<g;S++)s+=e[S]*t[S];return s}function normalizeInPlace(e){let t=0;for(let s=0;s<e.length;s++)t+=e[s]*e[s];if(t=Math.sqrt(t),t>0)for(let s=0;s<e.length;s++)e[s]/=t;return e}const DEFAULTS={maxBatchSize:96,maxBatchChars:96e3,docTimeoutMs:3e4,queryTimeoutMs:8e3,maxRetries:4,backoffBaseMs:500};function normalizeProviderId(e){try{let t=new URL(e),s=t.pathname.replace(/\/+$/,``);return`${t.protocol}//${t.host.toLowerCase()}${s}`}catch{return e.trim().replace(/\/+$/,``)}}function assertSafeEmbeddingsBaseUrl(e){let t;try{t=new URL(e)}catch{throw Error(`embeddings baseUrl is not a valid URL: ${e}`)}if(t.protocol===`https:`)return;let s=t.hostname.toLowerCase(),g=s===`localhost`||s===`127.0.0.1`||s===`::1`||s===`[::1]`;if(!(t.protocol===`http:`&&g))throw Error(`refusing to send the embeddings API key to a non-HTTPS endpoint (${t.protocol}//${t.host}); use https:// (http:// is allowed only for localhost)`)}const RETRYABLE_STATUS=new Set([408,409,429,500,502,503,504]);function defaultSleep$1(e){return new Promise(t=>setTimeout(t,e))}function createOpenAiEmbedder(e,t={}){let s=t.fetchImpl??fetch,g=t.sleep??defaultSleep$1,S=t.maxBatchSize??DEFAULTS.maxBatchSize,w=t.maxBatchChars??DEFAULTS.maxBatchChars,E=t.maxRetries??DEFAULTS.maxRetries,D=t.backoffBaseMs??DEFAULTS.backoffBaseMs,O=t.docTimeoutMs??DEFAULTS.docTimeoutMs,k=t.queryTimeoutMs??DEFAULTS.queryTimeoutMs;assertSafeEmbeddingsBaseUrl(e.baseUrl);let j=e.dimensions??1536,F=`${e.baseUrl.replace(/\/+$/,``)}/embeddings`;function L(e){let t=[],s=[],g=0;for(let E of e)s.length>0&&(s.length>=S||g+E.length>w)&&(t.push(s),s=[],g=0),s.push(E),g+=E.length;return s.length>0&&t.push(s),t}async function B(t,g,S,w){let E=new AbortController,D=setTimeout(()=>E.abort(),w),O=performance.now();try{let w=await s(F,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.apiKey}`},body:t,signal:E.signal});if(recordEmbeddingRequestDuration(S,performance.now()-O),!w.ok){await w.text().catch(()=>``);let e=w.status===429?`rate_limit`:`http_error`,t=Error(`embeddings request failed: HTTP ${w.status}`);return RETRYABLE_STATUS.has(w.status)?{kind:`retry`,reason:e,error:t}:{kind:`fatal`,reason:e,error:t}}let D=await w.json(),k=q(D,g,j);return recordEmbeddingTokens(S,D.usage?.total_tokens??0),{kind:`ok`,vectors:k}}catch(e){if(e instanceof EmbeddingDimsMismatchError)return{kind:`fatal`,reason:`dims_mismatch`,error:e};if(e instanceof MalformedEmbeddingResponseError)return{kind:`fatal`,reason:`malformed_response`,error:e};let t=e instanceof Error&&e.name===`AbortError`,s=e instanceof Error?e:Error(String(e));return{kind:`retry`,reason:t?`timeout`:`network`,error:s}}finally{clearTimeout(D)}}async function H(t,s){let S=s===`query`?k:O,w=s===`query`?`query`:`document`,j=JSON.stringify({model:e.model,input:t,encoding_format:`float`,...e.dimensions===void 0?{}:{dimensions:e.dimensions}}),F=0;for(;;){let e=await B(j,t.length,w,S);if(e.kind===`ok`)return e.vectors;if(recordEmbeddingProviderError(e.reason),e.kind===`fatal`||F>=E)throw e.error;F+=1;let s=D*2**(F-1);await g(Math.round(s/2+s/2*Math.random()))}}function q(e,t,s){let g=e.data;if(!Array.isArray(g)||g.length!==t)throw new MalformedEmbeddingResponseError(t,g?.length??0);let S=[...g].sort((e,t)=>(e.index??0)-(t.index??0)),w=[];for(let e of S){let g=e.embedding;if(!Array.isArray(g))throw new MalformedEmbeddingResponseError(t,0);if(g.length!==s)throw new EmbeddingDimsMismatchError(s,g.length);w.push(normalizeInPlace(Float32Array.from(g)))}return w}return{providerId:normalizeProviderId(e.baseUrl),modelId:e.model,dims:j,async embed(e,{role:t}){if(e.length===0)return[];let s=[];for(let g of L(e))s.push(...await H(g,t));return s}}}async function loadOpenAiEmbedder(e){let t=(e.keyStore?await e.keyStore.get().catch(()=>null):null)??process.env.OK_EMBEDDINGS_API_KEY??null;return t?createOpenAiEmbedder({...e.config,apiKey:t},e.options):null}const SECRETS_KEY_FIELD=`OPENAI_API_KEY`,LEGACY_KEY_FIELD=`embeddings`;function secretsFilePath(e){return join(e??homedir(),`.ok`,`secrets.yml`)}var FileEmbeddingsBackend=class{backend=`file`;secretsFile;constructor(e){this.secretsFile=e??secretsFilePath()}tightenPermsIfLoose(){let e;try{e=statSync(this.secretsFile).mode&511}catch{return}if(e&63)try{chmodSync(this.secretsFile,384),process.stderr.write(`[embeddings] ${this.secretsFile} was readable beyond your user account (mode ${e.toString(8)}); tightened to 600. It stores an API key.\n`)}catch(t){let s=t instanceof Error?t.message:`unknown error`;process.stderr.write(`[embeddings] ${this.secretsFile} is readable beyond your user account (mode ${e.toString(8)}) and could not be tightened (${s}); your API key remains exposed — run: chmod 600 ${this.secretsFile}\n`)}}read(){if(!existsSync(this.secretsFile))return{};this.tightenPermsIfLoose();try{return(0,import_dist$1.parse)(readFileSync(this.secretsFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[embeddings] Failed to parse ${this.secretsFile}: ${t}. Starting with empty secrets.\n`),{}}}write(e){let t=dirname(this.secretsFile);existsSync(t)||tracedMkdirSync(t,{recursive:!0,mode:448}),tracedWriteFileSync(this.secretsFile,(0,import_dist$1.stringify)(e),{mode:384}),chmodSync(this.secretsFile,384)}get(){let e=this.read(),t=e[SECRETS_KEY_FIELD]??e[LEGACY_KEY_FIELD];return Promise.resolve(typeof t==`string`&&t!==``?t:null)}set(e){let t=this.read();return delete t[LEGACY_KEY_FIELD],t[SECRETS_KEY_FIELD]=e,this.write(t),Promise.resolve()}clear(){let e=this.read();if(SECRETS_KEY_FIELD in e||LEGACY_KEY_FIELD in e)if(delete e[SECRETS_KEY_FIELD],delete e[LEGACY_KEY_FIELD],Object.keys(e).length===0)try{tracedUnlinkSync(this.secretsFile)}catch{}else this.write(e);return Promise.resolve()}};function createEmbeddingsSecretStore(e){return new FileEmbeddingsBackend(e)}function makeLazyEmbeddingsKeyStore(e){return new FileEmbeddingsBackend(e)}async function describeStoredEmbeddingsKey(e){return{file:await new FileEmbeddingsBackend(e).get()!=null}}async function clearEmbeddingsKeyFromAllBackends(e){let t=[],s=new FileEmbeddingsBackend(e);return await s.get()!=null&&(await s.clear(),t.push(`file`)),{touched:t}}function readProjectLocalSemanticConfig(e,t){let s=readConfigSafely({absPath:resolveConfigPath(`project-local`,e,t?.configHomedirOverride),sideline:!1,warn:t?.onWarn??(()=>{})}).value.search?.semantic;return{enabled:s?.enabled===!0,baseUrl:s?.baseUrl??`https://api.openai.com/v1`,model:s?.model??`text-embedding-3-small`,dimensions:s?.dimensions??void 0,similarityFloor:s?.similarityFloor??void 0}}const CHUNK_CONFIG_ID=`c8000-o400-m80`;function chunkDocument(e,t={}){let s=Math.max(1,t.targetChars??8e3),g=Math.max(0,Math.min(t.overlapChars??400,s-1)),S=t.maxChunks??80;if(e.trim().length===0)return[];if(e.length<=s)return[e.trim()];let w=[],E=0;for(;E<e.length&&w.length<S;){let t=Math.min(e.length,E+s);if(t<e.length){let g=Math.max(e.lastIndexOf(` `,t),e.lastIndexOf(`
|
|
825
|
-
`,t));g>E+Math.floor(s/2)&&(t=g)}let S=e.slice(E,t).trim();if(S&&w.push(S),t>=e.length)break;let D=t-g;E=D>E?D:t}return w}const log$14=getLogger(`embeddings`),MANIFEST_SCHEMA_VERSION=1,VEC_SUBDIR=`vec`,MANIFEST_NAME=`manifest.json`;function hashContent(e){return createHash(`sha256`).update(e,`utf-8`).digest(`hex`)}function serializeVectors(e){let t=0;for(let s of e)t+=s.length;let s=new Float32Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}function deserializeVectors(e,t){let s=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),g=new Float32Array(s);if(g.length%t!==0)throw Error(`vector blob length ${g.length} is not a multiple of dims ${t}`);let S=[];for(let e=0;e<g.length;e+=t)S.push(g.slice(e,e+t));return S}var VectorCache=class{cacheDir;vecDir;manifestPath;providerId;modelId;dims;chunkConfigId;entries=new Map;vectorsByHash=new Map;persistedHashes=new Set;dirty=!1;constructor(e){this.cacheDir=e.cacheDir,this.vecDir=e.cacheDir?join(e.cacheDir,VEC_SUBDIR):null,this.manifestPath=e.cacheDir?join(e.cacheDir,MANIFEST_NAME):null,this.providerId=e.providerId,this.modelId=e.modelId,this.dims=e.dims,this.chunkConfigId=e.chunkConfigId}async init(){if(!this.cacheDir||!this.manifestPath||!this.vecDir)return;let e=null;try{existsSync(this.manifestPath)&&(e=JSON.parse(await readFile$1(this.manifestPath,`utf-8`)))}catch(t){log$14.warn({err:t instanceof Error?t.message:String(t)},`[embeddings] unreadable cache manifest — rebuilding`),e=null}if(!(e!==null&&e.schemaVersion===MANIFEST_SCHEMA_VERSION&&e.providerId===this.providerId&&e.modelId===this.modelId&&e.dims===this.dims&&e.chunkConfigId===this.chunkConfigId)){e!==null&&log$14.info({hadModel:e.modelId,wantModel:this.modelId},`[embeddings] cache identity changed (provider/model/dims/chunking) — invalidating`),this.wipeDisk();return}if(e){for(let[t,s]of Object.entries(e.entries))if(s?.contentHash&&(this.entries.set(t,{contentHash:s.contentHash,mtimeMs:s.mtimeMs??0}),!this.vectorsByHash.has(s.contentHash)))try{let e=join(this.vecDir,`${s.contentHash}.bin`);if(existsSync(e)){let t=await readFile$1(e);this.vectorsByHash.set(s.contentHash,deserializeVectors(t,this.dims)),this.persistedHashes.add(s.contentHash)}}catch(e){log$14.warn({hash:s.contentHash,err:e instanceof Error?e.message:String(e)},`[embeddings] corrupt vector blob — will re-embed`)}}}isFresh(e,t){let s=this.entries.get(e);return s!==void 0&&s.mtimeMs===t&&this.vectorsByHash.has(s.contentHash)}link(e,t,s){if(!this.vectorsByHash.has(t))return!1;let g=this.entries.get(e);return(!g||g.contentHash!==t||g.mtimeMs!==s)&&(this.dirty=!0),this.entries.set(e,{contentHash:t,mtimeMs:s}),!0}store(e,t,s,g){this.vectorsByHash.set(t,g),this.entries.set(e,{contentHash:t,mtimeMs:s}),this.dirty=!0}getVectors(e){let t=this.entries.get(e);if(t)return this.vectorsByHash.get(t.contentHash)}get embeddedCount(){let e=0;for(let t of this.entries.values()){let s=this.vectorsByHash.get(t.contentHash);s&&s.length>0&&(e+=1)}return e}retain(e){for(let t of this.entries.keys())e.has(t)||(this.entries.delete(t),this.dirty=!0);let t=new Set;for(let e of this.entries.values())t.add(e.contentHash);for(let e of this.vectorsByHash.keys())t.has(e)||this.vectorsByHash.delete(e)}clearMemory(){this.entries.clear(),this.vectorsByHash.clear(),this.persistedHashes.clear(),this.dirty=!1}async persist(){if(!(!this.cacheDir||!this.manifestPath||!this.vecDir)&&this.dirty)try{await tracedMkdir(this.vecDir,{recursive:!0});let e=new Set;for(let t of this.entries.values())e.add(t.contentHash);for(let t of e){if(this.persistedHashes.has(t))continue;let e=this.vectorsByHash.get(t);e&&(await tracedWriteFile(join(this.vecDir,`${t}.bin`),serializeVectors(e)),this.persistedHashes.add(t))}let t={schemaVersion:MANIFEST_SCHEMA_VERSION,providerId:this.providerId,modelId:this.modelId,dims:this.dims,chunkConfigId:this.chunkConfigId,entries:Object.fromEntries(this.entries)},s=`${this.manifestPath}.tmp`;await tracedWriteFile(s,JSON.stringify(t)),await tracedRename(s,this.manifestPath);for(let t of readdirSync(this.vecDir)){if(!t.endsWith(`.bin`))continue;let s=t.slice(0,-4);e.has(s)||(tracedUnlinkSync(join(this.vecDir,t)),this.persistedHashes.delete(s))}this.dirty=!1}catch(e){log$14.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] failed to persist vector cache`)}}wipeDisk(){if(this.cacheDir)try{tracedRmSync(this.cacheDir,{recursive:!0,force:!0})}catch(e){log$14.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] failed to wipe stale cache`)}}};const log$13=getLogger(`embeddings`);function errMsg(e){return e instanceof Error?e.message:String(e)}const EMBED_BATCH_CHUNK_LIMIT=96,MAX_CONSECUTIVE_EMBED_FAILURES=5;var SemanticSearchService=class{loadEmbedder;cacheDir;enabled;providerFingerprint;capable=!1;ready=!1;embedder=null;cache=null;warmPromise=null;embedChain=Promise.resolve();queuedDocs=null;constructor(e){this.loadEmbedder=e.loadEmbedder,this.cacheDir=e.cacheDir,this.enabled=e.enabled??!1,this.providerFingerprint=e.providerFingerprint??``}isEnabled(){return this.enabled}getStatus(){return{enabled:this.enabled,capable:this.capable,ready:this.ready,embeddedCount:this.cache?.embeddedCount??0}}applyConfig(e){e.providerFingerprint!==this.providerFingerprint&&(this.providerFingerprint=e.providerFingerprint,this.resetWarm()),e.enabled!==this.enabled&&(this.enabled=e.enabled,e.enabled||(this.cache?.clearMemory(),this.resetWarm()))}resetWarm(){this.warmPromise=null,this.ready=!1,this.capable=!1,this.embedder=null,this.cache=null}ensureWarm(){return!this.enabled||this.ready?Promise.resolve():(this.warmPromise||=this.warm(),this.warmPromise)}async warm(){try{let e=await this.loadEmbedder();if(!e){this.capable=!1,this.ready=!0,log$13.info({},`[embeddings] no embeddings key configured — semantic search degrades to lexical`);return}this.embedder=e,this.cache=new VectorCache({cacheDir:this.cacheDir,providerId:e.providerId,modelId:e.modelId,dims:e.dims,chunkConfigId:CHUNK_CONFIG_ID}),await this.cache.init(),this.capable=!0,this.ready=!0}catch(e){this.capable=!1,this.ready=!0,log$13.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] warm failed`)}}embedCorpus(e){return this.enabled?(this.queuedDocs=e,this.embedChain=this.embedChain.then(async()=>{let e=this.queuedDocs;if(e){this.queuedDocs=null;try{await this.runEmbedPass(e)}catch(e){log$13.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] embed pass failed`)}}}),this.embedChain):Promise.resolve()}async runEmbedPass(e){if(await this.ensureWarm(),!this.enabled||!this.embedder||!this.cache)return;let t=this.cache,s=this.embedder,g=e.filter(e=>e.kind===`page`),S=new Set(g.map(e=>e.id)),w=[];for(let e of g){if(!this.enabled)return;let s=e.modifiedTs;if(t.isFresh(e.id,s))continue;let g=hashContent(e.content);t.link(e.id,g,s)||w.push({doc:e,contentHash:g,chunks:chunkDocument(e.content)})}let E=0,D=(e,s)=>{t.store(e.doc.id,e.contentHash,e.doc.modifiedTs,s)},O=async e=>{let t=e.flatMap(e=>e.chunks);try{let g=t.length?await s.embed(t,{role:`document`}):[],S=0;for(let t of e)D(t,g.slice(S,S+t.chunks.length)),S+=t.chunks.length;return E=0,!0}catch(t){if(e.length===1)return log$13.warn({docId:e[0].doc.id,err:errMsg(t)},`[embeddings] failed to embed document`),E+=1,E<MAX_CONSECUTIVE_EMBED_FAILURES;for(let t of e){if(!this.enabled)return!1;try{D(t,t.chunks.length?await s.embed(t.chunks,{role:`document`}):[]),E=0}catch(e){if(log$13.warn({docId:t.doc.id,err:errMsg(e)},`[embeddings] failed to embed document`),E+=1,E>=MAX_CONSECUTIVE_EMBED_FAILURES)return!1}}return!0}},k=[],j=0;for(let e of w){if(!this.enabled)break;if(k.push(e),j+=Math.max(1,e.chunks.length),j>=EMBED_BATCH_CHUNK_LIMIT){let e=await O(k);if(k=[],j=0,!e)break}}k.length>0&&this.enabled&&await O(k),!(!this.enabled||this.cache!==t)&&(t.retain(S),await t.persist())}async queryScores(e,t){if(!this.enabled||!this.capable||!this.ready||!this.embedder||!this.cache||this.cache.embeddedCount===0)return null;let s=e.trim();if(!s)return null;let g;try{[g]=await this.embedder.embed([s],{role:`query`})}catch(e){return log$13.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] query embed failed — degrading to lexical`),null}if(!g)return null;let S=new Map;for(let e of t){let t=this.cache.getVectors(e.id);if(!t||t.length===0)continue;let s=-1/0;for(let e of t){let t=cosineSimilarity(g,e);t>s&&(s=t)}s>-1/0&&S.set(e.id,s)}return S}};const log$12=()=>getLogger(`http`);function successResponse(e,t,s,g,S={}){if(e.headersSent||e.writableEnded||e.destroyed){log$12().error({event:`api.success.double-write`,status:t,handler:S.handler},`successResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}});return}let w=s.safeParse(g);if(!w.success){log$12().error({event:`api.success.malformed-body`,issues:w.error.issues,bodyKeys:typeof g==`object`&&g?Object.keys(g):null,handler:S.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler});return}let E;try{E=JSON.stringify(w.data)}catch(s){log$12().error({event:`api.success.unserializable-body`,bodyKeys:typeof w.data==`object`&&w.data!==null?Object.keys(w.data):null,handler:S.handler,originalStatus:t,err:s},`successResponse parsed body is not JSON-serializable — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler});return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(E)}const INSTALLED_AGENTS_SCHEMES=[`claude`,`codex`,`cursor`],INSTALLED_AGENTS_PROBE_TIMEOUT_MS=2e3,MACOS_APP_NAMES={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function createInstalledAgentsProbe(e){let t=new Map,s=e.now??Date.now,g=e.ttlMs??6e4;async function S(S){let w=t.get(S);if(w?.status===`resolved`&&w.expiresAt>s())return w.installed;if(w?.status===`inflight`)return w.promise;let E=(async()=>{try{let w=await e.probe(S);return t.set(S,{status:`resolved`,installed:w,expiresAt:s()+g}),w}catch{return t.set(S,{status:`resolved`,installed:!1,expiresAt:s()+g}),!1}})();return t.set(S,{status:`inflight`,promise:E}),E}async function w(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await S(e)]));return Object.fromEntries(e)}return{probeAll:w,probeWithCache:S}}function isLocalWebHost(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return isLoopbackHostname(e)}catch{}let s=e.headers.origin;if(typeof s==`string`&&s.length>0)try{return isLoopbackHostname(new URL(s).hostname)}catch{return!1}return!0}function isLoopbackHostname(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function handleInstalledAgents(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{successResponse(t,200,InstalledAgentsSuccessSchema,isLocalWebHost(e)?await s():Object.fromEntries(INSTALLED_AGENTS_SCHEMES.map(e=>[e,!0])),{handler:`installed-agents`})}catch(e){console.error(`[installed-agents]`,e),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function createOsProbe(e,t=execFile){return s=>e===`darwin`?probeMacOs(s,t):e===`win32`?probeWindows(s,t):probeLinux(s,t)}function probeMacOs(e,t){let s=MACOS_APP_NAMES[e];function g(e){return new Promise(s=>{t(`osascript`,[`-e`,`id of app "${e}"`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}return(async()=>{for(let e of s)if(await g(e))return!0;return!1})()}function probeWindows(e,t){return new Promise(s=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},e=>{s(!e)})})}function probeLinux(e,t){return new Promise(s=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}const MAX_BODY_BYTES=1048576,REQUEST_BODY_TIMEOUT_MS=3e4;function readRequestBody(e){return readBoundedJsonBody(e,{maxBytes:MAX_BODY_BYTES,timeoutMs:REQUEST_BODY_TIMEOUT_MS})}async function readBoundedJsonBody(e,t){let s=[],g=0,S=AbortSignal.timeout(t.timeoutMs),w=()=>e.destroy(new RequestBodyTimeoutError(t.timeoutMs));S.addEventListener(`abort`,w,{once:!0});try{for await(let S of e){if(g+=S.length,g>t.maxBytes)throw new PayloadTooLargeError(t.maxBytes);s.push(S)}return Buffer.concat(s)}finally{S.removeEventListener(`abort`,w)}}var PayloadTooLargeError=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${formatBytes(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},RequestBodyTimeoutError=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function formatBytes(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function validateBody(e,t,s,g={}){let S=e.safeParse(t);if(S.success)return{ok:!0,value:S.data};let w=S.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return errorResponse(s,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:g.handler,detail:w}),{ok:!1}}function withValidation(e,t,s={}){return async(g,S)=>{if(s.method!==void 0&&g.method!==s.method){errorResponse(S,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:s.handler,extraHeaders:{Allow:s.method}});return}if(s.preBodyGate!==void 0&&!s.preBodyGate(g,S)){!S.headersSent&&!S.writableEnded&&!S.destroyed&&errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:s.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(s.skipBodyParse){let w=validateBody(e,{},S,s);if(!w.ok)return;await t(g,S,w.value);return}let w;try{w=await readRequestBody(g)}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(S,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:s.handler,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(S,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:s.handler,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:s.handler,cause:e});return}let E;try{E=w.length===0?{}:JSON.parse(w.toString(`utf8`))}catch(e){errorResponse(S,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:s.handler,cause:e});return}let D=validateBody(e,E,S,s);D.ok&&await t(g,S,D.value)}}function classifySpawnError(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function spawnDetached(e,t,s){return new Promise(g=>{let S=!1,w=e=>{S||(S=!0,g(e))},E=setTimeout(()=>w({ok:!1,reason:`timeout`}),s);try{let s=spawn(e,[...t],{detached:!0,stdio:`ignore`,shell:!1});s.once(`error`,e=>{clearTimeout(E),w(classifySpawnError(e))}),s.once(`spawn`,()=>{if(!S){try{s.unref()}catch{}clearTimeout(E),w({ok:!0})}})}catch(e){console.warn(`[spawn-detached] synchronous spawn throw:`,e),clearTimeout(E),w(classifySpawnError(e))}})}const SPAWN_CURSOR_WHICH_TIMEOUT_MS=500,SPAWN_CURSOR_SPAWN_TIMEOUT_MS=2e3,SPAWN_CURSOR_MAX_BODY_BYTES=4*1024,SPAWN_CURSOR_BODY_READ_TIMEOUT_MS=5e3,HANDLER$1=`spawn-cursor`;function assertNeverSpawnReason(e){throw Error(`Unhandled spawn-cursor outcome.reason: ${String(e)}`)}async function handleSpawnCursor(e,t,s){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER$1,extraHeaders:{Allow:`POST`}});return}let g;try{g=await readBoundedJsonBody(e,{maxBytes:SPAWN_CURSOR_MAX_BODY_BYTES,timeoutMs:SPAWN_CURSOR_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER$1,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER$1,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER$1,cause:e});return}let S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER$1,cause:e});return}let w=typeof S.path==`string`?S.path:``;if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:HANDLER$1});return}if(!isPathWithinDir(w,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return}let E=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(SPAWN_CURSOR_WHICH_TIMEOUT_MS);if(!E){errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return}let D=resolveCursorSpawnInvocation(E,w,s.platform),O=await(s.spawnDetached??spawnDetached)(D.exec,D.args,SPAWN_CURSOR_SPAWN_TIMEOUT_MS);if(O.ok){successResponse(t,200,SpawnCursorSuccessSchema,{},{handler:HANDLER$1});return}switch(O.reason){case`not-installed`:errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return;case`timeout`:errorResponse(t,504,`urn:ok:error:cursor-spawn-timeout`,`Cursor spawn exceeded the deadline.`,{handler:HANDLER$1});return;case`spawn-error`:errorResponse(t,502,`urn:ok:error:cursor-spawn-failed`,`Cursor spawn failed.`,{handler:HANDLER$1});return;case`invalid-path`:errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return;default:return assertNeverSpawnReason(O.reason)}}const CURSOR_BUNDLE_PATHS_BY_PLATFORM={darwin:[()=>`/Applications/Cursor.app/Contents/Resources/app/bin/cursor`,e=>`${e}/Applications/Cursor.app/Contents/Resources/app/bin/cursor`],win32:[e=>`${e}\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd`,()=>`C:\\Program Files\\Cursor\\resources\\app\\bin\\cursor.cmd`]};async function resolveCursorBinaryDefault(e){let t=CURSOR_BUNDLE_PATHS_BY_PLATFORM[process.platform];if(t&&t.length>0){let e=homedir();for(let s of t){let t=s(e);try{return await access(t,constants$1.X_OK),t}catch(e){let s=e?.code;s!==`ENOENT`&&s!==`EACCES`&&s!==`EPERM`&&console.warn(`[spawn-cursor] unexpected fs.access error on bundle probe:`,s,t)}}}return new Promise(t=>{execFile(process.platform===`win32`?`where`:`which`,[`cursor`],{timeout:e,encoding:`utf-8`},(e,s)=>{if(e){t(null);return}let g=s.split(/\r?\n/)[0]?.trim();t(g&&g.length>0?g:null)})})}function resolveCursorSpawnInvocation(e,t,s){return s===`darwin`&&/\.app\/?$/.test(e)?{exec:`/usr/bin/open`,args:[`-a`,e.replace(/\/$/,``),t]}:s===`win32`&&/\.(cmd|bat)$/i.test(e)?{exec:process.env.ComSpec||`cmd.exe`,args:[`/d`,`/c`,e,t]}:{exec:e,args:[t]}}function isPathWithinDir(e,t,s){if(!e||typeof e!=`string`||e.includes(`\0`)||!t||typeof t!=`string`)return!1;if(s===`win32`){if(!/^([a-zA-Z]:[\\/]|\\\\)/.test(e)||!/^([a-zA-Z]:[\\/]|\\\\)/.test(t))return!1}else if(!e.startsWith(`/`)||!t.startsWith(`/`))return!1;let g=s===`win32`?win32:posix;try{let S=g.resolve(e),w=g.resolve(t);if(s===`win32`){let e=g.parse(S).root.toLowerCase(),t=g.parse(w).root.toLowerCase();if(!e||!t||e!==t)return!1}if(S===w)return!0;let E=g.relative(w,S);return E===``||E===`.`?!0:!(E===`..`||E.startsWith(`..${g.sep}`)||s===`win32`&&(/^[a-zA-Z]:[\\/]/.test(E)||E.startsWith(`\\\\`))||s!==`win32`&&E.startsWith(`/`))}catch(e){return console.warn(`[spawn-cursor] unexpected path-resolution error:`,e),!1}}const HANDLER=`handoff`,HANDOFF_MAX_BODY_BYTES=4*1024,HANDOFF_BODY_READ_TIMEOUT_MS=5e3,SPAWN_TIMEOUT_MS$1=2e3,WHICH_TIMEOUT_MS=500,QUIT_SETTLE_MS=3e3,APP_BUNDLE_SETTLE_MS=5e3,CURSOR_SETTLE_MS=1500,RECIPES={"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,probeScheme:`codex`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}},TARGET_VALUES=Object.keys(RECIPES),HandoffRequestSchema=object$1({target:_enum(TARGET_VALUES),url:string().min(1).max(4096),workspacePath:string().optional()}),HandoffSuccessSchema=object$1({}).loose();function defaultSleep(e){return new Promise(t=>setTimeout(t,e))}async function handleHandoffDispatch(e,t,s){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER,extraHeaders:{Allow:`POST`}});return}let g;try{g=await readBoundedJsonBody(e,{maxBytes:HANDOFF_MAX_BODY_BYTES,timeoutMs:HANDOFF_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER,cause:e});return}let S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER,cause:e});return}let w=HandoffRequestSchema.safeParse(S);if(!w.success){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid request body.`,{handler:HANDLER});return}let{target:E,url:D,workspacePath:O}=w.data,k=RECIPES[E];if(!D.startsWith(k.urlScheme)){errorResponse(t,400,`urn:ok:error:invalid-request`,`URL scheme must be ${k.urlScheme} for target ${E}.`,{handler:HANDLER});return}let j=s.sleep??defaultSleep,F=s.spawnDetached??spawnDetached,L=s.isSchemeRegistered??createOsProbe(s.platform);if(k.type===`app-bundle`){if(s.platform===`darwin`){k.quitFirst&&(await F(`/usr/bin/osascript`,[`-e`,`tell application "${k.appName}" to quit`],SPAWN_TIMEOUT_MS$1).catch(()=>void 0),await j(QUIT_SETTLE_MS));let e=await F(`/usr/bin/open`,[`-a`,k.appName],SPAWN_TIMEOUT_MS$1);if(!e.ok){emitSpawnFailure(t,E,e.reason);return}await j(APP_BUNDLE_SETTLE_MS)}else if(!await L(k.probeScheme)){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:HANDLER,extensions:{target:E}});return}let e=resolveUrlOpenInvocation(D,s.platform),g=await F(e.exec,e.args,SPAWN_TIMEOUT_MS$1);if(!g.ok){emitSpawnFailure(t,E,g.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER});return}if(!O){errorResponse(t,400,`urn:ok:error:invalid-request`,`workspacePath is required for cursor handoff.`,{handler:HANDLER});return}if(!isPathWithinDir(O,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER});return}let B=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(WHICH_TIMEOUT_MS);if(!B){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER,extensions:{target:`cursor`}});return}let H=resolveCursorSpawnInvocation(B,O,s.platform),q=await F(H.exec,H.args,SPAWN_TIMEOUT_MS$1);if(!q.ok){emitSpawnFailure(t,E,q.reason);return}await j(CURSOR_SETTLE_MS);let ee=resolveUrlOpenInvocation(D,s.platform),J=await F(ee.exec,ee.args,SPAWN_TIMEOUT_MS$1);if(!J.ok){emitSpawnFailure(t,E,J.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER})}function resolveUrlOpenInvocation(e,t){return t===`darwin`?{exec:`/usr/bin/open`,args:[e]}:t===`win32`?{exec:`rundll32.exe`,args:[`url.dll,FileProtocolHandler`,e]}:{exec:`xdg-open`,args:[e]}}function emitSpawnFailure(e,t,s){switch(s){case`not-installed`:errorResponse(e,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:HANDLER,extensions:{target:t}});return;case`timeout`:errorResponse(e,504,`urn:ok:error:handoff-spawn-timeout`,`Handoff spawn exceeded the deadline.`,{handler:HANDLER,extensions:{target:t}});return;case`spawn-error`:errorResponse(e,502,`urn:ok:error:handoff-spawn-failed`,`Handoff spawn failed.`,{handler:HANDLER,extensions:{target:t}});return;default:assertNeverReason(s)}}function assertNeverReason(e){throw Error(`Unhandled spawn reason: ${String(e)}`)}const FIXED_HUB_BASENAMES=[`INDEX`,`README`,`REPORT`,`SPEC`],MAX_CANDIDATES=3;function findHubCandidates(e,t){let s=[],g=new Set,S=t=>{!t||g.has(t)||t!==e&&(g.add(t),s.push(t))},w=buildLowerDocNameIndex(t),E=parentFolder(e);for(;;){for(let e of FIXED_HUB_BASENAMES)if(S(lookup$1(t,w,joinDocName(E,e))),s.length>=MAX_CANDIDATES)return s;let e=E===``?null:basename$1(E);if(e&&(S(lookup$1(t,w,joinDocName(E,e))),s.length>=MAX_CANDIDATES))return s;if(E===``)break;E=parentFolder(E)}return s}function lookup$1(e,t,s){return e.has(s)?s:t.get(s.toLowerCase())??null}function buildLowerDocNameIndex(e){let t=new Map;for(let s of e.keys()){let e=s.toLowerCase();t.has(e)||t.set(e,s)}return t}function parentFolder(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function basename$1(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function joinDocName(e,t){return e===``?t:`${e}/${t}`}const logger$4=getLogger(`installed-skills-marker`),TRACED_FS_ADAPTER={writeFile:(e,t,s)=>tracedWriteFile(e,t,s),rename:(e,t)=>tracedRename(e,t)};function installedSkillsPath(e){return join(e,...INSTALLED_SKILLS_REL)}const markerWriteChains=new Map;function withMarkerLock(e,t){let s=installedSkillsPath(e),g=(markerWriteChains.get(s)??Promise.resolve()).then(t,t);return markerWriteChains.set(s,g.then(()=>void 0,()=>void 0)),g}function readInstalledSkills(e){let t=installedSkillsPath(e);if(!existsSync(t))return emptyInstalledSkills();try{return parseInstalledSkills(readFileSync(t,`utf-8`))??emptyInstalledSkills()}catch(e){return logger$4.warn({err:e,path:t},`installed-skills marker unreadable`),emptyInstalledSkills()}}async function writeInstalledSkills(e,t){let s=InstalledSkillsSchema.safeParse(t);if(!s.success)throw Error(`Refusing to write invalid installed-skills marker: ${s.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let g=installedSkillsPath(e);await tracedMkdir(dirname(g),{recursive:!0}),await atomicWriteFile(g,`${JSON.stringify(s.data,null,2)}\n`,{fs:TRACED_FS_ADAPTER})}async function recordSkillInstall(e,t,s){return withMarkerLock(e,async()=>{let g=readInstalledSkills(e);await writeInstalledSkills(e,{...g,skills:{...g.skills,[t]:s}})})}async function removeSkillInstall(e,t){return withMarkerLock(e,async()=>{let s=readInstalledSkills(e),g=s.skills[t]??null;if(g===null)return null;let{[t]:S,...w}=s.skills;return await writeInstalledSkills(e,{...s,skills:w}),g})}const log$11=getLogger(`mermaid-validator`),MAX_FENCE_BYTES=1e5,MAX_FENCE_LINES=2e3,MAX_FENCES_PARSED=20,TOTAL_PARSE_BUDGET_MS=2e3,MAX_WARNINGS=10,MAX_MESSAGE_CHARS=500,MAX_FIRST_LINE_CHARS=200;let initPromise=null;function extractMermaidFences(e){let t=[],s=e.split(`
|
|
825
|
+
`,t));g>E+Math.floor(s/2)&&(t=g)}let S=e.slice(E,t).trim();if(S&&w.push(S),t>=e.length)break;let D=t-g;E=D>E?D:t}return w}const log$14=getLogger(`embeddings`),MANIFEST_SCHEMA_VERSION=1,VEC_SUBDIR=`vec`,MANIFEST_NAME=`manifest.json`;function hashContent(e){return createHash(`sha256`).update(e,`utf-8`).digest(`hex`)}function serializeVectors(e){let t=0;for(let s of e)t+=s.length;let s=new Float32Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}function deserializeVectors(e,t){let s=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),g=new Float32Array(s);if(g.length%t!==0)throw Error(`vector blob length ${g.length} is not a multiple of dims ${t}`);let S=[];for(let e=0;e<g.length;e+=t)S.push(g.slice(e,e+t));return S}var VectorCache=class{cacheDir;vecDir;manifestPath;providerId;modelId;dims;chunkConfigId;entries=new Map;vectorsByHash=new Map;persistedHashes=new Set;dirty=!1;constructor(e){this.cacheDir=e.cacheDir,this.vecDir=e.cacheDir?join(e.cacheDir,VEC_SUBDIR):null,this.manifestPath=e.cacheDir?join(e.cacheDir,MANIFEST_NAME):null,this.providerId=e.providerId,this.modelId=e.modelId,this.dims=e.dims,this.chunkConfigId=e.chunkConfigId}async init(){if(!this.cacheDir||!this.manifestPath||!this.vecDir)return;let e=null;try{existsSync(this.manifestPath)&&(e=JSON.parse(await readFile$1(this.manifestPath,`utf-8`)))}catch(t){log$14.warn({err:t instanceof Error?t.message:String(t)},`[embeddings] unreadable cache manifest — rebuilding`),e=null}if(!(e!==null&&e.schemaVersion===MANIFEST_SCHEMA_VERSION&&e.providerId===this.providerId&&e.modelId===this.modelId&&e.dims===this.dims&&e.chunkConfigId===this.chunkConfigId)){e!==null&&log$14.info({hadModel:e.modelId,wantModel:this.modelId},`[embeddings] cache identity changed (provider/model/dims/chunking) — invalidating`),this.wipeDisk();return}if(e){for(let[t,s]of Object.entries(e.entries))if(s?.contentHash&&(this.entries.set(t,{contentHash:s.contentHash,mtimeMs:s.mtimeMs??0}),!this.vectorsByHash.has(s.contentHash)))try{let e=join(this.vecDir,`${s.contentHash}.bin`);if(existsSync(e)){let t=await readFile$1(e);this.vectorsByHash.set(s.contentHash,deserializeVectors(t,this.dims)),this.persistedHashes.add(s.contentHash)}}catch(e){log$14.warn({hash:s.contentHash,err:e instanceof Error?e.message:String(e)},`[embeddings] corrupt vector blob — will re-embed`)}}}isFresh(e,t){let s=this.entries.get(e);return s!==void 0&&s.mtimeMs===t&&this.vectorsByHash.has(s.contentHash)}link(e,t,s){if(!this.vectorsByHash.has(t))return!1;let g=this.entries.get(e);return(!g||g.contentHash!==t||g.mtimeMs!==s)&&(this.dirty=!0),this.entries.set(e,{contentHash:t,mtimeMs:s}),!0}store(e,t,s,g){this.vectorsByHash.set(t,g),this.entries.set(e,{contentHash:t,mtimeMs:s}),this.dirty=!0}getVectors(e){let t=this.entries.get(e);if(t)return this.vectorsByHash.get(t.contentHash)}get embeddedCount(){let e=0;for(let t of this.entries.values()){let s=this.vectorsByHash.get(t.contentHash);s&&s.length>0&&(e+=1)}return e}retain(e){for(let t of this.entries.keys())e.has(t)||(this.entries.delete(t),this.dirty=!0);let t=new Set;for(let e of this.entries.values())t.add(e.contentHash);for(let e of this.vectorsByHash.keys())t.has(e)||this.vectorsByHash.delete(e)}clearMemory(){this.entries.clear(),this.vectorsByHash.clear(),this.persistedHashes.clear(),this.dirty=!1}async persist(){if(!(!this.cacheDir||!this.manifestPath||!this.vecDir)&&this.dirty)try{await tracedMkdir(this.vecDir,{recursive:!0});let e=new Set;for(let t of this.entries.values())e.add(t.contentHash);for(let t of e){if(this.persistedHashes.has(t))continue;let e=this.vectorsByHash.get(t);e&&(await tracedWriteFile(join(this.vecDir,`${t}.bin`),serializeVectors(e)),this.persistedHashes.add(t))}let t={schemaVersion:MANIFEST_SCHEMA_VERSION,providerId:this.providerId,modelId:this.modelId,dims:this.dims,chunkConfigId:this.chunkConfigId,entries:Object.fromEntries(this.entries)},s=`${this.manifestPath}.tmp`;await tracedWriteFile(s,JSON.stringify(t)),await tracedRename(s,this.manifestPath);for(let t of readdirSync(this.vecDir)){if(!t.endsWith(`.bin`))continue;let s=t.slice(0,-4);e.has(s)||(tracedUnlinkSync(join(this.vecDir,t)),this.persistedHashes.delete(s))}this.dirty=!1}catch(e){log$14.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] failed to persist vector cache`)}}wipeDisk(){if(this.cacheDir)try{tracedRmSync(this.cacheDir,{recursive:!0,force:!0})}catch(e){log$14.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] failed to wipe stale cache`)}}};const log$13=getLogger(`embeddings`);function errMsg(e){return e instanceof Error?e.message:String(e)}const EMBED_BATCH_CHUNK_LIMIT=96,MAX_CONSECUTIVE_EMBED_FAILURES=5;var SemanticSearchService=class{loadEmbedder;cacheDir;enabled;providerFingerprint;capable=!1;ready=!1;embedder=null;cache=null;warmPromise=null;embedChain=Promise.resolve();queuedDocs=null;constructor(e){this.loadEmbedder=e.loadEmbedder,this.cacheDir=e.cacheDir,this.enabled=e.enabled??!1,this.providerFingerprint=e.providerFingerprint??``}isEnabled(){return this.enabled}getStatus(){return{enabled:this.enabled,capable:this.capable,ready:this.ready,embeddedCount:this.cache?.embeddedCount??0}}applyConfig(e){e.providerFingerprint!==this.providerFingerprint&&(this.providerFingerprint=e.providerFingerprint,this.resetWarm()),e.enabled!==this.enabled&&(this.enabled=e.enabled,e.enabled||(this.cache?.clearMemory(),this.resetWarm()))}resetWarm(){this.warmPromise=null,this.ready=!1,this.capable=!1,this.embedder=null,this.cache=null}ensureWarm(){return!this.enabled||this.ready?Promise.resolve():(this.warmPromise||=this.warm(),this.warmPromise)}async warm(){try{let e=await this.loadEmbedder();if(!e){this.capable=!1,this.ready=!0,log$13.info({},`[embeddings] no embeddings key configured — semantic search degrades to lexical`);return}this.embedder=e,this.cache=new VectorCache({cacheDir:this.cacheDir,providerId:e.providerId,modelId:e.modelId,dims:e.dims,chunkConfigId:CHUNK_CONFIG_ID}),await this.cache.init(),this.capable=!0,this.ready=!0}catch(e){this.capable=!1,this.ready=!0,log$13.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] warm failed`)}}embedCorpus(e){return this.enabled?(this.queuedDocs=e,this.embedChain=this.embedChain.then(async()=>{let e=this.queuedDocs;if(e){this.queuedDocs=null;try{await this.runEmbedPass(e)}catch(e){log$13.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] embed pass failed`)}}}),this.embedChain):Promise.resolve()}async runEmbedPass(e){if(await this.ensureWarm(),!this.enabled||!this.embedder||!this.cache)return;let t=this.cache,s=this.embedder,g=e.filter(e=>e.kind===`page`),S=new Set(g.map(e=>e.id)),w=[];for(let e of g){if(!this.enabled)return;let s=e.modifiedTs;if(t.isFresh(e.id,s))continue;let g=hashContent(e.content);t.link(e.id,g,s)||w.push({doc:e,contentHash:g,chunks:chunkDocument(e.content)})}let E=0,D=(e,s)=>{t.store(e.doc.id,e.contentHash,e.doc.modifiedTs,s)},O=async e=>{let t=e.flatMap(e=>e.chunks);try{let g=t.length?await s.embed(t,{role:`document`}):[],S=0;for(let t of e)D(t,g.slice(S,S+t.chunks.length)),S+=t.chunks.length;return E=0,!0}catch(t){if(e.length===1)return log$13.warn({docId:e[0].doc.id,err:errMsg(t)},`[embeddings] failed to embed document`),E+=1,E<MAX_CONSECUTIVE_EMBED_FAILURES;for(let t of e){if(!this.enabled)return!1;try{D(t,t.chunks.length?await s.embed(t.chunks,{role:`document`}):[]),E=0}catch(e){if(log$13.warn({docId:t.doc.id,err:errMsg(e)},`[embeddings] failed to embed document`),E+=1,E>=MAX_CONSECUTIVE_EMBED_FAILURES)return!1}}return!0}},k=[],j=0;for(let e of w){if(!this.enabled)break;if(k.push(e),j+=Math.max(1,e.chunks.length),j>=EMBED_BATCH_CHUNK_LIMIT){let e=await O(k);if(k=[],j=0,!e)break}}k.length>0&&this.enabled&&await O(k),!(!this.enabled||this.cache!==t)&&(t.retain(S),await t.persist())}async queryScores(e,t){if(!this.enabled||!this.capable||!this.ready||!this.embedder||!this.cache||this.cache.embeddedCount===0)return null;let s=e.trim();if(!s)return null;let g;try{[g]=await this.embedder.embed([s],{role:`query`})}catch(e){return log$13.warn({err:e instanceof Error?e.message:String(e)},`[embeddings] query embed failed — degrading to lexical`),null}if(!g)return null;let S=new Map;for(let e of t){let t=this.cache.getVectors(e.id);if(!t||t.length===0)continue;let s=-1/0;for(let e of t){let t=cosineSimilarity(g,e);t>s&&(s=t)}s>-1/0&&S.set(e.id,s)}return S}};const log$12=()=>getLogger(`http`);function successResponse(e,t,s,g,S={}){if(e.headersSent||e.writableEnded||e.destroyed){log$12().error({event:`api.success.double-write`,status:t,handler:S.handler},`successResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}});return}let w=s.safeParse(g);if(!w.success){log$12().error({event:`api.success.malformed-body`,issues:w.error.issues,bodyKeys:typeof g==`object`&&g?Object.keys(g):null,handler:S.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler});return}let E;try{E=JSON.stringify(w.data)}catch(s){log$12().error({event:`api.success.unserializable-body`,bodyKeys:typeof w.data==`object`&&w.data!==null?Object.keys(w.data):null,handler:S.handler,originalStatus:t,err:s},`successResponse parsed body is not JSON-serializable — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler});return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(E)}const INSTALLED_AGENTS_SCHEMES=[`claude`,`codex`,`cursor`],INSTALLED_AGENTS_PROBE_TIMEOUT_MS=2e3,MACOS_APP_NAMES={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function createInstalledAgentsProbe(e){let t=new Map,s=e.now??Date.now,g=e.ttlMs??6e4;async function S(S){let w=t.get(S);if(w?.status===`resolved`&&w.expiresAt>s())return w.installed;if(w?.status===`inflight`)return w.promise;let E=(async()=>{try{let w=await e.probe(S);return t.set(S,{status:`resolved`,installed:w,expiresAt:s()+g}),w}catch{return t.set(S,{status:`resolved`,installed:!1,expiresAt:s()+g}),!1}})();return t.set(S,{status:`inflight`,promise:E}),E}async function w(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await S(e)]));return Object.fromEntries(e)}return{probeAll:w,probeWithCache:S}}function isLocalWebHost(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return isLoopbackHostname(e)}catch{}let s=e.headers.origin;if(typeof s==`string`&&s.length>0)try{return isLoopbackHostname(new URL(s).hostname)}catch{return!1}return!0}function isLoopbackHostname(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function handleInstalledAgents(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{successResponse(t,200,InstalledAgentsSuccessSchema,isLocalWebHost(e)?await s():Object.fromEntries(INSTALLED_AGENTS_SCHEMES.map(e=>[e,!0])),{handler:`installed-agents`})}catch(e){console.error(`[installed-agents]`,e),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function createOsProbe(e,t=execFile){return s=>e===`darwin`?probeMacOs(s,t):e===`win32`?probeWindows(s,t):probeLinux(s,t)}function probeMacOs(e,t){let s=MACOS_APP_NAMES[e];function g(e){return new Promise(s=>{t(`osascript`,[`-e`,`id of app "${e}"`],withHiddenWindowsConsole({timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`}),(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}return(async()=>{for(let e of s)if(await g(e))return!0;return!1})()}function probeWindows(e,t){return new Promise(s=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],withHiddenWindowsConsole({timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`}),e=>{s(!e)})})}function probeLinux(e,t){return new Promise(s=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],withHiddenWindowsConsole({timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`}),(e,t)=>{if(e){s(!1);return}s(t.trim().length>0)})})}const MAX_BODY_BYTES=1048576,REQUEST_BODY_TIMEOUT_MS=3e4;function readRequestBody(e){return readBoundedJsonBody(e,{maxBytes:MAX_BODY_BYTES,timeoutMs:REQUEST_BODY_TIMEOUT_MS})}async function readBoundedJsonBody(e,t){let s=[],g=0,S=AbortSignal.timeout(t.timeoutMs),w=()=>e.destroy(new RequestBodyTimeoutError(t.timeoutMs));S.addEventListener(`abort`,w,{once:!0});try{for await(let S of e){if(g+=S.length,g>t.maxBytes)throw new PayloadTooLargeError(t.maxBytes);s.push(S)}return Buffer.concat(s)}finally{S.removeEventListener(`abort`,w)}}var PayloadTooLargeError=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${formatBytes(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},RequestBodyTimeoutError=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function formatBytes(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function validateBody(e,t,s,g={}){let S=e.safeParse(t);if(S.success)return{ok:!0,value:S.data};let w=S.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return errorResponse(s,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:g.handler,detail:w}),{ok:!1}}function withValidation(e,t,s={}){return async(g,S)=>{if(s.method!==void 0&&g.method!==s.method){errorResponse(S,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:s.handler,extraHeaders:{Allow:s.method}});return}if(s.preBodyGate!==void 0&&!s.preBodyGate(g,S)){!S.headersSent&&!S.writableEnded&&!S.destroyed&&errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:s.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(s.skipBodyParse){let w=validateBody(e,{},S,s);if(!w.ok)return;await t(g,S,w.value);return}let w;try{w=await readRequestBody(g)}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(S,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:s.handler,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(S,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:s.handler,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:s.handler,cause:e});return}let E;try{E=w.length===0?{}:JSON.parse(w.toString(`utf8`))}catch(e){errorResponse(S,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:s.handler,cause:e});return}let D=validateBody(e,E,S,s);D.ok&&await t(g,S,D.value)}}const DETACHED_IGNORED_STDIO_OPTIONS={detached:!0,stdio:`ignore`,shell:!1};function classifySpawnError(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function spawnDetached(e,t,s){return new Promise(g=>{let S=!1,w=e=>{S||(S=!0,g(e))},E=setTimeout(()=>w({ok:!1,reason:`timeout`}),s);try{let s=spawn(e,[...t],withHiddenWindowsConsole(DETACHED_IGNORED_STDIO_OPTIONS));s.once(`error`,e=>{clearTimeout(E),w(classifySpawnError(e))}),s.once(`spawn`,()=>{if(!S){try{s.unref()}catch{}clearTimeout(E),w({ok:!0})}})}catch(e){console.warn(`[spawn-detached] synchronous spawn throw:`,e),clearTimeout(E),w(classifySpawnError(e))}})}const SPAWN_CURSOR_WHICH_TIMEOUT_MS=500,SPAWN_CURSOR_SPAWN_TIMEOUT_MS=2e3,SPAWN_CURSOR_MAX_BODY_BYTES=4*1024,SPAWN_CURSOR_BODY_READ_TIMEOUT_MS=5e3,HANDLER$1=`spawn-cursor`;function assertNeverSpawnReason(e){throw Error(`Unhandled spawn-cursor outcome.reason: ${String(e)}`)}async function handleSpawnCursor(e,t,s){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER$1,extraHeaders:{Allow:`POST`}});return}let g;try{g=await readBoundedJsonBody(e,{maxBytes:SPAWN_CURSOR_MAX_BODY_BYTES,timeoutMs:SPAWN_CURSOR_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER$1,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER$1,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER$1,cause:e});return}let S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER$1,cause:e});return}let w=typeof S.path==`string`?S.path:``;if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:HANDLER$1});return}if(!isPathWithinDir(w,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return}let E=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(SPAWN_CURSOR_WHICH_TIMEOUT_MS);if(!E){errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return}let D=resolveCursorSpawnInvocation(E,w,s.platform),O=await(s.spawnDetached??spawnDetached)(D.exec,D.args,SPAWN_CURSOR_SPAWN_TIMEOUT_MS);if(O.ok){successResponse(t,200,SpawnCursorSuccessSchema,{},{handler:HANDLER$1});return}switch(O.reason){case`not-installed`:errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return;case`timeout`:errorResponse(t,504,`urn:ok:error:cursor-spawn-timeout`,`Cursor spawn exceeded the deadline.`,{handler:HANDLER$1});return;case`spawn-error`:errorResponse(t,502,`urn:ok:error:cursor-spawn-failed`,`Cursor spawn failed.`,{handler:HANDLER$1});return;case`invalid-path`:errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return;default:return assertNeverSpawnReason(O.reason)}}const CURSOR_BUNDLE_PATHS_BY_PLATFORM={darwin:[()=>`/Applications/Cursor.app/Contents/Resources/app/bin/cursor`,e=>`${e}/Applications/Cursor.app/Contents/Resources/app/bin/cursor`],win32:[e=>`${e}\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd`,()=>`C:\\Program Files\\Cursor\\resources\\app\\bin\\cursor.cmd`]};async function resolveCursorBinaryDefault(e){let t=CURSOR_BUNDLE_PATHS_BY_PLATFORM[process.platform];if(t&&t.length>0){let e=homedir();for(let s of t){let t=s(e);try{return await access(t,constants$1.X_OK),t}catch(e){let s=e?.code;s!==`ENOENT`&&s!==`EACCES`&&s!==`EPERM`&&console.warn(`[spawn-cursor] unexpected fs.access error on bundle probe:`,s,t)}}}return new Promise(t=>{execFile(process.platform===`win32`?`where`:`which`,[`cursor`],withHiddenWindowsConsole({timeout:e,encoding:`utf-8`}),(e,s)=>{if(e){t(null);return}let g=s.split(/\r?\n/)[0]?.trim();t(g&&g.length>0?g:null)})})}function resolveCursorSpawnInvocation(e,t,s){return s===`darwin`&&/\.app\/?$/.test(e)?{exec:`/usr/bin/open`,args:[`-a`,e.replace(/\/$/,``),t]}:s===`win32`&&/\.(cmd|bat)$/i.test(e)?{exec:process.env.ComSpec||`cmd.exe`,args:[`/d`,`/c`,e,t]}:{exec:e,args:[t]}}function isPathWithinDir(e,t,s){if(!e||typeof e!=`string`||e.includes(`\0`)||!t||typeof t!=`string`)return!1;if(s===`win32`){if(!/^([a-zA-Z]:[\\/]|\\\\)/.test(e)||!/^([a-zA-Z]:[\\/]|\\\\)/.test(t))return!1}else if(!e.startsWith(`/`)||!t.startsWith(`/`))return!1;let g=s===`win32`?win32:posix;try{let S=g.resolve(e),w=g.resolve(t);if(s===`win32`){let e=g.parse(S).root.toLowerCase(),t=g.parse(w).root.toLowerCase();if(!e||!t||e!==t)return!1}if(S===w)return!0;let E=g.relative(w,S);return E===``||E===`.`?!0:!(E===`..`||E.startsWith(`..${g.sep}`)||s===`win32`&&(/^[a-zA-Z]:[\\/]/.test(E)||E.startsWith(`\\\\`))||s!==`win32`&&E.startsWith(`/`))}catch(e){return console.warn(`[spawn-cursor] unexpected path-resolution error:`,e),!1}}const HANDLER=`handoff`,HANDOFF_MAX_BODY_BYTES=4*1024,HANDOFF_BODY_READ_TIMEOUT_MS=5e3,SPAWN_TIMEOUT_MS$1=2e3,WHICH_TIMEOUT_MS=500,QUIT_SETTLE_MS=3e3,APP_BUNDLE_SETTLE_MS=5e3,CURSOR_SETTLE_MS=1500,RECIPES={"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,probeScheme:`claude`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,probeScheme:`codex`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}},TARGET_VALUES=Object.keys(RECIPES),HandoffRequestSchema=object$1({target:_enum(TARGET_VALUES),url:string().min(1).max(4096),workspacePath:string().optional()}),HandoffSuccessSchema=object$1({}).loose();function defaultSleep(e){return new Promise(t=>setTimeout(t,e))}async function handleHandoffDispatch(e,t,s){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER,extraHeaders:{Allow:`POST`}});return}let g;try{g=await readBoundedJsonBody(e,{maxBytes:HANDOFF_MAX_BODY_BYTES,timeoutMs:HANDOFF_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER,cause:e});return}let S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER,cause:e});return}let w=HandoffRequestSchema.safeParse(S);if(!w.success){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid request body.`,{handler:HANDLER});return}let{target:E,url:D,workspacePath:O}=w.data,k=RECIPES[E];if(!D.startsWith(k.urlScheme)){errorResponse(t,400,`urn:ok:error:invalid-request`,`URL scheme must be ${k.urlScheme} for target ${E}.`,{handler:HANDLER});return}let j=s.sleep??defaultSleep,F=s.spawnDetached??spawnDetached,L=s.isSchemeRegistered??createOsProbe(s.platform);if(k.type===`app-bundle`){if(s.platform===`darwin`){k.quitFirst&&(await F(`/usr/bin/osascript`,[`-e`,`tell application "${k.appName}" to quit`],SPAWN_TIMEOUT_MS$1).catch(()=>void 0),await j(QUIT_SETTLE_MS));let e=await F(`/usr/bin/open`,[`-a`,k.appName],SPAWN_TIMEOUT_MS$1);if(!e.ok){emitSpawnFailure(t,E,e.reason);return}await j(APP_BUNDLE_SETTLE_MS)}else if(!await L(k.probeScheme)){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:HANDLER,extensions:{target:E}});return}let e=resolveUrlOpenInvocation(D,s.platform),g=await F(e.exec,e.args,SPAWN_TIMEOUT_MS$1);if(!g.ok){emitSpawnFailure(t,E,g.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER});return}if(!O){errorResponse(t,400,`urn:ok:error:invalid-request`,`workspacePath is required for cursor handoff.`,{handler:HANDLER});return}if(!isPathWithinDir(O,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER});return}let B=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(WHICH_TIMEOUT_MS);if(!B){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER,extensions:{target:`cursor`}});return}let H=resolveCursorSpawnInvocation(B,O,s.platform),q=await F(H.exec,H.args,SPAWN_TIMEOUT_MS$1);if(!q.ok){emitSpawnFailure(t,E,q.reason);return}await j(CURSOR_SETTLE_MS);let ee=resolveUrlOpenInvocation(D,s.platform),J=await F(ee.exec,ee.args,SPAWN_TIMEOUT_MS$1);if(!J.ok){emitSpawnFailure(t,E,J.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER})}function resolveUrlOpenInvocation(e,t){return t===`darwin`?{exec:`/usr/bin/open`,args:[e]}:t===`win32`?{exec:`rundll32.exe`,args:[`url.dll,FileProtocolHandler`,e]}:{exec:`xdg-open`,args:[e]}}function emitSpawnFailure(e,t,s){switch(s){case`not-installed`:errorResponse(e,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:HANDLER,extensions:{target:t}});return;case`timeout`:errorResponse(e,504,`urn:ok:error:handoff-spawn-timeout`,`Handoff spawn exceeded the deadline.`,{handler:HANDLER,extensions:{target:t}});return;case`spawn-error`:errorResponse(e,502,`urn:ok:error:handoff-spawn-failed`,`Handoff spawn failed.`,{handler:HANDLER,extensions:{target:t}});return;default:assertNeverReason(s)}}function assertNeverReason(e){throw Error(`Unhandled spawn reason: ${String(e)}`)}const FIXED_HUB_BASENAMES=[`INDEX`,`README`,`REPORT`,`SPEC`],MAX_CANDIDATES=3;function findHubCandidates(e,t){let s=[],g=new Set,S=t=>{!t||g.has(t)||t!==e&&(g.add(t),s.push(t))},w=buildLowerDocNameIndex(t),E=parentFolder(e);for(;;){for(let e of FIXED_HUB_BASENAMES)if(S(lookup$1(t,w,joinDocName(E,e))),s.length>=MAX_CANDIDATES)return s;let e=E===``?null:basename$1(E);if(e&&(S(lookup$1(t,w,joinDocName(E,e))),s.length>=MAX_CANDIDATES))return s;if(E===``)break;E=parentFolder(E)}return s}function lookup$1(e,t,s){return e.has(s)?s:t.get(s.toLowerCase())??null}function buildLowerDocNameIndex(e){let t=new Map;for(let s of e.keys()){let e=s.toLowerCase();t.has(e)||t.set(e,s)}return t}function parentFolder(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function basename$1(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function joinDocName(e,t){return e===``?t:`${e}/${t}`}const logger$4=getLogger(`installed-skills-marker`),TRACED_FS_ADAPTER={writeFile:(e,t,s)=>tracedWriteFile(e,t,s),rename:(e,t)=>tracedRename(e,t)};function installedSkillsPath(e){return join(e,...INSTALLED_SKILLS_REL)}const markerWriteChains=new Map;function withMarkerLock(e,t){let s=installedSkillsPath(e),g=(markerWriteChains.get(s)??Promise.resolve()).then(t,t);return markerWriteChains.set(s,g.then(()=>void 0,()=>void 0)),g}function readInstalledSkills(e){let t=installedSkillsPath(e);if(!existsSync(t))return emptyInstalledSkills();try{return parseInstalledSkills(readFileSync(t,`utf-8`))??emptyInstalledSkills()}catch(e){return logger$4.warn({err:e,path:t},`installed-skills marker unreadable`),emptyInstalledSkills()}}async function writeInstalledSkills(e,t){let s=InstalledSkillsSchema.safeParse(t);if(!s.success)throw Error(`Refusing to write invalid installed-skills marker: ${s.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let g=installedSkillsPath(e);await tracedMkdir(dirname(g),{recursive:!0}),await atomicWriteFile(g,`${JSON.stringify(s.data,null,2)}\n`,{fs:TRACED_FS_ADAPTER})}async function recordSkillInstall(e,t,s){return withMarkerLock(e,async()=>{let g=readInstalledSkills(e);await writeInstalledSkills(e,{...g,skills:{...g.skills,[t]:s}})})}async function removeSkillInstall(e,t){return withMarkerLock(e,async()=>{let s=readInstalledSkills(e),g=s.skills[t]??null;if(g===null)return null;let{[t]:S,...w}=s.skills;return await writeInstalledSkills(e,{...s,skills:w}),g})}const log$11=getLogger(`mermaid-validator`),MAX_FENCE_BYTES=1e5,MAX_FENCE_LINES=2e3,MAX_FENCES_PARSED=20,TOTAL_PARSE_BUDGET_MS=2e3,MAX_WARNINGS=10,MAX_MESSAGE_CHARS=500,MAX_FIRST_LINE_CHARS=200;let initPromise=null;function extractMermaidFences(e){let t=[],s=e.split(`
|
|
826
826
|
`),g=e=>e.endsWith(`\r`)?e.slice(0,-1):e,S=0;for(;S<s.length;){let e=g(s[S]??``),w=e.match(/^ {0,3}(`{3,}|~{3,})[ \t]*([^\s`]*)/);if(!w){S++;continue}let E=w[1]??``,D=E[0]??"`";if(D==="`"&&e.slice(e.indexOf(E)+E.length).includes("`")){S++;continue}let O=w[2]??``,k=RegExp(`^ {0,3}\\${D}{${E.length},}[ \t]*$`),j=[],F=S+1;for(;F<s.length&&!k.test(g(s[F]??``));)j.push(s[F]??``),F++;if(O===`mermaid`){let e=j.join(`
|
|
827
827
|
`),s=(j.find(e=>e.trim().length>0)?.trim()??``).slice(0,MAX_FIRST_LINE_CHARS);t.push({firstLine:s,body:e})}S=F+1}return t}async function initMermaid(){let{Window:e}=await import(`./lib-CCQO9uWA.mjs`),t=new e({url:`http://localhost/`}),s={window:t,document:t.document,navigator:t.navigator,location:t.location,DOMParser:t.DOMParser,Element:t.Element,Node:t.Node,SVGElement:t.SVGElement,HTMLElement:t.HTMLElement,MutationObserver:t.MutationObserver},g=new Map;try{for(let[e,t]of Object.entries(s))g.set(e,Object.getOwnPropertyDescriptor(globalThis,e)),Object.defineProperty(globalThis,e,{value:t,configurable:!0,writable:!0});let e=(await import(`./mermaid.core-LrO0u_wA.mjs`)).default;return e.initialize({startOnLoad:!1,securityLevel:`strict`,suppressErrorRendering:!0}),await e.parse(`graph LR
|
|
828
828
|
A-->B`),e}finally{for(let[e,t]of g)t?Object.defineProperty(globalThis,e,t):delete globalThis[e]}}function getMermaid(e){return initPromise??=initMermaid().catch(t=>(log$11.warn({err:t,"doc.name":e},`mermaid validator unavailable — render validation disabled for this process`),null)),initPromise}function extractLineNumber(e){let t=e.match(/Parse error on line (\d+)/);if(!t?.[1])return;let s=Number(t[1]);return Number.isSafeInteger(s)&&s>0?s:void 0}async function validateMermaidFences(e,t){try{if(!e.includes(`mermaid`))return;let{body:s}=detectFmRegion(e),g=extractMermaidFences(s);if(g.length===0)return;let S=performance.now(),w=await getMermaid(t);if(w===null)return;let E=performance.now(),D=[],O=0;for(let e=0;e<g.length&&D.length<MAX_WARNINGS&&!(O>=MAX_FENCES_PARSED);e++){if(performance.now()-E>TOTAL_PARSE_BUDGET_MS){log$11.debug({"doc.name":t,skippedFrom:e+1,fences:g.length},`mermaid validation budget exceeded — remaining fences skipped`);break}let s=g[e];if(s!==void 0){if(s.body.length>MAX_FENCE_BYTES||s.body.split(`
|
|
829
829
|
`).length>MAX_FENCE_LINES){log$11.debug({"doc.name":t,fenceIndex:e+1},`mermaid fence over validation caps — skipped`);continue}try{O++,await w.parse(s.body)}catch(g){if(g instanceof TypeError){log$11.debug({err:g,"doc.name":t,fenceIndex:e+1},`mermaid validation skipped fence — environment failure`);continue}let S=g instanceof Error?g.message:String(g),w=S.slice(0,MAX_MESSAGE_CHARS),E=extractLineNumber(S);D.push({kind:`mermaid-parse-error`,fenceIndex:e+1,fenceFirstLine:s.firstLine,message:w,...E===void 0?{}:{line:E}})}}}let k=Math.round(performance.now()-S);if(D.length===0){k>250&&log$11.debug({"doc.name":t,durationMs:k,fences:g.length},`mermaid validation slow (no warnings)`);return}return log$11.debug({"doc.name":t,count:D.length,durationMs:k},`mermaid render warnings emitted`),D}catch(e){log$11.warn({err:e,"doc.name":t},`mermaid validation errored unexpectedly — skipped`);return}}const PANE_TARGET_FILE=`pane-target.json`,PANE_TARGET_TTL_MS=3e4;function armPaneTarget(e,t,s=Date.now()){if(!t.startsWith(`#/`))return!1;tracedMkdirSync(e,{recursive:!0});let g={route:t,armedAtMs:s};return tracedWriteFileSync(resolve(e,PANE_TARGET_FILE),JSON.stringify(g)),!0}function readArmedPaneTarget(e,t=Date.now(),s=PANE_TARGET_TTL_MS){let g=resolve(e,PANE_TARGET_FILE);if(!existsSync(g))return null;try{let e=JSON.parse(readFileSync(g,`utf-8`));return typeof e.route!=`string`||typeof e.armedAtMs!=`number`||t-e.armedAtMs>s?null:e.route}catch(e){let t=e.code;return(t===`EACCES`||t===`EPERM`||t===`EIO`)&&process.stderr.write(`[pane-target] readArmedPaneTarget failed at ${g}: ${e instanceof Error?e.message:String(e)}\n`),null}}function clearArmedPaneTarget(e){let t=resolve(e,PANE_TARGET_FILE);if(existsSync(t))try{tracedUnlinkSync(t)}catch{}}const SHARE_BASE_URL=`https://openknowledge.ai/d/`,SHARE_CONSTRUCT_URL_HANDLER_TAG=`share-construct-url`;function isValidSharePath(e,t){if(e===``)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function buildGitHubBlobUrl(e,t,s,g){return`https://github.com/${e}/${t}/blob/${encodeURIComponent(s)}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function buildGitHubTreeUrl(e,t,s,g){let S=`https://github.com/${e}/${t}/tree/${encodeURIComponent(s)}`;return g===``?S:`${S}/${g.split(`/`).map(encodeURIComponent).join(`/`)}`}function emitShareConstructUrlLog(e,t){let s=t?.branchExists,g=t?.kind,S=t?.freshness;getLogger(`share`).info({action:`construct-url`,result:e,...s===void 0?{}:{branchExists:s},...g===void 0?{}:{kind:g},...S===void 0?{}:{freshness:S}},`share action`)}function truncateError(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,500)}…`:t}const FRESHNESS_PROBE_TIMEOUT_MS=5e3;async function computeShareFreshness(e,t,s,g){try{let{git:g}=createGitInstance(e,{timeoutMs:FRESHNESS_PROBE_TIMEOUT_MS}),S=`refs/remotes/origin/${t}`;await g.raw([`rev-parse`,`--verify`,S]);let w=s===``?`.`:s,[E,D,O]=await Promise.all([g.raw([`cat-file`,`-e`,`${S}:${s}`]).then(()=>!0).catch(()=>!1),g.raw([`diff`,`--name-only`,S,`--`,w]),g.raw([`status`,`--porcelain`,`--untracked-files=all`,`--`,w])]);return E?D.trim()!==``||O.trim()!==``?`stale`:`current`:`absent`}catch(e){let t=truncateError(e);getLogger(`share`).warn({action:`freshness-probe-failed`,kind:g,error:t},`[share] freshness probe failed; omitting freshness`);return}}function resolveGitDir$1(e){let t=resolve(e,`.git`);if(!existsSync(t))return null;let s;try{s=statSync(t)}catch{return null}if(s.isDirectory())return t;if(s.isFile()){let s;try{s=readFileSync(t,`utf-8`)}catch{return null}let g=/^gitdir:\s*(.+)$/m.exec(s.trim());if(!g)return null;let S=g[1].trim(),w=isAbsolute(S)?S:resolve(e,S);return existsSync(w)?w:null}return null}function resolveCommonDir(e){let t=join(e,`commondir`);if(!existsSync(t))return e;let s;try{s=readFileSync(t,`utf-8`).trim()}catch{return e}return s.length===0?e:isAbsolute(s)?s:resolve(e,s)}function readGitHeadBranch(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(t,`HEAD`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=/^ref:\s*refs\/heads\/(.+)$/.exec(g.trim());return S?S[1]:null}function stripCommentAndTrim(e){let t=e.indexOf(`#`),s=e.indexOf(`;`),g=-1;return t>=0&&s>=0?g=Math.min(t,s):t>=0?g=t:s>=0&&(g=s),(g===-1?e:e.slice(0,g)).trim()}function extractOriginUrl(e){let t=!1;for(let s of e.split(/\r?\n/)){let e=stripCommentAndTrim(s);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let g=/^url\s*=\s*(.+)$/.exec(e);if(!g)continue;let S=g[1].trim();if((S.startsWith(`"`)&&S.endsWith(`"`)||S.startsWith(`'`)&&S.endsWith(`'`))&&(S=S.slice(1,-1)),S.length>0)return S}return null}function parseGitHubOriginUrl(e){let t=e.trim();if(!t)return null;let s=/^https?:\/\/(?:www\.)?github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return s||(s=/^ssh:\/\/(?:[\w.-]+@)?github\.com(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)||(s=/^[\w.-]+@github\.com:([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),s)||(s=/^git:\/\/github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),s)?{owner:s[1],repo:s[2]}:null}function readParsedOrigin(e){let t=resolveGitDir$1(e);if(!t)return null;let s=join(resolveCommonDir(t),`config`);if(!existsSync(s))return null;let g;try{g=readFileSync(s,`utf-8`)}catch{return null}let S=extractOriginUrl(g);return S?{originUrl:S,github:parseGitHubOriginUrl(S)}:null}function readOriginGitHubRepo(e){let t=readParsedOrigin(e);return t?t.github?{kind:`ok`,owner:t.github.owner,repo:t.github.repo}:{kind:`non-github`}:{kind:`no-remote`}}function readSyncRemoteInfo(e){let t=readParsedOrigin(e);return t?t.github?{label:`${t.github.owner}/${t.github.repo}`,webUrl:`https://github.com/${t.github.owner}/${t.github.repo}`}:{label:labelFromNonGitHubUrl(t.originUrl),webUrl:null}:null}function labelFromNonGitHubUrl(e){let t=e.trim().replace(/\.git$/,``),s=/^[\w.-]+@([^:/]+):(.+)$/.exec(t);if(s)return`${s[1]}/${s[2]}`;let g=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)*(.+)$/i.exec(t);return g?g[1]:t}function branchExistsOnOrigin(e,t){let s=resolveGitDir$1(e);if(!s)return!1;let g=resolveCommonDir(s);if(existsSync(join(g,`refs`,`remotes`,`origin`,t)))return!0;let S=join(g,`packed-refs`);if(!existsSync(S))return!1;let w;try{w=readFileSync(S,`utf-8`)}catch{return!1}let E=`refs/remotes/origin/${t}`;for(let e of w.split(/\r?\n/)){let t=e.trim();if(t.length===0||t.startsWith(`#`)||t.startsWith(`^`))continue;let s=t.split(/\s+/);if(s.length===2&&s[1]===E)return!0}return!1}const SHARE_PUBLISH_OWNERS_HANDLER_TAG=`share-publish-owners`,SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG=`share-publish-name-check`,SHARE_PUBLISH_HANDLER_TAG=`share-publish`,SHARE_PUBLISH_OWNERS_KEY=`/api/share/publish/owners`,SHARE_PUBLISH_NAME_CHECK_KEY=`/api/share/publish/name-check`,SHARE_PUBLISH_KEY=`/api/share/publish`,SHARE_PUBLISH_TIMEOUT_MS=3e4;function isValidShareRepoName(e){return e.length===0||e.length>100||e.startsWith(`.`)||e.startsWith(`-`)||/^-+$/.test(e)?!1:/^[A-Za-z0-9._-]+$/.test(e)}function isValidShareOwnerName(e){return e.length===0||e.length>39||e.startsWith(`-`)||e.endsWith(`-`)?!1:/^[A-Za-z0-9-]+$/.test(e)}function pickTerminalJsonLine(e){let t=e.split(`
|
|
830
830
|
`).map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e--)try{let s=JSON.parse(t[e]);if(s&&typeof s==`object`&&!Array.isArray(s))return s}catch{}return null}function parseOwnersEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`owners`&&Array.isArray(e.owners)){let t=[];for(let s of e.owners){if(!s||typeof s!=`object`)continue;let e=s,g=typeof e.login==`string`?e.login:null,S=e.kind===`user`||e.kind===`org`?e.kind:null;if(g===null||S===null)continue;let w=typeof e.avatarUrl==`string`?e.avatarUrl:void 0;t.push({login:g,kind:S,...w?{avatarUrl:w}:{}})}return{ok:!0,owners:t}}return e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function isOwnersErrorCode(e){return e===`auth-required`||e===`network`}function parseNameCheckEvent(e){return e===null?{ok:!1,error:`network`}:e.type===`name-check`&&typeof e.available==`boolean`?{ok:!0,available:e.available}:e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}const PUBLISH_ERROR_CODES=new Set([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]);function isPublishErrorCode(e){return typeof e==`string`&&PUBLISH_ERROR_CODES.has(e)}function parsePublishEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`publish`){let t=typeof e.ownerLogin==`string`?e.ownerLogin:null,s=typeof e.repoName==`string`?e.repoName:null,g=typeof e.cloneUrl==`string`?e.cloneUrl:null,S=typeof e.defaultBranch==`string`?e.defaultBranch:null;return t!==null&&s!==null&&g!==null&&S!==null?{ok:!0,ownerLogin:t,repoName:s,cloneUrl:g,defaultBranch:S}:{ok:!1,error:`network`}}return e.type===`error`?{ok:!1,error:isPublishErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function emitSharePublishLog(e,t,s){getLogger(`share`).info({action:e,result:t,...s?.count===void 0?{}:{count:s.count},...s?.available===void 0?{}:{available:s.available}},`share action`)}function redactShareSubprocessStderr(e){return e.replace(/(https?:\/\/)([^:@\s/]+):([^@\s/]+)@/g,`$1$2:***@`)}const SHARE_TARGET_STATUS_HANDLER_TAG=`share-target-status`,DEFAULT_FETCH_TIMEOUT_MS=15e3;function classifyDoc(e,t){for(let s of e)if(s.from===t){if(s.status.startsWith(`R`))return{verdict:`renamed`,renamedTo:s.to};if(s.status===`D`)return{verdict:`deleted`}}return{verdict:`deleted`}}function classifyFolder(e,t){let s=t.endsWith(`/`)?t:`${t}/`,g=new Set;for(let t of e){if(!t.from.startsWith(s)||!t.status.startsWith(`R`))continue;let e=t.from.slice(s.length);t.to.endsWith(`/${e}`)?g.add(t.to.slice(0,t.to.length-e.length-1)):g.add(`\0ambiguous`)}let S=g.size===1?[...g][0]:void 0;return S!==void 0&&S!==`\0ambiguous`?{verdict:`renamed`,renamedTo:S}:{verdict:`deleted`}}async function computeShareTargetStatus(e,t,s,g,S={}){let w=getLogger(`share`),E=e=>(w.info({action:`target-status`,verdict:e.verdict,kind:g},`target-status verdict`),e),{git:D}=createGitInstance(e,S.skipFetch?{}:{timeoutMs:S.fetchTimeoutMs??DEFAULT_FETCH_TIMEOUT_MS});if(!S.skipFetch)try{await D.raw([`fetch`,`origin`,t])}catch(e){return w.warn({action:`target-status`,kind:g,error:truncateError(e)},`target-status fetch failed`),E({verdict:`unknown`})}let O=`origin/${t}`;try{if(await D.raw([`cat-file`,`-e`,`${O}:${s}`]).then(()=>!0).catch(()=>!1)){let t=await D.raw([`cat-file`,`-e`,`HEAD:${s}`]).then(()=>!0).catch(()=>!1),g=existsSync(join(e,s));return E(t&&!g?{verdict:`changed-locally`}:{verdict:`on-origin`})}let t=(await D.raw([`log`,`-1`,`--format=%H`,O,`--`,s])).trim();if(t===``)return E({verdict:`never-on-branch`});let S=await listNameStatus(D,[`diff-tree`,`-M`,`-r`,`--no-commit-id`,`--name-status`,`${t}^1`,t]),w=g===`folder`?classifyFolder(S,s):classifyDoc(S,s);return w.verdict===`renamed`&&!await D.raw([`cat-file`,`-e`,`${O}:${w.renamedTo}`]).then(()=>!0).catch(()=>!1)?E({verdict:`deleted`}):E(w)}catch(e){return w.warn({action:`target-status`,kind:g,error:truncateError(e)},`target-status detection failed`),E({verdict:`unknown`})}}const BUNDLE_SKILL_NAME={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`},BUNDLE_IDS=Object.keys(BUNDLE_SKILL_NAME),BUNDLE_SCOPE={discovery:`user`,project:`project`,"write-skill":`user`},USER_GLOBAL_BUNDLE_IDS=BUNDLE_IDS.filter(e=>BUNDLE_SCOPE[e]===`user`);function bundleSkillMdPath(e){return`packages/server/assets/skills/${e}/SKILL.md`}const MAX_ZIP_BYTES=102400,DESKTOP_SKILLS_REL=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function resolveBundledSkillDir(e,t={}){let s=t.platform??process.platform,g=t.checkDesktop??!1,S=t.home??homedir(),w=[];g&&s===`darwin`&&(w.push(join(`/Applications`,DESKTOP_SKILLS_REL,e)),w.push(join(S,`Applications`,DESKTOP_SKILLS_REL,e))),w.push(fileURLToPath(new URL(`../dist/assets/skills/${e}`,import.meta.url))),w.push(fileURLToPath(new URL(`../assets/skills/${e}`,import.meta.url))),w.push(fileURLToPath(new URL(`./assets/skills/${e}`,import.meta.url)));for(let e of w)if(existsSync(e))return e;throw Error(`Bundled skill asset directory not found for bundle '${e}'. Tried: ${w.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function*walkFiles(e,t=e){let s=await readdir(e,{withFileTypes:!0});for(let g of s){let s=join(e,g.name);g.isDirectory()?yield*walkFiles(s,t):g.isFile()&&(yield relative(t,s))}}function computeWrapperFolderName(e,t=basename){return t(e)||`open-knowledge`}function toPosixZipPath(e,t=sep){return t===`/`?e:e.split(t).join(`/`)}async function zipDirectory(e,t,s=computeWrapperFolderName(e)){let g=new import_yazl.ZipFile;g.addEmptyDirectory(`${s}/`);let S=[];for await(let t of walkFiles(e))S.push(t);S.sort();for(let t of S){let S=join(e,t),w=`${s}/${toPosixZipPath(t)}`;g.addFile(S,w)}g.end(),await new Promise((e,s)=>{let S=createWriteStream(t);g.outputStream.pipe(S),S.on(`close`,()=>e()),S.on(`error`,s),g.outputStream.on(`error`,s)})}async function sha256OfFile(e){return new Promise((t,s)=>{let g=createHash(`sha256`),S=createReadStream(e);S.on(`data`,e=>g.update(e)),S.on(`end`,()=>t(g.digest(`hex`))),S.on(`error`,s)})}function extractMetadataVersion(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return;let s=unwrapFrontmatterFences(t),g=s.search(/^metadata:/m);if(g<0)return;let S=s.slice(g).split(`
|
|
831
|
-
`).slice(1);for(let e of S){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,s={}){let g=s.bundle??`project`,S=statSync(e).size;if(S>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${S} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let w=await sha256OfFile(e),E=await readFile$1(join(s.sourceDir??resolveBundledSkillDir(g,{checkDesktop:!1}),`SKILL.md`),`utf-8`),D=BUNDLE_SKILL_NAME[g];if(!RegExp(`^name:\\s+${D}$`,`m`).test(E.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${D}'. Check packages/server/assets/skills/${g}/SKILL.md frontmatter.`);let O=extractMetadataVersion(E);if(t!==void 0){if(!O)throw Error(`SKILL.md metadata.version missing. Add it to packages/server/assets/skills/${g}/SKILL.md.`);if(O!==t)throw Error(`SKILL.md metadata.version (${O}) does not match expected version (${t}).`)}return{size:S,sha256:w,skillVersion:O}}async function buildSkillZip(e={}){let t=e.bundle??`project`,s=e.sourceDir??resolveBundledSkillDir(t,{checkDesktop:e.checkDesktop??!1}),g=e.outputPath??join(process.cwd(),`openknowledge.skill`);await zipDirectory(s,g,BUNDLE_SKILL_NAME[t]);let{size:S,sha256:w,skillVersion:E}=await validateSkillZip(g,e.expectedSkillVersion,{bundle:t,sourceDir:s});return{outputPath:g,size:S,sha256:w,skillVersion:E}}const SKILL_INSTALL_EVENTS_FILE_REL=[`.ok`,`skill-install-events.jsonl`];async function recordSkillInstallEvent(e,t){let s=t?.homedir??(()=>process.env.HOME??``),g=t?.warn??((e,t)=>{console.warn(t,e)}),S=s();if(!S){g({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let w=join(S,...SKILL_INSTALL_EVENTS_FILE_REL),E=`${JSON.stringify(e)}\n`;try{await tracedMkdir(dirname(w),{recursive:!0})}catch(e){g({event:`skill-install-events.mkdir-failed`,error:String(e)},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await tracedWriteFile(w,E,{flag:`a`,encoding:`utf-8`})}catch(e){g({event:`skill-install-events.append-failed`,error:String(e)},`[skill-install-events] append failed; telemetry skipped`)}}const readFileAsync=promisify(readFile);function skillStateYamlPath(e){return join(e,...SKILL_STATE_REL)}async function withSkillStateWriteLock(e,t){let s=skillStateYamlPath(e);await tracedMkdir(dirname(s),{recursive:!0});try{return await withFileLock(`${s}.lock`,t)}catch(e){if(e.code===`LOCK_TIMEOUT`)return t();throw e}}const DEFAULT_LOGGER={warn:(e,t)=>console.warn(t,e)};async function readSkillStateFile(e,t=DEFAULT_LOGGER){let s=skillStateYamlPath(e),g;try{g=await readFileAsync(s,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let S=(0,import_dist$1.parseDocument)(g);if(S.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:s,errors:S.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let w=SkillStateSchema.safeParse(S.toJSON());if(!w.success){let e=w.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:s,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:s,issues:w.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return w.data}async function writeSkillStateFile(e,t){let s=SkillStateSchema.safeParse(t);if(!s.success)throw Error(`Refusing to write invalid skill-state: ${s.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let g=skillStateYamlPath(e);await tracedMkdir(dirname(g),{recursive:!0});let S=(0,import_dist$1.parseDocument)(``);S.contents=S.createNode(s.data),await atomicWriteFile(g,S.toString(),{fs:tracedAtomicFs})}async function readTargetVersion(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.version??null}async function readTargetRecordedAt(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.recordedAt??null}async function writeTargetVersion(e,t,s,g,S){if(!SKILL_STATE_VERSION_RE.test(s))throw Error(`Refusing to write invalid version string: ${s}`);await withSkillStateWriteLock(e,async()=>{let w=await readSkillStateFile(e,S)??emptySkillState(),E=new Date().toISOString(),D=w.targets[t],O=g===void 0?D?.surface??void 0:g,k=O===void 0?{version:s,recordedAt:E}:{version:s,recordedAt:E,surface:O};await writeSkillStateFile(e,{...w,targets:{...w.targets,[t]:k}})})}async function readBundleDecision(e,t,s){let g=(await readSkillStateFile(e,s).catch(()=>null))?.bundles?.[t];return typeof g?.enabled==`boolean`?g.enabled:null}async function writeBundleDecision(e,t,s,g){await withSkillStateWriteLock(e,async()=>{let S=await readSkillStateFile(e,g)??emptySkillState();await writeSkillStateFile(e,{...S,bundles:{...S.bundles,[t]:{enabled:s,decidedAt:new Date().toISOString()}}})})}async function readServerPackageVersion(){let e=await readFileAsync(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}async function readSkillInstallStateSnapshot(e,t){let[s,g]=await Promise.all([readServerPackageVersion(),readAllTargets(e,t)]);return{currentVersion:s,targets:g}}async function readAllTargets(e,t=DEFAULT_LOGGER){let s=null;try{s=await readSkillStateFile(e,t)}catch(g){t.warn({event:`skill-state.read-error`,path:skillStateYamlPath(e),error:String(g)},`non-ENOENT error reading skill-state.yml; treating as absent`),s=null}let g=SKILL_STATE_TARGETS.map(e=>{let t=s?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(g)}const LEGACY_USER_SKILL_NAME=`open-knowledge`,LEGACY_USER_SKILL_HOST_DIRS=[`.claude`,`.cursor`,`.agents`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS$4=6e4;function centralSkillDir(e,t){return join(e,`.agents`,`skills`,t)}async function centralSkillExists(e,t){try{return(await stat$1(centralSkillDir(e,t))).isDirectory()}catch{return!1}}function quoteForWindowsShell(e){return/\s/.test(e)?`"${e.replaceAll(`"`,`\\"`)}"`:e}function runSpawn(e,t,s,g,S,w){return new Promise(E=>{let D,O=w===`win32`,k=O?s.map(quoteForWindowsShell):s;try{D=e(t,k,{env:g,stdio:[`ignore`,`pipe`,`pipe`],...O?{shell:!0}:{}})}catch(e){E({kind:`spawn-error`,stderr:``,error:e});return}let j=``,F=!1,L=e=>{F||(F=!0,clearTimeout(B),E(e))};D.stderr?.on(`data`,e=>{j+=typeof e==`string`?e:e.toString(`utf-8`)}),D.on(`error`,e=>{L({kind:`spawn-error`,stderr:j,error:e})}),D.on(`exit`,e=>{L(e===0?{kind:`ok`,exitCode:e,stderr:j}:{kind:`nonzero`,exitCode:e,stderr:j})});let B=setTimeout(()=>{try{D.kill(`SIGTERM`)}catch{}L({kind:`timeout`,stderr:j})},S)})}async function anyLegacyUserSkillExists(e){for(let t of LEGACY_USER_SKILL_HOST_DIRS)try{if((await stat$1(join(e,t,`skills`,LEGACY_USER_SKILL_NAME))).isDirectory())return!0}catch{}return!1}async function removeLegacyUserSkill(e,t,s,g,S,w){if(!await anyLegacyUserSkillExists(e))return;let E=await runSpawn(t,`npx`,[`-y`,SKILLS_CLI_SPEC,`remove`,`--agent`,`*`,`-g`,LEGACY_USER_SKILL_NAME],s,g,w);E.kind!==`ok`&&S.warn({event:`skill-install.legacy-remove-failed`,reason:E.kind,exitCode:E.exitCode,stderr:E.stderr},"Legacy `open-knowledge` skill removal did not exit cleanly; continuing with install.")}async function installUserSkill(e={}){let t=e.home??homedir(),s=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},g=e.spawn??spawn,S=e.timeoutMs??DEFAULT_TIMEOUT_MS$4,w=e.surface??`cli-npx-skills-add`,E=e.platform??process.platform,D=e.bundleId??`discovery`,O=BUNDLE_SKILL_NAME[D],k=async(e,g,S)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:w,target:`cli-hosts`,bundle:D,outcome:e,...g===void 0?{}:{version:g},...S===void 0?{}:{reason:S}},{homedir:()=>t,warn:s.warn})},j;try{j=await readServerPackageVersion()}catch(e){return s.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await k(`failed`,void 0,`version-read-failed`),`failed`}let F=await readTargetVersion(t,`cli-hosts`,s).catch(e=>(s.warn({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(!e.force&&F!==null&&F===j){if(await centralSkillExists(t,O))return s.info?.({event:`skill-install.skip-current`,version:j},`OpenKnowledge skill already installed at current version; skipping.`),await k(`skip-current`,j),`skip-current`;s.info?.({event:`skill-install.reinstall-missing`,version:j,path:centralSkillDir(t,O)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let L;try{L=resolveBundledSkillDir(D,{checkDesktop:!1})}catch(e){return s.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled SKILL.md asset not found.`),await k(`failed`,j,`bundled-asset-missing`),`failed`}let B={...process.env,HOME:t};await removeLegacyUserSkill(t,g,B,S,s,E);let H=await runSpawn(g,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,L,`--agent`,`*`,`-g`,`-y`,`--copy`],B,S,E);if(H.kind===`ok`){try{await writeTargetVersion(t,`cli-hosts`,j,w,s)}catch(e){return s.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),await k(`failed`,j,`sidecar-write-failed`),`failed`}return s.info?.({event:`skill-install.installed`,version:j},`OpenKnowledge skill installed to detected agent hosts.`),await k(`installed`,j),`installed`}return H.kind===`timeout`?(s.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:S,stderr:H.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`timeout`),`failed`):H.kind===`spawn-error`?(s.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(H.error),stderr:H.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`spawn-error`),`failed`):(s.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:H.exitCode,stderr:H.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`nonzero-exit:${H.exitCode??`unknown`}`),`failed`)}const DOWNLOADS_DIR=`Downloads`,SKILL_FILENAME=`openknowledge.skill`;function defaultDownloadsPath(e){return join(e,DOWNLOADS_DIR,SKILL_FILENAME)}function invokeFileAssociation(e,t,s){let g={detached:!0,stdio:`ignore`};try{return t===`darwin`?(s(`open`,[e],g).unref(),{ok:!0}):t===`win32`?(s(`cmd`,[`/c`,`start`,`""`,e],g).unref(),{ok:!0}):t===`linux`?(s(`xdg-open`,[e],g).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function buildAndOpenSkill(e={}){let t=e.home??homedir(),s=resolve(e.out??defaultDownloadsPath(t)),g=e.platformName??platform(),S=e.spawnFn??spawn,w=e.logger,E=async(e,s,g)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...s===void 0?{}:{version:s},...g===void 0?{}:{reason:g}},{homedir:()=>t,warn:w?.warn})};if(!e.force){let e=null;try{e=await readServerPackageVersion()}catch(e){w?.warn?.({event:`skill-install.gate.version-read-failed`,error:String(e)},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let s=null,g=null;try{[s,g]=await Promise.all([readTargetVersion(t,`claude-cowork`,w),readTargetRecordedAt(t,`claude-cowork`,w)])}catch(e){w?.warn?.({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read claude-cowork install-state; rebuilding.`)}if(s!==null&&s===e)return w?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`OpenKnowledge skill already delivered at current version; skipping rebuild.`),await E(`skip-current`,e),{status:`skip-current`,skillVersion:e,...g===null?{}:{recordedAt:g}}}}try{await tracedMkdir(dirname(s),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let D;try{D=await buildSkillZip({outputPath:s,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let O={status:`built`,outputPath:D.outputPath,size:D.size,sha256:D.sha256,skillVersion:D.skillVersion};if(D.skillVersion)try{await writeTargetVersion(t,`claude-cowork`,D.skillVersion,`server-build-and-open`,w)}catch(e){w?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:D.skillVersion,error:String(e)},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await E(`built`,D.skillVersion),O;let k=invokeFileAssociation(D.outputPath,g,S);return k.ok?(await E(`installed`,D.skillVersion),{...O,status:`installed`}):(await E(`built`,D.skillVersion,`handoff-${k.reason}`),{...O,handoffError:{reason:k.reason,message:k.message}})}const logger$3=getLogger(`skill-management`),SKILL_MANAGEMENT_REL=[`.ok`,`local`,`skill-management.json`],SCHEMA_VERSION=1;function skillManagementPath(e){return join(e,...SKILL_MANAGEMENT_REL)}function readSkillManagement(e){let t=skillManagementPath(e);if(!existsSync(t))return null;try{let e=JSON.parse(readFileSync(t,`utf-8`));if(e&&typeof e==`object`&&typeof e.manageEditorSkills==`boolean`){let t=e;return{version:typeof t.version==`number`?t.version:SCHEMA_VERSION,manageEditorSkills:t.manageEditorSkills,decidedAt:typeof t.decidedAt==`string`?t.decidedAt:void 0,surface:typeof t.surface==`string`?t.surface:void 0}}return logger$3.warn({path:t},`skill-management marker malformed — treating as unset`),null}catch(e){return logger$3.warn({err:e,path:t},`skill-management marker unreadable — treating as unset`),null}}async function writeSkillManagement(e,t){let s={version:SCHEMA_VERSION,manageEditorSkills:t.manageEditorSkills,decidedAt:t.now??new Date().toISOString(),...t.surface?{surface:t.surface}:{}},g=skillManagementPath(e);await tracedMkdir(dirname(g),{recursive:!0}),await atomicWriteFile(g,`${JSON.stringify(s,null,2)}\n`,{fs:tracedAtomicFs})}function isProjectSkillManaged(e,t=process.env){if(t.OK_RECLAIM_DISABLE===`1`)return!1;let s=t.OK_SKILL_MANAGE;return s===`1`||s===`true`?!0:s===`0`||s===`false`?!1:readSkillManagement(e)?.manageEditorSkills??!1}const MIN_GIT_VERSION=`2.31.0`,PROBE_TIMEOUT_MS$1=5e3;var GitNotAvailableError=class extends Error{code=`GIT_NOT_AVAILABLE`;platform;guidance;constructor(e,t,s){super(buildMissingMessage(t),s),this.name=`GitNotAvailableError`,this.platform=e,this.guidance=t}},GitTooOldError=class extends Error{code=`GIT_TOO_OLD`;platform;detected;required;resolvedPath;guidance;constructor(e,t,s,g,S,w){super(buildTooOldMessage(t,s,g,S),w),this.name=`GitTooOldError`,this.platform=e,this.detected=t,this.required=s,this.resolvedPath=g,this.guidance=S}};function detectGit(){let e=probeGit(`git`);if(e.kind===`ok`)return{ok:!0,version:e.version,resolvedPath:e.resolvedPath,source:`PATH`};for(let e of fallbackPaths(process.platform)){if(!existsSync(e))continue;let t=probeGit(e);if(t.kind===`ok`)return{ok:!0,version:t.version,resolvedPath:e,source:`fallback`}}throw new GitNotAvailableError(process.platform,buildGuidance(process.platform))}function assertGitAvailable(){let e=detectGit();if(compareSemver(e.version,`2.31.0`)<0)throw new GitTooOldError(process.platform,e.version,MIN_GIT_VERSION,e.resolvedPath,buildGuidance(process.platform));return e}function probeGit(e){let t=spawnSync(e,[`--version`],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1,env:{...process.env,LANG:`C`,LC_ALL:`C`}});if(t.error)return`signal`in t&&t.signal===`SIGTERM`?{kind:`fail`,reason:`timeout`}:{kind:`fail`,reason:`enoent`};if(t.status!==0)return{kind:`fail`,reason:`nonzero`};let s=parseGitVersion(typeof t.stdout==`string`?t.stdout:``);return s===null?{kind:`fail`,reason:`unparseable`}:{kind:`ok`,version:s,resolvedPath:e===`git`?resolveOnPath(`git`)??e:e}}function parseGitVersion(e){let t=e.match(/git version (\d+)\.(\d+)\.(\d+)/);return t?`${t[1]}.${t[2]}.${t[3]}`:null}const SAFE_COMMAND_NAME_RE=/^[a-zA-Z0-9_.-]+$/,resolveOnPathCache=new Map;function resolveOnPath(e){if(!SAFE_COMMAND_NAME_RE.test(e))return null;let t=resolveOnPathCache.get(e);if(t!==void 0)return t;let s;if(process.platform===`win32`){let t=spawnSync(`where`,[e],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1});s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}else{let t=spawnSync(`/bin/sh`,[`-c`,`command -v ${e}`],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1});s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}return s!==null&&resolveOnPathCache.set(e,s),s}function fallbackPaths(e){switch(e){case`darwin`:return[`/opt/homebrew/bin/git`,`/usr/local/bin/git`,`/Library/Developer/CommandLineTools/usr/bin/git`,`/usr/bin/git`];case`win32`:return[`C:\\Program Files\\Git\\cmd\\git.exe`,`C:\\Program Files (x86)\\Git\\cmd\\git.exe`,join(homedir(),`scoop`,`apps`,`git`,`current`,`cmd`,`git.exe`)];default:return[`/usr/bin/git`,`/usr/local/bin/git`,join(homedir(),`.local`,`bin`,`git`),`/snap/bin/git`]}}function buildGuidance(e){switch(e){case`darwin`:{let e=[];return hasBrew()&&e.push({label:`Install with Homebrew (recommended; no admin needed)`,command:`brew install git`,requiresAdmin:!1}),e.push({label:`Install Xcode Command Line Tools`,command:`xcode-select --install`,requiresAdmin:!0}),{product:`Git`,url:`https://git-scm.com/download/mac`,options:e}}case`win32`:{let e=[];return hasWinget()&&e.push({label:`Install with winget`,command:`winget install --id Git.Git -e --source winget`,requiresAdmin:!0}),hasScoop()&&e.push({label:`Install with Scoop (no admin)`,command:`scoop install git`,requiresAdmin:!1}),hasChoco()&&e.push({label:`Install with Chocolatey`,command:`choco install git -y`,requiresAdmin:!0}),e.push({label:`Download the official installer`,command:`Open https://gitforwindows.org/ in your browser`,requiresAdmin:!1}),{product:`Git for Windows`,url:`https://gitforwindows.org/`,options:e}}default:return{product:`Git`,url:`https://git-scm.com/download/linux`,options:linuxInstallOptions()}}}function linuxInstallOptions(){switch(detectLinuxFamily()){case`debian`:return[{label:`Install with apt`,command:`sudo apt install git`,requiresAdmin:!0}];case`fedora`:return[{label:`Install with dnf`,command:`sudo dnf install git`,requiresAdmin:!0}];case`arch`:return[{label:`Install with pacman`,command:`sudo pacman -S git`,requiresAdmin:!0}];case`opensuse`:return[{label:`Install with zypper`,command:`sudo zypper install git`,requiresAdmin:!0}];case`alpine`:return[{label:`Install with apk`,command:`sudo apk add git`,requiresAdmin:!0}];default:return[{label:`Use your distribution's package manager`,command:`apt / dnf / pacman / zypper / apk install git (one of these will fit your system)`,requiresAdmin:!0}]}}function detectLinuxFamily(e){let t=e;if(t===void 0)try{t=readFileSync(`/etc/os-release`,`utf-8`)}catch{return`unknown`}let s=[/^ID=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``),...(/^ID_LIKE=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``)??``).split(/\s+/)].filter(e=>!!e);return s.some(e=>/^(debian|ubuntu|mint|pop)$/i.test(e))?`debian`:s.some(e=>/^(fedora|rhel|centos|alma|rocky)$/i.test(e))?`fedora`:s.some(e=>/^(arch|manjaro|endeavouros)$/i.test(e))?`arch`:s.some(e=>/^opensuse/i.test(e))||s.includes(`suse`)?`opensuse`:s.some(e=>/^alpine$/i.test(e))?`alpine`:`unknown`}function hasCommand(e){return resolveOnPath(e)!==null}function hasBrew(){return hasCommand(`brew`)}function hasWinget(){return hasCommand(`winget`)}function hasScoop(){return hasCommand(`scoop`)}function hasChoco(){return hasCommand(`choco`)}function buildMissingMessage(e){let t=[];if(t.push(`OpenKnowledge needs ${e.product} to track changes to your knowledge base, but it isn't installed (or isn't on PATH).`),t.push(``),e.options.length>0){t.push(`Install ${e.product}:`);for(let s of e.options){let e=s.requiresAdmin?` (admin required)`:``;t.push(` • ${s.label}${e}`),t.push(` ${s.command}`)}t.push(``)}return t.push(`Or download from: ${e.url}`),t.push(``),t.push(`After installing, re-run OpenKnowledge.`),t.push("Run `ok diagnose health --check git` to verify your installation."),t.join(`
|
|
831
|
+
`).slice(1);for(let e of S){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,s={}){let g=s.bundle??`project`,S=statSync(e).size;if(S>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${S} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let w=await sha256OfFile(e),E=await readFile$1(join(s.sourceDir??resolveBundledSkillDir(g,{checkDesktop:!1}),`SKILL.md`),`utf-8`),D=BUNDLE_SKILL_NAME[g];if(!RegExp(`^name:\\s+${D}$`,`m`).test(E.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${D}'. Check packages/server/assets/skills/${g}/SKILL.md frontmatter.`);let O=extractMetadataVersion(E);if(t!==void 0){if(!O)throw Error(`SKILL.md metadata.version missing. Add it to packages/server/assets/skills/${g}/SKILL.md.`);if(O!==t)throw Error(`SKILL.md metadata.version (${O}) does not match expected version (${t}).`)}return{size:S,sha256:w,skillVersion:O}}async function buildSkillZip(e={}){let t=e.bundle??`project`,s=e.sourceDir??resolveBundledSkillDir(t,{checkDesktop:e.checkDesktop??!1}),g=e.outputPath??join(process.cwd(),`openknowledge.skill`);await zipDirectory(s,g,BUNDLE_SKILL_NAME[t]);let{size:S,sha256:w,skillVersion:E}=await validateSkillZip(g,e.expectedSkillVersion,{bundle:t,sourceDir:s});return{outputPath:g,size:S,sha256:w,skillVersion:E}}const SKILL_INSTALL_EVENTS_FILE_REL=[`.ok`,`skill-install-events.jsonl`];async function recordSkillInstallEvent(e,t){let s=t?.homedir??(()=>process.env.HOME??``),g=t?.warn??((e,t)=>{console.warn(t,e)}),S=s();if(!S){g({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let w=join(S,...SKILL_INSTALL_EVENTS_FILE_REL),E=`${JSON.stringify(e)}\n`;try{await tracedMkdir(dirname(w),{recursive:!0})}catch(e){g({event:`skill-install-events.mkdir-failed`,error:String(e)},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await tracedWriteFile(w,E,{flag:`a`,encoding:`utf-8`})}catch(e){g({event:`skill-install-events.append-failed`,error:String(e)},`[skill-install-events] append failed; telemetry skipped`)}}const readFileAsync=promisify(readFile);function skillStateYamlPath(e){return join(e,...SKILL_STATE_REL)}async function withSkillStateWriteLock(e,t){let s=skillStateYamlPath(e);await tracedMkdir(dirname(s),{recursive:!0});try{return await withFileLock(`${s}.lock`,t)}catch(e){if(e.code===`LOCK_TIMEOUT`)return t();throw e}}const DEFAULT_LOGGER={warn:(e,t)=>console.warn(t,e)};async function readSkillStateFile(e,t=DEFAULT_LOGGER){let s=skillStateYamlPath(e),g;try{g=await readFileAsync(s,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let S=(0,import_dist$1.parseDocument)(g);if(S.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:s,errors:S.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let w=SkillStateSchema.safeParse(S.toJSON());if(!w.success){let e=w.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:s,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:s,issues:w.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return w.data}async function writeSkillStateFile(e,t){let s=SkillStateSchema.safeParse(t);if(!s.success)throw Error(`Refusing to write invalid skill-state: ${s.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let g=skillStateYamlPath(e);await tracedMkdir(dirname(g),{recursive:!0});let S=(0,import_dist$1.parseDocument)(``);S.contents=S.createNode(s.data),await atomicWriteFile(g,S.toString(),{fs:tracedAtomicFs})}async function readTargetVersion(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.version??null}async function readTargetRecordedAt(e,t,s){let g=await readSkillStateFile(e,s);return g===null?null:g.targets[t]?.recordedAt??null}async function writeTargetVersion(e,t,s,g,S){if(!SKILL_STATE_VERSION_RE.test(s))throw Error(`Refusing to write invalid version string: ${s}`);await withSkillStateWriteLock(e,async()=>{let w=await readSkillStateFile(e,S)??emptySkillState(),E=new Date().toISOString(),D=w.targets[t],O=g===void 0?D?.surface??void 0:g,k=O===void 0?{version:s,recordedAt:E}:{version:s,recordedAt:E,surface:O};await writeSkillStateFile(e,{...w,targets:{...w.targets,[t]:k}})})}async function readBundleDecision(e,t,s){let g=(await readSkillStateFile(e,s).catch(()=>null))?.bundles?.[t];return typeof g?.enabled==`boolean`?g.enabled:null}async function writeBundleDecision(e,t,s,g){await withSkillStateWriteLock(e,async()=>{let S=await readSkillStateFile(e,g)??emptySkillState();await writeSkillStateFile(e,{...S,bundles:{...S.bundles,[t]:{enabled:s,decidedAt:new Date().toISOString()}}})})}async function readServerPackageVersion(){let e=await readFileAsync(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}async function readSkillInstallStateSnapshot(e,t){let[s,g]=await Promise.all([readServerPackageVersion(),readAllTargets(e,t)]);return{currentVersion:s,targets:g}}async function readAllTargets(e,t=DEFAULT_LOGGER){let s=null;try{s=await readSkillStateFile(e,t)}catch(g){t.warn({event:`skill-state.read-error`,path:skillStateYamlPath(e),error:String(g)},`non-ENOENT error reading skill-state.yml; treating as absent`),s=null}let g=SKILL_STATE_TARGETS.map(e=>{let t=s?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(g)}const LEGACY_USER_SKILL_NAME=`open-knowledge`,LEGACY_USER_SKILL_HOST_DIRS=[`.claude`,`.cursor`,`.agents`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS$4=6e4;function centralSkillDir(e,t){return join(e,`.agents`,`skills`,t)}async function centralSkillExists(e,t){try{return(await stat$1(centralSkillDir(e,t))).isDirectory()}catch{return!1}}function quoteForWindowsShell(e){return/\s/.test(e)?`"${e.replaceAll(`"`,`\\"`)}"`:e}function runSpawn(e,t,s,g,S,w){return new Promise(E=>{let D,O=w===`win32`,k=O?s.map(quoteForWindowsShell):s;try{D=e(t,k,withHiddenWindowsConsole({env:g,stdio:[`ignore`,`pipe`,`pipe`],...O?{shell:!0}:{}}))}catch(e){E({kind:`spawn-error`,stderr:``,error:e});return}let j=``,F=!1,L=e=>{F||(F=!0,clearTimeout(B),E(e))};D.stderr?.on(`data`,e=>{j+=typeof e==`string`?e:e.toString(`utf-8`)}),D.on(`error`,e=>{L({kind:`spawn-error`,stderr:j,error:e})}),D.on(`exit`,e=>{L(e===0?{kind:`ok`,exitCode:e,stderr:j}:{kind:`nonzero`,exitCode:e,stderr:j})});let B=setTimeout(()=>{try{D.kill(`SIGTERM`)}catch{}L({kind:`timeout`,stderr:j})},S)})}async function anyLegacyUserSkillExists(e){for(let t of LEGACY_USER_SKILL_HOST_DIRS)try{if((await stat$1(join(e,t,`skills`,LEGACY_USER_SKILL_NAME))).isDirectory())return!0}catch{}return!1}async function removeLegacyUserSkill(e,t,s,g,S,w){if(!await anyLegacyUserSkillExists(e))return;let E=await runSpawn(t,`npx`,[`-y`,SKILLS_CLI_SPEC,`remove`,`--agent`,`*`,`-g`,LEGACY_USER_SKILL_NAME],s,g,w);E.kind!==`ok`&&S.warn({event:`skill-install.legacy-remove-failed`,reason:E.kind,exitCode:E.exitCode,stderr:E.stderr},"Legacy `open-knowledge` skill removal did not exit cleanly; continuing with install.")}async function installUserSkill(e={}){let t=e.home??homedir(),s=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},g=e.spawn??spawn,S=e.timeoutMs??DEFAULT_TIMEOUT_MS$4,w=e.surface??`cli-npx-skills-add`,E=e.platform??process.platform,D=e.bundleId??`discovery`,O=BUNDLE_SKILL_NAME[D],k=async(e,g,S)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:w,target:`cli-hosts`,bundle:D,outcome:e,...g===void 0?{}:{version:g},...S===void 0?{}:{reason:S}},{homedir:()=>t,warn:s.warn})},j;try{j=await readServerPackageVersion()}catch(e){return s.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await k(`failed`,void 0,`version-read-failed`),`failed`}let F=await readTargetVersion(t,`cli-hosts`,s).catch(e=>(s.warn({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(!e.force&&F!==null&&F===j){if(await centralSkillExists(t,O))return s.info?.({event:`skill-install.skip-current`,version:j},`OpenKnowledge skill already installed at current version; skipping.`),await k(`skip-current`,j),`skip-current`;s.info?.({event:`skill-install.reinstall-missing`,version:j,path:centralSkillDir(t,O)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let L;try{L=resolveBundledSkillDir(D,{checkDesktop:!1})}catch(e){return s.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled SKILL.md asset not found.`),await k(`failed`,j,`bundled-asset-missing`),`failed`}let B={...process.env,HOME:t};await removeLegacyUserSkill(t,g,B,S,s,E);let H=await runSpawn(g,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,L,`--agent`,`*`,`-g`,`-y`,`--copy`],B,S,E);if(H.kind===`ok`){try{await writeTargetVersion(t,`cli-hosts`,j,w,s)}catch(e){return s.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),await k(`failed`,j,`sidecar-write-failed`),`failed`}return s.info?.({event:`skill-install.installed`,version:j},`OpenKnowledge skill installed to detected agent hosts.`),await k(`installed`,j),`installed`}return H.kind===`timeout`?(s.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:S,stderr:H.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`timeout`),`failed`):H.kind===`spawn-error`?(s.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(H.error),stderr:H.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`spawn-error`),`failed`):(s.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:H.exitCode,stderr:H.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${L} --agent '*' -g -y --copy`),await k(`failed`,j,`nonzero-exit:${H.exitCode??`unknown`}`),`failed`)}const DOWNLOADS_DIR=`Downloads`,SKILL_FILENAME=`openknowledge.skill`;function defaultDownloadsPath(e){return join(e,DOWNLOADS_DIR,SKILL_FILENAME)}function invokeFileAssociation(e,t,s){let g=withHiddenWindowsConsole({detached:!0,stdio:`ignore`});try{return t===`darwin`?(s(`open`,[e],g).unref(),{ok:!0}):t===`win32`?(s(`cmd`,[`/c`,`start`,`""`,e],g).unref(),{ok:!0}):t===`linux`?(s(`xdg-open`,[e],g).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function buildAndOpenSkill(e={}){let t=e.home??homedir(),s=resolve(e.out??defaultDownloadsPath(t)),g=e.platformName??platform(),S=e.spawnFn??spawn,w=e.logger,E=async(e,s,g)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...s===void 0?{}:{version:s},...g===void 0?{}:{reason:g}},{homedir:()=>t,warn:w?.warn})};if(!e.force){let e=null;try{e=await readServerPackageVersion()}catch(e){w?.warn?.({event:`skill-install.gate.version-read-failed`,error:String(e)},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let s=null,g=null;try{[s,g]=await Promise.all([readTargetVersion(t,`claude-cowork`,w),readTargetRecordedAt(t,`claude-cowork`,w)])}catch(e){w?.warn?.({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read claude-cowork install-state; rebuilding.`)}if(s!==null&&s===e)return w?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`OpenKnowledge skill already delivered at current version; skipping rebuild.`),await E(`skip-current`,e),{status:`skip-current`,skillVersion:e,...g===null?{}:{recordedAt:g}}}}try{await tracedMkdir(dirname(s),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let D;try{D=await buildSkillZip({outputPath:s,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await E(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let O={status:`built`,outputPath:D.outputPath,size:D.size,sha256:D.sha256,skillVersion:D.skillVersion};if(D.skillVersion)try{await writeTargetVersion(t,`claude-cowork`,D.skillVersion,`server-build-and-open`,w)}catch(e){w?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:D.skillVersion,error:String(e)},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await E(`built`,D.skillVersion),O;let k=invokeFileAssociation(D.outputPath,g,S);return k.ok?(await E(`installed`,D.skillVersion),{...O,status:`installed`}):(await E(`built`,D.skillVersion,`handoff-${k.reason}`),{...O,handoffError:{reason:k.reason,message:k.message}})}const logger$3=getLogger(`skill-management`),SKILL_MANAGEMENT_REL=[`.ok`,`local`,`skill-management.json`],SCHEMA_VERSION=1;function skillManagementPath(e){return join(e,...SKILL_MANAGEMENT_REL)}function readSkillManagement(e){let t=skillManagementPath(e);if(!existsSync(t))return null;try{let e=JSON.parse(readFileSync(t,`utf-8`));if(e&&typeof e==`object`&&typeof e.manageEditorSkills==`boolean`){let t=e;return{version:typeof t.version==`number`?t.version:SCHEMA_VERSION,manageEditorSkills:t.manageEditorSkills,decidedAt:typeof t.decidedAt==`string`?t.decidedAt:void 0,surface:typeof t.surface==`string`?t.surface:void 0}}return logger$3.warn({path:t},`skill-management marker malformed — treating as unset`),null}catch(e){return logger$3.warn({err:e,path:t},`skill-management marker unreadable — treating as unset`),null}}async function writeSkillManagement(e,t){let s={version:SCHEMA_VERSION,manageEditorSkills:t.manageEditorSkills,decidedAt:t.now??new Date().toISOString(),...t.surface?{surface:t.surface}:{}},g=skillManagementPath(e);await tracedMkdir(dirname(g),{recursive:!0}),await atomicWriteFile(g,`${JSON.stringify(s,null,2)}\n`,{fs:tracedAtomicFs})}function isProjectSkillManaged(e,t=process.env){if(t.OK_RECLAIM_DISABLE===`1`)return!1;let s=t.OK_SKILL_MANAGE;return s===`1`||s===`true`?!0:s===`0`||s===`false`?!1:readSkillManagement(e)?.manageEditorSkills??!1}const MIN_GIT_VERSION=`2.31.0`,PROBE_TIMEOUT_MS$1=5e3;var GitNotAvailableError=class extends Error{code=`GIT_NOT_AVAILABLE`;platform;guidance;constructor(e,t,s){super(buildMissingMessage(t),s),this.name=`GitNotAvailableError`,this.platform=e,this.guidance=t}},GitTooOldError=class extends Error{code=`GIT_TOO_OLD`;platform;detected;required;resolvedPath;guidance;constructor(e,t,s,g,S,w){super(buildTooOldMessage(t,s,g,S),w),this.name=`GitTooOldError`,this.platform=e,this.detected=t,this.required=s,this.resolvedPath=g,this.guidance=S}};function detectGit(){let e=probeGit(`git`);if(e.kind===`ok`)return{ok:!0,version:e.version,resolvedPath:e.resolvedPath,source:`PATH`};for(let e of fallbackPaths(process.platform)){if(!existsSync(e))continue;let t=probeGit(e);if(t.kind===`ok`)return{ok:!0,version:t.version,resolvedPath:e,source:`fallback`}}throw new GitNotAvailableError(process.platform,buildGuidance(process.platform))}function assertGitAvailable(){let e=detectGit();if(compareSemver(e.version,`2.31.0`)<0)throw new GitTooOldError(process.platform,e.version,MIN_GIT_VERSION,e.resolvedPath,buildGuidance(process.platform));return e}function probeGit(e){let t=spawnSync(e,[`--version`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1,env:{...process.env,LANG:`C`,LC_ALL:`C`}}));if(t.error)return`signal`in t&&t.signal===`SIGTERM`?{kind:`fail`,reason:`timeout`}:{kind:`fail`,reason:`enoent`};if(t.status!==0)return{kind:`fail`,reason:`nonzero`};let s=parseGitVersion(typeof t.stdout==`string`?t.stdout:``);return s===null?{kind:`fail`,reason:`unparseable`}:{kind:`ok`,version:s,resolvedPath:e===`git`?resolveOnPath(`git`)??e:e}}function parseGitVersion(e){let t=e.match(/git version (\d+)\.(\d+)\.(\d+)/);return t?`${t[1]}.${t[2]}.${t[3]}`:null}const SAFE_COMMAND_NAME_RE=/^[a-zA-Z0-9_.-]+$/,resolveOnPathCache=new Map;function resolveOnPath(e){if(!SAFE_COMMAND_NAME_RE.test(e))return null;let t=resolveOnPathCache.get(e);if(t!==void 0)return t;let s;if(process.platform===`win32`){let t=spawnSync(`where`,[e],withHiddenWindowsConsole({encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1}));s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}else{let t=spawnSync(`/bin/sh`,[`-c`,`command -v ${e}`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1}));s=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}return s!==null&&resolveOnPathCache.set(e,s),s}function fallbackPaths(e){switch(e){case`darwin`:return[`/opt/homebrew/bin/git`,`/usr/local/bin/git`,`/Library/Developer/CommandLineTools/usr/bin/git`,`/usr/bin/git`];case`win32`:return[`C:\\Program Files\\Git\\cmd\\git.exe`,`C:\\Program Files (x86)\\Git\\cmd\\git.exe`,join(homedir(),`scoop`,`apps`,`git`,`current`,`cmd`,`git.exe`)];default:return[`/usr/bin/git`,`/usr/local/bin/git`,join(homedir(),`.local`,`bin`,`git`),`/snap/bin/git`]}}function buildGuidance(e){switch(e){case`darwin`:{let e=[];return hasBrew()&&e.push({label:`Install with Homebrew (recommended; no admin needed)`,command:`brew install git`,requiresAdmin:!1}),e.push({label:`Install Xcode Command Line Tools`,command:`xcode-select --install`,requiresAdmin:!0}),{product:`Git`,url:`https://git-scm.com/download/mac`,options:e}}case`win32`:{let e=[];return hasWinget()&&e.push({label:`Install with winget`,command:`winget install --id Git.Git -e --source winget`,requiresAdmin:!0}),hasScoop()&&e.push({label:`Install with Scoop (no admin)`,command:`scoop install git`,requiresAdmin:!1}),hasChoco()&&e.push({label:`Install with Chocolatey`,command:`choco install git -y`,requiresAdmin:!0}),e.push({label:`Download the official installer`,command:`Open https://gitforwindows.org/ in your browser`,requiresAdmin:!1}),{product:`Git for Windows`,url:`https://gitforwindows.org/`,options:e}}default:return{product:`Git`,url:`https://git-scm.com/download/linux`,options:linuxInstallOptions()}}}function linuxInstallOptions(){switch(detectLinuxFamily()){case`debian`:return[{label:`Install with apt`,command:`sudo apt install git`,requiresAdmin:!0}];case`fedora`:return[{label:`Install with dnf`,command:`sudo dnf install git`,requiresAdmin:!0}];case`arch`:return[{label:`Install with pacman`,command:`sudo pacman -S git`,requiresAdmin:!0}];case`opensuse`:return[{label:`Install with zypper`,command:`sudo zypper install git`,requiresAdmin:!0}];case`alpine`:return[{label:`Install with apk`,command:`sudo apk add git`,requiresAdmin:!0}];default:return[{label:`Use your distribution's package manager`,command:`apt / dnf / pacman / zypper / apk install git (one of these will fit your system)`,requiresAdmin:!0}]}}function detectLinuxFamily(e){let t=e;if(t===void 0)try{t=readFileSync(`/etc/os-release`,`utf-8`)}catch{return`unknown`}let s=[/^ID=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``),...(/^ID_LIKE=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``)??``).split(/\s+/)].filter(e=>!!e);return s.some(e=>/^(debian|ubuntu|mint|pop)$/i.test(e))?`debian`:s.some(e=>/^(fedora|rhel|centos|alma|rocky)$/i.test(e))?`fedora`:s.some(e=>/^(arch|manjaro|endeavouros)$/i.test(e))?`arch`:s.some(e=>/^opensuse/i.test(e))||s.includes(`suse`)?`opensuse`:s.some(e=>/^alpine$/i.test(e))?`alpine`:`unknown`}function hasCommand(e){return resolveOnPath(e)!==null}function hasBrew(){return hasCommand(`brew`)}function hasWinget(){return hasCommand(`winget`)}function hasScoop(){return hasCommand(`scoop`)}function hasChoco(){return hasCommand(`choco`)}function buildMissingMessage(e){let t=[];if(t.push(`OpenKnowledge needs ${e.product} to track changes to your knowledge base, but it isn't installed (or isn't on PATH).`),t.push(``),e.options.length>0){t.push(`Install ${e.product}:`);for(let s of e.options){let e=s.requiresAdmin?` (admin required)`:``;t.push(` • ${s.label}${e}`),t.push(` ${s.command}`)}t.push(``)}return t.push(`Or download from: ${e.url}`),t.push(``),t.push(`After installing, re-run OpenKnowledge.`),t.push("Run `ok diagnose health --check git` to verify your installation."),t.join(`
|
|
832
832
|
`)}function buildTooOldMessage(e,t,s,g){let S=[];if(S.push(`OpenKnowledge requires ${g.product} ${t} or newer (detected ${e} at ${s}).`),S.push(``),g.options.length>0){S.push(`Update ${g.product}:`);for(let e of g.options){let t=e.requiresAdmin?` (admin required)`:``;S.push(` • ${e.label}${t}`),S.push(` ${e.command}`)}S.push(``)}return S.push(`Or download from: ${g.url}`),S.push(``),S.push(`After updating, re-run OpenKnowledge.`),S.push("Run `ok diagnose health --check git` to verify your installation."),S.join(`
|
|
833
833
|
`)}function compareSemver(e,t){let s=e.split(`.`).map(e=>Number.parseInt(e,10)||0),g=t.split(`.`).map(e=>Number.parseInt(e,10)||0);for(let e=0;e<3;e++){let t=s[e]??0,S=g[e]??0;if(t!==S)return t-S}return 0}function resolvedHosts(e){let t=PROJECT_SKILL_EDITOR_IDS;return e.filter(e=>t.includes(e))}const RESERVED_SKILL_PREFIX=`open-knowledge`,PACK_SKILL_PREFIX=`open-knowledge-pack-`,SHIPPED_SKILL_NAME=`open-knowledge`,FRONTMATTER_RE=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,CONFLICT_MARKER_RES=[/^<{7} /m,/^={7}$/m,/^>{7} /m];function parseFrontmatter(e){let t=e.match(FRONTMATTER_RE);if(!t)return null;try{let e=(0,import_dist$1.parse)(t[1]??``);return e&&typeof e==`object`&&!Array.isArray(e)?e:null}catch{return null}}function validateSkillForInstall(e,t,s){let g=[],S=join(e,`SKILL.md`),w=existsSync(join(e,`scripts`))&&statSync(join(e,`scripts`)).isDirectory(),E=t.startsWith(RESERVED_SKILL_PREFIX)&&!t.startsWith(`open-knowledge-pack-`);if(!s?.allowReservedName&&E&&g.push(`"${t}" uses the reserved \`${RESERVED_SKILL_PREFIX}*\` prefix (reserved for OK's shipped skills) — choose another name.`),!existsSync(S))return g.push(`No SKILL.md found at ${e}.`),{ok:g.length===0,errors:g,hasScripts:w};let D;try{D=readFileSync(S,`utf-8`)}catch(e){return g.push(`Cannot read SKILL.md: ${e.message}.`),{ok:!1,errors:g,hasScripts:w}}CONFLICT_MARKER_RES.some(e=>e.test(D))&&g.push("SKILL.md contains git conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`). Resolve the conflict before installing.");let O=parseFrontmatter(D);if(O===null)g.push("SKILL.md has no valid `---` frontmatter block (name + description required).");else{let e=O.name,s=O.description;typeof e!=`string`||e.length===0?g.push(`SKILL.md frontmatter.name is missing or empty.`):e!==t&&g.push(`SKILL.md frontmatter.name ("${e}") must equal the skill directory ("${t}").`),(typeof s!=`string`||s.length===0)&&g.push(`SKILL.md frontmatter.description is missing or empty.`),(typeof e==`string`&&containsXmlTag(e)||typeof s==`string`&&containsXmlTag(s))&&g.push("SKILL.md name/description contains XML tags (`<...>`), which break the skill loader.")}return{ok:g.length===0,errors:g,hasScripts:w}}function detectProjectConfiguredTargets(e){return PROJECT_SKILL_EDITOR_IDS.filter(t=>{let s=EDITOR_PROJECT_CONFIG_PATH[t];return s!==null&&existsSync(resolve(e,s))})}function resolveSkillTargets(e,t){if(t&&t.length>0){let e=new Set(PROJECT_SKILL_EDITOR_IDS);return t.filter(t=>e.has(t))}return detectProjectConfiguredTargets(e)}function skillHostDir(e,t,s){let g=EDITOR_PROJECT_SKILL_ROOT[t];return g===null?null:resolve(e,g,s)}function hostSkillsRootEscapes(e,t){if(!existsSync(t))return!1;try{let s=relative(realpathSync(e),realpathSync(t));return s.startsWith(`..`)||isAbsolute(s)}catch{return!0}}function skillLinkTarget(e,t,s){let g=resolve(s),S=relative(resolve(e),g);return S!==``&&!S.startsWith(`..`)&&!isAbsolute(S)?relative(t,g):g}function projectSkill(e,t,s,g){let S=[];for(let w of g){let g=skillHostDir(s,w,t);if(g===null)continue;let E=dirname(g);hostSkillsRootEscapes(s,E)||(tracedRmSync(g,{recursive:!0,force:!0}),tracedMkdirSync(E,{recursive:!0}),tracedSymlinkSync(skillLinkTarget(s,E,e),g,`dir`),S.push(w))}return S}function reverseProjectSkill(e,t,s){let g=[];for(let S of s){let s=skillHostDir(t,S,e);if(s===null)continue;let w=!1;try{lstatSync(s),w=!0}catch{w=!1}w&&(tracedRmSync(s,{recursive:!0,force:!0}),g.push(S))}return g}function projectBundleSkill(e,t){let s;try{s=resolveBundledSkillDir(`project`,{checkDesktop:!0})}catch{return[]}let g=[];for(let S of t){let t=skillHostDir(e,S,SHIPPED_SKILL_NAME);t!==null&&(hostSkillsRootEscapes(e,dirname(t))||(tracedRmSync(t,{recursive:!0,force:!0}),tracedCpSync(s,t,{recursive:!0}),g.push(S)))}return g}function reverseBundleSkill(e,t){return reverseProjectSkill(SHIPPED_SKILL_NAME,e,t)}const MAX_BUNDLED_FILE_BYTES=256*1024;function listSkillFiles(e,t=``){let s=[];for(let g of readdirSync(e,{withFileTypes:!0})){let S=t?`${t}/${g.name}`:g.name;g.isDirectory()?s.push(...listSkillFiles(join(e,g.name),S)):g.isFile()&&s.push(S)}return s.sort()}function readSkillBundledFiles(e){if(!existsSync(e))return[];let t=[];for(let s of listSkillFiles(e)){if(s===`SKILL.md`)continue;let g=null;try{let t=readFileSync(join(e,s));t.length<=MAX_BUNDLED_FILE_BYTES&&!t.includes(0)&&(g=t.toString(`utf-8`))}catch(e){if(e?.code!==`ENOENT`)throw e;g=null}t.push({path:s,text:g})}return t}function isPackSkillName(e){return e.startsWith(PACK_SKILL_PREFIX)}function packIdFromSkillName(e){return isPackSkillName(e)?e.slice(20):null}function readSkillVersion(e){let{frontmatter:t}=stripFrontmatter(e);if(t===``)return;let{map:s}=parseFrontmatterYaml(unwrapFrontmatterFences(t)),g=s?.version;return typeof g==`string`&&g.trim()!==``?g:void 0}function bundledPackSkillDir(e){let t=packIdFromSkillName(e);if(t===null)return null;try{return resolveBundledSkillDir(`packs/${t}`,{checkDesktop:!1})}catch{return null}}function bundledPackVersion(e){let t=bundledPackSkillDir(e);if(t!==null)try{return readSkillVersion(readFileSync(join(t,`SKILL.md`),`utf-8`))}catch{return}}function readBundledPackSkill(e){let t=bundledPackSkillDir(e);if(t===null)return null;let s;try{s=readFileSync(join(t,`SKILL.md`),`utf-8`)}catch{return null}return{content:s,version:readSkillVersion(s)}}function packUpdateAvailable(e,t){return e===void 0?!0:compareSemver(t,e)>0}function computePackUpdateStatus(e,t){let s=bundledPackVersion(e);return s===void 0?{}:{bundledVersion:s,updateAvailable:packUpdateAvailable(t,s)}}const logger$2=getLogger(`skill-reconcile`),SHIPPED_BUNDLE_NAMES=new Set([`open-knowledge`,`open-knowledge-discovery`]);function detectionRoots(){let e=[];for(let t of PROJECT_SKILL_EDITOR_IDS){let s=EDITOR_PROJECT_SKILL_ROOT[t];s!==null&&e.push({rel:s,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function relativeLinkTarget(e,t){let s=relative(e,resolve(t));return isAbsolute(s)?resolve(t):s}const DIRS_EQUAL_MAX_BYTES=1048576;function dirsEqual(e,t){let s=listFiles(e),g=listFiles(t);if(s.length!==g.length)return!1;let S=0;for(let w=0;w<s.length;w+=1){if(s[w]!==g[w])return!1;let E=s[w],D=join(e,E),O=join(t,E);if(S+=statSync(D).size+statSync(O).size,S>DIRS_EQUAL_MAX_BYTES||!readFileSync(D).equals(readFileSync(O)))return!1}return!0}function parseSkillManifest(e){let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{fm:g,body:s}}function skillManifestsSame(e,t){let s=parseSkillManifest(e),g=parseSkillManifest(t);if(s.body!==g.body)return!1;for(let e of Object.keys(s.fm))if(e in g.fm&&JSON.stringify(s.fm[e])!==JSON.stringify(g.fm[e]))return!1;return!0}function sameSkillModuloFrontmatter(e,t){let s=listFiles(e),g=listFiles(t);if(s.length!==g.length)return!1;let S=0;for(let w=0;w<s.length;w+=1){if(s[w]!==g[w])return!1;let E=s[w],D=join(e,E),O=join(t,E);if(S+=statSync(D).size+statSync(O).size,S>DIRS_EQUAL_MAX_BYTES)return!1;let k=readFileSync(D),j=readFileSync(O);if(!k.equals(j)&&(E!==`SKILL.md`||!skillManifestsSame(k.toString(`utf8`),j.toString(`utf8`))))return!1}return!0}function listFiles(e,t=``){let s=[];for(let g of readdirSync(e,{withFileTypes:!0})){let S=t?`${t}/${g.name}`:g.name;g.isDirectory()?s.push(...listFiles(join(e,g.name),S)):g.isFile()&&s.push(S)}return s.sort()}function moveDir(e,t){tracedMkdirSync(dirname(t),{recursive:!0});try{tracedRenameSync(e,t)}catch(s){if(!(s instanceof Error)||s.code!==`EXDEV`)throw s;tracedCpSync(e,t,{recursive:!0}),tracedRmSync(e,{recursive:!0,force:!0})}}function linkInto(e,t,s){tracedRmSync(t,{recursive:!0,force:!0}),tracedMkdirSync(e,{recursive:!0}),tracedSymlinkSync(relativeLinkTarget(e,s),t,`dir`)}function pointsAtSource(e,t){try{let s=readlinkSync(e);return resolve(isAbsolute(s)?s:resolve(dirname(e),s))===resolve(t)}catch{return!1}}function countImportableEditorSkills(e){let{projectDir:t,skillsRoot:s}=e,g=new Set;for(let{rel:e}of detectionRoots()){let S=resolve(t,e);if(!existsSync(S)||hostSkillsRootEscapes(t,S))continue;let w;try{w=readdirSync(S)}catch(e){logger$2.warn({hostRoot:S,err:e.message},`reconcile: skipped unreadable host skills root`);continue}for(let e of w){if(SHIPPED_BUNDLE_NAMES.has(e)||!SKILL_NAME_REGEX.test(e))continue;let t=join(S,e),w;try{w=lstatSync(t)}catch{continue}if(w.isSymbolicLink()||!w.isDirectory())continue;let E=resolve(s,e);existsSync(E)&&(dirsEqual(t,E)||sameSkillModuloFrontmatter(t,E))||g.add(e)}}return g.size}async function reconcileSkillInstalls(e){let{projectDir:t,skillsRoot:s}=e,g={healed:[],adopted:[],replaced:[],collided:[],orphansRemoved:[],skipped:[]},S=isProjectSkillManaged(t),w=new Map,E=(e,t)=>{if(t===null)return;let s=w.get(e)??new Set;s.add(t),w.set(e,s)};for(let{rel:e,editor:w}of detectionRoots()){let D=resolve(t,e);if(!existsSync(D)||hostSkillsRootEscapes(t,D))continue;let O;try{O=readdirSync(D)}catch(e){logger$2.warn({hostRoot:D,err:e.message},`reconcile: skipped unreadable host skills root`);continue}for(let e of O){if(SHIPPED_BUNDLE_NAMES.has(e))continue;let t=join(D,e),O=resolve(s,e),k=existsSync(O);try{let j=lstatSync(t);if(j.isSymbolicLink()){if(pointsAtSource(t,O)&&k)continue;k?(linkInto(D,t,O),g.healed.push({name:e,editor:w})):(tracedRmSync(t,{recursive:!0,force:!0}),g.orphansRemoved.push({name:e,editor:w}));continue}if(!j.isDirectory())continue;if(!SKILL_NAME_REGEX.test(e)){logger$2.warn({skill:e,editor:w},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(k&&(dirsEqual(t,O)||sameSkillModuloFrontmatter(t,O))){linkInto(D,t,O),g.replaced.push({name:e,editor:w}),E(e,w);continue}if(!S){g.skipped.push({name:e,editor:w});continue}if(!k)moveDir(t,O),linkInto(D,t,O),g.adopted.push({name:e,editor:w}),E(e,w);else{let S=`${e}-${w??`agents`}`,O=resolve(s,S);if(existsSync(O)){logger$2.warn({skill:e,editor:w,suffixed:S},`collision: suffixed slot already occupied — skipping (manual resolution needed)`);continue}moveDir(t,O),linkInto(D,join(D,S),O),g.collided.push({name:e,editor:w}),E(S,w)}}catch(t){logger$2.warn({err:t,skill:e,editor:w},`reconcile skipped one skill entry after error`)}}}if(w.size>0){let e=readInstalledSkills(t);for(let[g,S]of w){let w=resolve(s,g);if(!existsSync(w))continue;let E=e.skills[g],D=Array.from(new Set([...E?.hosts??[],...S]));try{await recordSkillInstall(t,g,{hosts:D,scope:E?.scope??`project`,scripts:E?.scripts??validateSkillForInstall(w,g).hasScripts,installedAt:E?.installedAt??new Date().toISOString()})}catch(e){logger$2.warn({err:e,skill:g},`reconcile marker update failed (non-fatal)`)}}}return g}const logger$1=getLogger(`skill-reproject`),SKILL_SURFACE_EDITORS=PROJECT_SKILL_EDITOR_IDS;async function reprojectAllManagedSkills(e){let{projectDir:t,skillsRoot:s,targets:g}=e,S=new Set(g),w=readInstalledSkills(t),E=[];for(let[e,D]of Object.entries(w.skills)){if(D.scope!==`project`)continue;let w=resolvedHosts(D.hosts);try{let O=resolve(s,e),k=!existsSync(O),j=k?null:validateSkillForInstall(O,e);if(k||!j?.ok){!k&&j&&!j.ok&&logger$1.warn({skill:e,errors:j.errors},`managed skill failed validation — left un-projected; fix SKILL.md (e.g. frontmatter.name must equal the folder name)`),reverseProjectSkill(e,t,w),await recordSkillInstall(t,e,{...D,hosts:[]}),E.push({name:e,hosts:[]});continue}let F=w.filter(e=>!S.has(e));F.length>0&&reverseProjectSkill(e,t,F);let L=projectSkill(O,e,t,g);await recordSkillInstall(t,e,{...D,hosts:L}),E.push({name:e,hosts:L})}catch(t){logger$1.warn({err:t,skill:e},`reproject skipped one skill after error`)}}return reverseBundleSkill(t,SKILL_SURFACE_EDITORS.filter(e=>!S.has(e))),{reprojected:E,bundleHosts:projectBundleSkill(t,g)}}const logger=getLogger(`skill-targets-store`);function skillTargetsPath(e){return join(e,...SKILL_TARGETS_REL)}function readSkillTargets(e){let t=skillTargetsPath(e);if(!existsSync(t))return null;try{let e=parseSkillTargets(readFileSync(t,`utf-8`));return e?e.targets:null}catch(e){return logger.warn({err:e,path:t},`skill-targets store unreadable`),null}}async function writeSkillTargets(e,t){let s=Array.from(new Set(t)),g=SkillTargetsSchema.safeParse({schema:1,targets:s});if(!g.success)throw Error(`Refusing to write invalid skill-targets: ${g.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let S=skillTargetsPath(e);await tracedMkdir(dirname(S),{recursive:!0}),await atomicWriteFile(S,`${JSON.stringify(g.data,null,2)}\n`,{fs:tracedAtomicFs})}var UiLockCollisionError=class extends ProcessLockCollisionError{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function acquireUiLock(e,t){try{return acquireProcessLock({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof ProcessLockCollisionError&&e.lockName===`ui`?new UiLockCollisionError(e.existing,e.lockPath):e}}function updateUiLockPort(e,t){updateProcessLockPort({lockName:`ui`,lockDir:e,port:t})}function readUiLock(e){return readProcessLock({lockName:`ui`,lockDir:e})}function releaseUiLock(e,t){releaseProcessLock({lockName:`ui`,lockDir:e,...t})}function markUiLockDraining(e){markProcessLockDraining({lockName:`ui`,lockDir:e})}var UploadWriteError=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function uploadStatusFor(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return assertNeverProblemType(e)}}function classifyUploadErrno(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function uploadTitleFor(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return assertNeverProblemType(e)}}const log$10=getLogger(`upload-streaming`);var HashingPassThrough=class extends Transform{hash=createHash(`sha256`);bytes=0;digested=!1;_transform(e,t,s){this.hash.update(e),this.bytes+=e.length,s(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function tmpUploadDir(e){return resolve(getLocalDir(e),`tmp`)}function mintTempUploadPath(e){let t=tmpUploadDir(e);return tracedMkdirSync(t,{recursive:!0}),resolve(t,`upload-${randomUUID()}`)}function linkTempToFinalWithCollisionRetry(e,t,s){let g=extname(s),S=s.slice(0,s.length-g.length),w=[s,...Array.from({length:99},(e,t)=>`${S}-${t+1}${g}`)];for(let s of w){let g=resolve(t,s);try{tracedLinkSync(e,g);try{tracedUnlinkSync(e)}catch{}return s}catch(t){let s=t.code;if(s===`EEXIST`)continue;try{tracedUnlinkSync(e)}catch{}throw s===`ENOSPC`||s===`EDQUOT`?new UploadWriteError(`urn:ok:error:storage-full`,t):s===`EROFS`||s===`EACCES`||s===`EPERM`?new UploadWriteError(`urn:ok:error:storage-readonly`,t):new UploadWriteError(`urn:ok:error:storage-error`,t)}}try{tracedUnlinkSync(e)}catch{}throw new UploadWriteError(`urn:ok:error:collision-exhaustion`)}function cleanupOrphanUploadTempfiles(e,{ageMs:t=1440*60*1e3}={}){let s=tmpUploadDir(e),g={scanned:0,deleted:0,errors:0};if(!existsSync(s))return g;let S;try{S=readdirSync(s)}catch(e){return log$10.warn({err:e,dir:s},`[upload-tempfile-sweep] readdir failed`),g.errors++,g}let w=Date.now()-t;for(let e of S){if(!e.startsWith(`upload-`))continue;g.scanned++;let t=resolve(s,e);try{if(statSync(t).mtimeMs>=w)continue;tracedUnlinkSync(t),g.deleted++}catch(e){log$10.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),g.errors++}}return(g.deleted>0||g.errors>0)&&log$10.info({dir:s,scanned:g.scanned,deleted:g.deleted,errors:g.errors},`[upload-tempfile-sweep] swept ${g.deleted}/${g.scanned} (errors: ${g.errors})`),g}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let s=t[1],g=s[0];return g!=="`"&&g!==`~`?null:{char:g,length:s.length}}function isFenceClose$2(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$2(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$2(e,t){let s=0;for(;e[t+s]==="`";)s++;if(s===0)return null;let g=t+s,S=g;for(;S<e.length;){if(e[S]!=="`"){S++;continue}let t=0;for(;e[S+t]==="`";)t++;if(t===s)return{nextIndex:S+s};S+=t}return{nextIndex:g}}function readWikiLink$2(e,t){let s=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!s)return null;let g=s[1]?.trim(),S=s[2]?.trim()||null,w=s[3]?.trim()||null;return g?{target:g,alias:w,anchor:S,nextIndex:t+s[0].length}:null}function readWikiLinkOrEmbed(e,t){if(e[t]===`!`&&e[t+1]===`[`&&e[t+2]===`[`){let s=readWikiLink$2(e,t+1);return s?{...s,embed:!0}:null}if(e[t]===`[`&&e[t+1]===`[`){let s=readWikiLink$2(e,t);return s?{...s,embed:!1}:null}return null}function readMarkdownLink$2(e,t){let s=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!s)return null;let g=s[2]??``;return{text:s[1]??``,hrefRaw:g,href:g.startsWith(`<`)&&g.endsWith(`>`)?g.slice(1,-1):g,titleSuffix:s[3]??``,nextIndex:t+s[0].length}}function readImageRef(e,t){let s=/^!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!s)return null;let g=s[2]??``;return{alt:s[1]??``,hrefRaw:g,href:g.startsWith(`<`)&&g.endsWith(`>`)?g.slice(1,-1):g,titleSuffix:s[3]??``,nextIndex:t+s[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),s=[];for(let e=0;e<t.length;e+=2)s.push({line:t[e]??``,ending:t[e+1]??``});return s}function rewriteWikiLinksInLine(e,t,s){let g=``,S=0,w=0,E=leadingMarkdownPrefixLength$2(e);for(E>0&&(g+=e.slice(0,E),w=E);w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let E=readWikiLink$2(e,w);if(E){E.target===t?(g+=`[[${s}${E.anchor?`#${E.anchor}`:``}${E.alias?`|${E.alias}`:``}]]`,S++):g+=e.slice(w,E.nextIndex),w=E.nextIndex;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function recomputeRelativeImageHref(e,t,s){let g=e.indexOf(`#`),S=g>=0?e.slice(g):``,w=g>=0?e.slice(0,g):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``,O=E>=0?w.slice(0,E):w;if(O.startsWith(`/`)||O.startsWith(`//`)||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(O))return null;let k=posix.dirname(t),j=posix.dirname(s);if(k===j)return null;let F=k===`.`?`/`:`/${k}/`,L=posix.resolve(F,O).slice(1),B=posix.relative(j===`.`?``:j,L);return B||=posix.basename(L),O.startsWith(`./`)&&!B.startsWith(`./`)&&!B.startsWith(`../`)&&(B=`./${B}`),`${B}${D}${S}`}function decodeHrefForAssetResolution(e){try{return decodeURI(e)}catch{return e}}function splitHrefPathAndSuffix(e){let t=e.indexOf(`#`),s=t>=0?e.slice(t):``,g=t>=0?e.slice(0,t):e,S=g.indexOf(`?`),w=S>=0?g.slice(S):``;return{pathPart:S>=0?g.slice(0,S):g,suffix:`${w}${s}`}}function buildAssetHrefFromSource(e,t,s,g={}){let S=g.encodePath??!0,w=e=>S?encodeURI(e):e,{pathPart:E,suffix:D}=splitHrefPathAndSuffix(e);if(E.startsWith(`/`))return`/${w(s)}${D}`;let O=posix.dirname(t),k=posix.relative(O===`.`?``:O,s);return k||=posix.basename(s),E.startsWith(`./`)&&!k.startsWith(`./`)&&!k.startsWith(`../`)&&(k=`./${k}`),`${w(k)}${D}`}function rewriteAssetHrefForRename(e,t,s,g,S={}){return resolveAssetProjectPath(decodeHrefForAssetResolution(e),t)===s?buildAssetHrefFromSource(e,t,g,S):null}function recomputeRelativeMarkdownHref(e,t,s){let g=e.indexOf(`#`),S=g>=0?e.slice(g):``,w=g>=0?e.slice(0,g):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``,O=E>=0?w.slice(0,E):w,k=O.startsWith(`/`),j=posix.dirname(t),F=k?`/${s}`:posix.relative(j===`.`?``:j,s);return F||=posix.basename(s),O.endsWith(`.mdx`)?F+=`.mdx`:O.endsWith(`.md`)&&(F+=`.md`),!k&&O.startsWith(`./`)&&!F.startsWith(`./`)&&!F.startsWith(`../`)&&(F=`./${F}`),`${F}${D}${S}`}function rewriteMarkdownLinksInLine(e,t,s,g){let S=``,w=0,E=0,D=leadingMarkdownPrefixLength$2(e);for(D>0&&(S+=e.slice(0,D),E=D);E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e.slice(E,E+2),E+=2;continue}if(e[E]==="`"){let t=readInlineCode$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}if(e[E]===`[`&&e[E+1]===`[`){let t=readWikiLink$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}if(e[E]===`!`&&e[E+1]===`[`){let D=readImageRef(e,E);if(D){let O=t===s&&s!==g?recomputeRelativeImageHref(D.href,s,g):null;if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=``,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}if(e[E]===`[`){let D=readMarkdownLink$2(e,E);if(D){if(resolveInternalHref(D.href,t)?.docName===s){let e=recomputeRelativeMarkdownHref(D.href,t,g),s=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${e}>`:e;S+=`[${D.text}](${s}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}S+=e[E],E++}return{markdown:S,rewrites:w}}function renderWikiLinkOrEmbed(e,t){return`${e.embed?`!`:``}[[${t}${e.anchor?`#${e.anchor}`:``}${e.alias?`|${e.alias}`:``}]]`}const HTML_ASSET_ATTR_RE=/(\s(?:href|src)\s*=\s*)(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function rewriteHtmlAssetAttrsInTag(e,t,s,g){let S=0;return{markdown:e.replace(HTML_ASSET_ATTR_RE,(e,w,E,D,O,k)=>{let j=E??D??O??k;if(typeof j!=`string`)return e;let F=rewriteAssetHrefForRename(j,t,s,g);return F===null?e:(S++,E===void 0?D===void 0?O===void 0?`${w}${F}`:`${w}“${F}”`:`${w}'${F}'`:`${w}"${F}"`)}),rewrites:S}}function rewriteAssetReferencesInLine(e,t,s,g){let S=``,w=0,E=0,D=leadingMarkdownPrefixLength$2(e);for(D>0&&(S+=e.slice(0,D),E=D);E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e.slice(E,E+2),E+=2;continue}if(e[E]==="`"){let t=readInlineCode$2(e,E);if(t){S+=e.slice(E,t.nextIndex),E=t.nextIndex;continue}}let D=readWikiLinkOrEmbed(e,E);if(D){let O=rewriteAssetHrefForRename(D.target,t,s,g,{encodePath:!1});O===null?S+=e.slice(E,D.nextIndex):(S+=renderWikiLinkOrEmbed(D,O),w++),E=D.nextIndex;continue}if(e.startsWith(`<!--`,E)){let t=e.indexOf(`-->`,E+4);if(t===-1){S+=e.slice(E);break}S+=e.slice(E,t+3),E=t+3;continue}if(e[E]===`<`){let D=e.indexOf(`>`,E+1);if(D!==-1){let O=rewriteHtmlAssetAttrsInTag(e.slice(E,D+1),t,s,g);if(O.rewrites>0){S+=O.markdown,w+=O.rewrites,E=D+1;continue}}}if(e[E]===`!`&&e[E+1]===`[`){let D=readImageRef(e,E);if(D){let O=rewriteAssetHrefForRename(D.href,t,s,g);if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=``,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}if(e[E]===`[`){let D=readMarkdownLink$2(e,E);if(D){let O=rewriteAssetHrefForRename(D.href,t,s,g);if(O!==null){let e=D.hrefRaw.startsWith(`<`)&&D.hrefRaw.endsWith(`>`)?`<${O}>`:O;S+=`[${D.text}](${e}${D.titleSuffix})`,w++}else S+=e.slice(E,D.nextIndex);E=D.nextIndex;continue}}S+=e[E],E++}return{markdown:S,rewrites:w}}const MIRROR_TAG_RE=/<Mirror\b([^>]*)\/>/g,MIRROR_SRC_ATTR_RE=/(\bsrc=)(["'])([^"']*)\2/g;function rewriteMirrorSrcInLine(e,t,s){let g=``,S=0,w=0;for(;w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`<`){let E=new RegExp(MIRROR_TAG_RE.source),D=e.slice(w),O=E.exec(D);if(O&&O.index===0){let[e,E]=O,D=new RegExp(MIRROR_SRC_ATTR_RE.source,MIRROR_SRC_ATTR_RE.flags),k=E.replace(D,(e,g,w,E)=>E===t?(S++,`${g}${w}${s}${w}`):e);g+=`<Mirror${k}/>`,w+=e.length;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function rewriteMirrorSrcForDocumentRename(e,t,s){let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteMirrorSrcInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}function rewriteWikiLinksForDocumentRename(e,t,s){let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteWikiLinksInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}function rewriteMarkdownLinksForDocumentRename(e,t,s,g){let S=null,w=0;return{markdown:splitLines(e).map(({line:e,ending:E})=>{if(S)return isFenceClose$2(e,S)&&(S=null),`${e}${E}`;let D=matchFence$2(e);if(D)return S=D,`${e}${E}`;let O=rewriteMarkdownLinksInLine(e,t,s,g);return w+=O.rewrites,`${O.markdown}${E}`}).join(``),rewrites:w}}function rewriteAssetReferencesForRename(e,t,s,g){let S=null,w=0;return{markdown:splitLines(e).map(({line:e,ending:E})=>{if(S)return isFenceClose$2(e,S)&&(S=null),`${e}${E}`;let D=matchFence$2(e);if(D)return S=D,`${e}${E}`;let O=rewriteAssetReferencesInLine(e,t,s,g);return w+=O.rewrites,`${O.markdown}${E}`}).join(``),rewrites:w}}function rewriteOutboundMarkdownLinksInLine(e,t,s){let g=``,S=0,w=0,E=leadingMarkdownPrefixLength$2(e);for(E>0&&(g+=e.slice(0,E),w=E);w<e.length;){if(e[w]===`\\`&&w+1<e.length){g+=e.slice(w,w+2),w+=2;continue}if(e[w]==="`"){let t=readInlineCode$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let t=readWikiLink$2(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`!`&&e[w+1]===`[`){let t=readImageRef(e,w);if(t){g+=e.slice(w,t.nextIndex),w=t.nextIndex;continue}}if(e[w]===`[`){let E=readMarkdownLink$2(e,w);if(E){let D=resolveInternalHref(E.href,t);if(D!==null){let t=recomputeRelativeMarkdownHref(E.href,s,D.docName);if(t!==E.href){let e=E.hrefRaw.startsWith(`<`)&&E.hrefRaw.endsWith(`>`)?`<${t}>`:t;g+=`[${E.text}](${e}${E.titleSuffix})`,S++}else g+=e.slice(w,E.nextIndex)}else g+=e.slice(w,E.nextIndex);w=E.nextIndex;continue}}g+=e[w],w++}return{markdown:g,rewrites:S}}function rewriteOutboundMarkdownLinksForSourceMove(e,t,s){if(posix.dirname(t)===posix.dirname(s))return{markdown:e,rewrites:0};let g=null,S=0;return{markdown:splitLines(e).map(({line:e,ending:w})=>{if(g)return isFenceClose$2(e,g)&&(g=null),`${e}${w}`;let E=matchFence$2(e);if(E)return g=E,`${e}${w}`;let D=rewriteOutboundMarkdownLinksInLine(e,t,s);return S+=D.rewrites,`${D.markdown}${w}`}).join(``),rewrites:S}}var ManagedRenameCollisionError=class extends Error{colliding;constructor(e){super(`Managed rename collision: ${e.map(e=>`'${e.existing}' and '${e.incoming}' both target '${e.to}'`).join(`; `)}`),this.name=`ManagedRenameCollisionError`,this.colliding=e}},ManagedRenameSourceNotFoundError=class extends Error{kind;constructor(e,t=`${e} does not exist`){super(t),this.name=`ManagedRenameSourceNotFoundError`,this.kind=e}},ManagedRenameDestinationExistsError=class extends Error{constructor(){super(`Destination already exists`),this.name=`ManagedRenameDestinationExistsError`}},ManagedRenameSourceTypeMismatchError=class extends Error{kind;constructor(e,t=`Source path is not a ${e}`){super(t),this.name=`ManagedRenameSourceTypeMismatchError`,this.kind=e}},ManagedRenameInvalidRequestError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameInvalidRequestError`}},ManagedRenameReservedPathError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameReservedPathError`}},SymlinkEscapeError=class extends Error{constructor(e){super(`symlink-escape: ${e}`),this.name=`SymlinkEscapeError`}},BacklinkIndexRequiredError=class extends Error{constructor(){super(`Managed rename requires backlink index support`),this.name=`BacklinkIndexRequiredError`}},ManagedRenameSnapshotMissingError=class extends Error{docName;constructor(e){super(`Cannot snapshot missing document: ${e}`),this.name=`ManagedRenameSnapshotMissingError`,this.docName=e}},ManagedRenameMissingDocumentError=class extends Error{docName;constructor(e){super(`Cannot rename missing document: ${e}`),this.name=`ManagedRenameMissingDocumentError`,this.docName=e}};function buildRenameMap(e){let t=new Map,s=[];for(let{from:g,to:S}of e){for(let[e,w]of t)e!==g&&w===S&&s.push({existing:e,incoming:g,to:S});t.set(g,S)}if(s.length>0)throw new ManagedRenameCollisionError(s);return t}function rewriteSupportedLinksForRename(e,t,s,g){let{frontmatter:S,body:w}=stripFrontmatter(e),E=rewriteWikiLinksForDocumentRename(w,s,g),D=rewriteMarkdownLinksForDocumentRename(E.markdown,t,s,g),O=rewriteMirrorSrcForDocumentRename(D.markdown,s,g);return{markdown:prependFrontmatter(S,O.markdown),rewrites:E.rewrites+D.rewrites+O.rewrites}}function applyRenameMap(e,t,s){let g=e,S=0,w,E=[];for(let[e,g]of s)e!==g&&(e===t?w=g:E.push([e,g]));if(w!==void 0){let e=rewriteSupportedLinksForRename(g,t,t,w);g=e.markdown,S+=e.rewrites;let{frontmatter:s,body:E}=stripFrontmatter(g),D=rewriteOutboundMarkdownLinksForSourceMove(E,t,w);g=prependFrontmatter(s,D.markdown),S+=D.rewrites}let D=w??t,O=new Map;for(let[e,t]of E){let s=`__OK_RENAME_${randomUUID().replaceAll(`-`,``)}__`,w=rewriteSupportedLinksForRename(g,D,e,s);w.rewrites>0&&(g=w.markdown,S+=w.rewrites,O.set(s,t))}for(let[e,t]of O)g=rewriteSupportedLinksForRename(g,D,e,t).markdown;return{markdown:g,rewrites:S}}const WIKI_LINK_RE$1=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE$1=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function createEmptyState$1(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function parseSkillBundleDocAnyScope(e){let t=parseProjectSkillBundleDoc(e);if(t)return{name:t.name,kind:t.kind,skillDocName:skillLiveDocName(`project`,t.name)};let s=parseGlobalSkillBundleDoc(e);return s?{name:s.name,kind:s.kind,skillDocName:skillLiveDocName(`global`,s.name)}:null}function mergeLinkMeta(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function getRepresentativeAnchor(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function externalNodeId(e){return`external:${e}`}function externalUrlFromNodeId(e){return e.startsWith(`external:`)?e.slice(9):null}function normalizeSnippet$1(e){return e.replace(/\s+/g,` `).trim()}function snippetAround$1(e,t,s){if(!normalizeSnippet$1(e))return null;let g=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
|
|
834
834
|
`,t-1)),S=[e.indexOf(`.`,s),e.indexOf(`?`,s),e.indexOf(`!`,s),e.indexOf(`
|
|
@@ -852,7 +852,7 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
|
|
|
852
852
|
`,`
|
|
853
853
|
`).replaceAll(`\r`,`
|
|
854
854
|
`).split(`
|
|
855
|
-
`),D=[],O=new Set,k=null,j=(e,t,s)=>{O.has(e)||(O.add(e),D.push({href:e,resolvedTo:t,reason:s}))},F=e=>{let s=e.trim();if(s.startsWith(`#`))return;let w=classifyMarkdownHref(s,t);if(!w){j(s,null,`unresolvable`);return}if(w.kind===`doc`){S.has(w.docName)||j(s,w.docName,`no-such-doc`);return}if(w.kind===`asset`){if(!g)return;let e=resolveAssetProjectPath(w.url,t);if(e===null){j(s,null,`unresolvable`);return}g(e)||j(s,e,`no-such-file`);return}},L=(e,t)=>{let s=classifyWikiLinkTarget(e,t);!s||s.kind!==`doc`||S.has(s.docName)||j(`[[${e}${t?`#${t}`:``}]]`,s.docName,`no-such-doc`)};for(let e of E){if(k){isFenceClose$1(e,k)&&(k=null);continue}let t=matchFence$1(e);if(t){k=t;continue}let s=leadingMarkdownPrefixLength$1(e);for(;s<e.length;){if(e[s]===`\\`&&s+1<e.length){s+=2;continue}if(e[s]==="`"){let t=readInlineCode$1(e,s);if(t){s=t.nextIndex;continue}}if(e[s]===`[`&&e[s+1]===`[`){let t=readWikiLink$1(e,s);if(t){L(t.target,t.anchor),s=t.nextIndex;continue}}if(e[s]===`[`&&e[s-1]!==`!`){let t=readMarkdownLink$1(e,s);if(t){F(t.href),s=t.nextIndex;continue}}s++}}return D}function serializeState(e){return{backward:Object.fromEntries([...e.backward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet}))])),forward:Object.fromEntries([...e.forward.entries()].map(([e,t])=>[e,[...t].sort()])),externalForward:Object.fromEntries([...e.externalForward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url))]))}}function buildExternalBackward(e){let t=new Map;for(let[s,g]of e)for(let[e,S]of g){let g=t.get(e);g||(g=new Map,t.set(e,g)),g.set(s,S)}return t}function deserializeState(e){let t=new Map(Object.entries(e.externalForward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.url,{label:e.label??null,snippet:e.snippet??null}]))]));return{backward:new Map(Object.entries(e.backward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.source,{anchor:e.anchor??null,snippet:e.snippet??null}]))])),forward:new Map(Object.entries(e.forward??{}).map(([e,t])=>[e,new Set(t)])),externalForward:t,externalBackward:buildExternalBackward(t)}}var BacklinkIndex=class{projectDir;contentDir;contentFilter;states=new Map;mtimesByBranch=new Map;activeBranch=`main`;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.states.set(this.activeBranch,createEmptyState$1())}getState(e=this.activeBranch){let t=this.states.get(e);return t||(t=createEmptyState$1(),this.states.set(e,t)),t}structuralBundleNeighbors(e,t=this.activeBranch){let s=parseSkillBundleDocAnyScope(e),g=new Set;if(!s)return g;let S=this.getState(t);if(!S.forward.has(e))return g;if(s.kind===`skill`)for(let t of S.forward.keys()){let s=parseSkillBundleDocAnyScope(t);s?.kind===`reference`&&s.skillDocName===e&&g.add(t)}else S.forward.has(s.skillDocName)&&g.add(s.skillDocName);return g}getActiveBranch(){return this.activeBranch}switchBranch(e){this.activeBranch=e,this.getState(e)}cachePath(e=this.activeBranch){return resolve(getLocalDir(this.projectDir),`cache`,e,`backlinks.json`)}registerNodeOnly(e,t=this.activeBranch){let s=this.getState(t),g=s.forward.get(e)??new Set,S=s.externalForward.get(e)??new Map;for(let t of g){let g=s.backward.get(t);g&&(g.delete(e),g.size===0&&s.backward.delete(t))}for(let t of S.keys()){let g=s.externalBackward.get(t);g&&(g.delete(e),g.size===0&&s.externalBackward.delete(t))}s.forward.set(e,new Set),s.externalForward.set(e,new Map)}registerGlobalSkillBundleNode(e,t=this.activeBranch){parseGlobalSkillBundleDoc(e)&&this.registerNodeOnly(e,t)}updateDocument(e,t,s=[],g=this.activeBranch){if(isLinkIndexExcludedDoc(e))return;if(parseGlobalSkillBundleDoc(e)){this.registerNodeOnly(e,g);return}let S=this.getState(g),w=S.forward.get(e)??new Set,E=S.externalForward.get(e)??new Map;for(let t of w){let s=S.backward.get(t);s&&(s.delete(e),s.size===0&&S.backward.delete(t))}for(let t of E.keys()){let s=S.externalBackward.get(t);s&&(s.delete(e),s.size===0&&S.externalBackward.delete(t))}let D=new Set,O=new Map;S.forward.set(e,D),S.externalForward.set(e,O);for(let s of t){if(!s.target)continue;let t=managedArtifactDocNameFromContentTarget(s.target)??s.target;D.add(t);let g=S.backward.get(t);g||(g=new Map,S.backward.set(t,g)),g.set(e,mergeLinkMeta(g.get(e),{anchor:s.anchor,snippet:s.snippet}))}for(let t of s){if(!t.url)continue;O.set(t.url,{label:t.label,snippet:t.snippet});let s=S.externalBackward.get(t.url);s||(s=new Map,S.externalBackward.set(t.url,s)),(!s.has(e)||!s.get(e)?.snippet&&t.snippet)&&s.set(e,{label:t.label,snippet:t.snippet})}}updateDocumentFromMarkdown(e,t,s=this.activeBranch){try{let{body:g}=stripFrontmatter(t),S=extractWikiLinksFromMarkdown(g,e),w=extractMarkdownLinksFromMarkdown(g,e),E=extractExternalWikiLinksFromMarkdown(g),D=extractExternalMarkdownLinksFromMarkdown(g,e),O=new Set(S.map(e=>e.target)),k=[...S,...w.filter(e=>!O.has(e.target))],j=new Set(E.map(e=>e.url)),F=[...E,...D.filter(e=>!j.has(e.url))];this.updateDocument(e,k,F,s)}catch(t){console.warn(`[backlinks] Failed to scan ${e} for link extraction:`,t),this.deleteDocument(e,s)}}deleteDocument(e,t=this.activeBranch){if(isLinkIndexExcludedDoc(e))return;let s=this.getState(t),g=s.forward.get(e)??new Set,S=s.externalForward.get(e)??new Map;for(let t of g){let g=s.backward.get(t);g&&(g.delete(e),g.size===0&&s.backward.delete(t))}for(let t of S.keys()){let g=s.externalBackward.get(t);g&&(g.delete(e),g.size===0&&s.externalBackward.delete(t))}s.forward.delete(e),s.externalForward.delete(e)}renameDocument(e,t,s,g=this.activeBranch){this.deleteDocument(e,g),this.updateDocumentFromMarkdown(t,s,g)}getBacklinks(e,t=this.activeBranch){let s=this.getState(t).backward.get(e),g=new Map;if(s)for(let[e,t]of s)g.set(e,{source:e,anchor:t.anchor,snippet:t.snippet});for(let s of this.structuralBundleNeighbors(e,t))g.has(s)||g.set(s,{source:s,anchor:null,snippet:null});return[...g.values()].sort((e,t)=>e.source.localeCompare(t.source))}getBacklinkCount(e,t=this.activeBranch){let s=this.getState(t).backward.get(e),g=this.structuralBundleNeighbors(e,t);if(g.size===0)return s?.size??0;let S=new Set(s?.keys()??[]);for(let e of g)S.add(e);return S.size}getForwardLinks(e,t=this.activeBranch){let s=this.getState(t),g=new Set(s.forward.get(e)??new Set);for(let s of this.structuralBundleNeighbors(e,t))g.add(s);return[...g].sort((e,t)=>e.localeCompare(t))}getForwardLinkEntries(e,t=this.activeBranch){let s=this.getState(t),g=this.getForwardLinks(e,t).map(t=>({kind:`doc`,target:t,anchor:s.backward.get(t)?.get(e)?.anchor??null,snippet:s.backward.get(t)?.get(e)?.snippet??null})),S=[...(s.externalForward.get(e)??new Map).entries()].map(([e,t])=>({kind:`external`,url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url));return[...g,...S]}getOrphans(e,t=`both`,s=this.activeBranch){let g=this.getState(s),S=new Set;for(let e of g.forward.keys()){let t=parseSkillBundleDocAnyScope(e);t?.kind===`reference`&&S.add(t.skillDocName)}let w=e=>{let t=parseSkillBundleDocAnyScope(e);return!t||!g.forward.has(e)?!1:t.kind===`skill`?S.has(e):g.forward.has(t.skillDocName)};return[...e].filter(e=>{let s=w(e),S=s||(g.backward.get(e)?.size??0)>0,E=s||(g.forward.get(e)?.size??0)>0;return t===`incoming`?!S:(t===`outgoing`||!S)&&!E}).sort((e,t)=>e.localeCompare(t))}getHubs(e=20,t=this.activeBranch){return[...this.getState(t).backward.entries()].map(([e,t])=>({docName:e,count:t.size})).sort((e,t)=>t.count===e.count?e.docName.localeCompare(t.docName):t.count-e.count).slice(0,e)}getIndexedDocNames(e=this.activeBranch){return[...this.getState(e).forward.keys()]}getDeadLinks(e,t,s=this.activeBranch){let g=this.getState(s),S=new Set(e),w=t?.length?new Set(t):null;return[...g.backward.entries()].filter(([e,t])=>{if(S.has(e)||g.forward.has(e))return!1;if(!w)return t.size>0;for(let e of t.keys())if(w.has(e))return!0;return!1}).map(([e,t])=>({target:e,sources:[...t.entries()].filter(([e])=>!w||w.has(e)).map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet})).sort((e,t)=>e.source.localeCompare(t.source))})).filter(e=>e.sources.length>0).sort((e,t)=>t.sources.length===e.sources.length?e.target.localeCompare(t.target):t.sources.length-e.sources.length)}getLinkGraph(e=this.activeBranch){let t=this.getState(e),s=new Map,g=[];for(let[e,S]of t.forward){s.set(e,{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(t.backward.get(e))});for(let w of S)s.set(w,{kind:`doc`,id:w,docName:w,anchor:getRepresentativeAnchor(t.backward.get(w))}),g.push({source:e,target:w})}for(let[e,S]of t.externalForward){s.set(e,{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(t.backward.get(e))});for(let[t,w]of S){let S=externalNodeId(t);s.set(S,{kind:`external`,id:S,url:t,label:w.label}),g.push({source:e,target:S})}}for(let S of t.forward.keys())if(parseSkillBundleDocAnyScope(S)?.kind===`skill`)for(let w of this.structuralBundleNeighbors(S,e))t.forward.get(S)?.has(w)||t.forward.get(w)?.has(S)||(s.set(S,{kind:`doc`,id:S,docName:S,anchor:getRepresentativeAnchor(t.backward.get(S))}),s.set(w,{kind:`doc`,id:w,docName:w,anchor:getRepresentativeAnchor(t.backward.get(w))}),g.push({source:S,target:w}));return{nodes:[...s.values()].sort((e,t)=>e.id.localeCompare(t.id)),links:g}}getLinkGraphNeighborhood(e,t,s=this.activeBranch){let g=this.getState(s),S=new Map;for(let e of g.externalForward.values())for(let[t,s]of e)S.has(t)||S.set(t,s.label);let w=new Set([e]),E=[{nodeId:e,degree:0}],D=0;for(;D<E.length;){let e=E[D++];if(e.degree>=t)continue;let S=externalUrlFromNodeId(e.nodeId),O=new Set;if(S)for(let e of g.externalBackward.get(S)?.keys()??[])O.add(e);else{for(let t of g.forward.get(e.nodeId)??new Set)O.add(t);for(let t of g.externalForward.get(e.nodeId)?.keys()??[])O.add(externalNodeId(t));for(let t of g.backward.get(e.nodeId)?.keys()??[])O.add(t);for(let t of this.structuralBundleNeighbors(e.nodeId,s))O.add(t)}for(let t of O)w.has(t)||(w.add(t),E.push({nodeId:t,degree:e.degree+1}))}let O=[];for(let[e,t]of g.forward)if(w.has(e))for(let s of t)w.has(s)&&O.push({source:e,target:s});for(let[e,t]of g.externalForward)if(w.has(e))for(let s of t.keys()){let t=externalNodeId(s);w.has(t)&&O.push({source:e,target:t})}for(let e of w)if(parseSkillBundleDocAnyScope(e)?.kind===`skill`)for(let t of this.structuralBundleNeighbors(e,s))w.has(t)&&(g.forward.get(e)?.has(t)||g.forward.get(t)?.has(e)||O.push({source:e,target:t}));return{nodes:[...w].sort().map(e=>{let t=externalUrlFromNodeId(e);return t?{kind:`external`,id:e,url:t,label:S.get(t)??null}:{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(g.backward.get(e))}}),links:O}}async saveToDisk(e=this.activeBranch){let t=this.cachePath(e);mkdirSync(dirname(t),{recursive:!0});let s=this.getState(e),g=this.mtimesByBranch.get(e),S={...serializeState(s),...g?{mtimes:Object.fromEntries(g)}:{}};await writeFile(t,JSON.stringify(S,null,2),`utf-8`)}async loadFromDisk(e=this.activeBranch){let t=this.cachePath(e);if(!existsSync(t))return!1;try{let s=await readFile$1(t,`utf-8`),g=JSON.parse(s);return this.states.set(e,deserializeState(g)),g.mtimes?this.mtimesByBranch.set(e,new Map(Object.entries(g.mtimes))):this.mtimesByBranch.delete(e),!0}catch(t){return console.warn(`[backlinks] Failed to load cache for ${e}:`,t),!1}}clear(e=this.activeBranch){this.states.set(e,createEmptyState$1()),this.mtimesByBranch.delete(e)}async rebuildFromDisk(e=this.activeBranch){let t=createEmptyState$1(),s=new Map,g=[];await this.walkForPaths(this.contentDir,g);let S=new Set,w=g.filter(({docName:e})=>S.has(e)?!1:(S.add(e),!0)),E=50;for(let e=0;e<w.length;e+=50){let g=w.slice(e,e+50),S=await Promise.allSettled(g.map(async({docName:e,filePath:t})=>{let[s,g]=await Promise.all([stat$1(t),readFile$1(t,`utf-8`)]);return{docName:e,mtimeMs:s.mtimeMs,markdown:g}}));for(let e of S){if(e.status===`rejected`){console.warn(`[backlinks] Failed to rebuild entry:`,e.reason);continue}let{docName:g,mtimeMs:S,markdown:w}=e.value;s.set(g,S);let{body:E}=stripFrontmatter(w),D=extractWikiLinksFromMarkdown(E,g),O=extractMarkdownLinksFromMarkdown(E,g),k=extractExternalWikiLinksFromMarkdown(E),j=extractExternalMarkdownLinksFromMarkdown(E,g),F=new Set(D.map(e=>e.target)),L=[...D,...O.filter(e=>!F.has(e.target))],B=new Set(k.map(e=>e.url)),H=[...k,...j.filter(e=>!B.has(e.url))],q=new Set,ee=new Map;t.forward.set(g,q),t.externalForward.set(g,ee);for(let e of L){if(!e.target)continue;let s=managedArtifactDocNameFromContentTarget(e.target)??e.target;q.add(s);let S=t.backward.get(s);S||(S=new Map,t.backward.set(s,S)),S.set(g,mergeLinkMeta(S.get(g),{anchor:e.anchor,snippet:e.snippet}))}for(let e of H){if(!e.url)continue;ee.set(e.url,{label:e.label,snippet:e.snippet});let s=t.externalBackward.get(e.url);s||(s=new Map,t.externalBackward.set(e.url,s)),s.set(g,{label:e.label,snippet:e.snippet})}}}this.states.set(e,t),this.mtimesByBranch.set(e,s)}async walkForPaths(e,t){let s;try{s=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[backlinks] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=toPosix(relative(this.contentDir,s));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkForPaths(s,t)}else if(g.isFile()&&isSupportedDocFile(g.name)){let e=toPosix(relative(this.contentDir,s));if(this.contentFilter?.isExcluded(e))continue;t.push({docName:stripDocExtension(e),filePath:s})}}}async reconcileWithDisk(e=this.activeBranch){if(!existsSync(this.contentDir))return{added:0,updated:0,deleted:0,deletedDocNames:[]};let t=this.mtimesByBranch.get(e)??new Map,s=[];await this.walkForPaths(this.contentDir,s);let g=new Set,S=s.filter(({docName:e})=>g.has(e)?!1:(g.add(e),!0)),w=new Set(S.map(e=>e.docName)),E=new Map,D=0,O=0,k=[],j=await Promise.allSettled(S.map(async({docName:e,filePath:t})=>({docName:e,filePath:t,mtimeMs:(await stat$1(t)).mtimeMs})));for(let e of j){if(e.status===`rejected`)continue;let{docName:s,filePath:g,mtimeMs:S}=e.value,w=t.get(s);if(w!==void 0&&w===S){E.set(s,S);continue}k.push({docName:s,filePath:g,mtimeMs:S,isNew:w===void 0})}let F=50;for(let t=0;t<k.length;t+=50){let s=k.slice(t,t+50),g=await Promise.allSettled(s.map(async({docName:e,filePath:t,mtimeMs:s,isNew:g})=>({docName:e,mtimeMs:s,isNew:g,markdown:await readFile$1(t,`utf-8`)})));for(let t of g){if(t.status===`rejected`){console.warn(`[backlinks] Failed to reconcile file:`,t.reason);continue}let{docName:s,mtimeMs:g,isNew:S,markdown:w}=t.value;this.updateDocumentFromMarkdown(s,w,e),E.set(s,g),S?D++:O++}}let L=0,B=[],H=new Set([...t.keys(),...this.getState(e).forward.keys()]);for(let t of H)parseGlobalSkillBundleDoc(t)||w.has(t)||(this.deleteDocument(t,e),L++,B.push(t));return this.mtimesByBranch.set(e,E),{added:D,updated:O,deleted:L,deletedDocNames:B}}async ingestGlobalSkillBundles(e,t=this.activeBranch){let s=new Set;for(let g of e){if(!existsSync(g))continue;let e;try{e=await readdir(g,{withFileTypes:!0})}catch(e){console.warn(`[backlinks] Failed to read global skills root ${g}:`,e);continue}for(let S of e){if(!S.isDirectory())continue;let e=S.name,w=join(g,e),E=skillLiveDocName(`global`,e);existsSync(join(w,`SKILL.md`))&&parseGlobalSkillBundleDoc(E)&&(this.registerNodeOnly(E,t),s.add(E));let D=[];await this.walkGlobalSkillReferences(join(w,`references`),e,``,D);for(let{docName:e}of D)this.registerNodeOnly(e,t),s.add(e)}}let g=[];for(let e of this.getState(t).forward.keys())parseGlobalSkillBundleDoc(e)&&!s.has(e)&&g.push(e);for(let e of g)this.deleteDocument(e,t)}async walkGlobalSkillReferences(e,t,s,g){let S;try{S=await readdir(e,{withFileTypes:!0})}catch(t){t?.code!==`ENOENT`&&console.warn(`[backlinks] Failed to read skill references dir ${e}:`,t);return}for(let w of S){let S=s?`${s}/${w.name}`:w.name;if(w.isDirectory())await this.walkGlobalSkillReferences(join(e,w.name),t,S,g);else if(w.isFile()&&isSupportedDocFile(w.name)){let e=stripDocExtension(S);g.push({docName:`${MANAGED_ARTIFACT_PREFIX_SKILL}global/${t}/references/${e}`})}}}};let current,bootStartMono;function startBootTimings(e=new Date().toISOString()){current={startedAt:e},bootStartMono=performance.now()}function bootElapsedMs(){if(bootStartMono!==void 0)return Math.round(performance.now()-bootStartMono)}function recordBootPhase(e,t){current&&(current[e]=t)}function setBootField(e,t){current&&(current[e]=t)}function getBootTimings(){return current}function extractActorIdentity(e,t){let s=normalizeSummary(e.summary);if(s.kind===`invalid`)return{kind:`invalid-summary`};let g=parseAgentBodyFields(e),S=t?.()??null;return g.rawAgentId!==void 0&&g.writerId!==void 0?{kind:`agent`,writerId:g.writerId,displayName:g.displayName,colorSeed:g.colorSeed??g.rawAgentId,clientName:g.clientName,clientVersion:g.clientVersion,label:g.label,actor:{principalId:S?.id,agentType:resolveAgentType(g.clientName),clientName:g.clientName,clientVersion:g.clientVersion,label:g.label},summary:s}:S?{kind:`principal`,writerId:S.id,displayName:S.display_name,colorSeed:S.id,actor:{principalId:S.id},summary:s}:{kind:`anonymous`,summary:s}}const ANCESTOR_WALK_DEPTH_LIMIT$1=30;function isProjectRoot(e){try{return statSync(resolve(e,OK_PROJECT_MARKER)).isFile()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function findEnclosingProjectRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT$1;){let e=!1;try{e=isProjectRoot(t)}catch{e=!1}if(e)return{rootPath:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}async function dirtyFilesOverlapWith(e,t){let{git:s}=createGitInstance(e),[g,S]=await Promise.all([listPorcelainPaths(s),listNames(s,[`diff`,`--name-only`,`HEAD..${t}`])]),w=new Set(g);if(w.size===0||S.length===0)return{conflicts:!1,files:[]};let E=new Set;for(let e of S)w.has(e)&&E.add(e);return E.size===0?{conflicts:!1,files:[]}:{conflicts:!0,files:Array.from(E).sort()}}function isValidBranchInfoPath(e,t){if(typeof e!=`string`)return!1;if(e.length===0)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t.length===0||t===`..`||t===`.git`)return!1;return!0}async function computeBranchInfo(e,t,s,g){let{git:S}=createGitInstance(e);await S.raw([`rev-parse`,`--git-dir`]);let w=(async()=>{try{let e=(await S.raw([`symbolic-ref`,`HEAD`])).trim(),t=/^refs\/heads\/(.+)$/.exec(e);return{detached:!1,currentBranch:t?t[1]:null,currentHeadSha:null}}catch{let e=(await S.raw([`rev-parse`,`--short=7`,`HEAD`])).trim();return e.length===0?{detached:!1,currentBranch:null,currentHeadSha:null}:{detached:!0,currentBranch:null,currentHeadSha:e}}})(),E=w.then(async e=>{if(g===`folder`&&s===``)return!0;let t=e.detached?`HEAD`:e.currentBranch;if(!t)return!1;try{return await S.raw([`cat-file`,`-e`,`${t}:${s}`]),!0}catch{return!1}}),D=S.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1),O=(async()=>{let e=`origin/${t}`;if(await S.raw([`rev-parse`,`--verify`,e]).then(()=>!0).catch(()=>!1))return g===`folder`&&s===``?!0:S.raw([`cat-file`,`-e`,`${e}:${s}`]).then(()=>!0).catch(()=>!1)})(),k=dirtyFilesOverlapWith(e,t).catch(e=>{if(isBranchResolutionError(e))return{conflicts:!1,files:[]};let s=truncateError(e);return console.warn(`[git-branch-info] action=dirty-overlap-failed branch=${t} error=${s}`),{conflicts:!1,files:[]}}),[j,F,L,B,H]=await Promise.all([w,E,D,k,O]);return j.detached?{detached:!0,currentBranch:null,currentHeadSha:j.currentHeadSha,shareTargetExists:F,dirtyConflicts:B,branchIsLocal:L,shareTargetOnOriginBranch:H}:{detached:!1,currentBranch:j.currentBranch,currentHeadSha:null,shareTargetExists:F,dirtyConflicts:B,branchIsLocal:L,shareTargetOnOriginBranch:H}}const BRANCH_INFO_HANDLER_TAG=`git-branch-info`;function isBranchResolutionError(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const FF_FETCH_TIMEOUT_MS=15e3,BRANCH_IN_OTHER_WORKTREE_RE=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function isBranchInOtherWorktreeError(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(BRANCH_IN_OTHER_WORKTREE_RE);if(t===null)return{held:!1};let s=t[1];if(s===void 0||s.length===0)return{held:!1};let g;try{g=realpathSync(s)}catch{g=s}return{held:!0,path:g}}const CHECKOUT_HANDLER_TAG=`git-checkout`,isBranchNotFoundFetchError=isBranchNotFoundGitError;async function runCheckoutFlow(e,t,s){if(s?.fastForward&&await fastForwardBranchToOrigin(e,t)===`diverged`)return{ok:!1,reason:`ff-diverged`};let{git:g}=createGitInstance(e),S=await g.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1);if(!S)try{await g.raw([`fetch`,`origin`,t])}catch(e){return{ok:!1,reason:isBranchNotFoundFetchError(e)?`branch-not-found`:`fetch-failed`}}let w=await dirtyFilesOverlapWith(e,S?t:`origin/${t}`);if(w.conflicts)return{ok:!1,reason:`dirty-conflict`,files:w.files};try{return await g.raw([`checkout`,t]),{ok:!0}}catch(e){let s=isBranchInOtherWorktreeError(e);if(s.held)return console.warn(`[git-checkout] reason=branch-in-other-worktree branch=${t} held_at=${s.path}`),{ok:!1,reason:`branch-in-other-worktree`,otherWorktreePath:s.path};let g=truncateError(e);return console.warn(`[git-checkout] action=checkout-failed branch=${t} error=${g}`),{ok:!1,reason:`checkout-failed`}}}async function fastForwardBranchToOrigin(e,t){let{git:s}=createGitInstance(e,{timeoutMs:FF_FETCH_TIMEOUT_MS}),g=e=>s.raw([`rev-parse`,`--verify`,e]).then(e=>e.trim()).catch(()=>null);try{await s.raw([`fetch`,`origin`,t])}catch(e){let s=truncateError(e);return console.warn(`[git-checkout] action=ff-fetch-failed branch=${t} error=${s}`),`unavailable`}let S=await g(`refs/remotes/origin/${t}`);if(!S)return`unavailable`;let w=await g(`refs/heads/${t}`);if(!w||w===S)return`up-to-date`;let E=await s.raw([`merge-base`,w,S]).then(e=>e.trim()).catch(()=>``);if(E===w){try{await s.raw([`fetch`,`origin`,`${t}:${t}`])}catch(e){let s=truncateError(e);return console.warn(`[git-checkout] action=ff-advance-failed branch=${t} error=${s}`),`unavailable`}return await g(`refs/heads/${t}`)===S?`advanced`:`unavailable`}return E===S?`up-to-date`:`diverged`}const defaultGitConfigReader=(e,t,s)=>{let g=spawnSync(`git`,[`config`,s===`worktree`?`--worktree`:s===`local`?`--local`:`--global`,t],{cwd:e,encoding:`utf-8`,timeout:5e3});return g.status!==0||!g.stdout?null:g.stdout.trim()||null};function isLinkedWorktree(e){let t=spawnSync(`git`,[`rev-parse`,`--git-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||s.status!==0?!1:resolve(e,t.stdout.trim())!==resolve(e,s.stdout.trim())}function ensureWorktreeConfigExtension(e){let t=spawnSync(`git`,[`config`,`--local`,`--get`,`extensions.worktreeConfig`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&/^(true|yes|on|1)$/i.test(t.stdout.trim()))return;let s=spawnSync(`git`,[`config`,`--local`,`extensions.worktreeConfig`,`true`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(s.status!==0){let e=s.stderr?.trim()??``,t=s.error?` [${s.error.message}]`:``;throw Error(`failed to enable extensions.worktreeConfig: ${e}${t}`)}}async function resolveGitIdentity(e,t,s,g=defaultGitConfigReader){let S=g(e,`user.name`,`worktree`),w=g(e,`user.email`,`worktree`);if(S&&w)return{name:S,email:w};let E=g(e,`user.name`,`local`),D=g(e,`user.email`,`local`);if(E&&D)return{name:E,email:D};let O=g(e,`user.name`,`global`),k=g(e,`user.email`,`global`);if(O&&k)return{name:O,email:k};if(t&&s){let e=await t.get(s);if(e){let t=e.name??e.login,s=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:s}}}return null}function writeGitIdentity(e,t,s){let g=`--local`;isLinkedWorktree(e)&&(ensureWorktreeConfigExtension(e),g=`--worktree`);let S=(t,s)=>{let S=spawnSync(`git`,[`config`,g,t,s],{cwd:e,encoding:`utf-8`,timeout:5e3});if(S.status!==0){let e=S.stderr?.trim()??``,s=S.error?` [${S.error.message}]`:``;throw Error(`git config ${g} ${t} failed: ${e}${s}`)}};S(`user.name`,t),S(`user.email`,s)}const CONFIG_FILENAME=`config.yml`;function assertNotSymlink(e,t){let s;try{s=lstatSync(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(s.isSymbolicLink())throw Error(`Refusing to follow symlink at ${t} (${e}). An untrusted upstream may have committed this symlink to redirect writes outside the project. Remove the symlink and re-run.`)}function packageVersionMajorMinor(e){let[t=`0`,s=`0`]=e.split(`.`);return`${t.length>0?t:`0`}.${s.length>0?s:`0`}`}function quoteYamlScalar(e){return/^[A-Za-z0-9._\-/]+$/.test(e)?e:JSON.stringify(e)}function buildConfigYmlContent(e,t){let s=`# yaml-language-server: $schema=https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${CONFIG_SCHEMA_MAJOR_PATH}/config.project.schema.json
|
|
855
|
+
`),D=[],O=new Set,k=null,j=(e,t,s)=>{O.has(e)||(O.add(e),D.push({href:e,resolvedTo:t,reason:s}))},F=e=>{let s=e.trim();if(s.startsWith(`#`))return;let w=classifyMarkdownHref(s,t);if(!w){j(s,null,`unresolvable`);return}if(w.kind===`doc`){S.has(w.docName)||j(s,w.docName,`no-such-doc`);return}if(w.kind===`asset`){if(!g)return;let e=resolveAssetProjectPath(w.url,t);if(e===null){j(s,null,`unresolvable`);return}g(e)||j(s,e,`no-such-file`);return}},L=(e,t)=>{let s=classifyWikiLinkTarget(e,t);!s||s.kind!==`doc`||S.has(s.docName)||j(`[[${e}${t?`#${t}`:``}]]`,s.docName,`no-such-doc`)};for(let e of E){if(k){isFenceClose$1(e,k)&&(k=null);continue}let t=matchFence$1(e);if(t){k=t;continue}let s=leadingMarkdownPrefixLength$1(e);for(;s<e.length;){if(e[s]===`\\`&&s+1<e.length){s+=2;continue}if(e[s]==="`"){let t=readInlineCode$1(e,s);if(t){s=t.nextIndex;continue}}if(e[s]===`[`&&e[s+1]===`[`){let t=readWikiLink$1(e,s);if(t){L(t.target,t.anchor),s=t.nextIndex;continue}}if(e[s]===`[`&&e[s-1]!==`!`){let t=readMarkdownLink$1(e,s);if(t){F(t.href),s=t.nextIndex;continue}}s++}}return D}function serializeState(e){return{backward:Object.fromEntries([...e.backward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet}))])),forward:Object.fromEntries([...e.forward.entries()].map(([e,t])=>[e,[...t].sort()])),externalForward:Object.fromEntries([...e.externalForward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url))]))}}function buildExternalBackward(e){let t=new Map;for(let[s,g]of e)for(let[e,S]of g){let g=t.get(e);g||(g=new Map,t.set(e,g)),g.set(s,S)}return t}function deserializeState(e){let t=new Map(Object.entries(e.externalForward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.url,{label:e.label??null,snippet:e.snippet??null}]))]));return{backward:new Map(Object.entries(e.backward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.source,{anchor:e.anchor??null,snippet:e.snippet??null}]))])),forward:new Map(Object.entries(e.forward??{}).map(([e,t])=>[e,new Set(t)])),externalForward:t,externalBackward:buildExternalBackward(t)}}var BacklinkIndex=class{projectDir;contentDir;contentFilter;states=new Map;mtimesByBranch=new Map;activeBranch=`main`;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.states.set(this.activeBranch,createEmptyState$1())}getState(e=this.activeBranch){let t=this.states.get(e);return t||(t=createEmptyState$1(),this.states.set(e,t)),t}structuralBundleNeighbors(e,t=this.activeBranch){let s=parseSkillBundleDocAnyScope(e),g=new Set;if(!s)return g;let S=this.getState(t);if(!S.forward.has(e))return g;if(s.kind===`skill`)for(let t of S.forward.keys()){let s=parseSkillBundleDocAnyScope(t);s?.kind===`reference`&&s.skillDocName===e&&g.add(t)}else S.forward.has(s.skillDocName)&&g.add(s.skillDocName);return g}getActiveBranch(){return this.activeBranch}switchBranch(e){this.activeBranch=e,this.getState(e)}cachePath(e=this.activeBranch){return resolve(getLocalDir(this.projectDir),`cache`,e,`backlinks.json`)}registerNodeOnly(e,t=this.activeBranch){let s=this.getState(t),g=s.forward.get(e)??new Set,S=s.externalForward.get(e)??new Map;for(let t of g){let g=s.backward.get(t);g&&(g.delete(e),g.size===0&&s.backward.delete(t))}for(let t of S.keys()){let g=s.externalBackward.get(t);g&&(g.delete(e),g.size===0&&s.externalBackward.delete(t))}s.forward.set(e,new Set),s.externalForward.set(e,new Map)}registerGlobalSkillBundleNode(e,t=this.activeBranch){parseGlobalSkillBundleDoc(e)&&this.registerNodeOnly(e,t)}updateDocument(e,t,s=[],g=this.activeBranch){if(isLinkIndexExcludedDoc(e))return;if(parseGlobalSkillBundleDoc(e)){this.registerNodeOnly(e,g);return}let S=this.getState(g),w=S.forward.get(e)??new Set,E=S.externalForward.get(e)??new Map;for(let t of w){let s=S.backward.get(t);s&&(s.delete(e),s.size===0&&S.backward.delete(t))}for(let t of E.keys()){let s=S.externalBackward.get(t);s&&(s.delete(e),s.size===0&&S.externalBackward.delete(t))}let D=new Set,O=new Map;S.forward.set(e,D),S.externalForward.set(e,O);for(let s of t){if(!s.target)continue;let t=managedArtifactDocNameFromContentTarget(s.target)??s.target;D.add(t);let g=S.backward.get(t);g||(g=new Map,S.backward.set(t,g)),g.set(e,mergeLinkMeta(g.get(e),{anchor:s.anchor,snippet:s.snippet}))}for(let t of s){if(!t.url)continue;O.set(t.url,{label:t.label,snippet:t.snippet});let s=S.externalBackward.get(t.url);s||(s=new Map,S.externalBackward.set(t.url,s)),(!s.has(e)||!s.get(e)?.snippet&&t.snippet)&&s.set(e,{label:t.label,snippet:t.snippet})}}updateDocumentFromMarkdown(e,t,s=this.activeBranch){try{let{body:g}=stripFrontmatter(t),S=extractWikiLinksFromMarkdown(g,e),w=extractMarkdownLinksFromMarkdown(g,e),E=extractExternalWikiLinksFromMarkdown(g),D=extractExternalMarkdownLinksFromMarkdown(g,e),O=new Set(S.map(e=>e.target)),k=[...S,...w.filter(e=>!O.has(e.target))],j=new Set(E.map(e=>e.url)),F=[...E,...D.filter(e=>!j.has(e.url))];this.updateDocument(e,k,F,s)}catch(t){console.warn(`[backlinks] Failed to scan ${e} for link extraction:`,t),this.deleteDocument(e,s)}}deleteDocument(e,t=this.activeBranch){if(isLinkIndexExcludedDoc(e))return;let s=this.getState(t),g=s.forward.get(e)??new Set,S=s.externalForward.get(e)??new Map;for(let t of g){let g=s.backward.get(t);g&&(g.delete(e),g.size===0&&s.backward.delete(t))}for(let t of S.keys()){let g=s.externalBackward.get(t);g&&(g.delete(e),g.size===0&&s.externalBackward.delete(t))}s.forward.delete(e),s.externalForward.delete(e)}renameDocument(e,t,s,g=this.activeBranch){this.deleteDocument(e,g),this.updateDocumentFromMarkdown(t,s,g)}getBacklinks(e,t=this.activeBranch){let s=this.getState(t).backward.get(e),g=new Map;if(s)for(let[e,t]of s)g.set(e,{source:e,anchor:t.anchor,snippet:t.snippet});for(let s of this.structuralBundleNeighbors(e,t))g.has(s)||g.set(s,{source:s,anchor:null,snippet:null});return[...g.values()].sort((e,t)=>e.source.localeCompare(t.source))}getBacklinkCount(e,t=this.activeBranch){let s=this.getState(t).backward.get(e),g=this.structuralBundleNeighbors(e,t);if(g.size===0)return s?.size??0;let S=new Set(s?.keys()??[]);for(let e of g)S.add(e);return S.size}getForwardLinks(e,t=this.activeBranch){let s=this.getState(t),g=new Set(s.forward.get(e)??new Set);for(let s of this.structuralBundleNeighbors(e,t))g.add(s);return[...g].sort((e,t)=>e.localeCompare(t))}getForwardLinkEntries(e,t=this.activeBranch){let s=this.getState(t),g=this.getForwardLinks(e,t).map(t=>({kind:`doc`,target:t,anchor:s.backward.get(t)?.get(e)?.anchor??null,snippet:s.backward.get(t)?.get(e)?.snippet??null})),S=[...(s.externalForward.get(e)??new Map).entries()].map(([e,t])=>({kind:`external`,url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url));return[...g,...S]}getOrphans(e,t=`both`,s=this.activeBranch){let g=this.getState(s),S=new Set;for(let e of g.forward.keys()){let t=parseSkillBundleDocAnyScope(e);t?.kind===`reference`&&S.add(t.skillDocName)}let w=e=>{let t=parseSkillBundleDocAnyScope(e);return!t||!g.forward.has(e)?!1:t.kind===`skill`?S.has(e):g.forward.has(t.skillDocName)};return[...e].filter(e=>{let s=w(e),S=s||(g.backward.get(e)?.size??0)>0,E=s||(g.forward.get(e)?.size??0)>0;return t===`incoming`?!S:(t===`outgoing`||!S)&&!E}).sort((e,t)=>e.localeCompare(t))}getHubs(e=20,t=this.activeBranch){return[...this.getState(t).backward.entries()].map(([e,t])=>({docName:e,count:t.size})).sort((e,t)=>t.count===e.count?e.docName.localeCompare(t.docName):t.count-e.count).slice(0,e)}getIndexedDocNames(e=this.activeBranch){return[...this.getState(e).forward.keys()]}getDeadLinks(e,t,s=this.activeBranch){let g=this.getState(s),S=new Set(e),w=t?.length?new Set(t):null;return[...g.backward.entries()].filter(([e,t])=>{if(S.has(e)||g.forward.has(e))return!1;if(!w)return t.size>0;for(let e of t.keys())if(w.has(e))return!0;return!1}).map(([e,t])=>({target:e,sources:[...t.entries()].filter(([e])=>!w||w.has(e)).map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet})).sort((e,t)=>e.source.localeCompare(t.source))})).filter(e=>e.sources.length>0).sort((e,t)=>t.sources.length===e.sources.length?e.target.localeCompare(t.target):t.sources.length-e.sources.length)}getLinkGraph(e=this.activeBranch){let t=this.getState(e),s=new Map,g=[];for(let[e,S]of t.forward){s.set(e,{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(t.backward.get(e))});for(let w of S)s.set(w,{kind:`doc`,id:w,docName:w,anchor:getRepresentativeAnchor(t.backward.get(w))}),g.push({source:e,target:w})}for(let[e,S]of t.externalForward){s.set(e,{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(t.backward.get(e))});for(let[t,w]of S){let S=externalNodeId(t);s.set(S,{kind:`external`,id:S,url:t,label:w.label}),g.push({source:e,target:S})}}for(let S of t.forward.keys())if(parseSkillBundleDocAnyScope(S)?.kind===`skill`)for(let w of this.structuralBundleNeighbors(S,e))t.forward.get(S)?.has(w)||t.forward.get(w)?.has(S)||(s.set(S,{kind:`doc`,id:S,docName:S,anchor:getRepresentativeAnchor(t.backward.get(S))}),s.set(w,{kind:`doc`,id:w,docName:w,anchor:getRepresentativeAnchor(t.backward.get(w))}),g.push({source:S,target:w}));return{nodes:[...s.values()].sort((e,t)=>e.id.localeCompare(t.id)),links:g}}getLinkGraphNeighborhood(e,t,s=this.activeBranch){let g=this.getState(s),S=new Map;for(let e of g.externalForward.values())for(let[t,s]of e)S.has(t)||S.set(t,s.label);let w=new Set([e]),E=[{nodeId:e,degree:0}],D=0;for(;D<E.length;){let e=E[D++];if(e.degree>=t)continue;let S=externalUrlFromNodeId(e.nodeId),O=new Set;if(S)for(let e of g.externalBackward.get(S)?.keys()??[])O.add(e);else{for(let t of g.forward.get(e.nodeId)??new Set)O.add(t);for(let t of g.externalForward.get(e.nodeId)?.keys()??[])O.add(externalNodeId(t));for(let t of g.backward.get(e.nodeId)?.keys()??[])O.add(t);for(let t of this.structuralBundleNeighbors(e.nodeId,s))O.add(t)}for(let t of O)w.has(t)||(w.add(t),E.push({nodeId:t,degree:e.degree+1}))}let O=[];for(let[e,t]of g.forward)if(w.has(e))for(let s of t)w.has(s)&&O.push({source:e,target:s});for(let[e,t]of g.externalForward)if(w.has(e))for(let s of t.keys()){let t=externalNodeId(s);w.has(t)&&O.push({source:e,target:t})}for(let e of w)if(parseSkillBundleDocAnyScope(e)?.kind===`skill`)for(let t of this.structuralBundleNeighbors(e,s))w.has(t)&&(g.forward.get(e)?.has(t)||g.forward.get(t)?.has(e)||O.push({source:e,target:t}));return{nodes:[...w].sort().map(e=>{let t=externalUrlFromNodeId(e);return t?{kind:`external`,id:e,url:t,label:S.get(t)??null}:{kind:`doc`,id:e,docName:e,anchor:getRepresentativeAnchor(g.backward.get(e))}}),links:O}}async saveToDisk(e=this.activeBranch){let t=this.cachePath(e);mkdirSync(dirname(t),{recursive:!0});let s=this.getState(e),g=this.mtimesByBranch.get(e),S={...serializeState(s),...g?{mtimes:Object.fromEntries(g)}:{}};await writeFile(t,JSON.stringify(S,null,2),`utf-8`)}async loadFromDisk(e=this.activeBranch){let t=this.cachePath(e);if(!existsSync(t))return!1;try{let s=await readFile$1(t,`utf-8`),g=JSON.parse(s);return this.states.set(e,deserializeState(g)),g.mtimes?this.mtimesByBranch.set(e,new Map(Object.entries(g.mtimes))):this.mtimesByBranch.delete(e),!0}catch(t){return console.warn(`[backlinks] Failed to load cache for ${e}:`,t),!1}}clear(e=this.activeBranch){this.states.set(e,createEmptyState$1()),this.mtimesByBranch.delete(e)}async rebuildFromDisk(e=this.activeBranch){let t=createEmptyState$1(),s=new Map,g=[];await this.walkForPaths(this.contentDir,g);let S=new Set,w=g.filter(({docName:e})=>S.has(e)?!1:(S.add(e),!0)),E=50;for(let e=0;e<w.length;e+=50){let g=w.slice(e,e+50),S=await Promise.allSettled(g.map(async({docName:e,filePath:t})=>{let[s,g]=await Promise.all([stat$1(t),readFile$1(t,`utf-8`)]);return{docName:e,mtimeMs:s.mtimeMs,markdown:g}}));for(let e of S){if(e.status===`rejected`){console.warn(`[backlinks] Failed to rebuild entry:`,e.reason);continue}let{docName:g,mtimeMs:S,markdown:w}=e.value;s.set(g,S);let{body:E}=stripFrontmatter(w),D=extractWikiLinksFromMarkdown(E,g),O=extractMarkdownLinksFromMarkdown(E,g),k=extractExternalWikiLinksFromMarkdown(E),j=extractExternalMarkdownLinksFromMarkdown(E,g),F=new Set(D.map(e=>e.target)),L=[...D,...O.filter(e=>!F.has(e.target))],B=new Set(k.map(e=>e.url)),H=[...k,...j.filter(e=>!B.has(e.url))],q=new Set,ee=new Map;t.forward.set(g,q),t.externalForward.set(g,ee);for(let e of L){if(!e.target)continue;let s=managedArtifactDocNameFromContentTarget(e.target)??e.target;q.add(s);let S=t.backward.get(s);S||(S=new Map,t.backward.set(s,S)),S.set(g,mergeLinkMeta(S.get(g),{anchor:e.anchor,snippet:e.snippet}))}for(let e of H){if(!e.url)continue;ee.set(e.url,{label:e.label,snippet:e.snippet});let s=t.externalBackward.get(e.url);s||(s=new Map,t.externalBackward.set(e.url,s)),s.set(g,{label:e.label,snippet:e.snippet})}}}this.states.set(e,t),this.mtimesByBranch.set(e,s)}async walkForPaths(e,t){let s;try{s=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[backlinks] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=toPosix(relative(this.contentDir,s));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkForPaths(s,t)}else if(g.isFile()&&isSupportedDocFile(g.name)){let e=toPosix(relative(this.contentDir,s));if(this.contentFilter?.isExcluded(e))continue;t.push({docName:stripDocExtension(e),filePath:s})}}}async reconcileWithDisk(e=this.activeBranch){if(!existsSync(this.contentDir))return{added:0,updated:0,deleted:0,deletedDocNames:[]};let t=this.mtimesByBranch.get(e)??new Map,s=[];await this.walkForPaths(this.contentDir,s);let g=new Set,S=s.filter(({docName:e})=>g.has(e)?!1:(g.add(e),!0)),w=new Set(S.map(e=>e.docName)),E=new Map,D=0,O=0,k=[],j=await Promise.allSettled(S.map(async({docName:e,filePath:t})=>({docName:e,filePath:t,mtimeMs:(await stat$1(t)).mtimeMs})));for(let e of j){if(e.status===`rejected`)continue;let{docName:s,filePath:g,mtimeMs:S}=e.value,w=t.get(s);if(w!==void 0&&w===S){E.set(s,S);continue}k.push({docName:s,filePath:g,mtimeMs:S,isNew:w===void 0})}let F=50;for(let t=0;t<k.length;t+=50){let s=k.slice(t,t+50),g=await Promise.allSettled(s.map(async({docName:e,filePath:t,mtimeMs:s,isNew:g})=>({docName:e,mtimeMs:s,isNew:g,markdown:await readFile$1(t,`utf-8`)})));for(let t of g){if(t.status===`rejected`){console.warn(`[backlinks] Failed to reconcile file:`,t.reason);continue}let{docName:s,mtimeMs:g,isNew:S,markdown:w}=t.value;this.updateDocumentFromMarkdown(s,w,e),E.set(s,g),S?D++:O++}}let L=0,B=[],H=new Set([...t.keys(),...this.getState(e).forward.keys()]);for(let t of H)parseGlobalSkillBundleDoc(t)||w.has(t)||(this.deleteDocument(t,e),L++,B.push(t));return this.mtimesByBranch.set(e,E),{added:D,updated:O,deleted:L,deletedDocNames:B}}async ingestGlobalSkillBundles(e,t=this.activeBranch){let s=new Set;for(let g of e){if(!existsSync(g))continue;let e;try{e=await readdir(g,{withFileTypes:!0})}catch(e){console.warn(`[backlinks] Failed to read global skills root ${g}:`,e);continue}for(let S of e){if(!S.isDirectory())continue;let e=S.name,w=join(g,e),E=skillLiveDocName(`global`,e);existsSync(join(w,`SKILL.md`))&&parseGlobalSkillBundleDoc(E)&&(this.registerNodeOnly(E,t),s.add(E));let D=[];await this.walkGlobalSkillReferences(join(w,`references`),e,``,D);for(let{docName:e}of D)this.registerNodeOnly(e,t),s.add(e)}}let g=[];for(let e of this.getState(t).forward.keys())parseGlobalSkillBundleDoc(e)&&!s.has(e)&&g.push(e);for(let e of g)this.deleteDocument(e,t)}async walkGlobalSkillReferences(e,t,s,g){let S;try{S=await readdir(e,{withFileTypes:!0})}catch(t){t?.code!==`ENOENT`&&console.warn(`[backlinks] Failed to read skill references dir ${e}:`,t);return}for(let w of S){let S=s?`${s}/${w.name}`:w.name;if(w.isDirectory())await this.walkGlobalSkillReferences(join(e,w.name),t,S,g);else if(w.isFile()&&isSupportedDocFile(w.name)){let e=stripDocExtension(S);g.push({docName:`${MANAGED_ARTIFACT_PREFIX_SKILL}global/${t}/references/${e}`})}}}};let current,bootStartMono;function startBootTimings(e=new Date().toISOString()){current={startedAt:e},bootStartMono=performance.now()}function bootElapsedMs(){if(bootStartMono!==void 0)return Math.round(performance.now()-bootStartMono)}function recordBootPhase(e,t){current&&(current[e]=t)}function setBootField(e,t){current&&(current[e]=t)}function getBootTimings(){return current}function extractActorIdentity(e,t){let s=normalizeSummary(e.summary);if(s.kind===`invalid`)return{kind:`invalid-summary`};let g=parseAgentBodyFields(e),S=t?.()??null;return g.rawAgentId!==void 0&&g.writerId!==void 0?{kind:`agent`,writerId:g.writerId,displayName:g.displayName,colorSeed:g.colorSeed??g.rawAgentId,clientName:g.clientName,clientVersion:g.clientVersion,label:g.label,actor:{principalId:S?.id,agentType:resolveAgentType(g.clientName),clientName:g.clientName,clientVersion:g.clientVersion,label:g.label},summary:s}:S?{kind:`principal`,writerId:S.id,displayName:S.display_name,colorSeed:S.id,actor:{principalId:S.id},summary:s}:{kind:`anonymous`,summary:s}}const ANCESTOR_WALK_DEPTH_LIMIT$1=30;function isProjectRoot(e){try{return statSync(resolve(e,OK_PROJECT_MARKER)).isFile()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function findEnclosingProjectRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT$1;){let e=!1;try{e=isProjectRoot(t)}catch{e=!1}if(e)return{rootPath:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}async function dirtyFilesOverlapWith(e,t){let{git:s}=createGitInstance(e),[g,S]=await Promise.all([listPorcelainPaths(s),listNames(s,[`diff`,`--name-only`,`HEAD..${t}`])]),w=new Set(g);if(w.size===0||S.length===0)return{conflicts:!1,files:[]};let E=new Set;for(let e of S)w.has(e)&&E.add(e);return E.size===0?{conflicts:!1,files:[]}:{conflicts:!0,files:Array.from(E).sort()}}function isValidBranchInfoPath(e,t){if(typeof e!=`string`)return!1;if(e.length===0)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t.length===0||t===`..`||t===`.git`)return!1;return!0}async function computeBranchInfo(e,t,s,g){let{git:S}=createGitInstance(e);await S.raw([`rev-parse`,`--git-dir`]);let w=(async()=>{try{let e=(await S.raw([`symbolic-ref`,`HEAD`])).trim(),t=/^refs\/heads\/(.+)$/.exec(e);return{detached:!1,currentBranch:t?t[1]:null,currentHeadSha:null}}catch{let e=(await S.raw([`rev-parse`,`--short=7`,`HEAD`])).trim();return e.length===0?{detached:!1,currentBranch:null,currentHeadSha:null}:{detached:!0,currentBranch:null,currentHeadSha:e}}})(),E=w.then(async e=>{if(g===`folder`&&s===``)return!0;let t=e.detached?`HEAD`:e.currentBranch;if(!t)return!1;try{return await S.raw([`cat-file`,`-e`,`${t}:${s}`]),!0}catch{return!1}}),D=S.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1),O=(async()=>{let e=`origin/${t}`;if(await S.raw([`rev-parse`,`--verify`,e]).then(()=>!0).catch(()=>!1))return g===`folder`&&s===``?!0:S.raw([`cat-file`,`-e`,`${e}:${s}`]).then(()=>!0).catch(()=>!1)})(),k=dirtyFilesOverlapWith(e,t).catch(e=>{if(isBranchResolutionError(e))return{conflicts:!1,files:[]};let s=truncateError(e);return console.warn(`[git-branch-info] action=dirty-overlap-failed branch=${t} error=${s}`),{conflicts:!1,files:[]}}),[j,F,L,B,H]=await Promise.all([w,E,D,k,O]);return j.detached?{detached:!0,currentBranch:null,currentHeadSha:j.currentHeadSha,shareTargetExists:F,dirtyConflicts:B,branchIsLocal:L,shareTargetOnOriginBranch:H}:{detached:!1,currentBranch:j.currentBranch,currentHeadSha:null,shareTargetExists:F,dirtyConflicts:B,branchIsLocal:L,shareTargetOnOriginBranch:H}}const BRANCH_INFO_HANDLER_TAG=`git-branch-info`;function isBranchResolutionError(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const FF_FETCH_TIMEOUT_MS=15e3,BRANCH_IN_OTHER_WORKTREE_RE=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function isBranchInOtherWorktreeError(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(BRANCH_IN_OTHER_WORKTREE_RE);if(t===null)return{held:!1};let s=t[1];if(s===void 0||s.length===0)return{held:!1};let g;try{g=realpathSync(s)}catch{g=s}return{held:!0,path:g}}const CHECKOUT_HANDLER_TAG=`git-checkout`,isBranchNotFoundFetchError=isBranchNotFoundGitError;async function runCheckoutFlow(e,t,s){if(s?.fastForward&&await fastForwardBranchToOrigin(e,t)===`diverged`)return{ok:!1,reason:`ff-diverged`};let{git:g}=createGitInstance(e),S=await g.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1);if(!S)try{await g.raw([`fetch`,`origin`,t])}catch(e){return{ok:!1,reason:isBranchNotFoundFetchError(e)?`branch-not-found`:`fetch-failed`}}let w=await dirtyFilesOverlapWith(e,S?t:`origin/${t}`);if(w.conflicts)return{ok:!1,reason:`dirty-conflict`,files:w.files};try{return await g.raw([`checkout`,t]),{ok:!0}}catch(e){let s=isBranchInOtherWorktreeError(e);if(s.held)return console.warn(`[git-checkout] reason=branch-in-other-worktree branch=${t} held_at=${s.path}`),{ok:!1,reason:`branch-in-other-worktree`,otherWorktreePath:s.path};let g=truncateError(e);return console.warn(`[git-checkout] action=checkout-failed branch=${t} error=${g}`),{ok:!1,reason:`checkout-failed`}}}async function fastForwardBranchToOrigin(e,t){let{git:s}=createGitInstance(e,{timeoutMs:FF_FETCH_TIMEOUT_MS}),g=e=>s.raw([`rev-parse`,`--verify`,e]).then(e=>e.trim()).catch(()=>null);try{await s.raw([`fetch`,`origin`,t])}catch(e){let s=truncateError(e);return console.warn(`[git-checkout] action=ff-fetch-failed branch=${t} error=${s}`),`unavailable`}let S=await g(`refs/remotes/origin/${t}`);if(!S)return`unavailable`;let w=await g(`refs/heads/${t}`);if(!w||w===S)return`up-to-date`;let E=await s.raw([`merge-base`,w,S]).then(e=>e.trim()).catch(()=>``);if(E===w){try{await s.raw([`fetch`,`origin`,`${t}:${t}`])}catch(e){let s=truncateError(e);return console.warn(`[git-checkout] action=ff-advance-failed branch=${t} error=${s}`),`unavailable`}return await g(`refs/heads/${t}`)===S?`advanced`:`unavailable`}return E===S?`up-to-date`:`diverged`}const defaultGitConfigReader=(e,t,s)=>{let g=spawnSync(`git`,[`config`,s===`worktree`?`--worktree`:s===`local`?`--local`:`--global`,t],withHiddenWindowsConsole({cwd:e,encoding:`utf-8`,timeout:5e3}));return g.status!==0||!g.stdout?null:g.stdout.trim()||null};function isLinkedWorktree(e){let t=spawnSync(`git`,[`rev-parse`,`--git-dir`],withHiddenWindowsConsole({cwd:e,encoding:`utf-8`,timeout:5e3})),s=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],withHiddenWindowsConsole({cwd:e,encoding:`utf-8`,timeout:5e3}));return t.status!==0||s.status!==0?!1:resolve(e,t.stdout.trim())!==resolve(e,s.stdout.trim())}function ensureWorktreeConfigExtension(e){let t=spawnSync(`git`,[`config`,`--local`,`--get`,`extensions.worktreeConfig`],withHiddenWindowsConsole({cwd:e,encoding:`utf-8`,timeout:5e3}));if(t.status===0&&/^(true|yes|on|1)$/i.test(t.stdout.trim()))return;let s=spawnSync(`git`,[`config`,`--local`,`extensions.worktreeConfig`,`true`],withHiddenWindowsConsole({cwd:e,encoding:`utf-8`,timeout:5e3}));if(s.status!==0){let e=s.stderr?.trim()??``,t=s.error?` [${s.error.message}]`:``;throw Error(`failed to enable extensions.worktreeConfig: ${e}${t}`)}}async function resolveGitIdentity(e,t,s,g=defaultGitConfigReader){let S=g(e,`user.name`,`worktree`),w=g(e,`user.email`,`worktree`);if(S&&w)return{name:S,email:w};let E=g(e,`user.name`,`local`),D=g(e,`user.email`,`local`);if(E&&D)return{name:E,email:D};let O=g(e,`user.name`,`global`),k=g(e,`user.email`,`global`);if(O&&k)return{name:O,email:k};if(t&&s){let e=await t.get(s);if(e){let t=e.name??e.login,s=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:s}}}return null}function writeGitIdentity(e,t,s){let g=`--local`;isLinkedWorktree(e)&&(ensureWorktreeConfigExtension(e),g=`--worktree`);let S=(t,s)=>{let S=spawnSync(`git`,[`config`,g,t,s],withHiddenWindowsConsole({cwd:e,encoding:`utf-8`,timeout:5e3}));if(S.status!==0){let e=S.stderr?.trim()??``,s=S.error?` [${S.error.message}]`:``;throw Error(`git config ${g} ${t} failed: ${e}${s}`)}};S(`user.name`,t),S(`user.email`,s)}const CONFIG_FILENAME=`config.yml`;function assertNotSymlink(e,t){let s;try{s=lstatSync(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(s.isSymbolicLink())throw Error(`Refusing to follow symlink at ${t} (${e}). An untrusted upstream may have committed this symlink to redirect writes outside the project. Remove the symlink and re-run.`)}function packageVersionMajorMinor(e){let[t=`0`,s=`0`]=e.split(`.`);return`${t.length>0?t:`0`}.${s.length>0?s:`0`}`}function quoteYamlScalar(e){return/^[A-Za-z0-9._\-/]+$/.test(e)?e:JSON.stringify(e)}function buildConfigYmlContent(e,t){let s=`# yaml-language-server: $schema=https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${CONFIG_SCHEMA_MAJOR_PATH}/config.project.schema.json
|
|
856
856
|
# OpenKnowledge — project configuration
|
|
857
857
|
#
|
|
858
858
|
# This file overrides built-in defaults for this project. Every key below
|
|
@@ -952,7 +952,7 @@ last-spawn-error.log
|
|
|
952
952
|
# !keep.md # re-include a file .gitignore excluded
|
|
953
953
|
`,ROOT_GITIGNORE_TEMPLATE=`# Seeded by OpenKnowledge when this project was created. Edit freely.
|
|
954
954
|
.DS_Store
|
|
955
|
-
`;function initContent(e,t){let s=resolve(e,`.ok`),g=[],S=[],w=[];assertNotSymlink(s,`.ok/`),tracedMkdirSync(s,{recursive:!0});let E=ensureGitignoreEntries(join(s,`.gitignore`),OK_GITIGNORE_CONTENT);return E===`created`?g.push(`.gitignore`):E===`updated`?S.push(`.gitignore`):w.push(`.gitignore`),writeIfMissing(join(s,`config.yml`),buildConfigYmlContent(t?.packageVersion??`0.0.0`,{contentDir:t?.contentDir}),`.ok/config.yml`)?g.push(CONFIG_FILENAME):w.push(CONFIG_FILENAME),writeIfMissing(join(e,`.okignore`),OK_OKIGNORE_TEMPLATE,`.okignore`)?g.push(`.okignore`):w.push(`.okignore`),{created:g,updated:S,skipped:w}}function writeRootGitignoreForNewRepo(e){return writeIfMissing(join(e,`.gitignore`),ROOT_GITIGNORE_TEMPLATE,`.gitignore`)?`created`:`skipped`}const ALLOWED_URL_PATTERNS=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],BLOCKED_URL_PATTERNS=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function isAllowedGitUrl(e){return!e||typeof e!=`string`||BLOCKED_URL_PATTERNS.some(t=>t.test(e))?!1:ALLOWED_URL_PATTERNS.some(t=>t.test(e))}function expandTilde(e){return e===`~`?homedir():e.startsWith(`~/`)?join(homedir(),e.slice(2)):e}function ancestorChainHasSymlink(e,t){let s=dirname(e);for(;s!==t&&s!==dirname(s);){let e;try{e=lstatSync(s)}catch(e){let t=e.code;return console.warn(`[local-op-security] ancestorChainHasSymlink: lstat failed on ${s} (${t??`unknown`}); treating as symlink (fail-closed)`),!0}if(e.isSymbolicLink())return console.warn(`[local-op-security] ancestorChainHasSymlink: symlink detected at ${s}`),!0;s=dirname(s)}return!1}function isPathWithinHome(e,t){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let s;try{s=realpathSync(t)}catch(e){let s=e.code;return console.warn(`[local-op-security] realpath failed on home dir ${t} (${s??`unknown`}); rejecting all paths`),!1}let g=resolve(expandTilde(e)),S=[],w=g;for(;;){let e=null;try{e=lstatSync(w)}catch(e){let t=e.code;if(t!==`ENOENT`)return console.warn(`[local-op-security] lstat error at ${w} (${t??`unknown`}); rejecting`),!1}if(e!==null){let g;try{g=realpathSync(w)}catch(s){let S=s.code;if(e.isSymbolicLink())return console.warn(`[local-op-security] realpath failed on symlink leaf at ${w} (${S??`unknown`}); rejecting`),!1;if(S===`EPERM`||S===`EACCES`){if(ancestorChainHasSymlink(w,t))return console.warn(`[local-op-security] EPERM accept-branch refused at ${w}: symlinked ancestor in chain; rejecting`),!1;console.warn(`[local-op-security] realpath denied on non-symlink leaf at ${w} (${S??`unknown`}); trusting lexical path (TCC-class)`),g=w}else return console.warn(`[local-op-security] realpath failed on non-symlink leaf at ${w} (${S??`unknown`}); rejecting`),!1}let E=S.length===0?g:join(g,...S),D=relative(s,E);return D===``||!D.startsWith(`..`)&&!isAbsolute(D)}let g=dirname(w);if(g===w)return!1;S.unshift(basename(w)),w=g}}function isSafeLocalPath(e){return isPathWithinHome(e,homedir())}function isLoopbackRequest(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function hasValidLocalOpOrigin(e){let t=e.headers.origin;if(!t)return!0;try{let{hostname:e}=new URL(t);return e===`127.0.0.1`||e===`localhost`||e===`[::1]`||e===`::1`}catch{return!1}}function checkLocalOpSecurity(e,t,s){return isLoopbackRequest(e)?hasValidLocalOpOrigin(e)?!0:(errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin header is not a permitted loopback origin.`,{handler:s.handler}),!1):(errorResponse(t,403,`urn:ok:error:loopback-required`,`Local-op endpoints require a loopback connection.`,{handler:s.handler}),!1)}function createConcurrencyGuard(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}function runSubprocess(e){let[t,...s]=e.cliArgs;if(!t)return{done:Promise.resolve({code:-1,stderr:`no command provided`,timedOut:!1,cancelled:!1}),cancel:()=>{}};let g=[...s,...e.trailingArgs],S=!1,w=!1,E=``,D=[],O={...process.env};e.extraPathDirs&&e.extraPathDirs.length>0&&(O.PATH=[...e.extraPathDirs,process.env.PATH??``].filter(Boolean).join(delimiter));let k=spawn(t,g,{cwd:e.cwd,
|
|
955
|
+
`;function initContent(e,t){let s=resolve(e,`.ok`),g=[],S=[],w=[];assertNotSymlink(s,`.ok/`),tracedMkdirSync(s,{recursive:!0});let E=ensureGitignoreEntries(join(s,`.gitignore`),OK_GITIGNORE_CONTENT);return E===`created`?g.push(`.gitignore`):E===`updated`?S.push(`.gitignore`):w.push(`.gitignore`),writeIfMissing(join(s,`config.yml`),buildConfigYmlContent(t?.packageVersion??`0.0.0`,{contentDir:t?.contentDir}),`.ok/config.yml`)?g.push(CONFIG_FILENAME):w.push(CONFIG_FILENAME),writeIfMissing(join(e,`.okignore`),OK_OKIGNORE_TEMPLATE,`.okignore`)?g.push(`.okignore`):w.push(`.okignore`),{created:g,updated:S,skipped:w}}function writeRootGitignoreForNewRepo(e){return writeIfMissing(join(e,`.gitignore`),ROOT_GITIGNORE_TEMPLATE,`.gitignore`)?`created`:`skipped`}const ALLOWED_URL_PATTERNS=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],BLOCKED_URL_PATTERNS=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function isAllowedGitUrl(e){return!e||typeof e!=`string`||BLOCKED_URL_PATTERNS.some(t=>t.test(e))?!1:ALLOWED_URL_PATTERNS.some(t=>t.test(e))}function expandTilde(e){return e===`~`?homedir():e.startsWith(`~/`)?join(homedir(),e.slice(2)):e}function ancestorChainHasSymlink(e,t){let s=dirname(e);for(;s!==t&&s!==dirname(s);){let e;try{e=lstatSync(s)}catch(e){let t=e.code;return console.warn(`[local-op-security] ancestorChainHasSymlink: lstat failed on ${s} (${t??`unknown`}); treating as symlink (fail-closed)`),!0}if(e.isSymbolicLink())return console.warn(`[local-op-security] ancestorChainHasSymlink: symlink detected at ${s}`),!0;s=dirname(s)}return!1}function isPathWithinHome(e,t){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let s;try{s=realpathSync(t)}catch(e){let s=e.code;return console.warn(`[local-op-security] realpath failed on home dir ${t} (${s??`unknown`}); rejecting all paths`),!1}let g=resolve(expandTilde(e)),S=[],w=g;for(;;){let e=null;try{e=lstatSync(w)}catch(e){let t=e.code;if(t!==`ENOENT`)return console.warn(`[local-op-security] lstat error at ${w} (${t??`unknown`}); rejecting`),!1}if(e!==null){let g;try{g=realpathSync(w)}catch(s){let S=s.code;if(e.isSymbolicLink())return console.warn(`[local-op-security] realpath failed on symlink leaf at ${w} (${S??`unknown`}); rejecting`),!1;if(S===`EPERM`||S===`EACCES`){if(ancestorChainHasSymlink(w,t))return console.warn(`[local-op-security] EPERM accept-branch refused at ${w}: symlinked ancestor in chain; rejecting`),!1;console.warn(`[local-op-security] realpath denied on non-symlink leaf at ${w} (${S??`unknown`}); trusting lexical path (TCC-class)`),g=w}else return console.warn(`[local-op-security] realpath failed on non-symlink leaf at ${w} (${S??`unknown`}); rejecting`),!1}let E=S.length===0?g:join(g,...S),D=relative(s,E);return D===``||!D.startsWith(`..`)&&!isAbsolute(D)}let g=dirname(w);if(g===w)return!1;S.unshift(basename(w)),w=g}}function isSafeLocalPath(e){return isPathWithinHome(e,homedir())}function isLoopbackRequest(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function hasValidLocalOpOrigin(e){let t=e.headers.origin;if(!t)return!0;try{let{hostname:e}=new URL(t);return e===`127.0.0.1`||e===`localhost`||e===`[::1]`||e===`::1`}catch{return!1}}function checkLocalOpSecurity(e,t,s){return isLoopbackRequest(e)?hasValidLocalOpOrigin(e)?!0:(errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin header is not a permitted loopback origin.`,{handler:s.handler}),!1):(errorResponse(t,403,`urn:ok:error:loopback-required`,`Local-op endpoints require a loopback connection.`,{handler:s.handler}),!1)}function createConcurrencyGuard(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}const SUBPROCESS_PIPE_STDIO_OPTIONS={stdio:[`ignore`,`pipe`,`pipe`]};function runSubprocess(e){let[t,...s]=e.cliArgs;if(!t)return{done:Promise.resolve({code:-1,stderr:`no command provided`,timedOut:!1,cancelled:!1}),cancel:()=>{}};let g=[...s,...e.trailingArgs],S=!1,w=!1,E=``,D=[],O={...process.env};e.extraPathDirs&&e.extraPathDirs.length>0&&(O.PATH=[...e.extraPathDirs,process.env.PATH??``].filter(Boolean).join(delimiter));let k=spawn(t,g,withHiddenWindowsConsole({...SUBPROCESS_PIPE_STDIO_OPTIONS,cwd:e.cwd,env:O})),j=setTimeout(()=>{S=!0,k.kill(`SIGTERM`)},e.timeoutMs),F=t=>{if(!t.trim())return;let s=null;try{let e=JSON.parse(t);s=e&&typeof e==`object`?e:null}catch{s=null}e.onLine({raw:t,parsed:s})};return k.stdout.on(`data`,e=>{E+=e.toString(`utf-8`);let t=E.split(`
|
|
956
956
|
`);E=t.pop()??``;for(let e of t)F(e)}),k.stderr.on(`data`,t=>{D.push(t),e.onStderr?.(t)}),{done:new Promise(e=>{k.on(`close`,t=>{clearTimeout(j),E.trim()&&F(E),E=``,e({code:t,stderr:Buffer.concat(D).toString(`utf-8`).trim(),timedOut:S,cancelled:w})}),k.on(`error`,t=>{clearTimeout(j),D.push(Buffer.from(t.message,`utf-8`)),e({code:-1,stderr:Buffer.concat(D).toString(`utf-8`).trim(),timedOut:S,cancelled:w})})}),cancel:()=>{if(!w&&(w=!0,!k.killed))try{k.kill(`SIGTERM`)}catch{}}}}const DEFAULT_TIMEOUT_MS$3=600*1e3;function asAuthEvent(e){let t=e.type;return t===`verification`?typeof e.user_code==`string`&&typeof e.verification_uri==`string`&&typeof e.expires_in==`number`?{type:`verification`,user_code:e.user_code,verification_uri:e.verification_uri,expires_in:e.expires_in}:null:t===`complete`?{type:`complete`,host:typeof e.host==`string`?e.host:``,login:typeof e.login==`string`?e.login:``,name:typeof e.name==`string`?e.name:void 0,email:typeof e.email==`string`?e.email:void 0,avatarUrl:typeof e.avatarUrl==`string`?e.avatarUrl:void 0}:t===`error`?{type:`error`,message:typeof e.message==`string`?e.message:`Unknown error`}:null}function runDeviceFlowSubprocess(e){let t=e.host??`github.com`,s=e.timeoutMs??DEFAULT_TIMEOUT_MS$3,g=!1,S=runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`auth`,`login`,`--json`,`--host`,t],timeoutMs:s,onLine:({parsed:t})=>{if(!t)return;let s=asAuthEvent(t);s&&((s.type===`complete`||s.type===`error`)&&(g=!0),e.onEvent(s))}});return{done:S.done.then(s=>{g||(s.code===0?e.onEvent({type:`complete`,host:t,login:``}):e.onEvent({type:`error`,message:s.timedOut?`Sign-in timed out`:`auth login exited with code ${s.code??-1}`}))}),cancel:S.cancel}}const DEFAULT_TIMEOUT_MS$2=3e4;async function runAuthStatusSubprocess(e){let t=e.host??`github.com`,s=[],g=await runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`auth`,`status`,`--json`,`--host`,t],timeoutMs:e.timeoutMs??DEFAULT_TIMEOUT_MS$2,onLine:({parsed:e})=>{e&&s.push(e)}}).done;for(let e=s.length-1;e>=0;e--){let g=s[e];if(g.type!==`status`)continue;let S=typeof g.host==`string`?g.host:t;if(g.authenticated===!0&&typeof g.login==`string`){let e=g.tier===`A`||g.tier===`B`||g.tier===`C`?g.tier:void 0;return{authenticated:!0,host:S,login:g.login,tier:e,name:typeof g.name==`string`?g.name:void 0,email:typeof g.email==`string`?g.email:void 0}}return{authenticated:!1,host:S,error:typeof g.error==`string`?g.error:void 0}}return{authenticated:!1,host:t,error:g.timedOut?`auth status timed out`:g.code===0?void 0:g.stderr||`auth status exited with code ${g.code??-1}`}}async function runAuthReposSubprocess(e){let t=e.host??`github.com`,s=[],g=await runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`auth`,`repos`,`--json`,`--host`,t],timeoutMs:e.timeoutMs??DEFAULT_TIMEOUT_MS$2,onLine:({parsed:e})=>{e&&s.push(e)}}).done;if(g.timedOut)return{ok:!1,error:`auth repos timed out`};if(g.code!==0)return{ok:!1,error:g.stderr||`auth repos exited with code ${g.code??-1}`};for(let e=s.length-1;e>=0;e--){let g=s[e];if(g.type!==`repos`||!Array.isArray(g.repos))continue;let S=[];for(let e of g.repos){if(!e||typeof e!=`object`)continue;let t=e;typeof t.full_name!=`string`||typeof t.clone_url!=`string`||S.push({full_name:t.full_name,clone_url:t.clone_url,private:t.private===!0})}return{ok:!0,host:typeof g.host==`string`?g.host:t,repos:S}}return{ok:!1,error:`auth repos returned no data`}}const GENERIC_TITLE=`Clone subprocess reported an error.`,MAX_DETAIL_LEN=500;function classifyCloneError(e){let t=redactShareSubprocessStderr(e).trim().slice(0,MAX_DETAIL_LEN);return t.length===0?{title:GENERIC_TITLE,detail:``}:/repository not found|returned error:\s*404/i.test(t)?{title:`Can't access this repository. It may be private, or you may not have access.`,detail:t}:/permission denied|access denied|returned error:\s*403/i.test(t)?{title:`You don't have access to this repository.`,detail:t}:/authentication failed/i.test(t)?{title:`GitHub authentication failed. Try signing in again.`,detail:t}:{title:GENERIC_TITLE,detail:t}}const GIT_PREFLIGHT_FAIL_SPAN_NAME=`ok.preflight.git.fail`;function emitPreflightFailureSpan(e){let t=e instanceof GitTooOldError?`too_old`:`not_available`,s=e instanceof GitTooOldError?e.detected:``;withSpanSync(GIT_PREFLIGHT_FAIL_SPAN_NAME,{attributes:{"ok.platform":e.platform,"ok.preflight.git.reason":t,"ok.preflight.git.detected_version":s}},()=>{})}const log$9=getLogger(`clone-flow`),DEFAULT_TIMEOUT_MS$1=600*1e3;function validateCloneInputs(e,t){return isAllowedGitUrl(e)?isSafeLocalPath(t)?{ok:!0}:{ok:!1,reason:`invalid-dir`}:{ok:!1,reason:`invalid-url`}}function asRawCloneEvent(e){let t=e.type;return t===`progress`?typeof e.phase==`string`&&typeof e.pct==`number`?{type:`progress`,phase:e.phase,pct:e.pct}:null:t===`complete`?typeof e.dir==`string`?{type:`complete`,dir:e.dir}:null:t===`branch-fallback`?typeof e.branch==`string`&&e.branch.length>0?{type:`branch-fallback`,branch:e.branch}:null:t===`error`?{type:`error`,message:typeof e.message==`string`?e.message:`Unknown error`}:null}function runCloneSubprocess(e){let t=expandTilde(e.dir),s=e.timeoutMs??DEFAULT_TIMEOUT_MS$1,g;try{g=assertGitAvailable()}catch(t){t instanceof GitNotAvailableError||t instanceof GitTooOldError?(emitPreflightFailureSpan(t),log$9.warn({event:`git_preflight_fail`,platform:t.platform,reason:t instanceof GitTooOldError?`too_old`:`not_available`,detectedVersion:t instanceof GitTooOldError?t.detected:``},t instanceof GitTooOldError?`git binary too old`:`git binary not found`)):log$9.error({event:`clone_preflight_unexpected_error`,err:t},`unexpected error during clone preflight`);let s=t instanceof Error?t.message:String(t);return{done:Promise.resolve().then(()=>{e.onEvent({type:`error`,message:s})}),cancel:()=>{}}}let S=isAbsolute(g.resolvedPath)?[dirname(g.resolvedPath)]:[],w=!1,E=typeof e.branch==`string`&&e.branch.length>0?[`-b`,e.branch]:[],D=runSubprocess({cliArgs:e.cliArgs,trailingArgs:[`clone`,`--json`,...E,e.url,t],extraPathDirs:S,timeoutMs:s,onLine:({parsed:t})=>{if(!t)return;let s=asRawCloneEvent(t);s&&((s.type===`complete`||s.type===`error`)&&(w=!0),e.onEvent(s))}});return{done:D.done.then(s=>{if(!w){if(s.timedOut){e.onEvent({type:`error`,message:`Clone timed out after 10 minutes`});return}if(s.code!==0){let t=s.stderr?` — ${s.stderr}`:``;e.onEvent({type:`error`,message:`Clone process exited with code ${s.code??-1}${t}`});return}e.onEvent({type:`complete`,dir:t})}}),cancel:D.cancel}}function isLoopbackAddress(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function isAllowedWorkspaceHostHeader(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let s=e.slice(1,t),g=e.slice(t+1);return g!==``&&!/^:\d+$/.test(g)?!1:s===`::1`}let t=e.lastIndexOf(`:`),s=t>=0?e.slice(0,t):e,g=t>=0?e.slice(t+1):null;return g!==null&&!/^\d+$/.test(g)?!1:!!(s===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(s))}const MANAGED_RENAME_JOURNAL_FILENAME=`managed-rename.json`;function journalDir(e){return getLocalDir(e)}function managedRenameJournalPath(e){return resolve(journalDir(e),MANAGED_RENAME_JOURNAL_FILENAME)}function createManagedRenameRecoveryJournal(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 isManagedRenameSnapshot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function isManagedRenamePathSnapshot(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.path==`string`&&typeof t.content==`string`}function isManagedRenameCleanupPath(e){return typeof e==`string`&&e.length>0}function isManagedRenameAffectedDoc(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.from==`string`&&typeof t.to==`string`}function parseV2(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,s=e.pathSnapshots,g=e.cleanupPaths,S=Array.isArray(s)&&s.length>0,w=Array.isArray(g)&&g.length>0;if(!Array.isArray(t)||!t.every(isManagedRenameAffectedDoc)||t.length===0&&!S&&!w)throw Error(`Managed rename journal v2 has invalid affectedDocs`);if(!Array.isArray(e.snapshots)||t.length>0&&e.snapshots.length===0||!e.snapshots.every(isManagedRenameSnapshot))throw Error(`Managed rename journal v2 has invalid snapshots`);if(s!==void 0&&(!Array.isArray(s)||!s.every(isManagedRenamePathSnapshot)))throw Error(`Managed rename journal v2 has invalid pathSnapshots`);if(g!==void 0&&(!Array.isArray(g)||!g.every(isManagedRenameCleanupPath)))throw Error(`Managed rename journal v2 has invalid cleanupPaths`);for(let s of t)if(!e.snapshots.some(e=>e.docName===s.from))throw Error(`Managed rename journal v2 is missing snapshot for affected doc: ${s.from}`);return{version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:t,createdAt:e.createdAt,snapshots:e.snapshots,...S?{pathSnapshots:s}:{},...w?{cleanupPaths:g}:{}}}function parseV1(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(isManagedRenameSnapshot))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 parseManagedRenameRecoveryJournal(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version===2)return parseV2(t);if(t.version===1)return parseV1(t);throw Error(`Unsupported managed rename journal version: ${String(t.version)}`)}function readManagedRenameJournal(e){let t=managedRenameJournalPath(e);if(!existsSync(t))return null;try{let e=readFileSync(t,`utf-8`);return parseManagedRenameRecoveryJournal(JSON.parse(e))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function writeManagedRenameJournal(e,t){let s=managedRenameJournalPath(e);tracedMkdirSync(dirname(s),{recursive:!0});let g=`${s}.tmp`;tracedWriteFileSync(g,JSON.stringify(t,null,2),`utf-8`),tracedRenameSync(g,s)}function clearManagedRenameJournal(e){tracedRmSync(managedRenameJournalPath(e),{force:!0})}async function withManagedRenameRecovery(e,t,s){writeManagedRenameJournal(e,t);let g=await s();return clearManagedRenameJournal(e),g}function destinationsToCleanV1(e){return[e.destinationDocName]}function destinationsToCleanV2(e){return e.affectedDocs.map(e=>e.to)}function resolveRecoveryPath(e,t){let s=resolve(e),g=resolve(s,t);if(t.includes(`\0`)||g===s||!g.startsWith(`${s}${sep}`))throw Error(`Invalid recovery path: ${t}`);return g}function pruneEmptyAncestors(e,t){let s=resolve(t),g=`${s}${sep}`,S=dirname(e);for(;S.startsWith(g)&&S!==s;){let e;try{e=readdirSync(S)}catch(e){console.warn(`[managed-rename] pruneEmptyAncestors: cannot read ${S}:`,e);return}if(e.length>0)return;try{tracedRmdirSync(S)}catch(e){console.warn(`[managed-rename] pruneEmptyAncestors: cannot rmdir ${S}:`,e);return}S=dirname(S)}}function recoverPendingManagedRename(e,t=e){let s=readManagedRenameJournal(t);if(!s)return{recovered:!1,journal:null,restoredDocNames:[]};let g=new Set,S=new Set,w=[];for(let t of s.snapshots)try{let s=safeContentPath(t.docName,e);tracedMkdirSync(dirname(s),{recursive:!0}),tracedWriteFileSync(s,t.content,`utf-8`),g.add(t.docName)}catch(e){w.push({docName:t.docName,cause:e}),console.warn(`[managed-rename] Failed to restore ${t.docName}:`,e)}if(w.length>0){let e=w.map(e=>e.docName).join(`, `);console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${e})`);let t=w.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to restore: ${e}`)}if(s.version===2){let t=[];for(let g of s.pathSnapshots??[])try{let t=resolveRecoveryPath(e,g.path);tracedMkdirSync(dirname(t),{recursive:!0}),tracedWriteFileSync(t,g.content,`utf-8`),S.add(g.path)}catch(e){t.push({path:g.path,cause:e}),console.warn(`[managed-rename] Failed to restore path ${g.path}:`,e)}if(t.length>0){let e=t.map(e=>e.path).join(`, `);console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${e})`);let s=t.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(s,`Managed rename recovery incomplete; failed to restore paths: ${e}`)}}let E=s.version===2?destinationsToCleanV2(s):destinationsToCleanV1(s),D=[];for(let t of E){if(g.has(t))continue;let s=safeContentPath(t,e);try{tracedRmSync(s,{force:!0}),pruneEmptyAncestors(s,e)}catch(e){existsSync(s)&&console.warn(`[managed-rename] Both source and destination files exist after partial recovery for ${t}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination ${t}:`,e),D.push({destination:t,cause:e})}}if(s.version===2)for(let t of s.cleanupPaths??[]){if(S.has(t))continue;let s=null;try{s=resolveRecoveryPath(e,t),tracedRmSync(s,{force:!0}),pruneEmptyAncestors(s,e)}catch(e){s&&existsSync(s)&&console.warn(`[managed-rename] Both source and destination paths exist after partial recovery for ${t}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination path ${t}:`,e),D.push({destination:t,cause:e})}}if(D.length>0){let e=D.map(e=>e.destination).join(`, `),t=D.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 clearManagedRenameJournal(t),{recovered:!0,journal:s,restoredDocNames:[...g].sort((e,t)=>e.localeCompare(t))}}const PROJECT_SKILL_EDITOR_LABELS={claude:`Claude Code`,cursor:`Cursor`,codex:`Codex`},PLATFORM_SKILL_NAME=BUNDLE_SKILL_NAME.project;function resolvePackSkillSource(e){let t;try{t=resolveBundledSkillDir(`packs/${e}`,{checkDesktop:!0})}catch{return null}return{name:`open-knowledge-pack-${e}`,sourceDir:t}}async function installPackSkill(e,t){let s=resolvePackSkillSource(t);if(!s)return[];let{name:g,sourceDir:S}=s,w=join(e,`.ok`,`skills`,g);if(!existsSync(join(w,`SKILL.md`)))try{tracedRmSync(w,{recursive:!0,force:!0}),tracedMkdirSync(join(e,`.ok`,`skills`),{recursive:!0}),tracedCpSync(S,w,{recursive:!0})}catch(e){return getLogger(`seed`).warn({err:e,packId:t,okSkillDir:w},`pack skill source authoring failed — skill not installed`),[]}let E=projectSkill(w,g,e,PROJECT_SKILL_EDITOR_IDS.filter(t=>{let s=EDITOR_PROJECT_SKILL_ROOT[t];return s===null?!1:existsSync(join(e,s,PLATFORM_SKILL_NAME,`SKILL.md`))})),D=E.map(e=>PROJECT_SKILL_EDITOR_LABELS[e]??e);if(E.length>0)try{await recordSkillInstall(e,g,{hosts:E,scope:`project`,scripts:existsSync(join(w,`scripts`)),installedAt:new Date().toISOString()})}catch{}return D}var SeedPrerequisiteError=class extends Error{constructor(e){super(e),this.name=`SeedPrerequisiteError`}},SeedRootDirError=class extends Error{constructor(e){super(e),this.name=`SeedRootDirError`}};function assertEntryPathInProject(e,t){if(typeof t!=`string`||t===``)throw new SeedRootDirError(`entry path must be a non-empty string, got: ${typeof t}`);if(t.includes(`\0`))throw new SeedRootDirError(`entry path must not contain null bytes`);if(isAbsolute(t))throw new SeedRootDirError(`entry path must be relative, got: ${t}`);if(t.split(/[/\\]/).some(e=>e===`..`))throw new SeedRootDirError(`entry path must not contain '..' segments, got: ${t}`);let s=resolve(e),g=resolve(s,t);if(g!==s&&!g.startsWith(s+sep))throw new SeedRootDirError(`entry path must resolve inside the project directory, got: ${t}`);return assertNoSymlinkEscape$1(g,s),g}function assertNoSymlinkEscape$1(e,t){let s;try{s=realpathSync(t)}catch{return}let g=e;for(;;){if(existsSync(g)){let t;try{t=realpathSync(g)}catch(t){throw t.code===`ELOOP`?new SeedRootDirError(`entry path traverses a symlink cycle: ${e}`):t}if(t!==s&&!t.startsWith(s+sep))throw new SeedRootDirError(`entry path resolves outside the project directory via symlink: ${e}`);return}let t=dirname(g);if(t===g)throw new SeedRootDirError(`entry path has no existing ancestor inside the project directory: ${e}`);g=t}}const DEFAULT_PACK_ID=`knowledge-base`,KNOWLEDGE_BASE_FOLDERS=[{path:`external-sources`,title:`External Sources`,uiSummary:`The original sources, saved word-for-word.`,description:"Raw sources saved verbatim — the fetched text of URLs, extracted PDFs, and copied files, each with the original URL and access date in frontmatter. Produced by `ingest`. Immutable after capture; no analysis here (that goes in `research/`).",tags:[`source`,`immutable`,`layer-ingest`],starterTemplate:`clip`},{path:`research`,title:`Research`,uiSummary:`Your work-in-progress take on what the sources mean.`,description:"Provisional analysis that synthesizes the external sources. Every claim cites a doc in `external-sources/`; `status: provisional`. Promoted to `articles/` via `consolidate` once the findings are stable.",tags:[`research`,`provisional`,`layer-research`],starterTemplate:`research-log`},{path:`articles`,title:`Articles`,uiSummary:`The finished, trusted version you can rely on.`,description:"Canonical knowledge, committed after a team decision. The source of truth for the domain; carries a `supersedes:` chain back to the `research/` docs it replaces.",tags:[`article`,`canonical`,`layer-consolidate`],starterTemplate:`article`}],KNOWLEDGE_BASE_TEMPLATES={clip:`---
|
|
957
957
|
template:
|
|
958
958
|
title: External Source
|
|
@@ -1939,16 +1939,16 @@ Change history for this knowledge base, newest entry first. Add a dated entry (\
|
|
|
1939
1939
|
`).filter(Boolean);ce.push(...e)}catch{}if(ce.length===0&&se.length===0&&de.length===0)return EMPTY;let fe=[...se,...de],me=[];if(fe.length>0){let t=parseGitLogOutput(await oe.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...fe)).map(e=>({...e,type:`checkpoint`}));if(ne&&(t=await filterEntriesByChain(e,t,O,S,ee,ae,Y)),ue&&se.length>0&&de.length>0){let e=new Set(se),s=t.filter(t=>e.has(t.sha)),g=t.filter(t=>!e.has(t.sha)),S=s.reduce((e,t)=>{let s=new Date(t.timestamp).getTime();return s<e?s:e},1/0);me=[...s,...g.filter(e=>new Date(e.timestamp).getTime()<S)]}else me=t}let ge=[...ce];for(let e of fe)ge.push(e);let _e=[];if(ge.length>0&&(_e=parseGitLogOutput(await oe.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,`-n`,String(D),...ge,...ne?[`--`,ne]:[])),_e.length>=D&&(k=!0),J))for(let t=0;t<O.length-1;t++){let s=O[t];if(s.renameCommit!==null)try{let t=await buildSeeds(e,s.renameCommit,S,Y);if(t.length===0)continue;let g=ee(s.path),w=parseGitLogOutput(await logSeededReachable(e,[`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,`-n`,String(D)],t,g));w.length>=D&&(k=!0),_e=[..._e,...w]}catch(e){console.warn(`[timeline] predecessor walk failed for step ${t} (${s.path}); skipping:`,e)}}let ve=[...me,..._e],ye=new Set,Ce=[];for(let e of ve)ye.has(e.sha)||(ye.add(e.sha),Ce.push(e));let we=Ce;Ce.length>0&&O.length>0&&(we=filterEntriesByOkActorDocs(Ce,O,await Promise.all(O.map(async t=>{if(t.renameCommit===null)return null;let s=await buildSeeds(e,t.renameCommit,S,Y);return s.length===0?new Set:buildAncestorShaSet(e,s,S,ae)})))),we.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let Te=we;Te=Te.filter(e=>e.type!==`park`),H||(Te=Te.filter(e=>e.checkpoint?.kind!==`auto-consolidation`)),F.length>0&&(Te=Te.filter(e=>F.includes(e.type))),L.length>0&&(Te=Te.filter(e=>matchesAuthor(e,L))),B.length>0&&(Te=Te.filter(e=>!matchesAuthor(e,B)));let De=Te.length,je=Te.slice(E,E+w),Me=je.map(({rawBody:e,...t})=>t);return j(ge.length,Ce.length),{entries:Me,total:De,hasMore:k&&je.length>0||E+w<De}}catch(e){return console.warn(`[timeline] getDocumentHistory failed, returning empty result:`,e),j(0,0,!0),EMPTY}}async function getFolderTimeline(e,t,s=`.`,g){if(!existsSync(e.workTree)||!existsSync(e.gitDir)||t.includes(`..`)||t.includes(`\0`))return EMPTY;let S=g?.branch??`main`,w=Math.max(1,g?.limit??50),E=Math.max(0,g?.offset??0),D=s===`.`?``:s.replace(/^\.\//,``),O=t.replace(/^\.?\/+/,``).replace(/\/+$/,``),k=[D,O,`.ok`].filter(Boolean).join(`/`),j=shadowGit(e);try{let e=[];for(let t of[`refs/wip/${S}/`,`refs/checkpoints/${S}/`])try{let s=(await j.raw(`for-each-ref`,`--format=%(refname)`,t)).trim().split(`
|
|
1940
1940
|
`).filter(Boolean);e.push(...s)}catch{}if(e.length===0)return EMPTY;let t=historyWalkCap(E,w),s=parseGitLogOutput(await j.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,`-n`,String(t),...e,`--`,k)),g=s.length>=t,D=O?`${O}/.ok/`:`.ok/`,F=new Set,L=[];for(let e of s){if(F.has(e.sha)||!isFolderArtifactSubject(e.message)||!e.contributors.some(e=>e.docs.some(e=>e.startsWith(D))))continue;F.add(e.sha);let{rawBody:t,...s}=e;L.push(s)}let B=L.length,H=L.slice(E,E+w);return{entries:H,total:B,hasMore:g&&H.length>0||E+w<B}}catch(e){return console.warn(`[timeline] getFolderTimeline failed, returning empty result:`,e),EMPTY}}let _httpDurationHist=null;function httpDurationHist(){return _httpDurationHist||=getMeter().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),_httpDurationHist}let _hintEmittedCounter=null;function hintEmittedCounter(){return _hintEmittedCounter||=getMeter().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.`}),_hintEmittedCounter}let _agentPatchFmTouchCounter=null;function agentPatchFmTouchCounter(){return _agentPatchFmTouchCounter||=getMeter().createCounter(`ok.frontmatter.agent_patch_fm_touch_total`,{description:`Count of agent-patch calls whose find string targets the frontmatter region. Measures incidence during the soft-deprecation window before agent-patch FM-intersecting calls are enforced as 400. Bounded label: result ∈ {rejected, pre_deprecation_passthrough}.`}),_agentPatchFmTouchCounter}function findLooksLikeFrontmatter(e){return!!(/(^|\n)---(\s|\n|$)/.test(e)||/^\s*[\w-]+:\s+\S/.test(e))}let _renameAttributionCounter=null;function renameAttributionCounter(){return _renameAttributionCounter||=getMeter().createCounter(`ok.rename.attribution_kind`,{description:`Count of rename and rollback handler dispatches by attribution kind (agent | principal | anonymous)`}),_renameAttributionCounter}let _agentWriteGateFiredCounter=null;function agentWriteGateFiredCounter(){return _agentWriteGateFiredCounter||=getMeter().createCounter(`ok.agent_write.gate_fired_total`,{description:`Count of agent writes that ran the Site A content-divergence gate (denominator for the divergence rate). Bounded label: handler ∈ {agent-write-md, agent-patch, rollback}.`}),_agentWriteGateFiredCounter}let _agentWriteContentDivergenceCounter=null;function agentWriteContentDivergenceCounter(){return _agentWriteContentDivergenceCounter||=getMeter().createCounter(`ok.agent_write.content_divergence_total`,{description:`Count of agent writes whose converged Y.Text diverged from the composed intent (numerator for the divergence rate). Bounded labels: handler ∈ {agent-write-md, agent-patch, rollback}, divergence_type.`}),_agentWriteContentDivergenceCounter}let _searchCorpusTruncatedCounter=null;function searchCorpusTruncatedCounter(){return _searchCorpusTruncatedCounter||=getMeter().createCounter(`ok.search.corpus_truncated_total`,{description:`Count of search-corpus rebuilds where the name-only file tier hit OK_SEARCH_MAX_ENTRIES and dropped deepest-tail paths. One increment per truncated build; non-truncated builds do not increment.`}),_searchCorpusTruncatedCounter}function recordContentDivergenceGate(e,t){agentWriteGateFiredCounter().add(1,{handler:e}),t!==void 0&&agentWriteContentDivergenceCounter().add(1,{handler:e,divergence_type:t.divergenceType})}function resumeSyncOnAuthEvent(e,t){e.type===`complete`&&t?.()?.notifyCredentialsChanged().catch(()=>{})}const ROLLBACK_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},MANAGED_RENAME_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},log$7=getLogger(`api`);function ytextHasConflictMarkers(e){return/^<{7} /m.test(e)&&/^={7}$/m.test(e)&&/^>{7} /m.test(e)}function safeDocPath(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name.`};let s=t===`.`?``:t.replace(/^\.\//,``),g=managedArtifactTimelinePaths(e);if(g.managed&&g.versioned)return{path:s?`${s}/${g.filePath}`:g.filePath};let S=getDocExtension(e);return{path:s?`${s}/${e}${S}`:`${e}${S}`}}const GENERIC_PASTE_NAMES=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i,SAFE_FILENAME_CHARS=/[^\p{L}\p{N}\p{M}\p{Extended_Pictographic}.\-_ ]/gu,STRIP_ON_SIGHT=/[/\\\x00-\x1f\x7f]/g;function sanitizeFilename(e){let t=e.replace(STRIP_ON_SIGHT,``);if(t=t.replace(SAFE_FILENAME_CHARS,`_`),t=t.replace(/_+/g,`_`).replace(/\.{2,}/g,`.`),t=t.replace(/^[._]+/,``),t=t.replace(/\.+$/,``),t===``)return`upload`;let s=255,g=new TextEncoder;if(g.encode(t).length>255){let e=t.lastIndexOf(`.`),s=e>=0?t.slice(e):``,S=e>=0?t.slice(0,e):t;for(;g.encode(S+s).length>255&&S.length>0;)S=S.slice(0,-1);t=(S||`upload`)+s,g.encode(t).length>255&&(t=`upload`)}return t}function resolveUploadDestDir(e,t,s){let g=t.trim();return g===``||g===`./`?resolve(s,dirname(e)):g===`/`?s:g.startsWith(`./`)?resolve(s,dirname(e),g.slice(2)):resolve(s,g)}function readTempFileHead(e,t){let s=openSync(e,`r`);try{let e=Buffer.alloc(t),g=readSync(s,e,0,t,0);return e.subarray(0,g)}finally{closeSync(s)}}const MAX_DEDUP_SCAN_CANDIDATES=1e3;async function streamingHashFile(e){let t=createHash(`sha256`);return await pipeline(createReadStream(e),t),t.digest(`hex`)}async function findDuplicateAsset(e,t,s){let g;try{g=await readdir(e)}catch{return null}let S=getLogger(`upload`),w=0;for(let E of g){let g=extname(E).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(g))continue;let D=resolve(e,E),O;try{O=await stat$1(D)}catch{continue}if(!O.isFile()||O.size!==s)continue;if(w++,w>MAX_DEDUP_SCAN_CANDIDATES)return S.warn({event:`upload-dedup-skip`,reason:`scan-cap-exceeded`,destDir:e,scanned:MAX_DEDUP_SCAN_CANDIDATES,expectedSize:s},`[upload-dedup] candidate scan exceeded ${MAX_DEDUP_SCAN_CANDIDATES} same-size siblings — degrading to no-dedup for this upload`),null;let k;try{k=await streamingHashFile(D)}catch(e){let t=e.code;t!==`ENOENT`&&S.warn({event:`upload-dedup-skip`,reason:`read-failed`,code:t,entry:E},`[upload-dedup] skipped candidate — read failed`);continue}if(k===t)return E}return null}function readUploadBody(e,t){return new Promise((s,g)=>{let S;try{S=(0,import_lib.default)({headers:e.headers,limits:{files:1,fields:10,fieldSize:2*1024}})}catch(e){g(new UploadWriteError(`urn:ok:error:malformed-upload`,e));return}let w=!1,E=`upload`,D=``,O=``,k=``,j,F,L=!1,B=(e,t)=>{if(!w){if(w=!0,j)try{unlinkSync(j)}catch{}g(t instanceof UploadWriteError?t:new UploadWriteError(e,t))}},H=classifyUploadErrno;S.on(`field`,(e,t)=>{e===`parentDocName`&&(O=t),e===`placement`&&(k=t)}),S.on(`file`,(e,g,S)=>{L=!0,E=S.filename||`upload`,D=S.mimeType||``;let q;try{q=mintTempUploadPath(t)}catch(e){B(H(e),e),g.resume();return}j=q;let ee=new HashingPassThrough;pipeline(g,ee,createWriteStream(q)).then(()=>{w||(w=!0,s({filename:E,mimeType:D,parentDocName:O,placement:k,tempPath:q,sha:ee.digest(),byteLength:ee.byteLength()}))}).catch(e=>{F=e,B(H(e),e)})}),S.on(`error`,e=>{B(`urn:ok:error:malformed-upload`,e)}),S.on(`close`,()=>{w||F||L||(w=!0,s({filename:``,mimeType:``,parentDocName:O,placement:k,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{w||F||e.complete||B(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(S)})}function safeSubdir(e,t){let s=resolve(e,t);if(!isWithinDir(s,e))throw Error(`Invalid directory: ${t}`);return s}function synthesizeShowAllAssetExt(e){let t=extname(e);return t?t.slice(1).toLowerCase():e.startsWith(`.`)&&e.length>1?e.slice(1).toLowerCase():`file`}const DEFAULT_SHOWALL_MAX_ENTRIES=5e4;function getShowAllMaxEntries(){let e=process.env.OK_SHOWALL_MAX_ENTRIES;if(e===void 0)return DEFAULT_SHOWALL_MAX_ENTRIES;let t=Number(e);return Number.isInteger(t)&&t>0?t:DEFAULT_SHOWALL_MAX_ENTRIES}const DEFAULT_SEARCH_MAX_ENTRIES=5e4;function getSearchMaxEntries(){let e=process.env.OK_SEARCH_MAX_ENTRIES;if(e===void 0)return DEFAULT_SEARCH_MAX_ENTRIES;let t=Number(e);return Number.isInteger(t)&&t>0?t:DEFAULT_SEARCH_MAX_ENTRIES}let showAllWalkInvocations=0,showAllWalkAborts=0;function __getShowAllWalkStatsForTesting(){return{invocations:showAllWalkInvocations,aborts:showAllWalkAborts}}function __resetShowAllWalkStatsForTesting(){showAllWalkInvocations=0,showAllWalkAborts=0}function showAllWantsNdjson(e){let t=e.headers.accept;return typeof t==`string`&&t.includes(`application/x-ndjson`)}async function*streamShowAllEntries(e){let{contentDir:t,contentFilter:s,dirFilter:g,maxEntries:S,signal:w}=e,E=e.maxDepth??1/0;showAllWalkInvocations+=1;let D=0,O=!1,k=!1,j=e=>g?e===g||e.startsWith(`${g}/`):!0,F;try{F=await realpath(t)}catch{F=t}let L=e=>isWithinDir(e,F),B=async(e,t,g)=>{let S=new Map;for(let t of e){if(!t.isFile()&&!t.isSymbolicLink()||!isSupportedDocFile(t.name))continue;let e=stripDocExtension(g?`${g}/${t.name}`:t.name);S.set(e,(S.get(e)??0)+1)}let w=new Set([...S].filter(([,e])=>e>1).map(([e])=>e));if(w.size===0)return new Map;let E=new Map;for(let S of e){if(!S.isFile()&&!S.isSymbolicLink()||!isSupportedDocFile(S.name))continue;let e=g?`${g}/${S.name}`:S.name,D=stripDocExtension(e);if(w.has(D)&&!s.isExcluded(e,{bypassFilters:!0})&&j(e)){if(S.isSymbolicLink()){let e=join(t,S.name),s;try{s=await realpath(e)}catch{continue}if(!L(s))continue;let g;try{g=await stat$1(s)}catch{continue}if(!g.isFile())continue}else try{await stat$1(join(t,S.name))}catch{continue}E.set(D,(E.get(D)??0)+1)}}return E},H=(e,t)=>{let s=stripDocExtension(e);return(t.get(s)??0)>1?e:s};async function q(e,t){let g;try{g=await readdir(e,{withFileTypes:!0})}catch(t){return console.warn(`[document-list][showAll] probe readdir failed for ${e}:`,t),!1}for(let S of g){let g=t?`${t}/${S.name}`:S.name;if(S.isDirectory()){if(s.isDirExcluded(g,{bypassFilters:!0}))continue;try{if(!L(await realpath(join(e,S.name))))continue}catch(t){console.warn(`[document-list][showAll] probe realpath failed for ${e}/${S.name}:`,t);continue}return!0}if(S.isFile()&&!s.isExcluded(g,{bypassFilters:!0}))return!0}return!1}async function*ee(e,g,F){let ee=[{absDir:e,relDir:g,depth:F}];for(let e=0;e<ee.length;e++){if(w?.aborted){k=!0;return}let{absDir:g,relDir:F,depth:J}=ee[e],Y;try{Y=await readdir(g,{withFileTypes:!0})}catch(e){console.warn(`[document-list][showAll] readdir failed for ${g}:`,e);continue}let te=await B(Y,g,F);for(let e of Y){if(w?.aborted){k=!0;return}if(D>=S){O=!0;return}let B=F?`${F}/${e.name}`:e.name;if(e.isDirectory()){if(s.isDirExcluded(B,{bypassFilters:!0}))continue;let t=join(g,e.name),S;try{S=await realpath(t)}catch(e){console.warn(`[document-list][showAll] realpath failed for ${t}:`,e);continue}if(!L(S)){console.warn(`[document-list][showAll] refusing symlink-escape ${t} -> ${S}`);continue}if(j(B)){let e=null;try{e=await stat$1(t)}catch(e){console.warn(`[document-list][showAll] stat failed for ${t}:`,e)}D+=1;let s=J>=E?await q(t,B):void 0;yield{kind:`folder`,path:B,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null,...s===void 0?{}:{hasChildren:s}}}J<E&&ee.push({absDir:t,relDir:B,depth:J+1});continue}if(e.isSymbolicLink()){let S=join(g,e.name),w;try{w=await realpath(S)}catch(e){console.warn(`[document-list][showAll] symlink realpath failed for ${S}:`,e);continue}if(!L(w)){console.warn(`[document-list][showAll] refusing symlink-escape ${S} -> ${w}`);continue}let E;try{E=await stat$1(w)}catch(e){console.warn(`[document-list][showAll] symlink target stat failed for ${S}:`,e);continue}let O=toPosix(relative(t,w));if(E.isDirectory()){if(s.isDirExcluded(B,{bypassFilters:!0})||!j(B))continue;D+=1,yield{kind:`folder`,path:B,size:0,modified:E.mtime.toISOString(),docExt:`.md`,isSymlink:!0,canonicalDocName:O,targetPath:O,hasChildren:await q(w,B)};continue}if(!E.isFile()||s.isExcluded(B,{bypassFilters:!0})||!j(B))continue;if(D+=1,isSupportedDocFile(e.name))yield{kind:`document`,docName:H(B,te),docExt:extname(e.name),size:E.size,modified:E.mtime.toISOString(),isSymlink:!0,canonicalDocName:O.replace(/\.(md|mdx)$/i,``),targetPath:O};else{let t=synthesizeShowAllAssetExt(e.name);yield{kind:`asset`,docName:B,docExt:t,path:B,assetExt:t,mediaKind:mediaKindForSidebarAssetExtension(t),referencedBy:[],size:E.size,modified:E.mtime.toISOString(),isSymlink:!0,canonicalDocName:null,targetPath:O}}continue}if(!e.isFile()||s.isExcluded(B,{bypassFilters:!0})||!j(B))continue;let Y=null;try{Y=await stat$1(join(g,e.name))}catch(t){console.warn(`[document-list][showAll] stat failed for ${g}/${e.name}:`,t);continue}if(isSupportedDocFile(e.name)){let t=H(B,te),s=extname(e.name);D+=1,yield{kind:`document`,docName:t,docExt:s,size:Y.size,modified:Y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null};continue}let ne=synthesizeShowAllAssetExt(e.name),ae=mediaKindForSidebarAssetExtension(ne);D+=1,yield{kind:`asset`,docName:B,docExt:ne,path:B,assetExt:ne,mediaKind:ae,referencedBy:[],size:Y.size,modified:Y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null}}}}return yield*ee(g?join(t,g):t,g??``,1),k&&(showAllWalkAborts+=1),{truncated:O}}async function walkContentDirForShowAll(e){let{documents:t,...s}=e,g=streamShowAllEntries(s),S=await g.next();for(;!S.done;)t.push(S.value),S=await g.next();return S.value}function isValidRelativeContentPath(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function isReservedProjectStatePath(e){return e===`.ok`||e.startsWith(`.ok/`)||e===`.git`||e.startsWith(`.git/`)}function isReservedSyntheticFolderPath(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function listAffectedDocNames(e,t,s){let g=[...e.keys()].filter(e=>t===`file`?e===s:e===s||e.startsWith(`${s}/`));return g.sort((e,t)=>e.localeCompare(t)),g}function remapDocNameForRename(e,t,s,g){return t===`file`||e===s?g:`${g}${e.slice(s.length)}`}function requireNonEmptyDocName(e,t,s){return e!==void 0&&e.length>0?e:(errorResponse(t,400,`urn:ok:error:invalid-request`,"`docName` must be a non-empty document name.",{handler:s}),null)}function assertNoSymlinkEscape(e,t){let s;try{s=realpathSync(t)}catch(e){throw e.code===`ENOENT`?new SymlinkEscapeError(`content directory does not exist`):e}let g=e;for(;;)try{if(!isWithinContentDir(realpathSync(g),s))throw new SymlinkEscapeError(`path resolves outside content directory`);return}catch(e){let s=e.code;if(s===`ELOOP`)throw new SymlinkEscapeError(`symlink cycle in path`);if(s!==`ENOENT`)throw e;let S=dirname(g);if(S===g||S!==t&&!S.startsWith(`${t}${sep}`))throw e;g=S}}function resolveContentEntryPath(e,t,s){if(!isValidRelativeContentPath(s))throw Error(`path must be a relative content path`);let g=resolve(e),S=resolve(g,t===`file`?docNameToRelativePath(s):s);if(S!==g&&!S.startsWith(`${g}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(S,g),S}function splitContentPath(e){let t=e.lastIndexOf(`/`);return t===-1?{parent:``,basename:e}:{parent:e.slice(0,t),basename:e.slice(t+1)}}function joinContentPath(e,t){return e?`${e}/${t}`:t}function duplicateBasename(e,t){return t===1?`${e} copy`:`${e} copy ${t}`}var DuplicateNameExhaustedError=class extends Error{constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};function isAlreadyExistsError(e){let t=e.code;return t===`EEXIST`||t===`ERR_FS_CP_EEXIST`}function classifyDuplicatePathFilesystemProblem(e){let t=e.code;return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function docNameExistsWithAnySupportedExtension(e,t){return isSupportedDocFile(t)?existsSync(resolve(e,t)):SUPPORTED_DOC_EXTENSIONS.some(s=>existsSync(resolve(e,`${t}${s}`)))}function hasSameStemDocumentSibling(e,t){if(!isSupportedDocFile(t))return!1;let s=stripDocExtension(t),g=extname(t).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.some(t=>t.toLowerCase()===g?!1:existsSync(resolve(e,`${s}${t}`)))}function docNameForFileOperationPath(e,t){let s=stripDocExtension(t);return isSupportedDocFile(t)&&hasSameStemDocumentSibling(e,t)?t:s}function resolveDuplicateDocPath(e,t,s){if(!isValidRelativeContentPath(t))throw Error(`path must be a relative content path`);let g=resolve(e),S=resolve(g,`${t}${s}`);if(S!==g&&!S.startsWith(`${g}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(S,g),S}function nextAvailableDuplicateDocName(e,t){let{parent:s,basename:g}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let S=joinContentPath(s,duplicateBasename(g,t));if(!docNameExistsWithAnySupportedExtension(e,S))return{docName:S,attempt:t}}throw new DuplicateNameExhaustedError(t)}function nextAvailableDuplicateFolderPath(e,t){let{parent:s,basename:g}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let S=joinContentPath(s,duplicateBasename(g,t));if(!existsSync(resolveContentEntryPath(e,`folder`,S)))return{folderPath:S,attempt:t}}throw new DuplicateNameExhaustedError(t)}function collectMarkdownCopies(e,t){let s=resolveContentEntryPath(e,`folder`,t),g=[];function S(t,s){for(let w of readdirSync(t,{withFileTypes:!0})){let E=resolve(t,w.name),D=s?`${s}/${w.name}`:w.name;if(w.isDirectory()){S(E,D);continue}!w.isFile()||!isSupportedDocFile(D)||g.push({docName:docNameForFileOperationPath(e,D),fullPath:E,content:readFileSync(E,`utf-8`)})}}return S(s,t),g.sort((e,t)=>e.docName.localeCompare(t.docName)),g}function collectFolderPaths(e,t){let s=resolveContentEntryPath(e,`folder`,t),g=[t];function S(e,t){for(let s of readdirSync(e,{withFileTypes:!0})){if(!s.isDirectory())continue;let w=resolve(e,s.name),E=t?`${t}/${s.name}`:s.name;g.push(E),S(w,E)}}return S(s,t),g.sort((e,t)=>e.localeCompare(t)),g}function probeAndRegisterSourceFileExtension(e,t){if(!isValidRelativeContentPath(t))return;let s=resolve(e);if(isSupportedDocFile(t)){let e=stripDocExtension(t);for(let t of SUPPORTED_DOC_EXTENSIONS){let g=resolve(s,`${e}${t}`);g!==s&&!g.startsWith(`${s}${sep}`)||existsSync(g)&®isterDocExtension(e,t)}let g=resolve(s,t);g!==s&&g.startsWith(`${s}${sep}`)&&existsSync(g)&®isterDocExtension(e,extname(t));return}for(let e of SUPPORTED_DOC_EXTENSIONS){let g=resolve(s,`${t}${e}`);if(!(g!==s&&!g.startsWith(`${s}${sep}`))&&existsSync(g)){registerDocExtension(t,e);return}}}function toGitRelativePath(e,t){let s=resolve(e),g=resolve(t);return g!==s&&!g.startsWith(`${s}${sep}`)?null:relative(s,g).split(sep).join(`/`)}function stringsDifferOnlyByCase(e,t){return e!==t&&e.toLowerCase()===t.toLowerCase()}function pathsDifferOnlyByCase(e,t){return stringsDifferOnlyByCase(resolve(e),resolve(t))}function isCaseOnlySelfCollision(e,t){if(!pathsDifferOnlyByCase(e,t)||!existsSync(e)||!existsSync(t))return!1;try{let s=statSync(e),g=statSync(t);return s.dev===g.dev&&s.ino===g.ino}catch{return!1}}function createCaseOnlyRenameTempPath(e){let t=dirname(e);for(let e=0;e<10;e+=1){let e=resolve(t,`.ok-case-rename-${randomUUID()}`);if(!existsSync(e))return e}throw Error(`Unable to allocate temporary path for case-only rename`)}function writeFileIfContentDiffers(e,t){(existsSync(e)?readFileSync(e,`utf-8`):null)!==t&&tracedWriteFileSync(e,t,`utf-8`)}function renamePathOnDisk(e,t){if(tracedMkdirSync(dirname(t),{recursive:!0}),!pathsDifferOnlyByCase(e,t)){tracedRenameSync(e,t);return}let s=createCaseOnlyRenameTempPath(e);tracedRenameSync(e,s);try{tracedRenameSync(s,t)}catch(t){try{let t=existsSync(s),g=existsSync(e);t&&!g?tracedRenameSync(s,e):console.warn(`[renamePathOnDisk] skipped case-only rollback due to unexpected state:`,{tempExists:t,sourceExists:g})}catch(e){console.warn(`[renamePathOnDisk] failed to roll back temporary case-only rename:`,e)}throw t}}async function renameTrackedPathInGit(e,t,s){if(!e)return!1;let g=toGitRelativePath(e,t),S=toGitRelativePath(e,s);return!g||!S?!1:await withParentLock(async()=>{let w=esm_default({baseDir:e,timeout:{block:15e3}}),E=``;try{E=(await w.raw(`ls-files`,`--`,g)).trim()}catch(e){return console.warn(`[renameTrackedPathInGit] git ls-files failed, falling back to fs rename:`,e),!1}if(!E)return!1;mkdirSync(dirname(s),{recursive:!0});let D=!1;try{if(pathsDifferOnlyByCase(t,s)){let s=toGitRelativePath(e,createCaseOnlyRenameTempPath(t));if(!s)return!1;await w.raw(`mv`,`--`,g,s);try{await w.raw(`mv`,`--`,s,S)}catch(e){try{await w.raw(`mv`,`--`,s,g)}catch(e){console.warn(`[renameTrackedPathInGit] case-only git rename failed and rollback also failed; git index and disk may have diverged:`,e),D=!0}throw e}}else await w.raw(`mv`,`--`,g,S);return!0}catch(e){if(D)throw e;return console.warn(`[renameTrackedPathInGit] git mv failed, falling back to fs rename:`,e),!1}})}const workspaceSearchCaches=new Map;function extractHeadings(e){let{body:t}=stripFrontmatter(e),s=[],g=new Map,S=createCodeFenceTracker();for(let e of t.split(`
|
|
1941
1941
|
`)){if(S(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),S=getHeadingSlug(e,g);S&&s.push({level:t[1].length,text:e,slug:S})}}return s}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function applyDiskEventToLiveAllFilesIndex(e,t){let s=t();s instanceof Map&&updateFileIndex(e,s)}function createApiExtension(e){let{hocuspocus:t,sessionManager:s,contentDir:g,serverInstanceId:S,getFileIndex:w,getAttachmentFolderPath:E,getAllFilesIndex:D=w,mutateFileIndex:O=e=>applyDiskEventToLiveAllFilesIndex(e,D),getFileIndexGeneration:k,getFolderIndex:j,onReferencedAssetsCacheInvalidator:F,getAliasMap:L,getFolderAliasIndex:B,rescanFiles:H,enableTestRoutes:q=!1,shadowRef:ee,flushGitCommit:J,flushContributors:Y,takeStoreFailure:te,takeStoreDivergence:ne,markAgentWriteStore:ae,getCurrentBranch:oe,getDiskAckSVs:se,contentRoot:ce,backlinkIndex:ue,tagIndex:de,signalChannel:fe,agentFocusBroadcaster:me,agentPresenceBroadcaster:ge,onAgentWrite:_e,getSyncEngine:ve,localOpCliArgs:ye=[`open-knowledge`],projectDir:Ce,getPrincipal:we,homeDirOverride:Te,contentFilter:De,installedAgentsProbe:je,forceUnloadDocument:Me,ready:Pe,recentlyRemovedDocs:Ie,serializeDoc:Re,evictManagedArtifactLkg:ze,semanticSearch:Be,getSemanticSimilarityFloor:Ve,embeddingsSecretsFile:Ue,ephemeral:We=!1}=e,Ge=createConcurrencyGuard(),Ke=new Map,Xe=createSingleFlight(),$e=null;function nt(){let e=j?.();return e instanceof Map?e:null}function rt(e){let t=nt();if(t)try{upsertFolderIndexEntry(t,g,e,statSync(e),e)}catch(t){console.warn(`[api-extension] folder index stat failed for ${e}:`,t)}}function it(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)rt(resolve(g,t.slice(0,e).join(`/`)))}function at(e){let t=nt();t&&removeFolderIndexEntries(t,e)}function st(e,t){let s=nt();if(!s)return;let S=[];for(let[g,w]of s.entries()){if(g!==e&&!g.startsWith(`${e}/`))continue;s.delete(g);let E=g.slice(e.length);S.push([`${t}${E}`,w])}if(S.length===0){let e=resolveContentEntryPath(g,`folder`,t);existsSync(e)&&rt(e);return}for(let[e,t]of S)s.set(e,{...t,modified:new Date().toISOString(),canonicalPath:resolve(g,e)})}function vt(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
|
|
1942
|
-
`)}function St(){$e=null}F?.(St);let Tt=createInstalledAgentsProbe({probe:je??createOsProbe(process.platform)});function Et(e){if(isManagedArtifactDocName(e))try{return managedArtifactAbsPath(e,{projectDir:Ce??g,homedirOverride:Te})}catch{return null}if(!isSafeDocName(e))return null;let t=resolve(g),s=resolve(t,docNameToRelativePath(e));return isWithinDir(s,t)?s:null}function jt(e){let t=Et(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Mt(e,t){return t.has(e)?jt(e):e}let Ft={cluster:void 0,category:void 0,tags:void 0};function It(e){try{let s=t.documents.get(e);if(s){let e=readFmMap(s.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,s=typeof e.category==`string`?e.category:void 0,g;if(Array.isArray(e.tags)){let t=e.tags.filter(e=>typeof e==`string`);g=t.length>0?t:void 0}else typeof e.tags==`string`&&e.tags&&(g=[e.tags]);return{cluster:t,category:s,tags:g}}}}catch{}try{let t=Et(e);if(!t||!existsSync(t))return Ft;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):Ft}catch{return Ft}}function Lt(e,t){return t.has(e)?It(e):Ft}function Rt(e){if(ue)try{if(ue.getBacklinks(e).length>0)return;let t=performance.now(),s=findHubCandidates(e,w()),g=performance.now()-t;return g>5&&log$7.debug({docName:e,elapsedMs:g,candidateCount:s.length},`[orphan-hint] findHubCandidates slow`),s.length===0?void 0:[{type:`orphan`,parentCandidates:s,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): ${s.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function zt(e){return L?.().get(e)??e}function Bt(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function Vt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function Ht(e,s){let g=`onStoreDocument-${e}`;(t.debouncer.isDebounced(g)?t.debouncer.executeNow(g):Promise.resolve()).then(()=>J?.()).catch(e=>{log$7.warn({err:e},`[${s}] post-write flush failed`)})}async function Ut(e){let s=`onStoreDocument-${e}`;t.debouncer.isDebounced(s)&&(ae?.(e),await t.debouncer.executeNow(s));let g=te?.(e)??null;return g?{kind:`failure`,failure:g}:ne?.(e)?{kind:`divergence`}:null}function Wt(e,t,s){let g=classifyUploadErrno({code:t.code});errorResponse(e,uploadStatusFor(g),g,`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:s})}function Xt(e,t){errorResponse(e,409,`urn:ok:error:disk-divergence`,`The document changed on disk after your edit was prepared; your edit was NOT applied, to avoid overwriting the newer on-disk content. Re-read the document and retry.`,{handler:t})}function Zt(e){if(e.reconciled)return{kind:`disk-edit-reconciled`,intendedBytes:e.baseBytes,actualBytes:e.diskBytes,byteDelta:e.diskBytes-e.baseBytes,...e.mergeOutcome?{mergeOutcome:e.mergeOutcome}:{},hint:e.mergeOutcome===`merged`?'An out-of-band edit was three-way merged into this document before your edit was applied on top; the merge may have interleaved content blocks. Re-read it (e.g. `exec("cat <path>")`) and review the combined result carefully before continuing.':'An out-of-band edit was reconciled into this document before your edit was applied on top; the document now reflects that edit plus yours. Re-read it (e.g. `exec("cat <path>")`) to see the combined result before continuing.'}}function $t(e){if(!De)return!1;let t=docNameToRelativePath(e);return De.isExcluded(t)}function en(){let e=new Set;for(let[t,s]of w()){e.add(t);for(let t of s.aliases)e.add(t)}try{for(let t of[`project`,`global`]){let s=resolve(t===`global`?cu:g,`.ok`,`skills`);for(let g of hu(s,t).skills)e.add(`${MANAGED_ARTIFACT_PREFIX_SKILL}${t}/${g.name}`)}for(let t of resolveProjectTemplates(resolve(g)).templates)e.add(uu(t.source_folder,t.name))}catch(e){log$7.warn({err:e},`[collectAdmittedDocNames] managed-artifact enumeration failed`)}for(let t of ue?.getIndexedDocNames()??[])e.has(t)||$t(t)||e.add(t);return e}let tn=e=>existsSync(resolve(g,e));function rn(e,t){$t(e)||O?.({kind:w().has(e)?`update`:`create`,path:resolveContentEntryPath(g,`file`,e),docName:e,content:t})}function sn(){let e=Promise.resolve();return async function(t){let s=e,g=()=>{};e=new Promise(e=>{g=e}),await s;try{return await t()}finally{g()}}}let jr=sn(),Mr=e=>e.endsWith(`.`)?e:`${e}.`;function zr(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:Mr(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:Mr(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:Mr(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Mr(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:Mr(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:Mr(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:Mr(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 Br(e,g){let S=new Map;for(let s of e){let e=t.documents.get(s);e&&S.set(s,e.getText(`source`).toString())}for(let s of e){let e=t.documents.get(s);e&&e.getMap(`lifecycle`).set(`status`,g)}for(let t of e)await s.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let s of e){let e=t.documents.get(s);deleteReconciledBase(s),ze?.(s),e&&(t.closeConnections(s),await(Me??t.unloadDocument.bind(t))(e))}return S}function Vr(e,t){for(let{fromDocName:s,toDocName:S}of e){let e=safeContentPath(S,g),w=t.get(s);typeof w==`string`&&writeFileIfContentDiffers(e,w);let E=typeof w==`string`?w:existsSync(e)?readFileSync(e,`utf-8`):null;typeof E==`string`&®isterWrite(e,contentHash(E))}}function Hr(e,t){return e.map(e=>{let s=t.get(e);if(typeof s==`string`)return{docName:e,content:s};let S=safeContentPath(e,g);if(!existsSync(S))throw new ManagedRenameSnapshotMissingError(e);return{docName:e,content:readFileSync(S,`utf-8`)}})}function Ur(e){let s=t.documents.get(e);if(s)return s.getText(`source`).toString();let S=resolveContentEntryPath(g,`file`,e);return existsSync(S)?readFileSync(S,`utf-8`):null}function Wr(e,t){let s=resolveContentEntryPath(g,`file`,e);tracedMkdirSync(dirname(s),{recursive:!0}),writeFileIfContentDiffers(s,t),registerWrite(s,contentHash(t)),setReconciledBase(e,t),O?.({kind:`update`,path:s,docName:e,content:t})}function Gr(e,s,g=[]){let S=t.documents.get(e);if(!S)throw Error(`Document is not loaded: ${e}`);let w={markdown:``,rewrites:0};return S.transact(()=>{w=qr(S.getText(`source`).toString(),e,s.get(e)??e,s,g),w.rewrites!==0&&composeAndWriteRawBody(S,w.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),w}function Kr(e,t,s){let g=e,S=0;for(let{fromPath:e,toPath:w}of s){let s=rewriteAssetReferencesForRename(g,t,e,w);g=s.markdown,S+=s.rewrites}return{markdown:g,rewrites:S}}function qr(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=Kr(w.markdown,s,S);return{markdown:E.markdown,rewrites:E.markdown===e?0:w.rewrites+E.rewrites}}function Jr(e,s){let g=t.documents.get(e);if(!g)throw Error(`Document is not loaded: ${e}`);let S={markdown:``,rewrites:0};return g.transact(()=>{S=Kr(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function Yr(e){let t=[];if(e.length===0)return t;let s=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let g of s){let s=Ur(g);if(typeof s!=`string`)continue;let S=Kr(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function Xr(e){let s=ve?.(),g=new Set(s?s.getConflicts().map(e=>e.file):[]);for(let s of e){let e=t.documents.get(s),S=docNameToRelativePath(s),w=e!==void 0&&isDocInConflict(e),E=g.has(S);if(w||E)throw new DocInConflictError({file:S})}}function Zr(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?Jr(S.docName,s):S;e.rewrites!==0&&(Wr(S.docName,e.markdown),ue?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function Qr(e){if(extname(e))return{path:e,ambiguous:!1};let t=e.lastIndexOf(`/`),s=t===-1?``:e.slice(0,t),S=t===-1?e:e.slice(t+1),w=s?resolveContentEntryPath(g,`folder`,s):g,E;try{E=readdirSync(w,{withFileTypes:!0})}catch(t){let s=t.code;if(s===`ENOENT`||s===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let D=E.filter(e=>e.isFile()&&e.name.startsWith(`${S}.`)).map(e=>s?`${s}/${e.name}`:e.name).filter(e=>isSupportedAssetFile(e,LINKABLE_ASSET_EXTENSIONS));return D.length===1?{path:D[0],ambiguous:!1}:{path:e,ambiguous:D.length>1}}function Gi(e){let t=[];try{if(!statSync(e).isDirectory())return t}catch(e){let s=e.code;if(s===`ENOENT`||s===`ENOTDIR`)return t;throw e}function s(e){for(let S of readdirSync(e,{withFileTypes:!0})){let w=resolve(e,S.name),E=relative(g,w).split(sep).join(`/`);if(isReservedProjectStatePath(E))continue;if(S.isDirectory()){if(De?.isDirExcluded(E))continue;s(w);continue}if(!S.isFile()||!isSupportedDocFile(E)||De?.isExcluded(E))continue;let D=docNameForFileOperationPath(g,E);registerDocExtension(stripDocExtension(E),extname(E)),t.push(D)}}return s(e),t.sort((e,t)=>e.localeCompare(t)),t}function Ki(e,t,s){let S=[];function w(e){for(let E of readdirSync(e,{withFileTypes:!0})){let D=resolve(e,E.name),O=relative(g,D).split(sep).join(`/`);if(!isReservedProjectStatePath(O)){if(E.isDirectory()){if(De?.isDirExcluded(O))continue;w(D);continue}!E.isFile()||isSupportedDocFile(O)||De?.isExcluded(O)||(O===t?S.push({fromPath:O,toPath:s}):O.startsWith(`${t}/`)&&S.push({fromPath:O,toPath:`${s}${O.slice(t.length)}`}))}}}return w(e),S.sort((e,t)=>e.fromPath.localeCompare(t.fromPath)),S}async function Ji(e,t){return jr(async()=>withSpan(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async s=>{if(!ue)throw new BacklinkIndexRequiredError;let S=extname(t)?t:`${t}${extname(e)}`;if(isReservedProjectStatePath(e)||isReservedProjectStatePath(S))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(S))throw new ManagedRenameInvalidRequestError(`Destination asset is excluded by the project content config.`);let w=resolveContentEntryPath(g,`folder`,e),E=resolveContentEntryPath(g,`folder`,S);if(w===E)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,S))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(w))throw new ManagedRenameSourceNotFoundError(`asset`,`Asset does not exist.`);if(existsSync(E))throw new ManagedRenameDestinationExistsError;if(!statSync(w).isFile())throw new ManagedRenameSourceTypeMismatchError(`asset`,`Source path is not an asset file.`);let D=[{fromPath:e,toPath:S}],O=Yr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),Xr(O.map(e=>e.docName)),await renameTrackedPathInGit(Ce,w,E)||renamePathOnDisk(w,E);let k=Zr(O,D);return ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist asset rename cache for ${e} -> ${S}:`,t)}),fe?.(`files`),k.length>0&&(fe?.(`backlinks`),fe?.(`graph`)),k.sort((e,t)=>e.docName.localeCompare(t.docName)),s.setAttribute(`rename.rewrite_count`,k.length),{renamedAssets:D,rewrittenDocs:k}}))}async function Yi(e,s){return jr(async()=>withSpan(`rename.executeDocumentToFileRewrites`,{attributes:{"rename.kind":`asset`,"rename.transition":`document-to-file`}},async S=>{if(!ue)throw new BacklinkIndexRequiredError;if(!isSupportedDocFile(e)||isSupportedDocFile(s))throw new ManagedRenameInvalidRequestError(`Document-to-file rename requires a markdown source and non-markdown destination.`);let w=stripDocExtension(e);if(isSystemDoc(w)||isConfigDoc(w))throw new ManagedRenameReservedPathError(`Reserved document names cannot be renamed.`);if(isReservedProjectStatePath(e)||isReservedProjectStatePath(s))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(s))throw new ManagedRenameInvalidRequestError(`Destination file is excluded by the project content config.`);let E=resolveContentEntryPath(g,`folder`,e),D=resolveContentEntryPath(g,`folder`,s);if(E===D)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,s))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(E))throw new ManagedRenameSourceNotFoundError(`file`);if(existsSync(D))throw new ManagedRenameDestinationExistsError;if(!statSync(E).isFile())throw new ManagedRenameSourceTypeMismatchError(`file`,`Source path is not a document file.`);let k=ve?.(),j=new Set(k?k.getConflicts().map(e=>e.file):[]),F=t.documents.get(w);if(F!==void 0&&isDocInConflict(F)||j.has(e))throw new DocInConflictError({file:e});let L=[{fromPath:e,toPath:s}],B=Yr(L).filter(e=>e.docName!==w);S.setAttribute(`rename.rewrite_candidates`,B.length),Xr(B.map(e=>e.docName)),reconcileDiskBeforeAgentWrite(t,w,g),Ie&&!isSystemDoc(w)&&!isConfigDoc(w)&&Ie.setDeleted(w);let H=(await Br([w],`renamed`)).get(w),q=typeof H==`string`?H:readFileSync(E,`utf-8`),ee=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[{from:w,to:w}],snapshots:[{docName:w,content:q}],cleanupPaths:[s]}),J=[];return await withManagedRenameRecovery(Ce??g,ee,async()=>{writeFileIfContentDiffers(E,q),registerWrite(E,contentHash(q)),await renameTrackedPathInGit(Ce,E,D)||renamePathOnDisk(E,D),ue.deleteDocument(w),forgetDocExtension(w),O?.({kind:`delete`,path:E,docName:w});let t=statSync(D);O?.({kind:`file-create`,path:D,relativePath:s,size:t.size,modifiedTs:t.mtimeMs,inode:t.ino}),J=Zr(B,L),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist document-to-file rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),J.length>0&&(fe?.(`backlinks`),fe?.(`graph`))}),J.sort((e,t)=>e.docName.localeCompare(t.docName)),S.setAttribute(`rename.rewrite_count`,J.length),{renamedAssets:L,rewrittenDocs:J}}))}async function Xi(e,s,S,E){return jr(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":S}},async D=>{if(!ue)throw new BacklinkIndexRequiredError;let k=resolveContentEntryPath(g,S,e),j=resolveContentEntryPath(g,S,s);if(k===j)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!existsSync(k))throw new ManagedRenameSourceNotFoundError(S);if(existsSync(j)&&!isCaseOnlySelfCollision(k,j))throw new ManagedRenameDestinationExistsError;let F=statSync(k);if(S===`file`&&!F.isFile()||S===`folder`&&!F.isDirectory())throw new ManagedRenameSourceTypeMismatchError(S);let L=S===`folder`?Ki(k,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[docNameForFileOperationPath(g,e)]:Gi(k)).map(t=>({from:t,to:S===`file`?docNameForFileOperationPath(g,s):remapDocNameForRename(t,S,e,s)}));if(D.setAttribute(`rename.affected_docs`,B.length),B.length===0){let t=Yr(L);Xr(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(Ce,k,j)||renamePathOnDisk(k,j),st(e,s),fe?.(`files`)),g.push(...Zr(t,L)),g.length>0&&(ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`backlinks`),fe?.(`graph`)),g.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:[],renamedAssets:L,rewrittenDocs:g}}let H=buildRenameMap(B),q=B.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),J=new Set;for(let{from:e}of B)for(let t of ue.getBacklinks(e))H.has(t.source)||J.add(t.source);let Y=[...J].sort((e,t)=>e.localeCompare(t)),te=new Map,ne=new Set,ae=new Set,se=[];for(let e of[...H.keys(),...Y]){if(te.has(e))continue;if(!H.has(e)&&!existsSync(resolveContentEntryPath(g,`file`,e))){se.push(e);continue}reconcileDiskBeforeAgentWrite(t,e,g);let s=Ur(e);typeof s==`string`?(te.set(e,s),H.has(e)||ne.add(e)):H.has(e)||se.push(e)}if(L.length>0){let e=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let t of e){let e=te.get(t)??Ur(t);typeof e==`string`&&qr(e,t,H.get(t)??t,H,L).rewrites!==0&&(te.has(t)||te.set(t,e),ae.add(t),H.has(t)||ne.add(t))}}Xr(ae);for(let{from:e}of B)if(typeof te.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ce=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[...B],snapshots:Hr([...te.keys()],te)}),de=[],me=[...ne].sort((e,t)=>e.localeCompare(t));return await withManagedRenameRecovery(Ce??g,ce,async()=>{for(let e of se)ue.deleteDocument(e);for(let e of me){let s=t.documents.get(e)?Gr(e,H,L):qr(te.get(e)??``,e,e,H,L);s.rewrites>0&&(Wr(e,s.markdown),de.push({docName:e,rewrites:s.rewrites})),ue.updateDocumentFromMarkdown(e,s.markdown)}if(Ie)for(let{from:e,to:t}of B)isSystemDoc(e)||isConfigDoc(e)||(Ie.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let w=resolveContentEntryPath(g,S,e),D=resolveContentEntryPath(g,S,s);await renameTrackedPathInGit(Ce,w,D)||renamePathOnDisk(w,D),S===`folder`&&st(e,s);let k=await Br([...H.keys()],`renamed`);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(ee?.current){let e=ee.current,t=B.filter(({from:e,to:t})=>stripDocExtension(e)!==stripDocExtension(t));t.length>0&&withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":S}},s=>{let g=randomUUID(),w=new Date().toISOString(),D=oe?.()??`main`,O=getOrLoadRenameLogIndex(e.gitDir),k=E?.actor?{writerId:E.actor.writerId,displayName:E.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},j=0;for(let{from:s,to:F}of t){let t={v:1,from:s,to:F,at:w,commitSha:``,branch:D,groupId:g,kind:S,actor:k};appendRenameLogEntry(e.gitDir,t,O,e),j+=1,E?.actor?recordContributor(F,E.actor.writerId,E.actor.displayName,E.actor.colorSeed,formatRenameSubject(s,F),E.actor.actorMetadata,void 0,[{from:s,to:F}]):recordContributor(F,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(s,F),void 0,void 0,[{from:s,to:F}])}s.setAttribute(`rename.entries_appended`,j)})}let j=S===`file`&&isSupportedDocFile(s)?extname(s):null;for(let{from:e,to:t}of B){let s=isSupportedDocFile(e)?extname(e):getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,j??s)}let F=[...B].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of F){let s=resolveContentEntryPath(g,`file`,e),S=resolveContentEntryPath(g,`file`,t),w=qr(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Vr([{fromDocName:e,toDocName:t}],new Map([[e,w.markdown]])),setReconciledBase(t,w.markdown),O?.({kind:`rename`,oldPath:s,newPath:S,oldDocName:e,newDocName:t,content:w.markdown}),ue.renameDocument(e,t,w.markdown),w.rewrites>0&&de.push({docName:t,rewrites:w.rewrites})}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-journal-clear`)throw Error(`OK_TEST_RENAME_FAULT=pre-journal-clear`)}),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),fe?.(`backlinks`),fe?.(`graph`),de.sort((e,t)=>e.docName.localeCompare(t.docName)),D.setAttribute(`rename.rewrite_count`,de.length),{renamed:q,renamedAssets:L,rewrittenDocs:de}}))}function Qi(e){let t=parseAgentBodyFields(e),s=t.writerId??`claude-1`;return{rawAgentId:t.rawAgentId,agentId:s,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??s,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function Ra(e){return{principalId:we?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function eo(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 to(e){return{value:e.value}}function so(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function _s(e,t,s,g){if(s.length!==0)switch(e.kind){case`agent`:{let g=e.summary.kind===`value`,S=g?e.summary:normalizeSummary(t),w=eo(S),E=g||!w.response?w.response:to(w.response);for(let t=0;t<s.length;t++){let{docName:g,subject:S}=s[t];recordContributor(g,e.writerId,e.displayName,e.colorSeed,S,e.actor,t===0?w.stored:void 0)}incrementAgentWriteCalls(),so(S,!g);for(let{docName:e}of s)Ht(e,`rename-path`);return E}case`principal`:{let t=eo(e.summary);for(let g=0;g<s.length;g++){let{docName:S,subject:w}=s[g];recordContributor(S,e.writerId,e.displayName,e.colorSeed,w,e.actor,g===0?t.stored:void 0)}so(e.summary,!1);for(let{docName:e}of s)Ht(e,`rename-path`);return t.response}case`anonymous`:g.onAnonymous?.();return;default:{let t=e;throw Error(`Unhandled actor kind in ${g.context}: ${String(t.kind)}`)}}}function xs(e,t,s){let g=t.replace(/\/$/,``),S=g===``?``:`${g}/`;return e===`template`?`${S}.ok/templates/${s}`:e===`skill`?`${S}.ok/skills/${s}`:e===`folder-frontmatter`?`${S}.ok/frontmatter`:g===``?`.`:g}function Cs(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=eo(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Ts(e){if(Y)try{await Y()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let Ds=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Qi(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write`});return}let H=normalizeSummary(E.summary),q=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),J=new Date().toISOString(),Y=typeof E.content==`string`?E.content:`Hello from the agent! ${J}`,{response:te,stored:ne}=eo(H);try{let t=iconFromClientName(F),s=AGENT_ICON_COLORS[t]??colorFromSeed(j??O);ge?.setPresence(O,{displayName:k,icon:t,color:s,currentDoc:D,mode:`writing`,ts:Date.now()}),captureEffect(q.dc.document.getText(`source`),O,j,F),q.dc.document.transact(()=>{applyAgentMarkdownWrite(q.dc.document,`${Y}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),q.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${Y.slice(0,50)}`})},q.origin),recordContributor(D,O,k,j,void 0,Ra({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),so(H)}finally{ge?.touchMode(O,`idle`)}let ae=await Ut(D);if(ae?.kind===`failure`){Wt(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){Xt(w,`agent-write`);return}Ht(D,`agent-write`),_e?.();let oe=Zt(ee);successResponse(w,200,AgentWriteSuccessSchema,{timestamp:J,...te?{summary:te}:{},...oe?{warning:oe,warnings:[oe]}:{}},{handler:`agent-write`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[agent-write] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),Os=withValidation(AgentWriteMdRequestSchema,async(S,w,E)=>{try{let S=E.position??`append`,D=requireNonEmptyDocName(E.docName,w,`agent-write-md`);if(D===null)return;let O=zt(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=Qi(E);if(isSystemDoc(O)||isConfigDoc(O)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`agent-write-md`});return}E.extension!==void 0&&!docNameExistsWithAnySupportedExtension(g,O)&®isterDocExtension(O,E.extension);let q=normalizeSummary(E.summary),{response:ee,stored:J}=eo(q),Y=await s.getSession(O,k,{displayName:j,colorSeed:F,clientName:L}),te=reconcileDiskBeforeAgentWrite(t,O,g,e.resolveEmbed),ne=new Date().toISOString(),ae;try{let t=iconFromClientName(L),s=AGENT_ICON_COLORS[t]??colorFromSeed(F??k);ge?.setPresence(k,{displayName:j,icon:t,color:s,currentDoc:O,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),k,F,L),Y.dc.document.transact(()=>{ae=applyAgentMarkdownWrite(Y.dc.document,E.markdown,S,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0),Y.dc.document.getMap(`agent-flash`).set(k,{agentId:k,timestamp:Date.now(),type:`insert`,description:`Added (${j}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),ae!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:S,intendedBytes:ae.intendedBytes,actualBytes:ae.actualBytes,byteDelta:ae.byteDelta,"agent.id":k,"agent.client_name":L})),recordContentDivergenceGate(`agent-write-md`,ae),recordContributor(O,k,j,F,void 0,Ra({clientName:L,clientVersion:B,label:H}),J),incrementAgentWriteCalls(),so(q)}finally{ge?.touchMode(k,`idle`)}let oe=await Ut(O);if(oe?.kind===`failure`){Wt(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){Xt(w,`agent-write-md`);return}Ht(O,`agent-write-md`),me?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),_e?.();let se=Rt(O),ce=Y.dc.document.getText(`source`).toString();rn(O,ce);let ue=await validateMermaidFences(ce,O),de=en();de.add(O);let fe=computeBrokenOutboundLinks(ce,O,de,tn),ve=Bt(O),ye=Vt();ye===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let Ce=Zt(te),we=ae===void 0?void 0:toContentDivergenceWarning(ae),Te=[...we?[we]:[],...Ce?[Ce]:[],...ue??[]];successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ne,subscriberCount:ve,systemSubscriberCount:ye,...se?{hints:se}:{},...ee?{summary:ee}:{},...we?{warning:we}:Ce?{warning:Ce}:{},...Te.length>0?{warnings:Te}:{},brokenLinks:fe},{handler:`agent-write-md`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write-md`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write-md`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write-md`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[agent-write-md] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-md`,cause:e})}},{handler:`agent-write-md`,method:`POST`}),ks=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Qi(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let H=E.patch??{},q=Object.keys(H),ee=normalizeSummary(E.summary),{response:J,stored:Y}=eo(ee),te=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ne=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),ae=new Date().toISOString(),oe,se=!1,ce=!1,ue=[];try{let e=iconFromClientName(F),t=AGENT_ICON_COLORS[e]??colorFromSeed(j??O);ge?.setPresence(O,{displayName:k,icon:e,color:t,currentDoc:D,mode:`writing`,ts:Date.now()}),withSpanSync(`ok.frontmatter_patch`,{attributes:{"doc.name":D,"frontmatter_patch.keys":q.length}},()=>{te.dc.document.transact(()=>{let{fenced:e,body:t}=detectFmRegion(te.dc.document.getText(`source`).toString()),s=applyPatchToFm(e,H);if(!s.ok){oe=s.error;return}for(let e of Object.keys(H))ue.push(e);if(s.nextFenced!==e){let g=e===``&&t!==``&&!t.startsWith(`
|
|
1942
|
+
`)}function St(){$e=null}F?.(St);let Tt=createInstalledAgentsProbe({probe:je??createOsProbe(process.platform)});function Et(e){if(isManagedArtifactDocName(e))try{return managedArtifactAbsPath(e,{projectDir:Ce??g,homedirOverride:Te})}catch{return null}if(!isSafeDocName(e))return null;let t=resolve(g),s=resolve(t,docNameToRelativePath(e));return isWithinDir(s,t)?s:null}function jt(e){let t=Et(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Mt(e,t){return t.has(e)?jt(e):e}let Ft={cluster:void 0,category:void 0,tags:void 0};function It(e){try{let s=t.documents.get(e);if(s){let e=readFmMap(s.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,s=typeof e.category==`string`?e.category:void 0,g;if(Array.isArray(e.tags)){let t=e.tags.filter(e=>typeof e==`string`);g=t.length>0?t:void 0}else typeof e.tags==`string`&&e.tags&&(g=[e.tags]);return{cluster:t,category:s,tags:g}}}}catch{}try{let t=Et(e);if(!t||!existsSync(t))return Ft;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):Ft}catch{return Ft}}function Lt(e,t){return t.has(e)?It(e):Ft}function Rt(e){if(ue)try{if(ue.getBacklinks(e).length>0)return;let t=performance.now(),s=findHubCandidates(e,w()),g=performance.now()-t;return g>5&&log$7.debug({docName:e,elapsedMs:g,candidateCount:s.length},`[orphan-hint] findHubCandidates slow`),s.length===0?void 0:[{type:`orphan`,parentCandidates:s,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): ${s.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function zt(e){return L?.().get(e)??e}function Bt(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function Vt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function Ht(e,s){let g=`onStoreDocument-${e}`;(t.debouncer.isDebounced(g)?t.debouncer.executeNow(g):Promise.resolve()).then(()=>J?.()).catch(e=>{log$7.warn({err:e},`[${s}] post-write flush failed`)})}async function Ut(e){let s=`onStoreDocument-${e}`;t.debouncer.isDebounced(s)&&(ae?.(e),await t.debouncer.executeNow(s));let g=te?.(e)??null;return g?{kind:`failure`,failure:g}:ne?.(e)?{kind:`divergence`}:null}function Wt(e,t,s){let g=classifyUploadErrno({code:t.code});errorResponse(e,uploadStatusFor(g),g,`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:s})}function Xt(e,t){errorResponse(e,409,`urn:ok:error:disk-divergence`,`The document changed on disk after your edit was prepared; your edit was NOT applied, to avoid overwriting the newer on-disk content. Re-read the document and retry.`,{handler:t})}function Zt(e){if(e.reconciled)return{kind:`disk-edit-reconciled`,intendedBytes:e.baseBytes,actualBytes:e.diskBytes,byteDelta:e.diskBytes-e.baseBytes,...e.mergeOutcome?{mergeOutcome:e.mergeOutcome}:{},hint:e.mergeOutcome===`merged`?'An out-of-band edit was three-way merged into this document before your edit was applied on top; the merge may have interleaved content blocks. Re-read it (e.g. `exec("cat <path>")`) and review the combined result carefully before continuing.':'An out-of-band edit was reconciled into this document before your edit was applied on top; the document now reflects that edit plus yours. Re-read it (e.g. `exec("cat <path>")`) to see the combined result before continuing.'}}function $t(e){if(!De)return!1;let t=docNameToRelativePath(e);return De.isExcluded(t)}function en(){let e=new Set;for(let[t,s]of w()){e.add(t);for(let t of s.aliases)e.add(t)}try{for(let t of[`project`,`global`]){let s=resolve(t===`global`?du:g,`.ok`,`skills`);for(let g of vu(s,t).skills)e.add(`${MANAGED_ARTIFACT_PREFIX_SKILL}${t}/${g.name}`)}for(let t of resolveProjectTemplates(resolve(g)).templates)e.add(pu(t.source_folder,t.name))}catch(e){log$7.warn({err:e},`[collectAdmittedDocNames] managed-artifact enumeration failed`)}for(let t of ue?.getIndexedDocNames()??[])e.has(t)||$t(t)||e.add(t);return e}let tn=e=>existsSync(resolve(g,e));function rn(e,t){$t(e)||O?.({kind:w().has(e)?`update`:`create`,path:resolveContentEntryPath(g,`file`,e),docName:e,content:t})}function sn(){let e=Promise.resolve();return async function(t){let s=e,g=()=>{};e=new Promise(e=>{g=e}),await s;try{return await t()}finally{g()}}}let jr=sn(),Mr=e=>e.endsWith(`.`)?e:`${e}.`;function zr(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:Mr(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:Mr(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:Mr(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Mr(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:Mr(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:Mr(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:Mr(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 Br(e,g){let S=new Map;for(let s of e){let e=t.documents.get(s);e&&S.set(s,e.getText(`source`).toString())}for(let s of e){let e=t.documents.get(s);e&&e.getMap(`lifecycle`).set(`status`,g)}for(let t of e)await s.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let s of e){let e=t.documents.get(s);deleteReconciledBase(s),ze?.(s),e&&(t.closeConnections(s),await(Me??t.unloadDocument.bind(t))(e))}return S}function Vr(e,t){for(let{fromDocName:s,toDocName:S}of e){let e=safeContentPath(S,g),w=t.get(s);typeof w==`string`&&writeFileIfContentDiffers(e,w);let E=typeof w==`string`?w:existsSync(e)?readFileSync(e,`utf-8`):null;typeof E==`string`&®isterWrite(e,contentHash(E))}}function Hr(e,t){return e.map(e=>{let s=t.get(e);if(typeof s==`string`)return{docName:e,content:s};let S=safeContentPath(e,g);if(!existsSync(S))throw new ManagedRenameSnapshotMissingError(e);return{docName:e,content:readFileSync(S,`utf-8`)}})}function Ur(e){let s=t.documents.get(e);if(s)return s.getText(`source`).toString();let S=resolveContentEntryPath(g,`file`,e);return existsSync(S)?readFileSync(S,`utf-8`):null}function Wr(e,t){let s=resolveContentEntryPath(g,`file`,e);tracedMkdirSync(dirname(s),{recursive:!0}),writeFileIfContentDiffers(s,t),registerWrite(s,contentHash(t)),setReconciledBase(e,t),O?.({kind:`update`,path:s,docName:e,content:t})}function Gr(e,s,g=[]){let S=t.documents.get(e);if(!S)throw Error(`Document is not loaded: ${e}`);let w={markdown:``,rewrites:0};return S.transact(()=>{w=qr(S.getText(`source`).toString(),e,s.get(e)??e,s,g),w.rewrites!==0&&composeAndWriteRawBody(S,w.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),w}function Kr(e,t,s){let g=e,S=0;for(let{fromPath:e,toPath:w}of s){let s=rewriteAssetReferencesForRename(g,t,e,w);g=s.markdown,S+=s.rewrites}return{markdown:g,rewrites:S}}function qr(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=Kr(w.markdown,s,S);return{markdown:E.markdown,rewrites:E.markdown===e?0:w.rewrites+E.rewrites}}function Jr(e,s){let g=t.documents.get(e);if(!g)throw Error(`Document is not loaded: ${e}`);let S={markdown:``,rewrites:0};return g.transact(()=>{S=Kr(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function Yr(e){let t=[];if(e.length===0)return t;let s=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let g of s){let s=Ur(g);if(typeof s!=`string`)continue;let S=Kr(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function Xr(e){let s=ve?.(),g=new Set(s?s.getConflicts().map(e=>e.file):[]);for(let s of e){let e=t.documents.get(s),S=docNameToRelativePath(s),w=e!==void 0&&isDocInConflict(e),E=g.has(S);if(w||E)throw new DocInConflictError({file:S})}}function Zr(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?Jr(S.docName,s):S;e.rewrites!==0&&(Wr(S.docName,e.markdown),ue?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function Qr(e){if(extname(e))return{path:e,ambiguous:!1};let t=e.lastIndexOf(`/`),s=t===-1?``:e.slice(0,t),S=t===-1?e:e.slice(t+1),w=s?resolveContentEntryPath(g,`folder`,s):g,E;try{E=readdirSync(w,{withFileTypes:!0})}catch(t){let s=t.code;if(s===`ENOENT`||s===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let D=E.filter(e=>e.isFile()&&e.name.startsWith(`${S}.`)).map(e=>s?`${s}/${e.name}`:e.name).filter(e=>isSupportedAssetFile(e,LINKABLE_ASSET_EXTENSIONS));return D.length===1?{path:D[0],ambiguous:!1}:{path:e,ambiguous:D.length>1}}function Gi(e){let t=[];try{if(!statSync(e).isDirectory())return t}catch(e){let s=e.code;if(s===`ENOENT`||s===`ENOTDIR`)return t;throw e}function s(e){for(let S of readdirSync(e,{withFileTypes:!0})){let w=resolve(e,S.name),E=relative(g,w).split(sep).join(`/`);if(isReservedProjectStatePath(E))continue;if(S.isDirectory()){if(De?.isDirExcluded(E))continue;s(w);continue}if(!S.isFile()||!isSupportedDocFile(E)||De?.isExcluded(E))continue;let D=docNameForFileOperationPath(g,E);registerDocExtension(stripDocExtension(E),extname(E)),t.push(D)}}return s(e),t.sort((e,t)=>e.localeCompare(t)),t}function Ki(e,t,s){let S=[];function w(e){for(let E of readdirSync(e,{withFileTypes:!0})){let D=resolve(e,E.name),O=relative(g,D).split(sep).join(`/`);if(!isReservedProjectStatePath(O)){if(E.isDirectory()){if(De?.isDirExcluded(O))continue;w(D);continue}!E.isFile()||isSupportedDocFile(O)||De?.isExcluded(O)||(O===t?S.push({fromPath:O,toPath:s}):O.startsWith(`${t}/`)&&S.push({fromPath:O,toPath:`${s}${O.slice(t.length)}`}))}}}return w(e),S.sort((e,t)=>e.fromPath.localeCompare(t.fromPath)),S}async function Ji(e,t){return jr(async()=>withSpan(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async s=>{if(!ue)throw new BacklinkIndexRequiredError;let S=extname(t)?t:`${t}${extname(e)}`;if(isReservedProjectStatePath(e)||isReservedProjectStatePath(S))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(S))throw new ManagedRenameInvalidRequestError(`Destination asset is excluded by the project content config.`);let w=resolveContentEntryPath(g,`folder`,e),E=resolveContentEntryPath(g,`folder`,S);if(w===E)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,S))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(w))throw new ManagedRenameSourceNotFoundError(`asset`,`Asset does not exist.`);if(existsSync(E))throw new ManagedRenameDestinationExistsError;if(!statSync(w).isFile())throw new ManagedRenameSourceTypeMismatchError(`asset`,`Source path is not an asset file.`);let D=[{fromPath:e,toPath:S}],O=Yr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),Xr(O.map(e=>e.docName)),await renameTrackedPathInGit(Ce,w,E)||renamePathOnDisk(w,E);let k=Zr(O,D);return ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist asset rename cache for ${e} -> ${S}:`,t)}),fe?.(`files`),k.length>0&&(fe?.(`backlinks`),fe?.(`graph`)),k.sort((e,t)=>e.docName.localeCompare(t.docName)),s.setAttribute(`rename.rewrite_count`,k.length),{renamedAssets:D,rewrittenDocs:k}}))}async function Yi(e,s){return jr(async()=>withSpan(`rename.executeDocumentToFileRewrites`,{attributes:{"rename.kind":`asset`,"rename.transition":`document-to-file`}},async S=>{if(!ue)throw new BacklinkIndexRequiredError;if(!isSupportedDocFile(e)||isSupportedDocFile(s))throw new ManagedRenameInvalidRequestError(`Document-to-file rename requires a markdown source and non-markdown destination.`);let w=stripDocExtension(e);if(isSystemDoc(w)||isConfigDoc(w))throw new ManagedRenameReservedPathError(`Reserved document names cannot be renamed.`);if(isReservedProjectStatePath(e)||isReservedProjectStatePath(s))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(s))throw new ManagedRenameInvalidRequestError(`Destination file is excluded by the project content config.`);let E=resolveContentEntryPath(g,`folder`,e),D=resolveContentEntryPath(g,`folder`,s);if(E===D)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,s))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(E))throw new ManagedRenameSourceNotFoundError(`file`);if(existsSync(D))throw new ManagedRenameDestinationExistsError;if(!statSync(E).isFile())throw new ManagedRenameSourceTypeMismatchError(`file`,`Source path is not a document file.`);let k=ve?.(),j=new Set(k?k.getConflicts().map(e=>e.file):[]),F=t.documents.get(w);if(F!==void 0&&isDocInConflict(F)||j.has(e))throw new DocInConflictError({file:e});let L=[{fromPath:e,toPath:s}],B=Yr(L).filter(e=>e.docName!==w);S.setAttribute(`rename.rewrite_candidates`,B.length),Xr(B.map(e=>e.docName)),reconcileDiskBeforeAgentWrite(t,w,g),Ie&&!isSystemDoc(w)&&!isConfigDoc(w)&&Ie.setDeleted(w);let H=(await Br([w],`renamed`)).get(w),q=typeof H==`string`?H:readFileSync(E,`utf-8`),ee=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[{from:w,to:w}],snapshots:[{docName:w,content:q}],cleanupPaths:[s]}),J=[];return await withManagedRenameRecovery(Ce??g,ee,async()=>{writeFileIfContentDiffers(E,q),registerWrite(E,contentHash(q)),await renameTrackedPathInGit(Ce,E,D)||renamePathOnDisk(E,D),ue.deleteDocument(w),forgetDocExtension(w),O?.({kind:`delete`,path:E,docName:w});let t=statSync(D);O?.({kind:`file-create`,path:D,relativePath:s,size:t.size,modifiedTs:t.mtimeMs,inode:t.ino}),J=Zr(B,L),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist document-to-file rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),J.length>0&&(fe?.(`backlinks`),fe?.(`graph`))}),J.sort((e,t)=>e.docName.localeCompare(t.docName)),S.setAttribute(`rename.rewrite_count`,J.length),{renamedAssets:L,rewrittenDocs:J}}))}async function Xi(e,s,S,E){return jr(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":S}},async D=>{if(!ue)throw new BacklinkIndexRequiredError;let k=resolveContentEntryPath(g,S,e),j=resolveContentEntryPath(g,S,s);if(k===j)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!existsSync(k))throw new ManagedRenameSourceNotFoundError(S);if(existsSync(j)&&!isCaseOnlySelfCollision(k,j))throw new ManagedRenameDestinationExistsError;let F=statSync(k);if(S===`file`&&!F.isFile()||S===`folder`&&!F.isDirectory())throw new ManagedRenameSourceTypeMismatchError(S);let L=S===`folder`?Ki(k,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[docNameForFileOperationPath(g,e)]:Gi(k)).map(t=>({from:t,to:S===`file`?docNameForFileOperationPath(g,s):remapDocNameForRename(t,S,e,s)}));if(D.setAttribute(`rename.affected_docs`,B.length),B.length===0){let t=Yr(L);Xr(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(Ce,k,j)||renamePathOnDisk(k,j),st(e,s),fe?.(`files`)),g.push(...Zr(t,L)),g.length>0&&(ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`backlinks`),fe?.(`graph`)),g.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:[],renamedAssets:L,rewrittenDocs:g}}let H=buildRenameMap(B),q=B.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),J=new Set;for(let{from:e}of B)for(let t of ue.getBacklinks(e))H.has(t.source)||J.add(t.source);let Y=[...J].sort((e,t)=>e.localeCompare(t)),te=new Map,ne=new Set,ae=new Set,se=[];for(let e of[...H.keys(),...Y]){if(te.has(e))continue;if(!H.has(e)&&!existsSync(resolveContentEntryPath(g,`file`,e))){se.push(e);continue}reconcileDiskBeforeAgentWrite(t,e,g);let s=Ur(e);typeof s==`string`?(te.set(e,s),H.has(e)||ne.add(e)):H.has(e)||se.push(e)}if(L.length>0){let e=[...w().keys()].sort((e,t)=>e.localeCompare(t));for(let t of e){let e=te.get(t)??Ur(t);typeof e==`string`&&qr(e,t,H.get(t)??t,H,L).rewrites!==0&&(te.has(t)||te.set(t,e),ae.add(t),H.has(t)||ne.add(t))}}Xr(ae);for(let{from:e}of B)if(typeof te.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ce=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[...B],snapshots:Hr([...te.keys()],te)}),de=[],me=[...ne].sort((e,t)=>e.localeCompare(t));return await withManagedRenameRecovery(Ce??g,ce,async()=>{for(let e of se)ue.deleteDocument(e);for(let e of me){let s=t.documents.get(e)?Gr(e,H,L):qr(te.get(e)??``,e,e,H,L);s.rewrites>0&&(Wr(e,s.markdown),de.push({docName:e,rewrites:s.rewrites})),ue.updateDocumentFromMarkdown(e,s.markdown)}if(Ie)for(let{from:e,to:t}of B)isSystemDoc(e)||isConfigDoc(e)||(Ie.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let w=resolveContentEntryPath(g,S,e),D=resolveContentEntryPath(g,S,s);await renameTrackedPathInGit(Ce,w,D)||renamePathOnDisk(w,D),S===`folder`&&st(e,s);let k=await Br([...H.keys()],`renamed`);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(ee?.current){let e=ee.current,t=B.filter(({from:e,to:t})=>stripDocExtension(e)!==stripDocExtension(t));t.length>0&&withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":S}},s=>{let g=randomUUID(),w=new Date().toISOString(),D=oe?.()??`main`,O=getOrLoadRenameLogIndex(e.gitDir),k=E?.actor?{writerId:E.actor.writerId,displayName:E.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},j=0;for(let{from:s,to:F}of t){let t={v:1,from:s,to:F,at:w,commitSha:``,branch:D,groupId:g,kind:S,actor:k};appendRenameLogEntry(e.gitDir,t,O,e),j+=1,E?.actor?recordContributor(F,E.actor.writerId,E.actor.displayName,E.actor.colorSeed,formatRenameSubject(s,F),E.actor.actorMetadata,void 0,[{from:s,to:F}]):recordContributor(F,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(s,F),void 0,void 0,[{from:s,to:F}])}s.setAttribute(`rename.entries_appended`,j)})}let j=S===`file`&&isSupportedDocFile(s)?extname(s):null;for(let{from:e,to:t}of B){let s=isSupportedDocFile(e)?extname(e):getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,j??s)}let F=[...B].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of F){let s=resolveContentEntryPath(g,`file`,e),S=resolveContentEntryPath(g,`file`,t),w=qr(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Vr([{fromDocName:e,toDocName:t}],new Map([[e,w.markdown]])),setReconciledBase(t,w.markdown),O?.({kind:`rename`,oldPath:s,newPath:S,oldDocName:e,newDocName:t,content:w.markdown}),ue.renameDocument(e,t,w.markdown),w.rewrites>0&&de.push({docName:t,rewrites:w.rewrites})}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-journal-clear`)throw Error(`OK_TEST_RENAME_FAULT=pre-journal-clear`)}),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),fe?.(`backlinks`),fe?.(`graph`),de.sort((e,t)=>e.docName.localeCompare(t.docName)),D.setAttribute(`rename.rewrite_count`,de.length),{renamed:q,renamedAssets:L,rewrittenDocs:de}}))}function Qi(e){let t=parseAgentBodyFields(e),s=t.writerId??`claude-1`;return{rawAgentId:t.rawAgentId,agentId:s,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??s,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function Ra(e){return{principalId:we?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function eo(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 to(e){return{value:e.value}}function so(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function _s(e,t,s,g){if(s.length!==0)switch(e.kind){case`agent`:{let g=e.summary.kind===`value`,S=g?e.summary:normalizeSummary(t),w=eo(S),E=g||!w.response?w.response:to(w.response);for(let t=0;t<s.length;t++){let{docName:g,subject:S}=s[t];recordContributor(g,e.writerId,e.displayName,e.colorSeed,S,e.actor,t===0?w.stored:void 0)}incrementAgentWriteCalls(),so(S,!g);for(let{docName:e}of s)Ht(e,`rename-path`);return E}case`principal`:{let t=eo(e.summary);for(let g=0;g<s.length;g++){let{docName:S,subject:w}=s[g];recordContributor(S,e.writerId,e.displayName,e.colorSeed,w,e.actor,g===0?t.stored:void 0)}so(e.summary,!1);for(let{docName:e}of s)Ht(e,`rename-path`);return t.response}case`anonymous`:g.onAnonymous?.();return;default:{let t=e;throw Error(`Unhandled actor kind in ${g.context}: ${String(t.kind)}`)}}}function xs(e,t,s){let g=t.replace(/\/$/,``),S=g===``?``:`${g}/`;return e===`template`?`${S}.ok/templates/${s}`:e===`skill`?`${S}.ok/skills/${s}`:e===`folder-frontmatter`?`${S}.ok/frontmatter`:g===``?`.`:g}function Cs(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=eo(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Ts(e){if(Y)try{await Y()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let Ds=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Qi(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write`});return}let H=normalizeSummary(E.summary),q=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),J=new Date().toISOString(),Y=typeof E.content==`string`?E.content:`Hello from the agent! ${J}`,{response:te,stored:ne}=eo(H);try{let t=iconFromClientName(F),s=AGENT_ICON_COLORS[t]??colorFromSeed(j??O);ge?.setPresence(O,{displayName:k,icon:t,color:s,currentDoc:D,mode:`writing`,ts:Date.now()}),captureEffect(q.dc.document.getText(`source`),O,j,F),q.dc.document.transact(()=>{applyAgentMarkdownWrite(q.dc.document,`${Y}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),q.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${Y.slice(0,50)}`})},q.origin),recordContributor(D,O,k,j,void 0,Ra({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),so(H)}finally{ge?.touchMode(O,`idle`)}let ae=await Ut(D);if(ae?.kind===`failure`){Wt(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){Xt(w,`agent-write`);return}Ht(D,`agent-write`),_e?.();let oe=Zt(ee);successResponse(w,200,AgentWriteSuccessSchema,{timestamp:J,...te?{summary:te}:{},...oe?{warning:oe,warnings:[oe]}:{}},{handler:`agent-write`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[agent-write] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),Os=withValidation(AgentWriteMdRequestSchema,async(S,w,E)=>{try{let S=E.position??`append`,D=requireNonEmptyDocName(E.docName,w,`agent-write-md`);if(D===null)return;let O=zt(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=Qi(E);if(isSystemDoc(O)||isConfigDoc(O)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${O}' is a reserved document name.`,{handler:`agent-write-md`});return}E.extension!==void 0&&!docNameExistsWithAnySupportedExtension(g,O)&®isterDocExtension(O,E.extension);let q=normalizeSummary(E.summary),{response:ee,stored:J}=eo(q),Y=await s.getSession(O,k,{displayName:j,colorSeed:F,clientName:L}),te=reconcileDiskBeforeAgentWrite(t,O,g,e.resolveEmbed),ne=new Date().toISOString(),ae;try{let t=iconFromClientName(L),s=AGENT_ICON_COLORS[t]??colorFromSeed(F??k);ge?.setPresence(k,{displayName:j,icon:t,color:s,currentDoc:O,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),k,F,L),Y.dc.document.transact(()=>{ae=applyAgentMarkdownWrite(Y.dc.document,E.markdown,S,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0),Y.dc.document.getMap(`agent-flash`).set(k,{agentId:k,timestamp:Date.now(),type:`insert`,description:`Added (${j}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),ae!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:S,intendedBytes:ae.intendedBytes,actualBytes:ae.actualBytes,byteDelta:ae.byteDelta,"agent.id":k,"agent.client_name":L})),recordContentDivergenceGate(`agent-write-md`,ae),recordContributor(O,k,j,F,void 0,Ra({clientName:L,clientVersion:B,label:H}),J),incrementAgentWriteCalls(),so(q)}finally{ge?.touchMode(k,`idle`)}let oe=await Ut(O);if(oe?.kind===`failure`){Wt(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){Xt(w,`agent-write-md`);return}Ht(O,`agent-write-md`),me?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),_e?.();let se=Rt(O),ce=Y.dc.document.getText(`source`).toString();rn(O,ce);let ue=await validateMermaidFences(ce,O),de=en();de.add(O);let fe=computeBrokenOutboundLinks(ce,O,de,tn),ve=Bt(O),ye=Vt();ye===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let Ce=Zt(te),we=ae===void 0?void 0:toContentDivergenceWarning(ae),Te=[...we?[we]:[],...Ce?[Ce]:[],...ue??[]];successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ne,subscriberCount:ve,systemSubscriberCount:ye,...se?{hints:se}:{},...ee?{summary:ee}:{},...we?{warning:we}:Ce?{warning:Ce}:{},...Te.length>0?{warnings:Te}:{},brokenLinks:fe},{handler:`agent-write-md`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write-md`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write-md`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write-md`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[agent-write-md] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-md`,cause:e})}},{handler:`agent-write-md`,method:`POST`}),ks=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Qi(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let H=E.patch??{},q=Object.keys(H),ee=normalizeSummary(E.summary),{response:J,stored:Y}=eo(ee),te=await s.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ne=reconcileDiskBeforeAgentWrite(t,D,g,e.resolveEmbed),ae=new Date().toISOString(),oe,se=!1,ce=!1,ue=[];try{let e=iconFromClientName(F),t=AGENT_ICON_COLORS[e]??colorFromSeed(j??O);ge?.setPresence(O,{displayName:k,icon:e,color:t,currentDoc:D,mode:`writing`,ts:Date.now()}),withSpanSync(`ok.frontmatter_patch`,{attributes:{"doc.name":D,"frontmatter_patch.keys":q.length}},()=>{te.dc.document.transact(()=>{let{fenced:e,body:t}=detectFmRegion(te.dc.document.getText(`source`).toString()),s=applyPatchToFm(e,H);if(!s.ok){oe=s.error;return}for(let e of Object.keys(H))ue.push(e);if(s.nextFenced!==e){let g=e===``&&t!==``&&!t.startsWith(`
|
|
1943
1943
|
`),S=s.nextFenced+(g?`
|
|
1944
|
-
`:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),ce=!0}se=!0},te.origin)})}finally{ge?.touchMode(O,`idle`)}if(oe){let e;switch(oe.kind){case`invalid_value`:e={[oe.key]:oe.reason};break;case`reserved_key`:e={[oe.key]:`'${oe.key}' is reserved`};break;case`unknown_key`:e={[oe.key]:`'${oe.key}' is not a recognized key`};break;case`duplicate_target`:e={[oe.key]:`'${oe.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${oe.expected.join(`, `)}; got: ${oe.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${oe.bytes} > ${oe.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${oe.reason}`};break;case`invalid_path`:e={[oe.path.map(String).join(`.`)||`__path__`]:oe.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(oe)})`}}errorResponse(w,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(se&&ue.length>0){if(recordContributor(D,O,k,j,void 0,Ra({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),so(ee),ce){let e=await Ut(D);if(e?.kind===`failure`){Wt(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Xt(w,`frontmatter-patch`);return}}Ht(D,`frontmatter-patch`)}me?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),_e?.();let de=Bt(D),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=Zt(ne);rn(D,te.dc.document.getText(`source`).toString());let ye=en();ye.add(D);let Ce=computeBrokenOutboundLinks(te.dc.document.getText(`source`).toString(),D,ye,tn);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:de,systemSubscriberCount:fe,appliedKeys:ue,...J?{summary:J}:{},...ve?{warning:ve,warnings:[ve]}:{},brokenLinks:Ce},{handler:`frontmatter-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[frontmatter-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Ms(e){let t=e.getMap(`lifecycle`),s=t.get(`status`);if(typeof s!=`string`||s.length===0)return null;let g=t.get(`reason`);return{status:s,reason:typeof g==`string`?g:``}}let Ns=withValidation(EmptyRequestSchema,async(e,s)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(S)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let w=zt(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`document-read`});return}let E=t.documents.get(w);if(E){successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:E.getText(`source`).toString(),lifecycle:Ms(E)},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(g,`file`,w))){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document not found: ${w}.`,{handler:`document-read`});return}let D=await t.openDirectConnection(w);try{let e=D.document;if(!e){errorResponse(s,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:e.getText(`source`).toString(),lifecycle:Ms(e)},{handler:`document-read`})}finally{await D.disconnect()}}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),Ps=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$7.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=s.searchParams.get(`dir`),E=s.searchParams.get(`showAll`)===`true`,O=s.searchParams.get(`depth`)===`1`?1:1/0;if(S)try{safeSubdir(g,S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(E&&De&&showAllWantsNdjson(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let s=createStreamingErrorWriter(t,`document-list`),w=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let s=()=>{t.off(`drain`,s),t.off(`close`,s),e()};t.once(`drain`,s),t.once(`close`,s)})};try{let t=getShowAllMaxEntries(),s=streamShowAllEntries({contentDir:g,contentFilter:De,dirFilter:S,maxEntries:t,maxDepth:O,signal:e.signal}),E=0,D=await s.next();for(;!D.done;)await w(`${JSON.stringify(D.value)}\n`),E+=1,D=await s.next();let{truncated:k}=D.value;k&&log$7.info({handler:`document-list`,maxEntries:t,count:E},`[document-list][showAll] stream truncated at entry cap`),await w(`${JSON.stringify({type:`complete`,truncated:k,count:E})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?s(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):log$7.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(E&&De){let e=`showAll:${O===1?`d1:`:``}${S??``}`,s=Ke.get(e);if(!s){let t=new AbortController,w=(async()=>{let e=[],s=getShowAllMaxEntries(),{truncated:w}=await walkContentDirForShowAll({contentDir:g,contentFilter:De,dirFilter:S,documents:e,maxEntries:s,maxDepth:O,signal:t.signal});return e.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),w&&log$7.info({handler:`document-list`,maxEntries:s,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:w}})();s={promise:w,controller:t,waiters:0};let E=s;Ke.set(e,E),w.finally(()=>{Ke.get(e)===E&&Ke.delete(e)})}let w=s;w.waiters+=1;let E=!1,D=()=>{t.writableEnded||E||(E=!0,--w.waiters,w.waiters<=0&&(w.controller.abort(),Ke.get(e)===w&&Ke.delete(e)))};t.on(`close`,D);try{let{documents:e,truncated:s}=await w.promise;if(E)return;successResponse(t,200,DocumentListSuccessSchema,s?{documents:e,truncated:s}:{documents:e},{handler:`document-list`})}catch(e){if(E)return;errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,D)}return}let k=w(),F=D(),L=j?.()??new Map,H=[];for(let[e,t]of L)S&&!e.startsWith(`${S}/`)&&e!==S||H.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let q=[];try{let e=vt(k);$e?.signature!==e&&($e={signature:e,assets:collectReferencedAssets({contentDir:g,fileIndex:k,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:De?e=>De.isPathIgnored(e):void 0})}),q=$e?.assets??[]}catch(e){$e=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}let ee=new Set;for(let e of q)S&&!e.path.startsWith(`${S}/`)&&e.path!==S||(ee.add(e.path),H.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of F){if(t.kind===`markdown`){if(S&&!e.startsWith(`${S}/`)&&e!==S)continue;let s=getDocExtension(e);H.push({kind:`document`,docName:e,docExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let w of t.aliases){if(S&&!w.startsWith(`${S}/`)&&w!==S)continue;let E=toPosix(relative(g,t.canonicalPath));H.push({kind:`document`,docName:w,docExt:s,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:E})}continue}if((!S||e===S||e.startsWith(`${S}/`))&&!ee.has(e)){let s=synthesizeShowAllAssetExt(e);H.push({kind:`file`,docName:e,path:e,docExt:`.${s}`,assetExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let s of t.aliases){if(!(!S||s===S||s.startsWith(`${S}/`))||ee.has(s))continue;let w=toPosix(relative(g,t.canonicalPath)),E=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${E}`,assetExt:E,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:w})}}let J=B?.()??new Map;if(J.size>0){let e=e=>!S||e===S||e.startsWith(`${S}/`),t=new Map;for(let[e,s]of J){let g=t.get(s);g?g.push(e):t.set(s,[e])}for(let[s,S]of t){let t=L.get(s),w=t?toPosix(relative(g,t.canonicalPath)):s;for(let g of S)e(g)&&H.push({kind:`folder`,path:g,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:s,targetPath:w})}let s=(s,g)=>{for(let S=s.indexOf(`/`);S!==-1;S=s.indexOf(`/`,S+1)){let w=t.get(s.slice(0,S));if(!w)continue;let E=s.slice(S);for(let t of w){let s=`${t}${E}`;e(s)&&g(s)}}};for(let[e,t]of L)s(e,s=>{H.push({kind:`folder`,path:s,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:toPosix(relative(g,t.canonicalPath))})});for(let[e,t]of F)s(e,s=>{let S=toPosix(relative(g,t.canonicalPath));if(t.kind===`markdown`)H.push({kind:`document`,docName:s,docExt:getDocExtension(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S});else{let g=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${g}`,assetExt:g,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S})}})}H.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),successResponse(t,200,DocumentListSuccessSchema,{documents:H},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),Is=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}successResponse(t,200,BacklinksSuccessSchema,{docName:s,backlinks:ue.getBacklinks(s).map(e=>({source:e.source,anchor:e.anchor,title:jt(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),Ls=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let g={};for(let e of s.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(g[t]=ue.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:g},{handler:`backlink-counts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let g=en();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ue.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Mt(e.target,g),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),ec=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`docName`);if(g&&!isSafeDocName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let S=s.searchParams.get(`degrees`);if(S&&!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let w,E;if(S&&g){let e=Number.parseInt(S,10);if(!Number.isFinite(e)||e<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:w,links:E}=ue.getLinkGraphNeighborhood(g,e))}else ({nodes:w,links:E}=ue.getLinkGraph());let D=en();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=Lt(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Mt(e.docName,D),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:E},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),tc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}successResponse(t,200,OrphansSuccessSchema,{orphans:ue.getOrphans([...w().keys()],s).map(e=>({docName:e,title:jt(e)}))},{handler:`orphans`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),nc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),g=s?Number.parseInt(s,10):20,S=Number.isFinite(g)&&g>0?g:20,w=en();successResponse(t,200,HubsSuccessSchema,{hubs:ue.getHubs(S).map(e=>({docName:e.docName,title:Mt(e.docName,w),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),rc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(s.some(e=>e.length===0||!isSafeDocName(e))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let g=s.length?[...new Set(s.map(e=>zt(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ue.getDeadLinks(en(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:jt(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),ic=withValidation(AgentPatchRequestSchema,async(S,w,E)=>{try{let{find:S,replace:D,offset:O}=E,k=requireNonEmptyDocName(E.docName,w,`agent-patch`);if(k===null)return;let j=zt(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=Qi(E);if(findLooksLikeFrontmatter(S)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H}),te=reconcileDiskBeforeAgentWrite(t,j,g,e.resolveEmbed),ne=new Date().toISOString(),ae=!1,oe=!1,se=!1,ce;try{let t=iconFromClientName(H),s=AGENT_ICON_COLORS[t]??colorFromSeed(B??F);if(ge?.setPresence(F,{displayName:L,icon:t,color:s,currentDoc:j,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),F,B,H),Y.dc.document.transact(()=>{let{frontmatter:t,body:s}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),g=prependFrontmatter(t,s),w=O==null?g.indexOf(S):g.slice(O,O+S.length)===S?O:-1;if(w===-1){O==null?ae=!0:oe=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":j,findLength:S.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(w<t.length){se=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));ce=applyAgentMarkdownWrite(Y.dc.document,E,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0),Y.dc.document.getMap(`agent-flash`).set(F,{agentId:F,timestamp:Date.now(),type:`insert`,description:`Patched (${L}): ${S.slice(0,50)}`})},Y.origin),ce!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":j,position:`patch`,intendedBytes:ce.intendedBytes,actualBytes:ce.actualBytes,byteDelta:ce.byteDelta,"agent.id":F,"agent.client_name":H})),!ae&&!oe&&!se){let{stored:e}=eo(J);recordContributor(j,F,L,B,void 0,Ra({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),so(J),recordContentDivergenceGate(`agent-patch`,ce)}}finally{ge?.touchMode(F,`idle`)}if(oe){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(ae){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(se){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let ue=await Ut(j);if(ue?.kind===`failure`){Wt(w,ue.failure,`agent-patch`);return}if(ue?.kind===`divergence`){Xt(w,`agent-patch`);return}Ht(j,`agent-patch`),me?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),_e?.();let de=Bt(j),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=eo(J),ye=Y.dc.document.getText(`source`).toString();rn(j,ye);let Ce=await validateMermaidFences(ye,j),we=en();we.add(j);let Te=computeBrokenOutboundLinks(ye,j,we,tn),De=Zt(te),je=ce===void 0?void 0:toContentDivergenceWarning(ce),Me=[...je?[je]:[],...De?[De]:[],...Ce??[]];successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ne,subscriberCount:de,systemSubscriberCount:fe,...ve?{summary:ve}:{},...je?{warning:je}:De?{warning:De}:{},...Me.length>0?{warnings:Me}:{},brokenLinks:Te},{handler:`agent-patch`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-patch`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-patch`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[agent-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),ac=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=zt(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Qi(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(g,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:L}=S,B=S.scope===`session`||S.scope===`file`?`session`:`last`;if(!s.hasSession(w,L)){errorResponse(g,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let H=await s.getSession(w,L),q=!1;try{let t=iconFromClientName(k),s=AGENT_ICON_COLORS[t]??colorFromSeed(O??E);ge?.setPresence(E,{displayName:D,icon:t,color:s,currentDoc:w,mode:`writing`,ts:Date.now()}),q=applyAgentUndo(H,B,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:w}:void 0),q&&recordContributor(w,L,D,O,void 0,Ra({clientName:k,clientVersion:j,label:F}))}finally{ge?.touchMode(E,`idle`)}if(q){let e=await Ut(w);if(e?.kind===`failure`){Wt(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Xt(g,`agent-undo`);return}Ht(w,`agent-undo`)}me?.setFocus(L,{agentName:L,currentDoc:w,writeKind:`undo`,ts:Date.now()}),successResponse(g,200,AgentUndoSuccessSchema,{docName:w,scope:B,undone:q},{handler:`agent-undo`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(g,e,`agent-undo`);return}log$7.error({err:e},`[agent-undo] handler failed`),errorResponse(g,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),oc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(g===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(s,g),{handler:`agent-activity`})}catch(e){log$7.error({err:e},`[agent-activity] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),sc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=validateAgentId(g.searchParams.get(`agentId`)),w=g.searchParams.get(`docName`),E=g.searchParams.get(`stackIndex`);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!w||w.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let D=zt(w);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!E||Number.isNaN(Number(E))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let O=Number(E);if(!Number.isInteger(O)||O<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let k=s.getLiveSession(D,S);if(!k){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let j=k.um;if(O>=j.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${O} out of range (stack has ${j.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let F=j.undoStack[O];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(F,k.dc.document.getText(`source`),D),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$7.error({err:e},`[agent-burst-diff] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),cc=withValidation(EmptyRequestSchema,async(e,t)=>{try{await J?.(),successResponse(t,200,TestFlushGitSuccessSchema,{},{handler:`test-flush-git`})}catch(e){log$7.error({err:e},`[test-flush-git] flush failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:e})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),lc=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=zt(w.searchParams.get(`docName`)??`test-doc`),D;try{D=safeContentPath(E,g)}catch(e){log$7.error({err:e,docName:E},`[test-reset] safeContentPath rejected docName`),errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await s.closeAll(E),t.closeConnections(E);let O=`onStoreDocument-${E}`;t.debouncer.isDebounced(O)&&await t.debouncer.executeNow(O);let k=t.documents.get(E);if(k&&await(Me??t.unloadDocument.bind(t))(k),writeFileSync(D,``,`utf-8`),ue&&(ue.deleteDocument(E),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${E}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),w.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(g,`.okignore`),s=t.documents.get(CONFIG_DOC_NAME_OKIGNORE);if(s){let e=s.getText(`source`);e.length>0&&s.transact(()=>{e.delete(0,e.length)},CONFIG_VALIDATION_REVERT_ORIGIN)}existsSync(e)&&writeFileSync(e,``,`utf-8`),De&&await De.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}fe?.(`files`),successResponse(S,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),uc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ue.rebuildFromDisk(),await ue.ingestGlobalSkillBundles([resolve(cu,`.ok`,`skills`)]),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),fe?.(`backlinks`),fe?.(`graph`),successResponse(t,200,TestRescanBacklinksSuccessSchema,{},{handler:`test-rescan-backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),dc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!H){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await H(),fe?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),fc=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Qi(s),E=ee?.current;if(!E){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let D=/^[a-zA-Z0-9_-]+$/,O=[],k=!1;if(Array.isArray(s.writers))try{O=s.writers.map(e=>{let t=e.id??`unknown`;if(!D.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let j=oe?.()??`main`;if(O.length===0)if(e!==void 0)O=[{id:g,name:w?`${S} (${w})`:S,email:`${g}@openknowledge.local`}];else{let e=(await enumerateWipChains(E,j)).filter(e=>!e.isPark);O=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[SERVICE_WRITER],k=!0}let F=ce??`.`,L=normalizeSummary(typeof s.summary==`string`?s.summary:void 0),B=await saveVersion(E,F,O,j,L.kind===`value`?L.value:void 0,k?{includeUpstream:!1}:void 0);getLogger(`history`).info({checkpointRef:B.checkpointRef},`checkpoint`);try{await gcRenameLog(E,getOrLoadRenameLogIndex(E.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:B.checkpointRef},{handler:`save-version`})}catch(e){log$7.error({err:e},`[save-version] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),pc=withValidation(EmptyRequestSchema,async(e,t)=>{let s=ee?.current;if(!s){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`docName`)??``,w=g.searchParams.get(`folder`),E=g.searchParams.get(`branch`)??oe?.()??`main`;if(!S&&w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(E.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(w!==null&&!S){let e=Hl(w,t,`folder`,`history`);if(!e)return;let S=Number(g.searchParams.get(`limit`)??`50`),D=Math.min(200,Number.isFinite(S)?S:50),O=Number(g.searchParams.get(`offset`)??`0`),k=Math.max(0,Number.isFinite(O)?O:0),j=`folder\0${E}\0${e.folderRel}\0${D}\0${k}`,{promise:F,coalesced:L}=Xe.run(j,()=>getFolderTimeline(s,e.folderRel,ce??`.`,{branch:E,limit:D,offset:k}));L&&recordTimelineCoalesced(`folder`),successResponse(t,200,HistorySuccessSchema,{...await F},{handler:`history`});return}let D=ce??`.`,O=safeDocPath(S,D);if(`error`in O){errorResponse(t,400,`urn:ok:error:invalid-request`,O.error,{handler:`history`});return}let k=Number(g.searchParams.get(`limit`)??`50`),j=Number(g.searchParams.get(`offset`)??`0`),F=Math.min(200,Number.isFinite(k)?k:50),L=Number.isFinite(j)?j:0,B=g.searchParams.get(`type`)??void 0,H=g.searchParams.get(`author`)??void 0,q=g.searchParams.get(`excludeAuthor`)??void 0,J=g.searchParams.get(`includeAutoCheckpoints`)===`true`,Y=`doc\0${E}\0${S}\0${F}\0${L}\0${B??``}\0${H??``}\0${q??``}\0${J?`1`:`0`}`,te=Date.now();try{let{promise:e,coalesced:g}=Xe.run(Y,()=>getDocumentHistory(s,{docName:S,branch:E,limit:F,offset:L,type:B,author:H,excludeAuthor:q,includeAutoCheckpoints:J},D));g&&recordTimelineCoalesced(`doc`);let w=await e,O=Date.now()-te;getLogger(`timeline`).info({docName:S,entries:w.entries.length,durationMs:O},`query`),successResponse(t,200,HistorySuccessSchema,{...w},{handler:`history`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function mc(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let g=ee?.current;if(!g){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,w=ce??`.`,E=safeDocPath(S,w);if(`error`in E){errorResponse(t,400,`urn:ok:error:invalid-request`,E.error,{handler:`history-version`});return}let D=shadowGit(g),O=oe?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await resolveDocPathAtCommit(g,S,s,O,getOrLoadRenameLogIndex(g.gitDir),e=>{let t=safeDocPath(e,w);return`error`in t?`${e}.md`:t.path},createAncestorShaSetCache());if(e===null){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let E=await D.raw(`show`,`${s}:${e}`),[k=``,j=``]=(await D.raw(`log`,`-1`,`--format=%aI%x00%an`,s)).trim().split(`\0`);successResponse(t,200,HistoryVersionSuccessSchema,{sha:s,content:E,timestamp:k,author:j},{handler:`history-version`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let hc=withValidation(RollbackRequestSchema,async(s,g,S)=>{let w=extractActorIdentity(S,we);if(w.kind===`invalid-summary`){errorResponse(g,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let E=t.documents.get(S.docName);if(E&&isDocInConflict(E)){respondDocInConflict(g,new DocInConflictError({file:docNameToRelativePath(S.docName)}),`rollback`);return}let D=ee?.current;if(!D){errorResponse(g,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:O,commitSha:k}=S,j=ce??`.`,F=safeDocPath(O,j);if(`error`in F){errorResponse(g,400,`urn:ok:error:invalid-request`,F.error,{handler:`rollback`});return}let L=shadowGit(D),B=Date.now();try{let s=getOrLoadRenameLogIndex(D.gitDir),S=createAncestorShaSetCache(),E=await resolveDocPathAtCommit(D,O,k,oe?.()??`main`,s,e=>{let t=safeDocPath(e,j);return`error`in t?`${e}.md`:t.path},S);if(E===null){errorResponse(g,404,`urn:ok:error:doc-not-found`,`Commit ${k.slice(0,7)} does not contain document ${O} at any known historical path.`,{handler:`rollback`});return}let F=await L.raw(`show`,`${k}:${E}`),H=new Date().toISOString();await safetyCheckpoint(D,j,{action:`rollback`,context:{docName:O,targetSha:k}});let q=t.documents.get(O);if(!q){errorResponse(g,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let ee=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0,J;q.transact(()=>{replaceRawBody(q,F,ee),J=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),J!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:J.intendedBytes,actualBytes:J.actualBytes,byteDelta:J.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,J);let Y;switch(w.kind){case`agent`:{let e=k.slice(0,8),t=w.summary.kind===`value`,s=t?w.summary:normalizeSummary(`Restored to ${e}`),g=eo(s);Y=t||!g.response?g.response:to(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),so(s,!t);break}case`principal`:{let e=eo(w.summary);Y=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),so(w.summary,!1);break}case`anonymous`:log$7.debug({docName:O,commitSha:k.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(w.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:w.kind});let te=await Ut(O);if(te?.kind===`failure`){Wt(g,te.failure,`rollback`);return}if(te?.kind===`divergence`){Xt(g,`rollback`);return}Ht(O,`rollback`);let ne=Date.now()-B;getLogger(`rollback`).info({docName:O,from:k.slice(0,8),durationMs:ne},`rollback`),w.kind===`agent`&&me?.setFocus(w.writerId,{agentName:w.displayName,currentDoc:O,writeKind:`rollback-apply`,ts:Date.now()});let ae=J===void 0?void 0:toContentDivergenceWarning(J);successResponse(g,200,RollbackSuccessSchema,{restoredFrom:k,timestamp:H,...Y?{summary:Y}:{},...ae?{warning:ae,warnings:[ae]}:{}},{handler:`rollback`})}catch(e){errorResponse(g,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),gc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$7.error({err:e},`[metrics-reconciliation] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),_c=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$7.error({err:e},`[metrics-parse-health] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),vc=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$7.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=se?.(),g=getBootTimings();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s},...g===void 0?{}:{boot:g}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function yc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let s=we?.()??null;if(!s){errorResponse(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}successResponse(t,200,PrincipalSuccessSchema,s,{handler:`principal`})}async function bc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=ge?.getPresenceMap()??{},s=Date.now(),g={};for(let[t,S]of Object.entries(e))s-S.ts<2e4&&(g[t]=S);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:g},{handler:`metrics-agent-presence`})}catch(e){log$7.error({err:e},`[metrics-agent-presence] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function xc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let s=embedProbeRing.read();successResponse(t,200,EmbedDetectSuccessSchema,{entries:s,count:s.length,detection:deriveDetection(s[0])},{handler:`embed-detect`})}async function Sc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let s=resolve(g),S=s,w=!0;try{S=realpathSync(s)}catch(e){let g=e?.code;if(g===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:s}),w=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:s,err:e}),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:g??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:S,pathSeparator:sep,symlinkResolved:w},{handler:`workspace`})}let Cc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let S=assetContentTypeForPath(s),w=extname(s).slice(1).toLowerCase();if(!S||!ASSET_EXTENSIONS.has(w)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let E=realpathSync(g),D=resolve(E,s),O;try{O=realpathSync(D)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(O,E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let k;try{k=statSync(O)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!k.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let j=toContentRelativePath(E,O);if(j!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(De?.isPathIgnored(j)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let F=SANDBOXED_HTML_EXTENSIONS.has(w),L={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)||F?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`?L[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:F&&(L[`Content-Security-Policy`]=SANDBOXED_HTML_CSP),t.writeHead(200,L);try{await pipeline(createReadStream(O),t)}catch(e){log$7.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:s,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),wc=1048576,Tc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let S=realpathSync(g),w=resolve(S,s),E;try{E=realpathSync(w)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!isWithinContentDir(E,S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let D;try{D=statSync(E)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!D.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(toContentRelativePath(S,E)!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(D.size>wc){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${wc}-byte text-viewer cap.`,{handler:`asset-text`});return}let O=(await readFile$1(E)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(O)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),Ec=1440*60*1e3,Dc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ee?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),s=[],g=resolve(ee.current.gitDir,`rescue`);if(existsSync(g))try{let t=readdirSync(g).filter(e=>isSupportedDocFile(e));for(let S of t){let t=resolve(g,S),w=statSync(t);if(e-w.mtimeMs>864e5){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}s.push({docName:stripDocExtension(S),timestamp:w.mtime.toISOString(),size:w.size,source:`flat`})}}catch(e){log$7.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=oe?.()??`main`,t=await listRescueCheckpoints(ee.current,e);for(let e of t)s.push({...e,source:`timeline`})}catch(e){log$7.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}successResponse(t,200,RescueListSuccessSchema,s,{handler:`rescue-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),Oc=withValidation(CreatePageRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let S=s.path;if(!isSupportedDocFile(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(S.includes(`..`)||S.startsWith(`/`)||S.includes(`\0`)||S.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let w=resolve(g),E=resolve(w,S);if(!isWithinDir(E,w)){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let D=stripDocExtension(S);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`});return}if(S.split(`/`)[0]===`.ok`||isManagedArtifactDocName(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page under .ok/ — skills and templates are authored through their own validating flows.`});return}let k=typeof s.template==`string`?s.template.trim():``,j=``,F;if(k.length>0){if(!/^[A-Za-z0-9_-]+$/.test(k)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let s=S.includes(`/`)?S.slice(0,S.lastIndexOf(`/`)):``,g=resolveTemplatesAvailable(w,s),E=g.find(e=>e.name===k);if(!E){let e=g.length===0?`(none)`:g.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${k}" does not resolve for folder "${s||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let D=resolve(w,E.path),O;try{O=readFileSync(D,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${E.path}.`,{handler:`create-page`,cause:e});return}let L=instantiateDoc(O),B=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;j=applySubstitution(L,{date:todayIsoUtc(),user:B}),F=E.scope}mkdirSync(dirname(E),{recursive:!0});try{writeFileSync(E,j,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let L=stripDocExtension(S);switch(Ie?.delete(L),De&&De.incrementMdDir(dirname(L)),registerWrite(E,contentHash(j)),e.kind){case`agent`:case`principal`:recordContributor(L,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}O?.({kind:`create`,path:E,docName:L,content:j}),ue&&(ue.updateDocumentFromMarkdown(L,j),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${L}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),F!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:k,templateScope:F,docName:L})),successResponse(t,200,CreatePageSuccessSchema,{docName:L},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),kc=withValidation(CreateFolderRequestSchema,async(e,t,s)=>{try{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=s.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(De?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let S=resolveContentEntryPath(g,`folder`,e);if(existsSync(S)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(S,{recursive:!0}),it(e),fe?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),Ac=withValidation(DuplicatePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:w}=S,E=S.path,D=w===`file`?stripDocExtension(E):E;if(!isValidRelativeContentPath(E)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||w===`file`&&(isSystemDoc(D)||isConfigDoc(D))||w===`folder`&&isReservedSyntheticFolderPath(E)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}w===`file`&&probeAndRegisterSourceFileExtension(g,E);let k=resolveContentEntryPath(g,w,E);if(!existsSync(k)){if(w===`file`){let e=resolveContentEntryPath(g,`folder`,E);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}}errorResponse(s,404,`urn:ok:error:doc-not-found`,`${w} does not exist.`,{handler:`duplicate-path`});return}let j=statSync(k);if(w===`file`&&!j.isFile()||w===`folder`&&!j.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}let F=w===`file`?[docNameForFileOperationPath(g,E)]:Gi(resolveContentEntryPath(g,`folder`,E)),L=ve?.(),B=new Set(L?L.getConflicts().map(e=>e.file):[]);for(let e of F){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=B.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let H,q=[];if(w===`file`){let e=extname(k);if(H=nextAvailableDuplicateDocName(g,D).docName,isSystemDoc(H)||isConfigDoc(H)||De?.isExcluded(`${H}${e}`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let t=resolveDuplicateDocPath(g,H,e),S=readFileSync(k,`utf-8`),w=dirname(t),E=existsSync(w);try{tracedMkdirSync(w,{recursive:!0}),tracedWriteFileSync(t,S,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!E)try{tracedRmdirSync(w)}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTEMPTY`&&console.warn(`[duplicate-path] failed to clean duplicate parent directory:`,{destinationDir:w,err:e})}throw e}let j=!1;try{registerDocExtension(H,e),Ie?.delete(H),De&&(De.incrementMdDir(dirname(H)),j=!0),registerWrite(t,contentHash(S)),O?.({kind:`create`,path:t,docName:H,content:S}),ue?.updateDocumentFromMarkdown(H,S),q=[H]}catch(e){try{tracedRmSync(t,{force:!0})}catch(e){console.warn(`[duplicate-path] failed to clean partial file duplicate:`,{destinationPath:t,err:e})}throw forgetDocExtension(H),De&&j&&De.decrementMdDir(dirname(H)),O?.({kind:`delete`,path:t,docName:H}),e}}else{if(H=nextAvailableDuplicateFolderPath(g,E).folderPath,De?.isDirExcluded(H)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=resolveContentEntryPath(g,`folder`,H);try{tracedCpSync(k,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of collectFolderPaths(g,H))it(e);let e=collectMarkdownCopies(g,H);q=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(stripDocExtension(t.docName),e),Ie?.delete(t.docName),De&&De.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),O?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),ue?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{tracedRmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[duplicate-path] failed to clean partial folder duplicate:`,{destinationPath:e,err:t})}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of q)recordContributor(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}ue&&q.length>0&&(ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),successResponse(s,200,DuplicatePathSuccessSchema,{kind:w,path:H,duplicatedDocNames:q},{handler:`duplicate-path`})}catch(e){if(e instanceof DuplicateNameExhaustedError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=classifyDuplicatePathFilesystemProblem(e);if(t){errorResponse(s,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),jc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s||s.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let g=Et(s);if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(g)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:s,headings:extractHeadings(readFileSync(g,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),Mc=withValidation(RenamePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:w,fromPath:E,toPath:D}=S;if(!isValidRelativeContentPath(E)||!isValidRelativeContentPath(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(w===`file`&&(isSystemDoc(E)||isSystemDoc(D)||isConfigDoc(E)||isConfigDoc(D))){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||D===`.ok`||D.startsWith(`.ok/`)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(E===D){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let O=w===`asset`&&isSupportedDocFile(E)&&isSupportedDocFile(D)?`file`:w;if(O===`asset`){let t;try{t=isSupportedDocFile(E)&&!isSupportedDocFile(D)?await Yi(E,D):await Ji(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=zr(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&St();let g;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let s=`Renamed asset ${E} → ${D}`;g=_s(e,s,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:s})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$7.debug({kind:`asset`,fromPath:E,toPath:D,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(renameAttributionCounter().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...g?{summary:g}:{}},{handler:`rename-path`});return}O===`file`&&probeAndRegisterSourceFileExtension(g,E);let k=O===`file`?[docNameForFileOperationPath(g,E)]:Gi(resolveContentEntryPath(g,`folder`,E)),j=ve?.(),F=new Set(j?j.getConflicts().map(e=>e.file):[]);for(let e of k){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=F.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`rename-path`);return}}if(De){let e=isSupportedDocFile(E)?extname(E):getDocExtension(E);if(O===`file`?De.isExcluded(isSupportedDocFile(D)?D:`${D}${e}`):De.isDirExcluded(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Destination ${O===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let L=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,B;try{B=await Xi(E,D,O,L?{actor:L}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,Mr(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(B.renamed.length===0&&B.renamedAssets.length===0){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}B.renamedAssets.length>0&&St();let H,q=B.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(q.length>0&&(H=_s(e,`Renamed ${E} → ${D}`,q.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$7.debug({kind:w,fromPath:E,toPath:D,affectedDocs:B.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${O}`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:B.renamed,renamedAssets:B.renamedAssets,rewrittenDocs:B.rewrittenDocs,...H?{summary:H}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:g,error:S}=zr(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Nc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Qi(S);let{kind:e,path:w}=S;if(!isValidRelativeContentPath(w)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let E=e===`asset`?Qr(w):{path:w,ambiguous:!1};if(E.ambiguous){errorResponse(s,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let D=E.path,k=e===`asset`&&isSupportedDocFile(D)?`file`:e;if(k===`file`&&probeAndRegisterSourceFileExtension(g,D),k===`asset`&&isReservedProjectStatePath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let j=k===`asset`?resolveContentEntryPath(g,`folder`,D):resolveContentEntryPath(g,k,D);if(!existsSync(j)){errorResponse(s,404,`urn:ok:error:doc-not-found`,`${k} does not exist.`,{handler:`delete-path`});return}let F=statSync(j);if(k===`file`&&!F.isFile()||k===`asset`&&!F.isFile()||k===`folder`&&!F.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${k}.`,{handler:`delete-path`});return}let L=k===`asset`?[]:k===`file`?[docNameForFileOperationPath(g,D)]:Gi(resolveContentEntryPath(g,`folder`,D)),B=ve?.(),H=new Set(B?B.getConflicts().map(e=>e.file):[]);for(let e of L){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=H.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`delete-path`);return}}if(await Br(L,`deleted-upstream`),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));k===`file`||k===`asset`?tracedUnlinkSync(j):(tracedRmSync(j,{recursive:!0,force:!1}),at(D)),St();for(let e of L)O?.({kind:`delete`,path:resolve(g,docNameToRelativePath(e)),docName:e});fe?.(`files`),successResponse(s,200,DeletePathSuccessSchema,{deletedDocNames:L},{handler:`delete-path`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Pc=withValidation(TrashCleanupRequestSchema,async(e,t,s)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":s.kind,"ok.cleanup.path":normalizeFsPath(s.path),"ok.cleanup.path.role":classifyFsPath(s.path)}},async()=>{try{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:S}=s;if(!isValidRelativeContentPath(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let E=e===`asset`&&isSupportedDocFile(S)?`file`:e,D=stripDocExtension(S);E===`file`&&probeAndRegisterSourceFileExtension(g,S);let k=E===`folder`&&isReservedSyntheticFolderPath(S),j=E===`asset`&&isReservedProjectStatePath(S);if(E===`file`&&(isSystemDoc(D)||isConfigDoc(D))||k||j){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${S}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(E===`asset`){St(),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let F=w(),L=E===`file`?F.has(D)?[D]:[]:listAffectedDocNames(F,E,S);if(St(),L.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Br(L,`deleted-upstream`),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of L)O?.({kind:`delete`,path:resolve(g,docNameToRelativePath(e)),docName:e});E===`folder`&&at(S),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:L},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Fc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=w(),s=[];for(let[t,S]of e){let e=getDocExtension(t),w,E;if(S.title!==void 0)w=S.title,E=S.icon;else{w=t;try{let s=readFileSync(resolve(g,`${t}${e}`),`utf-8`);w=extractPageTitle(s,t),E=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}}s.push({docName:t,title:w,docExt:e,size:S.size,modified:S.modified,icon:E})}s.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:s},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),Ic=withValidation(EmptyRequestSchema,async(e,s)=>{try{let g=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!g){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(g)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(g)||isConfigDoc(g)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${g}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(s,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:w(),docName:g}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function Lc(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let s;try{s=await readUploadBody(e,Ce??g)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:S,tempPath:w,sha:D,byteLength:O,parentDocName:k,placement:j}=s,F=()=>{if(existsSync(w))try{unlinkSync(w)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:k,placement:j||void 0},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B,placement:H}=L.value,{agentId:q,agentName:ee}=Qi(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(O===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(g),Y;try{Y=H===`parent-dir`?`./`:E?.()??`./`}catch(e){F(),log$7.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!isValidAttachmentFolderPath(Y)){F(),errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let te=resolveUploadDestDir(B,normalizeAttachmentFolderPath(Y),J);if(!isWithinContentDir(te,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(te,J)}catch(e){if(F(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$7.error({err:e,destDir:te},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(te,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){F();let s=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(s),s,uploadTitleFor(s),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(te),s;try{s=realpathSync(J)}catch{s=J}if(!isWithinContentDir(e,s)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ne=readTempFileHead(w,4100),ae=await fileTypeFromBuffer(ne),oe=ae?.mime,se=ae?.ext;if(!oe){let e=ne.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(oe=`image/svg+xml`,se=`svg`)}{let s=await findDuplicateAsset(te,D,O);if(s){F();let S=toPosix(relative(g,resolve(te,s)));log$7.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!0,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!0},{handler:`upload-asset`});return}}let ce;if(!S||S===`upload`||GENERIC_PASTE_NAMES.test(S)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=S?extname(S).slice(1):``,s=se??t??``;ce=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else ce=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,te,ce),S=toPosix(relative(g,resolve(te,s)));log$7.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!1,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!1},{handler:`upload-asset`})}catch(s){let g=s instanceof UploadWriteError?s.reason:`urn:ok:error:storage-error`;log$7.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,filename:ce,size:O,reason:g,httpStatus:uploadStatusFor(g),err:s},`[upload] write failed`),errorResponse(t,uploadStatusFor(g),g,uploadTitleFor(g),{handler:`upload-asset`,cause:s})}}let Rc=`/api/local-op/clone`,zc=`/api/local-op/ok-init`,Bc=600*1e3,Vc=45e3,Hc=`local-op-clone`,Uc=withValidation(LocalOpCloneRequestSchema,Wc,{handler:Hc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Hc})});async function Wc(e,t,s){let{url:g,dir:S,branch:w}=s;if(!isAllowedGitUrl(g)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:Hc,cause:Error(`url=${g}`)});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:Hc,cause:Error(`dir=${S}`)});return}if(!Ge.tryAcquire(Rc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Hc,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,Hc),D=null,O=runCloneSubprocess({cliArgs:ye,url:g,dir:S,branch:w,timeoutMs:Bc,onEvent:e=>{if(e.type===`complete`){D=e.dir;return}if(e.type===`error`){e.message&&log$7.warn({stderr:redactShareSubprocessStderr(e.message),url:g,dir:S},`[local-op/clone] clone failed`);let t=classifyCloneError(e.message??``);E(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(redactShareSubprocessStderr(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await O.done,D&&!t.writableEnded&&!t.destroyed){let e=await Gc(D);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:D})}\n`):E(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?E(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$7.error({err:e,handler:Hc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ge.release(Rc)}})(),t.on(`close`,()=>{O.cancel()})}async function Gc(e,t){let s=resolve(expandTilde(e)),g=getLocalDir(s),S=readUiLock(g);if(S&&S.port>0)return{port:S.port};let[w,...E]=ye,D=e=>{let s=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...E,e,...s]},O=async e=>{let t=spawn(w,D(e),{cwd:s,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),S=[];t.stderr?.on(`data`,t=>{S.push(t),log$7.warn({cwd:s,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/clone] child stderr`)});let E=null,O=null,k=null;t.on(`exit`,(e,t)=>{E=e??-1,O=t??null}),t.on(`error`,t=>{k=t.message,E=-1,log$7.error({cwd:s,cliCmd:e,err:t.message},`[local-op/clone] failed to spawn child`)}),t.unref();let j=Date.now()+45e3;for(;Date.now()<j;){await setTimeout$1(500);let t=readUiLock(g);if(t&&t.port>0)return{port:t.port};if(E!==null){let t=Buffer.concat(S).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${k?`spawn failed: ${k}`:O?`killed by ${O}`:`code ${E}`})${t?` — ${t}`:``}`,exited:!0}}}let F=Buffer.concat(S).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${F?` — ${F}`:``}`,exited:!1}},k=readServerLock(g),j=k&&k.port>0?`ui`:`start`,F=await O(j);if(j===`start`&&`error`in F&&F.exited){let e=readServerLock(g);if(e&&e.port>0){let e=await O(`ui`);return`port`in e?e:{error:`${F.error}; connect fallback failed: ${e.error}`}}}return`port`in F?F:{error:F.error}}let Kc=`local-op-ok-init`,qc=withValidation(LocalOpOkInitRequestSchema,async(e,t,s)=>{let{projectPath:g}=s;if(!isAbsolute(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:Kc,cause:Error(`projectPath=${g}`)});return}let S;try{S=realpathSync(g)}catch(e){successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:Kc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Kc,cause:Error(`projectPath=${g}`)});return}let w=resolveGitDirDetailed(S).kind;if(w!==`directory`&&w!==`linked`){console.warn(`[ok-init] action=init project=${basename(S)} result=not-a-git-worktree kind=${w}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${w}).`},{handler:Kc});return}if(isProjectRoot(S)){console.warn(`[ok-init] action=init project=${basename(S)} result=already-initialized`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Kc});return}if(!Ge.tryAcquire(zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Kc,extraHeaders:{"Retry-After":`2`}});return}try{await withParentLock(async()=>{initContent(S)}),console.warn(`[ok-init] action=init project=${basename(S)} result=success`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Kc})}catch(e){let s=e instanceof Error?e.message:String(e);console.warn(`[ok-init] action=init project=${basename(S)} result=failed reason=${s}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`init-failed`,message:s},{handler:Kc})}finally{Ge.release(zc)}},{handler:Kc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Kc})}),Jc=`/api/local-op/auth/login`,Yc=`/api/local-op/auth/status`,Xc=`/api/local-op/auth/repos`,Zc=`/api/local-op/auth/signout`,Qc=null,$c=`local-op-auth-login`,dl=withValidation(LocalOpAuthHostRequestSchema,ml,{handler:$c,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:$c})});async function ml(e,t,s){let g=s.host??`github.com`;if(!Ge.tryAcquire(Jc)){let e=Qc;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-login-slot-no-controller`,channel:`auth`,transport:`http`})),errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:$c,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),Qc=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,$c),w=runDeviceFlowSubprocess({cliArgs:ye,host:g,timeoutMs:Bc,onEvent:e=>{if(e.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(resumeSyncOnAuthEvent(e,ve),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});Qc=w;let E=()=>{w.cancel(),Qc===w&&(Qc=null,Ge.release(Jc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}Qc===w&&(Qc=null,Ge.release(Jc))})}let hl=`local-op-auth-status`,gl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire(Yc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:hl,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`status`,`--json`,`--host`,g],w=(await new Promise((t,s)=>{let g=spawn(e,S,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,g.kill(`SIGTERM`)},3e4),D=[];g.stdout.on(`data`,e=>D.push(e)),g.on(`close`,()=>{if(clearTimeout(E),w){s(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(D).toString(`utf-8`))}),g.on(`error`,e=>{clearTimeout(E),s(e)})})).split(`
|
|
1945
|
-
`).map(e=>e.trim()).filter(Boolean),E=null;for(let e=w.length-1;e>=0;e--)try{E=JSON.parse(w[e]);break}catch{}E===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:
|
|
1946
|
-
`);k=s.pop()??``;for(let e of s){if(!e.trim())continue;let s=null;try{s=JSON.parse(e)}catch{}if(s&&s.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof s.message==`string`?s.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),j.stderr.on(`data`,e=>{log$7.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),j.on(`close`,e=>{clearTimeout(F),O||(O=!0,e!==0&&!t.writableEnded&&S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Ge.release(Xc))}),j.on(`error`,e=>{clearTimeout(F),O||(O=!0,t.writableEnded||(S(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),Ge.release(Xc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Ge.release(Xc))})}let xl=`local-op-auth-signout`,Cl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire(Zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:xl,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`signout`,`--host`,g];await new Promise((t,s)=>{let g=spawn(e,S,{stdio:`ignore`,env:{...process.env}}),w=setTimeout(()=>{g.kill(`SIGTERM`)},3e4);g.on(`close`,()=>{clearTimeout(w),t()}),g.on(`error`,e=>{clearTimeout(w),s(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:xl})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:xl,cause:e})}finally{Ge.release(Zc)}},{handler:xl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:xl})}),Tl=`/api/local-op/auth/set-identity`,El=`local-op-auth-set-identity`,Dl=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!Ce){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:El});return}if(!Ge.tryAcquire(Tl)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:El,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(Ce,g,S),ve?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:El})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:El,cause:e})}finally{Ge.release(Tl)}},{handler:El,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:El})});async function Ol(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let kl=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let S=s.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:S},{handler:`sync-trigger`}),g.trigger(S)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function jl(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Ml=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:S,strategy:w,content:E}=s;try{await g.resolveConflict(S,w,E),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Pl(e,s){if(!checkLocalOpSecurity(e,s,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(s,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!Ce){errorResponse(s,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`file`);if(!S){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=stripDocExtension(S),E=t.documents.get(w)?.getMap(`lifecycle`).get(`status`)===`conflict`,D=ve?.(),O=D?D.getConflicts().some(e=>e.file===S):!1;if(!E&&!O){errorResponse(s,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:S}});return}let k=g.searchParams.get(`source`),j=esm_default({baseDir:Ce,timeout:{block:15e3}});async function F(e){try{return{present:!0,content:await j.raw([`show`,`:${e}:${S}`])}}catch(t){let s=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(s))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:S,detail:s,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,g,w]=await Promise.all([F(1),F(2),F(3)]),E=e.present?e.content:``,D=w.present?w.content:``,O=g.present&&w.present?`both-modified`:!g.present&&w.present?`delete-modify`:g.present&&!w.present?`modify-delete`:`both-modified`,j=g.present?g.content:``,L=null;if(k===`ytext`){let e=stripDocExtension(S),s=t.documents.get(e);if(s){let t=s.getMap(`lifecycle`).get(`status`);if(L=typeof t==`string`&&t.length>0?t:null,O!==`delete-modify`){let t=Re?Re(e):null;t!==null&&!ytextHasConflictMarkers(t)?j=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(s,200,SyncConflictContentSuccessSchema,{file:S,base:E,ours:j,theirs:D,kind:O,lifecycleStatus:L},{handler:`sync-conflict-content`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Fl(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let s=new URL(e.url??`/`,`http://localhost`),S=s.searchParams.get(`rootDir`)??void 0,w=s.searchParams.get(`packId`),E=coercePackId(w);if(w!==null&&w!==``&&E===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${w}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:g,rootDir:S,packId:E})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Il=withValidation(SeedApplyRequestSchema,async(e,t,s)=>{let S=s.plan;if(!S||typeof S!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let w=S,E=s.packId,D=coercePackId(E);if(typeof E==`string`&&E.length>0&&D===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${E}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(w,{projectDir:g,packId:D})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function Ll(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let Rl=withValidation(InstallSkillRequestSchema,async(e,t,s)=>{if(s.out!==void 0&&!isSafeLocalPath(s.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...s.noOpen===void 0?{}:{noOpen:s.noOpen},...s.out===void 0?{}:{out:s.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function zl(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Tt.probeAll)}catch(e){t.headersSent||(log$7.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}let Bl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:de.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Vl(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let g;try{g=decodeURIComponent(s)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=de.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:jt(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:g,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function Hl(e,t,s=`path`,S=`folder-config`){let w=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(w.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${s}: must be project-root-relative.`,{handler:S}),null;let E=resolve(g),D=w===``?E:resolve(E,w);return D!==E&&!D.startsWith(`${E}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:S}),null):{folderRel:w,resolvedContentDir:E}}let Ul=/^[A-Za-z0-9_-]+$/;function Wl(e,t,s=`template`){return!e||!Ul.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:s}),!1):!0}function Gl(e,t,s){let g=t===``?[]:t.split(`/`);for(let t=g.length;t>=0;t--){let S=t===0?``:g.slice(0,t).join(`/`),w=S===``?e:resolve(e,S);if(w!==e&&!w.startsWith(`${e}${sep}`))continue;let E=resolve(w,`.ok`,`templates`,`${s}.md`);if(existsSync(E))return{abs:E,folder:S,scope:t===g.length?`local`:`inherited`}}return null}function Kl(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[s,g]of Object.entries(e))g!==void 0&&(t[s]=g);return t}async function ql(e,t){if(e.method===`GET`)return Jl(e,t);if(e.method===`PUT`)return Yl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Jl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=Hl(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!s)return;let g=await enrichDirectory(s.folderRel,{projectDir:s.resolvedContentDir}),S=resolve(resolve(s.resolvedContentDir,s.folderRel,`.ok`),`frontmatter.yml`),w=null;if(existsSync(S))try{let e=(0,import_dist$1.parse)(await readFile$1(S,`utf-8`));w=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${S}: ${t}`),w=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:g,frontmatter_local:w},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),Yl=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let g=Hl(s.path,t,`path`,`folder-config-put`);if(!g)return;let S=[];if(s.frontmatter!==void 0){let w=applyFolderFrontmatterPatch({anchorDir:g.resolvedContentDir,folderRel:g.folderRel,patch:s.frontmatter});if(!w.ok){let e=w.error.code===`WRITE_ERROR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:w.error.message,{handler:`folder-config-put`,detail:w.error.code,cause:Error(w.error.message)});return}S.push({path:w.path,action:w.action}),w.action!==`noop`&&(Cs(e,xs(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Ts(`folder-config-put`))}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:S},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function Xl(e,s,g,S){if(!s)return!1;let w=e===``?`.ok/templates/${s}`:`${e.replace(/\/$/,``)}/.ok/templates/${s}`,E=t.documents.get(w);return E&&isDocInConflict(E)?(respondDocInConflict(S,new DocInConflictError({file:`${w}.md`}),g),!0):!1}function Zl(e,s,g){let S=t.documents.get(e);return S&&isDocInConflict(S)?(respondDocInConflict(g,new DocInConflictError({file:`${e}.md`}),s),!0):!1}let Ql=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=resolveProjectTemplates(resolve(g));successResponse(t,200,TemplatesListSuccessSchema,{templates:e.templates.map(e=>{let{scope:t,...s}=e;return s}),truncated:e.truncated},{handler:`templates-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list templates.`,{handler:`templates-list`,cause:e})}},{handler:`templates-list`,method:`GET`,skipBodyParse:!0});async function $l(e,t){if(e.method===`GET`)return tu(e,t);if(e.method===`PUT`)return nu(e,t);if(e.method===`POST`)return iu(e,t);if(e.method===`DELETE`)return ru(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let eu=e=>{let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{frontmatter:g,body:s}},tu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Wl(g,t,`template-get`))return;let S=Hl(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=Gl(E,w,g);if(!D){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${g}" not found for folder "${w||`.`}". Walked leaf → root.`});return}let{abs:O,folder:k,scope:j}=D,F=parseTemplateFile(await readFile$1(O,`utf-8`)),L=F.identity,B=F.starterContent;successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:L,body:B}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),nu=withValidation(TemplatePutRequestSchema,async(e,t,g)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let S=g.name;if(!Wl(S,t,`template-put`))return;let w=Hl(g.folder,t,`folder`,`template-put`);if(!w||Xl(w.folderRel,S,`template-put`,t))return;let E=composeTemplateContent({name:S,body:typeof g.body==`string`?g.body:``,frontmatter:Kl(g.frontmatter)});if(!E.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}let D=resolve(w.resolvedContentDir,w.folderRel,`.ok`,`templates`,`${S}.md`),O=!existsSync(D),k=relative(w.resolvedContentDir,D).split(/[\\/]/).filter(Boolean).join(`/`),j=uu(w.folderRel,S),{agentId:F,agentName:L,colorSeed:B,clientName:H}=Qi(g),q=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H});q.dc.document.transact(()=>{composeAndWriteRawBody(q.dc.document,E.content,`agent`)},q.origin);let ee=await Ut(j);if(ee?.kind===`failure`){Wt(t,ee.failure,`template-put`);return}if(ee?.kind===`divergence`){Xt(t,`template-put`);return}Cs(e,xs(`template`,w.folderRel,S),`${O?`template-create`:`template-edit`}: ${k}`),await Ts(`template-put`),successResponse(t,200,TemplatePutSuccessSchema,{path:k,created:O,warnings:E.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),ru=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Wl(g,t,`template-delete`))return;let S=Hl(s.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!S)return;let w=s.searchParams,E=extractActorIdentity({agentId:w.get(`agentId`)??void 0,agentName:w.get(`agentName`)??void 0,colorSeed:w.get(`colorSeed`)??void 0,clientName:w.get(`clientName`)??void 0,clientVersion:w.get(`clientVersion`)??void 0,label:w.get(`label`)??void 0,summary:w.get(`summary`)??void 0},we);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Xl(S.folderRel,g,`template-delete`,t))return;await Br([uu(S.folderRel,g)],`deleted-upstream`);let D=applyTemplateDelete({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}D.existed&&(Cs(E,xs(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Ts(`template-delete`)),successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),iu=withValidation(TemplateMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Wl(s.fromName,t,`template-move`)||!Wl(s.toName,t,`template-move`))return;let g=Hl(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=Hl(s.toFolder,t,`folder`,`template-move`);if(!S||Xl(g.folderRel,s.fromName,`template-move`,t))return;await Br([uu(g.folderRel,s.fromName)],`renamed`);let w=await applyTemplateMove({projectDir:g.resolvedContentDir,fromFolder:g.folderRel,fromName:s.fromName,toFolder:S.folderRel,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!w.ok){if(w.error.code===`TEMPLATE_NOT_FOUND`){let e=Gl(g.resolvedContentDir,g.folderRel,s.fromName);if(e?.scope===`inherited`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${s.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${g.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:w.error.message});return}if(w.error.code===`TEMPLATE_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,w.error.message,{handler:`template-move`,detail:w.error.code});return}let e=w.error.code===`WRITE_ERROR`||w.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:w.error.code,cause:Error(w.error.message)});return}let E=null;if(s.body!==void 0||s.frontmatter!==void 0){let e;if(typeof s.body==`string`)e=s.body;else try{e=instantiateDoc(readFileSync(resolve(S.resolvedContentDir,w.toPath),`utf-8`))}catch{e=null}if(e===null)E={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=applyTemplateWrite({projectDir:S.resolvedContentDir,folder:S.folderRel,name:s.toName,body:e,frontmatter:Kl(s.frontmatter)});t.ok||(E=t.error)}}if(Cs(e,xs(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Ts(`template-move`),fe?.(`files`),E){let e=E.code===`WRITE_ERROR`||E.code===`READ_FAILED`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${w.toPath}", but updating its content failed.`,{handler:`template-move`,detail:E.code,cause:Error(E.message)});return}successResponse(t,200,TemplateMoveSuccessSchema,{from:w.fromPath,to:w.toPath,committed:w.committed},{handler:`template-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),au=500;function ou(e,t,s){return!e||e.length>64||!SKILL_NAME_REGEX.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:s}),!1):!0}function su(e,t,s){let g=SkillScopeSchema.safeParse(e??`project`);return g.success?g.data:(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:s}),null)}let cu=Te??homedir();function lu(e){return resolve(e===`global`?cu:g,`.ok`,`skills`)}function uu(e,t){return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function du(e){return e===`navigation`||e===`relevance`?e:void 0}function fu(e,t){return relative(t===`global`?cu:g,e).split(/[\\/]/).filter(Boolean).join(`/`)}function pu(e){return e===`global`?cu:Ce}async function mu(e,t){let s=await removeSkillInstall(e,t);return reverseProjectSkill(t,e,PROJECT_SKILL_EDITOR_IDS),s!==null}function hu(e,t){let s=[];if(!existsSync(e))return{skills:s,truncated:!1};let g;try{g=readdirSync(e,{withFileTypes:!0})}catch(g){return getLogger(`skills`).warn({err:g,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:s,truncated:!1}}let S=!1;for(let w of g.sort((e,t)=>e.name.localeCompare(t.name))){if(!w.isDirectory()||!SKILL_NAME_REGEX.test(w.name))continue;if(s.length>=500){S=!0;break}let g=resolve(e,w.name,`SKILL.md`);if(!existsSync(g))continue;let E,D;try{let{frontmatter:e}=eu(readFileSync(g,`utf-8`));typeof e.description==`string`&&(E=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(D=e.version)}catch{}s.push({name:w.name,...E===void 0?{}:{description:E},scope:t,path:fu(g,t),absolutePath:g,...D===void 0?{}:{installedVersion:D}})}return{skills:s,truncated:S}}let gu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=hu(lu(`project`),`project`),s=hu(lu(`global`),`global`),g=Ce?readInstalledSkills(Ce).skills:{},S=readInstalledSkills(cu).skills,w=(e,t)=>e.skills.map(e=>{let s=t[e.name]?.hosts??[],g=computePackUpdateStatus(e.name,e.installedVersion);return{...e,installed:s.length>0,hosts:s,...g}});successResponse(t,200,SkillsListSuccessSchema,{skills:[...w(e,g),...w(s,S)],truncated:e.truncated||s.truncated},{handler:`skills-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list skills.`,{handler:`skills-list`,cause:e})}},{handler:`skills-list`,method:`GET`,skipBodyParse:!0});async function _u(e,t){if(e.method===`GET`)return Cu(e,t);if(e.method===`PUT`)return wu(e,t);if(e.method===`POST`)return Eu(e,t);if(e.method===`DELETE`)return Tu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let vu=object$1({managed:boolean().nullable(),importable:number().int().nonnegative()}),yu=()=>({managed:Ce?readSkillManagement(Ce)?.manageEditorSkills??null:null,importable:Ce?countImportableEditorSkills({projectDir:Ce,skillsRoot:lu(`project`)}):0}),bu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}successResponse(t,200,vu,yu(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),xu=withValidation(object$1({manageEditorSkills:boolean()}),async(e,t,s)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await writeSkillManagement(Ce,{manageEditorSkills:s.manageEditorSkills,surface:`ui`}),s.manageEditorSkills){let e=await reconcileSkillInstalls({projectDir:Ce,skillsRoot:lu(`project`)});e.adopted.length+e.collided.length>0&&fe?.(`files`)}successResponse(t,200,vu,yu(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`});async function Su(e,t){if(e.method===`GET`)return bu(e,t);if(e.method===`PUT`)return xu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skills-management`,extraHeaders:{Allow:`GET, PUT`}})}let Cu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!ou(g,t,`skill-get`))return;let S=su(s.searchParams.get(`scope`),t,`skill-get`);if(S===null)return;let w=lu(S),E=resolve(w,g,`SKILL.md`);if(!existsSync(E)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${g}" not found in ${S} scope.`});return}let{frontmatter:D,body:O}=eu(await readFile$1(E,`utf-8`));successResponse(t,200,SkillGetSuccessSchema,{skill:{name:g,scope:S,path:fu(E,S),frontmatter:{name:typeof D.name==`string`?D.name:g,description:typeof D.description==`string`?D.description:``},body:O,files:readSkillBundledFiles(resolve(w,g))}},{handler:`skill-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),wu=withValidation(SkillPutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!ou(g.name,t,`skill-put`))return;let S=composeSkillContent({name:g.name,body:typeof g.body==`string`?g.body:``,frontmatter:{name:g.frontmatter.name,description:g.frontmatter.description}});if(!S.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:S.error.code,cause:Error(S.error.message)});return}let w=lu(g.scope),E=resolve(w,g.name,`SKILL.md`),D=!existsSync(E),O=relative(w,E).split(/[\\/]/).filter(Boolean).join(`/`),k=skillLiveDocName(g.scope,g.name);if(Zl(k,`skill-put`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Qi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-put`);return}if(q?.kind===`divergence`){Xt(t,`skill-put`);return}g.scope===`project`&&(Cs(e,xs(`skill`,``,g.name),`${D?`skill-create`:`skill-edit`}: ${O}`),await Ts(`skill-put`)),fe?.(`files`),successResponse(t,200,SkillPutSuccessSchema,{path:O,created:D,warnings:S.warnings},{handler:`skill-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),Tu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!ou(g,t,`skill-delete`))return;let S=su(s.searchParams.get(`scope`),t,`skill-delete`);if(S===null)return;let w=lu(S),E=s.searchParams,D=extractActorIdentity({agentId:E.get(`agentId`)??void 0,agentName:E.get(`agentName`)??void 0,colorSeed:E.get(`colorSeed`)??void 0,clientName:E.get(`clientName`)??void 0,clientVersion:E.get(`clientVersion`)??void 0,label:E.get(`label`)??void 0,summary:E.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Br([skillLiveDocName(S,g)],`deleted-upstream`);let O=applySkillDelete({skillsRoot:w,name:g});if(!O.ok){let e=O.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:O.error.code,cause:Error(O.error.message)});return}O.existed&&(S===`project`&&(Cs(D,xs(`skill`,``,g),`skill-delete: ${O.path}`),await Ts(`skill-delete`)),fe?.(`files`));let k=pu(S);k&&await mu(k,g),successResponse(t,200,SkillDeleteSuccessSchema,{existed:O.existed,path:O.path},{handler:`skill-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),Eu=withValidation(SkillMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!ou(s.fromName,t,`skill-move`)||!ou(s.toName,t,`skill-move`))return;let g=lu(s.scope);await Br([skillLiveDocName(s.scope,s.fromName)],`renamed`);let S=await applySkillMove({skillsRoot:g,fromName:s.fromName,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!S.ok){if(S.error.code===`SKILL_NOT_FOUND`){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:S.error.message});return}if(S.error.code===`SKILL_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,S.error.message,{handler:`skill-move`,detail:S.error.code});return}let e=S.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:S.error.code,cause:Error(S.error.message)});return}let w=null,E=resolve(g,s.toName,`SKILL.md`),D=``,O=``;try{let e=eu(readFileSync(E,`utf-8`));D=e.body,typeof e.frontmatter.description==`string`&&(O=e.frontmatter.description)}catch{}let k=typeof s.body==`string`?s.body:D,j=s.frontmatter===void 0?O:s.frontmatter.description,F=applySkillWrite({skillsRoot:g,name:s.toName,body:k,frontmatter:{name:s.toName,description:j}});if(F.ok||(w=F.error),s.scope===`project`&&!w)try{ju(g,s.fromName,s.toName)}catch(e){getLogger(`skill-move`).warn({err:e,fromName:s.fromName,toName:s.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let L=fu(resolve(g,s.fromName),s.scope),B=fu(resolve(g,s.toName),s.scope);s.scope===`project`&&(Cs(e,xs(`skill`,``,s.toName),`skill-rename: ${L} -> ${B}`,[{from:L,to:B}]),await Ts(`skill-move`));let H=pu(s.scope);if(H){let e=await removeSkillInstall(H,s.fromName);if(e){let t=resolvedHosts(e.hosts);reverseProjectSkill(s.fromName,H,t);let S=projectSkill(resolve(g,s.toName),s.toName,H,t);await recordSkillInstall(H,s.toName,{...e,hosts:S})}}if(fe?.(`files`),w){let e=w.code===`WRITE_ERROR`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${s.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:w.code,cause:Error(w.message)});return}successResponse(t,200,SkillMoveSuccessSchema,{from:L,to:B,committed:S.committed},{handler:`skill-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`});function Du(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function Ou(e,t,s){return e===`project`&&t===`reference`&&s.toLowerCase().endsWith(`.md`)}function ku(e,t){let s=t.replace(/\.md$/i,``);return`${projectSkillContentDocName(e).replace(/\/SKILL$/,``)}/${s}`}function Au(e,t){let s=resolve(e,t,`references`);if(!existsSync(s))return[];let g=[],S=(e,t)=>{for(let s of readdirSync(e,{withFileTypes:!0})){let w=t?`${t}/${s.name}`:s.name;s.isDirectory()?S(resolve(e,s.name),w):s.isFile()&&s.name.toLowerCase().endsWith(`.md`)&&g.push(`references/${w}`)}};return S(s,``),g}function ju(e,t,s){if(!ue)return;let g=(e,t,s)=>{let g;try{g=readFileSync(s,`utf-8`)}catch{ue.deleteDocument(e),de?.deleteDocument(e);return}ue.renameDocument(e,t,g),de?.renameDocument(e,t,g)};g(projectSkillContentDocName(t),projectSkillContentDocName(s),resolve(e,s,`SKILL.md`));for(let S of Au(e,s))g(ku(t,S),ku(s,S),resolve(e,s,S));fe?.(`backlinks`),fe?.(`graph`)}let Mu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!ou(g,t,`skill-file-get`))return;let S=su(s.searchParams.get(`scope`),t,`skill-file-get`);if(S===null)return;let w=s.searchParams.get(`path`)??``,E=Du(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let D=resolve(lu(S),g),O=resolve(D,w);if(O!==D&&!O.startsWith(`${D}${sep}`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let k=O,j=w;if(!existsSync(k)){let e=w.match(/^(.*)\.(?:md|mdx)$/),s=e?SUPPORTED_DOC_EXTENSIONS.map(t=>`${e[1]}${t}`).find(e=>e!==w&&existsSync(resolve(D,e))):void 0;if(s===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${w} not found in skill "${g}" (${S}).`});return}j=s,k=resolve(D,s)}let F=await readFile$1(k);if(F.includes(0)){errorResponse(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}successResponse(t,200,SkillFileGetSuccessSchema,{path:j.replace(/\\/g,`/`),kind:E,text:F.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),Nu=withValidation(SkillFilePutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!ou(g.name,t,`skill-file-put`))return;let S=Du(g.path);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(g.content,`utf-8`)>262144){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let w=lu(g.scope);if(!existsSync(resolve(w,g.name,`SKILL.md`))){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${g.name}" before adding bundle files.`});return}let E=g.path.replace(/\\/g,`/`),D=Ou(g.scope,S,E),O;if(D){let e=ku(g.name,E);if(Zl(e,`skill-file-put`,t))return;if(O=!existsSync(resolve(w,g.name,E)),O&&countBundleFiles(resolve(w,g.name))>=50){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${g.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:S,agentName:D,colorSeed:k,clientName:j}=Qi(g),F=await s.getSession(e,S,{displayName:D,colorSeed:k,clientName:j});F.dc.document.transact(()=>{composeAndWriteRawBody(F.dc.document,g.content,`agent`)},F.origin);let L=await Ut(e);if(L?.kind===`failure`){Wt(t,L.failure,`skill-file-put`);return}if(L?.kind===`divergence`){Xt(t,`skill-file-put`);return}}else{let e=applySkillBundleFileWrite({skillsRoot:w,name:g.name,relPath:E,content:g.content});if(!e.ok){let s=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;errorResponse(t,s,s===500?`urn:ok:error:internal-server-error`:s===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,s===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}O=e.created}g.scope===`project`&&(Cs(e,xs(`skill`,``,g.name),`${O?`skill-file-create`:`skill-file-edit`}: .ok/skills/${g.name}/${E}`),await Ts(`skill-file-put`)),fe?.(`files`),successResponse(t,200,SkillFilePutSuccessSchema,{path:E,created:O,kind:S,content:D},{handler:`skill-file-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),Pu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams,g=s.get(`name`)??``;if(!ou(g,t,`skill-file-delete`))return;let S=su(s.get(`scope`),t,`skill-file-delete`);if(S===null)return;let w=(s.get(`path`)??``).replace(/\\/g,`/`),E=Du(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let D=extractActorIdentity({agentId:s.get(`agentId`)??void 0,agentName:s.get(`agentName`)??void 0,colorSeed:s.get(`colorSeed`)??void 0,clientName:s.get(`clientName`)??void 0,clientVersion:s.get(`clientVersion`)??void 0,label:s.get(`label`)??void 0,summary:s.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let O=lu(S);Ou(S,E,w)&&await Br([ku(g,w)],`deleted-upstream`);let k=applySkillBundleFileDelete({skillsRoot:O,name:g,relPath:w});if(!k.ok){let e=k.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:k.error.code,cause:Error(k.error.message)});return}k.existed&&S===`project`&&(Cs(D,xs(`skill`,``,g),`skill-file-delete: .ok/skills/${g}/${w}`),await Ts(`skill-file-delete`)),k.existed&&fe?.(`files`),successResponse(t,200,SkillFileDeleteSuccessSchema,{path:w,existed:k.existed,kind:E},{handler:`skill-file-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0});async function Fu(e,t){if(e.method===`GET`)return Mu(e,t);if(e.method===`PUT`)return Nu(e,t);if(e.method===`DELETE`)return Pu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-file`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Iu=withValidation(SkillInstallRequestSchema,async(e,t,s)=>{try{let e=lu(s.scope);if(!ou(s.name,t,`skill-install`))return;if(s.scope===`project`&&!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let g=pu(s.scope),S=resolve(e,s.name);if(!existsSync(S)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${s.name}" not found in ${s.scope} scope — create it with write({ skill }) first.`});return}let w=validateSkillForInstall(S,s.name);if(!w.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${s.name}" cannot be installed: ${w.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let E=s.scope===`global`?s.targets?PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)):[...PROJECT_SKILL_EDITOR_IDS]:s.targets===void 0?resolveSkillTargets(g,readSkillTargets(g)??void 0):PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)),D=[],O=[];E.length===0&&s.targets===void 0&&(D.push(s.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),O.push(`no-targets`)),w.hasScripts&&(D.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),O.push(`scripts-present`));let k=resolvedHosts(readInstalledSkills(g).skills[s.name]?.hosts??[]).filter(e=>!E.includes(e));k.length>0&&reverseProjectSkill(s.name,g,k);let j=projectSkill(S,s.name,g,E);j.length===0?await removeSkillInstall(g,s.name):await recordSkillInstall(g,s.name,{hosts:j,scope:s.scope,scripts:w.hasScripts,installedAt:new Date().toISOString()}),fe?.(`files`),successResponse(t,200,SkillInstallSuccessSchema,{name:s.name,hosts:j,scripts:w.hasScripts,warnings:D,warningCodes:O},{handler:`skill-install`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Lu=withValidation(SkillUninstallRequestSchema,async(e,t,s)=>{try{if(!ou(s.name,t,`skill-uninstall`))return;let e=pu(s.scope);if(!e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let g=await mu(e,s.name);fe?.(`files`),successResponse(t,200,SkillUninstallSuccessSchema,{name:s.name,uninstalled:g},{handler:`skill-uninstall`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`});async function Ru(e,t){if(e.method===`GET`)return zu(e,t);if(e.method===`PUT`)return Bu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-targets`,extraHeaders:{Allow:`GET, PUT`}})}let zu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=Ce?readSkillTargets(Ce):null;successResponse(t,200,SkillTargetsGetSuccessSchema,{targets:resolveSkillTargets(Ce??``,e??void 0),configured:e!==null},{handler:`skill-targets-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),Bu=withValidation(SkillTargetsPutRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let e=s.targets,g=new Set(e),S=resolveSkillTargets(Ce,readSkillTargets(Ce)??void 0),w=lu(`project`);await writeSkillTargets(Ce,e);let{reprojected:E,bundleHosts:D}=await reprojectAllManagedSkills({projectDir:Ce,skillsRoot:w,targets:e});fe?.(`files`),successResponse(t,200,SkillTargetsPutSuccessSchema,{targets:e,reprojected:E,bundleHosts:D,removedFrom:S.filter(e=>!g.has(e))},{handler:`skill-targets-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`}),Vu=withValidation(SkillRestoreRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!ou(s.name,t,`skill-restore`))return;if(s.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let S=ee?.current;if(!S){errorResponse(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let w=await restoreSkillVersion({shadow:S,contentDir:g,contentRoot:ce??`.`,name:s.name,version:s.version});if(!w.ok){let[e,s]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[w.code];errorResponse(t,e,s,w.error,{handler:`skill-restore`,detail:w.code});return}let E=[],D=validateSkillForInstall(resolve(g,`.ok`,`skills`,s.name),s.name);D.ok||E.push(`Restored, but the skill no longer validates: ${D.errors.join(` `)}`),E.push("Run `install` to push the restored version to your editors."),Cs(e,xs(`skill`,``,s.name),`skill-restore: ${s.name} @ ${s.version.slice(0,8)}`),await Ts(`skill-restore`),fe?.(`files`),successResponse(t,200,SkillRestoreSuccessSchema,{name:s.name,version:s.version,restoredFiles:w.restoredFiles,warnings:E},{handler:`skill-restore`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Hu=withValidation(SkillUpdateRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!ou(g.name,t,`skill-update`))return;if(!isPackSkillName(g.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(g.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let S=readBundledPackSkill(g.name);if(S===null||S.version===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let w=resolve(lu(`project`),g.name,`SKILL.md`);if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let E;try{E=readSkillVersion(readFileSync(w,`utf-8`))}catch{}let D,O=ee?.current;if(O)try{let e=oe?.()??`main`;D=(await saveVersion(O,ce??`.`,[SERVICE_WRITER],e,`Before updating ${g.name} (${E??`unversioned`} → ${S.version})`)).checkpointRef}catch(e){getLogger(`skills`).warn({err:e,skill:g.name},`pre-update checkpoint failed — proceeding with overwrite`)}let k=skillLiveDocName(`project`,g.name);if(Zl(k,`skill-update`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Qi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-update`);return}if(q?.kind===`divergence`){Xt(t,`skill-update`);return}Cs(e,xs(`skill`,``,g.name),`skill-pack-update: ${g.name} (${E??`unversioned`} → ${S.version})`),await Ts(`skill-update`),fe?.(`files`),successResponse(t,200,SkillUpdateSuccessSchema,{name:g.name,version:S.version,...E===void 0?{}:{previousVersion:E},...D===void 0?{}:{checkpointRef:D}},{handler:`skill-update`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function Uu(e){let t=new Map;for(let s of e){let e=s.path.split(`/`).filter(Boolean);e.pop();for(let g=1;g<=e.length;g++){let S=e.slice(0,g).join(`/`);t.set(S,Math.max(t.get(S)??0,s.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function Wu(e,t){let s=t.trim().toLowerCase();if(!s||!e)return;let g=e.toLowerCase().indexOf(s);if(g<0)return;let S=Math.max(0,g-80),w=Math.min(e.length,g+s.length+120),E=S>0?`…`:``,D=w<e.length?`…`:``;return`${E}${e.slice(S,w).replace(/\s+/g,` `).trim()}${D}`.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,`�`)}function Gu(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Ku(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let s=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return s.length>0?s:void 0}function qu(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Ju(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function Yu(e,t,s,g){let S=g.documents.filter(e=>!isHiddenDocName(e.path)),w=S.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!Be?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:w,capable:!1};Be.embedCorpus(S);let E,D=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await Be.queryScores(e,S);if(D=performance.now()-t,s&&s.size>0){let e=Ve?.();E=e===void 0?{scores:s}:{scores:s,similarityFloor:e}}}let O=Be.getStatus();return{input:E,status:{capable:O.capable,applied:!1,coverage:{embedded:O.embeddedCount,total:w}},queryEmbedMs:D,pageTotal:w,capable:O.capable}}function Xu(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`?Wu(e.document.content,t):void 0}}async function Zu(e){let t=performance.now();if(sd())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:s,truncated:g}=await cd(),S=await Yu(e.query,e.intent,e.semanticParam,s),w=searchWorkspaceCorpus(s,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:S.input}).map(t=>Xu(t,e.query)),E;if(S.status){let t=w.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),s=t>0;E={...S.status,applied:s},recordSemanticQuery({outcome:S.capable?s?`applied`:S.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:S.capable,embedded:S.status.coverage.embedded,total:S.pageTotal,queryEmbedMs:S.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:w,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...E?{semantic:E}:{},...g?{truncated:!0}:{}}}function Qu(){let e=lu(`project`);if(!existsSync(e))return[];let t;try{t=readdirSync(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let g of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!g.isDirectory()||!SKILL_NAME_REGEX.test(g.name))continue;let t=resolve(e,g.name,`SKILL.md`);try{let e=statSync(t);s.push({name:g.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return s}function $u(){let e=[];for(let t of Qu()){let s=t.name,g=``;try{let{frontmatter:e,body:S}=eu(readFileSync(t.absolutePath,`utf-8`));typeof e.name==`string`&&e.name&&(s=e.name),g=`${typeof e.description==`string`?e.description:``}\n\n${S}`.trim()}catch{}e.push(createWorkspaceSearchDocument({kind:`page`,path:skillLiveDocName(`project`,t.name),title:s,content:g,modifiedTs:t.mtimeMs}))}return e}function ed(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let td=new Map;async function nd(){let e=[],t=[],s=new Set;for(let[g,S]of D()){if(isSystemDoc(g)||isConfigDoc(g)||g.startsWith(`.ok/skills/`))continue;if(S.kind===`file`){t.push(createWorkspaceSearchDocument({kind:`file`,path:g,modifiedTs:Date.parse(S.modified),aliases:S.aliases}));continue}s.add(g);let w=ed(S),E=td.get(g);if(E&&E.key===w){e.push(E.doc);continue}let D=``,O=g,k=!1;try{D=await readFile$1(S.canonicalPath,`utf-8`)}catch(e){k=!0,console.warn(`[search] Failed to read ${g}:`,e)}if(!k)try{O=extractPageTitle(D,g)}catch(e){console.warn(`[search] Failed to extract title for ${g}:`,e)}let j=createWorkspaceSearchDocument({kind:`page`,path:g,title:O,content:D,modifiedTs:Date.parse(S.modified),aliases:S.aliases});k||td.set(g,{key:w,doc:j}),e.push(j)}for(let e of td.keys())s.has(e)||td.delete(e);let g=getSearchMaxEntries(),S=t,w=!1;return t.length>g&&(w=!0,S=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,g),getLogger(`search`).warn({dropped:t.length-S.length,retained:S.length,limit:g},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),searchCorpusTruncatedCounter().add(1)),{documents:[...e,...$u(),...S,...Uu([...e,...S])],truncated:w}}function rd(){return Qu().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function ad(){return k?`gen:${k()}|skills${rd()}`:`${[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${ed(t)}`).join(``)}|skills${rd()}`}let od=Pe===void 0;Pe?.then(()=>{od=!0},e=>{od=!0,log$7.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function sd(){return!od}async function cd(){let e=`${g}${Ce??``}`,t=ad(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return{corpus:s.corpus,truncated:s.truncated??!1};if(s?.fingerprint===t&&s.pending)return s.pending;let S=nd().then(({documents:e,truncated:t})=>({corpus:createWorkspaceSearchCorpus(e),truncated:t}));workspaceSearchCaches.set(e,{fingerprint:t,pending:S});try{let s=await S;return workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:s.corpus,truncated:s.truncated}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function ld(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{cd().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}ld();async function ud(e,t){if(e.method===`GET`)return dd(e,t);if(e.method===`POST`)return fd(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let dd=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=Gu(s.searchParams.get(`intent`)),E=du(s.searchParams.get(`ranking`)),D=Ku(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),O=qu(s.searchParams.get(`semantic`)),k=Ju(s.searchParams.get(`source`)),j=g===null?void 0:Number(g);if(S.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{successResponse(t,200,SearchSuccessSchema,await Zu({query:S,intent:w,ranking:E,scopes:D,limit:j,semanticParam:O,source:k}),{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),fd=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=Gu(s.intent),w=du(s.ranking),E=Ku(s.scopes??s.scope),D=typeof s.limit==`number`?s.limit:void 0,O=qu(s.semantic),k=Ju(s.source);if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{successResponse(t,200,SearchSuccessSchema,await Zu({query:g,intent:S,ranking:w,scopes:E,limit:D,semanticParam:O,source:k}),{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),pd=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function md(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform,isSchemeRegistered:Tt.probeWithCache})}catch(e){t.headersSent||(log$7.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function hd(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$7.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let gd=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!Ce){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=s.kind===`doc`?s.docPath:s.folderPath;if(!isValidSharePath(e,s.kind)){emitShareConstructUrlLog(`invalid-path`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let S=readGitHeadBranch(Ce);if(S===null){if(readOriginGitHubRepo(Ce).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=readOriginGitHubRepo(Ce);if(w.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(w.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(Ce,S)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:S},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let E=toGitRelativePath(Ce,g);if(E===null)throw Error(`content dir is not contained within the project dir`);let D=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;E!==``&&D&&getLogger(`share`).warn({action:`construct-url`,kind:s.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let O;if(s.kind===`doc`)O=buildGitHubBlobUrl(w.owner,w.repo,S,s.docPath);else{let e=s.folderPath===``?E:s.folderPath;O=buildGitHubTreeUrl(w.owner,w.repo,S,e)}let k=`${SHARE_BASE_URL}${encodeShareUrl(O)}`,j=await computeShareFreshness(Ce,S,E===``?e:e===``?E:`${E}/${e}`,s.kind);emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind,freshness:j}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:k,sharedUrl:O,branch:S,freshness:j},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}),_d=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`branch`),S=s.searchParams.get(`path`),w=s.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!isValidBranchName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoPath(S,w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(Ce,g,S,w),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),vd=withValidation(ShareTargetStatusRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}if(!isValidBranchInfoPath(s.path,s.kind)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}let e=toGitRelativePath(Ce,g);if(e===null)throw Error(`content dir is not contained within the project dir`);let S=e===``?s.path:s.path===``?e:`${e}/${s.path}`;successResponse(t,200,ShareTargetStatusResponseSchema,await computeShareTargetStatus(Ce,s.branch,S,s.kind),{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG,cause:e})}},{handler:SHARE_TARGET_STATUS_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}),yd=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(Ce,s.branch,{fastForward:s.fastForward===!0})),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function bd(e){let[t,...s]=ye,g=[...s,...e];return await new Promise((e,s)=>{let S=spawn(t,g,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),w=!1,E=setTimeout(()=>{w=!0,S.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),D=[],O=[];S.stdout.on(`data`,e=>D.push(e)),S.stderr.on(`data`,e=>O.push(e)),S.on(`close`,t=>{if(clearTimeout(E),w){s(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let g=Buffer.concat(D).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(O).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:g,code:t})}),S.on(`error`,e=>{clearTimeout(E),s(e)})})}let xd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await bd([`share`,`owners`,`--json`]),s=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,s.ok?`ok`:s.error,s.ok?{count:s.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,s,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),Sd=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`owner`)??``,S=s.searchParams.get(`name`)??``;if(!isValidShareOwnerName(g)||!isValidShareRepoName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!Ge.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await bd([`share`,`name-check`,`--owner`,g,`--name`,S,`--json`]),s=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,s.ok?`ok`:s.error,s.ok?{available:s.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,s,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),Cd=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!Ce){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(s.owner)||!isValidShareRepoName(s.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!Ge.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,s.owner,`--name`,s.name,`--visibility`,s.visibility,`--project-dir`,Ce,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await bd(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&ve?.()?.refreshRemote().catch(()=>{}),successResponse(t,200,SharePublishResponseSchema,S,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),wd=withValidation(ClientLogsRequestSchema,async(e,t,s)=>{try{let e=getLogger(`renderer`);for(let t of s.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}successResponse(t,200,ClientLogsSuccessSchema,{accepted:s.entries.length},{handler:`client-logs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`client-logs`})}),Td=Ce?getLocalDir(Ce):null;async function Ed(e,t){if(e.method===`DELETE`){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-config`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-config`});return}Td&&clearArmedPaneTarget(Td),t.setHeader(`Cache-Control`,`no-store`),t.statusCode=204,t.end();return}if(e.method===`GET`||e.method===`HEAD`){try{let s=e.headers.host,g={collabUrl:s?`ws://${s}/collab`:null,previewUrl:null,port:Td?readServerLock(Td)?.port??0:0,paneTarget:Td?readArmedPaneTarget(Td):null,singleFile:We};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}successResponse(t,200,ApiConfigSuccessSchema,g,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD, DELETE`}})}let Dd=`local-op-embeddings-set-key`,Od=`local-op-embeddings-clear-key`,kd=`/api/local-op/embeddings`,Ad=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Ge.tryAcquire(kd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Dd,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(Ue).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:Dd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Dd,cause:e})}finally{Ge.release(kd)}},{handler:Dd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Dd})}),jd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(kd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Od,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(Ue),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:Od,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Od,cause:e})}finally{Ge.release(kd)}},{handler:Od,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Od})}),Md=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(Be){let t=Be.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(Ue).get(),D=process.env.OK_EMBEDDINGS_API_KEY??null,O=E?`file`:D?`env`:null,k=O!==null,j=E??D,F=j&&j.length>=8?j.slice(-4):null,L=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(L+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:k,keySource:O,keyHint:F,ready:s,capable:g,embedded:S,total:L},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Nd={"/api/config":Ed,"/api/asset":Cc,"/api/asset-text":Tc,"/api/document":Ns,"/api/documents":Ps,"/api/backlinks":Is,"/api/backlink-counts":Ls,"/api/forward-links":Rs,"/api/link-graph":ec,"/api/dead-links":rc,"/api/orphans":tc,"/api/hubs":nc,"/api/tags":Bl,"/api/pages":Fc,"/api/folder-config":ql,"/api/template":$l,"/api/templates":Ql,"/api/skill":_u,"/api/skill-file":Fu,"/api/skills":gu,"/api/skills/management":Su,"/api/skill/install":Iu,"/api/skill/uninstall":Lu,"/api/skill/restore":Vu,"/api/skill/update":Hu,"/api/skill-targets":Ru,"/api/search":ud,"/api/semantic-status":Md,"/api/suggest-links":Ic,"/api/page-headings":jc,"/api/create-page":Oc,"/api/create-folder":kc,"/api/duplicate-path":Ac,"/api/rename-path":Mc,"/api/delete-path":Nc,"/api/trash/cleanup":Pc,"/api/upload":Lc,"/api/agent-write":Ds,"/api/agent-write-md":Os,"/api/frontmatter-patch":ks,"/api/agent-patch":ic,"/api/agent-undo":ac,"/api/agent-activity":oc,"/api/agent-burst-diff":sc,"/api/save-version":fc,"/api/history":pc,"/api/rollback":hc,"/api/metrics/reconciliation":gc,"/api/metrics/parse-health":_c,"/api/metrics/agent-presence":bc,"/api/__embed-detect":xc,"/api/server-info":vc,"/api/share/construct-url":gd,"/api/share/target-status":vd,"/api/git/branch-info":_d,"/api/git/checkout":yd,"/api/share/publish/owners":xd,"/api/share/publish/name-check":Sd,"/api/share/publish":Cd,"/api/principal":yc,"/api/rescue":Dc,"/api/workspace":Sc,"/api/sync/status":Ol,"/api/sync/trigger":kl,"/api/sync/conflicts":jl,"/api/sync/conflict-content":Pl,"/api/sync/resolve-conflict":Ml,"/api/local-op/clone":Uc,"/api/local-op/ok-init":qc,"/api/local-op/auth/login":dl,"/api/local-op/auth/status":gl,"/api/local-op/auth/repos":vl,"/api/local-op/auth/signout":Cl,"/api/local-op/auth/set-identity":Dl,"/api/local-op/embeddings/set-key":Ad,"/api/local-op/embeddings/clear-key":jd,"/api/installed-agents":zl,"/api/spawn-cursor":hd,"/api/handoff":md,"/api/install-skill":Rl,"/api/skill/install-state":pd,"/api/seed/plan":Fl,"/api/seed/apply":Il,"/api/seed/packs":Ll,"/api/client-logs":wd};q&&(Nd[`/api/test-reset`]=lc,Nd[`/api/test-flush-git`]=cc,Nd[`/api/test-rescan-backlinks`]=uc,Nd[`/api/test-rescan-files`]=dc);let Pd=new Set(`/api/upload./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),Fd=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let s=e.url?.split(`?`)[0];if(!s)return;let g=t=>{let s=e.headers[t];if(s!==void 0)return Array.isArray(s)?s.join(`, `):s};if(recordEmbedProbe({ts:Date.now(),url:s,method:e.method??``,ua:g(`user-agent`),origin:g(`origin`),referer:g(`referer`),host:g(`host`),remote:e.socket?.remoteAddress,secChUa:g(`sec-ch-ua`),secChUaMobile:g(`sec-ch-ua-mobile`),secChUaPlatform:g(`sec-ch-ua-platform`),secFetchSite:g(`sec-fetch-site`),secFetchDest:g(`sec-fetch-dest`),secFetchMode:g(`sec-fetch-mode`),secFetchUser:g(`sec-fetch-user`)}),s.startsWith(`/api/`)){let s=e.headers.origin;if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${CLIENT_VERSION_HEADER.protocol}, ${CLIENT_VERSION_HEADER.runtime}, ${CLIENT_VERSION_HEADER.kind}`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Pd.has(s)||Fd.some(e=>s.startsWith(e))){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(We&&s.startsWith(`/api/`)){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:Nd[s]||(E=`/api/*`);let D=getTracer(),O=Date.now();await context.with(S,()=>D.startActiveSpan(`HTTP ${w} ${E}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_URL_PATH]:s,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async g=>{try{let S=Nd[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await mc(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await Vl(e,t,g))}E||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${w} ${s}`});let D=t.statusCode;g.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,D),D>=500&&g.setStatus({code:SpanStatusCode.ERROR,message:`status ${D}`})}catch(e){throw g.recordException(e),g.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E,cause:e}),e}finally{g.end();let e=(Date.now()-O)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedSingleDirBasenameIndex(e){let t;try{t=readdirSync(e.contentDir,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,e.contentDir);return}for(let s of t)s.isFile()&&isSupportedAssetFile(s.name,ASSET_EXTENSIONS)&&e.basenameIndex.add(s.name)}async function seedBasenameIndex(e){let t=e.contentDir,s=new Set;async function g(S){let w;try{w=await readdir(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=toPosix(relative(t,w));if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=await lstat(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=await realpath(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=await stat$1(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?await g(S):E.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),await g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}await g(t)}var AutoStartDisabledError=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const log$6=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$6.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$6.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$6.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,s,g=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:S}=await import(`./git-handle-DG8d2xCi-C_CAAChL.mjs`),w=S(this.projectDir,{credentialArgs:g});switch(t){case`mine`:await w.git.raw([`checkout`,`--ours`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`theirs`:await w.git.raw([`checkout`,`--theirs`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`content`:{if(s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),g=resolve(t,e);if(!isWithinDir(g,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(g,s,`utf-8`),await w.git.raw([`add`,`--`,e]);break}case`delete`:await w.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await w.git.raw([`commit`,`--no-edit`]),log$6.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let e=await listNames(w.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:s});g=e.length>0}catch(e){log$6.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}g||this.addConflict({file:e,detectedAt:s}),log$6.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let S=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${g?`unmerged files re-added`:`original file re-added`} — ${S}`,{cause:t})}}};const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,s=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,g=0,S=null,w=null,E=!1,D=!1;function O(){S!==null&&(t.clearTimeout(S),S=null),w!==null&&(t.clearTimeout(w),w=null)}function k(){O(),!(D||E)&&g===0&&(s>0&&s<e.thresholdMs&&(w=t.setTimeout(()=>{w=null,g===0&&!E&&e.log?.warn({msUntilShutdown:s,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-s)),S=t.setTimeout(()=>{if(S=null,!(D||E)&&g===0){E=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let j=(e,t)=>{e.url?.startsWith(`/collab`)&&(g++,O(),t.once(`close`,()=>{g--,g<0&&(g=0),g===0&&k()}))};return e.httpServer.on(`upgrade`,j),k(),{detach:()=>{D||(D=!0,e.httpServer.off(`upgrade`,j),O())}}}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function readRawSinkBlock(e){if(!existsSync(e))return{};let t;try{t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!isObject(t))return{};let s=t.telemetry;if(!isObject(s))return{};let g=s.localSink;return isObject(g)?g:{}}function readBoolean(e){return typeof e==`boolean`?e:void 0}function readPositiveNumber(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function readStringArray(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function readMaxBytes(e){if(isObject(e))return readPositiveNumber(e.maxBytes)}function resolveLocalSinkConfig(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=readRawSinkBlock(resolveConfigPath(`project`,e.projectDir)),s=readRawSinkBlock(resolveConfigPath(`project-local`,e.projectDir));if((readBoolean(s.enabled)??readBoolean(t.enabled)??!0)===!1)return null;let g=readMaxBytes(s.spans)??readMaxBytes(t.spans)??52428800,S=readMaxBytes(s.logs)??readMaxBytes(t.logs)??26214400,w=readStringArray(s.attributeDenylist)??readStringArray(t.attributeDenylist)??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:g,attributeDenylist:w},logs:{projectDir:e.projectDir,maxBytes:S}}}const MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let s=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return s?s.slice(0,128):t}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let s=t.validateToolInput;if(typeof s!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,g){if(!e.inputSchema||!isZodSchema(e.inputSchema))return s.call(this,e,t,g);let S=await e.inputSchema.safeParseAsync(t);if(S.success)return S.data;let w=prettifyError(S.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${g}:\n${w}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const SPAWN_TIMEOUT_MS=2e3,LOCK_SCAN_MAX_DEPTH=3,LOCK_SCAN_MAX_ENTRIES=2e3,OK_LOCK_DIR_ARG_PREFIX=`--ok-lock-dir-b64=`,OK_PROJECT_PATH_ARG_PREFIX=`--ok-project-path=`,OK_PROCESS_PGREP_QUERY=`cli\\.mjs|open-knowledge|Open ?Knowledge(\\.app| Helper)|--ok-lock-dir-b64=|--ok-project-path=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`,OK_PROCESS_PATTERNS=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function isOkProcess(e){return OK_PROCESS_PATTERNS.some(t=>t.test(e))}function extractMarkedLockDir(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(OK_LOCK_DIR_ARG_PREFIX));if(t==null)return null;let s=t.slice(18);if(!s)return null;try{let e=Buffer.from(s,`base64url`).toString(`utf8`);return isAbsolute(e)?e:null}catch{return null}}function extractProjectPathArg(e){let t=e.indexOf(OK_PROJECT_PATH_ARG_PREFIX);if(t===-1)return null;let s=t+18,g=e.slice(s),S=g.search(/\s--/),w=(S===-1?g:g.slice(0,S)).trim();return w&&isAbsolute(w)?w:null}function parsePgrepOutput(e){let t=[];for(let s of e.split(`
|
|
1944
|
+
`:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),ce=!0}se=!0},te.origin)})}finally{ge?.touchMode(O,`idle`)}if(oe){let e;switch(oe.kind){case`invalid_value`:e={[oe.key]:oe.reason};break;case`reserved_key`:e={[oe.key]:`'${oe.key}' is reserved`};break;case`unknown_key`:e={[oe.key]:`'${oe.key}' is not a recognized key`};break;case`duplicate_target`:e={[oe.key]:`'${oe.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${oe.expected.join(`, `)}; got: ${oe.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${oe.bytes} > ${oe.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${oe.reason}`};break;case`invalid_path`:e={[oe.path.map(String).join(`.`)||`__path__`]:oe.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(oe)})`}}errorResponse(w,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(se&&ue.length>0){if(recordContributor(D,O,k,j,void 0,Ra({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),so(ee),ce){let e=await Ut(D);if(e?.kind===`failure`){Wt(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Xt(w,`frontmatter-patch`);return}}Ht(D,`frontmatter-patch`)}me?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),_e?.();let de=Bt(D),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=Zt(ne);rn(D,te.dc.document.getText(`source`).toString());let ye=en();ye.add(D);let Ce=computeBrokenOutboundLinks(te.dc.document.getText(`source`).toString(),D,ye,tn);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:de,systemSubscriberCount:fe,appliedKeys:ue,...J?{summary:J}:{},...ve?{warning:ve,warnings:[ve]}:{},brokenLinks:Ce},{handler:`frontmatter-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[frontmatter-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Ms(e){let t=e.getMap(`lifecycle`),s=t.get(`status`);if(typeof s!=`string`||s.length===0)return null;let g=t.get(`reason`);return{status:s,reason:typeof g==`string`?g:``}}let Ns=withValidation(EmptyRequestSchema,async(e,s)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(S)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let w=zt(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`document-read`});return}let E=t.documents.get(w);if(E){successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:E.getText(`source`).toString(),lifecycle:Ms(E)},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(g,`file`,w))){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Document not found: ${w}.`,{handler:`document-read`});return}let D=await t.openDirectConnection(w);try{let e=D.document;if(!e){errorResponse(s,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}successResponse(s,200,DocumentReadSuccessSchema,{docName:w,content:e.getText(`source`).toString(),lifecycle:Ms(e)},{handler:`document-read`})}finally{await D.disconnect()}}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),Ps=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$7.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=s.searchParams.get(`dir`),E=s.searchParams.get(`showAll`)===`true`,O=s.searchParams.get(`depth`)===`1`?1:1/0;if(S)try{safeSubdir(g,S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(E&&De&&showAllWantsNdjson(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let s=createStreamingErrorWriter(t,`document-list`),w=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let s=()=>{t.off(`drain`,s),t.off(`close`,s),e()};t.once(`drain`,s),t.once(`close`,s)})};try{let t=getShowAllMaxEntries(),s=streamShowAllEntries({contentDir:g,contentFilter:De,dirFilter:S,maxEntries:t,maxDepth:O,signal:e.signal}),E=0,D=await s.next();for(;!D.done;)await w(`${JSON.stringify(D.value)}\n`),E+=1,D=await s.next();let{truncated:k}=D.value;k&&log$7.info({handler:`document-list`,maxEntries:t,count:E},`[document-list][showAll] stream truncated at entry cap`),await w(`${JSON.stringify({type:`complete`,truncated:k,count:E})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?s(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):log$7.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(E&&De){let e=`showAll:${O===1?`d1:`:``}${S??``}`,s=Ke.get(e);if(!s){let t=new AbortController,w=(async()=>{let e=[],s=getShowAllMaxEntries(),{truncated:w}=await walkContentDirForShowAll({contentDir:g,contentFilter:De,dirFilter:S,documents:e,maxEntries:s,maxDepth:O,signal:t.signal});return e.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),w&&log$7.info({handler:`document-list`,maxEntries:s,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:w}})();s={promise:w,controller:t,waiters:0};let E=s;Ke.set(e,E),w.finally(()=>{Ke.get(e)===E&&Ke.delete(e)})}let w=s;w.waiters+=1;let E=!1,D=()=>{t.writableEnded||E||(E=!0,--w.waiters,w.waiters<=0&&(w.controller.abort(),Ke.get(e)===w&&Ke.delete(e)))};t.on(`close`,D);try{let{documents:e,truncated:s}=await w.promise;if(E)return;successResponse(t,200,DocumentListSuccessSchema,s?{documents:e,truncated:s}:{documents:e},{handler:`document-list`})}catch(e){if(E)return;errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,D)}return}let k=w(),F=D(),L=j?.()??new Map,H=[];for(let[e,t]of L)S&&!e.startsWith(`${S}/`)&&e!==S||H.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let q=[];try{let e=vt(k);$e?.signature!==e&&($e={signature:e,assets:collectReferencedAssets({contentDir:g,fileIndex:k,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:De?e=>De.isPathIgnored(e):void 0})}),q=$e?.assets??[]}catch(e){$e=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}let ee=new Set;for(let e of q)S&&!e.path.startsWith(`${S}/`)&&e.path!==S||(ee.add(e.path),H.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of F){if(t.kind===`markdown`){if(S&&!e.startsWith(`${S}/`)&&e!==S)continue;let s=getDocExtension(e);H.push({kind:`document`,docName:e,docExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let w of t.aliases){if(S&&!w.startsWith(`${S}/`)&&w!==S)continue;let E=toPosix(relative(g,t.canonicalPath));H.push({kind:`document`,docName:w,docExt:s,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:E})}continue}if((!S||e===S||e.startsWith(`${S}/`))&&!ee.has(e)){let s=synthesizeShowAllAssetExt(e);H.push({kind:`file`,docName:e,path:e,docExt:`.${s}`,assetExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let s of t.aliases){if(!(!S||s===S||s.startsWith(`${S}/`))||ee.has(s))continue;let w=toPosix(relative(g,t.canonicalPath)),E=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${E}`,assetExt:E,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:w})}}let J=B?.()??new Map;if(J.size>0){let e=e=>!S||e===S||e.startsWith(`${S}/`),t=new Map;for(let[e,s]of J){let g=t.get(s);g?g.push(e):t.set(s,[e])}for(let[s,S]of t){let t=L.get(s),w=t?toPosix(relative(g,t.canonicalPath)):s;for(let g of S)e(g)&&H.push({kind:`folder`,path:g,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:s,targetPath:w})}let s=(s,g)=>{for(let S=s.indexOf(`/`);S!==-1;S=s.indexOf(`/`,S+1)){let w=t.get(s.slice(0,S));if(!w)continue;let E=s.slice(S);for(let t of w){let s=`${t}${E}`;e(s)&&g(s)}}};for(let[e,t]of L)s(e,s=>{H.push({kind:`folder`,path:s,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:toPosix(relative(g,t.canonicalPath))})});for(let[e,t]of F)s(e,s=>{let S=toPosix(relative(g,t.canonicalPath));if(t.kind===`markdown`)H.push({kind:`document`,docName:s,docExt:getDocExtension(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S});else{let g=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${g}`,assetExt:g,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S})}})}H.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),successResponse(t,200,DocumentListSuccessSchema,{documents:H},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),Is=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}successResponse(t,200,BacklinksSuccessSchema,{docName:s,backlinks:ue.getBacklinks(s).map(e=>({source:e.source,anchor:e.anchor,title:jt(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),Ls=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let g={};for(let e of s.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(g[t]=ue.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:g},{handler:`backlink-counts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let g=en();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ue.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Mt(e.target,g),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),ec=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`docName`);if(g&&!isSafeDocName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let S=s.searchParams.get(`degrees`);if(S&&!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let w,E;if(S&&g){let e=Number.parseInt(S,10);if(!Number.isFinite(e)||e<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:w,links:E}=ue.getLinkGraphNeighborhood(g,e))}else ({nodes:w,links:E}=ue.getLinkGraph());let D=en();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=Lt(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Mt(e.docName,D),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:E},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),tc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}successResponse(t,200,OrphansSuccessSchema,{orphans:ue.getOrphans([...w().keys()],s).map(e=>({docName:e,title:jt(e)}))},{handler:`orphans`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),nc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),g=s?Number.parseInt(s,10):20,S=Number.isFinite(g)&&g>0?g:20,w=en();successResponse(t,200,HubsSuccessSchema,{hubs:ue.getHubs(S).map(e=>({docName:e.docName,title:Mt(e.docName,w),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),rc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let s=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(s.some(e=>e.length===0||!isSafeDocName(e))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let g=s.length?[...new Set(s.map(e=>zt(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ue.getDeadLinks(en(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:jt(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),ic=withValidation(AgentPatchRequestSchema,async(S,w,E)=>{try{let{find:S,replace:D,offset:O}=E,k=requireNonEmptyDocName(E.docName,w,`agent-patch`);if(k===null)return;let j=zt(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=Qi(E);if(findLooksLikeFrontmatter(S)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H}),te=reconcileDiskBeforeAgentWrite(t,j,g,e.resolveEmbed),ne=new Date().toISOString(),ae=!1,oe=!1,se=!1,ce;try{let t=iconFromClientName(H),s=AGENT_ICON_COLORS[t]??colorFromSeed(B??F);if(ge?.setPresence(F,{displayName:L,icon:t,color:s,currentDoc:j,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),F,B,H),Y.dc.document.transact(()=>{let{frontmatter:t,body:s}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),g=prependFrontmatter(t,s),w=O==null?g.indexOf(S):g.slice(O,O+S.length)===S?O:-1;if(w===-1){O==null?ae=!0:oe=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":j,findLength:S.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(w<t.length){se=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));ce=applyAgentMarkdownWrite(Y.dc.document,E,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0),Y.dc.document.getMap(`agent-flash`).set(F,{agentId:F,timestamp:Date.now(),type:`insert`,description:`Patched (${L}): ${S.slice(0,50)}`})},Y.origin),ce!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":j,position:`patch`,intendedBytes:ce.intendedBytes,actualBytes:ce.actualBytes,byteDelta:ce.byteDelta,"agent.id":F,"agent.client_name":H})),!ae&&!oe&&!se){let{stored:e}=eo(J);recordContributor(j,F,L,B,void 0,Ra({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),so(J),recordContentDivergenceGate(`agent-patch`,ce)}}finally{ge?.touchMode(F,`idle`)}if(oe){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(ae){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(se){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let ue=await Ut(j);if(ue?.kind===`failure`){Wt(w,ue.failure,`agent-patch`);return}if(ue?.kind===`divergence`){Xt(w,`agent-patch`);return}Ht(j,`agent-patch`),me?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),_e?.();let de=Bt(j),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=eo(J),ye=Y.dc.document.getText(`source`).toString();rn(j,ye);let Ce=await validateMermaidFences(ye,j),we=en();we.add(j);let Te=computeBrokenOutboundLinks(ye,j,we,tn),De=Zt(te),je=ce===void 0?void 0:toContentDivergenceWarning(ce),Me=[...je?[je]:[],...De?[De]:[],...Ce??[]];successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ne,subscriberCount:de,systemSubscriberCount:fe,...ve?{summary:ve}:{},...je?{warning:je}:De?{warning:De}:{},...Me.length>0?{warnings:Me}:{},brokenLinks:Te},{handler:`agent-patch`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-patch`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-patch`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$7.error({err:e},`[agent-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),ac=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=zt(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Qi(S);if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(g,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:L}=S,B=S.scope===`session`||S.scope===`file`?`session`:`last`;if(!s.hasSession(w,L)){errorResponse(g,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let H=await s.getSession(w,L),q=!1;try{let t=iconFromClientName(k),s=AGENT_ICON_COLORS[t]??colorFromSeed(O??E);ge?.setPresence(E,{displayName:D,icon:t,color:s,currentDoc:w,mode:`writing`,ts:Date.now()}),q=applyAgentUndo(H,B,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:w}:void 0),q&&recordContributor(w,L,D,O,void 0,Ra({clientName:k,clientVersion:j,label:F}))}finally{ge?.touchMode(E,`idle`)}if(q){let e=await Ut(w);if(e?.kind===`failure`){Wt(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Xt(g,`agent-undo`);return}Ht(w,`agent-undo`)}me?.setFocus(L,{agentName:L,currentDoc:w,writeKind:`undo`,ts:Date.now()}),successResponse(g,200,AgentUndoSuccessSchema,{docName:w,scope:B,undone:q},{handler:`agent-undo`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(g,e,`agent-undo`);return}log$7.error({err:e},`[agent-undo] handler failed`),errorResponse(g,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),oc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(g===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(s,g),{handler:`agent-activity`})}catch(e){log$7.error({err:e},`[agent-activity] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),sc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=validateAgentId(g.searchParams.get(`agentId`)),w=g.searchParams.get(`docName`),E=g.searchParams.get(`stackIndex`);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!w||w.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let D=zt(w);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!E||Number.isNaN(Number(E))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let O=Number(E);if(!Number.isInteger(O)||O<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let k=s.getLiveSession(D,S);if(!k){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let j=k.um;if(O>=j.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${O} out of range (stack has ${j.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let F=j.undoStack[O];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(F,k.dc.document.getText(`source`),D),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$7.error({err:e},`[agent-burst-diff] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),cc=withValidation(EmptyRequestSchema,async(e,t)=>{try{await J?.(),successResponse(t,200,TestFlushGitSuccessSchema,{},{handler:`test-flush-git`})}catch(e){log$7.error({err:e},`[test-flush-git] flush failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:e})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),lc=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=zt(w.searchParams.get(`docName`)??`test-doc`),D;try{D=safeContentPath(E,g)}catch(e){log$7.error({err:e,docName:E},`[test-reset] safeContentPath rejected docName`),errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await s.closeAll(E),t.closeConnections(E);let O=`onStoreDocument-${E}`;t.debouncer.isDebounced(O)&&await t.debouncer.executeNow(O);let k=t.documents.get(E);if(k&&await(Me??t.unloadDocument.bind(t))(k),writeFileSync(D,``,`utf-8`),ue&&(ue.deleteDocument(E),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${E}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),w.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(g,`.okignore`),s=t.documents.get(CONFIG_DOC_NAME_OKIGNORE);if(s){let e=s.getText(`source`);e.length>0&&s.transact(()=>{e.delete(0,e.length)},CONFIG_VALIDATION_REVERT_ORIGIN)}existsSync(e)&&writeFileSync(e,``,`utf-8`),De&&await De.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}fe?.(`files`),successResponse(S,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),uc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ue.rebuildFromDisk(),await ue.ingestGlobalSkillBundles([resolve(du,`.ok`,`skills`)]),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),fe?.(`backlinks`),fe?.(`graph`),successResponse(t,200,TestRescanBacklinksSuccessSchema,{},{handler:`test-rescan-backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),dc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!H){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await H(),fe?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),fc=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Qi(s),E=ee?.current;if(!E){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let D=/^[a-zA-Z0-9_-]+$/,O=[],k=!1;if(Array.isArray(s.writers))try{O=s.writers.map(e=>{let t=e.id??`unknown`;if(!D.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let j=oe?.()??`main`;if(O.length===0)if(e!==void 0)O=[{id:g,name:w?`${S} (${w})`:S,email:`${g}@openknowledge.local`}];else{let e=(await enumerateWipChains(E,j)).filter(e=>!e.isPark);O=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[SERVICE_WRITER],k=!0}let F=ce??`.`,L=normalizeSummary(typeof s.summary==`string`?s.summary:void 0),B=await saveVersion(E,F,O,j,L.kind===`value`?L.value:void 0,k?{includeUpstream:!1}:void 0);getLogger(`history`).info({checkpointRef:B.checkpointRef},`checkpoint`);try{await gcRenameLog(E,getOrLoadRenameLogIndex(E.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:B.checkpointRef},{handler:`save-version`})}catch(e){log$7.error({err:e},`[save-version] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),pc=withValidation(EmptyRequestSchema,async(e,t)=>{let s=ee?.current;if(!s){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`docName`)??``,w=g.searchParams.get(`folder`),E=g.searchParams.get(`branch`)??oe?.()??`main`;if(!S&&w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(E.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(w!==null&&!S){let e=Gl(w,t,`folder`,`history`);if(!e)return;let S=Number(g.searchParams.get(`limit`)??`50`),D=Math.min(200,Number.isFinite(S)?S:50),O=Number(g.searchParams.get(`offset`)??`0`),k=Math.max(0,Number.isFinite(O)?O:0),j=`folder\0${E}\0${e.folderRel}\0${D}\0${k}`,{promise:F,coalesced:L}=Xe.run(j,()=>getFolderTimeline(s,e.folderRel,ce??`.`,{branch:E,limit:D,offset:k}));L&&recordTimelineCoalesced(`folder`),successResponse(t,200,HistorySuccessSchema,{...await F},{handler:`history`});return}let D=ce??`.`,O=safeDocPath(S,D);if(`error`in O){errorResponse(t,400,`urn:ok:error:invalid-request`,O.error,{handler:`history`});return}let k=Number(g.searchParams.get(`limit`)??`50`),j=Number(g.searchParams.get(`offset`)??`0`),F=Math.min(200,Number.isFinite(k)?k:50),L=Number.isFinite(j)?j:0,B=g.searchParams.get(`type`)??void 0,H=g.searchParams.get(`author`)??void 0,q=g.searchParams.get(`excludeAuthor`)??void 0,J=g.searchParams.get(`includeAutoCheckpoints`)===`true`,Y=`doc\0${E}\0${S}\0${F}\0${L}\0${B??``}\0${H??``}\0${q??``}\0${J?`1`:`0`}`,te=Date.now();try{let{promise:e,coalesced:g}=Xe.run(Y,()=>getDocumentHistory(s,{docName:S,branch:E,limit:F,offset:L,type:B,author:H,excludeAuthor:q,includeAutoCheckpoints:J},D));g&&recordTimelineCoalesced(`doc`);let w=await e,O=Date.now()-te;getLogger(`timeline`).info({docName:S,entries:w.entries.length,durationMs:O},`query`),successResponse(t,200,HistorySuccessSchema,{...w},{handler:`history`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function mc(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let g=ee?.current;if(!g){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,w=ce??`.`,E=safeDocPath(S,w);if(`error`in E){errorResponse(t,400,`urn:ok:error:invalid-request`,E.error,{handler:`history-version`});return}let D=shadowGit(g),O=oe?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await resolveDocPathAtCommit(g,S,s,O,getOrLoadRenameLogIndex(g.gitDir),e=>{let t=safeDocPath(e,w);return`error`in t?`${e}.md`:t.path},createAncestorShaSetCache());if(e===null){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let E=await D.raw(`show`,`${s}:${e}`),[k=``,j=``]=(await D.raw(`log`,`-1`,`--format=%aI%x00%an`,s)).trim().split(`\0`);successResponse(t,200,HistoryVersionSuccessSchema,{sha:s,content:E,timestamp:k,author:j},{handler:`history-version`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let hc=withValidation(RollbackRequestSchema,async(s,g,S)=>{let w=extractActorIdentity(S,we);if(w.kind===`invalid-summary`){errorResponse(g,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let E=t.documents.get(S.docName);if(E&&isDocInConflict(E)){respondDocInConflict(g,new DocInConflictError({file:docNameToRelativePath(S.docName)}),`rollback`);return}let D=ee?.current;if(!D){errorResponse(g,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:O,commitSha:k}=S,j=ce??`.`,F=safeDocPath(O,j);if(`error`in F){errorResponse(g,400,`urn:ok:error:invalid-request`,F.error,{handler:`rollback`});return}let L=shadowGit(D),B=Date.now();try{let s=getOrLoadRenameLogIndex(D.gitDir),S=createAncestorShaSetCache(),E=await resolveDocPathAtCommit(D,O,k,oe?.()??`main`,s,e=>{let t=safeDocPath(e,j);return`error`in t?`${e}.md`:t.path},S);if(E===null){errorResponse(g,404,`urn:ok:error:doc-not-found`,`Commit ${k.slice(0,7)} does not contain document ${O} at any known historical path.`,{handler:`rollback`});return}let F=await L.raw(`show`,`${k}:${E}`),H=new Date().toISOString();await safetyCheckpoint(D,j,{action:`rollback`,context:{docName:O,targetSha:k}});let q=t.documents.get(O);if(!q){errorResponse(g,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let ee=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:O}:void 0,J;q.transact(()=>{replaceRawBody(q,F,ee),J=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),J!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:J.intendedBytes,actualBytes:J.actualBytes,byteDelta:J.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,J);let Y;switch(w.kind){case`agent`:{let e=k.slice(0,8),t=w.summary.kind===`value`,s=t?w.summary:normalizeSummary(`Restored to ${e}`),g=eo(s);Y=t||!g.response?g.response:to(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),so(s,!t);break}case`principal`:{let e=eo(w.summary);Y=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),so(w.summary,!1);break}case`anonymous`:log$7.debug({docName:O,commitSha:k.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(w.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:w.kind});let te=await Ut(O);if(te?.kind===`failure`){Wt(g,te.failure,`rollback`);return}if(te?.kind===`divergence`){Xt(g,`rollback`);return}Ht(O,`rollback`);let ne=Date.now()-B;getLogger(`rollback`).info({docName:O,from:k.slice(0,8),durationMs:ne},`rollback`),w.kind===`agent`&&me?.setFocus(w.writerId,{agentName:w.displayName,currentDoc:O,writeKind:`rollback-apply`,ts:Date.now()});let ae=J===void 0?void 0:toContentDivergenceWarning(J);successResponse(g,200,RollbackSuccessSchema,{restoredFrom:k,timestamp:H,...Y?{summary:Y}:{},...ae?{warning:ae,warnings:[ae]}:{}},{handler:`rollback`})}catch(e){errorResponse(g,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),gc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$7.error({err:e},`[metrics-reconciliation] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),_c=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$7.error({err:e},`[metrics-parse-health] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),vc=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$7.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=se?.(),g=getBootTimings();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s},...g===void 0?{}:{boot:g}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function yc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let s=we?.()??null;if(!s){errorResponse(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}successResponse(t,200,PrincipalSuccessSchema,s,{handler:`principal`})}async function bc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=ge?.getPresenceMap()??{},s=Date.now(),g={};for(let[t,S]of Object.entries(e))s-S.ts<2e4&&(g[t]=S);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:g},{handler:`metrics-agent-presence`})}catch(e){log$7.error({err:e},`[metrics-agent-presence] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function xc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let s=embedProbeRing.read();successResponse(t,200,EmbedDetectSuccessSchema,{entries:s,count:s.length,detection:deriveDetection(s[0])},{handler:`embed-detect`})}async function Sc(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let s=resolve(g),S=s,w=!0;try{S=realpathSync(s)}catch(e){let g=e?.code;if(g===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:s}),w=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:s,err:e}),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:g??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:S,pathSeparator:sep,symlinkResolved:w},{handler:`workspace`})}let Cc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let S=assetContentTypeForPath(s),w=extname(s).slice(1).toLowerCase();if(!S||!ASSET_EXTENSIONS.has(w)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let E=realpathSync(g),D=resolve(E,s),O;try{O=realpathSync(D)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(O,E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let k;try{k=statSync(O)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!k.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let j=toContentRelativePath(E,O);if(j!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(De?.isPathIgnored(j)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let F=SANDBOXED_HTML_EXTENSIONS.has(w),L={"Content-Type":S,"Content-Length":String(k.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(w)||F?`inline`:`attachment`,"Cache-Control":`no-store`};w===`svg`?L[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:F&&(L[`Content-Security-Policy`]=SANDBOXED_HTML_CSP),t.writeHead(200,L);try{await pipeline(createReadStream(O),t)}catch(e){log$7.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:s,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),wc=1048576,Tc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!s||s.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let S=realpathSync(g),w=resolve(S,s),E;try{E=realpathSync(w)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!isWithinContentDir(E,S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let D;try{D=statSync(E)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!D.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(toContentRelativePath(S,E)!==s.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(D.size>wc){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${wc}-byte text-viewer cap.`,{handler:`asset-text`});return}let O=(await readFile$1(E)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(O)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),Ec=1440*60*1e3,Dc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ee?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),s=[],g=resolve(ee.current.gitDir,`rescue`);if(existsSync(g))try{let t=readdirSync(g).filter(e=>isSupportedDocFile(e));for(let S of t){let t=resolve(g,S),w=statSync(t);if(e-w.mtimeMs>864e5){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}s.push({docName:stripDocExtension(S),timestamp:w.mtime.toISOString(),size:w.size,source:`flat`})}}catch(e){log$7.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=oe?.()??`main`,t=await listRescueCheckpoints(ee.current,e);for(let e of t)s.push({...e,source:`timeline`})}catch(e){log$7.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}successResponse(t,200,RescueListSuccessSchema,s,{handler:`rescue-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),Oc=withValidation(CreatePageRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let S=s.path;if(!isSupportedDocFile(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(S.includes(`..`)||S.startsWith(`/`)||S.includes(`\0`)||S.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let w=resolve(g),E=resolve(w,S);if(!isWithinDir(E,w)){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let D=stripDocExtension(S);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`});return}if(S.split(`/`)[0]===`.ok`||isManagedArtifactDocName(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page under .ok/ — skills and templates are authored through their own validating flows.`});return}let k=typeof s.template==`string`?s.template.trim():``,j=``,F;if(k.length>0){if(!/^[A-Za-z0-9_-]+$/.test(k)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let s=S.includes(`/`)?S.slice(0,S.lastIndexOf(`/`)):``,g=resolveTemplatesAvailable(w,s),E=g.find(e=>e.name===k);if(!E){let e=g.length===0?`(none)`:g.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${k}" does not resolve for folder "${s||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let D=resolve(w,E.path),O;try{O=readFileSync(D,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${E.path}.`,{handler:`create-page`,cause:e});return}let L=instantiateDoc(O),B=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;j=applySubstitution(L,{date:todayIsoUtc(),user:B}),F=E.scope}mkdirSync(dirname(E),{recursive:!0});try{writeFileSync(E,j,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let L=stripDocExtension(S);switch(Ie?.delete(L),De&&De.incrementMdDir(dirname(L)),registerWrite(E,contentHash(j)),e.kind){case`agent`:case`principal`:recordContributor(L,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}O?.({kind:`create`,path:E,docName:L,content:j}),ue&&(ue.updateDocumentFromMarkdown(L,j),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${L}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),F!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:k,templateScope:F,docName:L})),successResponse(t,200,CreatePageSuccessSchema,{docName:L},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),kc=withValidation(CreateFolderRequestSchema,async(e,t,s)=>{try{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=s.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(De?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let S=resolveContentEntryPath(g,`folder`,e);if(existsSync(S)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(S,{recursive:!0}),it(e),fe?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),Ac=withValidation(DuplicatePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:w}=S,E=S.path,D=w===`file`?stripDocExtension(E):E;if(!isValidRelativeContentPath(E)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||w===`file`&&(isSystemDoc(D)||isConfigDoc(D))||w===`folder`&&isReservedSyntheticFolderPath(E)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}w===`file`&&probeAndRegisterSourceFileExtension(g,E);let k=resolveContentEntryPath(g,w,E);if(!existsSync(k)){if(w===`file`){let e=resolveContentEntryPath(g,`folder`,E);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}}errorResponse(s,404,`urn:ok:error:doc-not-found`,`${w} does not exist.`,{handler:`duplicate-path`});return}let j=statSync(k);if(w===`file`&&!j.isFile()||w===`folder`&&!j.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}let F=w===`file`?[docNameForFileOperationPath(g,E)]:Gi(resolveContentEntryPath(g,`folder`,E)),L=ve?.(),B=new Set(L?L.getConflicts().map(e=>e.file):[]);for(let e of F){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=B.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let H,q=[];if(w===`file`){let e=extname(k);if(H=nextAvailableDuplicateDocName(g,D).docName,isSystemDoc(H)||isConfigDoc(H)||De?.isExcluded(`${H}${e}`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let t=resolveDuplicateDocPath(g,H,e),S=readFileSync(k,`utf-8`),w=dirname(t),E=existsSync(w);try{tracedMkdirSync(w,{recursive:!0}),tracedWriteFileSync(t,S,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!E)try{tracedRmdirSync(w)}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTEMPTY`&&console.warn(`[duplicate-path] failed to clean duplicate parent directory:`,{destinationDir:w,err:e})}throw e}let j=!1;try{registerDocExtension(H,e),Ie?.delete(H),De&&(De.incrementMdDir(dirname(H)),j=!0),registerWrite(t,contentHash(S)),O?.({kind:`create`,path:t,docName:H,content:S}),ue?.updateDocumentFromMarkdown(H,S),q=[H]}catch(e){try{tracedRmSync(t,{force:!0})}catch(e){console.warn(`[duplicate-path] failed to clean partial file duplicate:`,{destinationPath:t,err:e})}throw forgetDocExtension(H),De&&j&&De.decrementMdDir(dirname(H)),O?.({kind:`delete`,path:t,docName:H}),e}}else{if(H=nextAvailableDuplicateFolderPath(g,E).folderPath,De?.isDirExcluded(H)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=resolveContentEntryPath(g,`folder`,H);try{tracedCpSync(k,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(isAlreadyExistsError(e)){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of collectFolderPaths(g,H))it(e);let e=collectMarkdownCopies(g,H);q=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(stripDocExtension(t.docName),e),Ie?.delete(t.docName),De&&De.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),O?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),ue?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{tracedRmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[duplicate-path] failed to clean partial folder duplicate:`,{destinationPath:e,err:t})}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of q)recordContributor(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}ue&&q.length>0&&(ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),successResponse(s,200,DuplicatePathSuccessSchema,{kind:w,path:H,duplicatedDocNames:q},{handler:`duplicate-path`})}catch(e){if(e instanceof DuplicateNameExhaustedError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=classifyDuplicatePathFilesystemProblem(e);if(t){errorResponse(s,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),jc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!s||s.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(s)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let g=Et(s);if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(g)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:s,headings:extractHeadings(readFileSync(g,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),Mc=withValidation(RenamePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:w,fromPath:E,toPath:D}=S;if(!isValidRelativeContentPath(E)||!isValidRelativeContentPath(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(w===`file`&&(isSystemDoc(E)||isSystemDoc(D)||isConfigDoc(E)||isConfigDoc(D))){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||D===`.ok`||D.startsWith(`.ok/`)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(E===D){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let O=w===`asset`&&isSupportedDocFile(E)&&isSupportedDocFile(D)?`file`:w;if(O===`asset`){let t;try{t=isSupportedDocFile(E)&&!isSupportedDocFile(D)?await Yi(E,D):await Ji(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=zr(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&St();let g;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let s=`Renamed asset ${E} → ${D}`;g=_s(e,s,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:s})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$7.debug({kind:`asset`,fromPath:E,toPath:D,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(renameAttributionCounter().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...g?{summary:g}:{}},{handler:`rename-path`});return}O===`file`&&probeAndRegisterSourceFileExtension(g,E);let k=O===`file`?[docNameForFileOperationPath(g,E)]:Gi(resolveContentEntryPath(g,`folder`,E)),j=ve?.(),F=new Set(j?j.getConflicts().map(e=>e.file):[]);for(let e of k){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=F.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`rename-path`);return}}if(De){let e=isSupportedDocFile(E)?extname(E):getDocExtension(E);if(O===`file`?De.isExcluded(isSupportedDocFile(D)?D:`${D}${e}`):De.isDirExcluded(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Destination ${O===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let L=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,B;try{B=await Xi(E,D,O,L?{actor:L}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,Mr(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(B.renamed.length===0&&B.renamedAssets.length===0){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}B.renamedAssets.length>0&&St();let H,q=B.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(q.length>0&&(H=_s(e,`Renamed ${E} → ${D}`,q.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$7.debug({kind:w,fromPath:E,toPath:D,affectedDocs:B.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${O}`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:B.renamed,renamedAssets:B.renamedAssets,rewrittenDocs:B.rewrittenDocs,...H?{summary:H}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:g,error:S}=zr(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Nc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Qi(S);let{kind:e,path:w}=S;if(!isValidRelativeContentPath(w)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let E=e===`asset`?Qr(w):{path:w,ambiguous:!1};if(E.ambiguous){errorResponse(s,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let D=E.path,k=e===`asset`&&isSupportedDocFile(D)?`file`:e;if(k===`file`&&probeAndRegisterSourceFileExtension(g,D),k===`asset`&&isReservedProjectStatePath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let j=k===`asset`?resolveContentEntryPath(g,`folder`,D):resolveContentEntryPath(g,k,D);if(!existsSync(j)){errorResponse(s,404,`urn:ok:error:doc-not-found`,`${k} does not exist.`,{handler:`delete-path`});return}let F=statSync(j);if(k===`file`&&!F.isFile()||k===`asset`&&!F.isFile()||k===`folder`&&!F.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${k}.`,{handler:`delete-path`});return}let L=k===`asset`?[]:k===`file`?[docNameForFileOperationPath(g,D)]:Gi(resolveContentEntryPath(g,`folder`,D)),B=ve?.(),H=new Set(B?B.getConflicts().map(e=>e.file):[]);for(let e of L){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=H.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`delete-path`);return}}if(await Br(L,`deleted-upstream`),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));k===`file`||k===`asset`?tracedUnlinkSync(j):(tracedRmSync(j,{recursive:!0,force:!1}),at(D)),St();for(let e of L)O?.({kind:`delete`,path:resolve(g,docNameToRelativePath(e)),docName:e});fe?.(`files`),successResponse(s,200,DeletePathSuccessSchema,{deletedDocNames:L},{handler:`delete-path`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Pc=withValidation(TrashCleanupRequestSchema,async(e,t,s)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":s.kind,"ok.cleanup.path":normalizeFsPath(s.path),"ok.cleanup.path.role":classifyFsPath(s.path)}},async()=>{try{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:S}=s;if(!isValidRelativeContentPath(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let E=e===`asset`&&isSupportedDocFile(S)?`file`:e,D=stripDocExtension(S);E===`file`&&probeAndRegisterSourceFileExtension(g,S);let k=E===`folder`&&isReservedSyntheticFolderPath(S),j=E===`asset`&&isReservedProjectStatePath(S);if(E===`file`&&(isSystemDoc(D)||isConfigDoc(D))||k||j){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${S}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(E===`asset`){St(),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let F=w(),L=E===`file`?F.has(D)?[D]:[]:listAffectedDocNames(F,E,S);if(St(),L.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Br(L,`deleted-upstream`),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of L)O?.({kind:`delete`,path:resolve(g,docNameToRelativePath(e)),docName:e});E===`folder`&&at(S),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:L},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Fc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=w(),s=[];for(let[t,S]of e){let e=getDocExtension(t),w,E;if(S.title!==void 0)w=S.title,E=S.icon;else{w=t;try{let s=readFileSync(resolve(g,`${t}${e}`),`utf-8`);w=extractPageTitle(s,t),E=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}}s.push({docName:t,title:w,docExt:e,size:S.size,modified:S.modified,icon:E})}s.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:s},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),Ic=withValidation(EmptyRequestSchema,async(e,s)=>{try{let g=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!g){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(g)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(g)||isConfigDoc(g)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`'${g}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(s,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:w(),docName:g}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(s,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function Lc(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let s;try{s=await readUploadBody(e,Ce??g)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:S,tempPath:w,sha:D,byteLength:O,parentDocName:k,placement:j}=s,F=()=>{if(existsSync(w))try{unlinkSync(w)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:k,placement:j||void 0},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B,placement:H}=L.value,{agentId:q,agentName:ee}=Qi(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(O===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(g),Y;try{Y=H===`parent-dir`?`./`:E?.()??`./`}catch(e){F(),log$7.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!isValidAttachmentFolderPath(Y)){F(),errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let te=resolveUploadDestDir(B,normalizeAttachmentFolderPath(Y),J);if(!isWithinContentDir(te,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(te,J)}catch(e){if(F(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$7.error({err:e,destDir:te},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(te,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){F();let s=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(s),s,uploadTitleFor(s),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(te),s;try{s=realpathSync(J)}catch{s=J}if(!isWithinContentDir(e,s)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ne=readTempFileHead(w,4100),ae=await fileTypeFromBuffer(ne),oe=ae?.mime,se=ae?.ext;if(!oe){let e=ne.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(oe=`image/svg+xml`,se=`svg`)}{let s=await findDuplicateAsset(te,D,O);if(s){F();let S=toPosix(relative(g,resolve(te,s)));log$7.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!0,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!0},{handler:`upload-asset`});return}}let ce;if(!S||S===`upload`||GENERIC_PASTE_NAMES.test(S)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=S?extname(S).slice(1):``,s=se??t??``;ce=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else ce=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,te,ce),S=toPosix(relative(g,resolve(te,s)));log$7.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!1,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!1},{handler:`upload-asset`})}catch(s){let g=s instanceof UploadWriteError?s.reason:`urn:ok:error:storage-error`;log$7.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,filename:ce,size:O,reason:g,httpStatus:uploadStatusFor(g),err:s},`[upload] write failed`),errorResponse(t,uploadStatusFor(g),g,uploadTitleFor(g),{handler:`upload-asset`,cause:s})}}let Rc=`/api/local-op/clone`,zc=`/api/local-op/ok-init`,Bc=600*1e3,Vc=45e3,Hc={stdio:[`ignore`,`ignore`,`pipe`]},Uc={stdio:[`ignore`,`pipe`,`pipe`]},Wc={stdio:`ignore`},Gc=`local-op-clone`,Kc=withValidation(LocalOpCloneRequestSchema,qc,{handler:Gc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Gc})});async function qc(e,t,s){let{url:g,dir:S,branch:w}=s;if(!isAllowedGitUrl(g)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:Gc,cause:Error(`url=${g}`)});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:Gc,cause:Error(`dir=${S}`)});return}if(!Ge.tryAcquire(Rc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Gc,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,Gc),D=null,O=runCloneSubprocess({cliArgs:ye,url:g,dir:S,branch:w,timeoutMs:Bc,onEvent:e=>{if(e.type===`complete`){D=e.dir;return}if(e.type===`error`){e.message&&log$7.warn({stderr:redactShareSubprocessStderr(e.message),url:g,dir:S},`[local-op/clone] clone failed`);let t=classifyCloneError(e.message??``);E(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(redactShareSubprocessStderr(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await O.done,D&&!t.writableEnded&&!t.destroyed){let e=await Jc(D);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:D})}\n`):E(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?E(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$7.error({err:e,handler:Gc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ge.release(Rc)}})(),t.on(`close`,()=>{O.cancel()})}async function Jc(e,t){let s=resolve(expandTilde(e)),g=getLocalDir(s),S=readUiLock(g);if(S&&S.port>0)return{port:S.port};let[w,...E]=ye,D=e=>{let s=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...E,e,...s]},O=async e=>{let t=spawn(w,D(e),withHiddenWindowsConsole({...Hc,cwd:s,detached:!0,env:{...process.env,OK_LOCK_KIND:`interactive`}})),S=[];t.stderr?.on(`data`,t=>{S.push(t),log$7.warn({cwd:s,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/clone] child stderr`)});let E=null,O=null,k=null;t.on(`exit`,(e,t)=>{E=e??-1,O=t??null}),t.on(`error`,t=>{k=t.message,E=-1,log$7.error({cwd:s,cliCmd:e,err:t.message},`[local-op/clone] failed to spawn child`)}),t.unref();let j=Date.now()+45e3;for(;Date.now()<j;){await setTimeout$1(500);let t=readUiLock(g);if(t&&t.port>0)return{port:t.port};if(E!==null){let t=Buffer.concat(S).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${k?`spawn failed: ${k}`:O?`killed by ${O}`:`code ${E}`})${t?` — ${t}`:``}`,exited:!0}}}let F=Buffer.concat(S).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${F?` — ${F}`:``}`,exited:!1}},k=readServerLock(g),j=k&&k.port>0?`ui`:`start`,F=await O(j);if(j===`start`&&`error`in F&&F.exited){let e=readServerLock(g);if(e&&e.port>0){let e=await O(`ui`);return`port`in e?e:{error:`${F.error}; connect fallback failed: ${e.error}`}}}return`port`in F?F:{error:F.error}}let Yc=`local-op-ok-init`,Xc=withValidation(LocalOpOkInitRequestSchema,async(e,t,s)=>{let{projectPath:g}=s;if(!isAbsolute(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:Yc,cause:Error(`projectPath=${g}`)});return}let S;try{S=realpathSync(g)}catch(e){successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:Yc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Yc,cause:Error(`projectPath=${g}`)});return}let w=resolveGitDirDetailed(S).kind;if(w!==`directory`&&w!==`linked`){console.warn(`[ok-init] action=init project=${basename(S)} result=not-a-git-worktree kind=${w}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${w}).`},{handler:Yc});return}if(isProjectRoot(S)){console.warn(`[ok-init] action=init project=${basename(S)} result=already-initialized`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Yc});return}if(!Ge.tryAcquire(zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Yc,extraHeaders:{"Retry-After":`2`}});return}try{await withParentLock(async()=>{initContent(S)}),console.warn(`[ok-init] action=init project=${basename(S)} result=success`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:S},{handler:Yc})}catch(e){let s=e instanceof Error?e.message:String(e);console.warn(`[ok-init] action=init project=${basename(S)} result=failed reason=${s}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`init-failed`,message:s},{handler:Yc})}finally{Ge.release(zc)}},{handler:Yc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Yc})}),Zc=`/api/local-op/auth/login`,Qc=`/api/local-op/auth/status`,$c=`/api/local-op/auth/repos`,dl=`/api/local-op/auth/signout`,ml=null,hl=`local-op-auth-login`,gl=withValidation(LocalOpAuthHostRequestSchema,_l,{handler:hl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:hl})});async function _l(e,t,s){let g=s.host??`github.com`;if(!Ge.tryAcquire(Zc)){let e=ml;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-login-slot-no-controller`,channel:`auth`,transport:`http`})),errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:hl,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),ml=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,hl),w=runDeviceFlowSubprocess({cliArgs:ye,host:g,timeoutMs:Bc,onEvent:e=>{if(e.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(resumeSyncOnAuthEvent(e,ve),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});ml=w;let E=()=>{w.cancel(),ml===w&&(ml=null,Ge.release(Zc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}ml===w&&(ml=null,Ge.release(Zc))})}let vl=`local-op-auth-status`,yl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire(Qc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:vl,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`status`,`--json`,`--host`,g],w=(await new Promise((t,s)=>{let g=spawn(e,S,withHiddenWindowsConsole({...Uc,env:{...process.env}})),w=!1,E=setTimeout(()=>{w=!0,g.kill(`SIGTERM`)},3e4),D=[];g.stdout.on(`data`,e=>D.push(e)),g.on(`close`,()=>{if(clearTimeout(E),w){s(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(D).toString(`utf-8`))}),g.on(`error`,e=>{clearTimeout(E),s(e)})})).split(`
|
|
1945
|
+
`).map(e=>e.trim()).filter(Boolean),E=null;for(let e=w.length-1;e>=0;e--)try{E=JSON.parse(w[e]);break}catch{}E===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:vl}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,E,{handler:vl})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:vl,cause:e})}finally{Ge.release(Qc)}},{handler:vl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:vl})}),xl=`local-op-auth-repos`,Cl=withValidation(LocalOpAuthHostRequestSchema,Tl,{handler:xl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:xl})});async function Tl(e,t,s){let g=s.host??`github.com`;if(!Ge.tryAcquire($c)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:xl,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let S=createStreamingErrorWriter(t,xl),[w,...E]=ye,D=[...E,`auth`,`repos`,`--json`,`--host`,g],O=!1,k=``,j=spawn(w,D,withHiddenWindowsConsole({...Uc,env:{...process.env}})),F=setTimeout(()=>{j.kill(`SIGTERM`)},Bc);j.stdout.on(`data`,e=>{k+=e.toString(`utf-8`);let s=k.split(`
|
|
1946
|
+
`);k=s.pop()??``;for(let e of s){if(!e.trim())continue;let s=null;try{s=JSON.parse(e)}catch{}if(s&&s.type===`error`){S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof s.message==`string`?s.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),j.stderr.on(`data`,e=>{log$7.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),j.on(`close`,e=>{clearTimeout(F),O||(O=!0,e!==0&&!t.writableEnded&&S(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Ge.release($c))}),j.on(`error`,e=>{clearTimeout(F),O||(O=!0,t.writableEnded||(S(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),Ge.release($c))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Ge.release($c))})}let El=`local-op-auth-signout`,Dl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire(dl)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:El,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,S=[...s,`auth`,`signout`,`--host`,g];await new Promise((t,s)=>{let g=spawn(e,S,withHiddenWindowsConsole({...Wc,env:{...process.env}})),w=setTimeout(()=>{g.kill(`SIGTERM`)},3e4);g.on(`close`,()=>{clearTimeout(w),t()}),g.on(`error`,e=>{clearTimeout(w),s(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:El})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:El,cause:e})}finally{Ge.release(dl)}},{handler:El,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:El})}),Ol=`/api/local-op/auth/set-identity`,kl=`local-op-auth-set-identity`,jl=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!Ce){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:kl});return}if(!Ge.tryAcquire(Ol)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:kl,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(Ce,g,S),ve?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:kl})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:kl,cause:e})}finally{Ge.release(Ol)}},{handler:kl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:kl})});async function Ml(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Pl=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let S=s.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:S},{handler:`sync-trigger`}),g.trigger(S)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Fl(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Il=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=ve?.();if(!g){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:S,strategy:w,content:E}=s;try{await g.resolveConflict(S,w,E),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Ll(e,s){if(!checkLocalOpSecurity(e,s,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(s,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!Ce){errorResponse(s,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let g=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),S=g.searchParams.get(`file`);if(!S){errorResponse(s,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(S.includes(`..`)||S.startsWith(`/`)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let w=stripDocExtension(S),E=t.documents.get(w)?.getMap(`lifecycle`).get(`status`)===`conflict`,D=ve?.(),O=D?D.getConflicts().some(e=>e.file===S):!1;if(!E&&!O){errorResponse(s,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:S}});return}let k=g.searchParams.get(`source`),j=esm_default({baseDir:Ce,timeout:{block:15e3}});async function F(e){try{return{present:!0,content:await j.raw([`show`,`:${e}:${S}`])}}catch(t){let s=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(s))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:S,detail:s,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,g,w]=await Promise.all([F(1),F(2),F(3)]),E=e.present?e.content:``,D=w.present?w.content:``,O=g.present&&w.present?`both-modified`:!g.present&&w.present?`delete-modify`:g.present&&!w.present?`modify-delete`:`both-modified`,j=g.present?g.content:``,L=null;if(k===`ytext`){let e=stripDocExtension(S),s=t.documents.get(e);if(s){let t=s.getMap(`lifecycle`).get(`status`);if(L=typeof t==`string`&&t.length>0?t:null,O!==`delete-modify`){let t=Re?Re(e):null;t!==null&&!ytextHasConflictMarkers(t)?j=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(s,200,SyncConflictContentSuccessSchema,{file:S,base:E,ours:j,theirs:D,kind:O,lifecycleStatus:L},{handler:`sync-conflict-content`})}catch(e){errorResponse(s,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Rl(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let s=new URL(e.url??`/`,`http://localhost`),S=s.searchParams.get(`rootDir`)??void 0,w=s.searchParams.get(`packId`),E=coercePackId(w);if(w!==null&&w!==``&&E===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${w}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:g,rootDir:S,packId:E})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let zl=withValidation(SeedApplyRequestSchema,async(e,t,s)=>{let S=s.plan;if(!S||typeof S!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let w=S,E=s.packId,D=coercePackId(E);if(typeof E==`string`&&E.length>0&&D===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${E}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(w,{projectDir:g,packId:D})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function Bl(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let Vl=withValidation(InstallSkillRequestSchema,async(e,t,s)=>{if(s.out!==void 0&&!isSafeLocalPath(s.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...s.noOpen===void 0?{}:{noOpen:s.noOpen},...s.out===void 0?{}:{out:s.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function Hl(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Tt.probeAll)}catch(e){t.headersSent||(log$7.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}let Ul=withValidation(EmptyRequestSchema,async(e,t)=>{if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:de.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Wl(e,t,s){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let g;try{g=decodeURIComponent(s)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!g){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=de.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:jt(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:g,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function Gl(e,t,s=`path`,S=`folder-config`){let w=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(w.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${s}: must be project-root-relative.`,{handler:S}),null;let E=resolve(g),D=w===``?E:resolve(E,w);return D!==E&&!D.startsWith(`${E}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:S}),null):{folderRel:w,resolvedContentDir:E}}let Kl=/^[A-Za-z0-9_-]+$/;function ql(e,t,s=`template`){return!e||!Kl.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:s}),!1):!0}function Jl(e,t,s){let g=t===``?[]:t.split(`/`);for(let t=g.length;t>=0;t--){let S=t===0?``:g.slice(0,t).join(`/`),w=S===``?e:resolve(e,S);if(w!==e&&!w.startsWith(`${e}${sep}`))continue;let E=resolve(w,`.ok`,`templates`,`${s}.md`);if(existsSync(E))return{abs:E,folder:S,scope:t===g.length?`local`:`inherited`}}return null}function Yl(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[s,g]of Object.entries(e))g!==void 0&&(t[s]=g);return t}async function Xl(e,t){if(e.method===`GET`)return Zl(e,t);if(e.method===`PUT`)return Ql(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Zl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=Gl(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!s)return;let g=await enrichDirectory(s.folderRel,{projectDir:s.resolvedContentDir}),S=resolve(resolve(s.resolvedContentDir,s.folderRel,`.ok`),`frontmatter.yml`),w=null;if(existsSync(S))try{let e=(0,import_dist$1.parse)(await readFile$1(S,`utf-8`));w=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${S}: ${t}`),w=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:g,frontmatter_local:w},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),Ql=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let g=Gl(s.path,t,`path`,`folder-config-put`);if(!g)return;let S=[];if(s.frontmatter!==void 0){let w=applyFolderFrontmatterPatch({anchorDir:g.resolvedContentDir,folderRel:g.folderRel,patch:s.frontmatter});if(!w.ok){let e=w.error.code===`WRITE_ERROR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:w.error.message,{handler:`folder-config-put`,detail:w.error.code,cause:Error(w.error.message)});return}S.push({path:w.path,action:w.action}),w.action!==`noop`&&(Cs(e,xs(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Ts(`folder-config-put`))}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:S},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function $l(e,s,g,S){if(!s)return!1;let w=e===``?`.ok/templates/${s}`:`${e.replace(/\/$/,``)}/.ok/templates/${s}`,E=t.documents.get(w);return E&&isDocInConflict(E)?(respondDocInConflict(S,new DocInConflictError({file:`${w}.md`}),g),!0):!1}function eu(e,s,g){let S=t.documents.get(e);return S&&isDocInConflict(S)?(respondDocInConflict(g,new DocInConflictError({file:`${e}.md`}),s),!0):!1}let tu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=resolveProjectTemplates(resolve(g));successResponse(t,200,TemplatesListSuccessSchema,{templates:e.templates.map(e=>{let{scope:t,...s}=e;return s}),truncated:e.truncated},{handler:`templates-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list templates.`,{handler:`templates-list`,cause:e})}},{handler:`templates-list`,method:`GET`,skipBodyParse:!0});async function nu(e,t){if(e.method===`GET`)return iu(e,t);if(e.method===`PUT`)return au(e,t);if(e.method===`POST`)return su(e,t);if(e.method===`DELETE`)return ou(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let ru=e=>{let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{frontmatter:g,body:s}},iu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!ql(g,t,`template-get`))return;let S=Gl(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=Jl(E,w,g);if(!D){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${g}" not found for folder "${w||`.`}". Walked leaf → root.`});return}let{abs:O,folder:k,scope:j}=D,F=parseTemplateFile(await readFile$1(O,`utf-8`)),L=F.identity,B=F.starterContent;successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:L,body:B}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),au=withValidation(TemplatePutRequestSchema,async(e,t,g)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let S=g.name;if(!ql(S,t,`template-put`))return;let w=Gl(g.folder,t,`folder`,`template-put`);if(!w||$l(w.folderRel,S,`template-put`,t))return;let E=composeTemplateContent({name:S,body:typeof g.body==`string`?g.body:``,frontmatter:Yl(g.frontmatter)});if(!E.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}let D=resolve(w.resolvedContentDir,w.folderRel,`.ok`,`templates`,`${S}.md`),O=!existsSync(D),k=relative(w.resolvedContentDir,D).split(/[\\/]/).filter(Boolean).join(`/`),j=pu(w.folderRel,S),{agentId:F,agentName:L,colorSeed:B,clientName:H}=Qi(g),q=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H});q.dc.document.transact(()=>{composeAndWriteRawBody(q.dc.document,E.content,`agent`)},q.origin);let ee=await Ut(j);if(ee?.kind===`failure`){Wt(t,ee.failure,`template-put`);return}if(ee?.kind===`divergence`){Xt(t,`template-put`);return}Cs(e,xs(`template`,w.folderRel,S),`${O?`template-create`:`template-edit`}: ${k}`),await Ts(`template-put`),successResponse(t,200,TemplatePutSuccessSchema,{path:k,created:O,warnings:E.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),ou=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!ql(g,t,`template-delete`))return;let S=Gl(s.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!S)return;let w=s.searchParams,E=extractActorIdentity({agentId:w.get(`agentId`)??void 0,agentName:w.get(`agentName`)??void 0,colorSeed:w.get(`colorSeed`)??void 0,clientName:w.get(`clientName`)??void 0,clientVersion:w.get(`clientVersion`)??void 0,label:w.get(`label`)??void 0,summary:w.get(`summary`)??void 0},we);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if($l(S.folderRel,g,`template-delete`,t))return;await Br([pu(S.folderRel,g)],`deleted-upstream`);let D=applyTemplateDelete({projectDir:S.resolvedContentDir,folder:S.folderRel,name:g});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}D.existed&&(Cs(E,xs(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Ts(`template-delete`)),successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),su=withValidation(TemplateMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!ql(s.fromName,t,`template-move`)||!ql(s.toName,t,`template-move`))return;let g=Gl(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=Gl(s.toFolder,t,`folder`,`template-move`);if(!S||$l(g.folderRel,s.fromName,`template-move`,t))return;await Br([pu(g.folderRel,s.fromName)],`renamed`);let w=await applyTemplateMove({projectDir:g.resolvedContentDir,fromFolder:g.folderRel,fromName:s.fromName,toFolder:S.folderRel,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!w.ok){if(w.error.code===`TEMPLATE_NOT_FOUND`){let e=Jl(g.resolvedContentDir,g.folderRel,s.fromName);if(e?.scope===`inherited`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${s.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${g.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:w.error.message});return}if(w.error.code===`TEMPLATE_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,w.error.message,{handler:`template-move`,detail:w.error.code});return}let e=w.error.code===`WRITE_ERROR`||w.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:w.error.code,cause:Error(w.error.message)});return}let E=null;if(s.body!==void 0||s.frontmatter!==void 0){let e;if(typeof s.body==`string`)e=s.body;else try{e=instantiateDoc(readFileSync(resolve(S.resolvedContentDir,w.toPath),`utf-8`))}catch{e=null}if(e===null)E={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=applyTemplateWrite({projectDir:S.resolvedContentDir,folder:S.folderRel,name:s.toName,body:e,frontmatter:Yl(s.frontmatter)});t.ok||(E=t.error)}}if(Cs(e,xs(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Ts(`template-move`),fe?.(`files`),E){let e=E.code===`WRITE_ERROR`||E.code===`READ_FAILED`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${w.toPath}", but updating its content failed.`,{handler:`template-move`,detail:E.code,cause:Error(E.message)});return}successResponse(t,200,TemplateMoveSuccessSchema,{from:w.fromPath,to:w.toPath,committed:w.committed},{handler:`template-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),cu=500;function lu(e,t,s){return!e||e.length>64||!SKILL_NAME_REGEX.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:s}),!1):!0}function uu(e,t,s){let g=SkillScopeSchema.safeParse(e??`project`);return g.success?g.data:(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:s}),null)}let du=Te??homedir();function fu(e){return resolve(e===`global`?du:g,`.ok`,`skills`)}function pu(e,t){return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function mu(e){return e===`navigation`||e===`relevance`?e:void 0}function hu(e,t){return relative(t===`global`?du:g,e).split(/[\\/]/).filter(Boolean).join(`/`)}function gu(e){return e===`global`?du:Ce}async function _u(e,t){let s=await removeSkillInstall(e,t);return reverseProjectSkill(t,e,PROJECT_SKILL_EDITOR_IDS),s!==null}function vu(e,t){let s=[];if(!existsSync(e))return{skills:s,truncated:!1};let g;try{g=readdirSync(e,{withFileTypes:!0})}catch(g){return getLogger(`skills`).warn({err:g,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:s,truncated:!1}}let S=!1;for(let w of g.sort((e,t)=>e.name.localeCompare(t.name))){if(!w.isDirectory()||!SKILL_NAME_REGEX.test(w.name))continue;if(s.length>=500){S=!0;break}let g=resolve(e,w.name,`SKILL.md`);if(!existsSync(g))continue;let E,D;try{let{frontmatter:e}=ru(readFileSync(g,`utf-8`));typeof e.description==`string`&&(E=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(D=e.version)}catch{}s.push({name:w.name,...E===void 0?{}:{description:E},scope:t,path:hu(g,t),absolutePath:g,...D===void 0?{}:{installedVersion:D}})}return{skills:s,truncated:S}}let yu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=vu(fu(`project`),`project`),s=vu(fu(`global`),`global`),g=Ce?readInstalledSkills(Ce).skills:{},S=readInstalledSkills(du).skills,w=(e,t)=>e.skills.map(e=>{let s=t[e.name]?.hosts??[],g=computePackUpdateStatus(e.name,e.installedVersion);return{...e,installed:s.length>0,hosts:s,...g}});successResponse(t,200,SkillsListSuccessSchema,{skills:[...w(e,g),...w(s,S)],truncated:e.truncated||s.truncated},{handler:`skills-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list skills.`,{handler:`skills-list`,cause:e})}},{handler:`skills-list`,method:`GET`,skipBodyParse:!0});async function bu(e,t){if(e.method===`GET`)return Eu(e,t);if(e.method===`PUT`)return Du(e,t);if(e.method===`POST`)return ku(e,t);if(e.method===`DELETE`)return Ou(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let xu=object$1({managed:boolean().nullable(),importable:number().int().nonnegative()}),Su=()=>({managed:Ce?readSkillManagement(Ce)?.manageEditorSkills??null:null,importable:Ce?countImportableEditorSkills({projectDir:Ce,skillsRoot:fu(`project`)}):0}),Cu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}successResponse(t,200,xu,Su(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),wu=withValidation(object$1({manageEditorSkills:boolean()}),async(e,t,s)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await writeSkillManagement(Ce,{manageEditorSkills:s.manageEditorSkills,surface:`ui`}),s.manageEditorSkills){let e=await reconcileSkillInstalls({projectDir:Ce,skillsRoot:fu(`project`)});e.adopted.length+e.collided.length>0&&fe?.(`files`)}successResponse(t,200,xu,Su(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`});async function Tu(e,t){if(e.method===`GET`)return Cu(e,t);if(e.method===`PUT`)return wu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skills-management`,extraHeaders:{Allow:`GET, PUT`}})}let Eu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!lu(g,t,`skill-get`))return;let S=uu(s.searchParams.get(`scope`),t,`skill-get`);if(S===null)return;let w=fu(S),E=resolve(w,g,`SKILL.md`);if(!existsSync(E)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${g}" not found in ${S} scope.`});return}let{frontmatter:D,body:O}=ru(await readFile$1(E,`utf-8`));successResponse(t,200,SkillGetSuccessSchema,{skill:{name:g,scope:S,path:hu(E,S),frontmatter:{name:typeof D.name==`string`?D.name:g,description:typeof D.description==`string`?D.description:``},body:O,files:readSkillBundledFiles(resolve(w,g))}},{handler:`skill-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),Du=withValidation(SkillPutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!lu(g.name,t,`skill-put`))return;let S=composeSkillContent({name:g.name,body:typeof g.body==`string`?g.body:``,frontmatter:{name:g.frontmatter.name,description:g.frontmatter.description}});if(!S.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:S.error.code,cause:Error(S.error.message)});return}let w=fu(g.scope),E=resolve(w,g.name,`SKILL.md`),D=!existsSync(E),O=relative(w,E).split(/[\\/]/).filter(Boolean).join(`/`),k=skillLiveDocName(g.scope,g.name);if(eu(k,`skill-put`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Qi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-put`);return}if(q?.kind===`divergence`){Xt(t,`skill-put`);return}g.scope===`project`&&(Cs(e,xs(`skill`,``,g.name),`${D?`skill-create`:`skill-edit`}: ${O}`),await Ts(`skill-put`)),fe?.(`files`),successResponse(t,200,SkillPutSuccessSchema,{path:O,created:D,warnings:S.warnings},{handler:`skill-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),Ou=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!lu(g,t,`skill-delete`))return;let S=uu(s.searchParams.get(`scope`),t,`skill-delete`);if(S===null)return;let w=fu(S),E=s.searchParams,D=extractActorIdentity({agentId:E.get(`agentId`)??void 0,agentName:E.get(`agentName`)??void 0,colorSeed:E.get(`colorSeed`)??void 0,clientName:E.get(`clientName`)??void 0,clientVersion:E.get(`clientVersion`)??void 0,label:E.get(`label`)??void 0,summary:E.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Br([skillLiveDocName(S,g)],`deleted-upstream`);let O=applySkillDelete({skillsRoot:w,name:g});if(!O.ok){let e=O.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:O.error.code,cause:Error(O.error.message)});return}O.existed&&(S===`project`&&(Cs(D,xs(`skill`,``,g),`skill-delete: ${O.path}`),await Ts(`skill-delete`)),fe?.(`files`));let k=gu(S);k&&await _u(k,g),successResponse(t,200,SkillDeleteSuccessSchema,{existed:O.existed,path:O.path},{handler:`skill-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),ku=withValidation(SkillMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!lu(s.fromName,t,`skill-move`)||!lu(s.toName,t,`skill-move`))return;let g=fu(s.scope);await Br([skillLiveDocName(s.scope,s.fromName)],`renamed`);let S=await applySkillMove({skillsRoot:g,fromName:s.fromName,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!S.ok){if(S.error.code===`SKILL_NOT_FOUND`){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:S.error.message});return}if(S.error.code===`SKILL_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,S.error.message,{handler:`skill-move`,detail:S.error.code});return}let e=S.error.code===`MOVE_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:S.error.code,cause:Error(S.error.message)});return}let w=null,E=resolve(g,s.toName,`SKILL.md`),D=``,O=``;try{let e=ru(readFileSync(E,`utf-8`));D=e.body,typeof e.frontmatter.description==`string`&&(O=e.frontmatter.description)}catch{}let k=typeof s.body==`string`?s.body:D,j=s.frontmatter===void 0?O:s.frontmatter.description,F=applySkillWrite({skillsRoot:g,name:s.toName,body:k,frontmatter:{name:s.toName,description:j}});if(F.ok||(w=F.error),s.scope===`project`&&!w)try{Pu(g,s.fromName,s.toName)}catch(e){getLogger(`skill-move`).warn({err:e,fromName:s.fromName,toName:s.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let L=hu(resolve(g,s.fromName),s.scope),B=hu(resolve(g,s.toName),s.scope);s.scope===`project`&&(Cs(e,xs(`skill`,``,s.toName),`skill-rename: ${L} -> ${B}`,[{from:L,to:B}]),await Ts(`skill-move`));let H=gu(s.scope);if(H){let e=await removeSkillInstall(H,s.fromName);if(e){let t=resolvedHosts(e.hosts);reverseProjectSkill(s.fromName,H,t);let S=projectSkill(resolve(g,s.toName),s.toName,H,t);await recordSkillInstall(H,s.toName,{...e,hosts:S})}}if(fe?.(`files`),w){let e=w.code===`WRITE_ERROR`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${s.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:w.code,cause:Error(w.message)});return}successResponse(t,200,SkillMoveSuccessSchema,{from:L,to:B,committed:S.committed},{handler:`skill-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`});function Au(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function ju(e,t,s){return e===`project`&&t===`reference`&&s.toLowerCase().endsWith(`.md`)}function Mu(e,t){let s=t.replace(/\.md$/i,``);return`${projectSkillContentDocName(e).replace(/\/SKILL$/,``)}/${s}`}function Nu(e,t){let s=resolve(e,t,`references`);if(!existsSync(s))return[];let g=[],S=(e,t)=>{for(let s of readdirSync(e,{withFileTypes:!0})){let w=t?`${t}/${s.name}`:s.name;s.isDirectory()?S(resolve(e,s.name),w):s.isFile()&&s.name.toLowerCase().endsWith(`.md`)&&g.push(`references/${w}`)}};return S(s,``),g}function Pu(e,t,s){if(!ue)return;let g=(e,t,s)=>{let g;try{g=readFileSync(s,`utf-8`)}catch{ue.deleteDocument(e),de?.deleteDocument(e);return}ue.renameDocument(e,t,g),de?.renameDocument(e,t,g)};g(projectSkillContentDocName(t),projectSkillContentDocName(s),resolve(e,s,`SKILL.md`));for(let S of Nu(e,s))g(Mu(t,S),Mu(s,S),resolve(e,s,S));fe?.(`backlinks`),fe?.(`graph`)}let Fu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!lu(g,t,`skill-file-get`))return;let S=uu(s.searchParams.get(`scope`),t,`skill-file-get`);if(S===null)return;let w=s.searchParams.get(`path`)??``,E=Au(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let D=resolve(fu(S),g),O=resolve(D,w);if(O!==D&&!O.startsWith(`${D}${sep}`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let k=O,j=w;if(!existsSync(k)){let e=w.match(/^(.*)\.(?:md|mdx)$/),s=e?SUPPORTED_DOC_EXTENSIONS.map(t=>`${e[1]}${t}`).find(e=>e!==w&&existsSync(resolve(D,e))):void 0;if(s===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${w} not found in skill "${g}" (${S}).`});return}j=s,k=resolve(D,s)}let F=await readFile$1(k);if(F.includes(0)){errorResponse(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}successResponse(t,200,SkillFileGetSuccessSchema,{path:j.replace(/\\/g,`/`),kind:E,text:F.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),Iu=withValidation(SkillFilePutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!lu(g.name,t,`skill-file-put`))return;let S=Au(g.path);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(g.content,`utf-8`)>262144){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let w=fu(g.scope);if(!existsSync(resolve(w,g.name,`SKILL.md`))){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${g.name}" before adding bundle files.`});return}let E=g.path.replace(/\\/g,`/`),D=ju(g.scope,S,E),O;if(D){let e=Mu(g.name,E);if(eu(e,`skill-file-put`,t))return;if(O=!existsSync(resolve(w,g.name,E)),O&&countBundleFiles(resolve(w,g.name))>=50){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${g.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:S,agentName:D,colorSeed:k,clientName:j}=Qi(g),F=await s.getSession(e,S,{displayName:D,colorSeed:k,clientName:j});F.dc.document.transact(()=>{composeAndWriteRawBody(F.dc.document,g.content,`agent`)},F.origin);let L=await Ut(e);if(L?.kind===`failure`){Wt(t,L.failure,`skill-file-put`);return}if(L?.kind===`divergence`){Xt(t,`skill-file-put`);return}}else{let e=applySkillBundleFileWrite({skillsRoot:w,name:g.name,relPath:E,content:g.content});if(!e.ok){let s=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;errorResponse(t,s,s===500?`urn:ok:error:internal-server-error`:s===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,s===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}O=e.created}g.scope===`project`&&(Cs(e,xs(`skill`,``,g.name),`${O?`skill-file-create`:`skill-file-edit`}: .ok/skills/${g.name}/${E}`),await Ts(`skill-file-put`)),fe?.(`files`),successResponse(t,200,SkillFilePutSuccessSchema,{path:E,created:O,kind:S,content:D},{handler:`skill-file-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),Lu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams,g=s.get(`name`)??``;if(!lu(g,t,`skill-file-delete`))return;let S=uu(s.get(`scope`),t,`skill-file-delete`);if(S===null)return;let w=(s.get(`path`)??``).replace(/\\/g,`/`),E=Au(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let D=extractActorIdentity({agentId:s.get(`agentId`)??void 0,agentName:s.get(`agentName`)??void 0,colorSeed:s.get(`colorSeed`)??void 0,clientName:s.get(`clientName`)??void 0,clientVersion:s.get(`clientVersion`)??void 0,label:s.get(`label`)??void 0,summary:s.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let O=fu(S);ju(S,E,w)&&await Br([Mu(g,w)],`deleted-upstream`);let k=applySkillBundleFileDelete({skillsRoot:O,name:g,relPath:w});if(!k.ok){let e=k.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:k.error.code,cause:Error(k.error.message)});return}k.existed&&S===`project`&&(Cs(D,xs(`skill`,``,g),`skill-file-delete: .ok/skills/${g}/${w}`),await Ts(`skill-file-delete`)),k.existed&&fe?.(`files`),successResponse(t,200,SkillFileDeleteSuccessSchema,{path:w,existed:k.existed,kind:E},{handler:`skill-file-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0});async function Ru(e,t){if(e.method===`GET`)return Fu(e,t);if(e.method===`PUT`)return Iu(e,t);if(e.method===`DELETE`)return Lu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-file`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let zu=withValidation(SkillInstallRequestSchema,async(e,t,s)=>{try{let e=fu(s.scope);if(!lu(s.name,t,`skill-install`))return;if(s.scope===`project`&&!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let g=gu(s.scope),S=resolve(e,s.name);if(!existsSync(S)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${s.name}" not found in ${s.scope} scope — create it with write({ skill }) first.`});return}let w=validateSkillForInstall(S,s.name);if(!w.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${s.name}" cannot be installed: ${w.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let E=s.scope===`global`?s.targets?PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)):[...PROJECT_SKILL_EDITOR_IDS]:s.targets===void 0?resolveSkillTargets(g,readSkillTargets(g)??void 0):PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)),D=[],O=[];E.length===0&&s.targets===void 0&&(D.push(s.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),O.push(`no-targets`)),w.hasScripts&&(D.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),O.push(`scripts-present`));let k=resolvedHosts(readInstalledSkills(g).skills[s.name]?.hosts??[]).filter(e=>!E.includes(e));k.length>0&&reverseProjectSkill(s.name,g,k);let j=projectSkill(S,s.name,g,E);j.length===0?await removeSkillInstall(g,s.name):await recordSkillInstall(g,s.name,{hosts:j,scope:s.scope,scripts:w.hasScripts,installedAt:new Date().toISOString()}),fe?.(`files`),successResponse(t,200,SkillInstallSuccessSchema,{name:s.name,hosts:j,scripts:w.hasScripts,warnings:D,warningCodes:O},{handler:`skill-install`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Bu=withValidation(SkillUninstallRequestSchema,async(e,t,s)=>{try{if(!lu(s.name,t,`skill-uninstall`))return;let e=gu(s.scope);if(!e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let g=await _u(e,s.name);fe?.(`files`),successResponse(t,200,SkillUninstallSuccessSchema,{name:s.name,uninstalled:g},{handler:`skill-uninstall`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`});async function Vu(e,t){if(e.method===`GET`)return Hu(e,t);if(e.method===`PUT`)return Uu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-targets`,extraHeaders:{Allow:`GET, PUT`}})}let Hu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=Ce?readSkillTargets(Ce):null;successResponse(t,200,SkillTargetsGetSuccessSchema,{targets:resolveSkillTargets(Ce??``,e??void 0),configured:e!==null},{handler:`skill-targets-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),Uu=withValidation(SkillTargetsPutRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let e=s.targets,g=new Set(e),S=resolveSkillTargets(Ce,readSkillTargets(Ce)??void 0),w=fu(`project`);await writeSkillTargets(Ce,e);let{reprojected:E,bundleHosts:D}=await reprojectAllManagedSkills({projectDir:Ce,skillsRoot:w,targets:e});fe?.(`files`),successResponse(t,200,SkillTargetsPutSuccessSchema,{targets:e,reprojected:E,bundleHosts:D,removedFrom:S.filter(e=>!g.has(e))},{handler:`skill-targets-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`}),Wu=withValidation(SkillRestoreRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!lu(s.name,t,`skill-restore`))return;if(s.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let S=ee?.current;if(!S){errorResponse(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let w=await restoreSkillVersion({shadow:S,contentDir:g,contentRoot:ce??`.`,name:s.name,version:s.version});if(!w.ok){let[e,s]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[w.code];errorResponse(t,e,s,w.error,{handler:`skill-restore`,detail:w.code});return}let E=[],D=validateSkillForInstall(resolve(g,`.ok`,`skills`,s.name),s.name);D.ok||E.push(`Restored, but the skill no longer validates: ${D.errors.join(` `)}`),E.push("Run `install` to push the restored version to your editors."),Cs(e,xs(`skill`,``,s.name),`skill-restore: ${s.name} @ ${s.version.slice(0,8)}`),await Ts(`skill-restore`),fe?.(`files`),successResponse(t,200,SkillRestoreSuccessSchema,{name:s.name,version:s.version,restoredFiles:w.restoredFiles,warnings:E},{handler:`skill-restore`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Gu=withValidation(SkillUpdateRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!lu(g.name,t,`skill-update`))return;if(!isPackSkillName(g.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(g.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let S=readBundledPackSkill(g.name);if(S===null||S.version===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let w=resolve(fu(`project`),g.name,`SKILL.md`);if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let E;try{E=readSkillVersion(readFileSync(w,`utf-8`))}catch{}let D,O=ee?.current;if(O)try{let e=oe?.()??`main`;D=(await saveVersion(O,ce??`.`,[SERVICE_WRITER],e,`Before updating ${g.name} (${E??`unversioned`} → ${S.version})`)).checkpointRef}catch(e){getLogger(`skills`).warn({err:e,skill:g.name},`pre-update checkpoint failed — proceeding with overwrite`)}let k=skillLiveDocName(`project`,g.name);if(eu(k,`skill-update`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Qi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-update`);return}if(q?.kind===`divergence`){Xt(t,`skill-update`);return}Cs(e,xs(`skill`,``,g.name),`skill-pack-update: ${g.name} (${E??`unversioned`} → ${S.version})`),await Ts(`skill-update`),fe?.(`files`),successResponse(t,200,SkillUpdateSuccessSchema,{name:g.name,version:S.version,...E===void 0?{}:{previousVersion:E},...D===void 0?{}:{checkpointRef:D}},{handler:`skill-update`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function Ku(e){let t=new Map;for(let s of e){let e=s.path.split(`/`).filter(Boolean);e.pop();for(let g=1;g<=e.length;g++){let S=e.slice(0,g).join(`/`);t.set(S,Math.max(t.get(S)??0,s.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function qu(e,t){let s=t.trim().toLowerCase();if(!s||!e)return;let g=e.toLowerCase().indexOf(s);if(g<0)return;let S=Math.max(0,g-80),w=Math.min(e.length,g+s.length+120),E=S>0?`…`:``,D=w<e.length?`…`:``;return`${E}${e.slice(S,w).replace(/\s+/g,` `).trim()}${D}`.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,`�`)}function Ju(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Yu(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let s=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return s.length>0?s:void 0}function Xu(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Zu(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function Qu(e,t,s,g){let S=g.documents.filter(e=>!isHiddenDocName(e.path)),w=S.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!Be?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:w,capable:!1};Be.embedCorpus(S);let E,D=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await Be.queryScores(e,S);if(D=performance.now()-t,s&&s.size>0){let e=Ve?.();E=e===void 0?{scores:s}:{scores:s,similarityFloor:e}}}let O=Be.getStatus();return{input:E,status:{capable:O.capable,applied:!1,coverage:{embedded:O.embeddedCount,total:w}},queryEmbedMs:D,pageTotal:w,capable:O.capable}}function $u(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`?qu(e.document.content,t):void 0}}async function ed(e){let t=performance.now();if(ud())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:s,truncated:g}=await dd(),S=await Qu(e.query,e.intent,e.semanticParam,s),w=searchWorkspaceCorpus(s,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:S.input}).map(t=>$u(t,e.query)),E;if(S.status){let t=w.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),s=t>0;E={...S.status,applied:s},recordSemanticQuery({outcome:S.capable?s?`applied`:S.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:S.capable,embedded:S.status.coverage.embedded,total:S.pageTotal,queryEmbedMs:S.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:w,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...E?{semantic:E}:{},...g?{truncated:!0}:{}}}function td(){let e=fu(`project`);if(!existsSync(e))return[];let t;try{t=readdirSync(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let g of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!g.isDirectory()||!SKILL_NAME_REGEX.test(g.name))continue;let t=resolve(e,g.name,`SKILL.md`);try{let e=statSync(t);s.push({name:g.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return s}function nd(){let e=[];for(let t of td()){let s=t.name,g=``;try{let{frontmatter:e,body:S}=ru(readFileSync(t.absolutePath,`utf-8`));typeof e.name==`string`&&e.name&&(s=e.name),g=`${typeof e.description==`string`?e.description:``}\n\n${S}`.trim()}catch{}e.push(createWorkspaceSearchDocument({kind:`page`,path:skillLiveDocName(`project`,t.name),title:s,content:g,modifiedTs:t.mtimeMs}))}return e}function rd(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let ad=new Map;async function od(){let e=[],t=[],s=new Set;for(let[g,S]of D()){if(isSystemDoc(g)||isConfigDoc(g)||g.startsWith(`.ok/skills/`))continue;if(S.kind===`file`){t.push(createWorkspaceSearchDocument({kind:`file`,path:g,modifiedTs:Date.parse(S.modified),aliases:S.aliases}));continue}s.add(g);let w=rd(S),E=ad.get(g);if(E&&E.key===w){e.push(E.doc);continue}let D=``,O=g,k=!1;try{D=await readFile$1(S.canonicalPath,`utf-8`)}catch(e){k=!0,console.warn(`[search] Failed to read ${g}:`,e)}if(!k)try{O=extractPageTitle(D,g)}catch(e){console.warn(`[search] Failed to extract title for ${g}:`,e)}let j=createWorkspaceSearchDocument({kind:`page`,path:g,title:O,content:D,modifiedTs:Date.parse(S.modified),aliases:S.aliases});k||ad.set(g,{key:w,doc:j}),e.push(j)}for(let e of ad.keys())s.has(e)||ad.delete(e);let g=getSearchMaxEntries(),S=t,w=!1;return t.length>g&&(w=!0,S=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,g),getLogger(`search`).warn({dropped:t.length-S.length,retained:S.length,limit:g},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),searchCorpusTruncatedCounter().add(1)),{documents:[...e,...nd(),...S,...Ku([...e,...S])],truncated:w}}function sd(){return td().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function cd(){return k?`gen:${k()}|skills${sd()}`:`${[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${rd(t)}`).join(``)}|skills${sd()}`}let ld=Pe===void 0;Pe?.then(()=>{ld=!0},e=>{ld=!0,log$7.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function ud(){return!ld}async function dd(){let e=`${g}${Ce??``}`,t=cd(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return{corpus:s.corpus,truncated:s.truncated??!1};if(s?.fingerprint===t&&s.pending)return s.pending;let S=od().then(({documents:e,truncated:t})=>({corpus:createWorkspaceSearchCorpus(e),truncated:t}));workspaceSearchCaches.set(e,{fingerprint:t,pending:S});try{let s=await S;return workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:s.corpus,truncated:s.truncated}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function fd(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{dd().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}fd();async function pd(e,t){if(e.method===`GET`)return md(e,t);if(e.method===`POST`)return hd(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let md=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=Ju(s.searchParams.get(`intent`)),E=mu(s.searchParams.get(`ranking`)),D=Yu(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),O=Xu(s.searchParams.get(`semantic`)),k=Zu(s.searchParams.get(`source`)),j=g===null?void 0:Number(g);if(S.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{successResponse(t,200,SearchSuccessSchema,await ed({query:S,intent:w,ranking:E,scopes:D,limit:j,semanticParam:O,source:k}),{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),hd=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=Ju(s.intent),w=mu(s.ranking),E=Yu(s.scopes??s.scope),D=typeof s.limit==`number`?s.limit:void 0,O=Xu(s.semantic),k=Zu(s.source);if(g.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{successResponse(t,200,SearchSuccessSchema,await ed({query:g,intent:S,ranking:w,scopes:E,limit:D,semanticParam:O,source:k}),{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),gd=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function _d(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform,isSchemeRegistered:Tt.probeWithCache})}catch(e){t.headersSent||(log$7.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function vd(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$7.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let yd=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!Ce){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=s.kind===`doc`?s.docPath:s.folderPath;if(!isValidSharePath(e,s.kind)){emitShareConstructUrlLog(`invalid-path`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let S=readGitHeadBranch(Ce);if(S===null){if(readOriginGitHubRepo(Ce).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=readOriginGitHubRepo(Ce);if(w.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(w.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(Ce,S)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:S},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let E=toGitRelativePath(Ce,g);if(E===null)throw Error(`content dir is not contained within the project dir`);let D=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;E!==``&&D&&getLogger(`share`).warn({action:`construct-url`,kind:s.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let O;if(s.kind===`doc`)O=buildGitHubBlobUrl(w.owner,w.repo,S,s.docPath);else{let e=s.folderPath===``?E:s.folderPath;O=buildGitHubTreeUrl(w.owner,w.repo,S,e)}let k=`${SHARE_BASE_URL}${encodeShareUrl(O)}`,j=await computeShareFreshness(Ce,S,E===``?e:e===``?E:`${E}/${e}`,s.kind);emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind,freshness:j}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:k,sharedUrl:O,branch:S,freshness:j},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}),bd=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`branch`),S=s.searchParams.get(`path`),w=s.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!isValidBranchName(g)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoPath(S,w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(Ce,g,S,w),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),xd=withValidation(ShareTargetStatusRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}if(!isValidBranchInfoPath(s.path,s.kind)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}let e=toGitRelativePath(Ce,g);if(e===null)throw Error(`content dir is not contained within the project dir`);let S=e===``?s.path:s.path===``?e:`${e}/${s.path}`;successResponse(t,200,ShareTargetStatusResponseSchema,await computeShareTargetStatus(Ce,s.branch,S,s.kind),{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG,cause:e})}},{handler:SHARE_TARGET_STATUS_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}),Sd=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(Ce,s.branch,{fastForward:s.fastForward===!0})),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function Cd(e){let[t,...s]=ye,g=[...s,...e];return await new Promise((e,s)=>{let S=spawn(t,g,withHiddenWindowsConsole({...Uc,env:{...process.env}})),w=!1,E=setTimeout(()=>{w=!0,S.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),D=[],O=[];S.stdout.on(`data`,e=>D.push(e)),S.stderr.on(`data`,e=>O.push(e)),S.on(`close`,t=>{if(clearTimeout(E),w){s(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let g=Buffer.concat(D).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(O).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:g,code:t})}),S.on(`error`,e=>{clearTimeout(E),s(e)})})}let wd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Cd([`share`,`owners`,`--json`]),s=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,s.ok?`ok`:s.error,s.ok?{count:s.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,s,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),Td=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`owner`)??``,S=s.searchParams.get(`name`)??``;if(!isValidShareOwnerName(g)||!isValidShareRepoName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!Ge.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Cd([`share`,`name-check`,`--owner`,g,`--name`,S,`--json`]),s=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,s.ok?`ok`:s.error,s.ok?{available:s.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,s,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),Ed=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!Ce){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(s.owner)||!isValidShareRepoName(s.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!Ge.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,s.owner,`--name`,s.name,`--visibility`,s.visibility,`--project-dir`,Ce,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await Cd(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&ve?.()?.refreshRemote().catch(()=>{}),successResponse(t,200,SharePublishResponseSchema,S,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{Ge.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),Dd=withValidation(ClientLogsRequestSchema,async(e,t,s)=>{try{let e=getLogger(`renderer`);for(let t of s.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}successResponse(t,200,ClientLogsSuccessSchema,{accepted:s.entries.length},{handler:`client-logs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`client-logs`})}),Od=Ce?getLocalDir(Ce):null;async function kd(e,t){if(e.method===`DELETE`){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-config`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-config`});return}Od&&clearArmedPaneTarget(Od),t.setHeader(`Cache-Control`,`no-store`),t.statusCode=204,t.end();return}if(e.method===`GET`||e.method===`HEAD`){try{let s=e.headers.host,g={collabUrl:s?`ws://${s}/collab`:null,previewUrl:null,port:Od?readServerLock(Od)?.port??0:0,paneTarget:Od?readArmedPaneTarget(Od):null,singleFile:We};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}successResponse(t,200,ApiConfigSuccessSchema,g,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD, DELETE`}})}let Ad=`local-op-embeddings-set-key`,jd=`local-op-embeddings-clear-key`,Md=`/api/local-op/embeddings`,Nd=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Ge.tryAcquire(Md)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Ad,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(Ue).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:Ad,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Ad,cause:e})}finally{Ge.release(Md)}},{handler:Ad,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Ad})}),Pd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(Md)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:jd,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(Ue),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:jd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:jd,cause:e})}finally{Ge.release(Md)}},{handler:jd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:jd})}),Fd=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(Be){let t=Be.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(Ue).get(),D=process.env.OK_EMBEDDINGS_API_KEY??null,O=E?`file`:D?`env`:null,k=O!==null,j=E??D,F=j&&j.length>=8?j.slice(-4):null,L=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(L+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:k,keySource:O,keyHint:F,ready:s,capable:g,embedded:S,total:L},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Id={"/api/config":kd,"/api/asset":Cc,"/api/asset-text":Tc,"/api/document":Ns,"/api/documents":Ps,"/api/backlinks":Is,"/api/backlink-counts":Ls,"/api/forward-links":Rs,"/api/link-graph":ec,"/api/dead-links":rc,"/api/orphans":tc,"/api/hubs":nc,"/api/tags":Ul,"/api/pages":Fc,"/api/folder-config":Xl,"/api/template":nu,"/api/templates":tu,"/api/skill":bu,"/api/skill-file":Ru,"/api/skills":yu,"/api/skills/management":Tu,"/api/skill/install":zu,"/api/skill/uninstall":Bu,"/api/skill/restore":Wu,"/api/skill/update":Gu,"/api/skill-targets":Vu,"/api/search":pd,"/api/semantic-status":Fd,"/api/suggest-links":Ic,"/api/page-headings":jc,"/api/create-page":Oc,"/api/create-folder":kc,"/api/duplicate-path":Ac,"/api/rename-path":Mc,"/api/delete-path":Nc,"/api/trash/cleanup":Pc,"/api/upload":Lc,"/api/agent-write":Ds,"/api/agent-write-md":Os,"/api/frontmatter-patch":ks,"/api/agent-patch":ic,"/api/agent-undo":ac,"/api/agent-activity":oc,"/api/agent-burst-diff":sc,"/api/save-version":fc,"/api/history":pc,"/api/rollback":hc,"/api/metrics/reconciliation":gc,"/api/metrics/parse-health":_c,"/api/metrics/agent-presence":bc,"/api/__embed-detect":xc,"/api/server-info":vc,"/api/share/construct-url":yd,"/api/share/target-status":xd,"/api/git/branch-info":bd,"/api/git/checkout":Sd,"/api/share/publish/owners":wd,"/api/share/publish/name-check":Td,"/api/share/publish":Ed,"/api/principal":yc,"/api/rescue":Dc,"/api/workspace":Sc,"/api/sync/status":Ml,"/api/sync/trigger":Pl,"/api/sync/conflicts":Fl,"/api/sync/conflict-content":Ll,"/api/sync/resolve-conflict":Il,"/api/local-op/clone":Kc,"/api/local-op/ok-init":Xc,"/api/local-op/auth/login":gl,"/api/local-op/auth/status":yl,"/api/local-op/auth/repos":Cl,"/api/local-op/auth/signout":Dl,"/api/local-op/auth/set-identity":jl,"/api/local-op/embeddings/set-key":Nd,"/api/local-op/embeddings/clear-key":Pd,"/api/installed-agents":Hl,"/api/spawn-cursor":vd,"/api/handoff":_d,"/api/install-skill":Vl,"/api/skill/install-state":gd,"/api/seed/plan":Rl,"/api/seed/apply":zl,"/api/seed/packs":Bl,"/api/client-logs":Dd};q&&(Id[`/api/test-reset`]=lc,Id[`/api/test-flush-git`]=cc,Id[`/api/test-rescan-backlinks`]=uc,Id[`/api/test-rescan-files`]=dc);let Ld=new Set(`/api/upload./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),Rd=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let s=e.url?.split(`?`)[0];if(!s)return;let g=t=>{let s=e.headers[t];if(s!==void 0)return Array.isArray(s)?s.join(`, `):s};if(recordEmbedProbe({ts:Date.now(),url:s,method:e.method??``,ua:g(`user-agent`),origin:g(`origin`),referer:g(`referer`),host:g(`host`),remote:e.socket?.remoteAddress,secChUa:g(`sec-ch-ua`),secChUaMobile:g(`sec-ch-ua-mobile`),secChUaPlatform:g(`sec-ch-ua-platform`),secFetchSite:g(`sec-fetch-site`),secFetchDest:g(`sec-fetch-dest`),secFetchMode:g(`sec-fetch-mode`),secFetchUser:g(`sec-fetch-user`)}),s.startsWith(`/api/`)){let s=e.headers.origin;if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${CLIENT_VERSION_HEADER.protocol}, ${CLIENT_VERSION_HEADER.runtime}, ${CLIENT_VERSION_HEADER.kind}`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Ld.has(s)||Rd.some(e=>s.startsWith(e))){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(We&&s.startsWith(`/api/`)){let s=e.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!s.startsWith(`/api/`))return;let S=propagation.extract(context.active(),e.headers),w=e.method??`GET`,E=s;s.startsWith(`/api/history/`)?E=`/api/history/:sha`:s.startsWith(`/api/tags/`)?E=`/api/tags/:name`:Id[s]||(E=`/api/*`);let D=getTracer(),O=Date.now();await context.with(S,()=>D.startActiveSpan(`HTTP ${w} ${E}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_URL_PATH]:s,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async g=>{try{let S=Id[s],E=!1;if(S)E=!0,await S(e,t);else if(s.startsWith(`/api/history/`)){let g=decodeURIComponent(s.slice(13));g&&(E=!0,await mc(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await Wl(e,t,g))}E||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${w} ${s}`});let D=t.statusCode;g.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,D),D>=500&&g.setStatus({code:SpanStatusCode.ERROR,message:`status ${D}`})}catch(e){throw g.recordException(e),g.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E,cause:e}),e}finally{g.end();let e=(Date.now()-O)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:w,[ATTR_HTTP_ROUTE]:E,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedSingleDirBasenameIndex(e){let t;try{t=readdirSync(e.contentDir,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,e.contentDir);return}for(let s of t)s.isFile()&&isSupportedAssetFile(s.name,ASSET_EXTENSIONS)&&e.basenameIndex.add(s.name)}async function seedBasenameIndex(e){let t=e.contentDir,s=new Set;async function g(S){let w;try{w=await readdir(S,{withFileTypes:!0})}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`read-failed`,s,S);return}for(let E of w){let w=join(S,E.name),D=toPosix(relative(t,w));if(D.startsWith(`..`)||e.contentFilter?.isDirExcluded(D)&&E.isDirectory())continue;let O;try{O=await lstat(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`lstat-failed`,s,w);continue}if(O.isSymbolicLink()){let S;try{S=await realpath(w)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`realpath-failed`,s,w);continue}if(!isWithinDir(S,t)){e.onSkip?.(`symlink-escape`,void 0,w);continue}let E;try{E=await stat$1(S)}catch(t){let s=errnoCode(t);s!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,s,S);continue}if(s.has(E.ino))continue;s.add(E.ino),E.isDirectory()?await g(S):E.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D);continue}if(O.isDirectory()){if(s.has(O.ino))continue;s.add(O.ino),await g(w);continue}O.isFile()&&isSupportedAssetFile(w,LINKABLE_ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(D)&&e.basenameIndex.add(D)}}await g(t)}var AutoStartDisabledError=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const log$6=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$6.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$6.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$6.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,s,g=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:S}=await import(`./git-handle-DG8d2xCi-C_CAAChL.mjs`),w=S(this.projectDir,{credentialArgs:g});switch(t){case`mine`:await w.git.raw([`checkout`,`--ours`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`theirs`:await w.git.raw([`checkout`,`--theirs`,`--`,e]),await w.git.raw([`add`,`--`,e]);break;case`content`:{if(s===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),g=resolve(t,e);if(!isWithinDir(g,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(g,s,`utf-8`),await w.git.raw([`add`,`--`,e]);break}case`delete`:await w.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await w.git.raw([`commit`,`--no-edit`]),log$6.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let e=await listNames(w.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:s});g=e.length>0}catch(e){log$6.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}g||this.addConflict({file:e,detectedAt:s}),log$6.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let S=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${g?`unmerged files re-added`:`original file re-added`} — ${S}`,{cause:t})}}};const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,s=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,g=0,S=null,w=null,E=!1,D=!1;function O(){S!==null&&(t.clearTimeout(S),S=null),w!==null&&(t.clearTimeout(w),w=null)}function k(){O(),!(D||E)&&g===0&&(s>0&&s<e.thresholdMs&&(w=t.setTimeout(()=>{w=null,g===0&&!E&&e.log?.warn({msUntilShutdown:s,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-s)),S=t.setTimeout(()=>{if(S=null,!(D||E)&&g===0){E=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let j=(e,t)=>{e.url?.startsWith(`/collab`)&&(g++,O(),t.once(`close`,()=>{g--,g<0&&(g=0),g===0&&k()}))};return e.httpServer.on(`upgrade`,j),k(),{detach:()=>{D||(D=!0,e.httpServer.off(`upgrade`,j),O())}}}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function readRawSinkBlock(e){if(!existsSync(e))return{};let t;try{t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!isObject(t))return{};let s=t.telemetry;if(!isObject(s))return{};let g=s.localSink;return isObject(g)?g:{}}function readBoolean(e){return typeof e==`boolean`?e:void 0}function readPositiveNumber(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function readStringArray(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function readMaxBytes(e){if(isObject(e))return readPositiveNumber(e.maxBytes)}function resolveLocalSinkConfig(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=readRawSinkBlock(resolveConfigPath(`project`,e.projectDir)),s=readRawSinkBlock(resolveConfigPath(`project-local`,e.projectDir));if((readBoolean(s.enabled)??readBoolean(t.enabled)??!0)===!1)return null;let g=readMaxBytes(s.spans)??readMaxBytes(t.spans)??52428800,S=readMaxBytes(s.logs)??readMaxBytes(t.logs)??26214400,w=readStringArray(s.attributeDenylist)??readStringArray(t.attributeDenylist)??DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:g,attributeDenylist:w},logs:{projectDir:e.projectDir,maxBytes:S}}}const MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let s=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return s?s.slice(0,128):t}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let s=t.validateToolInput;if(typeof s!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,g){if(!e.inputSchema||!isZodSchema(e.inputSchema))return s.call(this,e,t,g);let S=await e.inputSchema.safeParseAsync(t);if(S.success)return S.data;let w=prettifyError(S.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${g}:\n${w}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const SPAWN_TIMEOUT_MS=2e3,LOCK_SCAN_MAX_DEPTH=3,LOCK_SCAN_MAX_ENTRIES=2e3,OK_LOCK_DIR_ARG_PREFIX=`--ok-lock-dir-b64=`,OK_PROJECT_PATH_ARG_PREFIX=`--ok-project-path=`,OK_PROCESS_PGREP_QUERY=`cli\\.mjs|open-knowledge|Open ?Knowledge(\\.app| Helper)|--ok-lock-dir-b64=|--ok-project-path=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`,OK_PROCESS_PATTERNS=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function isOkProcess(e){return OK_PROCESS_PATTERNS.some(t=>t.test(e))}function extractMarkedLockDir(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(OK_LOCK_DIR_ARG_PREFIX));if(t==null)return null;let s=t.slice(18);if(!s)return null;try{let e=Buffer.from(s,`base64url`).toString(`utf8`);return isAbsolute(e)?e:null}catch{return null}}function extractProjectPathArg(e){let t=e.indexOf(OK_PROJECT_PATH_ARG_PREFIX);if(t===-1)return null;let s=t+18,g=e.slice(s),S=g.search(/\s--/),w=(S===-1?g:g.slice(0,S)).trim();return w&&isAbsolute(w)?w:null}function parsePgrepOutput(e){let t=[];for(let s of e.split(`
|
|
1947
1947
|
`)){let e=s.trim();if(!e)continue;let g=e.indexOf(` `);if(g===-1)continue;let S=e.slice(0,g),w=e.slice(g+1),E=Number.parseInt(S,10);!Number.isNaN(E)&&isOkProcess(w)&&t.push({pid:E,command:w})}return t}function parsePsOutput(e){let t=[],s=e.split(`
|
|
1948
|
-
`);for(let e=1;e<s.length;e++){let g=s[e]?.trim();if(!g)continue;let S=g.indexOf(` `);if(S===-1)continue;let w=g.slice(0,S),E=g.slice(S+1).trim(),D=Number.parseInt(w,10);!Number.isNaN(D)&&isOkProcess(E)&&t.push({pid:D,command:E})}return t}async function findOkProcessEntries(){let e=spawnSync(`pgrep`,[`-a`,`-f`,OK_PROCESS_PGREP_QUERY],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});if(!(e.error!=null&&e.error.code===`ENOENT`)){let t=e.stdout??``,s=parsePgrepOutput(t);if(s.length>0||t.trim()===``)return s}let t=spawnSync(`ps`,[`-axo`,`pid,command`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});return t.error!=null||!t.stdout?[]:parsePsOutput(t.stdout)}function extractOkBinaryPath(e){let t=e.trim().split(/\s+/).filter(Boolean);for(let e of t){if(e.startsWith(`@`))continue;let t=basename(e);if(t===`open-knowledge`||t===`ok`||e.endsWith(`/packages/cli/src/cli.ts`)||e.endsWith(`/packages/cli/dist/cli.mjs`)||t===`cli.mjs`||t===`cli.ts`)return e}return null}function processCommand(e){let t=spawnSync(`ps`,[`-p`,String(e),`-o`,`command=`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});return t.error!=null||!t.stdout?null:t.stdout.trim()||null}function processUsage(e){let t=spawnSync(`ps`,[`-p`,String(e),`-o`,`%cpu=,%mem=`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});if(t.error!=null||!t.stdout)return null;let[s,g]=t.stdout.trim().split(/\s+/),S=Number.parseFloat(s??``),w=Number.parseFloat(g??``);return Number.isNaN(S)||Number.isNaN(w)?null:{cpuPercent:S,memPercent:w}}async function pidCwd(e){let t=spawnSync(`lsof`,[`-p`,String(e),`-a`,`-d`,`cwd`,`-Fn`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});if(t.error!=null)return null;let s=t.stdout??``;for(let e of s.split(`
|
|
1948
|
+
`);for(let e=1;e<s.length;e++){let g=s[e]?.trim();if(!g)continue;let S=g.indexOf(` `);if(S===-1)continue;let w=g.slice(0,S),E=g.slice(S+1).trim(),D=Number.parseInt(w,10);!Number.isNaN(D)&&isOkProcess(E)&&t.push({pid:D,command:E})}return t}async function findOkProcessEntries(){let e=spawnSync(`pgrep`,[`-a`,`-f`,OK_PROCESS_PGREP_QUERY],withHiddenWindowsConsole({encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS}));if(!(e.error!=null&&e.error.code===`ENOENT`)){let t=e.stdout??``,s=parsePgrepOutput(t);if(s.length>0||t.trim()===``)return s}let t=spawnSync(`ps`,[`-axo`,`pid,command`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS}));return t.error!=null||!t.stdout?[]:parsePsOutput(t.stdout)}function extractOkBinaryPath(e){let t=e.trim().split(/\s+/).filter(Boolean);for(let e of t){if(e.startsWith(`@`))continue;let t=basename(e);if(t===`open-knowledge`||t===`ok`||e.endsWith(`/packages/cli/src/cli.ts`)||e.endsWith(`/packages/cli/dist/cli.mjs`)||t===`cli.mjs`||t===`cli.ts`)return e}return null}function processCommand(e){let t=spawnSync(`ps`,[`-p`,String(e),`-o`,`command=`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS}));return t.error!=null||!t.stdout?null:t.stdout.trim()||null}function processUsage(e){let t=spawnSync(`ps`,[`-p`,String(e),`-o`,`%cpu=,%mem=`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS}));if(t.error!=null||!t.stdout)return null;let[s,g]=t.stdout.trim().split(/\s+/),S=Number.parseFloat(s??``),w=Number.parseFloat(g??``);return Number.isNaN(S)||Number.isNaN(w)?null:{cpuPercent:S,memPercent:w}}async function pidCwd(e){let t=spawnSync(`lsof`,[`-p`,String(e),`-a`,`-d`,`cwd`,`-Fn`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS}));if(t.error!=null)return null;let s=t.stdout??``;for(let e of s.split(`
|
|
1949
1949
|
`))if(e.startsWith(`n`)&&e.length>1)return e.slice(1);return null}function parseListeningPids(e){let t=[],s=e.split(`
|
|
1950
|
-
`);for(let e=1;e<s.length;e++){let g=s[e]?.trim();if(!g)continue;let S=g.split(/\s+/);if(S.length<2)continue;let w=Number.parseInt(S[1]??``,10);Number.isNaN(w)||t.push(w)}return[...new Set(t)]}function hasLockFile(e){return existsSync(join(e,`server.lock`))||existsSync(join(e,`ui.lock`))}function addLockDirsForCwd(e,t){for(let s of[join(t,`.ok`,`local`),join(t,`.ok`)])existsSync(s)&&hasLockFile(s)&&e.add(s)}function addLockDirsUnderCwd(e,t){let s=0,g=(t,S)=>{if(s>=LOCK_SCAN_MAX_ENTRIES||(s++,addLockDirsForCwd(e,t),S>=LOCK_SCAN_MAX_DEPTH))return;let w;try{w=readdirSync(t)}catch{return}for(let e of w){if(s>=LOCK_SCAN_MAX_ENTRIES)return;if(e===`node_modules`||e===`.git`||e===`Library`||e.startsWith(`.`)&&e!==`.ok`)continue;let w=join(t,e),E=!1;try{E=lstatSync(w).isDirectory()}catch{continue}E&&g(w,S+1)}};g(t,0)}async function discoverLockDirs(){let e=new Set,t=await findOkProcessEntries(),s=t.map(e=>pidCwd(e.pid)),g=await Promise.all(s);for(let s of t){let t=extractMarkedLockDir(s.command);t!=null&&existsSync(t)&&e.add(t);let g=extractProjectPathArg(s.command);g!=null&&addLockDirsForCwd(e,g)}for(let t of g)t!=null&&addLockDirsForCwd(e,t);let S=spawnSync(`lsof`,[`-iTCP`,`-sTCP:LISTEN`,`-nP`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});if(S.error==null&&S.stdout){let s=parseListeningPids(S.stdout),g=new Set(t.map(e=>e.pid)),w=s.filter(e=>!g.has(e)).map(e=>pidCwd(e)),E=await Promise.all(w);for(let t of E)t!=null&&addLockDirsForCwd(e,t)}(e.size===0||g.some(e=>e===`/`))&&addLockDirsUnderCwd(e,process.cwd());let w=new Map;for(let t of e)try{let e=await realpath(t);w.set(e,e)}catch{w.set(t,t)}return[...w.values()]}function isPathInside(e,t){if(e===t)return!0;let s=t.endsWith(sep)?t:t+sep;return e.startsWith(s)}function toDocName(e,t){return relative(e,t).split(sep).join(`/`).replace(/\.(md|mdx)$/i,``)}async function resolveOffCwdTarget(e,t){let s=await t.realpath(resolve(e)).catch(()=>resolve(e)),g=await t.discover(),S=await Promise.all(g.map(e=>t.inspect(e).catch(()=>null))),w=null;for(let e of S)e===null||!e.alive||isPathInside(s,e.contentDir)&&(w===null||e.contentDir.length>w.contentDir.length)&&(w=e);return w===null?null:{baseUrl:w.baseUrl,docName:toDocName(w.contentDir,s)}}function projectDirOfLockDir(e){return dirname(dirname(e))}function createOffCwdResolverDeps(){return{discover:()=>discoverLockDirs(),realpath:e=>realpath(e).catch(()=>e),inspect:async e=>{let t=projectDirOfLockDir(e),s;try{let e=resolve(t,readConfigSafely({absPath:resolveConfigPath(`project`,t),sideline:!1,warn:()=>{}}).value.content?.dir??`.`);s=await realpath(e).catch(()=>e)}catch(t){return process.stderr.write(`[off-cwd-resolver] skipping ${e} (config unreadable): ${t instanceof Error?t.message:String(t)}\n`),null}let g=readUiLock(e),S=g?.port??0,w=g!=null&&S>0&&isProcessAlive(g.pid);return{lockDir:e,contentDir:s,baseUrl:`http://localhost:${S}`,alive:w}}}}const DEFAULT_POLL_INTERVAL_MS=500,DEFAULT_TIMEOUT_MS=15e3,inflight=new Map;function ensureSingleFileSession(e,t){let s=t.sleep??(e=>new Promise(t=>setTimeout(t,e))),g=t.now??(()=>Date.now()),S=t.pollIntervalMs??DEFAULT_POLL_INTERVAL_MS,w=t.timeoutMs??DEFAULT_TIMEOUT_MS;return(async()=>{let E=await t.realpath(resolve(e)).catch(()=>resolve(e)),D=inflight.get(E);if(D)return D;let O=(async()=>{let e=()=>t.isServing(E).catch(()=>!1);if(await e())return!0;t.spawnSession(E);let D=g()+w;for(;g()<D;)if(await s(S),await e())return!0;return!1})().finally(()=>{inflight.delete(E)});return inflight.set(E,O),O})()}function createEnsureSingleFileSession(){let e={spawnSession:e=>{if(!isSupportedDocFile(e)||!existsSync(e))return;let t=process.argv[1];if(!t){process.stderr.write(`[ensure-single-file-session] process.argv[1] is empty — cannot spawn a single-file session
|
|
1951
|
-
`);return}let s={...process.env,OK_SINGLE_FILE_NO_OPEN:`1`,ELECTRON_RUN_AS_NODE:`1`};spawn(process.execPath,[t,e],{
|
|
1950
|
+
`);for(let e=1;e<s.length;e++){let g=s[e]?.trim();if(!g)continue;let S=g.split(/\s+/);if(S.length<2)continue;let w=Number.parseInt(S[1]??``,10);Number.isNaN(w)||t.push(w)}return[...new Set(t)]}function hasLockFile(e){return existsSync(join(e,`server.lock`))||existsSync(join(e,`ui.lock`))}function addLockDirsForCwd(e,t){for(let s of[join(t,`.ok`,`local`),join(t,`.ok`)])existsSync(s)&&hasLockFile(s)&&e.add(s)}function addLockDirsUnderCwd(e,t){let s=0,g=(t,S)=>{if(s>=LOCK_SCAN_MAX_ENTRIES||(s++,addLockDirsForCwd(e,t),S>=LOCK_SCAN_MAX_DEPTH))return;let w;try{w=readdirSync(t)}catch{return}for(let e of w){if(s>=LOCK_SCAN_MAX_ENTRIES)return;if(e===`node_modules`||e===`.git`||e===`Library`||e.startsWith(`.`)&&e!==`.ok`)continue;let w=join(t,e),E=!1;try{E=lstatSync(w).isDirectory()}catch{continue}E&&g(w,S+1)}};g(t,0)}async function discoverLockDirs(){let e=new Set,t=await findOkProcessEntries(),s=t.map(e=>pidCwd(e.pid)),g=await Promise.all(s);for(let s of t){let t=extractMarkedLockDir(s.command);t!=null&&existsSync(t)&&e.add(t);let g=extractProjectPathArg(s.command);g!=null&&addLockDirsForCwd(e,g)}for(let t of g)t!=null&&addLockDirsForCwd(e,t);let S=spawnSync(`lsof`,[`-iTCP`,`-sTCP:LISTEN`,`-nP`],withHiddenWindowsConsole({encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS}));if(S.error==null&&S.stdout){let s=parseListeningPids(S.stdout),g=new Set(t.map(e=>e.pid)),w=s.filter(e=>!g.has(e)).map(e=>pidCwd(e)),E=await Promise.all(w);for(let t of E)t!=null&&addLockDirsForCwd(e,t)}(e.size===0||g.some(e=>e===`/`))&&addLockDirsUnderCwd(e,process.cwd());let w=new Map;for(let t of e)try{let e=await realpath(t);w.set(e,e)}catch{w.set(t,t)}return[...w.values()]}function isPathInside(e,t){if(e===t)return!0;let s=t.endsWith(sep)?t:t+sep;return e.startsWith(s)}function toDocName(e,t){return relative(e,t).split(sep).join(`/`).replace(/\.(md|mdx)$/i,``)}async function resolveOffCwdTarget(e,t){let s=await t.realpath(resolve(e)).catch(()=>resolve(e)),g=await t.discover(),S=await Promise.all(g.map(e=>t.inspect(e).catch(()=>null))),w=null;for(let e of S)e===null||!e.alive||isPathInside(s,e.contentDir)&&(w===null||e.contentDir.length>w.contentDir.length)&&(w=e);return w===null?null:{baseUrl:w.baseUrl,docName:toDocName(w.contentDir,s)}}function projectDirOfLockDir(e){return dirname(dirname(e))}function createOffCwdResolverDeps(){return{discover:()=>discoverLockDirs(),realpath:e=>realpath(e).catch(()=>e),inspect:async e=>{let t=projectDirOfLockDir(e),s;try{let e=resolve(t,readConfigSafely({absPath:resolveConfigPath(`project`,t),sideline:!1,warn:()=>{}}).value.content?.dir??`.`);s=await realpath(e).catch(()=>e)}catch(t){return process.stderr.write(`[off-cwd-resolver] skipping ${e} (config unreadable): ${t instanceof Error?t.message:String(t)}\n`),null}let g=readUiLock(e),S=g?.port??0,w=g!=null&&S>0&&isProcessAlive(g.pid);return{lockDir:e,contentDir:s,baseUrl:`http://localhost:${S}`,alive:w}}}}const DEFAULT_POLL_INTERVAL_MS=500,DEFAULT_TIMEOUT_MS=15e3,SINGLE_FILE_SESSION_SPAWN_OPTIONS={detached:!0,stdio:`ignore`},inflight=new Map;function ensureSingleFileSession(e,t){let s=t.sleep??(e=>new Promise(t=>setTimeout(t,e))),g=t.now??(()=>Date.now()),S=t.pollIntervalMs??DEFAULT_POLL_INTERVAL_MS,w=t.timeoutMs??DEFAULT_TIMEOUT_MS;return(async()=>{let E=await t.realpath(resolve(e)).catch(()=>resolve(e)),D=inflight.get(E);if(D)return D;let O=(async()=>{let e=()=>t.isServing(E).catch(()=>!1);if(await e())return!0;t.spawnSession(E);let D=g()+w;for(;g()<D;)if(await s(S),await e())return!0;return!1})().finally(()=>{inflight.delete(E)});return inflight.set(E,O),O})()}function createEnsureSingleFileSession(){let e={spawnSession:e=>{if(!isSupportedDocFile(e)||!existsSync(e))return;let t=process.argv[1];if(!t){process.stderr.write(`[ensure-single-file-session] process.argv[1] is empty — cannot spawn a single-file session
|
|
1951
|
+
`);return}let s={...process.env,OK_SINGLE_FILE_NO_OPEN:`1`,ELECTRON_RUN_AS_NODE:`1`};spawn(process.execPath,[t,e],withHiddenWindowsConsole({...SINGLE_FILE_SESSION_SPAWN_OPTIONS,env:s})).unref()},isServing:async e=>await resolveOffCwdTarget(e,createOffCwdResolverDeps())!==null,realpath:e=>realpath(e).catch(()=>e)};return t=>ensureSingleFileSession(t,e)}const loggerContext=new AsyncLocalStorage;var McpLogger=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??randomUUID().slice(0,12),this.corrId=randomUUID().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,s={}){let g=t?{error:t instanceof Error?t.message:String(t),...s}:s;this.emit(`error`,e,g)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,s){let g={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...s},S=`${JSON.stringify(g)}\n`;process.stderr.write(S);let w=process.env.OK_LOG_FILE;if(w)try{appendFileSync(w,S)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function runWithMcpLogger(e,t){return loggerContext.run(e,t)}function getCurrentMcpLogger(){return loggerContext.getStore()}const REDACTED_STRING_KEYS=new Set([`find`,`markdown`,`replace`]),COMMON_ARRAY_KEYS=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],COMMON_SCALAR_KEYS=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isToolExtraLike(e){return isPlainObject(e)&&`requestId`in e}function summarizeStringForLog(e,t){if(REDACTED_STRING_KEYS.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
|
|
1952
1952
|
`).length};let s=e===`command`?240:120;return t.length<=s?t:{type:`string`,length:t.length,preview:`${t.slice(0,s)}...`}}function summarizeArgValue(e,t){if(t===null)return null;if(typeof t==`string`)return summarizeStringForLog(e,t);if(typeof t==`number`||typeof t==`boolean`)return t;if(Array.isArray(t))return{type:`array`,length:t.length};if(isPlainObject(t)){let e=Object.keys(t).sort();return{type:`object`,keyCount:e.length,keys:e.slice(0,12)}}if(t!==void 0)return{type:typeof t}}function summarizeArgsForLog(e,t){return isPlainObject(t)?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,summarizeArgValue(e,t)])):summarizeArgValue(e,t)}function summarizeStructuredContentForLog(e){let t={structuredKeys:Object.keys(e).sort()};for(let s of COMMON_SCALAR_KEYS)s in e&&(t[s]=e[s]);for(let s of COMMON_ARRAY_KEYS){let g=e[s];Array.isArray(g)&&(t[`${s}Count`]=g.length)}return`previewUrl`in e&&(t.previewUrl=e.previewUrl??null),`previewUrlSource`in e&&(t.previewUrlSource=e.previewUrlSource),Array.isArray(e.warnings)&&(t.warningsCount=e.warnings.length),isPlainObject(e.warning)&&(t.warning=!0,`previewUrl`in e.warning&&(t.warningPreviewUrl=e.warning.previewUrl??null)),t}function summarizeToolResultForLog(e){if(!isPlainObject(e))return{resultType:typeof e};let t={isError:e.isError===!0};return Array.isArray(e.content)&&(t.contentItems=e.content.length,t.contentTextChars=e.content.reduce((e,t)=>isPlainObject(t)&&typeof t.text==`string`?e+t.text.length:e,0)),isPlainObject(e.structuredContent)&&Object.assign(t,summarizeStructuredContentForLog(e.structuredContent)),t}function summarizeIdentityForLog(e){return{connectionId:e.connectionId.slice(0,8),displayName:e.displayName,...e.clientInfo?.name?{clientName:e.clientInfo.name}:{}}}function splitInvocationArgs(e){let t=e.at(-1);return isToolExtraLike(t)?{toolArgs:e.length>1?e[0]:void 0,extra:t}:{toolArgs:e[0],extra:void 0}}function wrapToolHandlerForLogging(e,t,s){let g=s.logger;return g?async(...S)=>{let w=g.child(),E=Date.now(),{toolArgs:D,extra:O}=splitInvocationArgs(S);w.info(`tool start`,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},...O?.sessionId?{transportSessionId:O.sessionId}:{},...s.identityRef?.current?{agent:summarizeIdentityForLog(s.identityRef.current)}:{},...D===void 0?{}:{args:summarizeArgsForLog(e,D)}});try{let s=await runWithMcpLogger(w,async()=>await t(...S));return w.info(`tool finish`,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},durationMs:Date.now()-E,result:summarizeToolResultForLog(s)}),s}catch(t){throw w.error(`tool error`,t,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},durationMs:Date.now()-E}),t}}:t}function createLoggedServer(e,t){if(!t.logger)return e;let s=e.tool.bind(e),g=e.registerTool,S=typeof g==`function`?g.bind(e):void 0,w=Object.create(e);return w.tool=((...e)=>{let g=String(e[0]),S=e.at(-1);if(typeof S!=`function`)return s(...e);let w=[...e];return w[w.length-1]=wrapToolHandlerForLogging(g,S,t),s(...w)}),S&&(w.registerTool=((e,s,g)=>typeof g==`function`?S(e,s,wrapToolHandlerForLogging(e,g,t)):S(e,s,g))),w}const DESCRIPTION$18=[`[Requires: Hocuspocus server] Save a project-wide checkpoint of every document — a single restore point you can return to.`,``,`**Parameters:**`,'- `summary` — Optional one-line label for the checkpoint (≤80 chars). Defaults to "Checkpoint version". Appears as the checkpoint subject in `history`. Avoid secrets or PII — persisted to git history.',``,"Returns `{ version }` — the 40-char checkpoint SHA. Find checkpoints later via `history`; restore a single doc with `restore_version({ document, version })`."].join(`
|
|
1953
1953
|
`);function register$18(e,t){e.registerTool(`checkpoint`,{description:DESCRIPTION$18,inputSchema:{summary:summaryArgSchema.describe(`Optional one-line label for the checkpoint (≤80 chars). Defaults to "Checkpoint version". Persisted to git history.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({version:string().describe(VERSION_FIELD_DESCRIBE),previewUrl:previewUrlOutputField.describe(`Always null — a checkpoint is project-wide, not scoped to one doc.`)})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{url:g}=s;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S=t.identityRef?.current,w=await httpPost(g,`/api/save-version`,{...e.summary===void 0?{}:{summary:e.summary},...S?{writers:[{id:`agent-${S.connectionId}`,name:S.displayName,email:`agent-${S.connectionId}@openknowledge.local`}]}:{}});if(!w.ok)return textResult(`Error: ${w.error}`,!0);let E=typeof w.checkpointRef==`string`?w.checkpointRef:``,D=E.split(`/`).pop()??``;return/^[0-9a-f]{40}$/i.test(D)?textPlusStructured(`Checkpoint saved. Version: ${D}`,{version:D,previewUrl:null}):textResult(`Error: checkpoint committed but the server returned no usable version ref ("${E}"). Find the latest checkpoint via \`history\`.`,!0)})}const DESCRIPTION$17=[`[Operates on disk; no running OK server required] Read the effective merged OpenKnowledge config (defaults → user → project).`,``,`Use this when you need to inspect the config mid-session — e.g., after a write that may have changed disk state, or to re-confirm the value of a field before reading it again.`,``,"Read returns the FULL merged config or a sub-tree when `key` is provided. There is no allowlist on reads — every field is readable.",``,"Note: the `server.*`, `mcp.*`, and `github.*` config sub-trees, plus `preview.baseUrl` and `preview.scriptSrc`, were removed; their values are now built-in constants in `@inkeep/open-knowledge-core` (or, for the preview iframe, a fixed open network policy). Reading those keys returns `exists: false`. (`appearance.preview.autoOpen` is still a live key.)",``,`**Parameters:**`,'- `key` (optional) — Dotted config key. `"content"` returns the content sub-tree; `"appearance.theme"` returns just that leaf. Omit for full config.',"- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
|
|
1954
1954
|
`),InputSchema$3={key:string().optional().describe(`Dotted config key (e.g. "appearance.theme"). Omit to return the full merged config.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$5=outputSchemaWithText({value:unknown().describe(`Resolved config value at the requested path (or full config).`),exists:boolean().optional().describe('Whether the requested path resolved to a value. `false` distinguishes "path absent" from "path explicitly set to null". Always emitted — `true` on a full-config read.'),key:string().optional().describe(`Echo of the requested dotted key (absent when reading the full config).`)});function readConfigPath(e,t){let s=e;for(let e of t){if(typeof s!=`object`||!s)return;s=s[e]}return s}function register$17(e,t){e.registerTool(`config`,{description:DESCRIPTION$17,inputSchema:InputSchema$3,outputSchema:OutputSchema$5,annotations:{readOnlyHint:!0,idempotentHint:!0}},async e=>{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!s.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${s.error}`}]};let g=e.key?e.key.split(`.`).filter(e=>e.length>0):[],S=g.length>0?readConfigPath(s.config,g):s.config;return g.length>0&&S===void 0?textPlusStructured(`(no value at ${e.key})`,{value:null,exists:!1,...e.key?{key:e.key}:{}}):textPlusStructured(JSON.stringify(S,null,2),{value:S,exists:!0,...e.key?{key:e.key}:{}})})}const DESCRIPTION$16=["[Requires: Hocuspocus server] Read GitHub-sync merge conflicts. Dispatches on `kind`:",``,'- `kind: "list"` — enumerate every doc currently tracked in a merge-conflict state. Returns `{ list: [{ file, detectedAt, ... }] }` (empty when none). The entry point to the resolve flow.','- `kind: "content"` — fetch the three merge stages for one `file`. Returns `{ content: { file, base, ours, theirs, shape, lifecycleStatus } }`. `ours` reflects the live Y.Text (what the human sees) when the doc is loaded server-side.',``,`**Parameters:**`,"- `kind` — `list` | `content`.",'- `file` — Required for `kind: "content"`. Relative path WITH the `.md`/`.mdx` extension (e.g. `notes/sso.md`) — git stages key on the exact path, so do NOT strip the extension.',``,"The `shape` field discriminates the conflict: `both-modified` (both sides edited), `delete-modify` (you deleted, they edited — `ours` empty), or `modify-delete` (you edited, they deleted — `theirs` empty). Use it to pick the `resolve_conflict` strategy."].join(`
|
|
@@ -3240,7 +3240,7 @@ Incremental by default — don't re-read the whole repo.
|
|
|
3240
3240
|
`),{asset:{ok:!0,...B?{src:B}:{},...H?{path:H}:{},...q?{deduped:q}:{}}})}async function handleSkillWrite(e,t,s,g,S){let w=g.identityRef?.current,E=e.description!==void 0,D=e.files??[];if(!E&&D.length===0)return textResult("Error: provide `description` (to author SKILL.md) and/or `files` (to write references/scripts) — a skill write with neither does nothing.",!0);if(e.body!==void 0&&!E)return textResult('Error: `body` updates SKILL.md, so it needs a `description` too. To write a reference, use `files: [{ path: "references/...", content }]` instead.',!0);for(let e of D){let t=resolveSkillFilePath(e.path);if(!t.ok)return textResult(`Error: ${t.error}`,!0)}let O=[],k=null;if(E&&(k=await writeSkill(s,{name:e.name,scope:e.scope,description:e.description,body:e.body,summary:t,identity:w,lockDir:S}),k.isError))return k;for(let g of D){let S=await writeSkillFile(s,{name:e.name,scope:e.scope,path:g.path,content:g.content,summary:t,identity:w}),E=S.structuredContent;if(S.isError)O.push({path:g.path,ok:!1,error:S.content[0]?.text??`write failed`});else{let e=E?.skill?.file??{};O.push({path:g.path,ok:!0,...typeof e.kind==`string`?{kind:e.kind}:{},...typeof e.created==`boolean`?{created:e.created}:{}})}}let j=O.filter(e=>e.ok).length,F=O.some(e=>!e.ok),L=k?.structuredContent??{},B=L.skill??{ok:!0},H={...L,skill:{...B,...D.length>0?{files:O}:{}}},q=[];if(E&&k&&q.push(k.content[0]?.text??``),D.length>0){q.push(`${j}/${D.length} bundle file(s) written.`);for(let e of O)q.push(e.ok?` ${e.path} (${e.kind??`file`})`:` Failed ${e.path}: ${e.error}`)}return textPlusStructured(q.filter(Boolean).join(`
|
|
3241
3241
|
`),H,F)}async function handleBatch(e,t,s,g,S,w,E){let D=[];for(let w of e)D.push(await writeOneDoc(w,t,s,g,S));let O=D.map(e=>{if(!e.ok)return{docName:e.docName,ok:!1,error:e.error};let t=resolvePreviewUrl(e.docName,{lockDir:w}),s=parseAdvisoryWarnings(e.raw.warnings),g=parseBrokenLinks(e.raw.brokenLinks);return{docName:e.docName,ok:!0,position:e.position,...t?{previewUrl:t.url}:{},...s?{warnings:s}:{},...e.templateHint?{templateHint:e.templateHint}:{},brokenLinks:g}}),k=O.filter(e=>e.ok).length,j=k===O.length,F=e.map((e,t)=>{let s=D[t];if(!s?.ok)return`Failed ${e.path}: ${s?.error??`unknown error`}`;if(emptyAppendNoOpNote(s.position,e.content))return`No change to ${e.path} — empty ${s.position}, document unchanged.`;let g=O[t],S=[`Wrote ${e.path} (${s.position}).`];if(g?.ok&&g.warnings&&S.push(...formatAdvisoryBriefs(g.warnings)),g?.ok){let e=formatBrokenLinkBrief(g.brokenLinks);e&&S.push(e)}return s.ok&&s.templateHint&&S.push(`ℹ ${s.templateHint.length} template${s.templateHint.length===1?``:`s`} available here (pass \`template\`).`),S.join(` `)}),L=e.flatMap((e,t)=>{let s=D[t];if(!s?.ok)return[];let g=frontmatterIgnoredNote(s.position,e.content);return[...g?[g]:[],...s.extensionNote?[s.extensionNote]:[]].map(t=>`${e.path} — ${t}`)}),B=[`${k}/${O.length} written.`,...F,...L].join(`
|
|
3242
3242
|
`),H={documents:O},q=D.find(e=>e.ok);return q&&q.raw.systemSubscriberCount===0&&(H.warning=buildPreviewAttachWarning(resolvePreviewUrl(q.docName,{lockDir:w}),E)),textPlusStructured(B,H,!j)}async function handleSingleDoc(e,t,s,g,S,w,E){let D=await writeOneDoc(e,t,s,g,S);if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.raw,k=resolvePreviewUrl(D.docName,{lockDir:w}),j=(typeof O.systemSubscriberCount==`number`?O.systemSubscriberCount:void 0)===0,F=Array.isArray(O.hints)?O.hints:void 0,L=O.summary&&typeof O.summary==`object`?O.summary:void 0,B=typeof L?.hint==`string`?L.hint:void 0,H=parseAdvisoryWarnings(O.warnings),q=parseBrokenLinks(O.brokenLinks),ee=[emptyAppendNoOpNote(D.position,e.content)??(D.fromTemplate===void 0?`Written successfully (${D.position}).`:`Written successfully (instantiated from template "${D.fromTemplate}").`)],J=frontmatterIgnoredNote(D.position,e.content);if(J&&ee.push(J),D.extensionNote&&ee.push(D.extensionNote),j&&!k&&ee.push(START_UI_TEXT_HINT),B&&ee.push(B),F)for(let e of F)e.message&&ee.push(e.message);H&&ee.push(...formatAdvisoryLines(H)),ee.push(...formatBrokenLinkLines(q)),D.templateHint&&ee.push(formatTemplateHintLine(D.templateHint));let Y=ee.join(`
|
|
3243
|
-
`),te={brokenLinks:q};return F&&(te.hints=F),L&&(te.summary=L),H&&(te.warnings=H),D.templateHint&&(te.templateHint=D.templateHint),textPlusStructured(Y,nestDocResult(k,j?buildPreviewAttachWarning(k,E):void 0,te))}function register(e,t){let s={path:string().describe('Document path. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup". An optional `.md`/`.mdx` suffix selects the file format (default `.md`); prefer the `extension` field for that. The docName itself is always extension-less.'),content:string().optional().describe("The full Markdown body. Mutually exclusive with `template`."),extension:DocExtensionArg.optional(),template:string().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:FrontmatterArg.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:PositionArg.optional()};e.registerTool(`write`,{description:DESCRIPTION,inputSchema:{document:object$1(s).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:object$1({path:string().describe(`Folder path. Example: "meetings".`),frontmatter:FrontmatterArg.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:object$1({path:string().describe(TEMPLATE_PATH_DESCRIBE),content:string().describe(TEMPLATE_CONTENT_DESCRIBE),frontmatter:object$1({title:string().min(1).describe(`Required — the label shown when an agent picks this template.`),description:string().optional().describe(`Optional — shown beside the title in the template menu.`),tags:array(string()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),skill:object$1({name:string().describe(SKILL_NAME_DESCRIBE),description:string().optional().describe(`${SKILL_DESCRIPTION_DESCRIBE} Optional when writing ONLY \`files\` into an existing skill (omit to leave SKILL.md untouched).`),body:string().optional().describe(SKILL_BODY_DESCRIBE),files:array(object$1({path:string().describe("Skill-relative path under `references/` or `scripts/`."),content:string().describe(`Full text of the bundle file.`)})).optional().describe(SKILL_FILES_DESCRIBE),scope:SkillScopeArg.optional()}).optional().describe('Create or overwrite an agent SKILL bundle (`.ok/skills/<name>/`). SKILL.md is authored via `description`+`body`; `references/**` and `scripts/**` via the `files` array. Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }'),asset:object$1({path:string().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:string().optional().describe(`Base64 of the binary. Use for small files.`),source:string().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:array(object$1({...s,summary:summaryArgSchema})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1({hints:looseObjectArray.optional().describe(`Server-provided write hints, when any.`),...documentResultBaseShape}).optional().describe("Single-document write result. Always present on a successful single-doc write — it carries `brokenLinks` (possibly `[]`) plus any `summary`/`hints`/`warnings`."),folder:object$1({ok:boolean(),path:string(),frontmatterError:string().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:object$1({ok:boolean(),path:string(),created:boolean().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),skill:object$1({ok:boolean(),path:string().optional(),created:boolean().optional().describe(`true if created, false if an existing skill was overwritten.`),files:looseObjectArray.optional().describe("Per-bundle-file results `{ path, kind, created, ok, error? }`.")}).optional().describe(`Skill-create result (SKILL.md and/or bundle files).`),asset:object$1({ok:boolean(),src:string().optional().describe(`The reference src to embed in a doc.`),path:string().optional(),deduped:boolean().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:looseObjectArray.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, brokenLinks, error? }`. `brokenLinks` (possibly `[]`) is present on each successful entry, same as a single-doc write."),previewUrl:previewUrlOutputField.optional(),previewUrlSource:previewUrlSourceField,warning:previewAttachWarningField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s,E=resolveLockDir(g),D=resolveContentDir(S,g),O=S.appearance.preview.autoOpen;if(e.documents!==void 0){let s=exactlyOneTargetError(e,[`document`,`folder`,`template`,`skill`,`asset`,`documents`]);return s?textResult(`Error: ${s}`,!0):w?handleBatch(e.documents,g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)}let k=exactlyOneTargetError(e,[`document`,`folder`,`template`,`skill`,`asset`]);return k?textResult(`Error: ${k}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?e.skill===void 0?handleAsset(e.asset,g,w,t):handleSkillWrite(e.skill,e.summary,w,t,E):handleTemplate(e.template,e.summary,w,t):handleFolder(e.folder,e.summary,w,t):w?handleSingleDoc({...e.document,summary:e.summary},g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)})}function registerAllTools(e,t){let s=t.logger,g=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),S=e=>async g=>{try{let S=await t.resolveCwd(g);return(getCurrentMcpLogger()??s)?.debug(`tool cwd resolved`,{tool:e,cwd:S,...g?{explicit:g}:{}}),S}catch(t){throw(getCurrentMcpLogger()??s)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...g?{explicit:g}:{}}),t}};register$13(g,{resolveCwd:S(`exec`),serverUrl:t.serverUrl,config:t.config}),register$1(g,{config:t.config,resolveCwd:S(`workflow`)}),register$4(g,{resolveCwd:S(`search`),config:t.config,serverUrl:t.serverUrl}),register$9(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`links`)}),register(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`write`),identityRef:t.identityRef}),register$14(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`edit`),identityRef:t.identityRef}),register$15(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`delete`),identityRef:t.identityRef}),register$8(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`move`),identityRef:t.identityRef}),register$10(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`install`),identityRef:t.identityRef}),register$11(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`history`)}),register$2(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`skills`)}),register$18(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`checkpoint`),identityRef:t.identityRef}),register$5(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`restore_version`),identityRef:t.identityRef}),register$7(g,{resolveCwd:S(`palette`),config:t.config}),register$17(g,{config:t.config,resolveCwd:S(`config`)}),register$12(g,{config:t.config,resolveCwd:S(`preview_url`),serverUrl:t.serverUrl,isDesktopTerminal:t.isDesktopTerminal,...t.serverUrl?{ensureSingleFileSession:createEnsureSingleFileSession()}:{}}),register$16(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`conflicts`)}),register$6(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`resolve_conflict`)}),register$3(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`share_link`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,s){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(s))}function createSessionServer(e,t,s){let g=e.config,S=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION});installPrettyZodErrors(S);let w=s??randomUUID(),E={current:{connectionId:w,displayName:w,colorSeed:w}};S.server.oninitialized=()=>{let e=S.server.getClientVersion(),t=sanitizeClientName(e?.name,w);E.current={connectionId:w,clientInfo:e?{name:t,version:e.version}:void 0,displayName:displayNameFromClientName(t),colorSeed:t}};let D=e.projectDir??e.contentDir;return registerAllTools(S,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return D;let t=resolveWithinRoot(D,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:g,identityRef:E}),{server:S,transport:t}}function createMcpHttpHandler(e){let t=new Map,s=e.sessionTtlMs??1800*1e3,g=e.maxSessions??100;async function S(s,g){let S=t.get(s);if(!S)return;t.delete(s),S.ttlTimer!==void 0&&clearTimeout(S.ttlTimer);let w=await Promise.allSettled([S.server.close(),S.transport.close()]);for(let t of w)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:s,reason:g},`MCP HTTP session close failed`);e.log?.info?.({sessionId:s,reason:g},`MCP HTTP session closed`)}function w(t,g){g.ttlTimer!==void 0&&clearTimeout(g.ttlTimer),g.ttlTimer=setTimeout(()=>{S(t,`ttl-expired`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},s),g.ttlTimer.unref?.()}return{async handle(s,E){let D=firstHeader(s.headers[`mcp-session-id`]);if(D){let e=t.get(D);if(!e){writePlain(E,404,`MCP session not found`);return}w(D,e),await e.transport.handleRequest(s,E);return}if(s.method!==`POST`){writePlain(E,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=g){e.log?.warn?.({activeSessions:t.size,maxSessions:g},`MCP HTTP session cap reached`),writePlain(E,503,`Too many active MCP sessions`);return}let O=firstHeader(s.headers[MCP_CONNECTION_ID_HEADER]),k=validateAgentId(O)??void 0;O!==void 0&&k===void 0&&e.log?.warn?.({headerLength:O.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let j=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableJsonResponse:!0,onsessioninitialized:async s=>{try{let g=createSessionServer(e,j,k);await g.server.connect(j),t.set(s,g),w(s,g),e.log?.info?.({sessionId:s},`MCP HTTP session initialized`)}catch(g){throw t.delete(s),e.log?.error?.({err:g,sessionId:s},`MCP HTTP session initialization failed`),g}}});j.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},j.onclose=()=>{let t=j.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}S(t,`transport-closed`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await j.handleRequest(s,E)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>S(e,`handler-close`)))}}}const DEFAULT_KEEPALIVE_GRACE_MS=1e4,MAX_COLLAB_MESSAGE_BYTES=1024*1024,MCP_CORS_HEADERS={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function mountMcpAndApi(e){let{httpServer:t,hocuspocus:s,mcpHttpHandler:g,log:S,sessionManager:w,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:O,contentAssetMiddleware:k,reactShellMiddleware:j,ephemeral:F}=e,L=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,B=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});B.on(`error`,e=>{S.error({err:e},`WebSocketServer error`)});let H=new Map,q=new Set,ee=new Set,J=!1;return t.on(`request`,(e,t)=>{let w=e.url?.split(`?`)[0];if(g!==void 0&&w===`/mcp`){let s=e.headers.origin,w=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`));for(let[e,s]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,s);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}g.handle(e,t).catch(e=>{S.error({err:e,sessionId:w},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(w?.startsWith(`/api/`)){s.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${w}`})}).catch(e=>{S.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let E=(s,g,w)=>{if(s===void 0){w();return}try{s(e,t,()=>{t.writableEnded||t.headersSent||w()})}catch(e){S.error({err:e},`Unhandled ${g} middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},D=s=>{if(F===!0&&k!==void 0&&(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host))){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`content-asset`});return}E(k,`content-asset`,s)},O=e=>E(j,`react-shell`,e),L=()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${w??`/`}`})};if(j!==void 0&&w?.startsWith(`/assets/`)){O(()=>D(L));return}if(k!==void 0||j!==void 0){D(()=>O(L));return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${w??`/`}`})}),t.on(`upgrade`,(e,t,g)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive socket error`)}),ee.add(t),t.once(`close`,()=>ee.delete(t)),B.handleUpgrade(e,t,g,t=>{let s=parseKeepaliveConnectionId(e.url);if(s){let e=H.get(s);e!==void 0&&(clearTimeout(e),H.delete(s),S.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&D){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),g=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);D.setPresence(toBroadcasterKey(s),{displayName:t.displayName,icon:e,color:g,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){S.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let g=setInterval(()=>{try{t.ping()}catch{}},3e4);g.unref?.();let k=s?setInterval(()=>{D?.bumpPresenceTs(toBroadcasterKey(s))},3e3):null;k?.unref?.(),t.on(`close`,()=>{if(clearInterval(g),k!==null&&clearInterval(k),!s)return;let e=setTimeout(()=>{if(H.delete(s),J)return;let e=(async()=>{S.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await w?.closeAllForAgent(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{E?.clearFocus(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{D?.clearPresence(toBroadcasterKey(s))}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await O?.onSessionClose()}catch(e){S.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();q.add(e),e.finally(()=>q.delete(e))},L);e.unref?.(),H.set(s,e),S.info({connectionId:s,graceMs:L},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`Upgrade socket error`)}),ee.add(t),t.once(`close`,()=>ee.delete(t)),B.handleUpgrade(e,t,g,t=>{let g=s.handleConnection(t,e),w=!1;t.on(`message`,e=>{if(w)return;let s=e.byteLength;if(s>MAX_COLLAB_MESSAGE_BYTES){w=!0,incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,bytes:s,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket message rejected before Yjs processing`),t.close(1009,`Message Too Big`);return}g.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{g.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`),t.terminate();return}handleCollabSocketError(e)||S.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:B,shutdown:async()=>{if(!J){J=!0;for(let e of ee)try{e.destroy()}catch{}ee.clear();for(let e of H.values())clearTimeout(e);H.clear(),q.size>0&&await Promise.allSettled(q)}}}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_KEEPALIVE_IDENTITY_LEN=256;function sanitizeIdentityField(e){return e===null||e.length===0||e.length>MAX_KEEPALIVE_IDENTITY_LEN||/[-]/.test(e)?null:e}function parseKeepaliveIdentity(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),s=sanitizeIdentityField(t.searchParams.get(`displayName`)),g=sanitizeIdentityField(t.searchParams.get(`clientName`)),S=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return s===null||g===null||S===null?null:{displayName:s,clientName:g,colorSeed:S}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`OpenKnowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var MissingOkConfigError=class extends Error{kind;projectDir;constructor(e,t,s){super(MISSING_OK_CONFIG_MESSAGE,s),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};async function startConfigFileWatcher(e,t){let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-D1eNAlbX.mjs`),S=dirname(e);try{tracedMkdirSync(S,{recursive:!0})}catch(e){e.code!==`EEXIST`&&s.warn({err:e,watchDir:S},`failed to create watch directory; watcher may be inert`)}let w=g(S,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==S&&t!==e});await new Promise(e=>{w.once(`ready`,e)});let E=null;try{E=readFileSync(e,`utf-8`)}catch{}let D=(g,S=!0)=>{if(g!==e)return;let w;try{w=readFileSync(g,`utf-8`)}catch(e){if(e.code===`ENOENT`){S&&s.debug({path:g},`config file disappeared between event and read; dropping`);return}s.warn({err:e,path:g},`config file read failed; dropping event`);return}if(w!==E){E=w;try{t(w)}catch(e){s.warn({err:e,path:g},`config file change handler threw`)}}},O=e=>D(e);w.on(`add`,O),w.on(`change`,O),w.on(`unlink`,t=>{t===e&&s.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),w.on(`error`,t=>{s.warn({err:t,watchDir:S,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let k=0,j=setInterval(()=>{k++,D(e,!1),k>=20&&clearInterval(j)},500);j.unref?.();let F=!1;return async()=>{F||(F=!0,clearInterval(j),await w.close())}}async function startMultiPathConfigFileWatcher(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-D1eNAlbX.mjs`),S=new Set(e),w=Array.from(new Set(Array.from(S,e=>dirname(e))));for(let e of w)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&s.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let E=g(w,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!S.has(e)&&!w.includes(e)});await new Promise(e=>{E.once(`ready`,e)});let D=new Map;for(let e of S)try{D.set(e,readFileSync(e,`utf-8`))}catch{D.set(e,null)}let O=(e,g=!0)=>{if(!S.has(e))return;let w;try{w=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g&&s.debug({path:e},`config file disappeared between event and read; dropping`);return}s.warn({err:t,path:e},`config file read failed; dropping event`);return}if(w!==D.get(e)){D.set(e,w);try{t(e,w)}catch(t){s.warn({err:t,path:e},`config file change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{S.has(e)&&s.debug({path:e},`config file unlinked; downstream state retained`)}),E.on(`error`,e=>{s.warn({err:e,watchDirs:w,paths:Array.from(S)},`[config-file-watcher] chokidar error in multi-path watcher`)});let j=0,F=setInterval(()=>{j++;for(let e of S)O(e,!1);j>=20&&clearInterval(F)},500);F.unref?.();let L=!1;return async()=>{L||(L=!0,clearInterval(F),await E.close())}}function entryMatchesDocName(e,t,s,g){let S=toPosix(relative(g,join(s,e.file)));return S.startsWith(`..`)?!1:stripDocExtension(S)===t}function createConflictLifecycleSeedExtension(e){let{getSyncEngine:t,projectDir:s,contentDir:g}=e;return{async afterLoadDocument({documentName:e,document:S}){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let w=t();if(!w)return;let E=w.getConflicts();if(E.length===0||!E.some(t=>entryMatchesDocName(t,e,s,g)))return;let D=S.getMap(`lifecycle`);if(D.get(`status`)===`conflict`)return;D.set(`status`,`conflict`),D.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){console.warn(`[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${e}):`,t instanceof Error?t:String(t))}}}}const execFileAsync$1=promisify(execFile),BUILTIN_SKIP_DIRS=new Set(`node_modules,.venv,venv,env,__pycache__,vendor,dist,build,out,output,.next,.nuxt,.svelte-kit,.astro,.turbo,.cache,.parcel-cache,coverage,.git,.ok,.open-knowledge,.openknowledge,.claude,.cursor,.codex,.agents,.opencode,.pi,Library,Applications,.Trash`.split(`,`)),ALWAYS_SKIP_DIRS=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`,`.claude`,`.cursor`,`.codex`,`.agents`,`.opencode`,`.pi`]);function pathHasAlwaysSkipSegment(e){for(let t of e.split(`/`))if(ALWAYS_SKIP_DIRS.has(t))return!0;return!1}function isSkillContentFile(e){return e.startsWith(`${SKILL_CONTENT_ROOT}/`)}function isSkillContentAncestorDir(e){return e===`.ok`||e===`.ok/skills`||e.startsWith(`.ok/skills/`)}function globBlocksSkillContent(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``).trim();return t===`.ok`||t===`.ok/**`||t===`**/.ok`||t===`**/.ok/**`}const BUILTIN_SKIP_FILES=new Set([`.DS_Store`,`.localized`]);function isAlwaysSkipFile(e){return BUILTIN_SKIP_FILES.has(e.slice(e.lastIndexOf(`/`)+1))}const SECRET_BEARING_DIRS=new Set([`.ssh`,`.aws`,`.gnupg`,`.kube`,`.docker`]);function pathHasSecretBearingDirSegment(e){for(let t of e.split(`/`))if(SECRET_BEARING_DIRS.has(t.toLowerCase()))return!0;return!1}const SECRET_CREDENTIAL_BASENAMES=new Set([`credentials`,`.netrc`,`.npmrc`,`.pgpass`,`.git-credentials`]),SECRET_KEY_SUFFIXES=[`.pem`,`.key`,`.p12`,`.pfx`,`.keystore`,`.jks`,`.ppk`];function isSecretBearingFile(e){let t=e.slice(e.lastIndexOf(`/`)+1).toLowerCase();if(t===`.env`||t.startsWith(`.env.`)||SECRET_CREDENTIAL_BASENAMES.has(t)||t.startsWith(`id_rsa`)||t.startsWith(`id_ed25519`)||t.startsWith(`id_ecdsa`)||t.startsWith(`id_dsa`))return!0;for(let e of SECRET_KEY_SUFFIXES)if(t.endsWith(e))return!0;return!1}function isSingleDocAncestorDir(e,t){return t===e||t.startsWith(`${e}/`)}const IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function loadGitExcludeSources(e,t){let s=readGitCommonDirSync(e);if(s===null)return[];let g=[];appendExcludeFileIfExists(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=resolveGlobalExcludesfileSync(e);return S&&appendExcludeFileIfExists(S,t,g,`global excludesfile`),g}async function loadGitExcludeSourcesAsync(e,t){let s=await readGitCommonDirAsync(e);if(s===null)return[];let g=[];await appendExcludeFileIfExistsAsync(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=await resolveGlobalExcludesfileAsync(e);return S&&await appendExcludeFileIfExistsAsync(S,t,g,`global excludesfile`),g}function readGitCommonDirSync(e){let t=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||!t.stdout?null:resolve(e,t.stdout.trim())}async function readGitCommonDirAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t?resolve(e,t.trim()):null}catch{return null}}function resolveGlobalExcludesfileSync(e){let t=spawnSync(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return xdgGlobalIgnoreDefault()}async function resolveGlobalExcludesfileAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=t.trim();if(s)return s}catch{}return xdgGlobalIgnoreDefault()}function xdgGlobalIgnoreDefault(){let e=process.env.XDG_CONFIG_HOME?.trim();return join(e&&e.length>0?e:join(homedir(),`.config`),`git`,`ignore`)}function appendExcludeFileIfExists(e,t,s,g){if(existsSync(e))try{let g=readFileSync(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}async function appendExcludeFileIfExistsAsync(e,t,s,g){if(existsSync(e))try{let g=await readFile$1(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}function createContentFilter(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=toPosix(relative(t,s)),E=w.startsWith(`..`),D,O,k,j=0,F=0,L=0;function B(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[],S=0,B=0;for(let s of IGNORE_FILE_NAMES){let w=join(t,s);if(existsSync(w))try{let t=readFileSync(w,`utf-8`);S+=t.length;let s=parseIgnorePatterns(t);g.push(...s),e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${w}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=readFileSync(g,`utf-8`);S+=t.length,B++;let s=parseIgnorePatterns(t).map(e=>prefixPattern(e,w));e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let H={value:S};B+=loadNestedIgnoreFiles(s,t,e,H),S=H.value;let q=loadGitExcludeSources(t,H);S=H.value,q.length>0&&(g.push(...q),e.add(q));let ee=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)&&!globBlocksSkillContent(e));return D=e,O=g,k=ee,j=g.length,F=B,L=S,{patternCount:j,nestedFileCount:F,bytes:L}}B();let H=new Map;function q(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}let ee=()=>{S===void 0&&populateDirCount(s,``,q,H)};ee();function J(e){return isReservedForUserTree(stripDocExtension(e))}function Y(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:q(e)}return{isExcluded(e,t){if(J(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e))return!0;if(!t?.bypassFilters&&isSkillContentFile(e)){if(S!==void 0)return e!==S;if(isSupportedDocFile(e))return!1;let t=extname(e).slice(1).toLowerCase();return!LINKABLE_ASSET_EXTENSIONS.has(t)}if(pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(Y(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((H.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasSecretBearingDirSegment(e))return!0;if(!t?.bypassFilters&&isSkillContentAncestorDir(e))return!1;if(pathHasAlwaysSkipSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return J(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e)?!0:isSkillContentFile(e)?!1:pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)?!0:t?.bypassFilters?!1:Y(e)},getWatcherIgnoreGlobs(){return k},incrementMdDir(e){let t=e===`.`?``:e;H.set(t,(H.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=H.get(t)??0;s<=1?H.delete(t):H.set(t,s-1)},rebuildDirCount(){let e=new Map(H);H.clear();try{ee()}catch(t){for(let[t,s]of e)H.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=k,w=j,E=F,q=L,J=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async Y=>{try{let t=B();H.clear(),ee();let s=Date.now()-J;if(Y.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s},`content-filter rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s}}catch(g){D=t,O=s,k=S,j=w,F=E,L=q,H.clear();try{ee()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let B=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(B)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:B}}}})}}}function populateDirCount(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let w of S){let S=t?`${t}/${w.name}`:w.name;if(w.isDirectory()){if(BUILTIN_SKIP_DIRS.has(w.name)||s(S)||s(`${S}/`))continue;populateDirCount(join(e,w.name),S,s,g)}else w.isFile()&&isSupportedDocFile(w.name)&&!s(S)&&g.set(t,(g.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
|
|
3243
|
+
`),te={brokenLinks:q};return F&&(te.hints=F),L&&(te.summary=L),H&&(te.warnings=H),D.templateHint&&(te.templateHint=D.templateHint),textPlusStructured(Y,nestDocResult(k,j?buildPreviewAttachWarning(k,E):void 0,te))}function register(e,t){let s={path:string().describe('Document path. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup". An optional `.md`/`.mdx` suffix selects the file format (default `.md`); prefer the `extension` field for that. The docName itself is always extension-less.'),content:string().optional().describe("The full Markdown body. Mutually exclusive with `template`."),extension:DocExtensionArg.optional(),template:string().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:FrontmatterArg.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:PositionArg.optional()};e.registerTool(`write`,{description:DESCRIPTION,inputSchema:{document:object$1(s).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:object$1({path:string().describe(`Folder path. Example: "meetings".`),frontmatter:FrontmatterArg.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:object$1({path:string().describe(TEMPLATE_PATH_DESCRIBE),content:string().describe(TEMPLATE_CONTENT_DESCRIBE),frontmatter:object$1({title:string().min(1).describe(`Required — the label shown when an agent picks this template.`),description:string().optional().describe(`Optional — shown beside the title in the template menu.`),tags:array(string()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),skill:object$1({name:string().describe(SKILL_NAME_DESCRIBE),description:string().optional().describe(`${SKILL_DESCRIPTION_DESCRIBE} Optional when writing ONLY \`files\` into an existing skill (omit to leave SKILL.md untouched).`),body:string().optional().describe(SKILL_BODY_DESCRIBE),files:array(object$1({path:string().describe("Skill-relative path under `references/` or `scripts/`."),content:string().describe(`Full text of the bundle file.`)})).optional().describe(SKILL_FILES_DESCRIBE),scope:SkillScopeArg.optional()}).optional().describe('Create or overwrite an agent SKILL bundle (`.ok/skills/<name>/`). SKILL.md is authored via `description`+`body`; `references/**` and `scripts/**` via the `files` array. Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }'),asset:object$1({path:string().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:string().optional().describe(`Base64 of the binary. Use for small files.`),source:string().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:array(object$1({...s,summary:summaryArgSchema})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1({hints:looseObjectArray.optional().describe(`Server-provided write hints, when any.`),...documentResultBaseShape}).optional().describe("Single-document write result. Always present on a successful single-doc write — it carries `brokenLinks` (possibly `[]`) plus any `summary`/`hints`/`warnings`."),folder:object$1({ok:boolean(),path:string(),frontmatterError:string().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:object$1({ok:boolean(),path:string(),created:boolean().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),skill:object$1({ok:boolean(),path:string().optional(),created:boolean().optional().describe(`true if created, false if an existing skill was overwritten.`),files:looseObjectArray.optional().describe("Per-bundle-file results `{ path, kind, created, ok, error? }`.")}).optional().describe(`Skill-create result (SKILL.md and/or bundle files).`),asset:object$1({ok:boolean(),src:string().optional().describe(`The reference src to embed in a doc.`),path:string().optional(),deduped:boolean().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:looseObjectArray.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, brokenLinks, error? }`. `brokenLinks` (possibly `[]`) is present on each successful entry, same as a single-doc write."),previewUrl:previewUrlOutputField.optional(),previewUrlSource:previewUrlSourceField,warning:previewAttachWarningField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s,E=resolveLockDir(g),D=resolveContentDir(S,g),O=S.appearance.preview.autoOpen;if(e.documents!==void 0){let s=exactlyOneTargetError(e,[`document`,`folder`,`template`,`skill`,`asset`,`documents`]);return s?textResult(`Error: ${s}`,!0):w?handleBatch(e.documents,g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)}let k=exactlyOneTargetError(e,[`document`,`folder`,`template`,`skill`,`asset`]);return k?textResult(`Error: ${k}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?e.skill===void 0?handleAsset(e.asset,g,w,t):handleSkillWrite(e.skill,e.summary,w,t,E):handleTemplate(e.template,e.summary,w,t):handleFolder(e.folder,e.summary,w,t):w?handleSingleDoc({...e.document,summary:e.summary},g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)})}function registerAllTools(e,t){let s=t.logger,g=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),S=e=>async g=>{try{let S=await t.resolveCwd(g);return(getCurrentMcpLogger()??s)?.debug(`tool cwd resolved`,{tool:e,cwd:S,...g?{explicit:g}:{}}),S}catch(t){throw(getCurrentMcpLogger()??s)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...g?{explicit:g}:{}}),t}};register$13(g,{resolveCwd:S(`exec`),serverUrl:t.serverUrl,config:t.config}),register$1(g,{config:t.config,resolveCwd:S(`workflow`)}),register$4(g,{resolveCwd:S(`search`),config:t.config,serverUrl:t.serverUrl}),register$9(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`links`)}),register(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`write`),identityRef:t.identityRef}),register$14(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`edit`),identityRef:t.identityRef}),register$15(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`delete`),identityRef:t.identityRef}),register$8(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`move`),identityRef:t.identityRef}),register$10(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`install`),identityRef:t.identityRef}),register$11(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`history`)}),register$2(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`skills`)}),register$18(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`checkpoint`),identityRef:t.identityRef}),register$5(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`restore_version`),identityRef:t.identityRef}),register$7(g,{resolveCwd:S(`palette`),config:t.config}),register$17(g,{config:t.config,resolveCwd:S(`config`)}),register$12(g,{config:t.config,resolveCwd:S(`preview_url`),serverUrl:t.serverUrl,isDesktopTerminal:t.isDesktopTerminal,...t.serverUrl?{ensureSingleFileSession:createEnsureSingleFileSession()}:{}}),register$16(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`conflicts`)}),register$6(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`resolve_conflict`)}),register$3(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`share_link`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,s){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(s))}function createSessionServer(e,t,s){let g=e.config,S=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION});installPrettyZodErrors(S);let w=s??randomUUID(),E={current:{connectionId:w,displayName:w,colorSeed:w}};S.server.oninitialized=()=>{let e=S.server.getClientVersion(),t=sanitizeClientName(e?.name,w);E.current={connectionId:w,clientInfo:e?{name:t,version:e.version}:void 0,displayName:displayNameFromClientName(t),colorSeed:t}};let D=e.projectDir??e.contentDir;return registerAllTools(S,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return D;let t=resolveWithinRoot(D,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:g,identityRef:E}),{server:S,transport:t}}function createMcpHttpHandler(e){let t=new Map,s=e.sessionTtlMs??1800*1e3,g=e.maxSessions??100;async function S(s,g){let S=t.get(s);if(!S)return;t.delete(s),S.ttlTimer!==void 0&&clearTimeout(S.ttlTimer);let w=await Promise.allSettled([S.server.close(),S.transport.close()]);for(let t of w)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:s,reason:g},`MCP HTTP session close failed`);e.log?.info?.({sessionId:s,reason:g},`MCP HTTP session closed`)}function w(t,g){g.ttlTimer!==void 0&&clearTimeout(g.ttlTimer),g.ttlTimer=setTimeout(()=>{S(t,`ttl-expired`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},s),g.ttlTimer.unref?.()}return{async handle(s,E){let D=firstHeader(s.headers[`mcp-session-id`]);if(D){let e=t.get(D);if(!e){writePlain(E,404,`MCP session not found`);return}w(D,e),await e.transport.handleRequest(s,E);return}if(s.method!==`POST`){writePlain(E,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=g){e.log?.warn?.({activeSessions:t.size,maxSessions:g},`MCP HTTP session cap reached`),writePlain(E,503,`Too many active MCP sessions`);return}let O=firstHeader(s.headers[MCP_CONNECTION_ID_HEADER]),k=validateAgentId(O)??void 0;O!==void 0&&k===void 0&&e.log?.warn?.({headerLength:O.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let j=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableJsonResponse:!0,onsessioninitialized:async s=>{try{let g=createSessionServer(e,j,k);await g.server.connect(j),t.set(s,g),w(s,g),e.log?.info?.({sessionId:s},`MCP HTTP session initialized`)}catch(g){throw t.delete(s),e.log?.error?.({err:g,sessionId:s},`MCP HTTP session initialization failed`),g}}});j.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},j.onclose=()=>{let t=j.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}S(t,`transport-closed`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await j.handleRequest(s,E)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>S(e,`handler-close`)))}}}const DEFAULT_KEEPALIVE_GRACE_MS=1e4,MAX_COLLAB_MESSAGE_BYTES=1024*1024,MCP_CORS_HEADERS={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function mountMcpAndApi(e){let{httpServer:t,hocuspocus:s,mcpHttpHandler:g,log:S,sessionManager:w,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:O,contentAssetMiddleware:k,reactShellMiddleware:j,ephemeral:F}=e,L=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,B=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});B.on(`error`,e=>{S.error({err:e},`WebSocketServer error`)});let H=new Map,q=new Set,ee=new Set,J=!1;return t.on(`request`,(e,t)=>{let w=e.url?.split(`?`)[0];if(g!==void 0&&w===`/mcp`){let s=e.headers.origin,w=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`));for(let[e,s]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,s);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}g.handle(e,t).catch(e=>{S.error({err:e,sessionId:w},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(w?.startsWith(`/api/`)){s.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${w}`})}).catch(e=>{S.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let E=(s,g,w)=>{if(s===void 0){w();return}try{s(e,t,()=>{t.writableEnded||t.headersSent||w()})}catch(e){S.error({err:e},`Unhandled ${g} middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},D=s=>{if(F===!0&&k!==void 0&&(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host))){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`content-asset`});return}E(k,`content-asset`,s)},O=e=>E(j,`react-shell`,e),L=()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${w??`/`}`})};if(j!==void 0&&w?.startsWith(`/assets/`)){O(()=>D(L));return}if(k!==void 0||j!==void 0){D(()=>O(L));return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${w??`/`}`})}),t.on(`upgrade`,(e,t,g)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive socket error`)}),ee.add(t),t.once(`close`,()=>ee.delete(t)),B.handleUpgrade(e,t,g,t=>{let s=parseKeepaliveConnectionId(e.url);if(s){let e=H.get(s);e!==void 0&&(clearTimeout(e),H.delete(s),S.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&D){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),g=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);D.setPresence(toBroadcasterKey(s),{displayName:t.displayName,icon:e,color:g,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){S.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let g=setInterval(()=>{try{t.ping()}catch{}},3e4);g.unref?.();let k=s?setInterval(()=>{D?.bumpPresenceTs(toBroadcasterKey(s))},3e3):null;k?.unref?.(),t.on(`close`,()=>{if(clearInterval(g),k!==null&&clearInterval(k),!s)return;let e=setTimeout(()=>{if(H.delete(s),J)return;let e=(async()=>{S.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await w?.closeAllForAgent(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{E?.clearFocus(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{D?.clearPresence(toBroadcasterKey(s))}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await O?.onSessionClose()}catch(e){S.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();q.add(e),e.finally(()=>q.delete(e))},L);e.unref?.(),H.set(s,e),S.info({connectionId:s,graceMs:L},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`Upgrade socket error`)}),ee.add(t),t.once(`close`,()=>ee.delete(t)),B.handleUpgrade(e,t,g,t=>{let g=s.handleConnection(t,e),w=!1;t.on(`message`,e=>{if(w)return;let s=e.byteLength;if(s>MAX_COLLAB_MESSAGE_BYTES){w=!0,incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,bytes:s,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket message rejected before Yjs processing`),t.close(1009,`Message Too Big`);return}g.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{g.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`),t.terminate();return}handleCollabSocketError(e)||S.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:B,shutdown:async()=>{if(!J){J=!0;for(let e of ee)try{e.destroy()}catch{}ee.clear();for(let e of H.values())clearTimeout(e);H.clear(),q.size>0&&await Promise.allSettled(q)}}}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_KEEPALIVE_IDENTITY_LEN=256;function sanitizeIdentityField(e){return e===null||e.length===0||e.length>MAX_KEEPALIVE_IDENTITY_LEN||/[-]/.test(e)?null:e}function parseKeepaliveIdentity(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),s=sanitizeIdentityField(t.searchParams.get(`displayName`)),g=sanitizeIdentityField(t.searchParams.get(`clientName`)),S=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return s===null||g===null||S===null?null:{displayName:s,clientName:g,colorSeed:S}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`OpenKnowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var MissingOkConfigError=class extends Error{kind;projectDir;constructor(e,t,s){super(MISSING_OK_CONFIG_MESSAGE,s),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};async function startConfigFileWatcher(e,t){let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-D1eNAlbX.mjs`),S=dirname(e);try{tracedMkdirSync(S,{recursive:!0})}catch(e){e.code!==`EEXIST`&&s.warn({err:e,watchDir:S},`failed to create watch directory; watcher may be inert`)}let w=g(S,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==S&&t!==e});await new Promise(e=>{w.once(`ready`,e)});let E=null;try{E=readFileSync(e,`utf-8`)}catch{}let D=(g,S=!0)=>{if(g!==e)return;let w;try{w=readFileSync(g,`utf-8`)}catch(e){if(e.code===`ENOENT`){S&&s.debug({path:g},`config file disappeared between event and read; dropping`);return}s.warn({err:e,path:g},`config file read failed; dropping event`);return}if(w!==E){E=w;try{t(w)}catch(e){s.warn({err:e,path:g},`config file change handler threw`)}}},O=e=>D(e);w.on(`add`,O),w.on(`change`,O),w.on(`unlink`,t=>{t===e&&s.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),w.on(`error`,t=>{s.warn({err:t,watchDir:S,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let k=0,j=setInterval(()=>{k++,D(e,!1),k>=20&&clearInterval(j)},500);j.unref?.();let F=!1;return async()=>{F||(F=!0,clearInterval(j),await w.close())}}async function startMultiPathConfigFileWatcher(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-D1eNAlbX.mjs`),S=new Set(e),w=Array.from(new Set(Array.from(S,e=>dirname(e))));for(let e of w)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&s.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let E=g(w,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!S.has(e)&&!w.includes(e)});await new Promise(e=>{E.once(`ready`,e)});let D=new Map;for(let e of S)try{D.set(e,readFileSync(e,`utf-8`))}catch{D.set(e,null)}let O=(e,g=!0)=>{if(!S.has(e))return;let w;try{w=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g&&s.debug({path:e},`config file disappeared between event and read; dropping`);return}s.warn({err:t,path:e},`config file read failed; dropping event`);return}if(w!==D.get(e)){D.set(e,w);try{t(e,w)}catch(t){s.warn({err:t,path:e},`config file change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{S.has(e)&&s.debug({path:e},`config file unlinked; downstream state retained`)}),E.on(`error`,e=>{s.warn({err:e,watchDirs:w,paths:Array.from(S)},`[config-file-watcher] chokidar error in multi-path watcher`)});let j=0,F=setInterval(()=>{j++;for(let e of S)O(e,!1);j>=20&&clearInterval(F)},500);F.unref?.();let L=!1;return async()=>{L||(L=!0,clearInterval(F),await E.close())}}function entryMatchesDocName(e,t,s,g){let S=toPosix(relative(g,join(s,e.file)));return S.startsWith(`..`)?!1:stripDocExtension(S)===t}function createConflictLifecycleSeedExtension(e){let{getSyncEngine:t,projectDir:s,contentDir:g}=e;return{async afterLoadDocument({documentName:e,document:S}){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let w=t();if(!w)return;let E=w.getConflicts();if(E.length===0||!E.some(t=>entryMatchesDocName(t,e,s,g)))return;let D=S.getMap(`lifecycle`);if(D.get(`status`)===`conflict`)return;D.set(`status`,`conflict`),D.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){console.warn(`[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${e}):`,t instanceof Error?t:String(t))}}}}const execFileAsync$1=promisify(execFile),BUILTIN_SKIP_DIRS=new Set(`node_modules,.venv,venv,env,__pycache__,vendor,dist,build,out,output,.next,.nuxt,.svelte-kit,.astro,.turbo,.cache,.parcel-cache,coverage,.git,.ok,.open-knowledge,.openknowledge,.claude,.cursor,.codex,.agents,.opencode,.pi,Library,Applications,.Trash`.split(`,`)),ALWAYS_SKIP_DIRS=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`,`.claude`,`.cursor`,`.codex`,`.agents`,`.opencode`,`.pi`]);function pathHasAlwaysSkipSegment(e){for(let t of e.split(`/`))if(ALWAYS_SKIP_DIRS.has(t))return!0;return!1}function isSkillContentFile(e){return e.startsWith(`${SKILL_CONTENT_ROOT}/`)}function isSkillContentAncestorDir(e){return e===`.ok`||e===`.ok/skills`||e.startsWith(`.ok/skills/`)}function globBlocksSkillContent(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``).trim();return t===`.ok`||t===`.ok/**`||t===`**/.ok`||t===`**/.ok/**`}const BUILTIN_SKIP_FILES=new Set([`.DS_Store`,`.localized`]);function isAlwaysSkipFile(e){return BUILTIN_SKIP_FILES.has(e.slice(e.lastIndexOf(`/`)+1))}const SECRET_BEARING_DIRS=new Set([`.ssh`,`.aws`,`.gnupg`,`.kube`,`.docker`]);function pathHasSecretBearingDirSegment(e){for(let t of e.split(`/`))if(SECRET_BEARING_DIRS.has(t.toLowerCase()))return!0;return!1}const SECRET_CREDENTIAL_BASENAMES=new Set([`credentials`,`.netrc`,`.npmrc`,`.pgpass`,`.git-credentials`]),SECRET_KEY_SUFFIXES=[`.pem`,`.key`,`.p12`,`.pfx`,`.keystore`,`.jks`,`.ppk`];function isSecretBearingFile(e){let t=e.slice(e.lastIndexOf(`/`)+1).toLowerCase();if(t===`.env`||t.startsWith(`.env.`)||SECRET_CREDENTIAL_BASENAMES.has(t)||t.startsWith(`id_rsa`)||t.startsWith(`id_ed25519`)||t.startsWith(`id_ecdsa`)||t.startsWith(`id_dsa`))return!0;for(let e of SECRET_KEY_SUFFIXES)if(t.endsWith(e))return!0;return!1}function isSingleDocAncestorDir(e,t){return t===e||t.startsWith(`${e}/`)}const IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function loadGitExcludeSources(e,t){let s=readGitCommonDirSync(e);if(s===null)return[];let g=[];appendExcludeFileIfExists(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=resolveGlobalExcludesfileSync(e);return S&&appendExcludeFileIfExists(S,t,g,`global excludesfile`),g}async function loadGitExcludeSourcesAsync(e,t){let s=await readGitCommonDirAsync(e);if(s===null)return[];let g=[];await appendExcludeFileIfExistsAsync(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=await resolveGlobalExcludesfileAsync(e);return S&&await appendExcludeFileIfExistsAsync(S,t,g,`global excludesfile`),g}function readGitCommonDirSync(e){let t=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],withHiddenWindowsConsole({cwd:e,encoding:`utf-8`,timeout:5e3}));return t.status!==0||!t.stdout?null:resolve(e,t.stdout.trim())}async function readGitCommonDirAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`rev-parse`,`--git-common-dir`],withHiddenWindowsConsole({cwd:e,encoding:`utf-8`,timeout:5e3}));return t?resolve(e,t.trim()):null}catch{return null}}function resolveGlobalExcludesfileSync(e){let t=spawnSync(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],withHiddenWindowsConsole({cwd:e,encoding:`utf-8`,timeout:5e3}));if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return xdgGlobalIgnoreDefault()}async function resolveGlobalExcludesfileAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],withHiddenWindowsConsole({cwd:e,encoding:`utf-8`,timeout:5e3})),s=t.trim();if(s)return s}catch{}return xdgGlobalIgnoreDefault()}function xdgGlobalIgnoreDefault(){let e=process.env.XDG_CONFIG_HOME?.trim();return join(e&&e.length>0?e:join(homedir(),`.config`),`git`,`ignore`)}function appendExcludeFileIfExists(e,t,s,g){if(existsSync(e))try{let g=readFileSync(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}async function appendExcludeFileIfExistsAsync(e,t,s,g){if(existsSync(e))try{let g=await readFile$1(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}function createContentFilter(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=toPosix(relative(t,s)),E=w.startsWith(`..`),D,O,k,j=0,F=0,L=0;function B(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[],S=0,B=0;for(let s of IGNORE_FILE_NAMES){let w=join(t,s);if(existsSync(w))try{let t=readFileSync(w,`utf-8`);S+=t.length;let s=parseIgnorePatterns(t);g.push(...s),e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${w}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=readFileSync(g,`utf-8`);S+=t.length,B++;let s=parseIgnorePatterns(t).map(e=>prefixPattern(e,w));e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let H={value:S};B+=loadNestedIgnoreFiles(s,t,e,H),S=H.value;let q=loadGitExcludeSources(t,H);S=H.value,q.length>0&&(g.push(...q),e.add(q));let ee=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)&&!globBlocksSkillContent(e));return D=e,O=g,k=ee,j=g.length,F=B,L=S,{patternCount:j,nestedFileCount:F,bytes:L}}B();let H=new Map;function q(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}let ee=()=>{S===void 0&&populateDirCount(s,``,q,H)};ee();function J(e){return isReservedForUserTree(stripDocExtension(e))}function Y(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:q(e)}return{isExcluded(e,t){if(J(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e))return!0;if(!t?.bypassFilters&&isSkillContentFile(e)){if(S!==void 0)return e!==S;if(isSupportedDocFile(e))return!1;let t=extname(e).slice(1).toLowerCase();return!LINKABLE_ASSET_EXTENSIONS.has(t)}if(pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(Y(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((H.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasSecretBearingDirSegment(e))return!0;if(!t?.bypassFilters&&isSkillContentAncestorDir(e))return!1;if(pathHasAlwaysSkipSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return J(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e)?!0:isSkillContentFile(e)?!1:pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)?!0:t?.bypassFilters?!1:Y(e)},getWatcherIgnoreGlobs(){return k},incrementMdDir(e){let t=e===`.`?``:e;H.set(t,(H.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=H.get(t)??0;s<=1?H.delete(t):H.set(t,s-1)},rebuildDirCount(){let e=new Map(H);H.clear();try{ee()}catch(t){for(let[t,s]of e)H.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=k,w=j,E=F,q=L,J=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async Y=>{try{let t=B();H.clear(),ee();let s=Date.now()-J;if(Y.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s},`content-filter rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s}}catch(g){D=t,O=s,k=S,j=w,F=E,L=q,H.clear();try{ee()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let B=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(B)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:B}}}})}}}function populateDirCount(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let w of S){let S=t?`${t}/${w.name}`:w.name;if(w.isDirectory()){if(BUILTIN_SKIP_DIRS.has(w.name)||s(S)||s(`${S}/`))continue;populateDirCount(join(e,w.name),S,s,g)}else w.isFile()&&isSupportedDocFile(w.name)&&!s(S)&&g.set(t,(g.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
|
|
3244
3244
|
`).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function prefixPattern(e,t){let s=e.startsWith(`!`),g=s?e.slice(1):e,S=g.startsWith(`/`)?g.slice(1):g,w=S.endsWith(`/`)?S.slice(0,-1):S,E=g.startsWith(`/`)||w.includes(`/`)?`${t}/${S}`:`${t}/**/${S}`;return s?`!${E}`:E}function loadNestedIgnoreFiles(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){return console.warn(`[content-filter] Failed to read directory ${e}:`,t),0}let w=0;for(let E of S){if(!E.isDirectory()||BUILTIN_SKIP_DIRS.has(E.name))continue;let S=join(e,E.name),D=toPosix(relative(t,S));if(!D.startsWith(`..`)&&!(s.ignores(D)||s.ignores(`${D}/`))){for(let e of IGNORE_FILE_NAMES){let t=join(S,e);if(existsSync(t))try{let e=readFileSync(t,`utf-8`);g.value+=e.length;let S=parseIgnorePatterns(e).map(e=>prefixPattern(e,D));s.add(S),w++}catch(s){console.warn(`[content-filter] Failed to read nested ${e} at ${t}:`,s)}}w+=loadNestedIgnoreFiles(S,t,s,g)}}return w}async function initContentDirStateAsync(e,t,s,g,S,w,E){let D;try{D=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let O of D){let D=t?`${t}/${O.name}`:O.name;if(O.isDirectory()){if(BUILTIN_SKIP_DIRS.has(O.name))continue;let t=join(e,O.name);if(!w){let e=toPosix(relative(s,t));if(e.startsWith(`..`)||g.ignores(e)||g.ignores(`${e}/`))continue;for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.add(t.map(t=>prefixPattern(t,e)))}catch(e){console.warn(`[content-filter] Failed to read nested ${s} at ${S}:`,e)}}}await initContentDirStateAsync(t,D,s,g,S,w,E)}else if(O.isFile()&&isSupportedDocFile(O.name)){if(!w){let e=S?`${S}/${D}`:D;if(g.ignores(e))continue}E.set(t,(E.get(t)??0)+1)}}}async function createContentFilterAsync(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=toPosix(relative(t,s)),E=w.startsWith(`..`),D=(0,import_ignore.default)(),O=[],k=new Map,j=()=>{S===void 0&&populateDirCount(s,``,F,k)};function F(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}function L(e){return isReservedForUserTree(stripDocExtension(e))}function B(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:F(e)}async function H(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[];for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.push(...t),e.add(t)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${S}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=parseIgnorePatterns(await readFile$1(g,`utf-8`));e.add(t.map(e=>prefixPattern(e,w)))}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let j=await loadGitExcludeSourcesAsync(t,{value:0});j.length>0&&(g.push(...j),e.add(j));let F=new Map;S===void 0&&await initContentDirStateAsync(s,``,t,e,w,E,F),D=e,O=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)&&!globBlocksSkillContent(e)),k.clear();for(let[e,t]of F)k.set(e,t)}return await H(),{isExcluded(e,t){if(L(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e))return!0;if(!t?.bypassFilters&&isSkillContentFile(e)){if(S!==void 0)return e!==S;if(isSupportedDocFile(e))return!1;let t=extname(e).slice(1).toLowerCase();return!LINKABLE_ASSET_EXTENSIONS.has(t)}if(pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(B(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((k.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasSecretBearingDirSegment(e))return!0;if(!t?.bypassFilters&&isSkillContentAncestorDir(e))return!1;if(pathHasAlwaysSkipSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return L(e)||isSecretBearingFile(e)||pathHasSecretBearingDirSegment(e)?!0:isSkillContentFile(e)?!1:pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)?!0:t?.bypassFilters?!1:B(e)},getWatcherIgnoreGlobs(){return O},incrementMdDir(e){let t=e===`.`?``:e;k.set(t,(k.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=k.get(t)??0;s<=1?k.delete(t):k.set(t,s-1)},rebuildDirCount(){let e=new Map(k);k.clear();try{j()}catch(t){for(let[t,s]of e)k.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=new Map(k),w=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async E=>{try{await H();let t=Date.now()-w;if(E.setAttributes({"ok.ignore.pattern_count":O.length,"ok.ignore.nested_file_count":0,"ok.ignore.bytes":0}),e.info({durationMs:t},`content-filter async rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:O.length,nestedFileCount:0,bytes:0,durationMs:t}}catch(g){D=t,O=s,k.clear();for(let[e,t]of S)k.set(e,t);let w=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(w)},`content-filter async rebuild failed — rolled back`),{ok:!1,error:{message:w}}}})}}}function runDocLineageGuard(e,t,s){try{if(typeof t!=`string`||t.length===0||isSystemDoc(e)||isConfigDoc(e))return;let g=s.getLoadedDoc(e);if(g===void 0)throw incrementAuthDocLineageMismatch(),setActiveSpanAttributes({"auth.reason":`doc-lineage-mismatch`}),new HocuspocusAuthRejection(`doc-lineage-mismatch`,`doc lineage mismatch: claim against unloaded ${e} is stale by construction`);let S=g.getMap(`lifecycle`).get(LINEAGE_EPOCH_KEY);if(typeof S!=`string`||S.length===0||S!==t)throw incrementAuthDocLineageMismatch(),setActiveSpanAttributes({"auth.reason":`doc-lineage-mismatch`}),new HocuspocusAuthRejection(`doc-lineage-mismatch`,`doc lineage mismatch for ${e}: claimed epoch does not match the live lineage`)}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthDocLineageGuardError(),console.warn(JSON.stringify({event:`doc-lineage-guard-error`,documentName:e,errorName:t instanceof Error?t.name:typeof t,message:t instanceof Error?t.message:String(t)}))}}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let s=resolve(e,t.slice(5));try{return readFileSync(s,`utf-8`).trim()}catch{try{let s=readFileSync(resolve(e,`packed-refs`),`utf-8`),g=t.slice(5),S=s.split(`
|
|
3245
3245
|
`).find(e=>e.endsWith(` ${g}`));if(S)return S.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function readBranchFromHead(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}function watchedGitFile(e){let t=e.split(`/`).pop()??``;return WATCHED_FILES.has(t)?t:null}async function tryStartParcelHeadWatcher(e,t){let s;try{s=await import(`@parcel/watcher`)}catch(e){return getLogger(`head-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher unavailable; falling back to chokidar`),null}try{let g=await s.subscribe(e,(e,s)=>{if(e){getLogger(`head-watcher`).warn({err:e},`[head-watcher] parcel subscription error`);return}for(let e of s)t(e.path)});return()=>g.unsubscribe()}catch(e){return getLogger(`head-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher subscribe failed; falling back to chokidar`),null}}async function startChokidarHeadWatcher(e,t){let{watch:s}=await import(`./chokidar-D1eNAlbX.mjs`),g=s(e,{ignoreInitial:!0,depth:0,followSymlinks:!1});return g.on(`all`,(e,s)=>t(s)),g.on(`error`,e=>{getLogger(`head-watcher`).warn({err:e},`[head-watcher] chokidar watcher error`)}),()=>g.close()}async function startHeadWatcher(e,t,s,g={}){let S=resolveGitDir(e);if(!S)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let w=S,E=!1,D=null,O=null,k=null,j=null;async function F(e){if(B&&await B,!E)return;D&&=(clearTimeout(D),null),O&&=(clearTimeout(O),null);let t=readHeadSha(w),g=k!==t,S=readBranchFromHead(w),F;F=S?.startsWith(`detached-`)?`detached-head`:j===S?`within-branch`:`cross-branch`;let L=j;try{await s({headMoved:g,oldHead:k,newHead:t,timeout:e,batchKind:F,oldBranch:L,newBranch:S})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{E=!1,k=t,j=S}}function L(){D&&clearTimeout(D),D=setTimeout(()=>{D=null,F(!1)},QUIET_WINDOW_MS)}let B=null;async function H(e){if(!E){E=!0,k===null&&(k=readHeadSha(w));let s=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();B=s,await s,B=null,O=setTimeout(()=>{O=null,F(!0)},BATCH_TIMEOUT_MS)}L()}let q=e=>{let t=watchedGitFile(e);t!==null&&H(t)},ee=null,J=`chokidar`;if(g.forceBackend!==`chokidar`&&(ee=await tryStartParcelHeadWatcher(w,q),ee&&(J=`parcel`)),!ee){if(g.forceBackend===`parcel`)throw Error(`@parcel/watcher unavailable for HEAD watching (forced backend)`);ee=await startChokidarHeadWatcher(w,q),J=`chokidar`}let Y=ee;return k=readHeadSha(w),j=readBranchFromHead(w),getLogger(`head-watcher`).info({gitDir:w,backend:J},`watching for HEAD changes`),{unsubscribe:async()=>{E&&await F(!1),D&&clearTimeout(D),O&&clearTimeout(O),await Y()},getLastKnownBranch:()=>j}}const LIVE_DERIVED_INDEX_DEBOUNCE_MS=100;function isLocalOriginLike(e){return typeof e!=`object`||!e?!1:e.source===`local`}function serializeLiveDocument(e){return e.getText(`source`).toString()}function createLiveDerivedIndexExtension(e){let{backlinkIndex:t,tagIndex:s,signalChannel:g,debounceMs:S=100}=e,w=new Map;function E(e){let t=w.get(e);t&&(clearTimeout(t),w.delete(e))}function D(e,D){E(e),w.set(e,setTimeout(()=>{w.delete(e);try{let S=serializeLiveDocument(D);t.updateDocumentFromMarkdown(e,S),g?.(`backlinks`),g?.(`graph`),s&&(s.updateDocumentFromMarkdown(e,S),g?.(`tags`))}catch(t){console.error(`[live-derived-index] Failed to update derived views for ${e}:`,t)}},S))}return{async onChange({documentName:e,document:t,transactionOrigin:s}){isLinkIndexExcludedDoc(e)||isLocalOriginLike(s)&&s.context?.origin===`file-watcher`||D(e,t)},async beforeUnloadDocument({documentName:e}){E(e)},async onDestroy(){for(let e of w.values())clearTimeout(e);w.clear()}}}const log$5=getLogger(`shadow-gc`),GC_GRACE_PERIOD_MS=1440*60*1e3,SESSION_WRITER_TTL_MS=720*60*60*1e3;function extractBranchNames(e){let t=new Set;for(let s of e){let e=s.replace(/^refs\/wip\//,``),g=e.lastIndexOf(`/`);if(g<=0)continue;let S=e.slice(0,g);parseWriterId(e.slice(g+1)).classification!==`unknown`&&t.add(S)}return t}async function getProjectBranchSha(e,t){try{return(await esm_default().env({GIT_DIR:e}).raw(`rev-parse`,`refs/heads/${t}`)).trim()}catch{return null}}async function listProjectBranches(e){let t=new Set;try{let s=(await esm_default().env({GIT_DIR:e}).raw(`for-each-ref`,`refs/heads/`,`--format=%(refname:short)`)).trim();if(s)for(let e of s.split(`
|
|
3246
3246
|
`))e&&t.add(e)}catch(e){log$5.warn({err:e},`[shadow-gc] listProjectBranches failed; treating as no project branches`)}return t}async function gcShadowBranches(e,t,s=DEFAULT_CHECKPOINT_RETENTION,g=`.`){let S={deletedBranches:[],renamedBranches:[],retainedBranches:[],checkpointGc:{},deletedStaleSessionRefs:0},w=shadowGit(e,{timeoutMs:MAINTENANCE_GIT_TIMEOUT_MS}),E;try{E=(await w.raw(`for-each-ref`,`refs/wip/`,`--format=%(refname)`)).trim()}catch{return S}if(!E)return S;let D=E.split(`
|
|
@@ -3250,8 +3250,8 @@ Incremental by default — don't re-read the whole repo.
|
|
|
3250
3250
|
`).filter(Boolean)}catch{return 0}let S=0;for(let e of g){let[s=``,g=``,w=``]=e.split(`\0`);if(w.startsWith(`park:`))continue;let E=s.split(`/`).slice(3).join(`/`);if(!E||parseWriterId(E).classification!==`agent`)continue;let D=Number.parseInt(g,10);Number.isFinite(D)&&D*1e3<t&&(S+=1)}return S}const log$4=getLogger(`shadow-maintenance`),DEAD_CHAIN_THRESHOLD=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),CONSOLIDATION_MIN_SPACING_MS=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 600*1e3;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:600*1e3})();function isMaintenanceDisabled(){return process.env.OK_SHADOW_MAINTENANCE_DISABLED===`1`}function consolidationTriggerLabel(e){return e===`boot`?`boot`:e===`session-close`?`session-close`:e===`ttl`?`ttl`:`dead-chain`}var MaintenanceCoordinator=class{running=!1;destroyed=!1;flushCommitCounter=0;lastConsolidationAt=0;lastGcLatch=!1;constructor(e){this.deps=e}get isRunning(){return this.running}destroy(){this.destroyed=!0}noteFlushCommit(){isMaintenanceDisabled()||this.destroyed||(this.flushCommitCounter+=1,this.flushCommitCounter>=200&&(this.flushCommitCounter=0,this.runScheduledMaintenance(`flush-counter`)))}async runBootMaintenance(e=1e3){if(isMaintenanceDisabled()||this.destroyed)return;let t=this.runScheduledMaintenance(`boot`),s,g=new Promise(t=>{s=setTimeout(t,e)});await Promise.race([t.then(()=>void 0),g]),s&&clearTimeout(s),t.catch(e=>{log$4.warn({err:e},`[shadow-maintenance] boot maintenance background continuation failed`)})}async onSessionClose(){await this.runScheduledMaintenance(`session-close`)}async runScheduledMaintenance(e){if(!(isMaintenanceDisabled()||this.destroyed)&&!this.running){this.running=!0;try{await this.consolidateInner(e),await this.reapInner(e),await this.gcInner(e)}finally{this.running=!1}}}async runReap(e){if(!(isMaintenanceDisabled()||this.destroyed)&&!this.running){this.running=!0;try{await this.reapInner(e)}finally{this.running=!1}}}async reapInner(e){if(!this.deps.projectGitDir)return;let t=this.deps.getShadow();if(!t)return;let s=performance.now();try{await gcShadowBranches(t,this.deps.projectGitDir,void 0,this.deps.contentRoot??`.`),recordMaintenanceRun(`reap`,`ok`,performance.now()-s)}catch(t){recordMaintenanceRun(`reap`,`error`,performance.now()-s),log$4.warn({trigger:e,err:t},`[shadow-maintenance] reap failed; retrying next trigger`)}}async consolidateDeadChains(e){if(isMaintenanceDisabled()||this.destroyed)return{consolidated:!1,skipped:`disabled`};if(this.running)return{consolidated:!1,skipped:`busy`};this.running=!0;try{return await this.consolidateInner(e)}finally{this.running=!1}}async consolidateInner(e){let{getCurrentBranch:t,isWriterLive:s}=this.deps;if(!t||!s)return{consolidated:!1,skipped:`unconfigured`};if(Date.now()-this.lastConsolidationAt<CONSOLIDATION_MIN_SPACING_MS)return{consolidated:!1,skipped:`spacing`};let g=this.deps.getShadow();if(!g)return{consolidated:!1,skipped:`no-shadow`};try{let S=t()??`main`,w=await this.findDeadAgentChains(g,S,s);if(w.length<DEAD_CHAIN_THRESHOLD)return{consolidated:!1,skipped:`below-threshold`,deadChains:w.length};let E=await countWipRefs(g,S);await saveVersion(g,this.deps.contentRoot??``,w,S,void 0,{checkpointKind:{foldedRefs:w.length,trigger:consolidationTriggerLabel(e)},timeoutMs:MAINTENANCE_GIT_TIMEOUT_MS}),this.lastConsolidationAt=Date.now();let D=await countWipRefs(g,S);return recordConsolidation(consolidationTriggerLabel(e)),log$4.info({trigger:e,branch:S,foldedChains:w.length,widthBefore:E,widthAfter:D},`[shadow-maintenance] auto-consolidation folded dead agent chains`),{consolidated:!0,deadChains:w.length,widthBefore:E,widthAfter:D}}catch(t){return log$4.warn({trigger:e,err:t},`[shadow-maintenance] consolidation failed; retrying next trigger`),{consolidated:!1,skipped:`error`}}}async findDeadAgentChains(e,t,s){return(await enumerateWipChains(e,t)).filter(e=>e.classification===`agent`&&!e.isPark&&!s(e.writerId)).map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`}))}async runGc(e){if(isMaintenanceDisabled())return{ran:!1,skipped:`disabled`};if(this.destroyed)return{ran:!1,skipped:`no-shadow`};if(this.running)return recordMaintenanceRun(`gc`,`skipped`,0),{ran:!1,skipped:`busy`};this.running=!0;try{return await this.gcInner(e)}finally{this.running=!1}}async gcInner(e){let t=this.deps.getShadow();if(!t)return{ran:!1,skipped:`no-shadow`};let s=performance.now();try{let g=await countShadowObjects(t);await shadowGit(t,{timeoutMs:MAINTENANCE_GIT_TIMEOUT_MS}).raw(`gc`,`--auto`);let S=await countShadowObjects(t),w=hasGcLogLatch(t),E=performance.now()-s;return recordMaintenanceRun(`gc`,`ok`,E),w&&(this.lastGcLatch||recordGcLatch(),log$4.warn({trigger:e,looseObjects:S.looseObjects},`[shadow-maintenance] gc.log latch present — auto-gc disabled until it self-expires (~1 day); retrying next trigger`)),this.lastGcLatch=w,log$4.info({trigger:e,looseBefore:g.looseObjects,looseAfter:S.looseObjects,packfiles:S.packfiles,durationMs:Math.round(E)},`[shadow-maintenance] gc complete`),{ran:!0,looseBefore:g.looseObjects,looseAfter:S.looseObjects,packfilesAfter:S.packfiles,latch:w,durationMs:E}}catch(t){return recordMaintenanceRun(`gc`,`error`,performance.now()-s),log$4.warn({trigger:e,err:t},`[shadow-maintenance] gc failed; retrying next trigger`),{ran:!1,skipped:`error`}}}};function createMaintenanceCoordinator(e){return new MaintenanceCoordinator(e)}const SKILL_WATCH_OPTIONS={depth:1,acceptLeaf:e=>basename(e)===`SKILL.md`},TEMPLATE_WATCH_OPTIONS={depth:0,acceptLeaf:e=>basename(e).endsWith(`.md`)};async function startManagedArtifactWatcher(e,t,s=SKILL_WATCH_OPTIONS){let g=getLogger(`managed-artifact-watcher`),{watch:S}=await import(`./chokidar-D1eNAlbX.mjs`),w=Array.from(new Set(e));for(let e of w)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&g.warn({err:t,dir:e},`failed to create watch root; watcher may be inert`)}let E=S(w,{ignoreInitial:!0,depth:s.depth,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});await new Promise(e=>{E.once(`ready`,e)});let D=new Map,O=e=>{if(!s.acceptLeaf(e))return;let S;try{S=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g.debug({path:e},`managed-artifact leaf disappeared between event and read; dropping`);return}g.warn({err:t,path:e},`managed-artifact leaf read failed; dropping event`);return}if(S!==D.get(e)){D.set(e,S);try{t(e,S)}catch(t){g.warn({err:t,path:e},`managed-artifact change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{s.acceptLeaf(e)&&(D.delete(e),g.debug({path:e},`managed-artifact leaf unlinked; live doc retained at current state`))}),E.on(`error`,e=>{g.warn({err:e,watchRoots:w},`[managed-artifact-watcher] chokidar error`)});let j=!1;return async()=>{j||(j=!0,await E.close())}}const PRINCIPAL_FILE=`principal.json`,GIT_TIMEOUT_MS=3e3;async function readGitConfig(e){try{let t=esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function loadPrincipal(e){let t=getLocalDir(e),s=resolve(t,PRINCIPAL_FILE),{name:g,email:S}=await readGitConfig(e);if(existsSync(s)){let e;try{e=JSON.parse(readFileSync(s,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${randomUUID()}`,w=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),E=t.slice(10,18),D={id:t,display_name:g?sanitizeGitIdentity(g):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:S?sanitizeGitIdentity(S):typeof e.display_email==`string`?e.display_email:`principal-${E}@openknowledge.local`,source:g||S?`git-config`:`synthesized`,created_at:w};return writeFileSync(s,JSON.stringify(D,null,2),`utf-8`),D}mkdirSync(t,{recursive:!0});let w=`principal-${randomUUID()}`,E=w.slice(10,18),D={id:w,display_name:g?sanitizeGitIdentity(g):`Local User`,display_email:S?sanitizeGitIdentity(S):`principal-${E}@openknowledge.local`,source:g||S?`git-config`:`synthesized`,created_at:new Date().toISOString()};return writeFileSync(s,JSON.stringify(D,null,2),`utf-8`),D}const DEFAULT_CAPACITY=1e4;var RecentlyRemovedDocs=class{map=new Map;capacity;onEviction;onSizeChange;onMutate;now;constructor(e=DEFAULT_CAPACITY,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.onMutate=t.onMutate,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&(this.onSizeChange?.(this.map.size),this.onMutate?.())}get size(){return this.map.size}entries(){return[...this.map.entries()]}restore(e,t){this.put(e,t)}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size),this.onMutate?.()}};function fileExistsForDocName(e,t){let s=e.resolveFilePath(t);return s!==null&&e.fileExists(s)}async function runRemovalRedirectGuard(e,t){try{if(isReservedForUserTree(e))return;let s=t.recentlyRemovedDocs.get(e);if(s===void 0)return;if(s.kind===`deleted`){if(fileExistsForDocName(t,e)){t.recentlyRemovedDocs.delete(e);return}throw incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let g=new Set([e]),S=s.newDocName;for(;;){if(g.has(S)){incrementRemovalRedirectChainCycle(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:S}));return}g.add(S);let s=t.recentlyRemovedDocs.get(S);if(s===void 0)throw incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${S}`,S);if(s.kind===`deleted`)throw fileExistsForDocName(t,S)?(t.recentlyRemovedDocs.delete(S),incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${S}`,S)):(incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`));S=s.newDocName}}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthRemovalGuardError(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}const log$3=getLogger(`removed-docs-journal`),REMOVED_DOCS_JOURNAL_FILENAME=`removed-docs.json`;function removedDocsJournalPath(e){return join(getLocalDir(e),REMOVED_DOCS_JOURNAL_FILENAME)}function isJournalEntry(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.docName!=`string`||t.docName.length===0||typeof t.addedAt!=`number`?!1:t.kind===`deleted`?!0:t.kind===`renamed`?typeof t.newDocName==`string`:!1}function loadRemovedDocsJournal(e){let t=removedDocsJournalPath(e);if(!existsSync(t))return[];try{let e=JSON.parse(readFileSync(t,`utf-8`));if(e.version!==1||!Array.isArray(e.entries))return log$3.warn({path:t},`[removed-docs-journal] unrecognized journal shape — ignoring`),[];let s=[];for(let t of e.entries){if(!isJournalEntry(t))continue;let{docName:e,...g}=t;s.push([e,g])}return s}catch(e){return log$3.warn({path:t,err:e},`[removed-docs-journal] failed to read journal — ignoring`),[]}}function saveRemovedDocsJournal(e,t){let s=removedDocsJournalPath(e),g={version:1,entries:t.map(([e,t])=>({docName:e,...t}))};tracedMkdirSync(dirname(s),{recursive:!0});let S=`${s}.tmp`;tracedWriteFileSync(S,JSON.stringify(g),`utf-8`),tracedRenameSync(S,s)}function createServerObserverExtension(e){let t=new Map,s=new Map;return{async afterLoadDocument({documentName:g,document:S}){if(isSystemDoc(g)||isConfigDoc(g)||t.has(g))return;let w=S,E=w.getXmlFragment(`default`),D=w.getText(`source`),O=()=>{try{let s=setupServerObservers({doc:w,xmlFragment:E,ytext:D,mdManager:e.mdManager,schema:e.schema,docName:g,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize});return t.set(g,s),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${g}':`,e),incrementServerObserverError(`a`),incrementServerObserverError(`b`),!1}};if(!O()){let e=setTimeout(()=>{s.delete(g),!t.has(g)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${g}'`),O())},5e3);s.set(g,e)}},async afterUnloadDocument({documentName:e}){let g=s.get(e);g&&(clearTimeout(g),s.delete(e));let S=t.get(e);S&&(S(),t.delete(e))},async onDestroy(){for(let e of s.values())clearTimeout(e);s.clear();for(let[e,s]of t.entries())try{s()}catch(t){console.error(`[ServerObserverExtension] Cleanup failed for '${e}':`,t)}t.clear()}}}const STATE_MANIFEST_FILENAME=`state.json`;function detectProjectShape(e){return e.lockDir,existsSync(e.shadowRepoDir)?`adopt`:`fresh`}function manifestPath(e){return resolve(e,STATE_MANIFEST_FILENAME)}function isCompatibleSchema(e,t){return e===t||e===0&&t===1}var StateManifestError=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function isStateManifestRecord(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let s=t.createdBy;return!(typeof s.runtimeVersion!=`string`||s.protocolVersion!==void 0&&typeof s.protocolVersion!=`number`)}function readStateManifest(e){let t=manifestPath(e);if(!existsSync(t))return{status:`absent`};let s;try{s=readFileSync(t,`utf-8`)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let g;try{g=JSON.parse(s)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!isStateManifestRecord(g))throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:g}}function writeStateManifest(e,t){let s=manifestPath(e);mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function assertCompatibleStateManifest(e){let t=getLogger(`state-manifest`),s=e.currentStateSchemaVersion??1,g=e.currentRuntimeVersion??RUNTIME_VERSION,S=e.currentProtocolVersion??1,w=(e.now??(()=>new Date))().toISOString(),E=manifestPath(e.lockDir),D=readStateManifest(e.lockDir);if(D.status===`present`){let O=D.manifest;if(!isCompatibleSchema(O.stateSchemaVersion,s))throw new StateManifestError({kind:`incompatible`,path:E,message:`State manifest at ${E} declares stateSchemaVersion=${O.stateSchemaVersion} but this binary supports ${s}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${O.createdBy.runtimeVersion}, protocol ${O.createdBy.protocolVersion}.)`});try{let t={...O,lastWriteBy:{runtimeVersion:g,protocolVersion:S,at:w}};return writeStateManifest(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),O}}if(detectProjectShape({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let D={stateSchemaVersion:s,createdAt:w,createdBy:{runtimeVersion:g,protocolVersion:S}};return writeStateManifest(e.lockDir,D),t.info({path:E,stateSchemaVersion:s},`[state-manifest] fresh project — wrote manifest`),D}let O={stateSchemaVersion:0,createdAt:w,createdBy:{runtimeVersion:g,protocolVersion:S,adoptedAt:w}};return writeStateManifest(e.lockDir,O),t.warn({path:E,runtimeVersion:g},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),O}function deriveUserFacingCode(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`auth`&&t===`no-credential`?`auth-no-credential`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function extractStderr(e){return e.git?.toString()??e.message??``}function matchesAny(e,t){return t.some(t=>t.test(e))}const AUTH_SUBCLASS_MESSAGES={"no-credential":`No GitHub credential available — reconnect to resume syncing`,401:`Authentication failed — token may be expired`,403:`Access denied (403)`,"scope-mismatch":`GitHub token missing required scopes`,"ssh-auth":`SSH authentication failed — check your SSH key or host-key trust`,"unknown-auth":`Authentication failed`},NON_FAST_FORWARD_PATTERNS=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],PROTECTED_BRANCH_PATTERNS=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],MERGE_CONFLICT_PATTERNS=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],LFS_PATTERNS=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],LARGE_FILE_PATTERNS=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],PRE_RECEIVE_PATTERNS=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],SECRET_DETECTED_PATTERNS=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],INDEX_LOCK_PATTERNS=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],DIRTY_TREE_PATTERNS=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],DISK_FULL_PATTERNS=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/i],NETWORK_PATTERNS=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],HTTP_5XX_PATTERNS=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],HTTP_429_PATTERNS=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function classifyGitError(e){let t=classifyGitErrorBase(e);return{...t,userFacingCode:deriveUserFacingCode(t.class,t.subclass)}}function classifyGitErrorBase(e){let t=e instanceof Error?e:Error(String(e)),s=extractStderr(t),g=`${t.message}\n${s}`.toLowerCase();if(matchesAny(g,INDEX_LOCK_PATTERNS))return{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:s};if(matchesAny(g,DIRTY_TREE_PATTERNS))return{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:s};if(matchesAny(g,DISK_FULL_PATTERNS))return{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:s};let S=classifyGitAuthError(t);return S.kind===`auth`?S.subclass===`403`&&matchesAny(g,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:s}:{class:`auth`,subclass:S.subclass,retryable:!1,message:AUTH_SUBCLASS_MESSAGES[S.subclass],rawStderr:s}:matchesAny(g,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:s}:matchesAny(g,NON_FAST_FORWARD_PATTERNS)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:s}:matchesAny(g,MERGE_CONFLICT_PATTERNS)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:s}:matchesAny(g,LFS_PATTERNS)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:s}:matchesAny(g,LARGE_FILE_PATTERNS)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:s}:matchesAny(g,SECRET_DETECTED_PATTERNS)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:s}:matchesAny(g,PRE_RECEIVE_PATTERNS)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:s}:matchesAny(g,HTTP_429_PATTERNS)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:s}:matchesAny(g,HTTP_5XX_PATTERNS)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:s}:matchesAny(g,NETWORK_PATTERNS)?/timed? out/i.test(g)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:s}:/refused/i.test(g)||/econnrefused/i.test(g)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:s}:/resolve.*host/i.test(g)||/enotfound/i.test(g)||/getaddrinfo/i.test(g)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:s}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:s}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:s}}const DEFAULT_TTL_MS=6e4;function createGhTokenSource(e,t={}){let s=t.ttlMs??DEFAULT_TTL_MS,g=t.now??Date.now,S=new Map;return{get(t){if(!e)return null;let w=g(),E=S.get(t);if(E&&E.expiresAt>w)return E.token==null?null:{token:E.token,host:t};let D=e(t),O=D.available&&D.token?D.token:null;return S.set(t,{token:O,expiresAt:w+s}),O==null?null:{token:O,host:t}},invalidate(){S.clear()}}}const log$2=getLogger(`github-permissions`),PROBE_TIMEOUT_MS=5e3;function githubApiBase(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function buildHeaders(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function readPushFlag(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let s=t.push;return typeof s==`boolean`?s:null}async function classify(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return log$2.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let s=readPushFlag(t);return s===null?(log$2.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):s?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return log$2.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function resolveProbeTokenWithSource(e,t,s){let g=t(e);if(g.available&&g.token)return{token:g.token,source:`gh`};if(s)try{let t=await s.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){log$2.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function runProbe(e){let{owner:t,repo:s,host:g=`github.com`,detectGh:S=()=>({available:!1}),tokenStore:w,_fetchFn:E=fetch,_timeoutMs:D=PROBE_TIMEOUT_MS}=e,{token:O,source:k}=await resolveProbeTokenWithSource(g,S,w);if(k===`anonymous`)return log$2.info({host:g},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`no-collaborator`};let j=`${githubApiBase(g)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(s)}`;log$2.info({host:g,tokenSource:k,tokenLen:O===void 0?0:O.length},`[permissions] probe starting`);let F=new AbortController,L=setTimeout(()=>F.abort(),D);try{let e=await E(j,{signal:F.signal,headers:buildHeaders(O)}),t=await classify(e,O!==void 0);return log$2.info({host:g,tokenSource:k,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return F.signal.aborted?(log$2.warn({host:g,timeoutMs:D},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(log$2.warn({err:e,host:g},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(L)}}async function checkPushPermission(e){let t=performance.now(),s=await runProbe(e);return recordProbeTelemetry(s,performance.now()-t),s}function outcomeAttributes(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let _outcomeCounter=null;function outcomeCounter(){return _outcomeCounter||=getMeter().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,none}.`}),_outcomeCounter}let _durationHist=null;function durationHist(){return _durationHist||=getMeter().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),_durationHist}function recordProbeTelemetry(e,t){let s=outcomeAttributes(e);outcomeCounter().add(1,s),durationHist().record(t,{outcome:s.outcome})}function computeRemainingMs(e,t,s=Date.now()){if(!e)return 0;let g=new Date(e).getTime();if(Number.isNaN(g))return 0;let S=g+t*1e3;return Math.max(0,S-s)}const log$1=getLogger(`sync-engine`),SHA_HEX_40=/^[0-9a-f]{40}$/i,SYNC_GH_TOKEN_HOST=`github.com`;function pushPermissionStatusFrom(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function pushPermissionStatusEqual(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.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}function jitteredMs(e){let t=e*1e3,s=t*.15*(2*Math.random()-1);return Math.round(t+s)}function isUnbornHead(e){try{let t=join(e,`.git`,`HEAD`);if(!existsSync(t))return!1;let s=readFileSync(t,`utf-8`).trim(),g=/^ref:\s+(refs\/.+)$/.exec(s);if(!g)return!1;let S=g[1];if(existsSync(join(e,`.git`,S)))return!1;let w=join(e,`.git`,`packed-refs`);if(existsSync(w)){let e=readFileSync(w,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${S}$`,`m`).test(e))return!1}return!0}catch{return!1}}function backoffMs(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var SyncEngine=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;syncEnabled;credentialArgs;cc1Broadcaster;onStateChange;onContentConflictsDetected;setBatchInProgress;onAutoDisable;detectGh;ghTokenSource;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.syncEnabled=e.syncEnabled,this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.detectGh=e.detectGh,this.ghTokenSource=createGhTokenSource(e.detectGh),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??checkPushPermission,this.statePath=resolve(getLocalDir(this.projectDir),`sync-state.json`),this.conflictStore=new ConflictStore(this.projectDir,this.currentBranch)}gitHandle(e){return createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:e,ghToken:this.ghTokenSource.get(SYNC_GH_TOKEN_HOST)??void 0})}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.conflictStore.setBranch(e))}catch{}}catch(e){log$1.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),log$1.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){log$1.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=resolveGitDir(this.projectDir),s=t?join(t,`MERGE_HEAD`):null,g=s!==null&&existsSync(s);if(this.conflictCount>0&&!g)log$1.warn({count:this.conflictCount},`[sync] persisted conflicts but no MERGE_HEAD — clearing stale state`),this.conflictStore.clear(),this.conflictCount=0;else if(this.conflictCount>0&&g)try{let e=this.gitHandle(),t=new Set(await listNames(e.git,[`diff`,`--name-only`,`--diff-filter=U`])),s=this.conflictCount;for(let e of this.conflictStore.list())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<s&&log$1.info({cleared:s-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){log$1.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(g&&this.conflictCount===0){log$1.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),log$1.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let S=computeRemainingMs(this.lastFetchUtc,this.pullIntervalSeconds),w=computeRemainingMs(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(S>0?S:void 0),this.schedulePush(w>0?w:void 0),log$1.info({branch:this.currentBranch,pullDelayMs:S,pushDelayMs:w},`[sync] started`)}stop(){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()}async setEnabled(e){if(this.syncEnabled!==e){if(this.syncEnabled=e,!e){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null);let e=3e4,t=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-t>3e4){log$1.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] setEnabled(false): timed out waiting for in-flight cycle to drain`);break}await setTimeout$1(50)}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.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async notifyCredentialsChanged(){if(this.syncEnabled&&(this.ghTokenSource.invalidate(),!(this.state!==`auth-error`&&this.pausedReason!==`auth-error`))){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?log$1.warn({op:e,state:this.state,syncEnabled:this.syncEnabled,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):log$1.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(e===`pull`||await this.runPushCycle(),await this.runPullCycle())}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.syncEnabled===!0,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?readSyncRemoteInfo(this.projectDir):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.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await resolveGitIdentity(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=readOriginGitHubRepo(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,pushPermissionStatusEqual(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,log$1.info({caller:e,host:`github.com`,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let s;try{s=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:`github.com`,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){log$1.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),s={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let g=pushPermissionStatusFrom(s),S=this.pushPermission;this.pushPermission=g;let w=!1;return g.checkStatus===`denied`&&this.syncEnabled===!0?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),w=!0,log$1.info({reason:g.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):g.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.syncEnabled===!0&&this.transitionTo(`idle`),w=!0,log$1.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!w&&!pushPermissionStatusEqual(S,g)&&this.cc1Broadcaster?.signal(`sync-status`),g}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,log$1.info({syncEnabled:this.syncEnabled},`[sync] remote detected post-boot — re-evaluating state`),this.syncEnabled===!0?(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()):this.transitionTo(`disabled`))}async probeRemote(){if(!existsSync(join(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return log$1.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){if(this.conflictCount===0)return;let e=this.conflictCount,t=resolveGitDir(this.projectDir),s=t?join(t,`MERGE_HEAD`):null;if(!(s!==null&&existsSync(s)))log$1.info({cleared:e},`[sync] external resolve detected (no MERGE_HEAD) — clearing tracked conflicts`),this.conflictStore.clear(),this.conflictCount=0;else try{let t=this.gitHandle(),s=new Set(await listNames(t.git,[`diff`,`--name-only`,`--diff-filter=U`]));for(let e of this.conflictStore.list())s.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<e&&log$1.info({cleared:e-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){log$1.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}this.conflictCount!==e&&(this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,s){this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,s)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}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.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{log$1.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??jitteredMs(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{log$1.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=this.consecutiveFailures,t=backoffMs(e);return t>0?t:jitteredMs(this.pullIntervalSeconds)}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`||this.state===`auth-error`)){if(this.state===`conflict`){this.schedulePull();return}if(isUnbornHead(this.projectDir)){this.schedulePull();return}this.pullInFlight=!0;try{await this.doPullCycle()}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=this.gitHandle(),t;try{let s=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!s||s===`HEAD`){this.transitionTo(`disabled`),this.pausedReason=`detached-head`,log$1.warn({},`[sync] detached HEAD — pausing sync`);return}t=s,this.currentBranch=t}catch(e){this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))),`pull`);return}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));this.handleError(t,`pull`);return}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(e);let s=await this.prepareForMerge(e,t);if(!s.proceed)return;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{s.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`);return}finally{this.setBatchInProgress?.(!1)}}else this.transitionTo(`idle`);this.scheduleSaveState()}async runPushCycle(){if(!this.pushInFlight&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(isUnbornHead(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),s=join(tmpdir(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),g=null;this.transitionTo(`pushing`);try{await withParentLock(async()=>{let e=this.gitHandle(s);if(isUnbornHead(this.projectDir)){log$1.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let S;try{S=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),s=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(s)||/ambiguous argument 'HEAD'/i.test(s)||/does not have any commits yet/i.test(s)){log$1.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))),`push`);return}await e.git.raw([`read-tree`,S]);let w=await this.listHeadContentPaths(e,S);if(t.length>0){let s=100;for(let s=0;s<t.length;s+=100){let g=t.slice(s,s+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...g])}}let E=new Set(t.map(e=>e.projectRelPath)),D=[...w].filter(e=>!E.has(e));await this.removePathsFromIndex(e,D);let O=(await e.git.raw([`write-tree`])).trim(),k=``;try{k=(await e.git.raw([`rev-parse`,`${S}^{tree}`])).trim()}catch{}if(k&&k===O){let s=null;try{s=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(s===S){log$1.info({contentFileCount:t.length,headSha:S},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=S,this.lastSyncUtc=new Date().toISOString(),this.clearPushError(),this.transitionTo(`idle`);return}log$1.info({headSha:S,upstreamSha:s},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let w=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),w=!0}catch{}w?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),g=S;return}let j=[],F=[];try{let s=await listNames(e.git,[`diff-tree`,`--name-only`,`-r`,S,O]);if(s.length>0){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of s){j.push(t);let s=e.get(t)??toPosix(relative(this.contentDir,join(this.projectDir,t)));s&&!s.startsWith(`..`)&&F.push(s)}}}catch{j=t.map(e=>e.projectRelPath).concat(D),F=t.map(e=>e.contentRelPath)}let L=this.buildCommitMessage(F),B=await resolveGitIdentity(this.projectDir),H=B===null;this.identityUnresolved!==H&&(this.identityUnresolved=H,this.cc1Broadcaster?.signal(`sync-status`));let q=B?.name??`OpenKnowledge`,ee=B?.email??`sync@open-knowledge.local`;applyGitEnv(e,{GIT_AUTHOR_NAME:q,GIT_AUTHOR_EMAIL:ee,GIT_COMMITTER_NAME:q,GIT_COMMITTER_EMAIL:ee});let J=(await e.git.raw([`commit-tree`,O,`-p`,S,`-m`,L])).trim();if(!J||!SHA_HEX_40.test(J)){log$1.warn({raw:J},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,J,S]),await this.resetRealIndexForPaths(j);let Y=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),Y=!0}catch{}Y?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),g=J}),g&&(this.lastPushedSha=g,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let s=classifyGitError(t instanceof Error?t:Error(String(t)));if(s.class===`semantic`&&s.subclass===`non-fast-forward`){if(e>0){log$1.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);try{await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e);let t=await this.prepareForMerge(e,this.currentBranch);if(!t.proceed){this.setBatchInProgress?.(!1);return}try{await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}log$1.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(s,`push`)}finally{try{unlinkSync(s)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),s=this.gatherContentFilesSync(),g=await this.listHeadContentPaths(e,t);if(s.length===0&&g.size===0)return null;let S=join(tmpdir(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),w=this.gitHandle(S);try{await w.git.raw([`read-tree`,t]);let S=100;for(let e=0;e<s.length;e+=100){let t=s.slice(e,e+100).map(e=>e.projectRelPath);await w.git.raw([`add`,`--`,...t])}let E=new Set(s.map(e=>e.projectRelPath)),D=[...g].filter(e=>!E.has(e));await this.removePathsFromIndex(w,D);let O=(await w.git.raw([`write-tree`])).trim();if(O===(await w.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let k=[];try{k=await listNames(w.git,[`diff-tree`,`--name-only`,`-r`,t,O])}catch{k=s.map(e=>e.projectRelPath).concat(D)}let j=await resolveGitIdentity(this.projectDir),F=j?.name??`OpenKnowledge`,L=j?.email??`sync@open-knowledge.local`;applyGitEnv(w,{GIT_AUTHOR_NAME:F,GIT_AUTHOR_EMAIL:L,GIT_COMMITTER_NAME:F,GIT_COMMITTER_EMAIL:L});let B=(await w.git.raw([`commit-tree`,O,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!B||!SHA_HEX_40.test(B)?(log$1.warn({raw:B},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,B,t]),await this.resetRealIndexForPaths(k,e),B)}finally{try{unlinkSync(S)}catch{}}}async prepareForMerge(e,t){let s;try{s=await listNames(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return log$1.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}if(s.length===0)return{proceed:!0,needsStashPop:!1};let g;try{g=new Set(await listNames(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return log$1.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}let S=s.filter(e=>g.has(e));if(S.length>0){let e=S.slice(0,3).join(`, `),t=S.length>3?`, +${S.length-3} more`:``;return 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.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log$1.warn({files:S},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1}}let w=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,w])}catch(e){return log$1.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1}}return{proceed:!0,needsStashPop:!0}}async popPreMergeStash(e){try{await e.git.raw([`stash`,`pop`])}catch(e){log$1.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}gatherContentFilesSync(){let e=[],t=s=>{let g;try{g=readdirSync(s,{withFileTypes:!0})}catch{return}for(let S of g){let g=join(s,S.name);if(S.isDirectory()){let e=toPosix(relative(this.contentDir,g));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e))continue;t(g)}else if(S.isFile()||S.isSymbolicLink()){let t=toPosix(relative(this.contentDir,g));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let s=toPosix(relative(this.projectDir,g));e.push({contentRelPath:t,projectRelPath:s})}}}};return existsSync(this.contentDir)&&t(this.contentDir),e}async listHeadContentPaths(e,t){let s=new Set;try{let g=await listNames(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of g){let t=join(this.projectDir,e),g=toPosix(relative(this.contentDir,t));!g.startsWith(`..`)&&!this.contentFilter.isExcluded(g)&&s.add(e)}}catch{}return s}async removePathsFromIndex(e,t){if(t.length===0)return;let s=[...new Set(t)],g=100;for(let t=0;t<s.length;t+=100){let g=s.slice(t,t+100);await e.git.raw([`rm`,`--cached`,`--`,...g])}}async resetRealIndexForPaths(e,t){if(e.length===0)return;let s=t??this.gitHandle(),g=[...new Set(e)],S=100;for(let e=0;e<g.length;e+=100){let t=g.slice(e,e+100);try{await s.git.raw([`reset`,`HEAD`,`--`,...t])}catch{}}}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 listNames(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){log$1.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.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 s=[],g=[];for(let e of t){let t=join(this.projectDir,e),S=toPosix(relative(this.contentDir,t));!S.startsWith(`..`)&&isSupportedDocFile(S)&&!this.contentFilter.isExcluded(S)?s.push(e):g.push(e)}let S=[];for(let t of g)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log$1.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log$1.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),S.push({file:t,err:e})}if(S.length>0){let t=S.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let s=t.slice(0,3).join(`, `),g=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${s}${g}. 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.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log$1.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(s.length>0){for(let e of s)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(s),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log$1.warn({files:s},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),log$1.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log$1.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log$1.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){log$1.warn({err:t,files:e},`[sync] content conflict callback failed`)}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){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),log$1.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.ghTokenSource.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,log$1.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`||this.pausedReason===`auth-error`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};writeFileSync(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$1.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason===`no-push-permission`||t.pausedReason===`auth-error`?void 0:t.pausedReason;let s=t.inflightConflicts??[];if(s.length>0){for(let e of s)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log$1.warn({err:e},`[sync] failed to load sync state`)}}};const MOUNT_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function createSyncHandshakeSpanExtension(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(isSystemDoc(e)||isConfigDoc(e))return;let s=t?.get(`mountId`)??void 0,g={"doc.name":e};s!==void 0&&MOUNT_ID_PATTERN.test(s)&&(g[`mount.id`]=s);try{withSpanSync(`sync.handshake`,{attributes:g},()=>{})}catch(e){console.warn(`[sync-handshake-span] emission failed:`,e instanceof Error?e:String(e))}}}}const TAG_VALUE_RE=createTagInTextRegex();function createEmptyState(){return{byTag:new Map,byDoc:new Map,byDocLiteral:new Map}}function stripInlineCodeSpans(e){return e.replace(/`[^`]*`/g,``)}function extractInlineTagsFromBody(e){let t=e.replaceAll(`\r
|
|
3251
3251
|
`,`
|
|
3252
3252
|
`).split(`
|
|
3253
|
-
`),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);if(e===null)break;let t=e[2];t&&s.push(t)}}return s}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();initChain=Promise.resolve();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!isLinkIndexExcludedDoc(e))try{let{frontmatter:s,body:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isLinkIndexExcludedDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let s of t){let t=this.state.byTag.get(s);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(s))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,s){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,s)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let s=[];for(let g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].sort((e,t)=>e.localeCompare(t))})}return s.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),s=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&s.add(e.slice(0,t));let g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!s.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){let e=this.initChain.then(()=>this.initOnce());return this.initChain=e.catch(e=>{console.warn(`[tag-index] init failed (chain cleared for next init):`,e)}),e}async initOnce(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=await this.listDocsWithPaths(),t=50;for(let t=0;t<e.length;t+=50){let s=e.slice(t,t+50),g=await Promise.all(s.map(async({docName:e,filePath:t})=>{try{return{docName:e,markdown:await readFile$1(t,`utf-8`)}}catch(t){return console.warn(`[tag-index] Failed to read ${e} during init:`,t),null}}));for(let e of g)if(e)try{this.updateDocumentFromMarkdown(e.docName,e.markdown)}catch(t){console.warn(`[tag-index] Failed to index ${e.docName} during init:`,t)}}}applyDocSnapshot(e,t,s){let g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.size===0&&this.state.byTag.delete(t))}for(let t of s){let s=this.state.byTag.get(t);s||(s=new Set,this.state.byTag.set(t,s)),s.add(e)}s.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,s),this.state.byDocLiteral.set(e,t))}async listDocsWithPaths(){let e=[];await this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}async walkContentDir(e,t){let s;try{s=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=toPosix(relative(this.contentDir,s));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=toPosix(relative(this.contentDir,s));this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),filePath:s})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function buildSyncCredentialArgs(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(shellEscape).join(` `)} auth git-credential`]}function resolveUpstreamChanges(e,t,s,g){let S=new Map;if(!s)return S;let w;try{w=spawnSync(`git`,[`-c`,`core.quotePath=false`,`log`,`${s}..${g}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],{cwd:e,encoding:`utf-8`,timeout:5e3})}catch(e){return getLogger(`upstream-attribution`).warn({err:e,oldHead:s,newHead:g},`git log spawn threw; upstream docs keep file-system attribution`),S}if(w.error||w.status!==0||typeof w.stdout!=`string`)return getLogger(`upstream-attribution`).warn({err:w.error,status:w.status,signal:w.signal,stderr:typeof w.stderr==`string`?w.stderr.slice(0,500):void 0,oldHead:s,newHead:g},`git log failed; upstream docs keep file-system attribution`),S;let E=null;for(let s of w.stdout.split(`
|
|
3254
|
-
`)){let g=s.trim();if(g===``)continue;if(g.startsWith(`C\0`)){let[,e,t]=g.split(`\0`);E=e&&t?{name:e,email:t}:null;continue}if(!E||!g.endsWith(`.md`)&&!g.endsWith(`.mdx`))continue;let w=resolve(e,g);if(!isWithinContentDir(w,t))continue;let D=pathToDocName(w,t);S.has(D)||existsSync(w)&&S.set(D,E)}return S}function createServer$1(e){let{contentDir:t,projectDir:s=t,quiet:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1,singleDocRelPath:ee,ephemeral:J=!1}=e,Y=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=isKnownConfigError(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}Y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function ne(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;if(t!=null)return t===!0;e.valid||Y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let g=readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});return g.valid||Y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),g.value.autoSync?.default===!0}function ae(){return readProjectLocalSemanticConfig(s,{configHomedirOverride:k,onWarn:e=>Y.warn({message:e},`[config] could not read project-local config`)})}function oe(e){return`${normalizeProviderId(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}function se(e){let t;(e===`__config__/project`||e===`__local__/project`)&&(t=ne(),jr?.setEnabled(t).catch(s=>{Y.warn({err:s,enabled:t,docName:e},`[sync] failed to apply autoSync.enabled from config`)}));let s=ae();ze.applyConfig({enabled:s.enabled,providerFingerprint:oe(s)}),Y.info({docName:e,autoSyncEnabled:t,semanticEnabled:s.enabled},`[config] applied persisted config to in-process consumers`)}initTelemetry();let ce=randomUUID(),ue=getLocalDir(s);if(acquireServerLock(ue,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:ue,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(ue),e}let de=createBasenameIndex(),fe=(e,t)=>de.resolveEmbed(e,t),me=(e,s)=>{let g=de.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g);if(!isWithinDir(S,resolve(t)))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},ge,_e,ve,ye,Ce,we,Te,De,je=null,Me=null,Pe=null,Ie=null,Re=ae(),ze=new SemanticSearchService({loadEmbedder:e.embedderLoader??(()=>{let t=ae();return loadOpenAiEmbedder({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:join(getLocalDir(s),`embeddings`),enabled:Re.enabled,providerFingerprint:oe(Re)}),Be=null,Ve=new Set,Ue=!1,We,Ge,Ke,Xe=new Promise((e,t)=>{Ge=e,Ke=t});function $e(e){je?.signal(e)}let nt=2e3,rt=null;function it(){rt!==null&&clearTimeout(rt),rt=setTimeout(()=>{rt=null,_e.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let at=2e3,st=null,vt=!1,St=()=>{try{saveRemovedDocsJournal(s,Tt.entries())}catch(e){Y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Tt=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e),onMutate:()=>{!vt||st!==null||(st=setTimeout(()=>{st=null,St()},2e3))}});for(let[e,g]of loadRemovedDocsJournal(s))isReservedForUserTree(e)||isSafeDocName(e)&&([`.md`,`.mdx`].some(s=>{let g=resolve(t,`${e}${s}`);return isWithinDir(g,resolve(t))&&existsSync(g)})||Tt.restore(e,g));vt=!0;let Et=(e,t)=>{isReservedForUserTree(e)||Tt.setRenamed(e,t)},jt=e=>{if(!isReservedForUserTree(e)){if(Tt.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Tt.setDeleted(e)}},Mt=e=>{isReservedForUserTree(e)||Tt.delete(e)};try{ge=createContentFilter({projectDir:s,contentDir:t,singleDocRelPath:ee,onAfterRebuild:()=>{_e.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),ve.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),reconcileFileIndexAfterFilterRebuild(rn).then(({prunedFiles:e,prunedFolders:t})=>{let s=e+t;s>0?getLogger(`server-factory`).info({pruned:s,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):getLogger(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),_e=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:ge}),ve=new TagIndex({contentDir:t,contentFilter:ge}),ve.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[server-factory] tag-index init failed; continuing with empty index`)}),ye={current:F},Ce=E?createMaintenanceCoordinator({getShadow:()=>ye.current??null,getCurrentBranch:()=>sn?.getLastKnownBranch()??null,contentRoot:L??``,projectGitDir:resolveGitDir(s)??void 0,isWriterLive:e=>{if(!Pe&&!De)return getLogger(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Pe?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of De?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,we=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:ye,ephemeral:J,contentRoot:L,backlinkIndex:_e,configHomedirOverride:k,getCurrentBranch:()=>sn?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:me,getPrincipal:()=>Be,onAgentCommit:()=>je?.signal(`session-activity`),onFlushCommit:()=>Ce?.noteFlushCommit(),onDiskFlush:(e,t,s,g)=>{je?.emitDiskAck(e,t),!isReservedForUserTree(e)&&assetReferencesChanged(g,s)&&(Ie?.(),$e(`files`))},onConfigRejected:(e,t)=>je?.emitConfigValidationRejected(e,t),onConfigPersisted:se,isRecentlyRemoved:e=>Tt.has(e),mdManager:e.mdManager}),Te=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[we.extension]});let B=Te.shouldUnloadDocument.bind(Te);Te.shouldUnloadDocument=e=>{if(Ve.has(e)||Ue&&B(e))return!0;let t=e.name;return isReservedForUserTree(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},We=async e=>{Ve.add(e);try{await Te.unloadDocument(e)}finally{Ve.delete(e)}},je=new CC1Broadcaster(Te),Me=new AgentFocusBroadcaster(Te),Pe=new AgentPresenceBroadcaster(Te),De=new AgentSessionManager(Te);let q=createLiveDerivedIndexExtension({backlinkIndex:_e,tagIndex:ve,signalChannel:$e});Te.configuration.extensions.push(q),Te.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,s=parseHocuspocusAuthToken(t),g=s?.expectedServerInstanceId;if(typeof g==`string`&&g.length>0&&g!==ce)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ce}`);let S=s?.expectedBranch,w=getActiveBranch();if(typeof S==`string`&&S.length>0&&S!==w)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${S}, server is on ${w}`);if(!s)return;let E=e.context;typeof s.principalId==`string`&&(Be&&s.principalId===Be.id?E.principalId=Be.id:Be?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Be.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),Te.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName)&&!isManagedArtifactDoc(e.documentName))return;let t=e.request,s=t.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s))throw Error(`config-doc admission requires loopback peer (peer=${s}, doc=${e.documentName})`);let g=e.requestHeaders,S=(g&&typeof g.get==`function`?g.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(S))throw Error(`config-doc admission requires loopback Host header (host=${S??`<absent>`}, doc=${e.documentName})`)}});let Y=resolve(t);function ne(e){if(!isSafeDocName(e))return null;let t=resolve(Y,docNameToRelativePath(e));return isWithinDir(t,Y)?t:null}Te.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:Tt,resolveFilePath:ne,fileExists:existsSync})}}),Te.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=parseHocuspocusAuthToken(e.token);runDocLineageGuard(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Te.documents.get(e)})}}),Te.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let oe=createApiExtension({hocuspocus:Te,sessionManager:De,contentDir:t,contentFilter:ge,serverInstanceId:ce,getFileIndex:()=>rn?rn.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>rn?rn.getAllFilesIndex():new Map,getFileIndexGeneration:()=>rn?.getFileIndexGeneration()??0,mutateFileIndex:e=>rn?.mutateFileIndex(e),getFolderIndex:()=>rn?rn.getFolderIndex():new Map,getAliasMap:()=>rn?rn.getAliasMap():new Map,getFolderAliasIndex:()=>rn?rn.getFolderAliasIndex():new Map,rescanFiles:()=>rn?.rescanFromDisk(),enableTestRoutes:j,shadowRef:ye,flushGitCommit:()=>we.flushPendingGitCommit(),flushContributors:()=>we.flushContributors(),takeStoreFailure:e=>we.takeStoreFailure(e),takeStoreDivergence:e=>we.takeStoreDivergence(e),markAgentWriteStore:e=>we.markAgentWriteStore(e),getCurrentBranch:()=>sn?.getLastKnownBranch()??null,getDiskAckSVs:()=>je?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:_e,tagIndex:ve,signalChannel:$e,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>jr,localOpCliArgs:H,projectDir:s,resolveEmbed:fe,getPrincipal:()=>Be,homeDirOverride:k,forceUnloadDocument:We,ready:Xe,recentlyRemovedDocs:Tt,serializeDoc:zt,evictManagedArtifactLkg:e=>{we.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:ze,getSemanticSimilarityFloor:()=>ae().similarityFloor,embeddingsSecretsFile:secretsFilePath(k),ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{Ie=e}});Te.configuration.extensions.push(oe),Te.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:ye,contentRoot:L,getCurrentBranch:()=>sn?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:me})),Te.configuration.extensions.push(createSyncHandshakeSpanExtension()),Te.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>jr,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(ue),e}let Ft=null,It=new Map,Lt=[];function Rt(e,t){let s=resolve(e,`rescue`),g=resolve(s,docNameToRelativePath(t));return isWithinDir(g,s)?g:null}function zt(e){let t=Te.documents.get(e);return t?serializeYDocSource(t):null}let Bt=(e,t)=>applyExternalChange(Te,e,t,fe,me);function Vt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Ht=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of Te.documents){if(isReservedForUserTree(s))continue;let g=Te.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,fe,s)},FILE_WATCHER_ORIGIN)}catch(t){Y.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},Ut=null,Wt=e=>{e&&(Ut===null&&(Ut=new Set,setImmediate(()=>{let e=Ut;if(Ut=null,e)try{for(let t of e)Ht(t)}catch(t){Y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Ut.add(e))};function Xt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Zt(e){try{switch(e.kind){case`create`:Y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),_e.updateDocumentFromMarkdown(e.docName,e.content),it(),ve.updateDocumentFromMarkdown(e.docName,e.content),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),Mt(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=Te.documents.get(t);if(!g){_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`);return}let S=getReconciledBase(t)??``,w=zt(t)??S,E=reconcile({docName:t,base:S,ours:w,theirs:s}),D=contentHash(S).slice(0,6),O=contentHash(w).slice(0,6),k=contentHash(s).slice(0,6);switch(Y.info({docName:t,base:D,ours:O,theirs:k,result:E.kind},`[reconcile] ${t} base=${D} ours=${O} theirs=${k} result=${E.kind}`),E.kind){case`noop`:Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`);break;case`clean`:try{Bt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),Vt(g)}break;case`merged`:try{Bt(t,E.newContent),setReconciledBase(t,s),incrementReconcile(),Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),Vt(g)}break;case`conflicts`:try{Bt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,s)}{let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{incrementConflict();let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,E.reason);break}}break}case`delete`:{let{docName:t}=e,s=Te.documents.get(t);if(!s){_e.deleteDocument(t),it(),ve.deleteDocument(t),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),jt(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=zt(t)??``,w=S!==g;if(w&&ye.current){let e=ye.current,s=sn?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,L??``,{kind:`external-change-rescue`,docName:t,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:s,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),Y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{Y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),_e.deleteDocument(t),it(),ve.deleteDocument(t),Y.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),Te.closeConnections(t),await We(s),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),jt(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:s,content:g}=e,S=Te.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),_e.renameDocument(t,s,g),it(),ve.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}Y.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),Et(t,s),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:s,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,s=Te.documents.get(t);if(!s)return;let g=zt(t);g===null?Y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,g);let S=s.getMap(`lifecycle`);S.set(`status`,`conflict`),S.set(`reason`,`conflict-markers`),Y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:de.add(e.relativePath),$e(`files`),Wt(basename(e.relativePath));break;case`asset-delete`:de.remove(e.relativePath),$e(`files`),Wt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:$e(`files`);break;case`file-create`:case`file-update`:case`file-delete`:$e(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Xt(e);Y.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let $t=[];async function en(e){if(isBatchInProgress()){$t.push(e);return}await Zt(e)}async function tn(){let e=$t.splice(0,$t.length);for(let t of e)await Zt(t)}let rn=null,sn=null,jr=null,Mr=null;async function zr(e){if(Te.documents.size===0)return;let t=!1,s=new Promise(e=>{Te.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(Te.documents.keys());Te.closeConnections(),Te.flushPendingStores();for(let e of Te.documents.values())e.getConnectionsCount()===0&&Te.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let S,w=new Promise((s,w)=>{S=setTimeout(()=>{t=!0;let s=Array.from(Te.documents.keys()),S=[],E=[];if(ye.current){for(let e of s)if(!isReservedForUserTree(e))try{let t=zt(e);if(t===null){Y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=Rt(ye.current.gitDir,e);if(!s){Y.warn({docName:e,gitDir:ye.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),E.push(e);continue}mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,t,`utf-8`),incrementRescueBuffer(),S.push(e),Y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),Y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else Y.warn({stillLoadedCount:s.length},`[rescue] shadow repo unavailable at flush timeout — ${s.length} doc(s) will be lost: [${s.join(`, `)}]`),E.push(...s);let D=S.length>0||E.length>0?` — rescued [${S.join(`, `)}]${E.length>0?`, lost [${E.join(`, `)}]`:``}`:``;w(Error(`flushAllStoresAndWait timeout after ${e}ms — ${s.length}/${g.length} docs did not unload: [${s.join(`, `)}]${D}`))},e)});try{await Promise.race([s,w])}finally{S!==void 0&&clearTimeout(S)}}async function Br(){return Mr||(Mr=(async()=>{let e=Date.now(),t=[];Ue=!0;try{markServerLockDraining(ue)}catch(e){Y.warn({err:e},`[server] failed to mark server.lock draining`)}if(rt!==null&&(clearTimeout(rt),rt=null),st!==null&&(clearTimeout(st),st=null),vt)try{saveRemovedDocsJournal(s,Tt.entries())}catch(e){Y.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let g,S=await Promise.race([Xe.then(()=>`completed`,e=>(Y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&Y.warn({},`[server] init did not complete within 5s during shutdown`);let w=Te.documents.size;Ce?.destroy();try{try{try{sn&&=(await sn.unsubscribe(),null),rn&&=(await rn.unsubscribe(),null);for(let{docName:e,cleanup:t}of Lt)try{await t()}catch(t){Y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Lt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{je?.destroy(),Pe?.destroy(),Ft&&=(await Ft.disconnect(),null);for(let[e,t]of It)try{await t.disconnect()}catch(t){Y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}It.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await De.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await zr(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await we.flushPendingGitCommit(),await we.waitForPendingCommits()})(),new Promise((t,s)=>{e=setTimeout(()=>s(Error(`L2 git flush timeout`)),B)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{jr&&=(await jr.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(ye.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(ye.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(ye.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?Y.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):Y.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ue,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Mr)}let Vr=[];async function Hr(){try{Be=await loadPrincipal(s),Y.info({principalId:Be.id},`[server] principal loaded`)}catch(e){Y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!ye.current)try{ye.current=await initShadowRepo(s),Y.info({gitDir:ye.current.gitDir},`[server] history repo initialized at ${ye.current.gitDir}`)}catch(e){Y.error({err:e},`[server] history repo init failed`),Vr.push(`shadow-repo`)}if(ye.current){let e=null;try{e=loadRenameLogIndex(ye.current.gitDir),sweepLazyPopOrphans(ye.current.gitDir,e),setRenameLogIndex(ye.current.gitDir,e),Y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){Y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(ye.current,e,{rebuild:!0}),new Promise((e,s)=>setTimeout(()=>s(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){Y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await Ce?.runBootMaintenance()}catch(e){Y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(ye.current)try{await shadowGit(ye.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){Y.warn({},`[server] history repo appears corrupted — reinitializing`);try{ye.current=await initShadowRepo(s)}catch(e){Y.error({err:e},`[server] history repo reinit failed`),ye.current=void 0,Vr.includes(`shadow-repo`)||Vr.push(`shadow-repo`)}}else Y.error({err:e},`[server] history repo check failed (transient?)`)}if(ye.current)try{let e=resolve(ye.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let g=null;try{g=(await esm_default({baseDir:s,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(g!==null){if(g!==t){let e=`main`;try{let t=(await esm_default({baseDir:s,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}Y.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(ye.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){Y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else Y.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){Y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){Y.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,s);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,s=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;Y.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){Y.error({err:e},`[server] managed rename recovery failed`),Vr.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(s);(e.deleted>0||e.errors>0)&&Y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){Y.error({err:e},`[server] upload-tempfile sweep failed`),Vr.push(`upload-tempfile-sweep`)}try{Ft=await Te.openDirectConnection(SYSTEM_DOC_NAME),je?.emitServerInfo(ce,getActiveBranch())}catch(e){Y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Vr.push(`cc1-push`)}let g=J?[]:CONFIG_DOC_NAMES;for(let e of g)try{let t=await Te.openDirectConnection(e);It.set(e,t)}catch(t){Y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Vr.push(`config-doc:${e}`)}let S=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,s)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,s)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,s,k)]]);for(let e of g){let t=S.get(e);if(t)try{Y.info({docName:e,path:t},`[config-file-watcher] starting`);let s=await startConfigFileWatcher(t,t=>{let s=Te.documents.get(e);Y.info({docName:e,hasDocument:s!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,e,t,we.configPersistenceCtx);Y.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),se(e)});Lt.push({docName:e,cleanup:s}),Y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(s){Y.warn({err:s,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Vr.push(`config-file-watcher:${e}`)}}if(!J){let e=(e,t)=>{let s=managedArtifactDocNameForPath(e,we.managedArtifactCtx);if(!s)return;let g=applyExternalManagedArtifactChange(Te.documents.get(s)??null,s,t,we.managedArtifactCtx);Y.info({docName:s,outcome:g},`[managed-artifact-watcher] external change`),parseGlobalSkillBundleDoc(s)&&_e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),getActiveBranch()).then(()=>{$e(`backlinks`),$e(`graph`)}).catch(e=>{Y.warn({err:e,docName:s},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=managedArtifactSkillsRoots(we.managedArtifactCtx),s=await startManagedArtifactWatcher(t,e);Lt.push({docName:`__skill-files__`,cleanup:s}),Y.info({roots:t},`[managed-artifact-watcher] skills started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),Vr.push(`managed-artifact-watcher:skills`)}try{let t=new Set([``]);try{for(let e of resolveProjectTemplates(s).templates)t.add(e.source_folder)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let g=[...t].map(e=>e?resolve(s,e,`.ok`,`templates`):resolve(s,`.ok`,`templates`)),S=await startManagedArtifactWatcher(g,e,TEMPLATE_WATCH_OPTIONS);Lt.push({docName:`__template-files__`,cleanup:S}),Y.info({rootCount:g.length},`[managed-artifact-watcher] templates started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),Vr.push(`managed-artifact-watcher:templates`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:s,encoding:`utf-8`,timeout:5e3});if(e.status===0&&e.stdout){let t=join(resolve(s,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(S=t)}}catch{}let w=S?[e,g,S]:[e,g],E=Y;E.info({okignorePath:e,gitignorePath:g,gitInfoExcludePath:S,ephemeral:J},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let D=J?null:await startMultiPathConfigFileWatcher(w,(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(Te.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,we.configPersistenceCtx);E.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){E.error({err:e,changedPath:relative(s,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let S=await ge.rebuildIgnorePatterns();if(S.ok)E.info({changedPath:relative(s,t),patternCount:S.patternCount,nestedFileCount:S.nestedFileCount,durationMs:S.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),je?.signal(`files`);else{let e=relative(s,t)||`.`;E.warn({changedPath:e,error:S.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),je?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});D&&(Lt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`))}catch(e){Y.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Vr.push(`ignore-files-watcher`)}let w=resolveGitDir(s),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),_e.switchBranch(E);let D=performance.now();try{await withSpan(`ok.boot.indexes`,void 0,async()=>{let e=getActiveBranch();try{if(await _e.loadFromDisk(e)){let t=await _e.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&Y.info({added:t.added,updated:t.updated,deleted:t.deleted},`[backlinks] startup reconcile: offline changes applied`);let s=0;for(let e of t.deletedDocNames)isReservedForUserTree(e)||Tt.peek(e)?.kind!==`renamed`&&(Tt.setDeleted(e),s++);s>0&&Y.info({count:s},`[removal-guard] tombstoned docs deleted while the server was down`)}else await _e.rebuildFromDisk(e);try{await _e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),e)}catch(t){Y.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}_e.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){Y.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}let s=performance.now();rn=await withSpan(`ok.boot.seed-walk`,void 0,async()=>startWatcher(t,en,ge)),recordBootPhase(`seedWalkMs`,Math.round(performance.now()-s));{let e=resolve(t),s=0;for(let[t]of Tt.entries()){if(!isSafeDocName(t))continue;let g=resolve(e,`${t}${getDocExtension(t)}`);isWithinDir(g,e)&&existsSync(g)&&(Tt.delete(t),s++)}s>0&&Y.info({count:s},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}try{await ve.init()}catch(e){Y.error({err:e},`[tag-index] startup re-init failed; tag index updates incrementally via watcher events`),Vr.push(`tag-index`)}let g=0;try{ee===void 0?await seedBasenameIndex({contentDir:t,contentFilter:ge,basenameIndex:de,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):seedSingleDirBasenameIndex({contentDir:t,basenameIndex:de,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),g>0&&(Y.warn({count:g},`[basename-index] startup seed completed with ${g} skipped entries — embeds under inaccessible subtrees will not resolve`),Vr.push(`basename-index-partial`))}catch(e){Y.error({err:e},`[basename-index] startup seed failed`),Vr.push(`basename-index`)}})}catch(e){Y.error({err:e},`[server] disk bridge watcher failed to start`),Vr.push(`file-watcher`)}finally{recordBootPhase(`indexesMs`,Math.round(performance.now()-D)),rn&&setBootField(`fileCount`,rn.getFileIndex().size)}try{sn=await startHeadWatcher(s,async({trigger:e})=>{if(Y.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),Te.flushPendingStores(),await we.flushPendingGitCommit(),setBatchInProgress(!0),ye.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of Te.documents){if(isReservedForUserTree(e))continue;let s=null;if(t.transact(()=>{s=zt(e)},PARK_SNAPSHOT_ORIGIN),s===null)continue;let g=getReconciledBase(e)??s;S.push({docName:e,markdown:s,diskSnapshot:g})}if(S.length>0)try{let t=await parkBranch(ye.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),Y.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){Y.error({err:e},`[shadow] park failed`)}}},async e=>{let g=$t.length,S=e.newBranch??`main`;if(Y.info({kind:e.batchKind,headMoved:e.headMoved,docs:g,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${g}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await tn(),e.headMoved&&e.newHead){let g=resolveUpstreamChanges(s,resolve(t),e.oldHead,e.newHead);if(g.size>0){dropPendingDocs(g.keys());for(let[e,t]of g)recordContributor(e,gitAuthorWriterId(t.email),t.name,t.email,formatReconcileSubject(e));await we.flushContributors()}}if(await we.flushDeferredStores(`within-branch`),jr!==null)try{await jr.reconcileConflictsFromGit()}catch(e){Y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),$t.splice(0,$t.length),switchReconciledBaseScope(S),rt!==null&&(clearTimeout(rt),rt=null),_e.switchBranch(S),ge.rebuildDirCount();try{let e=0;de.clear(),await seedBasenameIndex({contentDir:t,contentFilter:ge,basenameIndex:de,onSkip:(t,s,g)=>{e++,Y.warn({reason:t,code:s,path:g,branch:S},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e,branch:S},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Vr.includes(`basename-index-partial`)||Vr.push(`basename-index-partial`))}catch(e){Y.error({err:e,branch:S},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of Te.documents)if(!isReservedForUserTree(e))try{let g=safeContentPath(e,t);if(!existsSync(g)){let t=getReconciledBase(e)??``,g=zt(e)??``;if(g!==t&&ye.current){let t=ye.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:g,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),Y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{Y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Y.info({docName:e,branch:S},`[branch-switch] tombstone: ${e} (not on ${S})`);continue}let w=readFileSync(g,`utf-8`);Bt(e,w),setReconciledBase(e,w),Y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){Y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}Y.info({branch:S,docCount:Te.documents.size},`[branch-switch] loaded branch ${S} (${Te.documents.size} docs)`);try{if(await _e.loadFromDisk(S)){let e=await _e.reconcileWithDisk(S);(e.added>0||e.updated>0||e.deleted>0)&&Y.info(e,`[backlinks] branch-switch reconcile for ${S}`)}else await _e.rebuildFromDisk(S);try{await _e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),S)}catch(e){Y.warn({err:e,branch:S},`[backlinks] branch-switch global skill bundle ingest failed`)}_e.saveToDisk(S).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${S}:`,e)})}catch(e){Y.error({err:e,branch:S},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(await ve.init(),ye.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Te.documents)if(!isReservedForUserTree(t))try{let s=await readParkedState(ye.current,S,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let g=getReconciledBase(t);if(!g)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:g});switch(w.kind){case`merged`:case`clean`:Bt(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:Bt(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=Te.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){Y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&Y.info({count:e,branch:S},`[branch-switch] restored ${e} parked docs on ${S}`)}if(e.oldBranch?.startsWith(`detached-`)&&ye.current)try{let t=shadowGit(ye.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
|
|
3255
|
-
`))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await we.flushDeferredStores(`discard-stale`),je?.emitBranchSwitched(S)}if(e.headMoved&&e.newHead&&ye.current&&g>0){let t=L??`.`;try{let s=await commitUpstreamImport(ye.current,t,e.oldHead,e.newHead,S);incrementUpstreamImport(),Y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Vr.push(`head-watcher`)}function O(e){for(let g of e)try{let e=toPosix(relative(t,join(s,g)));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=Te.documents.get(S);if(!w)continue;let E=zt(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let j=buildSyncCredentialArgs(H);try{jr=new SyncEngine({projectDir:s,contentDir:t,contentFilter:ge,contentRoot:L,syncEnabled:ne(),credentialArgs:j,cc1Broadcaster:je,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||we.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:O,onAutoDisable:async e=>{Y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||Y.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await jr.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),jr=null}$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`);let F=bootElapsedMs();F!==void 0&&recordBootPhase(`readyMs`,F)}return Hr().then(Ge,Ke),{hocuspocus:Te,sessionManager:De,cc1Broadcaster:je,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,maintenanceCoordinator:Ce,contentFilter:ge,basenameIndex:de,serverInstanceId:ce,destroy:Br,ready:Xe,degraded:Vr,lockDir:ue,get syncEngine(){return jr}}}const SERVER_MEMORY_SCHEMA_VERSION=1,BYTES_PER_MB=1024*1024;function toMb(e){return e/BYTES_PER_MB}function captureServerMemorySnapshot(){let e=process.memoryUsage();return{schemaVersion:SERVER_MEMORY_SCHEMA_VERSION,capturedAt:new Date().toISOString(),snapshot:{rssMb:toMb(e.rss),heapTotalMb:toMb(e.heapTotal),heapUsedMb:toMb(e.heapUsed),externalMb:toMb(e.external),arrayBuffersMb:toMb(e.arrayBuffers)}}}let cachedGauge=null;onTelemetryShutdown(()=>{cachedGauge=null});function installServerMemoryGauge(){if(cachedGauge)return;let e=getMeter().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=captureServerMemorySnapshot();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),cachedGauge=e}const TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`,TELEMETRY_PREV_FILENAME=`tolerance-telemetry.prev.jsonl`,TELEMETRY_MAX_BYTES=8*1024*1024;let appender=null,appendFailureWarned=!1;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);appender=new RotatingAppender({currentPath:resolve(t,TELEMETRY_FILENAME),previousPath:resolve(t,TELEMETRY_PREV_FILENAME),maxBytes:TELEMETRY_MAX_BYTES}),setToleranceTelemetryHook(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};appender?.append(`${JSON.stringify(t)}\n`).catch(e=>{appendFailureWarned||(appendFailureWarned=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null),await appender?.drain(),appender=null,appendFailureWarned=!1}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let s=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&s.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let g=resolve(e,t);try{existsSync(g)&&statSync(g).isDirectory()&&s.push(`${t}/`)}catch{}}return s}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){startBootTimings();let t=e.projectDir??e.contentDir,s=resolveLocalSinkConfig({projectDir:t});if(s){let e=s.telemetry.attributeDenylist,t=[];for(let s of e){t.push(s);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)t.push(`${`*.`.repeat(e)}${s}`)}loggerFactory.configure({pinoConfig:{fileSink:s.logs,redactPaths:t}})}initTelemetry({localSink:s?.telemetry}),initToleranceTelemetryWriter(t),installServerMemoryGauge();let{kind:g,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":g};S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S));let E=process.env.OK_STARTUP_TRACEPARENT,D=()=>withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e));if(E)try{let e=propagation.extract(context.active(),{traceparent:E});return context.with(e,D)}catch(e){getLogger(`boot`).warn({err:e instanceof Error?e.message:String(e)},`ok.boot trace-join failed — starting unparented boot`)}return D()}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{markServerLockDraining:O,releaseServerLock:k,updateServerLockPort:j}=await import(`./server-lock-GuuouVft-BFFcTQcA.mjs`),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let H=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&H()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let q=findLegacyRuntimeFiles(B);q.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${q.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let ee=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:J,destroy:Y,ready:te,degraded:ne,lockDir:ae,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,maintenanceCoordinator:ue}=ee,de=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),fe=e.port??0,me=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${de}:${fe}`,log:S}),ge=D();ge.headersTimeout=3e4,ge.requestTimeout=6e4;let _e=e.serveContentAssets?createAssetServeMiddleware({contentFilter:ee.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ve=!1;if(e.reactShellDistDir)try{acquireUiLock(ae,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ve=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:ae},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await Y().catch(()=>{}),k(ae),e}let ye=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,Ce=mountMcpAndApi({httpServer:ge,hocuspocus:J,mcpHttpHandler:me,log:S,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,maintenanceCoordinator:ue,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:_e,reactShellMiddleware:ye,ephemeral:e.ephemeral}),we=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Te=null;g!==null&&(Te=attachIdleShutdown({httpServer:ge,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await we()})})),await restoreLifecycleFromConflictsJson({hocuspocus:J,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);ge.once(`error`,g),ge.listen(e.port,e.host,()=>{ge.removeListener(`error`,g),t()})})}catch(e){if(ve)try{releaseUiLock(ae)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await Y().catch(()=>{}),k(ae),e}let De=bootElapsedMs();De!==void 0&&recordBootPhase(`httpListenMs`,De);let je=ge.address(),Me=typeof je==`object`&&je?je.port:e.port??0;if(fe=Me,j(ae,Me),ve&&updateUiLockPort(ae,Me),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ae,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let Pe=!1,Ie=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};we=async()=>{if(Pe)return;Pe=!0;let e=[],t=async(t,s)=>{try{await Ie(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{O(ae),ve&&markUiLockDraining(ae)}catch(e){S.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{Te?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>Ce.shutdown()),me!==void 0&&await t(`mcpHttpHandler.close`,()=>me.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{Ce.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{ge.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ge.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>Y()),ve&&await t(`releaseUiLock`,async()=>releaseUiLock(ae,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await reconcileSkillInstalls({projectDir:L,skillsRoot:resolve(e.contentDir,`.ok`,`skills`)}),s=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;s>0&&S.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${s} editor skill entr${s===1?`y`:`ies`} to the symlink model.`)}catch(e){S.warn?.({event:`installed-skills-reconcile-failed`,error:String(e)},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:ge,destroy:we,lockDir:ae,contentDir:e.contentDir,port:Me,ready:te,degraded:ne,didAutoInit:F,serverInstance:ee}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=simpleGit({baseDir:s,timeout:{block:5e3}});E=new Set(await listNames(g,[`diff`,`--name-only`,`--diff-filter=U`]))}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!0});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},g)}function flushFileLogger(e,t=250){return new Promise(s=>{if(!e){s();return}let g=e[import_pino.default.symbols.streamSym],S=!1,w=()=>{S||(S=!0,s())};if(!g||typeof g.flushSync!=`function`){w();return}let E=()=>{try{g.flushSync?.()}catch{}w()},D=setTimeout(w,t);typeof D.unref==`function`&&D.unref(),typeof g.fd==`number`&&g.fd>=0?(clearTimeout(D),E()):typeof g.once==`function`?g.once(`ready`,()=>{clearTimeout(D),E()}):(clearTimeout(D),E())})}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e,t){try{let{stdout:s}=await execFileAsync(e,[`rev-parse`,`--is-inside-work-tree`],{cwd:t});return s.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};log.info({},`detected partial .git/ — running git init to repair`),S=!0}let w;try{w=assertGitAvailable()}catch(e){throw e instanceof GitNotAvailableError||e instanceof GitTooOldError?(emitPreflightFailureSpan(e),log.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof GitTooOldError?`too_old`:`not_available`,detectedVersion:e instanceof GitTooOldError?e.detected:``},e instanceof GitTooOldError?`git binary too old`:`git binary not found`)):log.warn({event:`git_preflight_unexpected_error`,message:e instanceof Error?e.message:String(e)},`unexpected error during git preflight`),e}let E=w.resolvedPath;if(!S&&await isInsideExistingWorkTree(E,t))return{didInit:!1};let D=``;try{D=(await execFileAsync(E,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let s=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,s,{cause:e})}if(!existsSync(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,D);return S?(log.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(log.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}async function resolvePackageVersion(e,t){let s;try{s=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(s),g=0;g<32;g+=1){let s=join(t,`package.json`);if(existsSync(s))try{let t=JSON.parse(await readFile$1(s,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let g=dirname(t);if(g===t)return;t=g}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:s}of HOME_PATH_PATTERNS)t=t.replace(e,s);return t}function serializeError(e,t=0,s=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(s.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};s.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,s)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let g=e;return{name:String(g.name??`ObjectError`),message:scrubPaths(String(g.message??``))??``,stack:scrubPaths(g.stack),code:g.code,cause:g.cause===void 0?void 0:serializeError(g.cause,t+1,s)}}return{name:`UnknownError`,message:String(e)}}var SingleFileNotFoundError=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},SingleFileNotAFileError=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},SingleFileNotMarkdownError=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function prepareSingleFileOpen(e){if(!isSupportedDocFile(e))throw new SingleFileNotMarkdownError(e);let t;try{t=realpathSync(resolve(e))}catch(t){throw t.code===`ENOENT`?new SingleFileNotFoundError(e):t}if(!statSync(t).isFile())throw new SingleFileNotAFileError(e);let s=dirname(t),g=findEnclosingProjectRoot(s);if(g){let e=g.rootPath;return{mode:`project`,projectRoot:e,docName:stripDocExtension(relative(resolveProjectContentDir(e),t).split(sep).join(`/`)),canonicalFilePath:t}}let S=basename(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:s,singleDocRelPath:S,docName:stripDocExtension(S)}}function resolveProjectContentDir(e){return resolve(e,readConfigSafely({absPath:resolveConfigPath(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function createEphemeralProjectDir(e){let t=mkdtempSync(resolve(tmpdir(),`ok-ephemeral-`)),s=resolve(t,`.ok`);return mkdirSync(s,{recursive:!0}),writeFileSync(resolve(s,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),writeFileSync(resolve(s,`.gitignore`),`local/
|
|
3253
|
+
`),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);if(e===null)break;let t=e[2];t&&s.push(t)}}return s}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();initChain=Promise.resolve();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!isLinkIndexExcludedDoc(e))try{let{frontmatter:s,body:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isLinkIndexExcludedDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let s of t){let t=this.state.byTag.get(s);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(s))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,s){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,s)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let s=[];for(let g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].sort((e,t)=>e.localeCompare(t))})}return s.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),s=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&s.add(e.slice(0,t));let g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!s.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){let e=this.initChain.then(()=>this.initOnce());return this.initChain=e.catch(e=>{console.warn(`[tag-index] init failed (chain cleared for next init):`,e)}),e}async initOnce(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=await this.listDocsWithPaths(),t=50;for(let t=0;t<e.length;t+=50){let s=e.slice(t,t+50),g=await Promise.all(s.map(async({docName:e,filePath:t})=>{try{return{docName:e,markdown:await readFile$1(t,`utf-8`)}}catch(t){return console.warn(`[tag-index] Failed to read ${e} during init:`,t),null}}));for(let e of g)if(e)try{this.updateDocumentFromMarkdown(e.docName,e.markdown)}catch(t){console.warn(`[tag-index] Failed to index ${e.docName} during init:`,t)}}}applyDocSnapshot(e,t,s){let g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.size===0&&this.state.byTag.delete(t))}for(let t of s){let s=this.state.byTag.get(t);s||(s=new Set,this.state.byTag.set(t,s)),s.add(e)}s.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,s),this.state.byDocLiteral.set(e,t))}async listDocsWithPaths(){let e=[];await this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}async walkContentDir(e,t){let s;try{s=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=toPosix(relative(this.contentDir,s));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=toPosix(relative(this.contentDir,s));this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),filePath:s})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function buildSyncCredentialArgs(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(shellEscape).join(` `)} auth git-credential`]}function resolveUpstreamChanges(e,t,s,g){let S=new Map;if(!s)return S;let w;try{w=spawnSync(`git`,[`-c`,`core.quotePath=false`,`log`,`${s}..${g}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],withHiddenWindowsConsole({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return getLogger(`upstream-attribution`).warn({err:e,oldHead:s,newHead:g},`git log spawn threw; upstream docs keep file-system attribution`),S}if(w.error||w.status!==0||typeof w.stdout!=`string`)return getLogger(`upstream-attribution`).warn({err:w.error,status:w.status,signal:w.signal,stderr:typeof w.stderr==`string`?w.stderr.slice(0,500):void 0,oldHead:s,newHead:g},`git log failed; upstream docs keep file-system attribution`),S;let E=null;for(let s of w.stdout.split(`
|
|
3254
|
+
`)){let g=s.trim();if(g===``)continue;if(g.startsWith(`C\0`)){let[,e,t]=g.split(`\0`);E=e&&t?{name:e,email:t}:null;continue}if(!E||!g.endsWith(`.md`)&&!g.endsWith(`.mdx`))continue;let w=resolve(e,g);if(!isWithinContentDir(w,t))continue;let D=pathToDocName(w,t);S.has(D)||existsSync(w)&&S.set(D,E)}return S}function createServer$1(e){let{contentDir:t,projectDir:s=t,quiet:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1,singleDocRelPath:ee,ephemeral:J=!1}=e,Y=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=isKnownConfigError(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}Y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function ne(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;if(t!=null)return t===!0;e.valid||Y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let g=readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});return g.valid||Y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),g.value.autoSync?.default===!0}function ae(){return readProjectLocalSemanticConfig(s,{configHomedirOverride:k,onWarn:e=>Y.warn({message:e},`[config] could not read project-local config`)})}function oe(e){return`${normalizeProviderId(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}function se(e){let t;(e===`__config__/project`||e===`__local__/project`)&&(t=ne(),jr?.setEnabled(t).catch(s=>{Y.warn({err:s,enabled:t,docName:e},`[sync] failed to apply autoSync.enabled from config`)}));let s=ae();ze.applyConfig({enabled:s.enabled,providerFingerprint:oe(s)}),Y.info({docName:e,autoSyncEnabled:t,semanticEnabled:s.enabled},`[config] applied persisted config to in-process consumers`)}initTelemetry();let ce=randomUUID(),ue=getLocalDir(s);if(acquireServerLock(ue,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:ue,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(ue),e}let de=createBasenameIndex(),fe=(e,t)=>de.resolveEmbed(e,t),me=(e,s)=>{let g=de.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g);if(!isWithinDir(S,resolve(t)))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},ge,_e,ve,ye,Ce,we,Te,De,je=null,Me=null,Pe=null,Ie=null,Re=ae(),ze=new SemanticSearchService({loadEmbedder:e.embedderLoader??(()=>{let t=ae();return loadOpenAiEmbedder({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:join(getLocalDir(s),`embeddings`),enabled:Re.enabled,providerFingerprint:oe(Re)}),Be=null,Ve=new Set,Ue=!1,We,Ge,Ke,Xe=new Promise((e,t)=>{Ge=e,Ke=t});function $e(e){je?.signal(e)}let nt=2e3,rt=null;function it(){rt!==null&&clearTimeout(rt),rt=setTimeout(()=>{rt=null,_e.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let at=2e3,st=null,vt=!1,St=()=>{try{saveRemovedDocsJournal(s,Tt.entries())}catch(e){Y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Tt=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e),onMutate:()=>{!vt||st!==null||(st=setTimeout(()=>{st=null,St()},2e3))}});for(let[e,g]of loadRemovedDocsJournal(s))isReservedForUserTree(e)||isSafeDocName(e)&&([`.md`,`.mdx`].some(s=>{let g=resolve(t,`${e}${s}`);return isWithinDir(g,resolve(t))&&existsSync(g)})||Tt.restore(e,g));vt=!0;let Et=(e,t)=>{isReservedForUserTree(e)||Tt.setRenamed(e,t)},jt=e=>{if(!isReservedForUserTree(e)){if(Tt.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Tt.setDeleted(e)}},Mt=e=>{isReservedForUserTree(e)||Tt.delete(e)};try{ge=createContentFilter({projectDir:s,contentDir:t,singleDocRelPath:ee,onAfterRebuild:()=>{_e.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),ve.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),reconcileFileIndexAfterFilterRebuild(rn).then(({prunedFiles:e,prunedFolders:t})=>{let s=e+t;s>0?getLogger(`server-factory`).info({pruned:s,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):getLogger(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),_e=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:ge}),ve=new TagIndex({contentDir:t,contentFilter:ge}),ve.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[server-factory] tag-index init failed; continuing with empty index`)}),ye={current:F},Ce=E?createMaintenanceCoordinator({getShadow:()=>ye.current??null,getCurrentBranch:()=>sn?.getLastKnownBranch()??null,contentRoot:L??``,projectGitDir:resolveGitDir(s)??void 0,isWriterLive:e=>{if(!Pe&&!De)return getLogger(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Pe?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of De?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,we=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:ye,ephemeral:J,contentRoot:L,backlinkIndex:_e,configHomedirOverride:k,getCurrentBranch:()=>sn?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:me,getPrincipal:()=>Be,onAgentCommit:()=>je?.signal(`session-activity`),onFlushCommit:()=>Ce?.noteFlushCommit(),onDiskFlush:(e,t,s,g)=>{je?.emitDiskAck(e,t),!isReservedForUserTree(e)&&assetReferencesChanged(g,s)&&(Ie?.(),$e(`files`))},onConfigRejected:(e,t)=>je?.emitConfigValidationRejected(e,t),onConfigPersisted:se,isRecentlyRemoved:e=>Tt.has(e),mdManager:e.mdManager}),Te=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[we.extension]});let B=Te.shouldUnloadDocument.bind(Te);Te.shouldUnloadDocument=e=>{if(Ve.has(e)||Ue&&B(e))return!0;let t=e.name;return isReservedForUserTree(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},We=async e=>{Ve.add(e);try{await Te.unloadDocument(e)}finally{Ve.delete(e)}},je=new CC1Broadcaster(Te),Me=new AgentFocusBroadcaster(Te),Pe=new AgentPresenceBroadcaster(Te),De=new AgentSessionManager(Te);let q=createLiveDerivedIndexExtension({backlinkIndex:_e,tagIndex:ve,signalChannel:$e});Te.configuration.extensions.push(q),Te.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,s=parseHocuspocusAuthToken(t),g=s?.expectedServerInstanceId;if(typeof g==`string`&&g.length>0&&g!==ce)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ce}`);let S=s?.expectedBranch,w=getActiveBranch();if(typeof S==`string`&&S.length>0&&S!==w)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${S}, server is on ${w}`);if(!s)return;let E=e.context;typeof s.principalId==`string`&&(Be&&s.principalId===Be.id?E.principalId=Be.id:Be?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Be.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),Te.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName)&&!isManagedArtifactDoc(e.documentName))return;let t=e.request,s=t.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s))throw Error(`config-doc admission requires loopback peer (peer=${s}, doc=${e.documentName})`);let g=e.requestHeaders,S=(g&&typeof g.get==`function`?g.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(S))throw Error(`config-doc admission requires loopback Host header (host=${S??`<absent>`}, doc=${e.documentName})`)}});let Y=resolve(t);function ne(e){if(!isSafeDocName(e))return null;let t=resolve(Y,docNameToRelativePath(e));return isWithinDir(t,Y)?t:null}Te.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:Tt,resolveFilePath:ne,fileExists:existsSync})}}),Te.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=parseHocuspocusAuthToken(e.token);runDocLineageGuard(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Te.documents.get(e)})}}),Te.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let oe=createApiExtension({hocuspocus:Te,sessionManager:De,contentDir:t,contentFilter:ge,serverInstanceId:ce,getFileIndex:()=>rn?rn.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>rn?rn.getAllFilesIndex():new Map,getFileIndexGeneration:()=>rn?.getFileIndexGeneration()??0,mutateFileIndex:e=>rn?.mutateFileIndex(e),getFolderIndex:()=>rn?rn.getFolderIndex():new Map,getAliasMap:()=>rn?rn.getAliasMap():new Map,getFolderAliasIndex:()=>rn?rn.getFolderAliasIndex():new Map,rescanFiles:()=>rn?.rescanFromDisk(),enableTestRoutes:j,shadowRef:ye,flushGitCommit:()=>we.flushPendingGitCommit(),flushContributors:()=>we.flushContributors(),takeStoreFailure:e=>we.takeStoreFailure(e),takeStoreDivergence:e=>we.takeStoreDivergence(e),markAgentWriteStore:e=>we.markAgentWriteStore(e),getCurrentBranch:()=>sn?.getLastKnownBranch()??null,getDiskAckSVs:()=>je?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:_e,tagIndex:ve,signalChannel:$e,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>jr,localOpCliArgs:H,projectDir:s,resolveEmbed:fe,getPrincipal:()=>Be,homeDirOverride:k,forceUnloadDocument:We,ready:Xe,recentlyRemovedDocs:Tt,serializeDoc:zt,evictManagedArtifactLkg:e=>{we.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:ze,getSemanticSimilarityFloor:()=>ae().similarityFloor,embeddingsSecretsFile:secretsFilePath(k),ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{Ie=e}});Te.configuration.extensions.push(oe),Te.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:ye,contentRoot:L,getCurrentBranch:()=>sn?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:me})),Te.configuration.extensions.push(createSyncHandshakeSpanExtension()),Te.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>jr,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(ue),e}let Ft=null,It=new Map,Lt=[];function Rt(e,t){let s=resolve(e,`rescue`),g=resolve(s,docNameToRelativePath(t));return isWithinDir(g,s)?g:null}function zt(e){let t=Te.documents.get(e);return t?serializeYDocSource(t):null}let Bt=(e,t)=>applyExternalChange(Te,e,t,fe,me);function Vt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Ht=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of Te.documents){if(isReservedForUserTree(s))continue;let g=Te.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,fe,s)},FILE_WATCHER_ORIGIN)}catch(t){Y.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},Ut=null,Wt=e=>{e&&(Ut===null&&(Ut=new Set,setImmediate(()=>{let e=Ut;if(Ut=null,e)try{for(let t of e)Ht(t)}catch(t){Y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Ut.add(e))};function Xt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Zt(e){try{switch(e.kind){case`create`:Y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),_e.updateDocumentFromMarkdown(e.docName,e.content),it(),ve.updateDocumentFromMarkdown(e.docName,e.content),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),Mt(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=Te.documents.get(t);if(!g){_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`);return}let S=getReconciledBase(t)??``,w=zt(t)??S,E=reconcile({docName:t,base:S,ours:w,theirs:s}),D=contentHash(S).slice(0,6),O=contentHash(w).slice(0,6),k=contentHash(s).slice(0,6);switch(Y.info({docName:t,base:D,ours:O,theirs:k,result:E.kind},`[reconcile] ${t} base=${D} ours=${O} theirs=${k} result=${E.kind}`),E.kind){case`noop`:Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`);break;case`clean`:try{Bt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),Vt(g)}break;case`merged`:try{Bt(t,E.newContent),setReconciledBase(t,s),incrementReconcile(),Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),Vt(g)}break;case`conflicts`:try{Bt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,s)}{let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{incrementConflict();let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,E.reason);break}}break}case`delete`:{let{docName:t}=e,s=Te.documents.get(t);if(!s){_e.deleteDocument(t),it(),ve.deleteDocument(t),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),jt(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=zt(t)??``,w=S!==g;if(w&&ye.current){let e=ye.current,s=sn?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,L??``,{kind:`external-change-rescue`,docName:t,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:s,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),Y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{Y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),_e.deleteDocument(t),it(),ve.deleteDocument(t),Y.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),Te.closeConnections(t),await We(s),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),jt(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:s,content:g}=e,S=Te.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),_e.renameDocument(t,s,g),it(),ve.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}Y.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),Et(t,s),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:s,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,s=Te.documents.get(t);if(!s)return;let g=zt(t);g===null?Y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,g);let S=s.getMap(`lifecycle`);S.set(`status`,`conflict`),S.set(`reason`,`conflict-markers`),Y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:de.add(e.relativePath),$e(`files`),Wt(basename(e.relativePath));break;case`asset-delete`:de.remove(e.relativePath),$e(`files`),Wt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:$e(`files`);break;case`file-create`:case`file-update`:case`file-delete`:$e(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Xt(e);Y.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let $t=[];async function en(e){if(isBatchInProgress()){$t.push(e);return}await Zt(e)}async function tn(){let e=$t.splice(0,$t.length);for(let t of e)await Zt(t)}let rn=null,sn=null,jr=null,Mr=null;async function zr(e){if(Te.documents.size===0)return;let t=!1,s=new Promise(e=>{Te.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(Te.documents.keys());Te.closeConnections(),Te.flushPendingStores();for(let e of Te.documents.values())e.getConnectionsCount()===0&&Te.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let S,w=new Promise((s,w)=>{S=setTimeout(()=>{t=!0;let s=Array.from(Te.documents.keys()),S=[],E=[];if(ye.current){for(let e of s)if(!isReservedForUserTree(e))try{let t=zt(e);if(t===null){Y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=Rt(ye.current.gitDir,e);if(!s){Y.warn({docName:e,gitDir:ye.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),E.push(e);continue}mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,t,`utf-8`),incrementRescueBuffer(),S.push(e),Y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),Y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else Y.warn({stillLoadedCount:s.length},`[rescue] shadow repo unavailable at flush timeout — ${s.length} doc(s) will be lost: [${s.join(`, `)}]`),E.push(...s);let D=S.length>0||E.length>0?` — rescued [${S.join(`, `)}]${E.length>0?`, lost [${E.join(`, `)}]`:``}`:``;w(Error(`flushAllStoresAndWait timeout after ${e}ms — ${s.length}/${g.length} docs did not unload: [${s.join(`, `)}]${D}`))},e)});try{await Promise.race([s,w])}finally{S!==void 0&&clearTimeout(S)}}async function Br(){return Mr||(Mr=(async()=>{let e=Date.now(),t=[];Ue=!0;try{markServerLockDraining(ue)}catch(e){Y.warn({err:e},`[server] failed to mark server.lock draining`)}if(rt!==null&&(clearTimeout(rt),rt=null),st!==null&&(clearTimeout(st),st=null),vt)try{saveRemovedDocsJournal(s,Tt.entries())}catch(e){Y.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let g,S=await Promise.race([Xe.then(()=>`completed`,e=>(Y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&Y.warn({},`[server] init did not complete within 5s during shutdown`);let w=Te.documents.size;Ce?.destroy();try{try{try{sn&&=(await sn.unsubscribe(),null),rn&&=(await rn.unsubscribe(),null);for(let{docName:e,cleanup:t}of Lt)try{await t()}catch(t){Y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Lt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{je?.destroy(),Pe?.destroy(),Ft&&=(await Ft.disconnect(),null);for(let[e,t]of It)try{await t.disconnect()}catch(t){Y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}It.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await De.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await zr(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await we.flushPendingGitCommit(),await we.waitForPendingCommits()})(),new Promise((t,s)=>{e=setTimeout(()=>s(Error(`L2 git flush timeout`)),B)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{jr&&=(await jr.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(ye.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(ye.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(ye.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?Y.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):Y.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ue,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),Y.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Mr)}let Vr=[];async function Hr(){try{Be=await loadPrincipal(s),Y.info({principalId:Be.id},`[server] principal loaded`)}catch(e){Y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!ye.current)try{ye.current=await initShadowRepo(s),Y.info({gitDir:ye.current.gitDir},`[server] history repo initialized at ${ye.current.gitDir}`)}catch(e){Y.error({err:e},`[server] history repo init failed`),Vr.push(`shadow-repo`)}if(ye.current){let e=null;try{e=loadRenameLogIndex(ye.current.gitDir),sweepLazyPopOrphans(ye.current.gitDir,e),setRenameLogIndex(ye.current.gitDir,e),Y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){Y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(ye.current,e,{rebuild:!0}),new Promise((e,s)=>setTimeout(()=>s(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){Y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await Ce?.runBootMaintenance()}catch(e){Y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(ye.current)try{await shadowGit(ye.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){Y.warn({},`[server] history repo appears corrupted — reinitializing`);try{ye.current=await initShadowRepo(s)}catch(e){Y.error({err:e},`[server] history repo reinit failed`),ye.current=void 0,Vr.includes(`shadow-repo`)||Vr.push(`shadow-repo`)}}else Y.error({err:e},`[server] history repo check failed (transient?)`)}if(ye.current)try{let e=resolve(ye.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let g=null;try{g=(await esm_default({baseDir:s,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(g!==null){if(g!==t){let e=`main`;try{let t=(await esm_default({baseDir:s,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}Y.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(ye.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){Y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else Y.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){Y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){Y.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,s);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,s=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;Y.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){Y.error({err:e},`[server] managed rename recovery failed`),Vr.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(s);(e.deleted>0||e.errors>0)&&Y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){Y.error({err:e},`[server] upload-tempfile sweep failed`),Vr.push(`upload-tempfile-sweep`)}try{Ft=await Te.openDirectConnection(SYSTEM_DOC_NAME),je?.emitServerInfo(ce,getActiveBranch())}catch(e){Y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Vr.push(`cc1-push`)}let g=J?[]:CONFIG_DOC_NAMES;for(let e of g)try{let t=await Te.openDirectConnection(e);It.set(e,t)}catch(t){Y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Vr.push(`config-doc:${e}`)}let S=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,s)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,s)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,s,k)]]);for(let e of g){let t=S.get(e);if(t)try{Y.info({docName:e,path:t},`[config-file-watcher] starting`);let s=await startConfigFileWatcher(t,t=>{let s=Te.documents.get(e);Y.info({docName:e,hasDocument:s!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,e,t,we.configPersistenceCtx);Y.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),se(e)});Lt.push({docName:e,cleanup:s}),Y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(s){Y.warn({err:s,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Vr.push(`config-file-watcher:${e}`)}}if(!J){let e=(e,t)=>{let s=managedArtifactDocNameForPath(e,we.managedArtifactCtx);if(!s)return;let g=applyExternalManagedArtifactChange(Te.documents.get(s)??null,s,t,we.managedArtifactCtx);Y.info({docName:s,outcome:g},`[managed-artifact-watcher] external change`),parseGlobalSkillBundleDoc(s)&&_e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),getActiveBranch()).then(()=>{$e(`backlinks`),$e(`graph`)}).catch(e=>{Y.warn({err:e,docName:s},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=managedArtifactSkillsRoots(we.managedArtifactCtx),s=await startManagedArtifactWatcher(t,e);Lt.push({docName:`__skill-files__`,cleanup:s}),Y.info({roots:t},`[managed-artifact-watcher] skills started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),Vr.push(`managed-artifact-watcher:skills`)}try{let t=new Set([``]);try{for(let e of resolveProjectTemplates(s).templates)t.add(e.source_folder)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let g=[...t].map(e=>e?resolve(s,e,`.ok`,`templates`):resolve(s,`.ok`,`templates`)),S=await startManagedArtifactWatcher(g,e,TEMPLATE_WATCH_OPTIONS);Lt.push({docName:`__template-files__`,cleanup:S}),Y.info({rootCount:g.length},`[managed-artifact-watcher] templates started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),Vr.push(`managed-artifact-watcher:templates`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],withHiddenWindowsConsole({cwd:s,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=join(resolve(s,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(S=t)}}catch{}let w=S?[e,g,S]:[e,g],E=Y;E.info({okignorePath:e,gitignorePath:g,gitInfoExcludePath:S,ephemeral:J},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let D=J?null:await startMultiPathConfigFileWatcher(w,(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(Te.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,we.configPersistenceCtx);E.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){E.error({err:e,changedPath:relative(s,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let S=await ge.rebuildIgnorePatterns();if(S.ok)E.info({changedPath:relative(s,t),patternCount:S.patternCount,nestedFileCount:S.nestedFileCount,durationMs:S.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),je?.signal(`files`);else{let e=relative(s,t)||`.`;E.warn({changedPath:e,error:S.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),je?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});D&&(Lt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`))}catch(e){Y.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Vr.push(`ignore-files-watcher`)}let w=resolveGitDir(s),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),_e.switchBranch(E);let D=performance.now();try{await withSpan(`ok.boot.indexes`,void 0,async()=>{let e=getActiveBranch();try{if(await _e.loadFromDisk(e)){let t=await _e.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&Y.info({added:t.added,updated:t.updated,deleted:t.deleted},`[backlinks] startup reconcile: offline changes applied`);let s=0;for(let e of t.deletedDocNames)isReservedForUserTree(e)||Tt.peek(e)?.kind!==`renamed`&&(Tt.setDeleted(e),s++);s>0&&Y.info({count:s},`[removal-guard] tombstoned docs deleted while the server was down`)}else await _e.rebuildFromDisk(e);try{await _e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),e)}catch(t){Y.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}_e.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){Y.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}let s=performance.now();rn=await withSpan(`ok.boot.seed-walk`,void 0,async()=>startWatcher(t,en,ge)),recordBootPhase(`seedWalkMs`,Math.round(performance.now()-s));{let e=resolve(t),s=0;for(let[t]of Tt.entries()){if(!isSafeDocName(t))continue;let g=resolve(e,`${t}${getDocExtension(t)}`);isWithinDir(g,e)&&existsSync(g)&&(Tt.delete(t),s++)}s>0&&Y.info({count:s},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}try{await ve.init()}catch(e){Y.error({err:e},`[tag-index] startup re-init failed; tag index updates incrementally via watcher events`),Vr.push(`tag-index`)}let g=0;try{ee===void 0?await seedBasenameIndex({contentDir:t,contentFilter:ge,basenameIndex:de,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):seedSingleDirBasenameIndex({contentDir:t,basenameIndex:de,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),g>0&&(Y.warn({count:g},`[basename-index] startup seed completed with ${g} skipped entries — embeds under inaccessible subtrees will not resolve`),Vr.push(`basename-index-partial`))}catch(e){Y.error({err:e},`[basename-index] startup seed failed`),Vr.push(`basename-index`)}})}catch(e){Y.error({err:e},`[server] disk bridge watcher failed to start`),Vr.push(`file-watcher`)}finally{recordBootPhase(`indexesMs`,Math.round(performance.now()-D)),rn&&setBootField(`fileCount`,rn.getFileIndex().size)}try{sn=await startHeadWatcher(s,async({trigger:e})=>{if(Y.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),Te.flushPendingStores(),await we.flushPendingGitCommit(),setBatchInProgress(!0),ye.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of Te.documents){if(isReservedForUserTree(e))continue;let s=null;if(t.transact(()=>{s=zt(e)},PARK_SNAPSHOT_ORIGIN),s===null)continue;let g=getReconciledBase(e)??s;S.push({docName:e,markdown:s,diskSnapshot:g})}if(S.length>0)try{let t=await parkBranch(ye.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),Y.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){Y.error({err:e},`[shadow] park failed`)}}},async e=>{let g=$t.length,S=e.newBranch??`main`;if(Y.info({kind:e.batchKind,headMoved:e.headMoved,docs:g,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${g}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await tn(),e.headMoved&&e.newHead){let g=resolveUpstreamChanges(s,resolve(t),e.oldHead,e.newHead);if(g.size>0){dropPendingDocs(g.keys());for(let[e,t]of g)recordContributor(e,gitAuthorWriterId(t.email),t.name,t.email,formatReconcileSubject(e));await we.flushContributors()}}if(await we.flushDeferredStores(`within-branch`),jr!==null)try{await jr.reconcileConflictsFromGit()}catch(e){Y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),$t.splice(0,$t.length),switchReconciledBaseScope(S),rt!==null&&(clearTimeout(rt),rt=null),_e.switchBranch(S),ge.rebuildDirCount();try{let e=0;de.clear(),await seedBasenameIndex({contentDir:t,contentFilter:ge,basenameIndex:de,onSkip:(t,s,g)=>{e++,Y.warn({reason:t,code:s,path:g,branch:S},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e,branch:S},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Vr.includes(`basename-index-partial`)||Vr.push(`basename-index-partial`))}catch(e){Y.error({err:e,branch:S},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of Te.documents)if(!isReservedForUserTree(e))try{let g=safeContentPath(e,t);if(!existsSync(g)){let t=getReconciledBase(e)??``,g=zt(e)??``;if(g!==t&&ye.current){let t=ye.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:g,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),Y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{Y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Y.info({docName:e,branch:S},`[branch-switch] tombstone: ${e} (not on ${S})`);continue}let w=readFileSync(g,`utf-8`);Bt(e,w),setReconciledBase(e,w),Y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){Y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}Y.info({branch:S,docCount:Te.documents.size},`[branch-switch] loaded branch ${S} (${Te.documents.size} docs)`);try{if(await _e.loadFromDisk(S)){let e=await _e.reconcileWithDisk(S);(e.added>0||e.updated>0||e.deleted>0)&&Y.info(e,`[backlinks] branch-switch reconcile for ${S}`)}else await _e.rebuildFromDisk(S);try{await _e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),S)}catch(e){Y.warn({err:e,branch:S},`[backlinks] branch-switch global skill bundle ingest failed`)}_e.saveToDisk(S).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${S}:`,e)})}catch(e){Y.error({err:e,branch:S},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(await ve.init(),ye.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Te.documents)if(!isReservedForUserTree(t))try{let s=await readParkedState(ye.current,S,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let g=getReconciledBase(t);if(!g)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:g});switch(w.kind){case`merged`:case`clean`:Bt(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:Bt(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=Te.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){Y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&Y.info({count:e,branch:S},`[branch-switch] restored ${e} parked docs on ${S}`)}if(e.oldBranch?.startsWith(`detached-`)&&ye.current)try{let t=shadowGit(ye.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
|
|
3255
|
+
`))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await we.flushDeferredStores(`discard-stale`),je?.emitBranchSwitched(S)}if(e.headMoved&&e.newHead&&ye.current&&g>0){let t=L??`.`;try{let s=await commitUpstreamImport(ye.current,t,e.oldHead,e.newHead,S);incrementUpstreamImport(),Y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Vr.push(`head-watcher`)}function O(e){for(let g of e)try{let e=toPosix(relative(t,join(s,g)));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=Te.documents.get(S);if(!w)continue;let E=zt(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let j=buildSyncCredentialArgs(H);try{jr=new SyncEngine({projectDir:s,contentDir:t,contentFilter:ge,contentRoot:L,syncEnabled:ne(),credentialArgs:j,cc1Broadcaster:je,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||we.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:O,onAutoDisable:async e=>{Y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||Y.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await jr.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),jr=null}$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`);let F=bootElapsedMs();F!==void 0&&recordBootPhase(`readyMs`,F)}return Hr().then(Ge,Ke),{hocuspocus:Te,sessionManager:De,cc1Broadcaster:je,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,maintenanceCoordinator:Ce,contentFilter:ge,basenameIndex:de,serverInstanceId:ce,destroy:Br,ready:Xe,degraded:Vr,lockDir:ue,get syncEngine(){return jr}}}const SERVER_MEMORY_SCHEMA_VERSION=1,BYTES_PER_MB=1024*1024;function toMb(e){return e/BYTES_PER_MB}function captureServerMemorySnapshot(){let e=process.memoryUsage();return{schemaVersion:SERVER_MEMORY_SCHEMA_VERSION,capturedAt:new Date().toISOString(),snapshot:{rssMb:toMb(e.rss),heapTotalMb:toMb(e.heapTotal),heapUsedMb:toMb(e.heapUsed),externalMb:toMb(e.external),arrayBuffersMb:toMb(e.arrayBuffers)}}}let cachedGauge=null;onTelemetryShutdown(()=>{cachedGauge=null});function installServerMemoryGauge(){if(cachedGauge)return;let e=getMeter().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=captureServerMemorySnapshot();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),cachedGauge=e}const TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`,TELEMETRY_PREV_FILENAME=`tolerance-telemetry.prev.jsonl`,TELEMETRY_MAX_BYTES=8*1024*1024;let appender=null,appendFailureWarned=!1;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);appender=new RotatingAppender({currentPath:resolve(t,TELEMETRY_FILENAME),previousPath:resolve(t,TELEMETRY_PREV_FILENAME),maxBytes:TELEMETRY_MAX_BYTES}),setToleranceTelemetryHook(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};appender?.append(`${JSON.stringify(t)}\n`).catch(e=>{appendFailureWarned||(appendFailureWarned=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null),await appender?.drain(),appender=null,appendFailureWarned=!1}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let s=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&s.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let g=resolve(e,t);try{existsSync(g)&&statSync(g).isDirectory()&&s.push(`${t}/`)}catch{}}return s}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){startBootTimings();let t=e.projectDir??e.contentDir,s=resolveLocalSinkConfig({projectDir:t});if(s){let e=s.telemetry.attributeDenylist,t=[];for(let s of e){t.push(s);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)t.push(`${`*.`.repeat(e)}${s}`)}loggerFactory.configure({pinoConfig:{fileSink:s.logs,redactPaths:t}})}initTelemetry({localSink:s?.telemetry}),initToleranceTelemetryWriter(t),installServerMemoryGauge();let{kind:g,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":g};S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S));let E=process.env.OK_STARTUP_TRACEPARENT,D=()=>withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e));if(E)try{let e=propagation.extract(context.active(),{traceparent:E});return context.with(e,D)}catch(e){getLogger(`boot`).warn({err:e instanceof Error?e.message:String(e)},`ok.boot trace-join failed — starting unparented boot`)}return D()}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{markServerLockDraining:O,releaseServerLock:k,updateServerLockPort:j}=await import(`./server-lock-GuuouVft-BFFcTQcA.mjs`),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let H=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&H()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let q=findLegacyRuntimeFiles(B);q.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${q.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let ee=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:J,destroy:Y,ready:te,degraded:ne,lockDir:ae,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,maintenanceCoordinator:ue}=ee,de=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),fe=e.port??0,me=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${de}:${fe}`,log:S}),ge=D();ge.headersTimeout=3e4,ge.requestTimeout=6e4;let _e=e.serveContentAssets?createAssetServeMiddleware({contentFilter:ee.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ve=!1;if(e.reactShellDistDir)try{acquireUiLock(ae,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ve=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:ae},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await Y().catch(()=>{}),k(ae),e}let ye=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,Ce=mountMcpAndApi({httpServer:ge,hocuspocus:J,mcpHttpHandler:me,log:S,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,maintenanceCoordinator:ue,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:_e,reactShellMiddleware:ye,ephemeral:e.ephemeral}),we=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Te=null;g!==null&&(Te=attachIdleShutdown({httpServer:ge,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await we()})})),await restoreLifecycleFromConflictsJson({hocuspocus:J,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);ge.once(`error`,g),ge.listen(e.port,e.host,()=>{ge.removeListener(`error`,g),t()})})}catch(e){if(ve)try{releaseUiLock(ae)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await Y().catch(()=>{}),k(ae),e}let De=bootElapsedMs();De!==void 0&&recordBootPhase(`httpListenMs`,De);let je=ge.address(),Me=typeof je==`object`&&je?je.port:e.port??0;if(fe=Me,j(ae,Me),ve&&updateUiLockPort(ae,Me),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ae,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let Pe=!1,Ie=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};we=async()=>{if(Pe)return;Pe=!0;let e=[],t=async(t,s)=>{try{await Ie(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{O(ae),ve&&markUiLockDraining(ae)}catch(e){S.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{Te?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>Ce.shutdown()),me!==void 0&&await t(`mcpHttpHandler.close`,()=>me.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{Ce.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{ge.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ge.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>Y()),ve&&await t(`releaseUiLock`,async()=>releaseUiLock(ae,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await reconcileSkillInstalls({projectDir:L,skillsRoot:resolve(e.contentDir,`.ok`,`skills`)}),s=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;s>0&&S.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${s} editor skill entr${s===1?`y`:`ies`} to the symlink model.`)}catch(e){S.warn?.({event:`installed-skills-reconcile-failed`,error:String(e)},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:ge,destroy:we,lockDir:ae,contentDir:e.contentDir,port:Me,ready:te,degraded:ne,didAutoInit:F,serverInstance:ee}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=simpleGit({baseDir:s,timeout:{block:5e3}});E=new Set(await listNames(g,[`diff`,`--name-only`,`--diff-filter=U`]))}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!0});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},g)}function flushFileLogger(e,t=250){return new Promise(s=>{if(!e){s();return}let g=e[import_pino.default.symbols.streamSym],S=!1,w=()=>{S||(S=!0,s())};if(!g||typeof g.flushSync!=`function`){w();return}let E=()=>{try{g.flushSync?.()}catch{}w()},D=setTimeout(w,t);typeof D.unref==`function`&&D.unref(),typeof g.fd==`number`&&g.fd>=0?(clearTimeout(D),E()):typeof g.once==`function`?g.once(`ready`,()=>{clearTimeout(D),E()}):(clearTimeout(D),E())})}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e,t){try{let{stdout:s}=await execFileAsync(e,[`rev-parse`,`--is-inside-work-tree`],withHiddenWindowsConsole({cwd:t,encoding:`utf-8`}));return s.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};log.info({},`detected partial .git/ — running git init to repair`),S=!0}let w;try{w=assertGitAvailable()}catch(e){throw e instanceof GitNotAvailableError||e instanceof GitTooOldError?(emitPreflightFailureSpan(e),log.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof GitTooOldError?`too_old`:`not_available`,detectedVersion:e instanceof GitTooOldError?e.detected:``},e instanceof GitTooOldError?`git binary too old`:`git binary not found`)):log.warn({event:`git_preflight_unexpected_error`,message:e instanceof Error?e.message:String(e)},`unexpected error during git preflight`),e}let E=w.resolvedPath;if(!S&&await isInsideExistingWorkTree(E,t))return{didInit:!1};let D=``;try{D=(await execFileAsync(E,[`init`,`--initial-branch=main`,t],withHiddenWindowsConsole({encoding:`utf-8`}))).stderr??``}catch(e){let s=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,s,{cause:e})}if(!existsSync(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,D);return S?(log.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(log.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}async function resolvePackageVersion(e,t){let s;try{s=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(s),g=0;g<32;g+=1){let s=join(t,`package.json`);if(existsSync(s))try{let t=JSON.parse(await readFile$1(s,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let g=dirname(t);if(g===t)return;t=g}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:s}of HOME_PATH_PATTERNS)t=t.replace(e,s);return t}function serializeError(e,t=0,s=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(s.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};s.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,s)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let g=e;return{name:String(g.name??`ObjectError`),message:scrubPaths(String(g.message??``))??``,stack:scrubPaths(g.stack),code:g.code,cause:g.cause===void 0?void 0:serializeError(g.cause,t+1,s)}}return{name:`UnknownError`,message:String(e)}}var SingleFileNotFoundError=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},SingleFileNotAFileError=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},SingleFileNotMarkdownError=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function prepareSingleFileOpen(e){if(!isSupportedDocFile(e))throw new SingleFileNotMarkdownError(e);let t;try{t=realpathSync(resolve(e))}catch(t){throw t.code===`ENOENT`?new SingleFileNotFoundError(e):t}if(!statSync(t).isFile())throw new SingleFileNotAFileError(e);let s=dirname(t),g=findEnclosingProjectRoot(s);if(g){let e=g.rootPath;return{mode:`project`,projectRoot:e,docName:stripDocExtension(relative(resolveProjectContentDir(e),t).split(sep).join(`/`)),canonicalFilePath:t}}let S=basename(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:s,singleDocRelPath:S,docName:stripDocExtension(S)}}function resolveProjectContentDir(e){return resolve(e,readConfigSafely({absPath:resolveConfigPath(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function createEphemeralProjectDir(e){let t=mkdtempSync(resolve(tmpdir(),`ok-ephemeral-`)),s=resolve(t,`.ok`);return mkdirSync(s,{recursive:!0}),writeFileSync(resolve(s,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),writeFileSync(resolve(s,`.gitignore`),`local/
|
|
3256
3256
|
`,`utf-8`),t}export{STARTER_PACKS as $,validateCloneInputs as $i,isAllowedWorkspaceHostHeader as $n,resetMetrics as $r,createExternalChangeHandler as $t,HocuspocusAuthRejection as A,spansCurrentPath as Ai,formatPackRationale as An,planSeed as Ar,bundleSkillMdPath as At,McpLogger as B,tracedLinkSync as Bi,handleCollabSocketError as Bn,readSkillInstallStateSnapshot as Br,compareSemver as Bt,FILE_WATCHER_ORIGIN as C,resolveGitDirDetailed as Ca,seedBasenameIndex as Ci,fallbackPaths as Cn,normalizeFsPath as Cr,bootServer as Ct,GitNotAvailableError as D,shadowGit as Di,formatAuthRejectionWire as Dn,parseHocuspocusAuthToken as Dr,buildSkillZip as Dt,GIT_UPSTREAM_WRITER as E,setupServerObservers as Ei,flushFileLogger as En,parseGitVersion as Er,buildExecResult as Et,MANAGED_RENAME_ORIGIN as F,streamingProblemEvent as Fi,getLogger as Fn,readArmedPaneTarget as Fr,clearEmbeddingsKeyFromAllBackends as Ft,PinoLogger as G,tracedRmSync as Gi,initContent as Gn,readUiLock as Gr,countStaleAgentWipRefs as Gt,OBSERVER_SYNC_ORIGIN as H,tracedMkdirSync as Hi,hasGcLogLatch as Hn,readStateManifest as Hr,contentHash as Ht,MAX_AGENT_SESSIONS as I,swapContributors as Ii,getLogsDir as In,readBranchFromHead as Ir,coercePackId as It,ROOT_GITIGNORE_TEMPLATE as J,tracedWriteFile as Ji,initToleranceTelemetryWriter as Jn,recordSkillInstallEvent as Jr,createAssetServeMiddleware as Jt,ProjectGitInitError as K,tracedRmdirSync as Ki,initShadowRepo as Kn,reconcile as Kr,countWipRefs as Kt,MCP_CONNECTION_ID_HEADER as L,teardownToleranceTelemetryWriter as Li,getMeter as Ln,readBundleDecision as Lr,commitUpstreamImport as Lt,INSTALLED_AGENTS_SCHEMES as M,spawnDetached as Mi,getCurrentMcpLogger as Mn,processCommand as Mr,classifyFsPath as Mt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as N,splitMarkdownBlocks as Ni,getLocalDir as Nn,processUsage as Nr,clearArmedPaneTarget as Nt,GitTooOldError as O,shutdownTelemetry as Oi,formatContributors as On,parseKeepaliveConnectionId as Or,buildStarterFolderFrontmatterYaml as Ot,LOG_MD_TEMPLATE as P,startWatcher as Pi,getLogFilePath as Pn,readAllTargets as Pr,clearContributors as Pt,STARTER_FOLDER_FRONTMATTER_FILENAME as Q,validateAgentId as Qi,isAllowedApiOrigin as Qn,removeLastKnownHash as Qr,createEphemeralProjectDir as Qt,MIN_GIT_VERSION as R,toBroadcasterKey as Ri,getMetrics as Rn,readProjectLocalSemanticConfig as Rr,commitWip as Rt,FILE_SYSTEM_WRITER as S,parseCheckpoint as Sa,saveVersion as Si,extractWikiLinksFromMarkdown as Sn,mountMcpAndApi as Sr,attachIdleShutdown as St,GIT_PREFLIGHT_FAIL_SPAN_NAME as T,setActiveSpanAttributes as Ti,findEnclosingProjectRoot as Tn,parseAuthRejectionWire as Tr,buildConfigYmlContent as Tt,OK_OKIGNORE_TEMPLATE as U,tracedRename as Ui,incrementCollabSocketFilteredError as Un,readTargetRecordedAt as Ur,contributorCount as Ut,MissingOkConfigError as V,tracedMkdir as Vi,handleSpawnCursor as Vn,readSkillManagement as Vr,containsConflictMarkers as Vt,PANE_TARGET_TTL_MS as W,tracedRenameSync as Wi,incrementServerObserverFire as Wn,readTargetVersion as Wr,countShadowObjects as Wt,SKILL_INSTALL_EVENTS_FILE_REL as X,updateLastKnownHash as Xi,installTestLoggers as Xn,registerWrite as Xr,createContentFilterAsync as Xt,SERVICE_WRITER as Y,tracedWriteFileSync as Yi,installPrettyZodErrors as Yn,registerAllTools as Yr,createContentFilter as Yt,STARTER_FOLDERS as Z,updateUiLockPort as Zi,installUserSkill as Zn,releaseUiLock as Zr,createEmbeddingsSecretStore as Zt,ConfigSchema as _,resolveConfigPath as _a,safeContentPath as _i,encodeSkillRoute as _n,loadPrincipal as _r,applySeed as _t,AgentPresenceBroadcaster as a,writeSkillManagement as aa,resolvePack as ai,createServer$1 as an,isManagedArtifactDoc as ar,SingleFileNotAFileError as at,DEFAULT_PACK_ID as b,GitDirAccessError as ba,sanitizeClientName as bi,evictStaleTrackerEntries as bn,logsPreviousPath as br,assertGitAvailable as bt,AutoStartDisabledError as c,writeTracker as ca,restoreContributors as ci,createTestLogger as cn,isProjectRoot as cr,StateManifestError as ct,BUNDLE_SKILL_NAME as d,LATEST_PROTOCOL_VERSION as da,rewriteWikiLinksForDocumentRename as di,detectGit as dn,isSelfWrite as dr,UiLockCollisionError as dt,validateSkillZip as ea,resolveBundledSkillDir as ei,createFileLogger as en,isConfigDoc as er,STARTER_PACK_IDS as et,BacklinkIndex as f,isInitializedNotification as fa,runAuthReposSubprocess as fi,detectProjectShape as fn,isSystemDoc as fr,__getShowAllWalkStatsForTesting as ft,CURSOR_BUNDLE_PATHS_BY_PLATFORM as g,readConfigSafely as ga,runWithMcpLogger as gi,encodeFolderRoute as gn,listStarterPacks as gr,applyExternalChange as gt,CONFLICT_MARKER_RE as h,atomicWriteFileSync as ha,runDeviceFlowSubprocess as hi,encodeDocName as hn,listRescueCheckpoints as hr,applyAgentMarkdownWrite as ht,AgentFocusBroadcaster as i,writeRootGitignoreForNewRepo as ia,resolveLockDir as ii,createPersistenceExtension as in,isLoopbackAddress as ir,SeedRootDirError as it,HocuspocusAuthTokenSchema as j,spansPreviousPath as ji,gcCheckpointRefs as jn,prepareSingleFileOpen as jr,classifyEvents as jt,HOCUSPOCUS_AUTH_REJECTION_REASONS as k,skillManagementPath as ki,formatContributorsFrom as kn,pathToDocName as kr,buildWipTree as kt,BUNDLE_IDS as l,McpServer as la,restoreLifecycleFromConflictsJson as li,describeStoredEmbeddingsKey as ln,isProjectSkillManaged as lr,TagIndex as lt,CONFIG_FILENAME as m,isJSONRPCResultResponse as ma,runCloneSubprocess as mi,emitPreflightFailureSpan as mn,lastKnownHash as mr,acquireUiLock as mt,AGENT_ID_RE as n,withSpanSync as na,resolveCursorBinaryDefault as ni,createMcpHttpHandler as nn,isKnownPackId as nr,STATE_MANIFEST_FILENAME as nt,AgentSessionCapacityError as o,writeStateManifest as oa,resolvePackageVersion as oi,createServerObserverExtension as on,isPairedWriteOrigin as or,SingleFileNotFoundError as ot,CC1Broadcaster as p,isJSONRPCRequest as pa,runAuthStatusSubprocess as pi,discoverLockDirs as pn,isToleranceTelemetryEnabled as pr,__resetShowAllWalkStatsForTesting as pt,ROLLBACK_ORIGIN as q,tracedUnlinkSync as qi,initTelemetry as qn,recordContributor as qr,createApiExtension as qt,AGENT_WRITE_ORIGIN as r,writeBundleDecision as ra,resolveCursorSpawnInvocation as ri,createOsProbe as rn,isLinkIndexExcludedDoc as rr,SeedPrerequisiteError as rt,AgentSessionManager as s,writeTargetVersion as sa,resolveUiInfo as si,createStreamingErrorWriter as sn,isPathWithinDir as sr,SingleFileNotMarkdownError as st,AGENT_ID_MAX_LEN as t,withSpan as ta,resolveContentDir as ti,createLiveDerivedIndexExtension as tn,isHocuspocusAuthRejectionReason as tr,STARTER_TEMPLATES as tt,BUNDLE_SCOPE as u,JSONRPCMessageSchema as ua,rewriteMarkdownLinksForDocumentRename as ui,detectClaudeDesktopPresence as un,isReservedForUserTree as ur,USER_GLOBAL_BUNDLE_IDS as ut,DEFAULT_CHECKPOINT_RETENTION as v,withFileLockSync as va,safeSubdir as vi,ensureProjectGit as vn,loggerFactory as vr,armPaneTarget as vt,FileEmbeddingsBackend as w,resolveShadowDir as wa,serializeError as wi,findEnclosingGitRoot as wn,packageVersionMajorMinor as wr,buildAndOpenSkill as wt,EMBEDDINGS_API_KEY_ENV as x,MalformedGitPointerError as xa,saveInMemoryCheckpoint as xi,extractOkBinaryPath as xn,makeLazyEmbeddingsKeyStore as xr,assertNeverDiskEvent as xt,DEFAULT_EMBEDDINGS_DIMENSIONS as y,writeConfigPatch as ya,safetyCheckpoint as yi,errorResponse as yn,logsCurrentPath as yr,assertCompatibleStateManifest as yt,MISSING_OK_CONFIG_MESSAGE as z,tracedAppendFileSync as zi,getTracer as zn,readServerPackageVersion as zr,commitWipFromTree as zt};
|
|
3257
|
-
//# sourceMappingURL=dist-
|
|
3257
|
+
//# sourceMappingURL=dist-CD7iLv1c.mjs.map
|