@inkeep/open-knowledge 0.68.13-beta.5 → 0.68.14-beta.1
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-BI8OybyK.mjs → acp-harness-probe-_R_A7pqq.mjs} +2 -2
- package/dist/cli.mjs +6 -6
- package/dist/constants-kDKxgBFE.mjs +2 -0
- package/dist/index.mjs +1 -1
- package/dist/{init-9FGTLE2n.mjs → init-D60fKL1P.mjs} +3 -3
- package/dist/init-DmbjLByi.mjs +1 -0
- package/dist/{launch-json-removal-DE-UAuMX.mjs → launch-json-removal-DZoMh3Z4.mjs} +2 -2
- package/dist/{loader-CF8NswTm.mjs → loader-CjpKP9Bx.mjs} +2 -2
- package/dist/loader-b_Z0WqPc.mjs +1 -0
- package/dist/{open-browser-ACBO68Cc.mjs → open-browser-C8TrsdEd.mjs} +2 -2
- package/dist/{preview-D5Zr9LcW.mjs → preview-BXuQR8WY.mjs} +2 -2
- package/dist/preview-CGhYIq-c.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-Cqznyv0y.js → ActivityModeContent-V-Zp6YCT.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-B09rmPZP.js → AddPropertiesButton-Beyc2cUD.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-Df-Dy2Qy.js → AgentDiffPane-DwKcGEg1.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-BNABz26D.js → CodeMirrorPropInput-CHGRjNxF.js} +2 -2
- package/dist/public/assets/{DocumentContext-6W3WoJ8O.js → DocumentContext-8l8br9Eh.js} +5 -5
- package/dist/public/assets/{EditorModeToggle-C4Uqa423.js → EditorModeToggle-CnOYE3ui.js} +1 -1
- package/dist/public/assets/{EnableSyncConfirmDialog-DAIbgDQ_.js → EnableSyncConfirmDialog-CcCzKuog.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-CaYsO2lb.js → ExcalidrawDocEditor-BE_tRKal.js} +1 -1
- package/dist/public/assets/FeedbackForm-COUWM5yL.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-CX5zemAx.js → ImportSkillDialog-DDGDmBb8.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-C8I2tQLV.js → LintConfigEditor-TW5v1V_p.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-C5U7L_Hh.js +1 -0
- package/dist/public/assets/{ManagedArtifactProperties-BSeDbox7.js → ManagedArtifactProperties-CAbeaOX3.js} +1 -1
- package/dist/public/assets/{MermaidDocEditor-RB-yjEQs.js → MermaidDocEditor-B9JpWBpq.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-D5linTTH.js → PropertyDisplayRow-DmuD-oxI.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-U4DZJCzF.js → SchemaConfigEditor-DXIm2XqB.js} +1 -1
- package/dist/public/assets/{SessionsHost-CEemEnog.js → SessionsHost-CcOfjp1q.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-2X94sSE-.js → SettingsDialogBody-jsoSulYB.js} +1 -1
- package/dist/public/assets/{ShareReceiveMissDialog-fgGulOvX.js → ShareReceiveMissDialog-C9rCS0Vj.js} +1 -1
- package/dist/public/assets/{SkillInstallMenu-9Hz2wVYm.js → SkillInstallMenu-DR_AKxNE.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-DYPNqzzM.js → SkillToolbarControls-e1tYbkEp.js} +1 -1
- package/dist/public/assets/{SourceEditor-DcyBCmZ6.js → SourceEditor-DzDyaixq.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-DXTNzSVY.js → TerminalWindowApp-CXM5m5Wa.js} +1 -1
- package/dist/public/assets/{TextDocEditor-D6GOhYgw.js → TextDocEditor-oQd8R9AP.js} +1 -1
- package/dist/public/assets/{ThreadView-Di-z_Lpo.js → ThreadView-BUTdeOXR.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-CTIhYKSf.js → TimelineDiffPane-0W-Z0tRv.js} +1 -1
- package/dist/public/assets/{agent-diff-store-D1OOJO0v.js → agent-diff-store-CrwhzZYh.js} +1 -1
- package/dist/public/assets/{auth-state-cache-CdLQYIJK.js → auth-state-cache-D5neoYEY.js} +1 -1
- package/dist/public/assets/{client-version-CK0YLgx1.js → client-version-HeAaqVrn.js} +1 -1
- package/dist/public/assets/{comment-chips-CC-ZYzg_.js → comment-chips-DwJR7L-x.js} +1 -1
- package/dist/public/assets/{config-provider-COLAxUXw.js → config-provider-BSxNIrQb.js} +1 -1
- package/dist/public/assets/{doc-undo-manager-B5rjqtZ5.js → doc-undo-manager-D50TrVgg.js} +1 -1
- package/dist/public/assets/index-DoTHqxEX.js +2204 -0
- package/dist/public/assets/{pending-receive-nav-store-BBCEw2x8.js → pending-receive-nav-store-BVVH8Ilz.js} +1 -1
- package/dist/public/assets/{progress-DYW3Dyf1.js → progress-aXAg8oWH.js} +2 -2
- package/dist/public/assets/{selection-context-C6wtLX-y.js → selection-context-oj7m34SC.js} +1 -1
- package/dist/public/assets/{src-cp8fr65R.js → src-Cv3UWDRY.js} +1 -1
- package/dist/public/assets/{telemetry-impl-BIE2Hoo6.js → telemetry-impl-WWrY3Bx_.js} +1 -1
- package/dist/public/assets/{telemetry-startup-DFiY5t9A.js → telemetry-startup-pkZqKl4a.js} +1 -1
- package/dist/public/assets/typing-burst-detector-C_toXZHy.js +8 -0
- package/dist/public/assets/{use-activity-panel-BDPOp8nv.js → use-activity-panel-Dlu0zu7h.js} +1 -1
- package/dist/public/assets/{use-open-skill-O-GeI0vS.js → use-open-skill-WvF2Ant0.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-B8xwr-Lu.js → use-terminal-enabled-iYz6I1VH.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-DGIwDa8C.js → use-timeline-entry-diff-BmTAKKRa.js} +1 -1
- package/dist/public/index.html +19 -19
- package/dist/{repair-launch-json-CWi0Q3EG.mjs → repair-launch-json-FKN5P5yh.mjs} +2 -2
- package/dist/{repair-mcp-configs-DRQ2NqBA.mjs → repair-mcp-configs-DQNpA7pP.mjs} +2 -2
- package/dist/{repair-skills-C0qRuAMi.mjs → repair-skills-BWjReqnW.mjs} +2 -2
- package/dist/repair-skills-BtSE7hBi.mjs +1 -0
- package/dist/{resolve-project-root-kzI3Z6Qa.mjs → resolve-project-root-CGGchFLW.mjs} +2 -2
- package/dist/{skill-teardown-BdwgIxeF.mjs → skill-teardown-Ctp8ECaJ.mjs} +2 -2
- package/dist/{src-DJlTp4dO.mjs → src-BN3sDhQW.mjs} +2 -2
- package/dist/src-BTHE3J_O.mjs +1 -0
- package/dist/{src-CeQWnH8P.mjs → src-aZqW_iIK.mjs} +3 -3
- package/dist/{src-DAz7T8TL.mjs → src-pvuJUuAq.mjs} +1 -1
- package/dist/{start-BwZS9_Ch.mjs → start-CsItXu7n.mjs} +3 -3
- package/dist/start-hfttSK-P.mjs +1 -0
- package/package.json +4 -4
- package/dist/constants-tgED9Jlj.mjs +0 -2
- package/dist/init-Vem_RIae.mjs +0 -1
- package/dist/loader-QGEaLJh_.mjs +0 -1
- package/dist/preview-Mx5xzE-R.mjs +0 -1
- package/dist/public/assets/FeedbackForm-DK89kAAG.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-BaVeaEGS.js +0 -1
- package/dist/public/assets/index-6Bzxg85g.js +0 -2204
- package/dist/public/assets/typing-burst-detector-C2GKzQXa.js +0 -8
- package/dist/repair-skills-DphEbW5P.mjs +0 -1
- package/dist/src-B2P7C3Xm.mjs +0 -1
- package/dist/start-C_XguBtm.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
|
`:`
|
|
@@ -2042,4 +2042,4 @@ native-divergence-injected
|
|
|
2042
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(`
|
|
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-aZqW_iIK.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e,K as t,Ko as n,Qs as r,Uo as i,X as a,fs as o,ms as s,qo as c,ws as l,x as u}from"./src-B2bAQ64a.mjs";import{$ as d,$i as f,$n as p,$r as m,$t as h,A as g,Aa as _,Ai as v,An as y,Ar as b,At as x,B as S,Bi as C,Bn as w,Br as T,Bt as E,C as D,Ca as O,Cn as k,Cr as A,Ct as j,D as M,Da as N,Di as P,Dn as F,Dr as I,Dt as L,E as R,Ea as z,Ei as B,En as V,Er as H,Et as U,F as W,Fi as G,Fn as K,Fr as q,Ft as J,G as Y,Gi as X,Gn as Z,Gr as Q,Gt as $,H as ee,Hi as te,Hn as ne,Hr as re,Ht as ie,I as ae,Ii as oe,In as se,Ir as ce,It as le,J as ue,Ji as de,Jn as fe,Jt as pe,K as me,Ki as he,Kn as ge,Kr as _e,Kt as ve,L as ye,Li as be,Ln as xe,Lr as Se,Lt as Ce,M as we,Ma as Te,Mi as Ee,Mn as De,Mr as Oe,Mt as ke,N as Ae,Na as je,Ni as Me,Nn as Ne,Nr as Pe,Nt as Fe,O as Ie,Oa as Le,Oi as Re,On as ze,Or as Be,Ot as Ve,P as He,Pa as Ue,Pi as We,Pn as Ge,Pr as Ke,Pt as qe,Q as Je,Qi as Ye,Qn as Xe,Qr as Ze,Qt as Qe,R as $e,Ri as et,Rn as tt,Rr as nt,Rt as rt,S as it,Sa as at,Si as ot,Sn as st,Sr as ct,St as lt,T as ut,Ta as dt,Ti as ft,Tn as pt,Tr as mt,Tt as ht,U as gt,Ui as _t,Un as vt,Ur as yt,Ut as bt,V as xt,Vi as St,Vn as Ct,Vr as wt,Vt as Tt,W as Et,Wi as Dt,Wn as Ot,Wr as kt,Wt as At,X as jt,Xi as Mt,Xn as Nt,Xt as Pt,Y as Ft,Yi as It,Yn as Lt,Yt as Rt,Z as zt,Zi as Bt,Zn as Vt,Zt as Ht,_ as Ut,_a as Wt,_i as Gt,_n as Kt,_r as qt,a as Jt,aa as Yt,ai as Xt,an as Zt,ar as Qt,at as $t,b as en,ba as tn,bi as nn,bn as rn,br as an,bt as on,c as sn,ca as cn,ci as ln,cn as un,cr as dn,ct as fn,d as pn,da as mn,di as hn,dn as gn,dr as _n,dt as vn,ea as yn,ei as bn,en as xn,er as Sn,et as Cn,f as wn,fa as Tn,fi as En,fn as Dn,fr as On,ft as kn,g as An,ga as jn,gi as Mn,gn as Nn,gr as Pn,h as Fn,ha as In,hi as Ln,hn as Rn,hr as zn,i as Bn,ia as Vn,ii as Hn,in as Un,ir as Wn,it as Gn,j as Kn,ja as qn,ji as Jn,jn as Yn,jr as Xn,jt as Zn,k as Qn,ka as $n,ki as er,kn as tr,kr as nr,kt as rr,l as ir,la as ar,li as or,ln as sr,lr as cr,lt as lr,m as ur,ma as dr,mi as fr,mn as pr,mr,n as hr,na as gr,ni as _r,nn as vr,nr as yr,nt as br,o as xr,oa as Sr,oi as Cr,on as wr,or as Tr,ot as Er,p as Dr,pa as Or,pi as kr,pn as Ar,pr as jr,pt as Mr,q as Nr,qi as Pr,qn as Fr,qt as Ir,r as Lr,ra as Rr,ri as zr,rn as Br,rr as Vr,rt as Hr,s as Ur,sa as Wr,si as Gr,sn as Kr,sr as qr,st as Jr,t as Yr,ta as Xr,ti as Zr,tn as Qr,tr as $r,tt as ei,u as ti,ua as ni,ui as ri,un as ii,ur as ai,ut as oi,v as si,va as ci,vi as li,vn as ui,vr as di,w as fi,wa as pi,wi as mi,wn as hi,wr as gi,wt as _i,x as vi,xa as yi,xi as bi,xn as xi,xr as Si,xt as Ci,y as wi,ya as Ti,yi as Ei,yn as Di,yr as Oi,z as ki,zi as Ai,zn as ji,zr as Mi,zt as Ni}from"./src-CeQWnH8P.mjs";import{C as Pi,E as Fi,T as Ii,_ as Li,b as Ri,c as zi,d as Bi,g as Vi,i as Hi,l as Ui,m as Wi,n as Gi,p as Ki,s as qi,t as Ji,u as Yi,v as Xi,w as Zi,x as Qi,y as $i}from"./fs-traced-DgX7lP1u.mjs";import{a as ea,d as ta,f as na,i as ra,l as ia,n as aa,r as oa,t as sa,u as ca}from"./logger-Dq-cRhcP.mjs";import{C as la,S as ua,_ as da,a as fa,b as pa,c as ma,d as ha,f as ga,g as _a,h as va,i as ya,l as ba,m as xa,n as Sa,o as Ca,p as wa,r as Ta,s as Ea,t as Da,u as Oa,x as ka}from"./server-lock-DKS1ePB3.mjs";export{dt as AGENT_ID_MAX_LEN,z as AGENT_ID_RE,St as AGENT_WRITE_ORIGIN,Te as AcpPermissionStore,$n as AcpRegistry,P as AcpThreadManager,ft as AgentFocusBroadcaster,mi as AgentPresenceBroadcaster,te as AgentSessionCapacityError,_t as AgentSessionManager,lt as AutoStartDisabledError,Gt as BUNDLE_IDS,li as BUNDLE_SCOPE,Ei as BUNDLE_SKILL_NAME,qt as BacklinkIndex,f as CC1Broadcaster,s as CC1_CONTRACT_VERSION,Nn as CONFIG_FILENAME,_n as CONFLICT_MARKER_RE,Ni as CURSOR_BUNDLE_PATHS_BY_PLATFORM,en as ConfigSchema,Yt as DEFAULT_CHECKPOINT_RETENTION,tt as DEFAULT_EMBEDDINGS_DIMENSIONS,pe as DEFAULT_PACK_ID,Y as DocumentDurabilityState,ji as EMBEDDINGS_API_KEY_ENV,Yr as EPHEMERAL_PROJECT_DIR_PREFIX,Ct as ExposureConsentError,_ as FEATURED_AGENT_IDS,Sr as FILE_SYSTEM_WRITER,zn as FILE_WATCHER_ORIGIN,De as FileEmbeddingsBackend,ii as GIT_PREFLIGHT_FAIL_SPAN_NAME,Wr as GIT_UPSTREAM_WRITER,je as GitDirAccessError,Ee as GitNotAvailableError,Me as GitTooOldError,j as HOCUSPOCUS_AUTH_REJECTION_REASONS,_i as HocuspocusAuthRejection,ht as HocuspocusAuthTokenSchema,hi as HomeProjectRootError,Hn as INSTALLED_AGENTS_SCHEMES,kn as JSON_SCHEMA_DIALECT_2020_12,o as LINEAGE_EPOCH_KEY,ee as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Rt as LOG_MD_TEMPLATE,ke as MANAGED_RENAME_ORIGIN,Re as MAX_ACP_THREADS,Dt as MAX_AGENT_SESSIONS,v as MCP_CONNECTION_ID_HEADER,i as MCP_SERVER_NAME,X as MIN_EVICTABLE_IDLE_MS,We as MIN_GIT_VERSION,me as MISSING_OK_CONFIG_MESSAGE,Ue as MalformedGitPointerError,Gn as McpLogger,Nr as MissingOkConfigError,Pr as OBSERVER_SYNC_ORIGIN,Kt as OK_OKIGNORE_TEMPLATE,nn as ONBOARDING_BUNDLE_IDS,n as ORPHAN_MODES,r as PROTOCOL_VERSION,sa as PinoLogger,ba as ProcessLockCollisionError,wn as ProjectGitInitError,Fe as ROLLBACK_ORIGIN,ui as ROOT_GITIGNORE_TEMPLATE,pa as RUNTIME_VERSION,cn as SERVICE_WRITER,ce as SKILL_INSTALL_EVENTS_FILE_REL,t as SKILL_STATE_TARGETS,Pt as STARTER_FOLDERS,Ht as STARTER_FOLDER_FRONTMATTER_FILENAME,Qe as STARTER_PACKS,h as STARTER_PACK_IDS,xn as STARTER_TEMPLATES,Qn as STATE_MANIFEST_FILENAME,ka as STATE_SCHEMA_VERSION,l as SYSTEM_DOC_NAME,wr as SeedPrerequisiteError,Kr as SeedRootDirError,Da as ServerLockCollisionError,hr as SingleFileNotAFileError,Lr as SingleFileNotFoundError,Bn as SingleFileNotMarkdownError,Jt as SingleFileProjectOverrideError,g as StateManifestError,Pn as TagIndex,bi as USER_GLOBAL_BUNDLE_IDS,qe as __getShowAllWalkStatsForTesting,J as __resetShowAllWalkStatsForTesting,Oa as acquireProcessLock,Sa as acquireServerLock,he as applyAgentMarkdownWrite,cr as applyExternalChange,Ir as applySeed,Kn as assertCompatibleStateManifest,G as assertGitAvailable,Vt as assertNeverDiskEvent,pt as assertNotHomeProjectRoot,B as attachAcpThreadSocket,on as attachCollabClientCounter,Ci as attachIdleShutdown,vi as bootServer,ct as buildAndOpenSkill,Di as buildConfigYmlContent,d as buildExecResult,ne as buildIngressPolicy,er as buildOkMcpStdioCommand,fr as buildSkillZip,Qr as buildStarterFolderFrontmatterYaml,ar as buildWipTree,ot as bundleSkillMdPath,Ne as canonicalProjectKey,V as canonicalizeForCompare,Xe as classifyEvents,Ji as classifyFsPath,Ge as clearAllEmbeddingsKeys,Gr as clearContributors,vr as coercePackId,u as colorFromSeed,ni as commitUpstreamImport,mn as commitWip,Tn as commitWipFromTree,oe as compareSemver,Mi as composeEffectiveLinterConfig,T as composeFrontmatterSchemasConfig,On as containsConflictMarkers,p as contentHash,ln as contributorCount,$e as countShadowObjects,ki as countStaleAgentWipRefs,S as countWipRefs,le as createApiExtension,Zn as createAssetServeMiddleware,Ft as createCollaborationHost,Ze as createContentFilter,m as createContentFilterAsync,K as createEmbeddingsSecretStore,xr as createEphemeralProjectDir,ai as createExternalChangeHandler,Fn as createFileLogger,gt as createLiveDerivedIndexExtension,zt as createMcpHttpHandler,Xt as createOsProbe,ye as createPersistenceExtension,R as createServer,W as createServerObserverExtension,Mt as createStreamingErrorWriter,aa as createTestLogger,se as describeStoredEmbeddingsKey,wi as detectClaudeDesktopPresence,be as detectGit,we as detectProjectShape,A as detectUserSkillHosts,Jr as discoverLockDirs,yt as discoverMarkdownlintConfig,gn as emitPreflightFailureSpan,Cn as encodeDocName,ei as encodeFolderRoute,br as encodeSkillRoute,Dr as ensureProjectGit,rn as ensureProjectSkillGitignore,Bt as errorResponse,Sn as evictStaleTrackerEntries,Ce as extractHeadings,fn as extractOkBinaryPath,di as extractWikiLinksFromMarkdown,et as fallbackPaths,ur as findEnclosingGitRoot,bn as findEnclosingProjectRoot,kt as findNativeMarkdownlintFile,An as flushFileLogger,U as formatAuthRejectionWire,or as formatContributors,ri as formatContributorsFrom,$ as formatPackRationale,Or as gcCheckpointRefs,$t as getCurrentMcpLogger,vt as getIngressContext,Oi as getLocalDir,Ut as getLogFilePath,oa as getLogger,si as getLogsDir,da as getMachineId,$i as getMeter,tn as getMetrics,Ri as getTracer,yi as handleCollabSocketError,E as handleSpawnCursor,Ot as hasForwardingHeaders,xt as hasGcLogLatch,e as iconFromClientName,at as incrementCollabSocketFilteredError,O as incrementServerObserverFire,xi as initContent,dr as initShadowRepo,Qi as initTelemetry,D as initToleranceTelemetryWriter,Mr as installJsonSchemaDialect,vn as installPrettyZodErrors,ra as installTestLoggers,gi as installUserSkill,Nt as isAllowedApiOrigin,fe as isAllowedWorkspaceHostHeader,yn as isConfigDoc,L as isHocuspocusAuthRejectionReason,F as isHomeDir,Z as isHostAdmitted,Br as isKnownPackId,Xr as isLinkIndexExcludedDoc,Lt as isLoopbackAddress,gr as isManagedArtifactDoc,ge as isOriginAdmitted,c as isOrphanMode,de as isPairedWriteOrigin,Tt as isPathWithinDir,Fr as isPeerAdmitted,ua as isProcessAlive,Zr as isProjectRoot,Rr as isReservedForUserTree,$r as isSelfWrite,Vn as isSystemDoc,fi as isToleranceTelemetryEnabled,la as isValidLockPid,yr as lastKnownHash,In as listRescueCheckpoints,Un as listStarterPacks,qn as loadCustomAgents,ae as loadPrincipal,Ta as lockAdvertisesUi,ha as lockBaseUrl,ga as lockFilePath,ea as loggerFactory,ze as loginShapedUserinfoUser,ia as logsCurrentPath,ca as logsPreviousPath,xe as makeLazyEmbeddingsKeyStore,ya as markServerLockDraining,ue as mountMcpAndApi,Gi as normalizeFsPath,tr as originGitHubHost,st as packageVersionMajorMinor,Ve as parseAuthRejectionWire,Ai as parseGitVersion,rr as parseHocuspocusAuthToken,jt as parseKeepaliveConnectionId,Vr as pathToDocName,ve as planSeed,Ur as prepareSingleFileOpen,lr as processCommand,oi as processUsage,I as readAllTargets,Be as readBundleDecision,Q as readOwnNativeRules,wa as readProcessLock,xa as readProcessLockDetailed,Et as readProjectHeadState,Yn as readProjectLocalSemanticConfig,fa as readServerLock,nr as readServerPackageVersion,b as readSkillInstallStateSnapshot,Ae as readStateManifest,Xn as readTargetRecordedAt,Oe as readTargetVersion,jr as reconcile,hn as recordContributor,Se as recordSkillInstallEvent,Dn as redactShareSubprocessStderr,Je as registerAllTools,Wn as registerWrite,va as releaseProcessLock,Ca as releaseServerLock,Qt as removeLastKnownHash,H as reportSkillInstall,pi as resetMetrics,mt as resolveBuiltinSkillHosts,a as resolveBundleEnabled,Ln as resolveBundledSkillDir,an as resolveContentDir,ie as resolveCursorBinaryDefault,bt as resolveCursorSpawnInvocation,wt as resolveEffectiveLinterConfig,w as resolveEmbeddingsCredential,Ie as resolveGitHubAccountFromUrl,Si as resolveLockDir,re as resolveNativeConfigForDoc,_e as resolveNativeMarkdownlintConfig,Zt as resolvePack,ti as resolvePackageVersion,q as resolveSkillInstallReportSettings,Hr as resolveUiInfo,En as restoreContributors,it as restoreLifecycleFromConflictsJson,_r as rewriteMarkdownLinksForDocumentRename,zr as rewriteWikiLinksForDocumentRename,Ar as runAuthReposSubprocess,pr as runAuthStatusSubprocess,un as runCloneSubprocess,Rn as runDeviceFlowSubprocess,Er as runWithMcpLogger,Cr as safeContentPath,rt as safeSubdir,jn as safetyCheckpoint,y as sameGitHubLogin,Jn as sanitizeClientName,Wt as saveInMemoryCheckpoint,ci as saveVersion,x as seedBasenameIndex,sn as seedEphemeralProjectDir,ir as serializeError,Pi as setActiveSpanAttributes,It as setupServerObservers,Ti as shadowGit,Zi as shutdownTelemetry,ta as spansCurrentPath,na as spansPreviousPath,At as spawnDetached,mr as splitMarkdownBlocks,Tr as startWatcher,Ye as streamingProblemEvent,kr as swapContributors,ut as teardownToleranceTelemetryWriter,N as toBroadcasterKey,Hi as tracedAppendFileSync,qi as tracedLinkSync,zi as tracedMkdir,Ui as tracedMkdirSync,Yi as tracedRename,Bi as tracedRenameSync,Ki as tracedRmSync,Wi as tracedRmdirSync,Vi as tracedUnlinkSync,Li as tracedWriteFile,Xi as tracedWriteFileSync,M as trustSystemCertificates,pn as untrackTrackedProjectSkillProjection,qr as updateLastKnownHash,_a as updateProcessLockPort,Ea as updateServerLockPort,Le as validateAgentId,sr as validateCloneInputs,Mn as validateSkillZip,ma as waitForServerLockDrain,C as withHiddenWindowsConsole,Ii as withSpan,Fi as withSpanSync,Pe as writeBundleDecision,nt as writeMarkdownlintRule,k as writeRootGitignoreForNewRepo,He as writeStateManifest,Ke as writeTargetVersion,dn as writeTracker};
|
|
1
|
+
import{C as e,K as t,Ko as n,Qs as r,Uo as i,X as a,fs as o,ms as s,qo as c,ws as l,x as u}from"./src-B2bAQ64a.mjs";import{$ as d,$i as f,$n as p,$r as m,$t as h,A as g,Aa as _,Ai as v,An as y,Ar as b,At as x,B as S,Bi as C,Bn as w,Br as T,Bt as E,C as D,Ca as O,Cn as k,Cr as A,Ct as j,D as M,Da as N,Di as P,Dn as F,Dr as I,Dt as L,E as R,Ea as z,Ei as B,En as V,Er as H,Et as U,F as W,Fi as G,Fn as K,Fr as q,Ft as J,G as Y,Gi as X,Gn as Z,Gr as Q,Gt as $,H as ee,Hi as te,Hn as ne,Hr as re,Ht as ie,I as ae,Ii as oe,In as se,Ir as ce,It as le,J as ue,Ji as de,Jn as fe,Jt as pe,K as me,Ki as he,Kn as ge,Kr as _e,Kt as ve,L as ye,Li as be,Ln as xe,Lr as Se,Lt as Ce,M as we,Ma as Te,Mi as Ee,Mn as De,Mr as Oe,Mt as ke,N as Ae,Na as je,Ni as Me,Nn as Ne,Nr as Pe,Nt as Fe,O as Ie,Oa as Le,Oi as Re,On as ze,Or as Be,Ot as Ve,P as He,Pa as Ue,Pi as We,Pn as Ge,Pr as Ke,Pt as qe,Q as Je,Qi as Ye,Qn as Xe,Qr as Ze,Qt as Qe,R as $e,Ri as et,Rn as tt,Rr as nt,Rt as rt,S as it,Sa as at,Si as ot,Sn as st,Sr as ct,St as lt,T as ut,Ta as dt,Ti as ft,Tn as pt,Tr as mt,Tt as ht,U as gt,Ui as _t,Un as vt,Ur as yt,Ut as bt,V as xt,Vi as St,Vn as Ct,Vr as wt,Vt as Tt,W as Et,Wi as Dt,Wn as Ot,Wr as kt,Wt as At,X as jt,Xi as Mt,Xn as Nt,Xt as Pt,Y as Ft,Yi as It,Yn as Lt,Yt as Rt,Z as zt,Zi as Bt,Zn as Vt,Zt as Ht,_ as Ut,_a as Wt,_i as Gt,_n as Kt,_r as qt,a as Jt,aa as Yt,ai as Xt,an as Zt,ar as Qt,at as $t,b as en,ba as tn,bi as nn,bn as rn,br as an,bt as on,c as sn,ca as cn,ci as ln,cn as un,cr as dn,ct as fn,d as pn,da as mn,di as hn,dn as gn,dr as _n,dt as vn,ea as yn,ei as bn,en as xn,er as Sn,et as Cn,f as wn,fa as Tn,fi as En,fn as Dn,fr as On,ft as kn,g as An,ga as jn,gi as Mn,gn as Nn,gr as Pn,h as Fn,ha as In,hi as Ln,hn as Rn,hr as zn,i as Bn,ia as Vn,ii as Hn,in as Un,ir as Wn,it as Gn,j as Kn,ja as qn,ji as Jn,jn as Yn,jr as Xn,jt as Zn,k as Qn,ka as $n,ki as er,kn as tr,kr as nr,kt as rr,l as ir,la as ar,li as or,ln as sr,lr as cr,lt as lr,m as ur,ma as dr,mi as fr,mn as pr,mr,n as hr,na as gr,ni as _r,nn as vr,nr as yr,nt as br,o as xr,oa as Sr,oi as Cr,on as wr,or as Tr,ot as Er,p as Dr,pa as Or,pi as kr,pn as Ar,pr as jr,pt as Mr,q as Nr,qi as Pr,qn as Fr,qt as Ir,r as Lr,ra as Rr,ri as zr,rn as Br,rr as Vr,rt as Hr,s as Ur,sa as Wr,si as Gr,sn as Kr,sr as qr,st as Jr,t as Yr,ta as Xr,ti as Zr,tn as Qr,tr as $r,tt as ei,u as ti,ua as ni,ui as ri,un as ii,ur as ai,ut as oi,v as si,va as ci,vi as li,vn as ui,vr as di,w as fi,wa as pi,wi as mi,wn as hi,wr as gi,wt as _i,x as vi,xa as yi,xi as bi,xn as xi,xr as Si,xt as Ci,y as wi,ya as Ti,yi as Ei,yn as Di,yr as Oi,z as ki,zi as Ai,zn as ji,zr as Mi,zt as Ni}from"./src-aZqW_iIK.mjs";import{C as Pi,E as Fi,T as Ii,_ as Li,b as Ri,c as zi,d as Bi,g as Vi,i as Hi,l as Ui,m as Wi,n as Gi,p as Ki,s as qi,t as Ji,u as Yi,v as Xi,w as Zi,x as Qi,y as $i}from"./fs-traced-DgX7lP1u.mjs";import{a as ea,d as ta,f as na,i as ra,l as ia,n as aa,r as oa,t as sa,u as ca}from"./logger-Dq-cRhcP.mjs";import{C as la,S as ua,_ as da,a as fa,b as pa,c as ma,d as ha,f as ga,g as _a,h as va,i as ya,l as ba,m as xa,n as Sa,o as Ca,p as wa,r as Ta,s as Ea,t as Da,u as Oa,x as ka}from"./server-lock-DKS1ePB3.mjs";export{dt as AGENT_ID_MAX_LEN,z as AGENT_ID_RE,St as AGENT_WRITE_ORIGIN,Te as AcpPermissionStore,$n as AcpRegistry,P as AcpThreadManager,ft as AgentFocusBroadcaster,mi as AgentPresenceBroadcaster,te as AgentSessionCapacityError,_t as AgentSessionManager,lt as AutoStartDisabledError,Gt as BUNDLE_IDS,li as BUNDLE_SCOPE,Ei as BUNDLE_SKILL_NAME,qt as BacklinkIndex,f as CC1Broadcaster,s as CC1_CONTRACT_VERSION,Nn as CONFIG_FILENAME,_n as CONFLICT_MARKER_RE,Ni as CURSOR_BUNDLE_PATHS_BY_PLATFORM,en as ConfigSchema,Yt as DEFAULT_CHECKPOINT_RETENTION,tt as DEFAULT_EMBEDDINGS_DIMENSIONS,pe as DEFAULT_PACK_ID,Y as DocumentDurabilityState,ji as EMBEDDINGS_API_KEY_ENV,Yr as EPHEMERAL_PROJECT_DIR_PREFIX,Ct as ExposureConsentError,_ as FEATURED_AGENT_IDS,Sr as FILE_SYSTEM_WRITER,zn as FILE_WATCHER_ORIGIN,De as FileEmbeddingsBackend,ii as GIT_PREFLIGHT_FAIL_SPAN_NAME,Wr as GIT_UPSTREAM_WRITER,je as GitDirAccessError,Ee as GitNotAvailableError,Me as GitTooOldError,j as HOCUSPOCUS_AUTH_REJECTION_REASONS,_i as HocuspocusAuthRejection,ht as HocuspocusAuthTokenSchema,hi as HomeProjectRootError,Hn as INSTALLED_AGENTS_SCHEMES,kn as JSON_SCHEMA_DIALECT_2020_12,o as LINEAGE_EPOCH_KEY,ee as LIVE_DERIVED_INDEX_DEBOUNCE_MS,Rt as LOG_MD_TEMPLATE,ke as MANAGED_RENAME_ORIGIN,Re as MAX_ACP_THREADS,Dt as MAX_AGENT_SESSIONS,v as MCP_CONNECTION_ID_HEADER,i as MCP_SERVER_NAME,X as MIN_EVICTABLE_IDLE_MS,We as MIN_GIT_VERSION,me as MISSING_OK_CONFIG_MESSAGE,Ue as MalformedGitPointerError,Gn as McpLogger,Nr as MissingOkConfigError,Pr as OBSERVER_SYNC_ORIGIN,Kt as OK_OKIGNORE_TEMPLATE,nn as ONBOARDING_BUNDLE_IDS,n as ORPHAN_MODES,r as PROTOCOL_VERSION,sa as PinoLogger,ba as ProcessLockCollisionError,wn as ProjectGitInitError,Fe as ROLLBACK_ORIGIN,ui as ROOT_GITIGNORE_TEMPLATE,pa as RUNTIME_VERSION,cn as SERVICE_WRITER,ce as SKILL_INSTALL_EVENTS_FILE_REL,t as SKILL_STATE_TARGETS,Pt as STARTER_FOLDERS,Ht as STARTER_FOLDER_FRONTMATTER_FILENAME,Qe as STARTER_PACKS,h as STARTER_PACK_IDS,xn as STARTER_TEMPLATES,Qn as STATE_MANIFEST_FILENAME,ka as STATE_SCHEMA_VERSION,l as SYSTEM_DOC_NAME,wr as SeedPrerequisiteError,Kr as SeedRootDirError,Da as ServerLockCollisionError,hr as SingleFileNotAFileError,Lr as SingleFileNotFoundError,Bn as SingleFileNotMarkdownError,Jt as SingleFileProjectOverrideError,g as StateManifestError,Pn as TagIndex,bi as USER_GLOBAL_BUNDLE_IDS,qe as __getShowAllWalkStatsForTesting,J as __resetShowAllWalkStatsForTesting,Oa as acquireProcessLock,Sa as acquireServerLock,he as applyAgentMarkdownWrite,cr as applyExternalChange,Ir as applySeed,Kn as assertCompatibleStateManifest,G as assertGitAvailable,Vt as assertNeverDiskEvent,pt as assertNotHomeProjectRoot,B as attachAcpThreadSocket,on as attachCollabClientCounter,Ci as attachIdleShutdown,vi as bootServer,ct as buildAndOpenSkill,Di as buildConfigYmlContent,d as buildExecResult,ne as buildIngressPolicy,er as buildOkMcpStdioCommand,fr as buildSkillZip,Qr as buildStarterFolderFrontmatterYaml,ar as buildWipTree,ot as bundleSkillMdPath,Ne as canonicalProjectKey,V as canonicalizeForCompare,Xe as classifyEvents,Ji as classifyFsPath,Ge as clearAllEmbeddingsKeys,Gr as clearContributors,vr as coercePackId,u as colorFromSeed,ni as commitUpstreamImport,mn as commitWip,Tn as commitWipFromTree,oe as compareSemver,Mi as composeEffectiveLinterConfig,T as composeFrontmatterSchemasConfig,On as containsConflictMarkers,p as contentHash,ln as contributorCount,$e as countShadowObjects,ki as countStaleAgentWipRefs,S as countWipRefs,le as createApiExtension,Zn as createAssetServeMiddleware,Ft as createCollaborationHost,Ze as createContentFilter,m as createContentFilterAsync,K as createEmbeddingsSecretStore,xr as createEphemeralProjectDir,ai as createExternalChangeHandler,Fn as createFileLogger,gt as createLiveDerivedIndexExtension,zt as createMcpHttpHandler,Xt as createOsProbe,ye as createPersistenceExtension,R as createServer,W as createServerObserverExtension,Mt as createStreamingErrorWriter,aa as createTestLogger,se as describeStoredEmbeddingsKey,wi as detectClaudeDesktopPresence,be as detectGit,we as detectProjectShape,A as detectUserSkillHosts,Jr as discoverLockDirs,yt as discoverMarkdownlintConfig,gn as emitPreflightFailureSpan,Cn as encodeDocName,ei as encodeFolderRoute,br as encodeSkillRoute,Dr as ensureProjectGit,rn as ensureProjectSkillGitignore,Bt as errorResponse,Sn as evictStaleTrackerEntries,Ce as extractHeadings,fn as extractOkBinaryPath,di as extractWikiLinksFromMarkdown,et as fallbackPaths,ur as findEnclosingGitRoot,bn as findEnclosingProjectRoot,kt as findNativeMarkdownlintFile,An as flushFileLogger,U as formatAuthRejectionWire,or as formatContributors,ri as formatContributorsFrom,$ as formatPackRationale,Or as gcCheckpointRefs,$t as getCurrentMcpLogger,vt as getIngressContext,Oi as getLocalDir,Ut as getLogFilePath,oa as getLogger,si as getLogsDir,da as getMachineId,$i as getMeter,tn as getMetrics,Ri as getTracer,yi as handleCollabSocketError,E as handleSpawnCursor,Ot as hasForwardingHeaders,xt as hasGcLogLatch,e as iconFromClientName,at as incrementCollabSocketFilteredError,O as incrementServerObserverFire,xi as initContent,dr as initShadowRepo,Qi as initTelemetry,D as initToleranceTelemetryWriter,Mr as installJsonSchemaDialect,vn as installPrettyZodErrors,ra as installTestLoggers,gi as installUserSkill,Nt as isAllowedApiOrigin,fe as isAllowedWorkspaceHostHeader,yn as isConfigDoc,L as isHocuspocusAuthRejectionReason,F as isHomeDir,Z as isHostAdmitted,Br as isKnownPackId,Xr as isLinkIndexExcludedDoc,Lt as isLoopbackAddress,gr as isManagedArtifactDoc,ge as isOriginAdmitted,c as isOrphanMode,de as isPairedWriteOrigin,Tt as isPathWithinDir,Fr as isPeerAdmitted,ua as isProcessAlive,Zr as isProjectRoot,Rr as isReservedForUserTree,$r as isSelfWrite,Vn as isSystemDoc,fi as isToleranceTelemetryEnabled,la as isValidLockPid,yr as lastKnownHash,In as listRescueCheckpoints,Un as listStarterPacks,qn as loadCustomAgents,ae as loadPrincipal,Ta as lockAdvertisesUi,ha as lockBaseUrl,ga as lockFilePath,ea as loggerFactory,ze as loginShapedUserinfoUser,ia as logsCurrentPath,ca as logsPreviousPath,xe as makeLazyEmbeddingsKeyStore,ya as markServerLockDraining,ue as mountMcpAndApi,Gi as normalizeFsPath,tr as originGitHubHost,st as packageVersionMajorMinor,Ve as parseAuthRejectionWire,Ai as parseGitVersion,rr as parseHocuspocusAuthToken,jt as parseKeepaliveConnectionId,Vr as pathToDocName,ve as planSeed,Ur as prepareSingleFileOpen,lr as processCommand,oi as processUsage,I as readAllTargets,Be as readBundleDecision,Q as readOwnNativeRules,wa as readProcessLock,xa as readProcessLockDetailed,Et as readProjectHeadState,Yn as readProjectLocalSemanticConfig,fa as readServerLock,nr as readServerPackageVersion,b as readSkillInstallStateSnapshot,Ae as readStateManifest,Xn as readTargetRecordedAt,Oe as readTargetVersion,jr as reconcile,hn as recordContributor,Se as recordSkillInstallEvent,Dn as redactShareSubprocessStderr,Je as registerAllTools,Wn as registerWrite,va as releaseProcessLock,Ca as releaseServerLock,Qt as removeLastKnownHash,H as reportSkillInstall,pi as resetMetrics,mt as resolveBuiltinSkillHosts,a as resolveBundleEnabled,Ln as resolveBundledSkillDir,an as resolveContentDir,ie as resolveCursorBinaryDefault,bt as resolveCursorSpawnInvocation,wt as resolveEffectiveLinterConfig,w as resolveEmbeddingsCredential,Ie as resolveGitHubAccountFromUrl,Si as resolveLockDir,re as resolveNativeConfigForDoc,_e as resolveNativeMarkdownlintConfig,Zt as resolvePack,ti as resolvePackageVersion,q as resolveSkillInstallReportSettings,Hr as resolveUiInfo,En as restoreContributors,it as restoreLifecycleFromConflictsJson,_r as rewriteMarkdownLinksForDocumentRename,zr as rewriteWikiLinksForDocumentRename,Ar as runAuthReposSubprocess,pr as runAuthStatusSubprocess,un as runCloneSubprocess,Rn as runDeviceFlowSubprocess,Er as runWithMcpLogger,Cr as safeContentPath,rt as safeSubdir,jn as safetyCheckpoint,y as sameGitHubLogin,Jn as sanitizeClientName,Wt as saveInMemoryCheckpoint,ci as saveVersion,x as seedBasenameIndex,sn as seedEphemeralProjectDir,ir as serializeError,Pi as setActiveSpanAttributes,It as setupServerObservers,Ti as shadowGit,Zi as shutdownTelemetry,ta as spansCurrentPath,na as spansPreviousPath,At as spawnDetached,mr as splitMarkdownBlocks,Tr as startWatcher,Ye as streamingProblemEvent,kr as swapContributors,ut as teardownToleranceTelemetryWriter,N as toBroadcasterKey,Hi as tracedAppendFileSync,qi as tracedLinkSync,zi as tracedMkdir,Ui as tracedMkdirSync,Yi as tracedRename,Bi as tracedRenameSync,Ki as tracedRmSync,Wi as tracedRmdirSync,Vi as tracedUnlinkSync,Li as tracedWriteFile,Xi as tracedWriteFileSync,M as trustSystemCertificates,pn as untrackTrackedProjectSkillProjection,qr as updateLastKnownHash,_a as updateProcessLockPort,Ea as updateServerLockPort,Le as validateAgentId,sr as validateCloneInputs,Mn as validateSkillZip,ma as waitForServerLockDrain,C as withHiddenWindowsConsole,Ii as withSpan,Fi as withSpanSync,Pe as writeBundleDecision,nt as writeMarkdownlintRule,k as writeRootGitignoreForNewRepo,He as writeStateManifest,Ke as writeTargetVersion,dn as writeTracker};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{Gs as e,Is as t,Us as n,Ws as r,zs as i}from"./src-B2bAQ64a.mjs";import{L as a}from"./sleep-zea4v2sB.mjs";import{Ln as o,s,t as c,ti as l}from"./src-
|
|
2
|
-
`)))}let O=o.port===void 0?void 0:Number(o.port),k=h.overrides.find(e=>e.envVar===`PORT`)?.value,A=O??k??s.server?.port,j=B({explicitDir:o.reactShellDistDir,only:o.only,findBundledDir:z}),M=j.dir;j.missingBundle&&console.warn(`bundled web UI not found — serving /api and /mcp only. Reinstall @inkeep/open-knowledge, or build packages/app in a source checkout.`);let N;try{N=await Q({config:s,cwd:m,host:C,port:A,bind:w,...o.serveContentAssets===void 0?{}:{serveContentAssets:o.serveContentAssets},...M?{reactShellDistDir:M}:{},idleThresholdMs:t(o.idleShutdown??E.idleShutdown),serverRuntime:E,...o.singleFile?{singleFile:o.singleFile}:{},...o.projectDir?{projectDir:o.projectDir}:{}})}catch(e){e instanceof q&&(console.error(f(e.message)),process.exit(1)),e instanceof J&&(console.error(f(e.message)),process.exit(1));let t=await import(`./src-
|
|
1
|
+
import{Gs as e,Is as t,Us as n,Ws as r,zs as i}from"./src-B2bAQ64a.mjs";import{L as a}from"./sleep-zea4v2sB.mjs";import{Ln as o,s,t as c,ti as l}from"./src-aZqW_iIK.mjs";import{A as u,L as d}from"./fs-traced-DgX7lP1u.mjs";import{r as f}from"./server-lock-DKS1ePB3.mjs";import{C as p,S as m,x as h}from"./resolve-project-root-CGGchFLW.mjs";import{c as g,f as _,g as v,l as y,n as b,o as x,p as S,r as C,s as w,t as T}from"./acp-harness-probe-_R_A7pqq.mjs";import{y as E}from"./init-D60fKL1P.mjs";import{n as D}from"./constants-kDKxgBFE.mjs";import{spawn as O}from"node:child_process";import{basename as k,dirname as A,resolve as j}from"node:path";import{existsSync as M,realpathSync as N}from"node:fs";import{tmpdir as P}from"node:os";import{rm as F}from"node:fs/promises";import{setTimeout as I}from"node:timers/promises";function L(e,t){return e.bind?.[0]??t.HOST??`127.0.0.1`}function R(e){if(e===`server`)return e;throw new m(`--only must be 'server'`)}function z(e=M){let t=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[j(t,`public`),j(t,`../../app/dist`),j(t,`../../../app/dist`)].find(t=>e(t))}function B(e){if(e.explicitDir!==void 0)return{dir:e.explicitDir,missingBundle:!1};if(e.only===`server`)return{dir:void 0,missingBundle:!1};let t=e.findBundledDir();return{dir:t,missingBundle:t===void 0}}function V(e){if(e===`off`)return`off`;if(!a.test(e))throw new m(`--idle-shutdown must be 'off' or a duration like 90s, 30m, 2h`);return e}function H(e){return e===`localhost`||e===`::1`||e===`[::1]`||e.startsWith(`127.`)}function U(e){return!e.flagBindSet&&!e.okBindSet&&e.hostEnvSet&&e.fileBindCount>1}function W(e){return!e.openBrowser||e.ephemeral||e.only===`server`||!e.servesUi?!1:(e.explicitOn||H(e.host))&&e.isTTY}function ee(e,t){let n;try{n=new URL(t)}catch{throw new m(`${e} is not a valid URL: ${t}`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new m(`${e} must be an http(s) origin (got: ${t})`);return t}function G(e){return ee(`--external-url`,e)}function K(e){let t=k(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var q=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}},J=class extends Error{projectDir;constructor(e){super(`--project-dir must be a throwaway ${c}* directory under the OS temp dir. Refusing to write ephemeral session state into ${e}. Omit --project-dir to let ok start create (and clean up) its own.`),this.name=`EphemeralProjectDirNotThrowawayError`,this.projectDir=e}};function Y(e,t={}){let n=t.tmpdirFn??P,r=t.realpathFn??N,i=e=>{try{return r(e)}catch(t){return t.code===`ENOENT`?j(e):null}},a=j(e),o;try{o=r(a)}catch(e){if(e.code===`ENOENT`){let e=i(A(a));o=e===null?null:j(e,k(a))}else o=null}if(o===null)return!1;let s=i(n());return s===null?!1:A(o)===s&&k(o).startsWith(`ok-ephemeral-`)}function X(e,t,n=e=>F(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{if(Y(t))try{await n(t)}catch(e){process.stderr.write(`[start] ephemeral temp dir reap failed for ${t}: ${e instanceof Error?e.message:String(e)}\n`)}else process.stderr.write(`[start] leaving ${t} in place: only ${c}* dirs under the OS temp dir are removed on ephemeral teardown\n`)}}}function Z(e,t={}){let n=t.exit??(e=>process.exit(e)),r=t.getActiveHandles??(()=>{let e=process._getActiveHandles;return e?e.call(process):null});return async()=>{let i=!1;try{await e()}catch(e){i=!0,t.log?.error({err:e},`idle-shutdown: destroy failed — exiting anyway`)}finally{let e=null;try{let t=r();if(t!==null){e={};for(let n of t){let t=n?.constructor?.name??`unknown`;e[t]=(e[t]??0)+1}}}catch{e=null}t.log?.info({event:`idle-shutdown-exit`,exitCode:+!!i,openHandles:e??{},handlesAvailable:e!==null},`idle-shutdown: teardown finished — exiting process`),n(+!!i)}}}async function Q(e){let{config:t,cwd:n,host:r}=e,i=e.skipAutoInit??!1,a=e.idleThresholdMs===void 0?18e5:e.idleThresholdMs,{existsSync:c,mkdirSync:u}=await import(`node:fs`),{basename:d,dirname:f,resolve:p}=await import(`node:path`),{bootServer:m,createEphemeralProjectDir:h,getLogger:g,resolveContentDir:y,resolveLockDir:x,seedEphemeralProjectDir:w,waitForServerLockDrain:D}=await import(`./src-pvuJUuAq.mjs`),O=e.log??g(`start`),k=e.singleFile!==void 0,A=k?s(e.singleFile).canonicalFilePath:void 0,j=A?f(A):void 0,M=A?d(A):void 0,N,P=!1;if(j!==void 0)if(e.projectDir!==void 0){if(N=e.projectDir,!Y(N))throw new J(N);c(p(N,`.ok`,`config.yml`))||w(N,j)}else N=h(j),P=!0;let I=async()=>{if(!(!P||N===void 0)){if(!Y(N)){O.warn({ephemeralProjectDir:N},`[start] refusing to reap self-provisioned ephemeral dir: no longer resolves to an ok-ephemeral-* temp dir`);return}try{await F(N,{recursive:!0,force:!0})}catch(e){O.warn({err:e,ephemeralProjectDir:N},`[start] failed to reap self-provisioned ephemeral temp dir`)}}},L=N;if(!k){if(!i&&!l(n))throw new q(n);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{let t=typeof e.event==`string`?e.event:``;(t.endsWith(`-failed`)||t.endsWith(`-error`)||t.endsWith(`-missing`))&&O.warn({event:e},`[start] reclaim sweep reported a problem`)};try{(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-DQNpA7pP.mjs`)).repairMcpConfigs)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){O.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-FKN5P5yh.mjs`)).repairLaunchJson)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){O.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}try{await(e.repairSkillsFn??(await import(`./repair-skills-BtSE7hBi.mjs`)).repairSkills)({projectDir:n,reclaimDisableEnv:t,logger:r})}catch(e){O.warn({err:e},`[start] skill repair sweep failed; continuing`)}}let R=j??y(t,n);!k&&!c(R)&&(u(R,{recursive:!0}),O.info({contentDir:R},`Created content directory`));let z=v(),B=o(),V;try{{let e=x(N??n),t=Date.now(),r=await D(e);r!==`no-drain`&&O.info({event:`start-waited-for-draining-predecessor`,outcome:r,waitedMs:Date.now()-t,drainLockDir:e},r===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}V=await m({config:t,contentDir:R,projectDir:N??n,contentRoot:k?void 0:t.content.dir,port:e.port,host:r,quiet:!1,detectGh:_,detectGhAccounts:S,tokenStore:z,embeddingsKeyStore:B,mcpTomlEditor:E(),...k?{ephemeral:!0,singleDocRelPath:M,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],probeHarnessManagedMcpEntry:(e,t)=>T(e,t),probePiAcpBridge:e=>C(e),ensurePiAcpBridge:e=>b(e),idleShutdownMs:a,...e.serverRuntime===void 0?{}:{serverRuntime:e.serverRuntime},...e.bind===void 0?{}:{bind:e.bind},skipAutoInit:!0,idleShutdownHandler:t=>{let n=t;return Z(L===void 0?n:X(n,L),{log:O,exit:e.idleExit})},log:O,...e.serveContentAssets===void 0?{}:{serveContentAssets:e.serveContentAssets},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{}})}catch(e){throw await I(),e}let H=V.destroy,U=P?async()=>{try{await H()}finally{await I()}}:H;return{httpServer:V.httpServer,destroy:U,lockDir:V.lockDir,contentDir:R,port:V.port,ready:V.ready,degraded:V.degraded}}function $(e,t,n=()=>d({absPath:u(`user`,process.cwd()),sideline:!1,warn:()=>{}}).value){return t===void 0?e:n()}function te(e){if(e===`browser`||e===`app`)return e;throw new m(`--mode must be 'browser' or 'app'`)}function ne(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function re(e){let t=[`Stopping OpenKnowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function ie(a,o){let s=$(a,o.singleFile),c=ne(process.env);c!==null&&(process.env.OK_CONSOLE_LEVEL=c);let{renderBanner:l}=await import(`./banner-B14xalho.mjs`),{accent:u,dim:d,error:f,warning:p}=await import(`./colors-CpP5E4wV.mjs`),m=process.cwd();process.title=K(m);let h;try{h=e(process.env)}catch(e){throw e instanceof n&&(console.error(f(e.message)),process.exit(78)),e}for(let e of h.diagnostics)console.warn(p(`[config] ${e.message}`));let g=r(s,h.layer),_=h.overrides.some(e=>e.envVar===`OK_BIND`),v=o.bind!==void 0&&o.bind.length>0?o.bind:void 0,y=process.env.HOST,b=y!==void 0&&y.trim()!==``?y:void 0,x=i(g),S=v??(_||b===void 0?[...x.bind]:[b]);U({flagBindSet:v!==void 0,okBindSet:_,hostEnvSet:b!==void 0,fileBindCount:x.bind.length})&&console.warn(p(`[config] HOST=${b} overrides server.bind — dropping the file-configured addresses (${x.bind.join(`, `)}). Use OK_BIND with a space-separated list to keep multiple binds.`));let C=S[0]??`127.0.0.1`,w=S,T=o.externalUrl,E=i(r(g,{server:{bind:w,...T===void 0?{}:{externalUrl:T}}}));if(E.allowExternal&&(!E.loopbackOnly||E.externalUrl)){let e=E.externalUrl??E.bind.join(`, `);console.warn(p([``,`⚠ EXTERNAL ACCESS ENABLED (server.allowExternal) — no server-side authentication.`,` This server is reachable beyond this machine (${e}). Anyone who can`,` reach it has FULL control of this knowledge base — sync, publishing, GitHub`,` credentials, and local operations (clone, sign-in, repo spawn).`,` Restrict who can reach it at the edge: a Tailscale ACL, a reverse proxy with`,` auth (Cloudflare Access, oauth2-proxy), or a firewall.`,``].join(`
|
|
2
|
+
`)))}let O=o.port===void 0?void 0:Number(o.port),k=h.overrides.find(e=>e.envVar===`PORT`)?.value,A=O??k??s.server?.port,j=B({explicitDir:o.reactShellDistDir,only:o.only,findBundledDir:z}),M=j.dir;j.missingBundle&&console.warn(`bundled web UI not found — serving /api and /mcp only. Reinstall @inkeep/open-knowledge, or build packages/app in a source checkout.`);let N;try{N=await Q({config:s,cwd:m,host:C,port:A,bind:w,...o.serveContentAssets===void 0?{}:{serveContentAssets:o.serveContentAssets},...M?{reactShellDistDir:M}:{},idleThresholdMs:t(o.idleShutdown??E.idleShutdown),serverRuntime:E,...o.singleFile?{singleFile:o.singleFile}:{},...o.projectDir?{projectDir:o.projectDir}:{}})}catch(e){e instanceof q&&(console.error(f(e.message)),process.exit(1)),e instanceof J&&(console.error(f(e.message)),process.exit(1));let t=await import(`./src-pvuJUuAq.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),e instanceof t.ExposureConsentError&&(console.error(f(e.message)),process.exit(78)),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(f(e.message)),process.exit(1)),e instanceof t.MissingOkConfigError&&(console.error(f(e.message)),process.exit(1)),se(e,t)){let e=t.resolveLockDir(m),n=null;try{n=await ae({readServerLock:()=>t.readServerLock(e),now:Date.now,sleep:e=>I(e),timeoutMs:3e3,pollIntervalMs:50})}catch(e){process.stderr.write(`[start] spawn-or-reuse: lock poll failed (${e instanceof Error?e.message:String(e)}) — falling back to the collision message\n`)}if(n!==null){let[e,...t]=oe(n);console.log(u(e));for(let e of t)console.log(d(e));process.exit(0)}}let n=ce(e,m,t);n!==null&&(console.error(f(n)),process.exit(1)),console.error(`${f(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let P=!1,F=async e=>{if(P)return;P=!0;let[t,...n]=re(e);console.log(u(`\n${t}`));for(let e of n)console.log(d(` ${e}`));try{await N.destroy(`external-signal`)}catch(e){console.error(`${f(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{F(`SIGINT`)}),process.once(`SIGTERM`,()=>{F(`SIGTERM`)});let L=`http://${C.includes(`:`)&&!C.startsWith(`[`)?`[${C}]`:C}:${N.port}`,R=C===`0.0.0.0`||C===`::`?`http://0.0.0.0:${N.port}`:void 0,V=L;console.log(l({name:`open-knowledge`,version:D,localUrl:V,networkUrl:R,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let H={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};N.ready.then(async()=>{if(N.degraded.length>0){console.log();for(let e of N.degraded){let t=H[e]??`${e} (check server logs for details)`;console.warn(` ${p(`⚠`)} ${p(e)}: ${d(t)}`)}console.log()}if(W({openBrowser:o.openBrowser!==!1&&E.openBrowser,explicitOn:o.openBrowser!==!1&&g.server?.openBrowser===!0,host:C,isTTY:process.stdout.isTTY===!0,ephemeral:o.singleFile!==void 0,only:o.only,servesUi:M!==void 0})){let{openBrowser:e}=await import(`./open-browser-C8TrsdEd.mjs`);e(V)}}).catch(e=>{console.error(` ${f(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}async function ae(e){let t=e.now()+e.timeoutMs,n=e.readServerLock();for(;n!==null&&n.draining!==!0&&n.port<=0&&e.now()<t;)await e.sleep(e.pollIntervalMs),n=e.readServerLock();return n===null||n.draining===!0||n.port<=0?null:f(n)&&n.url!==void 0?{url:n.url,kind:n.kind,pid:n.pid,servesUi:!0}:{url:n.url??`http://127.0.0.1:${n.port}`,kind:n.kind,pid:n.pid,servesUi:!1}}function oe(e){return[`${e.kind===`mcp-spawned`?`An MCP-spawned OpenKnowledge server is already running on this project`:`OpenKnowledge is already running on this project`} (pid ${e.pid}).`,` ${e.url}`,"Leaving it running — run `ok stop` first if you want a fresh server."]}function se(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function ce(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=n.readServerLock(n.resolveLockDir(t));return e&&e.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function le(e){return new h(`start`).description(`Start the OpenKnowledge server (UI + API + MCP + collab on one port)`).option(`-p, --port <port>`,`Server port`,void 0).option(`--bind <address>`,`Bind address (repeatable; default 127.0.0.1 — loopback only)`,(e,t)=>[...t??[],e]).option(`--no-open-browser`,`Do not open the browser after start (interactive loopback starts open it by default)`).option(`--only <module>`,`Serve one module: 'server' (API + MCP only, no shell or browser)`,R).option(`--idle-shutdown <duration>`,`Shut the server down after this long with no connected clients ('off', or a duration like 90s, 30m, 2h; default 30m)`,V).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,te).option(`--serve-content-assets`,`Serve content assets from this server (now the default; kept for compatibility)`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path>`).addOption(new p(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).hideHelp()).addOption(new p(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).hideHelp()).option(`--external-url <url>`,`Canonical external origin clients dial (sets server.externalUrl for this run) — its host joins the Host/Origin allowlists (CORS + external-Host admission). External exposure additionally requires consent (OK_ALLOW_EXTERNAL=1 or server.allowExternal).`,G).action(async t=>{let n=e();if(t.only===`server`&&t.reactShellDistDir!==void 0&&(process.stderr.write(`error: option '--only server' cannot be combined with '--react-shell-dist-dir'
|
|
3
3
|
`),process.exit(2)),t.projectDir!==void 0&&t.singleFile===void 0&&(process.stderr.write(`error: option '--project-dir' requires '--single-file'
|
|
4
4
|
`),process.exit(2)),t.mode===`app`){let e=[];if(t.port!==void 0&&e.push(`--port`),t.bind!==void 0&&e.push(`--bind`),t.only!==void 0&&e.push(`--only`),t.idleShutdown!==void 0&&e.push(`--idle-shutdown`),t.openBrowser===!1&&e.push(`--no-open-browser`),t.externalUrl!==void 0&&e.push(`--external-url`),e.length>0){let t=process.env.OK_LOG_LEVEL??`info`;(t===`debug`||t===`trace`)&&console.error(`--mode=app: ignoring ${e.join(`, `)}`)}let n=w(x());if(n.available){g({spawn:O},n);return}console.error(y(n.reason)),process.exit(1)}await ie(n,t)})}export{ce as C,le as S,Z as T,ne as _,oe as a,W as b,Y as c,V as d,R as f,$ as g,ae as h,K as i,se as l,L as m,q as n,re as o,z as p,Q as r,H as s,J as t,G as u,B as v,X as w,U as x,ie as y};
|
|
5
|
-
//# sourceMappingURL=start-
|
|
5
|
+
//# sourceMappingURL=start-CsItXu7n.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{S as e,m as t,p as n,r}from"./start-CsItXu7n.mjs";export{r as bootStartServer,n as resolveBundledReactShellDir,t as resolveHost,e as startCommand};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inkeep/open-knowledge",
|
|
3
|
-
"version": "0.68.
|
|
3
|
+
"version": "0.68.14-beta.1",
|
|
4
4
|
"description": "Local-first, agent-friendly Markdown knowledge base with a cross-platform CLI and web editor",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"knowledge-base",
|
|
@@ -71,10 +71,10 @@
|
|
|
71
71
|
"ajv-formats": "^3.0.1",
|
|
72
72
|
"tsdown": "^0.21.7",
|
|
73
73
|
"typescript": "^5.9.3",
|
|
74
|
-
"@inkeep/open-knowledge-app": "0.68.13-beta.5",
|
|
75
74
|
"@inkeep/open-knowledge-native-config": "0.0.0",
|
|
76
|
-
"@inkeep/open-knowledge-
|
|
77
|
-
"@inkeep/open-knowledge-core": "0.68.
|
|
75
|
+
"@inkeep/open-knowledge-app": "0.68.14-beta.1",
|
|
76
|
+
"@inkeep/open-knowledge-core": "0.68.14-beta.1",
|
|
77
|
+
"@inkeep/open-knowledge-server": "0.68.14-beta.1"
|
|
78
78
|
},
|
|
79
79
|
"scripts": {
|
|
80
80
|
"build:cli": "rm -rf dist && tsdown",
|
package/dist/init-Vem_RIae.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./src-CeQWnH8P.mjs";import{g as e}from"./init-9FGTLE2n.mjs";export{e as runInit};
|
package/dist/loader-QGEaLJh_.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./loader-CF8NswTm.mjs";export{e as loadConfig};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./preview-D5Zr9LcW.mjs";export{t as formatPreviewBlock,e as previewContent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./index-6Bzxg85g.js";export{e as FeedbackForm};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./ManagedArtifactProperties-BSeDbox7.js";export{e as ManagedArtifactProperties};
|