@inkeep/open-knowledge 0.49.0-beta.23 → 0.49.0-beta.24
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-DHTPC2_O.mjs → acp-harness-probe-BUSbhOih.mjs} +2 -2
- package/dist/cli.mjs +7 -7
- package/dist/constants-D3YZBBb9.mjs +2 -0
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{init-CnXGfQDq.mjs → init-MCgaljSF.mjs} +3 -3
- package/dist/init-UTjBgomo.mjs +1 -0
- package/dist/{launch-json-removal-DYcqJsTT.mjs → launch-json-removal-BmDsNwPt.mjs} +2 -2
- package/dist/loader-B98DqiVc.mjs +1 -0
- package/dist/{loader-DSPsVV22.mjs → loader-ekJmDLtT.mjs} +2 -2
- package/dist/{open-browser-Dyp0opyo.mjs → open-browser-CxnOIVsL.mjs} +2 -2
- package/dist/preview-CUoBkJzj.mjs +1 -0
- package/dist/{preview-DmH53NEV.mjs → preview-DO6-cA5G.mjs} +2 -2
- package/dist/public/assets/{ActivityModeContent-BrGODY2p.js → ActivityModeContent-C08FYohG.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-FmW0Jthq.js → AgentDiffPane-T499-ugv.js} +1 -1
- package/dist/public/assets/{ChangedOutsideBadge-rT5rNbdQ.js → ChangedOutsideBadge-GeQfL_b-.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-DlE2CeLE.js → CodeMirrorPropInput-3TWUbzXY.js} +1 -1
- package/dist/public/assets/{DocumentContext-Dne83XLH.js → DocumentContext-C-Lo65-_.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-COteammg.js → EditorModeToggle-BjgmECAn.js} +1 -1
- package/dist/public/assets/{EnableSyncConfirmDialog-B54Vd_6F.js → EnableSyncConfirmDialog-B1Eo_sVE.js} +1 -1
- package/dist/public/assets/FeedbackForm-CmdTz11F.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-BCNx_uF4.js → ImportSkillDialog-ChsGV6eb.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-DjnEiT_w.js → LintConfigEditor-3f4-NF1O.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-nt-GCVB6.js → ManagedArtifactProperties-B1ZA0ofn.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-B_ecuboX.js +1 -0
- package/dist/public/assets/{MermaidDocEditor-mVJYUSOz.js → MermaidDocEditor-C30-UfMg.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-D1wdCvtf.js → SchemaConfigEditor-DPK5XbMd.js} +1 -1
- package/dist/public/assets/{SessionsHost-B64xibFa.js → SessionsHost-BobZkNwc.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-BehtaY5A.js → SettingsDialogBody-COTbFRqi.js} +1 -1
- package/dist/public/assets/{ShareReceiveMissDialog-j1zpEPgU.js → ShareReceiveMissDialog-B03ClkaE.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-DB2qTJQy.js → SkillToolbarControls-PvRY_LHn.js} +1 -1
- package/dist/public/assets/{SourceEditor-BzCwwYJX.js → SourceEditor-Duqpede9.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-CEJqmPwc.js → TerminalWindowApp-CgWp2eC-.js} +1 -1
- package/dist/public/assets/{TextDocEditor-CwKsLSYj.js → TextDocEditor-CHDC5byq.js} +1 -1
- package/dist/public/assets/{ThreadView-TiaaWpue.js → ThreadView-VqdgemBS.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-BQQyzTIK.js → TimelineDiffPane-DnaRcvCk.js} +1 -1
- package/dist/public/assets/{agent-diff-store-C2OrIeX2.js → agent-diff-store-B7oQn7l7.js} +1 -1
- package/dist/public/assets/{auth-state-cache-C9jGBLXQ.js → auth-state-cache-BUYyIMUZ.js} +1 -1
- package/dist/public/assets/{comment-chips-CQarmZw-.js → comment-chips-BhvfCPCk.js} +1 -1
- package/dist/public/assets/{config-provider-DY4FjDlE.js → config-provider-B7dMDFNr.js} +3 -3
- package/dist/public/assets/{follow-file-Bnld7t21.js → follow-file-CWSsUd-S.js} +1 -1
- package/dist/public/assets/i18n-CIRn0AvV.js +1 -0
- package/dist/public/assets/{index-DrvUuXnw.js → index-Dmlpu4P1.js} +7 -7
- package/dist/public/assets/messages-6Fd7I7zn.js +1 -0
- package/dist/public/assets/messages-BJIB1I1L.js +1 -0
- package/dist/public/assets/messages-BOXmrfhw.js +1 -0
- package/dist/public/assets/messages-BeOM8jWl.js +1 -0
- package/dist/public/assets/messages-CCWKIebo.js +1 -0
- package/dist/public/assets/messages-CQFityfC.js +1 -0
- package/dist/public/assets/messages-CzRXVtjz.js +1 -0
- package/dist/public/assets/messages-DYiuNk7y.js +1 -0
- package/dist/public/assets/messages-Db5U-G1d.js +1 -0
- package/dist/public/assets/messages-DohtKbKM.js +1 -0
- package/dist/public/assets/messages-WWFblTuV.js +1 -0
- package/dist/public/assets/{pending-receive-nav-store-CGk3bMB9.js → pending-receive-nav-store-SZ8w-xKW.js} +1 -1
- package/dist/public/assets/{selection-context-B4Z8zSar.js → selection-context-CSP8zK1H.js} +1 -1
- package/dist/public/assets/{skill-actions-ggcP_3dF.js → skill-actions-98H3SnCL.js} +1 -1
- package/dist/public/assets/{src-CiyQ3sov.js → src-VcUCSe0b.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-Cz38cmdR.js → typing-burst-detector-BOmjXV-P.js} +1 -1
- package/dist/public/assets/{uninstall-BgGdjAhC.js → uninstall-36twrq5C.js} +1 -1
- package/dist/public/assets/{use-activity-panel-BhetneWD.js → use-activity-panel-BwANCYjg.js} +1 -1
- package/dist/public/assets/{use-open-skill-B_JUaxIs.js → use-open-skill-DCSEJ3jJ.js} +1 -1
- package/dist/public/assets/use-settings-route-CKMxexs3.js +1 -0
- package/dist/public/assets/{use-skill-directory-5lm6x97m.js → use-skill-directory-D9S5f8By.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-CVALUkgl.js → use-terminal-enabled-Ctosnrg_.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-CmSMq0O7.js → use-timeline-entry-diff-CB_cI1yy.js} +1 -1
- package/dist/public/index.html +21 -21
- package/dist/public/uninstall.html +3 -3
- package/dist/{repair-launch-json-gt_xu8VR.mjs → repair-launch-json-BWUKaV3g.mjs} +2 -2
- package/dist/{repair-mcp-configs-CZap0wph.mjs → repair-mcp-configs-Bmgf-Fxv.mjs} +2 -2
- package/dist/{repair-skills-BKmAMyDn.mjs → repair-skills-CkZZbtNk.mjs} +2 -2
- package/dist/repair-skills-l9Id0gzv.mjs +1 -0
- package/dist/{skill-teardown-OyFyNPGz.mjs → skill-teardown-CZnemDLF.mjs} +2 -2
- package/dist/{src-BdylDHZb.mjs → src-9I3GiOoK.mjs} +3 -3
- package/dist/{src-CVfzGd-H.mjs → src-D9aX2_QH.mjs} +2 -2
- package/dist/{src-BVdLRbuK.mjs → src-h5dDPK2z.mjs} +1 -1
- package/dist/start-C6P7_3_m.mjs +1 -0
- package/dist/{start-DPV97Qyi.mjs → start-QAIJ6Ttm.mjs} +3 -3
- package/dist/{write-project-skill-jv0sIzZJ.mjs → write-project-skill-WXZSbQlg.mjs} +2 -2
- package/package.json +5 -5
- package/dist/constants-Db61uBoY.mjs +0 -2
- package/dist/init-Cg4cmiPF.mjs +0 -1
- package/dist/loader-h6m6KsF2.mjs +0 -1
- package/dist/preview-2nRdxeOJ.mjs +0 -1
- package/dist/public/assets/FeedbackForm-V1teW6On.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-BUuq-eWT.js +0 -1
- package/dist/public/assets/i18n-Ckp5vyuq.js +0 -1
- package/dist/public/assets/messages-B6_1Ejgf.js +0 -1
- package/dist/public/assets/messages-BIeTbEwr.js +0 -1
- package/dist/public/assets/messages-C5keGFu8.js +0 -1
- package/dist/public/assets/messages-CdE758JS.js +0 -1
- package/dist/public/assets/messages-DH9PADx7.js +0 -1
- package/dist/public/assets/messages-DjGb_ycu.js +0 -1
- package/dist/public/assets/messages-DododtZ5.js +0 -1
- package/dist/public/assets/messages-Du4LAkbI.js +0 -1
- package/dist/public/assets/messages-DumBz2db.js +0 -1
- package/dist/public/assets/messages-nrpTbeRu.js +0 -1
- package/dist/public/assets/messages-vu7QED0b.js +0 -1
- package/dist/public/assets/use-settings-route-DnETJDgF.js +0 -1
- package/dist/repair-skills-B8raYZKq.mjs +0 -1
- package/dist/start-CqvbbRHD.mjs +0 -1
|
@@ -6,7 +6,7 @@ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{At as r,Ct as i,D
|
|
|
6
6
|
`;n.right=new mb(xv(o,Nv(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new cb(i)),n.right.integrate(e,0),n.forward()}By(e,t,n,s)},Ky=(e,t,n,r,i)=>{let a=t,o=ih();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===ob){let e=a.content;o.set(e.key,e)}a=a.right}let s=0,c=!1;for(;t!==a;){if(n===t&&(c=!0),!t.deleted){let n=t.content;switch(n.constructor){case ob:{let{key:a,value:l}=n,u=r.get(a)??null;(o.get(a)!==n||u===l)&&(t.delete(e),s++,!c&&(i.get(a)??null)===l&&u!==l&&(u===null?i.delete(a):i.set(a,u))),!c&&!t.deleted&&Vy(i,n);break}}}t=t.right}return s},fie=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===ob){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},pie=e=>{let t=0;return Yv(e.doc,n=>{let r=e._start,i=e._start,a=ih(),o=ah(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case ob:Vy(o,i.content);break;default:t+=Ky(n,r,i,a,o),a=ah(o),r=i;break}i=i.right}}),t},mie=e=>{let t=new Set,n=e.doc;for(let[r,i]of e.afterState.entries()){let a=e.beforeState.get(r)||0;i!==a&&Vv(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===ob&&e.constructor!==eb&&t.add(e.parent)})}Yv(n,n=>{k_(e,e.deleteSet,e=>{if(e instanceof eb||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===ob?t.add(r):fie(n,e)});for(let e of t)pie(e)})},qy=(e,t,n)=>{let r=n,i=ah(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case lb:case ab:case cb:n<t.right.length&&Rv(e,xv(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}a&&Ky(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&gy(o._searchMarker,t.index,-r+n),t};var hie=class extends dy{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{e===null?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(this._changes===null){let e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];Yv(e,e=>{let n=new Map,r=new Map,i=this.target._start,a=null,o={},s=``,c=0,l=0,u=()=>{if(a!==null){let e=null;switch(a){case`delete`:l>0&&(e={delete:l}),l=0;break;case`insert`:(typeof s==`object`||s.length>0)&&(e={insert:s},n.size>0&&(e.attributes={},n.forEach((t,n)=>{t!==null&&(e.attributes[n]=t)}))),s=``;break;case`retain`:c>0&&(e={retain:c},Vg(o)||(e.attributes=Lg({},o))),c=0;break}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case lb:case ab:this.adds(i)?this.deletes(i)||(u(),a=`insert`,s=i.content.getContent()[0],u()):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=1):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=1);break;case cb:this.adds(i)?this.deletes(i)||(a!==`insert`&&(u(),a=`insert`),s+=i.content.str):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=i.length):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=i.length);break;case ob:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(Iy(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),Iy(s,r.get(t)??null)?delete o[t]:o[t]=s));else if(this.deletes(i)){r.set(t,s);let e=n.get(t)??null;Iy(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(Iy(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),Vy(n,i.content));break}}i=i.right}for(u();t.length>0;){let e=t[t.length-1];if(e.retain!==void 0&&e.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},Jy=class e extends vy{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??fy(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){console.error(e)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);let n=new hie(this,e,t);_y(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??fy();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===cb&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc===null?this._pending.push(()=>this.applyDelta(e)):Yv(this.doc,n=>{let r=new Ly(null,this._start,0,new Map);for(let i=0;i<e.length;i++){let a=e[i];if(a.insert!==void 0){let o=!t&&typeof a.insert==`string`&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
|
|
7
7
|
`?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&Wy(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&qy(n,r,a.delete):Gy(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??fy();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(Dv(s,e)||t!==void 0&&Dv(s,t))switch(s.content.constructor){case cb:{let r=i.get(`ychange`);e!==void 0&&!Dv(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!Dv(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case lb:case ab:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case ob:Dv(s,e)&&(c(),Vy(i,s.content));break}s=s.right}c()};return e||t?Yv(a,n=>{e&&Ov(n,e),t&&Ov(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):Yv(r,r=>{let i=zy(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),Wy(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):Yv(r,r=>{let i=zy(r,this,e,!n);Wy(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):Yv(n,n=>{qy(n,zy(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):Yv(r,r=>{let i=zy(r,this,e,!1);i.right!==null&&Gy(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):Yv(this.doc,t=>{Oy(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):Yv(this.doc,n=>{ky(n,this,e,t)})}getAttribute(e){return Ay(this,e)}getAttributes(){return jy(this)}_write(e){e.writeTypeRef(Iie)}};const gie=e=>new Jy;var Yy=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??fy()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===Zy||t.constructor===Xy)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}else e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},Xy=class e extends vy{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof vy?e.clone():e)),t}get length(){return this.doc??fy(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Yy(this,e)}querySelector(e){e=e.toUpperCase();let t=new Yy(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),dh(new Yy(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){_y(this,e,new yie(this,t,e))}toString(){return Sy(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),xy(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Yv(this.doc,n=>{Ey(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)Yv(this.doc,n=>{let r=e&&e instanceof vy?e._item:e;wy(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw og(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Yv(this.doc,n=>{Dy(n,this,e,t)})}toArray(){return by(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Cy(this,e)}slice(e=0,t=this.length){return yy(this,e,t)}forEach(e){xy(this,e)}_write(e){e.writeTypeRef(Rie)}};const _ie=e=>new Xy;var Zy=class e extends Xy{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return zg(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof vy?e.clone():e)),t}toString(){let e=this.getAttributes(),t=[],n=[];for(let t in e)n.push(t);n.sort();let r=n.length;for(let i=0;i<r;i++){let r=n[i];t.push(r+`="`+e[r]+`"`)}let i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?` `+t.join(` `):``}>${super.toString()}</${i}>`}removeAttribute(e){this.doc===null?this._prelimAttrs.delete(e):Yv(this.doc,t=>{Oy(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):Yv(this.doc,n=>{ky(n,this,e,t)})}getAttribute(e){return Ay(this,e)}hasAttribute(e){return My(this,e)}getAttributes(e){return e?sie(this,e):jy(this)}toDOM(e=document,t={},n){let r=e.createElement(this.nodeName),i=this.getAttributes();for(let e in i){let t=i[e];typeof t==`string`&&r.setAttribute(e,t)}return xy(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Lie),e.writeKey(this.nodeName)}};const vie=e=>new Zy(e.readKey());var yie=class extends dy{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{e===null?this.childListChanged=!0:this.attributesChanged.add(e)})}},bie=class e extends Fy{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){let t=new e(this.hookName);return this.forEach((e,n)=>{t.set(n,e)}),t}toDOM(e=document,t={},n){let r=t[this.hookName],i;return i=r===void 0?document.createElement(this.hookName):r.createDom(this),i.setAttribute(`data-yjs-hook`,this.hookName),n!==void 0&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(zie),e.writeKey(this.hookName)}};const xie=e=>new bie(e.readKey());var Qy=class e extends Jy{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,n){let r=e.createTextNode(this.toString());return n!==void 0&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{let t=[];for(let n in e.attributes){let r=[];for(let t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:n,attrs:r})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n=``;for(let e=0;e<t.length;e++){let r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){let t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=`>`}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n}).join(``)}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Bie)}};const Sie=e=>new Qy;var $y=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw sg()}mergeWith(e){return!1}write(e,t,n){throw sg()}integrate(e,t){throw sg()}},eb=class extends $y{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Pv(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},tb=class e{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(e){throw sg()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}};const Cie=e=>new tb(e.readBuf());var nb=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){let n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){P_(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}};const wie=e=>new nb(e.readLen()),rb=(e,t)=>new H_({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});var ib=class e{constructor(e){e._item&&console.error(`This document was already integrated as a sub-document. You should create a second instance instead with the same guid.`),this.doc=e;let t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(rb(this.doc.guid,this.opts))}splice(e){throw sg()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}};const Tie=e=>new ib(rb(e.readString(),e.readAny()));var ab=class e{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(e){throw sg()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}};const Eie=e=>new ab(e.readJSON());var ob=class e{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(e){throw sg()}mergeWith(e){return!1}integrate(e,t){let n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}};const Die=e=>new ob(e.readKey(),e.readJSON());var Oie=class e{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeString(t===void 0?`undefined`:JSON.stringify(t))}}getRef(){return 2}};const kie=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++){let t=e.readString();t===`undefined`?n.push(void 0):n.push(JSON.parse(t))}return new Oie(n)},Aie=n_(`node_env`)===`development`;var sb=class e{constructor(e){this.arr=e,Aie&&Kg(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeAny(t)}}getRef(){return 8}};const jie=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new sb(n)};var cb=class e{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split(``)}isCountable(){return!0}copy(){return new e(this.str)}splice(t){let n=new e(this.str.slice(t));this.str=this.str.slice(0,t);let r=this.str.charCodeAt(t-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+`�`,n.str=`�`+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}};const Mie=e=>new cb(e.readString()),Nie=[lie,die,gie,vie,_ie,xie,Sie],Pie=0,Fie=1,Iie=2,Lie=3,Rie=4,zie=5,Bie=6;var lb=class e{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(e){throw sg()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;t!==null;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}};const Vie=e=>new lb(Nie[e.readTypeRef()](e)),Hie=(e,t)=>{let n=t,r=0,i;do r>0&&(n=xv(n.client,n.clock+r)),i=Iv(e,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof mb);return{item:i,diff:r}},ub=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},db=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new mb(xv(r,i+n),t,xv(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&a.markDeleted(),t.keep&&(a.keep=!0),t.redone!==null&&(a.redone=xv(t.redone.client,t.redone.clock+n)),t.right=a,a.right!==null&&(a.right.left=a),e._mergeStructs.push(a),a.parentSub!==null&&a.right===null&&a.parent._map.set(a.parentSub,a),t.length=n,a},fb=(e,t)=>fh(e,e=>j_(e.deletions,t)),pb=(e,t,n,r,i,a)=>{let o=e.doc,s=o.store,c=o.clientID,l=t.redone;if(l!==null)return Rv(e,l);let u=t.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||pb(e,u,n,r,i,a)===null))return null;for(;u.redone!==null;)u=Rv(e,u.redone)}let p=u===null?t.parent:u.content.type;if(t.parentSub===null){for(d=t.left,f=t;d!==null;){let t=d;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Rv(e,t.redone);if(t!==null&&t.parent._item===u){d=t;break}d=d.left}for(;f!==null;){let t=f;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Rv(e,t.redone);if(t!==null&&t.parent._item===u){f=t;break}f=f.right}}else{if(f=null,t.right&&!i){for(d=t;d!==null&&d.right!==null&&(d.right.redone||j_(r,d.right.id)||fb(a.undoStack,d.right.id)||fb(a.redoStack,d.right.id));)for(d=d.right;d.redone;)d=Rv(e,d.redone);if(d&&d.right!==null)return null}else d=p._map.get(t.parentSub)||null;d!==null&&d.parent._item!==u&&(d=p._map.get(t.parentSub)||null)}let m=xv(c,Nv(s,c)),h=new mb(m,d,d&&d.lastId,f,f&&f.id,p,t.parentSub,t.content.copy());return t.redone=m,ub(h,!0),h.integrate(e,0),h};var mb=class e extends $y{constructor(e,t,n,r,i,a,o,s){super(e,s.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=a,this.parentSub=o,this.redone=null,this.content=s,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Nv(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Nv(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===yv&&this.id.client!==this.parent.client&&this.parent.clock>=Nv(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=zv(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=Rv(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===eb||this.right&&this.right.constructor===eb)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===yv){let e=Iv(n,this.parent);e.constructor===eb?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=zv(e,e.doc.store,xv(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let t=this.left,n;if(t!==null)n=t.right;else if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start;let r=new Set,i=new Set;for(;n!==null&&n!==this.right;){if(i.add(n),r.add(n),bv(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(bv(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(Iv(e.doc.store,n.origin)))r.has(Iv(e.doc.store,n.origin))||(t=n,r.clear());else break;n=n.right}this.left=t}if(this.left!==null){let e=this.left.right;this.right=e,this.left.right=this}else{let e;if(this.parentSub!==null)for(e=this.parent._map.get(this.parentSub)||null;e!==null&&e.left!==null;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}this.right===null?this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)):this.right.left=this,this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Pv(e.doc.store,this),this.content.integrate(e,this),Wv(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new eb(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:xv(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&bv(e.origin,this.lastId)&&this.right===e&&bv(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){let t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),P_(e.deleteSet,this.id.client,this.id.clock,this.length),Wv(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw cg();this.content.gc(e),t?Bv(e,this,new eb(this.id,this.length)):this.content=new nb(this.length)}write(e,t){let n=t>0?xv(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,a=this.content.getRef()&31|(n===null?0:128)|(r===null?0:64)|(i===null?0:32);if(e.writeInfo(a),n!==null&&e.writeLeftID(n),r!==null&&e.writeRightID(r),n===null&&r===null){let t=this.parent;if(t._item!==void 0){let n=t._item;if(n===null){let n=Sv(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===yv?(e.writeParentInfo(!1),e.writeLeftID(t)):cg();i!==null&&e.writeString(i)}this.content.write(e,t)}};const hb=(e,t)=>Uie[t&31](e),Uie=[()=>{cg()},wie,kie,Cie,Mie,Eie,Die,Vie,jie,Tie,()=>{cg()}];var gb=class extends $y{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){cg()}write(e,t){e.writeInfo(10),Bh(e.restEncoder,this.length-t)}getMissing(e,t){return null}};const _b=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},vb=`__ $YJS$ __`;_b[vb]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),_b[vb]=!0;const Wie=/[\uD800-\uDBFF]/,Gie=/[\uDC00-\uDFFF]/,Kie=(e,t)=>{let n=0,r=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;for(n>0&&Wie.test(e[n-1])&&n--;r+n<e.length&&r+n<t.length&&e[e.length-r-1]===t[t.length-r-1];)r++;return r>0&&Gie.test(e[e.length-r])&&r--,{index:n,remove:e.length-n-r,insert:t.slice(n,t.length-r)}},qie=e=>{let t=lu(`sha256`);return t.update(e),t.digest()},Jie=new uo(`y-sync`);new uo(`y-undo`),new uo(`yjs-cursor`);const Yie=e=>{for(let t=6;t<e.length;t++)e[t%6]=e[t%6]^e[t];return e.slice(0,6)},Xie=e=>o_(Yie(qie(c_(e)))),Zie=()=>({mapping:new Map,isOMark:new Map}),yb=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&t.sv.get(e.id.client)>e.id.clock&&!j_(t.ds,e.id),Qie=(e,t,n,r,i,a)=>{let o=n.mapping.get(e);if(o===void 0){if(e instanceof Zy)return bb(e,t,n,r,i,a);throw sg()}return o},bb=(e,t,n,r,i,a)=>{let o=[],s=e=>{if(e instanceof Zy){let s=Qie(e,t,n,r,i,a);s!==null&&o.push(s)}else{let s=e._item.right?.content?.type;s instanceof Jy&&!s._item.deleted&&s._item.id.client===s.doc.clientID&&(e.applyDelta([{retain:e.length},...s.toDelta()]),s.doc.transact(e=>{s._item.delete(e)}));let c=$ie(e,t,n,r,i,a);c!==null&&c.forEach(e=>{e!==null&&o.push(e)})}};r===void 0||i===void 0?e.toArray().forEach(s):iie(e,new wv(i.ds,r.sv)).forEach(s);try{let s=e.getAttributes(r);r!==void 0&&(yb(e._item,r)?yb(e._item,i)||(s.ychange=a?a(`added`,e._item.id):{type:`added`}):s.ychange=a?a(`removed`,e._item.id):{type:`removed`});let c=Db(s),l=Mb(c.marks,t),u=t.node(e.nodeName,c.plain,o,l.length?l:void 0);return n.mapping.set(e,u),u}catch(r){console.warn(`[y-prosemirror] schema.node(`+e.nodeName+`) threw:`,String(r&&r.message||r));let i=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};if(t.nodes[e.nodeName]&&t.nodes[e.nodeName].spec&&t.nodes[e.nodeName].spec.inline)i.inline++;else if(i.block++,t.nodes.rawMdxFallback)try{let i=t.node(`rawMdxFallback`,{reason:String(r&&r.message||r)},[t.text(e.nodeName)]);return n.mapping.set(e,i),i}catch(e){console.warn(`[y-prosemirror] rawMdxFallback substitution also failed:`,String(e&&e.message||e))}return n.mapping.delete(e),null}},$ie=(e,t,n,r,i,a)=>{let o=[],s=e.toDelta(r,i,a);try{for(let e=0;e<s.length;e++){let n=s[e];o.push(t.text(n.insert,Mb(n.attributes,t)))}}catch(e){console.warn(`[y-prosemirror] schema.text() threw:`,String(e&&e.message||e));let t=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};return t.inline++,null}return o},eae=(e,t)=>{let n=new Qy,r=e.map(e=>({insert:e.text,attributes:Nb(e.marks,t)}));return n.applyDelta(r),t.mapping.set(n,e),n},tae=(e,t)=>{let n=new Zy(e.type.name);for(let t in e.attrs){let r=e.attrs[t];r!==null&&t!==`ychange`&&n.setAttribute(t,r)}let r=Nb(e.marks||[],t);for(let e in r)n.setAttribute(Eb+e,{...r[e]});return n.insert(0,wb(e).map(e=>xb(e,t))),t.mapping.set(n,e),n},xb=(e,t)=>e instanceof Array?eae(e,t):tae(e,t),Sb=e=>typeof e==`object`&&!!e,Cb=(e,t)=>{let n=Object.keys(e).filter(t=>e[t]!==null),r=n.length===Object.keys(t).filter(e=>t[e]!==null).length;for(let i=0;i<n.length&&r;i++){let a=n[i],o=e[a],s=t[a];r=a===`ychange`||o===s||Sb(o)&&Sb(s)&&Cb(o,s)}return r},wb=e=>{let t=e.content.content,n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.isText){let r=[];for(let n=t[e];e<t.length&&n.isText;n=t[++e])r.push(n);e--,n.push(r)}else n.push(r)}return n},Tb=(e,t)=>{let n=e.toDelta();return n.length===t.length&&n.every((e,n)=>e.insert===t[n].text&&Rg(e.attributes||{}).length===t[n].marks.length&&Hg(e.attributes,(e,r)=>{let i=jb(r),a=t[n].marks;return a.find(e=>e.type.name===i)?Cb(e,a.find(e=>e.type.name===i)?.attrs):!1}))},Eb=`ymark:`,Db=e=>{let t={},n={};for(let r in e)r.startsWith(Eb)?n[r.slice(6)]=e[r]:t[r]=e[r];return{plain:t,marks:n}},nae=(e,t)=>{let n=Object.keys(e);return n.length===t.length?n.every(n=>{let r=jb(n),i=t.find(e=>e.type.name===r);return i?Cb(e[n],i.attrs):!1}):!1},Ob=(e,t)=>{if(e instanceof Zy&&!(t instanceof Array)&&Fb(e,t)){let n=wb(t),r=Db(e.getAttributes());return e._length===n.length&&nae(r.marks,t.marks)&&Cb(r.plain,t.attrs)&&e.toArray().every((e,t)=>Ob(e,n[t]))}return e instanceof Qy&&t instanceof Array&&Tb(e,t)},kb=(e,t)=>e===t||e instanceof Array&&t instanceof Array&&e.length===t.length&&e.every((e,n)=>t[n]===e),Ab=(e,t,n)=>{let r=e.toArray(),i=wb(t),a=i.length,o=r.length,s=_h(o,a),c=0,l=0,u=!1;for(;c<s;c++){let e=r[c],t=i[c];if(kb(n.mapping.get(e),t))u=!0;else if(!Ob(e,t))break}for(;c+l<s;l++){let e=r[o-l-1],t=i[a-l-1];if(kb(n.mapping.get(e),t))u=!0;else if(!Ob(e,t))break}return{equalityFactor:c+l,foundMappedChild:u}},rae=e=>{let t=``,n=e._start,r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof cb?t+=n.content.str:n.content instanceof ob&&(r[n.content.key]=null)),n=n.right;return{str:t,nAttrs:r}},iae=(e,t,n)=>{n.mapping.set(e,t);let{nAttrs:r,str:i}=rae(e),a=t.map(e=>({insert:e.text,attributes:Object.assign({},r,Nb(e.marks,n))})),{insert:o,remove:s,index:c}=Kie(i,a.map(e=>e.insert).join(``));e.delete(c,s),e.insert(c,o),e.applyDelta(a.map(e=>({retain:e.insert.length,attributes:e.attributes})))},aae=/(.*)(--[a-zA-Z0-9+/=]{8})$/,jb=e=>aae.exec(e)?.[1]??e,Mb=(e,t)=>{let n=[];for(let r in e)n.push(t.mark(jb(r),e[r]));return n},Nb=(e,t)=>{let n={};return e.forEach(e=>{if(e.type.name!==`ychange`){let r=oh(t.isOMark,e.type,()=>!e.type.excludes(e.type));n[r?`${e.type.name}--${Xie(e.toJSON())}`:e.type.name]=e.attrs}}),n},Pb=(e,t,n,r)=>{if(t instanceof Zy&&t.nodeName!==n.type.name)throw Error(`node name mismatch!`);if(r.mapping.set(t,n),t instanceof Zy){let e=t.getAttributes(),i=n.attrs;for(let n in i)i[n]===null?t.removeAttribute(n):e[n]!==i[n]&&n!==`ychange`&&t.setAttribute(n,i[n]);for(let n in e)i[n]===void 0&&!n.startsWith(Eb)&&t.removeAttribute(n);let a=Nb(n.marks||[],r);for(let n in a){let r=e[Eb+n];(r===void 0||!Cb(r,a[n]))&&t.setAttribute(Eb+n,{...a[n]})}for(let n in e)n.startsWith(Eb)&&a[n.slice(6)]===void 0&&t.removeAttribute(n)}let i=wb(n),a=i.length,o=t.toArray(),s=o.length,c=_h(a,s),l=0,u=0;for(;l<c;l++){let e=o[l],t=i[l];if(!kb(r.mapping.get(e),t))if(Ob(e,t))r.mapping.set(e,t);else break}for(;u+l+1<c;u++){let e=o[s-u-1],t=i[a-u-1];if(!kb(r.mapping.get(e),t))if(Ob(e,t))r.mapping.set(e,t);else break}e.transact(()=>{for(;s-l-u>0&&a-l-u>0;){let n=o[l],c=i[l],d=o[s-u-1],f=i[a-u-1];if(n instanceof Qy&&c instanceof Array)Tb(n,c)||iae(n,c,r),l+=1;else{let i=n instanceof Zy&&Fb(n,c),a=d instanceof Zy&&Fb(d,f);if(i&&a){let e=Ab(n,c,r),t=Ab(d,f,r);e.foundMappedChild&&!t.foundMappedChild?a=!1:!e.foundMappedChild&&t.foundMappedChild||e.equalityFactor<t.equalityFactor?i=!1:a=!1}i?(Pb(e,n,c,r),l+=1):a?(Pb(e,d,f,r),u+=1):(r.mapping.delete(t.get(l)),t.delete(l,1),t.insert(l,[xb(c,r)]),l+=1)}}let n=s-l-u;if(s===1&&a===0&&o[0]instanceof Qy?(r.mapping.delete(o[0]),o[0].delete(0,o[0].length)):n>0&&(t.slice(l,l+n).forEach(e=>r.mapping.delete(e)),t.delete(l,n)),l+u<a){let e=[];for(let t=l;t<a-u;t++)e.push(xb(i[t],r));t.insert(l,e)}},Jie)},Fb=(e,t)=>!(t instanceof Array)&&e.nodeName===t.type.name,oae=(e,t)=>{let n=e.toArray().map(e=>bb(e,t,Zie())).filter(e=>e!==null);return Wn.fromArray(n)},Ib=(e,t)=>t.topNodeType.create(null,oae(e,t));function Lb(e,t,n,r){let{body:i}=Qa(t);return r!==void 0&&r.rawContent===t?r.parsedJson:Po(`md.parseWithFallback`,{attributes:{"body.bytes":i.length,"doc.name":e.guid}},()=>Ao.parseWithFallback(i,Rb(n)))}function Rb(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function zb(e){return Ao.serialize(Ib(e,ko).toJSON())}function Bb(e,t,n,r,i,a){let o=zb(r),s=Ao.serialize(n),{body:c}=Qa(e.baselineFullMd),l=Ao.serialize(Ao.parseWithFallback(c,a));e.report({pendingBody:t,baselineBody:l,ytextDerivedBody:s,rebuiltBody:o,restorePayload:ln(i,t).md})}function Vb(e,t,n,r,i,a){Po(`bridge.composeAndWriteRawBody`,{attributes:{surface:n,"body.bytes":t.length,"doc.name":e.guid}},()=>{let n=e.getXmlFragment(`default`),o=e.getText(`source`),s=o.toString(),c=Lb(e,t,r,i),l=ko.nodeFromJSON(c),u=a?zb(n):void 0;if(s!==t&&Dn(o,s,t),Pb(e,n,l,{mapping:new Map,isOMark:new Map}),a&&u!==void 0){let{frontmatter:e}=Qa(a.baselineFullMd);Bb(a,u,c,n,e,Rb(r))}})}function Hb(e,t,n,r,i){Po(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let a=e.getXmlFragment(`default`),o=e.getText(`source`),s=Lb(e,t,n,r),c=ko.nodeFromJSON(s),l=i?zb(a):void 0,u=o.toString();if(u!==t&&(o.delete(0,u.length),o.insert(0,t)),Pb(e,a,c,{mapping:new Map,isOMark:new Map}),i&&l!==void 0){let{frontmatter:e}=Qa(i.baselineFullMd);Bb(i,l,s,a,e,Rb(n))}})}function sae(e,t,n){let r=e.getXmlFragment(`default`),{frontmatter:i,body:a}=Qa(e.getText(`source`).toString()),o=Rb(t),s=Ao.parseWithFallback(a,o),c=ko.nodeFromJSON(s),l=n?Ao.serialize(Ib(r,ko).toJSON()):void 0;if(Pb(e,r,c,{mapping:new Map,isOMark:new Map}),n&&l!==void 0){let e=Ao.serialize(Ib(r,ko).toJSON()),t=Ao.serialize(s),{body:a}=Qa(n.baselineFullMd),c=Ao.serialize(Ao.parseWithFallback(a,o));n.report({pendingBody:l,baselineBody:c,ytextDerivedBody:t,rebuiltBody:e,restorePayload:ln(i,l).md})}}const cae=I(`loss-capture`),Ub=`detector-trip`,Wb=`backstop-trip`,Gb=`checkpoint-write`;N({ts:P(),schemaVersion:P(),seq:P(),event:F(),docName:F(),writerId:F().nullable(),site:F().optional(),direction:F().optional(),lostLen:P().optional(),digest:F().optional(),checkpointSha:F().optional()});const Kb=[`.ok`,`local`,`loss-capture`];function lae(e){return R(e,...Kb,`loss-current.jsonl`)}function uae(e){return R(e,...Kb,`loss-prev.jsonl`)}var dae=class{#e;#t;#n=new Map;constructor(e){this.#e=new vs({currentPath:lae(e.projectDir),previousPath:uae(e.projectDir),maxBytes:e.maxBytes}),this.#t=e.now??Date.now}record(e){let t=(this.#n.get(e.docName)??0)+1;this.#n.set(e.docName,t);let n={ts:this.#t(),schemaVersion:1,seq:t,event:e.event,docName:e.docName,writerId:e.writerId,...e.site===void 0?{}:{site:e.site},...e.direction===void 0?{}:{direction:e.direction},...e.lostLen===void 0?{}:{lostLen:e.lostLen},...e.digest===void 0?{}:{digest:e.digest},...e.checkpointSha===void 0?{}:{checkpointSha:e.checkpointSha}};return this.#e.append(`${JSON.stringify(n)}\n`).catch(t=>{cae.warn({event:e.event,err:t},`[loss-capture] failed to write loss-class event`)})}async drain(){await this.#e.drain()}};const qb=I(`checkpoint-chain`);async function Jb(e,t){let n;try{n=await e.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch(e){throw qb.warn({branch:t,err:e},`[checkpoint-chain] for-each-ref failed; anchors are unknown`),e}let r=n.trim().split(`
|
|
8
8
|
`).map(e=>e.trim()).filter(e=>e.length===40);if(r.length===0)return[];let i;try{i=await e.raw(`log`,`--no-walk`,`--format=%H%x00%B%x1e`,...r)}catch(e){throw qb.warn({branch:t,shaCount:r.length,err:e},`[checkpoint-chain] checkpoint body read failed; anchors are unknown`),e}let a=[];for(let e of i.split(``)){let t=e.trimStart();if(!t)continue;let[n=``,r=``]=t.split(`\0`);n.length===40&&sa(wi(r)?.kind??null)&&a.push(n)}if(a.length<=1)return a;try{let t=(await e.raw(`merge-base`,`--independent`,...a)).trim().split(`
|
|
9
|
-
`).map(e=>e.trim()).filter(e=>e.length===40);return t.length>0?t:a}catch(e){return qb.warn({branch:t,anchorCount:a.length,err:e},`[checkpoint-chain] tip reduction failed; adopting the full anchor set`),a}}function fae(e){return e.split(`\0`).filter(e=>e.length>0)}function pae(e){let t=[],n=e.split(`\0`);for(let e=0;e<n.length;e++){let r=n[e]??``;r.length<4||(t.push(r.slice(3)),(r[0]===`R`||r[0]===`C`)&&e++)}return t}function mae(e){let t=e.split(`\0`),n=[],r=0;for(;r<t.length;){let e=t[r]??``;if(e===``)break;if(e[0]===`R`||e[0]===`C`)n.push({status:e,from:t[r+1]??``,to:t[r+2]??``}),r+=3;else{let i=t[r+1]??``;n.push({status:e,from:i,to:i}),r+=2}}return n}function hae(e){let t=[];for(let n of e.split(`\0`)){if(!n)continue;let e=n.indexOf(` `);if(e<0)continue;let[r=``,i=``,a=``,o=`0`]=n.slice(0,e).trim().split(/\s+/),s=Number(o);t.push({mode:r,type:i,object:a,size:Number.isFinite(s)?s:0,path:n.slice(e+1)})}return t}function Yb(e,t){let[n=``,...r]=t;return e.raw([n,`-z`,...r])}async function Xb(e,t){return fae(await Yb(e,t))}async function gae(e,t=[`status`,`--porcelain`]){return pae(await Yb(e,t))}async function _ae(e,t){return mae(await Yb(e,t))}async function vae(e,t){return hae(await Yb(e,t))}const G={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,persistenceStoreRemovedDocCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeContentGrowth:0,bridgeMergeCheckpointCreated:0,producerGuardFires:0,producerGuardFiresSuppressed:0,producerGuardCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,persistenceStalenessDetected:0,persistenceStalenessForcedStores:0,persistenceStalenessStoodDown:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,agentSessionEvictions:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,mapDrivenSpliceApplied:0,mapDrivenSpliceFallback:{},observerAResidualMergeRuns:0,observerADuplicationRederives:0,observerADuplicationCheckpointCreated:0,observerAApplyLoss:0,observerAApplyLossCheckpointCreated:0,deriveTimingDeferForceResolved:0,persistenceDeferHold:0,persistenceReconcileLoss:0,persistenceReconcileLossCheckpointCreated:0,persistenceReconcileLossDeduped:0,persistenceDuplicationReset:0,persistenceDuplicationResetCheckpointCreated:0,persistenceDuplicationResetDeduped:0,persistenceDuplicationSpared:0,persistenceDivergenceRealign:0,persistenceDivergenceRealignCheckpointCreated:0,persistenceDivergenceRealignDeduped:0,managedArtifactReconcile:0,managedArtifactReconcileCheckpointCreated:0,managedArtifactReconcileDeduped:0,reDeriveBackstopTripped:0,bridgeSplitBrainRederives:0,bridgeSplitBrainRederivesSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,reconcileOwnFlushSkips:0,reconcileInFlightFallthroughs:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0,authDocLineageMismatchCount:0,authDocLineageGuardErrors:0};function Zb(){G.reconcileCount++}function Qb(){G.conflictCount++}function yae(){G.batchCount++}function $b(){G.upstreamImportCount++}function bae(){G.persistenceStoreRemovedDocCount++}function ex(){G.rescueBufferCount++}function xae(){G.branchSwitchCount++}function Sae(){G.parkCount++}function tx(){G.gitAutoSaveFailureCount++}function Cae(){G.gitWriterCommitFailureCount++}function nx(){G.cc1BroadcastCount++}function rx(){G.cc1BroadcastDropCount++}function wae(e){G.cc1SubscriberCount=e}function ix(e){e===`a`?G.serverObserverFiresA++:G.serverObserverFiresB++}function Tae(){G.persistenceDiskWrites++}function ax(e){e===`a`?G.serverObserverErrorsA++:G.serverObserverErrorsB++}function Eae(){G.bridgeMergeContentLoss++}function Dae(){G.bridgeMergeContentGrowth++}function ox(){G.agentWriteCalls++}function Oae(){G.agentSessionEvictions++}function kae(){G.summariesProvided++}function Aae(){G.summariesTruncated++}function jae(){G.bridgeMergeCheckpointCreated++}function Mae(){G.producerGuardCheckpointCreated++}function Nae(){G.producerGuardFires++}function Pae(){G.producerGuardFiresSuppressed++}function Fae(){G.bridgeInvariantViolations++}function Iae(){G.bridgeInvariantViolationsSuppressed++}function Lae(){G.persistenceSkipNonQuiescent++}function Rae(){G.persistenceForceFlushDuringBurst++}function zae(){G.persistenceStalenessDetected++}function Bae(){G.persistenceStalenessForcedStores++}function Vae(){G.persistenceStalenessStoodDown++}function Hae(){G.agentPatchFindMismatches++}function Uae(e){G.bridgeToleranceApplied[e]=(G.bridgeToleranceApplied[e]??0)+1}function Wae(){G.observerAPathBFires++}function Gae(){G.observerAPathBFiresSuppressed++}function Kae(){G.mapDrivenSpliceApplied++}function sx(e){G.mapDrivenSpliceFallback[e]=(G.mapDrivenSpliceFallback[e]??0)+1}function qae(){G.observerAResidualMergeRuns++}function Jae(){G.observerADuplicationRederives++}function Yae(){G.observerADuplicationCheckpointCreated++}function Xae(){G.observerAApplyLoss++}function Zae(){G.observerAApplyLossCheckpointCreated++}function Qae(){G.deriveTimingDeferForceResolved++}function $ae(){G.persistenceDeferHold++}function eoe(){G.persistenceReconcileLoss++}function toe(){G.persistenceReconcileLossCheckpointCreated++}function noe(){G.persistenceReconcileLossDeduped++}function roe(){G.persistenceDuplicationReset++}function ioe(){G.persistenceDuplicationResetCheckpointCreated++}function aoe(){G.persistenceDuplicationResetDeduped++}function ooe(){G.persistenceDuplicationSpared++}function soe(){G.persistenceDivergenceRealign++}function coe(){G.persistenceDivergenceRealignCheckpointCreated++}function loe(){G.persistenceDivergenceRealignDeduped++}function uoe(){G.managedArtifactReconcile++}function doe(){G.managedArtifactReconcileCheckpointCreated++}function foe(){G.managedArtifactReconcileDeduped++}function poe(){G.reDeriveBackstopTripped++}function moe(){G.bridgeSplitBrainRederives++}function hoe(){G.bridgeSplitBrainRederivesSuppressed++}function goe(){G.persistenceReconciliationFailures++}function _oe(){G.externalChangeHandlerErrors++}function voe(){G.reconcileOwnFlushSkips++}function yoe(){G.reconcileInFlightFallthroughs++}function boe(){G.persistenceSanityCheckSerializeFailures++}function xoe(){G.deferredStoreFailures++}function cx(){G.authRenameRedirectCount++}function lx(){G.authDocDeletedCount++}function Soe(){G.recentlyRemovedDocsEvictions++}function Coe(e){G.recentlyRemovedDocsSize=e}function woe(){G.authRemovalGuardErrors++}function Toe(){G.removalRedirectChainCycles++}function ux(){G.authDocLineageMismatchCount++}function Eoe(){G.authDocLineageGuardErrors++}function dx(e){e===`EPIPE`?G.collabSocketEpipeCount++:G.collabSocketEconnresetCount++}function fx(){G.collabMessageTooLargeCount++}function Doe(e){G.shadowMigrationLegacyRefsDeleted+=e}function Ooe(){G.effectDiffCaptureFailures++}function koe(){G.agentPresenceMutationErrors++}function px(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(dx(e.code),!0):!1}function mx(e,t){G.cc1LastSeq[e]=t}function hx(){return{...G,cc1LastSeq:{...G.cc1LastSeq},bridgeToleranceApplied:{...G.bridgeToleranceApplied},mapDrivenSpliceFallback:{...G.mapDrivenSpliceFallback}}}function Aoe(){G.reconcileCount=0,G.conflictCount=0,G.batchCount=0,G.upstreamImportCount=0,G.persistenceStoreRemovedDocCount=0,G.rescueBufferCount=0,G.branchSwitchCount=0,G.parkCount=0,G.gitAutoSaveFailureCount=0,G.gitWriterCommitFailureCount=0,G.cc1BroadcastCount=0,G.cc1BroadcastDropCount=0,G.cc1SubscriberCount=0,G.cc1LastSeq={},G.serverObserverFiresA=0,G.serverObserverFiresB=0,G.serverObserverErrorsA=0,G.serverObserverErrorsB=0,G.persistenceDiskWrites=0,G.bridgeMergeContentLoss=0,G.bridgeMergeContentGrowth=0,G.bridgeMergeCheckpointCreated=0,G.producerGuardFires=0,G.producerGuardFiresSuppressed=0,G.producerGuardCheckpointCreated=0,G.bridgeInvariantViolations=0,G.bridgeInvariantViolationsSuppressed=0,G.persistenceSkipNonQuiescent=0,G.persistenceForceFlushDuringBurst=0,G.persistenceStalenessDetected=0,G.persistenceStalenessForcedStores=0,G.persistenceStalenessStoodDown=0,G.collabSocketEpipeCount=0,G.collabSocketEconnresetCount=0,G.collabMessageTooLargeCount=0,G.shadowMigrationLegacyRefsDeleted=0,G.effectDiffCaptureFailures=0,G.agentPresenceMutationErrors=0,G.agentWriteCalls=0,G.agentSessionEvictions=0,G.summariesProvided=0,G.summariesTruncated=0,G.agentPatchFindMismatches=0,G.bridgeToleranceApplied={},G.observerAPathBFires=0,G.observerAPathBFiresSuppressed=0,G.mapDrivenSpliceApplied=0,G.mapDrivenSpliceFallback={},G.observerAResidualMergeRuns=0,G.observerADuplicationRederives=0,G.observerADuplicationCheckpointCreated=0,G.observerAApplyLoss=0,G.observerAApplyLossCheckpointCreated=0,G.deriveTimingDeferForceResolved=0,G.persistenceDeferHold=0,G.persistenceReconcileLoss=0,G.persistenceReconcileLossCheckpointCreated=0,G.persistenceReconcileLossDeduped=0,G.persistenceDuplicationReset=0,G.persistenceDuplicationResetCheckpointCreated=0,G.persistenceDuplicationResetDeduped=0,G.persistenceDuplicationSpared=0,G.persistenceDivergenceRealign=0,G.persistenceDivergenceRealignCheckpointCreated=0,G.persistenceDivergenceRealignDeduped=0,G.managedArtifactReconcile=0,G.managedArtifactReconcileCheckpointCreated=0,G.managedArtifactReconcileDeduped=0,G.reDeriveBackstopTripped=0,G.bridgeSplitBrainRederives=0,G.bridgeSplitBrainRederivesSuppressed=0,G.persistenceReconciliationFailures=0,G.externalChangeHandlerErrors=0,G.reconcileOwnFlushSkips=0,G.reconcileInFlightFallthroughs=0,G.persistenceSanityCheckSerializeFailures=0,G.deferredStoreFailures=0,G.authRenameRedirectCount=0,G.authDocDeletedCount=0,G.recentlyRemovedDocsEvictions=0,G.recentlyRemovedDocsSize=0,G.authRemovalGuardErrors=0,G.removalRedirectChainCycles=0,G.authDocLineageMismatchCount=0,G.authDocLineageGuardErrors=0}const gx=I(`shadow-lock`);function joe(e,t){let n=B(e,`lock`);if(V(n)){let t=null;try{t=JSON.parse(H(n,`utf-8`))}catch{gx.warn({lockPath:n},`Corrupt lock file at ${n} — replacing`)}if(t&&!Ds(t.pid)&&(gx.warn({lockPath:n,pid:String(t.pid)},`Invalid lock pid (${String(t.pid)}) at ${n} — replacing`),t=null),t){let n=t.hostname===Zl();if(!(n&&t.pid===process.pid)){if(n&&Bs(t.pid))throw Error(`Shadow repo at ${e} is locked by another writer (pid=${t.pid}, worktree=${t.worktreeRoot}, started=${t.startedAt}). Only one active writer instance may mutate a given shadow root at a time.`);gx.warn({pid:t.pid,host:t.hostname},`Stale lock detected (pid=${t.pid}, host=${t.hostname}) — replacing`)}}}let r={pid:process.pid,hostname:Zl(),startedAt:new Date().toISOString(),worktreeRoot:t};return Jl(n,JSON.stringify(r,null,2),`utf-8`),n}function Moe(e){let t=B(e,`lock`);try{ql(t)}catch{}}const Noe=I(`shadow-op-gate`);var Poe=class{mutatorCount=0;exclusiveHeld=null;drainWaiters=[];get activeMutators(){return this.mutatorCount}get isExclusiveHeld(){return this.exclusiveHeld!==null}async withMutator(e){for(;this.exclusiveHeld;)await this.exclusiveHeld;this.mutatorCount+=1;try{return await e()}finally{if(--this.mutatorCount,this.mutatorCount===0)for(let e of this.drainWaiters.splice(0))e()}}async withExclusive(e){let t=performance.now();for(;;){if(this.exclusiveHeld){await this.exclusiveHeld;continue}if(this.mutatorCount>0){await new Promise(e=>{this.drainWaiters.push(e)});continue}break}let n=performance.now()-t;n>6e4&&Noe.warn({waitedMs:Math.round(n)},`[shadow-op-gate] exclusive acquisition waited a long time for the mutator drain — sustained write stream is starving maintenance`);let r;this.exclusiveHeld=new Promise(e=>{r=e});try{return await e()}finally{this.exclusiveHeld=null,r()}}};const _x=new Map;function vx(e){let t=_x.get(e.gitDir);return t||(t=new Poe,_x.set(e.gitDir,t)),t}function Foe(e){_x.delete(e)}const yx=I(`shadow-repo`),bx=(()=>{let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4})(),xx=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_GC_TIMEOUT_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})();function Sx(e,t){return xs({baseDir:e.workTree,timeout:{block:t?.timeoutMs??bx}}).env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree})}async function Ioe(e){let t=Sx(e);await t.raw(`config`,`gc.auto`,`512`),await t.raw(`config`,`gc.autoDetach`,`false`),await t.raw(`config`,`gc.writeCommitGraph`,`true`),await t.raw(`config`,`commitGraph.changedPaths`,`true`)}async function Cx(e,t){let n=Sx(e),r;try{r=(await n.raw(`for-each-ref`,`--format=%(refname)%00%(objectname)%00%(committerdate:unix)%00%(contents:subject)`,`refs/wip/${t}/`)).trim().split(`
|
|
9
|
+
`).map(e=>e.trim()).filter(e=>e.length===40);return t.length>0?t:a}catch(e){return qb.warn({branch:t,anchorCount:a.length,err:e},`[checkpoint-chain] tip reduction failed; adopting the full anchor set`),a}}function fae(e){return e.split(`\0`).filter(e=>e.length>0)}function pae(e){let t=[],n=e.split(`\0`);for(let e=0;e<n.length;e++){let r=n[e]??``;r.length<4||(t.push(r.slice(3)),(r[0]===`R`||r[0]===`C`)&&e++)}return t}function mae(e){let t=e.split(`\0`),n=[],r=0;for(;r<t.length;){let e=t[r]??``;if(e===``)break;if(e[0]===`R`||e[0]===`C`)n.push({status:e,from:t[r+1]??``,to:t[r+2]??``}),r+=3;else{let i=t[r+1]??``;n.push({status:e,from:i,to:i}),r+=2}}return n}function hae(e){let t=[];for(let n of e.split(`\0`)){if(!n)continue;let e=n.indexOf(` `);if(e<0)continue;let[r=``,i=``,a=``,o=`0`]=n.slice(0,e).trim().split(/\s+/),s=Number(o);t.push({mode:r,type:i,object:a,size:Number.isFinite(s)?s:0,path:n.slice(e+1)})}return t}function Yb(e,t){let[n=``,...r]=t;return e.raw([n,`-z`,...r])}async function Xb(e,t){return fae(await Yb(e,t))}async function gae(e,t=[`status`,`--porcelain`]){return pae(await Yb(e,t))}async function _ae(e,t){return mae(await Yb(e,t))}async function vae(e,t){return hae(await Yb(e,t))}const G={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,persistenceStoreRemovedDocCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeContentGrowth:0,bridgeMergeCheckpointCreated:0,producerGuardFires:0,producerGuardFiresSuppressed:0,producerGuardCheckpointCreated:0,bridgeInvariantViolations:0,bridgeInvariantViolationsSuppressed:0,persistenceSkipNonQuiescent:0,persistenceForceFlushDuringBurst:0,persistenceStalenessDetected:0,persistenceStalenessForcedStores:0,persistenceStalenessStoodDown:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0,collabMessageTooLargeCount:0,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,agentSessionEvictions:0,summariesProvided:0,summariesTruncated:0,agentPatchFindMismatches:0,bridgeToleranceApplied:{},observerAPathBFires:0,observerAPathBFiresSuppressed:0,mapDrivenSpliceApplied:0,mapDrivenSpliceFallback:{},observerAResidualMergeRuns:0,observerADuplicationRederives:0,observerADuplicationCheckpointCreated:0,observerAApplyLoss:0,observerAApplyLossCheckpointCreated:0,deriveTimingDeferForceResolved:0,persistenceDeferHold:0,persistenceReconcileLoss:0,persistenceReconcileLossCheckpointCreated:0,persistenceReconcileLossDeduped:0,persistenceDuplicationReset:0,persistenceDuplicationResetCheckpointCreated:0,persistenceDuplicationResetDeduped:0,persistenceDuplicationSpared:0,persistenceDivergenceRealign:0,persistenceDivergenceRealignCheckpointCreated:0,persistenceDivergenceRealignDeduped:0,managedArtifactReconcile:0,managedArtifactReconcileCheckpointCreated:0,managedArtifactReconcileDeduped:0,reDeriveBackstopTripped:0,bridgeSplitBrainRederives:0,bridgeSplitBrainRederivesSuppressed:0,persistenceReconciliationFailures:0,externalChangeHandlerErrors:0,reconcileOwnFlushSkips:0,reconcileInFlightFallthroughs:0,persistenceSanityCheckSerializeFailures:0,deferredStoreFailures:0,authRenameRedirectCount:0,authDocDeletedCount:0,recentlyRemovedDocsEvictions:0,recentlyRemovedDocsSize:0,authRemovalGuardErrors:0,removalRedirectChainCycles:0,authDocLineageMismatchCount:0,authDocLineageGuardErrors:0};function Zb(){G.reconcileCount++}function Qb(){G.conflictCount++}function yae(){G.batchCount++}function $b(){G.upstreamImportCount++}function bae(){G.persistenceStoreRemovedDocCount++}function ex(){G.rescueBufferCount++}function xae(){G.branchSwitchCount++}function Sae(){G.parkCount++}function tx(){G.gitAutoSaveFailureCount++}function Cae(){G.gitWriterCommitFailureCount++}function nx(){G.cc1BroadcastCount++}function rx(){G.cc1BroadcastDropCount++}function wae(e){G.cc1SubscriberCount=e}function ix(e){e===`a`?G.serverObserverFiresA++:G.serverObserverFiresB++}function Tae(){G.persistenceDiskWrites++}function ax(e){e===`a`?G.serverObserverErrorsA++:G.serverObserverErrorsB++}function Eae(){G.bridgeMergeContentLoss++}function Dae(){G.bridgeMergeContentGrowth++}function ox(){G.agentWriteCalls++}function Oae(){G.agentSessionEvictions++}function kae(){G.summariesProvided++}function Aae(){G.summariesTruncated++}function jae(){G.bridgeMergeCheckpointCreated++}function Mae(){G.producerGuardCheckpointCreated++}function Nae(){G.producerGuardFires++}function Pae(){G.producerGuardFiresSuppressed++}function Fae(){G.bridgeInvariantViolations++}function Iae(){G.bridgeInvariantViolationsSuppressed++}function Lae(){G.persistenceSkipNonQuiescent++}function Rae(){G.persistenceForceFlushDuringBurst++}function zae(){G.persistenceStalenessDetected++}function Bae(){G.persistenceStalenessForcedStores++}function Vae(){G.persistenceStalenessStoodDown++}function Hae(){G.agentPatchFindMismatches++}function Uae(e){G.bridgeToleranceApplied[e]=(G.bridgeToleranceApplied[e]??0)+1}function Wae(){G.observerAPathBFires++}function Gae(){G.observerAPathBFiresSuppressed++}function Kae(){G.mapDrivenSpliceApplied++}function sx(e){G.mapDrivenSpliceFallback[e]=(G.mapDrivenSpliceFallback[e]??0)+1}function qae(){G.observerAResidualMergeRuns++}function Jae(){G.observerADuplicationRederives++}function Yae(){G.observerADuplicationCheckpointCreated++}function Xae(){G.observerAApplyLoss++}function Zae(){G.observerAApplyLossCheckpointCreated++}function Qae(){G.deriveTimingDeferForceResolved++}function $ae(){G.persistenceDeferHold++}function eoe(){G.persistenceReconcileLoss++}function toe(){G.persistenceReconcileLossCheckpointCreated++}function noe(){G.persistenceReconcileLossDeduped++}function roe(){G.persistenceDuplicationReset++}function ioe(){G.persistenceDuplicationResetCheckpointCreated++}function aoe(){G.persistenceDuplicationResetDeduped++}function ooe(){G.persistenceDuplicationSpared++}function soe(){G.persistenceDivergenceRealign++}function coe(){G.persistenceDivergenceRealignCheckpointCreated++}function loe(){G.persistenceDivergenceRealignDeduped++}function uoe(){G.managedArtifactReconcile++}function doe(){G.managedArtifactReconcileCheckpointCreated++}function foe(){G.managedArtifactReconcileDeduped++}function poe(){G.reDeriveBackstopTripped++}function moe(){G.bridgeSplitBrainRederives++}function hoe(){G.bridgeSplitBrainRederivesSuppressed++}function goe(){G.persistenceReconciliationFailures++}function _oe(){G.externalChangeHandlerErrors++}function voe(){G.reconcileOwnFlushSkips++}function yoe(){G.reconcileInFlightFallthroughs++}function boe(){G.persistenceSanityCheckSerializeFailures++}function xoe(){G.deferredStoreFailures++}function cx(){G.authRenameRedirectCount++}function lx(){G.authDocDeletedCount++}function Soe(){G.recentlyRemovedDocsEvictions++}function Coe(e){G.recentlyRemovedDocsSize=e}function woe(){G.authRemovalGuardErrors++}function Toe(){G.removalRedirectChainCycles++}function ux(){G.authDocLineageMismatchCount++}function Eoe(){G.authDocLineageGuardErrors++}function dx(e){e===`EPIPE`?G.collabSocketEpipeCount++:G.collabSocketEconnresetCount++}function fx(){G.collabMessageTooLargeCount++}function Doe(e){G.shadowMigrationLegacyRefsDeleted+=e}function Ooe(){G.effectDiffCaptureFailures++}function koe(){G.agentPresenceMutationErrors++}function px(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(dx(e.code),!0):!1}function mx(e,t){G.cc1LastSeq[e]=t}function hx(){return{...G,cc1LastSeq:{...G.cc1LastSeq},bridgeToleranceApplied:{...G.bridgeToleranceApplied},mapDrivenSpliceFallback:{...G.mapDrivenSpliceFallback}}}function Aoe(){G.reconcileCount=0,G.conflictCount=0,G.batchCount=0,G.upstreamImportCount=0,G.persistenceStoreRemovedDocCount=0,G.rescueBufferCount=0,G.branchSwitchCount=0,G.parkCount=0,G.gitAutoSaveFailureCount=0,G.gitWriterCommitFailureCount=0,G.cc1BroadcastCount=0,G.cc1BroadcastDropCount=0,G.cc1SubscriberCount=0,G.cc1LastSeq={},G.serverObserverFiresA=0,G.serverObserverFiresB=0,G.serverObserverErrorsA=0,G.serverObserverErrorsB=0,G.persistenceDiskWrites=0,G.bridgeMergeContentLoss=0,G.bridgeMergeContentGrowth=0,G.bridgeMergeCheckpointCreated=0,G.producerGuardFires=0,G.producerGuardFiresSuppressed=0,G.producerGuardCheckpointCreated=0,G.bridgeInvariantViolations=0,G.bridgeInvariantViolationsSuppressed=0,G.persistenceSkipNonQuiescent=0,G.persistenceForceFlushDuringBurst=0,G.persistenceStalenessDetected=0,G.persistenceStalenessForcedStores=0,G.persistenceStalenessStoodDown=0,G.collabSocketEpipeCount=0,G.collabSocketEconnresetCount=0,G.collabMessageTooLargeCount=0,G.shadowMigrationLegacyRefsDeleted=0,G.effectDiffCaptureFailures=0,G.agentPresenceMutationErrors=0,G.agentWriteCalls=0,G.agentSessionEvictions=0,G.summariesProvided=0,G.summariesTruncated=0,G.agentPatchFindMismatches=0,G.bridgeToleranceApplied={},G.observerAPathBFires=0,G.observerAPathBFiresSuppressed=0,G.mapDrivenSpliceApplied=0,G.mapDrivenSpliceFallback={},G.observerAResidualMergeRuns=0,G.observerADuplicationRederives=0,G.observerADuplicationCheckpointCreated=0,G.observerAApplyLoss=0,G.observerAApplyLossCheckpointCreated=0,G.deriveTimingDeferForceResolved=0,G.persistenceDeferHold=0,G.persistenceReconcileLoss=0,G.persistenceReconcileLossCheckpointCreated=0,G.persistenceReconcileLossDeduped=0,G.persistenceDuplicationReset=0,G.persistenceDuplicationResetCheckpointCreated=0,G.persistenceDuplicationResetDeduped=0,G.persistenceDuplicationSpared=0,G.persistenceDivergenceRealign=0,G.persistenceDivergenceRealignCheckpointCreated=0,G.persistenceDivergenceRealignDeduped=0,G.managedArtifactReconcile=0,G.managedArtifactReconcileCheckpointCreated=0,G.managedArtifactReconcileDeduped=0,G.reDeriveBackstopTripped=0,G.bridgeSplitBrainRederives=0,G.bridgeSplitBrainRederivesSuppressed=0,G.persistenceReconciliationFailures=0,G.externalChangeHandlerErrors=0,G.reconcileOwnFlushSkips=0,G.reconcileInFlightFallthroughs=0,G.persistenceSanityCheckSerializeFailures=0,G.deferredStoreFailures=0,G.authRenameRedirectCount=0,G.authDocDeletedCount=0,G.recentlyRemovedDocsEvictions=0,G.recentlyRemovedDocsSize=0,G.authRemovalGuardErrors=0,G.removalRedirectChainCycles=0,G.authDocLineageMismatchCount=0,G.authDocLineageGuardErrors=0}const gx=I(`shadow-lock`);function joe(e,t){let n=B(e,`lock`);if(V(n)){let t=null;try{t=JSON.parse(H(n,`utf-8`))}catch{gx.warn({lockPath:n},`Corrupt lock file at ${n} — replacing`)}if(t&&!Ds(t.pid)&&(gx.warn({lockPath:n,pid:String(t.pid)},`Invalid lock pid (${String(t.pid)}) at ${n} — replacing`),t=null),t){let n=t.hostname===Zl();if(!(n&&t.pid===process.pid)){if(n&&Bs(t.pid))throw Error(`Shadow repo at ${e} is locked by another writer (pid=${t.pid}, worktree=${t.worktreeRoot}, started=${t.startedAt}). Only one active writer instance may mutate a given shadow root at a time.`);gx.warn({pid:t.pid,host:t.hostname},`Stale lock detected (pid=${t.pid}, host=${t.hostname}) — replacing`)}}}let r={pid:process.pid,hostname:Zl(),startedAt:new Date().toISOString(),worktreeRoot:t};return Jl(n,JSON.stringify(r,null,2),`utf-8`),n}function Moe(e){let t=B(e,`lock`);try{ql(t)}catch{}}const Noe=I(`shadow-op-gate`);var Poe=class{mutatorCount=0;exclusiveHeld=null;drainWaiters=[];get activeMutators(){return this.mutatorCount}get isExclusiveHeld(){return this.exclusiveHeld!==null}async withMutator(e){for(;this.exclusiveHeld;)await this.exclusiveHeld;this.mutatorCount+=1;try{return await e()}finally{if(--this.mutatorCount,this.mutatorCount===0)for(let e of this.drainWaiters.splice(0))e()}}async withExclusive(e){let t=performance.now();for(;;){if(this.exclusiveHeld){await this.exclusiveHeld;continue}if(this.mutatorCount>0){await new Promise(e=>{this.drainWaiters.push(e)});continue}break}let n=performance.now()-t;n>6e4&&Noe.warn({waitedMs:Math.round(n)},`[shadow-op-gate] exclusive acquisition waited a long time for the mutator drain — sustained write stream is starving maintenance`);let r;this.exclusiveHeld=new Promise(e=>{r=e});try{return await e()}finally{this.exclusiveHeld=null,r()}}async drain(){this.mutatorCount!==0&&await new Promise(e=>{this.drainWaiters.push(e)})}};const _x=new Map;function vx(e){let t=_x.get(e.gitDir);return t||(t=new Poe,_x.set(e.gitDir,t)),t}function Foe(e){_x.delete(e)}const yx=I(`shadow-repo`),bx=(()=>{let e=process.env.OK_GIT_TIMEOUT_MS;if(!e)return 3e4;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:3e4})(),xx=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_GC_TIMEOUT_MS;if(!e)return 6e5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:6e5})();function Sx(e,t){return xs({baseDir:e.workTree,timeout:{block:t?.timeoutMs??bx}}).env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree})}async function Ioe(e){let t=Sx(e);await t.raw(`config`,`gc.auto`,`512`),await t.raw(`config`,`gc.autoDetach`,`false`),await t.raw(`config`,`gc.writeCommitGraph`,`true`),await t.raw(`config`,`commitGraph.changedPaths`,`true`)}async function Cx(e,t){let n=Sx(e),r;try{r=(await n.raw(`for-each-ref`,`--format=%(refname)%00%(objectname)%00%(committerdate:unix)%00%(contents:subject)`,`refs/wip/${t}/`)).trim().split(`
|
|
10
10
|
`).filter(Boolean)}catch{return[]}let i=[];for(let e of r){let[t=``,n=``,r=``,a=``]=e.split(`\0`),o=t.split(`/`).slice(3).join(`/`);if(!o)continue;let s=Number.parseInt(r,10);i.push({writerId:o,tipSha:n,classification:Ju(o).classification,isPark:a.startsWith(`park:`),committedAtMs:Number.isFinite(s)?s*1e3:0})}return i}async function wx(e){let t=Ou(e),n=B(e,`.git/openknowledge`),r=V(n),i=V(t);if(r&&!i?Wo(n,t):r&&i&&yx.warn({legacyDir:n,shadowDir:t},`[shadow-repo] unexpected legacy + new shadow both present — no rename performed`),!V(B(t,`HEAD`))){Zo(t,{recursive:!0}),await xs({baseDir:e,timeout:{block:bx}}).raw(`init`,`--bare`,t);let n=xs({timeout:{block:bx}}).env({GIT_DIR:t});await n.raw(`config`,`--unset`,`core.bare`),await n.raw(`config`,`core.worktree`,e),await n.raw(`config`,`user.name`,`openknowledge`),await n.raw(`config`,`user.email`,`noreply@openknowledge.local`)}let a={gitDir:t,workTree:e};try{await Ioe(a)}catch(e){yx.warn({err:e},`failed to write gc config (non-fatal)`)}return await Roe(a),Boe(a),joe(t,e),a}function Loe(e){Moe(e.gitDir),Foe(e.gitDir)}async function Roe(e){let t=Sx(e),n;try{n=(await t.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip`)).trim().split(`
|
|
11
11
|
`).filter(e=>e.length>0)}catch{return 0}let r=[],i={server:0,"human-":0,upstream:0};for(let e of n){let t=e.split(`/`);if(t.length<4)continue;let n=t.slice(3).join(`/`);Ju(n).classification===`unknown`&&(n===`server`?(r.push(e),i.server++):n.startsWith(`human-`)?(r.push(e),i[`human-`]++):n===`upstream`&&(r.push(e),i.upstream++))}if(r.length===0)return 0;let a=0;return await vx(e).withMutator(async()=>{for(let e of r)try{await t.raw(`update-ref`,`-d`,e),a++}catch(t){yx.warn({ref:e,err:t},`[shadow-migration] failed to delete legacy ref ${e}`)}}),Doe(a),yx.warn({deleted:a,server:i.server,human:i[`human-`],upstream:i.upstream},`[shadow-migration] deleted ${a} legacy refs: server=${i.server} human-=${i[`human-`]} upstream=${i.upstream}`),a}const Tx=new Map;async function Ex(e,t,n,r,i=`main`,a){return zo(`shadow.commitWip`,{attributes:{"shadow.writer":t.id,"shadow.branch":i}},async()=>{let o=`${e.gitDir}\0${t.id}`,s=()=>vx(e).withMutator(()=>zoe(e,t,n,r,i,a?.date)),c=(Tx.get(o)??Promise.resolve()).then(s,s);return Tx.set(o,c),c})}async function zoe(e,t,n,r,i=`main`,a){let o=B(e.gitDir,`index-wip-${t.id}`),s=`refs/wip/${i}/${t.id}`,c=Sx(e),l=n||`.`;try{try{let t=(await c.raw(`rev-parse`,`${s}^{tree}`)).trim();await c.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`read-tree`,t)}catch(e){let t=e instanceof Error?e.message:String(e);if(!(t.includes(`unknown revision`)||t.includes(`bad revision`)))throw yx.error({ref:s,err:e},`Unexpected error seeding index for ${s}`),e}await c.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:o}).raw(`add`,l);let n=(await c.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`write-tree`)).trim(),i=null;try{i=(await c.raw(`rev-parse`,s)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw yx.error({ref:s,err:e},`Unexpected error resolving ${s}`),e}let u=[`commit-tree`,n,`-m`,r];i&&u.push(`-p`,i);let d={GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`};a&&(d.GIT_AUTHOR_DATE=a,d.GIT_COMMITTER_DATE=a);let f=(await c.env(d).raw(...u)).trim();return await c.raw(`update-ref`,s,f),f}finally{try{Wl(o)}catch{}}}const Dx=`index-wip-fanout`;function Boe(e){let t=0;try{for(let n of Vl(e.gitDir)){let r=n.startsWith(`${Dx}-`),i=n===`${Dx}.lock`,a=n.startsWith(`tmp-park-blobs-`);if(!(!r&&!i&&!a))try{Wl(B(e.gitDir,n),{recursive:!0,force:!0}),t++}catch{}}}catch{}return t}async function Ox(e,t){return vx(e).withMutator(()=>Voe(e,t))}async function kx(e,t,n){let r=Sx(e),i=t||`.`;return await r.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:n}).raw(`add`,i),(await r.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:n}).raw(`write-tree`)).trim()}async function Voe(e,t){let n=B(e.gitDir,Dx);try{return await kx(e,t,n)}catch(r){yx.warn({err:r},`[shadow-repo] persistent fan-out index failed — rebuilding from a fresh index`);for(let e of[n,`${n}.lock`])try{Wl(e)}catch{}let i=B(e.gitDir,`${Dx}-${uu()}`);try{return await kx(e,t,i)}finally{try{Wl(i)}catch{}}}}async function Ax(e,t,n,r,i=`main`){return zo(`shadow.commitWipFromTree`,{attributes:{"shadow.writer":t.id,"shadow.branch":i,"shadow.tree":n.slice(0,8)}},async()=>vx(e).withMutator(()=>Hoe(e,t,n,r,i)))}async function Hoe(e,t,n,r,i=`main`){let a=`refs/wip/${i}/${t.id}`,o=Sx(e),s=null;try{s=(await o.raw(`rev-parse`,a)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw yx.error({ref:a,err:e},`Unexpected error resolving ${a}`),e}let c=[`commit-tree`,n,`-m`,r];s&&c.push(`-p`,s);let l=(await o.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...c)).trim();return await o.raw(`update-ref`,a,l),l}const jx={id:`file-system`,name:`File System`,email:`file-system@openknowledge.local`},Mx={id:`git-upstream`,name:`Git (upstream)`,email:`git@openknowledge.local`},Nx={id:`openknowledge-service`,name:`OpenKnowledge (service)`,email:`service@openknowledge.local`},Px=Mx;async function Fx(e,t,n,r,i=`main`){return zo(`shadow.commitUpstreamImport`,{attributes:{"shadow.branch":i,"shadow.new_head":r.slice(0,8)}},async()=>Uoe(e,t,n,r,i))}async function Uoe(e,t,n,r,i=`main`){return Ex(e,Px,t,`${cne(n,r)}\n\n${Fu({v:1,writer_id:Px.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:Px.name,color_seed:Px.id,docs:[]})}`,i)}const Ix=Nx;async function Lx(e,t,n,r=`main`){return Ex(e,Ix,t,`${Gu(`pre-${n.action}`)}\n\n${Fu({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)}async function Rx(e,t,n){return vx(e).withMutator(()=>Woe(e,t,n))}async function Woe(e,t,n){let r=n.branch??`main`,i=Sx(e),a=uu(),o=B(e.gitDir,`index-checkpoint-${a}`),s=B(e.gitDir,`tmp-checkpoint-blob-${a}`),c=t===`.`?``:t.replace(/^\.\//,``).replace(/\/$/,``),l=c?`${c}/${n.docName}`:n.docName,u=Buffer.byteLength(n.contents,`utf-8`),d;switch(n.kind){case`bridge-merge-loss`:d={kind:`bridge-merge-loss`,docName:n.docName,size:u,metadata:n.metadata};break;case`producer-guard-loss`:d={kind:`producer-guard-loss`,docName:n.docName,size:u,metadata:n.metadata};break;case`observer-a-duplication`:d={kind:`observer-a-duplication`,docName:n.docName,size:u,metadata:n.metadata};break;case`external-change-rescue`:d={kind:`external-change-rescue`,docName:n.docName,size:u,metadata:n.metadata};break;case`defer-exhaustion-loss`:d={kind:`defer-exhaustion-loss`,docName:n.docName,size:u,metadata:n.metadata};break;case`observer-a-apply-loss`:d={kind:`observer-a-apply-loss`,docName:n.docName,size:u,metadata:n.metadata};break;case`bridge-derive-loss`:d={kind:`bridge-derive-loss`,docName:n.docName,size:u,metadata:n.metadata};break;case`bridge-backstop-trip`:d={kind:`bridge-backstop-trip`,docName:n.docName,size:u,metadata:n.metadata};break;case`persistence-reconcile-loss`:d={kind:`persistence-reconcile-loss`,docName:n.docName,size:u,metadata:n.metadata};break;case`persistence-duplication-reset`:d={kind:`persistence-duplication-reset`,docName:n.docName,size:u,metadata:n.metadata};break;case`persistence-divergence-realign`:d={kind:`persistence-divergence-realign`,docName:n.docName,size:u,metadata:n.metadata};break;case`managed-artifact-reconcile`:d={kind:`managed-artifact-reconcile`,docName:n.docName,size:u,metadata:n.metadata};break}let f=Ua(d),p=`checkpoint: ${n.label}\n\n${f}`;try{os(s,n.contents,`utf-8`);let t=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`hash-object`,`-w`,s)).trim();await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${t},${l}`);let a=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`write-tree`)).trim(),c={GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`};n.date&&(c.GIT_AUTHOR_DATE=n.date,c.GIT_COMMITTER_DATE=n.date);let u=(await i.env(c).raw(`commit-tree`,a,`-m`,p)).trim();return await i.raw(`update-ref`,`refs/checkpoints/${r}/${u}`,u),u}finally{try{Wl(o)}catch{}try{Wl(s)}catch{}}}async function zx(e,t=`main`){let n=Sx(e),r;try{r=await n.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch{return[]}let i=r.trim().split(`
|
|
12
12
|
`).filter(e=>e.length===40);if(i.length===0)return[];let a;try{a=await n.raw(`log`,`--no-walk`,`--author-date-order`,`--format=%H%x00%aI%x00%s%x00%B%x1e`,...i)}catch{return[]}let o=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[r=``,i=``,a=``,s=``]=t.split(`\0`),c=wi(s);if(c?.kind!==`external-change-rescue`)continue;let l=c.docName??``,u=c.size??0;if(!l)try{let e=(await vae(n,[`ls-tree`,`-r`,`--long`,r]))[0];e&&(u===0&&(u=e.size),l=e.path.replace(/\.mdx?$/,``).split(`/`).slice(-1)[0]??``)}catch{}l&&o.push({docName:l,timestamp:i,size:u,sha:r,label:a.replace(/^checkpoint:\s*/,``),incomingDiskSha:c.metadata.incomingDiskSha})}return o}const Bx={maxBridgeMergeLoss:50,maxProducerGuardLoss:50,maxObserverADuplication:50,maxExternalChangeRescue:50,maxDeferExhaustionLoss:50,maxBridgeDeriveLoss:50,maxObserverAApplyLoss:50,maxBridgeBackstopTrip:50,maxPersistenceReconcileLoss:50,maxPersistenceDuplicationReset:50,maxPersistenceDivergenceRealign:50,maxManagedArtifactReconcile:50,maxAutoConsolidation:2,ttlMs:720*60*60*1e3},Goe={"bridge-merge-loss":{limit:e=>e.maxBridgeMergeLoss,counter:`deletedBridgeMergeLoss`,applyTtl:!0},"producer-guard-loss":{limit:e=>e.maxProducerGuardLoss,counter:`deletedProducerGuardLoss`,applyTtl:!0},"observer-a-duplication":{limit:e=>e.maxObserverADuplication,counter:`deletedObserverADuplication`,applyTtl:!0},"external-change-rescue":{limit:e=>e.maxExternalChangeRescue,counter:`deletedExternalChangeRescue`,applyTtl:!0},"defer-exhaustion-loss":{limit:e=>e.maxDeferExhaustionLoss,counter:`deletedDeferExhaustionLoss`,applyTtl:!0},"observer-a-apply-loss":{limit:e=>e.maxObserverAApplyLoss,counter:`deletedObserverAApplyLoss`,applyTtl:!0},"bridge-derive-loss":{limit:e=>e.maxBridgeDeriveLoss,counter:`deletedBridgeDeriveLoss`,applyTtl:!0},"bridge-backstop-trip":{limit:e=>e.maxBridgeBackstopTrip,counter:`deletedBridgeBackstopTrip`,applyTtl:!0},"persistence-reconcile-loss":{limit:e=>e.maxPersistenceReconcileLoss,counter:`deletedPersistenceReconcileLoss`,applyTtl:!0},"persistence-duplication-reset":{limit:e=>e.maxPersistenceDuplicationReset,counter:`deletedPersistenceDuplicationReset`,applyTtl:!0},"persistence-divergence-realign":{limit:e=>e.maxPersistenceDivergenceRealign,counter:`deletedPersistenceDivergenceRealign`,applyTtl:!0},"managed-artifact-reconcile":{limit:e=>e.maxManagedArtifactReconcile,counter:`deletedManagedArtifactReconcile`,applyTtl:!0},"auto-consolidation":{limit:e=>e.maxAutoConsolidation,counter:`deletedAutoConsolidation`,applyTtl:!1}};async function Vx(e,t=`main`,n=Bx){return vx(e).withMutator(()=>Koe(e,t,n))}async function Koe(e,t=`main`,n=Bx){let r={scanned:0,deletedBridgeMergeLoss:0,deletedProducerGuardLoss:0,deletedObserverADuplication:0,deletedExternalChangeRescue:0,deletedDeferExhaustionLoss:0,deletedBridgeDeriveLoss:0,deletedObserverAApplyLoss:0,deletedBridgeBackstopTrip:0,deletedPersistenceReconcileLoss:0,deletedPersistenceDuplicationReset:0,deletedPersistenceDivergenceRealign:0,deletedManagedArtifactReconcile:0,deletedAutoConsolidation:0,retained:0},i=Sx(e),a;try{a=await i.raw(`for-each-ref`,`--format=%(objectname) %(refname)`,`refs/checkpoints/${t}/`)}catch{return r}let o=a.trim().split(`
|
|
@@ -2026,7 +2026,7 @@ $$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-p
|
|
|
2026
2026
|
native-divergence-injected
|
|
2027
2027
|
`,`utf-8`),o&&ee!==void 0){let r=null;try{V(O)&&(r=H(O,`utf-8`))}catch(e){r=null,A7.warn({err:e,documentName:i},`[persistence] L3 disk-read failed; divergence check skipped for this store`)}if(r!==null&&ti(r)!==ti(ee)){let a=r;console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":i,outcome:`reverted`,diskBytes:a.length,baseBytes:ee.length,candidateBytes:S.length})),_e(n,i,S,a);let o=e?.getLossRing?.(),s={baselineFullMd:a,report:e=>{try{let t=Ux(e);if(t.length===0)return;o?.record({event:Ub,docName:i,writerId:jx.id,direction:`b`,site:de,lostLen:t.reduce((e,t)=>e+t.length,0),digest:er(t.join(`
|
|
2028
2028
|
`))})}catch(e){A7.warn({documentName:i,err:e},`[persistence] divergence-realign loss detection failed`)}}};try{n.transact(()=>{x(n,a,void 0,void 0,void 0,s)},yR)}catch(e){throw t.recordStoreFailure(i,P7(e)),C.delete(i),e}t.setReconciledBase(i,a),t.recordStoreDivergence(i),C.delete(i);return}}e?.isRecentlyRemoved?.(i)&&(bae(),console.warn(JSON.stringify({event:`persistence-store-removed-doc`,"doc.name":i})));let k=`${O}.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 Bo(k,S,`utf-8`),await as(k,O),HR(O,WR(S)),t.clearStoreFailure(i),Tae();try{d?.(i,f,S,ee??null)}catch(e){A7.warn({err:e,documentName:i},`[persistence] onDiskFlush callback failed for ${i}`)}}catch(e){try{Ko(k)}catch{}throw C.delete(i),t.recordStoreFailure(i,P7(e)),A7.error({err:e,documentName:i},`[persistence] Failed to save ${i}`),e}A7.info({filePath:O,bytes:S.length},`[persistence] Wrote ${O} (${S.length} bytes)`),t.setReconciledBase(i,S),b.add(i),y.delete(i),C.delete(i);try{await s?.recordDurableStore(i,S)}catch(e){A7.warn({err:e,documentName:i},`[derived-index] durable-store projection failed; disk write remains authoritative`)}Mo({"persistence.bytes":S.length}),j()}).finally(()=>{l!==void 0&&t.finishInFlightFlush(i,l),be?.record((Date.now()-o)/1e3)})}function we({document:e,documentName:n,lastTransactionOrigin:r}){re.set(n,{branch:t.getActiveBranch(),document:e,lastTransactionOrigin:r})}async function Te(e=`within-branch`){return k?(S=S===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,k):(k=(async()=>{let n=e;for(;;){let e=[...re.entries()];if(re.clear(),n!==`discard-stale`){for(let[n,r]of e)if(r.branch===t.getActiveBranch())try{await Ce({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=er(r),a;try{a=kEe(e)}catch(e){let r=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":n,classifyErrorHash:er(r),errorMessageHash:i,...t?{classifyErrorMessage:r}:{},timestamp:new Date().toISOString()})),a=`unknown`}xoe(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":n,errorClass:a,errorMessageHash:i,...t?{errorMessage:r}:{},timestamp:new Date().toISOString()})),A7.error({err:e,documentName:n},`[persistence] Deferred store failed for ${n}`)}}let r=S;if(S=null,re.size===0&&r===null)break;n=r??`within-branch`}})().finally(()=>{k=null}),k)}let F={async onLoadDocument({document:n,documentName:i,context:a}){if(b.delete(i),rS(i))return;if(iS(i)){KTe(n,i,h);return}if(aS(i)){GG(n,i,_);return}if(oS(i)||sS(i)){CEe(n,i,v);return}Se();let o=Date.now();return zo(`persistence.onLoadDocument`,{attributes:{"doc.name":i}},async()=>{A7.info({documentName:i,connections:n.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${i} (connections: ${n.getConnectionsCount?.()??`?`})`);let a=ID(i,r);if(!V(a))return;let o=a;try{let e=U(a);if(!LD(e,r)){A7.warn({path:a,canonical:e},`[persistence] symlink-escape on load: ${a} → ${e}, refusing`);return}o=e}catch(e){if(Vs(e)===`ELOOP`){A7.warn({path:a},`[persistence] Symlink cycle on load: ${a}, refusing`);return}}let s=Kl(o).size;if(s>524288)throw A7.warn({documentName:i,fileSize:s,limit:jn},`[persistence] Document exceeds open byte limit; refusing to load`),new DEe(i,s);let c=H(a,`utf-8`),l=n.getXmlFragment(`default`);A7.info({documentName:i,fragmentLength:l.length},`[persistence] onLoadDocument ${i}: fragment.length=${l.length} before update`),l.length===0?(n.transact(()=>{bR(n,c,e?.resolveEmbed,i,e?.resolveSize),n.getMap(`lifecycle`).set(Fe,crypto.randomUUID())},yR),A7.info({filePath:a,children:l.length},`[persistence] Loaded ${a} into Y.Doc (${l.length} children)`),l.observeDeep(()=>{A7.info({documentName:i,fragmentLength:l.length},`[persistence] MUTATION on ${i}: fragment.length=${l.length}`)})):A7.info({documentName:i,children:l.length},`[persistence] Skipped load for ${i} — fragment already has ${l.length} children`),t.setReconciledBase(i,c)}).finally(()=>{P?.record((Date.now()-o)/1e3)})},async onStoreDocument({document:e,documentName:n,lastTransactionOrigin:r,lastContext:i}){if(!rS(n)){if(iS(n)){let t=await JTe(e,n,r,h);if(t===`persisted`||t===`reconciled`)try{f?.(n)}catch(e){A7.warn({err:e,documentName:n},`[persistence] onConfigPersisted callback failed`)}return}if(aS(n)){if(await JG(e,n,r,_)===`persisted`){let e=j7(r,c);if(e&&e.id!==Nx.id&&!e.id.startsWith(`agent-`)){let t=FG(n);t&&(qj(t.docKey,e.id,e.name,e.id,t.subject),j())}}return}if(oS(n)||sS(n)){await wEe(e,n,r,v);return}if(t.isBatchInProgress()){we({document:e,documentName:n,lastTransactionOrigin:r});return}return Ce({document:e,documentName:n,lastTransactionOrigin:r})}}};async function Ee(){ne&&await ne}async function De(){if(ne){await ne;return}tM()!==0&&(ne=A().finally(()=>{ne=null,O&&(O=!1,j())}),await ne)}function Oe(){return{branchDeferred:re.size,quiescenceDeferred:C.size}}async function ke(e,n){if(!uS(n)){if(t.isBatchInProgress()){we({document:e,documentName:n,lastTransactionOrigin:null});return}return Ce({document:e,documentName:n,lastTransactionOrigin:null})}}return{extension:F,durabilityState:t,flushDeferredStores:Te,flushPendingGitCommit:oe,flushContributors:De,waitForPendingCommits:Ee,getQueueDepths:Oe,forceStore:ke,configPersistenceCtx:h,managedArtifactCtx:_}}const I7=I(`persistence-staleness`);var L7=class extends Error{constructor(e){super(e),this.name=`StructuralDiskReadError`}};function AEe(e){let t=e.graceMs??3e5,n=e.sweepIntervalMs??6e4,r=e.now??Date.now,{getBase:i,isBatchActive:a,peekInFlight:o}=e,s=e.msSinceLastUserTx??rC,c=new Map,l=!1,u=null;function d(e){return N7(e)}function f(e){return e===void 0?void 0:ti(e)}function p(e,t,n,r){return t===void 0?e!==``:e===t?r!==void 0&&Ya(r,n):!0}async function m(){if(l||a())return;let n=r(),u=0,m=0,h=0,g=0,_=new Set;for(let[n,v]of e.getLoadedDocuments()){if(l)return;if(_.add(n),uS(n)||xS(v)!==null||o(n)!==void 0)continue;u++;let y=v.getText(`source`).toString(),b=i(n);if(b!==void 0&&y===b){c.delete(n);continue}let x=d(y),S=f(b);if(!p(x,S,y,b)){c.delete(n);continue}m++;let C=r(),w=s(v,C);if(w!==null&&w<t)continue;let T=c.get(n);if(T&&T.fingerprint===x&&(T.declined||C-T.atMs<t))continue;let ee=T?.fingerprint!==x;ee&&zae();let te=!ee&&T?T.firstDetectedAtMs:C,E=C-te,D=null,ne=!1;try{let t=e.readDiskBytes(n);S===void 0?t!==null&&(D=`disk-file-never-loaded`):t===null?D=`disk-file-missing`:ti(t)!==S&&(D=`disk-diverged-from-base`)}catch(e){e instanceof L7?(D=`disk-read-refused`,I7.error({err:e,docName:n},`[persistence-staleness] disk read refused; standing down until content changes`)):(D=`disk-read-failed`,ne=!0,I7.warn({err:e,docName:n},`[persistence-staleness] disk read failed; standing down`))}if(D!==null){g++,Vae(),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:te,declined:!ne}),I7.warn({docName:n,ageMs:w,staleForMs:E,candidateBytes:x.length,baseBytes:b?.length??0,action:`stood-down`,reason:D},`[persistence-staleness] Unflushed edits detected for ${n} but disk state is unverified or unreconciled; not overwriting`);continue}I7.warn({docName:n,ageMs:w,staleForMs:E,candidateBytes:x.length,baseBytes:b?.length??0,action:`forced-store`},`[persistence-staleness] Doc ${n} has unpersisted edits past the grace window with no pending store; forcing a store`),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:te,declined:!1}),Bae(),h++;try{await e.forceStore(v,n)}catch(e){I7.error({err:e,docName:n,staleForMs:E},`[persistence-staleness] Forced store failed for ${n}; will retry`);continue}if(l||a())return;let O=v.getText(`source`).toString(),k=i(n),re=d(O);p(re,f(k),O,k)&&re===x?(c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:te,declined:!0}),I7.info({docName:n},`[persistence-staleness] Store completed without clearing divergence for ${n}; suppressing until content changes`)):c.delete(n)}for(let e of c.keys())_.has(e)||c.delete(e);let v={scanned:u,divergent:m,forced:h,stoodDown:g,elapsedMs:r()-n};m>0||h>0||g>0?I7.info(v,`[persistence-staleness] sweep complete`):I7.debug(v,`[persistence-staleness] sweep complete`)}function h(){return u||(u=m().finally(()=>{u=null}),u)}let g=setInterval(()=>{h().catch(e=>{I7.error({err:e},`[persistence-staleness] sweep failed`)})},n);return g.unref?.(),{sweep:h,dispose:()=>(l=!0,clearInterval(g),u??Promise.resolve())}}async function jEe(e){try{let t=xs({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 R7(e){let t=ok(e),n=B(t,`principal.json`),{name:r,email:i}=await jEe(e);if(V(n)){let e;try{e=JSON.parse(H(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${uu()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?Zm(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?Zm(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return Jl(n,JSON.stringify(s,null,2),`utf-8`),s}Rl(t,{recursive:!0});let a=`principal-${uu()}`,o=a.slice(10,18),s={id:a,display_name:r?Zm(r):`Local User`,display_email:i?Zm(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return Jl(n,JSON.stringify(s,null,2),`utf-8`),s}var MEe=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?.()}};function z7(e,t){let n=e.resolveFilePath(t);return n!==null&&e.fileExists(n)}async function NEe(e,t){try{if(cS(e))return;let n=t.recentlyRemovedDocs.get(e);if(n===void 0)return;if(n.kind===`deleted`){if(z7(t,e)){t.recentlyRemovedDocs.delete(e);return}throw lx(),Mo({"auth.reason":`doc-deleted`}),new TQ(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let r=new Set([e]),i=n.newDocName;for(;;){if(r.has(i)){Toe(),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 cx(),Mo({"auth.reason":`rename-redirect`}),new TQ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i);if(n.kind===`deleted`)throw z7(t,i)?(t.recentlyRemovedDocs.delete(i),cx(),Mo({"auth.reason":`rename-redirect`}),new TQ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i)):(lx(),Mo({"auth.reason":`doc-deleted`}),new TQ(`doc-deleted`,`removed-doc rejection for deleted ${e}`));i=n.newDocName}}catch(t){if(t instanceof TQ)throw t;woe(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}const B7=I(`removed-docs-journal`);function V7(e){return R(ok(e),`removed-docs.json`)}function PEe(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 FEe(e){let t=V7(e);if(!V(t))return[];try{let e=JSON.parse(H(t,`utf-8`));if(e.version!==1||!Array.isArray(e.entries))return B7.warn({path:t},`[removed-docs-journal] unrecognized journal shape — ignoring`),[];let n=[];for(let t of e.entries){if(!PEe(t))continue;let{docName:e,...r}=t;n.push([e,r])}return n}catch(e){return B7.warn({path:t,err:e},`[removed-docs-journal] failed to read journal — ignoring`),[]}}function H7(e,t){let n=V7(e),r={version:1,entries:t.map(([e,t])=>({docName:e,...t}))};Zo(L(n),{recursive:!0});let i=`${n}.tmp`;os(i,JSON.stringify(r),`utf-8`),Wo(i,n)}const U7=I(`server-observers`);function W7(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(rS(r)||iS(r)||oS(r)||sS(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=bw({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 U7.error({docName:r,err:e},`[ServerObserverExtension] Failed to attach observers for '${r}'`),ax(`a`),ax(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(U7.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){U7.error({docName:e,err:t},`[ServerObserverExtension] Cleanup failed for '${e}'`)}t.clear()}}}const G7=`state.json`;function K7(e){return e.lockDir,V(e.shadowRepoDir)?`adopt`:`fresh`}function q7(e){return B(e,G7)}function IEe(e,t){return e===t||e===0&&t===1}var J7=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function LEe(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 Y7(e){let t=q7(e);if(!V(t))return{status:`absent`};let n;try{n=H(t,`utf-8`)}catch(e){throw new J7({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 J7({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!LEe(r))throw new J7({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:r}}function X7(e,t){let n=q7(e);Rl(L(n),{recursive:!0}),Jl(n,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function Z7(e){let t=I(`state-manifest`),n=e.currentStateSchemaVersion??1,r=e.currentRuntimeVersion??Ns,i=e.currentProtocolVersion??1,a=(e.now??(()=>new Date))().toISOString(),o=q7(e.lockDir),s=Y7(e.lockDir);if(s.status===`present`){let c=s.manifest;if(!IEe(c.stateSchemaVersion,n))throw new J7({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 X7(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),c}}if(K7({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let s={stateSchemaVersion:n,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i}};return X7(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 X7(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 REe(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`auth`&&t===`no-credential`?`auth-no-credential`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function zEe(e){return e.git?.toString()??e.message??``}function Q7(e,t){return t.some(t=>t.test(e))}const BEe={"no-credential":`No GitHub credential available — reconnect to resume syncing`,401:`Authentication failed — token may be expired`,403:`Access denied (403)`,"scope-mismatch":`GitHub token missing required scopes`,"ssh-auth":`SSH authentication failed — check your SSH key or host-key trust`,"unknown-auth":`Authentication failed`},VEe=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],$7=[/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],HEe=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],UEe=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],WEe=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],GEe=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],KEe=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],qEe=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],JEe=[/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],YEe=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/i],XEe=[/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],ZEe=[/\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],QEe=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function e9(e){let t=$Ee(e);return{...t,userFacingCode:REe(t.class,t.subclass)}}function $Ee(e){let t=e instanceof Error?e:Error(String(e)),n=zEe(t),r=`${t.message}\n${n}`.toLowerCase();if(Q7(r,qEe))return{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n};if(Q7(r,JEe))return{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n};if(Q7(r,YEe))return{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n};let i=fa(t);return i.kind===`auth`?i.subclass===`403`&&Q7(r,$7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:{class:`auth`,subclass:i.subclass,retryable:!1,message:BEe[i.subclass],rawStderr:n}:Q7(r,$7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:Q7(r,VEe)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:Q7(r,HEe)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:Q7(r,UEe)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:Q7(r,WEe)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:Q7(r,KEe)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:Q7(r,GEe)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:Q7(r,QEe)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:Q7(r,ZEe)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:Q7(r,XEe)?/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 eDe(e,t={}){let n=t.ttlMs??6e4,r=t.now??Date.now,i=new Map;return{get(t){if(!e)return null;let a=r(),o=i.get(t);if(o&&o.expiresAt>a)return o.token==null?null:{token:o.token,host:t};let s=e(t),c=s.available&&s.token?s.token:null;return i.set(t,{token:c,expiresAt:a+n}),c==null?null:{token:c,host:t}},invalidate(){i.clear()}}}const t9=I(`github-permissions`);function tDe(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function nDe(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function rDe(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 iDe(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return t9.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let n=rDe(t);return n===null?(t9.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 t9.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function aDe(e,t,n){let r=t(e);if(r.available&&r.token)return{token:r.token,source:`gh`};if(n)try{let t=await n.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){t9.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function oDe(e){let{owner:t,repo:n,host:r=`github.com`,transport:i=`https`,detectGh:a=()=>({available:!1}),tokenStore:o,_fetchFn:s=fetch,_timeoutMs:c=5e3}=e,{token:l,source:u}=await aDe(r,a,o);if(u===`anonymous`)return i===`ssh`||i===`git`?(t9.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`}):(t9.info({host:r},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`not-authenticated`});let d=`${tDe(r)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}`;t9.info({host:r,tokenSource:u,tokenLen:l===void 0?0:l.length},`[permissions] probe starting`);let f=new AbortController,p=setTimeout(()=>f.abort(),c);try{let e=await s(d,{signal:f.signal,headers:nDe(l)}),t=await iDe(e,l!==void 0);return t9.info({host:r,tokenSource:u,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return f.signal.aborted?(t9.warn({host:r,timeoutMs:c},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(t9.warn({err:e,host:r},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(p)}}async function sDe(e){let t=performance.now(),n=await oDe(e);return dDe(n,performance.now()-t),n}function cDe(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let n9=null;function lDe(){return n9||=ls().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}.`}),n9}let r9=null;function uDe(){return r9||=ls().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),r9}function dDe(e,t){let n=cDe(e);lDe().add(1,n),uDe().record(t,{outcome:n.outcome})}function i9(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}function fDe(e,t){return t===`anonymous`?Math.max(180,e):e}const a9=I(`sync-engine`),o9=/^[0-9a-f]{40}$/i,pDe=gu(bl);function mDe(e){let{exitCode:t,stderr:n}=e,r=n??``;return t===128||/^fatal:/m.test(r)&&/not possible to fast-forward/i.test(r)?`divergence`:/^error:/m.test(r)&&/would be overwritten by merge/i.test(r)?`overlay-overlap`:`unknown`}function hDe(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function s9(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}function c9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function l9(e){let t=bu(e);if(t.kind!==`repository`)return!1;let n=t.repository.readHead();return n.kind===`branch`?t.repository.readRef(n.ref).kind===`absent`:!1}function gDe(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}const u9=12e4;var _De=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;mode;credentialArgs;cc1Broadcaster;onStateChange;onContentConflictsDetected;onContentConflictsResolved;setBatchInProgress;onAutoDisable;checkpointBeforeStrandedConversion;checkpointBeforeOverlayRestore;detectGh;ghTokenSource;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;authTier=`unknown`;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;lastPullUtc=null;lastPullOutcome=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.mode=e.mode??(e.syncEnabled===!0?`full`:`off`),this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.onContentConflictsResolved=e.onContentConflictsResolved,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.checkpointBeforeStrandedConversion=e.checkpointBeforeStrandedConversion,this.checkpointBeforeOverlayRestore=e.checkpointBeforeOverlayRestore,this.detectGh=e.detectGh,this.ghTokenSource=eDe(e.detectGh),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??sDe,this.statePath=B(ok(this.projectDir),`sync-state.json`),this.conflictStore=new kQ(this.projectDir,this.currentBranch)}syncGhTokenHost(){return SF(this.projectDir)}gitHandle(e){return ws(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:e,ghToken:this.ghTokenSource.get(this.syncGhTokenHost())??void 0,timeoutMs:12e4})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){a9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),a9.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){a9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=Du(this.projectDir),n=t?R(t,`MERGE_HEAD`):null,r=n!==null&&V(n);this.conflictCount=this.conflictStore.count();let i=()=>this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(i().length>0&&!r){a9.warn({count:i().length},`[sync] persisted merge conflicts but no MERGE_HEAD — clearing stale state`);for(let e of i())this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count()}else if(i().length>0&&r)try{let e=this.gitHandle(),t=new Set(await Xb(e.git,[`diff`,`--name-only`,`--diff-filter=U`])),n=this.conflictCount;for(let e of i())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<n&&a9.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){a9.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(r&&i().length===0){a9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(i().length>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),a9.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let a=this.conflictStore.list().filter(e=>e.variant===`working-tree`);a.length>0&&await this.notifyContentConflictsDetected(a.map(e=>e.file)),this.mode===`follow`&&await this.refreshAuthTier();let o=i9(this.lastFetchUtc,this.currentPullIntervalSeconds()),s=i9(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(o>0?o:void 0),this.schedulePush(s>0?s:void 0),a9.info({branch:this.currentBranch,pullDelayMs:o,pushDelayMs:s},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setMode(e,t=`config`){if(this.mode===e)return;let n=this.mode;if(this.mode=e,a9.info({from:n,to:e,source:t},`[sync] mode changed`),e===`off`){this.cancelScheduledCycles(),await this.drainInFlightCycles(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}e===`follow`&&(await this.drainInFlightCycles(),this.cancelScheduledCycles(),await this.convertStrandedCommitsToOverlay()),this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}async setEnabled(e){await this.setMode(e?`full`:`off`)}cancelScheduledCycles(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null)}async drainInFlightCycles(){let e=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-e>3e4){a9.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await hu(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||l9(this.projectDir)?0:this.unpushedCommitCount(this.gitHandle())}async unpushedCommitCount(e){try{let t=await e.git.status();if(t.tracking)return t.ahead}catch{}try{let t=(await e.git.raw([`rev-list`,`--count`,`origin/${this.currentBranch}..HEAD`])).trim(),n=Number.parseInt(t,10);return Number.isFinite(n)?n:0}catch{return 0}}async convertStrandedCommitsToOverlay(){if(!this.hasRemote||l9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){a9.warn({err:e},`[sync] pull-only: could not probe stranded commits — skipping conversion`);return}if(t!==0){try{await this.checkpointBeforeStrandedConversion?.({branch:this.currentBranch,ahead:t})}catch(e){a9.warn({err:e},`[sync] pull-only: stranded-commit checkpoint failed — proceeding`)}try{let n=(await e.git.raw([`merge-base`,`HEAD`,`origin/${this.currentBranch}`])).trim();this.setBatchInProgress?.(!0);try{await Ss(()=>e.git.raw([`reset`,`--mixed`,n]))}finally{this.setBatchInProgress?.(!1)}let r=await e.git.status();this.ahead=r.ahead,this.behind=r.behind,this.pausedReason=void 0,a9.info({ahead:t,behind:this.behind},`[sync] pull-only: folded stranded local commits into a working-tree overlay`)}catch(e){this.pausedReason=`diverged-local-commits`,a9.warn({err:e},`[sync] pull-only: stranded-commit conversion failed — leaving branch as-is`)}}}async notifyCredentialsChanged(){if(this.mode!==`off`&&(this.ghTokenSource.invalidate(),!(this.state!==`auth-error`&&this.pausedReason!==`auth-error`))){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){if(this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),e===`pull`){await this.pullOnce();return}this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?a9.warn({op:e,state:this.state,mode:this.mode,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):a9.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(await this.runPushCycle(),await this.runPullCycle())}async pullOnce(){let e=this.mode,t=await this.runOneShotPull();return a9.info({mode:e,outcome:t},`[sync] one-shot pull complete`),t}async runOneShotPull(){if(this.pullInFlight||this.pushInFlight||this.state===`conflict`||!this.hasRemote||l9(this.projectDir))return this.recordPullOutcome(`refused`);let e=this.mode,t=this.state,n=this.pausedReason;this.pullInFlight=!0;try{return this.recordPullOutcome(await this.doPullCycle())}finally{this.pullInFlight=!1,e===`off`?(this.pausedReason=n,this.transitionTo(t)):this.schedulePull()}}recordPullOutcome(e){return this.lastPullUtc=new Date().toISOString(),this.lastPullOutcome=e,this.cc1Broadcaster?.signal(`sync-status`),e}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,lastPullUtc:this.lastPullUtc,lastPullOutcome:this.lastPullOutcome,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.mode!==`off`,syncMode:this.mode,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?Ude(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await Hz(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=xF(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,s9(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,a9.info({caller:e,host:t.host,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let n;try{n=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,transport:t.transport,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){a9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),n={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let r=hDe(n),i=this.pushPermission;this.pushPermission=r;let a=!1;return r.checkStatus===`denied`&&this.mode===`full`?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),a=!0,a9.info({reason:r.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):r.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),a=!0,a9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!a&&!s9(i,r)&&this.cc1Broadcaster?.signal(`sync-status`),r}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,a9.info({mode:this.mode},`[sync] remote detected post-boot — re-evaluating state`),this.mode===`off`?this.transitionTo(`disabled`):(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()))}async probeRemote(){if(!V(R(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return a9.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){let e=this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(e.length===0)return;let t=this.conflictCount,n=Du(this.projectDir),r=n?R(n,`MERGE_HEAD`):null;if(r!==null&&V(r))try{let n=this.gitHandle(),r=new Set(await Xb(n.git,[`diff`,`--name-only`,`--diff-filter=U`]));for(let t of e)r.has(t.file)||this.conflictStore.removeConflict(t.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<t&&a9.info({cleared:t-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){a9.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}else{a9.info({cleared:e.length},`[sync] external resolve detected (no MERGE_HEAD) — clearing merge-native conflicts`);for(let t of e)this.conflictStore.removeConflict(t.file);this.conflictCount=this.conflictStore.count()}this.conflictCount!==t&&(this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,n){let r=this.conflictStore.list().find(t=>t.file===e)?.variant===`working-tree`;this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,n)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}r&&(a9.info({choice:t},`[sync] pull-only: conflict resolved by choice`),await this.notifyContentConflictsResolved([e])),this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{a9.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){if(this.mode!==`full`)return;this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??c9(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{a9.error({err:e},`[sync] push cycle uncaught error`)})},t)}async resolveAuthTier(){let e=this.syncGhTokenHost();if(this.ghTokenSource.get(e)!==null)return`authenticated`;if(this.tokenStore)try{if((await this.tokenStore.get(e))?.token)return`authenticated`}catch(e){a9.warn({err:e},`[sync] auth-tier token-store lookup threw — treating as anonymous`)}return`anonymous`}async refreshAuthTier(){this.authTier=await this.resolveAuthTier()}currentPullIntervalSeconds(){return this.mode===`follow`?fDe(this.pullIntervalSeconds,this.authTier===`anonymous`?`anonymous`:`authenticated`):this.pullIntervalSeconds}effectivePullDelayMs(){let e=gDe(this.consecutiveFailures);return c9(e>0?e/1e3:this.currentPullIntervalSeconds())}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`||this.state===`auth-error`)){if(this.state===`conflict`){this.schedulePull();return}if(l9(this.projectDir)){this.schedulePull();return}this.mode===`follow`&&await this.refreshAuthTier(),this.pullInFlight=!0;try{this.recordPullOutcome(await this.doPullCycle())}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=this.gitHandle(),t;try{let n=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!n||n===`HEAD`)return this.transitionTo(`disabled`),this.pausedReason=`detached-head`,a9.warn({},`[sync] detached HEAD — pausing sync`),`refused`;t=n,this.currentBranch=t}catch(e){return this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=e9(e instanceof Error?e:Error(String(e)));return this.handleError(t,`pull`),`error`}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.mode!==`full`){let n=await this.doPullCycleB1(e,t);return this.scheduleSaveState(),n}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(e);let n=await this.prepareForMerge(e,t);if(!n.proceed)return`refused`;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{n.needsStashPop&&await this.popPreMergeStash(e)}return this.scheduleSaveState(),`succeeded`}catch(e){let t=e9(e instanceof Error?e:Error(String(e)));return t.class===`semantic`&&t.subclass===`merge-conflict`?(await this.handleMergeConflict(),this.state===`conflict`?`conflict`:this.pullError?`error`:`succeeded`):(this.handleError(t,`pull`),`error`)}finally{this.setBatchInProgress?.(!1)}}return this.transitionTo(`idle`),this.scheduleSaveState(),this.behind===0?`up-to-date`:`conflict`}async doPullCycleB1(e,t){if(this.transitionTo(`pulling`),this.ahead>0)return this.clearPullError(),this.pausedReason=`diverged-local-commits`,this.transitionTo(`idle`),a9.warn({ahead:this.ahead,behind:this.behind},`[sync] pull-only: local history diverged — not fast-forwardable, skipping cycle`),`refused`;let n,r;try{n=(await e.git.revparse([`HEAD`])).trim();let i=await Xb(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await Xb(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]));r=i.filter(e=>a.has(e))}catch(e){return this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}let i=new Map;for(let e of this.conflictStore.list())e.variant===`working-tree`&&i.set(e.file,e);let a;try{a=await this.planOverlapReconciliation(e,t,n,r,i)}catch(e){return this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.setBatchInProgress?.(!0);try{if(r.length>0){try{await this.checkpointBeforeOverlayRestore?.({branch:t,paths:r.length})}catch(e){a9.warn({err:e,paths:r.length},`[sync] pull-only: overlay checkpoint failed before restore — proceeding`)}try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,`--`,...r])}catch(e){return a9.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}}let n=await this.fastForwardOnly(e,t);if(!n.ok){try{this.applyOverlayPlan(a.mineRestore,a.deletions)}catch(e){return a9.error({err:e,refusal:n.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}return n.timedOut?(a9.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(e9(Error(`git merge --ff-only timed out after ${u9}ms`)),`pull`),`error`):(n.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),a9.warn({refusal:n.refusal,stderr:n.stderr.slice(0,200)},`[sync] pull-only: fast-forward refused — skipping cycle`),`refused`)}try{this.applyOverlayPlan(a.writes,a.deletions)}catch(e){return a9.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}let i=!0;for(let e of a.upserts)i=this.conflictStore.addConflict(e)&&i;for(let e of a.dissolved)i=this.conflictStore.removeConflict(e)&&i;if(this.conflictCount=this.conflictStore.count(),!i)return a9.error({},`[sync] pull-only: failed to persist conflict state after fast-forward — surfacing as error`),this.handleError(e9(Error(`failed to persist conflict state after fast-forward`)),`pull`),`error`;this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.clearPullError(),this.pausedReason=void 0,this.transitionTo(`idle`),a.newConflicts.length>0&&await this.notifyContentConflictsDetected(a.newConflicts),a.dissolved.length>0&&await this.notifyContentConflictsResolved(a.dissolved),(a.newConflicts.length>0||a.dissolved.length>0)&&this.cc1Broadcaster?.signal(`sync-status`);let o=await this.countStandingOverlay(e);return a9.info({created:a.newConflicts.length,autoCombined:a.autoCombined.length,autoDissolved:a.dissolved.length,autoRestored:a.autoRestored.length,overlayStock:o},`[sync] pull-only: fast-forwarded to origin tip`),a.newConflicts.length>0?`conflict`:`succeeded`}finally{this.setBatchInProgress?.(!1)}}async fastForwardOnly(e,t){try{return await pDe(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,`origin/${t}`],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:u9}),{ok:!0}}catch(e){let t=e,n=t.killed===!0||t.signal===`SIGTERM`,r=typeof t.code==`number`?t.code:null,i=typeof t.stderr==`string`?t.stderr:e instanceof Error?e.message:String(e);return{ok:!1,refusal:mDe({exitCode:r,stderr:i}),stderr:i,exitCode:r,timedOut:n}}}async planOverlapReconciliation(e,t,n,r,i){let a=[],o=[],s=[],c=[],l=[],u=[],d=[],f=[];for(let p of r){let r=i.get(p),m=r!==void 0;if(!V(R(this.projectDir,p))){try{await e.git.revparse([`origin/${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),a9.warn({err:e,path:p},`[sync] pull-only: unexpected error probing origin for a deleted overlay — deferring reconcile`);continue}s.push(p),m&&l.push(p);continue}if(!this.isContentConflictPath(p)){s.push(p);continue}f.push(p),m&&l.push(p);continue}let h;try{h=H(R(this.projectDir,p))}catch{continue}o.push({path:p,bytes:h});let g=h.toString(`utf-8`),_=null;try{_=await e.git.raw([`show`,`origin/${t}:${p}`])}catch(e){this.classifyRefReadFailure(e)===`error`&&a9.warn({err:e,path:p},`[sync] pull-only: unexpected error reading origin blob — keeping overlay, deferring reconcile`),_=null}if(_!==null&&_===g){m&&l.push(p);continue}if(_===null||!this.isContentConflictPath(p)){a.push({path:p,bytes:h});continue}let v=m?r.baseSha:await this.gitBlobSha(e,`${n}:${p}`),y=li(v?await this.gitBlobContent(e,v):``,g,_);if(y.clean){a.push({path:p,bytes:Buffer.from(y.merged,`utf-8`)}),d.push(p),m&&l.push(p);continue}a.push({path:p,bytes:h});let b=await this.gitBlobSha(e,`origin/${t}:${p}`);if(b===void 0){a9.warn({path:p},`[sync] pull-only: could not pin origin blob for a collision — keeping overlay, deferring`);continue}c.push({file:p,detectedAt:r?.detectedAt??new Date().toISOString(),variant:`working-tree`,theirsSha:b,baseSha:v}),m||u.push(p)}return{writes:a,mineRestore:o,deletions:s,upserts:c,dissolved:l,newConflicts:u,autoCombined:d,autoRestored:f}}applyOverlayPlan(e,t){for(let{path:t,bytes:n}of e){let e=R(this.projectDir,t);eL(e,this.projectDir),os(e,n)}for(let e of t){let t=R(this.projectDir,e);eL(t,this.projectDir);try{Ko(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=R(this.projectDir,e),n=PD(z(this.contentDir,t));return!n.startsWith(`..`)&&Gx(n)&&!this.contentFilter.isExcluded(n)}async gitBlobSha(e,t){try{return(await e.git.revparse([t])).trim()}catch{return}}classifyRefReadFailure(e){let t=e instanceof Error?e.message:String(e);return/does not exist in|exists on disk, but not in/i.test(t)?`absent`:`error`}async gitBlobContent(e,t){return e.git.raw([`cat-file`,`blob`,t])}async countStandingOverlay(e){try{return(await Xb(e.git,[`diff-index`,`--name-only`,`HEAD`])).filter(e=>this.isContentConflictPath(e)).length}catch{return null}}async runPushCycle(){if(!this.pushInFlight&&this.mode===`full`&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(l9(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),n=R($l(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),r=null;this.transitionTo(`pushing`);try{await Ss(async()=>{let e=this.gitHandle(n);if(l9(this.projectDir)){a9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){a9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(e9(e instanceof Error?e:Error(String(e))),`push`);return}await e.git.raw([`read-tree`,i]);let a=await this.listHeadContentPaths(e,i);if(t.length>0)for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...r])}let o=new Set(t.map(e=>e.projectRelPath)),s=[...a].filter(e=>!o.has(e));await this.removePathsFromIndex(e,s);let c=(await e.git.raw([`write-tree`])).trim(),l=``;try{l=(await e.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(l&&l===c){let n=null;try{n=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(n===i){a9.info({contentFileCount:t.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.lastSyncUtc=new Date().toISOString(),this.clearPushError(),this.transitionTo(`idle`);return}a9.info({headSha:i,upstreamSha:n},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=i;return}let u=[],d=[];try{let n=await Xb(e.git,[`diff-tree`,`--name-only`,`-r`,i,c]);if(n.length>0){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of n){u.push(t);let n=e.get(t)??PD(z(this.contentDir,R(this.projectDir,t)));n&&!n.startsWith(`..`)&&d.push(n)}}}catch{u=t.map(e=>e.projectRelPath).concat(s),d=t.map(e=>e.contentRelPath)}let f=this.buildCommitMessage(d),p=await Hz(this.projectDir),m=p===null;this.identityUnresolved!==m&&(this.identityUnresolved=m,this.cc1Broadcaster?.signal(`sync-status`));let h=p?.name??`OpenKnowledge`,g=p?.email??`sync@open-knowledge.local`;Es(e,{GIT_AUTHOR_NAME:h,GIT_AUTHOR_EMAIL:g,GIT_COMMITTER_NAME:h,GIT_COMMITTER_EMAIL:g});let _=(await e.git.raw([`commit-tree`,c,`-p`,i,`-m`,f])).trim();if(!_||!o9.test(_)){a9.warn({raw:_},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,_,i]),await this.resetRealIndexForPaths(u);let v=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),v=!0}catch{}v?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=_}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let n=e9(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){a9.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);try{await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e);let t=await this.prepareForMerge(e,this.currentBranch);if(!t.proceed){this.setBatchInProgress?.(!1);return}try{await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=e9(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}a9.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n,`push`)}finally{try{ql(n)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync(),r=await this.listHeadContentPaths(e,t);if(n.length===0&&r.size===0)return null;let i=R($l(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),a=this.gitHandle(i);try{await a.git.raw([`read-tree`,t]);for(let e=0;e<n.length;e+=100){let t=n.slice(e,e+100).map(e=>e.projectRelPath);await a.git.raw([`add`,`--`,...t])}let i=new Set(n.map(e=>e.projectRelPath)),o=[...r].filter(e=>!i.has(e));await this.removePathsFromIndex(a,o);let s=(await a.git.raw([`write-tree`])).trim();if(s===(await a.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let c=[];try{c=await Xb(a.git,[`diff-tree`,`--name-only`,`-r`,t,s])}catch{c=n.map(e=>e.projectRelPath).concat(o)}let l=await Hz(this.projectDir),u=l?.name??`OpenKnowledge`,d=l?.email??`sync@open-knowledge.local`;Es(a,{GIT_AUTHOR_NAME:u,GIT_AUTHOR_EMAIL:d,GIT_COMMITTER_NAME:u,GIT_COMMITTER_EMAIL:d});let f=(await a.git.raw([`commit-tree`,s,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!f||!o9.test(f)?(a9.warn({raw:f},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,f,t]),await this.resetRealIndexForPaths(c,e),f)}finally{try{ql(i)}catch{}}}async prepareForMerge(e,t){let n;try{n=await Xb(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return a9.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}if(n.length===0)return{proceed:!0,needsStashPop:!1};let r;try{r=new Set(await Xb(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return a9.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}let i=n.filter(e=>r.has(e));if(i.length>0){let e=i.slice(0,3).join(`, `),t=i.length>3?`, +${i.length-3} more`:``;return this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),a9.warn({files:i},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1}}let a=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,a])}catch(e){return a9.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1}}return{proceed:!0,needsStashPop:!0}}async popPreMergeStash(e){try{await e.git.raw([`stash`,`pop`])}catch(e){a9.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=Vl(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=R(n,i.name);if(i.isDirectory()){let e=PD(z(this.contentDir,r));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e))continue;t(r)}else if(i.isFile()||i.isSymbolicLink()){let t=PD(z(this.contentDir,r));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=PD(z(this.projectDir,r));e.push({contentRelPath:t,projectRelPath:n})}}}};return V(this.contentDir)&&t(this.contentDir),e}async listHeadContentPaths(e,t){let n=new Set;try{let r=await Xb(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r){let t=R(this.projectDir,e),r=PD(z(this.contentDir,t));!r.startsWith(`..`)&&!this.contentFilter.isExcluded(r)&&n.add(e)}}catch{}return n}async removePathsFromIndex(e,t){if(t.length===0)return;let n=[...new Set(t)];for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100);await e.git.raw([`rm`,`--cached`,`--`,...r])}}async resetRealIndexForPaths(e,t){if(e.length===0)return;let n=t??this.gitHandle(),r=[...new Set(e)];for(let e=0;e<r.length;e+=100){let t=r.slice(e,e+100);try{await n.git.raw([`reset`,`HEAD`,`--`,...t])}catch{}}}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=this.gitHandle(),t=[];try{t=await Xb(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){a9.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=R(this.projectDir,e),i=PD(z(this.contentDir,t));!i.startsWith(`..`)&&Gx(i)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}let i=[];for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),a9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){a9.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),i.push({file:t,err:e})}if(i.length>0){let t=i.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let n=t.slice(0,3).join(`, `),r=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${n}${r}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),a9.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(n),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),a9.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await e.git.raw([`commit`,`--no-edit`]);let n=Du(this.projectDir);t=n===null||!V(R(n,`MERGE_HEAD`))}catch(e){a9.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),a9.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullError=`Sync paused — could not finalize the merge. Retry sync to try again.`,this.transitionTo(`idle`),a9.warn({},`[sync] could not finalize merge after auto-resolving conflicts — merge aborted`)}}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){a9.warn({err:t,files:e},`[sync] content conflict callback failed`)}}async notifyContentConflictsResolved(e){if(e.length!==0)try{await this.onContentConflictsResolved?.(e)}catch(t){a9.warn({err:t,files:e},`[sync] content conflict resolved callback failed`)}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),a9.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.ghTokenSource.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.mode=`off`,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,a9.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`||this.pausedReason===`auth-error`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};Jl(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){a9.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(V(this.statePath))try{let e=H(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason===`no-push-permission`||t.pausedReason===`auth-error`?void 0:t.pausedReason;let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){a9.warn({err:e},`[sync] failed to load sync state`)}}};Do();const vDe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function yDe(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(rS(e)||iS(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&vDe.test(n)&&(r[`mount.id`]=n);try{let e=()=>{Po(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),Oo.with(To.extract(Oo.active(),r),e)}else e()}catch(e){I(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let d9=!1;function f9(){if(d9)return;let e=Jte;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){d9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),d9=!0}catch(e){I(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const bDe=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function xDe(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(v8).join(` `)} auth git-credential`]}function SDe(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=Sl(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],xN({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return I(`upstream-attribution`).warn({err:e,oldHead:n,newHead:r},`git log spawn threw; upstream docs keep file-system attribution`),i}if(a.error||a.status!==0||typeof a.stdout!=`string`)return I(`upstream-attribution`).warn({err:a.error,status:a.status,signal:a.signal,stderr:typeof a.stderr==`string`?a.stderr.slice(0,500):void 0,oldHead:n,newHead:r},`git log failed; upstream docs keep file-system attribution`),i;let o=null;for(let n of a.stdout.split(`
|
|
2029
|
-
`)){let r=n.trim();if(r===``)continue;if(r.startsWith(`C\0`)){let[,e,t]=r.split(`\0`);o=e&&t?{name:e,email:t}:null;continue}if(!o||!r.endsWith(`.md`)&&!r.endsWith(`.mdx`))continue;let a=B(e,r);if(!LD(a,t))continue;let s=tz(a,t);i.has(s)||V(a)&&i.set(s,o)}return i}function p9(e){f9();let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,configHomedirOverride:l,enableTestRoutes:u=!1,shadowRepo:d,contentRoot:f,destroyTimeoutMs:p=1e4,localOpCliArgs:m,authStreamHeartbeatMs:h,skipStateManifestCheck:g=!1,singleDocRelPath:_,ephemeral:v=!1}=e,y=I(`server`),x=new c7,S=()=>x.getActiveBranch(),C=e=>x.getReconciledBase(e),w=(e,t)=>x.setReconciledBase(e,t),T=e=>x.deleteReconciledBase(e),ee=e=>x.switchReconciledBaseScope(e),te=e=>x.setBatchInProgress(e),E=()=>x.isBatchInProgress();function ne(){let e=Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=se(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function O(){let e=Fo({absPath:Lo(`project-local`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)}),t=b(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||y.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let r=Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});return r.valid||y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:D(r.value.autoSync?.default)??`off`,source:`committed-default`}}function k(){let e=Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?Vn(e):Qe}function re(){return Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function A(){return WM(n,{configHomedirOverride:l,onWarn:e=>y.warn({message:e},`[config] could not read project-local config`)})}function ie(){let e=Fo({absPath:Lo(`project-local`,n,l),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function j(){return No({cwd:n,homedirOverride:l,warn:e=>y.debug({message:e},`[config] diagnostics read`)})}function oe(){for(let e of j().diagnostics)e.code===`REMOVED_KEY`&&y.warn({scope:e.scope,file:e.file,path:e.path.join(`.`)},`[config] ${e.path.join(`.`)} is no longer read and was ignored. ${e.redirect}`)}function ce(e){return`${PM(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function le(e){let t;if(e===`__config__/project`||e===`__local__/project`){let n=O();t=n.mode,ft?.setMode(n.mode,n.source).catch(t=>{y.warn({err:t,mode:n.mode,docName:e},`[sync] failed to apply autoSync mode from config`)})}let n=A();Ae.applyConfig({enabled:n.enabled,providerFingerprint:ce(n)}),e===`__config__/project`&&we?.signal(`lint-config`),y.info({docName:e,autoSyncMode:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}cs();let ue=uu(),de=ok(n),fe=new od({localDir:de,log:I(`acp-registry`)}),M=new Qu(de,I(`acp-permissions`));if(Rs(de,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!g)try{Z7({lockDir:de,shadowRepoDir:Ou(n)})}catch(e){throw Os(de),e}let pe=Da(),me=(e,t)=>pe.resolveEmbed(e,t),he=(e,n)=>{let r=pe.resolveEmbed(e,n);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=B(t,r);if(!FD(i,B(t)))return null;try{let e=Kl(i);return e.isFile()?e.size:null}catch{return null}},ge,N,_e,ve,ye,P,be,xe,Se,Ce,we=null,Te=null,F=null,Ee=null,De=null,Oe=null,ke=A(),Ae=new Xle({loadEmbedder:e.embedderLoader??(()=>{let t=A();return Ile({keyStore:e.embeddingsKeyStore??null,projectDir:n,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:R(ok(n),`embeddings`),enabled:ke.enabled,providerFingerprint:ce(ke)}),je=null,Me=new Set,Ne=!1,Pe=[],Fe,Ie,Le,Re=new Promise((e,t)=>{Ie=e,Le=t});function ze(e){we?.signal(e)}let Be=null,Ve=!1,He=()=>{try{H7(n,Ue.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Ue=new MEe(void 0,{onEviction:()=>Soe(),onSizeChange:e=>Coe(e),onMutate:()=>{!Ve||Be!==null||(Be=setTimeout(()=>{Be=null,He()},2e3))}});for(let[e,r]of FEe(n))cS(e)||gQ(e)&&([`.md`,`.mdx`].some(n=>{let r=B(t,`${e}${n}`);return FD(r,B(t))&&V(r)})||Ue.restore(e,r));Ve=!0;let We={current:null},Ge=(e,t)=>{cS(e)||Ue.setRenamed(e,t)},Ke=e=>{if(!cS(e)){if(Ue.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Ue.setDeleted(e),We.current?.deleted(e)}},qe=e=>{cS(e)||Ue.delete(e)};try{ge=hP({projectDir:n,contentDir:t,singleDocRelPath:_,inPlaceSkillDirs:$I(t),rescanInPlaceSkillDirs:()=>$I(t),onAfterRebuild:()=>{N.refreshContentScope().catch(e=>{I(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),wz(ut).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?I(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):I(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{I(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),N=new vR({projectDir:n,contentDir:t,contentFilter:ge,getGlobalSkillRoots:()=>LG(ye.managedArtifactCtx),signalChannel:ze}),_e={current:d},ve=o?bEe({getShadow:()=>_e.current??null,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,contentRoot:f??``,projectGitDir:Du(n)??void 0,isWriterLive:e=>{if(!Ee&&!xe)return I(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Ee?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of xe?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,ye=F7({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:_e,ephemeral:v,contentRoot:f,derivedDocumentIndex:N,configHomedirOverride:l,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,resolveEmbed:me,resolveSize:he,getPrincipal:()=>je,onAgentCommit:()=>we?.signal(`session-activity`),onFlushCommit:()=>ve?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{we?.emitDiskAck(e,t),!cS(e)&&oO(r,n)&&(De?.(),ze(`files`))},onConfigRejected:(e,t)=>we?.emitConfigValidationRejected(e,t),onConfigPersisted:le,isRecentlyRemoved:e=>Ue.has(e),mdManager:e.mdManager,getLossRing:()=>P,durabilityState:x}),be=new ITe({quiet:r,debounce:i,maxDebounce:a,extensions:[ye.extension]});let p=be;Pe.push(Mse(()=>p.documents.size),Nse(()=>ye.getQueueDepths()),Fse(()=>{let e=0;for(let t of p.documents.values())e+=t.directConnectionsCount;return{websocket:p.getConnectionsCount()-e,direct:e}})),JC(),v||(Oe=AEe({getLoadedDocuments:()=>p.documents,forceStore:(e,t)=>ye.forceStore(e,t),getBase:e=>x.getReconciledBase(e),isBatchActive:()=>x.isBatchInProgress(),peekInFlight:e=>x.peekInFlightFlush(e),readDiskBytes:e=>{let n=ID(e,t),r,i;try{r=U(n),i=Kl(r).size}catch(t){let n=Vs(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new L7(`symlink cycle at content path: ${e}`):t}if(!LD(r,t))throw new L7(`symlink-escape: ${n} resolves outside the content dir`);if(i>524288)throw new L7(`document exceeds the open byte limit: ${e}`);try{return H(r,`utf-8`)}catch(e){if(Vs(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let g=be.shouldUnloadDocument.bind(be);be.shouldUnloadDocument=e=>{if(Me.has(e)||Ne&&g(e))return!0;let t=e.name;return cS(t)||C(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:g(e)},Fe=async e=>{Me.add(e);try{await be.unloadDocument(e)}finally{Me.delete(e)}},we=new dS(be),F=new NE(be),Ee=new PE(be),xe=new Nw(be,e.agentSessionOptions);let b=xe;Pe.push(qC(()=>({active:b.liveSessionCount,limit:b.sessionLimit})));let w=f7({derivedDocumentIndex:N,onDocumentSettled:e=>We.current?.changed(e)});be.configuration.extensions.push(w),be.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=EQ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==ue)throw new TQ(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${ue}`);let i=n?.expectedBranch,a=S();if(typeof i==`string`&&i.length>0&&i!==a)throw new TQ(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(je&&n.principalId===je.id?o.principalId=je.id:je?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:je.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),be.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(t){if(!iS(t.documentName)&&!aS(t.documentName))return;let n=t.request,r=n.socket?.remoteAddress;if(r!==void 0&&!Wz(r))throw Error(`config-doc admission requires loopback peer (peer=${r}, doc=${t.documentName})`);let i=t.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0,o=e.remotePublicHost!==void 0&&Xz(a,e.remotePublicHost);if(!Gz(a)&&!o)throw Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${t.documentName})`)}});let T=B(t);function ee(e){if(!gQ(e))return null;let t=B(T,eS(e));return FD(t,T)?t:null}be.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await NEe(e.documentName,{recentlyRemovedDocs:Ue,resolveFilePath:ee,fileExists:V})}}),be.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=EQ(e.token);QTe(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>be.documents.get(e)})}}),be.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new E5(e.update);if(t.readVarString(),t.readVarUint()===L5.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${qr} rejected — server-only channel`)}});let te=_Q({hocuspocus:be,durabilityState:x,remotePublicHost:e.remotePublicHost,sessionManager:xe,commentDocHooksRef:We,contentDir:t,contentFilter:ge,serverInstanceId:ue,getFileIndex:()=>ut?ut.getFileIndex():new Map,getAttachmentFolderPath:ne,getAllFilesIndex:()=>ut?ut.getAllFilesIndex():new Map,getFileIndexGeneration:()=>ut?.getFileIndexGeneration()??0,mutateFileIndex:e=>ut?.mutateFileIndex(e),getFolderIndex:()=>ut?ut.getFolderIndex():new Map,getAliasMap:()=>ut?ut.getAliasMap():new Map,getFolderAliasIndex:()=>ut?ut.getFolderAliasIndex():new Map,rescanFiles:()=>ut?.rescanFromDisk(),enableTestRoutes:u,shadowRef:_e,flushGitCommit:()=>ye.flushPendingGitCommit(),flushContributors:()=>ye.flushContributors(),getCurrentBranch:()=>dt?.getLastKnownBranch()??null,getDiskAckSVs:()=>we?.getLatestDiskAckSVsAsBase64()??{},contentRoot:f,derivedDocumentIndex:N,signalChannel:ze,agentFocusBroadcaster:F,agentPresenceBroadcaster:Ee,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>ft,localOpCliArgs:m,authStreamHeartbeatMs:h,projectDir:n,resolveEmbed:me,getBridgeLossReporter:()=>Ce,getPrincipal:()=>je,acpRegistry:fe,loadAcpCustomAgents:()=>sd(de,I(`acp-registry`)),homeDirOverride:l,forceUnloadDocument:Fe,ready:Re,recentlyRemovedDocs:Ue,serializeDoc:$e,evictManagedArtifactLkg:e=>{ye.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Ae,getSemanticSimilarityFloor:()=>A().similarityFloor,getLinterBaseConfig:()=>k(),getLinksValidationSetting:()=>re(),getLinkPreviewsEnabled:ie,getConfigDiagnostics:j,embeddingsSecretsFile:VM(l),readSemanticProviderConfig:A,ephemeral:v,onReferencedAssetsCacheInvalidator:e=>{De=e}});be.configuration.extensions.push(te),Se=te.nativeApi;let E=Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for bridge guards`)}),D=E.value.bridge.deferGuard.enabled,O=E.value.bridge.fixedPoint.enabled,ae=E.value.bridge.preDrain.enabled;P=E.value.lossCapture.enabled?new dae({projectDir:n,maxBytes:E.value.lossCapture.maxBytes}):void 0,E.value.bridge.lossDetector.enabled&&(Ce=nse({shadow:()=>_e.current,ring:P,getBranch:()=>dt?.getLastKnownBranch()??`main`,contentRoot:f??``}),xe.attachBridgeLossReporter(Ce)),be.configuration.extensions.push(W7({mdManager:Ao,schema:ko,shadowRef:_e,contentRoot:f,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,resolveEmbed:me,resolveSize:he,deferGuardEnabled:D,lossDetectorEnabled:E.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:O,preDrainEnabled:ae,lossRing:P})),be.configuration.extensions.push(yDe()),be.configuration.extensions.push(ZTe({getSyncEngine:()=>ft,projectDir:n,contentDir:t}))}catch(e){for(let e of Pe.splice(0))e();throw Oe?.dispose(),Oe=null,Os(de),e}let Je=null,Ye=new Map,Xe=[];function Ze(e,t){let n=B(e,`rescue`),r=B(n,eS(t));return FD(r,n)?r:null}function $e(e){let t=be.documents.get(e);return t?jR(t):null}let et=(e,t)=>OR(x,be,e,t,me,he,Ce);function tt(e){if(!bS(e)||ft?.getConflicts().some(r=>s7(r,e.name,n,t)))return;let r=e.getMap(`lifecycle`);r.delete(`status`),r.delete(`reason`)}let nt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of be.documents){if(cS(n))continue;let r=be.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{bR(r,i,me,n)},yR)}catch(t){y.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},rt=null,it=e=>{e&&(rt===null&&(rt=new Set,setImmediate(()=>{let e=rt;if(rt=null,e)try{for(let t of e)nt(t)}catch(t){y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),rt.add(e))};function at(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return LR(e)}}async function ot(e){try{switch(e.kind){case`create`:y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await N.recordDiskUpsert(e.docName,e.content),ze(`files`),qe(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=be.documents.get(t);if(!r){await N.recordDiskUpsert(t,n);return}let i=C(t)??``,a=$e(t)??i,o=wR({docName:t,base:i,ours:a,theirs:n}),s=WR(i).slice(0,6),c=WR(a).slice(0,6),l=WR(n).slice(0,6);switch(y.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:tt(r),await N.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{et(t,o.newContent),w(t,o.newContent),Zb(),tt(r),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),w(t,n),tt(r)}e&&await N.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{et(t,o.newContent),w(t,n),Zb(),tt(r),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),w(t,n),tt(r)}e&&await N.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{et(t,o.newContent),w(t,o.newContent),Zb(),Qb(),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),w(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}e&&await N.recordDiskUpsert(t,n);break}case`refused`:{Qb();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=be.documents.get(t);if(!n){await N.recordDiskDelete(t),ze(`files`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=C(t)??``,i=$e(t)??``,a=i!==r;if(a&&_e.current){let e=_e.current,n=dt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{Rx(e,f??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{ex(),y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),T(t),await N.recordDiskDelete(t),y.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),be.closeConnections(t),await Fe(n),ze(`files`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=be.documents.get(t);if(T(t),w(n,r),await N.recordDiskRename(t,n,r),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}y.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),ze(`files`),Ge(t,n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,n=be.documents.get(t);if(!n)return;let r=$e(t);r===null?y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):w(t,r);let i=n.getMap(`lifecycle`);i.set(`status`,`conflict`),i.set(`reason`,`conflict-markers`),y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:pe.add(e.relativePath),ze(`files`),it(wl(e.relativePath));break;case`asset-delete`:pe.remove(e.relativePath),ze(`files`),it(wl(e.relativePath));break;case`folder-create`:case`folder-delete`:ze(`files`);break;case`file-create`:case`file-update`:case`file-delete`:ze(`files`);break;default:LR(e)}}catch(t){let n=at(e);y.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let st=[];async function ct(e){if(E()){st.push(e);return}await ot(e)}async function lt(){let e=st.splice(0,st.length);for(let t of e)await ot(t)}let ut=null,dt=null,ft=null,pt=null;async function mt(e){if(be.documents.size===0)return;let t=!1,n=new Promise(e=>{be.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(be.documents.keys());be.closeConnections(),be.flushPendingStores();for(let e of be.documents.values())e.getConnectionsCount()===0&&be.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(be.documents.keys()),i=[],o=[];if(_e.current){for(let e of n)if(!cS(e))try{let t=$e(e);if(t===null){y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=Ze(_e.current.gitDir,e);if(!n){y.warn({docName:e,gitDir:_e.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}Rl(L(n),{recursive:!0}),Jl(n,t,`utf-8`),ex(),i.push(e),y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else y.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function ht(){return pt||(pt=(async()=>{let e=Date.now(),t=[];Ne=!0;for(let e of Pe.splice(0))e();try{await Oe?.dispose()}catch(e){y.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Oe=null;try{zs(de)}catch(e){y.warn({err:e},`[server] failed to mark server.lock draining`)}if(Be!==null&&(clearTimeout(Be),Be=null),Ve)try{H7(n,Ue.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let r,i=await Promise.race([Re.then(()=>`completed`,e=>(y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&y.warn({},`[server] init did not complete within 5s during shutdown`);let a=be.documents.size;ve?.destroy();try{try{try{Te&&=(clearTimeout(Te),null),dt&&=(await dt.unsubscribe(),null),ut&&=(await ut.unsubscribe(),null);for(let{docName:e,cleanup:t}of Xe)try{await t()}catch(t){y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Xe.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{we?.destroy(),Ee?.destroy(),Je&&=(await Je.disconnect(),null);for(let[e,t]of Ye)try{await t.disconnect()}catch(t){y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Ye.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await xe.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await gse()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await mt(p)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-3 flush failed`)}N.close();let e;try{await Promise.race([(async()=>{await ye.flushPendingGitCommit(),await ye.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),p)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{ft&&=(await ft.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(_e.current){try{let e=(await xs({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&Jl(B(_e.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{Loe(_e.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?y.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):y.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{Os(de,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await ss()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),pt)}let gt=[];async function _t(){try{je=await R7(n),y.info({principalId:je.id},`[server] principal loaded`)}catch(e){y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!_e.current)try{_e.current=await wx(n),y.info({gitDir:_e.current.gitDir},`[server] history repo initialized at ${_e.current.gitDir}`)}catch(e){y.error({err:e},`[server] history repo init failed`),gt.push(`shadow-repo`)}if(_e.current){let e=null;try{e=kK(_e.current.gitDir),QK(_e.current.gitDir,e),PK(_e.current.gitDir,e),y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([$K(_e.current,e,{rebuild:!0}),new Promise((e,n)=>setTimeout(()=>n(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await ve?.runBootMaintenance()}catch(e){y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(_e.current)try{await Sx(_e.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){y.warn({},`[server] history repo appears corrupted — reinitializing`);try{_e.current=await wx(n)}catch(e){y.error({err:e},`[server] history repo reinit failed`),_e.current=void 0,gt.includes(`shadow-repo`)||gt.push(`shadow-repo`)}}else y.error({err:e},`[server] history repo check failed (transient?)`)}if(_e.current)try{let e=B(_e.current.gitDir,`last-known-head`),t=null;try{t=H(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await xs({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await xs({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}y.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await Fx(_e.current,f??``,t,r,e),$b()}catch(e){y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else y.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{Jl(e,r,`utf-8`)}catch(e){y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){y.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=hK(t,n);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;y.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){y.error({err:e},`[server] managed rename recovery failed`),gt.push(`managed-rename-recovery`)}try{let e=hL(n);(e.deleted>0||e.errors>0)&&y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){y.error({err:e},`[server] upload-tempfile sweep failed`),gt.push(`upload-tempfile-sweep`)}try{Je=await be.openDirectConnection(qr),we?.emitServerInfo(ue,S())}catch(e){y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),gt.push(`cc1-push`)}let r=v?[]:oa;for(let e of r)try{let t=await be.openDirectConnection(e);Ye.set(e,t)}catch(t){y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),gt.push(`config-doc:${e}`)}let i=new Map([[Ci,Lo(`project`,n)],[Ar,Lo(`project-local`,n)],[ma,Lo(`user`,n,l)]]);for(let e of r){let t=i.get(e);if(t)try{y.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await X5(t,t=>{let n=be.documents.get(e);y.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=o7(n??null,e,t,ye.configPersistenceCtx);y.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),le(e)});Xe.push({docName:e,cleanup:n}),y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){y.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),gt.push(`config-file-watcher:${e}`)}}if(!v){let e=(e,t)=>{let n=WG(e,ye.managedArtifactCtx);if(!n)return;let r=YG(be.documents.get(n)??null,n,t,ye.managedArtifactCtx);y.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),ze(`files`),ci(n)&&N.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})},t=e=>{let t=WG(e,ye.managedArtifactCtx);ze(`files`),t&&ci(t)&&N.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:t},`[backlinks] global skill bundle prune failed`)})};try{let n=LG(ye.managedArtifactCtx),r=await w7(n,e,void 0,t);Xe.push({docName:`__skill-files__`,cleanup:r}),y.info({roots:n},`[managed-artifact-watcher] skills started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),gt.push(`managed-artifact-watcher:skills`)}try{let e=B(PG(ye.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await X5(e,()=>{ze(`files`)});Xe.push({docName:`__skill-state__`,cleanup:t}),y.info({path:e},`[skill-state-watcher] started`)}catch(e){y.warn({err:e},`[skill-state-watcher] failed to start`),gt.push(`skill-state-watcher`)}try{let t=new Set([``]);try{for(let e of(await CA(n)).templates)t.add(e.source_folder)}catch(e){y.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let r=[...t].map(e=>e?B(n,e,`.ok`,`templates`):B(n,`.ok`,`templates`)),i=await w7(r,e,SEe);Xe.push({docName:`__template-files__`,cleanup:i}),y.info({rootCount:r.length},`[managed-artifact-watcher] templates started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),gt.push(`managed-artifact-watcher:templates`)}}try{let e=B(t,`.okignore`),r=B(n,`.gitignore`),i=null;try{let e=Sl(`git`,[`rev-parse`,`--git-common-dir`],xN({cwd:n,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=R(B(n,e.stdout.trim()),`info`,`exclude`);V(L(t))&&(i=t)}}catch{}let a=i?[e,r,i]:[e,r],o=y;o.info({okignorePath:e,gitignorePath:r,gitInfoExcludePath:i,ephemeral:v},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=v?null:await HTe(a,(t,r)=>{(async()=>{if(t===e)try{let e=o7(be.documents.get(`__config__/okignore`)??null,ja,r,ye.configPersistenceCtx);o.info({docName:ja,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:z(n,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await ge.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:z(n,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),we?.signal(`files`);else{let e=z(n,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),we?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:z(n,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Xe.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:r},`[ignore-watcher] multi-path watcher started`))}catch(e){y.warn({err:e,projectDir:n,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),gt.push(`ignore-files-watcher`)}let a=d7(n).branch??`main`;ee(a);let o=N.beginStartup(a),s=!1,c=performance.now();try{await zo(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:r}=await o.backlinksReady;r&>.push(`backlink-index`);let i=0;for(let t of e)cS(t)||Ue.peek(t)?.kind!==`renamed`&&(Ue.setDeleted(t),i++);i>0&&y.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`);let a=performance.now(),c=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,u=ge?$I(t):new Set,d=e=>{e.some(e=>c.test(z(t,e).split(Al).join(`/`)))&&(Te&&clearTimeout(Te),Te=setTimeout(()=>{Te=null;try{QX(n,t).then(e=>{e>0&&(y.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),we?.signal(`files`))}).catch(e=>y.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=$I(t);if(!(e.size!==u.size||[...e].some(e=>!u.has(e))))return;u=e,ge.rebuildIgnorePatterns().then(t=>{t.ok?(y.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),we?.signal(`files`)):y.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>y.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){y.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};ut=await zo(`ok.boot.seed-walk`,void 0,async()=>Cz(t,ct,ge,{onRawBatch:d})),QX(n,t).then(e=>{e>0&&y.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>y.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=l??Xl();QX(e,e,ZI(e)).then(e=>{e>0&&y.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>y.warn({err:e},`[in-place-skills] global copy re-sync failed`))}tR(`seedWalkMs`,Math.round(performance.now()-a));{let e=B(t),n=0;for(let[t]of Ue.entries()){if(!gQ(t))continue;let r=B(e,`${t}${Qx(t)}`);FD(r,e)&&V(r)&&(Ue.delete(t),n++)}n>0&&y.info({count:n},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let f=await N.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&>.push(`tag-index`);let p=0;try{_===void 0?await bQ({contentDir:t,contentFilter:ge,basenameIndex:pe,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):Tpe({contentDir:t,basenameIndex:pe,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),p>0&&(y.warn({count:p},`[basename-index] startup seed completed with ${p} skipped entries — embeds under inaccessible subtrees will not resolve`),gt.push(`basename-index-partial`))}catch(e){y.error({err:e},`[basename-index] startup seed failed`),gt.push(`basename-index`)}})}catch(e){if(y.error({err:e},`[server] disk bridge watcher failed to start`),gt.push(`file-watcher`),!s){let e=await N.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&>.push(`tag-index`)}}finally{tR(`indexesMs`,Math.round(performance.now()-c)),ut&&nR(`fileCount`,ut.getFileIndex().size)}try{dt=await rEe(n,async({trigger:e})=>{if(y.info({trigger:e},`[batch] begin trigger=${e}`),yae(),be.flushPendingStores(),await ye.flushPendingGitCommit(),te(!0),_e.current){let e=S(),t=d7(n).branch??e,r=[];for(let[e,t]of be.documents){if(cS(e))continue;let n=null;if(t.transact(()=>{n=$e(e)},bDe),n===null)continue;let i=C(e)??n;r.push({docName:e,markdown:n,diskSnapshot:i})}if(r.length>0)try{let n=await qoe(_e.current,e,Nx.id,r,t);n&&(Sae(),y.info({count:r.length,branch:e,sha:n.slice(0,8)},`[history] parked ${r.length} docs on ${e} → ${n.slice(0,8)}`))}catch(e){y.error({err:e},`[shadow] park failed`)}}},async e=>{let r=st.length,i=e.newBranch??`main`;if(y.info({kind:e.batchKind,headMoved:e.headMoved,docs:r,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${r}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(te(!1),await lt(),e.headMoved&&e.newHead){let r=SDe(n,B(t),e.oldHead,e.newHead);if(r.size>0){Jj(r.keys());for(let[e,t]of r)qj(e,tne(t.email),t.name,t.email,Hu(e));await ye.flushContributors()}}if(await ye.flushDeferredStores(`within-branch`),ft!==null)try{await ft.reconcileConflictsFromGit()}catch(e){y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{xae(),st.splice(0,st.length);let n=!1,r;try{ee(i),r=await N.beginBranchSwitch(i),ge.rebuildDirCount();try{let e=0;pe.clear(),await bQ({contentDir:t,contentFilter:ge,basenameIndex:pe,onSkip:(t,n,r)=>{e++,y.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(y.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),gt.includes(`basename-index-partial`)||gt.push(`basename-index-partial`))}catch(e){y.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,n]of be.documents)if(!cS(e))try{let r=ID(e,t);if(!V(r)){let t=C(e)??``,r=$e(e)??``;if(r!==t&&_e.current){let t=_e.current;queueMicrotask(()=>{Rx(t,f??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{ex(),y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),y.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=H(r,`utf-8`);et(e,a),w(e,a),y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}y.info({branch:i,docCount:be.documents.size},`[branch-switch] loaded branch ${i} (${be.documents.size} docs)`);try{await N.settleBranchFromDisk(r)}catch(e){N.abortBranchSwitch(r),y.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(_e.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of be.documents)if(!cS(t))try{let n=await Yoe(_e.current,i,Nx.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=C(t);if(!r)continue;let a=wR({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:et(t,a.newContent),w(t,a.newContent),e++;break;case`conflicts`:et(t,a.newContent),w(t,a.newContent),Qb(),e++;{let e=be.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&y.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&_e.current)try{let t=Sx(_e.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await vx(_e.current).withMutator(async()=>{for(let e of n.split(`
|
|
2029
|
+
`)){let r=n.trim();if(r===``)continue;if(r.startsWith(`C\0`)){let[,e,t]=r.split(`\0`);o=e&&t?{name:e,email:t}:null;continue}if(!o||!r.endsWith(`.md`)&&!r.endsWith(`.mdx`))continue;let a=B(e,r);if(!LD(a,t))continue;let s=tz(a,t);i.has(s)||V(a)&&i.set(s,o)}return i}function p9(e){f9();let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,configHomedirOverride:l,enableTestRoutes:u=!1,shadowRepo:d,contentRoot:f,destroyTimeoutMs:p=1e4,localOpCliArgs:m,authStreamHeartbeatMs:h,skipStateManifestCheck:g=!1,singleDocRelPath:_,ephemeral:v=!1}=e,y=I(`server`),x=new c7,S=()=>x.getActiveBranch(),C=e=>x.getReconciledBase(e),w=(e,t)=>x.setReconciledBase(e,t),T=e=>x.deleteReconciledBase(e),ee=e=>x.switchReconciledBaseScope(e),te=e=>x.setBatchInProgress(e),E=()=>x.isBatchInProgress();function ne(){let e=Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=se(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function O(){let e=Fo({absPath:Lo(`project-local`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)}),t=b(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||y.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let r=Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});return r.valid||y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:D(r.value.autoSync?.default)??`off`,source:`committed-default`}}function k(){let e=Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?Vn(e):Qe}function re(){return Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function A(){return WM(n,{configHomedirOverride:l,onWarn:e=>y.warn({message:e},`[config] could not read project-local config`)})}function ie(){let e=Fo({absPath:Lo(`project-local`,n,l),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function j(){return No({cwd:n,homedirOverride:l,warn:e=>y.debug({message:e},`[config] diagnostics read`)})}function oe(){for(let e of j().diagnostics)e.code===`REMOVED_KEY`&&y.warn({scope:e.scope,file:e.file,path:e.path.join(`.`)},`[config] ${e.path.join(`.`)} is no longer read and was ignored. ${e.redirect}`)}function ce(e){return`${PM(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function le(e){let t;if(e===`__config__/project`||e===`__local__/project`){let n=O();t=n.mode,ft?.setMode(n.mode,n.source).catch(t=>{y.warn({err:t,mode:n.mode,docName:e},`[sync] failed to apply autoSync mode from config`)})}let n=A();Ae.applyConfig({enabled:n.enabled,providerFingerprint:ce(n)}),e===`__config__/project`&&we?.signal(`lint-config`),y.info({docName:e,autoSyncMode:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}cs();let ue=uu(),de=ok(n),fe=new od({localDir:de,log:I(`acp-registry`)}),M=new Qu(de,I(`acp-permissions`));if(Rs(de,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!g)try{Z7({lockDir:de,shadowRepoDir:Ou(n)})}catch(e){throw Os(de),e}let pe=Da(),me=(e,t)=>pe.resolveEmbed(e,t),he=(e,n)=>{let r=pe.resolveEmbed(e,n);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=B(t,r);if(!FD(i,B(t)))return null;try{let e=Kl(i);return e.isFile()?e.size:null}catch{return null}},ge,N,_e,ve,ye,P,be,xe,Se,Ce,we=null,Te=null,F=null,Ee=null,De=null,Oe=null,ke=A(),Ae=new Xle({loadEmbedder:e.embedderLoader??(()=>{let t=A();return Ile({keyStore:e.embeddingsKeyStore??null,projectDir:n,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:R(ok(n),`embeddings`),enabled:ke.enabled,providerFingerprint:ce(ke)}),je=null,Me=new Set,Ne=!1,Pe=[],Fe,Ie,Le,Re=new Promise((e,t)=>{Ie=e,Le=t});function ze(e){we?.signal(e)}let Be=null,Ve=!1,He=()=>{try{H7(n,Ue.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Ue=new MEe(void 0,{onEviction:()=>Soe(),onSizeChange:e=>Coe(e),onMutate:()=>{!Ve||Be!==null||(Be=setTimeout(()=>{Be=null,He()},2e3))}});for(let[e,r]of FEe(n))cS(e)||gQ(e)&&([`.md`,`.mdx`].some(n=>{let r=B(t,`${e}${n}`);return FD(r,B(t))&&V(r)})||Ue.restore(e,r));Ve=!0;let We={current:null},Ge=(e,t)=>{cS(e)||Ue.setRenamed(e,t)},Ke=e=>{if(!cS(e)){if(Ue.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Ue.setDeleted(e),We.current?.deleted(e)}},qe=e=>{cS(e)||Ue.delete(e)};try{ge=hP({projectDir:n,contentDir:t,singleDocRelPath:_,inPlaceSkillDirs:$I(t),rescanInPlaceSkillDirs:()=>$I(t),onAfterRebuild:()=>{N.refreshContentScope().catch(e=>{I(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),wz(ut).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?I(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):I(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{I(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),N=new vR({projectDir:n,contentDir:t,contentFilter:ge,getGlobalSkillRoots:()=>LG(ye.managedArtifactCtx),signalChannel:ze}),_e={current:d},ve=o?bEe({getShadow:()=>_e.current??null,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,contentRoot:f??``,projectGitDir:Du(n)??void 0,isWriterLive:e=>{if(!Ee&&!xe)return I(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Ee?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of xe?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,ye=F7({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:_e,ephemeral:v,contentRoot:f,derivedDocumentIndex:N,configHomedirOverride:l,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,resolveEmbed:me,resolveSize:he,getPrincipal:()=>je,onAgentCommit:()=>we?.signal(`session-activity`),onFlushCommit:()=>ve?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{we?.emitDiskAck(e,t),!cS(e)&&oO(r,n)&&(De?.(),ze(`files`))},onConfigRejected:(e,t)=>we?.emitConfigValidationRejected(e,t),onConfigPersisted:le,isRecentlyRemoved:e=>Ue.has(e),mdManager:e.mdManager,getLossRing:()=>P,durabilityState:x}),be=new ITe({quiet:r,debounce:i,maxDebounce:a,extensions:[ye.extension]});let p=be;Pe.push(Mse(()=>p.documents.size),Nse(()=>ye.getQueueDepths()),Fse(()=>{let e=0;for(let t of p.documents.values())e+=t.directConnectionsCount;return{websocket:p.getConnectionsCount()-e,direct:e}})),JC(),v||(Oe=AEe({getLoadedDocuments:()=>p.documents,forceStore:(e,t)=>ye.forceStore(e,t),getBase:e=>x.getReconciledBase(e),isBatchActive:()=>x.isBatchInProgress(),peekInFlight:e=>x.peekInFlightFlush(e),readDiskBytes:e=>{let n=ID(e,t),r,i;try{r=U(n),i=Kl(r).size}catch(t){let n=Vs(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new L7(`symlink cycle at content path: ${e}`):t}if(!LD(r,t))throw new L7(`symlink-escape: ${n} resolves outside the content dir`);if(i>524288)throw new L7(`document exceeds the open byte limit: ${e}`);try{return H(r,`utf-8`)}catch(e){if(Vs(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let g=be.shouldUnloadDocument.bind(be);be.shouldUnloadDocument=e=>{if(Me.has(e)||Ne&&g(e))return!0;let t=e.name;return cS(t)||C(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:g(e)},Fe=async e=>{Me.add(e);try{await be.unloadDocument(e)}finally{Me.delete(e)}},we=new dS(be),F=new NE(be),Ee=new PE(be),xe=new Nw(be,e.agentSessionOptions);let b=xe;Pe.push(qC(()=>({active:b.liveSessionCount,limit:b.sessionLimit})));let w=f7({derivedDocumentIndex:N,onDocumentSettled:e=>We.current?.changed(e)});be.configuration.extensions.push(w),be.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=EQ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==ue)throw new TQ(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${ue}`);let i=n?.expectedBranch,a=S();if(typeof i==`string`&&i.length>0&&i!==a)throw new TQ(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(je&&n.principalId===je.id?o.principalId=je.id:je?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:je.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),be.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(t){if(!iS(t.documentName)&&!aS(t.documentName))return;let n=t.request,r=n.socket?.remoteAddress;if(r!==void 0&&!Wz(r))throw Error(`config-doc admission requires loopback peer (peer=${r}, doc=${t.documentName})`);let i=t.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0,o=e.remotePublicHost!==void 0&&Xz(a,e.remotePublicHost);if(!Gz(a)&&!o)throw Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${t.documentName})`)}});let T=B(t);function ee(e){if(!gQ(e))return null;let t=B(T,eS(e));return FD(t,T)?t:null}be.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await NEe(e.documentName,{recentlyRemovedDocs:Ue,resolveFilePath:ee,fileExists:V})}}),be.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=EQ(e.token);QTe(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>be.documents.get(e)})}}),be.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new E5(e.update);if(t.readVarString(),t.readVarUint()===L5.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${qr} rejected — server-only channel`)}});let te=_Q({hocuspocus:be,durabilityState:x,remotePublicHost:e.remotePublicHost,sessionManager:xe,commentDocHooksRef:We,contentDir:t,contentFilter:ge,serverInstanceId:ue,getFileIndex:()=>ut?ut.getFileIndex():new Map,getAttachmentFolderPath:ne,getAllFilesIndex:()=>ut?ut.getAllFilesIndex():new Map,getFileIndexGeneration:()=>ut?.getFileIndexGeneration()??0,mutateFileIndex:e=>ut?.mutateFileIndex(e),getFolderIndex:()=>ut?ut.getFolderIndex():new Map,getAliasMap:()=>ut?ut.getAliasMap():new Map,getFolderAliasIndex:()=>ut?ut.getFolderAliasIndex():new Map,rescanFiles:()=>ut?.rescanFromDisk(),enableTestRoutes:u,shadowRef:_e,flushGitCommit:()=>ye.flushPendingGitCommit(),flushContributors:()=>ye.flushContributors(),getCurrentBranch:()=>dt?.getLastKnownBranch()??null,getDiskAckSVs:()=>we?.getLatestDiskAckSVsAsBase64()??{},contentRoot:f,derivedDocumentIndex:N,signalChannel:ze,agentFocusBroadcaster:F,agentPresenceBroadcaster:Ee,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>ft,localOpCliArgs:m,authStreamHeartbeatMs:h,projectDir:n,resolveEmbed:me,getBridgeLossReporter:()=>Ce,getPrincipal:()=>je,acpRegistry:fe,loadAcpCustomAgents:()=>sd(de,I(`acp-registry`)),homeDirOverride:l,forceUnloadDocument:Fe,ready:Re,recentlyRemovedDocs:Ue,serializeDoc:$e,evictManagedArtifactLkg:e=>{ye.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Ae,getSemanticSimilarityFloor:()=>A().similarityFloor,getLinterBaseConfig:()=>k(),getLinksValidationSetting:()=>re(),getLinkPreviewsEnabled:ie,getConfigDiagnostics:j,embeddingsSecretsFile:VM(l),readSemanticProviderConfig:A,ephemeral:v,onReferencedAssetsCacheInvalidator:e=>{De=e}});be.configuration.extensions.push(te),Se=te.nativeApi;let E=Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for bridge guards`)}),D=E.value.bridge.deferGuard.enabled,O=E.value.bridge.fixedPoint.enabled,ae=E.value.bridge.preDrain.enabled;P=E.value.lossCapture.enabled?new dae({projectDir:n,maxBytes:E.value.lossCapture.maxBytes}):void 0,E.value.bridge.lossDetector.enabled&&(Ce=nse({shadow:()=>_e.current,ring:P,getBranch:()=>dt?.getLastKnownBranch()??`main`,contentRoot:f??``}),xe.attachBridgeLossReporter(Ce)),be.configuration.extensions.push(W7({mdManager:Ao,schema:ko,shadowRef:_e,contentRoot:f,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,resolveEmbed:me,resolveSize:he,deferGuardEnabled:D,lossDetectorEnabled:E.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:O,preDrainEnabled:ae,lossRing:P})),be.configuration.extensions.push(yDe()),be.configuration.extensions.push(ZTe({getSyncEngine:()=>ft,projectDir:n,contentDir:t}))}catch(e){for(let e of Pe.splice(0))e();throw Oe?.dispose(),Oe=null,Os(de),e}let Je=null,Ye=new Map,Xe=[];function Ze(e,t){let n=B(e,`rescue`),r=B(n,eS(t));return FD(r,n)?r:null}function $e(e){let t=be.documents.get(e);return t?jR(t):null}let et=(e,t)=>OR(x,be,e,t,me,he,Ce);function tt(e){if(!bS(e)||ft?.getConflicts().some(r=>s7(r,e.name,n,t)))return;let r=e.getMap(`lifecycle`);r.delete(`status`),r.delete(`reason`)}let nt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of be.documents){if(cS(n))continue;let r=be.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{bR(r,i,me,n)},yR)}catch(t){y.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},rt=null,it=e=>{e&&(rt===null&&(rt=new Set,setImmediate(()=>{let e=rt;if(rt=null,e)try{for(let t of e)nt(t)}catch(t){y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),rt.add(e))};function at(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return LR(e)}}async function ot(e){try{switch(e.kind){case`create`:y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await N.recordDiskUpsert(e.docName,e.content),ze(`files`),qe(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=be.documents.get(t);if(!r){await N.recordDiskUpsert(t,n);return}let i=C(t)??``,a=$e(t)??i,o=wR({docName:t,base:i,ours:a,theirs:n}),s=WR(i).slice(0,6),c=WR(a).slice(0,6),l=WR(n).slice(0,6);switch(y.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:tt(r),await N.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{et(t,o.newContent),w(t,o.newContent),Zb(),tt(r),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),w(t,n),tt(r)}e&&await N.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{et(t,o.newContent),w(t,n),Zb(),tt(r),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),w(t,n),tt(r)}e&&await N.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{et(t,o.newContent),w(t,o.newContent),Zb(),Qb(),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),w(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}e&&await N.recordDiskUpsert(t,n);break}case`refused`:{Qb();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=be.documents.get(t);if(!n){await N.recordDiskDelete(t),ze(`files`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=C(t)??``,i=$e(t)??``,a=i!==r;if(a&&_e.current){let e=_e.current,n=dt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{Rx(e,f??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{ex(),y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),T(t),await N.recordDiskDelete(t),y.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),be.closeConnections(t),await Fe(n),ze(`files`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=be.documents.get(t);if(T(t),w(n,r),await N.recordDiskRename(t,n,r),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}y.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),ze(`files`),Ge(t,n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,n=be.documents.get(t);if(!n)return;let r=$e(t);r===null?y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):w(t,r);let i=n.getMap(`lifecycle`);i.set(`status`,`conflict`),i.set(`reason`,`conflict-markers`),y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:pe.add(e.relativePath),ze(`files`),it(wl(e.relativePath));break;case`asset-delete`:pe.remove(e.relativePath),ze(`files`),it(wl(e.relativePath));break;case`folder-create`:case`folder-delete`:ze(`files`);break;case`file-create`:case`file-update`:case`file-delete`:ze(`files`);break;default:LR(e)}}catch(t){let n=at(e);y.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let st=[];async function ct(e){if(E()){st.push(e);return}await ot(e)}async function lt(){let e=st.splice(0,st.length);for(let t of e)await ot(t)}let ut=null,dt=null,ft=null,pt=null;async function mt(e){if(be.documents.size===0)return;let t=!1,n=new Promise(e=>{be.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(be.documents.keys());be.closeConnections(),be.flushPendingStores();for(let e of be.documents.values())e.getConnectionsCount()===0&&be.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(be.documents.keys()),i=[],o=[];if(_e.current){for(let e of n)if(!cS(e))try{let t=$e(e);if(t===null){y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=Ze(_e.current.gitDir,e);if(!n){y.warn({docName:e,gitDir:_e.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}Rl(L(n),{recursive:!0}),Jl(n,t,`utf-8`),ex(),i.push(e),y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else y.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function ht(){return pt||(pt=(async()=>{let e=Date.now(),t=[];Ne=!0;for(let e of Pe.splice(0))e();try{await Oe?.dispose()}catch(e){y.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Oe=null;try{zs(de)}catch(e){y.warn({err:e},`[server] failed to mark server.lock draining`)}if(Be!==null&&(clearTimeout(Be),Be=null),Ve)try{H7(n,Ue.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let r,i=await Promise.race([Re.then(()=>`completed`,e=>(y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&y.warn({},`[server] init did not complete within 5s during shutdown`);let a=be.documents.size;ve?.destroy();try{try{try{Te&&=(clearTimeout(Te),null),dt&&=(await dt.unsubscribe(),null),ut&&=(await ut.unsubscribe(),null);for(let{docName:e,cleanup:t}of Xe)try{await t()}catch(t){y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Xe.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{we?.destroy(),Ee?.destroy(),Je&&=(await Je.disconnect(),null);for(let[e,t]of Ye)try{await t.disconnect()}catch(t){y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Ye.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await xe.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await gse()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await mt(p)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-3 flush failed`)}N.close();let e;try{await Promise.race([(async()=>{await ye.flushPendingGitCommit(),await ye.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),p)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{ft&&=(await ft.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(_e.current){let e;try{await Promise.race([vx(_e.current).drain(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`shadow mutator drain timeout`)),p)})])}catch(e){t.push({phase:`shadow-mutator-drain`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-5 shadow mutator drain failed`)}finally{e!==void 0&&clearTimeout(e)}try{let e=(await xs({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&Jl(B(_e.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{Loe(_e.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?y.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):y.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{Os(de,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await ss()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),pt)}let gt=[];async function _t(){try{je=await R7(n),y.info({principalId:je.id},`[server] principal loaded`)}catch(e){y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!_e.current)try{_e.current=await wx(n),y.info({gitDir:_e.current.gitDir},`[server] history repo initialized at ${_e.current.gitDir}`)}catch(e){y.error({err:e},`[server] history repo init failed`),gt.push(`shadow-repo`)}if(_e.current){let e=null;try{e=kK(_e.current.gitDir),QK(_e.current.gitDir,e),PK(_e.current.gitDir,e),y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([$K(_e.current,e,{rebuild:!0}),new Promise((e,n)=>setTimeout(()=>n(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await ve?.runBootMaintenance()}catch(e){y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(_e.current)try{await Sx(_e.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){y.warn({},`[server] history repo appears corrupted — reinitializing`);try{_e.current=await wx(n)}catch(e){y.error({err:e},`[server] history repo reinit failed`),_e.current=void 0,gt.includes(`shadow-repo`)||gt.push(`shadow-repo`)}}else y.error({err:e},`[server] history repo check failed (transient?)`)}if(_e.current)try{let e=B(_e.current.gitDir,`last-known-head`),t=null;try{t=H(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await xs({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await xs({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}y.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await Fx(_e.current,f??``,t,r,e),$b()}catch(e){y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else y.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{Jl(e,r,`utf-8`)}catch(e){y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){y.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=hK(t,n);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;y.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){y.error({err:e},`[server] managed rename recovery failed`),gt.push(`managed-rename-recovery`)}try{let e=hL(n);(e.deleted>0||e.errors>0)&&y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){y.error({err:e},`[server] upload-tempfile sweep failed`),gt.push(`upload-tempfile-sweep`)}try{Je=await be.openDirectConnection(qr),we?.emitServerInfo(ue,S())}catch(e){y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),gt.push(`cc1-push`)}let r=v?[]:oa;for(let e of r)try{let t=await be.openDirectConnection(e);Ye.set(e,t)}catch(t){y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),gt.push(`config-doc:${e}`)}let i=new Map([[Ci,Lo(`project`,n)],[Ar,Lo(`project-local`,n)],[ma,Lo(`user`,n,l)]]);for(let e of r){let t=i.get(e);if(t)try{y.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await X5(t,t=>{let n=be.documents.get(e);y.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=o7(n??null,e,t,ye.configPersistenceCtx);y.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),le(e)});Xe.push({docName:e,cleanup:n}),y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){y.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),gt.push(`config-file-watcher:${e}`)}}if(!v){let e=(e,t)=>{let n=WG(e,ye.managedArtifactCtx);if(!n)return;let r=YG(be.documents.get(n)??null,n,t,ye.managedArtifactCtx);y.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),ze(`files`),ci(n)&&N.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})},t=e=>{let t=WG(e,ye.managedArtifactCtx);ze(`files`),t&&ci(t)&&N.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:t},`[backlinks] global skill bundle prune failed`)})};try{let n=LG(ye.managedArtifactCtx),r=await w7(n,e,void 0,t);Xe.push({docName:`__skill-files__`,cleanup:r}),y.info({roots:n},`[managed-artifact-watcher] skills started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),gt.push(`managed-artifact-watcher:skills`)}try{let e=B(PG(ye.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await X5(e,()=>{ze(`files`)});Xe.push({docName:`__skill-state__`,cleanup:t}),y.info({path:e},`[skill-state-watcher] started`)}catch(e){y.warn({err:e},`[skill-state-watcher] failed to start`),gt.push(`skill-state-watcher`)}try{let t=new Set([``]);try{for(let e of(await CA(n)).templates)t.add(e.source_folder)}catch(e){y.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let r=[...t].map(e=>e?B(n,e,`.ok`,`templates`):B(n,`.ok`,`templates`)),i=await w7(r,e,SEe);Xe.push({docName:`__template-files__`,cleanup:i}),y.info({rootCount:r.length},`[managed-artifact-watcher] templates started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),gt.push(`managed-artifact-watcher:templates`)}}try{let e=B(t,`.okignore`),r=B(n,`.gitignore`),i=null;try{let e=Sl(`git`,[`rev-parse`,`--git-common-dir`],xN({cwd:n,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=R(B(n,e.stdout.trim()),`info`,`exclude`);V(L(t))&&(i=t)}}catch{}let a=i?[e,r,i]:[e,r],o=y;o.info({okignorePath:e,gitignorePath:r,gitInfoExcludePath:i,ephemeral:v},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=v?null:await HTe(a,(t,r)=>{(async()=>{if(t===e)try{let e=o7(be.documents.get(`__config__/okignore`)??null,ja,r,ye.configPersistenceCtx);o.info({docName:ja,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:z(n,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await ge.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:z(n,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),we?.signal(`files`);else{let e=z(n,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),we?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:z(n,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Xe.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:r},`[ignore-watcher] multi-path watcher started`))}catch(e){y.warn({err:e,projectDir:n,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),gt.push(`ignore-files-watcher`)}let a=d7(n).branch??`main`;ee(a);let o=N.beginStartup(a),s=!1,c=performance.now();try{await zo(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:r}=await o.backlinksReady;r&>.push(`backlink-index`);let i=0;for(let t of e)cS(t)||Ue.peek(t)?.kind!==`renamed`&&(Ue.setDeleted(t),i++);i>0&&y.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`);let a=performance.now(),c=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,u=ge?$I(t):new Set,d=e=>{e.some(e=>c.test(z(t,e).split(Al).join(`/`)))&&(Te&&clearTimeout(Te),Te=setTimeout(()=>{Te=null;try{QX(n,t).then(e=>{e>0&&(y.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),we?.signal(`files`))}).catch(e=>y.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=$I(t);if(!(e.size!==u.size||[...e].some(e=>!u.has(e))))return;u=e,ge.rebuildIgnorePatterns().then(t=>{t.ok?(y.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),we?.signal(`files`)):y.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>y.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){y.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};ut=await zo(`ok.boot.seed-walk`,void 0,async()=>Cz(t,ct,ge,{onRawBatch:d})),QX(n,t).then(e=>{e>0&&y.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>y.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=l??Xl();QX(e,e,ZI(e)).then(e=>{e>0&&y.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>y.warn({err:e},`[in-place-skills] global copy re-sync failed`))}tR(`seedWalkMs`,Math.round(performance.now()-a));{let e=B(t),n=0;for(let[t]of Ue.entries()){if(!gQ(t))continue;let r=B(e,`${t}${Qx(t)}`);FD(r,e)&&V(r)&&(Ue.delete(t),n++)}n>0&&y.info({count:n},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let f=await N.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&>.push(`tag-index`);let p=0;try{_===void 0?await bQ({contentDir:t,contentFilter:ge,basenameIndex:pe,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):Tpe({contentDir:t,basenameIndex:pe,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),p>0&&(y.warn({count:p},`[basename-index] startup seed completed with ${p} skipped entries — embeds under inaccessible subtrees will not resolve`),gt.push(`basename-index-partial`))}catch(e){y.error({err:e},`[basename-index] startup seed failed`),gt.push(`basename-index`)}})}catch(e){if(y.error({err:e},`[server] disk bridge watcher failed to start`),gt.push(`file-watcher`),!s){let e=await N.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&>.push(`tag-index`)}}finally{tR(`indexesMs`,Math.round(performance.now()-c)),ut&&nR(`fileCount`,ut.getFileIndex().size)}try{dt=await rEe(n,async({trigger:e})=>{if(y.info({trigger:e},`[batch] begin trigger=${e}`),yae(),be.flushPendingStores(),await ye.flushPendingGitCommit(),te(!0),_e.current){let e=S(),t=d7(n).branch??e,r=[];for(let[e,t]of be.documents){if(cS(e))continue;let n=null;if(t.transact(()=>{n=$e(e)},bDe),n===null)continue;let i=C(e)??n;r.push({docName:e,markdown:n,diskSnapshot:i})}if(r.length>0)try{let n=await qoe(_e.current,e,Nx.id,r,t);n&&(Sae(),y.info({count:r.length,branch:e,sha:n.slice(0,8)},`[history] parked ${r.length} docs on ${e} → ${n.slice(0,8)}`))}catch(e){y.error({err:e},`[shadow] park failed`)}}},async e=>{let r=st.length,i=e.newBranch??`main`;if(y.info({kind:e.batchKind,headMoved:e.headMoved,docs:r,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${r}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(te(!1),await lt(),e.headMoved&&e.newHead){let r=SDe(n,B(t),e.oldHead,e.newHead);if(r.size>0){Jj(r.keys());for(let[e,t]of r)qj(e,tne(t.email),t.name,t.email,Hu(e));await ye.flushContributors()}}if(await ye.flushDeferredStores(`within-branch`),ft!==null)try{await ft.reconcileConflictsFromGit()}catch(e){y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{xae(),st.splice(0,st.length);let n=!1,r;try{ee(i),r=await N.beginBranchSwitch(i),ge.rebuildDirCount();try{let e=0;pe.clear(),await bQ({contentDir:t,contentFilter:ge,basenameIndex:pe,onSkip:(t,n,r)=>{e++,y.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(y.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),gt.includes(`basename-index-partial`)||gt.push(`basename-index-partial`))}catch(e){y.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,n]of be.documents)if(!cS(e))try{let r=ID(e,t);if(!V(r)){let t=C(e)??``,r=$e(e)??``;if(r!==t&&_e.current){let t=_e.current;queueMicrotask(()=>{Rx(t,f??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{ex(),y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),y.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=H(r,`utf-8`);et(e,a),w(e,a),y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}y.info({branch:i,docCount:be.documents.size},`[branch-switch] loaded branch ${i} (${be.documents.size} docs)`);try{await N.settleBranchFromDisk(r)}catch(e){N.abortBranchSwitch(r),y.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(_e.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of be.documents)if(!cS(t))try{let n=await Yoe(_e.current,i,Nx.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=C(t);if(!r)continue;let a=wR({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:et(t,a.newContent),w(t,a.newContent),e++;break;case`conflicts`:et(t,a.newContent),w(t,a.newContent),Qb(),e++;{let e=be.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&y.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&_e.current)try{let t=Sx(_e.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await vx(_e.current).withMutator(async()=>{for(let e of n.split(`
|
|
2030
2030
|
`))e&&await t.raw(`update-ref`,`-d`,e)}),y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){y.error({err:e},`[branch-switch] detached cleanup failed`)}te(!1),await ye.flushDeferredStores(`discard-stale`),n=!0,we?.emitBranchSwitched(i)}finally{N.abortBranchSwitch(r),n||(te(!1),await ye.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&_e.current&&r>0){let t=f??`.`;try{let n=await Fx(_e.current,t,e.oldHead,e.newHead,i);$b(),y.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){y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){y.error({err:e},`[server] HEAD watcher failed to start`),gt.push(`head-watcher`)}function u(e){for(let r of e)try{let e=PD(z(t,R(n,r)));if(e.startsWith(`..`))continue;let i=qx(e),a=be.documents.get(i);if(!a)continue;let o=$e(i);o===null?y.warn({docName:i,file:r},`[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`),y.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){y.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let r of e)try{let e=PD(z(t,R(n,r)));if(e.startsWith(`..`))continue;let i=be.documents.get(qx(e));i&&tt(i)}catch(e){y.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let p=xDe(m),h=O();h.mode!==`off`&&y.info({mode:h.mode,source:h.source},`[sync] mode active at boot`);try{ft=new _De({projectDir:n,contentDir:t,contentFilter:ge,contentRoot:f,mode:h.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:p,cc1Broadcaster:we,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{te(e),e||ye.flushDeferredStores(`within-branch`).catch(e=>{y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:u,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=_e.current;n&&await Lx(n,f??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=_e.current;n&&await Lx(n,f??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await Xo({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:ae(t.error),configPath:Lo(`project-local`,n)},`[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 ft.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ft=null}ze(`files`),N.announceReadyViews();let g=eR();g!==void 0&&tR(`readyMs`,g),oe()}return _t().then(Ie,e=>{N.close(),Le(e)}),{hocuspocus:be,durabilityState:x,sessionManager:xe,nativeApi:Se,cc1Broadcaster:we,agentFocusBroadcaster:F,agentPresenceBroadcaster:Ee,maintenanceCoordinator:ve,contentFilter:ge,basenameIndex:pe,serverInstanceId:ue,destroy:ht,ready:Re,degraded:gt,lockDir:de,get syncEngine(){return ft},getLinkPreviewsEnabled:ie,resolveEmbed:me,acpRegistry:fe,acpPermissions:M}}function m9(e){return e/1048576}function CDe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:m9(e.rss),heapTotalMb:m9(e.heapTotal),heapUsedMb:m9(e.heapUsed),externalMb:m9(e.external),arrayBuffersMb:m9(e.arrayBuffers)}}}let h9=null,g9=null,_9=null;const v9=1e6;let y9=null,b9=null;Ro(()=>{h9=null,g9=null,_9=null,y9?.disable(),y9=null,b9=null});function wDe(){if(h9)return;let e=ls().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}=CDe();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`})}),h9=e}function TDe(){if(!g9){let e=ls().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(!y9){y9=Fte({resolution:20}),y9.enable();return}e.observe(y9.percentile(50)/v9,{stat:`p50`}),e.observe(y9.percentile(99)/v9,{stat:`p99`}),y9.reset()}),g9=e}if(!_9){let e=ls().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=b9;if(b9={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`}))}),_9=e}}const x9=I(`skill-migrate`);function S9(e){return[{host:`agents`,root:`.agents/skills`},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=sD.indexOf(e.host),r=sD.indexOf(t.host);return(n===-1?sD.length:n)-(r===-1?sD.length:r)||e.host.localeCompare(t.host)})}const EDe=S9(Xt),DDe=S9(wa);function ODe(e,t){Zo(L(t),{recursive:!0});try{Wo(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;es(e,t,{recursive:!0}),ts(e,{recursive:!0,force:!0})}}function kDe(e,t,n){let r=mI(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 C9(e,t){let n;try{n=U(B(e,`.ok`,`skills`))}catch{n=B(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!U(B(e,t.dir)).startsWith(n+Al)}catch{return!0}}).map(e=>e.name))}async function w9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??EDe,a={migrated:[],skipped:[]};if(!V(n))return a;let o;try{o=Vl(n)}catch{return a}let s=z(t,n).split(Al).join(`/`),c=new Set;for(let[e,n]of Object.entries(YX(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Le.test(e)||FF.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=B(n,e);if(!V(R(o,`SKILL.md`)))continue;let s=tD(o)?.contentHash;if(s===void 0)continue;let l=U(o),u=i.map(({host:n,root:r})=>{let i=B(t,r);return{host:n,root:r,path:R(i,e),escapes:SI(t,i),state:kDe(R(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=>e.state.kind===`absent`&&V(B(t,e.root)))??u.find(e=>e.host===`claude`);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`?ts(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&ts(d.path,{recursive:!0,force:!0}),ODe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(ts(e.path,{recursive:!0,force:!0}),es(d.path,e.path,{recursive:!0}));await XN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),x9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),x9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const T9=I(`skill-reconcile`),ADe=FF;function E9(){let e=[];for(let t of gr){let n=Xt[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function jDe(e,t){let n=z(e,B(t));return Dl(n)?B(t):n}function D9(e){let{frontmatter:t,body:n}=Qa(e),r={};if(t!==``)try{let e=(0,kD.parse)(go(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function MDe(e,t){let n=D9(e),r=D9(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 O9(e,t){let n=k9(e),r=k9(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=R(e,o),c=R(t,o);if(i+=Kl(s).size+Kl(c).size,i>1048576)return!1;let l=H(s),u=H(c);if(!l.equals(u)&&(o!==`SKILL.md`||!MDe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function k9(e,t=``){let n=[];for(let r of Vl(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...k9(R(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function A9(e,t,n){ts(t,{recursive:!0,force:!0}),Zo(e,{recursive:!0}),qo(jDe(e,n),t,`dir`)}function j9(e,t){try{let n=Hl(e);return B(Dl(n)?n:B(L(e),n))===B(t)}catch{return!1}}function NDe(e,t){try{let n=Hl(e),r=Dl(n)?B(n):B(L(e),n);if(!V(r))return!1;let i=z(B(t),r);return i!==``&&(i.startsWith(`..`)||Dl(i))}catch(t){return T9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const PDe=[...gr,`agents`];function FDe(e){for(let t of PDe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function IDe(e){let{projectDir:t,skillsRoot:n}=e;if(!V(n))return;let r;try{r=Vl(n)}catch{return}let i=E9();for(let e of r){let r=FDe(e);if(r===null)continue;let a=B(n,e),o=B(n,r);if(V(o))try{let n=Ll(a);if(n.isSymbolicLink()||!n.isDirectory()||!V(R(a,`SKILL.md`))||!V(R(o,`SKILL.md`))||!O9(o,a))continue;for(let{rel:n}of i){let r=B(t,n);if(SI(t,r))continue;let i=R(r,e);j9(i,a)&&A9(r,i,o)}ts(a,{recursive:!0,force:!0}),T9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){T9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function LDe(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 E9()){let o=B(t,e);if(!V(o)||SI(t,o))continue;let s;try{s=Vl(o)}catch(e){T9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(ADe.has(e))continue;let t=R(o,e),s=B(n,e),c=V(s);try{let l=Ll(t);if(l.isSymbolicLink()){if(j9(t,s)&&c)continue;if(NDe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(A9(o,t,s),r.healed.push({name:e,editor:i})):(ts(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Le.test(e)){T9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&O9(t,s)){A9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){T9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=qN(t);for(let[r,a]of i){let i=B(n,r);if(!V(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await YN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??_I(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){T9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{IDe({projectDir:t,skillsRoot:n})}catch(e){T9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let M9=null,N9=!1;function P9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function F9(e){if(!P9())return;let t=ok(e);M9=new vs({currentPath:B(t,`tolerance-telemetry.jsonl`),previousPath:B(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ha(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};M9?.append(`${JSON.stringify(t)}\n`).catch(e=>{N9||(N9=!0,I(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function I9(){ha(null),await M9?.drain(),M9=null,N9=!1}Do();const RDe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],zDe=[`cache`,`tmp`];function BDe(e){let t=B(e,_e);if(!(()=>{if(!V(t))return!0;try{return Vl(t).length===0}catch{return!0}})())return[];let n=[];for(let t of RDe)V(B(e,t))&&n.push(t);for(let t of zDe){let r=B(e,t);try{V(r)&&Kl(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function VDe(e){let t=Eu(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 L9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function HDe(e){$L();let t=e.projectDir??e.contentDir,n=Mpe({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}`)}ms.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}cs({localSink:n?.telemetry}),F9(t),wDe(),TDe();let{kind:r,gitdir:i}=VDe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=$o(i));let o=Ape(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>zo(`ok.boot`,{attributes:a},async()=>UDe(e)),l=()=>{if(s)try{let e=To.extract(Oo.active(),{traceparent:s});return Oo.with(e,c)}catch(e){I(`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()=>{try{await d()}finally{o.uninstall()}},u}async function UDe(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??I(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?qz(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new Kz("remote access was requested but remote.url is not set — pass a url (`ok start --remote <url>`) or set remote.url in .ok/config.yml.");let a=i===null?e.idleShutdownMs:null,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:l}=await import(`node:http`),{markServerLockDraining:u,releaseServerLock:d,updateServerLockPort:f}=await import(`./server-lock-uucDARDL.mjs`),p=!1;if(!t&&e.autoInitFn)try{p=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let m=e.projectDir??e.contentDir,h=B(m,`.ok`);if(!V(B(h,`config.yml`)))throw new Y8(V(h)?`config`:`okdir`,m);let g=B(h,`.gitignore`);V(g)||I(`boot`).warn({path:g},"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 _=e.gitPreflight??QW;try{e.gitEnabled!==!1&&_()}catch(e){if(e instanceof YW||e instanceof XW){let t=e instanceof XW?e.detected:``,n=e instanceof XW?`too_old`:`not_available`;_G(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:n,detectedVersion:t},n===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await ss(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let v=BDe(h);v.length>0&&I(`boot`).warn({files:v},`Found legacy runtime files at .ok/${v.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${_e}/.`);let y=p9({contentDir:e.contentDir,projectDir:e.projectDir,remotePublicHost:i?.publicHost,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:b,destroy:S,ready:C,degraded:w,lockDir:T,sessionManager:te,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:ne}=y,O=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),k=e.port??0,re=e.ephemeral?void 0:H8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${O}:${k}`,log:r}),A=l();A.headersTimeout=3e4,A.requestTimeout=6e4;let ie=e.serveContentAssets===!1?void 0:vQ({contentFilter:y.contentFilter,contentSirv:Gs(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:ee,assetExtensions:c,blocklistExtensions:x}),ae=!1;if(e.reactShellDistDir)try{nL(T,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ae=!0}catch(e){if(e instanceof tL)r.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:T},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await S().catch(()=>{}),d(T),e}let j=e.reactShellDistDir?Gs(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,oe=e.ephemeral?null:new bE({contentDir:e.contentDir,localDir:T,globalDir:B(Xl(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:te,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:()=>`http://${O}:${k}`,getMcpStdioCommand:()=>yE(e.localOpCliArgs,k),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});oe!==null&&await oe.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let se=`pending`;C.then(()=>{se=`ready`},()=>{se=`failed`});let ce=q8({httpServer:A,hocuspocus:b,nativeApi:y.nativeApi,mcpHttpHandler:re,remoteAccess:i,health:{readiness:()=>se,degraded:()=>w},log:r,sessionManager:te,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:ne,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ie,reactShellMiddleware:j,ephemeral:e.ephemeral,acpThreadManager:oe}),le=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ue=null;a!==null&&(ue=MQ({httpServer:A,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await le()})})),await R9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);A.once(`error`,r),A.listen(e.port,e.host,()=>{A.removeListener(`error`,r),t()})})}catch(e){if(ae)try{aL(T)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await S().catch(()=>{}),d(T),e}let de=eR();de!==void 0&&tR(`httpListenMs`,de);let fe=A.address(),M=typeof fe==`object`&&fe?fe.port:e.port??0;if(k=M,f(T,M),ae&&rL(T,M),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:T,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let pe=!1,me=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${L9}ms`))},L9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};le=async()=>{if(pe)return;pe=!0,se=`draining`;let e=[],t=async(t,n)=>{try{await me(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{u(T),ae&&Ufe(T)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{ue?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(oe!==null&&await t(`acpThreads.destroy`,()=>oe.destroy()),await t(`mount.shutdown`,()=>ce.shutdown()),re!==void 0&&await t(`mcpHttpHandler.close`,()=>re.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ce.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{A.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{A.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>S()),ae&&await t(`releaseUiLock`,async()=>aL(T,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>ss()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>ms.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await w9({projectDir:m,skillsRoot:B(e.contentDir,`.ok`,`skills`),inPlaceNames:C9(e.contentDir,XI(e.contentDir))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=Xl(),t=await w9({projectDir:e,skillsRoot:B(e,`.ok`,`skills`),hostRoots:DDe,inPlaceNames:C9(e,ZI(e))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await LDe({projectDir:m,skillsRoot:B(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.replaced.length+t.orphansRemoved.length;n>0&&r.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){r.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:A,destroy:le,lockDir:T,contentDir:e.contentDir,port:M,ready:C,degraded:w,didAutoInit:p,serverInstance:y,runtime:zwe(y,{contentDir:e.contentDir,projectDir:m}),acpThreadManager:oe}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new kQ(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=Du(n),t=e?R(e,`MERGE_HEAD`):null;if(!t||!V(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=Cs({baseDir:n,timeout:{block:5e3}});s=new Set(await Xb(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=qx(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 WDe=ke;function GDe(e={}){let t=e.home??Xl(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?V(R(t,`Library`,`Application Support`,`Claude`)):n===`win32`?V(R(r.APPDATA??R(t,`AppData`,`Roaming`),`Claude`)):!1}var z9=t(_s(),1);const B9=R(Xl(),`.ok`,`logs`),KDe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function qDe(){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 JDe(e){Rl(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function YDe(e){try{if(Kl(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{Ul(n,r)}catch{}}try{ql(`${e}.3`)}catch{}}function XDe(e){try{let t=Date.now(),n=10080*60*1e3,r=Vl(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=Kl(R(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{ql(R(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{ql(R(e,t.name)),a-=t.size}catch{}}}catch{}}function ZDe(e){JDe(B9);let t=V9(),n=e.filePath??R(B9,`${e.name}.${t}.log`);YDe(n),(e._setTimeout??setTimeout)(()=>XDe(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:qDe(),name:e.name,redact:{paths:KDe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:z9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function QDe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[z9.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 $De(e){return R(B9,`${e}.${V9()}.log`)}function eOe(){return B9}function tOe(e){let t=B(e),n=0;for(;n<30;){let e=!1;try{e=V(B(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=L(t);if(r===t)return null;t=r,n+=1}return null}const H9=gu(bl),U9=I(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function nOe(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],xN({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function rOe(e){let t=B(e),n=B(t,`.git`),r=B(n,`HEAD`),i=!1;if(V(n)){if(!Kl(n).isDirectory()||V(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=QW()}catch(e){throw e instanceof YW||e instanceof XW?(_G(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof XW?`too_old`:`not_available`,detectedVersion:e instanceof XW?e.detected:``},e instanceof XW?`git binary too old`:`git binary not found`)):U9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let o=a.resolvedPath;if(!i&&await nOe(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],xN({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new W9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!V(r))throw new W9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,s);return i?(U9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(U9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=I(`project-skill-git`),K9=/^[0-9a-f]{40}$/,iOe=mr.map(e=>e.replace(/\/$/,``));async function aOe(e){let t=Du(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(lOe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=ws(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await Ss(async()=>{let t=await oOe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await sOe(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await q9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=ws(e,{gitIndexFile:R($l(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`)});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 cOe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await Hz(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Es(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 \`${vr}\` 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(!K9.test(f))return G9.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 G9.info({branch:t,err:J9(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){G9.info({err:J9(e)},`real-index reset after untrack failed (cosmetic)`)}return G9.info({dirs:i,commitSha:f},`untracked project-skill projection`),{kind:`untracked`,dirs:i,commitSha:f}})}catch(e){return{kind:`failed`,error:J9(e)}}}async function q9(e){let t=[];for(let n of iOe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function oOe(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 sOe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function cOe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function lOe(e){return V(R(e,`MERGE_HEAD`))||V(R(e,`rebase-merge`))||V(R(e,`rebase-apply`))||V(R(e,`CHERRY_PICK_HEAD`))||V(R(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function uOe(e,t){let n;try{n=yl(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=L(n),r=0;r<32;r+=1){let n=R(t,`package.json`);if(V(n))try{let t=JSON.parse(await ru(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=L(t);if(r===t)return;t=r}}const dOe=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function Y9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of dOe)t=t.replace(e,n);return t}function X9(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:Y9(e.message)??``,stack:Y9(e.stack),code:e.code,cause:e.cause===void 0?void 0:X9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:Y9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:Y9(String(r.message??``))??``,stack:Y9(r.stack),code:r.code,cause:r.cause===void 0?void 0:X9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var Z9=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},Q9=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},$9=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function fOe(e){if(!Gx(e))throw new $9(e);let t;try{t=U(B(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!Kl(t).isFile())throw new Q9(e);let n=L(t),r=Ez(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:qx(z(pOe(e),t).split(Al).join(`/`)),canonicalFilePath:t}}let i=wl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:qx(i)}}function pOe(e){return B(e,Fo({absPath:Lo(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function mOe(e){let t=zl(B($l(),`ok-ephemeral-`)),n=B(t,`.ok`);return Rl(n,{recursive:!0}),Jl(B(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),Jl(B(n,`.gitignore`),`local/
|
|
2031
2031
|
`,`utf-8`),t}export{Y2 as $,Vx as $i,rL as $n,BM as $r,YW as $t,X7 as A,Vse as Ai,UR as An,WP as Ar,hQ as At,d7 as B,iS as Bi,kR as Bn,AN as Br,kq as Bt,p9 as C,xu as Ca,fE as Ci,Gz as Cn,SF as Cr,bQ as Ct,Z7 as D,Sw as Di,LR as Dn,$P as Dr,upe as Dt,J7 as E,Iw as Ei,Tz as En,QP as Er,RZ as Et,gEe as F,bw as Fi,cz as Fn,HP as Fr,wq as Ft,K8 as G,Bx as Gi,yR as Gn,DN as Gr,Pq as Gt,J8 as H,aS as Hi,SR as Hn,NN as Hr,Bq as Ht,b7 as I,yS as Ii,Cz as In,VP as Ir,Rq as It,z8 as J,Nx as Ji,HL as Jn,xN as Jr,xq as Jt,W8 as K,jx as Ki,fR as Kn,SN as Kr,Aq as Kt,y7 as L,K as Li,sz as Ln,sde as Lr,Iq as Lt,R7 as M,Ow as Mi,oz as Mn,GP as Mr,Zq as Mt,F7 as N,ZC as Ni,tz as Nn,UP as Nr,Jq as Nt,K7 as O,jw as Oi,lz as On,XP as Or,dpe as Ot,v7 as P,QC as Pi,HR as Pn,cde as Pr,Uq as Pt,W2 as Q,Ax as Qi,aL as Qn,UM as Qr,_G as Qt,iEe as R,vS as Ri,BR as Rn,hP as Rr,zq as Rt,I9 as S,Ou as Sa,bE as Si,qz as Sn,efe as Sr,EQ as St,G7 as T,Pw as Ti,Ez as Tn,ZP as Tr,zZ as Tt,Y8 as U,cS as Ui,wR as Un,jN as Ur,Mq as Ut,c7 as V,lS as Vi,xR as Vn,kN as Vr,Lq as Vt,q8 as W,rS as Wi,CR as Wn,MN as Wr,jq as Wt,H2 as X,Fx as Xi,nL as Xn,oN as Xr,yG as Xt,k8 as Y,Ox as Yi,tL as Yn,sN as Yr,xG as Yt,U2 as Z,Ex as Zi,iL as Zn,WM as Zr,gG as Zt,WDe as _,sd as _a,ID as _i,DU as _n,WF as _r,TQ as _t,fOe as a,Sx as aa,DM as ai,iG as an,iI as ar,i_e as at,F9 as b,Au as ba,NE as bi,eB as bn,PF as br,CQ as bt,aOe as c,dx as ca,tM as ci,UW as cn,nI as cr,K0 as ct,tOe as d,Zre as da,qj as di,wU as dn,rI as dr,Sme as dt,wx as ea,Ule as ei,XW as en,pI as er,g_e as et,ZDe as f,Qm as fa,Xj as fi,TU as fn,JF as fr,h1 as ft,GDe as g,$u as ga,sk as gi,vU as gn,HF as gr,SQ as gt,eOe as h,od as ha,ak as hi,EU as hn,GF as hr,DQ as ht,mOe as i,Hx as ia,EM as ii,ZW as in,sI as ir,r_e as it,W7 as j,Hse as ji,uz as jn,KP as jr,HZ as jt,Y7 as k,Nw as ki,WR as kn,pde as kr,_Q as kt,W9 as l,ix as la,Qj as li,BW as ln,tI as lr,S1 as lt,$De as m,$m as ma,ok as mi,kU as mn,qF as mr,MQ as mt,Z9 as n,Lx as na,Hle as ni,QW as nn,vfe as nr,F2 as nt,X9 as o,hx as oa,IM as oi,eG as on,aI as or,a_e as ot,QDe as p,eh as pa,Yj as pi,bU as pn,KF as pr,v1 as pt,H8 as q,Mx as qi,XL as qn,TN as qr,bq as qt,$9 as r,Rx as ra,Vle as ri,hG as rn,lI as rr,A2 as rt,uOe as s,px as sa,eM as si,WW as sn,oI as sr,w2 as st,Q9 as t,zx as ta,Ble as ti,qW as tn,fI as tr,I2 as tt,rOe as u,Aoe as ua,Zj as ui,gU as un,ofe as ur,e1 as ut,HDe as v,Qu as va,ED as vi,tB as vn,LF as vr,xQ as vt,f9 as w,bu as wa,yE as wi,Wz as wn,dF as wr,vQ as wt,P9 as x,Yu as xa,ME as xi,Qz as xn,zF as xr,Epe as xt,R9 as y,ju as ya,PE as yi,Kz as yn,RF as yr,wQ as yt,f7 as z,dS as zi,OR as zn,Kue as zr,Oq as zt};
|
|
2032
|
-
//# sourceMappingURL=src-
|
|
2032
|
+
//# sourceMappingURL=src-9I3GiOoK.mjs.map
|