@inkeep/open-knowledge 0.68.14-beta.0 → 0.68.15-beta.0
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/{acp-harness-probe-Dm40jhIz.mjs → acp-harness-probe-Bj8oA0_L.mjs} +2 -2
- package/dist/cli.mjs +6 -6
- package/dist/constants-mkJ6OI6E.mjs +2 -0
- package/dist/index.mjs +1 -1
- package/dist/{init-PzfJr9rO.mjs → init-BajN-Y_a.mjs} +3 -3
- package/dist/init-C-hfVQOM.mjs +1 -0
- package/dist/{launch-json-removal-45EceD9q.mjs → launch-json-removal-BrYT_N2l.mjs} +2 -2
- package/dist/loader-EdVXnN2T.mjs +1 -0
- package/dist/{loader-BwChO6Xd.mjs → loader-emIHYjgj.mjs} +2 -2
- package/dist/{open-browser-ACBO68Cc.mjs → open-browser-B4DCMrL7.mjs} +2 -2
- package/dist/{preview-Cq2xyJ4Y.mjs → preview-33UMDNTO.mjs} +2 -2
- package/dist/preview-COq4A7S9.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-V-Zp6YCT.js → ActivityModeContent-f2VL2lxy.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-Beyc2cUD.js → AddPropertiesButton-hTYiBjgZ.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-DwKcGEg1.js → AgentDiffPane-FfZ2OhEu.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-CHGRjNxF.js → CodeMirrorPropInput-CWmnK_9r.js} +1 -1
- package/dist/public/assets/{DocumentContext-8l8br9Eh.js → DocumentContext-CuexGhVG.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-CnOYE3ui.js → EditorModeToggle-B7SHnWjQ.js} +1 -1
- package/dist/public/assets/{EnableSyncConfirmDialog-CcCzKuog.js → EnableSyncConfirmDialog-BaSS4GY6.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-BE_tRKal.js → ExcalidrawDocEditor-D6k25yjw.js} +1 -1
- package/dist/public/assets/FeedbackForm-BJZM3jQp.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-DDGDmBb8.js → ImportSkillDialog-BqLYbauN.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-TW5v1V_p.js → LintConfigEditor-BFqeu9sX.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-CAbeaOX3.js → ManagedArtifactProperties-BXQcpKgs.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-CX_IgRy0.js +1 -0
- package/dist/public/assets/{MermaidDocEditor-B9JpWBpq.js → MermaidDocEditor-DJ-XRcVW.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-DmuD-oxI.js → PropertyDisplayRow-BXbkduAb.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-DXIm2XqB.js → SchemaConfigEditor-BpYYLnYb.js} +1 -1
- package/dist/public/assets/{SessionsHost-CcOfjp1q.js → SessionsHost-CD08AOoT.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-jsoSulYB.js → SettingsDialogBody-B3e-vYmC.js} +1 -1
- package/dist/public/assets/{ShareReceiveMissDialog-C9rCS0Vj.js → ShareReceiveMissDialog-D3unawEw.js} +1 -1
- package/dist/public/assets/{SkillInstallMenu-DR_AKxNE.js → SkillInstallMenu-DNPd9Oqe.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-e1tYbkEp.js → SkillToolbarControls-CIPbzm90.js} +1 -1
- package/dist/public/assets/{SourceEditor-DzDyaixq.js → SourceEditor-BTijuzYl.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-CXM5m5Wa.js → TerminalWindowApp-BvW49cZz.js} +1 -1
- package/dist/public/assets/{TextDocEditor-oQd8R9AP.js → TextDocEditor-BuoxjxMm.js} +1 -1
- package/dist/public/assets/{ThreadView-BUTdeOXR.js → ThreadView-Dt9V0sr5.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-0W-Z0tRv.js → TimelineDiffPane-iZ_JWQDo.js} +1 -1
- package/dist/public/assets/{agent-diff-store-CrwhzZYh.js → agent-diff-store-BKVCrWen.js} +1 -1
- package/dist/public/assets/{auth-state-cache-D5neoYEY.js → auth-state-cache-DEgQh16l.js} +1 -1
- package/dist/public/assets/{client-version-HeAaqVrn.js → client-version-DoTixOLP.js} +1 -1
- package/dist/public/assets/{comment-chips-DwJR7L-x.js → comment-chips-DRisS_i1.js} +1 -1
- package/dist/public/assets/{config-provider-BSxNIrQb.js → config-provider-DFQc6Sp1.js} +1 -1
- package/dist/public/assets/{doc-undo-manager-D50TrVgg.js → doc-undo-manager-BdEQSxA0.js} +1 -1
- package/dist/public/assets/{index-DoTHqxEX.js → index-Poxc4ods.js} +7 -7
- package/dist/public/assets/{pending-receive-nav-store-BVVH8Ilz.js → pending-receive-nav-store-o3Vxolpy.js} +1 -1
- package/dist/public/assets/{progress-aXAg8oWH.js → progress-BK_oMsaW.js} +1 -1
- package/dist/public/assets/{selection-context-oj7m34SC.js → selection-context-CoBsFLGs.js} +1 -1
- package/dist/public/assets/{src-Cv3UWDRY.js → src-D-hiz3zn.js} +1 -1
- package/dist/public/assets/{telemetry-impl-WWrY3Bx_.js → telemetry-impl-DACYt1sl.js} +1 -1
- package/dist/public/assets/{telemetry-startup-pkZqKl4a.js → telemetry-startup-CNDPp_xk.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-C_toXZHy.js → typing-burst-detector-DnYhm_MD.js} +1 -1
- package/dist/public/assets/{use-activity-panel-Dlu0zu7h.js → use-activity-panel-BuA04mHT.js} +1 -1
- package/dist/public/assets/{use-open-skill-WvF2Ant0.js → use-open-skill-D5tGMT8R.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-iYz6I1VH.js → use-terminal-enabled-CT62vh72.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-BmTAKKRa.js → use-timeline-entry-diff-Cwu0F72k.js} +1 -1
- package/dist/public/index.html +19 -19
- package/dist/{repair-launch-json-R-uKC24a.mjs → repair-launch-json-BAkAxYjG.mjs} +2 -2
- package/dist/{repair-mcp-configs-l-f4iDkZ.mjs → repair-mcp-configs-BabcrHLz.mjs} +2 -2
- package/dist/repair-skills-B6sre6xt.mjs +1 -0
- package/dist/{repair-skills-C0qRuAMi.mjs → repair-skills-CUazcTMq.mjs} +2 -2
- package/dist/{resolve-project-root-kzI3Z6Qa.mjs → resolve-project-root-GkFasO3k.mjs} +2 -2
- package/dist/{skill-teardown-BdwgIxeF.mjs → skill-teardown-BA04Mb7T.mjs} +2 -2
- package/dist/{src-CeQWnH8P.mjs → src-BaJbYARI.mjs} +5 -5
- package/dist/src-Ck_x6BGE.mjs +1 -0
- package/dist/{src-DAz7T8TL.mjs → src-DyC_gUkX.mjs} +1 -1
- package/dist/{src-Cg6XHTdP.mjs → src-ntnCf53D.mjs} +2 -2
- package/dist/{start-CXvoh8Ep.mjs → start-BdxnXMci.mjs} +3 -3
- package/dist/start-D9CKrwIR.mjs +1 -0
- package/package.json +5 -5
- package/dist/constants-8CB0Ahts.mjs +0 -2
- package/dist/init-CxQ5dRb6.mjs +0 -1
- package/dist/loader-CRq6UPI3.mjs +0 -1
- package/dist/preview-CQ49aEXX.mjs +0 -1
- package/dist/public/assets/FeedbackForm-COUWM5yL.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-C5U7L_Hh.js +0 -1
- package/dist/repair-skills-DphEbW5P.mjs +0 -1
- package/dist/src-BqabnCxP.mjs +0 -1
- package/dist/start-g5ChXDvt.mjs +0 -1
|
@@ -2025,11 +2025,11 @@ ${V5}
|
|
|
2025
2025
|
`).filter(Boolean).length}catch{return 0}}async function $Fe(e,t){let n=Kb(e),r;try{r=(await n.raw(`for-each-ref`,`--format=%(refname)%00%(committerdate:unix)%00%(contents:subject)`,`refs/wip/`)).trim().split(`
|
|
2026
2026
|
`).filter(Boolean)}catch{return 0}let i=0;for(let e of r){let[n=``,r=``,a=``]=e.split(`\0`);if(a.startsWith(`park:`))continue;let o=n.split(`/`).slice(3).join(`/`);if(!o||hd(o).classification!==`agent`)continue;let s=Number.parseInt(r,10);Number.isFinite(s)&&s*1e3<t&&(i+=1)}return i}const Q5=R(`shadow-maintenance`),eIe=(()=>{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})(),tIe=(()=>{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 $5(){return process.env.OK_SHADOW_MAINTENANCE_DISABLED===`1`}function e7(e){return e===`boot`?`boot`:e===`session-close`?`session-close`:e===`ttl`?`ttl`:`dead-chain`}var nIe=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(){$5()||this.destroyed||(this.flushCommitCounter+=1,this.flushCommitCounter>=200&&(this.flushCommitCounter=0,this.runScheduledMaintenance(`flush-counter`)))}async runBootMaintenance(){$5()||this.destroyed||await this.runScheduledMaintenance(`boot`)}async onSessionClose(){await this.runScheduledMaintenance(`session-close`)}async runScheduledMaintenance(e){if(!($5()||this.destroyed)&&!this.running){this.running=!0;try{if(await this.consolidateInner(e),this.destroyed||(await this.reapInner(e),this.destroyed))return;await this.gcInner(e)}finally{this.running=!1}}}async runReap(e){if(!($5()||this.destroyed)&&!this.running){this.running=!0;try{await this.reapInner(e)}finally{this.running=!1}}}async reapInner(e){if(!this.deps.projectGitDir)return;let t=this.deps.getShadow();if(!t)return;let n=performance.now();try{await qFe(t,this.deps.projectGitDir,void 0,this.deps.contentRoot??`.`),J5(`reap`,`ok`,performance.now()-n)}catch(t){J5(`reap`,`error`,performance.now()-n),Q5.warn({trigger:e,err:t},`[shadow-maintenance] reap failed; retrying next trigger`)}}async consolidateDeadChains(e){if($5()||this.destroyed)return{consolidated:!1,skipped:`disabled`};if(this.running)return{consolidated:!1,skipped:`busy`};this.running=!0;try{return await this.consolidateInner(e)}finally{this.running=!1}}async consolidateInner(e){let{getCurrentBranch:t,isWriterLive:n}=this.deps;if(!t||!n)return{consolidated:!1,skipped:`unconfigured`};if(Date.now()-this.lastConsolidationAt<tIe)return{consolidated:!1,skipped:`spacing`};let r=this.deps.getShadow();if(!r)return{consolidated:!1,skipped:`no-shadow`};try{let i=t()??`main`,a=await this.findDeadAgentChains(r,i,n);if(a.length<eIe)return{consolidated:!1,skipped:`below-threshold`,deadChains:a.length};let o=await Z5(r,i);await px(r,this.deps.contentRoot??``,a,i,void 0,{checkpointKind:{foldedRefs:a.length,trigger:e7(e)},timeoutMs:Wb}),this.lastConsolidationAt=Date.now();let s=await Z5(r,i);return QFe(e7(e)),Q5.info({trigger:e,branch:i,foldedChains:a.length,widthBefore:o,widthAfter:s},`[shadow-maintenance] auto-consolidation folded dead agent chains`),{consolidated:!0,deadChains:a.length,widthBefore:o,widthAfter:s}}catch(t){return Q5.warn({trigger:e,err:t},`[shadow-maintenance] consolidation failed; retrying next trigger`),{consolidated:!1,skipped:`error`}}}async findDeadAgentChains(e,t,n){return(await Jb(e,t)).filter(e=>e.classification===`agent`&&!e.isPark&&!n(e.writerId)).map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`}))}async runGc(e){if($5())return{ran:!1,skipped:`disabled`};if(this.destroyed)return{ran:!1,skipped:`no-shadow`};if(this.running)return J5(`gc`,`skipped`,0),{ran:!1,skipped:`busy`};this.running=!0;try{return await this.gcInner(e)}finally{this.running=!1}}async gcInner(e){let t=this.deps.getShadow();return t?Vb(t).withExclusive(()=>this.gcRun(e,t)):{ran:!1,skipped:`no-shadow`}}async gcRun(e,t){let n=performance.now();try{let r=await Y5(t);await Kb(t,{timeoutMs:Wb}).raw(`gc`,`--auto`);let i=await Y5(t),a=X5(t),o=performance.now()-n;return J5(`gc`,`ok`,o),a&&(this.lastGcLatch||ZFe(),Q5.warn({trigger:e,looseObjects:i.looseObjects},`[shadow-maintenance] gc.log latch present — auto-gc disabled until it self-expires (~1 day); retrying next trigger`)),this.lastGcLatch=a,Q5.info({trigger:e,looseBefore:r.looseObjects,looseAfter:i.looseObjects,packfiles:i.packfiles,durationMs:Math.round(o)},`[shadow-maintenance] gc complete`),{ran:!0,looseBefore:r.looseObjects,looseAfter:i.looseObjects,packfilesAfter:i.packfiles,latch:a,durationMs:o}}catch(t){return J5(`gc`,`error`,performance.now()-n),Q5.warn({trigger:e,err:t},`[shadow-maintenance] gc failed; retrying next trigger`),{ran:!1,skipped:`error`}}}};function rIe(e){return new nIe(e)}const t7=e=>Al(e)===`SKILL.md`;async function iIe(e,t,n){let r=R(`managed-artifact-watcher`),{watch:i}=await import(`./chokidar-BCS--vwu.mjs`),a=Array.from(new Set(e));for(let e of a)try{Es(e,{recursive:!0})}catch(t){pc(t)!==`EEXIST`&&r.warn({err:t,dir:e},`failed to create watch root; watcher may be inert`)}let o=i(a,{ignoreInitial:!0,depth:1,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});await new Promise(e=>{o.once(`ready`,e)});let s=new Map,c=e=>{if(!t7(e))return;let n;try{n=W(e,`utf-8`)}catch(t){if(pc(t)===`ENOENT`){r.debug({path:e},`managed-artifact leaf disappeared between event and read; dropping`);return}r.warn({err:t,path:e},`managed-artifact leaf read failed; dropping event`);return}if(n!==s.get(e)){s.set(e,n);try{t(e,n)}catch(t){r.warn({err:t,path:e},`managed-artifact change handler threw`)}}},l=e=>c(e);o.on(`add`,l),o.on(`change`,l),o.on(`unlink`,e=>{if(t7(e)&&(s.delete(e),r.debug({path:e},`managed-artifact leaf unlinked; live doc retained at current state`),n))try{n(e)}catch(t){r.warn({err:t,path:e},`managed-artifact unlink handler threw`)}}),o.on(`error`,e=>{r.warn({err:e,watchRoots:a},`[managed-artifact-watcher] chokidar error`)});let u=!1;return async()=>{u||(u=!0,await o.close())}}const n7=R(`mermaid-persistence`),r7={source:`local`,skipStoreHooks:!0,context:{origin:`mermaid-source`}};function i7(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let n=H(t,Dx(e));if(!MO(n,t))throw Error(`Invalid document name: ${e}`);return n}function a7(e,t,n){let r=e.getText(`source`);e.transact(()=>{r.length>0&&r.delete(0,r.length),t.length>0&&r.insert(0,t),n&&e.getMap(`lifecycle`).set(gi,crypto.randomUUID())},r7)}function aIe(e,t,n){if(e.getText(`source`).length>0)return;let r=i7(t,n.contentDir);if(!U(r))return;let i;try{i=W(r,`utf-8`)}catch(e){n7.warn({documentName:t,err:e},`load: could not read; seeding empty`);return}a7(e,i,!0),n.lkgCache.set(t,i)}async function oIe(e,t,n,r){if(n===r7)return`no-op`;let i=e.getText(`source`).toString(),a=r.lkgCache.get(t);if(i===a)return`no-op`;let o=i7(t,r.contentDir);try{if(await vs(H(o,`..`),{recursive:!0}),U(o)){let n=null;try{n=W(o,`utf-8`)}catch(e){e.code!==`ENOENT`&&n7.warn({documentName:t,err:e},`store: pre-write disk read failed (non-ENOENT); proceeding to write`),n=null}if(n!==null&&n!==a&&n!==i)return a7(e,n,!1),r.lkgCache.set(t,n),`reconciled`}return await us(o,i,{fs:_s}),r.lkgCache.set(t,i),`persisted`}catch(e){return n7.warn({documentName:t,err:e},`store: write failed`),`write-failed`}}function o7(e){let{body:t}=po(e);return Na(t).trim()}function sIe(e){return e===` `||e===`
|
|
2027
2027
|
`||e===` `||e===`\r`}function cIe(e,t){let n=o7(t);if(n.length===0)return{kind:`allow`,reason:`empty-base`};let r=o7(e);if(r===n)return{kind:`allow`,reason:`identical`};if(r.length<n.length*2)return{kind:`allow`,reason:`too-short`};let i=0,a=0;for(;i<r.length;){if(r.slice(i,i+n.length)!==n)return{kind:`allow`,reason:`not-integer-multiple`};for(i+=n.length,a++;i<r.length&&sIe(r[i]??``);)i++}return a>=2?{kind:`block`,reason:`structural-duplication`,copies:a}:{kind:`allow`,reason:`single-copy`}}const s7=R(`persistence`);var lIe=class extends Error{docName;size;limit;constructor(e,t,n=ni){super(`Document "${e}" is ${ce(t)}; OpenKnowledge opens documents up to ${ce(n)}.`),this.name=`DocumentOpenSizeLimitError`,this.docName=e,this.size=t,this.limit=n}};function c7(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(n.source===`local`){let e=n.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?nx:e.origin===`upstream-import`||e.origin===`git-upstream`?rx:ix}if(n.source===`connection`){let e=n.connection?.context;if(typeof e?.principalId==`string`){let n=e.principalId,r=t?.();return r&&r.id===n&&r.display_name&&r.display_email?{id:r.id,name:r.display_name,email:r.display_email}:{id:n,name:`Local User`,email:`${n}@openknowledge.local`}}return ix}return null}const uIe=new Set([`EACCES`,`EBADF`,`EBUSY`,`EEXIST`,`EISDIR`,`ELOOP`,`EMFILE`,`ENFILE`,`ENOENT`,`ENOSPC`,`ENOTDIR`,`EPERM`,`EROFS`,`ETXTBSY`,`EXDEV`]);function dIe(e){if(typeof e!=`object`||!e)return`unknown`;let t=e,n=typeof t.message==`string`?t.message:``;return n.startsWith(`symlink-escape:`)?`disk-write`:typeof t.code==`string`&&uIe.has(t.code)?n.includes(`rename`)?`traced-rename`:`disk-write`:e instanceof le?`serialize`:`unknown`}function fIe(e){return{sv:X_(e),json:ib(e.getXmlFragment(`default`),as).toJSON()}}function l7(e){let{frontmatter:t,body:n}=po(e);return Na(un(t,n))}function pIe(e){let t=e.getConnectionsCount;if(typeof t!=`function`)return 0;try{let n=t.call(e);return typeof n==`number`&&Number.isFinite(n)?n:0}catch{return 0}}function u7(e){let t;try{let n=e?.code;typeof n==`string`&&(t=n)}catch{}let n=`unknown store error`;try{n=e instanceof Error?e.message:String(e)}catch{}return{code:t,message:n}}function d7(e){let t=e?.durabilityState??new L5,n=e?.contentDir??process.cwd(),r;try{r=G(n)}catch{r=n}let i=e?.projectDir??process.cwd(),a=e?.shadowRef,o=e?.contentRoot??(jO(V(i,r))||`.`),s=e?.derivedDocumentIndex,c=e?.getPrincipal,l=e?.onAgentCommit,u=e?.onFlushCommit,d=e?.onDiskFlush,f=e?.onConfigPersisted,p=e?.onManagedSkillPersisted,m=e?.mdManager??os,h=e?.ephemeral??!1,g={projectDir:i,contentDir:r,lkgCache:new Map,homedirOverride:e?.configHomedirOverride,onConfigRejected:e?.onConfigRejected,ephemeral:h},_=new Map,v={projectDir:i,homedirOverride:e?.configHomedirOverride,lkgCache:_,setReconciledBase:(e,n)=>t.setReconciledBase(e,n),getReconciledBase:e=>t.getReconciledBase(e),beforeReconcileDivergence:(e,t,n,r)=>A(e,t,n,r)},y={contentDir:r,lkgCache:new Map},b=new Set,x=new Set,S=e?.applyDiskContentToDoc??dF,C=null,w=new Map,T=e?.gitEnabled??!0,E=e?.commitDebounceMs??15e3,D=e?.wipRef??`refs/wip/main`,ee=e?.getCurrentBranch,te=null,O=0,k=null,ne=!1,re=null,ie=new Map;async function ae(){De();let e=Date.now();return hs(`persistence.commitToWipRef`,void 0,async()=>await oe()).finally(()=>{Ee?.record((Date.now()-e)/1e3)})}async function oe(){let e=a?.current;if(e){let t=CO(),n=ee?.()??`main`;if(t.size===0){let t={v:1,writer_id:ix.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:ix.name,color_seed:ix.id,docs:[]},r=`${od([])}\n\n${nd(t)}`;try{let t=await Zb(e,ix,o,r,n);O=0,s7.info({sha:t.slice(0,8),writer:ix.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${ix.id}`);try{xV(e.gitDir,ix.id,t,aV(e.gitDir))}catch(e){s7.warn({err:e},`[rename-log] service-writer backfill failed`)}}catch(e){O++,wb(),s7.error({err:e,attempt:O},`[persistence] Shadow commit failed (attempt ${O})`),O>=3&&s7.error({err:e,attempt:O},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let r;try{r=await $b(e,o)}catch(e){wO(t),O++,wb(),s7.error({err:e,attempt:O},`[persistence] Shadow WIP tree build failed (attempt ${O})`);return}let i=!1;for(let[a,o]of t){let t={id:a,name:o.displayName,email:`${a}@openknowledge.local`},s=[...o.docs],c=o.actor,d=[...o.summaries],f=[...o.previousPaths],p={v:1,writer_id:a,principal:c?.principalId??null,agent_session:a.startsWith(`agent-`)?a.slice(6):null,agent_type:c?.agentType??null,client_name:c?.clientName??null,client_version:c?.clientVersion??null,label:c?.label??null,display_name:o.displayName,color_seed:o.colorSeed,docs:s,...d.length>0?{summaries:d}:{},...f.length>0?{previous_paths:f}:{}},m=`${md(o.subjectOverride??od(s),d)}\n\n${nd(p)}`;try{let o=await tx(e,t,r,m,n);i=!0;try{u?.()}catch(e){s7.warn({err:e},`[persistence] onFlushCommit callback failed (non-fatal)`)}s7.info({sha:o.slice(0,8),writer:a,tree:r.slice(0,8)},`[persistence] Shadow WIP commit: ${o.slice(0,8)} on refs/wip/${a}`);try{xV(e.gitDir,a,o,aV(e.gitDir))}catch(e){s7.warn({err:e},`[rename-log] backfill failed; will retry next commit`)}a.startsWith(`agent-`)&&l?.()}catch(e){DO(a,o),Cse(),s7.error({err:e,writer:a},`[persistence] Per-writer shadow commit failed for ${a}`)}}i?O=0:(O++,wb(),O>=3&&s7.error({attempt:O},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=Kb({gitDir:H(i,`.git`),workTree:i}),n=H(i,`.git/index-wip`),r={GIT_INDEX_FILE:n};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(r).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?s7.info({},`[persistence] Empty repo — starting with empty index`):s7.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(r).raw(`add`,o);let e=(await t.env(r).raw(`write-tree`)).trim(),n=null;try{n=(await t.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 e}let i=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];n&&i.push(`-p`,n);let a=(await t.raw(...i)).trim();await t.raw(`update-ref`,D,a),O=0,s7.info({sha:a.slice(0,8),wipRef:D},`[persistence] Git commit: ${a.slice(0,8)} on ${D}`)}catch(e){O++,wb(),s7.error({err:e,attempt:O},`[persistence] Git commit failed (attempt ${O})`),O>=3&&s7.error({err:e,attempt:O},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{xs(n)}catch{}}}function se(e){if(e<=0)return E;let t=2**Math.min(e,5),n=Math.random()*.25*E;return E*t+n}function ce(){T&&(t.isBatchInProgress()||(te&&clearTimeout(te),te=setTimeout(()=>{if(te=null,k){ne=!0;return}k=ae().finally(()=>{k=null,ne&&(ne=!1,ce())})},se(O))))}async function le(){te&&(clearTimeout(te),te=null,k||=ae().finally(()=>{k=null,ne&&(ne=!1,ce())})),k&&await k}function ue(t,n){try{let{frontmatter:r,body:i}=po(t),a=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:n}:void 0,o=m.parseWithFallback(i,a);return Na(un(r,m.serialize(o)))}catch(e){return s7.debug({err:e,documentName:n},`[g8] ephemeral canonical baseline failed; falling through to write`),null}}function de(t,n,r){e?.getLossRing?.()?.record({event:`repair-rebuild`,docName:r,writerId:null,direction:`b`,site:fe,connections:pIe(t)});try{let i=t.getXmlFragment(`default`),a=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:r}:void 0,o=os.parseWithFallback(n,a),s=as.nodeFromJSON(o);t.transact(()=>{nb(t,i,s,{mapping:new Map,isOMark:new Map})},_C)}catch(e){gce(),s7.warn({err:e,documentName:r},`[persistence] reconcileFragmentNow failed for ${r}`)}}let fe=`persistence-prewrite`,pe=`persistence-duplication-reset`,me=`persistence-divergence-realign`,he=`managed-artifact-reconcile`,ge=new WeakMap;function _e(t,n){$se(),e?.getLossRing?.()?.record({event:`persistence-hold`,docName:t,writerId:null,direction:`b`,site:fe,lostLen:n.reduce((e,t)=>e+t.length,0)})}function ve(t,n,r,i,s){if(ece(),ge.get(t)===r){nce();return}ge.set(t,r);let c=uo(r,i,``),l=c.reduce((e,t)=>e+t.length,0),u=e?.getLossRing?.(),d=a?.current;if(!d){u?.record({event:pb,docName:n,writerId:null,direction:`b`,site:fe,lostLen:l,witnessAvailable:s});return}let f=ee?.()??`main`;queueMicrotask(()=>{lx(d,o,{kind:`persistence-reconcile-loss`,docName:n,contents:r,label:`Before persistence fragment rebuild @ ${new Date().toISOString()}`,branch:f,metadata:{atRiskLines:c.length,witnessAvailable:s}}).then(e=>{tce(),u?.record({event:pb,docName:n,writerId:null,direction:`b`,site:fe,lostLen:l,witnessAvailable:s,checkpointSha:e}),console.warn(JSON.stringify({event:`persistence-reconcile-loss-checkpoint-created`,docName:n,sha:e,kind:`persistence-reconcile-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{ge.get(t)===r&&ge.delete(t);let i=e instanceof Error?e:Error(String(e));s7.warn({documentName:n,err:i},`[persistence] reconcile-loss checkpoint write failed`),u?.record({event:pb,docName:n,writerId:null,direction:`b`,site:fe,lostLen:l,witnessAvailable:s})})})}let ye=new WeakMap;function be(t,n,r,i,s){rce();let c=e?.getLossRing?.(),l=a?.current;if(!l){c?.record({event:pb,docName:n,writerId:null,direction:`b`,site:pe,lostLen:r.length});return}if(ye.get(t)===r){ace();return}ye.set(t,r);let u=ee?.()??`main`;queueMicrotask(()=>{lx(l,o,{kind:`persistence-duplication-reset`,docName:n,contents:r,label:`Before duplication reset @ ${new Date().toISOString()}`,branch:u,metadata:{copies:i,fragmentChildren:s}}).then(e=>{ice(),c?.record({event:pb,docName:n,writerId:null,direction:`b`,site:pe,lostLen:r.length,checkpointSha:e}),console.warn(JSON.stringify({event:`persistence-duplication-reset-checkpoint-created`,docName:n,sha:e,kind:`persistence-duplication-reset`,timestamp:new Date().toISOString()}))}).catch(e=>{ye.get(t)===r&&ye.delete(t);let i=e instanceof Error?e:Error(String(e));s7.warn({documentName:n,err:i},`[persistence] duplication-reset checkpoint write failed`)})})}let xe=new WeakMap;function Se(t,n,r,i){sce();let s=e?.getLossRing?.(),c=a?.current;if(!c){s?.record({event:pb,docName:n,writerId:null,direction:`b`,site:me,lostLen:r.length});return}if(xe.get(t)===r){lce();return}xe.set(t,r);let l=ee?.()??`main`;queueMicrotask(()=>{lx(c,o,{kind:`persistence-divergence-realign`,docName:n,contents:r,label:`Before divergence realign @ ${new Date().toISOString()}`,branch:l,metadata:{diskBytes:i.length,discardedBytes:r.length}}).then(e=>{cce(),s?.record({event:pb,docName:n,writerId:null,direction:`b`,site:me,lostLen:r.length,checkpointSha:e}),console.warn(JSON.stringify({event:`persistence-divergence-realign-checkpoint-created`,docName:n,sha:e,kind:`persistence-divergence-realign`,timestamp:new Date().toISOString()}))}).catch(e=>{xe.get(t)===r&&xe.delete(t);let i=e instanceof Error?e:Error(String(e));s7.warn({documentName:n,err:i},`[persistence] divergence-realign checkpoint write failed`)})})}let Ce=new WeakMap;function A(t,n,r,i){let s=e?.getLossRing?.(),c={baselineFullMd:i,report:e=>{try{let t=mx(e);if(t.length===0)return;s?.record({event:db,docName:n,writerId:nx.id,direction:`b`,site:he,lostLen:t.reduce((e,t)=>e+t.length,0),digest:Zi(t.join(`
|
|
2028
|
-
`))})}catch(e){s7.warn({documentName:n,err:e},`[persistence] managed-artifact reconcile loss detection failed`)}}},l=NV(n),u=a?.current;if(!u||!l.managed||!l.versioned)return s?.record({event:pb,docName:n,writerId:null,direction:`b`,site:he,lostLen:r.length}),c;if(Ce.get(t)===r)return fce(),c;Ce.set(t,r);let d=ee?.()??`main`,f=l.docKey;return queueMicrotask(()=>{lx(u,o,{kind:`managed-artifact-reconcile`,docName:f,contents:r,label:`Before artifact reconcile @ ${new Date().toISOString()}`,branch:d,metadata:{diskBytes:i.length,discardedBytes:r.length}}).then(e=>{dce(),s?.record({event:pb,docName:n,writerId:null,direction:`b`,site:he,lostLen:r.length,checkpointSha:e}),console.warn(JSON.stringify({event:`managed-artifact-reconcile-checkpoint-created`,docName:n,sha:e,kind:`managed-artifact-reconcile`,timestamp:new Date().toISOString()}))}).catch(e=>{Ce.get(t)===r&&Ce.delete(t);let i=e instanceof Error?e:Error(String(e));s7.warn({documentName:n,err:i},`[persistence] managed-artifact reconcile checkpoint write failed`)})}),c}let we=null,Te=null,Ee=null;function De(){if(we)return;let e=Rs();we=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),Te=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),Ee=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}async function Oe({document:n,documentName:i,lastTransactionOrigin:a}){De();let o=Date.now(),l;return hs(`persistence.onStoreDocument`,{attributes:{"doc.name":i}},async()=>{let o=
|
|
2028
|
+
`))})}catch(e){s7.warn({documentName:n,err:e},`[persistence] managed-artifact reconcile loss detection failed`)}}},l=NV(n),u=a?.current;if(!u||!l.managed||!l.versioned)return s?.record({event:pb,docName:n,writerId:null,direction:`b`,site:he,lostLen:r.length}),c;if(Ce.get(t)===r)return fce(),c;Ce.set(t,r);let d=ee?.()??`main`,f=l.docKey;return queueMicrotask(()=>{lx(u,o,{kind:`managed-artifact-reconcile`,docName:f,contents:r,label:`Before artifact reconcile @ ${new Date().toISOString()}`,branch:d,metadata:{diskBytes:i.length,discardedBytes:r.length}}).then(e=>{dce(),s?.record({event:pb,docName:n,writerId:null,direction:`b`,site:he,lostLen:r.length,checkpointSha:e}),console.warn(JSON.stringify({event:`managed-artifact-reconcile-checkpoint-created`,docName:n,sha:e,kind:`managed-artifact-reconcile`,timestamp:new Date().toISOString()}))}).catch(e=>{Ce.get(t)===r&&Ce.delete(t);let i=e instanceof Error?e:Error(String(e));s7.warn({documentName:n,err:i},`[persistence] managed-artifact reconcile checkpoint write failed`)})}),c}let we=null,Te=null,Ee=null;function De(){if(we)return;let e=Rs();we=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),Te=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),Ee=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}async function Oe({document:n,documentName:i,lastTransactionOrigin:a}){De();let o=Date.now(),l;return hs(`persistence.onStoreDocument`,{attributes:{"doc.name":i}},async()=>{let o=Zx(n);if(o!==null){s7.info({documentName:i,lifecycleStatus:o},`[persistence] Skipped store for ${i}: lifecycle=${o}`),w.delete(i),b.delete(i);return}if(!Tle(n)){let e=w.get(i)??0;if(e<8){let t=IS(n);console.warn(JSON.stringify({event:`persistence-skip-non-quiescent`,"doc.name":i,wallClockMsSinceLastTransaction:t??null,deferCount:e})),Lse(),w.set(i,e+1);return}console.warn(JSON.stringify({event:`persistence-force-flush-during-burst`,"doc.name":i,wallClockMsSinceLastTransaction:IS(n)??null,deferCount:e})),Rse()}let u=t.consumeAgentWriteStore(i),{sv:f,json:p}=fIe(n),g=n.getText(`source`).toString(),{frontmatter:_,body:v}=po(g),y=un(_,v),C,T=null;try{T=un(_,m.serialize(p)),C=GS(y,T,{site:`persistence`,docName:i,suppressDevThrow:!0,canonicalizeBody:WS(m,{resolveEmbed:e?.resolveEmbed,resolveSize:e?.resolveSize,docName:i})})}catch(e){Sce(),console.warn(JSON.stringify({event:`persistence-sanity-check-serialize-failed`,"doc.name":i,"error.type":e instanceof Error?e.constructor.name:typeof e,timestamp:new Date().toISOString()})),s7.warn({err:e,documentName:i},`[persistence] Sanity-check serialize failed for ${i}; proceeding with ytext bytes`),T=null,C=!1}if(!C){let e=T===null?void 0:eue(n);T!==null&&e!==void 0&&ro(T,y,e)?_e(i,uo(T,y,e)):(T!==null&&ve(n,i,T,y,e!==void 0),de(n,v,i))}let E=t.getReconciledBase(i),D=l7(g),ee=E!==void 0&&(u?y===E:D===Na(E)&&!Zr(E,y));if(!ee&&!u&&h&&E!==void 0){let e=ue(E,i);e!==null&&D===e&&(ee=!0)}if(ee){kO()>0&&ce(),w.delete(i);return}if(E===void 0&&Na(y)===``){s7.warn({documentName:i},`[persistence] Skipped phantom write for ${i}: empty Y.Doc with no reconciled base`),w.delete(i);return}let te=c7(a,c);if(te&&te.id!==ix.id&&(AO(te.id)||xO(i,te.id,te.name,te.id)),E!==void 0){let t=cIe(y,E);if(t.kind===`block`&&x.has(i))oce(),console.warn(JSON.stringify({event:`ok-persistence-duplication-spared`,"doc.name":i,candidateBytes:y.length,baseBytes:E.length,fragmentChildren:n.getXmlFragment(`default`).length,copies:t.copies,reason:t.reason}));else if(t.kind===`block`){if(b.has(i)){s7.warn({documentName:i},`[persistence] Tripwire breaker active — skipping duplicate store for ${i}`);return}let a=n.getXmlFragment(`default`).length;console.warn(JSON.stringify({event:`ok-persistence-duplication-blocked`,"doc.name":i,candidateBytes:y.length,baseBytes:E.length,fragmentChildren:a,copies:t.copies,reason:t.reason}));try{let o=NO(i,r),s;if(U(o)){let e=null;try{e=G(o)}catch(e){s7.warn({err:e,documentName:i},`[persistence] Tripwire reset realpath failed for ${i}; using currentBase`)}if(e&&PO(e,r))try{s=W(e,`utf-8`)}catch(t){s7.warn({err:t,documentName:i,canonical:e},`[persistence] Tripwire reset readFileSync failed for ${i}; using currentBase`),s=E}else e&&s7.warn({docName:i,originalPath:o,canonical:e,contentDir:r},`[persistence] symlink-escape on tripwire reset: ${o} → ${e}, using currentBase`),s=E}else s=E;be(n,i,y,t.copies,a);let c=e?.getLossRing?.(),l={baselineFullMd:s,report:e=>{try{let t=mx(e);if(t.length===0)return;c?.record({event:db,docName:i,writerId:nx.id,direction:`b`,site:pe,lostLen:t.reduce((e,t)=>e+t.length,0),digest:Zi(t.join(`
|
|
2029
2029
|
`))})}catch(e){s7.warn({documentName:i,err:e},`[persistence] duplication-reset loss detection failed`)}}};n.transact(()=>{S(n,s,void 0,void 0,void 0,l)},uF),b.delete(i)}catch(e){b.add(i),s7.error({err:e,documentName:i},`[persistence] Tripwire reset failed for ${i}`)}w.delete(i);return}}l=Na(y),t.beginInFlightFlush(i,l);let O=NO(i,r);await vs(z(O),{recursive:!0});let k;try{k=await gu(O)}catch(e){let t=pc(e);if(t===`ENOENT`){let e=!1;try{e=Kl(O).isSymbolicLink()}catch(e){pc(e)!==`ENOENT`&&s7.warn({err:e,path:O},`[persistence] lstat failed during broken-symlink check`)}e&&s7.warn({docName:i,reason:`broken-symlink`},`[persistence] broken-symlink fallback`),k=O}else if(t===`ELOOP`)throw s7.error({path:O,err:e},`[persistence] Symlink cycle at ${O}`),Error(`Symlink cycle detected at ${O}`);else throw e}if(!PO(k,r)){let e=`symlink-escape: ${O} resolves to ${k} outside ${r}`;throw s7.error({docName:i,originalPath:O,canonical:k,contentDir:r},`[persistence] ${e}`),Error(e)}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_DIVERGENCE===i&&await gs(k,`# NATIVE
|
|
2030
2030
|
|
|
2031
2031
|
native-divergence-injected
|
|
2032
|
-
`,`utf-8`),
|
|
2032
|
+
`,`utf-8`),u&&E!==void 0){let r=null;try{U(k)&&(r=W(k,`utf-8`))}catch(e){r=null,s7.warn({err:e,documentName:i},`[persistence] L3 disk-read failed; divergence check skipped for this store`)}if(r!==null&&Na(r)!==Na(E)){let a=r;console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":i,outcome:`reverted`,diskBytes:a.length,baseBytes:E.length,candidateBytes:y.length})),Se(n,i,y,a);let o=e?.getLossRing?.(),s={baselineFullMd:a,report:e=>{try{let t=mx(e);if(t.length===0)return;o?.record({event:db,docName:i,writerId:nx.id,direction:`b`,site:me,lostLen:t.reduce((e,t)=>e+t.length,0),digest:Zi(t.join(`
|
|
2033
2033
|
`))})}catch(e){s7.warn({documentName:i,err:e},`[persistence] divergence-realign loss detection failed`)}}};try{n.transact(()=>{S(n,a,void 0,void 0,void 0,s)},uF)}catch(e){throw t.recordStoreFailure(i,u7(e)),w.delete(i),e}t.setReconciledBase(i,a),t.recordStoreDivergence(i),w.delete(i);return}}e?.isRecentlyRemoved?.(i)&&(bse(),console.warn(JSON.stringify({event:`persistence-store-removed-doc`,"doc.name":i})));let ne=`${k}.tmp.${crypto.randomUUID()}`;try{if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_FAULT===i){let e=Error(`OK_TEST_STORE_FAULT: simulated disk failure for ${i}`);throw e.code=`ENOSPC`,e}await gs(ne,y,`utf-8`),await Ps(ne,k),AF(k,MF(y)),t.clearStoreFailure(i),Tse();try{d?.(i,f,y,E??null)}catch(e){s7.warn({err:e,documentName:i},`[persistence] onDiskFlush callback failed for ${i}`)}}catch(e){try{xs(ne)}catch{}throw w.delete(i),t.recordStoreFailure(i,u7(e)),s7.error({err:e,documentName:i},`[persistence] Failed to save ${i}`),e}s7.info({filePath:k,bytes:y.length},`[persistence] Wrote ${k} (${y.length} bytes)`),t.setReconciledBase(i,y),x.add(i),b.delete(i),w.delete(i);try{await s?.recordDurableStore(i,y)}catch(e){s7.warn({err:e,documentName:i},`[derived-index] durable-store projection failed; disk write remains authoritative`)}cs({"persistence.bytes":y.length}),ce()}).finally(()=>{l!==void 0&&t.finishInFlightFlush(i,l),Te?.record((Date.now()-o)/1e3)})}function ke({document:e,documentName:n,lastTransactionOrigin:r}){ie.set(n,{branch:t.getActiveBranch(),document:e,lastTransactionOrigin:r})}async function Ae(e=`within-branch`){return re?(C=C===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,re):(re=(async()=>{let n=e;for(;;){let e=[...ie.entries()];if(ie.clear(),n!==`discard-stale`){for(let[n,r]of e)if(r.branch===t.getActiveBranch())try{await Oe({document:r.document,documentName:n,lastTransactionOrigin:r.lastTransactionOrigin})}catch(e){let t=process.env.OK_TELEMETRY_VERBOSE===`1`,r=``;try{r=String(e?.message??``)}catch{r=``}let i=Zi(r),a;try{a=dIe(e)}catch(e){let r=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":n,classifyErrorHash:Zi(r),errorMessageHash:i,...t?{classifyErrorMessage:r}:{},timestamp:new Date().toISOString()})),a=`unknown`}Cce(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":n,errorClass:a,errorMessageHash:i,...t?{errorMessage:r}:{},timestamp:new Date().toISOString()})),s7.error({err:e,documentName:n},`[persistence] Deferred store failed for ${n}`)}}let r=C;if(C=null,ie.size===0&&r===null)break;n=r??`within-branch`}})().finally(()=>{re=null}),re)}let je={async onLoadDocument({document:n,documentName:i,context:a}){if(x.delete(i),Ax(i))return;if(jx(i)){tFe(n,i,g);return}if(Mx(i)){BV(n,i,v);return}if(Nx(i)||Px(i)||Fx(i)){aIe(n,i,y);return}De();let o=Date.now();return hs(`persistence.onLoadDocument`,{attributes:{"doc.name":i}},async()=>{s7.info({documentName:i,connections:n.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${i} (connections: ${n.getConnectionsCount?.()??`?`})`);let a=NO(i,r);if(!U(a))return;let o=a;try{let e=G(a);if(!PO(e,r)){s7.warn({path:a,canonical:e},`[persistence] symlink-escape on load: ${a} → ${e}, refusing`);return}o=e}catch(e){if(pc(e)===`ELOOP`){s7.warn({path:a},`[persistence] Symlink cycle on load: ${a}, refusing`);return}}let s=ru(o).size;if(s>524288)throw s7.warn({documentName:i,fileSize:s,limit:ni},`[persistence] Document exceeds open byte limit; refusing to load`),new lIe(i,s);let c=W(a,`utf-8`),l=n.getXmlFragment(`default`);s7.info({documentName:i,fragmentLength:l.length},`[persistence] onLoadDocument ${i}: fragment.length=${l.length} before update`),l.length===0?(n.transact(()=>{dF(n,c,e?.resolveEmbed,i,e?.resolveSize),n.getMap(`lifecycle`).set(gi,crypto.randomUUID())},uF),s7.info({filePath:a,children:l.length},`[persistence] Loaded ${a} into Y.Doc (${l.length} children)`),l.observeDeep(()=>{s7.info({documentName:i,fragmentLength:l.length},`[persistence] MUTATION on ${i}: fragment.length=${l.length}`)})):s7.info({documentName:i,children:l.length},`[persistence] Skipped load for ${i} — fragment already has ${l.length} children`),t.setReconciledBase(i,c)}).finally(()=>{we?.record((Date.now()-o)/1e3)})},async onStoreDocument({document:e,documentName:n,lastTransactionOrigin:r,lastContext:i}){if(!Ax(n)){if(jx(n)){let t=await rFe(e,n,r,g);if(t===`persisted`||t===`reconciled`)try{f?.(n)}catch(e){s7.warn({err:e,documentName:n},`[persistence] onConfigPersisted callback failed`)}return}if(Mx(n)){if(await UV(e,n,r,v)===`persisted`){let e=c7(r,c);if(e&&e.id!==ix.id&&!e.id.startsWith(`agent-`)){let t=MV(n);t&&(xO(t.docKey,e.id,e.name,e.id,t.subject),ce())}try{p?.(n)}catch(e){s7.warn({err:e,documentName:n},`[persistence] onManagedSkillPersisted callback failed`)}}return}if(Nx(n)||Px(n)||Fx(n)){await oIe(e,n,r,y);return}if(t.isBatchInProgress()){ke({document:e,documentName:n,lastTransactionOrigin:r});return}return Oe({document:e,documentName:n,lastTransactionOrigin:r})}}};async function Me(){k&&await k}async function Ne(){for(;k;)await k;kO()!==0&&(k=ae().finally(()=>{k=null,ne&&(ne=!1,ce())}),await k)}function Pe(){return{branchDeferred:ie.size,quiescenceDeferred:w.size}}async function Fe(e,n){if(!zx(n)){if(t.isBatchInProgress()){ke({document:e,documentName:n,lastTransactionOrigin:null});return}return Oe({document:e,documentName:n,lastTransactionOrigin:null})}}return{extension:je,durabilityState:t,flushDeferredStores:Ae,flushPendingGitCommit:le,flushContributors:Ne,waitForPendingCommits:Me,getQueueDepths:Pe,forceStore:Fe,configPersistenceCtx:g,managedArtifactCtx:v}}const f7=R(`persistence-staleness`);var p7=class extends Error{constructor(e){super(e),this.name=`StructuralDiskReadError`}};function mIe(e){let t=e.graceMs??3e5,n=e.sweepIntervalMs??6e4,r=e.now??Date.now,i=e.forceStoreTimeoutMs??3e4,{getBase:a,isBatchActive:o,hasInFlight:s}=e,c=e.msSinceLastUserTx??IS,l=new Map,u=!1,d=null;function f(e){return l7(e)}function p(e){return e===void 0?void 0:Na(e)}function m(e,t,n,r){return t===void 0?e!==``:e===t?r!==void 0&&Zr(r,n):!0}async function h(){if(u||o())return;let n=r(),d=0,h=0,_=0,v=0,y=0,b=new Set;for(let[n,x]of e.getLoadedDocuments()){if(u)return;if(b.add(n),zx(n)||Zx(x)!==null)continue;if(s(n)){h++;continue}d++;let S=x.getText(`source`).toString(),C=a(n);if(C!==void 0&&S===C){l.delete(n);continue}let w=f(S),T=p(C);if(!m(w,T,S,C)){l.delete(n);continue}_++;let E=r(),D=c(x,E);if(D!==null&&D<t)continue;let ee=l.get(n);if(ee&&ee.fingerprint===w&&(ee.declined||E-ee.atMs<t))continue;let te=ee?.fingerprint!==w;te&&zse();let O=!te&&ee?ee.firstDetectedAtMs:E,k=E-O,ne=null,re=!1;try{let t=e.readDiskBytes(n);T===void 0?t!==null&&(ne=`disk-file-never-loaded`):t===null?ne=`disk-file-missing`:Na(t)!==T&&(ne=`disk-diverged-from-base`)}catch(e){e instanceof p7?(ne=`disk-read-refused`,f7.error({err:e,docName:n},`[persistence-staleness] disk read refused; standing down until content changes`)):(ne=`disk-read-failed`,re=!0,f7.warn({err:e,docName:n},`[persistence-staleness] disk read failed; standing down`))}if(ne!==null){y++,Vse(),l.set(n,{fingerprint:w,atMs:E,firstDetectedAtMs:O,declined:!re}),f7.warn({docName:n,ageMs:D,staleForMs:k,candidateBytes:w.length,baseBytes:C?.length??0,action:`stood-down`,reason:ne},`[persistence-staleness] Unflushed edits detected for ${n} but disk state is unverified or unreconciled; not overwriting`);continue}f7.warn({docName:n,ageMs:D,staleForMs:k,candidateBytes:w.length,baseBytes:C?.length??0,action:`forced-store`},`[persistence-staleness] Doc ${n} has unpersisted edits past the grace window with no pending store; forcing a store`),l.set(n,{fingerprint:w,atMs:E,firstDetectedAtMs:O,declined:!1}),Bse(),v++;let ie;try{ie=e.forceStore(x,n)}catch(e){ie=Promise.reject(e)}let ae=await g(ie).catch(e=>(f7.error({err:e,docName:n,staleForMs:k},`[persistence-staleness] Forced store failed for ${n}; will retry`),`failed`));if(ae===`failed`)continue;if(ae===`timeout`){xce(),f7.error({docName:n,staleForMs:k,forceStoreTimeoutMs:i},`[persistence-staleness] Forced store for ${n} did not settle within ${i}ms; setting it aside until that store settles or its content changes, so the sweep stays live for other documents`);let e={fingerprint:w,atMs:r(),firstDetectedAtMs:O,declined:!0};l.set(n,e);let t=()=>u?`watchdog-disposed`:l.get(n)===e?(l.set(n,{...e,declined:!1}),`resumed`):`superseded`;ie.then(()=>{let i=t();f7.info({docName:n,disposition:i,settledAfterTimeoutMs:r()-e.atMs},`[persistence-staleness] Previously timed-out forced store for ${n} landed`)},i=>{let a=t();f7.warn({err:i,docName:n,disposition:a,settledAfterTimeoutMs:r()-e.atMs},`[persistence-staleness] Previously timed-out forced store for ${n} settled with an error`)}).catch(()=>{});continue}if(u||o())return;let oe=x.getText(`source`).toString(),se=a(n),ce=f(oe);m(ce,p(se),oe,se)&&ce===w?(l.set(n,{fingerprint:w,atMs:E,firstDetectedAtMs:O,declined:!0}),f7.info({docName:n},`[persistence-staleness] Store completed without clearing divergence for ${n}; suppressing until content changes`)):l.delete(n)}for(let e of l.keys())b.has(e)||l.delete(e);let x={scanned:d,divergent:_,forced:v,stoodDown:y,skippedInFlight:h,elapsedMs:r()-n};_>0||v>0||y>0?f7.info(x,`[persistence-staleness] sweep complete`):f7.debug(x,`[persistence-staleness] sweep complete`)}async function g(e){let t,n=new Promise(e=>{t=setTimeout(()=>e(`timeout`),i),t.unref?.()});return Promise.race([e.then(()=>`settled`),n]).finally(()=>{t!==void 0&&clearTimeout(t)})}function _(){return d||(d=h().finally(()=>{d=null}),d)}let v=setInterval(()=>{_().catch(e=>{f7.error({err:e},`[persistence-staleness] sweep failed`)})},n);return v.unref?.(),{sweep:_,dispose:()=>(u=!0,clearInterval(v),d??Promise.resolve())}}async function hIe(e){try{let t=nc({baseDir:e,timeout:{block:3e3}});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 m7(e){let t=dP(e),n=H(t,`principal.json`),{name:r,email:i}=await hIe(e);if(U(n)){let e;try{e=JSON.parse(W(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${xu()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?Um(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?Um(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return au(n,JSON.stringify(s,null,2),`utf-8`),s}ql(t,{recursive:!0});let a=`principal-${xu()}`,o=a.slice(10,18),s={id:a,display_name:r?Um(r):`Local User`,display_email:i?Um(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return au(n,JSON.stringify(s,null,2),`utf-8`),s}var gIe=class{map=new Map;capacity;onEviction;onSizeChange;onMutate;now;constructor(e=1e4,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?.()}};const _Ie=R(`recovered-file-target`);function vIe({watcher:e,contentDir:t,relativePath:n,exists:r,invalidateReferencedAssetsCache:i}){let a=B(t,n);if(!r){e.mutateFileIndex({kind:`file-delete`,path:a,relativePath:n}),i?.();return}try{let t=G(a),r=ru(t);e.mutateFileIndex({kind:`file-create`,path:t,relativePath:n,size:r.size,modifiedTs:r.mtimeMs,inode:r.ino})}catch(t){let r=t instanceof Error&&`code`in t&&typeof t.code==`string`?t.code:`UNKNOWN`;r!==`ENOENT`&&_Ie.warn({code:r},`recovered file metadata unavailable; treating local target as deleted`),e.mutateFileIndex({kind:`file-delete`,path:a,relativePath:n})}i?.()}function h7(e,t){let n=e.resolveFilePath(t);return n!==null&&e.fileExists(n)}async function yIe(e,t){try{if(Ix(e))return;let n=t.recentlyRemovedDocs.get(e);if(n===void 0)return;if(n.kind===`deleted`){if(h7(t,e)){t.recentlyRemovedDocs.delete(e);return}throw Mb(),cs({"auth.reason":`doc-deleted`}),new rZ(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let r=new Set([e]),i=n.newDocName;for(;;){if(r.has(i)){Dce(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:i}));return}r.add(i);let n=t.recentlyRemovedDocs.get(i);if(n===void 0)throw jb(),cs({"auth.reason":`rename-redirect`}),new rZ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i);if(n.kind===`deleted`)throw h7(t,i)?(t.recentlyRemovedDocs.delete(i),jb(),cs({"auth.reason":`rename-redirect`}),new rZ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i)):(Mb(),cs({"auth.reason":`doc-deleted`}),new rZ(`doc-deleted`,`removed-doc rejection for deleted ${e}`));i=n.newDocName}}catch(t){if(t instanceof rZ)throw t;Ece(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}const g7=R(`removed-docs-journal`);function _7(e){return B(dP(e),`removed-docs.json`)}function bIe(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 xIe(e){let t=_7(e);if(!U(t))return[];try{let e=JSON.parse(W(t,`utf-8`));if(e.version!==1||!Array.isArray(e.entries))return g7.warn({path:t},`[removed-docs-journal] unrecognized journal shape — ignoring`),[];let n=[];for(let t of e.entries){if(!bIe(t))continue;let{docName:e,...r}=t;n.push([e,r])}return n}catch(e){return g7.warn({path:t,err:e},`[removed-docs-journal] failed to read journal — ignoring`),[]}}function v7(e,t){let n=_7(e),r={version:1,entries:t.map(([e,t])=>({docName:e,...t}))};Es(z(n),{recursive:!0});let i=`${n}.tmp`;Fs(i,JSON.stringify(r),`utf-8`),ys(i,n)}const y7=R(`server-observers`);function b7(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(Ax(r)||jx(r)||Nx(r)||Px(r)||Fx(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=FC({doc:a,xmlFragment:o,ytext:s,mdManager:e.mdManager,schema:e.schema,docName:r,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,deferGuardEnabled:e.deferGuardEnabled,lossDetectorEnabled:e.lossDetectorEnabled,fixedPointBackstopEnabled:e.fixedPointBackstopEnabled,preDrainEnabled:e.preDrainEnabled,lossRing:e.lossRing});return t.set(r,n),!0}catch(e){return y7.error({docName:r,err:e},`[ServerObserverExtension] Failed to attach observers for '${r}'`),Ob(`a`),Ob(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(y7.warn({docName:r},`[ServerObserverExtension] Retrying observer attachment for '${r}'`),c())},5e3);n.set(r,e)}},async afterUnloadDocument({documentName:e}){let r=n.get(e);r&&(clearTimeout(r),n.delete(e));let i=t.get(e);i&&(i(),t.delete(e))},async onDestroy(){for(let e of n.values())clearTimeout(e);n.clear();for(let[e,n]of t.entries())try{n()}catch(t){y7.error({docName:e,err:t},`[ServerObserverExtension] Cleanup failed for '${e}'`)}t.clear()}}}const x7=`state.json`;function S7(e){return e.lockDir,U(e.shadowRepoDir)?`adopt`:`fresh`}function C7(e){return H(e,x7)}function SIe(e,t){return e===t||e===0&&t===1}var w7=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function CIe(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 n=t.createdBy;return!(typeof n.runtimeVersion!=`string`||n.protocolVersion!==void 0&&typeof n.protocolVersion!=`number`)}function T7(e){let t=C7(e);if(!U(t))return{status:`absent`};let n;try{n=W(t,`utf-8`)}catch(e){throw new w7({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let r;try{r=JSON.parse(n)}catch(e){throw new w7({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!CIe(r))throw new w7({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:r}}function E7(e,t){let n=C7(e);ql(z(n),{recursive:!0}),au(n,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function D7(e){let t=R(`state-manifest`),n=e.currentStateSchemaVersion??1,r=e.currentRuntimeVersion??sc,i=e.currentProtocolVersion??2,a=(e.now??(()=>new Date))().toISOString(),o=C7(e.lockDir),s=T7(e.lockDir);if(s.status===`present`){let c=s.manifest;if(!SIe(c.stateSchemaVersion,n))throw new w7({kind:`incompatible`,path:o,message:`State manifest at ${o} declares stateSchemaVersion=${c.stateSchemaVersion} but this binary supports ${n}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${c.createdBy.runtimeVersion}, protocol ${c.createdBy.protocolVersion}.)`});try{let t={...c,lastWriteBy:{runtimeVersion:r,protocolVersion:i,at:a}};return E7(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),c}}if(S7({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let s={stateSchemaVersion:n,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i}};return E7(e.lockDir,s),t.info({path:o,stateSchemaVersion:n},`[state-manifest] fresh project — wrote manifest`),s}let c={stateSchemaVersion:0,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i,adoptedAt:a}};return E7(e.lockDir,c),t.warn({path:o,runtimeVersion:r},`[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.`),c}function wIe(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===`auth`&&t===`not-found-as-identity`?`auth-not-found-as-identity`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function TIe(e){return e.git?.toString()??e.message??``}function O7(e,t){return t.some(t=>t.test(e))}const EIe={"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`,"not-found-as-identity":`Repository not found — it may not exist, or the account used may not have access`,"unknown-auth":`Authentication failed`},DIe=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],k7=[/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],OIe=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],kIe=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],AIe=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],jIe=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],MIe=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],NIe=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],PIe=[/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],FIe=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/i],IIe=[/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],LIe=[/\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],RIe=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function A7(e){let t=zIe(e);return{...t,userFacingCode:wIe(t.class,t.subclass)}}function zIe(e){let t=e instanceof Error?e:Error(String(e)),n=TIe(t),r=`${t.message}\n${n}`.toLowerCase();if(O7(r,NIe))return{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n};if(O7(r,PIe))return{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n};if(O7(r,FIe))return{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n};let i=ei(t);return i.kind===`auth`?i.subclass===`403`&&O7(r,k7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:{class:`auth`,subclass:i.subclass,retryable:!1,message:EIe[i.subclass],rawStderr:n}:O7(r,k7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:O7(r,DIe)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:O7(r,OIe)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:O7(r,kIe)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:O7(r,AIe)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:O7(r,MIe)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:O7(r,jIe)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:O7(r,RIe)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:O7(r,LIe)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:O7(r,IIe)?/timed? out/i.test(r)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:n}:/refused/i.test(r)||/econnrefused/i.test(r)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:n}:/resolve.*host/i.test(r)||/enotfound/i.test(r)||/getaddrinfo/i.test(r)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:n}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:n}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:n}}function BIe(e,t={}){let n=t.ttlMs??6e4,r=t.fallbackTtlMs??5e3,i=t.now??Date.now,a=new Map,o=new Map;function s(e,t){return e.token==null?null:{token:e.token,host:t,...e.resolvedLogin?{login:e.resolvedLogin}:{}}}return{get(t,c){if(!e)return null;let l=`${t}\0${c??``}`,u=i(),d=a.get(l);if(d&&d.expiresAt>u)return s(d,t);let f=e(t,{login:c}),p=f.available&&f.token?f.token:null,m=f.available?f.resolvedLogin:void 0,h=!c||p!=null&&TB(m,c),g;if(h)o.delete(l),g=n;else{let e=o.get(l)??0;o.set(l,e+1),g=Math.min(r*2**e,n)}let _={token:p,resolvedLogin:m,expiresAt:u+g};return a.set(l,_),s(_,t)},invalidate(){a.clear(),o.clear()}}}const j7=R(`github-permissions`);function VIe(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function HIe(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function UIe(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let n=t.push;return typeof n==`boolean`?n:null}async function WIe(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return j7.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let n=UIe(t);return n===null?(j7.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):n?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403: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 j7.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function GIe(e,t,n,r,i){let a=n(e,{login:t?.login});if(a.available&&a.token){if(t?.login!==void 0&&a.fallback===!0){let n=N7(i,e);TB(n,t.login)||j7.warn({host:e,declaredLogin:t.login,declaredSource:t.source,resolvedLogin:n},`[permissions] declared GitHub account did not produce the gh token — probing as the active account`)}return{token:a.token,source:`gh`,resolvedLogin:a.resolvedLogin}}if(r)try{let t=await r.get(e);if(t?.token){let e=t.login===`unknown`?void 0:t.login;return{token:t.token,source:`token-store`,resolvedLogin:e}}}catch(t){j7.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}function KIe(e,t){let n=t.resolvedLogin??(t.tokenSource===`gh`?N7(t.detectGhAccounts,t.host):void 0);return{...e,...n===void 0?{}:{resolvedLogin:n},...M7(t.account,n)}}function M7(e,t){return e?.login===void 0||TB(e.login,t)?{}:{declaredLogin:e.login,declaredSource:e.source}}function N7(e,t){if(e)try{return e(t)?.find(e=>e.active)?.login}catch(e){j7.warn({err:e,host:t},`[permissions] detectGhAccounts failed — denial stays unnamed`);return}}async function qIe(e){let{owner:t,repo:n,host:r=`github.com`,transport:i=`https`,account:a,detectGh:o=()=>({available:!1}),detectGhAccounts:s,tokenStore:c,_fetchFn:l=fetch,_timeoutMs:u=5e3}=e,{token:d,source:f,resolvedLogin:p}=await GIe(r,a,o,c,s);if(f===`anonymous`)return i===`ssh`||i===`git`?(j7.info({host:r,transport:i},`[permissions] no credential resolved for ssh/git origin — abstaining (push auths with SSH keys, not tokens)`),{kind:`unknown`,error:`ssh-unverified`}):(j7.info({host:r},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`not-authenticated`,...M7(a,void 0)});let m=`${VIe(r)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}`;j7.info({host:r,tokenSource:f,tokenLen:d===void 0?0:d.length},`[permissions] probe starting`);let h=new AbortController,g=setTimeout(()=>h.abort(),u);try{let e=await l(m,{signal:h.signal,headers:HIe(d)}),t=await WIe(e,d!==void 0),n=t.kind===`denied`?KIe(t,{account:a,tokenSource:f,resolvedLogin:p,detectGhAccounts:s,host:r}):t;return j7.info({host:r,tokenSource:f,httpStatus:e.status,kind:n.kind,reason:n.kind===`denied`?n.reason:void 0,error:n.kind===`unknown`?n.error:void 0},`[permissions] probe classified`),n}catch(e){return h.signal.aborted?(j7.warn({host:r,timeoutMs:u},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(j7.warn({err:e,host:r},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(g)}}async function JIe(e){let t=performance.now(),n=await qIe(e);return QIe(n,performance.now()-t),n}function YIe(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let P7=null;function XIe(){return P7||=Rs().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,not-authenticated,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,ssh-unverified,none}.`}),P7}let F7=null;function ZIe(){return F7||=Rs().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),F7}function QIe(e,t){let n=YIe(e);XIe().add(1,n),ZIe().record(t,{outcome:n.outcome})}const $Ie=[`.mcp.json`,`.cursor/mcp.json`,`.codex/config.toml`,`opencode.json`],I7={".mcp.json":{format:`json`,topLevelKey:`mcpServers`,managedKeys:[`command`,`args`]},".cursor/mcp.json":{format:`json`,topLevelKey:`mcpServers`,managedKeys:[`command`,`args`]},".codex/config.toml":{format:`toml`,topLevelKey:`mcp_servers`,managedKeys:[`command`,`args`]},"opencode.json":{format:`json`,topLevelKey:`mcp`,managedKeys:[`type`,`command`]}};function L7(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function R7(e){return Object.hasOwn(I7,e)?I7[e]:null}function z7(e){return e.charCodeAt(0)===65279?{bom:``,body:e.slice(1)}:{bom:``,body:e}}function eLe(e){let t=e.match(/\n([ \t]+)["}]/)?.[1]??` `;return{insertSpaces:!t.includes(` `),tabSize:t.includes(` `)?1:Math.max(1,t.length),eol:e.includes(`\r
|
|
2034
2034
|
`)?`\r
|
|
2035
2035
|
`:`
|
|
@@ -2038,8 +2038,8 @@ native-divergence-injected
|
|
|
2038
2038
|
`);return o=a?`${o.replace(/\n+$/,``)}\n`:o.replace(/\n+$/,``),i&&(o=o.replace(/\n/g,`\r
|
|
2039
2039
|
`)),`${n}${o}`}function nLe(e,t){let{bom:n,body:r}=z7(e),i=[],a=Kj(r,i,{allowTrailingComma:!0,disallowComments:!1});if(!a||i.length>0||a.type!==`object`)return{kind:`declined`,reason:`unparseable`};if(tLe(a,t.topLevelKey)>1)return{kind:`declined`,reason:`duplicate-container`};let o=[t.topLevelKey,`open-knowledge`],s=qj(a,o);if(!s)return{kind:`no-entry`,raw:e,shell:e};let c=Jj(s);if(!L7(c))return{kind:`declined`,reason:`foreign-entry`};let l=Ve(c);if(l.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let u=r,d=t.managedKeys.map(e=>({key:e,node:qj(a,[...o,e])})).filter(e=>e.node!==void 0).sort((e,t)=>t.node.offset-e.node.offset);for(let{key:e,node:n}of d){let r=JSON.stringify(V7(t,e));u=`${u.slice(0,n.offset)}${r}${u.slice(n.offset+n.length)}`}return{kind:`managed`,raw:e,shell:`${n}${u}`,entry:c,descriptor:l.descriptor}}function V7(e,t){return e.topLevelKey===`mcp`&&t===`type`?`__ok_managed_type__`:t===`command`&&e.topLevelKey===`mcp`?[`__ok_managed_command__`]:t===`command`?`__ok_managed_command__`:[`__ok_managed_args__`]}function rLe(e,t,n){if(!n)return{kind:`declined`,reason:`no-native-writer`};let{bom:r,body:i}=z7(e),a;try{a=n.parseToObject(i)}catch{return{kind:`declined`,reason:`unparseable`}}let o=a[t.topLevelKey],s=L7(o)?o[`open-knowledge`]:void 0;if(s===void 0)return{kind:`no-entry`,raw:e,shell:e};if(!L7(s))return{kind:`declined`,reason:`foreign-entry`};let c=Ve(s);if(c.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let l;try{l=n.upsertEntry(i,`open-knowledge`,Object.fromEntries(t.managedKeys.map(e=>[e,V7(t,e)])))}catch{return{kind:`declined`,reason:`unparseable`}}let u=B7(e,l.text);return{kind:`managed`,raw:`${r}${i}`,shell:u,entry:s,descriptor:c.descriptor}}function H7(e,t,n){return e===null?{kind:`absent`}:Buffer.byteLength(e,`utf8`)>10485760?{kind:`declined`,reason:`oversize`}:t.format===`json`?nLe(e,t):rLe(e,t,n)}function iLe(e,t,n){let{bom:r,body:i}=z7(e),a=i;for(let e of t.managedKeys){let r=Kj(a,[],{allowTrailingComma:!0,disallowComments:!1}),o=r?qj(r,[t.topLevelKey,`open-knowledge`,e]):void 0;o&&JSON.stringify(Jj(o))===JSON.stringify(n[e])||(a=Xj(a,Yj(a,[t.topLevelKey,`open-knowledge`,e],n[e],{formattingOptions:eLe(i)})))}return`${r}${a}`}function U7(e,t,n,r){if(t.format===`json`)return iLe(e,t,n);if(!r)return null;let{body:i}=z7(e),a=Object.fromEntries(t.managedKeys.map(e=>[e,n[e]]));try{return B7(e,r.upsertEntry(i,`open-knowledge`,a).text)}catch{return null}}function aLe(e){let t=R7(e.target);return t?U7(e.raw,t,e.entry,e.tomlEditor):null}function W7(e){let t=R7(e.target);if(!t)return null;let n=H7(e.raw,t,e.tomlEditor);return n.kind===`managed`||n.kind===`no-entry`?n.shell:null}function oLe(e,t,n){return t.shell===n.shell?t.shell:t.shell===e.shell?n.shell:n.shell===e.shell?t.shell:null}function G7(e){let t=R7(e.target);if(!t)return{kind:`declined`,reason:`unsupported-target`};let n={base:H7(e.layers.base,t,e.tomlEditor),head:H7(e.layers.head,t,e.tomlEditor),index:H7(e.layers.index,t,e.tomlEditor),worktree:H7(e.layers.worktree,t,e.tomlEditor),incoming:H7(e.layers.incoming,t,e.tomlEditor)},r=Object.values(n),i=r.find(e=>e.kind===`declined`);if(i?.kind===`declined`)return i;if(r.some(e=>e.kind===`absent`))return r.every(e=>e.kind===`absent`)?{kind:`unchanged`}:{kind:`declined`,reason:`file-deletion-ambiguity`};if(r.some(e=>e.kind===`no-entry`))return r.every(e=>e.kind===`no-entry`)?{kind:`declined`,reason:`no-entry`}:{kind:`declined`,reason:`entry-deletion-ambiguity`};let a=n;if(a.index.shell!==a.worktree.shell)return{kind:`declined`,reason:`index-worktree-divergence`};let o=oLe(a.base,a.worktree,a.incoming);if(o===null)return{kind:`declined`,reason:`unowned-shell-conflict`};let s=Object.values(a).map(e=>({entry:e.entry,descriptor:e.descriptor}));if(e.runningEntry){let t=Ve(e.runningEntry);t.kind===`recognized`&&s.push({entry:e.runningEntry,descriptor:t.descriptor})}if(new Set(s.map(e=>e.descriptor.family)).size!==1)return{kind:`declined`,reason:`mixed-launcher-family`};let c=s.reduce((e,t)=>t.descriptor.revision>e.descriptor.revision?t:e),l=[a.worktree,a.index,a.head,a.incoming,a.base].find(e=>e.shell===o);if(!l)return{kind:`declined`,reason:`unowned-shell-conflict`};let u=U7(l.raw,t,c.entry,e.tomlEditor);return u===null?{kind:`declined`,reason:e.tomlEditor?`unparseable`:`no-native-writer`}:{kind:`resolved`,raw:u,winner:c.descriptor,winnerEntry:c.entry}}const sLe=R(`github-account`),cLe=(e,t)=>{let n=Ol(`git`,[`config`,`--get-urlmatch`,`credential`,e],XC({cwd:t,encoding:`utf-8`,timeout:5e3}));return n.error||n.status===null||n.status!==0&&n.status!==1?(sLe.warn({status:n.status,signal:n.signal,err:n.error,stderr:typeof n.stderr==`string`?NK(n.stderr).slice(0,200):void 0},`[github-account] git config --get-urlmatch failed — treating the URL as declaring no account`),null):n.status!==0||!n.stdout?null:n.stdout};function lLe(e){return e.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/]*@/i,`$1`)}function uLe(e){let t;for(let n of e.split(`
|
|
2040
2040
|
`)){let e=n.startsWith(`credential.username `)?n.slice(20).trim():void 0;e&&(t=e)}return t}function K7(e,t={}){let n=AB(e);if(!n)return{source:`active`};let r=n.host;if(n.login)return{host:r,login:n.login,source:`remote-url`};if(n.transport!==`https`)return{host:r,source:`active`};let i=(t._readCredentialUrlMatch??cLe)(lLe(e),t.cwd??process.cwd()),a=i?DB(uLe(i)):void 0;return a?{host:r,login:a,source:`credential-config`}:{host:r,source:`active`}}function dLe(e={}){let t=e.ttlMs??6e4,n=e.now??Date.now,r;return{resolve(i){let a=jB(i);if(!a)return{source:`active`};let o=n();if(r&&r.projectDir===i&&r.url===a&&r.expiresAt>o)return r.account;let s=K7(a,{cwd:i,_readCredentialUrlMatch:e._readCredentialUrlMatch});return r={projectDir:i,url:a,account:s,expiresAt:o+t},s},invalidate(){r=void 0}}}function q7(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}function fLe(e,t){return t===`anonymous`?Math.max(180,e):e}const $=R(`sync-engine`),J7=new Set($Ie),Y7=/^[0-9a-f]{40}$/i,pLe=Du(El);var X7=class extends Error{constructor(e,t){super(`Shareable .ok subtree "${e}" could not be fully enumerated; sync staging aborted`,{cause:t}),this.name=`ShareableOkEnumerationError`}};function mLe(e){let{exitCode:t,stderr:n}=e,r=n??``;return t===128||/^fatal:/m.test(r)&&/not possible to fast-forward/i.test(r)?`divergence`:/^error:/m.test(r)&&/would be overwritten by merge/i.test(r)?`overlay-overlap`:`unknown`}function hLe(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason,...e.resolvedLogin===void 0?{}:{resolvedLogin:e.resolvedLogin},...e.declaredLogin===void 0?{}:{declaredLogin:e.declaredLogin},...e.declaredSource===void 0?{}:{declaredSource:e.declaredSource}}:{checkStatus:`unknown`,unknownError:e.error}}function Z7(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason&&e.resolvedLogin===t.resolvedLogin&&e.declaredLogin===t.declaredLogin&&e.declaredSource===t.declaredSource:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}const Q7={syncScope:{pathBase:`content`}},$7={syncScope:{pathBase:`project`}},e9=new Set([`diverged-local-commits`,`external-changes-pending`]);function t9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function n9(e){let t=Iu(e);if(t.kind!==`repository`)return!1;let n=t.repository.readHead();return n.kind===`branch`?t.repository.readRef(n.ref).kind===`absent`:!1}function gLe(e){return e.class===`network`&&e.subclass!==`429`&&e.subclass!==`5xx`}function r9(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}const i9=12e4;var _Le=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;rootOkOutsideContentWalk;pullIntervalSeconds;pushIntervalSeconds;mode;credentialConfig;cc1Broadcaster;onStateChange;onContentConflictsDetected;onContentConflictsResolved;setBatchInProgress;onAutoDisable;checkpointBeforeStrandedConversion;checkpointBeforeOverlayRestore;mcpTomlEditor;detectGh;detectGhAccounts;ghTokenSource;ghAccountResolver;declaredAccountWarnKey;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;authTier=`unknown`;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;get lastRunUtc(){return this.lastPullOkUtc===null?this.lastPushOkUtc:this.lastPushOkUtc===null||this.lastPullOkUtc>this.lastPushOkUtc?this.lastPullOkUtc:this.lastPushOkUtc}lastPullOkUtc=null;lastPushOkUtc=null;pushCycleLanded=!1;fetchOnlyInFlight=!1;lastFetchUtc=null;lastPushedSha=null;lastPullUtc=null;lastPullOutcome=null;consecutivePullFailures=0;consecutivePushFailures=0;pushStreakIsConnectivity=!1;consecutiveContentions=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;blockingPaths=[];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.rootOkOutsideContentWalk=jO(V(this.contentDir,B(this.projectDir,`.ok`))).startsWith(`..`),this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.mode=e.mode??(e.syncEnabled===!0?`full`:`off`),this.credentialConfig=e.credentialConfig??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.onContentConflictsResolved=e.onContentConflictsResolved,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.checkpointBeforeStrandedConversion=e.checkpointBeforeStrandedConversion,this.checkpointBeforeOverlayRestore=e.checkpointBeforeOverlayRestore,this.mcpTomlEditor=e.mcpTomlEditor,this.detectGh=e.detectGh,this.detectGhAccounts=e.detectGhAccounts,this.ghTokenSource=BIe(e.detectGh),this.ghAccountResolver=dLe({_readCredentialUrlMatch:e._readCredentialUrlMatch}),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??JIe,this.statePath=H(dP(this.projectDir),`sync-state.json`),this.conflictStore=new dZ(this.projectDir,this.currentBranch)}syncGhTarget(){let e=this.ghAccountResolver.resolve(this.projectDir);return{account:e,host:e.host??`github.com`}}resolveRelayGhToken(){let{account:e,host:t}=this.syncGhTarget(),n=this.ghTokenSource.get(t,e.login);return this.noteDeclaredAccountOutcome(e,t,n),n}noteDeclaredAccountOutcome(e,t,n){let r=e.login,i=n===null?void 0:n.login??this.activeGhLogin(t);if(!(r!==void 0&&(n===null||!TB(i,r)))){this.declaredAccountWarnKey=void 0;return}let a=`${t}\0${r}\0${e.source}\0${n===null?`none`:`fallback`}`;a!==this.declaredAccountWarnKey&&(n===null?$.warn({host:t,declaredLogin:r,declaredSource:e.source},`[sync] declared GitHub account produced no gh token — git runs with no relayed credential`):$.warn({host:t,declaredLogin:r,declaredSource:e.source,resolvedLogin:i},`[sync] declared GitHub account did not produce the gh token — using the active account`)),this.declaredAccountWarnKey=a}parkedOnAmbiguousNotFound(){return(this.state===`auth-error`||this.pausedReason===`auth-error`)&&(this.pushErrorCode===`auth-not-found-as-identity`||this.pullErrorCode===`auth-not-found-as-identity`)}activeGhLogin(e){if(this.detectGhAccounts)try{return this.detectGhAccounts(e)?.find(e=>e.active)?.login}catch(t){$.warn({err:t,host:e},`[sync] detectGhAccounts failed — fallback identity stays unnamed`);return}}gitHandle(e){return Qs(this.projectDir,{credentialConfig:this.credentialConfig,gitIndexFile:e,ghToken:this.resolveRelayGhToken()??void 0,timeoutMs:12e4})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){$.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),$.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){$.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=Ku(this.projectDir),n=t?B(t,`MERGE_HEAD`):null,r=n!==null&&U(n);this.conflictCount=this.conflictStore.count();let i=()=>this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(i().length>0&&!r){$.warn({count:i().length},`[sync] persisted merge conflicts but no MERGE_HEAD — clearing stale state`);for(let e of i())this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count()}else if(i().length>0&&r)try{let e=this.gitHandle(),t=new Set(await vb(e.git,[`diff`,`--name-only`,`--diff-filter=U`])),n=this.conflictCount;for(let e of i())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<n&&$.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){$.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(r&&i().length===0){$.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(i().length>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),$.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let a=this.conflictStore.list().filter(e=>e.variant===`working-tree`);a.length>0&&await this.notifyContentConflictsDetected(a.map(e=>e.file)),this.mode===`follow`&&await this.refreshAuthTier();let o=q7(this.lastFetchUtc,this.currentPullIntervalSeconds()),s=q7(this.lastPushOkUtc,this.pushIntervalSeconds);this.schedulePull(o>0?o:void 0),this.schedulePush(s>0?s:void 0),$.info({branch:this.currentBranch,pullDelayMs:o,pushDelayMs:s},`[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()}setIntervals(e,t){let n=this.pullIntervalSeconds!==e,r=this.pushIntervalSeconds!==t;!n&&!r||($.info({pullFrom:this.pullIntervalSeconds,pullTo:e,pushFrom:this.pushIntervalSeconds,pushTo:t},`[sync] cycle intervals changed`),this.pullIntervalSeconds=e,this.pushIntervalSeconds=t,n&&this.pullTimer!==null&&this.schedulePull(),r&&this.pushTimer!==null&&this.schedulePush())}async setMode(e,t=`config`){if(this.mode===e)return;let n=this.mode;if(this.mode=e,$.info({from:n,to:e,source:t},`[sync] mode changed`),e===`off`){this.cancelScheduledCycles(),await this.drainInFlightCycles(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}e===`follow`&&(await this.drainInFlightCycles(),this.cancelScheduledCycles(),await this.convertStrandedCommitsToOverlay()),this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(0),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}async setEnabled(e){await this.setMode(e?`full`:`off`)}cancelScheduledCycles(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null)}async drainInFlightCycles(){let e=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-e>3e4){$.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await Ou(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||n9(this.projectDir)?0:this.unpushedCommitCount(this.gitHandle())}async unpushedCommitCount(e){try{let t=await e.git.status();if(t.tracking)return t.ahead}catch{}try{let t=(await e.git.raw([`rev-list`,`--count`,`origin/${this.currentBranch}..HEAD`])).trim(),n=Number.parseInt(t,10);return Number.isFinite(n)?n:0}catch{return 0}}async convertStrandedCommitsToOverlay(){if(!this.hasRemote||n9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){$.warn({err:e},`[sync] pull-only: could not probe stranded commits — skipping conversion`);return}if(t!==0){try{await this.checkpointBeforeStrandedConversion?.({branch:this.currentBranch,ahead:t})}catch(e){$.warn({err:e},`[sync] pull-only: stranded-commit checkpoint failed — proceeding`)}try{let n=(await e.git.raw([`merge-base`,`HEAD`,`origin/${this.currentBranch}`])).trim();this.setBatchInProgress?.(!0);try{await Xs(()=>e.git.raw([`reset`,`--mixed`,n]))}finally{this.setBatchInProgress?.(!1)}let r=await e.git.status();this.ahead=r.ahead,this.behind=r.behind,this.pausedReason=void 0,$.info({ahead:t,behind:this.behind},`[sync] pull-only: folded stranded local commits into a working-tree overlay`)}catch(e){this.pausedReason=`diverged-local-commits`,$.warn({err:e},`[sync] pull-only: stranded-commit conversion failed — leaving branch as-is`)}}}async notifyCredentialsChanged(){if(this.mode!==`off`&&(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),!(this.state!==`auth-error`&&this.pausedReason!==`auth-error`))){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(0),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){if(e===`fetch`){await this.fetchOnly();return}if(this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.consecutiveContentions=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.parkedOnAmbiguousNotFound()&&(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()),this.probePushPermissionInternal(`refresh`),e===`pull`){await this.pullOnce();return}if(e===`push`){await this.pushOnce();return}this.state===`dormant`||this.state===`conflict`||this.state===`auth-error`?$.warn({op:e,state:this.state,mode:this.mode,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):$.info({op:e,state:this.state},`[sync] trigger(${e}) running`),await this.pushOnce(),await this.pullOnce(`sync`)}async pushOnce(){if(this.mode===`full`){await this.runPushCycle();return}await this.runOneShotPush()}async runOneShotPush(){if(this.pushInFlight||this.pullInFlight){$.info({pushInFlight:this.pushInFlight,pullInFlight:this.pullInFlight},`[sync] one-shot push refused — a cycle is already in flight`);return}if(this.state===`conflict`||this.state===`auth-error`){$.info({state:this.state},`[sync] one-shot push refused — state=${this.state}`);return}if(this.conflictCount>0){$.info({conflictCount:this.conflictCount},`[sync] one-shot push refused — unresolved conflicts hold the tree`);return}if(!this.hasRemote||n9(this.projectDir)){$.info({hasRemote:this.hasRemote},`[sync] one-shot push refused — no remote, or no commits yet`);return}let e=this.state;this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.pushCycleLanded&&this.markRun();let t=this.currentState();t!==`conflict`&&t!==`auth-error`&&this.transitionTo(e),this.cc1Broadcaster?.signal(`sync-status`)}}async fetchOnly(){if(!this.hasRemote||n9(this.projectDir)||this.pullInFlight||this.pushInFlight||this.fetchOnlyInFlight)return!1;this.fetchOnlyInFlight=!0;let e=this.gitHandle();try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.scheduleSaveState()}catch(e){return $.debug({err:e},`[sync] panel-open fetch failed — counts left as they were`),!1}finally{this.fetchOnlyInFlight=!1}return await this.refreshDivergenceCounts(e),this.cc1Broadcaster?.signal(`sync-status`),!0}async refreshDivergenceCounts(e){try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch(e){$.debug({err:e},`[sync] divergence-count refresh failed — keeping previous counts`)}}async pullOnce(e=`explicit`){let t=this.mode,n=await this.runOneShotPull(e);return $.info({mode:t,outcome:n},`[sync] one-shot pull complete`),n}async runOneShotPull(e){if(this.pullInFlight||this.pushInFlight)return $.info({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] one-shot pull refused — a cycle is already in flight`),this.recordPullOutcome(`refused`);if(this.state===`conflict`)return $.info({state:this.state},`[sync] one-shot pull refused — the conflict resolver holds the tree`),this.recordPullOutcome(`refused`);if(!this.hasRemote||n9(this.projectDir))return $.info({hasRemote:this.hasRemote},`[sync] one-shot pull refused — no remote, or no commits yet`),this.recordPullOutcome(`refused`);let t=this.mode,n=this.state,r=this.pausedReason;this.pullInFlight=!0;try{return this.recordPullOutcome(await this.doPullCycle(e))}finally{this.pullInFlight=!1,t===`off`?(e9.has(this.pausedReason)||e9.has(r)||(this.pausedReason=r),this.transitionTo(n)):this.schedulePull()}}recordPullOutcome(e){return this.lastPullUtc=new Date().toISOString(),this.lastPullOutcome=e,(e===`succeeded`||e===`up-to-date`||e===`conflict`)&&(this.lastPullOkUtc=new Date().toISOString()),this.cc1Broadcaster?.signal(`sync-status`),e}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastRunUtc:this.lastRunUtc,lastPullOkUtc:this.lastPullOkUtc,lastPushOkUtc:this.lastPushOkUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,lastPullUtc:this.lastPullUtc,lastPullOutcome:this.lastPullOutcome,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutivePullFailures,consecutivePushFailures:this.consecutivePushFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.mode!==`off`,syncMode:this.mode,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?IB(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.blockingPathsForStatus().length>0?{blockingPaths:this.blockingPathsForStatus()}:{},...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}blockingPathsForStatus(){return this.pausedReason===`external-changes-pending`?this.blockingPaths.slice(0,50):[]}getBlockingPaths(){return this.pausedReason===`external-changes-pending`?[...this.blockingPaths]:[]}async commitBlockingPaths(){let e=this.getBlockingPaths();if(e.length===0)return null;let t=this.gitHandle();return Xs(async()=>{await this.applyCommitIdentity(t);try{if(await t.git.raw([`add`,`--`,...e]),(await vb(t.git,[`diff`,`--cached`,`--name-only`,`--`,...e])).length===0)return null;await t.git.raw([`commit`,`-m`,`Commit local changes before syncing`,`--`,...e])}catch(n){throw await t.git.raw([`reset`,`--`,...e]).catch(()=>{}),$.error({err:n,files:e.length},`[sync] commit of blocking paths failed`),n}let n=(await t.git.revparse(`HEAD`)).trim();return this.clearBlockingPause(),$.info({files:e.length},`[sync] committed overlapping paths at user request`),n})}clearBlockingPause(){this.blockingPaths=[],this.pausedReason=void 0,this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await PG(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async applyCommitIdentity(e){let t=await PG(this.projectDir),n=t===null;this.identityUnresolved!==n&&(this.identityUnresolved=n,this.cc1Broadcaster?.signal(`sync-status`));let r=t?.name??`OpenKnowledge`,i=t?.email??`sync@open-knowledge.local`;rc(e,{GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i})}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=NB(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,Z7(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,$.info({caller:e,host:t.host,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let{account:n}=this.syncGhTarget(),r;try{r=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,transport:t.transport,account:n,detectGh:this.detectGh,detectGhAccounts:this.detectGhAccounts,tokenStore:this.tokenStore})}catch(t){$.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),r={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let i=hLe(r),a=this.pushPermission;this.pushPermission=i;let o=!1;return i.checkStatus===`denied`&&this.mode===`full`&&this.parkedOnAmbiguousNotFound()&&$.info({reason:i.deniedReason,caller:e},`[sync] probe denial not applied — repository-not-found park is the more specific diagnosis`),i.checkStatus===`denied`&&this.mode===`full`&&!this.parkedOnAmbiguousNotFound()?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),o=!0,$.info({reason:i.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):i.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),o=!0,$.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!o&&!Z7(a,i)&&this.cc1Broadcaster?.signal(`sync-status`),i}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,$.info({mode:this.mode},`[sync] remote detected post-boot — re-evaluating state`),this.mode===`off`?this.transitionTo(`disabled`):(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()))}async probeRemote(){if(!U(B(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return $.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){let e=this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(e.length===0)return;let t=this.conflictCount,n=Ku(this.projectDir),r=n?B(n,`MERGE_HEAD`):null;if(r!==null&&U(r))try{let n=this.gitHandle(),r=new Set(await vb(n.git,[`diff`,`--name-only`,`--diff-filter=U`]));for(let t of e)r.has(t.file)||this.conflictStore.removeConflict(t.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<t&&$.info({cleared:t-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){$.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}else{$.info({cleared:e.length},`[sync] external resolve detected (no MERGE_HEAD) — clearing merge-native conflicts`);for(let t of e)this.conflictStore.removeConflict(t.file);this.conflictCount=this.conflictStore.count()}this.conflictCount!==t&&(this.conflictCount===0?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush(0)):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,n){let r=this.conflictStore.list().find(t=>t.file===e)?.variant===`working-tree`;this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,n)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}r&&$.info({choice:t},`[sync] pull-only: conflict resolved by choice`),await this.notifyContentConflictsResolved([e]),this.conflictCount=this.conflictStore.count(),this.conflictCount===0?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush(0)):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(0)))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{$.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){if(this.mode!==`full`)return;this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??this.effectivePushDelayMs();this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{$.error({err:e},`[sync] push cycle uncaught error`)})},t)}async resolveAuthTier(){if(this.resolveRelayGhToken()!==null)return`authenticated`;if(this.tokenStore)try{if((await this.tokenStore.get(this.syncGhTarget().host))?.token)return`authenticated`}catch(e){$.warn({err:e},`[sync] auth-tier token-store lookup threw — treating as anonymous`)}return`anonymous`}async refreshAuthTier(){this.authTier=await this.resolveAuthTier()}currentPullIntervalSeconds(){return this.mode===`follow`?fLe(this.pullIntervalSeconds,this.authTier===`anonymous`?`anonymous`:`authenticated`):this.pullIntervalSeconds}effectivePullDelayMs(){let e=r9(this.consecutivePullFailures),t=e>0?e/1e3:0;return t9(Math.max(t,this.currentPullIntervalSeconds()))}effectivePushDelayMs(){let e=r9(this.consecutivePushFailures),t=e>0?e/1e3:0;return t9(Math.max(t,this.pushIntervalSeconds))}logContention(){let e={consecutiveContentions:this.consecutiveContentions,consecutivePushFailures:this.consecutivePushFailures,releasedConnectivityStreak:this.pushStreakIsConnectivity};this.consecutiveContentions>=3?$.warn(e,`[sync] push repeatedly losing to remote contention — not backing off by design`):$.info(e,`[sync] push still rejected after retry (contention) — scheduling next push at base cadence`)}bumpFailureCount(e,t=!1){e===`push`?(this.consecutiveContentions=0,this.consecutivePushFailures++,this.pushStreakIsConnectivity=(this.consecutivePushFailures===1||this.pushStreakIsConnectivity)&&t):this.consecutivePullFailures++}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`||this.state===`auth-error`)){if(this.state===`conflict`){this.schedulePull();return}if(n9(this.projectDir)){this.schedulePull();return}this.mode===`follow`&&await this.refreshAuthTier(),this.pullInFlight=!0;try{this.recordPullOutcome(await this.doPullCycle(this.mode===`full`?`sync`:`explicit`))}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(e){let t=this.gitHandle(),n;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!e||e===`HEAD`)return this.transitionTo(`disabled`),this.pausedReason=`detached-head`,$.warn({},`[sync] detached HEAD — pausing sync`),`refused`;n=e,this.currentBranch=n}catch(e){return this.handleError(A7(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.transitionTo(`fetching`);try{await t.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutivePullFailures=0,this.clearPullError(),this.consecutivePushFailures>0&&this.pushStreakIsConnectivity&&($.info({cleared:this.consecutivePushFailures},`[sync] fetch succeeded — releasing connectivity-class push backoff`),this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.schedulePush())}catch(e){let t=A7(e instanceof Error?e:Error(String(e)));return this.handleError(t,`pull`),`error`}if(await this.refreshDivergenceCounts(t),this.behind>0&&e===`explicit`){let e=await this.doPullCycleB1(t,n);return this.scheduleSaveState(),e}if(this.behind>0&&this.conflictCount===0){this.pausedReason===`diverged-local-commits`&&(this.pausedReason=void 0),this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(t);let e=await this.prepareForMerge(t,n);if(!e.proceed)return`refused`;let r=!0,i=!0;try{await this.applyCommitIdentity(t),await t.git.merge([`origin/${n}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.pausedReason===`external-changes-pending`&&this.clearBlockingPause(),this.transitionTo(`idle`)}finally{e.needsStashPop&&(r=await this.popPreMergeStash(t)),i=this.restoreReconciledMcpOverlays(e.reconciled)}if(!r)throw Error(`failed to replay pre-merge working-tree state`);if(!i)throw Error(`failed to restore reconciled MCP overlays`);return await this.persistReconciledMcpEntries(e.reconciled),this.scheduleSaveState(),`succeeded`}catch(e){let t=A7(e instanceof Error?e:Error(String(e)));return t.class===`semantic`&&t.subclass===`merge-conflict`?(await this.handleMergeConflict(),this.state===`conflict`?`conflict`:this.pullError?`error`:`succeeded`):(this.handleError(t,`pull`),`error`)}finally{this.setBatchInProgress?.(!1)}}return this.transitionTo(`idle`),this.scheduleSaveState(),this.behind===0?`up-to-date`:`conflict`}async doPullCycleB1(e,t){if(this.transitionTo(`pulling`),this.ahead>0)return this.clearPullError(),this.pausedReason=`diverged-local-commits`,this.transitionTo(`idle`),$.warn({ahead:this.ahead,behind:this.behind},`[sync] pull-only: local history diverged — not fast-forwardable, skipping cycle`),`refused`;let n,r;try{n=(await e.git.revparse([`HEAD`])).trim();let i=await vb(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await vb(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]));r=i.filter(e=>a.has(e))}catch(e){return this.handleError(A7(e instanceof Error?e:Error(String(e))),`pull`),`error`}let i=new Map;for(let e of this.conflictStore.list())e.variant===`working-tree`&&i.set(e.file,e);let a;try{a=await this.planOverlapReconciliation(e,t,n,r,i)}catch(e){return this.handleError(A7(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.setBatchInProgress?.(!0);try{if(r.length>0){try{await this.checkpointBeforeOverlayRestore?.({branch:t,paths:r.length})}catch(e){$.warn({err:e,paths:r.length},`[sync] pull-only: overlay checkpoint failed before restore — proceeding`)}try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,`--`,...r])}catch(e){return $.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError(A7(e instanceof Error?e:Error(String(e))),`pull`),`error`}}let n=await this.fastForwardOnly(e,t);if(!n.ok){try{this.applyOverlayPlan(a.mineRestore,a.deletions)}catch(e){return $.error({err:e,refusal:n.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError(A7(e instanceof Error?e:Error(String(e))),`pull`),`error`}return n.timedOut?($.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(A7(Error(`git merge --ff-only timed out after ${i9}ms`)),`pull`),`error`):(n.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),$.warn({refusal:n.refusal,stderr:n.stderr.slice(0,200)},`[sync] pull-only: fast-forward refused — skipping cycle`),`refused`)}try{this.applyOverlayPlan(a.writes,a.deletions)}catch(e){return $.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError(A7(e instanceof Error?e:Error(String(e))),`pull`),`error`}let i=!0;for(let e of a.upserts)i=this.conflictStore.addConflict(e)&&i;for(let e of a.dissolved)i=this.conflictStore.removeConflict(e)&&i;if(this.conflictCount=this.conflictStore.count(),!i)return $.error({},`[sync] pull-only: failed to persist conflict state after fast-forward — surfacing as error`),this.handleError(A7(Error(`failed to persist conflict state after fast-forward`)),`pull`),`error`;this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.clearPullError(),this.pausedReason=void 0,this.blockingPaths=[],this.transitionTo(`idle`),a.newConflicts.length>0&&await this.notifyContentConflictsDetected(a.newConflicts),a.dissolved.length>0&&await this.notifyContentConflictsResolved(a.dissolved),(a.newConflicts.length>0||a.dissolved.length>0)&&this.cc1Broadcaster?.signal(`sync-status`);let o=await this.countStandingOverlay(e);return $.info({created:a.newConflicts.length,autoCombined:a.autoCombined.length,autoDissolved:a.dissolved.length,autoRestored:a.autoRestored.length,overlayStock:o},`[sync] pull-only: fast-forwarded to origin tip`),a.newConflicts.length>0?`conflict`:`succeeded`}finally{this.setBatchInProgress?.(!1)}}async fastForwardOnly(e,t){try{return await pLe(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,`origin/${t}`],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:i9}),{ok:!0}}catch(e){let t=e,n=t.killed===!0||t.signal===`SIGTERM`,r=typeof t.code==`number`?t.code:null,i=typeof t.stderr==`string`?t.stderr:e instanceof Error?e.message:String(e);return{ok:!1,refusal:mLe({exitCode:r,stderr:i}),stderr:i,exitCode:r,timedOut:n}}}async planOverlapReconciliation(e,t,n,r,i){let a=[],o=[],s=[],c=[],l=[],u=[],d=[],f=[];for(let p of r){let r=i.get(p),m=r!==void 0;if(!U(B(this.projectDir,p))){try{await e.git.revparse([`origin/${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),$.warn({err:e,path:p},`[sync] pull-only: unexpected error probing origin for a deleted overlay — deferring reconcile`);continue}s.push(p),m&&l.push(p);continue}if(!this.isContentConflictPath(p)){s.push(p);continue}f.push(p),m&&l.push(p);continue}let h;try{h=W(B(this.projectDir,p))}catch{continue}o.push({path:p,bytes:h});let g=h.toString(`utf-8`),_=null;try{_=await e.git.raw([`show`,`origin/${t}:${p}`])}catch(e){this.classifyRefReadFailure(e)===`error`&&$.warn({err:e,path:p},`[sync] pull-only: unexpected error reading origin blob — keeping overlay, deferring reconcile`),_=null}if(_!==null&&_===g){m&&l.push(p);continue}if(_!==null&&J7.has(p)){let t=await this.readMcpGitBlob(e,n,p),r=G7({target:p,layers:{base:t,head:t,index:await this.readMcpGitBlob(e,``,p),worktree:g,incoming:_},tomlEditor:this.mcpTomlEditor});if(r.kind===`resolved`){r.raw!==_&&a.push({path:p,bytes:Buffer.from(r.raw,`utf8`)}),$.info({event:`mcp-config-reconcile`,target:p,outcome:`auto-resolved`},`[sync] pull-only: auto-resolved OpenKnowledge MCP entry overlap`);continue}r.kind===`declined`&&$.warn({event:`mcp-config-reconcile`,target:p,outcome:`declined`,reason:r.reason},`[sync] pull-only: declined OpenKnowledge MCP entry reconciliation`)}if(_===null||!this.isContentConflictPath(p)){a.push({path:p,bytes:h});continue}let v=m?r.baseSha:await this.gitBlobSha(e,`${n}:${p}`),y=br(v?await this.gitBlobContent(e,v):``,g,_);if(y.clean){a.push({path:p,bytes:Buffer.from(y.merged,`utf-8`)}),d.push(p),m&&l.push(p);continue}a.push({path:p,bytes:h});let b=await this.gitBlobSha(e,`origin/${t}:${p}`);if(b===void 0){$.warn({path:p},`[sync] pull-only: could not pin origin blob for a collision — keeping overlay, deferring`);continue}c.push({file:p,detectedAt:r?.detectedAt??new Date().toISOString(),variant:`working-tree`,theirsSha:b,baseSha:v}),m||u.push(p)}return{writes:a,mineRestore:o,deletions:s,upserts:c,dissolved:l,newConflicts:u,autoCombined:d,autoRestored:f}}applyOverlayPlan(e,t){let n={allowShareableOkArtifact:aj};for(let{path:t,bytes:r}of e){let e=B(this.projectDir,t);Iq(e,this.projectDir,n),Fs(e,r)}for(let e of t){let t=B(this.projectDir,e);Iq(t,this.projectDir,n);try{xs(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=B(this.projectDir,e),n=jO(V(this.contentDir,t));return!n.startsWith(`..`)&&gx(n)&&!this.contentFilter.isExcluded(n)}async gitBlobSha(e,t){try{return(await e.git.revparse([t])).trim()}catch{return}}classifyRefReadFailure(e){let t=e instanceof Error?e.message:String(e);return/does not exist in|exists on disk, but not in/i.test(t)?`absent`:`error`}async gitBlobContent(e,t){return e.git.raw([`cat-file`,`blob`,t])}async countStandingOverlay(e){try{return(await vb(e.git,[`diff-index`,`--name-only`,`HEAD`])).filter(e=>this.isContentConflictPath(e)).length}catch{return null}}async runPushCycle(){if(!this.pushInFlight&&this.mode===`full`&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(this.conflictCount>0){this.schedulePush();return}if(n9(this.projectDir)){this.schedulePush();return}if(this.pullInFlight){$.info({pullInFlight:!0},`[sync] push cycle deferred — a pull cycle holds the tree`),this.pushTimer===null&&this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.pushCycleLanded&&this.markRun(),this.schedulePush()}}}async doPushCycle(e=0){this.pushCycleLanded=!1;let t=B(uu(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),n=null;this.transitionTo(`pushing`);try{let e=this.gatherContentFilesSync();await Xs(async()=>{let r=this.gitHandle(t);if(n9(this.projectDir)){$.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await r.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){$.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(A7(e instanceof Error?e:Error(String(e))),`push`);return}await r.git.raw([`read-tree`,i]);let a=await this.listHeadContentPaths(r,i),o=await this.stageContentFiles(r,e),s=new Set(o.map(e=>e.projectRelPath)),c=[...a].filter(e=>!s.has(e));await this.removePathsFromIndex(r,c);let l=(await r.git.raw([`write-tree`])).trim(),u=``;try{u=(await r.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(u&&u===l){let t=null;try{t=(await r.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(t===i){$.info({contentFileCount:e.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.lastSyncUtc=new Date().toISOString(),this.pushCycleLanded=!0,this.consecutivePushFailures=0,this.consecutiveContentions=0,this.pushStreakIsConnectivity=!1,this.clearPushError(),this.transitionTo(`idle`);return}$.info({headSha:i,upstreamSha:t},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=i;return}let d=[],f=[];try{let t=await vb(r.git,[`diff-tree`,`--name-only`,`-r`,i,l]);if(t.length>0){let n=new Map(e.map(e=>[e.projectRelPath,e.contentRelPath]));for(let e of t){d.push(e);let t=n.get(e)??jO(V(this.contentDir,B(this.projectDir,e)));t&&!t.startsWith(`..`)&&f.push(t)}}}catch{d=e.map(e=>e.projectRelPath).concat(c),f=e.map(e=>e.contentRelPath)}let p=this.buildCommitMessage(f);await this.applyCommitIdentity(r);let m=(await r.git.raw([`commit-tree`,l,`-p`,i,`-m`,p])).trim();if(!m||!Y7.test(m)){$.warn({raw:m},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await r.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,m,i]),await this.resetRealIndexForPaths(d);let h=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),h=!0}catch{}h?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=m}),n&&(this.lastPushedSha=n,this.lastSyncUtc=new Date().toISOString(),this.pushCycleLanded=!0,this.ahead=0,this.consecutivePushFailures=0,this.consecutiveContentions=0,this.pushStreakIsConnectivity=!1,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let n=t instanceof Error?t:Error(String(t));n instanceof X7&&$.warn({err:n},`[sync] push cycle: staging error detail`);let r=A7(n);if(r.class===`semantic`&&r.subclass===`non-fast-forward`){if(e>0){$.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);let t=`fetch`;try{await e.git.fetch(`origin`),t=`push`,await this.commitDirtyContentFilesToHead(e);let n=await this.prepareForMerge(e,this.currentBranch);if(!n.proceed){this.setBatchInProgress?.(!1);return}let r=!0,i=!0;try{await this.applyCommitIdentity(e),t=`merge`,await e.git.merge([`origin/${this.currentBranch}`]),t=`push`}finally{n.needsStashPop&&(r=await this.popPreMergeStash(e)),i=this.restoreReconciledMcpOverlays(n.reconciled)}if(!r)throw Error(`failed to replay pre-merge working-tree state`);if(!i)throw Error(`failed to restore reconciled MCP overlays`);await this.persistReconciledMcpEntries(n.reconciled)}catch(e){let n=A7(e instanceof Error?e:Error(String(e)));if(n.class===`semantic`&&n.subclass===`merge-conflict`)await this.handleMergeConflict();else{let r=t===`merge`||t===`fetch`?`pull`:`push`;$.warn({err:e,stage:t},`[sync] push retry error detail`),this.handleError(n,r)}this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}this.consecutiveContentions++,this.logContention(),this.pushStreakIsConnectivity&&(this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.clearPushError()),this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(r,`push`)}finally{try{iu(t)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync(),r=await this.listHeadContentPaths(e,t);if(n.length===0&&r.size===0)return null;let i=B(uu(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),a=this.gitHandle(i);try{await a.git.raw([`read-tree`,t]);let i=await this.stageContentFiles(a,n),o=new Set(i.map(e=>e.projectRelPath)),s=[...r].filter(e=>!o.has(e));await this.removePathsFromIndex(a,s);let c=(await a.git.raw([`write-tree`])).trim();if(c===(await a.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let l=[];try{l=await vb(a.git,[`diff-tree`,`--name-only`,`-r`,t,c])}catch{l=n.map(e=>e.projectRelPath).concat(s)}await this.applyCommitIdentity(a);let u=(await a.git.raw([`commit-tree`,c,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!u||!Y7.test(u)?($.warn({raw:u},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,u,t]),await this.resetRealIndexForPaths(l,e),u)}finally{try{iu(i)}catch{}}}async readMcpGitBlob(e,t,n){try{return await e.git.raw([`cat-file`,`-e`,`${t}:${n}`]),await e.git.raw([`show`,`${t}:${n}`])}catch{return null}}async planTrackedMcpOverlap(e,t,n){let r;try{r=(await e.git.raw([`merge-base`,`HEAD`,`origin/${t}`])).trim()}catch(e){return $.warn({err:e,branch:t,path:n},`[sync] MCP reconciliation merge-base unavailable — declining`),{kind:`declined`,reason:`merge-base-unavailable`}}let[i,a,o,s]=await Promise.all([this.readMcpGitBlob(e,r,n),this.readMcpGitBlob(e,`HEAD`,n),this.readMcpGitBlob(e,``,n),this.readMcpGitBlob(e,`origin/${t}`,n)]),c=null;try{c=W(B(this.projectDir,n),`utf8`)}catch{}return G7({target:n,layers:{base:i,head:a,index:o,worktree:c,incoming:s},tomlEditor:this.mcpTomlEditor})}async prepareForMerge(e,t){let n=[],r;try{r=await vb(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return $.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1,reconciled:n}}if(r.length===0)return{proceed:!0,needsStashPop:!1,reconciled:n};let i;try{i=new Set(await vb(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return $.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1,reconciled:n}}let a=r.filter(e=>i.has(e)),o=J7,s=a.filter(e=>o.has(e));if(s.length>0){let r=await Promise.all(s.map(async n=>({path:n,plan:await this.planTrackedMcpOverlap(e,t,n)}))),i=r.find(({plan:e})=>e.kind===`declined`),c=a.some(e=>!o.has(e));if(!i&&!c){for(let{path:e,plan:t}of r)t.kind===`resolved`&&(n.push({path:e,raw:t.raw,winnerEntry:t.winnerEntry}),$.info({event:`mcp-config-reconcile`,target:e,outcome:`auto-resolved`},`[sync] auto-resolved OpenKnowledge MCP entry overlap`));a=a.filter(e=>!o.has(e))}else i?$.warn({event:`mcp-config-reconcile`,target:i.path,outcome:`declined`,reason:i.plan.kind===`declined`?i.plan.reason:void 0},`[sync] declined OpenKnowledge MCP entry reconciliation`):c&&$.info({event:`mcp-config-reconcile`,targets:s,outcome:`suppressed`,reason:`other-blocking-path`},`[sync] suppressed MCP entry reconciliation because another path blocks the merge`)}if(a.length>0){let e=a.slice(0,3).join(`, `),t=a.length>3?`, +${a.length-3} more`:``;return this.blockingPaths=a,this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutivePullFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),$.warn({files:a},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1,reconciled:[]}}if(n.length>0)try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,`--`,...n.map(e=>e.path)])}catch(e){return $.warn({err:e},`[sync] could not isolate reconciled MCP paths from pre-merge stash`),this.pullError=`Sync paused — OpenKnowledge could not safely isolate local MCP launcher changes before merging.`,this.pausedReason=`external-changes-pending`,this.blockingPaths=[],this.transitionTo(`idle`),this.scheduleSaveState(),{proceed:!1,needsStashPop:!1,reconciled:[]}}let c=new Set(n.map(e=>e.path));if(r.every(e=>c.has(e)))return{proceed:!0,needsStashPop:!1,reconciled:n};let l=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,l])}catch(e){return $.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1,reconciled:n}}return{proceed:!0,needsStashPop:!0,reconciled:n}}restoreReconciledMcpOverlays(e){let t=!0;for(let n of e)try{let e=B(this.projectDir,n.path);Iq(e,this.projectDir);let t=null;try{t=W(e,`utf8`)}catch(e){$.warn({err:e,path:n.path},`[sync] could not read MCP config before restoring reconciled overlay`)}t!==n.raw&&Fs(e,n.raw,`utf8`)}catch(e){t=!1,$.warn({err:e,path:n.path},`[sync] could not restore reconciled MCP overlay`)}return t}async popPreMergeStash(e){try{return await e.git.raw([`stash`,`pop`]),!0}catch(e){return $.warn({err:e},`[sync] stash pop failed — stash remains on stack`),!1}}hasGitOperationInProgress(){let e=Ku(this.projectDir);return e?[`MERGE_HEAD`,`CHERRY_PICK_HEAD`,`REVERT_HEAD`,`rebase-merge`,`rebase-apply`].some(t=>U(B(e,t))):!0}async persistReconciledMcpEntries(e){if(e.length!==0){if(this.hasGitOperationInProgress())throw Error(`refusing MCP entry commit while a Git operation is in progress`);await Xs(async()=>{let t=B(uu(),`ok-mcp-sync-idx-${process.pid}-${Date.now()}.idx`),n=[];try{let r=this.gitHandle(),i=this.gitHandle(t),a=(await i.git.revparse(`HEAD`)).trim(),o=(await i.git.revparse([`--abbrev-ref`,`HEAD`])).trim();if(o===`HEAD`)throw Error(`refusing MCP entry commit on detached HEAD`);await i.git.raw([`read-tree`,a]);let s=[];for(let r=0;r<e.length;r++){let o=e[r];if(!o)continue;let c=await this.readMcpGitBlob(i,a,o.path);if(c===null)throw Error(`tracked MCP path disappeared: ${o.path}`);let l=aLe({target:o.path,raw:c,entry:o.winnerEntry,tomlEditor:this.mcpTomlEditor});if(l===null)throw Error(`cannot edit tracked MCP path: ${o.path}`);let u=(await i.git.raw([`ls-tree`,a,`--`,o.path])).match(/^(100644|100755)\s/)?.[1];if(!u)throw Error(`unsafe tracked MCP mode: ${o.path}`);let d=`${t}.commit-${r}`;n.push(d),au(d,l,`utf8`);let f=(await i.git.raw([`hash-object`,`-w`,d])).trim();await i.git.raw([`update-index`,`--add`,`--cacheinfo`,`${u},${f},${o.path}`]);let p=W7({target:o.path,raw:l,tomlEditor:this.mcpTomlEditor}),m=W7({target:o.path,raw:o.raw,tomlEditor:this.mcpTomlEditor}),h=p!==null&&p===m?l:o.raw,g=`${t}.replay-${r}`;n.push(g),au(g,h,`utf8`);let _=(await i.git.raw([`hash-object`,`-w`,g])).trim();s.push({path:o.path,mode:u,blobSha:_,raw:h})}let c=(await i.git.raw([`write-tree`])).trim();if(c===(await i.git.raw([`rev-parse`,`${a}^{tree}`])).trim())return;await this.applyCommitIdentity(i);let l=(await i.git.raw([`commit-tree`,c,`-p`,a,`-m`,`Update OpenKnowledge MCP launcher`])).trim();if(!Y7.test(l))throw Error(`commit-tree returned an invalid SHA`);try{await i.git.raw([`update-ref`,`refs/heads/${o}`,l,a])}catch(e){$.info({event:`mcp-config-reconcile`,outcome:`ref-race`,branch:o,err:e},`[sync] skipped MCP launcher commit because the branch moved`);return}try{for(let e of s){await r.git.raw([`update-index`,`--add`,`--cacheinfo`,`${e.mode},${e.blobSha},${e.path}`]);let t=B(this.projectDir,e.path);Iq(t,this.projectDir),W(t,`utf8`)!==e.raw&&Fs(t,e.raw,`utf8`)}}catch(t){$.warn({event:`mcp-config-reconcile`,outcome:`overlay-replay-failed`,err:t},`[sync] MCP overlay replay failed; resetting the affected index entries`),await this.resetRealIndexForPaths(s.map(e=>e.path)),this.restoreReconciledMcpOverlays(e)}$.info({event:`mcp-config-reconcile`,outcome:`persisted-entry-commit`},`[sync] persisted OpenKnowledge MCP launcher entry commit`)}finally{for(let e of n)try{iu(e)}catch{}try{iu(t)}catch{}}})}}async stageContentFiles(e,t){if(t.length===0)return t;let n=new Set,r=!0;for(let i=0;i<t.length;i+=100){let a=t.slice(i,i+100).map(e=>e.projectRelPath);try{let t=await vb(e.git,[`ls-files`,`--others`,`--ignored`,`--exclude-standard`,`--`,...a]);for(let e of t)n.add(e)}catch(e){r=!1,$.warn({err:e},`[sync] ignored-path probe failed — staging unfiltered without -f`)}}n.size>0&&$.info({count:n.size,sample:[...n].slice(0,5)},`[sync] skipping gitignored untracked path(s) — in content scope but excluded from git`);let i=r?t.filter(e=>!n.has(e.projectRelPath)):t,a=e=>e.startsWith(`.ok/`)||e.includes(`/.ok/`),o=r?i.filter(e=>a(e.projectRelPath)):[],s=r?i.filter(e=>!a(e.projectRelPath)):i;for(let[t,n]of[[[`add`,`--`],s],[[`add`,`-f`,`--`],o]])for(let r=0;r<n.length;r+=100){let i=n.slice(r,r+100).map(e=>e.projectRelPath);await e.git.raw([...t,...i])}return i}gatherContentFilesSync(){let e=[],t=(e,t)=>{throw new X7(jO(V(this.projectDir,t))||`.`,e)},n=(r,i,a,o)=>{let s;try{s=Ql(r,{withFileTypes:!0})}catch(e){o?.(e,r);return}for(let c of s){let s=B(r,c.name);if(c.isDirectory()){let e=jO(V(i,s));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e,a))continue;let r=e.split(`/`).some(e=>e.toLowerCase()===`.ok`);n(s,i,a,o??(r?t:void 0))}else if(c.isFile()||c.isSymbolicLink()){let t=jO(V(i,s));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t,a)){let t=jO(V(this.contentDir,s)),n=jO(V(this.projectDir,s));e.push({contentRelPath:t,projectRelPath:n})}}}};if(U(this.contentDir)&&n(this.contentDir,this.contentDir,Q7),this.rootOkOutsideContentWalk){let e=B(this.projectDir,`.ok`);U(e)&&!this.contentFilter.isDirExcluded(`.ok`,$7)&&n(e,this.projectDir,$7,t)}return e}isSyncScopedPath(e){let t=B(this.projectDir,e),n=jO(V(this.contentDir,t)),r=!n.startsWith(`..`)&&!this.contentFilter.isExcluded(n,Q7),i=this.rootOkOutsideContentWalk&&e.startsWith(`.ok/`)&&!this.contentFilter.isExcluded(e,$7);return r||i}async listHeadContentPaths(e,t){let n=new Set;try{let r=await vb(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r)this.isSyncScopedPath(e)&&n.add(e)}catch{}return n}async removePathsFromIndex(e,t){if(t.length===0)return;let n=[...new Set(t)];for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100);await e.git.raw([`rm`,`--cached`,`--`,...r])}}async resetRealIndexForPaths(e,t){if(e.length===0)return;let n=t??this.gitHandle(),r=[...new Set(e)];for(let e=0;e<r.length;e+=100){let t=r.slice(e,e+100);try{await n.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 vb(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){$.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){$.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t)this.isContentConflictPath(e)?n.push(e):r.push(e);let i=[],a=jO(V(this.projectDir,ss(`project`,this.projectDir)));for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),t.toLowerCase()===a.toLowerCase()?$.warn({file:t},`[sync] auto-resolved .ok/config.yml conflict with theirs: local project config edits were overwritten by the remote version`):$.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){$.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),i.push({file:t,err:e})}if(i.length>0){let t=i.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let n=t.slice(0,3).join(`, `),r=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${n}${r}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutivePullFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),$.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(n),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),$.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await this.applyCommitIdentity(e),await e.git.raw([`commit`,`--no-edit`]);let n=Ku(this.projectDir);t=n===null||!U(B(n,`MERGE_HEAD`))}catch(e){$.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),$.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullError=`Sync paused — could not finalize the merge. Retry sync to try again.`,this.transitionTo(`idle`),$.warn({},`[sync] could not finalize merge after auto-resolving conflicts — merge aborted`)}}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){$.warn({err:t,files:e},`[sync] content conflict callback failed`)}}async notifyContentConflictsResolved(e){if(e.length!==0)try{await this.onContentConflictsResolved?.(e)}catch(t){$.warn({err:t,files:e},`[sync] content conflict resolved 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),$.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.mode=`off`,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.bumpFailureCount(t),this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.bumpFailureCount(t,gLe(e)),this.transitionTo(`offline`)):(this.bumpFailureCount(t),this.transitionTo(`idle`))}currentState(){return this.state}markRun(){this.lastPushOkUtc=new Date().toISOString(),this.cc1Broadcaster?.signal(`sync-status`)}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,$.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,lastPullOkUtc:this.lastPullOkUtc,lastPushOkUtc:this.lastPushOkUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutivePullFailures,consecutivePushFailures:this.consecutivePushFailures,pushStreakIsConnectivity:this.pushStreakIsConnectivity,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};au(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){$.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(U(this.statePath))try{let e=W(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastPullOkUtc=t.lastPullOkUtc??null,this.lastPushOkUtc=t.lastPushOkUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutivePullFailures=t.consecutiveFailures??0,this.consecutivePushFailures=t.consecutivePushFailures??0,this.pushStreakIsConnectivity=t.pushStreakIsConnectivity??!1,this.pausedReason=t.pausedReason===`no-push-permission`||t.pausedReason===`auth-error`||t.pausedReason===`external-changes-pending`?void 0:t.pausedReason;let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){$.warn({err:e},`[sync] failed to load sync state`)}}};rs();const vLe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function yLe(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(Ax(e)||jx(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&vLe.test(n)&&(r[`mount.id`]=n);try{let e=()=>{ls(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),is.with(ns.extract(is.active(),r),e)}else e()}catch(e){R(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let a9=!1;function o9(){if(a9)return;let e=Pu;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){a9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),a9=!0}catch(e){R(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const bLe=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),xLe=(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function SLe(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=Ol(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],XC({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return R(`upstream-attribution`).warn({err:e,oldHead:n,newHead:r},`git log spawn threw; upstream docs keep file-system attribution`),i}if(a.error||a.status!==0||typeof a.stdout!=`string`)return R(`upstream-attribution`).warn({err:a.error,status:a.status,signal:a.signal,stderr:typeof a.stderr==`string`?a.stderr.slice(0,500):void 0,oldHead:n,newHead:r},`git log failed; upstream docs keep file-system attribution`),i;let o=null;for(let n of a.stdout.split(`
|
|
2041
|
-
`)){let r=n.trim();if(r===``)continue;if(r.startsWith(`C\0`)){let[,e,t]=r.split(`\0`);o=e&&t?{name:e,email:t}:null;continue}if(!o||!r.endsWith(`.md`)&&!r.endsWith(`.mdx`))continue;let a=H(e,r);if(!PO(a,t))continue;let s=BF(a,t);i.has(s)||U(a)&&i.set(s,o)}return i}function s9(e){o9();let t=e.ingressPolicy??pI({}),{contentDir:n,projectDir:r=n,quiet:i=!0,debounce:a=2e3,maxDebounce:o=1e4,gitEnabled:s=!0,commitDebounceMs:c=3e4,wipRef:l=`refs/wip/main`,configHomedirOverride:u,enableTestRoutes:d=!1,shadowRepo:f,contentRoot:p,destroyTimeoutMs:m=1e4,localOpCliArgs:h,authStreamHeartbeatMs:g,skipStateManifestCheck:_=!1,singleDocRelPath:v,ephemeral:y=!1}=e,b=R(`server`),x=new L5,S=()=>x.getActiveBranch(),C=e=>x.getReconciledBase(e),w=(e,t)=>x.setReconciledBase(e,t),T=e=>x.deleteReconciledBase(e),E=e=>x.switchReconciledBaseScope(e),D=e=>x.setBatchInProgress(e),ee=()=>x.isBatchInProgress();function te(e){let t=ds({absPath:ss(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});if(!t.valid){let n=Lo(t.error)&&t.error.code===`SCHEMA_INVALID`?t.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(n.length>0){let e=n.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}if(e?.requireValid)throw Error(`Project config is invalid`,{cause:t.error});b.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return t.value.content.attachmentFolderPath??`./`}function O(){let e=ds({absPath:ss(`project-local`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)}),t=kte(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||b.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let n=ds({absPath:ss(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});return n.valid||b.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:Fte(n.value.autoSync?.default)??`off`,source:`committed-default`}}function k(){return Kte(ds({absPath:ss(`project-local`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)}).value.autoSync)}function ne(){let e=ds({absPath:ss(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules,t=e?$n(e):Xr;return RFe(r,t.plugins.okf),t}function re(){return ds({absPath:ss(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function ie(){return uL(r,{configHomedirOverride:u,onWarn:e=>b.warn({message:e},`[config] could not read project-local config`)})}function ae(){let e=ds({absPath:ss(`project-local`,r,u),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function oe(){return Ts({cwd:r,homedirOverride:u,warn:e=>b.debug({message:e},`[config] diagnostics read`)})}function se(){for(let e of oe().diagnostics)e.code===`REMOVED_KEY`&&b.warn({scope:e.scope,file:e.file,path:e.path.join(`.`)},`[config] ${e.path.join(`.`)} is no longer read and was ignored. ${e.redirect}`)}function ce(e){return`${eL(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}let le;function ue(e,t){let i;if(e===`__config__/project`||e===`__local__/project`){let t=O();i=t.mode,on?.setMode(t.mode,t.source).catch(n=>{b.warn({err:n,mode:t.mode,docName:e},`[sync] failed to apply autoSync mode from config`)});let n=k();on?.setIntervals(n.pullIntervalSeconds,n.pushIntervalSeconds)}let a=ie();if(Fe.applyConfig({enabled:a.enabled,providerFingerprint:ce(a)}),e===`__config__/project`){try{let e=te({requireValid:!0});ve?.setAttachmentFolderPath(e),le!==void 0&&e!==le&&b.warn({previous:le,next:e},`[content-filter] attachment folder changed — files under the previous folder no longer sync`),le=e}catch(e){b.warn({err:e},`[content-filter] project config invalid — keeping previous attachment admission`)}Oe?.signal(`lint-config`),(t??ne().plugins.okf?.generate?.index===!0)||b5({projectDir:r,contentDir:n,generatedDocNames:Ot(),enabled:!1}).then(e=>{e.ok||b.warn({state:e.status.state},`[index] could not remove Open Knowledge generated-index Git attributes`)}),Ct()}b.info({docName:e,autoSyncMode:i,semanticEnabled:a.enabled},`[config] applied persisted config to in-process consumers`)}Ls();let de=xu(),fe=dP(r),pe=new Od({localDir:fe,log:R(`acp-registry`)}),me=new yd(fe,R(`acp-permissions`));if(uc(fe,{port:0,worktreeRoot:r,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),!_)try{D7({lockDir:fe,shadowRepoDir:qu(r)})}catch(e){throw dc(fe),e}let he=ta(),ge=(e,t)=>he.resolveEmbed(e,t),_e=(e,t)=>{let r=he.resolveEmbed(e,t);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=H(n,r);if(!MO(i,H(n)))return null;try{let e=ru(i);return e.isFile()?e.size:null}catch{return null}},ve,ye,be,xe,Se,Ce,A,we,Te,Ee,De,Oe=null,ke=null,Ae=null,je=null,Me=null,Ne=null,Pe=ie(),Fe=new u_e({loadEmbedder:e.embedderLoader??(()=>{let t=ie();return Xge({keyStore:e.embeddingsKeyStore??null,projectDir:r,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:B(dP(r),`embeddings`),enabled:Pe.enabled,providerFingerprint:ce(Pe)}),Ie=null,Le=new Set,Re=!1,ze=[],Be,Ve,He,Ue=new Promise((e,t)=>{Ve=e,He=t}),We,Ge=new Promise(e=>{We=e});async function Ke(){let e,t=Symbol(`branch-scope-gate-timeout`),n=new Promise(n=>{e=setTimeout(()=>n(t),1e4),e.unref?.()});try{if(await Promise.race([Ge,n])!==t)return S()}finally{e&&clearTimeout(e)}try{return B5(r).branch??null}catch(e){return b.warn({err:e},`[auth] branch scope gate expired and HEAD is unreadable — skipping the branch claim check`),null}}function qe(e){Oe?.signal(e)}let Je,Ye,Xe,Ze=!1,Qe=!1,$e=new AbortController,et=new Set,tt=!1,nt=!1,rt=!1,it=0,at,ot=new Promise(e=>{at=e});function st(e){rt||(rt=!0,at(e))}function ct(){return tt||et.size>0}function lt(){Qe||!Ze||(Je!==void 0&&clearTimeout(Je),Je=setTimeout(()=>{Je=void 0,vt()},500),Je.unref?.())}function ut(){if(Qe){st({status:`cancelled`,indexCount:0});return}tt=!0,nt=!0,Ye=setImmediate(()=>{Ye=void 0,vt()})}let dt,ft,pt=!1,mt=null;async function ht(){let e=be.current;if(!e||pt)return;let t=performance.now();b.info({gitDir:e.gitDir},`[shadow-housekeeping] deferred boot housekeeping started`);try{await qb(e)}catch(e){b.warn({err:e},`failed to write gc config (non-fatal)`)}if(!pt){if(mt)try{let t=Number.parseInt(process.env.OK_BOOT_RENAME_GC_RETRY_INTERVAL_MS??``,10)||1e3,n=!1;for(let r=0;r<30;r++){if(!(await CV(e,mt,{rebuild:!0})).skipped){n=!0;break}if(r===29)break;if(await new Promise(e=>{setTimeout(e,t).unref?.()}),pt)return}n||b.warn({gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild retry budget exhausted (persistent GC contention); rebuild deferred to next boot`)}catch(t){b.warn({err:t,gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild failed; index loaded without GC`)}if(!pt){try{await xe?.runBootMaintenance()}catch(e){b.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}b.info({gitDir:e.gitDir,durationMs:Math.round(performance.now()-t)},`[shadow-housekeeping] deferred boot housekeeping complete`)}}}function gt(){pt||(dt=setImmediate(()=>{dt=void 0,ft=ht().catch(e=>{b.error({err:e},`[shadow-housekeeping] unexpected uncaught failure`)})}))}async function _t(){if(pt=!0,dt!==void 0&&(clearImmediate(dt),dt=void 0),!ft)return;let e,t=new Promise(t=>{e=setTimeout(()=>t(`timeout`),m)});try{if(await Promise.race([ft,t])===`timeout`)throw Error(`shadow housekeeping drain timed out after ${m}ms — abandoning in-flight housekeeping`)}finally{e!==void 0&&clearTimeout(e)}}function vt(){if(Qe||!Ze||!ct())return;if(Xe!==void 0){e.generatedIndexTestHooks?.onKickWhileInFlight?.();return}if(x.isBatchInProgress()){lt();return}let t=tt,n=new Set(et),r=nt;tt=!1,et.clear(),nt=!1;let i=t?{fullSweep:!0}:{fullSweep:!1,directories:n};Xe=(async()=>{let e=await Mt(i,$e.signal);if(e.status===`deferred`){tt=!0,r&&(it+=e.indexCount,nt=!0);return}r&&(it+=e.indexCount,e.status===`completed`&&ct()?nt=!0:st({...e,indexCount:it}))})().catch(e=>{b.warn({err:e},`[index] index regeneration coordinator failed`),r&&st({status:`failed`,indexCount:0})}).finally(()=>{if(Xe=void 0,Qe){r&&st({status:`cancelled`,indexCount:0});return}ct()&&Je===void 0?lt():!ct()&&Je===void 0&&e.generatedIndexTestHooks?.onIdle?.()})}async function yt(){if(!Qe){let e=Xe;Qe=!0,$e.abort(),Je!==void 0&&(clearTimeout(Je),Je=void 0),Ye!==void 0&&(clearImmediate(Ye),Ye=void 0),et.clear(),tt=!1,nt=!1,e===void 0&&st({status:`cancelled`,indexCount:0})}await Xe}function bt(e){Qe||EFe(e)||(et.add(j5(e)),lt())}function xt(e){if(!Qe){for(let t of TFe(e))et.add(t);lt()}}function St(e){let t=rn?.getFileIndex();if(!t){bt(e);return}let n=j5(e);if(P5(t.keys()).has(n)){bt(e);return}xt(j5(n))}function Ct(){Qe||(tt=!0,lt())}function wt(e){let t=rn?.getFileIndex().get(e);if(t)return{title:t.title,description:t.description,type:t.type}}let Tt=!1,Et={origin:xLe,writer:Wce,isConflict:e=>on?.getConflicts().some(t=>o5(t,e,r,n))===!0,getDocument:e=>A.documents.get(e),writeDisk:async(e,t)=>{Es(z(e),{recursive:!0}),await us(e,t,{fs:_s})},registerWrite:(e,t)=>AF(e,MF(t)),noteFileIndex:e=>rn?.mutateFileIndex({kind:e.kind,path:e.absPath,docName:e.docName,content:e.markdown}),signalFiles:()=>qe(`files`),attribute:async(e,t)=>{xO(e,t.id,t.name,t.id),Tt=!0}};function Dt(e){return e===``?k5:`${e}/${k5}`}function Ot(){return[...rn?P5(rn.getFileIndex().keys()):new Set([``])].map(Dt)}function kt(e){let t=ne().plugins.okf?.generate?.index===!0,n=e.state===`ready`||e.state===`not-applicable`;return{enabled:t,active:t&&n,git:e.state===`ready`?{state:e.state,ownership:e.ownership}:{state:e.state}}}function At(){return kt(v5({projectDir:r,contentDir:n,generatedDocNames:Ot()}))}async function jt(e){let t=await b5({projectDir:r,contentDir:n,generatedDocNames:Ot(),enabled:e});if(!t.ok)return{...At(),applied:!1,reason:t.status.state===`conflict`?`git-conflict`:`git-unavailable`};let i=await ws({cwd:r,scope:`project`,patch:{contentRules:{okf:{generate:{index:e}}}}});if(!i.ok){try{await t.rollback()}catch(e){b.error({err:e},`[index] could not roll back generated-index Git attributes`)}return{...At(),applied:!1,reason:`config-write`}}try{let e=W(i.path,`utf-8`);a5(A.documents.get(`__config__/project`)??null,Tr,e,Se.configPersistenceCtx)}catch(e){b.warn({err:e},`[index] generated-index settings reflection deferred to config watcher`)}return ue(Tr,e),{...At(),applied:!0}}async function Mt(t,i){let a=0,o=t.fullSweep?performance.now():void 0,s=()=>ne().plugins.okf?.generate?.index!==!0;try{if(i.aborted)return{status:`cancelled`,indexCount:0};if(s())return{status:`disabled`,indexCount:0};let c=rn?.getFileIndex();if(!c)return{status:`failed`,indexCount:0};try{if(await e.generatedIndexTestHooks?.beforePlan?.({fullSweep:t.fullSweep,signal:i}),i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};if(x.isBatchInProgress())return{status:`deferred`,indexCount:a};let o=DFe({docs:c,docExtension:wx,currentMarkdownFor:()=>null}),l=v5({projectDir:r,contentDir:n,generatedDocNames:o.map(({directory:e})=>Dt(e))});if(l.state!==`ready`&&l.state!==`not-applicable`)return b.warn({state:l.state},`[index] generated index regeneration paused by Git attributes`),{status:`blocked`,indexCount:a};for(let{directory:r,markdown:c}of o){if(!t.fullSweep&&!t.directories.has(r))continue;if(i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};if(x.isBatchInProgress())return{status:`deferred`,indexCount:a};if(await e.generatedIndexTestHooks?.beforeDecision?.({directory:r,fullSweep:t.fullSweep,signal:i}),i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};let o=Dt(r),l=H(n,`${o}.md`),u;try{u=W(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&b.warn({err:e,path:Os(l)},`[index] could not read the existing generated index; treating it as absent`),u=null}a+=1;let d=await sFe({docName:o,absPath:l,markdown:c,currentMarkdown:u},Et);d===`blocked-conflict`?b.warn({event:`generated-index-regeneration`,outcome:`blocked`,directory:r,reason:`conflict`},`[index] generated index regeneration blocked by active conflict`):b.info({event:`generated-index-regeneration`,outcome:d===`unchanged`?`unchanged`:`written`,directory:r},`[index] generated index regeneration completed`),await e.generatedIndexTestHooks?.afterWrite?.({docName:o,fullSweep:t.fullSweep,signal:i}),!t.fullSweep&&r!==``&&u===null&&xt(j5(r))}}finally{Tt&&=(await Se.waitForPendingCommits(),await Se.flushContributors(),!1),o!==void 0&&(HI(`generatedIndexSweepMs`,Math.round((performance.now()-o)*100)/100),UI(`generatedIndexCount`,a))}return{status:`completed`,indexCount:a}}catch(e){return b.warn({err:e},`[index] index regeneration failed`),{status:`failed`,indexCount:a}}}let Nt=null,Pt=!1,Ft=()=>{try{v7(r,It.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},It=new gIe(void 0,{onEviction:()=>wce(),onSizeChange:e=>Tce(e),onMutate:()=>{!Pt||Nt!==null||(Nt=setTimeout(()=>{Nt=null,Ft()},2e3))}});for(let[e,t]of xIe(r))Ix(e)||JX(e)&&([`.md`,`.mdx`].some(t=>{let r=H(n,`${e}${t}`);return MO(r,H(n))&&U(r)})||It.restore(e,t));Pt=!0;let Lt={current:null},Rt=(e,t)=>{Ix(e)||It.setRenamed(e,t)},zt=e=>{if(!Ix(e)){if(It.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}It.setDeleted(e),Lt.current?.deleted(e)}},Bt=e=>{Ix(e)||It.delete(e)};try{let m=`./`;try{m=te()}catch(e){b.warn({err:e},`[content-filter] invalid attachment folder at boot — using sibling admission`)}le=m,ve=yj({projectDir:r,contentDir:n,singleDocRelPath:v,attachmentFolderPath:m,inPlaceSkillDirs:cP(n),rescanInPlaceSkillDirs:()=>cP(n),skillRootPaths:fhe(n),onAfterRebuild:()=>{ye.refreshContentScope().catch(e=>{R(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),dge(rn).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?R(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):R(`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=>{R(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),ye=new Vhe({projectDir:r,contentDir:n,contentFilter:ve,getGlobalSkillRoots:()=>PV(Se.managedArtifactCtx),signalChannel:qe,getLocalTargetInventory:()=>Lye(rn,n),onRecoveredFileTarget:(e,t)=>{rn&&vIe({watcher:rn,contentDir:n,relativePath:e,exists:t,invalidateReferencedAssetsCache:Me})}}),be={current:f},xe=s?rIe({getShadow:()=>be.current??null,getCurrentBranch:()=>an?.getLastKnownBranch()??null,contentRoot:p??``,projectGitDir:Ku(r)??void 0,isWriterLive:e=>{if(!je&&!we)return R(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(je?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of we?.sessionsForConnection(t)??[])return!0;return!1}}):void 0;let _=null;Se=d7({contentDir:n,projectDir:r,gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:be,ephemeral:y,contentRoot:p,derivedDocumentIndex:ye,configHomedirOverride:u,getCurrentBranch:()=>an?.getLastKnownBranch()??null,resolveEmbed:ge,resolveSize:_e,getPrincipal:()=>Ie,onAgentCommit:()=>Oe?.signal(`session-activity`),onFlushCommit:()=>xe?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{Oe?.emitDiskAck(e,t),!Ix(e)&&(OFe(r,n,e)&&bt(e),m_e(r,n)&&(Me?.(),qe(`files`)))},onConfigRejected:(e,t)=>Oe?.emitConfigValidationRejected(e,t),onConfigPersisted:ue,onManagedSkillPersisted:e=>{let t=ea(e);t?.kind!==`skill`||t.scope!==`global`||(_!==null&&clearTimeout(_),_=setTimeout(()=>{_=null;let e=u??su();IJ(e,e,oP(e)).then(e=>{e>0&&b.info({refreshed:e},`[in-place-skills] post-edit copy re-sync`)}).catch(e=>b.warn({err:e},`[in-place-skills] post-edit copy re-sync failed`))},2e3),_.unref?.())},isRecentlyRemoved:e=>It.has(e),mdManager:e.mdManager,getLossRing:()=>Ce,durabilityState:x}),A=new GPe({quiet:i,debounce:a,maxDebounce:o,extensions:[Se.extension]});let S=A.openDirectConnection.bind(A);A.openDirectConnection=((e,t)=>S(Ex(e),t));let w=A;ze.push(mC(()=>w.documents.size),Yle(()=>Se.getQueueDepths()),Zle(()=>{let e=0;for(let t of w.documents.values())e+=t.directConnectionsCount;return{websocket:w.getConnectionsCount()-e,direct:e}})),$le(),y||(Ne=mIe({getLoadedDocuments:()=>w.documents,forceStore:(e,t)=>Se.forceStore(e,t),getBase:e=>x.getReconciledBase(e),isBatchActive:()=>x.isBatchInProgress(),hasInFlight:e=>x.inFlightFlushCount(e)>0,readDiskBytes:e=>{let t=NO(e,n),r,i;try{r=G(t),i=ru(r).size}catch(t){let n=pc(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new p7(`symlink cycle at content path: ${e}`):t}if(!PO(r,n))throw new p7(`symlink-escape: ${t} resolves outside the content dir`);if(i>524288)throw new p7(`document exceeds the open byte limit: ${e}`);try{return W(r,`utf-8`)}catch(e){if(pc(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let T=A.shouldUnloadDocument.bind(A);A.shouldUnloadDocument=e=>{if(Le.has(e)||Re&&T(e))return!0;let t=e.name;return Ix(t)||C(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:T(e)},Be=async e=>{Le.add(e);try{await A.unloadDocument(e)}finally{Le.delete(e)}},Oe=new Bx(A),Ae=new gE(A),je=new _E(A),we=new JC(A,e.agentSessionOptions);let E=we;ze.push(Qle(()=>({active:E.liveSessionCount,limit:E.sessionLimit})));let D=U5({derivedDocumentIndex:ye,onDocumentSettled:e=>Lt.current?.changed(e)});A.configuration.extensions.push(D);function ee(e,t,n={}){b.warn({reason:e,docName:t,...n},`[auth-rejection] ${e}`)}A.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=iZ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==de)throw ee(`server-instance-mismatch`,e.documentName,{claimedServerInstanceId:r,currentServerInstanceId:de}),new rZ(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${de}`);let i=n?.expectedBranch;if(typeof i==`string`&&i.length>0){let t=await Ke();if(t!==null&&i!==t)throw ee(`branch-mismatch`,e.documentName,{claimedBranch:i,currentBranch:t}),new rZ(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${t}`)}if(!n)return;let a=e.context;typeof n.principalId==`string`&&(Ie&&n.principalId===Ie.id?a.principalId=Ie.id:Ie?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:Ie.id})):a.principalId=n.principalId),typeof n.tabSessionId==`string`&&(a.tabSessionId=n.tabSessionId),a.kind=`human`}}),A.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!jx(e.documentName)&&!Mx(e.documentName))return;let n=e.request,r=n.socket?.remoteAddress;if(r!==void 0&&!mI(r,t))throw ee(`config-doc-admission-denied`,e.documentName,{check:`peer`}),Error(`config-doc admission requires loopback peer (peer=${r}, doc=${e.documentName})`);let i=e.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0;if(!hI(a,t))throw ee(`config-doc-admission-denied`,e.documentName,{check:`host`}),Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${e.documentName})`)}});let O=H(n);function k(e){if(!JX(e))return null;let t=H(O,Dx(e));return MO(t,O)?t:null}A.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await yIe(e.documentName,{recentlyRemovedDocs:It,resolveFilePath:k,fileExists:U})}}),A.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=iZ(e.token);kFe(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>A.documents.get(e)})}}),A.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new T8(e.update);if(t.readVarString(),t.readVarUint()===I8.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${ao} rejected — server-only channel`)}});let se=YX({hocuspocus:A,durabilityState:x,ingressPolicy:t,sessionManager:we,commentDocHooksRef:Lt,contentDir:n,getGeneratedIndexSettingsStatus:At,setGeneratedIndexEnabled:jt,contentFilter:ve,serverInstanceId:de,getFileIndex:()=>rn?rn.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>rn?rn.getAllFilesIndex():new Map,getFileIndexGeneration:()=>rn?.getFileIndexGeneration()??0,mutateFileIndex:e=>{let t=e.kind===`update`?wt(e.docName):void 0;switch(rn?.mutateFileIndex(e),e.kind){case`update`:I5(t,e.content,e.docName)&&bt(e.docName);break;case`create`:case`conflict`:bt(e.docName);break;case`delete`:St(e.docName);break;case`rename`:St(e.oldDocName),bt(e.newDocName);break;case`folder-create`:case`folder-delete`:xt(e.relativePath);break;case`asset-create`:case`asset-delete`:case`file-create`:case`file-update`:case`file-delete`:break;default:EF(e)}},getFolderIndex:()=>rn?rn.getFolderIndex():new Map,getAliasMap:()=>rn?rn.getAliasMap():new Map,getFolderAliasIndex:()=>rn?rn.getFolderAliasIndex():new Map,rescanFiles:()=>rn?.rescanFromDisk(),enableTestRoutes:d,shadowRef:be,flushGitCommit:()=>Se.flushPendingGitCommit(),flushContributors:()=>Se.flushContributors(),getCurrentBranch:()=>an?.getLastKnownBranch()??null,getDiskAckSVs:()=>Oe?.getLatestDiskAckSVsAsBase64()??{},getCollabClientCount:e.getCollabClientCount,contentRoot:p,derivedDocumentIndex:ye,signalChannel:qe,agentFocusBroadcaster:Ae,agentPresenceBroadcaster:je,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>on,localOpCliArgs:h,authStreamHeartbeatMs:g,projectDir:r,resolveEmbed:ge,getBridgeLossReporter:()=>De,getPrincipal:()=>Ie,acpRegistry:pe,loadAcpCustomAgents:()=>kd(fe,R(`acp-registry`)),homeDirOverride:u,forceUnloadDocument:Be,ready:Ue,recentlyRemovedDocs:It,serializeDoc:Kt,evictManagedArtifactLkg:e=>{Se.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Fe,getSemanticSimilarityFloor:()=>ie().similarityFloor,getLinterBaseConfig:()=>ne(),getLinksValidationSetting:()=>re(),getLinkPreviewsEnabled:ae,getConfigDiagnostics:oe,embeddingsSecretsFile:sL(u),readSemanticProviderConfig:ie,ephemeral:y,onReferencedAssetsCacheInvalidator:e=>{Me=e}});A.configuration.extensions.push(se),Te=se.nativeApi,Ee=se.localApi;let ce=ds({absPath:ss(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for bridge guards`)}),me=ce.value.bridge.deferGuard.enabled,he=ce.value.bridge.fixedPoint.enabled,ke=ce.value.bridge.preDrain.enabled;Ce=ce.value.lossCapture.enabled?new use({projectDir:r,maxBytes:ce.value.lossCapture.maxBytes}):void 0,ce.value.bridge.lossDetector.enabled&&(De=ile({shadow:()=>be.current,ring:Ce,getBranch:()=>an?.getLastKnownBranch()??`main`,contentRoot:p??``}),we.attachBridgeLossReporter(De)),A.configuration.extensions.push(b7({mdManager:os,schema:as,shadowRef:be,contentRoot:p,getCurrentBranch:()=>an?.getLastKnownBranch()??null,resolveEmbed:ge,resolveSize:_e,deferGuardEnabled:me,lossDetectorEnabled:ce.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:he,preDrainEnabled:ke,lossRing:Ce})),A.configuration.extensions.push(yLe()),A.configuration.extensions.push(oFe({getSyncEngine:()=>on,projectDir:r,contentDir:n}))}catch(e){for(let e of ze.splice(0))e();throw Ne?.dispose(),Ne=null,dc(fe),e}let Vt=null,Ht=new Map,Ut=[];function Gt(e,t){let n=H(e,`rescue`),r=H(n,Dx(t));return MO(r,n)?r:null}function Kt(e){let t=A.documents.get(e);return t?bF(t):null}let qt=(e,t)=>vF(x,A,e,t,ge,_e,De);function Jt(e){if(!Xx(e)||on?.getConflicts().some(t=>o5(t,e.name,r,n)))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Yt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of A.documents){if(Ix(n))continue;let r=A.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{dF(r,i,ge,n)},uF)}catch(t){b.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},Xt=null,Zt=e=>{e&&(Xt===null&&(Xt=new Set,setImmediate(()=>{let e=Xt;if(Xt=null,e)try{for(let t of e)Yt(t)}catch(t){b.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Xt.add(e))};function Qt(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 EF(e)}}async function $t(e){try{switch(e.kind){case`create`:b.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await ye.recordDiskUpsert(e.docName,e.content),qe(`files`),bt(e.docName),Bt(e.docName);break;case`update`:{let{docName:t,content:n}=e;I5(e.previousIndexedFields,n,t)&&bt(t);let r=A.documents.get(t);if(!r){await ye.recordDiskUpsert(t,n);return}let i=C(t)??``,a=Kt(t)??i,o=gF({docName:t,base:i,ours:a,theirs:n}),s=MF(i).slice(0,6),c=MF(a).slice(0,6),l=MF(n).slice(0,6);switch(b.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:Jt(r),await ye.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{qt(t,o.newContent),w(t,o.newContent),bb(),Jt(r),e=!0}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),w(t,n),Jt(r)}e&&await ye.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{qt(t,o.newContent),w(t,n),bb(),Jt(r),e=!0}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),w(t,n),Jt(r)}e&&await ye.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{qt(t,o.newContent),w(t,o.newContent),bb(),xb(),e=!0}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),w(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}e&&await ye.recordDiskUpsert(t,n);break}case`refused`:{xb();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=A.documents.get(t);if(!n){await ye.recordDiskDelete(t),qe(`files`),zt(t),St(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=C(t)??``,i=Kt(t)??``,a=i!==r;if(a&&be.current){let e=be.current,n=an?.getLastKnownBranch()??`main`;queueMicrotask(()=>{lx(e,p??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{Cb(),b.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{b.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),T(t),await ye.recordDiskDelete(t),b.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),A.closeConnections(t),await Be(n),qe(`files`),zt(t),St(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=A.documents.get(t);if(i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}T(t),w(n,r),await ye.recordDiskRename(t,n,r),b.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),qe(`files`),Rt(t,n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`})),St(t),bt(n);break}case`conflict`:{let{docName:t}=e,n=A.documents.get(t);if(!n)return;let r=Kt(t);r===null?b.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):w(t,r);let i=n.getMap(`lifecycle`);i.set(`status`,`conflict`),i.set(`reason`,`conflict-markers`),b.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:he.add(e.relativePath),qe(`files`),Zt(Al(e.relativePath));break;case`asset-delete`:he.remove(e.relativePath),qe(`files`),Zt(Al(e.relativePath));break;case`folder-create`:case`folder-delete`:qe(`files`),xt(e.relativePath);break;case`file-create`:case`file-update`:await ye.recordFileTargetUpsert(e.relativePath),Me?.(),qe(`files`);break;case`file-delete`:await ye.recordFileTargetDelete(e.relativePath),Me?.(),qe(`files`);break;default:EF(e)}}catch(t){let n=Qt(e);b.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let en=[];async function tn(e){if(ee()){en.push(e);return}await $t(e)}async function nn(){let e=en.splice(0,en.length);for(let t of e)await $t(t)}let rn=null,an=null,on=null,sn=null;async function cn(e){if(A.documents.size===0)return;let t=!1,n=new Promise(e=>{A.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(A.documents.keys());A.closeConnections(),A.flushPendingStores();for(let e of A.documents.values())e.getConnectionsCount()===0&&A.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 i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(A.documents.keys()),i=[],o=[];if(be.current){for(let e of n)if(!Ix(e))try{let t=Kt(e);if(t===null){b.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=Gt(be.current.gitDir,e);if(!n){b.warn({docName:e,gitDir:be.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}ql(z(n),{recursive:!0}),au(n,t,`utf-8`),Cb(),i.push(e),b.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),b.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else b.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function ln(){return sn||(sn=(async()=>{let e=Date.now(),t=[];Re=!0;try{await yt()}catch(e){b.warn({err:e},`[index] generated index shutdown drain failed`),t.push({phase:`generated-index-drain`,error:String(e)})}for(let e of ze.splice(0))e();try{await Ne?.dispose()}catch(e){b.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Ne=null;try{lc(fe)}catch(e){b.warn({err:e},`[server] failed to mark server.lock draining`)}xe?.destroy();try{await _t()}catch(e){b.warn({err:e},`[shadow-housekeeping] shutdown drain failed`),t.push({phase:`shadow-housekeeping-drain`,error:String(e)})}if(Nt!==null&&(clearTimeout(Nt),Nt=null),Pt)try{v7(r,It.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let n,i=await Promise.race([Ue.then(()=>`completed`,e=>(b.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{n=setTimeout(()=>e(`timeout`),5e3)})]);n!==void 0&&clearTimeout(n),i===`timeout`&&b.warn({},`[server] init did not complete within 5s during shutdown`);let a=A.documents.size;try{try{try{ke&&=(clearTimeout(ke),null),an&&=(await an.unsubscribe(),null),rn&&=(await rn.unsubscribe(),null);for(let{docName:e,cleanup:t}of Ut)try{await t()}catch(t){b.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Ut.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{Oe?.destroy(),je?.destroy(),Vt&&=(await Vt.disconnect(),null);for(let[e,t]of Ht)try{await t.disconnect()}catch(t){b.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Ht.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await we.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await ble()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await cn(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-3 flush failed`)}ye.close();let e;try{await Promise.race([(async()=>{await Se.flushPendingGitCommit(),await Se.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{on&&=(await on.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(be.current){let e;try{await Promise.race([Vb(be.current).drain(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`shadow mutator drain timeout`)),m)})])}catch(e){t.push({phase:`shadow-mutator-drain`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-5 shadow mutator drain failed`)}finally{e!==void 0&&clearTimeout(e)}try{let e=(await nc({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&au(H(be.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{Rce(be.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let n=Date.now()-e;t.length===0?b.info({documentCount:a,durationMs:n},`[server] shutdown flushed ${a} documents in ${n}ms`):b.warn({documentCount:a,durationMs:n,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${n}ms with ${t.length} phase error(s)`)}}finally{try{dc(fe,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await Is()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),sn)}let un=[];async function dn(){try{Ie=await m7(r),b.info({principalId:Ie.id},`[server] principal loaded`)}catch(e){b.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!be.current)try{be.current=await Yb(r,{deferGcConfig:!0}),b.info({gitDir:be.current.gitDir},`[server] history repo initialized at ${be.current.gitDir}`)}catch(e){b.error({err:e},`[server] history repo init failed`),un.push(`shadow-repo`)}if(be.current)try{let e=$B(be.current.gitDir);SV(be.current.gitDir,e),iV(be.current.gitDir,e),mt=e,b.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){b.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(be.current)try{await Kb(be.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`)){b.warn({},`[server] history repo appears corrupted — reinitializing`);try{be.current=await Yb(r,{deferGcConfig:!0})}catch(e){b.error({err:e},`[server] history repo reinit failed`),be.current=void 0,un.includes(`shadow-repo`)||un.push(`shadow-repo`)}}else b.error({err:e},`[server] history repo check failed (transient?)`)}if(be.current){let e=be.current,t=jO(V(r,n))||`.`;setTimeout(()=>{$b(e,t).catch(e=>{b.debug({err:e},`[shadow] fan-out index warm-up failed (non-fatal)`)})},3e3).unref()}if(be.current)try{let e=H(be.current.gitDir,`last-known-head`),t=null;try{t=W(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await nc({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await nc({baseDir:r,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}b.info({lastKnownHead:t,currentHead:n,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=import`);try{await ox(be.current,p??``,t,n,e),Sb()}catch(e){b.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else b.info({currentHead:n},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=noop`);try{au(e,n,`utf-8`)}catch(e){b.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){b.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=Yye(n,r);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;b.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){b.error({err:e},`[server] managed rename recovery failed`),un.push(`managed-rename-recovery`)}try{let e=ZL(r);(e.deleted>0||e.errors>0)&&b.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){b.error({err:e},`[server] upload-tempfile sweep failed`),un.push(`upload-tempfile-sweep`)}try{Vt=await A.openDirectConnection(ao),Oe?.emitServerInfo(de,S())}catch(e){b.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),un.push(`cc1-push`)}let t=y?[]:Mi;for(let e of t)try{let t=await A.openDirectConnection(e);Ht.set(e,t)}catch(t){b.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),un.push(`config-doc:${e}`)}let i=new Map([[Tr,ss(`project`,r)],[Yee,ss(`project-local`,r)],[hte,ss(`user`,r,u)]]);for(let e of t){let t=i.get(e);if(t)try{b.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await Y8(t,t=>{let n=A.documents.get(e);b.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=a5(n??null,e,t,Se.configPersistenceCtx);b.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),ue(e)});Ut.push({docName:e,cleanup:n}),b.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){b.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),un.push(`config-file-watcher:${e}`)}}if(!y){let e=null,t=t=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,ye.refreshGlobalSkillNodes().catch(e=>{b.warn({err:e,docName:t},`[backlinks] global skill bundle re-ingest failed`)})},300)},n=(e,n)=>{let r=zV(e,Se.managedArtifactCtx);if(!r)return;let i=WV(A.documents.get(r)??null,r,n,Se.managedArtifactCtx);b.info({docName:r,outcome:i},`[managed-artifact-watcher] external change`),qe(`files`),Wt(r)&&t(r)},r=e=>{let n=zV(e,Se.managedArtifactCtx);qe(`files`),n&&Wt(n)&&t(n)};try{let e=PV(Se.managedArtifactCtx),t=await iIe(e,n,r);Ut.push({docName:`__skill-files__`,cleanup:t}),b.info({roots:e},`[managed-artifact-watcher] skills started`)}catch(e){b.warn({err:e},`[managed-artifact-watcher] skills failed to start`),un.push(`managed-artifact-watcher:skills`)}try{let e=H(jV(Se.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await Y8(e,()=>{qe(`files`)});Ut.push({docName:`__skill-state__`,cleanup:t}),b.info({path:e},`[skill-state-watcher] started`)}catch(e){b.warn({err:e},`[skill-state-watcher] failed to start`),un.push(`skill-state-watcher`)}}try{let e=H(n,`.okignore`),t=H(r,`.gitignore`),i=null;try{let e=Ol(`git`,[`rev-parse`,`--git-common-dir`],XC({cwd:r,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=B(H(r,e.stdout.trim()),`info`,`exclude`);U(z(t))&&(i=t)}}catch{}let a=i?[e,t,i]:[e,t],o=b;o.info({okignorePath:e,gitignorePath:t,gitInfoExcludePath:i,ephemeral:y},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=y?null:await ZPe(a,(t,n)=>{(async()=>{if(t===e)try{let e=a5(A.documents.get(`__config__/okignore`)??null,wi,n,Se.configPersistenceCtx);o.info({docName:wi,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:V(r,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await ve.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:V(r,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),Oe?.signal(`files`);else{let e=V(r,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),Oe?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:V(r,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Ut.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:t},`[ignore-watcher] multi-path watcher started`))}catch(e){b.warn({err:e,projectDir:r,contentDir:n},`[ignore-watcher] failed to start multi-path watcher`),un.push(`ignore-files-watcher`)}let a=B5(r).branch??`main`;E(a),We();let o=ye.beginStartup(a),s=!1,c=performance.now();try{await hs(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:t}=await o.backlinksReady;t&&un.push(`backlink-index`);let i=0;for(let t of e)Ix(t)||It.peek(t)?.kind!==`renamed`&&(It.setDeleted(t),i++);i>0&&b.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`);let a=performance.now(),c=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,l=ve?cP(n):new Set,d=e=>{e.some(e=>c.test(V(n,e).split(Ll).join(`/`)))&&(ke&&clearTimeout(ke),ke=setTimeout(()=>{ke=null;try{IJ(r,n).then(e=>{e>0&&(b.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),Oe?.signal(`files`))}).catch(e=>b.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=cP(n);if(!(e.size!==l.size||[...e].some(e=>!l.has(e))))return;l=e,ve.rebuildIgnorePatterns().then(t=>{t.ok?(b.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),Oe?.signal(`files`)):b.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>b.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){b.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};rn=await hs(`ok.boot.seed-walk`,void 0,async()=>nI(n,tn,ve,{onRawBatch:d})),IJ(r,n).then(e=>{e>0&&b.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>b.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=u??su();IJ(e,e,oP(e)).then(e=>{e>0&&b.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>b.warn({err:e},`[in-place-skills] global copy re-sync failed`))}HI(`seedWalkMs`,Math.round(performance.now()-a));{let e=H(n),t=0;for(let[n]of It.entries()){if(!JX(n))continue;let r=H(e,`${n}${wx(n)}`);MO(r,e)&&U(r)&&(It.delete(n),t++)}t>0&&b.info({count:t},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let f=await ye.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&un.push(`tag-index`);let p=0;try{v===void 0?await QX({contentDir:n,contentFilter:ve,basenameIndex:he,onSkip:(e,t,n)=>{p++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):iSe({contentDir:n,basenameIndex:he,onSkip:(e,t,n)=>{p++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),p>0&&(b.warn({count:p},`[basename-index] startup seed completed with ${p} skipped entries — embeds under inaccessible subtrees will not resolve`),un.push(`basename-index-partial`))}catch(e){b.error({err:e},`[basename-index] startup seed failed`),un.push(`basename-index`)}})}catch(e){if(b.error({err:e},`[server] disk bridge watcher failed to start`),un.push(`file-watcher`),!s){let e=await ye.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&un.push(`tag-index`)}}finally{HI(`indexesMs`,Math.round(performance.now()-c)),rn&&UI(`fileCount`,rn.getFileIndex().size)}try{an=await PFe(r,async({trigger:e})=>{if(b.info({trigger:e},`[batch] begin trigger=${e}`),yse(),A.flushPendingStores(),await Se.flushPendingGitCommit(),D(!0),be.current){let e=S(),t=B5(r).branch??e,n=[];for(let[e,t]of A.documents){if(Ix(e))continue;let r=null;if(t.transact(()=>{r=Kt(e)},bLe),r===null)continue;let i=C(e)??r;n.push({docName:e,markdown:r,diskSnapshot:i})}if(n.length>0)try{let r=await Yce(be.current,e,ix.id,n,t);r&&(Sse(),b.info({count:n.length,branch:e,sha:r.slice(0,8)},`[history] parked ${n.length} docs on ${e} → ${r.slice(0,8)}`))}catch(e){b.error({err:e},`[shadow] park failed`)}}},async e=>{let t=en.length,i=e.newBranch??`main`;if(b.info({kind:e.batchKind,headMoved:e.headMoved,docs:t,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${t}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(D(!1),await nn(),e.headMoved&&e.newHead){let t=SLe(r,H(n),e.oldHead,e.newHead);if(t.size>0){SO(t.keys());for(let[e,n]of t)xO(e,$ne(n.email),n.name,n.email,sd(e));await Se.flushContributors()}}if(await Se.flushDeferredStores(`within-branch`),on!==null)try{await on.reconcileConflictsFromGit()}catch(e){b.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{xse(),en.splice(0,en.length);let t=!1,r;try{E(i),r=await ye.beginBranchSwitch(i),ve.rebuildDirCount();try{let e=0;he.clear(),await QX({contentDir:n,contentFilter:ve,basenameIndex:he,onSkip:(t,n,r)=>{e++,b.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(b.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),un.includes(`basename-index-partial`)||un.push(`basename-index-partial`))}catch(e){b.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,t]of A.documents)if(!Ix(e))try{let r=NO(e,n);if(!U(r)){let n=C(e)??``,r=Kt(e)??``;if(r!==n&&be.current){let t=be.current;queueMicrotask(()=>{lx(t,p??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{Cb(),b.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{b.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}t.getMap(`lifecycle`).set(`status`,`deleted-upstream`),b.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=W(r,`utf-8`);qt(e,a),w(e,a),b.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){b.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}b.info({branch:i,docCount:A.documents.size},`[branch-switch] loaded branch ${i} (${A.documents.size} docs)`);try{await ye.settleBranchFromDisk(r)}catch(e){ye.abortBranchSwitch(r),b.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(be.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of A.documents)if(!Ix(t))try{let n=await Zce(be.current,i,ix.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=C(t);if(!r)continue;let a=gF({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:qt(t,a.newContent),w(t,a.newContent),e++;break;case`conflicts`:qt(t,a.newContent),w(t,a.newContent),xb(),e++;{let e=A.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){b.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&b.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&be.current)try{let t=Kb(be.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await Vb(be.current).withMutator(async()=>{for(let e of n.split(`
|
|
2042
|
-
`))e&&await t.raw(`update-ref`,`-d`,e)}),b.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){b.error({err:e},`[branch-switch] detached cleanup failed`)}D(!1),await Se.flushDeferredStores(`discard-stale`),t=!0,Oe?.emitBranchSwitched(i)}finally{ye.abortBranchSwitch(r),t||(D(!1),await Se.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&be.current&&t>0){let t=p??`.`;try{let n=await ox(be.current,t,e.oldHead,e.newHead,i);Sb(),b.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){b.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){b.error({err:e},`[server] HEAD watcher failed to start`),un.push(`head-watcher`)}function l(e){for(let t of e)try{let e=jO(V(n,B(r,t)));if(e.startsWith(`..`))continue;let i=vx(e),a=A.documents.get(i);if(!a)continue;let o=Kt(i);o===null?b.warn({docName:i,file:t},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),b.info({docName:i,file:t},`[sync] marked loaded content conflict`)}catch(e){b.warn({err:e,file:t},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let t of e)try{let e=jO(V(n,B(r,t)));if(e.startsWith(`..`))continue;let i=A.documents.get(vx(e));i&&Jt(i)}catch(e){b.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=FB(r);b.debug({resetAmbientCredentials:f,originKind:NB(r).kind},`[sync] ambient credential-chain reset decision at boot`);let m=tc(h,{resetAmbient:f}),g=O(),_=k();g.mode!==`off`&&b.info({mode:g.mode,source:g.source},`[sync] mode active at boot`);try{on=new _Le({projectDir:r,contentDir:n,contentFilter:ve,contentRoot:p,mcpTomlEditor:e.mcpTomlEditor,mode:g.mode,pullIntervalSeconds:e.pullIntervalSeconds??_.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds??_.pushIntervalSeconds,credentialConfig:m,cc1Broadcaster:Oe,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{D(e),e||Se.flushDeferredStores(`within-branch`).catch(e=>{b.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{b.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:l,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=be.current;n&&await cx(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=be.current;n&&await cx(n,p??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{b.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await ws({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:qte(t.error),configPath:ss(`project-local`,r)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await on.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),on=null}qe(`files`),ye.announceReadyViews();let x=VI();x!==void 0&&HI(`readyMs`,x),se()}return dn().then(()=>{Ze=!0,Ve(),ut(),gt()},e=>{Qe=!0,$e.abort(),st({status:`failed`,indexCount:0}),ye.close(),We(),He(e)}),{hocuspocus:A,durabilityState:x,sessionManager:we,nativeApi:Te,localApi:Ee,cc1Broadcaster:Oe,agentFocusBroadcaster:Ae,agentPresenceBroadcaster:je,maintenanceCoordinator:xe,contentFilter:ve,basenameIndex:he,serverInstanceId:de,destroy:ln,ready:Ue,generatedIndexSweepReady:ot,degraded:un,lockDir:fe,get syncEngine(){return on},getLinkPreviewsEnabled:ae,resolveEmbed:ge,acpRegistry:pe,acpPermissions:me}}function c9(e){return e/1048576}function CLe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:c9(e.rss),heapTotalMb:c9(e.heapTotal),heapUsedMb:c9(e.heapUsed),externalMb:c9(e.external),arrayBuffersMb:c9(e.arrayBuffers)}}}let l9=null,u9=null,d9=null;const f9=1e6;let p9=null,m9=null;ms(()=>{l9=null,u9=null,d9=null,p9?.disable(),p9=null,m9=null});function wLe(){if(l9)return;let e=Rs().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss, external, array_buffers}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=CLe();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),l9=e}function TLe(){if(!u9){let e=Rs().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!p9){p9=Bne({resolution:20}),p9.enable();return}e.observe(p9.percentile(50)/f9,{stat:`p50`}),e.observe(p9.percentile(99)/f9,{stat:`p99`}),p9.reset()}),u9=e}if(!d9){let e=Rs().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=m9;if(m9={cpu:t,hrtimeNs:n},!r)return;let i=Number(n-r.hrtimeNs)/1e3;i<=0||(e.observe((t.user-r.cpu.user)/i,{mode:`user`}),e.observe((t.system-r.cpu.system)/i,{mode:`system`}))}),d9=e}}const h9=R(`skill-migrate`);function g9(e){return[{host:`agents`,root:g},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=GE.indexOf(e.host),r=GE.indexOf(t.host);return(n===-1?GE.length:n)-(r===-1?GE.length:r)||e.host.localeCompare(t.host)})}const ELe=g9(ci),DLe=g9(Qa);function OLe(e,t){return U(H(e,to(t)))}function kLe(e,t){Es(z(t),{recursive:!0});try{ys(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;ks(e,t,{recursive:!0}),As(e,{recursive:!0,force:!0})}}function ALe(e,t,n){let r=EN(e,t,n);switch(r.kind){case`absent`:return{kind:`absent`};case`other`:return{kind:`occupied`,by:`different`};case`symlink`:return r.resolution===`target`?{kind:`store-link`}:{kind:`occupied`,by:`foreign-link`};case`dir`:return r.identity===`different`?{kind:`occupied`,by:`different`}:{kind:`same-copy`}}}function _9(e,t){let n;try{n=G(H(e,`.ok`,`skills`))}catch{n=H(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!G(H(e,t.dir)).startsWith(n+Ll)}catch{return!0}}).map(e=>e.name))}async function v9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??ELe,a={migrated:[],skipped:[]};if(!U(n))return a;let o;try{o=Ql(n)}catch{return a}let s=V(t,n).split(Ll).join(`/`),c=new Set;for(let[e,n]of Object.entries(NJ(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Vr.test(e)||CD.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=H(n,e);if(!U(B(o,`SKILL.md`)))continue;let s=zE(o)?.contentHash;if(s===void 0)continue;let l=G(o),u=i.map(({host:n,root:r})=>{let i=H(t,r);return{host:n,root:r,path:B(i,e),escapes:PN(t,i),state:ALe(B(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>OLe(t,e.root));if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?As(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&As(d.path,{recursive:!0,force:!0}),kLe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(As(e.path,{recursive:!0,force:!0}),ks(d.path,e.path,{recursive:!0}));await _k(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),h9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),h9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const y9=R(`skill-reconcile`),jLe=CD;function b9(){let e=[];for(let t of Bi){let n=ci[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:g,editor:null}),e}function MLe(e,t){let n=V(e,H(t));return Nl(n)?H(t):n}function x9(e){let{frontmatter:t,body:n}=po(e),r={};if(t!==``)try{let e=(0,$D.parse)(S(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function NLe(e,t){let n=x9(e),r=x9(t);if(n.body!==r.body)return!1;for(let e of Object.keys(n.fm))if(e in r.fm&&JSON.stringify(n.fm[e])!==JSON.stringify(r.fm[e]))return!1;return!0}function S9(e,t){let n=C9(e),r=C9(t);if(n.length!==r.length)return!1;let i=0;for(let a=0;a<n.length;a+=1){if(n[a]!==r[a])return!1;let o=n[a],s=B(e,o),c=B(t,o);if(i+=ru(s).size+ru(c).size,i>1048576)return!1;let l=W(s),u=W(c);if(!l.equals(u)&&(o!==`SKILL.md`||!NLe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function C9(e,t=``){let n=[];for(let r of Ql(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...C9(B(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function w9(e,t,n){As(t,{recursive:!0,force:!0}),Es(e,{recursive:!0}),Ss(MLe(e,n),t,`dir`)}function T9(e,t){try{let n=$l(e);return H(Nl(n)?n:H(z(e),n))===H(t)}catch{return!1}}function PLe(e,t){try{let n=$l(e),r=Nl(n)?H(n):H(z(e),n);if(!U(r))return!1;let i=V(H(t),r);return i!==``&&(i.startsWith(`..`)||Nl(i))}catch(t){return y9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const FLe=[...Bi,`agents`];function ILe(e){for(let t of FLe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function LLe(e){let{projectDir:t,skillsRoot:n}=e;if(!U(n))return;let r;try{r=Ql(n)}catch{return}let i=b9();for(let e of r){let r=ILe(e);if(r===null)continue;let a=H(n,e),o=H(n,r);if(U(o))try{let n=Kl(a);if(n.isSymbolicLink()||!n.isDirectory()||!U(B(a,`SKILL.md`))||!U(B(o,`SKILL.md`))||!S9(o,a))continue;for(let{rel:n}of i){let r=H(t,n);if(PN(t,r))continue;let i=B(r,e);T9(i,a)&&w9(r,i,o)}As(a,{recursive:!0,force:!0}),y9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){y9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function RLe(e){let{projectDir:t,skillsRoot:n}=e,r={healed:[],replaced:[],orphansRemoved:[],skipped:[]},i=new Map,a=(e,t)=>{if(t===null)return;let n=i.get(e)??new Set;n.add(t),i.set(e,n)};for(let{rel:e,editor:i}of b9()){let o=H(t,e);if(!U(o)||PN(t,o))continue;let s;try{s=Ql(o)}catch(e){y9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(jLe.has(e))continue;let t=B(o,e),s=H(n,e),c=U(s);try{let l=Kl(t);if(l.isSymbolicLink()){if(T9(t,s)&&c)continue;if(PLe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(w9(o,t,s),r.healed.push({name:e,editor:i})):(As(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Vr.test(e)){y9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&S9(t,s)){w9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){y9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=mk(t);for(let[r,a]of i){let i=H(n,r);if(!U(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await gk(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??kN(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){y9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{LLe({projectDir:t,skillsRoot:n})}catch(e){y9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let E9=null,D9=!1;function O9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function k9(e){if(!O9())return;let t=dP(e);E9=new Gs({currentPath:H(t,`tolerance-telemetry.jsonl`),previousPath:H(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),_e(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};E9?.append(`${JSON.stringify(t)}\n`).catch(e=>{D9||(D9=!0,R(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function A9(){_e(null),await E9?.drain(),E9=null,D9=!1}rs();const zLe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],BLe=[`cache`,`tmp`];function VLe(e){let t=H(e,Ho);if(!(()=>{if(!U(t))return!0;try{return Ql(t).length===0}catch{return!0}})())return[];let n=[];for(let t of zLe)U(H(e,t))&&n.push(t);for(let t of BLe){let r=H(e,t);try{U(r)&&ru(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function HLe(e){let t=Gu(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 j9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function ULe(e){Age();let t=e.projectDir??e.contentDir,n=ySe({projectDir:t});if(n){let e=n.telemetry.attributeDenylist,t=[];for(let n of e){t.push(n);for(let e=1;e<=5;e++)t.push(`${`*.`.repeat(e)}${n}`)}Vs.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}Ls({localSink:n?.telemetry}),k9(t),wLe(),TLe();let{kind:r,gitdir:i}=HLe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=Os(i));let o=_Se(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>hs(`ok.boot`,{attributes:a},async()=>WLe(e)),l=()=>{if(s)try{let e=ns.extract(is.active(),{traceparent:s});return is.with(e,c)}catch(e){R(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async e=>{try{await d(e)}finally{o.uninstall()}},u}async function WLe(e){let t=e.skipAutoInit??!1,n=e.log??R(`boot`),r=e.serverRuntime??{...xte(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((mn(r)||!vt(i))&&!r.allowExternal)throw new dI(`refusing to start: the server would bind a non-loopback address (${(vt(i)?r.bind:i).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let a=pI({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.externalUrl===void 0&&(a.bindLiterals.length===0?n.warn({bind:r.bind},`[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.externalUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.externalUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.`):n.info({bind:r.bind},`[ingress] server.allowExternal is set with no server.externalUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.externalUrl to admit a hostname.`));let o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-D-DD35fh.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=H(p,`.ok`);if(!U(H(m,`config.yml`)))throw new J6(U(m)?`config`:`okdir`,p);let h=H(m,`.gitignore`);U(h)||R(`boot`).warn({path:h},"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 g=e.gitPreflight??nw;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof $C||e instanceof ew){let t=e instanceof ew?e.detected:``,r=e instanceof ew?`too_old`:`not_available`;IK(e),n.warn({event:`git_preflight_fail`,platform:e.platform,reason:r,detectedVersion:t},r===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await Is(),await Promise.race([A9(),new Promise(e=>setTimeout(e,j9))]),e}let _=VLe(m);_.length>0&&R(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${Ho}/.`);let v=null,y=s9({getCollabClientCount:()=>v?.getCount()??0,contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:a,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,mcpTomlEditor:e.mcpTomlEditor,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral,configHomedirOverride:e.configHomedirOverride}),{hocuspocus:b,destroy:x,ready:S,degraded:C,lockDir:w,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:ee}=y,te=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),O=e.port??0,k=()=>`http://${te}:${O}`,ne=e.ephemeral?void 0:V6({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>k(),localApi:y.localApi,log:n}),re=c();re.headersTimeout=3e4,re.requestTimeout=6e4;let ie=e.serveContentAssets===!1?void 0:XX({contentFilter:y.contentFilter,contentSirv:lZ(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:$o,assetExtensions:Wo,blocklistExtensions:Wte,ingressPolicy:a}),ae=e.reactShellDistDir?lZ(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,oe=e.ephemeral?null:new aE({contentDir:e.contentDir,localDir:w,globalDir:H(su(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:T,agentPresenceBroadcaster:D,resolveEmbed:y.resolveEmbed,isExcludedPath:e=>y.contentFilter.isExcluded(e),isIgnoredPath:e=>y.contentFilter.isPathIgnored(e),getLoadedDocText:e=>b.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>k(),getMcpStdioCommand:()=>iE(e.localOpCliArgs,O,{log:n}),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,probePiAcpBridge:e.probePiAcpBridge,ensurePiAcpBridge:e.ensurePiAcpBridge,log:n});oe!==null&&await oe.init();let se=`pending`;S.then(()=>{se=`ready`},()=>{se=`failed`});let ce=K6({httpServer:re,hocuspocus:b,nativeApi:y.nativeApi,mcpHttpHandler:ne,ingressPolicy:a,health:{readiness:()=>se,degraded:()=>C},log:n,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:ee,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ie,reactShellMiddleware:ae,ephemeral:e.ephemeral,acpThreadManager:oe}),le=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)};v=mZ(re);let ue=null;if(e.idleShutdownMs!==null){let t=e.idleShutdownMs??18e5,r=e.idleShutdownHandler??(e=>async()=>{await e()});ue=hZ({httpServer:re,counter:v,thresholdMs:t,log:n,onShutdown:r(async()=>{await le(`idle-shutdown`)})})}await M9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:n});let de=[...new Set(i)],fe=de[0],pe=async()=>{await x().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(w)},me=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await me(re,e.port??0,fe??`127.0.0.1`)}catch(e){throw await pe(),e}let he=re.address(),ge=typeof he==`object`&&he?he.port:e.port??0,_e=[];for(let e of de.slice(1)){let t=c();t.headersTimeout=re.headersTimeout,t.requestTimeout=re.requestTimeout;for(let e of re.listeners(`request`))t.on(`request`,e);for(let e of re.listeners(`upgrade`))t.on(`upgrade`,e);try{await me(t,ge,e)}catch(t){n.error({err:t,failedAddress:e,port:ge,alreadyBound:_e.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[..._e,re])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await pe(),t}_e.push(t)}let ve=VI();ve!==void 0&&HI(`httpListenMs`,ve);let ye=re.address(),be=typeof ye==`object`&&ye?ye.port:e.port??0;O=be;let xe=k();d(w,be,xe),n.info({event:`server-listening`,pid:process.pid,port:be,addresses:de,url:xe,lockDir:w},`[boot] listening on ${xe}`);let Se=!1,Ce=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${j9}ms`))},j9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};le=async(e=`unspecified`)=>{if(Se)return;Se=!0,n.info({reason:e,pid:process.pid,lockDir:w},`[server] shutdown initiated (${e})`),se=`draining`;let t=[],r=async(e,r)=>{try{await Ce(e,r)}catch(r){t.push(r),n.warn({err:r,step:e},`bootServer destroy step failed`)}};try{l(w)}catch(e){n.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{v?.detach()}catch(e){n.warn({err:e,step:`collabClientCounter.detach`},`bootServer destroy step failed`)}try{ue?.detach()}catch(e){t.push(e),n.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(oe!==null&&await r(`acpThreads.destroy`,()=>oe.destroy()),await r(`secondaryListeners.close`,async()=>{for(let e of _e)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await r(`mount.shutdown`,()=>ce.shutdown()),ne!==void 0&&await r(`mcpHttpHandler.close`,()=>ne.close()),await r(`mount.wss.close`,()=>new Promise((e,t)=>{ce.wss.close(n=>n?t(n):e())})),await r(`httpServer.closeAllConnections`,async()=>{re.closeAllConnections?.()}),await r(`httpServer.close`,()=>new Promise((e,t)=>{re.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await r(`destroyHocuspocus`,()=>x()),await r(`shutdownTelemetry`,()=>Is()),await r(`teardownToleranceTelemetry`,()=>A9()),await r(`flushLogFileSinks`,()=>Vs.flushAllFileSinks()),t.length>0)throw AggregateError(t,`bootServer destroy completed with errors`)};try{let t=await v9({projectDir:p,skillsRoot:H(e.contentDir,`.ok`,`skills`),inPlaceNames:_9(e.contentDir,aP(e.contentDir))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=su(),t=await v9({projectDir:e,skillsRoot:H(e,`.ok`,`skills`),hostRoots:DLe,inPlaceNames:_9(e,oP(e))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await RLe({projectDir:p,skillsRoot:H(e.contentDir,`.ok`,`skills`)}),r=t.healed.length+t.replaced.length+t.orphansRemoved.length;r>0&&n.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${r} editor skill entr${r===1?`y`:`ies`} to the symlink model.`)}catch(e){n.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:re,destroy:le,lockDir:w,contentDir:e.contentDir,port:be,ready:S,generatedIndexSweepReady:y.generatedIndexSweepReady,degraded:C,didAutoInit:f,serverInstance:y,runtime:JNe(y,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:oe}}async function M9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new dZ(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=e=>e.variant===`working-tree`,s=null;try{let e=Ku(n),t=e?B(e,`MERGE_HEAD`):null;if(!t||!U(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=Zs({baseDir:n,timeout:{block:5e3}});s=new Set(await vb(e,[`diff`,`--name-only`,`--diff-filter=U`]))}}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(s!==null){let e=0;for(let t of a)!o(t)&&!s.has(t.file)&&(i.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:a.length-e})),a=a.filter(e=>o(e)||s?.has(e.file)),a.length===0)return}for(let e of a){let n=vx(e.file),i=null,a=!1;try{i=await t.openDirectConnection(n);let e=i.document;if(!e)continue;let r=e.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),a=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":n}))}catch(e){r.warn({err:e,docName:n},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(i)try{await i.disconnect()}catch(e){r.warn({err:e,docName:n,restored:a},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const GLe=ho;function KLe(e={}){let t=e.home??su(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?U(B(t,`Library`,`Application Support`,`Claude`)):n===`win32`?U(B(r.APPDATA??B(t,`AppData`,`Roaming`),`Claude`)):!1}var N9=t(Ws(),1);const P9=B(su(),`.ok`,`logs`),qLe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function JLe(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],n=e.toLowerCase();if(t.includes(n))return n}return process.env.NODE_ENV===`test`?`silent`:`info`}function YLe(e){ql(e,{recursive:!0})}function F9(){return new Date().toISOString().slice(0,10)}function XLe(e){try{if(ru(e).size<5242880)return}catch{return}for(let t=2;t>=1;t--){let n=t===1?e:`${e}.${t-1}`,r=`${e}.${t}`;try{eu(n,r)}catch{}}try{iu(`${e}.3`)}catch{}}function ZLe(e){try{let t=Date.now(),n=10080*60*1e3,r=Ql(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=ru(B(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{iu(B(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{iu(B(e,t.name)),a-=t.size}catch{}}}catch{}}function QLe(e){YLe(P9);let t=F9(),n=e.filePath??B(P9,`${e.name}.${t}.log`);XLe(n),(e._setTimeout??setTimeout)(()=>ZLe(P9),5e3).unref();let r=N9.default.destination({dest:n,append:!0,sync:!0});return(0,N9.default)({level:JLe(),name:e.name,redact:{paths:qLe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:N9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function $Le(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[N9.default.symbols.streamSym],i=!1,a=()=>{i||(i=!0,n())};if(!r||typeof r.flushSync!=`function`){a();return}let o=()=>{try{r.flushSync?.()}catch{}a()},s=setTimeout(a,t);typeof s.unref==`function`&&s.unref(),typeof r.fd==`number`&&r.fd>=0?(clearTimeout(s),o()):typeof r.once==`function`?r.once(`ready`,()=>{clearTimeout(s),o()}):(clearTimeout(s),o())})}function eRe(e){return B(P9,`${e}.${F9()}.log`)}function tRe(){return P9}function nRe(e){let t=H(e),n=0;for(;n<30;){let e=!1;try{e=U(H(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=z(t);if(r===t)return null;t=r,n+=1}return null}const I9=Du(El),L9=R(`project-git`);var R9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function rRe(e,t){try{return await I9(e,[`var`,`GIT_COMMITTER_IDENT`],XC({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function iRe(e,t){try{let{stdout:n}=await I9(e,[`for-each-ref`,`--count=1`,`refs/`],XC({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return L9.warn({path:t,stderr:z9(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function aRe(e){let t=H(e,`packed-refs`);if(U(t))try{if(W(t,`utf-8`).split(`
|
|
2041
|
+
`)){let r=n.trim();if(r===``)continue;if(r.startsWith(`C\0`)){let[,e,t]=r.split(`\0`);o=e&&t?{name:e,email:t}:null;continue}if(!o||!r.endsWith(`.md`)&&!r.endsWith(`.mdx`))continue;let a=H(e,r);if(!PO(a,t))continue;let s=BF(a,t);i.has(s)||U(a)&&i.set(s,o)}return i}function s9(e){o9();let t=e.ingressPolicy??pI({}),{contentDir:n,projectDir:r=n,quiet:i=!0,debounce:a=2e3,maxDebounce:o=1e4,gitEnabled:s=!0,commitDebounceMs:c=3e4,wipRef:l=`refs/wip/main`,configHomedirOverride:u,enableTestRoutes:d=!1,shadowRepo:f,contentRoot:p,destroyTimeoutMs:m=1e4,localOpCliArgs:h,authStreamHeartbeatMs:g,skipStateManifestCheck:_=!1,singleDocRelPath:v,ephemeral:y=!1}=e,b=R(`server`),x=new L5,S=()=>x.getActiveBranch(),C=e=>x.getReconciledBase(e),w=(e,t)=>x.setReconciledBase(e,t),T=e=>x.deleteReconciledBase(e),E=e=>x.switchReconciledBaseScope(e),D=e=>x.setBatchInProgress(e),ee=()=>x.isBatchInProgress();function te(e){let t=ds({absPath:ss(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});if(!t.valid){let n=Lo(t.error)&&t.error.code===`SCHEMA_INVALID`?t.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(n.length>0){let e=n.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}if(e?.requireValid)throw Error(`Project config is invalid`,{cause:t.error});b.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return t.value.content.attachmentFolderPath??`./`}function O(){let e=ds({absPath:ss(`project-local`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)}),t=kte(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||b.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let n=ds({absPath:ss(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});return n.valid||b.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:Fte(n.value.autoSync?.default)??`off`,source:`committed-default`}}function k(){return Kte(ds({absPath:ss(`project-local`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)}).value.autoSync)}function ne(){let e=ds({absPath:ss(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules,t=e?$n(e):Xr;return RFe(r,t.plugins.okf),t}function re(){return ds({absPath:ss(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function ie(){return uL(r,{configHomedirOverride:u,onWarn:e=>b.warn({message:e},`[config] could not read project-local config`)})}function ae(){let e=ds({absPath:ss(`project-local`,r,u),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function oe(){return Ts({cwd:r,homedirOverride:u,warn:e=>b.debug({message:e},`[config] diagnostics read`)})}function se(){for(let e of oe().diagnostics)e.code===`REMOVED_KEY`&&b.warn({scope:e.scope,file:e.file,path:e.path.join(`.`)},`[config] ${e.path.join(`.`)} is no longer read and was ignored. ${e.redirect}`)}function ce(e){return`${eL(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}let le;function ue(e,t){let i;if(e===`__config__/project`||e===`__local__/project`){let t=O();i=t.mode,on?.setMode(t.mode,t.source).catch(n=>{b.warn({err:n,mode:t.mode,docName:e},`[sync] failed to apply autoSync mode from config`)});let n=k();on?.setIntervals(n.pullIntervalSeconds,n.pushIntervalSeconds)}let a=ie();if(Fe.applyConfig({enabled:a.enabled,providerFingerprint:ce(a)}),e===`__config__/project`){try{let e=te({requireValid:!0});ve?.setAttachmentFolderPath(e),le!==void 0&&e!==le&&b.warn({previous:le,next:e},`[content-filter] attachment folder changed — files under the previous folder no longer sync`),le=e}catch(e){b.warn({err:e},`[content-filter] project config invalid — keeping previous attachment admission`)}Oe?.signal(`lint-config`),(t??ne().plugins.okf?.generate?.index===!0)||b5({projectDir:r,contentDir:n,generatedDocNames:Ot(),enabled:!1}).then(e=>{e.ok||b.warn({state:e.status.state},`[index] could not remove Open Knowledge generated-index Git attributes`)}),Ct()}b.info({docName:e,autoSyncMode:i,semanticEnabled:a.enabled},`[config] applied persisted config to in-process consumers`)}Ls();let de=xu(),fe=dP(r),pe=new Od({localDir:fe,log:R(`acp-registry`),fetchImpl:e.acpRegistryFetchImpl}),me=new yd(fe,R(`acp-permissions`));if(uc(fe,{port:0,worktreeRoot:r,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),!_)try{D7({lockDir:fe,shadowRepoDir:qu(r)})}catch(e){throw dc(fe),e}let he=ta(),ge=(e,t)=>he.resolveEmbed(e,t),_e=(e,t)=>{let r=he.resolveEmbed(e,t);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=H(n,r);if(!MO(i,H(n)))return null;try{let e=ru(i);return e.isFile()?e.size:null}catch{return null}},ve,ye,be,xe,Se,Ce,A,we,Te,Ee,De,Oe=null,ke=null,Ae=null,je=null,Me=null,Ne=null,Pe=ie(),Fe=new u_e({loadEmbedder:e.embedderLoader??(()=>{let t=ie();return Xge({keyStore:e.embeddingsKeyStore??null,projectDir:r,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:B(dP(r),`embeddings`),enabled:Pe.enabled,providerFingerprint:ce(Pe)}),Ie=null,Le=new Set,Re=!1,ze=[],Be,Ve,He,Ue=new Promise((e,t)=>{Ve=e,He=t}),We,Ge=new Promise(e=>{We=e});async function Ke(){let e,t=Symbol(`branch-scope-gate-timeout`),n=new Promise(n=>{e=setTimeout(()=>n(t),1e4),e.unref?.()});try{if(await Promise.race([Ge,n])!==t)return S()}finally{e&&clearTimeout(e)}try{return B5(r).branch??null}catch(e){return b.warn({err:e},`[auth] branch scope gate expired and HEAD is unreadable — skipping the branch claim check`),null}}function qe(e){Oe?.signal(e)}let Je,Ye,Xe,Ze=!1,Qe=!1,$e=new AbortController,et=new Set,tt=!1,nt=!1,rt=!1,it=0,at,ot=new Promise(e=>{at=e});function st(e){rt||(rt=!0,at(e))}function ct(){return tt||et.size>0}function lt(){Qe||!Ze||(Je!==void 0&&clearTimeout(Je),Je=setTimeout(()=>{Je=void 0,vt()},500),Je.unref?.())}function ut(){if(Qe){st({status:`cancelled`,indexCount:0});return}tt=!0,nt=!0,Ye=setImmediate(()=>{Ye=void 0,vt()})}let dt,ft,pt=!1,mt=null;async function ht(){let e=be.current;if(!e||pt)return;let t=performance.now();b.info({gitDir:e.gitDir},`[shadow-housekeeping] deferred boot housekeeping started`);try{await qb(e)}catch(e){b.warn({err:e},`failed to write gc config (non-fatal)`)}if(!pt){if(mt)try{let t=Number.parseInt(process.env.OK_BOOT_RENAME_GC_RETRY_INTERVAL_MS??``,10)||1e3,n=!1;for(let r=0;r<30;r++){if(!(await CV(e,mt,{rebuild:!0})).skipped){n=!0;break}if(r===29)break;if(await new Promise(e=>{setTimeout(e,t).unref?.()}),pt)return}n||b.warn({gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild retry budget exhausted (persistent GC contention); rebuild deferred to next boot`)}catch(t){b.warn({err:t,gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild failed; index loaded without GC`)}if(!pt){try{await xe?.runBootMaintenance()}catch(e){b.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}b.info({gitDir:e.gitDir,durationMs:Math.round(performance.now()-t)},`[shadow-housekeeping] deferred boot housekeeping complete`)}}}function gt(){pt||(dt=setImmediate(()=>{dt=void 0,ft=ht().catch(e=>{b.error({err:e},`[shadow-housekeeping] unexpected uncaught failure`)})}))}async function _t(){if(pt=!0,dt!==void 0&&(clearImmediate(dt),dt=void 0),!ft)return;let e,t=new Promise(t=>{e=setTimeout(()=>t(`timeout`),m)});try{if(await Promise.race([ft,t])===`timeout`)throw Error(`shadow housekeeping drain timed out after ${m}ms — abandoning in-flight housekeeping`)}finally{e!==void 0&&clearTimeout(e)}}function vt(){if(Qe||!Ze||!ct())return;if(Xe!==void 0){e.generatedIndexTestHooks?.onKickWhileInFlight?.();return}if(x.isBatchInProgress()){lt();return}let t=tt,n=new Set(et),r=nt;tt=!1,et.clear(),nt=!1;let i=t?{fullSweep:!0}:{fullSweep:!1,directories:n};Xe=(async()=>{let e=await Mt(i,$e.signal);if(e.status===`deferred`){tt=!0,r&&(it+=e.indexCount,nt=!0);return}r&&(it+=e.indexCount,e.status===`completed`&&ct()?nt=!0:st({...e,indexCount:it}))})().catch(e=>{b.warn({err:e},`[index] index regeneration coordinator failed`),r&&st({status:`failed`,indexCount:0})}).finally(()=>{if(Xe=void 0,Qe){r&&st({status:`cancelled`,indexCount:0});return}ct()&&Je===void 0?lt():!ct()&&Je===void 0&&e.generatedIndexTestHooks?.onIdle?.()})}async function yt(){if(!Qe){let e=Xe;Qe=!0,$e.abort(),Je!==void 0&&(clearTimeout(Je),Je=void 0),Ye!==void 0&&(clearImmediate(Ye),Ye=void 0),et.clear(),tt=!1,nt=!1,e===void 0&&st({status:`cancelled`,indexCount:0})}await Xe}function bt(e){Qe||EFe(e)||(et.add(j5(e)),lt())}function xt(e){if(!Qe){for(let t of TFe(e))et.add(t);lt()}}function St(e){let t=rn?.getFileIndex();if(!t){bt(e);return}let n=j5(e);if(P5(t.keys()).has(n)){bt(e);return}xt(j5(n))}function Ct(){Qe||(tt=!0,lt())}function wt(e){let t=rn?.getFileIndex().get(e);if(t)return{title:t.title,description:t.description,type:t.type}}let Tt=!1,Et={origin:xLe,writer:Wce,isConflict:e=>on?.getConflicts().some(t=>o5(t,e,r,n))===!0,getDocument:e=>A.documents.get(e),writeDisk:async(e,t)=>{Es(z(e),{recursive:!0}),await us(e,t,{fs:_s})},registerWrite:(e,t)=>AF(e,MF(t)),noteFileIndex:e=>rn?.mutateFileIndex({kind:e.kind,path:e.absPath,docName:e.docName,content:e.markdown}),signalFiles:()=>qe(`files`),attribute:async(e,t)=>{xO(e,t.id,t.name,t.id),Tt=!0}};function Dt(e){return e===``?k5:`${e}/${k5}`}function Ot(){return[...rn?P5(rn.getFileIndex().keys()):new Set([``])].map(Dt)}function kt(e){let t=ne().plugins.okf?.generate?.index===!0,n=e.state===`ready`||e.state===`not-applicable`;return{enabled:t,active:t&&n,git:e.state===`ready`?{state:e.state,ownership:e.ownership}:{state:e.state}}}function At(){return kt(v5({projectDir:r,contentDir:n,generatedDocNames:Ot()}))}async function jt(e){let t=await b5({projectDir:r,contentDir:n,generatedDocNames:Ot(),enabled:e});if(!t.ok)return{...At(),applied:!1,reason:t.status.state===`conflict`?`git-conflict`:`git-unavailable`};let i=await ws({cwd:r,scope:`project`,patch:{contentRules:{okf:{generate:{index:e}}}}});if(!i.ok){try{await t.rollback()}catch(e){b.error({err:e},`[index] could not roll back generated-index Git attributes`)}return{...At(),applied:!1,reason:`config-write`}}try{let e=W(i.path,`utf-8`);a5(A.documents.get(`__config__/project`)??null,Tr,e,Se.configPersistenceCtx)}catch(e){b.warn({err:e},`[index] generated-index settings reflection deferred to config watcher`)}return ue(Tr,e),{...At(),applied:!0}}async function Mt(t,i){let a=0,o=t.fullSweep?performance.now():void 0,s=()=>ne().plugins.okf?.generate?.index!==!0;try{if(i.aborted)return{status:`cancelled`,indexCount:0};if(s())return{status:`disabled`,indexCount:0};let c=rn?.getFileIndex();if(!c)return{status:`failed`,indexCount:0};try{if(await e.generatedIndexTestHooks?.beforePlan?.({fullSweep:t.fullSweep,signal:i}),i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};if(x.isBatchInProgress())return{status:`deferred`,indexCount:a};let o=DFe({docs:c,docExtension:wx,currentMarkdownFor:()=>null}),l=v5({projectDir:r,contentDir:n,generatedDocNames:o.map(({directory:e})=>Dt(e))});if(l.state!==`ready`&&l.state!==`not-applicable`)return b.warn({state:l.state},`[index] generated index regeneration paused by Git attributes`),{status:`blocked`,indexCount:a};for(let{directory:r,markdown:c}of o){if(!t.fullSweep&&!t.directories.has(r))continue;if(i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};if(x.isBatchInProgress())return{status:`deferred`,indexCount:a};if(await e.generatedIndexTestHooks?.beforeDecision?.({directory:r,fullSweep:t.fullSweep,signal:i}),i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};let o=Dt(r),l=H(n,`${o}.md`),u;try{u=W(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&b.warn({err:e,path:Os(l)},`[index] could not read the existing generated index; treating it as absent`),u=null}a+=1;let d=await sFe({docName:o,absPath:l,markdown:c,currentMarkdown:u},Et);d===`blocked-conflict`?b.warn({event:`generated-index-regeneration`,outcome:`blocked`,directory:r,reason:`conflict`},`[index] generated index regeneration blocked by active conflict`):b.info({event:`generated-index-regeneration`,outcome:d===`unchanged`?`unchanged`:`written`,directory:r},`[index] generated index regeneration completed`),await e.generatedIndexTestHooks?.afterWrite?.({docName:o,fullSweep:t.fullSweep,signal:i}),!t.fullSweep&&r!==``&&u===null&&xt(j5(r))}}finally{Tt&&=(await Se.waitForPendingCommits(),await Se.flushContributors(),!1),o!==void 0&&(HI(`generatedIndexSweepMs`,Math.round((performance.now()-o)*100)/100),UI(`generatedIndexCount`,a))}return{status:`completed`,indexCount:a}}catch(e){return b.warn({err:e},`[index] index regeneration failed`),{status:`failed`,indexCount:a}}}let Nt=null,Pt=!1,Ft=()=>{try{v7(r,It.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},It=new gIe(void 0,{onEviction:()=>wce(),onSizeChange:e=>Tce(e),onMutate:()=>{!Pt||Nt!==null||(Nt=setTimeout(()=>{Nt=null,Ft()},2e3))}});for(let[e,t]of xIe(r))Ix(e)||JX(e)&&([`.md`,`.mdx`].some(t=>{let r=H(n,`${e}${t}`);return MO(r,H(n))&&U(r)})||It.restore(e,t));Pt=!0;let Lt={current:null},Rt=(e,t)=>{Ix(e)||It.setRenamed(e,t)},zt=e=>{if(!Ix(e)){if(It.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}It.setDeleted(e),Lt.current?.deleted(e)}},Bt=e=>{Ix(e)||It.delete(e)};try{let m=`./`;try{m=te()}catch(e){b.warn({err:e},`[content-filter] invalid attachment folder at boot — using sibling admission`)}le=m,ve=yj({projectDir:r,contentDir:n,singleDocRelPath:v,attachmentFolderPath:m,inPlaceSkillDirs:cP(n),rescanInPlaceSkillDirs:()=>cP(n),skillRootPaths:fhe(n),onAfterRebuild:()=>{ye.refreshContentScope().catch(e=>{R(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),dge(rn).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?R(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):R(`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=>{R(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),ye=new Vhe({projectDir:r,contentDir:n,contentFilter:ve,getGlobalSkillRoots:()=>PV(Se.managedArtifactCtx),signalChannel:qe,getLocalTargetInventory:()=>Lye(rn,n),onRecoveredFileTarget:(e,t)=>{rn&&vIe({watcher:rn,contentDir:n,relativePath:e,exists:t,invalidateReferencedAssetsCache:Me})}}),be={current:f},xe=s?rIe({getShadow:()=>be.current??null,getCurrentBranch:()=>an?.getLastKnownBranch()??null,contentRoot:p??``,projectGitDir:Ku(r)??void 0,isWriterLive:e=>{if(!je&&!we)return R(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(je?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of we?.sessionsForConnection(t)??[])return!0;return!1}}):void 0;let _=null;Se=d7({contentDir:n,projectDir:r,gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:be,ephemeral:y,contentRoot:p,derivedDocumentIndex:ye,configHomedirOverride:u,getCurrentBranch:()=>an?.getLastKnownBranch()??null,resolveEmbed:ge,resolveSize:_e,getPrincipal:()=>Ie,onAgentCommit:()=>Oe?.signal(`session-activity`),onFlushCommit:()=>xe?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{Oe?.emitDiskAck(e,t),!Ix(e)&&(OFe(r,n,e)&&bt(e),m_e(r,n)&&(Me?.(),qe(`files`)))},onConfigRejected:(e,t)=>Oe?.emitConfigValidationRejected(e,t),onConfigPersisted:ue,onManagedSkillPersisted:e=>{let t=ea(e);t?.kind!==`skill`||t.scope!==`global`||(_!==null&&clearTimeout(_),_=setTimeout(()=>{_=null;let e=u??su();IJ(e,e,oP(e)).then(e=>{e>0&&b.info({refreshed:e},`[in-place-skills] post-edit copy re-sync`)}).catch(e=>b.warn({err:e},`[in-place-skills] post-edit copy re-sync failed`))},2e3),_.unref?.())},isRecentlyRemoved:e=>It.has(e),mdManager:e.mdManager,getLossRing:()=>Ce,durabilityState:x}),A=new GPe({quiet:i,debounce:a,maxDebounce:o,extensions:[Se.extension]});let S=A.openDirectConnection.bind(A);A.openDirectConnection=((e,t)=>S(Ex(e),t));let w=A;ze.push(mC(()=>w.documents.size),Yle(()=>Se.getQueueDepths()),Zle(()=>{let e=0;for(let t of w.documents.values())e+=t.directConnectionsCount;return{websocket:w.getConnectionsCount()-e,direct:e}})),$le(),y||(Ne=mIe({getLoadedDocuments:()=>w.documents,forceStore:(e,t)=>Se.forceStore(e,t),getBase:e=>x.getReconciledBase(e),isBatchActive:()=>x.isBatchInProgress(),hasInFlight:e=>x.inFlightFlushCount(e)>0,readDiskBytes:e=>{let t=NO(e,n),r,i;try{r=G(t),i=ru(r).size}catch(t){let n=pc(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new p7(`symlink cycle at content path: ${e}`):t}if(!PO(r,n))throw new p7(`symlink-escape: ${t} resolves outside the content dir`);if(i>524288)throw new p7(`document exceeds the open byte limit: ${e}`);try{return W(r,`utf-8`)}catch(e){if(pc(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let T=A.shouldUnloadDocument.bind(A);A.shouldUnloadDocument=e=>{if(Le.has(e)||Re&&T(e))return!0;let t=e.name;return Ix(t)||C(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:T(e)},Be=async e=>{Le.add(e);try{await A.unloadDocument(e)}finally{Le.delete(e)}},Oe=new Bx(A),Ae=new gE(A),je=new _E(A),we=new JC(A,e.agentSessionOptions);let E=we;ze.push(Qle(()=>({active:E.liveSessionCount,limit:E.sessionLimit})));let D=U5({derivedDocumentIndex:ye,onDocumentSettled:e=>Lt.current?.changed(e)});A.configuration.extensions.push(D);function ee(e,t,n={}){b.warn({reason:e,docName:t,...n},`[auth-rejection] ${e}`)}A.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=iZ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==de)throw ee(`server-instance-mismatch`,e.documentName,{claimedServerInstanceId:r,currentServerInstanceId:de}),new rZ(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${de}`);let i=n?.expectedBranch;if(typeof i==`string`&&i.length>0){let t=await Ke();if(t!==null&&i!==t)throw ee(`branch-mismatch`,e.documentName,{claimedBranch:i,currentBranch:t}),new rZ(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${t}`)}if(!n)return;let a=e.context;typeof n.principalId==`string`&&(Ie&&n.principalId===Ie.id?a.principalId=Ie.id:Ie?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:Ie.id})):a.principalId=n.principalId),typeof n.tabSessionId==`string`&&(a.tabSessionId=n.tabSessionId),a.kind=`human`}}),A.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!jx(e.documentName)&&!Mx(e.documentName))return;let n=e.request,r=n.socket?.remoteAddress;if(r!==void 0&&!mI(r,t))throw ee(`config-doc-admission-denied`,e.documentName,{check:`peer`}),Error(`config-doc admission requires loopback peer (peer=${r}, doc=${e.documentName})`);let i=e.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0;if(!hI(a,t))throw ee(`config-doc-admission-denied`,e.documentName,{check:`host`}),Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${e.documentName})`)}});let O=H(n);function k(e){if(!JX(e))return null;let t=H(O,Dx(e));return MO(t,O)?t:null}A.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await yIe(e.documentName,{recentlyRemovedDocs:It,resolveFilePath:k,fileExists:U})}}),A.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=iZ(e.token);kFe(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>A.documents.get(e)})}}),A.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new T8(e.update);if(t.readVarString(),t.readVarUint()===I8.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${ao} rejected — server-only channel`)}});let se=YX({hocuspocus:A,durabilityState:x,ingressPolicy:t,sessionManager:we,commentDocHooksRef:Lt,contentDir:n,getGeneratedIndexSettingsStatus:At,setGeneratedIndexEnabled:jt,contentFilter:ve,serverInstanceId:de,getFileIndex:()=>rn?rn.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>rn?rn.getAllFilesIndex():new Map,getFileIndexGeneration:()=>rn?.getFileIndexGeneration()??0,mutateFileIndex:e=>{let t=e.kind===`update`?wt(e.docName):void 0;switch(rn?.mutateFileIndex(e),e.kind){case`update`:I5(t,e.content,e.docName)&&bt(e.docName);break;case`create`:case`conflict`:bt(e.docName);break;case`delete`:St(e.docName);break;case`rename`:St(e.oldDocName),bt(e.newDocName);break;case`folder-create`:case`folder-delete`:xt(e.relativePath);break;case`asset-create`:case`asset-delete`:case`file-create`:case`file-update`:case`file-delete`:break;default:EF(e)}},getFolderIndex:()=>rn?rn.getFolderIndex():new Map,getAliasMap:()=>rn?rn.getAliasMap():new Map,getFolderAliasIndex:()=>rn?rn.getFolderAliasIndex():new Map,rescanFiles:()=>rn?.rescanFromDisk(),enableTestRoutes:d,shadowRef:be,flushGitCommit:()=>Se.flushPendingGitCommit(),flushContributors:()=>Se.flushContributors(),getCurrentBranch:()=>an?.getLastKnownBranch()??null,getDiskAckSVs:()=>Oe?.getLatestDiskAckSVsAsBase64()??{},getCollabClientCount:e.getCollabClientCount,contentRoot:p,derivedDocumentIndex:ye,signalChannel:qe,agentFocusBroadcaster:Ae,agentPresenceBroadcaster:je,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>on,localOpCliArgs:h,authStreamHeartbeatMs:g,projectDir:r,resolveEmbed:ge,getBridgeLossReporter:()=>De,getPrincipal:()=>Ie,acpRegistry:pe,loadAcpCustomAgents:()=>kd(fe,R(`acp-registry`)),homeDirOverride:u,forceUnloadDocument:Be,ready:Ue,recentlyRemovedDocs:It,serializeDoc:Kt,evictManagedArtifactLkg:e=>{Se.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Fe,getSemanticSimilarityFloor:()=>ie().similarityFloor,getLinterBaseConfig:()=>ne(),getLinksValidationSetting:()=>re(),getLinkPreviewsEnabled:ae,getConfigDiagnostics:oe,embeddingsSecretsFile:sL(u),readSemanticProviderConfig:ie,ephemeral:y,onReferencedAssetsCacheInvalidator:e=>{Me=e}});A.configuration.extensions.push(se),Te=se.nativeApi,Ee=se.localApi;let ce=ds({absPath:ss(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for bridge guards`)}),me=ce.value.bridge.deferGuard.enabled,he=ce.value.bridge.fixedPoint.enabled,ke=ce.value.bridge.preDrain.enabled;Ce=ce.value.lossCapture.enabled?new use({projectDir:r,maxBytes:ce.value.lossCapture.maxBytes}):void 0,ce.value.bridge.lossDetector.enabled&&(De=ile({shadow:()=>be.current,ring:Ce,getBranch:()=>an?.getLastKnownBranch()??`main`,contentRoot:p??``}),we.attachBridgeLossReporter(De)),A.configuration.extensions.push(b7({mdManager:os,schema:as,shadowRef:be,contentRoot:p,getCurrentBranch:()=>an?.getLastKnownBranch()??null,resolveEmbed:ge,resolveSize:_e,deferGuardEnabled:me,lossDetectorEnabled:ce.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:he,preDrainEnabled:ke,lossRing:Ce})),A.configuration.extensions.push(yLe()),A.configuration.extensions.push(oFe({getSyncEngine:()=>on,projectDir:r,contentDir:n}))}catch(e){for(let e of ze.splice(0))e();throw Ne?.dispose(),Ne=null,dc(fe),e}let Vt=null,Ht=new Map,Ut=[];function Gt(e,t){let n=H(e,`rescue`),r=H(n,Dx(t));return MO(r,n)?r:null}function Kt(e){let t=A.documents.get(e);return t?bF(t):null}let qt=(e,t)=>vF(x,A,e,t,ge,_e,De);function Jt(e){if(!Xx(e)||on?.getConflicts().some(t=>o5(t,e.name,r,n)))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Yt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of A.documents){if(Ix(n))continue;let r=A.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{dF(r,i,ge,n)},uF)}catch(t){b.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},Xt=null,Zt=e=>{e&&(Xt===null&&(Xt=new Set,setImmediate(()=>{let e=Xt;if(Xt=null,e)try{for(let t of e)Yt(t)}catch(t){b.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Xt.add(e))};function Qt(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 EF(e)}}async function $t(e){try{switch(e.kind){case`create`:b.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await ye.recordDiskUpsert(e.docName,e.content),qe(`files`),bt(e.docName),Bt(e.docName);break;case`update`:{let{docName:t,content:n}=e;I5(e.previousIndexedFields,n,t)&&bt(t);let r=A.documents.get(t);if(!r){await ye.recordDiskUpsert(t,n);return}let i=C(t)??``,a=Kt(t)??i,o=gF({docName:t,base:i,ours:a,theirs:n}),s=MF(i).slice(0,6),c=MF(a).slice(0,6),l=MF(n).slice(0,6);switch(b.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:Jt(r),await ye.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{qt(t,o.newContent),w(t,o.newContent),bb(),Jt(r),e=!0}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),w(t,n),Jt(r)}e&&await ye.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{qt(t,o.newContent),w(t,n),bb(),Jt(r),e=!0}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),w(t,n),Jt(r)}e&&await ye.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{qt(t,o.newContent),w(t,o.newContent),bb(),xb(),e=!0}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),w(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}e&&await ye.recordDiskUpsert(t,n);break}case`refused`:{xb();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=A.documents.get(t);if(!n){await ye.recordDiskDelete(t),qe(`files`),zt(t),St(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=C(t)??``,i=Kt(t)??``,a=i!==r;if(a&&be.current){let e=be.current,n=an?.getLastKnownBranch()??`main`;queueMicrotask(()=>{lx(e,p??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{Cb(),b.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{b.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),T(t),await ye.recordDiskDelete(t),b.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),A.closeConnections(t),await Be(n),qe(`files`),zt(t),St(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=A.documents.get(t);if(i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}T(t),w(n,r),await ye.recordDiskRename(t,n,r),b.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),qe(`files`),Rt(t,n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`})),St(t),bt(n);break}case`conflict`:{let{docName:t}=e,n=A.documents.get(t);if(!n)return;let r=Kt(t);r===null?b.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):w(t,r);let i=n.getMap(`lifecycle`);i.set(`status`,`conflict`),i.set(`reason`,`conflict-markers`),b.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:he.add(e.relativePath),qe(`files`),Zt(Al(e.relativePath));break;case`asset-delete`:he.remove(e.relativePath),qe(`files`),Zt(Al(e.relativePath));break;case`folder-create`:case`folder-delete`:qe(`files`),xt(e.relativePath);break;case`file-create`:case`file-update`:await ye.recordFileTargetUpsert(e.relativePath),Me?.(),qe(`files`);break;case`file-delete`:await ye.recordFileTargetDelete(e.relativePath),Me?.(),qe(`files`);break;default:EF(e)}}catch(t){let n=Qt(e);b.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let en=[];async function tn(e){if(ee()){en.push(e);return}await $t(e)}async function nn(){let e=en.splice(0,en.length);for(let t of e)await $t(t)}let rn=null,an=null,on=null,sn=null;async function cn(e){if(A.documents.size===0)return;let t=!1,n=new Promise(e=>{A.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(A.documents.keys());A.closeConnections(),A.flushPendingStores();for(let e of A.documents.values())e.getConnectionsCount()===0&&A.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 i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(A.documents.keys()),i=[],o=[];if(be.current){for(let e of n)if(!Ix(e))try{let t=Kt(e);if(t===null){b.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=Gt(be.current.gitDir,e);if(!n){b.warn({docName:e,gitDir:be.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}ql(z(n),{recursive:!0}),au(n,t,`utf-8`),Cb(),i.push(e),b.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),b.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else b.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function ln(){return sn||(sn=(async()=>{let e=Date.now(),t=[];Re=!0;try{await yt()}catch(e){b.warn({err:e},`[index] generated index shutdown drain failed`),t.push({phase:`generated-index-drain`,error:String(e)})}for(let e of ze.splice(0))e();try{await Ne?.dispose()}catch(e){b.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Ne=null;try{lc(fe)}catch(e){b.warn({err:e},`[server] failed to mark server.lock draining`)}xe?.destroy();try{await _t()}catch(e){b.warn({err:e},`[shadow-housekeeping] shutdown drain failed`),t.push({phase:`shadow-housekeeping-drain`,error:String(e)})}if(Nt!==null&&(clearTimeout(Nt),Nt=null),Pt)try{v7(r,It.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let n,i=await Promise.race([Ue.then(()=>`completed`,e=>(b.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{n=setTimeout(()=>e(`timeout`),5e3)})]);n!==void 0&&clearTimeout(n),i===`timeout`&&b.warn({},`[server] init did not complete within 5s during shutdown`);let a=A.documents.size;try{try{try{ke&&=(clearTimeout(ke),null),an&&=(await an.unsubscribe(),null),rn&&=(await rn.unsubscribe(),null);for(let{docName:e,cleanup:t}of Ut)try{await t()}catch(t){b.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Ut.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{Oe?.destroy(),je?.destroy(),Vt&&=(await Vt.disconnect(),null);for(let[e,t]of Ht)try{await t.disconnect()}catch(t){b.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Ht.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await we.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await ble()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await cn(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-3 flush failed`)}ye.close();let e;try{await Promise.race([(async()=>{await Se.flushPendingGitCommit(),await Se.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{on&&=(await on.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(be.current){let e;try{await Promise.race([Vb(be.current).drain(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`shadow mutator drain timeout`)),m)})])}catch(e){t.push({phase:`shadow-mutator-drain`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-5 shadow mutator drain failed`)}finally{e!==void 0&&clearTimeout(e)}try{let e=(await nc({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&au(H(be.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{Rce(be.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let n=Date.now()-e;t.length===0?b.info({documentCount:a,durationMs:n},`[server] shutdown flushed ${a} documents in ${n}ms`):b.warn({documentCount:a,durationMs:n,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${n}ms with ${t.length} phase error(s)`)}}finally{try{dc(fe,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await Is()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),sn)}let un=[];async function dn(){try{Ie=await m7(r),b.info({principalId:Ie.id},`[server] principal loaded`)}catch(e){b.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!be.current)try{be.current=await Yb(r,{deferGcConfig:!0}),b.info({gitDir:be.current.gitDir},`[server] history repo initialized at ${be.current.gitDir}`)}catch(e){b.error({err:e},`[server] history repo init failed`),un.push(`shadow-repo`)}if(be.current)try{let e=$B(be.current.gitDir);SV(be.current.gitDir,e),iV(be.current.gitDir,e),mt=e,b.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){b.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(be.current)try{await Kb(be.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`)){b.warn({},`[server] history repo appears corrupted — reinitializing`);try{be.current=await Yb(r,{deferGcConfig:!0})}catch(e){b.error({err:e},`[server] history repo reinit failed`),be.current=void 0,un.includes(`shadow-repo`)||un.push(`shadow-repo`)}}else b.error({err:e},`[server] history repo check failed (transient?)`)}if(be.current){let e=be.current,t=jO(V(r,n))||`.`;setTimeout(()=>{$b(e,t).catch(e=>{b.debug({err:e},`[shadow] fan-out index warm-up failed (non-fatal)`)})},3e3).unref()}if(be.current)try{let e=H(be.current.gitDir,`last-known-head`),t=null;try{t=W(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await nc({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await nc({baseDir:r,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}b.info({lastKnownHead:t,currentHead:n,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=import`);try{await ox(be.current,p??``,t,n,e),Sb()}catch(e){b.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else b.info({currentHead:n},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=noop`);try{au(e,n,`utf-8`)}catch(e){b.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){b.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=Yye(n,r);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;b.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){b.error({err:e},`[server] managed rename recovery failed`),un.push(`managed-rename-recovery`)}try{let e=ZL(r);(e.deleted>0||e.errors>0)&&b.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){b.error({err:e},`[server] upload-tempfile sweep failed`),un.push(`upload-tempfile-sweep`)}try{Vt=await A.openDirectConnection(ao),Oe?.emitServerInfo(de,S())}catch(e){b.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),un.push(`cc1-push`)}let t=y?[]:Mi;for(let e of t)try{let t=await A.openDirectConnection(e);Ht.set(e,t)}catch(t){b.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),un.push(`config-doc:${e}`)}let i=new Map([[Tr,ss(`project`,r)],[Yee,ss(`project-local`,r)],[hte,ss(`user`,r,u)]]);for(let e of t){let t=i.get(e);if(t)try{b.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await Y8(t,t=>{let n=A.documents.get(e);b.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=a5(n??null,e,t,Se.configPersistenceCtx);b.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),ue(e)});Ut.push({docName:e,cleanup:n}),b.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){b.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),un.push(`config-file-watcher:${e}`)}}if(!y){let e=null,t=t=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,ye.refreshGlobalSkillNodes().catch(e=>{b.warn({err:e,docName:t},`[backlinks] global skill bundle re-ingest failed`)})},300)},n=(e,n)=>{let r=zV(e,Se.managedArtifactCtx);if(!r)return;let i=WV(A.documents.get(r)??null,r,n,Se.managedArtifactCtx);b.info({docName:r,outcome:i},`[managed-artifact-watcher] external change`),qe(`files`),Wt(r)&&t(r)},r=e=>{let n=zV(e,Se.managedArtifactCtx);qe(`files`),n&&Wt(n)&&t(n)};try{let e=PV(Se.managedArtifactCtx),t=await iIe(e,n,r);Ut.push({docName:`__skill-files__`,cleanup:t}),b.info({roots:e},`[managed-artifact-watcher] skills started`)}catch(e){b.warn({err:e},`[managed-artifact-watcher] skills failed to start`),un.push(`managed-artifact-watcher:skills`)}try{let e=H(jV(Se.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await Y8(e,()=>{qe(`files`)});Ut.push({docName:`__skill-state__`,cleanup:t}),b.info({path:e},`[skill-state-watcher] started`)}catch(e){b.warn({err:e},`[skill-state-watcher] failed to start`),un.push(`skill-state-watcher`)}}try{let e=H(n,`.okignore`),t=H(r,`.gitignore`),i=null;try{let e=Ol(`git`,[`rev-parse`,`--git-common-dir`],XC({cwd:r,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=B(H(r,e.stdout.trim()),`info`,`exclude`);U(z(t))&&(i=t)}}catch{}let a=i?[e,t,i]:[e,t],o=b;o.info({okignorePath:e,gitignorePath:t,gitInfoExcludePath:i,ephemeral:y},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=y?null:await ZPe(a,(t,n)=>{(async()=>{if(t===e)try{let e=a5(A.documents.get(`__config__/okignore`)??null,wi,n,Se.configPersistenceCtx);o.info({docName:wi,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:V(r,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await ve.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:V(r,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),Oe?.signal(`files`);else{let e=V(r,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),Oe?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:V(r,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Ut.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:t},`[ignore-watcher] multi-path watcher started`))}catch(e){b.warn({err:e,projectDir:r,contentDir:n},`[ignore-watcher] failed to start multi-path watcher`),un.push(`ignore-files-watcher`)}let a=B5(r).branch??`main`;E(a),We();let o=ye.beginStartup(a),s=!1,c=performance.now();try{await hs(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:t}=await o.backlinksReady;t&&un.push(`backlink-index`);let i=0;for(let t of e)Ix(t)||It.peek(t)?.kind!==`renamed`&&(It.setDeleted(t),i++);i>0&&b.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`);let a=performance.now(),c=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,l=ve?cP(n):new Set,d=e=>{e.some(e=>c.test(V(n,e).split(Ll).join(`/`)))&&(ke&&clearTimeout(ke),ke=setTimeout(()=>{ke=null;try{IJ(r,n).then(e=>{e>0&&(b.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),Oe?.signal(`files`))}).catch(e=>b.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=cP(n);if(!(e.size!==l.size||[...e].some(e=>!l.has(e))))return;l=e,ve.rebuildIgnorePatterns().then(t=>{t.ok?(b.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),Oe?.signal(`files`)):b.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>b.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){b.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};rn=await hs(`ok.boot.seed-walk`,void 0,async()=>nI(n,tn,ve,{onRawBatch:d})),IJ(r,n).then(e=>{e>0&&b.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>b.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=u??su();IJ(e,e,oP(e)).then(e=>{e>0&&b.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>b.warn({err:e},`[in-place-skills] global copy re-sync failed`))}HI(`seedWalkMs`,Math.round(performance.now()-a));{let e=H(n),t=0;for(let[n]of It.entries()){if(!JX(n))continue;let r=H(e,`${n}${wx(n)}`);MO(r,e)&&U(r)&&(It.delete(n),t++)}t>0&&b.info({count:t},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let f=await ye.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&un.push(`tag-index`);let p=0;try{v===void 0?await QX({contentDir:n,contentFilter:ve,basenameIndex:he,onSkip:(e,t,n)=>{p++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):iSe({contentDir:n,basenameIndex:he,onSkip:(e,t,n)=>{p++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),p>0&&(b.warn({count:p},`[basename-index] startup seed completed with ${p} skipped entries — embeds under inaccessible subtrees will not resolve`),un.push(`basename-index-partial`))}catch(e){b.error({err:e},`[basename-index] startup seed failed`),un.push(`basename-index`)}})}catch(e){if(b.error({err:e},`[server] disk bridge watcher failed to start`),un.push(`file-watcher`),!s){let e=await ye.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&un.push(`tag-index`)}}finally{HI(`indexesMs`,Math.round(performance.now()-c)),rn&&UI(`fileCount`,rn.getFileIndex().size)}try{an=await PFe(r,async({trigger:e})=>{if(b.info({trigger:e},`[batch] begin trigger=${e}`),yse(),A.flushPendingStores(),await Se.flushPendingGitCommit(),D(!0),be.current){let e=S(),t=B5(r).branch??e,n=[];for(let[e,t]of A.documents){if(Ix(e))continue;let r=null;if(t.transact(()=>{r=Kt(e)},bLe),r===null)continue;let i=C(e)??r;n.push({docName:e,markdown:r,diskSnapshot:i})}if(n.length>0)try{let r=await Yce(be.current,e,ix.id,n,t);r&&(Sse(),b.info({count:n.length,branch:e,sha:r.slice(0,8)},`[history] parked ${n.length} docs on ${e} → ${r.slice(0,8)}`))}catch(e){b.error({err:e},`[shadow] park failed`)}}},async e=>{let t=en.length,i=e.newBranch??`main`;if(b.info({kind:e.batchKind,headMoved:e.headMoved,docs:t,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${t}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(D(!1),await nn(),e.headMoved&&e.newHead){let t=SLe(r,H(n),e.oldHead,e.newHead);if(t.size>0){SO(t.keys());for(let[e,n]of t)xO(e,$ne(n.email),n.name,n.email,sd(e));await Se.flushContributors()}}if(await Se.flushDeferredStores(`within-branch`),on!==null)try{await on.reconcileConflictsFromGit()}catch(e){b.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{xse(),en.splice(0,en.length);let t=!1,r;try{E(i),r=await ye.beginBranchSwitch(i),ve.rebuildDirCount();try{let e=0;he.clear(),await QX({contentDir:n,contentFilter:ve,basenameIndex:he,onSkip:(t,n,r)=>{e++,b.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(b.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),un.includes(`basename-index-partial`)||un.push(`basename-index-partial`))}catch(e){b.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,t]of A.documents)if(!Ix(e))try{let r=NO(e,n);if(!U(r)){let n=C(e)??``,r=Kt(e)??``;if(r!==n&&be.current){let t=be.current;queueMicrotask(()=>{lx(t,p??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{Cb(),b.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{b.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}t.getMap(`lifecycle`).set(`status`,`deleted-upstream`),b.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=W(r,`utf-8`);qt(e,a),w(e,a),b.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){b.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}b.info({branch:i,docCount:A.documents.size},`[branch-switch] loaded branch ${i} (${A.documents.size} docs)`);try{await ye.settleBranchFromDisk(r)}catch(e){ye.abortBranchSwitch(r),b.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(be.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of A.documents)if(!Ix(t))try{let n=await Zce(be.current,i,ix.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=C(t);if(!r)continue;let a=gF({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:qt(t,a.newContent),w(t,a.newContent),e++;break;case`conflicts`:qt(t,a.newContent),w(t,a.newContent),xb(),e++;{let e=A.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){b.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&b.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&be.current)try{let t=Kb(be.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await Vb(be.current).withMutator(async()=>{for(let e of n.split(`
|
|
2042
|
+
`))e&&await t.raw(`update-ref`,`-d`,e)}),b.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){b.error({err:e},`[branch-switch] detached cleanup failed`)}D(!1),await Se.flushDeferredStores(`discard-stale`),t=!0,Oe?.emitBranchSwitched(i)}finally{ye.abortBranchSwitch(r),t||(D(!1),await Se.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&be.current&&t>0){let t=p??`.`;try{let n=await ox(be.current,t,e.oldHead,e.newHead,i);Sb(),b.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){b.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){b.error({err:e},`[server] HEAD watcher failed to start`),un.push(`head-watcher`)}function l(e){for(let t of e)try{let e=jO(V(n,B(r,t)));if(e.startsWith(`..`))continue;let i=vx(e),a=A.documents.get(i);if(!a)continue;let o=Kt(i);o===null?b.warn({docName:i,file:t},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),b.info({docName:i,file:t},`[sync] marked loaded content conflict`)}catch(e){b.warn({err:e,file:t},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let t of e)try{let e=jO(V(n,B(r,t)));if(e.startsWith(`..`))continue;let i=A.documents.get(vx(e));i&&Jt(i)}catch(e){b.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=FB(r);b.debug({resetAmbientCredentials:f,originKind:NB(r).kind},`[sync] ambient credential-chain reset decision at boot`);let m=tc(h,{resetAmbient:f}),g=O(),_=k();g.mode!==`off`&&b.info({mode:g.mode,source:g.source},`[sync] mode active at boot`);try{on=new _Le({projectDir:r,contentDir:n,contentFilter:ve,contentRoot:p,mcpTomlEditor:e.mcpTomlEditor,mode:g.mode,pullIntervalSeconds:e.pullIntervalSeconds??_.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds??_.pushIntervalSeconds,credentialConfig:m,cc1Broadcaster:Oe,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{D(e),e||Se.flushDeferredStores(`within-branch`).catch(e=>{b.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{b.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:l,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=be.current;n&&await cx(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=be.current;n&&await cx(n,p??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{b.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await ws({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:qte(t.error),configPath:ss(`project-local`,r)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await on.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),on=null}qe(`files`),ye.announceReadyViews();let x=VI();x!==void 0&&HI(`readyMs`,x),se()}return dn().then(()=>{Ze=!0,Ve(),ut(),gt()},e=>{Qe=!0,$e.abort(),st({status:`failed`,indexCount:0}),ye.close(),We(),He(e)}),{hocuspocus:A,durabilityState:x,sessionManager:we,nativeApi:Te,localApi:Ee,cc1Broadcaster:Oe,agentFocusBroadcaster:Ae,agentPresenceBroadcaster:je,maintenanceCoordinator:xe,contentFilter:ve,basenameIndex:he,serverInstanceId:de,destroy:ln,ready:Ue,generatedIndexSweepReady:ot,degraded:un,lockDir:fe,get syncEngine(){return on},getLinkPreviewsEnabled:ae,resolveEmbed:ge,acpRegistry:pe,acpPermissions:me}}function c9(e){return e/1048576}function CLe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:c9(e.rss),heapTotalMb:c9(e.heapTotal),heapUsedMb:c9(e.heapUsed),externalMb:c9(e.external),arrayBuffersMb:c9(e.arrayBuffers)}}}let l9=null,u9=null,d9=null;const f9=1e6;let p9=null,m9=null;ms(()=>{l9=null,u9=null,d9=null,p9?.disable(),p9=null,m9=null});function wLe(){if(l9)return;let e=Rs().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss, external, array_buffers}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=CLe();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),l9=e}function TLe(){if(!u9){let e=Rs().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!p9){p9=Bne({resolution:20}),p9.enable();return}e.observe(p9.percentile(50)/f9,{stat:`p50`}),e.observe(p9.percentile(99)/f9,{stat:`p99`}),p9.reset()}),u9=e}if(!d9){let e=Rs().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=m9;if(m9={cpu:t,hrtimeNs:n},!r)return;let i=Number(n-r.hrtimeNs)/1e3;i<=0||(e.observe((t.user-r.cpu.user)/i,{mode:`user`}),e.observe((t.system-r.cpu.system)/i,{mode:`system`}))}),d9=e}}const h9=R(`skill-migrate`);function g9(e){return[{host:`agents`,root:g},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=GE.indexOf(e.host),r=GE.indexOf(t.host);return(n===-1?GE.length:n)-(r===-1?GE.length:r)||e.host.localeCompare(t.host)})}const ELe=g9(ci),DLe=g9(Qa);function OLe(e,t){return U(H(e,to(t)))}function kLe(e,t){Es(z(t),{recursive:!0});try{ys(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;ks(e,t,{recursive:!0}),As(e,{recursive:!0,force:!0})}}function ALe(e,t,n){let r=EN(e,t,n);switch(r.kind){case`absent`:return{kind:`absent`};case`other`:return{kind:`occupied`,by:`different`};case`symlink`:return r.resolution===`target`?{kind:`store-link`}:{kind:`occupied`,by:`foreign-link`};case`dir`:return r.identity===`different`?{kind:`occupied`,by:`different`}:{kind:`same-copy`}}}function _9(e,t){let n;try{n=G(H(e,`.ok`,`skills`))}catch{n=H(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!G(H(e,t.dir)).startsWith(n+Ll)}catch{return!0}}).map(e=>e.name))}async function v9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??ELe,a={migrated:[],skipped:[]};if(!U(n))return a;let o;try{o=Ql(n)}catch{return a}let s=V(t,n).split(Ll).join(`/`),c=new Set;for(let[e,n]of Object.entries(NJ(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Vr.test(e)||CD.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=H(n,e);if(!U(B(o,`SKILL.md`)))continue;let s=zE(o)?.contentHash;if(s===void 0)continue;let l=G(o),u=i.map(({host:n,root:r})=>{let i=H(t,r);return{host:n,root:r,path:B(i,e),escapes:PN(t,i),state:ALe(B(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>OLe(t,e.root));if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?As(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&As(d.path,{recursive:!0,force:!0}),kLe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(As(e.path,{recursive:!0,force:!0}),ks(d.path,e.path,{recursive:!0}));await _k(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),h9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),h9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const y9=R(`skill-reconcile`),jLe=CD;function b9(){let e=[];for(let t of Bi){let n=ci[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:g,editor:null}),e}function MLe(e,t){let n=V(e,H(t));return Nl(n)?H(t):n}function x9(e){let{frontmatter:t,body:n}=po(e),r={};if(t!==``)try{let e=(0,$D.parse)(S(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function NLe(e,t){let n=x9(e),r=x9(t);if(n.body!==r.body)return!1;for(let e of Object.keys(n.fm))if(e in r.fm&&JSON.stringify(n.fm[e])!==JSON.stringify(r.fm[e]))return!1;return!0}function S9(e,t){let n=C9(e),r=C9(t);if(n.length!==r.length)return!1;let i=0;for(let a=0;a<n.length;a+=1){if(n[a]!==r[a])return!1;let o=n[a],s=B(e,o),c=B(t,o);if(i+=ru(s).size+ru(c).size,i>1048576)return!1;let l=W(s),u=W(c);if(!l.equals(u)&&(o!==`SKILL.md`||!NLe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function C9(e,t=``){let n=[];for(let r of Ql(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...C9(B(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function w9(e,t,n){As(t,{recursive:!0,force:!0}),Es(e,{recursive:!0}),Ss(MLe(e,n),t,`dir`)}function T9(e,t){try{let n=$l(e);return H(Nl(n)?n:H(z(e),n))===H(t)}catch{return!1}}function PLe(e,t){try{let n=$l(e),r=Nl(n)?H(n):H(z(e),n);if(!U(r))return!1;let i=V(H(t),r);return i!==``&&(i.startsWith(`..`)||Nl(i))}catch(t){return y9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const FLe=[...Bi,`agents`];function ILe(e){for(let t of FLe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function LLe(e){let{projectDir:t,skillsRoot:n}=e;if(!U(n))return;let r;try{r=Ql(n)}catch{return}let i=b9();for(let e of r){let r=ILe(e);if(r===null)continue;let a=H(n,e),o=H(n,r);if(U(o))try{let n=Kl(a);if(n.isSymbolicLink()||!n.isDirectory()||!U(B(a,`SKILL.md`))||!U(B(o,`SKILL.md`))||!S9(o,a))continue;for(let{rel:n}of i){let r=H(t,n);if(PN(t,r))continue;let i=B(r,e);T9(i,a)&&w9(r,i,o)}As(a,{recursive:!0,force:!0}),y9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){y9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function RLe(e){let{projectDir:t,skillsRoot:n}=e,r={healed:[],replaced:[],orphansRemoved:[],skipped:[]},i=new Map,a=(e,t)=>{if(t===null)return;let n=i.get(e)??new Set;n.add(t),i.set(e,n)};for(let{rel:e,editor:i}of b9()){let o=H(t,e);if(!U(o)||PN(t,o))continue;let s;try{s=Ql(o)}catch(e){y9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(jLe.has(e))continue;let t=B(o,e),s=H(n,e),c=U(s);try{let l=Kl(t);if(l.isSymbolicLink()){if(T9(t,s)&&c)continue;if(PLe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(w9(o,t,s),r.healed.push({name:e,editor:i})):(As(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Vr.test(e)){y9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&S9(t,s)){w9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){y9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=mk(t);for(let[r,a]of i){let i=H(n,r);if(!U(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await gk(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??kN(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){y9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{LLe({projectDir:t,skillsRoot:n})}catch(e){y9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let E9=null,D9=!1;function O9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function k9(e){if(!O9())return;let t=dP(e);E9=new Gs({currentPath:H(t,`tolerance-telemetry.jsonl`),previousPath:H(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),_e(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};E9?.append(`${JSON.stringify(t)}\n`).catch(e=>{D9||(D9=!0,R(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function A9(){_e(null),await E9?.drain(),E9=null,D9=!1}rs();const zLe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],BLe=[`cache`,`tmp`];function VLe(e){let t=H(e,Ho);if(!(()=>{if(!U(t))return!0;try{return Ql(t).length===0}catch{return!0}})())return[];let n=[];for(let t of zLe)U(H(e,t))&&n.push(t);for(let t of BLe){let r=H(e,t);try{U(r)&&ru(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function HLe(e){let t=Gu(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 j9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function ULe(e){Age();let t=e.projectDir??e.contentDir,n=ySe({projectDir:t});if(n){let e=n.telemetry.attributeDenylist,t=[];for(let n of e){t.push(n);for(let e=1;e<=5;e++)t.push(`${`*.`.repeat(e)}${n}`)}Vs.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}Ls({localSink:n?.telemetry}),k9(t),wLe(),TLe();let{kind:r,gitdir:i}=HLe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=Os(i));let o=_Se(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>hs(`ok.boot`,{attributes:a},async()=>WLe(e)),l=()=>{if(s)try{let e=ns.extract(is.active(),{traceparent:s});return is.with(e,c)}catch(e){R(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async e=>{try{await d(e)}finally{o.uninstall()}},u}async function WLe(e){let t=e.skipAutoInit??!1,n=e.log??R(`boot`),r=e.serverRuntime??{...xte(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((mn(r)||!vt(i))&&!r.allowExternal)throw new dI(`refusing to start: the server would bind a non-loopback address (${(vt(i)?r.bind:i).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let a=pI({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.externalUrl===void 0&&(a.bindLiterals.length===0?n.warn({bind:r.bind},`[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.externalUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.externalUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.`):n.info({bind:r.bind},`[ingress] server.allowExternal is set with no server.externalUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.externalUrl to admit a hostname.`));let o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-D-DD35fh.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=H(p,`.ok`);if(!U(H(m,`config.yml`)))throw new J6(U(m)?`config`:`okdir`,p);let h=H(m,`.gitignore`);U(h)||R(`boot`).warn({path:h},"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 g=e.gitPreflight??nw;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof $C||e instanceof ew){let t=e instanceof ew?e.detected:``,r=e instanceof ew?`too_old`:`not_available`;IK(e),n.warn({event:`git_preflight_fail`,platform:e.platform,reason:r,detectedVersion:t},r===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await Is(),await Promise.race([A9(),new Promise(e=>setTimeout(e,j9))]),e}let _=VLe(m);_.length>0&&R(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${Ho}/.`);let v=null,y=s9({getCollabClientCount:()=>v?.getCount()??0,acpRegistryFetchImpl:e.acpRegistryFetchImpl,contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:a,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,mcpTomlEditor:e.mcpTomlEditor,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral,configHomedirOverride:e.configHomedirOverride}),{hocuspocus:b,destroy:x,ready:S,degraded:C,lockDir:w,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:ee}=y,te=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),O=e.port??0,k=()=>`http://${te}:${O}`,ne=e.ephemeral?void 0:V6({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>k(),localApi:y.localApi,log:n}),re=c();re.headersTimeout=3e4,re.requestTimeout=6e4;let ie=e.serveContentAssets===!1?void 0:XX({contentFilter:y.contentFilter,contentSirv:lZ(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:$o,assetExtensions:Wo,blocklistExtensions:Wte,ingressPolicy:a}),ae=e.reactShellDistDir?lZ(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,oe=e.ephemeral?null:new aE({contentDir:e.contentDir,localDir:w,globalDir:H(su(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:T,agentPresenceBroadcaster:D,resolveEmbed:y.resolveEmbed,isExcludedPath:e=>y.contentFilter.isExcluded(e),isIgnoredPath:e=>y.contentFilter.isPathIgnored(e),getLoadedDocText:e=>b.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>k(),getMcpStdioCommand:()=>iE(e.localOpCliArgs,O,{log:n}),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,probePiAcpBridge:e.probePiAcpBridge,ensurePiAcpBridge:e.ensurePiAcpBridge,log:n});oe!==null&&await oe.init();let se=`pending`;S.then(()=>{se=`ready`},()=>{se=`failed`});let ce=K6({httpServer:re,hocuspocus:b,nativeApi:y.nativeApi,mcpHttpHandler:ne,ingressPolicy:a,health:{readiness:()=>se,degraded:()=>C},log:n,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:ee,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ie,reactShellMiddleware:ae,ephemeral:e.ephemeral,acpThreadManager:oe}),le=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)};v=mZ(re);let ue=null;if(e.idleShutdownMs!==null){let t=e.idleShutdownMs??18e5,r=e.idleShutdownHandler??(e=>async()=>{await e()});ue=hZ({httpServer:re,counter:v,thresholdMs:t,log:n,onShutdown:r(async()=>{await le(`idle-shutdown`)})})}await M9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:n});let de=[...new Set(i)],fe=de[0],pe=async()=>{await x().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(w)},me=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await me(re,e.port??0,fe??`127.0.0.1`)}catch(e){throw await pe(),e}let he=re.address(),ge=typeof he==`object`&&he?he.port:e.port??0,_e=[];for(let e of de.slice(1)){let t=c();t.headersTimeout=re.headersTimeout,t.requestTimeout=re.requestTimeout;for(let e of re.listeners(`request`))t.on(`request`,e);for(let e of re.listeners(`upgrade`))t.on(`upgrade`,e);try{await me(t,ge,e)}catch(t){n.error({err:t,failedAddress:e,port:ge,alreadyBound:_e.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[..._e,re])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await pe(),t}_e.push(t)}let ve=VI();ve!==void 0&&HI(`httpListenMs`,ve);let ye=re.address(),be=typeof ye==`object`&&ye?ye.port:e.port??0;O=be;let xe=k();d(w,be,xe),n.info({event:`server-listening`,pid:process.pid,port:be,addresses:de,url:xe,lockDir:w},`[boot] listening on ${xe}`);let Se=!1,Ce=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${j9}ms`))},j9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};le=async(e=`unspecified`)=>{if(Se)return;Se=!0,n.info({reason:e,pid:process.pid,lockDir:w},`[server] shutdown initiated (${e})`),se=`draining`;let t=[],r=async(e,r)=>{try{await Ce(e,r)}catch(r){t.push(r),n.warn({err:r,step:e},`bootServer destroy step failed`)}};try{l(w)}catch(e){n.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{v?.detach()}catch(e){n.warn({err:e,step:`collabClientCounter.detach`},`bootServer destroy step failed`)}try{ue?.detach()}catch(e){t.push(e),n.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(oe!==null&&await r(`acpThreads.destroy`,()=>oe.destroy()),await r(`secondaryListeners.close`,async()=>{for(let e of _e)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await r(`mount.shutdown`,()=>ce.shutdown()),ne!==void 0&&await r(`mcpHttpHandler.close`,()=>ne.close()),await r(`mount.wss.close`,()=>new Promise((e,t)=>{ce.wss.close(n=>n?t(n):e())})),await r(`httpServer.closeAllConnections`,async()=>{re.closeAllConnections?.()}),await r(`httpServer.close`,()=>new Promise((e,t)=>{re.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await r(`destroyHocuspocus`,()=>x()),await r(`shutdownTelemetry`,()=>Is()),await r(`teardownToleranceTelemetry`,()=>A9()),await r(`flushLogFileSinks`,()=>Vs.flushAllFileSinks()),t.length>0)throw AggregateError(t,`bootServer destroy completed with errors`)};try{let t=await v9({projectDir:p,skillsRoot:H(e.contentDir,`.ok`,`skills`),inPlaceNames:_9(e.contentDir,aP(e.contentDir))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=su(),t=await v9({projectDir:e,skillsRoot:H(e,`.ok`,`skills`),hostRoots:DLe,inPlaceNames:_9(e,oP(e))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await RLe({projectDir:p,skillsRoot:H(e.contentDir,`.ok`,`skills`)}),r=t.healed.length+t.replaced.length+t.orphansRemoved.length;r>0&&n.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${r} editor skill entr${r===1?`y`:`ies`} to the symlink model.`)}catch(e){n.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:re,destroy:le,lockDir:w,contentDir:e.contentDir,port:be,ready:S,generatedIndexSweepReady:y.generatedIndexSweepReady,degraded:C,didAutoInit:f,serverInstance:y,runtime:JNe(y,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:oe}}async function M9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new dZ(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=e=>e.variant===`working-tree`,s=null;try{let e=Ku(n),t=e?B(e,`MERGE_HEAD`):null;if(!t||!U(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=Zs({baseDir:n,timeout:{block:5e3}});s=new Set(await vb(e,[`diff`,`--name-only`,`--diff-filter=U`]))}}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(s!==null){let e=0;for(let t of a)!o(t)&&!s.has(t.file)&&(i.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:a.length-e})),a=a.filter(e=>o(e)||s?.has(e.file)),a.length===0)return}for(let e of a){let n=vx(e.file),i=null,a=!1;try{i=await t.openDirectConnection(n);let e=i.document;if(!e)continue;let r=e.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),a=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":n}))}catch(e){r.warn({err:e,docName:n},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(i)try{await i.disconnect()}catch(e){r.warn({err:e,docName:n,restored:a},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const GLe=ho;function KLe(e={}){let t=e.home??su(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?U(B(t,`Library`,`Application Support`,`Claude`)):n===`win32`?U(B(r.APPDATA??B(t,`AppData`,`Roaming`),`Claude`)):!1}var N9=t(Ws(),1);const P9=B(su(),`.ok`,`logs`),qLe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function JLe(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],n=e.toLowerCase();if(t.includes(n))return n}return process.env.NODE_ENV===`test`?`silent`:`info`}function YLe(e){ql(e,{recursive:!0})}function F9(){return new Date().toISOString().slice(0,10)}function XLe(e){try{if(ru(e).size<5242880)return}catch{return}for(let t=2;t>=1;t--){let n=t===1?e:`${e}.${t-1}`,r=`${e}.${t}`;try{eu(n,r)}catch{}}try{iu(`${e}.3`)}catch{}}function ZLe(e){try{let t=Date.now(),n=10080*60*1e3,r=Ql(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=ru(B(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{iu(B(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{iu(B(e,t.name)),a-=t.size}catch{}}}catch{}}function QLe(e){YLe(P9);let t=F9(),n=e.filePath??B(P9,`${e.name}.${t}.log`);XLe(n),(e._setTimeout??setTimeout)(()=>ZLe(P9),5e3).unref();let r=N9.default.destination({dest:n,append:!0,sync:!0});return(0,N9.default)({level:JLe(),name:e.name,redact:{paths:qLe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:N9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function $Le(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[N9.default.symbols.streamSym],i=!1,a=()=>{i||(i=!0,n())};if(!r||typeof r.flushSync!=`function`){a();return}let o=()=>{try{r.flushSync?.()}catch{}a()},s=setTimeout(a,t);typeof s.unref==`function`&&s.unref(),typeof r.fd==`number`&&r.fd>=0?(clearTimeout(s),o()):typeof r.once==`function`?r.once(`ready`,()=>{clearTimeout(s),o()}):(clearTimeout(s),o())})}function eRe(e){return B(P9,`${e}.${F9()}.log`)}function tRe(){return P9}function nRe(e){let t=H(e),n=0;for(;n<30;){let e=!1;try{e=U(H(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=z(t);if(r===t)return null;t=r,n+=1}return null}const I9=Du(El),L9=R(`project-git`);var R9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function rRe(e,t){try{return await I9(e,[`var`,`GIT_COMMITTER_IDENT`],XC({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function iRe(e,t){try{let{stdout:n}=await I9(e,[`for-each-ref`,`--count=1`,`refs/`],XC({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return L9.warn({path:t,stderr:z9(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function aRe(e){let t=H(e,`packed-refs`);if(U(t))try{if(W(t,`utf-8`).split(`
|
|
2043
2043
|
`).some(e=>e.trim()!==``&&!e.startsWith(`#`)))return!0}catch{return!0}try{return Ql(H(e,`refs/heads`)).length>0}catch{return!1}}function z9(e){let t=typeof e==`object`&&e?e:null,n=t?.stderr;return n==null?String(t?.message??e):Buffer.isBuffer(n)?n.toString(`utf-8`):String(n)}async function B9(e,t){if(await iRe(e,t))return;let n=[`commit`,`--allow-empty`,`--no-verify`,`--no-gpg-sign`,`-m`,`Initial commit`],r=await rRe(e,t),i=r?n:[`-c`,`user.name=Open Knowledge`,`-c`,`user.email=noreply@openknowledge.local`,...n];try{await I9(e,i,XC({cwd:t,encoding:`utf-8`})),r||L9.info({path:t},`created initial commit with fallback identity (git identity unset)`)}catch(e){L9.warn({path:t,stderr:z9(e)},`could not create initial commit`)}}async function oRe(e,t){try{let{stdout:n}=await I9(e,[`rev-parse`,`--is-inside-work-tree`],XC({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function sRe(e){let t=H(e);zG(t);let n=H(t,`.git`),r=H(n,`HEAD`),i=!1,a=!1;if(U(n)){if(!ru(n).isDirectory())return{didInit:!1};if(U(r)){if(aRe(n))return{didInit:!1};a=!0}else L9.info({},`detected partial .git/ — running git init to repair`),i=!0}let o;try{o=nw()}catch(e){throw e instanceof $C||e instanceof ew?(IK(e),L9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof ew?`too_old`:`not_available`,detectedVersion:e instanceof ew?e.detected:``},e instanceof ew?`git binary too old`:`git binary not found`)):L9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let s=o.resolvedPath;if(a)return await B9(s,t),{didInit:!1};if(!i&&await oRe(s,t))return{didInit:!1};let c=``;try{c=(await I9(s,[`init`,`--initial-branch=main`,t],XC({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new R9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!U(r))throw new R9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,c);return await B9(s,t),i?(L9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(L9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const V9=R(`project-skill-git`),H9=/^[0-9a-f]{40}$/,cRe=Mr.map(e=>e.replace(/\/$/,``));async function lRe(e){let t=Ku(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(pRe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=Qs(e,{credentialConfig:[]});if((await U9(n)).length===0)return{kind:`nothing-tracked`};try{return await Xs(async()=>{let t=await uRe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await dRe(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await U9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=Qs(e,{gitIndexFile:B(uu(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`),credentialConfig:[]});await a.git.raw([`read-tree`,r]),await a.git.raw([`rm`,`--cached`,`-r`,`--ignore-unmatch`,`--`,...i]);let o=(await a.git.raw([`write-tree`])).trim(),s=await fRe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await PG(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;rc(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${ka}\` skill is regenerated per machine and version-stamped per app build, so tracking it causes recurring sync conflicts. It is now git-ignored.`,f=(await a.git.raw([`commit-tree`,o,`-p`,r,`-m`,d])).trim();if(!H9.test(f))return V9.warn({raw:f},`commit-tree returned invalid SHA — aborting untrack`),{kind:`failed`,error:`commit-tree returned invalid SHA`};try{await n.git.raw([`update-ref`,`refs/heads/${t}`,f,r])}catch(e){return V9.info({branch:t,err:W9(e)},`update-ref CAS failed — ref moved, retry next open`),{kind:`skipped`,reason:`ref-race`}}try{await n.git.raw([`reset`,`-q`,f,`--`,...i])}catch(e){V9.info({err:W9(e)},`real-index reset after untrack failed (cosmetic)`)}return V9.info({dirs:i,commitSha:f},`untracked project-skill projection`),{kind:`untracked`,dirs:i,commitSha:f}})}catch(e){return{kind:`failed`,error:W9(e)}}}async function U9(e){let t=[];for(let n of cRe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function uRe(e){try{let t=(await e.git.raw([`rev-parse`,`--abbrev-ref`,`HEAD`])).trim();return t.length===0||t===`HEAD`?null:t}catch{return null}}async function dRe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return H9.test(t)?t:null}catch{return null}}async function fRe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return H9.test(n)?n:null}catch{return null}}function pRe(e){return U(B(e,`MERGE_HEAD`))||U(B(e,`rebase-merge`))||U(B(e,`rebase-apply`))||U(B(e,`CHERRY_PICK_HEAD`))||U(B(e,`REVERT_HEAD`))}function W9(e){return e instanceof Error?e.message:String(e)}async function mRe(e,t){let n;try{n=Tl(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=z(n),r=0;r<32;r+=1){let n=B(t,`package.json`);if(U(n))try{let t=JSON.parse(await mu(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=z(t);if(r===t)return;t=r}}const hRe=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function G9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of hRe)t=t.replace(e,n);return t}function K9(e,t=0,n=new WeakSet){if(t>=5)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > 5; truncated`};if(typeof e==`object`&&e){if(n.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};n.add(e)}if(e instanceof Error)return{name:e.name,message:G9(e.message)??``,stack:G9(e.stack),code:e.code,cause:e.cause===void 0?void 0:K9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:G9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:G9(String(r.message??``))??``,stack:G9(r.stack),code:r.code,cause:r.cause===void 0?void 0:K9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var q9=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},J9=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},Y9=class extends Error{constructor(e,t){super(`Cannot open with --project ${e}: ${t}`),this.projectRoot=e,this.name=`SingleFileProjectOverrideError`}},X9=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function gRe(e,t={}){if(!gx(e))throw new X9(e);let n;try{n=G(H(e))}catch(t){throw t.code===`ENOENT`?new q9(e):t}if(!ru(n).isFile())throw new J9(e);let r=z(n);if(t.projectRoot!==void 0){let e=H(t.projectRoot);if(!BA(e))throw new Y9(e,`no .ok/config.yml there, so it is not an OpenKnowledge project root`);let r=V(Z9(e),n);if(r.startsWith(`..`)||Nl(r))throw new Y9(e,`${n} is not inside that project's content directory`);return{mode:`project`,projectRoot:e,docName:vx(r.split(Ll).join(`/`)),canonicalFilePath:n}}let i=VA(r);if(i){let e=i.rootPath;return{mode:`project`,projectRoot:e,docName:vx(V(Z9(e),n).split(Ll).join(`/`)),canonicalFilePath:n}}let a=Al(n);return{mode:`ephemeral`,canonicalFilePath:n,contentDir:r,singleDocRelPath:a,docName:vx(a)}}function Z9(e){return H(e,ds({absPath:ss(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}const Q9=`ok-ephemeral-`;function $9(e,t){let n=H(e,`.ok`);return ql(n,{recursive:!0}),au(H(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(t)}\n`,`utf-8`),au(H(n,`.gitignore`),`local/
|
|
2044
2044
|
`,`utf-8`),e}function _Re(e){return $9(Jl(H(uu(),Q9)),e)}export{O6 as $,Bx as $i,MF as $n,bpe as $r,pq as $t,w7 as A,bd as Aa,hw as Ai,TB as An,_N as Ar,QX as At,Z5 as B,XC as Bi,nL as Bn,aM as Br,Bq as Bt,k9 as C,Db as Ca,hD as Ci,ZG as Cn,CN as Cr,eZ as Ct,o9 as D,Km as Da,aE as Di,RG as Dn,vN as Dr,tZ as Dt,s9 as E,Wm as Ea,hE as Ei,LG as En,bN as Er,nZ as Et,b7 as F,gd as Fa,nw as Fi,e_e as Fn,$M as Fr,Kxe as Ft,L5 as G,pue as Gi,hI as Gn,$j as Gr,ive as Gt,VFe as H,GC as Hi,pI as Hn,rM as Hr,Hq as Ht,m7 as I,qu as Ia,mw as Ii,n_e as In,ZM as Ir,YX as It,K6 as J,vC as Ji,sI as Jn,Jj as Jr,cq as Jt,q6 as K,HC as Ki,gI as Kn,Qj as Kr,Cq as Kt,d7 as L,Lu as La,tw as Li,t_e as Ln,QM as Lr,qX as Lt,S7 as M,yd as Ma,$C as Mi,lL as Mn,fN as Mr,vX as Mt,T7 as N,Qu as Na,ew as Ni,oL as Nn,Lme as Nr,_X as Nt,K7 as O,Gm as Oa,lde as Oi,OB as On,hN as Or,aSe as Ot,E7 as P,Zu as Pa,ZC as Pi,r_e as Pn,mN as Pr,kX as Pt,R6 as Q,qx as Qi,JF as Qn,yj as Qr,fq as Qt,Y5 as R,lw as Ri,Wge as Rn,yM as Rr,SX as Rt,M9 as S,Pb as Sa,qfe as Si,HG as Sn,TN as Sr,aZ as St,A9 as T,Tae as Ta,gE as Ti,zG as Tn,Gme as Tr,$X as Tt,U5 as U,JC as Ui,xge as Un,zpe as Ur,Uq as Ut,X5 as V,LC as Vi,dI as Vn,oM as Vr,Wq as Vt,B5 as W,fue as Wi,lI as Wn,Zj as Wr,Rq as Wt,U6 as X,Jx as Xi,aI as Xn,Gj as Xr,Y_e as Xt,G6 as Y,FC as Yi,oI as Yn,Yj as Yr,Z_e as Yt,V6 as Z,J as Zi,EF as Zn,Kj as Zr,vq as Zt,eRe as _,lx as _a,TD as _i,JG as _n,JP as _r,lCe as _t,Y9 as a,dx as aa,ZO as ai,mq as an,qF as ar,C0 as at,GLe as b,Rb as ba,Kfe as bi,$G as bn,uP as br,mZ as bt,$9 as c,ix as ca,kO as ci,RK as cn,OF as cr,WTe as ct,lRe as d,Zb as da,xO as di,IK as dn,pF as dr,d0 as dt,jx as ea,VA as ei,X_e as en,jF as er,k0 as et,R9 as f,tx as fa,wO as fi,NK as fn,mF as fr,c0 as ft,$Le as g,cx as ga,MD as gi,BG as gn,iF as gr,RQ as gt,QLe as h,ux as ha,AD as hi,hK as hn,uF as hr,o$ as ht,X9 as i,Ax as ia,WO as ii,_q as in,AF as ir,rEe as it,D7 as j,kd as ja,_w as ji,uL as jn,pN as jr,XX as jt,x7 as k,Od as ka,iE as ki,PB as kn,gN as kr,iZ as kt,K9 as l,$b as la,EO as li,D_e as ln,vF as lr,GTe as lt,nRe as m,Yb as ma,ND as mi,vK as mn,hF as mr,A1 as mt,J9 as n,Mx as na,CA as ni,gq as nn,GF as nr,j0 as nt,_Re as o,nx as oa,NO as oi,rq as on,nI as or,S0 as ot,sRe as p,fx as pa,CO as pi,yK as pn,gF as pr,u0 as pt,J6 as q,_C as qi,mI as qn,Xj as qr,xq as qt,q9 as r,Ix as ra,SA as ri,hq as rn,BF as rr,I0 as rt,gRe as s,rx as sa,OO as si,iq as sn,KF as sr,_0 as st,Q9 as t,Lx as ta,BA as ti,yq as tn,YF as tr,A0 as tt,mRe as u,ox as ua,TO as ui,FK as un,Xhe as ur,KTe as ut,tRe as v,px as va,ED as vi,YG as vn,WP as vr,$Q as vt,O9 as w,Mce as wa,_E as wi,IG as wn,Xme as wr,rZ as wt,ULe as x,Ib as xa,DD as xi,XG as xn,fP as xr,hZ as xt,KLe as y,Kb as ya,SD as yi,WG as yn,dP as yr,n$ as yt,$Fe as z,iw as zi,YI as zn,iM as zr,Vq as zt};
|
|
2045
|
-
//# sourceMappingURL=src-
|
|
2045
|
+
//# sourceMappingURL=src-BaJbYARI.mjs.map
|