@inkeep/open-knowledge 0.88.0-beta.6 → 0.88.0-beta.7

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.
Files changed (84) hide show
  1. package/dist/cli.mjs +6 -6
  2. package/dist/constants-DQu8wMs0.mjs +1 -0
  3. package/dist/{dist-6mRqHaPH.mjs → dist-Crqm_bf2.mjs} +1 -1
  4. package/dist/{dist-cEMV5fgn.mjs → dist-DuYtMHVN.mjs} +1 -1
  5. package/dist/index.mjs +1 -1
  6. package/dist/init-Co5-v9oY.mjs +1 -0
  7. package/dist/{init-DFdh051o.mjs → init-Dks6MSzi.mjs} +2 -2
  8. package/dist/{launch-json-removal-CYzSQDdc.mjs → launch-json-removal-Dh4fwUfr.mjs} +1 -1
  9. package/dist/loader-CUornGA0.mjs +1 -0
  10. package/dist/{loader-BoNz0iVg.mjs → loader-DU3qFKoP.mjs} +1 -1
  11. package/dist/{open-browser-D1i95Ud7.mjs → open-browser-Bo79lvT6.mjs} +1 -1
  12. package/dist/{preview-CbOBbupp.mjs → preview-BjDqLmfh.mjs} +1 -1
  13. package/dist/preview-DvBLVGwz.mjs +1 -0
  14. package/dist/public/assets/{AccountSection-G-bEok1r.js → AccountSection-CGQRWLJl.js} +1 -1
  15. package/dist/public/assets/{ActivityModeContent-JZbbBTrm.js → ActivityModeContent-DvfUSV8-.js} +1 -1
  16. package/dist/public/assets/{AddPropertiesButton-0jmf9Gqy.js → AddPropertiesButton-Bd_kx-s6.js} +1 -1
  17. package/dist/public/assets/{AgentDiffPane-_RdEVyc3.js → AgentDiffPane-HWPPiNF-.js} +1 -1
  18. package/dist/public/assets/{AttachmentsSection-Mms_06ol.js → AttachmentsSection-1lY_BAA7.js} +1 -1
  19. package/dist/public/assets/{CodeMirrorPropInput-BUDmLzYA.js → CodeMirrorPropInput-D1awhlZB.js} +1 -1
  20. package/dist/public/assets/{ContentRulesSection-DUWbyVg5.js → ContentRulesSection-D3b_YVz5.js} +1 -1
  21. package/dist/public/assets/{DocumentContext-Yvvvh9eq.js → DocumentContext-D3VHaJ7a.js} +1 -1
  22. package/dist/public/assets/{EditorModeToggle-JURdI3H4.js → EditorModeToggle-CRSMmpYf.js} +1 -1
  23. package/dist/public/assets/{ExcalidrawDocEditor-CW0kiQbn.js → ExcalidrawDocEditor-CD9WNtEA.js} +1 -1
  24. package/dist/public/assets/FeedbackForm-BsEM8tmS.js +1 -0
  25. package/dist/public/assets/{ImportSkillDialog-DEsVCAq1.js → ImportSkillDialog-Dx8bkmBJ.js} +1 -1
  26. package/dist/public/assets/{LinkPreviewsSection-D5T6WFZF.js → LinkPreviewsSection-CfK2gajD.js} +1 -1
  27. package/dist/public/assets/{LintConfigEditor-CFNi30Uy.js → LintConfigEditor-CQhbI_qp.js} +1 -1
  28. package/dist/public/assets/{LintingSection-BT5Mx9gK.js → LintingSection-aTVxHitK.js} +1 -1
  29. package/dist/public/assets/{ManagedArtifactProperties-MbEvT_Ng.js → ManagedArtifactProperties-CmS5TFx-.js} +1 -1
  30. package/dist/public/assets/ManagedArtifactProperties-bCnZ5ZzZ.js +1 -0
  31. package/dist/public/assets/{MermaidDocEditor-Dxmko28H.js → MermaidDocEditor-CVc7KMUF.js} +1 -1
  32. package/dist/public/assets/{NetworkAccessSection-DibRYILi.js → NetworkAccessSection-s5shVCiv.js} +1 -1
  33. package/dist/public/assets/{PropertyDisplayRow-B-yVuNvT.js → PropertyDisplayRow-BXx__S6W.js} +1 -1
  34. package/dist/public/assets/{PublishToGitHubDialog-CS3MfTWA.js → PublishToGitHubDialog-BEiB27aS.js} +1 -1
  35. package/dist/public/assets/{SchemaConfigEditor-CuMqV7Bp.js → SchemaConfigEditor-DZVkf4nV.js} +1 -1
  36. package/dist/public/assets/{SearchSection-CQSk8ahG.js → SearchSection-DYZJxhhG.js} +1 -1
  37. package/dist/public/assets/{SessionsHost-Dp_umkBZ.js → SessionsHost-Btpcnhu9.js} +2 -2
  38. package/dist/public/assets/{SettingsDialogBody-BNCcnp-C.js → SettingsDialogBody-DemcmvuA.js} +2 -2
  39. package/dist/public/assets/{ShareReceiveMissDialog-DskjHISp.js → ShareReceiveMissDialog-H5XNDMhU.js} +1 -1
  40. package/dist/public/assets/{SkillToolbarControls-eXGKl94y.js → SkillToolbarControls-C8Eiz4xo.js} +1 -1
  41. package/dist/public/assets/{SourceEditor-C055Y6xM.js → SourceEditor-DSvphG_j.js} +1 -1
  42. package/dist/public/assets/{SyncSection-BGWdYO91.js → SyncSection-DhieJiA0.js} +1 -1
  43. package/dist/public/assets/{SyncStatusBadge-D8rRxj99.js → SyncStatusBadge-CpaM0q1T.js} +1 -1
  44. package/dist/public/assets/{TerminalSection-BsxddHKZ.js → TerminalSection-PJQGmByd.js} +1 -1
  45. package/dist/public/assets/{TerminalWindowApp-BckE4Qr9.js → TerminalWindowApp-Caex3svP.js} +1 -1
  46. package/dist/public/assets/{TextDocEditor-DqCTs_PQ.js → TextDocEditor-SpGjWOlR.js} +1 -1
  47. package/dist/public/assets/{ThreadView-BxkX51yn.js → ThreadView-Bai8DmiN.js} +1 -1
  48. package/dist/public/assets/{TimelineDiffPane-suBAtK0T.js → TimelineDiffPane-D2i1Ngt_.js} +1 -1
  49. package/dist/public/assets/{client-version-1PpvH5hZ.js → client-version-CK3M6CP-.js} +1 -1
  50. package/dist/public/assets/{comment-chips-JWhqnPo7.js → comment-chips-CglJppcr.js} +1 -1
  51. package/dist/public/assets/{config-provider-BjfR2_Gp.js → config-provider-CLcJRVxe.js} +1 -1
  52. package/dist/public/assets/{doc-undo-manager-BhwVEZP9.js → doc-undo-manager-D5QmZ-um.js} +1 -1
  53. package/dist/public/assets/{index-CFqwCPJL.js → index-CMrIkfb-.js} +7 -7
  54. package/dist/public/assets/{lint-plugins-C6GePwEn.js → lint-plugins-BvLFgmXw.js} +1 -1
  55. package/dist/public/assets/{pending-receive-nav-store-BoALKlnl.js → pending-receive-nav-store-CR-nIEgF.js} +1 -1
  56. package/dist/public/assets/{preferred-session-events-BCMVH9Jc.js → preferred-session-events-CvHnIynN.js} +1 -1
  57. package/dist/public/assets/{progress-weUhe6LA.js → progress-KUvqLd4A.js} +1 -1
  58. package/dist/public/assets/{selection-context-D74HP0kz.js → selection-context-BPLBdnF9.js} +1 -1
  59. package/dist/public/assets/{src-DbQdMrYl.js → src-DCGeeL9K.js} +1 -1
  60. package/dist/public/assets/{telemetry-impl-Dpd17Qkv.js → telemetry-impl-CjMHfi8E.js} +1 -1
  61. package/dist/public/assets/{telemetry-startup-Dis6bVxP.js → telemetry-startup-Cgk6D2Jb.js} +1 -1
  62. package/dist/public/assets/{typing-burst-detector-D1zBEr2_.js → typing-burst-detector-BWijPQPm.js} +1 -1
  63. package/dist/public/assets/{use-activity-panel-JvC10OLa.js → use-activity-panel-DxGme0mE.js} +1 -1
  64. package/dist/public/assets/{use-open-skill-CRF_BjfN.js → use-open-skill-ZiVlXbcq.js} +1 -1
  65. package/dist/public/assets/{use-terminal-enabled-gjumBxXb.js → use-terminal-enabled-B4DFECG2.js} +1 -1
  66. package/dist/public/assets/{use-timeline-entry-diff-j-ETn5AY.js → use-timeline-entry-diff-D5TQVmB6.js} +1 -1
  67. package/dist/public/index.html +19 -19
  68. package/dist/{registry-probes-C3Z9yWC5.mjs → registry-probes-BtWlHuXg.mjs} +1 -1
  69. package/dist/{removal-file-path-RedaejUo.mjs → removal-file-path-D8DKJhn5.mjs} +1 -1
  70. package/dist/{repair-launch-json-DoCOMfXL.mjs → repair-launch-json-C6L6Oc-7.mjs} +1 -1
  71. package/dist/{repair-mcp-configs-DrR0Ro08.mjs → repair-mcp-configs-9SjNFr3a.mjs} +1 -1
  72. package/dist/{src-DSfFbGlT.mjs → src-D1OZaRhJ.mjs} +1 -1
  73. package/dist/src-DEPlGd4H.mjs +1 -0
  74. package/dist/start-B949-g6-.mjs +1 -0
  75. package/dist/{start-N8_Gk9Cw.mjs → start-q7jrdwYc.mjs} +3 -3
  76. package/package.json +4 -4
  77. package/dist/constants-VukQvYdL.mjs +0 -1
  78. package/dist/init-BgZVtpTY.mjs +0 -1
  79. package/dist/loader-BlmPb6AB.mjs +0 -1
  80. package/dist/preview-BWr_S3BA.mjs +0 -1
  81. package/dist/public/assets/FeedbackForm-CzKdxyG2.js +0 -1
  82. package/dist/public/assets/ManagedArtifactProperties-lTSbp_Pu.js +0 -1
  83. package/dist/src-CR6-YY-U.mjs +0 -1
  84. package/dist/start-fBA_FE9y.mjs +0 -1
@@ -2225,7 +2225,7 @@ restat-race-injected
2225
2225
  `)){let e=n.startsWith(`credential.username `)?n.slice(20).trim():void 0;e&&(t=e)}return t}function wFt(e,t={}){let n=Nvt(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??xFt)(SFt(e),t.cwd??process.cwd()),a=i?Avt(CFt(i)):void 0;return a?{host:r,login:a,source:`credential-config`}:{host:r,source:`active`}}function TFt(e={}){let t=e.ttlMs??6e4,n=e.now??Date.now,r;return{resolve(i){let a=S6(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=wFt(a,{cwd:i,_readCredentialUrlMatch:e._readCredentialUrlMatch});return r={projectDir:i,url:a,account:s,expiresAt:o+t},s},invalidate(){r=void 0}}}function EFt(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 O9=q(`sync-engine`),DFt=new Set(oFt),k9=/^[0-9a-f]{40}$/i,OFt=Lc(Ms);var A9=class extends Error{constructor(){super(`Sync paused while a Git operation is in progress or the index has unresolved conflicts`),this.name=`GitOperationInProgressError`}},kFt=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 AFt(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 jFt(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 MFt(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 NFt={syncScope:{pathBase:`content`}},j9={syncScope:{pathBase:`project`}},PFt=/(^|[/\\])index\.lock\b/i,FFt=new Set(Koe);function IFt(e){return FFt.has(e)}const LFt=new Set([`diverged-local-commits`,`external-changes-pending`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`]),RFt=[`no-push-permission`,`auth-error`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`],zFt=new Set(RFt),BFt=new Set([...RFt,`external-changes-pending`]);function M9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function VFt(e){return new Promise(t=>{setTimeout(t,e)})}function N9(e){let t=j_e(e);if(t.kind!==`repository`)return!1;let n=t.repository.readHead();return n.kind===`branch`&&t.repository.readRef(n.ref).kind===`absent`}function HFt(e){return e.class===`network`&&e.subclass!==`429`&&e.subclass!==`5xx`}function UFt(e){return e>=8?36e5:e>=5?9e5:e>=3?3e5:0}const WFt=12e4;var GFt=class{declaredGitHubHosts;state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;rootOkOutsideContentWalk;pullIntervalSeconds;pushIntervalSeconds;mode;credentialConfig;resolveCredentialConfig;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())w7e(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??x6(),this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.rootOkOutsideContentWalk=cG(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.resolveCredentialConfig=e.resolveCredentialConfig,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=Lxt(e.detectGh),this.ghAccountResolver=TFt({_readCredentialUrlMatch:e._readCredentialUrlMatch}),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??sxt,this.statePath=W(qJ(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||!b6(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?O9.warn({host:t,declaredLogin:r,declaredSource:e.source},`[sync] declared GitHub account produced no gh token — git runs with no relayed credential`):O9.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){O9.warn({err:t,host:e},`[sync] detectGhAccounts failed — fallback identity stays unnamed`);return}}gitHandle(e){return gK(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){O9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),O9.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){O9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=zx(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()){O9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){O9.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.subscribeToConflicts(),i()){this.transitionTo(`conflict`),O9.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let a=EFt(this.lastFetchUtc,this.pullIntervalSeconds),o=EFt(this.lastPushOkUtc,this.pushIntervalSeconds);this.schedulePull(a>0?a:void 0),this.schedulePush(o>0?o:void 0),O9.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||(O9.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,O9.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){O9.warn({cycleInFlight:this.cycleInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await Hae(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||N9(this.projectDir)?0:this.unpushedCommitCount(this.gitHandle())}async unpushedCommitCount(e){try{let t=await e.git.status();if(t.tracking)return t.ahead}catch{}try{let t=(await e.git.raw([`rev-list`,`--count`,`origin/${this.currentBranch}..HEAD`])).trim(),n=Number.parseInt(t,10);return Number.isFinite(n)?n:0}catch{return 0}}async convertStrandedCommitsToOverlay(){if(!this.hasRemote||N9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){O9.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){O9.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 hK(()=>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,O9.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`,O9.warn({err:e},`[sync] pull-only: stranded-commit conversion failed — leaving branch as-is`)}}}getCredentialConfig(){return this.credentialConfig}async refreshCredentialConfig(){if(this.resolveCredentialConfig)try{this.credentialConfig=await this.resolveCredentialConfig()}catch(e){O9.warn({err:e},`[sync] credential config refresh failed — keeping the previous chain`)}}async notifyCredentialsChanged(){if(await this.refreshCredentialConfig(),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`?O9.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}`):O9.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){O9.info({cycleInFlight:this.cycleInFlight},`[sync] one-shot push refused — a cycle is already in flight`);return}if(this.state===`conflict`||this.state===`auth-error`){O9.info({state:this.state},`[sync] one-shot push refused — state=${this.state}`);return}if(this.conflictCount>0){O9.info({conflictCount:this.conflictCount},`[sync] one-shot push refused — unresolved conflicts hold the tree`);return}if(!this.hasRemote){O9.info({hasRemote:!1},`[sync] one-shot push refused — no remote`);return}if(N9(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||N9(this.projectDir)||this.cycleInFlight!==null||this.fetchOnlyInFlight)return!1;this.fetchOnlyInFlight=!0,await this.refreshCredentialConfig();let e=this.gitHandle();try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.scheduleSaveState()}catch(e){return O9.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){O9.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 O9.info({mode:t,outcome:n},`[sync] one-shot pull complete`),n}async runOneShotPull(e){if(this.cycleInFlight!==null)return O9.info({cycleInFlight:this.cycleInFlight},`[sync] one-shot pull refused — a cycle is already in flight`),this.recordPullOutcome(`refused`);if(this.state===`conflict`)return O9.info({state:this.state},`[sync] one-shot pull refused — the conflict resolver holds the tree`),this.recordPullOutcome(`refused`);if(!this.hasRemote||N9(this.projectDir))return O9.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`?(LFt.has(this.pausedReason)||LFt.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?Vvt(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 hK(async()=>{await this.applyCommitIdentity(t);try{if(await t.git.raw([`add`,...Gt(e)]),(await Jq(t.git,[`diff`,`--cached`,`--name-only`,...Gt(e)])).length===0)return null;await t.git.raw([`commit`,`-m`,`Commit local changes before syncing`,...Gt(e)])}catch(n){throw await t.git.raw([`reset`,...Gt(e)]).catch(t=>{O9.warn({resetErr:t,files:e.length},`[sync] blocking-path index reset failed; paths may remain staged`)}),O9.error({err:n,files:e.length},`[sync] commit of blocking paths failed`),n}let n=(await t.git.revparse(`HEAD`)).trim();return this.clearBlockingPause(),O9.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 Svt(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async applyCommitIdentity(e){let t=await Svt(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`;p4e(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=C6(this.projectDir,this.declaredGitHubHosts);if(t.kind!==`ok`){let n={checkStatus:`unknown`},r=this.pushPermission;return this.pushPermission=n,this.pausedReason===`no-push-permission`?(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),O9.info({caller:e,originKind:t.kind},`[sync] push-permission pause cleared — origin is no longer a GitHub host`),this.cc1Broadcaster?.signal(`sync-status`)):MFt(r,n)||this.cc1Broadcaster?.signal(`sync-status`),n}this.pushPermissionProbeInFlight=!0,O9.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){O9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),r={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let i=jFt(r),a=this.pushPermission;this.pushPermission=i;let o=!1;return i.checkStatus===`denied`&&this.mode===`full`&&this.parkedOnAmbiguousNotFound()&&O9.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,O9.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,O9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!o&&!MFt(a,i)&&this.cc1Broadcaster?.signal(`sync-status`),i}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,O9.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 O9.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=>{O9.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=>{O9.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=UFt(this.consecutivePullFailures),t=e>0?e/1e3:0;return M9(Math.max(t,this.pullIntervalSeconds))}effectivePushDelayMs(){let e=UFt(this.consecutivePushFailures),t=e>0?e/1e3:0;return M9(Math.max(t,this.pushIntervalSeconds))}logContention(){let e={consecutiveContentions:this.consecutiveContentions,consecutivePushFailures:this.consecutivePushFailures,releasedConnectivityStreak:this.pushStreakIsConnectivity};this.consecutiveContentions>=3?O9.warn(e,`[sync] push repeatedly losing to remote contention — not backing off by design`):O9.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(N9(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 A9?(this.handleGitOperationRefusal(e,`pull`),`refused`):(this.handleError(C9(e instanceof Error?e:Error(String(e))),`pull`),`error`)}await this.refreshCredentialConfig();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`,O9.warn({},`[sync] detached HEAD — pausing sync`),`refused`;n=e,this.currentBranch=n}catch(e){return this.handleError(C9(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&&(O9.info({cleared:this.consecutivePushFailures},`[sync] fetch succeeded — releasing connectivity-class push backoff`),this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.schedulePush())}catch(e){let t=C9(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 CK?(this.handleIncomingSymlinkRefusal(e,`pull`),`refused`):(this.handleError(C9(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 A9)return this.handleGitOperationRefusal(t,`pull`),`refused`;if(t instanceof CK)return this.handleIncomingSymlinkRefusal(t,`pull`),`refused`;if(t instanceof TK&&e&&i)return O9.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 TK?Error(e?`failed to restore reconciled MCP overlays`:`failed to replay pre-merge working-tree state`):t,o=C9(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`),O9.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 Jq(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await Jq(e.git,[`diff`,`--name-only`,`HEAD..${n}`]));i=t.filter(e=>a.has(e))}catch(e){return this.handleError(C9(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(C9(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){O9.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`,...Gt(i)])}catch(e){return O9.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError(C9(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 O9.error({err:e,refusal:r.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError(C9(e instanceof Error?e:Error(String(e))),`pull`),`error`}return r.timedOut?(O9.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(C9(Error(`git merge --ff-only timed out after ${WFt}ms`)),`pull`),`error`):(r.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),O9.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 O9.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError(C9(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 O9.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 OFt(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,t],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:WFt}),{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:AFt({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),O9.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`&&O9.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&&DFt.has(p)){let t=await this.readMcpGitBlob(e,n,p),r=yFt({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`)}),O9.info({event:`mcp-config-reconcile`,target:p,outcome:`auto-resolved`},`[sync] pull-only: auto-resolved OpenKnowledge MCP entry overlap`);continue}r.kind===`declined`&&O9.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=Hne(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){O9.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:aK};for(let{path:t,bytes:r}of e)qU(VY(H(this.projectDir,t),this.projectDir,n),r);for(let e of t){let t=H(this.projectDir,e);VY(t,this.projectDir,n);try{$U(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=H(this.projectDir,e),n=cG(U(this.contentDir,t));return!n.startsWith(`..`)&&zH(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 Jq(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(N9(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,await this.refreshCredentialConfig();let t=H(Sc(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),n=null;try{let e=this.gatherContentFilesSync(),r=await this.snapshotPromisedPaths(),i=new Set;await hK(async()=>{await this.assertNoGitOperationInProgress(),this.transitionTo(`pushing`);try{let r=this.gitHandle(t);if(N9(this.projectDir)){O9.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)){O9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(C9(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){O9.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}O9.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 Jq(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)??cG(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||!k9.test(h)){O9.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 A9){this.handleGitOperationRefusal(t,`push`);return}let n=t instanceof Error?t:Error(String(t));n instanceof kFt&&O9.warn({err:n},`[sync] push cycle: staging error detail`);let r=C9(n);if(r.class===`semantic`&&r.subclass===`non-fast-forward`){if(e>0){O9.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 A9){this.handleGitOperationRefusal(e,`push`);return}if(e instanceof CK){this.handleIncomingSymlinkRefusal(e,`push`);return}if(e instanceof TK&&n&&r){O9.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 TK?Error(n?`failed to restore reconciled MCP overlays`:`failed to replay pre-merge working-tree state`):e,a=C9(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`;O9.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{hc(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(Sc(),`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 Jq(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||!k9.test(d)?(O9.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{hc(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 O9.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 yFt({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 Jq(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return O9.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 Jq(e.git,[`diff`,`--name-only`,`HEAD..${n}`]))}catch(e){return O9.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=DFt,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}),O9.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?O9.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&&O9.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(),O9.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`,...Gt(r.map(e=>e.path))])}catch(e){return O9.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 O9.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=VY(H(this.projectDir,n.path),this.projectDir),t=null;try{t=K(e,`utf8`)}catch(e){O9.warn({err:e,path:n.path},`[sync] could not read MCP config before restoring reconciled overlay`)}t!==n.raw&&qU(e,n.raw,`utf8`)}catch(e){t=!1,O9.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 O9.warn({err:e},`[sync] stash pop failed — stash remains on stack`),!1}}async assertNoGitOperationInProgress(){if(this.hasGitOperationInProgress()||(await Jq(this.gitHandle().git,[`diff`,`--name-only`,`--diff-filter=U`])).length>0||this.hasGitOperationInProgress())throw new A9;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`)),O9.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 SK(e.git,r),await wK(e.git,i,`merge`,e.env)}catch(e){let n=e instanceof CK?e.unsafe.slice(0,50):null,a=n===null?void 0:JSON.stringify([i,n]);throw n!==null&&a!==this.loggedSymlinkRefusal&&(this.loggedSymlinkRefusal=a,O9.warn({event:`unsafe-incoming-symlinks`,branch:t,incoming:i,links:n},`[sync] refusing incoming changes with unsafe symlinks until they are fixed`)),n===null&&O9.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 Z4e(e.git,{name:r,trackingRef:`refs/remotes/${r}`,commit:n})}catch(e){throw e instanceof Y4e&&O9.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=zx(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 A9;await hK(async()=>{let t=H(Sc(),`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=gFt({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,...Gt([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),gc(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=_Ft({target:o.path,raw:l,tomlEditor:this.mcpTomlEditor}),m=_Ft({target:o.path,raw:o.raw,tomlEditor:this.mcpTomlEditor}),h=p!==null&&p===m?l:o.raw,g=`${t}.replay-${r}`;n.push(g),gc(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(!k9.test(l))throw Error(`commit-tree returned an invalid SHA`);try{await i.git.raw([`update-ref`,`refs/heads/${o}`,l,a])}catch(e){O9.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=VY(H(this.projectDir,e.path),this.projectDir);K(t,`utf8`)!==e.raw&&qU(t,e.raw,`utf8`)}}catch(t){O9.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)}O9.info({event:`mcp-config-reconcile`,outcome:`persisted-entry-commit`},`[sync] persisted OpenKnowledge MCP launcher entry commit`)}finally{for(let e of n)try{hc(e)}catch{}try{hc(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 Jq(e.git,[`ls-files`,`--others`,`--ignored`,`--exclude-standard`,...Gt(a)]);for(let e of t)n.add(e)}catch(e){r=!1,O9.warn({err:e},`[sync] ignored-path probe failed — staging unfiltered without -f`)}}n.size>0&&O9.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,...Gt(i)])}return o}gatherContentFilesSync(){let e=[],t=(e,t)=>{throw new kFt(cG(U(this.projectDir,t))||`.`,e)},n=(r,i,a,o)=>{let s;try{s=lc(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=cG(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=cG(U(i,s));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t,a)){let t=cG(U(this.contentDir,s)),n=cG(U(this.projectDir,s));e.push({contentRelPath:t,projectRelPath:n})}}}};if(G(this.contentDir)&&n(this.contentDir,this.contentDir,NFt),this.rootOkOutsideContentWalk){let e=H(this.projectDir,`.ok`);G(e)&&!this.contentFilter.isDirExcluded(`.ok`,j9)&&n(e,this.projectDir,j9,t)}return e}isSyncScopedPath(e){let t=H(this.projectDir,e),n=cG(U(this.contentDir,t)),r=!n.startsWith(`..`)&&!this.contentFilter.isExcluded(n,NFt),i=this.rootOkOutsideContentWalk&&e.startsWith(`.ok/`)&&!this.contentFilter.isExcluded(e,j9);return r||i}async listHeadContentPaths(e,t){let n=new Set;try{let r=await Jq(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`,...Gt(r)])}}async snapshotPromisedPaths(){let e,t;try{let{git:n}=this.gitHandle();e=await z8e(n,Gq),t=new Set(await Jq(n,[`diff`,`--name-only`,`--diff-filter=U`]))}catch(e){return O9.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()){O9.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 Yq(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 Jq(r.git,[`diff`,`--name-only`,`HEAD`])}catch(e){O9.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),O9.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`,...Gt(t)]);return}catch(e){r=e}let i=C9(r),a=r,o=!1;if(i.class===`local`&&i.subclass===`index-lock`){await this.beforeRealIndexResetRetry?.(),await VFt(M9(.05));try{await e.git.raw([`reset`,`HEAD`,...Gt(t)]),o=!0}catch(e){a=e,i=C9(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?O9.warn(s,`[sync] stale-index reset needed a second attempt — it succeeded, so the panel listing is current`):O9.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 Jq(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){O9.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){O9.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=cG(U(this.projectDir,cS(`project`,this.projectDir)));for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,...Gt([t])]),await e.git.raw([`add`,...Gt([t])]),t.toLowerCase()===a.toLowerCase()?O9.warn({file:t},`[sync] auto-resolved .ok/config.yml conflict with theirs: local project config edits were overwritten by the remote version`):O9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){O9.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){O9.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(),O9.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`),O9.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=zx(this.projectDir);t=n===null||!G(H(n,`MERGE_HEAD`))}catch(e){O9.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),O9.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){O9.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`),O9.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),O9.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,HFt(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 PFt.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?O9.error(i,`[sync] index locked — another program is holding .git/index.lock, so sync cannot update it`):O9.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`&&O9.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,O9.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=zFt.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`;qU(n,JSON.stringify(t,null,2),`utf-8`),XU(n,this.statePath)}catch(e){O9.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&&IFt(n)?n:void 0;n!==void 0&&r===void 0&&n.length>0&&O9.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=BFt.has(r)?void 0:r}catch(e){O9.warn({err:e},`[sync] failed to load sync state`)}}};const KFt=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function qFt(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(gU(e)||_U(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&KFt.test(n)&&(r[`mount.id`]=n);try{let e=()=>{FU(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),Co.with(Do.extract(Co.active(),r),e)}else e()}catch(e){q(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let P9=!1;function JFt(){if(P9)return;let e=eoe;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){P9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),P9=!0}catch(e){q(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const YFt=uG(``),XFt=1e4,F9=3e4;function ZFt(e,t){let n=e.filter(t);return n.length===1?n[0]:void 0}function QFt(e){let t=new Set;for(let n of e.split(`
2226
2226
  `)){let e=n.trim();e!==``&&t.add(e)}return t}function $Ft(e,t){let n=QFt(e),r=QFt(t),i=0;for(let e of n)r.has(e)&&i++;return i>0&&i>=Math.max(n.size,r.size)*.5}function eIt(e,t){return e.size!==void 0&&e.modified!==void 0&&t.size===e.size&&t.modified===e.modified}function tIt(e,t,n){return e.identity===void 0||t.identity!==e.identity?!1:eIt(e,t)?!0:e.text!==void 0&&n!==void 0&&$Ft(e.text,n)}var nIt=class{pending=new Map;recentCreates=new Map;get size(){return this.pending.size}hold(e){this.pending.set(e.docName,e)}has(e){return this.pending.has(e)}release(e){let t=this.pending.get(e);return this.pending.delete(e),t}all(){return[...this.pending.values()]}matchCreate(e){let t=this.pending.get(e.docName);if(t)return{vanished:t,by:`same-name`};for(let t of this.pending.values())if(tIt(t,e,e.content))return{vanished:t,by:`identity`};if(e.hash===YFt)return;let n=ZFt([...this.pending.values()],t=>t.hashes.has(e.hash));return n?{vanished:n,by:`hash`}:void 0}dueAfter(e){return this.all().filter(t=>t.afterPass<e)}heldBefore(e){return this.all().filter(t=>t.heldAt<=e)}rememberCreate(e){this.forgetCreatesBefore(e.at-XFt),this.recentCreates.delete(e.docName),this.recentCreates.set(e.docName,e);for(let e of this.recentCreates.keys()){if(this.recentCreates.size<=256)break;this.recentCreates.delete(e)}}forgetCreatesBefore(e){for(let[t,n]of this.recentCreates)n.at<e&&this.recentCreates.delete(t)}matchRecentCreate(e,t,n){this.forgetCreatesBefore(t-XFt);let r=[...this.recentCreates.values()].filter(t=>t.docName!==e.docName),i;for(let t of r)if(e.identity!==void 0&&t.identity===e.identity&&tIt(e,t,eIt(e,t)?void 0:n(t))){i={create:t,by:`identity`};break}if(!i){let t=ZFt(r.filter(e=>e.hash!==YFt),t=>e.hashes.has(t.hash));t&&(i={create:t,by:`hash`})}return i&&this.recentCreates.delete(i.create.docName),i}clear(){this.pending.clear(),this.recentCreates.clear()}};function rIt(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 iIt=5e3,aIt=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),oIt=(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function sIt(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=Fs(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],sW({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(`
2227
2227
  `)){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(!GG(a,t))continue;let s=OX(a,t);i.has(s)||G(a)&&i.set(s,o)}return i}function cIt(e){JFt();let t=e.ingressPolicy??BQ({}),{contentDir:n,projectDir:r=n,quiet:i=!0,debounce:a=2e3,maxDebounce:o=1e4,gitEnabled:s=!0,commitDebounceMs:c=3e4,wipRef:l=`refs/wip/main`,configHomedirOverride:u,enableTestRoutes:d=!1,shadowRepo:f,contentRoot:p,destroyTimeoutMs:m=1e4,localOpCliArgs:h,authStreamHeartbeatMs:g,skipStateManifestCheck:_=!1,singleDocRelPath:v,ephemeral:y=!1}=e,b=RG(n,{root:`content`,component:`server-factory`}),x=x6(u),S=zvt({projectDir:r,tokenStore:e.tokenStore,localOpCliArgs:h,declaredGitHubHosts:x}),C=q(`server`),w=null,T=()=>w?.getLastKnownBranch()??null,E=()=>w?w.getLastKnownBranch():t9(r).branch,D=dMt(W(n)),O=null,k=t9(r).branch??`main`,A=new i2e({path:H(qJ(r),`receipts.jsonl`)}),j=n2e(n),M=new OG(k,{persistencePath:H(qJ(r),`stale-external-writes.json`),receipts:A,onStaleExternalWriteChange:()=>{O?.signal(`sync-status`),de()},onStoreRefused:e=>{oi(e,`refused-store-mark`)===`lost`&&C.warn({docName:e},`[rescue] refused-store content for ${e} was not durably buffered at refusal time`)},fileForDocName:e=>U(r,WG(e,n)).replaceAll(`\\`,`/`),hasResolvedExtension:qH}),N=()=>M.getActiveBranch(),te=e=>M.getReconciledBase(e),ne=(e,t)=>M.setReconciledBase(e,t),P=e=>M.deleteReconciledBase(e),re=e=>M.switchReconciledBaseScope(e),ie=new nIt,ae=e=>M.holdBatch(e),oe=e=>M.releaseBatch(e),se=async()=>{try{await Qr()}finally{$r()}await Ze.flushDeferredStores(`within-branch`)},ce=e=>t=>{if(t){ae(e);return}oe(e)&&se().catch(t=>{C.error({err:t,owner:e},`[batch] draining after the batch failed`)})},le=()=>M.isBatchInProgress(),ue=new Gtt({projectDir:r,contentDir:n,assertResolutionPath:Fe,branch:k,signal:{signal:e=>O?.signal(e)},io:{gitRaw:async e=>gK(r,{credentialConfig:[],timeoutMs:3e4}).git.raw(e),writeProjectFileUntracked:(e,t)=>{Fe(e),qU(e,t,`utf-8`)},unlinkProjectFileUndeclared:e=>{Fe(e),$U(e)},deleteResolvedContent:(e,t)=>{Me(t);let n=Pet(t);try{$U(t)}catch(e){throw Fet(n),e}qe.decrementMdDir(V(e)),Cn.current?.deleted(e)},applyResolvedContent:async(e,t,n)=>{Me(t);let r=!G(t);hX(t,uG(n)),await aS(t,n,{fs:Pe}),r&&qe.incrementMdDir(V(e)),$e.documents.get(e)&&Yn(e,n),ne(e,n),await Je.recordDiskUpsert(e,n)},readLiveContent:e=>Jn(e),finalizeReconcileResolution:async(e,t,n)=>{let r;if(e.reason===`stale-external-write`){let i=M.getStaleExternalWrite(n);i&&(r={conflict:i,branch:M.getActiveBranch()}),t===`mine`||t===`content`?M.recordDisplacedVersion(n,e.stages.theirs):M.clearDisplacedVersions(n),M.clearStaleExternalWrite(n)}if(t===`delete`&&On(n)){C.debug({docName:n,source:`resolve-delete`,bindingRecreated:!0},`[reconcile] delete skipped: ${n} (binding recreated)`);return}let i=$e.documents.get(n),a=i?.getMap(`lifecycle`);if(t===`delete`){let e=Ln(n);try{let t=e.residentCurrent()&&i?Rr(n,w?.getLastKnownBranch()??`main`,`delete`,!0):!1;if(e.namespaceCurrent()&&(Cn.current?.deleted(n),await Je.recordDiskDelete(n)),!e.namespaceCurrent()&&!e.residentCurrent()){C.debug({docName:n,source:`resolve-delete`,namespaceCurrent:!1,residentCurrent:!1},`[reconcile] delete skipped: ${n} (stale removal)`);return}C.info({docName:n,isDirty:t,source:`resolve-delete`},`[reconcile] delete: ${n} (dirty=${t})`);let o=a?{status:a.get(`status`),reason:a.get(`reason`),detectedAt:a.get(`detectedAt`)}:void 0;if(i&&e.residentCurrent()){a?.set(`status`,`deleted-upstream`),a?.delete(`reason`),a?.delete(`detectedAt`);try{$e.closeConnections(n),await _t(i,e.residentCurrent)}catch(t){if(e.residentCurrent()&&a&&o)for(let[e,t]of Object.entries(o))t===void 0?a.delete(e):a.set(e,t);if(e.namespaceCurrent()&&r)try{M.restoreStaleExternalWrite(r.conflict,r.branch)}catch(e){C.error({err:e,docName:n},`[reconcile] stale-external-write rollback failed for ${n}; the retry may not find the conflict`)}throw t}}if(!e.namespaceCurrent()){C.debug({docName:n,source:`resolve-delete`,namespaceCurrent:!1,residentCurrent:e.residentCurrent()},`[reconcile] delete: ${n} not recorded as removed (stale removal)`);return}P(n),Vn(n),cn(n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:n,kind:`deleted`,source:`resolve-delete`}))}finally{e.dispose()}}else a?.get(`reason`)===e.reason&&(a.delete(`status`),a.delete(`reason`),a.delete(`detectedAt`));jt(`files`)}}});function de(){for(let e of M.listStaleExternalWrites()){let t=te(e.docName)??e.diskContent;ue.raise({kind:`reconcile`,file:e.file,reason:`stale-external-write`,detectedAt:e.detectedAt,stages:{base:t,ours:e.retainedContent??t,theirs:e.diskContent}})}}de();function fe(e){let t=tS({absPath:cS(`project`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project config`)});if(!t.valid){let n=Ai(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});C.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return t.value.content.attachmentFolderPath??`./`}function pe(){let e=tS({absPath:cS(`project-local`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project-local config`)}),t=ote(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||C.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let n=tS({absPath:cS(`project`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project config`)});return n.valid||C.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:fie(n.value.autoSync?.default)??`off`,source:`committed-default`}}function me(){let e=tS({absPath:cS(`project-local`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project-local config`)});return Nie(e.value.autoSync)}function he(){let e=tS({absPath:cS(`project`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules,t=e?xre(e):_a;return vNt(r,t.plugins.okf),t}function ge(){let e=tS({absPath:cS(`project`,r),sideline:!1,warn:e=>C.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 _e(){return hpt(r,{configHomedirOverride:u,onWarn:e=>C.warn({message:e},`[config] could not read project-local config`)})}function ye(){let e=tS({absPath:cS(`project-local`,r,u),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function be(){return pye({cwd:r,homedirOverride:u,warn:e=>C.debug({message:e},`[config] diagnostics read`)})}function xe(e){let t={user:gne,project:ve,"project-local":zn};for(let n of be().diagnostics)if(e===void 0||t[n.scope]===e){if(n.code===`VALUE_FALLBACK`){for(let e of n.issues)C.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`&&C.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 Se(e){return`${c4(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function Ce(e){return`${e.maxBatchSize}|${e.maxBatchChars}|${e.docTimeoutMs}`}let we,Te=0;function Ee(e,t){let i;if(e===`__config__/project`||e===`__local__/project`){let t=pe();i=t.mode,ii?.setMode(t.mode,t.source).catch(n=>{C.warn({err:n,mode:t.mode,docName:e},`[sync] failed to apply autoSync mode from config`)});let n=me();ii?.setIntervals(n.pullIntervalSeconds,n.pushIntervalSeconds)}let a=_e();if(ft.applyConfig({enabled:a.enabled,providerFingerprint:Se(a),transportFingerprint:Ce(a),maxBatchSize:a.maxBatchSize}),e===`__config__/project`){Te+=1;try{let e=fe({requireValid:!0});qe?.setAttachmentFolderPath(e),we!==void 0&&e!==we&&C.warn({previous:we,next:e},`[content-filter] attachment folder changed — files under the previous folder no longer sync`),we=e}catch(e){C.warn({err:e},`[content-filter] project config invalid — keeping previous attachment admission`)}O?.signal(`lint-config`),(t??he().plugins.okf?.generate?.index===!0)||zMt({projectDir:r,contentDir:n,generatedDocNames:mn(),enabled:!1}).then(e=>{e.ok||C.warn({state:e.status.state},`[index] could not remove Open Knowledge generated-index Git attributes`)}),ln()}C.info({docName:e,autoSyncMode:i,semanticEnabled:a.enabled},`[config] applied persisted config to in-process consumers`)}kU();let De=Pc(),Oe=!1,ke=!1,Ae=g3e(n,v),Me=e=>{if(Oe)throw new JK(!1);y3e(Ae,e)},Ne=e=>{Me(e),b3e(Ae,e)},Pe=h3e(Me);function Fe(e){VY(e,r,{allowShareableOkArtifact:aK});let t=YK(e),n=cG(U(YK(r),t));Ae.kind===`tree`&&!KK({kind:`tree`,path:Ae.path,excluded:[]},t)&&aK(n)||Me(t)}let Ie=qJ(r),Le=new pXe({localDir:Ie,log:q(`acp-registry`),fetchImpl:e.acpRegistryFetchImpl}),Re=new iXe(Ie,q(`acp-permissions`)),ze;try{ze=m3e({scope:Ae,projectDir:YK(r),serverInstanceId:De,registryPath:e.authorityRegistryPath})}catch(e){if(e instanceof VK&&e.existing.projectDir===YK(r)){let t=N4(Ie);if(t?.pid===e.existing.pid)throw new j4(t,H(Ie,`server.lock`))}throw e}Ae=ze.scope;let Be=!1;try{M4(Ie,{port:0,worktreeRoot:r,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),Be=!0,_||HPt({lockDir:Ie,shadowRepoDir:Bx(r)})}catch(e){Be&&F4(Ie);try{ze.release()}catch(e){C.error({err:e},`[server] startup authority release failed`)}throw e}let Ve=Rn(),Ue=Idt(()=>B2(ei,n)),We=Ldt(()=>B2(ei,n)),Ge=(e,t)=>{let n=Nut(e);return n===null||!n.includes(`/`)?Ve.resolveEmbed(e,t):We(n)??null},Ke=(e,t)=>{let r=Ge(e,t);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=W(n,r);if(!lG(i,W(n)))return null;try{let e=mc(i);return e.isFile()?e.size:null}catch{return null}},qe,Je,Ye,Xe,Ze,Qe,$e,et,tt,nt,rt,it,at=null,ot=null,st=null,ct=null,lt=null,ut=null,dt=_e(),ft=new Cpt({loadEmbedder:()=>{let t=_e(),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??apt)(n)},cacheDir:H(qJ(r),`embeddings`),enabled:dt.enabled,providerFingerprint:Se(dt),transportFingerprint:Ce(dt),maxBatchSize:dt.maxBatchSize}),pt=null,mt=new Map,ht=!1,gt=[],_t,vt,yt,bt,xt=new Promise((e,t)=>{yt=e,bt=t}),St=!1;xt.then(()=>{St=!0},()=>{});let Ct=e=>W3(e,r,u??yc()),wt=()=>!0,Tt=new iNt({projectDir:r,contentDir:n,getShadow:()=>Ye?.current,isReady:()=>St,signal:()=>O?.signal(`sync-status`),isHeld:e=>ie.has(e),isSaveHeld:e=>wt(e),resolveFile:e=>{let t;try{if(_U(e))t=M7(e,Ze.configPersistenceCtx);else if(vU(e))t=r6(e,Ze.managedArtifactCtx);else return null}catch(t){return C.debug({err:t,docName:e},`[doc-notices] no file to name for a notice outside the content folder`),null}return{abs:t,display:Ct(t)}}}),Et=kCt({getShadow:()=>Ye?.current,contentRoot:p??``,getBranch:T,writeCheckpoint:e.mergeHistoryWriter,notices:Tt}),Dt=Promise.withResolvers(),Ot,kt=new Promise(e=>{Ot=e});async function At(){let e,t=Symbol(`branch-scope-gate-timeout`),n=new Promise(n=>{e=setTimeout(()=>n(t),1e4),e.unref?.()});try{if(await Promise.race([kt,n])!==t)return N()}finally{e&&clearTimeout(e)}try{return t9(r).branch??null}catch(e){return C.warn({err:e},`[auth] branch scope gate expired and HEAD is unreadable — skipping the branch claim check`),null}}function jt(e){O?.signal(e)}let Mt,Nt,Pt,It=!1,Lt=!1,Rt=new AbortController,zt=new Set,Bt=!1,Vt=!1,Ht=!1,Ut=0,Wt,Gt=new Promise(e=>{Wt=e});function Kt(e){Ht||(Ht=!0,Wt(e))}function qt(){return Bt||zt.size>0}function Jt(){Lt||!It||(Mt!==void 0&&clearTimeout(Mt),Mt=setTimeout(()=>{Mt=void 0,rn()},500),Mt.unref?.())}function Yt(){if(Lt){Kt({status:`cancelled`,indexCount:0});return}Bt=!0,Vt=!0,Nt=setImmediate(()=>{Nt=void 0,rn()})}let Xt,Zt,Qt=!1,$t=null;async function en(){let e=Ye.current;if(!e||Qt)return;let t=performance.now();C.info({gitDir:e.gitDir},`[shadow-housekeeping] deferred boot housekeeping started`);try{await W5e(e)}catch(e){C.warn({err:e},`failed to write gc config (non-fatal)`)}if(!Qt){if($t)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 B$(e,$t,{rebuild:!0})).skipped){n=!0;break}if(r===29)break;if(await new Promise(e=>{setTimeout(e,t).unref?.()}),Qt)return}n||C.warn({gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild retry budget exhausted (persistent GC contention); rebuild deferred to next boot`)}catch(t){C.warn({err:t,gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild failed; index loaded without GC`)}if(!Qt){try{await Xe?.runBootMaintenance()}catch(e){C.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}C.info({gitDir:e.gitDir,durationMs:Math.round(performance.now()-t)},`[shadow-housekeeping] deferred boot housekeeping complete`)}}}function tn(){Qt||(Xt=setImmediate(()=>{Xt=void 0,Zt=en().catch(e=>{C.error({err:e},`[shadow-housekeeping] unexpected uncaught failure`)})}))}async function nn(){if(Qt=!0,Xt!==void 0&&(clearImmediate(Xt),Xt=void 0),!Zt)return;let e,t=new Promise(t=>{e=setTimeout(()=>t(`timeout`),m)});try{if(await Promise.race([Zt,t])===`timeout`)throw Error(`shadow housekeeping drain timed out after ${m}ms — abandoning in-flight housekeeping`)}finally{e!==void 0&&clearTimeout(e)}}function rn(){if(Lt||!It||!qt())return;if(Pt!==void 0){e.generatedIndexTestHooks?.onKickWhileInFlight?.();return}if(M.isBatchInProgress()){Jt();return}let t=Bt,n=new Set(zt),r=Vt;Bt=!1,zt.clear(),Vt=!1;let i=t?{fullSweep:!0}:{fullSweep:!1,directories:n};Pt=(async()=>{let e=await vn(i,Rt.signal);if(e.status===`deferred`){Bt=!0,r&&(Ut+=e.indexCount,Vt=!0);return}r&&(Ut+=e.indexCount,e.status===`completed`&&qt()?Vt=!0:Kt({...e,indexCount:Ut}))})().catch(e=>{C.warn({err:e},`[index] index regeneration coordinator failed`),r&&Kt({status:`failed`,indexCount:0})}).finally(()=>{if(Pt=void 0,Lt){r&&Kt({status:`cancelled`,indexCount:0});return}qt()&&Mt===void 0?Jt():!qt()&&Mt===void 0&&e.generatedIndexTestHooks?.onIdle?.()})}async function an(){if(!Lt){let e=Pt;Lt=!0,Rt.abort(),Mt!==void 0&&(clearTimeout(Mt),Mt=void 0),Nt!==void 0&&(clearImmediate(Nt),Nt=void 0),zt.clear(),Bt=!1,Vt=!1,e===void 0&&Kt({status:`cancelled`,indexCount:0})}await Pt}function on(e){Lt||UMt(e)||(zt.add(J7(e)),Jt())}function sn(e){if(!Lt){for(let t of HMt(e))zt.add(t);Jt()}}function cn(e){let t=ei?.getFileIndex();if(!t){on(e);return}let n=J7(e);if(Y7(t.keys()).has(n)){on(e);return}sn(J7(n))}function ln(){Lt||(Bt=!0,Jt())}function un(e){let t=ei?.getFileIndex().get(e);if(t)return{title:t.title,description:t.description,type:t.type}}let dn=!1,fn={origin:oIt,writer:e7e,isConflict:e=>ue.has(e),getDocument:e=>$e.documents.get(e),writeDisk:async(e,t)=>{Me(e),YU(V(e),{recursive:!0}),await aS(e,t,{fs:Pe})},registerWrite:(e,t)=>hX(e,uG(t)),noteFileIndex:e=>ei?.mutateFileIndex({kind:e.kind,path:e.absPath,docName:e.docName,content:e.markdown}),signalFiles:()=>jt(`files`),attribute:async(e,t)=>{c$(e,t.id,t.name,t.id),dn=!0}};function pn(e){return e===``?K7:`${e}/${K7}`}function mn(){return[...ei?Y7(ei.getFileIndex().keys()):new Set([``])].map(pn)}function hn(e){let t=he().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 gn(){return hn(FMt({projectDir:r,contentDir:n,generatedDocNames:mn()}))}async function _n(e){let t=await zMt({projectDir:r,contentDir:n,generatedDocNames:mn(),enabled:e});if(!t.ok)return{...gn(),applied:!1,reason:t.status.state===`conflict`?`git-conflict`:`git-unavailable`};let i=await uS({cwd:r,scope:`project`,patch:{contentRules:{okf:{generate:{index:e}}}}});if(!i.ok){try{await t.rollback()}catch(e){C.error({err:e},`[index] could not roll back generated-index Git attributes`)}return{...gn(),applied:!1,reason:`config-write`}}try{let e=K(i.path,`utf-8`);await F7($e.documents.get(`__config__/project`)??null,ve,e,Ze.configPersistenceCtx)}catch(e){C.warn({err:e},`[index] generated-index settings reflection deferred to config watcher`)}return Ee(ve,e),xe(ve),{...gn(),applied:!0}}async function vn(t,i){let a=0,o=t.fullSweep?performance.now():void 0,s=()=>he().plugins.okf?.generate?.index!==!0;try{if(i.aborted)return{status:`cancelled`,indexCount:0};if(s())return{status:`disabled`,indexCount:0};let c=ei?.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(M.isBatchInProgress())return{status:`deferred`,indexCount:a};let o=qMt({docs:c,docExtension:KH,currentMarkdownFor:()=>null,warningScope:D}),l=FMt({projectDir:r,contentDir:n,generatedDocNames:o.map(({directory:e})=>pn(e))});if(l.state!==`ready`&&l.state!==`not-applicable`)return C.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(M.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=pn(r),l=W(n,`${o}.md`);Me(l);let u;try{u=K(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&C.warn({err:e,path:RU(l)},`[index] could not read the existing generated index; treating it as absent`),u=null}a+=1;let d=await TMt({docName:o,absPath:l,markdown:c,currentMarkdown:u},fn);d===`blocked-conflict`?C.warn({event:`generated-index-regeneration`,outcome:`blocked`,directory:r,reason:`conflict`},`[index] generated index regeneration blocked by active conflict`):C.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&&sn(J7(r))}}finally{dn&&=(await Ze.waitForPendingCommits(),await Ze.flushContributors(),!1),o!==void 0&&(r4(`generatedIndexSweepMs`,Math.round((performance.now()-o)*100)/100),Nft(`generatedIndexCount`,a))}return{status:`completed`,indexCount:a}}catch(e){return C.warn({err:e},`[index] index regeneration failed`),{status:`failed`,indexCount:a}}}let yn=null,bn=!1,xn=()=>{try{FPt(r,Sn.entries())}catch(e){C.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Sn=new EPt(void 0,{onEviction:()=>NQe(),onSizeChange:e=>PQe(e),onMutate:()=>{!bn||yn!==null||(yn=setTimeout(()=>{yn=null,xn()},2e3))}});for(let[e,t]of PPt(r))SU(e)||o5(e)&&([`.md`,`.mdx`].some(t=>{let r=W(n,`${e}${t}`);return lG(r,W(n))&&G(r)})||Sn.restore(e,t));bn=!0;let Cn={current:null},wn=new WeakMap,Tn=new Map,En=W(n);function Dn(e){if(!o5(e))return null;let t=YH(e),n=W(En,t);return lG(n,En)?n:null}function On(e){let t=ei?.getFileIndex().get(e)?.canonicalPath??Dn(e);return t!==null&&KX(e,t,n,qe)}function kn(e){let t=wn.get(e);return t||(t={source:e.getText(`source`).toString(),mutation:void 0,adoption:void 0,pendingRetirement:!1},wn.set(e,t)),t}function An(e){for(let t of Tn.get(e)??[])t.namespaceAllowed=!1}function jn(e,t){if(ke||e.isDestroyed||$e.documents.get(t)!==e)return;let n=kn(e);n.pendingRetirement=!1,n.adoption={};for(let e of Tn.get(t)??[])e.namespaceAllowed=!1,e.residentAllowed=!1}function Mn(e){wn.set(e,{source:e.getText(`source`).toString(),mutation:void 0,adoption:void 0,pendingRetirement:!0})}function Nn(e){if(ke)return;An(e);let t=$e.documents.get(e);t&&Mn(t),Cn.current?.deleted(e)}function Pn(e){let t=$e.documents.get(e),n=t?kn(t):void 0,r=n?.adoption;return()=>{ke||(An(e),t&&$e.documents.get(e)===t&&wn.get(t)===n&&n?.adoption===r&&Mn(t))}}function Fn(e,t){let n=wn.get(e)?.mutation;if(n)return()=>{wn.get(e)===n.occurrence&&jn(e,t)}}function In(e,t){On(e)&&jn(t,e)}function Ln(e,t){let n=$e.documents.get(e),r=()=>(t?.()??!0)&&!On(e),i=!ke&&r(),a={namespaceAllowed:i,residentAllowed:!ke&&n!==void 0&&(i||kn(n).pendingRetirement)},o=Tn.get(e)??new Set;return ke||(o.add(a),Tn.set(e,o)),{document:n,namespaceCurrent:()=>(a.namespaceAllowed&&!r()&&(a.namespaceAllowed=!1),a.namespaceAllowed),residentCurrent:()=>(a.residentAllowed&&(n===void 0||n.isDestroyed||$e.documents.get(e)!==n)&&(a.residentAllowed=!1),a.residentAllowed),dispose:()=>{a.namespaceAllowed=!1,a.residentAllowed=!1,o.delete(a),o.size===0&&Tn.delete(e)}}}let Bn=(e,t)=>{SU(e)||Sn.setRenamed(e,t)},Vn=e=>{if(!SU(e)){if(Sn.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Sn.setDeleted(e)}},Hn=e=>{SU(e)||Sn.delete(e)};try{let m=`./`;try{m=fe()}catch(e){C.warn({err:e},`[content-filter] invalid attachment folder at boot — using sibling admission`)}we=m,qe=dK({projectDir:r,contentDir:n,isContentScopeExcluded:e=>{if(Ae.kind!==`tree`)return!1;try{let t=YK(e);return Ae.excluded.some(e=>KK({kind:`tree`,path:e,excluded:[]},t))}catch(t){let n=sG(t);if(!(t instanceof EK)&&n!==`EACCES`&&n!==`EPERM`)throw t;return C.warn({path:RU(e),code:n},`[content-filter] scope path could not be inspected`),!0}},singleDocRelPath:v,attachmentFolderPath:m,inPlaceSkillDirs:new Set(U1(n).map(e=>e.dir)),rescanInPlaceSkillDirs:e=>uct(n,e),skillRootPaths:sct(n),onAfterRebuild:()=>{Je.refreshContentScope().catch(e=>{q(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),Rtt(ei).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`)})}}),Je=new uft({projectDir:r,contentDir:n,contentFilter:qe,getGlobalSkillRoots:()=>Vgt(Ze.managedArtifactCtx),signalChannel:jt,getLocalTargetInventory:()=>B2(ei,b),onRecoveredFileTarget:(e,t)=>{ei&&OPt({watcher:ei,contentDir:n,relativePath:e,exists:t,invalidateReferencedAssetsCache:lt})}}),Ye={current:f},Xe=s?UNt({getShadow:()=>Ye.current??null,getCurrentBranch:T,contentRoot:p??``,projectGitDir:zx(r)??void 0,isWriterLive:e=>{if(!ct&&!et)return q(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(ct?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of et?.sessionsForConnection(t)??[])return!0;return!1}}):void 0;let _=null;Ze=SPt({contentDir:n,assertContentPath:Me,projectDir:r,conflicts:ue,lifecycleOf:(e,t)=>ue.lifecycleOf(e,t),gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:Ye,ephemeral:y,contentRoot:p,derivedDocumentIndex:Je,configHomedirOverride:u,getCurrentBranch:T,resolveEmbed:Ge,resolveSize:Ke,getPrincipal:()=>pt,onAgentCommit:()=>O?.signal(`session-activity`),onFlushCommit:()=>Xe?.noteFlushCommit(),capturePublicationReceipt:Fn,onDiskFlush:(e,t,n,r)=>{O?.emitDiskAck(e,t),!SU(e)&&(JMt(r,n,e)&&on(e),imt(r,n)&&(lt?.(),jt(`files`)))},onConfigRejected:(e,t)=>O?.emitConfigValidationRejected(e,t),onConfigPersisted:e=>{Ee(e),xe(e)},onManagedSkillPersisted:e=>{let t=ee(e);t?.kind===`skill`&&t.scope===`global`&&(_!==null&&clearTimeout(_),_=setTimeout(()=>{_=null;let e=u??yc();G1(e).then(t=>o0(e,e,t)).then(e=>{e>0&&C.info({refreshed:e},`[in-place-skills] post-edit copy re-sync`)}).catch(e=>C.warn({err:e},`[in-place-skills] post-edit copy re-sync failed`))},2e3),_.unref?.())},isRecentlyRemoved:e=>Sn.has(e),mdManager:e.mdManager,getLossRing:()=>Qe,mergeHistory:Et,ingestDiskAtStore:async(e,t,n)=>{let r;try{r=await Kr({kind:`update`,path:t,docName:e,content:n})}catch(e){return{kind:`failed`,error:e}}switch(r.kind){case`applied`:return r.merge===void 0?{kind:`taken-in`}:{kind:`taken-in`,merge:r.merge};case`nothing-to-take`:return{kind:`taken-in`};case`conflict`:return{kind:`conflict`};case`failed`:return{kind:`failed`,error:r.error};default:return Wr(r)}},durabilityState:M}),wt=e=>Ze.hasHeldSave(e),$e=new HJe({quiet:i,debounce:a,maxDebounce:o,extensions:[Ze.extension]});let w=$e.hooks.bind($e);$e.hooks=(e,t,n)=>{if((e===`afterLoadDocument`||e===`onChange`)&&`document`in t&&!SU(t.document.name)){let n=t.document,r=kn(n);e===`onChange`&&r.mutation===void 0&&n.getText(`source`).toString()!==r.source&&(r.source=void 0,r.mutation={occurrence:r})}return e===`connected`&&`connection`in t&&t.connection&&!SU(t.documentName)&&In(t.documentName,t.connection.document),w(e,t,n)};let D=$e.openDirectConnection.bind($e);function k(e){if(ke)throw new JK(!1);if(SU(e)){if(v!==void 0&&e!==`__system__`&&!_U(e))throw new qK;return}if(v!==void 0&&JH(e)!==JH(HH(v)))throw new qK;if(Oe)throw new JK(!1);v3e(Ae,WG(e,n))}$e.openDirectConnection=(async(e,t)=>{let n=JH(e);return k(n),D(n,t)});let A=$e;gt.push(irt(()=>A.documents.size),art(()=>Ze.getQueueDepths()),srt(()=>{let e=0;for(let t of A.documents.values())e+=t.directConnectionsCount;return{websocket:A.getConnectionsCount()-e,direct:e}})),lrt(),y||(ut=CPt({getLoadedDocuments:()=>A.documents,lifecycleOf:(e,t)=>ue.lifecycleOf(e,t),forceStore:(e,t)=>Ze.forceStore(e,t),isHeldSaveDue:e=>Ze.isHeldSaveDue(e),retryHeldSave:(e,t)=>Ze.retryHeldSave(e,t),getBase:e=>M.getReconciledBase(e),isBatchActive:()=>M.isBatchInProgress(),hasInFlight:e=>M.inFlightFlushCount(e)>0,readDiskBytes:e=>{let t=WG(e,n),r,i;try{r=uc(t),i=mc(r).size}catch(t){let n=sG(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new _9(`symlink cycle at content path: ${e}`):t}if(AK(t,r,n))throw new _9(`symlink-escape: ${t} resolves outside the content dir or into private state`);if(i>524288)throw new _9(`document exceeds the open byte limit: ${e}`);try{return K(r,`utf-8`)}catch(e){if(sG(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs})),vt=$e.shouldUnloadDocument.bind($e),$e.shouldUnloadDocument=e=>{let t=mt.get(e);if(t)return[...t].some(e=>e());if(ht&&!SU(e.name)&&M.isStoreRefused(e.name))return!1;if(ht&&vt(e))return!0;let n=e.name;return SU(n)||te(n)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:vt(e)},_t=async(e,t)=>{let n=()=>$e.documents.get(e.name)===e&&(t?.()??!0),r=mt.get(e)??new Set;r.add(n),mt.set(e,r);try{await $e.unloadDocument(e)}finally{r.delete(n),r.size===0&&mt.delete(e)}},O=new l$e($e),st=new y8e($e),ct=new x8e($e),et=new Yrt($e,{...e.agentSessionOptions,assertDocumentScope:k,awaitWriteAdmission:()=>M.whenWriteAdmitted()});let j=et;gt.push(crt(()=>({active:j.liveSessionCount,limit:j.sessionLimit})));let N=wNt({derivedDocumentIndex:Je,onDocumentSettled:e=>Cn.current?.changed(e)});$e.configuration.extensions.push(N);function ne(e,t,n={}){C.warn({reason:e,docName:t,...n},`[auth-rejection] ${e}`)}$e.configuration.extensions.push({__kind:`principal-auth`,async beforeHandleMessage(e){k(e.documentName)},async onAuthenticate(e){k(e.documentName);let t=e.token,n=f5(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==De)throw ne(`server-instance-mismatch`,e.documentName,{claimedServerInstanceId:r,currentServerInstanceId:De}),new d5(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${De}`);let i=n?.expectedBranch;if(typeof i==`string`&&i.length>0){let t=await At();if(t!==null&&i!==t)throw ne(`branch-mismatch`,e.documentName,{claimedBranch:i,currentBranch:t}),new d5(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${t}`)}if(!n)return;let a=e.context;typeof n.principalId==`string`&&(pt&&n.principalId===pt.id?a.principalId=pt.id:pt?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:pt.id})):a.principalId=n.principalId),typeof n.tabSessionId==`string`&&(a.tabSessionId=n.tabSessionId),a.kind=`human`}}),$e.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!_U(e.documentName)&&!vU(e.documentName))return;let n=e.request,r=n.socket?.remoteAddress;if(r!==void 0&&!VQ(r,t))throw ne(`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(!HQ(a,t))throw ne(`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})`)}}),$e.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){if(!SU(e.documentName)){let t=Dn(e.documentName);if(t!==null&&!G(t))try{await Promise.race([Dt.promise,xt])}catch(t){throw C.error({err:t,docName:e.documentName},`[removal-guard] missing-document admission refused after startup failure`),t}}await APt(e.documentName,{recentlyRemovedDocs:Sn,resolveFilePath:Dn,fileExists:G})}}),$e.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=f5(e.token);XMt(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>$e.documents.get(e)})}}),$e.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()===iH.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${He} rejected — server-only channel`)}}),$e.configuration.extensions.push({async afterUnloadDocument({documentName:e}){M.endRenameCarry(e)}});let P=Qwt({mergeHistoryWriter:e.mergeHistoryWriter,docNotices:Tt,declaredGitHubHosts:x,resolveSyncCredentialConfig:S,hocuspocus:$e,durabilityState:M,ingressPolicy:t,sessionManager:et,commentDocHooksRef:Cn,onNamespaceCreateAccepted:Nn,capturePublicationReceipt:Fn,captureNamespaceMove:Pn,onResidentAdopted:jn,contentDir:n,assertContentPath:Me,assertContentSubtree:Ne,getGeneratedIndexSettingsStatus:gn,setGeneratedIndexEnabled:_n,contentFilter:qe,serverInstanceId:De,getFileIndex:()=>ei?ei.getFileIndex():new Map,getAttachmentFolderPath:fe,getAllFilesIndex:()=>ei?ei.getAllFilesIndex():new Map,getFileIndexGeneration:()=>ei?.getFileIndexGeneration()??0,mutateFileIndex:e=>{let t=e.kind===`update`?un(e.docName):void 0;switch(ei?.mutateFileIndex(e),e.kind){case`update`:YMt(t,e.content,e.docName)&&on(e.docName);break;case`create`:Xn(e.docName,e.content),on(e.docName);break;case`conflict`:on(e.docName);break;case`delete`:Cn.current?.deleted(e.docName),cn(e.docName);break;case`rename`:cn(e.oldDocName),on(e.newDocName);break;case`folder-create`:case`folder-delete`:sn(e.relativePath);break;case`asset-create`:case`asset-delete`:case`file-create`:case`file-update`:case`file-delete`:break;default:cX(e)}},getFolderIndex:()=>ei?ei.getFolderIndex():new Map,getAliasMap:()=>ei?ei.getAliasMap():new Map,getFolderAliasIndex:()=>ei?ei.getFolderAliasIndex():new Map,resolveTrackedFile:Ue,rescanFiles:()=>ei?.rescanFromDisk(),settleDiskEventsForTest:async()=>{await ei?.settle()},enableTestRoutes:d,shadowRef:Ye,flushGitCommit:()=>Ze.flushPendingGitCommit(),flushContributors:()=>Ze.flushContributors(),getCurrentBranch:T,getReportedBranch:E,getDiskAckSVs:()=>O?.getLatestDiskAckSVsAsBase64()??{},getCollabClientCount:e.getCollabClientCount,contentRoot:p,derivedDocumentIndex:Je,signalChannel:jt,agentFocusBroadcaster:st,agentPresenceBroadcaster:ct,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>ii,conflicts:ue,setBatchInProgress:ce(`conflict-resolve`),refreshDocumentsFromDisk:ri,localOpCliArgs:h,authStreamHeartbeatMs:g,projectDir:r,resolveEmbed:Ge,getBridgeLossReporter:()=>it,getPrincipal:()=>pt,agentIntegrations:e.agentIntegrations,acpRegistry:Le,loadAcpCustomAgents:()=>wH(Ie,q(`acp-registry`)),homeDirOverride:u,resetSettingsForTest:u===void 0?void 0:()=>{for(let e of Ur)rMt($e.documents.get(e)??null,e,Ze.configPersistenceCtx),Kn.get(e)?.(),Ee(e)},forceUnloadDocument:_t,ready:xt,recentlyRemovedDocs:Sn,serializeDoc:Jn,evictManagedArtifactLkg:e=>{Ze.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:ft,getSemanticSimilarityFloor:()=>_e().similarityFloor,getLinterBaseConfig:()=>he(),getLinkAdvisoryPolicy:ge,getProjectConfigEpoch:()=>Te,getLinkPreviewsEnabled:ye,resolveGitHubToken:Bxt(e.detectGh,e.tokenStore),getConfigDiagnostics:be,embeddingsSecretsFile:lpt(u),readSemanticProviderConfig:_e,ephemeral:y,onReferencedAssetsCacheInvalidator:e=>{lt=e}});$e.configuration.extensions.push(P),$e.configuration.extensions.push(sNt({clock:e.watcherClock??nX(),refresh:ri})),tt=P.nativeApi,nt=P.localApi,rt=P.shutdownLocalOps;let re=tS({absPath:cS(`project`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project config for bridge guards`)}),ie=re.value.bridge.deferGuard.enabled,ae=re.value.bridge.fixedPoint.enabled,oe=re.value.bridge.preDrain.enabled;Qe=re.value.lossCapture.enabled?new j8e({projectDir:r,maxBytes:re.value.lossCapture.maxBytes}):void 0,re.value.bridge.lossDetector.enabled&&(it=h7e({shadow:()=>Ye.current,ring:Qe,getBranch:()=>T()??`main`,contentRoot:p??``}),et.attachBridgeLossReporter(it)),$e.configuration.extensions.push(IPt({mdManager:Ga,schema:ja,shadowRef:Ye,contentRoot:p,getCurrentBranch:T,resolveEmbed:Ge,resolveSize:Ke,deferGuardEnabled:ie,lossDetectorEnabled:re.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:ae,preDrainEnabled:oe,lossRing:Qe})),$e.configuration.extensions.push(qFt()),$e.configuration.extensions.push({async afterLoadDocument({document:e}){Vtt(e,ue)}})}catch(e){for(let e of gt.splice(0))e();ut?.dispose(),ut=null,Oe=!0,F4(Ie);try{ze.release()}catch(e){C.error({err:e},`[server] construction authority release failed`)}throw e}let Un=null,Wn=new Map,Gn=[],Kn=new Map;function qn(e,t){let n=W(e,`rescue`),r=YH(t),i=W(n,r);return lG(i,n)?i:null}function Jn(e){let t=$e.documents.get(e);return t?w$(t):null}let Yn=(e,t)=>{let n=$e.documents.get(e);m$(M,$e,e,t,Ge,Ke,it),n&&On(e)&&jn(n,e)},Xn=(e,t)=>{let n=fat(M,$e,e,t,Ge,Ke,it),r=$e.documents.get(e);return n===`revived`&&r&&On(e)&&jn(r,e),n},Zn=(e,t)=>{let n=0;for(let[r]of $e.documents){if(SU(r))continue;let i=$e.documents.get(r);if(!i)continue;let a=i.getText(`source`).toString();if(a.includes(e))try{i.transact(()=>{d$(i,a,Ge,r)},u$),n++}catch(e){C.error({originalError:p$(e),docName:r,...t},t.reason===`asset-event`?`[asset-event] failed to re-render ${r} for asset basename ${t.assetBasename}`:`[basename-index] failed to refresh loaded startup embeds in ${r}`)}}return n},Qn=e=>{e&&Zn(`[[${e}]]`,{reason:`asset-event`,assetBasename:e})},$n=()=>{try{let e=Zn(`![[`,{reason:`startup`});C.debug({documentCount:e},`[basename-index] refreshed loaded startup embeds`)}catch(e){C.warn({err:e},`[basename-index] loaded startup embed refresh failed`)}},er=null,tr=e=>{e&&(er===null&&(er=new Set,setImmediate(()=>{let e=er;if(er=null,e)try{for(let t of e)Qn(t)}catch(t){C.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),er.add(e))};function nr(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 cX(e)}}let rr={delete:`external-change-rescue`,rename:`external-change-rescue`,"branch-switch":`external-change-rescue`,"disk-update":`external-change-rescue-disk-update`},ir=(e,t,n,r,i=``,a=!1)=>{if(!Ye.current){let t=a?r===`delete`?` — the delete that follows destroys the document content`:` — the overwrite that follows replaces the document content`:``;return C.warn({docName:e,site:r},`[reconcile] rescue checkpoint not minted for ${e} (${r}) — shadow repo unavailable${t}`),QH(),!1}let o=Ye.current;return queueMicrotask(()=>{VJ(o,p??``,{kind:rr[r],docName:e,contents:t,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:i}}).then(()=>{aZe(),C.info({docName:e,site:r},`[reconcile] rescue checkpoint saved (${r}): ${e}`)}).catch(t=>{oZe();let n=a?r===`delete`?` — the delete that follows destroys the document content`:` — the overwrite that follows replaces the document content`:``;C.error({docName:e,site:r,err:t},`[reconcile] rescue checkpoint write failed (${r}): ${e}${n}`)})}),!0},ar=new WeakSet,or=e.watcherClock??nX(),sr=null,cr=!1,lr=e=>{ie.hold(e),M.holdStores(e.docName)},ur=new Set,dr=new Map,fr=e=>{ie.release(e),dr.delete(e),ur.delete(e),M.releaseStores(e)},pr=null,mr=0;function hr(){mr+=1,or.clearTimeout(pr),pr=null}function gr(e){hr(),_r(e,mr,1).catch(t=>{C.error({err:t,branch:e},`[branch-switch] the follow-up re-checks stopped`)})}async function _r(e,t,n){if(!ei||t!==mr)return;let r;try{r=await ei.recheck(`full`)}catch(t){C.warn({err:t,branch:e,attempt:n},`[branch-switch] follow-up re-check ${n} after switching to ${e} failed`)}if(t!==mr||r?.status===`closed`)return;if(r?.status===`completed`&&!r.partial){C.info({branch:e,attempt:n},`[branch-switch] follow-up re-check ${n} observed the whole tree after switching to ${e}`);return}ZQe();let i={branch:e,attempt:n,status:r?.status??`failed`,partial:r?.partial===!0};if(n>=3){C.warn(i,`[branch-switch] ${n} follow-up re-checks after switching to ${e} did not observe the whole tree; open documents may keep text from the previous branch until a later re-check observes it`);return}C.warn(i,`[branch-switch] follow-up re-check ${n} after switching to ${e} did not observe the whole tree; trying again in ${iIt/1e3} s`),pr=or.setTimeout(()=>{pr=null,_r(e,t,n+1).catch(t=>{C.error({err:t,branch:e},`[branch-switch] the follow-up re-checks stopped`)})},iIt),pr.unref()}let vr=()=>{sr||cr||ie.size===0||(sr=or.setTimeout(()=>{sr=null,yr().catch(e=>{C.error({err:e},`[reconcile] the re-check loop for vanished documents failed`)})},1e3),sr.unref())};async function yr(){if(!ei)return;cr=!0;let e;try{e=await ei.recheck(`metadata`)}catch(e){C.warn({err:e},`[reconcile] the re-check for vanished documents failed`)}finally{cr=!1}try{ie.size>0&&(e?.status!==`completed`||e.partial)&&C.info({status:e?.status??`failed`,partial:e?.partial===!0},`[reconcile] the re-check for ${ie.size} vanished document(s) did not observe the whole tree; trying again`),await jr()}finally{vr()}}function br(e){try{return rc(e),!0}catch(t){let n=sG(t);return n===`ENOENT`||n===`ENOTDIR`?!1:(C.warn({err:t,path:e},`[reconcile] could not tell whether a vanished file is gone`),!0)}}function xr(e,t){let r=e=>{let t=sG(e);return t===`ENOENT`||t===`ENOTDIR`?{kind:`absent`}:{kind:`unreadable`,code:t??`unknown`}};try{rc(t),Ys(t,$s.R_OK)}catch(e){let t=r(e);if(t.kind===`absent`||sG(e)!==`ELOOP`)return t}if(!KX(e,t,n,qe))return{kind:`refused`};try{return{kind:`present`,path:t,content:K(t,`utf-8`)}}catch(e){return r(e)}}function F(e){let t=ei?.getFileIndex().get(e.docName)?.canonicalPath??Dn(e.docName)??e.path;return xr(e.docName,t)}async function Sr(e){if(!ei||br(e.path))return!1;let t=Yet(e),n=te(e.docName),r=new Set;t.lastHash!==void 0&&r.add(t.lastHash),n!==void 0&&r.add(uG(n));let i={docName:e.docName,path:e.path,identity:t.identity,size:t.size,modified:t.modified,hashes:r,text:n??Jn(e.docName)??void 0},a=ie.matchRecentCreate(i,or.now(),e=>{let t=xr(e.docName,e.path);return t.kind===`present`?t.content:void 0});if(a){let t=xr(a.create.docName,a.create.path);if(t.kind===`present`)return pU(a.by===`identity`?`paired-identity`:`paired-hash`),await Jr({kind:`rename`,oldPath:e.path,newPath:a.create.path,oldDocName:e.docName,newDocName:a.create.docName,content:t.content}),!0;C.info({docName:e.docName,create:a.create.docName,probe:t.kind},`[reconcile] ${e.docName}: a recent create could not be read; holding the document instead`)}return lr({...i,afterPass:ei.recoveryPassesStarted(),heldAt:or.now()}),pU(`pending`),C.info({docName:e.docName},`[reconcile] ${e.docName}: its file vanished; it stays open until a re-check of the whole tree, in case it was moved`),vr(),!0}let Cr=()=>{le()||Ze.flushDeferredStores(`within-branch`).catch(e=>{C.error({err:e},`[persistence] deferred store drain failed after a vanished file resolved`)})};async function wr(e,t){fr(e.docName);try{pU(`recreated`),C.info({docName:e.docName},`[reconcile] ${e.docName}: its file is back; taking it in as an update`),await Xr({kind:`update`,path:t.path,docName:e.docName,content:t.content})}finally{Cr()}}async function Tr(e,t){Ze.discardDeferredStore(e.docName,{kind:`deleted-outside`}),fr(e.docName),pU(t);let n={kind:`delete`,path:e.path,docName:e.docName};ar.add(n),await Xr(n)}function Er(e,t){ur.has(e.docName)||(ur.add(e.docName),C.warn({docName:e.docName,code:t},`[reconcile] ${e.docName}: a file is at its path but cannot be read (${t}); it stays held until it can be read or the hold limit passes`))}function Dr(e,t,n,r){let i=ie.has(e.docName),a=r===void 0?``:` (attempt ${r} of 3 past the hold limit)`;C.error({err:n,docName:e.docName,action:t.action,stillHeld:i,overdueAttempt:r},i?`[reconcile] ${e.docName}: ${t.action} failed with an internal error${a}; it is still held`:`[reconcile] ${e.docName}: ${t.action} failed with an internal error${a}; its hold had already ended`)}function Or(e,t){fr(e.docName),Cr(),C.error({docName:e.docName,attempts:t},`[reconcile] ${e.docName}: ended its hold after ${t} failed attempts past the hold limit; its deferred saves were released to run as normal saves`)}async function kr(e,t){if(t)for(let t of ie.dueAfter(e)){let e={action:`checking its path`};try{await Ar(t,e)}catch(n){Dr(t,e,n)}}}async function Ar(e,t){let n=F(e);switch(n.kind){case`present`:t.action=`taking its returned file in`,await wr(e,n);return;case`unreadable`:Er(e,n.code);return;case`absent`:case`refused`:t.action=`applying the delete`,C.info({docName:e.docName,probe:n.kind},`[reconcile] ${e.docName}: no move found after a re-check of the whole tree; the delete stands`),await Tr(e,`deleted`);return;default:throw Error(`unhandled file probe: ${JSON.stringify(n)}`)}}async function jr(){for(let e of ie.heldBefore(or.now()-F9)){let t={action:`resolving its hold at the limit`};try{await Mr(e,t)}catch(n){if(!ie.has(e.docName)){Dr(e,t,n);continue}let r=(dr.get(e.docName)??0)+1;dr.set(e.docName,r),Dr(e,t,n,r),r>=3&&Or(e,r)}}}async function Mr(e,t){let n=`${F9/1e3} s`,r;try{r=F(e)}catch(t){C.error({err:t,docName:e.docName,limitMs:F9},`[reconcile] ${e.docName}: checking its path at the hold limit failed with an internal error; the delete stands as at any hold limit`)}switch(r?.kind){case void 0:break;case`present`:t.action=`taking its returned file in`,await wr(e,r);return;case`absent`:C.warn({docName:e.docName,probe:r.kind,limitMs:F9},`[reconcile] ${e.docName}: its file is gone and no re-check observed the whole tree within ${n}; the delete stands and unsaved typing is in its history`);break;case`unreadable`:C.warn({docName:e.docName,probe:r.kind,code:r.code,limitMs:F9},`[reconcile] ${e.docName}: a file at its path still cannot be read (${r.code}) after ${n}; the hold ends, the document closes and unsaved typing is in its history`);break;case`refused`:C.warn({docName:e.docName,probe:r.kind,limitMs:F9},`[reconcile] ${e.docName}: the entry at its path is still not an admitted Markdown file after ${n}; the hold ends, the document closes and unsaved typing is in its history`);break;default:throw Error(`unhandled file probe: ${JSON.stringify(r)}`)}t.action=`applying the delete at the hold limit`,await Tr(e,`unconfirmed`)}function Nr(e,t,n){let r=T()??`main`,i={from:e,to:t,toFile:`${t}${zs(n)}`},a={writerId:PJ.id,displayName:PJ.name,colorSeed:PJ.id};P8({moves:[i],kind:`file`,branch:r,writer:a,shadow:void 0,notices:Tt});let o=Ye.current;o&&Fr(o,r,i,a)}async function Pr(e,t){try{return(await OJ(e).raw(`for-each-ref`,`--sort=-committerdate`,`--format=%(objectname)`,`refs/wip/${t}/`)).split(`
2228
- `).map(e=>e.trim()).filter(e=>/^[0-9a-f]{40}$/.test(e))}catch(e){return C.warn({err:e,branch:t},`[reconcile] rename: could not read the writers' history heads; the move is recorded without them`),[]}}async function Fr(e,t,n,r){let i=await Pr(e,t),a;try{a=P8({moves:[n],kind:`file`,branch:t,writer:r,shadow:e,notices:void 0,anchors:i})}catch(e){YQe(),C.warn({err:e,oldDocName:n.from,newDocName:n.to},`[reconcile] rename: could not write the rename-log entry for ${n.from} -> ${n.to}; history before the move will not show under the new name`);return}if(a===0)return;let o;try{await Ze.flushContributors()}catch(e){o=e}let s=N$(e.gitDir).byTo.get(n.to);if(s!==void 0&&s.commitSha===``){XQe(),C.warn({err:o,oldDocName:n.from,newDocName:n.to},`[reconcile] rename: wrote the rename-log entry for ${n.from} -> ${n.to}, but no commit claimed it yet; a later commit by the file-system writer claims it, and the next start drops it if none does`);return}o!==void 0&&C.warn({err:o,oldDocName:n.from,newDocName:n.to},`[reconcile] rename: the commit after recording the move failed`)}async function Ir(e,t,n,r,i){let a;try{return a=await $e.openDirectConnection(e),Yn(e,r),ne(e,n),i!==n&&await Jr({kind:`update`,path:t,docName:e,content:i}),C.info({newDocName:e},`[reconcile] rename: unsaved typing carried into ${e}`),!0}catch(t){return C.error({err:t,newDocName:e},`[reconcile] rename: could not carry unsaved typing into ${e}; it is in the rename checkpoint`),!1}finally{await a?.disconnect()}}function Lr(e){for(let[t,r]of $e.documents)if(!SU(t)&&r.getMap(`lifecycle`).get(`status`)===void 0)try{let i=WG(t,n);if(!G(i)||!AK(i,uc(i),n))continue;Rr(t,e,`branch-switch`),r.getMap(`lifecycle`).set(`status`,`deleted-upstream`),C.warn({docName:t,branch:e},`[branch-switch] tombstone: ${t} resolves outside the content dir or into private state on ${e}`)}catch(e){C.error({err:e,docName:t},`[branch-switch] could not check where ${t} resolves`)}}let Rr=(e,t,n,r=!1)=>{let i=te(e),a=Jn(e)??``,o=i===void 0?a!==``:a!==i;return o&&(ir(e,a,t,n,``,r),o)};function zr(e){ue.dissolveReconcile(e),ue.dissolveWorkingTree(ue.fileOf(e))}let Br=(e,t,n,r)=>{(t.kind===`merged`||t.kind===`both-kept`)&&t.dedupSkipped&&(GXe(),C.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`))},Vr=async(e,t,n)=>{let r=n===void 0;wQe();let i=Jn(e)??``,a=T()??`main`,o=uG(t).slice(0,6),s=i!==``&&i!==t,c=s?oi(e,`disk-authoritative-ingest`):`not-needed`;s&&ir(e,i,a,`disk-update`,o,!0);let l=uG(i).slice(0,6),u=r?`absent`:`blockless`,d,f=!1;try{Yn(e,t),zr(e),f=!0}catch(s){d=s,TQe(),C.error({err:s,docName:e},`[reconcile] failed to apply disk-authoritative ingest to Y.Doc for ${e}`),ir(e,t,a,`disk-update`,o,!0),zr(e);let f;try{f=Jn(e)??void 0}catch(t){C.error({err:t,docName:e},`[reconcile] unable to read ${e} back after a failed disk-authoritative ingest; treating the live content as lost`)}f===t?ne(e,t):M.restoreReconciledBase(e,n),c===`lost`&&f!==i&&(EQe(),C.warn({docName:e,baseAbsent:r,reason:`no-base`,ours:l,theirs:o,result:`clean-unrescued`,rescue:c,applyFailed:!0},`[reconcile] ${e} base=${u} reason=no-base result=clean-unrescued ours=${l} theirs=${o} rescue=${c} applyFailed=true`))}if(f){let n=c===`lost`?`clean-unrescued`:`clean`;return c===`lost`&&EQe(),(c===`lost`?C.warn.bind(C):C.info.bind(C))({docName:e,baseAbsent:r,reason:`no-base`,ours:l,theirs:o,result:n,rescue:c},`[reconcile] ${e} base=${u} reason=no-base result=${n} ours=${l} theirs=${o} rescue=${c}`),await Hr(e,t),s?{kind:`applied`,merge:`disk-replaced`}:{kind:`applied`}}return{kind:`failed`,error:d}},Hr=async(e,t)=>{try{await Je.recordDiskUpsert(e,t)}catch(t){C.warn({err:t,docName:e},`[reconcile] ${e}: the derived index could not record the disk version`)}};function Wr(e){throw Error(`unhandled disk intake outcome: ${e.kind}`)}function Gr(e){throw Error(`unhandled reconcile outcome: ${e.kind}`)}async function Kr(e){let{docName:t,content:n}=e;if(Hn(t),YMt(e.previousIndexedFields,n,t)&&on(t),ue.findByDocName(t)?.kind===`merge-native`)try{await ue.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e,docName:t},`[reconcile] conflict prune against git failed`)}let r=$e.documents.get(t);if(!r)return b$(M,void 0,t,n,ue)||M.refreshReceiptWithoutBase(t,n),await Je.recordDiskUpsert(t,n),{kind:`nothing-to-take`};if(Xn(t,n)!==`not-frozen`)return await Je.recordDiskUpsert(t,n),{kind:`nothing-to-take`};let i=uG(n),a=Fgt({receiptHash:M.getReceipt(t)?.hash,eventHash:i,isRecentOwnWrite:M.isRecentOwnWrite(t,i),readDiskHash:()=>{try{return uG(K(e.path,`utf-8`))}catch{return null}}}),o=Igt(a);if(o!==null&&M.getStaleExternalWrite(t)===void 0)return nQe(o),C.debug({docName:t,receiptIntake:a},`[reconcile] ${t}: the disk bytes match its receipt (${a}); nothing to take in`),ue.dissolveReconcile(t),await Hr(t,n),{kind:`nothing-to-take`};let s=te(t),c=Jn(t)??s??``;if(b$(M,r,t,n,ue,c))return await Hr(t,n),{kind:`conflict`};if(s===void 0)return Vr(t,n,void 0);let l=cY({docName:t,base:s,ours:c,theirs:n}),u=uG(s).slice(0,6),d=uG(c).slice(0,6),f=uG(n).slice(0,6),p=c.length,m=n.length,h=l.kind===`clean`||l.kind===`merged`||l.kind===`both-kept`?l.newContent.length:void 0,g=h===void 0?void 0:h-Math.max(p,m),_=h===void 0?``:` newLen=${h} delta=${g}`;switch(C.info({docName:t,base:u,ours:d,theirs:f,result:l.kind,oursLen:p,theirsLen:m,...h===void 0?{}:{newLen:h,delta:g}},`[reconcile] ${t} base=${u} ours=${d} theirs=${f} result=${l.kind} oursLen=${p} theirsLen=${m}${_}`),Br(t,l,c,n),l.kind){case`noop`:return ue.dissolveReconcile(t),await Hr(t,n),{kind:`nothing-to-take`};case`clean`:try{Yn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),ne(t,s),ue.dissolveReconcile(t),{kind:`failed`,error:e}}return ne(t,l.newContent),ZH(),ue.dissolveReconcile(t),await Hr(t,n),{kind:`applied`,merge:`clean`};case`merged`:try{Yn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),ne(t,s),ue.dissolveReconcile(t),{kind:`failed`,error:e}}return ne(t,n),ZH(),ue.dissolveReconcile(t),await Hr(t,n),{kind:`applied`,merge:`merged`};case`both-kept`:try{Yn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply both-kept content to Y.Doc for ${t}; raising the conflict`),ne(t,s),WXe(),ue.raise({kind:`reconcile`,file:ue.fileOf(t),reason:`merged-with-markers`,stages:{base:s,ours:c,theirs:n}}),{kind:`failed`,error:e}}return Et.bothKept(t,{ours:c,theirs:n},l.kept),ne(t,n),ZH(),v$(t,l.kept,`watcher`),ue.dissolveReconcile(t),await Hr(t,n),{kind:`applied`,merge:`both-kept`};case`refused`:return l.reason===`no-base`?Vr(t,n,s):(_$(t,l,`watcher`),(l.reason===`check-failed`||l.reason===`too-large`)&&await Et.keptLive(t,{side:`theirs`,bytes:n},l.reason)?(ne(t,n),y$(t,l.reason,`watcher`),ue.dissolveReconcile(t),await Hr(t,n),{kind:`applied`,merge:`kept-live`}):(WXe(),ue.raise({kind:`reconcile`,file:ue.fileOf(t),reason:mat(l.reason),stages:{base:s,ours:c,theirs:n}}),{kind:`conflict`}));default:return Gr(l)}}let qr=new Map;async function Jr(e,t=e.kind===`delete`||e.kind===`rename`?qr.get(e)??Ln(e.kind===`delete`?e.docName:e.oldDocName,GX(e)):void 0){try{switch(e.kind){case`create`:{let t=Yet(e),n=uG(e.content),r=ie.matchCreate({docName:e.docName,identity:t.identity,size:t.size,modified:t.modified,hash:n,content:e.content});if(r){if(fr(r.vanished.docName),r.by===`same-name`){pU(`recreated`),C.info({docName:e.docName},`[reconcile] ${e.docName}: its file came back; taking it in as an update`),await Jr({kind:`update`,path:e.path,docName:e.docName,content:e.content}),Cr();break}let t=M.beginRenameCarry(r.vanished.docName);try{Ze.discardDeferredStore(r.vanished.docName,{kind:`renamed-outside`,to:e.docName,carry:t}),pU(r.by===`identity`?`paired-identity`:`paired-hash`),await Jr({kind:`rename`,oldPath:r.vanished.path,newPath:e.path,oldDocName:r.vanished.docName,newDocName:e.docName,content:e.content})}finally{M.abandonRenameCarry(r.vanished.docName)}break}ie.rememberCreate({docName:e.docName,path:e.path,identity:t.identity,size:t.size,modified:t.modified,hash:n,at:or.now()}),C.info({docName:e.docName},`[reconcile] create: ${e.docName}`),Xn(e.docName,e.content),await Je.recordDiskUpsert(e.docName,e.content),jt(`files`),on(e.docName),Hn(e.docName);break}case`update`:await Kr(e);break;case`delete`:{let{docName:n}=e,r=t??Ln(n,GX(e));qr.delete(e);try{let t=r.namespaceCurrent(),i=r.residentCurrent();if(!t&&!i){C.debug({docName:n,source:`watcher-delete`,namespaceCurrent:t,residentCurrent:i},`[reconcile] delete skipped: ${n} (stale removal)`);return}if(t&&i&&r.document&&!ar.has(e)&&await Sr(e))return;t&&(zr(n),Cn.current?.deleted(n));let{document:a}=r,o=i&&a?Rr(n,T()??`main`,`delete`,!0):!1;if(i&&(a?.getMap(`lifecycle`).set(`status`,`deleted-upstream`),M.endRenameCarry(n)),t&&P(n),t&&await Je.recordDiskDelete(n),!r.namespaceCurrent()&&!r.residentCurrent()){C.debug({docName:n,source:`watcher-delete`,namespaceCurrent:!1,residentCurrent:!1},`[reconcile] delete skipped: ${n} (stale removal)`);return}if(C.info({docName:n,isDirty:o,source:`watcher-delete`},`[reconcile] delete: ${n} (dirty=${o})`),r.residentCurrent()&&a&&($e.closeConnections(n),await _t(a,r.residentCurrent)),!r.namespaceCurrent()){C.debug({docName:n,source:`watcher-delete`,namespaceCurrent:!1,residentCurrent:r.residentCurrent()},`[reconcile] delete: ${n} not recorded as removed (stale removal)`);return}jt(`files`),Vn(n),cn(n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:n,kind:`deleted`,source:`watcher-delete`}))}finally{r.dispose()}break}case`rename`:{let{oldDocName:n,newDocName:r,content:i}=e,a=t??Ln(n,GX(e));qr.delete(e),M.beginRenameCarry(n);let o=null,s=!1;try{let t=a.document,c=a.residentCurrent()&&t?t:null,l=c?Jn(n):null,u=c?pG(c):null,d=te(n),f=e=>{let t=e.getMap(`lifecycle`);t.set(`status`,`renamed`),t.set(`newPath`,r)},p=a.residentCurrent()&&t?Rr(n,T()??`main`,`rename`):!1;a.residentCurrent()&&t&&f(t),a.namespaceCurrent()&&(zr(n),P(n),Ze.forgetObservedFile(n),Bn(n,r)),ne(r,i),C.info({oldDocName:n,newDocName:r,isDirty:p},`[reconcile] rename: ${n} → ${r} (dirty=${p})`),jt(`files`),Hn(r);try{a.namespaceCurrent()?await Je.recordDiskRename(n,r,i):await Je.recordDiskUpsert(r,i)}catch(e){C.error({oldDocName:n,newDocName:r,err:e},`[reconcile] rename: index update failed for ${n} → ${r}; completing client teardown anyway`)}let m=a.namespaceCurrent()?$e.documents.get(n):void 0,h=m===t?void 0:m;h&&f(h),Xn(r,i),on(r),a.namespaceCurrent()&&Nr(n,r,e.newPath),l!==null&&d!==void 0&&(l===d||await Ir(r,e.newPath,d,l,i))&&(o=u);let g=a.residentCurrent()&&t?t:h;if(s=!!g,g){let e=g.getConnectionsCount();$e.closeConnections(n),await et.closeAllForDoc(n),e>0&&C.info({oldDocName:n,newDocName:r,closedConnections:e},`[reconcile] rename: closed ${e} connection(s) on ${n}`)}if(!a.namespaceCurrent()){C.debug({docName:n,newDocName:r,source:`watcher-rename`,namespaceCurrent:!1,residentCurrent:a.residentCurrent()},`[reconcile] rename: ${n} not recorded as removed (stale removal)`);break}console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:n,to:r,kind:`renamed`,source:`watcher-rename`})),cn(n)}finally{M.settleRenameCarry(n,o),s||M.endRenameCarry(n),a.dispose()}break}case`conflict`:{let{docName:t}=e;if(!$e.documents.get(t))return;let n=te(t)??``,r=Jn(t);r===null?C.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):ne(t,r),ue.raise({kind:`reconcile`,file:ue.fileOf(t),reason:`disk-markers`,stages:{base:n,ours:r??n,theirs:e.content}}),C.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:Ve.add(e.relativePath),jt(`files`),tr(Ls(e.relativePath));break;case`asset-delete`:Ve.remove(e.relativePath),jt(`files`),tr(Ls(e.relativePath));break;case`folder-create`:case`folder-delete`:jt(`files`),sn(e.relativePath);break;case`file-create`:case`file-update`:await Je.recordFileTargetUpsert(e.relativePath),lt?.(),jt(`files`),await ni(e.relativePath);break;case`file-delete`:await Je.recordFileTargetDelete(e.relativePath),lt?.(),jt(`files`);break;default:cX(e)}}catch(t){let n=nr(e);C.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let Yr=[];async function Xr(e){if(!ke){if((e.kind===`delete`||e.kind===`rename`)&&!qr.has(e)&&qr.set(e,Ln(e.kind===`delete`?e.docName:e.oldDocName,GX(e))),le()||Zr!==null){Yr.push(e);return}await Jr(e)}}let Zr=null;function Qr(){if(Zr)return Zr;if(Yr.length===0)return Promise.resolve();let e=Promise.withResolvers();return Zr=e.promise,(async()=>{try{for(;Yr.length>0;){let e=Yr.splice(0,Yr.length);for(let t of e)await Jr(t)}e.resolve()}catch(t){e.reject(t)}finally{Zr=null}})(),e.promise}function $r(){for(let e of qr.values())e.dispose();qr.clear()}let ei=null;function ti(e){return yU(e)||bU(e)||xU(e)}async function ni(e){if(!ti(e))return!1;let t=$e.documents.get(e);return t?await $Nt(t,e,Ze.mermaidPersistenceCtx)!==`unchanged`:!1}async function ri(e,t){if(!ei)return{checked:0,found:0};let r=ei.getAliasMap(),i=ei.getFileIndex(),a=[],o={checked:0,found:0};for(let s of new Set(e)){let e=r.get(s)??s;if(SU(e))continue;if(ti(e)){o.checked++,await ni(e)&&o.found++;continue}let c=i.get(e)?.canonicalPath;if(c!==void 0){a.push(c);continue}try{a.push(WG(e,n))}catch(e){C.debug({err:e,trigger:t},`[reconcile] skipped a re-read for a name outside the content tree`)}}let s=a.length===0?{checked:0,found:0}:await ei.recheckPaths(a),c={checked:s.checked+o.checked,found:s.found+o.found},l={trigger:t,...c};return c.found>0?C.info(l,`[reconcile] re-read on ${t} found outside changes`):C.debug(l,`[reconcile] re-read on ${t} found nothing new`),c}let ii=null,ai=null,oi=(e,t)=>{let n=Ye.current;if(!n)return C.warn({docName:e,context:t},`[rescue] shadow repo unavailable — cannot buffer ${e} (${t})`),QH(),`lost`;try{let r=wU(e)?$e.documents.get(e)?.getText(`source`).toString()??null:Jn(e);if(r===null)return C.warn({docName:e,context:t},`[rescue] skipping ${e} — document dropped from map mid-rescue (${t})`),QH(),`lost`;let i=qn(n.gitDir,e);return i?(YU(V(i),{recursive:!0}),qU(i,r,`utf-8`),aZe(),C.info({docName:e,context:t},`[rescue] rescue buffer saved (${t}): ${e}`),`rescued`):(C.warn({docName:e,gitDir:n.gitDir,context:t},`[rescue] path-traversal guard rejected docName: ${e} (${t})`),QH(),`lost`)}catch(n){return C.error({err:n,docName:e,context:t},`[rescue] failed to write rescue buffer for ${e} (${t})`),QH(),`lost`}};async function si(e){if($e.documents.size===0)return;let t=!1,n=Date.now()+e,r,i=Promise.withResolvers(),a=rIt($e,()=>{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())}};$e.configuration.extensions.push(o);try{let o=Array.from($e.documents.keys());$e.closeConnections(),$e.flushPendingStores();for(let e of $e.documents.values())e.getConnectionsCount()===0&&$e.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($e.documents.values()).some(e=>e.getConnectionsCount()===0&&!vt(e));)await new Promise(e=>setTimeout(e,25));for(let e of M.getRefusedStoreDocNames()){if(SU(e))continue;let t=$e.documents.get(e);if(!t||!vt(t))continue;if(n-Date.now()<50){C.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(oi(e,`refused-store-shutdown`)!==`rescued`){C.warn({docName:e},`[rescue] refused-store doc rescue failed; leaving ${e} to the flush timeout path`);continue}let r=!1,i=!1,a=_t(t).then(()=>{r=!0}).catch(t=>{i=!0,r=!0,C.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){C.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||C.info({docName:e},`[rescue] refused-store doc unload completed after the flush deadline: ${e}`)});continue}i||C.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($e.documents.keys()),r=[],i=[];if(Ye.current)for(let e of n)SU(e)||(oi(e,`flush-timeout`)===`rescued`?r.push(e):i.push(e));else{C.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)SU(e)||(i.push(e),QH())}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=$e.configuration.extensions,n=e.indexOf(o);n!==-1&&e.splice(n,1),r&&clearTimeout(r.id)}}async function ci(){return ai||(ai=(async()=>{let e=Date.now(),t=[],n=Date.now()+Math.min(m,Dne/5),i=()=>Math.max(1,n-Date.now()),a=async(e,t)=>{let n;try{return await Promise.race([e,new Promise((e,r)=>{n=setTimeout(()=>r(Error(`${t} did not retire before the pre-flush deadline`)),i())})])}finally{clearTimeout(n)}};ht=!0;let o=Promise.allSettled([rt()]),s;try{[s]=await a(o,`mutation-drain`)}catch(e){t.push({phase:`mutation-drain`,error:String(e)}),C.error({err:e},`[server] shutdown mutation drain failed`)}or.clearTimeout(sr),sr=null,hr();for(let e of ie.all())Ze.discardDeferredStore(e.docName,{kind:`shutdown`}),Rr(e.docName,T()??`main`,`delete`,!0),pU(`shutdown`),M.releaseStores(e.docName);ie.clear(),M.endAllRenameCarries(),ur.clear(),dr.clear(),ke=!0,$r();for(let e of Tn.values())for(let t of e)t.namespaceAllowed=!1,t.residentAllowed=!1;Tn.clear(),wn=new WeakMap;try{await a(an(),`generated-index`)}catch(e){C.warn({err:e},`[index] generated index shutdown drain failed`),t.push({phase:`generated-index-drain`,error:String(e)})}for(let e of gt.splice(0))e();try{await a(Promise.resolve(ut?.dispose()),`staleness-watchdog`)}catch(e){C.warn({err:e},`[server] staleness watchdog drain failed during destroy`),t.push({phase:`staleness-watchdog-drain`,error:String(e)})}ut=null;try{I4(Ie)}catch(e){C.warn({err:e},`[server] failed to mark server.lock draining`)}Xe?.destroy();try{await a(nn(),`shadow-housekeeping`)}catch(e){C.warn({err:e},`[shadow-housekeeping] shutdown drain failed`),t.push({phase:`shadow-housekeeping-drain`,error:String(e)})}if(yn!==null&&(clearTimeout(yn),yn=null),bn)try{FPt(r,Sn.entries())}catch(e){C.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let c,l=await Promise.race([xt.then(()=>`completed`,e=>(C.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{c=setTimeout(()=>e(`timeout`),i())})]);c!==void 0&&clearTimeout(c),l===`timeout`&&(C.warn({},`[server] init did not complete before the pre-flush deadline`),t.push({phase:`initialization-drain`,error:`Initialization remains pending`}));let u;try{await Promise.race([Promise.allSettled($e.loadingDocuments.values()),new Promise((e,t)=>{u=setTimeout(()=>t(Error(`Pending document loads did not retire`)),i())})])}catch(e){t.push({phase:`document-load-drain`,error:String(e)}),C.error({err:e},`[server] shutdown document load drain failed`)}finally{clearTimeout(u)}let d=$e.documents.size;try{try{try{at&&=(clearTimeout(at),null),ot&&=(clearTimeout(ot),null),w&&=(await w.unsubscribe(),null),ei&&=(await ei.unsubscribe(),null);for(let{docName:e,cleanup:t}of Gn)try{await t()}catch(t){C.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Gn.length=0,Kn.clear()}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{O?.destroy(),ct?.destroy(),Un&&=(await Un.disconnect(),null);for(let[e,t]of Wn)try{await t.disconnect()}catch(t){C.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Wn.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await et.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await fnt()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await si(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-3 flush failed`)}Je.close();let e;try{await Promise.race([(async()=>{await Ze.flushPendingGitCommit(),await Ze.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{ii&&=(await ii.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(Ye.current){let e;try{await Promise.race([xJ(Ye.current).drain(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`shadow mutator drain timeout`)),m)})])}catch(e){t.push({phase:`shadow-mutator-drain`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-5 shadow mutator drain failed`)}finally{e!==void 0&&clearTimeout(e)}try{let e=(await Xj({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&gc(W(Ye.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{G5e(Ye.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}if(s?.status===`rejected`){let e=s.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(`; `)}),C.error({err:e},`[server] shutdown local-op subprocess drain failed`)}let n=Date.now()-e;if(t.length===0){Oe=!0;try{ze.release()}catch(e){t.push({phase:`authority-release`,error:String(e)}),C.error({err:e},`[server] shutdown authority release failed`)}C.info({documentCount:d,durationMs:n},`[server] shutdown flushed ${d} documents in ${n}ms`)}else C.warn({documentCount:d,durationMs:n,phaseErrors:t},`[server] shutdown flushed ${d} documents in ${n}ms with ${t.length} phase error(s)`)}}finally{try{F4(Ie,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await jU()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}if(s?.status===`rejected`)throw s.reason})(),ai)}let li=[];async function ui(){try{pt=await TPt(r),C.info({principalId:pt.id},`[server] principal loaded`)}catch(e){C.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!Ye.current)try{Ye.current=await AJ(r,{deferGcConfig:!0}),C.info({gitDir:Ye.current.gitDir},`[server] history repo initialized at ${Ye.current.gitDir}`),V5e(Ye.current)&&!li.includes(`shadow-excludes`)&&li.push(`shadow-excludes`)}catch(e){C.error({err:e},`[server] history repo init failed`),li.push(`shadow-repo`)}if(Ye.current)try{let e=Nat(Ye.current.gitDir);Zat(Ye.current.gitDir,e),Rat(Ye.current.gitDir,e),$t=e,C.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){C.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(Ye.current)try{await OJ(Ye.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){C.warn({},`[server] history repo appears corrupted — reinitializing`);try{Ye.current=await AJ(r,{deferGcConfig:!0}),V5e(Ye.current)&&!li.includes(`shadow-excludes`)&&li.push(`shadow-excludes`)}catch(e){C.error({err:e},`[server] history repo reinit failed`),Ye.current=void 0,li.includes(`shadow-repo`)||li.push(`shadow-repo`)}}else C.error({err:e},`[server] history repo check failed (transient?)`)}if(Ye.current&&ai===null){let e=Ye.current,t=cG(U(r,n))||`.`;ot=setTimeout(()=>{ot=null,NJ(e,t).catch(e=>{C.debug({err:e},`[shadow] fan-out index warm-up failed (non-fatal)`)})},3e3),ot.unref?.()}if(Ye.current)try{let e=W(Ye.current.gitDir,`last-known-head`),t=null;try{t=K(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await Xj({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await Xj({baseDir:r,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}C.info({lastKnownHead:t,currentHead:n,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=import`);try{await RJ(Ye.current,p??``,t,n,e),nZe()}catch(e){C.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else C.info({currentHead:n},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=noop`);try{gc(e,n,`utf-8`)}catch(e){C.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){C.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=ECt(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;C.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){C.error({err:e},`[server] managed rename recovery failed`),li.push(`managed-rename-recovery`)}try{let e=kmt(r);(e.deleted>0||e.errors>0)&&C.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){C.error({err:e},`[server] upload-tempfile sweep failed`),li.push(`upload-tempfile-sweep`)}try{Un=await $e.openDirectConnection(He),O?.emitServerInfo(De,E()??void 0)}catch(e){C.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),li.push(`cc1-push`)}let t=y?[]:Ur;for(let e of t)try{let t=await $e.openDirectConnection(e);Wn.set(e,t)}catch(t){C.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),li.push(`config-doc:${e}`)}let i=new Map([[ve,cS(`project`,r)],[zn,cS(`project-local`,r)],[gne,cS(`user`,r,u)]]);for(let e of t){let t=i.get(e);if(t)try{C.info({docName:e,path:t},`[config-file-watcher] starting`);let n=async t=>{let n=$e.documents.get(e),r=iMt(e,t,Ze.configPersistenceCtx);C.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let i=await F7(n??null,e,t,Ze.configPersistenceCtx);C.info({docName:e,outcome:i,isEcho:r},`[config-file-watcher] applyExternalConfigChange outcome`),Ee(e),r||xe(e)},r=await Fjt(t,t=>{n(t).catch(t=>{C.warn({err:t,docName:e},`[config-file-watcher] change handler failed`)})});Gn.push({docName:e,cleanup:r}),Kn.set(e,r.resync),C.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){C.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),li.push(`config-file-watcher:${e}`)}}if(!y){let e=null,t=t=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,Je.refreshGlobalSkillNodes().catch(e=>{C.warn({err:e,docName:t},`[backlinks] global skill bundle re-ingest failed`)})},300)},n=async(e,n)=>{let r=Ggt(e,Ze.managedArtifactCtx);if(!r)return;let i=await Zgt($e.documents.get(r)??null,r,n,Ze.managedArtifactCtx);C.info({docName:r,outcome:i},`[managed-artifact-watcher] external change`),jt(`files`),vo(r)&&t(r)},r=e=>{let n=Ggt(e,Ze.managedArtifactCtx);jt(`files`),n&&vo(n)&&t(n)};try{let e=Vgt(Ze.managedArtifactCtx),t=await WNt(e,n,r);Gn.push({docName:`__skill-files__`,cleanup:t}),C.info({roots:e},`[managed-artifact-watcher] skills started`)}catch(e){C.warn({err:e},`[managed-artifact-watcher] skills failed to start`),li.push(`managed-artifact-watcher:skills`)}try{let e=DQ(t6(Ze.managedArtifactCtx)),t=await Fjt(e,()=>{jt(`files`)});Gn.push({docName:`__skill-state__`,cleanup:t}),C.info({path:e},`[skill-state-watcher] started`)}catch(e){C.warn({err:e},`[skill-state-watcher] failed to start`),li.push(`skill-state-watcher`)}}try{let e=W(n,`.okignore`),t=W(r,`.gitignore`),i=null;try{let e=Fs(`git`,[`rev-parse`,`--git-common-dir`],sW({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=C;o.info({okignorePath:e,gitignorePath:t,gitInfoExcludePath:i,ephemeral:y},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=y?null:await Ijt(a,(t,n)=>{(async()=>{if(t===e)try{let e=await F7($e.documents.get(`__config__/okignore`)??null,je,n,Ze.configPersistenceCtx);o.info({docName:je,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 qe.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`),O?.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`),O?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:U(r,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Gn.push({docName:`__ignore-files__`,cleanup:s}),Kn.set(je,s.resync),o.info({okignorePath:e,gitignorePath:t},`[ignore-watcher] multi-path watcher started`))}catch(e){C.warn({err:e,projectDir:r,contentDir:n},`[ignore-watcher] failed to start multi-path watcher`),li.push(`ignore-files-watcher`)}let a=t9(r).branch??`main`;re(a),Ot();let o=Je.beginStartup(a),s=!1,c=performance.now();try{await PU(`ok.boot.indexes`,void 0,async()=>{let t=await o.offlineDeletionsReady,i=0;for(let e of t)SU(e)||Sn.peek(e)?.kind!==`renamed`&&(Sn.setDeleted(e),i++);i>0&&C.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`),Dt.resolve();let{backlinkIndexDegraded:a}=await o.backlinksReady;a&&li.push(`backlink-index`);let c=performance.now(),l=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,d=qe?new Set(U1(n).map(e=>e.dir)):new Set,f=e=>{e.some(e=>l.test(U(b,e).split(Ws).join(`/`)))&&(at&&clearTimeout(at),at=setTimeout(()=>{at=null;try{o0(r,n).then(e=>{e>0&&(C.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),O?.signal(`files`))}).catch(e=>C.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=uct(n,d);if(!(e.size!==d.size||[...e].some(e=>!d.has(e))))return;d=e,qe.rebuildIgnorePatterns().then(t=>{t.ok?(C.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),O?.signal(`files`)):C.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>C.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){C.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};ei=await PU(`ok.boot.seed-walk`,void 0,async()=>Itt(b,Xr,qe,{onRawBatch:f,onRecoveryComplete:()=>Je.recordInventoryReconciled(),onRecoveryPassCompleted:(e,t)=>kr(e,t),nativeBackend:e.watcherBackend,clock:e.watcherClock,freshnessIntervalMs:e.freshnessIntervalMs===void 0?5e3:e.freshnessIntervalMs})),o0(r,n).then(e=>{e>0&&C.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>C.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=u??yc();G1(e).then(t=>o0(e,e,t)).then(e=>{e>0&&C.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>C.warn({err:e},`[in-place-skills] global copy re-sync failed`))}r4(`seedWalkMs`,Math.round(performance.now()-c));{let e=W(n),t=0;for(let[n]of Sn.entries()){if(!o5(n))continue;let r=W(e,`${n}${KH(n)}`);lG(r,e)&&G(r)&&(Sn.delete(n),t++)}t>0&&C.info({count:t},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let p=await Je.settleStartupAfterWatcherSeed();s=!0,p.tagIndexDegraded&&li.push(`tag-index`);let m=0;try{v===void 0?await u5({contentDir:n,contentFilter:qe,basenameIndex:Ve,onSkip:(e,t,n)=>{m++,C.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):nTt({contentDir:n,basenameIndex:Ve,onSkip:(e,t,n)=>{m++,C.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),m>0&&(C.warn({count:m},`[basename-index] startup seed completed with ${m} skipped entries — embeds under inaccessible subtrees will not resolve`),li.push(`basename-index-partial`))}catch(e){C.error({err:e},`[basename-index] startup seed failed`),li.push(`basename-index`)}})}catch(e){if(C.error({err:e},`[server] disk bridge watcher failed to start`),li.push(`file-watcher`),!s){let e=await Je.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&li.push(`tag-index`)}}finally{r4(`indexesMs`,Math.round(performance.now()-c)),ei&&Nft(`fileCount`,ei.getFileIndex().size),$n()}let l=()=>{};try{w=await fNt(r,async({trigger:e})=>{if(C.info({trigger:e},`[batch] begin trigger=${e}`),tZe(),$e.flushPendingStores(),await Ze.flushPendingGitCommit(),ae(`head-watcher`),l(),l=M.holdWriteAdmission(),Ye.current){let e=N(),t=t9(r).branch??e,n=[],i=0;for(let[e,t]of $e.documents){if(SU(e))continue;let r=null;if(t.transact(()=>{r=Jn(e)},aIt),r===null)continue;let a=te(e);if(a===void 0){i++;continue}n.push({docName:e,markdown:r,diskSnapshot:a})}if(i>0&&C.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 s7e(Ye.current,e,IJ.id,n,t);r&&(cZe(),C.info({count:n.length,branch:e,sha:r.slice(0,8)},`[history] parked ${n.length} docs on ${e} → ${r.slice(0,8)}`))}catch(e){C.error({err:e},`[shadow] park failed`)}}},async e=>{let t=Yr.length,i=e.newBranch??`main`;if(C.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`){try{try{await Qr()}finally{$r()}if(e.headMoved&&e.newHead){let t=sIt(r,W(n),e.oldHead,e.newHead);if(t.size>0){tat(t.keys());for(let[e,n]of t)c$(e,R_e(n.email),n.name,n.email,sve(e));await Ze.flushContributors()}}}finally{try{oe(`head-watcher`)&&await se()}finally{l()}}try{await ue.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e},`[head-watcher] conflict prune against git failed`)}}else{sZe(),hr();let t=!1,r=!1,a;try{re(i),ue.setBranch(i),de(),a=await Je.beginBranchSwitch(i),qe.rebuildDirCount();try{let e=0;Ve.clear(),await u5({contentDir:n,contentFilter:qe,basenameIndex:Ve,onSkip:(t,n,r)=>{e++,C.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(C.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`),li.includes(`basename-index-partial`)||li.push(`basename-index-partial`))}catch(e){C.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}try{await Je.settleBranchFromDisk(a)}catch(e){Je.abortBranchSwitch(a),C.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}try{await Qr();let e=await ei?.recheck(`full`);e&&(e.status!==`completed`||e.partial)&&(r=!0,ZQe(),C.warn({branch:i,status:e.status,partial:e.partial===!0},`[branch-switch] the re-check after switching to ${i} did not observe the whole tree; another one runs once the switch ends`)),await Qr()}finally{$r()}if(Lr(i),C.info({branch:i,docCount:$e.documents.size},`[branch-switch] loaded branch ${i} (${$e.documents.size} docs)`),e.oldBranch?.startsWith(`detached-`)&&Ye.current)try{let t=OJ(Ye.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await xJ(Ye.current).withMutator(async()=>{for(let e of n.split(`
2228
+ `).map(e=>e.trim()).filter(e=>/^[0-9a-f]{40}$/.test(e))}catch(e){return C.warn({err:e,branch:t},`[reconcile] rename: could not read the writers' history heads; the move is recorded without them`),[]}}async function Fr(e,t,n,r){let i=await Pr(e,t),a;try{a=P8({moves:[n],kind:`file`,branch:t,writer:r,shadow:e,notices:void 0,anchors:i})}catch(e){YQe(),C.warn({err:e,oldDocName:n.from,newDocName:n.to},`[reconcile] rename: could not write the rename-log entry for ${n.from} -> ${n.to}; history before the move will not show under the new name`);return}if(a===0)return;let o;try{await Ze.flushContributors()}catch(e){o=e}let s=N$(e.gitDir).byTo.get(n.to);if(s!==void 0&&s.commitSha===``){XQe(),C.warn({err:o,oldDocName:n.from,newDocName:n.to},`[reconcile] rename: wrote the rename-log entry for ${n.from} -> ${n.to}, but no commit claimed it yet; a later commit by the file-system writer claims it, and the next start drops it if none does`);return}o!==void 0&&C.warn({err:o,oldDocName:n.from,newDocName:n.to},`[reconcile] rename: the commit after recording the move failed`)}async function Ir(e,t,n,r,i){let a;try{return a=await $e.openDirectConnection(e),Yn(e,r),ne(e,n),i!==n&&await Jr({kind:`update`,path:t,docName:e,content:i}),C.info({newDocName:e},`[reconcile] rename: unsaved typing carried into ${e}`),!0}catch(t){return C.error({err:t,newDocName:e},`[reconcile] rename: could not carry unsaved typing into ${e}; it is in the rename checkpoint`),!1}finally{await a?.disconnect()}}function Lr(e){for(let[t,r]of $e.documents)if(!SU(t)&&r.getMap(`lifecycle`).get(`status`)===void 0)try{let i=WG(t,n);if(!G(i)||!AK(i,uc(i),n))continue;Rr(t,e,`branch-switch`),r.getMap(`lifecycle`).set(`status`,`deleted-upstream`),C.warn({docName:t,branch:e},`[branch-switch] tombstone: ${t} resolves outside the content dir or into private state on ${e}`)}catch(e){C.error({err:e,docName:t},`[branch-switch] could not check where ${t} resolves`)}}let Rr=(e,t,n,r=!1)=>{let i=te(e),a=Jn(e)??``,o=i===void 0?a!==``:a!==i;return o&&(ir(e,a,t,n,``,r),o)};function zr(e){ue.dissolveReconcile(e),ue.dissolveWorkingTree(ue.fileOf(e))}let Br=(e,t,n,r)=>{(t.kind===`merged`||t.kind===`both-kept`)&&t.dedupSkipped&&(GXe(),C.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`))},Vr=async(e,t,n)=>{let r=n===void 0;wQe();let i=Jn(e)??``,a=T()??`main`,o=uG(t).slice(0,6),s=i!==``&&i!==t,c=s?oi(e,`disk-authoritative-ingest`):`not-needed`;s&&ir(e,i,a,`disk-update`,o,!0);let l=uG(i).slice(0,6),u=r?`absent`:`blockless`,d,f=!1;try{Yn(e,t),zr(e),f=!0}catch(s){d=s,TQe(),C.error({err:s,docName:e},`[reconcile] failed to apply disk-authoritative ingest to Y.Doc for ${e}`),ir(e,t,a,`disk-update`,o,!0),zr(e);let f;try{f=Jn(e)??void 0}catch(t){C.error({err:t,docName:e},`[reconcile] unable to read ${e} back after a failed disk-authoritative ingest; treating the live content as lost`)}f===t?ne(e,t):M.restoreReconciledBase(e,n),c===`lost`&&f!==i&&(EQe(),C.warn({docName:e,baseAbsent:r,reason:`no-base`,ours:l,theirs:o,result:`clean-unrescued`,rescue:c,applyFailed:!0},`[reconcile] ${e} base=${u} reason=no-base result=clean-unrescued ours=${l} theirs=${o} rescue=${c} applyFailed=true`))}if(f){let n=c===`lost`?`clean-unrescued`:`clean`;return c===`lost`&&EQe(),(c===`lost`?C.warn.bind(C):C.info.bind(C))({docName:e,baseAbsent:r,reason:`no-base`,ours:l,theirs:o,result:n,rescue:c},`[reconcile] ${e} base=${u} reason=no-base result=${n} ours=${l} theirs=${o} rescue=${c}`),await Hr(e,t),s?{kind:`applied`,merge:`disk-replaced`}:{kind:`applied`}}return{kind:`failed`,error:d}},Hr=async(e,t)=>{try{await Je.recordDiskUpsert(e,t)}catch(t){C.warn({err:t,docName:e},`[reconcile] ${e}: the derived index could not record the disk version`)}};function Wr(e){throw Error(`unhandled disk intake outcome: ${e.kind}`)}function Gr(e){throw Error(`unhandled reconcile outcome: ${e.kind}`)}async function Kr(e){let{docName:t,content:n}=e;if(Hn(t),YMt(e.previousIndexedFields,n,t)&&on(t),ue.findByDocName(t)?.kind===`merge-native`)try{await ue.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e,docName:t},`[reconcile] conflict prune against git failed`)}let r=$e.documents.get(t);if(!r)return b$(M,void 0,t,n,ue)||M.refreshReceiptWithoutBase(t,n),await Je.recordDiskUpsert(t,n),{kind:`nothing-to-take`};if(Xn(t,n)!==`not-frozen`)return await Je.recordDiskUpsert(t,n),{kind:`nothing-to-take`};let i=uG(n),a=Fgt({receiptHash:M.getReceipt(t)?.hash,eventHash:i,isRecentOwnWrite:M.isRecentOwnWrite(t,i),readDiskHash:()=>{try{return uG(K(e.path,`utf-8`))}catch{return null}}}),o=Igt(a);if(o!==null&&M.getStaleExternalWrite(t)===void 0)return nQe(o),C.debug({docName:t,receiptIntake:a},`[reconcile] ${t}: the disk bytes match its receipt (${a}); nothing to take in`),ue.dissolveReconcile(t),await Hr(t,n),{kind:`nothing-to-take`};let s=te(t),c=Jn(t)??s??``;if(b$(M,r,t,n,ue,c))return await Hr(t,n),{kind:`conflict`};if(s===void 0)return Vr(t,n,void 0);let l=cY({docName:t,base:s,ours:c,theirs:n}),u=uG(s).slice(0,6),d=uG(c).slice(0,6),f=uG(n).slice(0,6),p=c.length,m=n.length,h=l.kind===`clean`||l.kind===`merged`||l.kind===`both-kept`?l.newContent.length:void 0,g=h===void 0?void 0:h-Math.max(p,m),_=h===void 0?``:` newLen=${h} delta=${g}`;switch(C.info({docName:t,base:u,ours:d,theirs:f,result:l.kind,oursLen:p,theirsLen:m,...h===void 0?{}:{newLen:h,delta:g}},`[reconcile] ${t} base=${u} ours=${d} theirs=${f} result=${l.kind} oursLen=${p} theirsLen=${m}${_}`),Br(t,l,c,n),l.kind){case`noop`:return ue.dissolveReconcile(t),await Hr(t,n),{kind:`nothing-to-take`};case`clean`:try{Yn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),ne(t,s),ue.dissolveReconcile(t),{kind:`failed`,error:e}}return ne(t,l.newContent),ZH(),ue.dissolveReconcile(t),await Hr(t,n),{kind:`applied`,merge:`clean`};case`merged`:try{Yn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),ne(t,s),ue.dissolveReconcile(t),{kind:`failed`,error:e}}return ne(t,n),ZH(),ue.dissolveReconcile(t),await Hr(t,n),{kind:`applied`,merge:`merged`};case`both-kept`:try{Yn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply both-kept content to Y.Doc for ${t}; raising the conflict`),ne(t,s),WXe(),ue.raise({kind:`reconcile`,file:ue.fileOf(t),reason:`merged-with-markers`,stages:{base:s,ours:c,theirs:n}}),{kind:`failed`,error:e}}return Et.bothKept(t,{ours:c,theirs:n},l.kept),ne(t,n),ZH(),v$(t,l.kept,`watcher`),ue.dissolveReconcile(t),await Hr(t,n),{kind:`applied`,merge:`both-kept`};case`refused`:return l.reason===`no-base`?Vr(t,n,s):(_$(t,l,`watcher`),(l.reason===`check-failed`||l.reason===`too-large`)&&await Et.keptLive(t,{side:`theirs`,bytes:n},l.reason)?(ne(t,n),y$(t,l.reason,`watcher`),ue.dissolveReconcile(t),await Hr(t,n),{kind:`applied`,merge:`kept-live`}):(WXe(),ue.raise({kind:`reconcile`,file:ue.fileOf(t),reason:mat(l.reason),stages:{base:s,ours:c,theirs:n}}),{kind:`conflict`}));default:return Gr(l)}}let qr=new Map;async function Jr(e,t=e.kind===`delete`||e.kind===`rename`?qr.get(e)??Ln(e.kind===`delete`?e.docName:e.oldDocName,GX(e)):void 0){try{switch(e.kind){case`create`:{let t=Yet(e),n=uG(e.content),r=ie.matchCreate({docName:e.docName,identity:t.identity,size:t.size,modified:t.modified,hash:n,content:e.content});if(r){if(fr(r.vanished.docName),r.by===`same-name`){pU(`recreated`),C.info({docName:e.docName},`[reconcile] ${e.docName}: its file came back; taking it in as an update`),await Jr({kind:`update`,path:e.path,docName:e.docName,content:e.content}),Cr();break}let t=M.beginRenameCarry(r.vanished.docName);try{Ze.discardDeferredStore(r.vanished.docName,{kind:`renamed-outside`,to:e.docName,carry:t}),pU(r.by===`identity`?`paired-identity`:`paired-hash`),await Jr({kind:`rename`,oldPath:r.vanished.path,newPath:e.path,oldDocName:r.vanished.docName,newDocName:e.docName,content:e.content})}finally{M.abandonRenameCarry(r.vanished.docName)}break}ie.rememberCreate({docName:e.docName,path:e.path,identity:t.identity,size:t.size,modified:t.modified,hash:n,at:or.now()}),C.info({docName:e.docName},`[reconcile] create: ${e.docName}`),Xn(e.docName,e.content),await Je.recordDiskUpsert(e.docName,e.content),jt(`files`),on(e.docName),Hn(e.docName);break}case`update`:await Kr(e);break;case`delete`:{let{docName:n}=e,r=t??Ln(n,GX(e));qr.delete(e);try{let t=r.namespaceCurrent(),i=r.residentCurrent();if(!t&&!i){C.debug({docName:n,source:`watcher-delete`,namespaceCurrent:t,residentCurrent:i},`[reconcile] delete skipped: ${n} (stale removal)`);return}if(t&&i&&r.document&&!ar.has(e)&&await Sr(e))return;t&&(zr(n),Cn.current?.deleted(n));let{document:a}=r,o=i&&a?Rr(n,T()??`main`,`delete`,!0):!1;if(i&&(a?.getMap(`lifecycle`).set(`status`,`deleted-upstream`),M.endRenameCarry(n)),t&&P(n),t&&await Je.recordDiskDelete(n),!r.namespaceCurrent()&&!r.residentCurrent()){C.debug({docName:n,source:`watcher-delete`,namespaceCurrent:!1,residentCurrent:!1},`[reconcile] delete skipped: ${n} (stale removal)`);return}if(C.info({docName:n,isDirty:o,source:`watcher-delete`},`[reconcile] delete: ${n} (dirty=${o})`),r.residentCurrent()&&a&&($e.closeConnections(n),await _t(a,r.residentCurrent)),!r.namespaceCurrent()){C.debug({docName:n,source:`watcher-delete`,namespaceCurrent:!1,residentCurrent:r.residentCurrent()},`[reconcile] delete: ${n} not recorded as removed (stale removal)`);return}jt(`files`),Vn(n),cn(n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:n,kind:`deleted`,source:`watcher-delete`}))}finally{r.dispose()}break}case`rename`:{let{oldDocName:n,newDocName:r,content:i}=e,a=t??Ln(n,GX(e));qr.delete(e),M.beginRenameCarry(n);let o=null,s=!1;try{let t=a.document,c=a.residentCurrent()&&t?t:null,l=c?Jn(n):null,u=c?pG(c):null,d=te(n),f=e=>{let t=e.getMap(`lifecycle`);t.set(`status`,`renamed`),t.set(`newPath`,r)},p=a.residentCurrent()&&t?Rr(n,T()??`main`,`rename`):!1;a.residentCurrent()&&t&&f(t),a.namespaceCurrent()&&(zr(n),P(n),Ze.forgetObservedFile(n),Bn(n,r)),ne(r,i),C.info({oldDocName:n,newDocName:r,isDirty:p},`[reconcile] rename: ${n} → ${r} (dirty=${p})`),jt(`files`),Hn(r);try{a.namespaceCurrent()?await Je.recordDiskRename(n,r,i):await Je.recordDiskUpsert(r,i)}catch(e){C.error({oldDocName:n,newDocName:r,err:e},`[reconcile] rename: index update failed for ${n} → ${r}; completing client teardown anyway`)}let m=a.namespaceCurrent()?$e.documents.get(n):void 0,h=m===t?void 0:m;h&&f(h),Xn(r,i),on(r),a.namespaceCurrent()&&Nr(n,r,e.newPath),l!==null&&d!==void 0&&(l===d||await Ir(r,e.newPath,d,l,i))&&(o=u);let g=a.residentCurrent()&&t?t:h;if(s=!!g,g){let e=g.getConnectionsCount();$e.closeConnections(n),await et.closeAllForDoc(n),e>0&&C.info({oldDocName:n,newDocName:r,closedConnections:e},`[reconcile] rename: closed ${e} connection(s) on ${n}`)}if(!a.namespaceCurrent()){C.debug({docName:n,newDocName:r,source:`watcher-rename`,namespaceCurrent:!1,residentCurrent:a.residentCurrent()},`[reconcile] rename: ${n} not recorded as removed (stale removal)`);break}console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:n,to:r,kind:`renamed`,source:`watcher-rename`})),cn(n)}finally{M.settleRenameCarry(n,o),s||M.endRenameCarry(n),a.dispose()}break}case`conflict`:{let{docName:t}=e;if(!$e.documents.get(t))return;let n=te(t)??``,r=Jn(t);r===null?C.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):ne(t,r),ue.raise({kind:`reconcile`,file:ue.fileOf(t),reason:`disk-markers`,stages:{base:n,ours:r??n,theirs:e.content}}),C.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:Ve.add(e.relativePath),jt(`files`),tr(Ls(e.relativePath));break;case`asset-delete`:Ve.remove(e.relativePath),jt(`files`),tr(Ls(e.relativePath));break;case`folder-create`:case`folder-delete`:jt(`files`),sn(e.relativePath);break;case`file-create`:case`file-update`:await Je.recordFileTargetUpsert(e.relativePath),lt?.(),jt(`files`),await ni(e.relativePath);break;case`file-delete`:await Je.recordFileTargetDelete(e.relativePath),lt?.(),jt(`files`);break;default:cX(e)}}catch(t){let n=nr(e);C.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let Yr=[];async function Xr(e){if(!ke){if((e.kind===`delete`||e.kind===`rename`)&&!qr.has(e)&&qr.set(e,Ln(e.kind===`delete`?e.docName:e.oldDocName,GX(e))),le()||Zr!==null){Yr.push(e);return}await Jr(e)}}let Zr=null;function Qr(){if(Zr)return Zr;if(Yr.length===0)return Promise.resolve();let e=Promise.withResolvers();return Zr=e.promise,(async()=>{try{for(;Yr.length>0;){let e=Yr.splice(0,Yr.length);for(let t of e)await Jr(t)}e.resolve()}catch(t){e.reject(t)}finally{Zr=null}})(),e.promise}function $r(){for(let e of qr.values())e.dispose();qr.clear()}let ei=null;function ti(e){return yU(e)||bU(e)||xU(e)}async function ni(e){if(!ti(e))return!1;let t=$e.documents.get(e);return t?await $Nt(t,e,Ze.mermaidPersistenceCtx)!==`unchanged`:!1}async function ri(e,t){if(!ei)return{checked:0,found:0};let r=ei.getAliasMap(),i=ei.getFileIndex(),a=[],o={checked:0,found:0};for(let s of new Set(e)){let e=r.get(s)??s;if(SU(e))continue;if(ti(e)){o.checked++,await ni(e)&&o.found++;continue}let c=i.get(e)?.canonicalPath;if(c!==void 0){a.push(c);continue}try{a.push(WG(e,n))}catch(e){C.debug({err:e,trigger:t},`[reconcile] skipped a re-read for a name outside the content tree`)}}let s=a.length===0?{checked:0,found:0}:await ei.recheckPaths(a),c={checked:s.checked+o.checked,found:s.found+o.found},l={trigger:t,...c};return c.found>0?C.info(l,`[reconcile] re-read on ${t} found outside changes`):C.debug(l,`[reconcile] re-read on ${t} found nothing new`),c}let ii=null,ai=null,oi=(e,t)=>{let n=Ye.current;if(!n)return C.warn({docName:e,context:t},`[rescue] shadow repo unavailable — cannot buffer ${e} (${t})`),QH(),`lost`;try{let r=wU(e)?$e.documents.get(e)?.getText(`source`).toString()??null:Jn(e);if(r===null)return C.warn({docName:e,context:t},`[rescue] skipping ${e} — document dropped from map mid-rescue (${t})`),QH(),`lost`;let i=qn(n.gitDir,e);return i?(YU(V(i),{recursive:!0}),qU(i,r,`utf-8`),aZe(),C.info({docName:e,context:t},`[rescue] rescue buffer saved (${t}): ${e}`),`rescued`):(C.warn({docName:e,gitDir:n.gitDir,context:t},`[rescue] path-traversal guard rejected docName: ${e} (${t})`),QH(),`lost`)}catch(n){return C.error({err:n,docName:e,context:t},`[rescue] failed to write rescue buffer for ${e} (${t})`),QH(),`lost`}};async function si(e){if($e.documents.size===0)return;let t=!1,n=Date.now()+e,r,i=Promise.withResolvers(),a=rIt($e,()=>{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())}};$e.configuration.extensions.push(o);try{let o=Array.from($e.documents.keys());$e.closeConnections(),$e.flushPendingStores();for(let e of $e.documents.values())e.getConnectionsCount()===0&&$e.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($e.documents.values()).some(e=>e.getConnectionsCount()===0&&!vt(e));)await new Promise(e=>setTimeout(e,25));for(let e of M.getRefusedStoreDocNames()){if(SU(e))continue;let t=$e.documents.get(e);if(!t||!vt(t))continue;if(n-Date.now()<50){C.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(oi(e,`refused-store-shutdown`)!==`rescued`){C.warn({docName:e},`[rescue] refused-store doc rescue failed; leaving ${e} to the flush timeout path`);continue}let r=!1,i=!1,a=_t(t).then(()=>{r=!0}).catch(t=>{i=!0,r=!0,C.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){C.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||C.info({docName:e},`[rescue] refused-store doc unload completed after the flush deadline: ${e}`)});continue}i||C.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($e.documents.keys()),r=[],i=[];if(Ye.current)for(let e of n)SU(e)||(oi(e,`flush-timeout`)===`rescued`?r.push(e):i.push(e));else{C.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)SU(e)||(i.push(e),QH())}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=$e.configuration.extensions,n=e.indexOf(o);n!==-1&&e.splice(n,1),r&&clearTimeout(r.id)}}async function ci(){return ai||(ai=(async()=>{let e=Date.now(),t=[],n=Math.min(m,Dne/5),i=Date.now()+n,a=()=>Math.max(1,i-Date.now()),o=async(e,t)=>{let n;try{return await Promise.race([e,new Promise((e,r)=>{n=setTimeout(()=>r(Error(`${t} did not retire before the pre-flush deadline`)),a())})])}finally{clearTimeout(n)}};ht=!0;let s=Promise.allSettled([rt()]),c;try{[c]=await o(s,`mutation-drain`)}catch(e){t.push({phase:`mutation-drain`,error:String(e)}),C.error({err:e},`[server] shutdown mutation drain failed`)}or.clearTimeout(sr),sr=null,hr();for(let e of ie.all())Ze.discardDeferredStore(e.docName,{kind:`shutdown`}),Rr(e.docName,T()??`main`,`delete`,!0),pU(`shutdown`),M.releaseStores(e.docName);ie.clear(),M.endAllRenameCarries(),ur.clear(),dr.clear(),ke=!0,$r();for(let e of Tn.values())for(let t of e)t.namespaceAllowed=!1,t.residentAllowed=!1;Tn.clear(),wn=new WeakMap;try{await o(an(),`generated-index`)}catch(e){C.warn({err:e},`[index] generated index shutdown drain failed`),t.push({phase:`generated-index-drain`,error:String(e)})}for(let e of gt.splice(0))e();try{await o(Promise.resolve(ut?.dispose()),`staleness-watchdog`)}catch(e){C.warn({err:e},`[server] staleness watchdog drain failed during destroy`),t.push({phase:`staleness-watchdog-drain`,error:String(e)})}ut=null;try{I4(Ie)}catch(e){C.warn({err:e},`[server] failed to mark server.lock draining`)}Xe?.destroy();try{await o(nn(),`shadow-housekeeping`)}catch(e){C.warn({err:e},`[shadow-housekeeping] shutdown drain failed`),t.push({phase:`shadow-housekeeping-drain`,error:String(e)})}if(yn!==null&&(clearTimeout(yn),yn=null),bn)try{FPt(r,Sn.entries())}catch(e){C.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let l,u=await Promise.race([xt.then(()=>`completed`,e=>(C.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{l=setTimeout(()=>e(`timeout`),a())})]);l!==void 0&&clearTimeout(l),u===`timeout`&&(C.warn({},`[server] init did not complete before the pre-flush deadline`),t.push({phase:`initialization-drain`,error:`Initialization remains pending`}));let d;try{await Promise.race([Promise.allSettled($e.loadingDocuments.values()),new Promise((e,t)=>{d=setTimeout(()=>t(Error(`Pending document loads did not retire`)),a())})])}catch(e){t.push({phase:`document-load-drain`,error:String(e)}),C.error({err:e},`[server] shutdown document load drain failed`)}finally{clearTimeout(d)}let f=$e.documents.size;try{try{try{at&&=(clearTimeout(at),null),ot&&=(clearTimeout(ot),null),w&&=(await w.unsubscribe(),null),ei&&=(await ei.unsubscribe(),null);for(let{docName:e,cleanup:t}of Gn)try{await t()}catch(t){C.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Gn.length=0,Kn.clear()}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{O?.destroy(),ct?.destroy(),Un&&=(await Un.disconnect(),null);for(let[e,t]of Wn)try{await t.disconnect()}catch(t){C.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Wn.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await et.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await fnt()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await si(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([Je.close(),new Promise((t,r)=>{e=setTimeout(()=>r(Error(`derived index close did not settle within ${n}ms`)),n)})])}catch(e){t.push({phase:`derived-index-close`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown derived-index close failed`)}finally{e!==void 0&&clearTimeout(e)}let r;try{await Promise.race([(async()=>{await Ze.flushPendingGitCommit(),await Ze.waitForPendingCommits()})(),new Promise((e,t)=>{r=setTimeout(()=>t(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{r!==void 0&&clearTimeout(r)}try{ii&&=(await ii.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(Ye.current){let e;try{await Promise.race([xJ(Ye.current).drain(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`shadow mutator drain timeout`)),m)})])}catch(e){t.push({phase:`shadow-mutator-drain`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-5 shadow mutator drain failed`)}finally{e!==void 0&&clearTimeout(e)}try{let e=(await Xj({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&gc(W(Ye.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{G5e(Ye.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}if(c?.status===`rejected`){let e=c.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(`; `)}),C.error({err:e},`[server] shutdown local-op subprocess drain failed`)}let n=Date.now()-e;if(t.length===0){Oe=!0;try{ze.release()}catch(e){t.push({phase:`authority-release`,error:String(e)}),C.error({err:e},`[server] shutdown authority release failed`)}C.info({documentCount:f,durationMs:n},`[server] shutdown flushed ${f} documents in ${n}ms`)}else C.warn({documentCount:f,durationMs:n,phaseErrors:t},`[server] shutdown flushed ${f} documents in ${n}ms with ${t.length} phase error(s)`)}}finally{try{F4(Ie,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),C.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await jU()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}if(c?.status===`rejected`)throw c.reason})(),ai)}let li=[];async function ui(){try{pt=await TPt(r),C.info({principalId:pt.id},`[server] principal loaded`)}catch(e){C.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!Ye.current)try{Ye.current=await AJ(r,{deferGcConfig:!0}),C.info({gitDir:Ye.current.gitDir},`[server] history repo initialized at ${Ye.current.gitDir}`),V5e(Ye.current)&&!li.includes(`shadow-excludes`)&&li.push(`shadow-excludes`)}catch(e){C.error({err:e},`[server] history repo init failed`),li.push(`shadow-repo`)}if(Ye.current)try{let e=Nat(Ye.current.gitDir);Zat(Ye.current.gitDir,e),Rat(Ye.current.gitDir,e),$t=e,C.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){C.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(Ye.current)try{await OJ(Ye.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){C.warn({},`[server] history repo appears corrupted — reinitializing`);try{Ye.current=await AJ(r,{deferGcConfig:!0}),V5e(Ye.current)&&!li.includes(`shadow-excludes`)&&li.push(`shadow-excludes`)}catch(e){C.error({err:e},`[server] history repo reinit failed`),Ye.current=void 0,li.includes(`shadow-repo`)||li.push(`shadow-repo`)}}else C.error({err:e},`[server] history repo check failed (transient?)`)}if(Ye.current&&ai===null){let e=Ye.current,t=cG(U(r,n))||`.`;ot=setTimeout(()=>{ot=null,NJ(e,t).catch(e=>{C.debug({err:e},`[shadow] fan-out index warm-up failed (non-fatal)`)})},3e3),ot.unref?.()}if(Ye.current)try{let e=W(Ye.current.gitDir,`last-known-head`),t=null;try{t=K(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await Xj({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await Xj({baseDir:r,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}C.info({lastKnownHead:t,currentHead:n,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=import`);try{await RJ(Ye.current,p??``,t,n,e),nZe()}catch(e){C.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else C.info({currentHead:n},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=noop`);try{gc(e,n,`utf-8`)}catch(e){C.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){C.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=ECt(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;C.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){C.error({err:e},`[server] managed rename recovery failed`),li.push(`managed-rename-recovery`)}try{let e=kmt(r);(e.deleted>0||e.errors>0)&&C.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){C.error({err:e},`[server] upload-tempfile sweep failed`),li.push(`upload-tempfile-sweep`)}try{Un=await $e.openDirectConnection(He),O?.emitServerInfo(De,E()??void 0)}catch(e){C.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),li.push(`cc1-push`)}let t=y?[]:Ur;for(let e of t)try{let t=await $e.openDirectConnection(e);Wn.set(e,t)}catch(t){C.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),li.push(`config-doc:${e}`)}let i=new Map([[ve,cS(`project`,r)],[zn,cS(`project-local`,r)],[gne,cS(`user`,r,u)]]);for(let e of t){let t=i.get(e);if(t)try{C.info({docName:e,path:t},`[config-file-watcher] starting`);let n=async t=>{let n=$e.documents.get(e),r=iMt(e,t,Ze.configPersistenceCtx);C.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let i=await F7(n??null,e,t,Ze.configPersistenceCtx);C.info({docName:e,outcome:i,isEcho:r},`[config-file-watcher] applyExternalConfigChange outcome`),Ee(e),r||xe(e)},r=await Fjt(t,t=>{n(t).catch(t=>{C.warn({err:t,docName:e},`[config-file-watcher] change handler failed`)})});Gn.push({docName:e,cleanup:r}),Kn.set(e,r.resync),C.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){C.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),li.push(`config-file-watcher:${e}`)}}if(!y){let e=null,t=t=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,Je.refreshGlobalSkillNodes().catch(e=>{C.warn({err:e,docName:t},`[backlinks] global skill bundle re-ingest failed`)})},300)},n=async(e,n)=>{let r=Ggt(e,Ze.managedArtifactCtx);if(!r)return;let i=await Zgt($e.documents.get(r)??null,r,n,Ze.managedArtifactCtx);C.info({docName:r,outcome:i},`[managed-artifact-watcher] external change`),jt(`files`),vo(r)&&t(r)},r=e=>{let n=Ggt(e,Ze.managedArtifactCtx);jt(`files`),n&&vo(n)&&t(n)};try{let e=Vgt(Ze.managedArtifactCtx),t=await WNt(e,n,r);Gn.push({docName:`__skill-files__`,cleanup:t}),C.info({roots:e},`[managed-artifact-watcher] skills started`)}catch(e){C.warn({err:e},`[managed-artifact-watcher] skills failed to start`),li.push(`managed-artifact-watcher:skills`)}try{let e=DQ(t6(Ze.managedArtifactCtx)),t=await Fjt(e,()=>{jt(`files`)});Gn.push({docName:`__skill-state__`,cleanup:t}),C.info({path:e},`[skill-state-watcher] started`)}catch(e){C.warn({err:e},`[skill-state-watcher] failed to start`),li.push(`skill-state-watcher`)}}try{let e=W(n,`.okignore`),t=W(r,`.gitignore`),i=null;try{let e=Fs(`git`,[`rev-parse`,`--git-common-dir`],sW({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=C;o.info({okignorePath:e,gitignorePath:t,gitInfoExcludePath:i,ephemeral:y},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=y?null:await Ijt(a,(t,n)=>{(async()=>{if(t===e)try{let e=await F7($e.documents.get(`__config__/okignore`)??null,je,n,Ze.configPersistenceCtx);o.info({docName:je,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 qe.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`),O?.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`),O?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:U(r,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Gn.push({docName:`__ignore-files__`,cleanup:s}),Kn.set(je,s.resync),o.info({okignorePath:e,gitignorePath:t},`[ignore-watcher] multi-path watcher started`))}catch(e){C.warn({err:e,projectDir:r,contentDir:n},`[ignore-watcher] failed to start multi-path watcher`),li.push(`ignore-files-watcher`)}let a=t9(r).branch??`main`;re(a),Ot();let o=Je.beginStartup(a),s=!1,c=performance.now();try{await PU(`ok.boot.indexes`,void 0,async()=>{let t=await o.offlineDeletionsReady,i=0;for(let e of t)SU(e)||Sn.peek(e)?.kind!==`renamed`&&(Sn.setDeleted(e),i++);i>0&&C.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`),Dt.resolve();let{backlinkIndexDegraded:a}=await o.backlinksReady;a&&li.push(`backlink-index`);let c=performance.now(),l=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,d=qe?new Set(U1(n).map(e=>e.dir)):new Set,f=e=>{e.some(e=>l.test(U(b,e).split(Ws).join(`/`)))&&(at&&clearTimeout(at),at=setTimeout(()=>{at=null;try{o0(r,n).then(e=>{e>0&&(C.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),O?.signal(`files`))}).catch(e=>C.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=uct(n,d);if(!(e.size!==d.size||[...e].some(e=>!d.has(e))))return;d=e,qe.rebuildIgnorePatterns().then(t=>{t.ok?(C.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),O?.signal(`files`)):C.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>C.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){C.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};ei=await PU(`ok.boot.seed-walk`,void 0,async()=>Itt(b,Xr,qe,{onRawBatch:f,onRecoveryComplete:()=>Je.recordInventoryReconciled(),onRecoveryPassCompleted:(e,t)=>kr(e,t),nativeBackend:e.watcherBackend,clock:e.watcherClock,freshnessIntervalMs:e.freshnessIntervalMs===void 0?5e3:e.freshnessIntervalMs})),o0(r,n).then(e=>{e>0&&C.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>C.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=u??yc();G1(e).then(t=>o0(e,e,t)).then(e=>{e>0&&C.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>C.warn({err:e},`[in-place-skills] global copy re-sync failed`))}r4(`seedWalkMs`,Math.round(performance.now()-c));{let e=W(n),t=0;for(let[n]of Sn.entries()){if(!o5(n))continue;let r=W(e,`${n}${KH(n)}`);lG(r,e)&&G(r)&&(Sn.delete(n),t++)}t>0&&C.info({count:t},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let p=await Je.settleStartupAfterWatcherSeed();s=!0,p.tagIndexDegraded&&li.push(`tag-index`);let m=0;try{v===void 0?await u5({contentDir:n,contentFilter:qe,basenameIndex:Ve,onSkip:(e,t,n)=>{m++,C.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):nTt({contentDir:n,basenameIndex:Ve,onSkip:(e,t,n)=>{m++,C.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),m>0&&(C.warn({count:m},`[basename-index] startup seed completed with ${m} skipped entries — embeds under inaccessible subtrees will not resolve`),li.push(`basename-index-partial`))}catch(e){C.error({err:e},`[basename-index] startup seed failed`),li.push(`basename-index`)}})}catch(e){if(C.error({err:e},`[server] disk bridge watcher failed to start`),li.push(`file-watcher`),!s){let e=await Je.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&li.push(`tag-index`)}}finally{r4(`indexesMs`,Math.round(performance.now()-c)),ei&&Nft(`fileCount`,ei.getFileIndex().size),$n()}let l=()=>{};try{w=await fNt(r,async({trigger:e})=>{if(C.info({trigger:e},`[batch] begin trigger=${e}`),tZe(),$e.flushPendingStores(),await Ze.flushPendingGitCommit(),ae(`head-watcher`),l(),l=M.holdWriteAdmission(),Ye.current){let e=N(),t=t9(r).branch??e,n=[],i=0;for(let[e,t]of $e.documents){if(SU(e))continue;let r=null;if(t.transact(()=>{r=Jn(e)},aIt),r===null)continue;let a=te(e);if(a===void 0){i++;continue}n.push({docName:e,markdown:r,diskSnapshot:a})}if(i>0&&C.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 s7e(Ye.current,e,IJ.id,n,t);r&&(cZe(),C.info({count:n.length,branch:e,sha:r.slice(0,8)},`[history] parked ${n.length} docs on ${e} → ${r.slice(0,8)}`))}catch(e){C.error({err:e},`[shadow] park failed`)}}},async e=>{let t=Yr.length,i=e.newBranch??`main`;if(C.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`){try{try{await Qr()}finally{$r()}if(e.headMoved&&e.newHead){let t=sIt(r,W(n),e.oldHead,e.newHead);if(t.size>0){tat(t.keys());for(let[e,n]of t)c$(e,R_e(n.email),n.name,n.email,sve(e));await Ze.flushContributors()}}}finally{try{oe(`head-watcher`)&&await se()}finally{l()}}try{await ue.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e},`[head-watcher] conflict prune against git failed`)}}else{sZe(),hr();let t=!1,r=!1,a;try{re(i),ue.setBranch(i),de(),a=await Je.beginBranchSwitch(i),qe.rebuildDirCount();try{let e=0;Ve.clear(),await u5({contentDir:n,contentFilter:qe,basenameIndex:Ve,onSkip:(t,n,r)=>{e++,C.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(C.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`),li.includes(`basename-index-partial`)||li.push(`basename-index-partial`))}catch(e){C.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}try{await Je.settleBranchFromDisk(a)}catch(e){Je.abortBranchSwitch(a),C.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}try{await Qr();let e=await ei?.recheck(`full`);e&&(e.status!==`completed`||e.partial)&&(r=!0,ZQe(),C.warn({branch:i,status:e.status,partial:e.partial===!0},`[branch-switch] the re-check after switching to ${i} did not observe the whole tree; another one runs once the switch ends`)),await Qr()}finally{$r()}if(Lr(i),C.info({branch:i,docCount:$e.documents.size},`[branch-switch] loaded branch ${i} (${$e.documents.size} docs)`),e.oldBranch?.startsWith(`detached-`)&&Ye.current)try{let t=OJ(Ye.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await xJ(Ye.current).withMutator(async()=>{for(let e of n.split(`
2229
2229
  `))e&&await t.raw(`update-ref`,`-d`,e)}),C.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){C.error({err:e},`[branch-switch] detached cleanup failed`)}t=!0,oe(`head-watcher`)&&await se(),O?.emitBranchSwitched(i),r&&gr(i)}finally{try{Je.abortBranchSwitch(a),!t&&oe(`head-watcher`)&&await se()}finally{l()}}}if(e.headMoved&&e.newHead&&Ye.current&&t>0){let t=p??`.`;try{let n=await RJ(Ye.current,t,e.oldHead,e.newHead,i);nZe(),C.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){C.error({err:e},`[shadow] upstream-import failed`)}}},{nativeBackend:e.watcherBackend,clock:e.watcherClock,onGaveUp:()=>{li.includes(`head-watcher`)||li.push(`head-watcher`)},onBack:()=>{let e=li.indexOf(`head-watcher`);e!==-1&&li.splice(e,1)}})}catch(e){C.error({err:e},`[server] HEAD watcher failed to start`),li.push(`head-watcher`)}ue.subscribe(e=>{if(e.type!==`raised`||e.conflict.kind===`reconcile`)return;let t=e.docName;if(t===null||!$e.documents.get(t))return;let n=Jn(t);n===null?C.warn({docName:t,file:e.conflict.file},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):ne(t,n)});try{await ue.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e},`[conflicts] boot prune of merge-native entries failed`)}let d=await S(),f=pe(),m=me();f.mode!==`off`&&C.info({mode:f.mode,source:f.source},`[sync] mode active at boot`);try{ii=new GFt({declaredGitHubHosts:x,projectDir:r,contentDir:n,contentFilter:qe,contentRoot:p,mcpTomlEditor:e.mcpTomlEditor,mode:f.mode,pullIntervalSeconds:e.pullIntervalSeconds??m.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds??m.pushIntervalSeconds,credentialConfig:d,resolveCredentialConfig:S,cc1Broadcaster:O,conflicts:ue,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:ce(`sync-engine`),onStateChange:e=>{C.info({state:e},`[sync] state → ${e}`)},checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=Ye.current;n&&await BJ(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=Ye.current;n&&await BJ(n,p??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{C.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await uS({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||C.error({result:t,reason:e,humanError:Ft(t.error),configPath:cS(`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 ii.start()}catch(e){C.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ii=null}jt(`files`),Je.announceReadyViews();let h=Mft();h!==void 0&&r4(`readyMs`,h),xe()}return ui().then(()=>{It=!0,yt(),setImmediate(()=>{let e=A.pruneGone(j);e>0&&C.info({pruned:e},`[disk-receipts] dropped ${e} receipt(s) whose file is gone`)}).unref(),Yt(),tn()},e=>{Lt=!0,Rt.abort(),Kt({status:`failed`,indexCount:0}),Je.close(),Ot(),bt(e)}),{hocuspocus:$e,durabilityState:M,sessionManager:et,nativeApi:tt,localApi:nt,cc1Broadcaster:O,agentFocusBroadcaster:st,agentPresenceBroadcaster:ct,maintenanceCoordinator:Xe,contentFilter:qe,basenameIndex:Ve,serverInstanceId:De,destroy:ci,ready:xt,generatedIndexSweepReady:Gt,degraded:li,lockDir:Ie,get syncEngine(){return ii},conflicts:ue,getLinkPreviewsEnabled:ye,resolveEmbed:Ge,resolveTrackedFile:Ue,acpRegistry:Le,acpPermissions:Re,recheckDisk:()=>ei?ei.recheck():Promise.reject(Error(`the file watcher is not running, so there is nothing to re-check`))}}function I9(e){return e/1048576}function lIt(){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 uIt=1e6;let B9=null,V9=null;AU(()=>{L9=null,R9=null,z9=null,B9?.disable(),B9=null,V9=null});function dIt(){if(L9)return;let e=NU().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}=lIt();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 fIt(){if(!R9){let e=NU().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=zae({resolution:20}),B9.enable();return}e.observe(B9.percentile(50)/uIt,{stat:`p50`}),e.observe(B9.percentile(99)/uIt,{stat:`p99`}),B9.reset()}),R9=e}if(!z9){let e=NU().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 pIt=q(`skill-migrate`);function mIt(e){return[{host:`agents`,root:ki},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=$M.indexOf(e.host),r=$M.indexOf(t.host);return(n===-1?$M.length:n)-(r===-1?$M.length:r)||e.host.localeCompare(t.host)})}const hIt=mIt(to),gIt=mIt(Gr);function _It(e,t){return G(W(e,sn(t)))}function vIt(e,t){YU(V(t),{recursive:!0});try{XU(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;ZU(e,t,{recursive:!0}),rW(e,{recursive:!0,force:!0})}}function yIt(e,t,n){let r=Act(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 bIt(e,t){let n;try{n=uc(W(e,`.ok`,`skills`))}catch{n=W(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!uc(W(e,t.dir)).startsWith(n+Ws)}catch{return!0}}).map(e=>e.name))}async function xIt(e){let{projectDir:t,skillsRoot:n}=e,r,i=async t=>(r??=e.inPlaceNames?.()??Promise.resolve(new Set),(await r).has(t)),a=e.hostRoots??hIt,o={migrated:[],skipped:[]};if(!G(n))return o;let s;try{s=lc(n)}catch{return o}let c=U(t,n).split(Ws).join(`/`),l=new Set;for(let[e,n]of Object.entries(i0(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===c&&l.add(e);for(let e of s)try{if(!Te.test(e)||NH.has(e))continue;if(await i(e)){o.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(l.has(e)){o.skipped.push({name:e,reason:`recorded-placement`});continue}let r=W(n,e);if(!G(H(r,`SKILL.md`)))continue;let s=GM(r)?.contentHash;if(s===void 0)continue;let c=uc(r),u=a.map(({host:n,root:r})=>{let i=W(t,r);return{host:n,root:r,path:H(i,e),escapes:m0(t,i),state:yIt(H(i,e),c,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>_It(t,e.root));if(!d){o.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){o.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?rW(r,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&rW(d.path,{recursive:!0,force:!0}),vIt(r,d.path));for(let e of u)e!==d&&e.state.kind===`store-link`&&(rW(e.path,{recursive:!0,force:!0}),ZU(d.path,e.path,{recursive:!0}));await Z1(t,e),o.migrated.push({name:e,to:`${d.root}/${e}`}),pIt.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){o.skipped.push({name:e,reason:`error`}),pIt.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return o}let H9=null,U9=!1;function SIt(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function CIt(e){if(!SIt())return;let t=qJ(e);H9=new kx({currentPath:W(t,`tolerance-telemetry.jsonl`),previousPath:W(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),yr(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(){yr(null),await H9?.drain(),H9=null,U9=!1}function wIt(e){let t=W(e,Ti);if(!(()=>{if(!G(t))return!0;try{return lc(t).length===0}catch{return!0}})())return[];let n=[];for(let t of c)G(W(e,t))&&n.push(t);for(let t of See){let r=W(e,t);try{G(r)&&mc(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function TIt(e){let t=Rx(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 EIt(e){jft();let t=e.projectDir??e.contentDir,n=bTt({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}`)}Nx.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}kU({localSink:n?.telemetry}),CIt(t),dIt(),fIt();let{kind:r,gitdir:i}=TIt(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=RU(i));let o=pTt(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>PU(`ok.boot`,{attributes:a},async()=>DIt(e)),l=()=>{if(s)try{let e=Do.extract(Co.active(),{traceparent:s});return Co.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 DIt(e){let t=e.skipAutoInit??!1,n=e.log??q(`boot`),r=e.serverRuntime??{...lr(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((gee(r)||!br(i))&&!r.allowExternal)throw new bit(`refusing to start: the server would bind a non-loopback address (${(br(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=BQ({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(()=>Kpt),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 Djt(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 \`${Ci()} init\` to add the recommended ignore entries.`);let _=e.gitPreflight??dW;try{e.gitEnabled!==!1&&_()}catch(e){if(e instanceof cW||e instanceof lW||e instanceof uW){let t=N6(e);P6(e),n.warn({event:`git_preflight_fail`,platform:e.platform,reason:t.reason,detectedVersion:t.detectedVersion},t.logMessage),process.stderr.write(`${e.message}\n`)}throw await jU(),await Promise.race([W9(),new Promise(e=>setTimeout(e,G9))]),e}let v=wIt(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/${Ti}/.`);let y=null,b=cIt({authorityRegistryPath:e.authorityRegistryPath,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,watcherBackend:e.watcherBackend,watcherClock:e.watcherClock,freshnessIntervalMs:e.freshnessIntervalMs}),{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:vjt({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 te=e.serveContentAssets===!1?void 0:tTt({contentDir:e.contentDir,contentFilter:b.contentFilter,contentSirv:yI(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:Ire,assetExtensions:ia,blocklistExtensions:Xne,ingressPolicy:a,resolveTrackedFile:b.resolveTrackedFile}),ne=e.reactShellDistDir?yI(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0,setHeaders:mTt(e.reactShellDistDir)}):void 0,P=e.ephemeral?null:new i8e({contentDir:e.contentDir,localDir:T,globalDir:nS(),registry:b.acpRegistry,permissions:b.acpPermissions,sessionManager:E,agentPresenceBroadcaster:O,localApi:b.localApi,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:()=>r8e(e.localOpCliArgs,ee,{log:n}),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,probePiAcpBridge:e.probePiAcpBridge,ensurePiAcpBridge:e.ensurePiAcpBridge,terminalAuthAvailable:e.terminalAuthAvailable===!0,hostSnapshot:()=>Pq({env:`local-web`,resolve:e.agentIntegrations?.probe}),autoApproveOkTools:()=>QYe(e.projectDir??e.contentDir,e.configHomedirOverride,n),agentBrowserTools:()=>$Ye(e.projectDir??e.contentDir,e.configHomedirOverride,n),log:n});P!==null&&await P.init();let re=`pending`;C.then(()=>{re=`ready`},()=>{re=`failed`});let ie=Tjt({httpServer:N,hocuspocus:x,nativeApi:b.nativeApi,mcpHttpHandler:M,ingressPolicy:a,health:{readiness:()=>re,degraded:()=>w},log:n,sessionManager:E,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,maintenanceCoordinator:k,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:te,reactShellMiddleware:ne,ephemeral:e.ephemeral,acpThreadManager:P}),ae=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)};y=m5(N);let oe=null;if(e.idleShutdownMs!==null){let t=e.idleShutdownMs??18e5,r=e.idleShutdownHandler??(e=>async()=>{await e()});oe=hTt({httpServer:N,counter:y,thresholdMs:t,log:n,onShutdown:r(async()=>{await ae(`idle-shutdown`)})})}let se=[...new Set(i)],ce=se[0],le=async()=>{await S().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(T)},ue=(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 ue(N,e.port??0,ce??`127.0.0.1`)}catch(e){throw await le(),e}let de=N.address(),fe=typeof de==`object`&&de?de.port:e.port??0,pe=[];for(let e of se.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 ue(t,fe,e)}catch(t){n.error({err:t,failedAddress:e,port:fe,alreadyBound:pe.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...pe,N])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await le(),t}pe.push(t)}let me=Mft();me!==void 0&&r4(`httpListenMs`,me);let he=N.address(),ge=typeof he==`object`&&he?he.port:e.port??0;ee=ge;let _e=j();d(T,ge,_e),n.info({event:`server-listening`,pid:process.pid,port:ge,addresses:se,url:_e,lockDir:T},`[boot] listening on ${_e}`);let ve=!1,ye=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=rIt(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)}};ae=async(e=`unspecified`)=>{if(ve)return;ve=!0,n.info({reason:e,pid:process.pid,lockDir:T},`[server] shutdown initiated (${e})`),re=`draining`;let t=[],r=async(e,r,i)=>{try{await ye(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{oe?.detach()}catch(e){t.push(e),n.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(P!==null&&await r(`acpThreads.destroy`,()=>P.destroy()),await r(`secondaryListeners.close`,async()=>{for(let e of pe)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`,()=>ie.shutdown()),M!==void 0&&await r(`mcpHttpHandler.close`,()=>M.close()),await r(`mount.wss.close`,()=>new Promise((e,t)=>{ie.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`,()=>jU()),await r(`teardownToleranceTelemetry`,()=>W9()),await r(`flushLogFileSinks`,()=>Nx.flushAllFileSinks()),t.length>0)throw AggregateError(t,`bootServer destroy completed with errors`)};try{let t=await xIt({projectDir:p,skillsRoot:W(e.contentDir,`.ok`,Oa),inPlaceNames:async()=>bIt(e.contentDir,U1(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=yc(),t=await xIt({projectDir:e,skillsRoot:W(e,`.ok`,Oa),hostRoots:gIt,inPlaceNames:async()=>bIt(e,await G1(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:ae,lockDir:T,contentDir:e.contentDir,port:ge,ready:C,generatedIndexSweepReady:b.generatedIndexSweepReady,degraded:w,didAutoInit:f,serverInstance:b,runtime:Ojt(b,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:P}}const OIt=Pe;function kIt(e={}){let t=e.home??yc(),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=mx(Mge(),1);function q9(){return H(nS(),`logs`)}const AIt=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function jIt(){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 MIt(e){ic(e,{recursive:!0})}function NIt(){return new Date().toISOString().slice(0,10)}function PIt(e){try{if(mc(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{dc(n,r)}catch{}}try{hc(`${e}.3`)}catch{}}function FIt(e){try{let t=Date.now(),n=6048e5,r=lc(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=mc(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{hc(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{hc(H(e,t.name)),a-=t.size}catch{}}}catch{}}function IIt(e){MIt(q9());let t=NIt(),n=e.filePath??H(q9(),`${e.name}.${t}.log`);PIt(n),(e._setTimeout??setTimeout)(()=>FIt(q9()),5e3).unref();let r=K9.default.destination({dest:n,append:!0,sync:!0}),i=jIt();return(0,K9.default)({level:i,name:e.name,redact:{paths:AIt,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 LIt(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 RIt(e){return H(q9(),`${e}.${NIt()}.log`)}function zIt(){return q9()}function BIt(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=Lc(Ms),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 VIt(e,t){try{return await J9(e,[`var`,`GIT_COMMITTER_IDENT`],sW({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function HIt(e,t){try{let{stdout:n}=await J9(e,[`for-each-ref`,`--count=1`,`refs/`],sW({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return Y9.warn({path:t,stderr:WIt(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function UIt(e){let t=W(e,`packed-refs`);if(G(t))try{if(K(t,`utf-8`).split(`
2230
2230
  `).some(e=>e.trim()!==``&&!e.startsWith(`#`)))return!0}catch{return!0}try{return lc(W(e,`refs/heads`)).length>0}catch{return!1}}function WIt(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 GIt(e,t){if(await HIt(e,t))return;let n=[`commit`,`--allow-empty`,`--no-verify`,`--no-gpg-sign`,`-m`,`Initial commit`],r=await VIt(e,t),i=r?n:[`-c`,`user.name=Open Knowledge`,`-c`,`user.email=noreply@openknowledge.local`,...n];try{await J9(e,i,sW({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:WIt(e)},`could not create initial commit`)}}async function KIt(e,t){try{let{stdout:n}=await J9(e,[`rev-parse`,`--is-inside-work-tree`],sW({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function qIt(e){let t=W(e);Zq(t);let n=W(t,`.git`),r=W(n,`HEAD`),i=!1,a=!1;if(G(n)){if(!mc(n).isDirectory())return{didInit:!1};if(G(r)){if(UIt(n))return{didInit:!1};a=!0}else Y9.info({},`detected partial .git/ — running git init to repair`),i=!0}let o;try{o=dW()}catch(e){if(e instanceof cW||e instanceof lW||e instanceof uW){let t=N6(e);P6(e),Y9.warn({event:`git_preflight_fail`,platform:e.platform,reason:t.reason,detectedVersion:t.detectedVersion},t.logMessage)}else Y9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`);throw e}let s=o.resolvedPath;if(a)return await GIt(s,t),{didInit:!1};if(!i&&await KIt(s,t))return{didInit:!1};let c=``;try{c=(await J9(s,[`init`,`--initial-branch=main`,t],sW({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 GIt(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 JIt(e,t){let n;try{n=js(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 Ec(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 YIt=[{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 YIt)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 XIt=class extends Error{filePath;constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},ZIt=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`}},QIt=class extends Error{filePath;constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function $It(e,t={}){if(!zH(e))throw new QIt(e);let n;try{n=uc(W(e))}catch(t){throw t.code===`ENOENT`?new XIt(e):t}if(!mc(n).isFile())throw new ZIt(e);let r=V(n);if(t.projectRoot!==void 0){let e=W(t.projectRoot);if(!zG(e))throw new $9(e,`no .ok/config.yml there, so it is not an OpenKnowledge project root`);let r=eLt(e),i=U(r,n);if(i.startsWith(`..`)||Bs(i))throw new $9(e,`${n} is not inside that project's content directory`);return{mode:`project`,projectRoot:e,docName:HH(i.split(Ws).join(`/`)),canonicalFilePath:n}}let i=w2e(r);if(i){let e=i.rootPath,t=eLt(e);return{mode:`project`,projectRoot:e,docName:HH(U(t,n).split(Ws).join(`/`)),canonicalFilePath:n}}let a=Ls(n);return{mode:`ephemeral`,canonicalFilePath:n,contentDir:r,singleDocRelPath:a,docName:HH(a)}}function eLt(e){let t=tS({absPath:cS(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`;return W(e,t)}const tLt=`ok-ephemeral-`;function nLt(e,t){let n=W(e,`.ok`);return ic(n,{recursive:!0}),gc(W(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(t)}\n`,`utf-8`),gc(W(n,`.gitignore`),`local/
2231
2231
  `,`utf-8`),e}function rLt(e){return nLt(ac(W(Sc(),tLt)),e)}const iLt=`server-base`;export{Krt as $,lEt as $a,Pvt as $i,kIt as $n,Az as $o,aTt as $r,_8e as $t,bit as A,_st as Aa,o5e as Ai,l$ as An,XU as Ao,iJ as Ar,Mx as As,b9 as At,uW as B,G0 as Ba,f5 as Bi,rLt as Bn,EH as Bo,n5e as Br,Loe as Bs,M4 as Bt,HJ as C,F4 as Ca,tbt as Ci,jJ as Cn,DH as Co,mbt as Cr,aye as Cs,VK as Ct,EG as D,h1 as Da,D4 as Di,q0 as Dn,KU as Do,qJ as Dr,Jx as Ds,XIt as Dt,OG as E,Q8e as Ea,P4 as Ei,K0 as En,tW as Eo,Oit as Er,Vx as Es,ZIt as Et,H8e as F,J0 as Fa,RU as Fi,tTt as Fn,qU as Fo,Vbt as Fr,jx as Fs,ywt as Ft,n1 as G,R5 as Ga,$It as Gi,i1 as Gn,PU as Go,CTt as Gr,ooe as Gs,HPt as Gt,d5 as H,K6 as Ha,pJ as Hi,IIt as Hn,RXe as Ho,kU as Hr,Moe as Hs,m$ as Ht,_yt as I,u4 as Ia,jH as Ii,xjt as In,JFt as Io,RQ as Ir,x_e as Is,bwt as It,wpt as J,H9e as Ja,zTt as Ji,cIt as Jn,mvt as Jo,_it as Jr,Z4e as Jt,_5 as K,rat as Ka,RTt as Ki,SPt as Kn,FU as Ko,Cst as Kr,dW as Kt,FJ as L,wFt as La,K8e as Li,dK as Ln,zX as Lo,LNt as Lr,m_e as Ls,x0e as Lt,PJ as M,KJ as Ma,I4 as Mi,RNt as Mn,iW as Mo,a$e as Mr,q as Ms,aft as Mt,u$ as N,n8 as Na,Ejt as Ni,a9 as Nn,$U as No,MU as Nr,k_e as Ns,LH as Nt,$ft as O,o$e as Oa,x4 as Oi,nY as On,YU as Oo,RIt as Or,Bx as Os,QIt as Ot,h4 as P,r8 as Pa,Tjt as Pi,Qwt as Pn,HU as Po,mU as Pr,Nx as Ps,CK as Pt,P$e as Q,lyt as Qa,x6 as Qi,ppt as Qn,pX as Qo,W8e as Qr,gJ as Qt,cW as R,Ivt as Ra,sTt as Ri,s4e as Rn,O4 as Ro,QQe as Rr,h_e as Rs,$W as Rt,Gtt as S,A4 as Sa,r7e as Si,RJ as Sn,W9 as So,iat as Sr,sS as Ss,U6 as St,Qyt as T,E4 as Ta,TPt as Ti,gW as Tn,JU as To,T5 as Tr,Hx as Ts,j4 as Tt,rTt as U,JIt as Ua,OX as Ui,wNt as Un,Jpt as Uo,CIt as Ur,Yc as Us,obt as Ut,iTt as V,Ult as Va,yjt as Vi,pat as Vn,xyt as Vo,AJ as Vr,Zc as Vs,CQ as Vt,V8e as W,o1 as Wa,dbt as Wi,vjt as Wn,sW as Wo,STt as Wr,toe as Ws,q4e as Wt,W6e as X,myt as Xa,ait as Xi,C8e as Xn,x9 as Xo,HTt as Xr,J4e as Xt,V8 as Y,hyt as Ya,$Ye as Yi,IPt as Yn,r5e as Yo,_U as Yr,cX as Yt,Grt as Z,Cyt as Za,$rt as Zi,eq as Zn,MQ as Zo,yZ as Zr,Zq as Zt,Irt as _,S5e as _a,hst as _i,zU as _n,Itt as _o,w2e as _r,nS as _s,LPt as _t,pXe as a,b5 as aa,WTt as ai,Est as an,VJ as ao,P6 as ar,yF as as,EXe as at,Hbt as b,m5e as ba,nJ as bi,q6 as bn,E3e as bo,dut as br,yye as bs,h4e as bt,x8e as c,N4 as ca,eG as ci,BQ as cn,u5 as co,P5 as cr,YN as cs,X9 as ct,cTt as d,VPt as da,i8 as di,ibt as dn,IU as do,Let as dr,TN as ds,_W as dt,C6 as ea,U8e as ei,m5 as en,WG as eo,_$e as er,oR as es,g$e as et,FH as f,Qrt as fa,VQ as fi,NJ as fn,Nrt as fo,Pwt as fr,Gj as fs,IJ as ft,l$e as g,a1 as ga,qX as gi,$et as gn,A7e as go,BIt as gr,Zx as gs,G6 as gt,j2 as h,c$ as ha,SU as hi,Xq as hn,e8 as ho,w$e as hr,rye as hs,W6 as ht,iXe as i,dJ as ia,mJ as ii,EIt as in,I$e as io,Hlt as ir,nR as is,e5e as it,aXe as j,RH as ja,fpt as ji,i9 as jn,rW as jo,NU as jr,O_e as js,iLt as jt,tLt as k,L0 as ka,jvt as ki,uG as kn,GU as ko,zIt as kr,Px as ks,$9 as kt,EQ as l,NQ as la,UQ as li,r8e as ln,nLt as lo,qIt as lr,GN as ls,lot as lt,MH as m,cY as ma,zG as mi,m4 as mn,jU as mo,k2 as mr,iS as ms,rbt as mt,gXe as n,k4 as na,$yt as ni,Ilt as nn,BJ as no,_1 as nr,Pze as ns,Djt as nt,i8e as o,t9 as oa,IQ as oi,J8e as on,UJ as oo,N5 as or,XN as os,b4 as ot,IH as p,jQ as pa,tJ as pi,DXe as pn,OJ as po,LTt as pr,Xj as ps,Jot as pt,xNt as q,U9e as qa,fJ as qi,ZTt as qn,eit as qo,git as qr,wK as qt,Prt as r,Wpt as ra,CU as ri,Vtt as rn,b6 as ro,XTt as rr,$L as rs,fQ as rt,y8e as s,hpt as sa,vU as si,xkt as sn,QTt as so,aDt as sr,JN as ss,Opt as st,_Xe as t,Wlt as ta,HQ as ti,hTt as tn,fwt as to,RPt as tr,RL as ts,cEt as tt,Yrt as u,iit as ua,pQ as ui,zXe as un,Q9 as uo,X as ur,KN as us,t5e as ut,Qq as v,k6 as va,gU as vi,vJ as vn,XJ as vo,U0 as vr,bye as vs,R$e as vt,Qft as w,BX as wa,wH as wi,Q5e as wn,T4 as wo,a7e as wr,uS as ws,HK as wt,OIt as x,hX as xa,NX as xi,Pq as xn,nat as xo,oTt as xr,cS as xs,H6 as xt,D7e as y,gjt as ya,SIt as yi,mpt as yn,gH as yo,LIt as yr,tS as ys,g4e as yt,lW as z,JJ as za,fW as zi,dpt as zn,qpt as zo,nU as zr,el as zs,Bpt as zt};
package/dist/index.mjs CHANGED
@@ -1550,6 +1550,6 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
1550
1550
  `);O(e,o)}function M9(e,t){let n=C(e,`utf-8`);if(n.trim().length!==0)try{let r=A9(JSON.parse(n),t),i=n.endsWith(`
1551
1551
  `)?`
1552
1552
  `:``;O(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=k9(n,t.contentDirSpellings);r!==n&&O(e,r)}}function N9(e,t){let n=C(e,`utf-8`),r=k9(n,t.contentDirSpellings);r!==n&&O(e,r)}function P9(e){try{return T(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>j(e,t.name))}catch{return[]}}const $Fe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function F9(e){return/\.log\.\d+$/.test(e)}function eIe(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||F9(e)}const tIe=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function nIe(e){let t={contentDirSpellings:O9(e.contentDir)};for(let n of tIe)for(let r of P9(j(e.stagingDir,n)))eIe(r)?j9(r,t):r.endsWith(`.json`)?M9(r,t):N9(r,t);for(let n of P9(j(e.stagingDir,`state`))){let e=oe(n);n.endsWith(`.jsonl`)?j9(n,t):$Fe.has(e)?M9(n,t):N9(n,t)}}const I9=[`.ok`,`local`,`telemetry`],L9=[`.ok`,`local`,`logs`],R9=[`.ok`,`local`,`loss-capture`],z9=`spans-current.jsonl`,B9=`spans-prev.jsonl`,V9=`server-current.jsonl`,H9=`server-prev.jsonl`,U9=`loss-current.jsonl`,W9=`loss-prev.jsonl`;function rIe(e){return j(e,...I9,z9)}function iIe(e){return j(e,...I9,B9)}function aIe(e){return j(e,...L9,V9)}function oIe(e){return j(e,...L9,H9)}function sIe(e){return j(e,...R9,U9)}function cIe(e){return j(e,...R9,W9)}const G9=1e3;async function lIe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function uIe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function dIe(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}function fIe(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return null;let n=t.decisions;return Array.isArray(n)?n.length===0?``:`${n.map(e=>JSON.stringify(e)).join(`
1553
- `)}\n`:null}catch{return null}}function pIe(e){let t=j(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],z6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function mIe(e){let t=j(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],z6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function hIe(){return{nodeVersion:process.version,platform:be(),arch:he()}}function gIe(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!_(e))return{};let t;try{t=(0,js.parse)(C(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function _Ie(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return _Ie(e.maxBytes)}function vIe(e){let t=J9(bJ(`project`,e)),n=J9(bJ(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function yIe(e){return Ee(`sha256`).update(e).digest(`hex`)}function bIe(e){let t=C(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const xIe=[`"doc.name"`,`"docName"`];function SIe(e){let t=C(e,`utf-8`),n=0;for(let e of xIe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!_(e))return!1;try{return y(k(t),{recursive:!0}),e.endsWith(`.ips`)?O(t,Y5(C(e,`utf-8`))):h(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=T(e,{withFileTypes:!0});for(let i of r){let r=j(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const CIe=new Set([`.jsonl`]);function wIe(e){let t=e.lastIndexOf(`.`);return t!==-1&&CIe.has(e.slice(t))}const TIe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function EIe(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&TIe.has(e.slice(t))}function DIe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!EIe(r))continue;let{redacted:i,patterns:a,lineCount:o}=vP(C(n,`utf-8`));a.length!==0&&(O(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return N(e,t).split(ue).join(`/`)}async function OIe(e){let t=le(e.contentDir),n=le(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??lIe,a=r.fetchAgentEffects??uIe,o=r.fetchWatcherRecent??dIe,s=r.readShadowHead??pIe,c=r.readCheckpointRefs??mIe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.88.0-beta.6`),d=r.readDesktopEnv??K9,f=r.readLanguage??D9,p=r.readRuntime??hIe,m=r.isOtlpPushEnabled??gIe,g=b(j(Se(),`ok-bundle-`));try{y(j(g,`telemetry`),{recursive:!0}),y(j(g,`logs`),{recursive:!0}),y(j(g,`state`),{recursive:!0}),Z9(rIe(n),j(g,`telemetry`,z9)),Z9(iIe(n),j(g,`telemetry`,B9)),Z9(aIe(n),j(g,`logs`,V9)),Z9(oIe(n),j(g,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,j(g,`logs`,oe(t)));for(let t of e.userStateFiles??[])Z9(t,j(g,eJ,oe(t)));let v=0;for(let t of e.diagnosticReports?.files??[])Z9(t,j(g,`diagnostic-reports`,oe(t)))&&(v+=1);let b=j(n,`.ok`,`local`),x=j(b,`server.lock`),S=`not-running`,w=`no server.lock`,T=null;if(_(x)){Z9(x,j(g,`state`,`server.lock`));try{let e=C(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(O(j(g,`state`,`agent-presence.json`),e),S=`running`,w=``);let t=await a(T);t!==null&&O(j(g,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=fIe(n);e!==null&&O(j(g,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&O(j(g,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&O(j(g,`state`,`checkpoint-refs.txt`),D),Z9(sIe(n),j(g,`state`,U9)),Z9(cIe(n),j(g,`state`,W9)),Z9(j(b,`last-spawn-error.log`),j(g,`state`,`last-spawn-error.log`)),Z9(j(b,Gd),j(g,`state`,Gd)),Z9(j(b,Kd),j(g,`state`,Kd)),Z9(j(b,Wd),j(g,`state`,Wd));let ee=p(),ne=d(),ie=f(),ae={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};O(j(g,`state`,`runtime.json`),`${JSON.stringify(ae,null,2)}\n`);let k=S===`running`?`running
1553
+ `)}\n`:null}catch{return null}}function pIe(e){let t=j(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],z6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function mIe(e){let t=j(e,`.git`,`ok`);if(!_(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],z6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function hIe(){return{nodeVersion:process.version,platform:be(),arch:he()}}function gIe(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!_(e))return{};let t;try{t=(0,js.parse)(C(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function _Ie(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return _Ie(e.maxBytes)}function vIe(e){let t=J9(bJ(`project`,e)),n=J9(bJ(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function yIe(e){return Ee(`sha256`).update(e).digest(`hex`)}function bIe(e){let t=C(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const xIe=[`"doc.name"`,`"docName"`];function SIe(e){let t=C(e,`utf-8`),n=0;for(let e of xIe){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!_(e))return!1;try{return y(k(t),{recursive:!0}),e.endsWith(`.ips`)?O(t,Y5(C(e,`utf-8`))):h(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=T(e,{withFileTypes:!0});for(let i of r){let r=j(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const CIe=new Set([`.jsonl`]);function wIe(e){let t=e.lastIndexOf(`.`);return t!==-1&&CIe.has(e.slice(t))}const TIe=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function EIe(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&TIe.has(e.slice(t))}function DIe(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!EIe(r))continue;let{redacted:i,patterns:a,lineCount:o}=vP(C(n,`utf-8`));a.length!==0&&(O(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return N(e,t).split(ue).join(`/`)}async function OIe(e){let t=le(e.contentDir),n=le(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??lIe,a=r.fetchAgentEffects??uIe,o=r.fetchWatcherRecent??dIe,s=r.readShadowHead??pIe,c=r.readCheckpointRefs??mIe,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.88.0-beta.7`),d=r.readDesktopEnv??K9,f=r.readLanguage??D9,p=r.readRuntime??hIe,m=r.isOtlpPushEnabled??gIe,g=b(j(Se(),`ok-bundle-`));try{y(j(g,`telemetry`),{recursive:!0}),y(j(g,`logs`),{recursive:!0}),y(j(g,`state`),{recursive:!0}),Z9(rIe(n),j(g,`telemetry`,z9)),Z9(iIe(n),j(g,`telemetry`,B9)),Z9(aIe(n),j(g,`logs`,V9)),Z9(oIe(n),j(g,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,j(g,`logs`,oe(t)));for(let t of e.userStateFiles??[])Z9(t,j(g,eJ,oe(t)));let v=0;for(let t of e.diagnosticReports?.files??[])Z9(t,j(g,`diagnostic-reports`,oe(t)))&&(v+=1);let b=j(n,`.ok`,`local`),x=j(b,`server.lock`),S=`not-running`,w=`no server.lock`,T=null;if(_(x)){Z9(x,j(g,`state`,`server.lock`));try{let e=C(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(O(j(g,`state`,`agent-presence.json`),e),S=`running`,w=``);let t=await a(T);t!==null&&O(j(g,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=fIe(n);e!==null&&O(j(g,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&O(j(g,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&O(j(g,`state`,`checkpoint-refs.txt`),D),Z9(sIe(n),j(g,`state`,U9)),Z9(cIe(n),j(g,`state`,W9)),Z9(j(b,`last-spawn-error.log`),j(g,`state`,`last-spawn-error.log`)),Z9(j(b,Gd),j(g,`state`,Gd)),Z9(j(b,Kd),j(g,`state`,Kd)),Z9(j(b,Wd),j(g,`state`,Wd));let ee=p(),ne=d(),ie=f(),ae={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};O(j(g,`state`,`runtime.json`),`${JSON.stringify(ae,null,2)}\n`);let k=S===`running`?`running
1554
1554
  `:`not-running (${w})\n`;O(j(g,`state`,`server-status.txt`),k);let A=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:J5(e.diagnosticReports,v);if(O(j(g,`state`,`diagnostic-reports-status.txt`),`${A}\n`),O(j(g,Q5),y7(e.osTerminationEvidence)),e.processDir&&_(e.processDir)){let t=j(g,`process`);y(t,{recursive:!0}),h(e.processDir,t,{recursive:!0})}let se=e.redact===!0;se&&nIe({stagingDir:g,contentDir:t}),e.note&&O(j(g,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=DIe(g));for(let t of e.extraFiles??[]){let e=t.zipName??oe(t.sourcePath);if(!Z9(t.sourcePath,j(g,`extra`,e))){r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);continue}let n=x7(t,`extra/${e}`);n!==null&&(ce??={redactions:[],redactedLineCount:0},ce.redactions.push(n),ce.redactedLineCount+=n.lineCount)}let M=vIe(n),N=Q9(g),le=[],ue=0,de=0;for(let e of N){let t=$9(g,e),n=re(e).size,r=wIe(t)?bIe(e):0;le.push({path:t,bytes:n,lines:r}),ue+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=SIe(e))}let fe={applied:se};ce!==null&&(fe.secretScrub=ce);let P={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie},contentDir:{pathSha256:yIe(t),absolutePath:se?`<CONTENT_DIR>`:t},telemetry:{localSink:M,otlpPushEnabled:m()},redaction:fe,serverStatus:S,files:le};O(j(g,`manifest.json`),`${JSON.stringify(P,null,2)}\n`);let pe=O9(t),me=N.some(e=>{try{let t=C(e,`utf-8`);return pe.some(e=>t.includes(e))}catch{return!1}}),he={stagedDiagnosticReports:v,totalBytes:ue,fileCount:le.length,docNameCount:de,contentDirVisible:me,redacted:se},ge=!1;return{stagingDir:g,manifest:P,summary:he,cleanup:()=>{ge||(ge=!0,te(g,{recursive:!0,force:!0}))}}}catch(e){throw te(g,{recursive:!0,force:!0}),e}}async function kIe(e){let{collected:t,outputPath:n}=e,r=k(n);if(!_(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new kTe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=g(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function AIe(e,t){let n=j(e,`.ok`,`config.yml`);if(_(n))try{let t=(0,js.parse)(C(n,`utf-8`)),r=BJ(t)?t.content:void 0,i=BJ(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return le(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return le(e)}async function jIe(e,t,n,r,i,a){let o=S7(t,e.logger),s=await OIe({contentDir:AIe(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...kPe(o,e.userLogsDir??j(pJ(),`logs`)),...w7(e.cachesDir??j(ve(),`Library`,`Caches`))],userStateFiles:T7(e.bugReportsDir??b7()),diagnosticReports:i,osTerminationEvidence:a,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{y(k(e.outputPath),{recursive:!0}),await kIe({collected:s,outputPath:e.outputPath});let t=s.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:o,files:s.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:s.manifest.createdAt}}}finally{s.cleanup()}}async function MIe(e){let{projectDir:t}=e,n=e.readDesktopEnv??K9,r=e.readLanguage??D9,i=()=>tPe(e.diagnosticReportsDir??j(ve(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return jIe(e,t,n,r,i(),await v7(e.osTerminationEvidenceDeps));let{zipPath:a,summary:o}=await PPe({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:w7(e.cachesDir??j(ve(),`Library`,`Caches`)),bugReportLedgerFiles:T7(e.bugReportsDir??b7()),diagnosticReports:e.level===`full`?i():void 0,osTerminationEvidence:e.level===`full`?await v7(e.osTerminationEvidenceDeps):void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}export{YJ as ALL_EDITOR_IDS,XJ as EDITOR_LABELS,AY as EDITOR_TARGETS,Exe as HOSTS_WITH_USER_SKILL_DIR,UNe as LAUNCH_CONFIG_NAME,FFe as PATH_SHIM_BEGIN,LFe as PATH_SHIM_BLOCK_RE,IFe as PATH_SHIM_END,l5 as ProjectPathSafetyError,bNe as addOkPathsToGitExclude,u5 as assertProjectPathSafe,dY as buildManagedServerEntry,_Fe as buildMcpConfigDeclineEvent,vFe as buildMcpConfigMigrateEvent,xY as canonicalEntryFor,G5 as classifyExistingMcpEntry,MIe as collectReportBundle,HFe as createCliProbeResolver,EJ as createTokenStore,EPe as defaultBugReportZipPath,qe as detectGh,Xe as detectGhAccounts,qNe as detectInstalledEditors,bY as droppedManagedKeys,qxe as editorConfigPathDisplay,Kxe as editorEntryLocator,oFe as ensurePiBridge,sPe as findJetsamKillSync,C5 as formatTrackedRemediation,CNe as getExcludedOkPaths,x5 as getInstalledSkillProjectionPaths,Txe as getNativeTomlMcpEditor,b5 as getOkArtifactPaths,lY as isEntryUpToDate,fY as isOwnManagedEntry,MFe as loadConfig,$be as makeLazyProbeTokenStore,b7 as okBugReportsDir,y9 as parseGitHubBlobUrl,NFe as parseGitHubShareUrl,b9 as parseGitHubTreeUrl,v9 as parseGitUrl,RFe as pathInstallMarkerPath,aNe as previewContent,JNe as probeOwnManagedEditorMcpEntry,iFe as probePiBridgeState,S5 as probeTrackedOkPaths,U5 as readExistingMcpEntry,SNe as readSharingMode,vP as redactContent,RPe as registerWindowsProcessStartReader,xNe as removeOkPathsFromGitExclude,pFe as removeOwnMcpEntry,gNe as removeProjectSkill,WFe as removeUserGlobalSkillBundle,XFe as removeUserSkill,uNe as resolveProjectRoot,EFe as runStop,f9 as truncatePriorEntry,T9 as userGlobalSkillBundleTargets,YFe as userSkillPresentAnywhere,PFe as validateLocalFolderForShare,H5 as writeEditorMcpConfig,qFe as writeProjectAiIntegrations,h5 as writeProjectSkill,KNe as writeUserMcpConfigs,JFe as writeUserSkill};
1555
1555
  //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ import"./dist-DuYtMHVN.mjs";import{v as e}from"./init-Dks6MSzi.mjs";export{e as runInit};