@inkeep/open-knowledge 0.82.2 → 0.82.3
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/cli.mjs +6 -6
- package/dist/constants-CiYP-S0i.mjs +1 -0
- package/dist/{dist-EULQvkfN.mjs → dist-CDKkB8Dz.mjs} +1 -1
- package/dist/{dist-D6yWo5z5.mjs → dist-Zhe_SWbs.mjs} +1 -1
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +1 -1
- package/dist/init-DlhFI_Fe.mjs +1 -0
- package/dist/{init-rGhLi7hI.mjs → init-YJoPYnfY.mjs} +2 -2
- package/dist/{launch-json-removal-DxoNTgkD.mjs → launch-json-removal-hdP8RUsg.mjs} +1 -1
- package/dist/loader-3cWE7cQf.mjs +1 -0
- package/dist/{loader-1N0cCGnL.mjs → loader-MjAFSnaj.mjs} +1 -1
- package/dist/{open-browser-BO21sxV5.mjs → open-browser-xMoTGHAP.mjs} +1 -1
- package/dist/preview-ChCA1dLZ.mjs +1 -0
- package/dist/{preview-B_ZWBhj-.mjs → preview-DdSgmXnL.mjs} +1 -1
- package/dist/public/assets/{ActivityModeContent-CMJY3iPZ.js → ActivityModeContent-Ck1WP638.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-CEHnfIOR.js → AddPropertiesButton-CMcuCASX.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-Ci_WlUqJ.js → AgentDiffPane-DjwhepFs.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-BvsTaGnu.js → CodeMirrorPropInput-Rch2F2Q-.js} +1 -1
- package/dist/public/assets/{DocumentContext-1IN55dhx.js → DocumentContext-DE2mJGsm.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-qt2PNGdC.js → EditorModeToggle-BHOvUpx8.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-EX0AGT48.js → ExcalidrawDocEditor-2g7O_f8F.js} +1 -1
- package/dist/public/assets/FeedbackForm-C2lwH0XX.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-Bebn-RLY.js → ImportSkillDialog-BCYvz04M.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-izVq_bYk.js → LintConfigEditor-BrQCB7b3.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-B717BQDe.js → ManagedArtifactProperties-D9jhgJgS.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-eW6dLE85.js +1 -0
- package/dist/public/assets/{MermaidDocEditor-6x9pXT5e.js → MermaidDocEditor-DLfy8oTo.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-D4nY1-k0.js → PropertyDisplayRow-BupKrPyE.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-3RhKxmLf.js → SchemaConfigEditor-CTijsRcx.js} +1 -1
- package/dist/public/assets/{SessionsHost-PaeFusQS.js → SessionsHost-B0ECmgas.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-C95zPMwR.js → SettingsDialogBody-DkOnHCwl.js} +1 -1
- package/dist/public/assets/{ShareReceiveMissDialog-4bA55vn5.js → ShareReceiveMissDialog-40NitdbR.js} +1 -1
- package/dist/public/assets/{SkillInstallMenu-BK0wvn5U.js → SkillInstallMenu-N8LcDQmg.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-BXpDNT0R.js → SkillToolbarControls-Bmef3toR.js} +1 -1
- package/dist/public/assets/{SourceEditor-BtmK5cJH.js → SourceEditor-j0S7cqWF.js} +1 -1
- package/dist/public/assets/{SyncStatusBadge-CWQSe8pe.js → SyncStatusBadge-GtJ1zGFv.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-BFl5AncI.js → TerminalWindowApp-tKMhog_9.js} +1 -1
- package/dist/public/assets/{TextDocEditor-Bf_oBx7o.js → TextDocEditor-un9fE4rY.js} +1 -1
- package/dist/public/assets/{ThreadView-CSfRmmXE.js → ThreadView-9WgVHAZE.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-IJZfcy5d.js → TimelineDiffPane-Bsa2EHb5.js} +1 -1
- package/dist/public/assets/{auth-state-cache-DwtH4Lkk.js → auth-state-cache-DwUhuRPR.js} +1 -1
- package/dist/public/assets/{comment-chips-DcgD9BSP.js → comment-chips-B-CFD67T.js} +1 -1
- package/dist/public/assets/{config-provider-Cz7yJeqI.js → config-provider-BOS9Ub5f.js} +1 -1
- package/dist/public/assets/{doc-undo-manager-Ause2OKj.js → doc-undo-manager-BueHZinR.js} +1 -1
- package/dist/public/assets/{index-DXUGzU6-.js → index-C51NLigd.js} +7 -7
- package/dist/public/assets/{messages-15pqM65e.js → messages-BKAVtROm.js} +1 -1
- package/dist/public/assets/{messages-C7pSlTmA.js → messages-B_ScSw2c.js} +1 -1
- package/dist/public/assets/{messages-Dd9VKFx-.js → messages-CAn6CTQ8.js} +1 -1
- package/dist/public/assets/{messages-CibA1WyZ.js → messages-CDCDnHMz.js} +1 -1
- package/dist/public/assets/{messages-CAYad86H.js → messages-CHG-1z-e.js} +1 -1
- package/dist/public/assets/{messages-KKn5PQmE.js → messages-CoSNN1mV.js} +1 -1
- package/dist/public/assets/{messages-DsNN544W.js → messages-CxK7hCWJ.js} +1 -1
- package/dist/public/assets/{messages-B_Wv5APO.js → messages-D6KysslY.js} +1 -1
- package/dist/public/assets/{messages-CciFZ7sP.js → messages-DhIQupTz.js} +1 -1
- package/dist/public/assets/{messages-9WOa9KUm.js → messages-DjY3XlJH.js} +1 -1
- package/dist/public/assets/{messages-CQ1vIgoS.js → messages-Su9sYNOw.js} +1 -1
- package/dist/public/assets/{messages-spfa9ZpO.js → messages-bHra1JBo.js} +1 -1
- package/dist/public/assets/{messages-WxVoyVTt.js → messages-kEPId8v1.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-C6nBYFJa.js → pending-receive-nav-store-b50rFqLr.js} +1 -1
- package/dist/public/assets/{progress-CDFU5XuP.js → progress-DuOqZzQX.js} +1 -1
- package/dist/public/assets/{selection-context-BQknXKNK.js → selection-context-DDUKdsG4.js} +1 -1
- package/dist/public/assets/{src-D0fT5ICF.js → src-DhvYkxXd.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-D_VGJ9dT.js → typing-burst-detector-DGIBRtme.js} +1 -1
- package/dist/public/assets/{uninstall-BXBr3BfR.js → uninstall-BXSKQxv5.js} +1 -1
- package/dist/public/assets/{use-activity-panel-BImUsjDN.js → use-activity-panel-sPqQSXuc.js} +1 -1
- package/dist/public/assets/{use-apply-config-language--jTlcFWU.js → use-apply-config-language-_-NDopzX.js} +2 -2
- package/dist/public/assets/{use-open-skill-D2yatv2H.js → use-open-skill-BfJNw5D1.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-DxJng8VS.js → use-terminal-enabled-CvzHai7_.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-CdTwqczN.js → use-timeline-entry-diff-BON9-fB7.js} +1 -1
- package/dist/public/index.html +19 -19
- package/dist/public/uninstall.html +3 -3
- package/dist/{registry-probes-DbobRkdf.mjs → registry-probes-B1W_iif2.mjs} +1 -1
- package/dist/{removal-file-path-DaW3Vngk.mjs → removal-file-path-0yAyQewr.mjs} +1 -1
- package/dist/{repair-launch-json-D_lmC4mJ.mjs → repair-launch-json-DkrwefwF.mjs} +1 -1
- package/dist/{repair-mcp-configs-N6USvw-_.mjs → repair-mcp-configs-BxfnbeyY.mjs} +1 -1
- package/dist/src-DKIekFkz.mjs +1 -0
- package/dist/{src-BPGRe6DB.mjs → src-zDKD_jbC.mjs} +1 -1
- package/dist/{start-XsBa1w_R.mjs → start-D2N3n2Y-.mjs} +3 -3
- package/dist/start-PmoMeHRR.mjs +1 -0
- package/package.json +4 -4
- package/dist/constants-DoXI_inL.mjs +0 -1
- package/dist/init--hg3FJlb.mjs +0 -1
- package/dist/loader-BonjJy5S.mjs +0 -1
- package/dist/preview-Cm5JPLNg.mjs +0 -1
- package/dist/public/assets/FeedbackForm-CJD21fJO.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-CIrkTNd5.js +0 -1
- package/dist/src-xZY2wsgi.mjs +0 -1
- package/dist/start-bvNkI3K0.mjs +0 -1
|
@@ -2125,7 +2125,7 @@ native-divergence-injected
|
|
|
2125
2125
|
`),o=t.replace(/\r\n/g,`
|
|
2126
2126
|
`);return o=a?`${o.replace(/\n+$/,``)}\n`:o.replace(/\n+$/,``),i&&(o=o.replace(/\n/g,`\r
|
|
2127
2127
|
`)),`${n}${o}`}function Yxt(e,t){let{bom:n,body:r}=D9(e),i=[],a=ZM(r,i,{allowTrailingComma:!0,disallowComments:!1});if(!a||i.length>0||a.type!==`object`)return{kind:`declined`,reason:`unparseable`};if(qxt(a,t.topLevelKey)>1)return{kind:`declined`,reason:`duplicate-container`};let o=[t.topLevelKey,t.serverName],s=QM(a,o);if(!s)return{kind:`no-entry`,raw:e,shell:e};let c=$M(s);if(!T9(c))return{kind:`declined`,reason:`foreign-entry`};let l=Jt(c,void 0,t.chainTag);if(l.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let u=r,d=t.managedKeys.map(e=>({key:e,node:QM(a,[...o,e])})).filter(e=>e.node!==void 0).sort((e,t)=>t.node.offset-e.node.offset);for(let{key:e,node:n}of d){let r=JSON.stringify(Xxt(t,e));u=`${u.slice(0,n.offset)}${r}${u.slice(n.offset+n.length)}`}return{kind:`managed`,raw:e,shell:`${n}${u}`,entry:c,descriptor:l.descriptor}}function Xxt(e,t){return e.topLevelKey===`mcp`&&t===`type`?`__ok_managed_type__`:t===`command`&&e.topLevelKey===`mcp`?[`__ok_managed_command__`]:t===`command`?`__ok_managed_command__`:[`__ok_managed_args__`]}function Zxt(e,t,n){if(!n)return{kind:`declined`,reason:`no-native-writer`};let{bom:r,body:i}=D9(e),a;try{a=n.parseToObject(i)}catch{return{kind:`declined`,reason:`unparseable`}}let o=a[t.topLevelKey],s=T9(o)?o[t.serverName]:void 0;if(s===void 0)return{kind:`no-entry`,raw:e,shell:e};if(!T9(s))return{kind:`declined`,reason:`foreign-entry`};let c=Jt(s,void 0,t.chainTag);if(c.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let l;try{l=n.upsertEntry(i,t.serverName,Object.fromEntries(t.managedKeys.map(e=>[e,Xxt(t,e)])))}catch{return{kind:`declined`,reason:`unparseable`}}let u=Jxt(e,l.text);return{kind:`managed`,raw:`${r}${i}`,shell:u,entry:s,descriptor:c.descriptor}}function O9(e,t,n){return e===null?{kind:`absent`}:Buffer.byteLength(e,`utf8`)>10485760?{kind:`declined`,reason:`oversize`}:t.format===`json`?Yxt(e,t):Zxt(e,t,n)}function Qxt(e,t,n){let{bom:r,body:i}=D9(e),a=i;for(let e of t.managedKeys){let r=ZM(a,[],{allowTrailingComma:!0,disallowComments:!1}),o=r?QM(r,[t.topLevelKey,t.serverName,e]):void 0;o&&JSON.stringify($M(o))===JSON.stringify(n[e])||(a=tN(a,eN(a,[t.topLevelKey,t.serverName,e],n[e],{formattingOptions:Kxt(i)})))}return`${r}${a}`}function $xt(e,t,n,r){if(t.format===`json`)return Qxt(e,t,n);if(!r)return null;let{body:i}=D9(e),a=Object.fromEntries(t.managedKeys.map(e=>[e,n[e]]));try{return Jxt(e,r.upsertEntry(i,t.serverName,a).text)}catch{return null}}function eSt(e){let t=E9(e.target);return t?$xt(e.raw,t,e.entry,e.tomlEditor):null}function tSt(e){let t=E9(e.target);if(!t)return null;let n=O9(e.raw,t,e.tomlEditor);return n.kind===`managed`||n.kind===`no-entry`?n.shell:null}function nSt(e,t,n){return t.shell===n.shell?t.shell:t.shell===e.shell?n.shell:n.shell===e.shell?t.shell:null}function rSt(e){let t=E9(e.target);if(!t)return{kind:`declined`,reason:`unsupported-target`};let n={base:O9(e.layers.base,t,e.tomlEditor),head:O9(e.layers.head,t,e.tomlEditor),index:O9(e.layers.index,t,e.tomlEditor),worktree:O9(e.layers.worktree,t,e.tomlEditor),incoming:O9(e.layers.incoming,t,e.tomlEditor)},r=Object.values(n),i=r.find(e=>e.kind===`declined`);if(i?.kind===`declined`)return i;if(r.some(e=>e.kind===`absent`))return r.every(e=>e.kind===`absent`)?{kind:`unchanged`}:{kind:`declined`,reason:`file-deletion-ambiguity`};if(r.some(e=>e.kind===`no-entry`))return r.every(e=>e.kind===`no-entry`)?{kind:`declined`,reason:`no-entry`}:{kind:`declined`,reason:`entry-deletion-ambiguity`};let a=n;if(a.index.shell!==a.worktree.shell)return{kind:`declined`,reason:`index-worktree-divergence`};let o=nSt(a.base,a.worktree,a.incoming);if(o===null)return{kind:`declined`,reason:`unowned-shell-conflict`};let s=Object.values(a).map(e=>({entry:e.entry,descriptor:e.descriptor}));if(e.runningEntry){let n=Jt(e.runningEntry,void 0,t.chainTag);n.kind===`recognized`&&s.push({entry:e.runningEntry,descriptor:n.descriptor})}if(new Set(s.map(e=>e.descriptor.family)).size!==1)return{kind:`declined`,reason:`mixed-launcher-family`};let c=s.reduce((e,t)=>t.descriptor.revision>e.descriptor.revision?t:e),l=[a.worktree,a.index,a.head,a.incoming,a.base].filter(e=>e.shell===o),u=l.find(e=>t.managedKeys.every(t=>JSON.stringify(e.entry[t])===JSON.stringify(c.entry[t])))??l[0];if(!u)return{kind:`declined`,reason:`unowned-shell-conflict`};let d=$xt(u.raw,t,c.entry,e.tomlEditor);return d===null?{kind:`declined`,reason:e.tomlEditor?`unparseable`:`no-native-writer`}:{kind:`resolved`,raw:d,winner:c.descriptor,winnerEntry:c.entry}}const iSt=q(`github-account`),aSt=(e,t)=>{let n=Xo(`git`,[`config`,`--get-urlmatch`,`credential`,e],PK({cwd:t,encoding:`utf-8`,timeout:5e3}));return n.error||n.status===null||n.status!==0&&n.status!==1?(iSt.warn({status:n.status,signal:n.signal,err:n.error,stderr:typeof n.stderr==`string`?i8(n.stderr).slice(0,200):void 0},`[github-account] git config --get-urlmatch failed — treating the URL as declaring no account`),null):n.status!==0||!n.stdout?null:n.stdout};function oSt(e){return e.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/]*@/i,`$1`)}function sSt(e){let t;for(let n of e.split(`
|
|
2128
|
-
`)){let e=n.startsWith(`credential.username `)?n.slice(20).trim():void 0;e&&(t=e)}return t}function cSt(e,t={}){let n=nat(e);if(!n)return{source:`active`};let r=n.host;if(n.login)return{host:r,login:n.login,source:`remote-url`};if(n.transport!==`https`)return{host:r,source:`active`};let i=(t._readCredentialUrlMatch??aSt)(oSt(e),t.cwd??process.cwd()),a=i?$it(sSt(i)):void 0;return a?{host:r,login:a,source:`credential-config`}:{host:r,source:`active`}}function lSt(e={}){let t=e.ttlMs??6e4,n=e.now??Date.now,r;return{resolve(i){let a=rat(i);if(!a)return{source:`active`};let o=n();if(r&&r.projectDir===i&&r.url===a&&r.expiresAt>o)return r.account;let s=cSt(a,{cwd:i,_readCredentialUrlMatch:e._readCredentialUrlMatch});return r={projectDir:i,url:a,account:s,expiresAt:o+t},s},invalidate(){r=void 0}}}function uSt(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}const k9=q(`sync-engine`),dSt=new Set(Wxt),A9=/^[0-9a-f]{40}$/i,fSt=$s(Jo);var j9=class extends Error{constructor(){super(`Sync paused while a Git operation is in progress or the index has unresolved conflicts`),this.name=`GitOperationInProgressError`}},pSt=class extends Error{constructor(e,t){super(`Shareable .ok subtree "${e}" could not be fully enumerated; sync staging aborted`,{cause:t}),this.name=`ShareableOkEnumerationError`}};function mSt(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 hSt(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason,...e.resolvedLogin===void 0?{}:{resolvedLogin:e.resolvedLogin},...e.declaredLogin===void 0?{}:{declaredLogin:e.declaredLogin},...e.declaredSource===void 0?{}:{declaredSource:e.declaredSource}}:{checkStatus:`unknown`,unknownError:e.error}}function gSt(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason&&e.resolvedLogin===t.resolvedLogin&&e.declaredLogin===t.declaredLogin&&e.declaredSource===t.declaredSource:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}const _St={syncScope:{pathBase:`content`}},M9={syncScope:{pathBase:`project`}},vSt=/(^|[/\\])index\.lock\b/i,ySt=new Set(ate);function bSt(e){return ySt.has(e)}const xSt=new Set([`diverged-local-commits`,`external-changes-pending`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`]),SSt=[`no-push-permission`,`auth-error`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`],CSt=new Set(SSt),wSt=new Set([...SSt,`external-changes-pending`]);function N9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function TSt(e){return new Promise(t=>{setTimeout(t,e)})}function P9(e){let t=Px(e);if(t.kind!==`repository`)return!1;let n=t.repository.readHead();return n.kind===`branch`&&t.repository.readRef(n.ref).kind===`absent`}function ESt(e){return e.class===`network`&&e.subclass!==`429`&&e.subclass!==`5xx`}function DSt(e){return e>=8?36e5:e>=5?9e5:e>=3?3e5:0}const OSt=12e4;var kSt=class{declaredGitHubHosts;state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;rootOkOutsideContentWalk;pullIntervalSeconds;pushIntervalSeconds;mode;credentialConfig;cc1Broadcaster;onStateChange;setBatchInProgress;onAutoDisable;checkpointBeforeStrandedConversion;checkpointBeforeOverlayRestore;beforeRealIndexResetRetry;mcpTomlEditor;detectGh;detectGhAccounts;ghTokenSource;ghAccountResolver;declaredAccountWarnKey;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;get lastRunUtc(){return this.lastPullOkUtc===null?this.lastPushOkUtc:this.lastPushOkUtc===null||this.lastPullOkUtc>this.lastPushOkUtc?this.lastPullOkUtc:this.lastPushOkUtc}lastPullOkUtc=null;lastPushOkUtc=null;pushCycleLanded=!1;fetchOnlyInFlight=!1;lastFetchUtc=null;lastPushedSha=null;lastPullUtc=null;lastPullOutcome=null;consecutivePullFailures=0;consecutivePushFailures=0;pushStreakIsConnectivity=!1;consecutiveContentions=0;ahead=0;behind=0;get conflictCount(){let e=0;for(let t of this.conflicts.list())TK(t)&&e++;return e}pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;indexLockHitThisCycle=!1;lastLockNoticeKind;restingIndexLockPause;blockingPaths=[];loggedSymlinkRefusal;refusedSymlinkPaths=[];currentBranch=`main`;cycleInFlight=null;hasRemote=!1;identityUnresolved=!1;statePath;conflicts;unsubscribeConflicts=null;constructor(e){this.projectDir=e.projectDir,this.declaredGitHubHosts=e.declaredGitHubHosts??I6(),this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.rootOkOutsideContentWalk=LK(U(this.contentDir,H(this.projectDir,`.ok`))).startsWith(`..`),this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.mode=e.mode??(e.syncEnabled===!0?`full`:`off`),this.credentialConfig=e.credentialConfig??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.checkpointBeforeStrandedConversion=e.checkpointBeforeStrandedConversion,this.checkpointBeforeOverlayRestore=e.checkpointBeforeOverlayRestore,this.beforeRealIndexResetRetry=e._beforeRealIndexResetRetry,this.mcpTomlEditor=e.mcpTomlEditor,this.detectGh=e.detectGh,this.detectGhAccounts=e.detectGhAccounts,this.ghTokenSource=jlt(e.detectGh),this.ghAccountResolver=lSt({_readCredentialUrlMatch:e._readCredentialUrlMatch}),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??tlt,this.statePath=W(xK(this.projectDir),`sync-state.json`),this.conflicts=e.conflicts}syncGhTarget(){let e=this.ghAccountResolver.resolve(this.projectDir);return{account:e,host:e.host??`github.com`}}resolveRelayGhToken(){let{account:e,host:t}=this.syncGhTarget(),n=this.ghTokenSource.get(t,e.login);return this.noteDeclaredAccountOutcome(e,t,n),n}noteDeclaredAccountOutcome(e,t,n){let r=e.login,i=n===null?void 0:n.login??this.activeGhLogin(t);if(!(r!==void 0&&(n===null||!F6(i,r)))){this.declaredAccountWarnKey=void 0;return}let a=`${t}\0${r}\0${e.source}\0${n===null?`none`:`fallback`}`;a!==this.declaredAccountWarnKey&&(n===null?k9.warn({host:t,declaredLogin:r,declaredSource:e.source},`[sync] declared GitHub account produced no gh token — git runs with no relayed credential`):k9.warn({host:t,declaredLogin:r,declaredSource:e.source,resolvedLogin:i},`[sync] declared GitHub account did not produce the gh token — using the active account`)),this.declaredAccountWarnKey=a}parkedOnAmbiguousNotFound(){return(this.state===`auth-error`||this.pausedReason===`auth-error`)&&(this.pushErrorCode===`auth-not-found-as-identity`||this.pullErrorCode===`auth-not-found-as-identity`)}activeGhLogin(e){if(this.detectGhAccounts)try{return this.detectGhAccounts(e)?.find(e=>e.active)?.login}catch(t){k9.warn({err:t,host:e},`[sync] detectGhAccounts failed — fallback identity stays unnamed`);return}}gitHandle(e){return bJ(this.projectDir,{credentialConfig:this.credentialConfig,gitIndexFile:e,ghToken:this.resolveRelayGhToken()??void 0,timeoutMs:12e4})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflicts.setBranch(e))}catch{}}catch(e){k9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),k9.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){k9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=Hx(this.projectDir),n=t?H(t,`MERGE_HEAD`):null,r=n!==null&&G(n);await this.conflicts.pruneMergeNativeAgainstGit();let i=()=>this.conflicts.list().some(e=>e.kind===`merge-native`);if(r&&!i()){k9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){k9.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.subscribeToConflicts(),i()){this.transitionTo(`conflict`),k9.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let a=uSt(this.lastFetchUtc,this.pullIntervalSeconds),o=uSt(this.lastPushOkUtc,this.pushIntervalSeconds);this.schedulePull(a>0?a:void 0),this.schedulePush(o>0?o:void 0),k9.info({branch:this.currentBranch,pullDelayMs:a,pushDelayMs:o},`[sync] started`)}stop(){this.unsubscribeConflicts?.(),this.unsubscribeConflicts=null,this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}setIntervals(e,t){let n=this.pullIntervalSeconds!==e,r=this.pushIntervalSeconds!==t;!n&&!r||(k9.info({pullFrom:this.pullIntervalSeconds,pullTo:e,pushFrom:this.pushIntervalSeconds,pushTo:t},`[sync] cycle intervals changed`),this.pullIntervalSeconds=e,this.pushIntervalSeconds=t,n&&this.pullTimer!==null&&this.schedulePull(),r&&this.pushTimer!==null&&this.schedulePush())}async setMode(e,t=`config`){if(this.mode===e)return;let n=this.mode;if(this.mode=e,k9.info({from:n,to:e,source:t},`[sync] mode changed`),e===`off`){this.cancelScheduledCycles(),await this.drainInFlightCycles(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}e===`follow`&&(await this.drainInFlightCycles(),this.cancelScheduledCycles(),await this.convertStrandedCommitsToOverlay()),this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(0),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}async setEnabled(e){await this.setMode(e?`full`:`off`)}cancelScheduledCycles(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null)}async drainInFlightCycles(){let e=Date.now();for(;this.cycleInFlight!==null;){if(Date.now()-e>3e4){k9.warn({cycleInFlight:this.cycleInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await tc(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||P9(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||P9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){k9.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){k9.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 yJ(()=>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,k9.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`,k9.warn({err:e},`[sync] pull-only: stranded-commit conversion failed — leaving branch as-is`)}}}async notifyCredentialsChanged(){if(this.mode!==`off`&&(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.state===`auth-error`||this.pausedReason===`auth-error`)){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(0),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){if(e===`fetch`){await this.fetchOnly();return}if(this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.consecutiveContentions=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`||this.pausedReason===`git-index-locked`||this.pausedReason===`no-commits-yet`)&&(this.pausedReason=void 0,this.clearPullError()),this.parkedOnAmbiguousNotFound()&&(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()),this.probePushPermissionInternal(`refresh`),e===`pull`){await this.pullOnce();return}if(e===`push`){await this.pushOnce();return}this.state===`dormant`||this.state===`conflict`||this.state===`auth-error`?k9.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}`):k9.info({op:e,state:this.state},`[sync] trigger(${e}) running`),await this.pushOnce(),await this.pullOnce(`sync`)}async pushOnce(){if(this.mode===`full`){await this.runPushCycle();return}await this.runOneShotPush()}async runOneShotPush(){if(this.cycleInFlight!==null){k9.info({cycleInFlight:this.cycleInFlight},`[sync] one-shot push refused — a cycle is already in flight`);return}if(this.state===`conflict`||this.state===`auth-error`){k9.info({state:this.state},`[sync] one-shot push refused — state=${this.state}`);return}if(this.conflictCount>0){k9.info({conflictCount:this.conflictCount},`[sync] one-shot push refused — unresolved conflicts hold the tree`);return}if(!this.hasRemote){k9.info({hasRemote:!1},`[sync] one-shot push refused — no remote`);return}if(P9(this.projectDir)){this.noteUnbornHeadRefusal();return}this.clearUnbornHeadPause();let e=this.state;this.cycleInFlight=`push`,this.beginIndexLockWatch(`push`);try{await this.doPushCycle(1)}finally{this.cycleInFlight=null,this.settleIndexLockPause(`push`),this.pushCycleLanded&&this.markRun();let t=this.currentState();t!==`conflict`&&t!==`auth-error`&&this.transitionTo(e),this.cc1Broadcaster?.signal(`sync-status`)}}async fetchOnly(){if(!this.hasRemote||P9(this.projectDir)||this.cycleInFlight!==null||this.fetchOnlyInFlight)return!1;this.fetchOnlyInFlight=!0;let e=this.gitHandle();try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.scheduleSaveState()}catch(e){return k9.debug({err:e},`[sync] panel-open fetch failed — counts left as they were`),!1}finally{this.fetchOnlyInFlight=!1}return await this.refreshDivergenceCounts(e),this.cc1Broadcaster?.signal(`sync-status`),!0}async refreshDivergenceCounts(e){try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch(e){k9.debug({err:e},`[sync] divergence-count refresh failed — keeping previous counts`)}}async pullOnce(e=`explicit`){let t=this.mode,n=await this.runOneShotPull(e);return k9.info({mode:t,outcome:n},`[sync] one-shot pull complete`),n}async runOneShotPull(e){if(this.cycleInFlight!==null)return k9.info({cycleInFlight:this.cycleInFlight},`[sync] one-shot pull refused — a cycle is already in flight`),this.recordPullOutcome(`refused`);if(this.state===`conflict`)return k9.info({state:this.state},`[sync] one-shot pull refused — the conflict resolver holds the tree`),this.recordPullOutcome(`refused`);if(!this.hasRemote||P9(this.projectDir))return k9.info({hasRemote:this.hasRemote},`[sync] one-shot pull refused — no remote, or no commits yet`),this.recordPullOutcome(`refused`);this.clearUnbornHeadPause();let t=this.mode,n=this.state,r=this.pausedReason;this.cycleInFlight=`pull`,this.beginIndexLockWatch(`pull`);try{return this.recordPullOutcome(await this.doPullCycle(e))}finally{this.cycleInFlight=null,this.settleIndexLockPause(`pull`),t===`off`?(xSt.has(this.pausedReason)||xSt.has(r)||(this.pausedReason=r),this.transitionTo(n)):this.schedulePull()}}recordPullOutcome(e){return this.lastPullUtc=new Date().toISOString(),this.lastPullOutcome=e,(e===`succeeded`||e===`up-to-date`||e===`conflict`)&&(this.lastPullOkUtc=new Date().toISOString(),this.saveStateNow()),this.cc1Broadcaster?.signal(`sync-status`),e}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastRunUtc:this.lastRunUtc,lastPullOkUtc:this.lastPullOkUtc,lastPushOkUtc:this.lastPushOkUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,lastPullUtc:this.lastPullUtc,lastPullOutcome:this.lastPullOutcome,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutivePullFailures,consecutivePushFailures:this.consecutivePushFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.mode!==`off`,syncMode:this.mode,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?oat(this.projectDir,this.declaredGitHubHosts):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.blockingPathsForStatus().length>0?{blockingPaths:this.blockingPathsForStatus()}:{},...this.pausedReason===`unsafe-incoming-symlinks`&&this.refusedSymlinkPaths.length>0?{refusedSymlinkPaths:this.refusedSymlinkPaths.slice(0,50)}:{},...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}blockingPathsForStatus(){return this.pausedReason===`external-changes-pending`?this.blockingPaths.slice(0,50):[]}getBlockingPaths(){return this.pausedReason===`external-changes-pending`?[...this.blockingPaths]:[]}async commitBlockingPaths(){let e=this.getBlockingPaths();if(e.length===0)return null;let t=this.gitHandle();return yJ(async()=>{await this.applyCommitIdentity(t);try{if(await t.git.raw([`add`,...Fn(e)]),(await pW(t.git,[`diff`,`--cached`,`--name-only`,...Fn(e)])).length===0)return null;await t.git.raw([`commit`,`-m`,`Commit local changes before syncing`,...Fn(e)])}catch(n){throw await t.git.raw([`reset`,...Fn(e)]).catch(t=>{k9.warn({resetErr:t,files:e.length},`[sync] blocking-path index reset failed; paths may remain staged`)}),k9.error({err:n,files:e.length},`[sync] commit of blocking paths failed`),n}let n=(await t.git.revparse(`HEAD`)).trim();return this.clearBlockingPause(),k9.info({files:e.length},`[sync] committed overlapping paths at user request`),n})}clearBlockingPause(){this.blockingPaths=[],this.pausedReason=void 0,this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await Bot(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async applyCommitIdentity(e){let t=await Bot(this.projectDir),n=t===null;this.identityUnresolved!==n&&(this.identityUnresolved=n,this.cc1Broadcaster?.signal(`sync-status`));let r=t?.name??`OpenKnowledge`,i=t?.email??`sync@open-knowledge.local`;eZe(e,{GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i})}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=L6(this.projectDir,this.declaredGitHubHosts);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,gSt(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,k9.info({caller:e,host:t.host,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let{account:n}=this.syncGhTarget(),r;try{r=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,transport:t.transport,account:n,detectGh:this.detectGh,detectGhAccounts:this.detectGhAccounts,tokenStore:this.tokenStore})}catch(t){k9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),r={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let i=hSt(r),a=this.pushPermission;this.pushPermission=i;let o=!1;return i.checkStatus===`denied`&&this.mode===`full`&&this.parkedOnAmbiguousNotFound()&&k9.info({reason:i.deniedReason,caller:e},`[sync] probe denial not applied — repository-not-found park is the more specific diagnosis`),i.checkStatus===`denied`&&this.mode===`full`&&!this.parkedOnAmbiguousNotFound()?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),o=!0,k9.info({reason:i.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):i.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),o=!0,k9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!o&&!gSt(a,i)&&this.cc1Broadcaster?.signal(`sync-status`),i}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,k9.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(!G(H(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return k9.warn({err:e},`[sync] remote detection failed`),!1}}subscribeToConflicts(){this.unsubscribeConflicts===null&&(this.unsubscribeConflicts=this.conflicts.subscribe(()=>{let e=this.conflicts.list().some(e=>e.kind===`merge-native`);if(e&&this.state!==`conflict`){this.transitionTo(`conflict`),this.scheduleSaveState();return}!e&&this.state===`conflict`&&(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush(),this.scheduleSaveState())}))}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflicts.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush(0)))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{k9.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){if(this.mode!==`full`)return;this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??this.effectivePushDelayMs();this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{k9.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=DSt(this.consecutivePullFailures),t=e>0?e/1e3:0;return N9(Math.max(t,this.pullIntervalSeconds))}effectivePushDelayMs(){let e=DSt(this.consecutivePushFailures),t=e>0?e/1e3:0;return N9(Math.max(t,this.pushIntervalSeconds))}logContention(){let e={consecutiveContentions:this.consecutiveContentions,consecutivePushFailures:this.consecutivePushFailures,releasedConnectivityStreak:this.pushStreakIsConnectivity};this.consecutiveContentions>=3?k9.warn(e,`[sync] push repeatedly losing to remote contention — not backing off by design`):k9.info(e,`[sync] push still rejected after retry (contention) — scheduling next push at base cadence`)}bumpFailureCount(e,t=!1){e===`push`?(this.consecutiveContentions=0,this.consecutivePushFailures++,this.pushStreakIsConnectivity=(this.consecutivePushFailures===1||this.pushStreakIsConnectivity)&&t):this.consecutivePullFailures++}async runPullCycle(){if(this.cycleInFlight!==null){this.cycleInFlight===`push`&&this.pullTimer===null&&this.schedulePull();return}if(this.state!==`dormant`&&this.state!==`disabled`&&this.state!==`auth-error`){if(this.state===`conflict`){this.schedulePull();return}if(P9(this.projectDir)){this.schedulePull();return}this.clearUnbornHeadPause(),this.cycleInFlight=`pull`,this.beginIndexLockWatch(`pull`);try{this.recordPullOutcome(await this.doPullCycle(this.mode===`full`?`sync`:`explicit`))}finally{this.cycleInFlight=null,this.settleIndexLockPause(`pull`),this.schedulePull()}}}async doPullCycle(e){if(this.pausedReason===`git-operation-in-progress`)try{await this.assertNoGitOperationInProgress()}catch(e){return e instanceof j9?(this.handleGitOperationRefusal(e,`pull`),`refused`):(this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`)}let t=this.gitHandle(),n;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!e||e===`HEAD`)return this.transitionTo(`disabled`),this.pausedReason=`detached-head`,k9.warn({},`[sync] detached HEAD — pausing sync`),`refused`;n=e,this.currentBranch=n}catch(e){return this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.transitionTo(`fetching`);try{await t.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutivePullFailures=0,this.clearPullError(),this.consecutivePushFailures>0&&this.pushStreakIsConnectivity&&(k9.info({cleared:this.consecutivePushFailures},`[sync] fetch succeeded — releasing connectivity-class push backoff`),this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.schedulePush())}catch(e){let t=w9(e instanceof Error?e:Error(String(e)));return this.handleError(t,`pull`),`error`}await this.refreshDivergenceCounts(t);let r=``;if(this.behind>0&&(e===`explicit`?this.ahead===0:this.conflictCount===0))try{r=await this.validateIncomingSymlinks(t,n)}catch(e){return e instanceof eY?(this.handleIncomingSymlinkRefusal(e,`pull`),`refused`):(this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`)}else this.behind===0&&this.clearIncomingSymlinkPause();if(this.behind>0&&e===`explicit`){let e=await this.doPullCycleB1(t,n,r);return this.scheduleSaveState(),e}if(this.behind>0&&this.conflictCount===0){this.pausedReason===`diverged-local-commits`&&(this.pausedReason=void 0),this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);let e=!0,i=!0;try{await this.commitDirtyContentFilesToHead(t,`pull`),await this.validateIncomingSymlinks(t,n,r);let a=await this.prepareForMerge(t,n,r);if(!a.proceed)return`refused`;try{await this.applyCommitIdentity(t),await this.mergeIncomingCommit(t,n,r),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.pausedReason===`external-changes-pending`&&this.clearBlockingPause(),this.transitionTo(`idle`)}finally{a.needsStashPop&&(e=await this.popPreMergeStash(t)),i=this.restoreReconciledMcpOverlays(a.reconciled)}if(!e)throw Error(`failed to replay pre-merge working-tree state`);if(!i)throw Error(`failed to restore reconciled MCP overlays`);return await this.persistReconciledMcpEntries(a.reconciled),this.scheduleSaveState(),`succeeded`}catch(t){if(t instanceof j9)return this.handleGitOperationRefusal(t,`pull`),`refused`;if(t instanceof eY)return this.handleIncomingSymlinkRefusal(t,`pull`),`refused`;if(t instanceof rY&&e&&i)return k9.info({branch:n,incoming:r,ref:t.ref},`[sync] incoming commit moved after inspection; re-inspecting next cycle`),this.transitionTo(`idle`),`refused`;let a=t instanceof rY?Error(e?`failed to restore reconciled MCP overlays`:`failed to replay pre-merge working-tree state`):t,o=w9(a instanceof Error?a:Error(String(a)));return o.class===`semantic`&&o.subclass===`merge-conflict`?(await this.handleMergeConflict(),this.state===`conflict`?`conflict`:this.pullError?`error`:`succeeded`):(this.handleError(o,`pull`),`error`)}finally{this.setBatchInProgress?.(!1)}}return this.transitionTo(`idle`),this.scheduleSaveState(),this.behind===0?`up-to-date`:`conflict`}async doPullCycleB1(e,t,n){if(this.transitionTo(`pulling`),this.ahead>0)return this.clearPullError(),this.pausedReason=`diverged-local-commits`,this.transitionTo(`idle`),k9.warn({ahead:this.ahead,behind:this.behind},`[sync] pull-only: local history diverged — not fast-forwardable, skipping cycle`),`refused`;let r,i;try{r=(await e.git.revparse([`HEAD`])).trim();let t=await pW(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await pW(e.git,[`diff`,`--name-only`,`HEAD..${n}`]));i=t.filter(e=>a.has(e))}catch(e){return this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`}let a=new Map;for(let e of this.conflicts.list())e.kind===`working-tree`&&a.set(e.file,e);let o;try{o=await this.planOverlapReconciliation(e,n,r,i,a)}catch(e){return this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.setBatchInProgress?.(!0);try{if(i.length>0){try{await this.checkpointBeforeOverlayRestore?.({branch:t,paths:i.length})}catch(e){k9.warn({err:e,paths:i.length},`[sync] pull-only: overlay checkpoint failed before restore — proceeding`)}try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,...Fn(i)])}catch(e){return k9.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`}}let r=await this.fastForwardOnly(e,n);if(!r.ok){try{this.applyOverlayPlan(o.mineRestore,o.deletions)}catch(e){return k9.error({err:e,refusal:r.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`}return r.timedOut?(k9.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(w9(Error(`git merge --ff-only timed out after ${OSt}ms`)),`pull`),`error`):(r.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),k9.warn({refusal:r.refusal,stderr:r.stderr.slice(0,200)},`[sync] pull-only: fast-forward refused — skipping cycle`),`refused`)}try{this.applyOverlayPlan(o.writes,o.deletions)}catch(e){return k9.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`}for(let e of o.upserts)this.conflicts.raise(e);for(let e of o.dissolved)this.conflicts.dissolveWorkingTree(e);this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.clearPullError(),this.pausedReason=void 0,this.blockingPaths=[],this.transitionTo(`idle`);let a=await this.countStandingOverlay(e);return k9.info({created:o.newConflicts.length,autoCombined:o.autoCombined.length,autoDissolved:o.dissolved.length,autoRestored:o.autoRestored.length,overlayStock:a},`[sync] pull-only: fast-forwarded to origin tip`),o.newConflicts.length>0?`conflict`:`succeeded`}finally{this.setBatchInProgress?.(!1)}}async fastForwardOnly(e,t){try{return await fSt(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,t],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:OSt}),{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:mSt({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(!G(H(this.projectDir,p))){try{await e.git.revparse([`${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),k9.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=K(H(this.projectDir,p))}catch{continue}o.push({path:p,bytes:h});let g=h.toString(`utf-8`),_=null;try{_=await e.git.raw([`show`,`${t}:${p}`])}catch(e){this.classifyRefReadFailure(e)===`error`&&k9.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&&dSt.has(p)){let t=await this.readMcpGitBlob(e,n,p),r=rSt({target:p,layers:{base:t,head:t,index:await this.readMcpGitBlob(e,``,p),worktree:g,incoming:_},tomlEditor:this.mcpTomlEditor});if(r.kind===`resolved`){r.raw!==_&&a.push({path:p,bytes:Buffer.from(r.raw,`utf8`)}),k9.info({event:`mcp-config-reconcile`,target:p,outcome:`auto-resolved`},`[sync] pull-only: auto-resolved OpenKnowledge MCP entry overlap`);continue}r.kind===`declined`&&k9.warn({event:`mcp-config-reconcile`,target:p,outcome:`declined`,reason:r.reason},`[sync] pull-only: declined OpenKnowledge MCP entry reconciliation`)}if(_===null||!this.isContentConflictPath(p)){a.push({path:p,bytes:h});continue}let v=m?r.baseSha:await this.gitBlobSha(e,`${n}:${p}`),y=v?await this.gitBlobContent(e,v):``,b=Qne(y,g,_);if(b.clean){a.push({path:p,bytes:Buffer.from(b.merged,`utf-8`)}),d.push(p),m&&l.push(p);continue}a.push({path:p,bytes:h});let x=await this.gitBlobSha(e,`${t}:${p}`);if(x===void 0){k9.warn({path:p},`[sync] pull-only: could not pin origin blob for a collision — keeping overlay, deferring`);continue}c.push({kind:`working-tree`,file:p,theirsSha:x,...v===void 0?{}:{baseSha:v}}),m||u.push(p)}return{writes:a,mineRestore:o,deletions:s,upserts:c,dissolved:l,newConflicts:u,autoCombined:d,autoRestored:f}}applyOverlayPlan(e,t){let n={allowShareableOkArtifact:aq};for(let{path:t,bytes:r}of e)$U(kY(H(this.projectDir,t),this.projectDir,n),r);for(let e of t){let t=H(this.projectDir,e);kY(t,this.projectDir,n);try{iW(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=H(this.projectDir,e),n=LK(U(this.contentDir,t));return!n.startsWith(`..`)&&FG(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 pW(e.git,[`diff-index`,`--name-only`,`HEAD`])).filter(e=>this.isContentConflictPath(e)).length}catch{return null}}async runPushCycle(){if(this.mode===`full`&&this.state!==`dormant`&&this.state!==`disabled`&&this.state!==`conflict`&&this.state!==`auth-error`){if(this.conflictCount>0){this.schedulePush();return}if(P9(this.projectDir)){this.hasRemote&&this.noteUnbornHeadRefusal(),this.schedulePush();return}if(this.clearUnbornHeadPause(),this.cycleInFlight!==null){this.cycleInFlight===`pull`&&this.pushTimer===null&&this.schedulePush();return}if(this.pausedReason===`unsafe-incoming-symlinks`){this.schedulePush();return}this.cycleInFlight=`push`,this.beginIndexLockWatch(`push`);try{await this.doPushCycle(1)}finally{this.cycleInFlight=null,this.settleIndexLockPause(`push`),this.pushCycleLanded&&this.markRun(),this.schedulePush()}}}async doPushCycle(e=0){this.pushCycleLanded=!1;let t=H(Ps(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),n=null;try{let e=this.gatherContentFilesSync(),r=await this.snapshotPromisedPaths(),i=new Set;await yJ(async()=>{await this.assertNoGitOperationInProgress(),this.transitionTo(`pushing`);try{let r=this.gitHandle(t);if(P9(this.projectDir)){k9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let a;try{a=(await r.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){k9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(w9(e instanceof Error?e:Error(String(e))),`push`);return}await r.git.raw([`read-tree`,a]);let o=await this.listHeadContentPaths(r,a),s=await this.stageContentFiles(r,e),c=new Set(s.map(e=>e.projectRelPath)),l=[...o].filter(e=>!c.has(e));await this.removePathsFromIndex(r,l);let u=(await r.git.raw([`write-tree`])).trim(),d=``;try{d=(await r.git.raw([`rev-parse`,`${a}^{tree}`])).trim()}catch{}if(d&&d===u){let t=null;try{t=(await r.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(t===a){k9.info({contentFileCount:e.length,headSha:a},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=a,this.lastSyncUtc=new Date().toISOString(),this.pushCycleLanded=!0,this.consecutivePushFailures=0,this.consecutiveContentions=0,this.pushStreakIsConnectivity=!1,this.clearPushError(),this.transitionTo(`idle`);return}k9.info({headSha:a,upstreamSha:t},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let i=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),i=!0}catch{}i?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=a;return}let f=[],p=[];try{let t=await pW(r.git,[`diff-tree`,`--name-only`,`-r`,a,u]);if(t.length>0){let n=new Map(e.map(e=>[e.projectRelPath,e.contentRelPath]));for(let e of t){f.push(e);let t=n.get(e)??LK(U(this.contentDir,H(this.projectDir,e)));t&&!t.startsWith(`..`)&&p.push(t)}}}catch{f=e.map(e=>e.projectRelPath).concat(l),p=e.map(e=>e.contentRelPath)}let m=this.buildCommitMessage(p);await this.applyCommitIdentity(r);let h=(await r.git.raw([`commit-tree`,u,`-p`,a,`-m`,m])).trim();if(!h||!A9.test(h)){k9.warn({raw:h},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await r.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,h,a]),await this.resetRealIndexForPaths(f,`push`);for(let e of f)i.add(e);let g=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),g=!0}catch{}g?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=h}finally{await this.healStaleRealIndex(r,i)}}),n&&(this.lastPushedSha=n,this.lastSyncUtc=new Date().toISOString(),this.pushCycleLanded=!0,this.ahead=0,this.consecutivePushFailures=0,this.consecutiveContentions=0,this.pushStreakIsConnectivity=!1,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){if(t instanceof j9){this.handleGitOperationRefusal(t,`push`);return}let n=t instanceof Error?t:Error(String(t));n instanceof pSt&&k9.warn({err:n},`[sync] push cycle: staging error detail`);let r=w9(n);if(r.class===`semantic`&&r.subclass===`non-fast-forward`){if(e>0){k9.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);let t=`fetch`,n=!0,r=!0;try{await e.git.fetch(`origin`);let i=await this.validateIncomingSymlinks(e,this.currentBranch);t=`push`,await this.commitDirtyContentFilesToHead(e,`push`),t=`fetch`,await this.validateIncomingSymlinks(e,this.currentBranch,i),t=`push`;let a=await this.prepareForMerge(e,this.currentBranch,i);if(!a.proceed){this.setBatchInProgress?.(!1);return}try{await this.applyCommitIdentity(e),t=`merge`,await this.mergeIncomingCommit(e,this.currentBranch,i),t=`push`}finally{a.needsStashPop&&(n=await this.popPreMergeStash(e)),r=this.restoreReconciledMcpOverlays(a.reconciled)}if(!n)throw Error(`failed to replay pre-merge working-tree state`);if(!r)throw Error(`failed to restore reconciled MCP overlays`);await this.persistReconciledMcpEntries(a.reconciled)}catch(e){if(e instanceof j9){this.handleGitOperationRefusal(e,`push`);return}if(e instanceof eY){this.handleIncomingSymlinkRefusal(e,`push`);return}if(e instanceof rY&&n&&r){k9.info({ref:e.ref},`[sync] push retry: incoming commit moved after inspection; re-inspecting next cycle`),this.state===`pushing`&&this.transitionTo(`idle`),this.scheduleSaveState();return}let i=e instanceof rY?Error(n?`failed to restore reconciled MCP overlays`:`failed to replay pre-merge working-tree state`):e,a=w9(i instanceof Error?i:Error(String(i)));if(a.class===`semantic`&&a.subclass===`merge-conflict`)await this.handleMergeConflict();else{let n=t===`merge`||t===`fetch`?`pull`:`push`;k9.warn({err:e,stage:t},`[sync] push retry error detail`),this.handleError(a,n)}this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}this.consecutiveContentions++,this.logContention(),this.pushStreakIsConnectivity&&(this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.clearPushError()),this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(r,`push`)}finally{try{Ds(t)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e,t){if(await this.assertNoGitOperationInProgress(),(await e.git.status()).files.length===0)return null;let n=(await e.git.revparse(`HEAD`)).trim(),r=this.gatherContentFilesSync(),i=await this.listHeadContentPaths(e,n);if(r.length===0&&i.size===0)return null;let a=H(Ps(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),o=this.gitHandle(a);try{await o.git.raw([`read-tree`,n]);let a=await this.stageContentFiles(o,r),s=new Set(a.map(e=>e.projectRelPath)),c=[...i].filter(e=>!s.has(e));await this.removePathsFromIndex(o,c);let l=(await o.git.raw([`write-tree`])).trim();if(l===(await o.git.raw([`rev-parse`,`${n}^{tree}`])).trim())return null;let u=[];try{u=await pW(o.git,[`diff-tree`,`--name-only`,`-r`,n,l])}catch{u=r.map(e=>e.projectRelPath).concat(c)}await this.applyCommitIdentity(o);let d=(await o.git.raw([`commit-tree`,l,`-p`,n,`-m`,`Auto-save: interim before merge`])).trim();return!d||!A9.test(d)?(k9.warn({raw:d},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,d,n]),await this.resetRealIndexForPaths(u,t,e),d)}finally{try{Ds(a)}catch{}}}async readMcpGitBlob(e,t,n){try{return await e.git.raw([`cat-file`,`-e`,`${t}:${n}`]),await e.git.raw([`show`,`${t}:${n}`])}catch{return null}}async planTrackedMcpOverlap(e,t,n){let r;try{r=(await e.git.raw([`merge-base`,`HEAD`,t])).trim()}catch(e){return k9.warn({err:e,incomingCommit:t,path:n},`[sync] MCP reconciliation merge-base unavailable — declining`),{kind:`declined`,reason:`merge-base-unavailable`}}let[i,a,o,s]=await Promise.all([this.readMcpGitBlob(e,r,n),this.readMcpGitBlob(e,`HEAD`,n),this.readMcpGitBlob(e,``,n),this.readMcpGitBlob(e,t,n)]),c=null;try{c=K(H(this.projectDir,n),`utf8`)}catch{}return rSt({target:n,layers:{base:i,head:a,index:o,worktree:c,incoming:s},tomlEditor:this.mcpTomlEditor})}async prepareForMerge(e,t,n){let r=[],i;try{i=await pW(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return k9.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1,reconciled:r}}if(i.length===0)return{proceed:!0,needsStashPop:!1,reconciled:r};let a;try{a=new Set(await pW(e.git,[`diff`,`--name-only`,`HEAD..${n}`]))}catch(e){return k9.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1,reconciled:r}}let o=i.filter(e=>a.has(e)),s=dSt,c=o.filter(e=>s.has(e));if(c.length>0){let t=await Promise.all(c.map(async t=>({path:t,plan:await this.planTrackedMcpOverlap(e,n,t)}))),i=t.find(({plan:e})=>e.kind===`declined`),a=o.some(e=>!s.has(e));if(!i&&!a){for(let{path:e,plan:n}of t)n.kind===`resolved`&&(r.push({path:e,raw:n.raw,winnerEntry:n.winnerEntry}),k9.info({event:`mcp-config-reconcile`,target:e,outcome:`auto-resolved`},`[sync] auto-resolved OpenKnowledge MCP entry overlap`));o=o.filter(e=>!s.has(e))}else i?k9.warn({event:`mcp-config-reconcile`,target:i.path,outcome:`declined`,reason:i.plan.kind===`declined`?i.plan.reason:void 0},`[sync] declined OpenKnowledge MCP entry reconciliation`):a&&k9.info({event:`mcp-config-reconcile`,targets:c,outcome:`suppressed`,reason:`other-blocking-path`},`[sync] suppressed MCP entry reconciliation because another path blocks the merge`)}if(o.length>0){let e=o.slice(0,3).join(`, `),t=o.length>3?`, +${o.length-3} more`:``;return this.blockingPaths=o,this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutivePullFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),k9.warn({files:o},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1,reconciled:[]}}if(r.length>0)try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,...Fn(r.map(e=>e.path))])}catch(e){return k9.warn({err:e},`[sync] could not isolate reconciled MCP paths from pre-merge stash`),this.pullError=`Sync paused — OpenKnowledge could not safely isolate local MCP launcher changes before merging.`,this.pausedReason=`external-changes-pending`,this.blockingPaths=[],this.transitionTo(`idle`),this.scheduleSaveState(),{proceed:!1,needsStashPop:!1,reconciled:[]}}let l=new Set(r.map(e=>e.path));if(i.every(e=>l.has(e)))return{proceed:!0,needsStashPop:!1,reconciled:r};let u=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,u])}catch(e){return k9.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1,reconciled:r}}return{proceed:!0,needsStashPop:!0,reconciled:r}}restoreReconciledMcpOverlays(e){let t=!0;for(let n of e)try{let e=kY(H(this.projectDir,n.path),this.projectDir),t=null;try{t=K(e,`utf8`)}catch(e){k9.warn({err:e,path:n.path},`[sync] could not read MCP config before restoring reconciled overlay`)}t!==n.raw&&$U(e,n.raw,`utf8`)}catch(e){t=!1,k9.warn({err:e,path:n.path},`[sync] could not restore reconciled MCP overlay`)}return t}async popPreMergeStash(e){try{return await e.git.raw([`stash`,`pop`]),!0}catch(e){return k9.warn({err:e},`[sync] stash pop failed — stash remains on stack`),!1}}async assertNoGitOperationInProgress(){if(this.hasGitOperationInProgress()||(await pW(this.gitHandle().git,[`diff`,`--name-only`,`--diff-filter=U`])).length>0||this.hasGitOperationInProgress())throw new j9;this.pausedReason===`git-operation-in-progress`&&(this.pausedReason=void 0,this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}handleGitOperationRefusal(e,t){this.state===`conflict`||this.conflictCount>0?this.transitionTo(`conflict`):(this.pausedReason=`git-operation-in-progress`,t===`push`?this.clearPushError():this.clearPullError(),(this.state===`pushing`||this.state===`pulling`||this.state===`fetching`)&&this.transitionTo(`idle`)),k9.error({event:`git-operation-refusal`,err:e,op:t,branch:this.currentBranch},`[sync] cycle refused because a Git operation holds the tree — finish or abort it to resume sync`),this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}async validateIncomingSymlinks(e,t,n){let r=`refs/remotes/origin/${t}`,i=n;try{i??=await QJ(e.git,r),await tY(e.git,i,`merge`,e.env)}catch(e){let n=e instanceof eY?e.unsafe.slice(0,50):null,a=n===null?void 0:JSON.stringify([i,n]);throw n!==null&&a!==this.loggedSymlinkRefusal&&(this.loggedSymlinkRefusal=a,k9.warn({event:`unsafe-incoming-symlinks`,branch:t,incoming:i,links:n},`[sync] refusing incoming changes with unsafe symlinks until they are fixed`)),n===null&&k9.warn({err:e,branch:t,trackingRef:r,incoming:i},`[sync] incoming symlink inspection failed`),e}return this.clearIncomingSymlinkPause(),i}handleIncomingSymlinkRefusal(e,t){this.pausedReason=`unsafe-incoming-symlinks`,this.refusedSymlinkPaths=e.displayPaths(),t===`push`?this.clearPushError():this.clearPullError(),(this.state===`pushing`||this.state===`pulling`||this.state===`fetching`)&&this.transitionTo(`idle`),this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}clearIncomingSymlinkPause(){this.loggedSymlinkRefusal=void 0,this.pausedReason===`unsafe-incoming-symlinks`&&(this.pausedReason=void 0,this.refusedSymlinkPaths=[],this.cc1Broadcaster?.signal(`sync-status`))}async mergeIncomingCommit(e,t,n){let r=`origin/${t}`;try{await oY(e.git,{name:r,trackingRef:`refs/remotes/${r}`,commit:n})}catch(e){throw e instanceof iY&&k9.warn({event:`incoming-ref-shadowed`,shadowedName:e.shadowedName,incoming:n},`[sync] another ref shadows the incoming branch name; delete it locally and on the remote`),e}await e.git.merge([r])}hasGitOperationInProgress(){let e=Hx(this.projectDir);return!e||[`MERGE_HEAD`,`CHERRY_PICK_HEAD`,`REVERT_HEAD`,`rebase-merge`,`rebase-apply`].some(t=>G(H(e,t)))}async persistReconciledMcpEntries(e){if(e.length!==0){if(this.hasGitOperationInProgress())throw new j9;await yJ(async()=>{let t=H(Ps(),`ok-mcp-sync-idx-${process.pid}-${Date.now()}.idx`),n=[];try{let r=this.gitHandle(),i=this.gitHandle(t),a=(await i.git.revparse(`HEAD`)).trim(),o=(await i.git.revparse([`--abbrev-ref`,`HEAD`])).trim();if(o===`HEAD`)throw Error(`refusing MCP entry commit on detached HEAD`);await i.git.raw([`read-tree`,a]);let s=[];for(let r=0;r<e.length;r++){let o=e[r];if(!o)continue;let c=await this.readMcpGitBlob(i,a,o.path);if(c===null)throw Error(`tracked MCP path disappeared: ${o.path}`);let l=eSt({target:o.path,raw:c,entry:o.winnerEntry,tomlEditor:this.mcpTomlEditor});if(l===null)throw Error(`cannot edit tracked MCP path: ${o.path}`);let u=(await i.git.raw([`ls-tree`,a,...Fn([o.path])])).match(/^(100644|100755)\s/)?.[1];if(!u)throw Error(`unsafe tracked MCP mode: ${o.path}`);let d=`${t}.commit-${r}`;n.push(d),Os(d,l,`utf8`);let f=(await i.git.raw([`hash-object`,`-w`,d])).trim();await i.git.raw([`update-index`,`--add`,`--cacheinfo`,`${u},${f},${o.path}`]);let p=tSt({target:o.path,raw:l,tomlEditor:this.mcpTomlEditor}),m=tSt({target:o.path,raw:o.raw,tomlEditor:this.mcpTomlEditor}),h=p!==null&&p===m?l:o.raw,g=`${t}.replay-${r}`;n.push(g),Os(g,h,`utf8`);let _=(await i.git.raw([`hash-object`,`-w`,g])).trim();s.push({path:o.path,mode:u,blobSha:_,raw:h})}let c=(await i.git.raw([`write-tree`])).trim();if(c===(await i.git.raw([`rev-parse`,`${a}^{tree}`])).trim())return;await this.applyCommitIdentity(i);let l=(await i.git.raw([`commit-tree`,c,`-p`,a,`-m`,`Update OpenKnowledge MCP launcher`])).trim();if(!A9.test(l))throw Error(`commit-tree returned an invalid SHA`);try{await i.git.raw([`update-ref`,`refs/heads/${o}`,l,a])}catch(e){k9.info({event:`mcp-config-reconcile`,outcome:`ref-race`,branch:o,err:e},`[sync] skipped MCP launcher commit because the branch moved`);return}try{for(let e of s){await r.git.raw([`update-index`,`--add`,`--cacheinfo`,`${e.mode},${e.blobSha},${e.path}`]);let t=kY(H(this.projectDir,e.path),this.projectDir);K(t,`utf8`)!==e.raw&&$U(t,e.raw,`utf8`)}}catch(t){k9.warn({event:`mcp-config-reconcile`,outcome:`overlay-replay-failed`,err:t},`[sync] MCP overlay replay failed; resetting the affected index entries`),await this.resetRealIndexForPaths(s.map(e=>e.path),`mcp-reconcile`),this.restoreReconciledMcpOverlays(e)}k9.info({event:`mcp-config-reconcile`,outcome:`persisted-entry-commit`},`[sync] persisted OpenKnowledge MCP launcher entry commit`)}finally{for(let e of n)try{Ds(e)}catch{}try{Ds(t)}catch{}}})}}async stageContentFiles(e,t){if(t.length===0)return t;let n=new Set,r=!0;for(let i=0;i<t.length;i+=100){let a=t.slice(i,i+100).map(e=>e.projectRelPath);try{let t=await pW(e.git,[`ls-files`,`--others`,`--ignored`,`--exclude-standard`,...Fn(a)]);for(let e of t)n.add(e)}catch(e){r=!1,k9.warn({err:e},`[sync] ignored-path probe failed — staging unfiltered without -f`)}}n.size>0&&k9.info({count:n.size,sample:[...n].slice(0,5)},`[sync] skipping gitignored untracked path(s) — in content scope but excluded from git`);let i=r?t.filter(e=>!n.has(e.projectRelPath)):t,a=e=>e.startsWith(`.ok/`)||e.includes(`/.ok/`),o=r?i.filter(e=>a(e.projectRelPath)):[],s=r?i.filter(e=>!a(e.projectRelPath)):i;for(let[t,n]of[[[`add`],s],[[`add`,`-f`],o]])for(let r=0;r<n.length;r+=100){let i=n.slice(r,r+100).map(e=>e.projectRelPath);await e.git.raw([...t,...Fn(i)])}return i}gatherContentFilesSync(){let e=[],t=(e,t)=>{throw new pSt(LK(U(this.projectDir,t))||`.`,e)},n=(r,i,a,o)=>{let s;try{s=xs(r,{withFileTypes:!0})}catch(e){o?.(e,r);return}for(let c of s){let s=H(r,c.name);if(c.isDirectory()){let e=LK(U(i,s));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e,a))continue;let r=e.split(`/`).some(e=>e.toLowerCase()===`.ok`);n(s,i,a,o??(r?t:void 0))}else if(c.isFile()||c.isSymbolicLink()){let t=LK(U(i,s));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t,a)){let t=LK(U(this.contentDir,s)),n=LK(U(this.projectDir,s));e.push({contentRelPath:t,projectRelPath:n})}}}};if(G(this.contentDir)&&n(this.contentDir,this.contentDir,_St),this.rootOkOutsideContentWalk){let e=H(this.projectDir,`.ok`);G(e)&&!this.contentFilter.isDirExcluded(`.ok`,M9)&&n(e,this.projectDir,M9,t)}return e}isSyncScopedPath(e){let t=H(this.projectDir,e),n=LK(U(this.contentDir,t)),r=!n.startsWith(`..`)&&!this.contentFilter.isExcluded(n,_St),i=this.rootOkOutsideContentWalk&&e.startsWith(`.ok/`)&&!this.contentFilter.isExcluded(e,M9);return r||i}async listHeadContentPaths(e,t){let n=new Set;try{let r=await pW(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r)this.isSyncScopedPath(e)&&n.add(e)}catch{}return n}async removePathsFromIndex(e,t){if(t.length===0)return;let n=[...new Set(t)];for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100);await e.git.raw([`rm`,`--cached`,...Fn(r)])}}async snapshotPromisedPaths(){let e,t;try{let{git:n}=this.gitHandle();e=await mW(n,uW),t=new Set(await pW(n,[`diff`,`--name-only`,`--diff-filter=U`]))}catch(e){return k9.warn({event:`snapshot-read-failed`,err:e,branch:this.currentBranch},`[sync] could not read the real index before the push cycle — skipping stale-index self-heal`),[]}let n=[];for(let r of e)if(!t.has(r.path)&&this.isSyncScopedPath(r.path)&&(n.push(r.path),n.length===100))break;return n}async healStaleRealIndex(e,t){let n=new Set(e.filter(e=>!t.has(e)));if(n.size===0)return;if(this.hasGitOperationInProgress()){k9.warn({event:`self-heal-skipped-git-operation`,branch:this.currentBranch,pathCount:n.size,paths:[...n].slice(0,20)},`[sync] self-heal skipped — a Git operation now holds the tree, so the promised paths stay listed until it ends`);return}let r=this.gitHandle(),i,a;try{i=(await hW(r.git,[`diff-index`,`--cached`,`--name-status`,`HEAD`])).flatMap(e=>e.status[0]===`R`||e.status[0]===`C`?[e.from,e.to]:[e.to]),a=await pW(r.git,[`diff`,`--name-only`,`HEAD`])}catch(e){k9.error({event:`self-heal-skipped`,branch:this.currentBranch,pathCount:n.size,paths:[...n].slice(0,20),err:e},`[sync] self-heal could not compare the real index against HEAD — the promised paths stay listed in the real index`);return}let o=new Set(a),s=[...new Set(i.filter(e=>n.has(e)&&!o.has(e)))];s.length!==0&&(await this.resetRealIndexForPaths(s,`push`,r),k9.warn({event:`self-heal-applied`,branch:this.currentBranch,pathCount:s.length,paths:s.slice(0,20)},`[sync] self-heal cleared stale real-index entries left behind by an earlier push cycle`))}async resetRealIndexForPaths(e,t,n){if(e.length===0)return;let r=n??this.gitHandle(),i=[...new Set(e)];for(let e=0;e<i.length;e+=100){let n=i.slice(e,e+100);await this.resetRealIndexBatch(r,n,t)}}async resetRealIndexBatch(e,t,n){let r;try{await e.git.raw([`reset`,`HEAD`,...Fn(t)]);return}catch(e){r=e}let i=w9(r),a=r,o=!1;if(i.class===`local`&&i.subclass===`index-lock`){await this.beforeRealIndexResetRetry?.(),await TSt(N9(.05));try{await e.git.raw([`reset`,`HEAD`,...Fn(t)]),o=!0}catch(e){a=e,i=w9(e)}}let s={event:`stale-index-reset`,outcome:o?`recovered-on-retry`:`failed`,op:n,branch:this.currentBranch,pathCount:t.length,paths:t.slice(0,20),errorClass:i.class,errorSubclass:i.subclass,err:a};o?k9.warn(s,`[sync] stale-index reset needed a second attempt — it succeeded, so the panel listing is current`):k9.error(s,`[sync] stale-index reset failed — the panel listing may stay stale`),!o&&i.class===`local`&&i.subclass===`index-lock`&&this.noteIndexLockEncountered(n,i)}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=this.gitHandle(),t=[];try{t=await pW(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){k9.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){k9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t)this.isContentConflictPath(e)?n.push(e):r.push(e);let i=[],a=LK(U(this.projectDir,wS(`project`,this.projectDir)));for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,...Fn([t])]),await e.git.raw([`add`,...Fn([t])]),t.toLowerCase()===a.toLowerCase()?k9.warn({file:t},`[sync] auto-resolved .ok/config.yml conflict with theirs: local project config edits were overwritten by the remote version`):k9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){k9.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){k9.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let n=t.slice(0,3).join(`, `),r=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${n}${r}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutivePullFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),k9.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(n.length>0){for(let e of n)this.conflicts.raise({kind:`merge-native`,file:e});this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),k9.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await this.applyCommitIdentity(e),await e.git.raw([`commit`,`--no-edit`]);let n=Hx(this.projectDir);t=n===null||!G(H(n,`MERGE_HEAD`))}catch(e){k9.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),k9.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){k9.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`),k9.warn({},`[sync] could not finalize merge after auto-resolving conflicts — merge aborted`)}}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){if(e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),k9.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`)this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`;else if(e.class===`semantic`&&e.subclass===`protected-branch`)this.mode=`off`,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`);else if(e.class===`local`&&e.subclass===`index-lock`)this.bumpFailureCount(t),(this.state===`pushing`||this.state===`pulling`||this.state===`fetching`)&&this.transitionTo(`idle`),this.noteIndexLockEncountered(t,e);else if(e.class===`local`&&e.subclass===`dirty-tree`){if(this.state===`conflict`||this.conflictCount>0){this.transitionTo(`conflict`);return}this.bumpFailureCount(t),this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)}else e.retryable?(this.bumpFailureCount(t,ESt(e)),this.transitionTo(`offline`)):(this.bumpFailureCount(t),this.transitionTo(`idle`))}otherLegInFlight(e){return this.cycleInFlight!==null&&this.cycleInFlight!==e}beginIndexLockWatch(e){if(this.otherLegInFlight(e))return;let t=this.pausedReason===`git-index-locked`;this.indexLockHitThisCycle=!1,t||(this.lastLockNoticeKind=void 0),this.restingIndexLockPause=t?void 0:this.pausedReason}holdsIndexLock(e){return vSt.test(`${e.message}\n${e.rawStderr??``}`)}noteIndexLockEncountered(e,t){let n=this.holdsIndexLock(t),r=n?`index-locked`:`git-lock-held`;if(this.lastLockNoticeKind!==r){this.lastLockNoticeKind=r;let i={event:r,op:e,branch:this.currentBranch,errorClass:t.class,errorSubclass:t.subclass};n?k9.error(i,`[sync] index locked — another program is holding .git/index.lock, so sync cannot update it`):k9.error(i,`[sync] a git lock file blocked the operation — the held lock is not .git/index.lock, so the listing is not paused on it`)}n&&(this.indexLockHitThisCycle=!0,this.pausedReason!==`git-index-locked`&&(this.pausedReason=`git-index-locked`,this.cc1Broadcaster?.signal(`sync-status`)))}noteUnbornHeadRefusal(){this.pausedReason!==`no-commits-yet`&&k9.error({event:`unborn-head-refusal`,branch:this.currentBranch},`[sync] push refused — this repository has no commits yet, so there is nothing to send`),this.pausedReason=`no-commits-yet`,this.cc1Broadcaster?.signal(`sync-status`)}clearUnbornHeadPause(){this.pausedReason===`no-commits-yet`&&(this.pausedReason=void 0,this.cc1Broadcaster?.signal(`sync-status`))}settleIndexLockPause(e){this.otherLegInFlight(e)||this.indexLockHitThisCycle||this.pausedReason===`git-index-locked`&&(this.pausedReason=this.restingIndexLockPause,this.cc1Broadcaster?.signal(`sync-status`))}currentState(){return this.state}markRun(){this.lastPushOkUtc=new Date().toISOString(),this.saveStateNow(),this.cc1Broadcaster?.signal(`sync-status`)}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,k9.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null);try{let e=CSt.has(this.pausedReason)?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastPullOkUtc:this.lastPullOkUtc,lastPushOkUtc:this.lastPushOkUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutivePullFailures,consecutivePushFailures:this.consecutivePushFailures,pushStreakIsConnectivity:this.pushStreakIsConnectivity,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0},n=`${this.statePath}.tmp`;$U(n,JSON.stringify(t,null,2),`utf-8`),nW(n,this.statePath)}catch(e){k9.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(G(this.statePath))try{let e=K(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastPullOkUtc=t.lastPullOkUtc??null,this.lastPushOkUtc=t.lastPushOkUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutivePullFailures=t.consecutiveFailures??0,this.consecutivePushFailures=t.consecutivePushFailures??0,this.pushStreakIsConnectivity=t.pushStreakIsConnectivity??!1;let n=typeof t.pausedReason==`string`?t.pausedReason:void 0,r=n!==void 0&&bSt(n)?n:void 0;n!==void 0&&r===void 0&&n.length>0&&k9.warn({event:`paused-reason-unrecognized`,pausedReason:n},`[sync] persisted pause reason is not one this build knows — dropping it and continuing without a pause`),this.pausedReason=wSt.has(r)?void 0:r}catch(e){k9.warn({err:e},`[sync] failed to load sync state`)}}};const ASt=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function jSt(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(YG(e)||XG(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&ASt.test(n)&&(r[`mount.id`]=n);try{let e=()=>{kU(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),Ya.with($a.extract(Ya.active(),r),e)}else e()}catch(e){q(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let F9=!1;function MSt(){if(F9)return;let e=hoe;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){F9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),F9=!0}catch(e){q(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}function NSt(e,t){let n=!0,r={async afterUnloadDocument(){n&&t()}};return e.configuration.extensions.unshift(r),()=>{n=!1;let t=e.configuration.extensions,i=t.indexOf(r);i!==-1&&t.splice(i,1)}}const PSt=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),FSt=(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function ISt(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=Xo(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],PK({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return q(`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 q(`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(`
|
|
2128
|
+
`)){let e=n.startsWith(`credential.username `)?n.slice(20).trim():void 0;e&&(t=e)}return t}function cSt(e,t={}){let n=nat(e);if(!n)return{source:`active`};let r=n.host;if(n.login)return{host:r,login:n.login,source:`remote-url`};if(n.transport!==`https`)return{host:r,source:`active`};let i=(t._readCredentialUrlMatch??aSt)(oSt(e),t.cwd??process.cwd()),a=i?$it(sSt(i)):void 0;return a?{host:r,login:a,source:`credential-config`}:{host:r,source:`active`}}function lSt(e={}){let t=e.ttlMs??6e4,n=e.now??Date.now,r;return{resolve(i){let a=rat(i);if(!a)return{source:`active`};let o=n();if(r&&r.projectDir===i&&r.url===a&&r.expiresAt>o)return r.account;let s=cSt(a,{cwd:i,_readCredentialUrlMatch:e._readCredentialUrlMatch});return r={projectDir:i,url:a,account:s,expiresAt:o+t},s},invalidate(){r=void 0}}}function uSt(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}const k9=q(`sync-engine`),dSt=new Set(Wxt),A9=/^[0-9a-f]{40}$/i,fSt=$s(Jo);var j9=class extends Error{constructor(){super(`Sync paused while a Git operation is in progress or the index has unresolved conflicts`),this.name=`GitOperationInProgressError`}},pSt=class extends Error{constructor(e,t){super(`Shareable .ok subtree "${e}" could not be fully enumerated; sync staging aborted`,{cause:t}),this.name=`ShareableOkEnumerationError`}};function mSt(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 hSt(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason,...e.resolvedLogin===void 0?{}:{resolvedLogin:e.resolvedLogin},...e.declaredLogin===void 0?{}:{declaredLogin:e.declaredLogin},...e.declaredSource===void 0?{}:{declaredSource:e.declaredSource}}:{checkStatus:`unknown`,unknownError:e.error}}function gSt(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason&&e.resolvedLogin===t.resolvedLogin&&e.declaredLogin===t.declaredLogin&&e.declaredSource===t.declaredSource:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}const _St={syncScope:{pathBase:`content`}},M9={syncScope:{pathBase:`project`}},vSt=/(^|[/\\])index\.lock\b/i,ySt=new Set(ate);function bSt(e){return ySt.has(e)}const xSt=new Set([`diverged-local-commits`,`external-changes-pending`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`]),SSt=[`no-push-permission`,`auth-error`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`],CSt=new Set(SSt),wSt=new Set([...SSt,`external-changes-pending`]);function N9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function TSt(e){return new Promise(t=>{setTimeout(t,e)})}function P9(e){let t=Px(e);if(t.kind!==`repository`)return!1;let n=t.repository.readHead();return n.kind===`branch`&&t.repository.readRef(n.ref).kind===`absent`}function ESt(e){return e.class===`network`&&e.subclass!==`429`&&e.subclass!==`5xx`}function DSt(e){return e>=8?36e5:e>=5?9e5:e>=3?3e5:0}const OSt=12e4;var kSt=class{declaredGitHubHosts;state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;rootOkOutsideContentWalk;pullIntervalSeconds;pushIntervalSeconds;mode;credentialConfig;cc1Broadcaster;onStateChange;setBatchInProgress;onAutoDisable;checkpointBeforeStrandedConversion;checkpointBeforeOverlayRestore;beforeRealIndexResetRetry;mcpTomlEditor;detectGh;detectGhAccounts;ghTokenSource;ghAccountResolver;declaredAccountWarnKey;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;get lastRunUtc(){return this.lastPullOkUtc===null?this.lastPushOkUtc:this.lastPushOkUtc===null||this.lastPullOkUtc>this.lastPushOkUtc?this.lastPullOkUtc:this.lastPushOkUtc}lastPullOkUtc=null;lastPushOkUtc=null;pushCycleLanded=!1;fetchOnlyInFlight=!1;lastFetchUtc=null;lastPushedSha=null;lastPullUtc=null;lastPullOutcome=null;consecutivePullFailures=0;consecutivePushFailures=0;pushStreakIsConnectivity=!1;consecutiveContentions=0;ahead=0;behind=0;get conflictCount(){let e=0;for(let t of this.conflicts.list())TK(t)&&e++;return e}pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;indexLockHitThisCycle=!1;lastLockNoticeKind;restingIndexLockPause;blockingPaths=[];loggedSymlinkRefusal;refusedSymlinkPaths=[];currentBranch=`main`;cycleInFlight=null;hasRemote=!1;identityUnresolved=!1;statePath;conflicts;unsubscribeConflicts=null;constructor(e){this.projectDir=e.projectDir,this.declaredGitHubHosts=e.declaredGitHubHosts??I6(),this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.rootOkOutsideContentWalk=LK(U(this.contentDir,H(this.projectDir,`.ok`))).startsWith(`..`),this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.mode=e.mode??(e.syncEnabled===!0?`full`:`off`),this.credentialConfig=e.credentialConfig??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.checkpointBeforeStrandedConversion=e.checkpointBeforeStrandedConversion,this.checkpointBeforeOverlayRestore=e.checkpointBeforeOverlayRestore,this.beforeRealIndexResetRetry=e._beforeRealIndexResetRetry,this.mcpTomlEditor=e.mcpTomlEditor,this.detectGh=e.detectGh,this.detectGhAccounts=e.detectGhAccounts,this.ghTokenSource=jlt(e.detectGh),this.ghAccountResolver=lSt({_readCredentialUrlMatch:e._readCredentialUrlMatch}),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??tlt,this.statePath=W(xK(this.projectDir),`sync-state.json`),this.conflicts=e.conflicts}syncGhTarget(){let e=this.ghAccountResolver.resolve(this.projectDir);return{account:e,host:e.host??`github.com`}}resolveRelayGhToken(){let{account:e,host:t}=this.syncGhTarget(),n=this.ghTokenSource.get(t,e.login);return this.noteDeclaredAccountOutcome(e,t,n),n}noteDeclaredAccountOutcome(e,t,n){let r=e.login,i=n===null?void 0:n.login??this.activeGhLogin(t);if(!(r!==void 0&&(n===null||!F6(i,r)))){this.declaredAccountWarnKey=void 0;return}let a=`${t}\0${r}\0${e.source}\0${n===null?`none`:`fallback`}`;a!==this.declaredAccountWarnKey&&(n===null?k9.warn({host:t,declaredLogin:r,declaredSource:e.source},`[sync] declared GitHub account produced no gh token — git runs with no relayed credential`):k9.warn({host:t,declaredLogin:r,declaredSource:e.source,resolvedLogin:i},`[sync] declared GitHub account did not produce the gh token — using the active account`)),this.declaredAccountWarnKey=a}parkedOnAmbiguousNotFound(){return(this.state===`auth-error`||this.pausedReason===`auth-error`)&&(this.pushErrorCode===`auth-not-found-as-identity`||this.pullErrorCode===`auth-not-found-as-identity`)}activeGhLogin(e){if(this.detectGhAccounts)try{return this.detectGhAccounts(e)?.find(e=>e.active)?.login}catch(t){k9.warn({err:t,host:e},`[sync] detectGhAccounts failed — fallback identity stays unnamed`);return}}gitHandle(e){return bJ(this.projectDir,{credentialConfig:this.credentialConfig,gitIndexFile:e,ghToken:this.resolveRelayGhToken()??void 0,timeoutMs:12e4})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflicts.setBranch(e))}catch{}}catch(e){k9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),k9.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){k9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=Hx(this.projectDir),n=t?H(t,`MERGE_HEAD`):null,r=n!==null&&G(n);await this.conflicts.pruneMergeNativeAgainstGit();let i=()=>this.conflicts.list().some(e=>e.kind===`merge-native`);if(r&&!i()){k9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){k9.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.subscribeToConflicts(),i()){this.transitionTo(`conflict`),k9.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let a=uSt(this.lastFetchUtc,this.pullIntervalSeconds),o=uSt(this.lastPushOkUtc,this.pushIntervalSeconds);this.schedulePull(a>0?a:void 0),this.schedulePush(o>0?o:void 0),k9.info({branch:this.currentBranch,pullDelayMs:a,pushDelayMs:o},`[sync] started`)}stop(){this.unsubscribeConflicts?.(),this.unsubscribeConflicts=null,this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}setIntervals(e,t){let n=this.pullIntervalSeconds!==e,r=this.pushIntervalSeconds!==t;!n&&!r||(k9.info({pullFrom:this.pullIntervalSeconds,pullTo:e,pushFrom:this.pushIntervalSeconds,pushTo:t},`[sync] cycle intervals changed`),this.pullIntervalSeconds=e,this.pushIntervalSeconds=t,n&&this.pullTimer!==null&&this.schedulePull(),r&&this.pushTimer!==null&&this.schedulePush())}async setMode(e,t=`config`){if(this.mode===e)return;let n=this.mode;if(this.mode=e,k9.info({from:n,to:e,source:t},`[sync] mode changed`),e===`off`){this.cancelScheduledCycles(),await this.drainInFlightCycles(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}e===`follow`&&(await this.drainInFlightCycles(),this.cancelScheduledCycles(),await this.convertStrandedCommitsToOverlay()),this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(0),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}async setEnabled(e){await this.setMode(e?`full`:`off`)}cancelScheduledCycles(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null)}async drainInFlightCycles(){let e=Date.now();for(;this.cycleInFlight!==null;){if(Date.now()-e>3e4){k9.warn({cycleInFlight:this.cycleInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await tc(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||P9(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||P9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){k9.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){k9.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 yJ(()=>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,k9.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`,k9.warn({err:e},`[sync] pull-only: stranded-commit conversion failed — leaving branch as-is`)}}}async notifyCredentialsChanged(){if(this.mode!==`off`&&(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.state===`auth-error`||this.pausedReason===`auth-error`)){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(0),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){if(e===`fetch`){await this.fetchOnly();return}if(this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.consecutiveContentions=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`||this.pausedReason===`git-index-locked`||this.pausedReason===`no-commits-yet`)&&(this.pausedReason=void 0,this.clearPullError()),this.parkedOnAmbiguousNotFound()&&(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()),this.probePushPermissionInternal(`refresh`),e===`pull`){await this.pullOnce();return}if(e===`push`){await this.pushOnce();return}this.state===`dormant`||this.state===`conflict`||this.state===`auth-error`?k9.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}`):k9.info({op:e,state:this.state},`[sync] trigger(${e}) running`),await this.pushOnce(),await this.pullOnce(`sync`)}async pushOnce(){if(this.mode===`full`){await this.runPushCycle();return}await this.runOneShotPush()}async runOneShotPush(){if(this.cycleInFlight!==null){k9.info({cycleInFlight:this.cycleInFlight},`[sync] one-shot push refused — a cycle is already in flight`);return}if(this.state===`conflict`||this.state===`auth-error`){k9.info({state:this.state},`[sync] one-shot push refused — state=${this.state}`);return}if(this.conflictCount>0){k9.info({conflictCount:this.conflictCount},`[sync] one-shot push refused — unresolved conflicts hold the tree`);return}if(!this.hasRemote){k9.info({hasRemote:!1},`[sync] one-shot push refused — no remote`);return}if(P9(this.projectDir)){this.noteUnbornHeadRefusal();return}this.clearUnbornHeadPause();let e=this.state;this.cycleInFlight=`push`,this.beginIndexLockWatch(`push`);try{await this.doPushCycle(1)}finally{this.cycleInFlight=null,this.settleIndexLockPause(`push`),this.pushCycleLanded&&this.markRun();let t=this.currentState();t!==`conflict`&&t!==`auth-error`&&this.transitionTo(e),this.cc1Broadcaster?.signal(`sync-status`)}}async fetchOnly(){if(!this.hasRemote||P9(this.projectDir)||this.cycleInFlight!==null||this.fetchOnlyInFlight)return!1;this.fetchOnlyInFlight=!0;let e=this.gitHandle();try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.scheduleSaveState()}catch(e){return k9.debug({err:e},`[sync] panel-open fetch failed — counts left as they were`),!1}finally{this.fetchOnlyInFlight=!1}return await this.refreshDivergenceCounts(e),this.cc1Broadcaster?.signal(`sync-status`),!0}async refreshDivergenceCounts(e){try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch(e){k9.debug({err:e},`[sync] divergence-count refresh failed — keeping previous counts`)}}async pullOnce(e=`explicit`){let t=this.mode,n=await this.runOneShotPull(e);return k9.info({mode:t,outcome:n},`[sync] one-shot pull complete`),n}async runOneShotPull(e){if(this.cycleInFlight!==null)return k9.info({cycleInFlight:this.cycleInFlight},`[sync] one-shot pull refused — a cycle is already in flight`),this.recordPullOutcome(`refused`);if(this.state===`conflict`)return k9.info({state:this.state},`[sync] one-shot pull refused — the conflict resolver holds the tree`),this.recordPullOutcome(`refused`);if(!this.hasRemote||P9(this.projectDir))return k9.info({hasRemote:this.hasRemote},`[sync] one-shot pull refused — no remote, or no commits yet`),this.recordPullOutcome(`refused`);this.clearUnbornHeadPause();let t=this.mode,n=this.state,r=this.pausedReason;this.cycleInFlight=`pull`,this.beginIndexLockWatch(`pull`);try{return this.recordPullOutcome(await this.doPullCycle(e))}finally{this.cycleInFlight=null,this.settleIndexLockPause(`pull`),t===`off`?(xSt.has(this.pausedReason)||xSt.has(r)||(this.pausedReason=r),this.transitionTo(n)):this.schedulePull()}}recordPullOutcome(e){return this.lastPullUtc=new Date().toISOString(),this.lastPullOutcome=e,(e===`succeeded`||e===`up-to-date`||e===`conflict`)&&(this.lastPullOkUtc=new Date().toISOString(),this.saveStateNow()),this.cc1Broadcaster?.signal(`sync-status`),e}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastRunUtc:this.lastRunUtc,lastPullOkUtc:this.lastPullOkUtc,lastPushOkUtc:this.lastPushOkUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,lastPullUtc:this.lastPullUtc,lastPullOutcome:this.lastPullOutcome,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutivePullFailures,consecutivePushFailures:this.consecutivePushFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.mode!==`off`,syncMode:this.mode,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?oat(this.projectDir,this.declaredGitHubHosts):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.blockingPathsForStatus().length>0?{blockingPaths:this.blockingPathsForStatus()}:{},...this.pausedReason===`unsafe-incoming-symlinks`&&this.refusedSymlinkPaths.length>0?{refusedSymlinkPaths:this.refusedSymlinkPaths.slice(0,50)}:{},...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}blockingPathsForStatus(){return this.pausedReason===`external-changes-pending`?this.blockingPaths.slice(0,50):[]}getBlockingPaths(){return this.pausedReason===`external-changes-pending`?[...this.blockingPaths]:[]}async commitBlockingPaths(){let e=this.getBlockingPaths();if(e.length===0)return null;let t=this.gitHandle();return yJ(async()=>{await this.applyCommitIdentity(t);try{if(await t.git.raw([`add`,...Fn(e)]),(await pW(t.git,[`diff`,`--cached`,`--name-only`,...Fn(e)])).length===0)return null;await t.git.raw([`commit`,`-m`,`Commit local changes before syncing`,...Fn(e)])}catch(n){throw await t.git.raw([`reset`,...Fn(e)]).catch(t=>{k9.warn({resetErr:t,files:e.length},`[sync] blocking-path index reset failed; paths may remain staged`)}),k9.error({err:n,files:e.length},`[sync] commit of blocking paths failed`),n}let n=(await t.git.revparse(`HEAD`)).trim();return this.clearBlockingPause(),k9.info({files:e.length},`[sync] committed overlapping paths at user request`),n})}clearBlockingPause(){this.blockingPaths=[],this.pausedReason=void 0,this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await Bot(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async applyCommitIdentity(e){let t=await Bot(this.projectDir),n=t===null;this.identityUnresolved!==n&&(this.identityUnresolved=n,this.cc1Broadcaster?.signal(`sync-status`));let r=t?.name??`OpenKnowledge`,i=t?.email??`sync@open-knowledge.local`;eZe(e,{GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i})}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=L6(this.projectDir,this.declaredGitHubHosts);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,gSt(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,k9.info({caller:e,host:t.host,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let{account:n}=this.syncGhTarget(),r;try{r=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,transport:t.transport,account:n,detectGh:this.detectGh,detectGhAccounts:this.detectGhAccounts,tokenStore:this.tokenStore})}catch(t){k9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),r={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let i=hSt(r),a=this.pushPermission;this.pushPermission=i;let o=!1;return i.checkStatus===`denied`&&this.mode===`full`&&this.parkedOnAmbiguousNotFound()&&k9.info({reason:i.deniedReason,caller:e},`[sync] probe denial not applied — repository-not-found park is the more specific diagnosis`),i.checkStatus===`denied`&&this.mode===`full`&&!this.parkedOnAmbiguousNotFound()?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),o=!0,k9.info({reason:i.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):i.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),o=!0,k9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!o&&!gSt(a,i)&&this.cc1Broadcaster?.signal(`sync-status`),i}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,k9.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(!G(H(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return k9.warn({err:e},`[sync] remote detection failed`),!1}}subscribeToConflicts(){this.unsubscribeConflicts===null&&(this.unsubscribeConflicts=this.conflicts.subscribe(()=>{let e=this.conflicts.list().some(e=>e.kind===`merge-native`);if(e&&this.state!==`conflict`){this.transitionTo(`conflict`),this.scheduleSaveState();return}!e&&this.state===`conflict`&&(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush(),this.scheduleSaveState())}))}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflicts.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush(0)))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{k9.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){if(this.mode!==`full`)return;this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??this.effectivePushDelayMs();this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{k9.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=DSt(this.consecutivePullFailures),t=e>0?e/1e3:0;return N9(Math.max(t,this.pullIntervalSeconds))}effectivePushDelayMs(){let e=DSt(this.consecutivePushFailures),t=e>0?e/1e3:0;return N9(Math.max(t,this.pushIntervalSeconds))}logContention(){let e={consecutiveContentions:this.consecutiveContentions,consecutivePushFailures:this.consecutivePushFailures,releasedConnectivityStreak:this.pushStreakIsConnectivity};this.consecutiveContentions>=3?k9.warn(e,`[sync] push repeatedly losing to remote contention — not backing off by design`):k9.info(e,`[sync] push still rejected after retry (contention) — scheduling next push at base cadence`)}bumpFailureCount(e,t=!1){e===`push`?(this.consecutiveContentions=0,this.consecutivePushFailures++,this.pushStreakIsConnectivity=(this.consecutivePushFailures===1||this.pushStreakIsConnectivity)&&t):this.consecutivePullFailures++}async runPullCycle(){if(this.cycleInFlight!==null){this.cycleInFlight===`push`&&this.pullTimer===null&&this.schedulePull();return}if(this.state!==`dormant`&&this.state!==`disabled`&&this.state!==`auth-error`){if(this.state===`conflict`){this.schedulePull();return}if(P9(this.projectDir)){this.schedulePull();return}this.clearUnbornHeadPause(),this.cycleInFlight=`pull`,this.beginIndexLockWatch(`pull`);try{this.recordPullOutcome(await this.doPullCycle(this.mode===`full`?`sync`:`explicit`))}finally{this.cycleInFlight=null,this.settleIndexLockPause(`pull`),this.schedulePull()}}}async doPullCycle(e){if(this.pausedReason===`git-operation-in-progress`)try{await this.assertNoGitOperationInProgress()}catch(e){return e instanceof j9?(this.handleGitOperationRefusal(e,`pull`),`refused`):(this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`)}let t=this.gitHandle(),n;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!e||e===`HEAD`)return this.transitionTo(`disabled`),this.pausedReason=`detached-head`,k9.warn({},`[sync] detached HEAD — pausing sync`),`refused`;n=e,this.currentBranch=n}catch(e){return this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.transitionTo(`fetching`);try{await t.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutivePullFailures=0,this.clearPullError(),this.consecutivePushFailures>0&&this.pushStreakIsConnectivity&&(k9.info({cleared:this.consecutivePushFailures},`[sync] fetch succeeded — releasing connectivity-class push backoff`),this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.schedulePush())}catch(e){let t=w9(e instanceof Error?e:Error(String(e)));return this.handleError(t,`pull`),`error`}await this.refreshDivergenceCounts(t);let r=``;if(this.behind>0&&(e===`explicit`?this.ahead===0:this.conflictCount===0))try{r=await this.validateIncomingSymlinks(t,n)}catch(e){return e instanceof eY?(this.handleIncomingSymlinkRefusal(e,`pull`),`refused`):(this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`)}else this.behind===0&&this.clearIncomingSymlinkPause();if(this.behind>0&&e===`explicit`){let e=await this.doPullCycleB1(t,n,r);return this.scheduleSaveState(),e}if(this.behind>0&&this.conflictCount===0){this.pausedReason===`diverged-local-commits`&&(this.pausedReason=void 0),this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);let e=!0,i=!0;try{await this.commitDirtyContentFilesToHead(t,`pull`),await this.validateIncomingSymlinks(t,n,r);let a=await this.prepareForMerge(t,n,r);if(!a.proceed)return`refused`;try{await this.applyCommitIdentity(t),await this.mergeIncomingCommit(t,n,r),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.pausedReason===`external-changes-pending`&&this.clearBlockingPause(),this.transitionTo(`idle`)}finally{a.needsStashPop&&(e=await this.popPreMergeStash(t)),i=this.restoreReconciledMcpOverlays(a.reconciled)}if(!e)throw Error(`failed to replay pre-merge working-tree state`);if(!i)throw Error(`failed to restore reconciled MCP overlays`);return await this.persistReconciledMcpEntries(a.reconciled),this.scheduleSaveState(),`succeeded`}catch(t){if(t instanceof j9)return this.handleGitOperationRefusal(t,`pull`),`refused`;if(t instanceof eY)return this.handleIncomingSymlinkRefusal(t,`pull`),`refused`;if(t instanceof rY&&e&&i)return k9.info({branch:n,incoming:r,ref:t.ref},`[sync] incoming commit moved after inspection; re-inspecting next cycle`),this.transitionTo(`idle`),`refused`;let a=t instanceof rY?Error(e?`failed to restore reconciled MCP overlays`:`failed to replay pre-merge working-tree state`):t,o=w9(a instanceof Error?a:Error(String(a)));return o.class===`semantic`&&o.subclass===`merge-conflict`?(await this.handleMergeConflict(),this.state===`conflict`?`conflict`:this.pullError?`error`:`succeeded`):(this.handleError(o,`pull`),`error`)}finally{this.setBatchInProgress?.(!1)}}return this.transitionTo(`idle`),this.scheduleSaveState(),this.behind===0?`up-to-date`:`conflict`}async doPullCycleB1(e,t,n){if(this.transitionTo(`pulling`),this.ahead>0)return this.clearPullError(),this.pausedReason=`diverged-local-commits`,this.transitionTo(`idle`),k9.warn({ahead:this.ahead,behind:this.behind},`[sync] pull-only: local history diverged — not fast-forwardable, skipping cycle`),`refused`;let r,i;try{r=(await e.git.revparse([`HEAD`])).trim();let t=await pW(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await pW(e.git,[`diff`,`--name-only`,`HEAD..${n}`]));i=t.filter(e=>a.has(e))}catch(e){return this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`}let a=new Map;for(let e of this.conflicts.list())e.kind===`working-tree`&&a.set(e.file,e);let o;try{o=await this.planOverlapReconciliation(e,n,r,i,a)}catch(e){return this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.setBatchInProgress?.(!0);try{if(i.length>0){try{await this.checkpointBeforeOverlayRestore?.({branch:t,paths:i.length})}catch(e){k9.warn({err:e,paths:i.length},`[sync] pull-only: overlay checkpoint failed before restore — proceeding`)}try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,...Fn(i)])}catch(e){return k9.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`}}let r=await this.fastForwardOnly(e,n);if(!r.ok){try{this.applyOverlayPlan(o.mineRestore,o.deletions)}catch(e){return k9.error({err:e,refusal:r.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`}return r.timedOut?(k9.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(w9(Error(`git merge --ff-only timed out after ${OSt}ms`)),`pull`),`error`):(r.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),k9.warn({refusal:r.refusal,stderr:r.stderr.slice(0,200)},`[sync] pull-only: fast-forward refused — skipping cycle`),`refused`)}try{this.applyOverlayPlan(o.writes,o.deletions)}catch(e){return k9.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError(w9(e instanceof Error?e:Error(String(e))),`pull`),`error`}for(let e of o.upserts)this.conflicts.raise(e);for(let e of o.dissolved)this.conflicts.dissolveWorkingTree(e);this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.clearPullError(),this.pausedReason=void 0,this.blockingPaths=[],this.transitionTo(`idle`);let a=await this.countStandingOverlay(e);return k9.info({created:o.newConflicts.length,autoCombined:o.autoCombined.length,autoDissolved:o.dissolved.length,autoRestored:o.autoRestored.length,overlayStock:a},`[sync] pull-only: fast-forwarded to origin tip`),o.newConflicts.length>0?`conflict`:`succeeded`}finally{this.setBatchInProgress?.(!1)}}async fastForwardOnly(e,t){try{return await fSt(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,t],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:OSt}),{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:mSt({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(!G(H(this.projectDir,p))){try{await e.git.revparse([`${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),k9.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=K(H(this.projectDir,p))}catch{continue}o.push({path:p,bytes:h});let g=h.toString(`utf-8`),_=null;try{_=await e.git.raw([`show`,`${t}:${p}`])}catch(e){this.classifyRefReadFailure(e)===`error`&&k9.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&&dSt.has(p)){let t=await this.readMcpGitBlob(e,n,p),r=rSt({target:p,layers:{base:t,head:t,index:await this.readMcpGitBlob(e,``,p),worktree:g,incoming:_},tomlEditor:this.mcpTomlEditor});if(r.kind===`resolved`){r.raw!==_&&a.push({path:p,bytes:Buffer.from(r.raw,`utf8`)}),k9.info({event:`mcp-config-reconcile`,target:p,outcome:`auto-resolved`},`[sync] pull-only: auto-resolved OpenKnowledge MCP entry overlap`);continue}r.kind===`declined`&&k9.warn({event:`mcp-config-reconcile`,target:p,outcome:`declined`,reason:r.reason},`[sync] pull-only: declined OpenKnowledge MCP entry reconciliation`)}if(_===null||!this.isContentConflictPath(p)){a.push({path:p,bytes:h});continue}let v=m?r.baseSha:await this.gitBlobSha(e,`${n}:${p}`),y=v?await this.gitBlobContent(e,v):``,b=Qne(y,g,_);if(b.clean){a.push({path:p,bytes:Buffer.from(b.merged,`utf-8`)}),d.push(p),m&&l.push(p);continue}a.push({path:p,bytes:h});let x=await this.gitBlobSha(e,`${t}:${p}`);if(x===void 0){k9.warn({path:p},`[sync] pull-only: could not pin origin blob for a collision — keeping overlay, deferring`);continue}c.push({kind:`working-tree`,file:p,theirsSha:x,...v===void 0?{}:{baseSha:v}}),m||u.push(p)}return{writes:a,mineRestore:o,deletions:s,upserts:c,dissolved:l,newConflicts:u,autoCombined:d,autoRestored:f}}applyOverlayPlan(e,t){let n={allowShareableOkArtifact:aq};for(let{path:t,bytes:r}of e)$U(kY(H(this.projectDir,t),this.projectDir,n),r);for(let e of t){let t=H(this.projectDir,e);kY(t,this.projectDir,n);try{iW(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=H(this.projectDir,e),n=LK(U(this.contentDir,t));return!n.startsWith(`..`)&&FG(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 pW(e.git,[`diff-index`,`--name-only`,`HEAD`])).filter(e=>this.isContentConflictPath(e)).length}catch{return null}}async runPushCycle(){if(this.mode===`full`&&this.state!==`dormant`&&this.state!==`disabled`&&this.state!==`conflict`&&this.state!==`auth-error`){if(this.conflictCount>0){this.schedulePush();return}if(P9(this.projectDir)){this.hasRemote&&this.noteUnbornHeadRefusal(),this.schedulePush();return}if(this.clearUnbornHeadPause(),this.cycleInFlight!==null){this.cycleInFlight===`pull`&&this.pushTimer===null&&this.schedulePush();return}if(this.pausedReason===`unsafe-incoming-symlinks`){this.schedulePush();return}this.cycleInFlight=`push`,this.beginIndexLockWatch(`push`);try{await this.doPushCycle(1)}finally{this.cycleInFlight=null,this.settleIndexLockPause(`push`),this.pushCycleLanded&&this.markRun(),this.schedulePush()}}}async doPushCycle(e=0){this.pushCycleLanded=!1;let t=H(Ps(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),n=null;try{let e=this.gatherContentFilesSync(),r=await this.snapshotPromisedPaths(),i=new Set;await yJ(async()=>{await this.assertNoGitOperationInProgress(),this.transitionTo(`pushing`);try{let r=this.gitHandle(t);if(P9(this.projectDir)){k9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let a;try{a=(await r.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){k9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(w9(e instanceof Error?e:Error(String(e))),`push`);return}await r.git.raw([`read-tree`,a]);let o=await this.listHeadContentPaths(r,a),s=await this.stageContentFiles(r,e),c=new Set(s.map(e=>e.projectRelPath)),l=[...o].filter(e=>!c.has(e));await this.removePathsFromIndex(r,l);let u=(await r.git.raw([`write-tree`])).trim(),d=``;try{d=(await r.git.raw([`rev-parse`,`${a}^{tree}`])).trim()}catch{}if(d&&d===u){let t=null;try{t=(await r.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(t===a){k9.info({contentFileCount:e.length,headSha:a},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=a,this.lastSyncUtc=new Date().toISOString(),this.pushCycleLanded=!0,this.consecutivePushFailures=0,this.consecutiveContentions=0,this.pushStreakIsConnectivity=!1,this.clearPushError(),this.transitionTo(`idle`);return}k9.info({headSha:a,upstreamSha:t},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let i=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),i=!0}catch{}i?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=a;return}let f=[],p=[];try{let t=await pW(r.git,[`diff-tree`,`--name-only`,`-r`,a,u]);if(t.length>0){let n=new Map(e.map(e=>[e.projectRelPath,e.contentRelPath]));for(let e of t){f.push(e);let t=n.get(e)??LK(U(this.contentDir,H(this.projectDir,e)));t&&!t.startsWith(`..`)&&p.push(t)}}}catch{f=e.map(e=>e.projectRelPath).concat(l),p=e.map(e=>e.contentRelPath)}let m=this.buildCommitMessage(p);await this.applyCommitIdentity(r);let h=(await r.git.raw([`commit-tree`,u,`-p`,a,`-m`,m])).trim();if(!h||!A9.test(h)){k9.warn({raw:h},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await r.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,h,a]),await this.resetRealIndexForPaths(f,`push`);for(let e of f)i.add(e);let g=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),g=!0}catch{}g?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=h}finally{await this.healStaleRealIndex(r,i)}}),n&&(this.lastPushedSha=n,this.lastSyncUtc=new Date().toISOString(),this.pushCycleLanded=!0,this.ahead=0,this.consecutivePushFailures=0,this.consecutiveContentions=0,this.pushStreakIsConnectivity=!1,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){if(t instanceof j9){this.handleGitOperationRefusal(t,`push`);return}let n=t instanceof Error?t:Error(String(t));n instanceof pSt&&k9.warn({err:n},`[sync] push cycle: staging error detail`);let r=w9(n);if(r.class===`semantic`&&r.subclass===`non-fast-forward`){if(e>0){k9.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);let t=`fetch`,n=!0,r=!0;try{await e.git.fetch(`origin`);let i=await this.validateIncomingSymlinks(e,this.currentBranch);t=`push`,await this.commitDirtyContentFilesToHead(e,`push`),t=`fetch`,await this.validateIncomingSymlinks(e,this.currentBranch,i),t=`push`;let a=await this.prepareForMerge(e,this.currentBranch,i);if(!a.proceed){this.setBatchInProgress?.(!1);return}try{await this.applyCommitIdentity(e),t=`merge`,await this.mergeIncomingCommit(e,this.currentBranch,i),t=`push`}finally{a.needsStashPop&&(n=await this.popPreMergeStash(e)),r=this.restoreReconciledMcpOverlays(a.reconciled)}if(!n)throw Error(`failed to replay pre-merge working-tree state`);if(!r)throw Error(`failed to restore reconciled MCP overlays`);await this.persistReconciledMcpEntries(a.reconciled)}catch(e){if(e instanceof j9){this.handleGitOperationRefusal(e,`push`);return}if(e instanceof eY){this.handleIncomingSymlinkRefusal(e,`push`);return}if(e instanceof rY&&n&&r){k9.info({ref:e.ref},`[sync] push retry: incoming commit moved after inspection; re-inspecting next cycle`),this.state===`pushing`&&this.transitionTo(`idle`),this.scheduleSaveState();return}let i=e instanceof rY?Error(n?`failed to restore reconciled MCP overlays`:`failed to replay pre-merge working-tree state`):e,a=w9(i instanceof Error?i:Error(String(i)));if(a.class===`semantic`&&a.subclass===`merge-conflict`)await this.handleMergeConflict();else{let n=t===`merge`||t===`fetch`?`pull`:`push`;k9.warn({err:e,stage:t},`[sync] push retry error detail`),this.handleError(a,n)}this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}this.consecutiveContentions++,this.logContention(),this.pushStreakIsConnectivity&&(this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.clearPushError()),this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(r,`push`)}finally{try{Ds(t)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e,t){if(await this.assertNoGitOperationInProgress(),(await e.git.status()).files.length===0)return null;let n=(await e.git.revparse(`HEAD`)).trim(),r=this.gatherContentFilesSync(),i=await this.listHeadContentPaths(e,n);if(r.length===0&&i.size===0)return null;let a=H(Ps(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),o=this.gitHandle(a);try{await o.git.raw([`read-tree`,n]);let a=await this.stageContentFiles(o,r),s=new Set(a.map(e=>e.projectRelPath)),c=[...i].filter(e=>!s.has(e));await this.removePathsFromIndex(o,c);let l=(await o.git.raw([`write-tree`])).trim();if(l===(await o.git.raw([`rev-parse`,`${n}^{tree}`])).trim())return null;let u=[];try{u=await pW(o.git,[`diff-tree`,`--name-only`,`-r`,n,l])}catch{u=r.map(e=>e.projectRelPath).concat(c)}await this.applyCommitIdentity(o);let d=(await o.git.raw([`commit-tree`,l,`-p`,n,`-m`,`Auto-save: interim before merge`])).trim();return!d||!A9.test(d)?(k9.warn({raw:d},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,d,n]),await this.resetRealIndexForPaths(u,t,e),d)}finally{try{Ds(a)}catch{}}}async readMcpGitBlob(e,t,n){try{return await e.git.raw([`cat-file`,`-e`,`${t}:${n}`]),await e.git.raw([`show`,`${t}:${n}`])}catch{return null}}async planTrackedMcpOverlap(e,t,n){let r;try{r=(await e.git.raw([`merge-base`,`HEAD`,t])).trim()}catch(e){return k9.warn({err:e,incomingCommit:t,path:n},`[sync] MCP reconciliation merge-base unavailable — declining`),{kind:`declined`,reason:`merge-base-unavailable`}}let[i,a,o,s]=await Promise.all([this.readMcpGitBlob(e,r,n),this.readMcpGitBlob(e,`HEAD`,n),this.readMcpGitBlob(e,``,n),this.readMcpGitBlob(e,t,n)]),c=null;try{c=K(H(this.projectDir,n),`utf8`)}catch{}return rSt({target:n,layers:{base:i,head:a,index:o,worktree:c,incoming:s},tomlEditor:this.mcpTomlEditor})}async prepareForMerge(e,t,n){let r=[],i;try{i=await pW(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return k9.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1,reconciled:r}}if(i.length===0)return{proceed:!0,needsStashPop:!1,reconciled:r};let a;try{a=new Set(await pW(e.git,[`diff`,`--name-only`,`HEAD..${n}`]))}catch(e){return k9.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1,reconciled:r}}let o=i.filter(e=>a.has(e)),s=dSt,c=o.filter(e=>s.has(e));if(c.length>0){let t=await Promise.all(c.map(async t=>({path:t,plan:await this.planTrackedMcpOverlap(e,n,t)}))),i=t.find(({plan:e})=>e.kind===`declined`),a=o.some(e=>!s.has(e));if(!i&&!a){for(let{path:e,plan:n}of t)n.kind===`resolved`&&(r.push({path:e,raw:n.raw,winnerEntry:n.winnerEntry}),k9.info({event:`mcp-config-reconcile`,target:e,outcome:`auto-resolved`},`[sync] auto-resolved OpenKnowledge MCP entry overlap`));o=o.filter(e=>!s.has(e))}else i?k9.warn({event:`mcp-config-reconcile`,target:i.path,outcome:`declined`,reason:i.plan.kind===`declined`?i.plan.reason:void 0},`[sync] declined OpenKnowledge MCP entry reconciliation`):a&&k9.info({event:`mcp-config-reconcile`,targets:c,outcome:`suppressed`,reason:`other-blocking-path`},`[sync] suppressed MCP entry reconciliation because another path blocks the merge`)}if(o.length>0){let e=o.slice(0,3).join(`, `),t=o.length>3?`, +${o.length-3} more`:``;return this.blockingPaths=o,this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutivePullFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),k9.warn({files:o},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1,reconciled:[]}}if(r.length>0)try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,...Fn(r.map(e=>e.path))])}catch(e){return k9.warn({err:e},`[sync] could not isolate reconciled MCP paths from pre-merge stash`),this.pullError=`Sync paused — OpenKnowledge could not safely isolate local MCP launcher changes before merging.`,this.pausedReason=`external-changes-pending`,this.blockingPaths=[],this.transitionTo(`idle`),this.scheduleSaveState(),{proceed:!1,needsStashPop:!1,reconciled:[]}}let l=new Set(r.map(e=>e.path));if(i.every(e=>l.has(e)))return{proceed:!0,needsStashPop:!1,reconciled:r};let u=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,u])}catch(e){return k9.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1,reconciled:r}}return{proceed:!0,needsStashPop:!0,reconciled:r}}restoreReconciledMcpOverlays(e){let t=!0;for(let n of e)try{let e=kY(H(this.projectDir,n.path),this.projectDir),t=null;try{t=K(e,`utf8`)}catch(e){k9.warn({err:e,path:n.path},`[sync] could not read MCP config before restoring reconciled overlay`)}t!==n.raw&&$U(e,n.raw,`utf8`)}catch(e){t=!1,k9.warn({err:e,path:n.path},`[sync] could not restore reconciled MCP overlay`)}return t}async popPreMergeStash(e){try{return await e.git.raw([`stash`,`pop`]),!0}catch(e){return k9.warn({err:e},`[sync] stash pop failed — stash remains on stack`),!1}}async assertNoGitOperationInProgress(){if(this.hasGitOperationInProgress()||(await pW(this.gitHandle().git,[`diff`,`--name-only`,`--diff-filter=U`])).length>0||this.hasGitOperationInProgress())throw new j9;this.pausedReason===`git-operation-in-progress`&&(this.pausedReason=void 0,this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}handleGitOperationRefusal(e,t){this.state===`conflict`||this.conflictCount>0?this.transitionTo(`conflict`):(this.pausedReason=`git-operation-in-progress`,t===`push`?this.clearPushError():this.clearPullError(),(this.state===`pushing`||this.state===`pulling`||this.state===`fetching`)&&this.transitionTo(`idle`)),k9.error({event:`git-operation-refusal`,err:e,op:t,branch:this.currentBranch},`[sync] cycle refused because a Git operation holds the tree — finish or abort it to resume sync`),this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}async validateIncomingSymlinks(e,t,n){let r=`refs/remotes/origin/${t}`,i=n;try{i??=await QJ(e.git,r),await tY(e.git,i,`merge`,e.env)}catch(e){let n=e instanceof eY?e.unsafe.slice(0,50):null,a=n===null?void 0:JSON.stringify([i,n]);throw n!==null&&a!==this.loggedSymlinkRefusal&&(this.loggedSymlinkRefusal=a,k9.warn({event:`unsafe-incoming-symlinks`,branch:t,incoming:i,links:n},`[sync] refusing incoming changes with unsafe symlinks until they are fixed`)),n===null&&k9.warn({err:e,branch:t,trackingRef:r,incoming:i},`[sync] incoming symlink inspection failed`),e}return this.clearIncomingSymlinkPause(),i}handleIncomingSymlinkRefusal(e,t){this.pausedReason=`unsafe-incoming-symlinks`,this.refusedSymlinkPaths=e.displayPaths(),t===`push`?this.clearPushError():this.clearPullError(),(this.state===`pushing`||this.state===`pulling`||this.state===`fetching`)&&this.transitionTo(`idle`),this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}clearIncomingSymlinkPause(){this.loggedSymlinkRefusal=void 0,this.pausedReason===`unsafe-incoming-symlinks`&&(this.pausedReason=void 0,this.refusedSymlinkPaths=[],this.cc1Broadcaster?.signal(`sync-status`))}async mergeIncomingCommit(e,t,n){let r=`origin/${t}`;try{await oY(e.git,{name:r,trackingRef:`refs/remotes/${r}`,commit:n})}catch(e){throw e instanceof iY&&k9.warn({event:`incoming-ref-shadowed`,shadowedName:e.shadowedName,incoming:n},`[sync] another ref shadows the incoming branch name; delete it locally and on the remote`),e}await e.git.merge([r])}hasGitOperationInProgress(){let e=Hx(this.projectDir);return!e||[`MERGE_HEAD`,`CHERRY_PICK_HEAD`,`REVERT_HEAD`,`rebase-merge`,`rebase-apply`].some(t=>G(H(e,t)))}async persistReconciledMcpEntries(e){if(e.length!==0){if(this.hasGitOperationInProgress())throw new j9;await yJ(async()=>{let t=H(Ps(),`ok-mcp-sync-idx-${process.pid}-${Date.now()}.idx`),n=[];try{let r=this.gitHandle(),i=this.gitHandle(t),a=(await i.git.revparse(`HEAD`)).trim(),o=(await i.git.revparse([`--abbrev-ref`,`HEAD`])).trim();if(o===`HEAD`)throw Error(`refusing MCP entry commit on detached HEAD`);await i.git.raw([`read-tree`,a]);let s=[];for(let r=0;r<e.length;r++){let o=e[r];if(!o)continue;let c=await this.readMcpGitBlob(i,a,o.path);if(c===null)throw Error(`tracked MCP path disappeared: ${o.path}`);let l=eSt({target:o.path,raw:c,entry:o.winnerEntry,tomlEditor:this.mcpTomlEditor});if(l===null)throw Error(`cannot edit tracked MCP path: ${o.path}`);let u=(await i.git.raw([`ls-tree`,a,...Fn([o.path])])).match(/^(100644|100755)\s/)?.[1];if(!u)throw Error(`unsafe tracked MCP mode: ${o.path}`);let d=`${t}.commit-${r}`;n.push(d),Os(d,l,`utf8`);let f=(await i.git.raw([`hash-object`,`-w`,d])).trim();await i.git.raw([`update-index`,`--add`,`--cacheinfo`,`${u},${f},${o.path}`]);let p=tSt({target:o.path,raw:l,tomlEditor:this.mcpTomlEditor}),m=tSt({target:o.path,raw:o.raw,tomlEditor:this.mcpTomlEditor}),h=p!==null&&p===m?l:o.raw,g=`${t}.replay-${r}`;n.push(g),Os(g,h,`utf8`);let _=(await i.git.raw([`hash-object`,`-w`,g])).trim();s.push({path:o.path,mode:u,blobSha:_,raw:h})}let c=(await i.git.raw([`write-tree`])).trim();if(c===(await i.git.raw([`rev-parse`,`${a}^{tree}`])).trim())return;await this.applyCommitIdentity(i);let l=(await i.git.raw([`commit-tree`,c,`-p`,a,`-m`,`Update OpenKnowledge MCP launcher`])).trim();if(!A9.test(l))throw Error(`commit-tree returned an invalid SHA`);try{await i.git.raw([`update-ref`,`refs/heads/${o}`,l,a])}catch(e){k9.info({event:`mcp-config-reconcile`,outcome:`ref-race`,branch:o,err:e},`[sync] skipped MCP launcher commit because the branch moved`);return}try{for(let e of s){await r.git.raw([`update-index`,`--add`,`--cacheinfo`,`${e.mode},${e.blobSha},${e.path}`]);let t=kY(H(this.projectDir,e.path),this.projectDir);K(t,`utf8`)!==e.raw&&$U(t,e.raw,`utf8`)}}catch(t){k9.warn({event:`mcp-config-reconcile`,outcome:`overlay-replay-failed`,err:t},`[sync] MCP overlay replay failed; resetting the affected index entries`),await this.resetRealIndexForPaths(s.map(e=>e.path),`mcp-reconcile`),this.restoreReconciledMcpOverlays(e)}k9.info({event:`mcp-config-reconcile`,outcome:`persisted-entry-commit`},`[sync] persisted OpenKnowledge MCP launcher entry commit`)}finally{for(let e of n)try{Ds(e)}catch{}try{Ds(t)}catch{}}})}}async stageContentFiles(e,t){if(t.length===0)return t;let n=new Set,r=!0;for(let i=0;i<t.length;i+=100){let a=t.slice(i,i+100).map(e=>e.projectRelPath);try{let t=await pW(e.git,[`ls-files`,`--others`,`--ignored`,`--exclude-standard`,...Fn(a)]);for(let e of t)n.add(e)}catch(e){r=!1,k9.warn({err:e},`[sync] ignored-path probe failed — staging unfiltered without -f`)}}n.size>0&&k9.info({count:n.size,sample:[...n].slice(0,5)},`[sync] skipping gitignored untracked path(s) — in content scope but excluded from git`);let i=[...n].filter(e=>e.endsWith(`/`)),a=e=>n.has(e)||i.some(t=>e.startsWith(t)),o=r?t.filter(e=>!a(e.projectRelPath)):t,s=e=>e.startsWith(`.ok/`)||e.includes(`/.ok/`),c=r?o.filter(e=>s(e.projectRelPath)):[],l=r?o.filter(e=>!s(e.projectRelPath)):o;for(let[t,n]of[[[`add`],l],[[`add`,`-f`],c]])for(let r=0;r<n.length;r+=100){let i=n.slice(r,r+100).map(e=>e.projectRelPath);await e.git.raw([...t,...Fn(i)])}return o}gatherContentFilesSync(){let e=[],t=(e,t)=>{throw new pSt(LK(U(this.projectDir,t))||`.`,e)},n=(r,i,a,o)=>{let s;try{s=xs(r,{withFileTypes:!0})}catch(e){o?.(e,r);return}for(let c of s){let s=H(r,c.name);if(c.isDirectory()){let e=LK(U(i,s));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e,a))continue;let r=e.split(`/`).some(e=>e.toLowerCase()===`.ok`);n(s,i,a,o??(r?t:void 0))}else if(c.isFile()||c.isSymbolicLink()){let t=LK(U(i,s));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t,a)){let t=LK(U(this.contentDir,s)),n=LK(U(this.projectDir,s));e.push({contentRelPath:t,projectRelPath:n})}}}};if(G(this.contentDir)&&n(this.contentDir,this.contentDir,_St),this.rootOkOutsideContentWalk){let e=H(this.projectDir,`.ok`);G(e)&&!this.contentFilter.isDirExcluded(`.ok`,M9)&&n(e,this.projectDir,M9,t)}return e}isSyncScopedPath(e){let t=H(this.projectDir,e),n=LK(U(this.contentDir,t)),r=!n.startsWith(`..`)&&!this.contentFilter.isExcluded(n,_St),i=this.rootOkOutsideContentWalk&&e.startsWith(`.ok/`)&&!this.contentFilter.isExcluded(e,M9);return r||i}async listHeadContentPaths(e,t){let n=new Set;try{let r=await pW(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r)this.isSyncScopedPath(e)&&n.add(e)}catch{}return n}async removePathsFromIndex(e,t){if(t.length===0)return;let n=[...new Set(t)];for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100);await e.git.raw([`rm`,`--cached`,...Fn(r)])}}async snapshotPromisedPaths(){let e,t;try{let{git:n}=this.gitHandle();e=await mW(n,uW),t=new Set(await pW(n,[`diff`,`--name-only`,`--diff-filter=U`]))}catch(e){return k9.warn({event:`snapshot-read-failed`,err:e,branch:this.currentBranch},`[sync] could not read the real index before the push cycle — skipping stale-index self-heal`),[]}let n=[];for(let r of e)if(!t.has(r.path)&&this.isSyncScopedPath(r.path)&&(n.push(r.path),n.length===100))break;return n}async healStaleRealIndex(e,t){let n=new Set(e.filter(e=>!t.has(e)));if(n.size===0)return;if(this.hasGitOperationInProgress()){k9.warn({event:`self-heal-skipped-git-operation`,branch:this.currentBranch,pathCount:n.size,paths:[...n].slice(0,20)},`[sync] self-heal skipped — a Git operation now holds the tree, so the promised paths stay listed until it ends`);return}let r=this.gitHandle(),i,a;try{i=(await hW(r.git,[`diff-index`,`--cached`,`--name-status`,`HEAD`])).flatMap(e=>e.status[0]===`R`||e.status[0]===`C`?[e.from,e.to]:[e.to]),a=await pW(r.git,[`diff`,`--name-only`,`HEAD`])}catch(e){k9.error({event:`self-heal-skipped`,branch:this.currentBranch,pathCount:n.size,paths:[...n].slice(0,20),err:e},`[sync] self-heal could not compare the real index against HEAD — the promised paths stay listed in the real index`);return}let o=new Set(a),s=[...new Set(i.filter(e=>n.has(e)&&!o.has(e)))];s.length!==0&&(await this.resetRealIndexForPaths(s,`push`,r),k9.warn({event:`self-heal-applied`,branch:this.currentBranch,pathCount:s.length,paths:s.slice(0,20)},`[sync] self-heal cleared stale real-index entries left behind by an earlier push cycle`))}async resetRealIndexForPaths(e,t,n){if(e.length===0)return;let r=n??this.gitHandle(),i=[...new Set(e)];for(let e=0;e<i.length;e+=100){let n=i.slice(e,e+100);await this.resetRealIndexBatch(r,n,t)}}async resetRealIndexBatch(e,t,n){let r;try{await e.git.raw([`reset`,`HEAD`,...Fn(t)]);return}catch(e){r=e}let i=w9(r),a=r,o=!1;if(i.class===`local`&&i.subclass===`index-lock`){await this.beforeRealIndexResetRetry?.(),await TSt(N9(.05));try{await e.git.raw([`reset`,`HEAD`,...Fn(t)]),o=!0}catch(e){a=e,i=w9(e)}}let s={event:`stale-index-reset`,outcome:o?`recovered-on-retry`:`failed`,op:n,branch:this.currentBranch,pathCount:t.length,paths:t.slice(0,20),errorClass:i.class,errorSubclass:i.subclass,err:a};o?k9.warn(s,`[sync] stale-index reset needed a second attempt — it succeeded, so the panel listing is current`):k9.error(s,`[sync] stale-index reset failed — the panel listing may stay stale`),!o&&i.class===`local`&&i.subclass===`index-lock`&&this.noteIndexLockEncountered(n,i)}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=this.gitHandle(),t=[];try{t=await pW(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){k9.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){k9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t)this.isContentConflictPath(e)?n.push(e):r.push(e);let i=[],a=LK(U(this.projectDir,wS(`project`,this.projectDir)));for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,...Fn([t])]),await e.git.raw([`add`,...Fn([t])]),t.toLowerCase()===a.toLowerCase()?k9.warn({file:t},`[sync] auto-resolved .ok/config.yml conflict with theirs: local project config edits were overwritten by the remote version`):k9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){k9.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){k9.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let n=t.slice(0,3).join(`, `),r=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${n}${r}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutivePullFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),k9.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(n.length>0){for(let e of n)this.conflicts.raise({kind:`merge-native`,file:e});this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),k9.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await this.applyCommitIdentity(e),await e.git.raw([`commit`,`--no-edit`]);let n=Hx(this.projectDir);t=n===null||!G(H(n,`MERGE_HEAD`))}catch(e){k9.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),k9.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){k9.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`),k9.warn({},`[sync] could not finalize merge after auto-resolving conflicts — merge aborted`)}}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){if(e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),k9.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`)this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`;else if(e.class===`semantic`&&e.subclass===`protected-branch`)this.mode=`off`,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`);else if(e.class===`local`&&e.subclass===`index-lock`)this.bumpFailureCount(t),(this.state===`pushing`||this.state===`pulling`||this.state===`fetching`)&&this.transitionTo(`idle`),this.noteIndexLockEncountered(t,e);else if(e.class===`local`&&e.subclass===`dirty-tree`){if(this.state===`conflict`||this.conflictCount>0){this.transitionTo(`conflict`);return}this.bumpFailureCount(t),this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)}else e.retryable?(this.bumpFailureCount(t,ESt(e)),this.transitionTo(`offline`)):(this.bumpFailureCount(t),this.transitionTo(`idle`))}otherLegInFlight(e){return this.cycleInFlight!==null&&this.cycleInFlight!==e}beginIndexLockWatch(e){if(this.otherLegInFlight(e))return;let t=this.pausedReason===`git-index-locked`;this.indexLockHitThisCycle=!1,t||(this.lastLockNoticeKind=void 0),this.restingIndexLockPause=t?void 0:this.pausedReason}holdsIndexLock(e){return vSt.test(`${e.message}\n${e.rawStderr??``}`)}noteIndexLockEncountered(e,t){let n=this.holdsIndexLock(t),r=n?`index-locked`:`git-lock-held`;if(this.lastLockNoticeKind!==r){this.lastLockNoticeKind=r;let i={event:r,op:e,branch:this.currentBranch,errorClass:t.class,errorSubclass:t.subclass};n?k9.error(i,`[sync] index locked — another program is holding .git/index.lock, so sync cannot update it`):k9.error(i,`[sync] a git lock file blocked the operation — the held lock is not .git/index.lock, so the listing is not paused on it`)}n&&(this.indexLockHitThisCycle=!0,this.pausedReason!==`git-index-locked`&&(this.pausedReason=`git-index-locked`,this.cc1Broadcaster?.signal(`sync-status`)))}noteUnbornHeadRefusal(){this.pausedReason!==`no-commits-yet`&&k9.error({event:`unborn-head-refusal`,branch:this.currentBranch},`[sync] push refused — this repository has no commits yet, so there is nothing to send`),this.pausedReason=`no-commits-yet`,this.cc1Broadcaster?.signal(`sync-status`)}clearUnbornHeadPause(){this.pausedReason===`no-commits-yet`&&(this.pausedReason=void 0,this.cc1Broadcaster?.signal(`sync-status`))}settleIndexLockPause(e){this.otherLegInFlight(e)||this.indexLockHitThisCycle||this.pausedReason===`git-index-locked`&&(this.pausedReason=this.restingIndexLockPause,this.cc1Broadcaster?.signal(`sync-status`))}currentState(){return this.state}markRun(){this.lastPushOkUtc=new Date().toISOString(),this.saveStateNow(),this.cc1Broadcaster?.signal(`sync-status`)}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,k9.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null);try{let e=CSt.has(this.pausedReason)?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastPullOkUtc:this.lastPullOkUtc,lastPushOkUtc:this.lastPushOkUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutivePullFailures,consecutivePushFailures:this.consecutivePushFailures,pushStreakIsConnectivity:this.pushStreakIsConnectivity,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0},n=`${this.statePath}.tmp`;$U(n,JSON.stringify(t,null,2),`utf-8`),nW(n,this.statePath)}catch(e){k9.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(G(this.statePath))try{let e=K(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastPullOkUtc=t.lastPullOkUtc??null,this.lastPushOkUtc=t.lastPushOkUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutivePullFailures=t.consecutiveFailures??0,this.consecutivePushFailures=t.consecutivePushFailures??0,this.pushStreakIsConnectivity=t.pushStreakIsConnectivity??!1;let n=typeof t.pausedReason==`string`?t.pausedReason:void 0,r=n!==void 0&&bSt(n)?n:void 0;n!==void 0&&r===void 0&&n.length>0&&k9.warn({event:`paused-reason-unrecognized`,pausedReason:n},`[sync] persisted pause reason is not one this build knows — dropping it and continuing without a pause`),this.pausedReason=wSt.has(r)?void 0:r}catch(e){k9.warn({err:e},`[sync] failed to load sync state`)}}};const ASt=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function jSt(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(YG(e)||XG(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&ASt.test(n)&&(r[`mount.id`]=n);try{let e=()=>{kU(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),Ya.with($a.extract(Ya.active(),r),e)}else e()}catch(e){q(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let F9=!1;function MSt(){if(F9)return;let e=hoe;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){F9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),F9=!0}catch(e){q(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}function NSt(e,t){let n=!0,r={async afterUnloadDocument(){n&&t()}};return e.configuration.extensions.unshift(r),()=>{n=!1;let t=e.configuration.extensions,i=t.indexOf(r);i!==-1&&t.splice(i,1)}}const PSt=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),FSt=(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function ISt(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=Xo(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],PK({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return q(`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 q(`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(`
|
|
2129
2129
|
`)){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=W(e,r);if(!hJ(a,t))continue;let s=dX(a,t);i.has(s)||G(a)&&i.set(s,o)}return i}function LSt(e){MSt();let t=e.ingressPolicy??i1({}),{contentDir:n,projectDir:r=n,quiet:i=!0,debounce:a=2e3,maxDebounce:o=1e4,gitEnabled:s=!0,commitDebounceMs:c=3e4,wipRef:l=`refs/wip/main`,configHomedirOverride:d,enableTestRoutes:f=!1,shadowRepo:p,contentRoot:m,destroyTimeoutMs:h=1e4,localOpCliArgs:g,authStreamHeartbeatMs:_,skipStateManifestCheck:v=!1,singleDocRelPath:y,ephemeral:b=!1}=e,x=I6(d),S=q(`server`),C=null,w=()=>C?.getLastKnownBranch()??null,T=()=>C?C.getLastKnownBranch():s9(r).branch,E=vyt(W(n)),D=null,O=s9(r).branch??`main`,k=new z4(O,{persistencePath:H(xK(r),`stale-external-writes.json`),onStaleExternalWriteChange:()=>{D?.signal(`sync-status`),re()},onStoreRefused:e=>{wn(e,`refused-store-mark`)===`lost`&&S.warn({docName:e},`[rescue] refused-store content for ${e} was not durably buffered at refusal time`)},fileForDocName:e=>U(r,mJ(e,n)).replaceAll(`\\`,`/`),hasResolvedExtension:WG}),A=()=>k.getActiveBranch(),ee=e=>k.getReconciledBase(e),j=(e,t)=>k.setReconciledBase(e,t),M=e=>k.deleteReconciledBase(e),N=e=>k.switchReconciledBaseScope(e),P=e=>k.setBatchInProgress(e),te=e=>{P(e),e||Ae.flushDeferredStores(`within-branch`).catch(e=>{S.error({err:e},`[persistence] deferred store drain failed after batch`)})},ne=()=>k.isBatchInProgress(),F=new MX({projectDir:r,contentDir:n,branch:O,signal:{signal:e=>D?.signal(e)},io:{gitRaw:async e=>bJ(r,{credentialConfig:[],timeoutMs:3e4}).git.raw(e),writeProjectFileUntracked:(e,t)=>$U(e,t,`utf-8`),unlinkProjectFileUndeclared:e=>iW(e),deleteResolvedContent:(e,t)=>{let n=JZe(t);try{iW(t)}catch(e){throw YZe(n),e}Te.decrementMdDir(V(e))},applyResolvedContent:async(e,t,n)=>{let r=!G(t);QY(t,GY(n)),await bS(t,n,{fs:lW}),r&&Te.incrementMdDir(V(e)),Me.documents.get(e)&&an(e,n),j(e,n),await Ee.recordDiskUpsert(e,n)},readLiveContent:e=>rn(e),finalizeReconcileResolution:async(e,t,n)=>{let r;if(e.reason===`stale-external-write`){let i=k.getStaleExternalWrite(n);i&&(r={conflict:i,branch:k.getActiveBranch()}),t===`mine`||t===`content`?k.recordDisplacedVersion(n,e.stages.theirs):k.clearDisplacedVersions(n),k.clearStaleExternalWrite(n)}let i=Me.documents.get(n),a=i?.getMap(`lifecycle`);if(t===`delete`){let e=i?pn(n,C?.getLastKnownBranch()??`main`,`delete`,!0):!1;await Ee.recordDiskDelete(n),S.info({docName:n,isDirty:e,source:`resolve-delete`},`[reconcile] delete: ${n} (dirty=${e})`);let t=a?{status:a.get(`status`),reason:a.get(`reason`),detectedAt:a.get(`detectedAt`)}:void 0;if(a?.set(`status`,`deleted-upstream`),a?.delete(`reason`),a?.delete(`detectedAt`),i)try{Me.closeConnections(n),await Ze(i)}catch(e){if(a&&t)for(let[e,n]of Object.entries(t))n===void 0?a.delete(e):a.set(e,n);if(r)try{k.restoreStaleExternalWrite(r.conflict,r.branch)}catch(e){S.error({err:e,docName:n},`[reconcile] stale-external-write rollback failed for ${n}; the retry may not find the conflict`)}throw e}M(n),Zt(n),Ft(n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:n,kind:`deleted`,source:`resolve-delete`}))}else a?.get(`reason`)===e.reason&&(a.delete(`status`),a.delete(`reason`),a.delete(`detectedAt`));at(`files`)}}});function re(){for(let e of k.listStaleExternalWrites()){let t=ee(e.docName)??e.diskContent;F.raise({kind:`reconcile`,file:e.file,reason:`stale-external-write`,detectedAt:e.detectedAt,stages:{base:t,ours:e.retainedContent??t,theirs:e.diskContent}})}}re();function ie(e){let t=mS({absPath:wS(`project`,r),sideline:!1,warn:e=>S.warn({message:e},`[config] could not read project config`)});if(!t.valid){let n=di(t.error)&&t.error.code===`SCHEMA_INVALID`?t.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(n.length>0){let e=n.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}if(e?.requireValid)throw Error(`Project config is invalid`,{cause:t.error});S.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return t.value.content.attachmentFolderPath??`./`}function ae(){let e=mS({absPath:wS(`project-local`,r),sideline:!1,warn:e=>S.warn({message:e},`[config] could not read project-local config`)}),t=ln(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||S.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let n=mS({absPath:wS(`project`,r),sideline:!1,warn:e=>S.warn({message:e},`[config] could not read project config`)});return n.valid||S.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:De(n.value.autoSync?.default)??`off`,source:`committed-default`}}function oe(){let e=mS({absPath:wS(`project-local`,r),sideline:!1,warn:e=>S.warn({message:e},`[config] could not read project-local config`)});return jne(e.value.autoSync)}function se(){let e=mS({absPath:wS(`project`,r),sideline:!1,warn:e=>S.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules,t=e?Dte(e):xi;return mbt(r,t.plugins.okf),t}function ce(){let e=mS({absPath:wS(`project`,r),sideline:!1,warn:e=>S.warn({message:e},`[config] could not read project config for link validation`)});return{links:e.value.validation?.links??`warning`,suppressLogLinkAdvisories:e.value.validation?.suppressLogLinkAdvisories??!0}}function le(){return Ztt(r,{configHomedirOverride:d,onWarn:e=>S.warn({message:e},`[config] could not read project-local config`)})}function ue(){let e=mS({absPath:wS(`project-local`,r,d),sideline:!1,warn:e=>S.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function de(){return Qge({cwd:r,homedirOverride:d,warn:e=>S.debug({message:e},`[config] diagnostics read`)})}function fe(e){let t={user:wa,project:u,"project-local":Wte};for(let n of de().diagnostics)if(e===void 0||t[n.scope]===e){if(n.code===`VALUE_FALLBACK`){for(let e of n.issues)S.warn({code:n.code,scope:n.scope,file:n.file,path:e.path.join(`.`),line:e.line,column:e.column},`[config] ${e.path.join(`.`)}: ${e.message}`);continue}n.code===`REMOVED_KEY`&&S.warn({scope:n.scope,file:n.file,path:n.path.join(`.`)},`[config] ${n.path.join(`.`)} is no longer read and was ignored. ${n.redirect}`)}}function pe(e){return`${$4(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function me(e){return`${e.maxBatchSize}|${e.maxBatchChars}|${e.docTimeoutMs}`}let he,ge=0;function _e(e,t){let i;if(e===`__config__/project`||e===`__local__/project`){let t=ae();i=t.mode,Sn?.setMode(t.mode,t.source).catch(n=>{S.warn({err:n,mode:t.mode,docName:e},`[sync] failed to apply autoSync mode from config`)});let n=oe();Sn?.setIntervals(n.pullIntervalSeconds,n.pushIntervalSeconds)}let a=le();if(Ke.applyConfig({enabled:a.enabled,providerFingerprint:pe(a),transportFingerprint:me(a),maxBatchSize:a.maxBatchSize}),e===`__config__/project`){ge+=1;try{let e=ie({requireValid:!0});Te?.setAttachmentFolderPath(e),he!==void 0&&e!==he&&S.warn({previous:he,next:e},`[content-filter] attachment folder changed — files under the previous folder no longer sync`),he=e}catch(e){S.warn({err:e},`[content-filter] project config invalid — keeping previous attachment admission`)}D?.signal(`lint-config`),(t??se().plugins.okf?.generate?.index===!0)||Kyt({projectDir:r,contentDir:n,generatedDocNames:Vt(),enabled:!1}).then(e=>{e.ok||S.warn({state:e.status.state},`[index] could not remove Open Knowledge generated-index Git attributes`)}),It()}S.info({docName:e,autoSyncMode:i,semanticEnabled:a.enabled},`[config] applied persisted config to in-process consumers`)}xU();let ve=Ys(),ye=xK(r),be=new eU({localDir:ye,log:q(`acp-registry`),fetchImpl:e.acpRegistryFetchImpl}),xe=new qH(ye,q(`acp-permissions`));if(C3(ye,{port:0,worktreeRoot:r,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),!v)try{Ext({lockDir:ye,shadowRepoDir:Ux(r)})}catch(e){throw E3(ye),e}let Se=zee(),Ce=(e,t)=>Se.resolveEmbed(e,t),we=(e,t)=>{let r=Se.resolveEmbed(e,t);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=W(n,r);if(!RK(i,W(n)))return null;try{let e=Es(i);return e.isFile()?e.size:null}catch{return null}},Te,Ee,Oe,ke,Ae,je,Me,Ne,Pe,Fe,Ie,Le,Re=null,ze=null,Be=null,Ve=null,Ue=null,We=null,Ge=le(),Ke=new ant({loadEmbedder:()=>{let t=le(),n={keyStore:e.embeddingsKeyStore??null,projectDir:r,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions},options:{maxBatchSize:t.maxBatchSize,maxBatchChars:t.maxBatchChars,docTimeoutMs:t.docTimeoutMs}};return(e.embedderLoader??Vtt)(n)},cacheDir:H(xK(r),`embeddings`),enabled:Ge.enabled,providerFingerprint:pe(Ge),transportFingerprint:me(Ge),maxBatchSize:Ge.maxBatchSize}),qe=null,Je=new Set,Ye=!1,Xe=[],Ze,Qe,$e,et,tt=new Promise((e,t)=>{$e=e,et=t}),nt,rt=new Promise(e=>{nt=e});async function it(){let e,t=Symbol(`branch-scope-gate-timeout`),n=new Promise(n=>{e=setTimeout(()=>n(t),1e4),e.unref?.()});try{if(await Promise.race([rt,n])!==t)return A()}finally{e&&clearTimeout(e)}try{return s9(r).branch??null}catch(e){return S.warn({err:e},`[auth] branch scope gate expired and HEAD is unreadable — skipping the branch claim check`),null}}function at(e){D?.signal(e)}let ot,st,ct,lt=!1,ut=!1,dt=new AbortController,ft=new Set,pt=!1,mt=!1,ht=!1,gt=0,_t,vt=new Promise(e=>{_t=e});function yt(e){ht||(ht=!0,_t(e))}function bt(){return pt||ft.size>0}function xt(){ut||!lt||(ot!==void 0&&clearTimeout(ot),ot=setTimeout(()=>{ot=void 0,jt()},500),ot.unref?.())}function St(){if(ut){yt({status:`cancelled`,indexCount:0});return}pt=!0,mt=!0,st=setImmediate(()=>{st=void 0,jt()})}let wt,Tt,Et=!1,Dt=null;async function Ot(){let e=Oe.current;if(!e||Et)return;let t=performance.now();S.info({gitDir:e.gitDir},`[shadow-housekeeping] deferred boot housekeeping started`);try{await fG(e)}catch(e){S.warn({err:e},`failed to write gc config (non-fatal)`)}if(!Et){if(Dt)try{let t=Number.parseInt(process.env.OK_BOOT_RENAME_GC_RETRY_INTERVAL_MS??``,10)||1e3,n=!1;for(let r=0;r<30;r++){if(!(await e0(e,Dt,{rebuild:!0})).skipped){n=!0;break}if(r===29)break;if(await new Promise(e=>{setTimeout(e,t).unref?.()}),Et)return}n||S.warn({gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild retry budget exhausted (persistent GC contention); rebuild deferred to next boot`)}catch(t){S.warn({err:t,gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild failed; index loaded without GC`)}if(!Et){try{await ke?.runBootMaintenance()}catch(e){S.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}S.info({gitDir:e.gitDir,durationMs:Math.round(performance.now()-t)},`[shadow-housekeeping] deferred boot housekeeping complete`)}}}function kt(){Et||(wt=setImmediate(()=>{wt=void 0,Tt=Ot().catch(e=>{S.error({err:e},`[shadow-housekeeping] unexpected uncaught failure`)})}))}async function At(){if(Et=!0,wt!==void 0&&(clearImmediate(wt),wt=void 0),!Tt)return;let e,t=new Promise(t=>{e=setTimeout(()=>t(`timeout`),h)});try{if(await Promise.race([Tt,t])===`timeout`)throw Error(`shadow housekeeping drain timed out after ${h}ms — abandoning in-flight housekeeping`)}finally{e!==void 0&&clearTimeout(e)}}function jt(){if(ut||!lt||!bt())return;if(ct!==void 0){e.generatedIndexTestHooks?.onKickWhileInFlight?.();return}if(k.isBatchInProgress()){xt();return}let t=pt,n=new Set(ft),r=mt;pt=!1,ft.clear(),mt=!1;let i=t?{fullSweep:!0}:{fullSweep:!1,directories:n};ct=(async()=>{let e=await Gt(i,dt.signal);if(e.status===`deferred`){pt=!0,r&&(gt+=e.indexCount,mt=!0);return}r&&(gt+=e.indexCount,e.status===`completed`&&bt()?mt=!0:yt({...e,indexCount:gt}))})().catch(e=>{S.warn({err:e},`[index] index regeneration coordinator failed`),r&&yt({status:`failed`,indexCount:0})}).finally(()=>{if(ct=void 0,ut){r&&yt({status:`cancelled`,indexCount:0});return}bt()&&ot===void 0?xt():!bt()&&ot===void 0&&e.generatedIndexTestHooks?.onIdle?.()})}async function Mt(){if(!ut){let e=ct;ut=!0,dt.abort(),ot!==void 0&&(clearTimeout(ot),ot=void 0),st!==void 0&&(clearImmediate(st),st=void 0),ft.clear(),pt=!1,mt=!1,e===void 0&&yt({status:`cancelled`,indexCount:0})}await ct}function Nt(e){ut||Xyt(e)||(ft.add(r9(e)),xt())}function Pt(e){if(!ut){for(let t of Yyt(e))ft.add(t);xt()}}function Ft(e){let t=xn?.getFileIndex();if(!t){Nt(e);return}let n=r9(e);if(i9(t.keys()).has(n)){Nt(e);return}Pt(r9(n))}function It(){ut||(pt=!0,xt())}function Lt(e){let t=xn?.getFileIndex().get(e);if(t)return{title:t.title,description:t.description,type:t.type}}let Rt=!1,zt={origin:FSt,writer:wYe,isConflict:e=>F.has(e),getDocument:e=>Me.documents.get(e),writeDisk:async(e,t)=>{tW(V(e),{recursive:!0}),await bS(e,t,{fs:lW})},registerWrite:(e,t)=>QY(e,GY(t)),noteFileIndex:e=>xn?.mutateFileIndex({kind:e.kind,path:e.absPath,docName:e.docName,content:e.markdown}),signalFiles:()=>at(`files`),attribute:async(e,t)=>{E1(e,t.id,t.name,t.id),Rt=!0}};function Bt(e){return e===``?t9:`${e}/${t9}`}function Vt(){return[...xn?i9(xn.getFileIndex().keys()):new Set([``])].map(Bt)}function Ht(e){let t=se().plugins.okf?.generate?.index===!0,n=e.state===`ready`||e.state===`not-applicable`;return{enabled:t,active:t&&n,git:e.state===`ready`?{state:e.state,ownership:e.ownership}:{state:e.state}}}function Ut(){return Ht(Hyt({projectDir:r,contentDir:n,generatedDocNames:Vt()}))}async function Wt(e){let t=await Kyt({projectDir:r,contentDir:n,generatedDocNames:Vt(),enabled:e});if(!t.ok)return{...Ut(),applied:!1,reason:t.status.state===`conflict`?`git-conflict`:`git-unavailable`};let i=await ES({cwd:r,scope:`project`,patch:{contentRules:{okf:{generate:{index:e}}}}});if(!i.ok){try{await t.rollback()}catch(e){S.error({err:e},`[index] could not roll back generated-index Git attributes`)}return{...Ut(),applied:!1,reason:`config-write`}}try{let e=K(i.path,`utf-8`);W7(Me.documents.get(`__config__/project`)??null,u,e,Ae.configPersistenceCtx)}catch(e){S.warn({err:e},`[index] generated-index settings reflection deferred to config watcher`)}return _e(u,e),fe(u),{...Ut(),applied:!0}}async function Gt(t,i){let a=0,o=t.fullSweep?performance.now():void 0,s=()=>se().plugins.okf?.generate?.index!==!0;try{if(i.aborted)return{status:`cancelled`,indexCount:0};if(s())return{status:`disabled`,indexCount:0};let c=xn?.getFileIndex();if(!c)return{status:`failed`,indexCount:0};try{if(await e.generatedIndexTestHooks?.beforePlan?.({fullSweep:t.fullSweep,signal:i}),i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};if(k.isBatchInProgress())return{status:`deferred`,indexCount:a};let o=ebt({docs:c,docExtension:UG,currentMarkdownFor:()=>null,warningScope:E}),l=Hyt({projectDir:r,contentDir:n,generatedDocNames:o.map(({directory:e})=>Bt(e))});if(l.state!==`ready`&&l.state!==`not-applicable`)return S.warn({state:l.state},`[index] generated index regeneration paused by Git attributes`),{status:`blocked`,indexCount:a};for(let{directory:r,markdown:c}of o){if(!t.fullSweep&&!t.directories.has(r))continue;if(i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};if(k.isBatchInProgress())return{status:`deferred`,indexCount:a};if(await e.generatedIndexTestHooks?.beforeDecision?.({directory:r,fullSweep:t.fullSweep,signal:i}),i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};let o=Bt(r),l=W(n,`${o}.md`),u;try{u=K(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&S.warn({err:e,path:WU(l)},`[index] could not read the existing generated index; treating it as absent`),u=null}a+=1;let d=await jyt({docName:o,absPath:l,markdown:c,currentMarkdown:u},zt);d===`blocked-conflict`?S.warn({event:`generated-index-regeneration`,outcome:`blocked`,directory:r,reason:`conflict`},`[index] generated index regeneration blocked by active conflict`):S.info({event:`generated-index-regeneration`,outcome:d===`unchanged`?`unchanged`:`written`,directory:r},`[index] generated index regeneration completed`),await e.generatedIndexTestHooks?.afterWrite?.({docName:o,fullSweep:t.fullSweep,signal:i}),!t.fullSweep&&r!==``&&u===null&&Pt(r9(r))}}finally{Rt&&=(await Ae.waitForPendingCommits(),await Ae.flushContributors(),!1),o!==void 0&&(J4(`generatedIndexSweepMs`,Math.round((performance.now()-o)*100)/100),htt(`generatedIndexCount`,a))}return{status:`completed`,indexCount:a}}catch(e){return S.warn({err:e},`[index] index regeneration failed`),{status:`failed`,indexCount:a}}}let Kt=null,qt=!1,Jt=()=>{try{yxt(r,Yt.entries())}catch(e){S.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Yt=new uxt(void 0,{onEviction:()=>XJe(),onSizeChange:e=>ZJe(e),onMutate:()=>{!qt||Kt!==null||(Kt=setTimeout(()=>{Kt=null,Jt()},2e3))}});for(let[e,t]of vxt(r))tK(e)||A5(e)&&([`.md`,`.mdx`].some(t=>{let r=W(n,`${e}${t}`);return RK(r,W(n))&&G(r)})||Yt.restore(e,t));qt=!0;let I={current:null},Xt=(e,t)=>{tK(e)||Yt.setRenamed(e,t)},Zt=e=>{if(!tK(e)){if(Yt.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Yt.setDeleted(e),I.current?.deleted(e)}},Qt=e=>{tK(e)||Yt.delete(e)};try{let u=`./`;try{u=ie()}catch(e){S.warn({err:e},`[content-filter] invalid attachment folder at boot — using sibling admission`)}he=u,Te=yq({projectDir:r,contentDir:n,singleDocRelPath:y,attachmentFolderPath:u,inPlaceSkillDirs:T2(n),rescanInPlaceSkillDirs:()=>T2(n),skillRootPaths:D7e(n),onAfterRebuild:()=>{Ee.refreshContentScope().catch(e=>{q(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),uQe(xn).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?q(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):q(`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=>{q(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),Ee=new Wet({projectDir:r,contentDir:n,contentFilter:Te,getGlobalSkillRoots:()=>fat(Ae.managedArtifactCtx),signalChannel:at,getLocalTargetInventory:()=>adt(xn,n),onRecoveredFileTarget:(e,t)=>{xn&&fxt({watcher:xn,contentDir:n,relativePath:e,exists:t,invalidateReferencedAssetsCache:Ue})}}),Oe={current:p},ke=s?zbt({getShadow:()=>Oe.current??null,getCurrentBranch:w,contentRoot:m??``,projectGitDir:Hx(r)??void 0,isWriterLive:e=>{if(!Ve&&!Ne)return q(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Ve?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of Ne?.sessionsForConnection(t)??[])return!0;return!1}}):void 0;let h=null;Ae=oxt({contentDir:n,projectDir:r,conflicts:F,lifecycleOf:(e,t)=>F.lifecycleOf(e,t),gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:Oe,ephemeral:b,contentRoot:m,derivedDocumentIndex:Ee,configHomedirOverride:d,getCurrentBranch:w,resolveEmbed:Ce,resolveSize:we,getPrincipal:()=>qe,onAgentCommit:()=>D?.signal(`session-activity`),onFlushCommit:()=>ke?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{D?.emitDiskAck(e,t),!tK(e)&&(tbt(r,n,e)&&Nt(e),jnt(r,n)&&(Ue?.(),at(`files`)))},onConfigRejected:(e,t)=>D?.emitConfigValidationRejected(e,t),onConfigPersisted:e=>{_e(e),fe(e)},onManagedSkillPersisted:e=>{let t=Ct(e);t?.kind===`skill`&&t.scope===`global`&&(h!==null&&clearTimeout(h),h=setTimeout(()=>{h=null;let e=d??js();R2(e,e,C2(e)).then(e=>{e>0&&S.info({refreshed:e},`[in-place-skills] post-edit copy re-sync`)}).catch(e=>S.warn({err:e},`[in-place-skills] post-edit copy re-sync failed`))},2e3),h.unref?.())},isRecentlyRemoved:e=>Yt.has(e),mdManager:e.mdManager,getLossRing:()=>je,durabilityState:k}),Me=new pKe({quiet:i,debounce:a,maxDebounce:o,extensions:[Ae.extension]});let v=Me.openDirectConnection.bind(Me);Me.openDirectConnection=((e,t)=>v(GG(e),t));let C=Me;Xe.push(e$e(()=>C.documents.size),t$e(()=>Ae.getQueueDepths()),r$e(()=>{let e=0;for(let t of C.documents.values())e+=t.directConnectionsCount;return{websocket:C.getConnectionsCount()-e,direct:e}})),a$e(),b||(We=sxt({getLoadedDocuments:()=>C.documents,lifecycleOf:(e,t)=>F.lifecycleOf(e,t),forceStore:(e,t)=>Ae.forceStore(e,t),getBase:e=>k.getReconciledBase(e),isBatchActive:()=>k.isBatchInProgress(),hasInFlight:e=>k.inFlightFlushCount(e)>0,readDiskBytes:e=>{let t=mJ(e,n),r,i;try{r=Ss(t),i=Es(r).size}catch(t){let n=_J(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new v9(`symlink cycle at content path: ${e}`):t}if(dY(t,r,n))throw new v9(`symlink-escape: ${t} resolves outside the content dir or into private state`);if(i>524288)throw new v9(`document exceeds the open byte limit: ${e}`);try{return K(r,`utf-8`)}catch(e){if(_J(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs})),Qe=Me.shouldUnloadDocument.bind(Me),Me.shouldUnloadDocument=e=>{if(Je.has(e))return!0;if(Ye&&!tK(e.name)&&k.isStoreRefused(e.name))return!1;if(Ye&&Qe(e))return!0;let t=e.name;return tK(t)||ee(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:Qe(e)},Ze=async e=>{Je.add(e);try{await Me.unloadDocument(e)}finally{Je.delete(e)}},D=new aK(Me),Be=new D4e(Me),Ve=new k4e(Me),Ne=new OQ(Me,e.agentSessionOptions);let E=Ne;Xe.push(i$e(()=>({active:E.liveSessionCount,limit:E.sessionLimit})));let O=bbt({derivedDocumentIndex:Ee,onDocumentSettled:e=>I.current?.changed(e)});Me.configuration.extensions.push(O);function A(e,t,n={}){S.warn({reason:e,docName:t,...n},`[auth-rejection] ${e}`)}Me.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=F5(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==ve)throw A(`server-instance-mismatch`,e.documentName,{claimedServerInstanceId:r,currentServerInstanceId:ve}),new P5(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${ve}`);let i=n?.expectedBranch;if(typeof i==`string`&&i.length>0){let t=await it();if(t!==null&&i!==t)throw A(`branch-mismatch`,e.documentName,{claimedBranch:i,currentBranch:t}),new P5(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${t}`)}if(!n)return;let a=e.context;typeof n.principalId==`string`&&(qe&&n.principalId===qe.id?a.principalId=qe.id:qe?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:qe.id})):a.principalId=n.principalId),typeof n.tabSessionId==`string`&&(a.tabSessionId=n.tabSessionId),a.kind=`human`}}),Me.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!XG(e.documentName)&&!ZG(e.documentName))return;let n=e.request,r=n.socket?.remoteAddress;if(r!==void 0&&!a1(r,t))throw A(`config-doc-admission-denied`,e.documentName,{check:`peer`}),Error(`config-doc admission requires loopback peer (peer=${r}, doc=${e.documentName})`);let i=e.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0;if(!o1(a,t))throw A(`config-doc-admission-denied`,e.documentName,{check:`host`}),Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${e.documentName})`)}});let j=W(n);function M(e){if(!A5(e))return null;let t=KG(e),n=W(j,t);return RK(n,j)?n:null}Me.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await mxt(e.documentName,{recentlyRemovedDocs:Yt,resolveFilePath:M,fileExists:G})}}),Me.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=F5(e.token);rbt(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Me.documents.get(e)})}}),Me.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new QV(e.update);if(t.readVarString(),t.readVarUint()===lH.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${Ci} rejected — server-only channel`)}});let N=Tft({declaredGitHubHosts:x,hocuspocus:Me,durabilityState:k,ingressPolicy:t,sessionManager:Ne,commentDocHooksRef:I,contentDir:n,getGeneratedIndexSettingsStatus:Ut,setGeneratedIndexEnabled:Wt,contentFilter:Te,serverInstanceId:ve,getFileIndex:()=>xn?xn.getFileIndex():new Map,getAttachmentFolderPath:ie,getAllFilesIndex:()=>xn?xn.getAllFilesIndex():new Map,getFileIndexGeneration:()=>xn?.getFileIndexGeneration()??0,mutateFileIndex:e=>{let t=e.kind===`update`?Lt(e.docName):void 0;switch(xn?.mutateFileIndex(e),e.kind){case`update`:nbt(t,e.content,e.docName)&&Nt(e.docName);break;case`create`:case`conflict`:Nt(e.docName);break;case`delete`:Ft(e.docName);break;case`rename`:Ft(e.oldDocName),Nt(e.newDocName);break;case`folder-create`:case`folder-delete`:Pt(e.relativePath);break;case`asset-create`:case`asset-delete`:case`file-create`:case`file-update`:case`file-delete`:break;default:qY(e)}},getFolderIndex:()=>xn?xn.getFolderIndex():new Map,getAliasMap:()=>xn?xn.getAliasMap():new Map,getFolderAliasIndex:()=>xn?xn.getFolderAliasIndex():new Map,rescanFiles:()=>xn?.rescanFromDisk(),enableTestRoutes:f,shadowRef:Oe,flushGitCommit:()=>Ae.flushPendingGitCommit(),flushContributors:()=>Ae.flushContributors(),getCurrentBranch:w,getReportedBranch:T,getDiskAckSVs:()=>D?.getLatestDiskAckSVsAsBase64()??{},getCollabClientCount:e.getCollabClientCount,contentRoot:m,derivedDocumentIndex:Ee,signalChannel:at,agentFocusBroadcaster:Be,agentPresenceBroadcaster:Ve,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Sn,conflicts:F,setBatchInProgress:te,localOpCliArgs:g,authStreamHeartbeatMs:_,projectDir:r,resolveEmbed:Ce,getBridgeLossReporter:()=>Le,getPrincipal:()=>qe,agentIntegrations:e.agentIntegrations,acpRegistry:be,loadAcpCustomAgents:()=>tU(ye,q(`acp-registry`)),homeDirOverride:d,forceUnloadDocument:Ze,ready:tt,recentlyRemovedDocs:Yt,serializeDoc:rn,evictManagedArtifactLkg:e=>{Ae.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Ke,getSemanticSimilarityFloor:()=>le().similarityFloor,getLinterBaseConfig:()=>se(),getLinkAdvisoryPolicy:ce,getProjectConfigEpoch:()=>ge,getLinkPreviewsEnabled:ue,resolveGitHubToken:Plt(e.detectGh,e.tokenStore),getConfigDiagnostics:de,embeddingsSecretsFile:Wtt(d),readSemanticProviderConfig:le,ephemeral:b,onReferencedAssetsCacheInvalidator:e=>{Ue=e}});Me.configuration.extensions.push(N),Pe=N.nativeApi,Fe=N.localApi,Ie=N.shutdownLocalOps;let P=mS({absPath:wS(`project`,r),sideline:!1,warn:e=>S.warn({message:e},`[config] could not read project config for bridge guards`)}),ne=P.value.bridge.deferGuard.enabled,re=P.value.bridge.fixedPoint.enabled,ae=P.value.bridge.preDrain.enabled;je=P.value.lossCapture.enabled?new xqe({projectDir:r,maxBytes:P.value.lossCapture.maxBytes}):void 0,P.value.bridge.lossDetector.enabled&&(Le=RYe({shadow:()=>Oe.current,ring:je,getBranch:()=>w()??`main`,contentRoot:m??``}),Ne.attachBridgeLossReporter(Le)),Me.configuration.extensions.push(bxt({mdManager:xa,schema:Gi,shadowRef:Oe,contentRoot:m,getCurrentBranch:w,resolveEmbed:Ce,resolveSize:we,deferGuardEnabled:ne,lossDetectorEnabled:P.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:re,preDrainEnabled:ae,lossRing:je})),Me.configuration.extensions.push(jSt()),Me.configuration.extensions.push({async afterLoadDocument({document:e}){AX(e,F)}})}catch(e){for(let e of Xe.splice(0))e();throw We?.dispose(),We=null,E3(ye),e}let $t=null,en=new Map,tn=[];function nn(e,t){let n=W(e,`rescue`),r=KG(t),i=W(n,r);return RK(i,n)?i:null}function rn(e){let t=Me.documents.get(e);return t?I1(t):null}let an=(e,t)=>j1(k,Me,e,t,Ce,we,Le),on=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of Me.documents){if(tK(n))continue;let r=Me.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{k1(r,i,Ce,n)},O1)}catch(t){S.error({originalError:q3e(t),docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},sn=null,cn=e=>{e&&(sn===null&&(sn=new Set,setImmediate(()=>{let e=sn;if(sn=null,e)try{for(let t of e)on(t)}catch(t){S.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),sn.add(e))};function un(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 qY(e)}}let dn={delete:`external-change-rescue`,rename:`external-change-rescue`,"branch-switch":`external-change-rescue`,"disk-update":`external-change-rescue-disk-update`},fn=(e,t,n,r,i=``,a=!1)=>{if(!Oe.current){let t=a?r===`delete`?` — the delete that follows destroys the document content`:` — the overwrite that follows replaces the document content`:``;return S.warn({docName:e,site:r},`[reconcile] rescue checkpoint not minted for ${e} (${r}) — shadow repo unavailable${t}`),PW(),!1}let o=Oe.current;return queueMicrotask(()=>{OG(o,m??``,{kind:dn[r],docName:e,contents:t,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:i}}).then(()=>{NW(),S.info({docName:e,site:r},`[reconcile] rescue checkpoint saved (${r}): ${e}`)}).catch(t=>{Bqe();let n=a?r===`delete`?` — the delete that follows destroys the document content`:` — the overwrite that follows replaces the document content`:``;S.error({docName:e,site:r,err:t},`[reconcile] rescue checkpoint write failed (${r}): ${e}${n}`)})}),!0},pn=(e,t,n,r=!1)=>{let i=ee(e),a=rn(e)??``,o=i===void 0?a!==``:a!==i;return o&&(fn(e,a,t,n,``,r),o)};function mn(e){F.dissolveReconcile(e),F.dissolveWorkingTree(F.fileOf(e))}let hn=(e,t,n,r)=>{(t.kind===`merged`||t.kind===`conflicts`)&&t.dedupSkipped&&(jW(),S.warn({docName:e,oursLen:n.length,theirsLen:r.length,newLen:t.newContent.length},`[reconcile] ${e} insert-group dedup skipped (LCS cell cap); union emitted with possible same-block duplication`))},gn=async(e,t,n)=>{WJe();let r=rn(e)??``,i=w()??`main`,a=GY(t).slice(0,6),o=r!==``&&r!==t,s=o?wn(e,`disk-authoritative-ingest`):`not-needed`;o&&fn(e,r,i,`disk-update`,a,!0);let c=GY(r).slice(0,6),l=n?`absent`:`blockless`,u=!1;try{an(e,t),mn(e),u=!0}catch(o){GJe(),S.error({err:o,docName:e},`[reconcile] failed to apply disk-authoritative ingest to Y.Doc for ${e}`),j(e,t),fn(e,t,i,`disk-update`,a,!0),mn(e);let u;try{u=rn(e)??void 0}catch(t){S.error({err:t,docName:e},`[reconcile] unable to read ${e} back after a failed disk-authoritative ingest; treating the live content as lost`)}s===`lost`&&u!==r&&(HW(),S.warn({docName:e,baseAbsent:n,reason:`no-base`,ours:c,theirs:a,result:`clean-unrescued`,rescue:s,applyFailed:!0},`[reconcile] ${e} base=${l} reason=no-base result=clean-unrescued ours=${c} theirs=${a} rescue=${s} applyFailed=true`))}if(u){let r=s===`lost`?`clean-unrescued`:`clean`;s===`lost`&&HW(),(s===`lost`?S.warn.bind(S):S.info.bind(S))({docName:e,baseAbsent:n,reason:`no-base`,ours:c,theirs:a,result:r,rescue:s},`[reconcile] ${e} base=${l} reason=no-base result=${r} ours=${c} theirs=${a} rescue=${s}`),await Ee.recordDiskUpsert(e,t)}};async function _n(e){try{switch(e.kind){case`create`:S.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await Ee.recordDiskUpsert(e.docName,e.content),at(`files`),Nt(e.docName),Qt(e.docName);break;case`update`:{let{docName:t,content:n}=e;if(nbt(e.previousIndexedFields,n,t)&&Nt(t),F.findByDocName(t)?.kind===`merge-native`)try{await F.pruneMergeNativeAgainstGit()}catch(e){S.warn({err:e,docName:t},`[reconcile] conflict prune against git failed`)}let r=Me.documents.get(t);if(!r){P1(k,void 0,t,n,F),await Ee.recordDiskUpsert(t,n);return}let i=ee(t),a=rn(t)??i??``;if(P1(k,r,t,n,F,a)){await Ee.recordDiskUpsert(t,n);return}if(i===void 0){await gn(t,n,!0);break}let o=kq({docName:t,base:i,ours:a,theirs:n}),s=GY(i).slice(0,6),c=GY(a).slice(0,6),l=GY(n).slice(0,6),u=a.length,d=n.length,f=o.kind===`clean`||o.kind===`merged`||o.kind===`conflicts`?o.newContent.length:void 0,p=f===void 0?void 0:f-Math.max(u,d),m=f===void 0?``:` newLen=${f} delta=${p}`;switch(S.info({docName:t,base:s,ours:c,theirs:l,result:o.kind,oursLen:u,theirsLen:d,...f===void 0?{}:{newLen:f,delta:p}},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind} oursLen=${u} theirsLen=${d}${m}`),hn(t,o,a,n),o.kind){case`noop`:F.dissolveReconcile(t),await Ee.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{an(t,o.newContent),j(t,o.newContent),kW(),F.dissolveReconcile(t),e=!0}catch(e){S.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),j(t,n),F.dissolveReconcile(t)}e&&await Ee.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{an(t,o.newContent),j(t,n),kW(),F.dissolveReconcile(t),e=!0}catch(e){S.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),j(t,n),F.dissolveReconcile(t)}e&&await Ee.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{an(t,o.newContent),j(t,o.newContent),kW(),AW(),e=!0}catch(e){S.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),j(t,n)}F.raise({kind:`reconcile`,file:F.fileOf(t),reason:`merged-with-markers`,stages:{base:i,ours:a,theirs:n}}),e&&await Ee.recordDiskUpsert(t,n);break}case`refused`:if(o.reason===`no-base`){await gn(t,n,!1);break}AW(),F.raise({kind:`reconcile`,file:F.fileOf(t),reason:Y3e(o.reason),stages:{base:i,ours:a,theirs:n}})}break}case`delete`:{let{docName:t}=e;mn(t);let n=Me.documents.get(t);if(!n){M(t),await Ee.recordDiskDelete(t),at(`files`),Zt(t),Ft(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=pn(t,w()??`main`,`delete`,!0);n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),M(t),await Ee.recordDiskDelete(t),S.info({docName:t,isDirty:r,source:`watcher-delete`},`[reconcile] delete: ${t} (dirty=${r})`),Me.closeConnections(t),await Ze(n),at(`files`),Zt(t),Ft(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;mn(t);let i=e=>{let t=e.getMap(`lifecycle`);t.set(`status`,`renamed`),t.set(`newPath`,n)},a=Me.documents.get(t),o=a?pn(t,w()??`main`,`rename`):!1;a&&i(a),M(t),Ae.forgetObservedFile(t),j(n,r),S.info({oldDocName:t,newDocName:n,isDirty:o},`[reconcile] rename: ${t} → ${n} (dirty=${o})`),at(`files`),Qt(n),Xt(t,n);try{await Ee.recordDiskRename(t,n,r)}catch(e){S.error({oldDocName:t,newDocName:n,err:e},`[reconcile] rename: index update failed for ${t} → ${n}; completing client teardown anyway`)}let s=Me.documents.get(t);s&&s!==a&&i(s);let c=Me.documents.get(n);if(c&&c.getMap(`lifecycle`).get(`status`)===`renamed`){let e=c.getMap(`lifecycle`);e.delete(`status`),e.delete(`newPath`),an(n,r),S.info({newDocName:n},`[reconcile] rename: cleared stale renamed lifecycle on ${n}`)}await Ne.closeAllForDoc(t);let l=s?.getConnectionsCount()??0;Me.closeConnections(t),l>0&&S.info({oldDocName:t,newDocName:n,closedConnections:l},`[reconcile] rename: closed ${l} connection(s) on ${t}`),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`})),Ft(t),Nt(n);break}case`conflict`:{let{docName:t}=e;if(!Me.documents.get(t))return;let n=ee(t)??``,r=rn(t);r===null?S.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):j(t,r),F.raise({kind:`reconcile`,file:F.fileOf(t),reason:`disk-markers`,stages:{base:n,ours:r??n,theirs:e.content}}),S.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:Se.add(e.relativePath),at(`files`),cn(Qo(e.relativePath));break;case`asset-delete`:Se.remove(e.relativePath),at(`files`),cn(Qo(e.relativePath));break;case`folder-create`:case`folder-delete`:at(`files`),Pt(e.relativePath);break;case`file-create`:case`file-update`:await Ee.recordFileTargetUpsert(e.relativePath),Ue?.(),at(`files`);break;case`file-delete`:await Ee.recordFileTargetDelete(e.relativePath),Ue?.(),at(`files`);break;default:qY(e)}}catch(t){let n=un(e);S.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let vn=[];async function yn(e){if(ne()){vn.push(e);return}await _n(e)}async function bn(){let e=vn.splice(0,vn.length);for(let t of e)await _n(t)}let xn=null,Sn=null,Cn=null,wn=(e,t)=>{let n=Oe.current;if(!n)return S.warn({docName:e,context:t},`[rescue] shadow repo unavailable — cannot buffer ${e} (${t})`),PW(),`lost`;try{let r=rn(e);if(r===null)return S.warn({docName:e,context:t},`[rescue] skipping ${e} — document dropped from map mid-rescue (${t})`),PW(),`lost`;let i=nn(n.gitDir,e);return i?(tW(V(i),{recursive:!0}),$U(i,r,`utf-8`),NW(),S.info({docName:e,context:t},`[rescue] rescue buffer saved (${t}): ${e}`),`rescued`):(S.warn({docName:e,gitDir:n.gitDir,context:t},`[rescue] path-traversal guard rejected docName: ${e} (${t})`),PW(),`lost`)}catch(n){return S.error({err:n,docName:e,context:t},`[rescue] failed to write rescue buffer for ${e} (${t})`),PW(),`lost`}};async function Tn(e){if(Me.documents.size===0)return;let t=!1,n=Date.now()+e,r,i=Promise.withResolvers(),a=NSt(Me,()=>{t||(n=Date.now()+e,r&&(clearTimeout(r.id),r.id=setTimeout(r.expire,Math.max(n-Date.now(),250))))}),o={async afterUnloadDocument({instance:e}){!t&&e.getDocumentsCount()===0&&(t=!0,i.resolve())}};Me.configuration.extensions.push(o);try{let o=Array.from(Me.documents.keys());Me.closeConnections(),Me.flushPendingStores();for(let e of Me.documents.values())e.getConnectionsCount()===0&&Me.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});for(;Date.now()<n-250&&Array.from(Me.documents.values()).some(e=>e.getConnectionsCount()===0&&!Qe(e));)await new Promise(e=>setTimeout(e,25));for(let e of k.getRefusedStoreDocNames()){if(tK(e))continue;let t=Me.documents.get(e);if(!t||!Qe(t))continue;if(n-Date.now()<50){S.warn({docName:e},`[rescue] refused-store pass out of budget before ${e}; leaving it and any remaining refused docs to the flush timeout path`);break}if(wn(e,`refused-store-shutdown`)!==`rescued`){S.warn({docName:e},`[rescue] refused-store doc rescue failed; leaving ${e} to the flush timeout path`);continue}let r=!1,i=!1,a=Ze(t).then(()=>{r=!0}).catch(t=>{i=!0,r=!0,S.warn({docName:e,err:t},`[rescue] refused-store doc unload failed at shutdown: ${e}`)}),o=0;do{let e=Math.max(n-Date.now(),50);o+=e;let t;try{await Promise.race([a,new Promise(n=>{t=setTimeout(n,e)})])}finally{t!==void 0&&clearTimeout(t)}}while(!r&&Date.now()<n);if(!r){S.warn({docName:e,unloadDeadline:o},`[rescue] refused-store doc unload did not finish before the flush deadline; leaving ${e} to the flush timeout path`),a.then(()=>{i||S.info({docName:e},`[rescue] refused-store doc unload completed after the flush deadline: ${e}`)});continue}i||S.info({docName:e},`[rescue] refused-store doc rescued and unloaded at shutdown: ${e}`)}let s=new Promise((i,s)=>{let c=()=>{if(t)return;t=!0,a();let n=Array.from(Me.documents.keys()),r=[],i=[];if(Oe.current)for(let e of n)tK(e)||(wn(e,`flush-timeout`)===`rescued`?r.push(e):i.push(e));else{S.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`);for(let e of n)tK(e)||(i.push(e),PW())}let c=r.length>0||i.length>0?` — rescued [${r.join(`, `)}]${i.length>0?`, lost [${i.join(`, `)}]`:``}`:``;s(Error(`flushAllStoresAndWait timeout: no document retired for ${e}ms — ${n.length}/${o.length} docs did not unload: [${n.join(`, `)}]${c}`))};r={id:setTimeout(c,Math.max(n-Date.now(),250)),expire:c}});await Promise.race([i.promise,s])}finally{t=!0,a();let e=Me.configuration.extensions,n=e.indexOf(o);n!==-1&&e.splice(n,1),r&&clearTimeout(r.id)}}async function En(){return Cn||(Cn=(async()=>{let e=Date.now(),t=[];Ye=!0;let n=Promise.allSettled([Ie()]),i;try{await Mt()}catch(e){S.warn({err:e},`[index] generated index shutdown drain failed`),t.push({phase:`generated-index-drain`,error:String(e)})}for(let e of Xe.splice(0))e();try{await We?.dispose()}catch(e){S.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}We=null;try{D3(ye)}catch(e){S.warn({err:e},`[server] failed to mark server.lock draining`)}ke?.destroy();try{await At()}catch(e){S.warn({err:e},`[shadow-housekeeping] shutdown drain failed`),t.push({phase:`shadow-housekeeping-drain`,error:String(e)})}if(Kt!==null&&(clearTimeout(Kt),Kt=null),qt)try{yxt(r,Yt.entries())}catch(e){S.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let a,o=await Promise.race([tt.then(()=>`completed`,e=>(S.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{a=setTimeout(()=>e(`timeout`),5e3)})]);a!==void 0&&clearTimeout(a),o===`timeout`&&S.warn({},`[server] init did not complete within 5s during shutdown`);let s=Me.documents.size;try{try{try{Re&&=(clearTimeout(Re),null),ze&&=(clearTimeout(ze),null),C&&=(await C.unsubscribe(),null),xn&&=(await xn.unsubscribe(),null);for(let{docName:e,cleanup:t}of tn)try{await t()}catch(t){S.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}tn.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),S.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{D?.destroy(),Ve?.destroy(),$t&&=(await $t.disconnect(),null);for(let[e,t]of en)try{await t.disconnect()}catch(t){S.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}en.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),S.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await Ne.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),S.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await SQe()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),S.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await Tn(h)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),S.error({err:e},`[server] shutdown phase-3 flush failed`)}Ee.close();let e;try{await Promise.race([(async()=>{await Ae.flushPendingGitCommit(),await Ae.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),h)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),S.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Sn&&=(await Sn.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),S.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(Oe.current){let e;try{await Promise.race([nG(Oe.current).drain(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`shadow mutator drain timeout`)),h)})])}catch(e){t.push({phase:`shadow-mutator-drain`,error:e instanceof Error?e.message:String(e)}),S.error({err:e},`[server] shutdown phase-5 shadow mutator drain failed`)}finally{e!==void 0&&clearTimeout(e)}try{let e=(await oM({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&Os(W(Oe.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{vYe(Oe.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),S.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}if([i]=await n,i.status===`rejected`){let e=i.reason,n=e instanceof AggregateError?e.errors:[e];t.push({phase:`local-op-subprocess-shutdown`,error:n.map(e=>e instanceof Error?e.message:String(e)).join(`; `)}),S.error({err:e},`[server] shutdown local-op subprocess drain failed`)}let a=Date.now()-e;t.length===0?S.info({documentCount:s,durationMs:a},`[server] shutdown flushed ${s} documents in ${a}ms`):S.warn({documentCount:s,durationMs:a,phaseErrors:t},`[server] shutdown flushed ${s} documents in ${a}ms with ${t.length} phase error(s)`)}}finally{try{E3(ye,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),S.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await TU()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}if(i?.status===`rejected`)throw i.reason})(),Cn)}let Dn=[];async function On(){try{qe=await lxt(r),S.info({principalId:qe.id},`[server] principal loaded`)}catch(e){S.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!Oe.current)try{Oe.current=await mG(r,{deferGcConfig:!0}),S.info({gitDir:Oe.current.gitDir},`[server] history repo initialized at ${Oe.current.gitDir}`),lG(Oe.current)&&!Dn.includes(`shadow-excludes`)&&Dn.push(`shadow-excludes`)}catch(e){S.error({err:e},`[server] history repo init failed`),Dn.push(`shadow-repo`)}if(Oe.current)try{let e=T6e(Oe.current.gitDir);z6e(Oe.current.gitDir,e),O6e(Oe.current.gitDir,e),Dt=e,S.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){S.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(Oe.current)try{await dG(Oe.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`)){S.warn({},`[server] history repo appears corrupted — reinitializing`);try{Oe.current=await mG(r,{deferGcConfig:!0}),lG(Oe.current)&&!Dn.includes(`shadow-excludes`)&&Dn.push(`shadow-excludes`)}catch(e){S.error({err:e},`[server] history repo reinit failed`),Oe.current=void 0,Dn.includes(`shadow-repo`)||Dn.push(`shadow-repo`)}}else S.error({err:e},`[server] history repo check failed (transient?)`)}if(Oe.current&&Cn===null){let e=Oe.current,t=LK(U(r,n))||`.`;ze=setTimeout(()=>{ze=null,vG(e,t).catch(e=>{S.debug({err:e},`[shadow] fan-out index warm-up failed (non-fatal)`)})},3e3),ze.unref?.()}if(Oe.current)try{let e=W(Oe.current.gitDir,`last-known-head`),t=null;try{t=K(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await oM({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await oM({baseDir:r,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}S.info({lastKnownHead:t,currentHead:n,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=import`);try{await TG(Oe.current,m??``,t,n,e),MW()}catch(e){S.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else S.info({currentHead:n},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=noop`);try{Os(e,n,`utf-8`)}catch(e){S.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){S.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=wdt(n,r);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;S.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){S.error({err:e},`[server] managed rename recovery failed`),Dn.push(`managed-rename-recovery`)}try{let e=rrt(r);(e.deleted>0||e.errors>0)&&S.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){S.error({err:e},`[server] upload-tempfile sweep failed`),Dn.push(`upload-tempfile-sweep`)}try{$t=await Me.openDirectConnection(Ci),D?.emitServerInfo(ve,T()??void 0)}catch(e){S.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Dn.push(`cc1-push`)}let t=b?[]:$r;for(let e of t)try{let t=await Me.openDirectConnection(e);en.set(e,t)}catch(t){S.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Dn.push(`config-doc:${e}`)}let i=new Map([[u,wS(`project`,r)],[Wte,wS(`project-local`,r)],[wa,wS(`user`,r,d)]]);for(let e of t){let t=i.get(e);if(t)try{S.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await Zvt(t,t=>{let n=Me.documents.get(e),r=fyt(e,t,Ae.configPersistenceCtx);S.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let i=W7(n??null,e,t,Ae.configPersistenceCtx);S.info({docName:e,outcome:i,isEcho:r},`[config-file-watcher] applyExternalConfigChange outcome`),_e(e),r||fe(e)});tn.push({docName:e,cleanup:n}),S.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){S.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Dn.push(`config-file-watcher:${e}`)}}if(!b){let e=null,t=t=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,Ee.refreshGlobalSkillNodes().catch(e=>{S.warn({err:e,docName:t},`[backlinks] global skill bundle re-ingest failed`)})},300)},n=(e,n)=>{let r=gat(e,Ae.managedArtifactCtx);if(!r)return;let i=xat(Me.documents.get(r)??null,r,n,Ae.managedArtifactCtx);S.info({docName:r,outcome:i},`[managed-artifact-watcher] external change`),at(`files`),He(r)&&t(r)},r=e=>{let n=gat(e,Ae.managedArtifactCtx);at(`files`),n&&He(n)&&t(n)};try{let e=fat(Ae.managedArtifactCtx),t=await Bbt(e,n,r);tn.push({docName:`__skill-files__`,cleanup:t}),S.info({roots:e},`[managed-artifact-watcher] skills started`)}catch(e){S.warn({err:e},`[managed-artifact-watcher] skills failed to start`),Dn.push(`managed-artifact-watcher:skills`)}try{let e=G$(B6(Ae.managedArtifactCtx)),t=await Zvt(e,()=>{at(`files`)});tn.push({docName:`__skill-state__`,cleanup:t}),S.info({path:e},`[skill-state-watcher] started`)}catch(e){S.warn({err:e},`[skill-state-watcher] failed to start`),Dn.push(`skill-state-watcher`)}}try{let e=W(n,`.okignore`),t=W(r,`.gitignore`),i=null;try{let e=Xo(`git`,[`rev-parse`,`--git-common-dir`],PK({cwd:r,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=W(r,e.stdout.trim()),n=H(t,`info`,`exclude`);G(V(n))&&(i=n)}}catch{}let a=i?[e,t,i]:[e,t],o=S;o.info({okignorePath:e,gitignorePath:t,gitInfoExcludePath:i,ephemeral:b},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=b?null:await Qvt(a,(t,n)=>{(async()=>{if(t===e)try{let e=W7(Me.documents.get(`__config__/okignore`)??null,Qn,n,Ae.configPersistenceCtx);o.info({docName:Qn,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:U(r,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await Te.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:U(r,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),D?.signal(`files`);else{let e=U(r,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),D?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:U(r,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(tn.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:t},`[ignore-watcher] multi-path watcher started`))}catch(e){S.warn({err:e,projectDir:r,contentDir:n},`[ignore-watcher] failed to start multi-path watcher`),Dn.push(`ignore-files-watcher`)}let a=s9(r).branch??`main`;N(a),nt();let o=Ee.beginStartup(a),s=!1,c=performance.now();try{await OU(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:t}=await o.backlinksReady;t&&Dn.push(`backlink-index`);let i=0;for(let t of e)tK(t)||Yt.peek(t)?.kind!==`renamed`&&(Yt.setDeleted(t),i++);i>0&&S.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`);let a=performance.now(),c=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,l=Te?T2(n):new Set,u=e=>{e.some(e=>c.test(U(n,e).split(is).join(`/`)))&&(Re&&clearTimeout(Re),Re=setTimeout(()=>{Re=null;try{R2(r,n).then(e=>{e>0&&(S.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),D?.signal(`files`))}).catch(e=>S.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=T2(n);if(!(e.size!==l.size||[...e].some(e=>!l.has(e))))return;l=e,Te.rebuildIgnorePatterns().then(t=>{t.ok?(S.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),D?.signal(`files`)):S.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>S.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){S.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};xn=await OU(`ok.boot.seed-walk`,void 0,async()=>DX(n,yn,Te,{onRawBatch:u})),R2(r,n).then(e=>{e>0&&S.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>S.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=d??js();R2(e,e,C2(e)).then(e=>{e>0&&S.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>S.warn({err:e},`[in-place-skills] global copy re-sync failed`))}J4(`seedWalkMs`,Math.round(performance.now()-a));{let e=W(n),t=0;for(let[n]of Yt.entries()){if(!A5(n))continue;let r=W(e,`${n}${UG(n)}`);RK(r,e)&&G(r)&&(Yt.delete(n),t++)}t>0&&S.info({count:t},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let f=await Ee.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&Dn.push(`tag-index`);let p=0;try{y===void 0?await N5({contentDir:n,contentFilter:Te,basenameIndex:Se,onSkip:(e,t,n)=>{p++,S.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):kft({contentDir:n,basenameIndex:Se,onSkip:(e,t,n)=>{p++,S.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),p>0&&(S.warn({count:p},`[basename-index] startup seed completed with ${p} skipped entries — embeds under inaccessible subtrees will not resolve`),Dn.push(`basename-index-partial`))}catch(e){S.error({err:e},`[basename-index] startup seed failed`),Dn.push(`basename-index`)}})}catch(e){if(S.error({err:e},`[server] disk bridge watcher failed to start`),Dn.push(`file-watcher`),!s){let e=await Ee.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&Dn.push(`tag-index`)}}finally{J4(`indexesMs`,Math.round(performance.now()-c)),xn&&htt(`fileCount`,xn.getFileIndex().size)}try{C=await cbt(r,async({trigger:e})=>{if(S.info({trigger:e},`[batch] begin trigger=${e}`),Lqe(),Me.flushPendingStores(),await Ae.flushPendingGitCommit(),P(!0),Oe.current){let e=A(),t=s9(r).branch??e,n=[],i=0;for(let[e,t]of Me.documents){if(tK(e))continue;let r=null;if(t.transact(()=>{r=rn(e)},PSt),r===null)continue;let a=ee(e);if(a===void 0){i++;continue}n.push({docName:e,markdown:r,diskSnapshot:a})}if(i>0&&S.warn({count:i,branch:e},`[history] skipped parking ${i} doc(s) with no reconciled base; their content was not parked to the shadow history`),n.length>0)try{let r=await kYe(Oe.current,e,CG.id,n,t);r&&(Hqe(),S.info({count:n.length,branch:e,sha:r.slice(0,8)},`[history] parked ${n.length} docs on ${e} → ${r.slice(0,8)}`))}catch(e){S.error({err:e},`[shadow] park failed`)}}},async e=>{let t=vn.length,i=e.newBranch??`main`;if(S.info({kind:e.batchKind,headMoved:e.headMoved,docs:t,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${t}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(P(!1),await bn(),e.headMoved&&e.newHead){let t=ISt(r,W(n),e.oldHead,e.newHead);if(t.size>0){I3e(t.keys());for(let[e,n]of t)E1(e,ige(n.email),n.name,n.email,eS(e));await Ae.flushContributors()}}await Ae.flushDeferredStores(`within-branch`);try{await F.pruneMergeNativeAgainstGit()}catch(e){S.warn({err:e},`[head-watcher] conflict prune against git failed`)}}else{Vqe(),vn.splice(0,vn.length);let t=!1,r;try{N(i),F.setBranch(i),re(),r=await Ee.beginBranchSwitch(i),Te.rebuildDirCount();try{let e=0;Se.clear(),await N5({contentDir:n,contentFilter:Te,basenameIndex:Se,onSkip:(t,n,r)=>{e++,S.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(S.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`),Dn.includes(`basename-index-partial`)||Dn.push(`basename-index-partial`))}catch(e){S.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,t]of Me.documents)if(!tK(e))try{let r=mJ(e,n);if(!G(r)){pn(e,i,`branch-switch`),t.getMap(`lifecycle`).set(`status`,`deleted-upstream`),S.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}if(dY(r,Ss(r),n)){pn(e,i,`branch-switch`),t.getMap(`lifecycle`).set(`status`,`deleted-upstream`),S.warn({docName:e,branch:i},`[branch-switch] tombstone: ${e} resolves outside the content dir or into private state on ${i}`);continue}let a=K(r,`utf-8`);if(ee(e)===void 0){let t=rn(e)??``;t!==``&&t!==a&&pn(e,i,`branch-switch`,!0)}an(e,a),j(e,a),S.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){S.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}S.info({branch:i,docCount:Me.documents.size},`[branch-switch] loaded branch ${i} (${Me.documents.size} docs)`);try{await Ee.settleBranchFromDisk(r)}catch(e){Ee.abortBranchSwitch(r),S.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(Oe.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Me.documents)if(!tK(t))try{let n=await jYe(Oe.current,i,CG.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=ee(t);if(!r)continue;let a=kq({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(hn(t,a,n.markdown,r),a.kind){case`merged`:case`clean`:an(t,a.newContent),j(t,a.newContent),e++;break;case`conflicts`:an(t,a.newContent),j(t,a.newContent),AW(),e++,F.raise({kind:`reconcile`,file:F.fileOf(t),reason:`merged-with-markers`,stages:{base:n.diskSnapshot,ours:n.markdown,theirs:r}});break;case`noop`:break;case`refused`:switch(a.reason){case`conflict-markers`:case`no-base`:case`too-large`:S.warn({docName:t,reason:a.reason,branch:i},`[branch-switch] parked WIP not restored for ${t} (reconcile refused: ${a.reason})`);break;default:{let e=a.reason;S.warn({docName:t,reason:String(e),branch:i},`[branch-switch] parked WIP not restored for ${t} (reconcile refused: ${String(e)})`);break}}}}catch(e){S.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&S.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&Oe.current)try{let t=dG(Oe.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await nG(Oe.current).withMutator(async()=>{for(let e of n.split(`
|
|
2130
2130
|
`))e&&await t.raw(`update-ref`,`-d`,e)}),S.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){S.error({err:e},`[branch-switch] detached cleanup failed`)}P(!1),await Ae.flushDeferredStores(`discard-stale`),t=!0,D?.emitBranchSwitched(i)}finally{Ee.abortBranchSwitch(r),t||(P(!1),await Ae.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&Oe.current&&t>0){let t=m??`.`;try{let n=await TG(Oe.current,t,e.oldHead,e.newHead,i);MW(),S.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){S.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){S.error({err:e},`[server] HEAD watcher failed to start`),Dn.push(`head-watcher`)}F.subscribe(e=>{if(e.type!==`raised`||e.conflict.kind===`reconcile`)return;let t=e.docName;if(t===null||!Me.documents.get(t))return;let n=rn(t);n===null?S.warn({docName:t,file:e.conflict.file},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):j(t,n)});try{await F.pruneMergeNativeAgainstGit()}catch(e){S.warn({err:e},`[conflicts] boot prune of merge-native entries failed`)}let l=R6(r,x);S.debug({resetAmbientCredentials:l,originKind:L6(r,x).kind},`[sync] ambient credential-chain reset decision at boot`);let f=xJ(g,{resetAmbient:l}),p=ae(),h=oe();p.mode!==`off`&&S.info({mode:p.mode,source:p.source},`[sync] mode active at boot`);try{Sn=new kSt({declaredGitHubHosts:x,projectDir:r,contentDir:n,contentFilter:Te,contentRoot:m,mcpTomlEditor:e.mcpTomlEditor,mode:p.mode,pullIntervalSeconds:e.pullIntervalSeconds??h.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds??h.pushIntervalSeconds,credentialConfig:f,cc1Broadcaster:D,conflicts:F,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:te,onStateChange:e=>{S.info({state:e},`[sync] state → ${e}`)},checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=Oe.current;n&&await DG(n,m??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=Oe.current;n&&await DG(n,m??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{S.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await ES({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||S.error({result:t,reason:e,humanError:nne(t.error),configPath:wS(`project-local`,r)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await Sn.start()}catch(e){S.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Sn=null}at(`files`),Ee.announceReadyViews();let _=mtt();_!==void 0&&J4(`readyMs`,_),fe()}return On().then(()=>{lt=!0,$e(),St(),kt()},e=>{ut=!0,dt.abort(),yt({status:`failed`,indexCount:0}),Ee.close(),nt(),et(e)}),{hocuspocus:Me,durabilityState:k,sessionManager:Ne,nativeApi:Pe,localApi:Fe,cc1Broadcaster:D,agentFocusBroadcaster:Be,agentPresenceBroadcaster:Ve,maintenanceCoordinator:ke,contentFilter:Te,basenameIndex:Se,serverInstanceId:ve,destroy:En,ready:tt,generatedIndexSweepReady:vt,degraded:Dn,lockDir:ye,get syncEngine(){return Sn},conflicts:F,getLinkPreviewsEnabled:ue,resolveEmbed:Ce,acpRegistry:be,acpPermissions:xe}}function I9(e){return e/1048576}function RSt(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:I9(e.rss),heapTotalMb:I9(e.heapTotal),heapUsedMb:I9(e.heapUsed),externalMb:I9(e.external),arrayBuffersMb:I9(e.arrayBuffers)}}}let L9=null,R9=null,z9=null;const zSt=1e6;let B9=null,V9=null;wU(()=>{L9=null,R9=null,z9=null,B9?.disable(),B9=null,V9=null});function BSt(){if(L9)return;let e=DU().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}=RSt();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),L9=e}function VSt(){if(!R9){let e=DU().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(!B9){B9=eoe({resolution:20}),B9.enable();return}e.observe(B9.percentile(50)/zSt,{stat:`p50`}),e.observe(B9.percentile(99)/zSt,{stat:`p99`}),B9.reset()}),R9=e}if(!z9){let e=DU().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=V9;if(V9={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`}))}),z9=e}}const HSt=q(`skill-migrate`);function USt(e){return[{host:`agents`,root:Xr},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=CM.indexOf(e.host),r=CM.indexOf(t.host);return(n===-1?CM.length:n)-(r===-1?CM.length:r)||e.host.localeCompare(t.host)})}const WSt=USt(Ea),GSt=USt(_i);function KSt(e,t){return G(W(e,re(t)))}function qSt(e,t){tW(V(t),{recursive:!0});try{nW(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;rW(e,t,{recursive:!0}),sW(e,{recursive:!0,force:!0})}}function JSt(e,t,n){let r=q7e(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 YSt(e,t){let n;try{n=Ss(W(e,`.ok`,`skills`))}catch{n=W(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!Ss(W(e,t.dir)).startsWith(n+is)}catch{return!0}}).map(e=>e.name))}async function XSt(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??WSt,a={migrated:[],skipped:[]};if(!G(n))return a;let o;try{o=xs(n)}catch{return a}let s=U(t,n).split(is).join(`/`),c=new Set;for(let[e,n]of Object.entries(I2(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Wr.test(e)||AQ.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=W(n,e);if(!G(H(o,`SKILL.md`)))continue;let s=vM(o)?.contentHash;if(s===void 0)continue;let l=Ss(o),u=i.map(({host:n,root:r})=>{let i=W(t,r);return{host:n,root:r,path:H(i,e),escapes:K2(t,i),state:JSt(H(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=>KSt(t,e.root));if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?sW(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&sW(d.path,{recursive:!0,force:!0}),qSt(o,d.path));for(let e of u)e!==d&&e.state.kind===`store-link`&&(sW(e.path,{recursive:!0,force:!0}),rW(d.path,e.path,{recursive:!0}));await k2(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),HSt.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),HSt.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}let H9=null,U9=!1;function ZSt(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function QSt(e){if(!ZSt())return;let t=xK(e);H9=new yx({currentPath:W(t,`tolerance-telemetry.jsonl`),previousPath:W(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),fa(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};H9?.append(`${JSON.stringify(t)}\n`).catch(e=>{U9||(U9=!0,q(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function W9(){fa(null),await H9?.drain(),H9=null,U9=!1}function $St(e){let t=W(e,qi);if(!(()=>{if(!G(t))return!0;try{return xs(t).length===0}catch{return!0}})())return[];let n=[];for(let t of oi)G(W(e,t))&&n.push(t);for(let t of pa){let r=W(e,t);try{G(r)&&Es(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function eCt(e){let t=Vx(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 G9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function tCt(e){ptt();let t=e.projectDir??e.contentDir,n=Kft({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}`)}Mx.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}xU({localSink:n?.telemetry}),QSt(t),BSt(),VSt();let{kind:r,gitdir:i}=eCt(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=WU(i));let o=Bft(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>OU(`ok.boot`,{attributes:a},async()=>nCt(e)),l=()=>{if(s)try{let e=$a.extract(Ya.active(),{traceparent:s});return Ya.with(e,c)}catch(e){q(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async e=>{try{await d(e)}finally{o.uninstall()}},u}async function nCt(e){let t=e.skipAutoInit??!1,n=e.log??q(`boot`),r=e.serverRuntime??{...Nre(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((vee(r)||!jt(i))&&!r.allowExternal)throw new n3e(`refusing to start: the server would bind a non-loopback address (${(jt(i)?r.bind:i).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let a=i1({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.externalUrl===void 0&&(a.bindLiterals.length===0?n.warn({bind:r.bind},`[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.externalUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.externalUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.`):n.info({bind:r.bind},`[ingress] server.allowExternal is set with no server.externalUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.externalUrl to admit a hostname.`));let o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await Promise.resolve().then(()=>xnt),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=W(p,`.ok`),h=W(m,`config.yml`);if(!G(h))throw new Vvt(G(m)?`config`:`okdir`,p);let g=W(m,`.gitignore`);G(g)||q(`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??EJ;try{e.gitEnabled!==!1&&_()}catch(e){if(e instanceof CJ||e instanceof wJ){let t=e instanceof wJ?e.detected:``,r=e instanceof wJ?`too_old`:`not_available`;c8(e),n.warn({event:`git_preflight_fail`,platform:e.platform,reason:r,detectedVersion:t},r===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await TU(),await Promise.race([W9(),new Promise(e=>setTimeout(e,G9))]),e}let v=$St(m);v.length>0&&q(`boot`).warn({files:v},`Found legacy runtime files at .ok/${v.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${qi}/.`);let y=null,b=LSt({getCollabClientCount:()=>y?.getCount()??0,acpRegistryFetchImpl:e.acpRegistryFetchImpl,contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:a,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,mcpTomlEditor:e.mcpTomlEditor,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,agentIntegrations:e.agentIntegrations,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral,configHomedirOverride:e.configHomedirOverride}),{hocuspocus:x,destroy:S,ready:C,degraded:w,lockDir:T,sessionManager:E,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,maintenanceCoordinator:k}=b,A=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ee=e.port??0,j=()=>`http://${A}:${ee}`,M=e.ephemeral?void 0:Mvt({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>j(),localApi:b.localApi,log:n}),N=c();N.headersTimeout=3e4,N.requestTimeout=6e4;let P=e.serveContentAssets===!1?void 0:Oft({contentDir:e.contentDir,contentFilter:b.contentFilter,contentSirv:zP(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:Et,assetExtensions:Mi,blocklistExtensions:Ge,ingressPolicy:a}),te=e.reactShellDistDir?zP(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,ne=e.ephemeral?null:new f4e({contentDir:e.contentDir,localDir:T,globalDir:hS(),registry:b.acpRegistry,permissions:b.acpPermissions,sessionManager:E,agentPresenceBroadcaster:O,resolveEmbed:b.resolveEmbed,isExcludedPath:e=>b.contentFilter.isExcluded(e),isIgnoredPath:e=>b.contentFilter.isPathIgnored(e),getLoadedDocText:e=>x.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>j(),getMcpStdioCommand:()=>d4e(e.localOpCliArgs,ee,{log:n}),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,probePiAcpBridge:e.probePiAcpBridge,ensurePiAcpBridge:e.ensurePiAcpBridge,terminalAuthAvailable:e.terminalAuthAvailable===!0,hostSnapshot:()=>W$({env:`local-web`,resolve:e.agentIntegrations?.probe}),autoApproveOkTools:()=>oqe(e.projectDir??e.contentDir,e.configHomedirOverride,n),agentBrowserTools:()=>GH(e.projectDir??e.contentDir,e.configHomedirOverride,n),log:n});ne!==null&&await ne.init();let F=`pending`;C.then(()=>{F=`ready`},()=>{F=`failed`});let re=zvt({httpServer:N,hocuspocus:x,nativeApi:b.nativeApi,mcpHttpHandler:M,ingressPolicy:a,health:{readiness:()=>F,degraded:()=>w},log:n,sessionManager:E,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,maintenanceCoordinator:k,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:P,reactShellMiddleware:te,ephemeral:e.ephemeral,acpThreadManager:ne}),ie=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)};y=L5(N);let ae=null;if(e.idleShutdownMs!==null){let t=e.idleShutdownMs??18e5,r=e.idleShutdownHandler??(e=>async()=>{await e()});ae=Vft({httpServer:N,counter:y,thresholdMs:t,log:n,onShutdown:r(async()=>{await ie(`idle-shutdown`)})})}let oe=[...new Set(i)],se=oe[0],ce=async()=>{await S().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(T)},le=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await le(N,e.port??0,se??`127.0.0.1`)}catch(e){throw await ce(),e}let ue=N.address(),de=typeof ue==`object`&&ue?ue.port:e.port??0,fe=[];for(let e of oe.slice(1)){let t=c();t.headersTimeout=N.headersTimeout,t.requestTimeout=N.requestTimeout;for(let e of N.listeners(`request`))t.on(`request`,e);for(let e of N.listeners(`upgrade`))t.on(`upgrade`,e);try{await le(t,de,e)}catch(t){n.error({err:t,failedAddress:e,port:de,alreadyBound:fe.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...fe,N])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await ce(),t}fe.push(t)}let pe=mtt();pe!==void 0&&J4(`httpListenMs`,pe);let me=N.address(),he=typeof me==`object`&&me?me.port:e.port??0;ee=he;let ge=j();d(T,he,ge),n.info({event:`server-listening`,pid:process.pid,port:he,addresses:oe,url:ge,lockDir:T},`[boot] listening on ${ge}`);let _e=!1,ve=async(e,t,n)=>{let r,i,a=!1,o=Promise.withResolvers(),s=()=>{a||(a=!0,o.reject(Error(n?`${e} timed out: no document retired for ${G9}ms`:`${e} timed out after ${G9}ms`)))},c=()=>{r=setTimeout(s,G9),r.unref?.()};try{n&&(i=NSt(n,()=>{a||(r!==void 0&&clearTimeout(r),c())}),c());let e=t();n||c(),await Promise.race([e,o.promise])}finally{a=!0,i?.(),r!==void 0&&clearTimeout(r)}};ie=async(e=`unspecified`)=>{if(_e)return;_e=!0,n.info({reason:e,pid:process.pid,lockDir:T},`[server] shutdown initiated (${e})`),F=`draining`;let t=[],r=async(e,r,i)=>{try{await ve(e,r,i)}catch(r){t.push(r),n.warn({err:r,step:e},`bootServer destroy step failed`)}};try{l(T)}catch(e){n.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{y?.detach()}catch(e){n.warn({err:e,step:`collabClientCounter.detach`},`bootServer destroy step failed`)}try{ae?.detach()}catch(e){t.push(e),n.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(ne!==null&&await r(`acpThreads.destroy`,()=>ne.destroy()),await r(`secondaryListeners.close`,async()=>{for(let e of fe)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await r(`mount.shutdown`,()=>re.shutdown()),M!==void 0&&await r(`mcpHttpHandler.close`,()=>M.close()),await r(`mount.wss.close`,()=>new Promise((e,t)=>{re.wss.close(n=>n?t(n):e())})),await r(`httpServer.closeAllConnections`,async()=>{N.closeAllConnections?.()}),await r(`httpServer.close`,()=>new Promise((e,t)=>{N.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await r(`destroyHocuspocus`,()=>S(),x),await r(`shutdownTelemetry`,()=>TU()),await r(`teardownToleranceTelemetry`,()=>W9()),await r(`flushLogFileSinks`,()=>Mx.flushAllFileSinks()),t.length>0)throw AggregateError(t,`bootServer destroy completed with errors`)};try{let t=await XSt({projectDir:p,skillsRoot:W(e.contentDir,`.ok`,Ye),inPlaceNames:YSt(e.contentDir,S2(e.contentDir))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=js(),t=await XSt({projectDir:e,skillsRoot:W(e,`.ok`,Ye),hostRoots:GSt,inPlaceNames:YSt(e,C2(e))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}return{httpServer:N,destroy:ie,lockDir:T,contentDir:e.contentDir,port:he,ready:C,generatedIndexSweepReady:b.generatedIndexSweepReady,degraded:w,didAutoInit:f,serverInstance:b,runtime:Hvt(b,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:ne}}const rCt=Bn;function iCt(e={}){let t=e.home??js(),n=e.platformName??process.platform,r=e.env??process.env;if(n===`darwin`)return G(H(t,`Library`,`Application Support`,`Claude`));if(n===`win32`){let e=r.APPDATA??H(t,`AppData`,`Roaming`);return G(H(e,`Claude`))}return!1}var K9=Lb(Gb(),1);function q9(){return H(hS(),`logs`)}const aCt=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function oCt(){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 sCt(e){gs(e,{recursive:!0})}function cCt(){return new Date().toISOString().slice(0,10)}function lCt(e){try{if(Es(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{Cs(n,r)}catch{}}try{Ds(`${e}.3`)}catch{}}function uCt(e){try{let t=Date.now(),n=6048e5,r=xs(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=Es(H(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{Ds(H(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{Ds(H(e,t.name)),a-=t.size}catch{}}}catch{}}function dCt(e){sCt(q9());let t=cCt(),n=e.filePath??H(q9(),`${e.name}.${t}.log`);lCt(n),(e._setTimeout??setTimeout)(()=>uCt(q9()),5e3).unref();let r=K9.default.destination({dest:n,append:!0,sync:!0}),i=oCt();return(0,K9.default)({level:i,name:e.name,redact:{paths:aCt,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:K9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function fCt(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[K9.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 pCt(e){return H(q9(),`${e}.${cCt()}.log`)}function mCt(){return q9()}function hCt(e){let t=W(e),n=0;for(;n<30;){let e=!1;try{e=G(W(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=V(t);if(r===t)return null;t=r,n+=1}return null}const J9=$s(Jo),Y9=q(`project-git`);var X9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function gCt(e,t){try{return await J9(e,[`var`,`GIT_COMMITTER_IDENT`],PK({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function _Ct(e,t){try{let{stdout:n}=await J9(e,[`for-each-ref`,`--count=1`,`refs/`],PK({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return Y9.warn({path:t,stderr:yCt(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function vCt(e){let t=W(e,`packed-refs`);if(G(t))try{if(K(t,`utf-8`).split(`
|
|
2131
2131
|
`).some(e=>e.trim()!==``&&!e.startsWith(`#`)))return!0}catch{return!0}try{return xs(W(e,`refs/heads`)).length>0}catch{return!1}}function yCt(e){let t=typeof e==`object`&&e?e:null,n=t?.stderr;return n==null?String(t?.message??e):Buffer.isBuffer(n)?n.toString(`utf-8`):String(n)}async function bCt(e,t){if(await _Ct(e,t))return;let n=[`commit`,`--allow-empty`,`--no-verify`,`--no-gpg-sign`,`-m`,`Initial commit`],r=await gCt(e,t),i=r?n:[`-c`,`user.name=Open Knowledge`,`-c`,`user.email=noreply@openknowledge.local`,...n];try{await J9(e,i,PK({cwd:t,encoding:`utf-8`})),r||Y9.info({path:t},`created initial commit with fallback identity (git identity unset)`)}catch(e){Y9.warn({path:t,stderr:yCt(e)},`could not create initial commit`)}}async function xCt(e,t){try{let{stdout:n}=await J9(e,[`rev-parse`,`--is-inside-work-tree`],PK({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function SCt(e){let t=W(e);yW(t);let n=W(t,`.git`),r=W(n,`HEAD`),i=!1,a=!1;if(G(n)){if(!Es(n).isDirectory())return{didInit:!1};if(G(r)){if(vCt(n))return{didInit:!1};a=!0}else Y9.info({},`detected partial .git/ — running git init to repair`),i=!0}let o;try{o=EJ()}catch(e){throw e instanceof CJ||e instanceof wJ?(c8(e),Y9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof wJ?`too_old`:`not_available`,detectedVersion:e instanceof wJ?e.detected:``},e instanceof wJ?`git binary too old`:`git binary not found`)):Y9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let s=o.resolvedPath;if(a)return await bCt(s,t),{didInit:!1};if(!i&&await xCt(s,t))return{didInit:!1};let c=``;try{c=(await J9(s,[`init`,`--initial-branch=main`,t],PK({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new X9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!G(r))throw new X9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,c);return await bCt(s,t),i?(Y9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(Y9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}async function CCt(e,t){let n;try{n=qo(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=V(n),r=0;r<32;r+=1){let n=H(t,`package.json`);if(G(n))try{let t=JSON.parse(await zs(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=V(t);if(r===t)return;t=r}}const wCt=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function Z9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of wCt)t=t.replace(e,n);return t}function Q9(e,t=0,n=new WeakSet){if(t>=5)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > 5; truncated`};if(typeof e==`object`&&e){if(n.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};n.add(e)}if(e instanceof Error)return{name:e.name,message:Z9(e.message)??``,stack:Z9(e.stack),code:e.code,cause:e.cause===void 0?void 0:Q9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:Z9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:Z9(String(r.message??``))??``,stack:Z9(r.stack),code:r.code,cause:r.cause===void 0?void 0:Q9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var TCt=class extends Error{filePath;constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},ECt=class extends Error{filePath;constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},$9=class extends Error{projectRoot;constructor(e,t){super(`Cannot open with --project ${e}: ${t}`),this.projectRoot=e,this.name=`SingleFileProjectOverrideError`}},DCt=class extends Error{filePath;constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function OCt(e,t={}){if(!FG(e))throw new DCt(e);let n;try{n=Ss(W(e))}catch(t){throw t.code===`ENOENT`?new TCt(e):t}if(!Es(n).isFile())throw new ECt(e);let r=V(n);if(t.projectRoot!==void 0){let e=W(t.projectRoot);if(!FK(e))throw new $9(e,`no .ok/config.yml there, so it is not an OpenKnowledge project root`);let r=kCt(e),i=U(r,n);if(i.startsWith(`..`)||ts(i))throw new $9(e,`${n} is not inside that project's content directory`);return{mode:`project`,projectRoot:e,docName:LG(i.split(is).join(`/`)),canonicalFilePath:n}}let i=IK(r);if(i){let e=i.rootPath,t=kCt(e);return{mode:`project`,projectRoot:e,docName:LG(U(t,n).split(is).join(`/`)),canonicalFilePath:n}}let a=Qo(n);return{mode:`ephemeral`,canonicalFilePath:n,contentDir:r,singleDocRelPath:a,docName:LG(a)}}function kCt(e){let t=mS({absPath:wS(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`;return W(e,t)}const ACt=`ok-ephemeral-`;function jCt(e,t){let n=W(e,`.ok`);return gs(n,{recursive:!0}),Os(W(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(t)}\n`,`utf-8`),Os(W(n,`.gitignore`),`local/
|
package/dist/index.d.mts
CHANGED
|
@@ -10554,6 +10554,7 @@ interface OkUpdateRelaunchFailedInfo {
|
|
|
10554
10554
|
readonly message?: string;
|
|
10555
10555
|
readonly downloadUrl?: string;
|
|
10556
10556
|
readonly dismissPending?: boolean;
|
|
10557
|
+
readonly reason?: 'no-longer-pending';
|
|
10557
10558
|
}
|
|
10558
10559
|
interface OkWhatsNewInfo {
|
|
10559
10560
|
readonly version: string;
|