@inkeep/open-knowledge 0.88.3-beta.4 → 0.88.3-beta.5

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-BrQxqUNL.mjs +1 -0
  3. package/dist/{dist-Ct4bMI-g.mjs → dist-BniR5KN1.mjs} +3 -3
  4. package/dist/{dist-hTv5fgjN.mjs → dist-D5Ry9hFU.mjs} +1 -1
  5. package/dist/index.mjs +1 -1
  6. package/dist/init-CxYfudet.mjs +1 -0
  7. package/dist/{init-OBtcJxhq.mjs → init-UZr9GVxw.mjs} +2 -2
  8. package/dist/{launch-json-removal-B7ix5ecY.mjs → launch-json-removal-DdasfWvu.mjs} +1 -1
  9. package/dist/{loader-B0JdOkpt.mjs → loader-Dbq_EWV8.mjs} +1 -1
  10. package/dist/loader-iVVo3m-3.mjs +1 -0
  11. package/dist/{open-browser-B3XV-jm1.mjs → open-browser-CDTeL9eY.mjs} +1 -1
  12. package/dist/{preview-DkM0pIYu.mjs → preview-BRJmRFNY.mjs} +1 -1
  13. package/dist/preview-ca3pkl9K.mjs +1 -0
  14. package/dist/public/assets/{AccountSection-lpUY-5BJ.js → AccountSection-B7HfUudL.js} +1 -1
  15. package/dist/public/assets/{ActivityModeContent-DC30-6yq.js → ActivityModeContent-CmhZGNsW.js} +1 -1
  16. package/dist/public/assets/{AddPropertiesButton-BGGeJ9T_.js → AddPropertiesButton-BT2D84aD.js} +1 -1
  17. package/dist/public/assets/{AgentDiffPane-BK5lmU7c.js → AgentDiffPane-CHF9pABO.js} +1 -1
  18. package/dist/public/assets/{AttachmentsSection-DgWSYEMg.js → AttachmentsSection-ByGVMvG9.js} +1 -1
  19. package/dist/public/assets/{CodeMirrorPropInput-y_25d_tk.js → CodeMirrorPropInput-DR1N5trk.js} +1 -1
  20. package/dist/public/assets/{ContentRulesSection-BYldFTEc.js → ContentRulesSection-C9Req4oF.js} +1 -1
  21. package/dist/public/assets/{DocumentContext-FHsPdLlh.js → DocumentContext-CSDucywQ.js} +28 -28
  22. package/dist/public/assets/{EditorModeToggle-CeBi7iXJ.js → EditorModeToggle-gpcNAVY7.js} +1 -1
  23. package/dist/public/assets/{ExcalidrawDocEditor-BTW6-Xx-.js → ExcalidrawDocEditor-Cgmhgars.js} +1 -1
  24. package/dist/public/assets/FeedbackForm-ZahAS6z-.js +1 -0
  25. package/dist/public/assets/{ImportSkillDialog-c-m_C9lz.js → ImportSkillDialog-D_sEyaYd.js} +1 -1
  26. package/dist/public/assets/{LinkPreviewsSection-Da0QLy97.js → LinkPreviewsSection-9BI_Ve7c.js} +1 -1
  27. package/dist/public/assets/{LintConfigEditor-8V02t6Dd.js → LintConfigEditor-Cd7vchN2.js} +1 -1
  28. package/dist/public/assets/{LintingSection-CS4JpSUl.js → LintingSection-CYt6Mzbc.js} +1 -1
  29. package/dist/public/assets/ManagedArtifactProperties-BBtQ0jlN.js +1 -0
  30. package/dist/public/assets/{ManagedArtifactProperties-COkvjxeU.js → ManagedArtifactProperties-DD9uK5we.js} +1 -1
  31. package/dist/public/assets/{MermaidDocEditor-BP3JjkCY.js → MermaidDocEditor-C_HMHLXm.js} +1 -1
  32. package/dist/public/assets/{NetworkAccessSection-BqoHE2vC.js → NetworkAccessSection-BrbkXzyJ.js} +1 -1
  33. package/dist/public/assets/{PropertyDisplayRow-BLK092E8.js → PropertyDisplayRow-DrvArJ_K.js} +1 -1
  34. package/dist/public/assets/{PublishToGitHubDialog-CcP28Go2.js → PublishToGitHubDialog-D0GzPYlL.js} +1 -1
  35. package/dist/public/assets/{SchemaConfigEditor-DVt2AgB2.js → SchemaConfigEditor-Cxv9ZBLk.js} +1 -1
  36. package/dist/public/assets/{SearchSection-BekOA3Hq.js → SearchSection-B2hY3rln.js} +1 -1
  37. package/dist/public/assets/{SessionsHost-Br6UHeKX.js → SessionsHost-Dhya-YYl.js} +2 -2
  38. package/dist/public/assets/{SettingsDialogBody-0OzHKb49.js → SettingsDialogBody-BqSzx5Tb.js} +2 -2
  39. package/dist/public/assets/{ShareReceiveMissDialog--9kihy_4.js → ShareReceiveMissDialog-BIVMX9w3.js} +1 -1
  40. package/dist/public/assets/{SkillToolbarControls-BgTc1qxM.js → SkillToolbarControls-F1L2HGgN.js} +1 -1
  41. package/dist/public/assets/{SourceEditor-D_q9P9sn.js → SourceEditor-KucnhTGF.js} +1 -1
  42. package/dist/public/assets/{SyncSection-TZI8M5TN.js → SyncSection-B5pv2M0p.js} +1 -1
  43. package/dist/public/assets/{SyncStatusBadge-B9Fy_mbF.js → SyncStatusBadge-emJ3GW6F.js} +1 -1
  44. package/dist/public/assets/{TerminalSection-C-GMhnvQ.js → TerminalSection-BTwUAO1z.js} +1 -1
  45. package/dist/public/assets/{TerminalWindowApp-CLa6m4k3.js → TerminalWindowApp-DqRB0Vv9.js} +1 -1
  46. package/dist/public/assets/{TextDocEditor-DE7Ok5c_.js → TextDocEditor-DI35AumM.js} +1 -1
  47. package/dist/public/assets/{ThreadView-QJDCr1W3.js → ThreadView-Dykd2VWP.js} +1 -1
  48. package/dist/public/assets/{TimelineDiffPane-BLOFOVKH.js → TimelineDiffPane-BMkb_oht.js} +1 -1
  49. package/dist/public/assets/{client-version-BFeQeLHx.js → client-version-BLwdND1C.js} +1 -1
  50. package/dist/public/assets/{comment-chips-Uvd_Ct2o.js → comment-chips-CvYUezma.js} +1 -1
  51. package/dist/public/assets/{config-provider-Cms0DKDS.js → config-provider-DW_79HvK.js} +1 -1
  52. package/dist/public/assets/{doc-undo-manager-C5T0buVF.js → doc-undo-manager-CLhgkmvC.js} +1 -1
  53. package/dist/public/assets/{index-BXfeXF07.js → index-X807k4xA.js} +7 -7
  54. package/dist/public/assets/{lint-plugins-rsLPQGXE.js → lint-plugins-Czjcu-H_.js} +1 -1
  55. package/dist/public/assets/{pending-receive-nav-store-Db29sZMC.js → pending-receive-nav-store-C-OIVRCW.js} +1 -1
  56. package/dist/public/assets/{preferred-session-events-BXPcTKfZ.js → preferred-session-events-BNgqIkFZ.js} +1 -1
  57. package/dist/public/assets/{progress-BTqUZu-S.js → progress-CWeTZaVu.js} +1 -1
  58. package/dist/public/assets/{selection-context-CZfYHE9G.js → selection-context-BdQZZ1HB.js} +1 -1
  59. package/dist/public/assets/{src-BW32L7LZ.js → src-DO7J3WVu.js} +1 -1
  60. package/dist/public/assets/{telemetry-impl-CuBrRrsw.js → telemetry-impl-BTJogCD2.js} +1 -1
  61. package/dist/public/assets/{telemetry-startup-Dq5kshA5.js → telemetry-startup-CjA9BXC1.js} +1 -1
  62. package/dist/public/assets/{typing-burst-detector-BE0S-jqK.js → typing-burst-detector-fQQTAQsm.js} +1 -1
  63. package/dist/public/assets/{use-activity-panel-CzOa6AZJ.js → use-activity-panel-D2QIpezB.js} +1 -1
  64. package/dist/public/assets/{use-open-skill-B_KByYbj.js → use-open-skill-CkTZwt2b.js} +1 -1
  65. package/dist/public/assets/{use-terminal-enabled-DLxTzfRe.js → use-terminal-enabled-CZCtVTgy.js} +1 -1
  66. package/dist/public/assets/{use-timeline-entry-diff-CzWepG-H.js → use-timeline-entry-diff-BwKzDqXd.js} +1 -1
  67. package/dist/public/index.html +19 -19
  68. package/dist/{registry-probes-BeMk3GG0.mjs → registry-probes-DA_47MnL.mjs} +1 -1
  69. package/dist/{removal-file-path-B3RdV7_I.mjs → removal-file-path-Yisg-4PO.mjs} +1 -1
  70. package/dist/{repair-launch-json-BgeNu67g.mjs → repair-launch-json-ByHbUrvl.mjs} +1 -1
  71. package/dist/{repair-mcp-configs-zKT1r7UX.mjs → repair-mcp-configs-Cz7RUmn9.mjs} +1 -1
  72. package/dist/{src-0tNismMR.mjs → src--qjAZ5fK.mjs} +1 -1
  73. package/dist/src-ue3sSI-I.mjs +1 -0
  74. package/dist/{start-TpCQ2Akm.mjs → start-0pD-b-lJ.mjs} +3 -3
  75. package/dist/start-r-TtnKpy.mjs +1 -0
  76. package/package.json +4 -4
  77. package/dist/constants-Bhos24bn.mjs +0 -1
  78. package/dist/init-COFrSasH.mjs +0 -1
  79. package/dist/loader-DRu9Zt3m.mjs +0 -1
  80. package/dist/preview-B3-KxNOs.mjs +0 -1
  81. package/dist/public/assets/FeedbackForm-CQP943AQ.js +0 -1
  82. package/dist/public/assets/ManagedArtifactProperties-N_hn0Aa4.js +0 -1
  83. package/dist/src--2sBJJyk.mjs +0 -1
  84. package/dist/start-4JOzF_CU.mjs +0 -1
@@ -2224,8 +2224,8 @@ restat-race-injected
2224
2224
  `)),`${n}${o}`}function OFt(e,t){let{bom:n,body:r}=E9(e),i=[],a=QN(r,i,{allowTrailingComma:!0,disallowComments:!1});if(!a||i.length>0||a.type!==`object`)return{kind:`declined`,reason:`unparseable`};if(EFt(a,t.topLevelKey)>1)return{kind:`declined`,reason:`duplicate-container`};let o=[t.topLevelKey,t.serverName],s=$N(a,o);if(!s)return{kind:`no-entry`,raw:e,shell:e};let c=eP(s);if(!w9(c))return{kind:`declined`,reason:`foreign-entry`};let l=ke(c,void 0,t.chainTag);if(l.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let u=r,d=t.managedKeys.map(e=>({key:e,node:$N(a,[...o,e])})).filter(e=>e.node!==void 0).sort((e,t)=>t.node.offset-e.node.offset);for(let{key:e,node:n}of d){let r=JSON.stringify(kFt(t,e));u=`${u.slice(0,n.offset)}${r}${u.slice(n.offset+n.length)}`}return{kind:`managed`,raw:e,shell:`${n}${u}`,entry:c,descriptor:l.descriptor}}function kFt(e,t){return e.topLevelKey===`mcp`&&t===`type`?`__ok_managed_type__`:t===`command`&&e.topLevelKey===`mcp`?[`__ok_managed_command__`]:t===`command`?`__ok_managed_command__`:[`__ok_managed_args__`]}function AFt(e,t,n){if(!n)return{kind:`declined`,reason:`no-native-writer`};let{bom:r,body:i}=E9(e),a;try{a=n.parseToObject(i)}catch{return{kind:`declined`,reason:`unparseable`}}let o=a[t.topLevelKey],s=w9(o)?o[t.serverName]:void 0;if(s===void 0)return{kind:`no-entry`,raw:e,shell:e};if(!w9(s))return{kind:`declined`,reason:`foreign-entry`};let c=ke(s,void 0,t.chainTag);if(c.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let l;try{l=n.upsertEntry(i,t.serverName,Object.fromEntries(t.managedKeys.map(e=>[e,kFt(t,e)])))}catch{return{kind:`declined`,reason:`unparseable`}}let u=DFt(e,l.text);return{kind:`managed`,raw:`${r}${i}`,shell:u,entry:s,descriptor:c.descriptor}}function D9(e,t,n){return e===null?{kind:`absent`}:Buffer.byteLength(e,`utf8`)>10485760?{kind:`declined`,reason:`oversize`}:t.format===`json`?OFt(e,t):AFt(e,t,n)}function jFt(e,t,n){let{bom:r,body:i}=E9(e),a=i;for(let e of t.managedKeys){let r=QN(a,[],{allowTrailingComma:!0,disallowComments:!1}),o=r?$N(r,[t.topLevelKey,t.serverName,e]):void 0;o&&JSON.stringify(eP(o))===JSON.stringify(n[e])||(a=nP(a,tP(a,[t.topLevelKey,t.serverName,e],n[e],{formattingOptions:TFt(i)})))}return`${r}${a}`}function MFt(e,t,n,r){if(t.format===`json`)return jFt(e,t,n);if(!r)return null;let{body:i}=E9(e),a=Object.fromEntries(t.managedKeys.map(e=>[e,n[e]]));try{return DFt(e,r.upsertEntry(i,t.serverName,a).text)}catch{return null}}function NFt(e){let t=T9(e.target);return t?MFt(e.raw,t,e.entry,e.tomlEditor):null}function PFt(e){let t=T9(e.target);if(!t)return null;let n=D9(e.raw,t,e.tomlEditor);return n.kind===`managed`||n.kind===`no-entry`?n.shell:null}function FFt(e,t,n){return t.shell===n.shell?t.shell:t.shell===e.shell?n.shell:n.shell===e.shell?t.shell:null}function IFt(e){let t=T9(e.target);if(!t)return{kind:`declined`,reason:`unsupported-target`};let n={base:D9(e.layers.base,t,e.tomlEditor),head:D9(e.layers.head,t,e.tomlEditor),index:D9(e.layers.index,t,e.tomlEditor),worktree:D9(e.layers.worktree,t,e.tomlEditor),incoming:D9(e.layers.incoming,t,e.tomlEditor)},r=Object.values(n),i=r.find(e=>e.kind===`declined`);if(i?.kind===`declined`)return i;if(r.some(e=>e.kind===`absent`))return r.every(e=>e.kind===`absent`)?{kind:`unchanged`}:{kind:`declined`,reason:`file-deletion-ambiguity`};if(r.some(e=>e.kind===`no-entry`))return r.every(e=>e.kind===`no-entry`)?{kind:`declined`,reason:`no-entry`}:{kind:`declined`,reason:`entry-deletion-ambiguity`};let a=n;if(a.index.shell!==a.worktree.shell)return{kind:`declined`,reason:`index-worktree-divergence`};let o=FFt(a.base,a.worktree,a.incoming);if(o===null)return{kind:`declined`,reason:`unowned-shell-conflict`};let s=Object.values(a).map(e=>({entry:e.entry,descriptor:e.descriptor}));if(e.runningEntry){let n=ke(e.runningEntry,void 0,t.chainTag);n.kind===`recognized`&&s.push({entry:e.runningEntry,descriptor:n.descriptor})}if(new Set(s.map(e=>e.descriptor.family)).size!==1)return{kind:`declined`,reason:`mixed-launcher-family`};let c=s.reduce((e,t)=>t.descriptor.revision>e.descriptor.revision?t:e),l=[a.worktree,a.index,a.head,a.incoming,a.base].filter(e=>e.shell===o),u=l.find(e=>t.managedKeys.every(t=>JSON.stringify(e.entry[t])===JSON.stringify(c.entry[t])))??l[0];if(!u)return{kind:`declined`,reason:`unowned-shell-conflict`};let d=MFt(u.raw,t,c.entry,e.tomlEditor);return d===null?{kind:`declined`,reason:e.tomlEditor?`unparseable`:`no-native-writer`}:{kind:`resolved`,raw:d,winner:c.descriptor,winnerEntry:c.entry}}const LFt=q(`github-account`),RFt=(e,t)=>{let n=Ws(`git`,[`config`,`--get-urlmatch`,`credential`,e],aW({cwd:t,encoding:`utf-8`,timeout:5e3}));return n.error||n.status===null||n.status!==0&&n.status!==1?(LFt.warn({status:n.status,signal:n.signal,err:n.error,stderr:typeof n.stderr==`string`?k6(n.stderr).slice(0,200):void 0},`[github-account] git config --get-urlmatch failed — treating the URL as declaring no account`),null):n.status!==0||!n.stdout?null:n.stdout};function zFt(e){return e.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/]*@/i,`$1`)}function BFt(e){let t;for(let n of e.split(`
2225
2225
  `)){let e=n.startsWith(`credential.username `)?n.slice(20).trim():void 0;e&&(t=e)}return t}function VFt(e,t={}){let n=Wvt(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??RFt)(zFt(e),t.cwd??process.cwd()),a=i?Vvt(BFt(i)):void 0;return a?{host:r,login:a,source:`credential-config`}:{host:r,source:`active`}}function HFt(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=VFt(a,{cwd:i,_readCredentialUrlMatch:e._readCredentialUrlMatch});return r={projectDir:i,url:a,account:s,expiresAt:o+t},s},invalidate(){r=void 0}}}function UFt(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`),WFt=new Set(CFt),k9=/^[0-9a-f]{40}$/i,GFt=Hc(Vs);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 qFt(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 YFt(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 XFt={syncScope:{pathBase:`content`}},j9={syncScope:{pathBase:`project`}},ZFt=/(^|[/\\])index\.lock\b/i,QFt=new Set(Woe);function $Ft(e){return QFt.has(e)}const eIt=new Set([`diverged-local-commits`,`external-changes-pending`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`]),tIt=[`no-push-permission`,`auth-error`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`,`unsafe-incoming-symlinks`],nIt=new Set(tIt),rIt=new Set([...tIt,`external-changes-pending`]);function M9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function iIt(e){return new Promise(t=>{setTimeout(t,e)})}function N9(e){let t=yve(e);if(t.kind!==`repository`)return!1;let n=t.repository.readHead();return n.kind===`branch`&&t.repository.readRef(n.ref).kind===`absent`}function aIt(e){return e.class===`network`&&e.subclass!==`429`&&e.subclass!==`5xx`}function oIt(e){return e>=8?36e5:e>=5?9e5:e>=3?3e5:0}const sIt=12e4;var cIt=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())F7e(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=oG(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=Jxt(e.detectGh),this.ghAccountResolver=HFt({_readCredentialUrlMatch:e._readCredentialUrlMatch}),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??vxt,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 pK(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=aS(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=UFt(this.lastFetchUtc,this.pullIntervalSeconds),o=UFt(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 Wc(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 fK(()=>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`?(eIt.has(this.pausedReason)||eIt.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?Qvt(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 fK(async()=>{await this.applyCommitIdentity(t);try{if(await t.git.raw([`add`,...Kt(e)]),(await Jq(t.git,[`diff`,`--cached`,`--name-only`,...Kt(e)])).length===0)return null;await t.git.raw([`commit`,`-m`,`Commit local changes before syncing`,...Kt(e)])}catch(n){throw await t.git.raw([`reset`,...Kt(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 Nvt(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async applyCommitIdentity(e){let t=await Nvt(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`;C4e(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`)):YFt(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&&!YFt(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=oIt(this.consecutivePullFailures),t=e>0?e/1e3:0;return M9(Math.max(t,this.pullIntervalSeconds))}effectivePushDelayMs(){let e=oIt(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 bK?(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 bK)return this.handleIncomingSymlinkRefusal(t,`pull`),`refused`;if(t instanceof SK&&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 SK?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`,...Kt(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 ${sIt}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 GFt(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,t],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:sIt}),{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:qFt({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&&WFt.has(p)){let t=await this.readMcpGitBlob(e,n,p),r=IFt({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=Sre(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:nK};for(let{path:t,bytes:r}of e)GU(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{ZU(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=H(this.projectDir,e),n=oG(U(this.contentDir,t));return!n.startsWith(`..`)&&IH(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(Dc(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),n=null;try{let e=this.gatherContentFilesSync(),r=await this.snapshotPromisedPaths(),i=new Set;await fK(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)??oG(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 bK){this.handleIncomingSymlinkRefusal(e,`push`);return}if(e instanceof SK&&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 SK?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{bc(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(Dc(),`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{bc(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 IFt({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=WFt,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`,...Kt(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&&GU(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 yK(e.git,r),await xK(e.git,i,`merge`,e.env)}catch(e){let n=e instanceof bK?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 s3e(e.git,{name:r,trackingRef:`refs/remotes/${r}`,commit:n})}catch(e){throw e instanceof a3e&&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=aS(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 fK(async()=>{let t=H(Dc(),`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=NFt({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,...Kt([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),xc(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=PFt({target:o.path,raw:l,tomlEditor:this.mcpTomlEditor}),m=PFt({target:o.path,raw:o.raw,tomlEditor:this.mcpTomlEditor}),h=p!==null&&p===m?l:o.raw,g=`${t}.replay-${r}`;n.push(g),xc(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&&GU(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{bc(e)}catch{}try{bc(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`,...Kt(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,...Kt(i)])}return o}gatherContentFilesSync(){let e=[],t=(e,t)=>{throw new KFt(oG(U(this.projectDir,t))||`.`,e)},n=(r,i,a,o)=>{let s;try{s=mc(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=oG(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=oG(U(i,s));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t,a)){let t=oG(U(this.contentDir,s)),n=oG(U(this.projectDir,s));e.push({contentRelPath:t,projectRelPath:n})}}}};if(G(this.contentDir)&&n(this.contentDir,this.contentDir,XFt),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=oG(U(this.contentDir,t)),r=!n.startsWith(`..`)&&!this.contentFilter.isExcluded(n,XFt),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`,...Kt(r)])}}async snapshotPromisedPaths(){let e,t;try{let{git:n}=this.gitHandle();e=await X8e(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`,...Kt(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 iIt(M9(.05));try{await e.git.raw([`reset`,`HEAD`,...Kt(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=oG(U(this.projectDir,bl(`project`,this.projectDir)));for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,...Kt([t])]),await e.git.raw([`add`,...Kt([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=aS(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,aIt(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 ZFt.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=nIt.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`;GU(n,JSON.stringify(t,null,2),`utf-8`),JU(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&&$Ft(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=rIt.has(r)?void 0:r}catch(e){O9.warn({err:e},`[sync] failed to load sync state`)}}};const lIt=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function uIt(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(pU(e)||mU(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&lIt.test(n)&&(r[`mount.id`]=n);try{let e=()=>{MU(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),Mo.with(Io.extract(Mo.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 dIt(){if(P9)return;let e=Qae;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 fIt=cG(``),pIt=1e4,F9=3e4;function mIt(e,t){let n=e.filter(t);return n.length===1?n[0]:void 0}function hIt(e){let t=new Set;for(let n of e.split(`
2226
2226
  `)){let e=n.trim();e!==``&&t.add(e)}return t}function gIt(e,t){let n=hIt(e),r=hIt(t),i=0;for(let e of n)r.has(e)&&i++;return i>0&&i>=Math.max(n.size,r.size)*.5}function _It(e,t){return e.size!==void 0&&e.modified!==void 0&&t.size===e.size&&t.modified===e.modified}function vIt(e,t,n){return e.identity===void 0||t.identity!==e.identity?!1:_It(e,t)?!0:e.text!==void 0&&n!==void 0&&gIt(e.text,n)}var yIt=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(vIt(t,e,e.content))return{vanished:t,by:`identity`};if(e.hash===fIt)return;let n=mIt([...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-pIt),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-pIt);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&&vIt(e,t,_It(e,t)?void 0:n(t))){i={create:t,by:`identity`};break}if(!i){let t=mIt(r.filter(e=>e.hash!==fIt),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 bIt(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 xIt=5e3,SIt=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),CIt=(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function wIt(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=Ws(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],aW({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
- `)){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(!UG(a,t))continue;let s=OX(a,t);i.has(s)||G(a)&&i.set(s,o)}return i}function TIt(e){dIt();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=IG(n,{root:`content`,component:`server-factory`}),x=x6(u),S=Xvt({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=OMt(W(n)),O=null,k=t9(r).branch??`main`,A=new p2e({path:H(qJ(r),`receipts.jsonl`)}),j=d2e(n),M=new EG(k,{persistencePath:H(qJ(r),`stale-external-writes.json`),receipts:A,onStaleExternalWriteChange:()=>{O?.signal(`sync-status`),le()},onStoreRefused:e=>{ri(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,HG(e,n)).replaceAll(`\\`,`/`),hasResolvedExtension:WH}),P=()=>M.getActiveBranch(),F=e=>M.getReconciledBase(e),ee=(e,t)=>M.setReconciledBase(e,t),I=e=>M.deleteReconciledBase(e),te=e=>M.switchReconciledBaseScope(e),ne=new yIt,re=e=>M.holdBatch(e),ie=e=>M.releaseBatch(e),ae=async()=>{try{await Yr()}finally{Xr()}await Ye.flushDeferredStores(`within-branch`)},oe=e=>t=>{if(t){re(e);return}ie(e)&&ae().catch(t=>{C.error({err:t,owner:e},`[batch] draining after the batch failed`)})},se=()=>M.isBatchInProgress(),ce=new nnt({projectDir:r,contentDir:n,assertResolutionPath:Ne,branch:k,signal:{signal:e=>O?.signal(e)},io:{gitRaw:async e=>pK(r,{credentialConfig:[],timeoutMs:3e4}).git.raw(e),writeProjectFileUntracked:(e,t)=>{Ne(e),GU(e,t,`utf-8`)},unlinkProjectFileUndeclared:e=>{Ne(e),ZU(e)},deleteResolvedContent:(e,t)=>{ke(t);let n=Get(t);try{ZU(t)}catch(e){throw Ket(n),e}Ge.decrementMdDir(V(e)),bn.current?.deleted(e)},applyResolvedContent:async(e,t,n)=>{ke(t);let r=!G(t);hX(t,cG(n)),await _l(t,n,{fs:Me}),r&&Ge.incrementMdDir(V(e)),Ze.documents.get(e)&&Kn(e,n),ee(e,n),await Ke.recordDiskUpsert(e,n)},readLiveContent:e=>Gn(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`&&Tn(n)){C.debug({docName:n,source:`resolve-delete`,bindingRecreated:!0},`[reconcile] delete skipped: ${n} (binding recreated)`);return}let i=Ze.documents.get(n),a=i?.getMap(`lifecycle`);if(t===`delete`){let e=Pn(n);try{let t=e.residentCurrent()&&i?Fr(n,w?.getLastKnownBranch()??`main`,`delete`,!0):!1;if(e.namespaceCurrent()&&(bn.current?.deleted(n),await Ke.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{Ze.closeConnections(n),await ht(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}I(n),In(n),an(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`));kt(`files`)}}});function le(){for(let e of M.listStaleExternalWrites()){let t=F(e.docName)??e.diskContent;ce.raise({kind:`reconcile`,file:e.file,reason:`stale-external-write`,detectedAt:e.detectedAt,stages:{base:t,ours:e.retainedContent??t,theirs:e.diskContent}})}}le();function ue(e){let t=pl({absPath:bl(`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 de(){let e=pl({absPath:bl(`project-local`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project-local config`)}),t=yie(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=pl({absPath:bl(`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:Die(n.value.autoSync?.default)??`off`,source:`committed-default`}}function fe(){let e=pl({absPath:bl(`project-local`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project-local config`)});return tte(e.value.autoSync)}function pe(){let e=pl({absPath:bl(`project`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules,t=e?Va(e):va;return FNt(r,t.plugins.okf),t}function me(){let e=pl({absPath:bl(`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 he(){return Ept(r,{configHomedirOverride:u,onWarn:e=>C.warn({message:e},`[config] could not read project-local config`)})}function ge(){let e=pl({absPath:bl(`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 _e(){return Ose({cwd:r,homedirOverride:u,warn:e=>C.debug({message:e},`[config] diagnostics read`)})}function ye(e){let t={user:pne,project:ve,"project-local":Rn};for(let n of _e().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 be(e){return`${c4(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function xe(e){return`${e.maxBatchSize}|${e.maxBatchChars}|${e.docTimeoutMs}`}let Se,Ce=0;function we(e,t){let i;if(e===`__config__/project`||e===`__local__/project`){let t=de();i=t.mode,ti?.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=fe();ti?.setIntervals(n.pullIntervalSeconds,n.pushIntervalSeconds)}let a=he();if(ut.applyConfig({enabled:a.enabled,providerFingerprint:be(a),transportFingerprint:xe(a),maxBatchSize:a.maxBatchSize}),e===`__config__/project`){Ce+=1;try{let e=ue({requireValid:!0});Ge?.setAttachmentFolderPath(e),Se!==void 0&&e!==Se&&C.warn({previous:Se,next:e},`[content-filter] attachment folder changed — files under the previous folder no longer sync`),Se=e}catch(e){C.warn({err:e},`[content-filter] project config invalid — keeping previous attachment admission`)}O?.signal(`lint-config`),(t??pe().plugins.okf?.generate?.index===!0)||nNt({projectDir:r,contentDir:n,generatedDocNames:dn(),enabled:!1}).then(e=>{e.ok||C.warn({state:e.status.state},`[index] could not remove Open Knowledge generated-index Git attributes`)}),on()}C.info({docName:e,autoSyncMode:i,semanticEnabled:a.enabled},`[config] applied persisted config to in-process consumers`)}EU();let Te=kc(),Ee=!1,De=!1,Oe=D3e(n,v),ke=e=>{if(Ee)throw new JK(!1);A3e(Oe,e)},Ae=e=>{ke(e),j3e(Oe,e)},Me=E3e(ke);function Ne(e){VY(e,r,{allowShareableOkArtifact:nK});let t=YK(e),n=oG(U(YK(r),t));Oe.kind===`tree`&&!WK({kind:`tree`,path:Oe.path,excluded:[]},t)&&nK(n)||ke(t)}let Pe=qJ(r),Fe=new SXe({localDir:Pe,log:q(`acp-registry`),fetchImpl:e.acpRegistryFetchImpl}),Ie=new mXe(Pe,q(`acp-permissions`)),Le;try{Le=T3e({scope:Oe,projectDir:YK(r),serverInstanceId:Te,registryPath:e.authorityRegistryPath})}catch(e){if(e instanceof RK&&e.existing.projectDir===YK(r)){let t=N4(Pe);if(t?.pid===e.existing.pid)throw new j4(t,H(Pe,`server.lock`))}throw e}Oe=Le.scope;let Re=!1;try{M4(Pe,{port:0,worktreeRoot:r,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),Re=!0,_||aFt({lockDir:Pe,shadowRepoDir:oS(r)})}catch(e){Re&&F4(Pe);try{Le.release()}catch(e){C.error({err:e},`[server] startup authority release failed`)}throw e}let ze=Ln(),Be=qdt(()=>B2(Zr,n)),Ve=Jdt(()=>B2(Zr,n)),He=(e,t)=>{let n=Wut(e);return n===null||!n.includes(`/`)?ze.resolveEmbed(e,t):Ve(n)??null},We=(e,t)=>{let r=He(e,t);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=W(n,r);if(!sG(i,W(n)))return null;try{let e=yc(i);return e.isFile()?e.size:null}catch{return null}},Ge,Ke,qe,Je,Ye,Xe,Ze,Qe,$e,et,tt,nt,rt=null,it=null,at=null,ot=null,st=null,ct=null,lt=he(),ut=new Ppt({loadEmbedder:()=>{let t=he(),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??gpt)(n)},cacheDir:H(qJ(r),`embeddings`),enabled:lt.enabled,providerFingerprint:be(lt),transportFingerprint:xe(lt),maxBatchSize:lt.maxBatchSize}),dt=null,ft=new Map,pt=!1,mt=[],ht,gt,_t,vt,yt=new Promise((e,t)=>{_t=e,vt=t}),bt=!1;yt.then(()=>{bt=!0},()=>{});let xt=e=>W3(e,r,u??wc()),St=()=>!0,Ct=new xNt({projectDir:r,contentDir:n,getShadow:()=>qe?.current,isReady:()=>bt,signal:()=>O?.signal(`sync-status`),isHeld:e=>ne.has(e),isSaveHeld:e=>St(e),resolveFile:e=>{let t;try{if(mU(e))t=M7(e,Ye.configPersistenceCtx);else if(hU(e))t=r6(e,Ye.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:xt(t)}}}),wt=BCt({getShadow:()=>qe?.current,contentRoot:p??``,getBranch:T,writeCheckpoint:e.mergeHistoryWriter,notices:Ct}),Tt=Promise.withResolvers(),Et,Dt=new Promise(e=>{Et=e});async function Ot(){let e,t=Symbol(`branch-scope-gate-timeout`),n=new Promise(n=>{e=setTimeout(()=>n(t),1e4),e.unref?.()});try{if(await Promise.race([Dt,n])!==t)return P()}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 kt(e){O?.signal(e)}let At,jt,Mt,Nt=!1,Pt=!1,It=new AbortController,Lt=new Set,Rt=!1,zt=!1,Bt=!1,Vt=0,Ht,Ut=new Promise(e=>{Ht=e});function Wt(e){Bt||(Bt=!0,Ht(e))}function Gt(){return Rt||Lt.size>0}function Kt(){Pt||!Nt||(At!==void 0&&clearTimeout(At),At=setTimeout(()=>{At=void 0,en()},500),At.unref?.())}function qt(){if(Pt){Wt({status:`cancelled`,indexCount:0});return}Rt=!0,zt=!0,jt=setImmediate(()=>{jt=void 0,en()})}let L,Jt,Yt=!1,Xt=null;async function Zt(){let e=qe.current;if(!e||Yt)return;let t=performance.now();C.info({gitDir:e.gitDir},`[shadow-housekeeping] deferred boot housekeeping started`);try{await t7e(e)}catch(e){C.warn({err:e},`failed to write gc config (non-fatal)`)}if(!Yt){if(Xt)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,Xt,{rebuild:!0})).skipped){n=!0;break}if(r===29)break;if(await new Promise(e=>{setTimeout(e,t).unref?.()}),Yt)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(!Yt){try{await Je?.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 Qt(){Yt||(L=setImmediate(()=>{L=void 0,Jt=Zt().catch(e=>{C.error({err:e},`[shadow-housekeeping] unexpected uncaught failure`)})}))}async function $t(){if(Yt=!0,L!==void 0&&(clearImmediate(L),L=void 0),!Jt)return;let e,t=new Promise(t=>{e=setTimeout(()=>t(`timeout`),m)});try{if(await Promise.race([Jt,t])===`timeout`)throw Error(`shadow housekeeping drain timed out after ${m}ms — abandoning in-flight housekeeping`)}finally{e!==void 0&&clearTimeout(e)}}function en(){if(Pt||!Nt||!Gt())return;if(Mt!==void 0){e.generatedIndexTestHooks?.onKickWhileInFlight?.();return}if(M.isBatchInProgress()){Kt();return}let t=Rt,n=new Set(Lt),r=zt;Rt=!1,Lt.clear(),zt=!1;let i=t?{fullSweep:!0}:{fullSweep:!1,directories:n};Mt=(async()=>{let e=await hn(i,It.signal);if(e.status===`deferred`){Rt=!0,r&&(Vt+=e.indexCount,zt=!0);return}r&&(Vt+=e.indexCount,e.status===`completed`&&Gt()?zt=!0:Wt({...e,indexCount:Vt}))})().catch(e=>{C.warn({err:e},`[index] index regeneration coordinator failed`),r&&Wt({status:`failed`,indexCount:0})}).finally(()=>{if(Mt=void 0,Pt){r&&Wt({status:`cancelled`,indexCount:0});return}Gt()&&At===void 0?Kt():!Gt()&&At===void 0&&e.generatedIndexTestHooks?.onIdle?.()})}async function tn(){if(!Pt){let e=Mt;Pt=!0,It.abort(),At!==void 0&&(clearTimeout(At),At=void 0),jt!==void 0&&(clearImmediate(jt),jt=void 0),Lt.clear(),Rt=!1,zt=!1,e===void 0&&Wt({status:`cancelled`,indexCount:0})}await Mt}function nn(e){Pt||oNt(e)||(Lt.add(J7(e)),Kt())}function rn(e){if(!Pt){for(let t of aNt(e))Lt.add(t);Kt()}}function an(e){let t=Zr?.getFileIndex();if(!t){nn(e);return}let n=J7(e);if(Y7(t.keys()).has(n)){nn(e);return}rn(J7(n))}function on(){Pt||(Rt=!0,Kt())}function sn(e){let t=Zr?.getFileIndex().get(e);if(t)return{title:t.title,description:t.description,type:t.type}}let cn=!1,ln={origin:CIt,writer:d7e,isConflict:e=>ce.has(e),getDocument:e=>Ze.documents.get(e),writeDisk:async(e,t)=>{ke(e),qU(V(e),{recursive:!0}),await _l(e,t,{fs:Me})},registerWrite:(e,t)=>hX(e,cG(t)),noteFileIndex:e=>Zr?.mutateFileIndex({kind:e.kind,path:e.absPath,docName:e.docName,content:e.markdown}),signalFiles:()=>kt(`files`),attribute:async(e,t)=>{c$(e,t.id,t.name,t.id),cn=!0}};function un(e){return e===``?K7:`${e}/${K7}`}function dn(){return[...Zr?Y7(Zr.getFileIndex().keys()):new Set([``])].map(un)}function fn(e){let t=pe().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 pn(){return fn(QMt({projectDir:r,contentDir:n,generatedDocNames:dn()}))}async function mn(e){let t=await nNt({projectDir:r,contentDir:n,generatedDocNames:dn(),enabled:e});if(!t.ok)return{...pn(),applied:!1,reason:t.status.state===`conflict`?`git-conflict`:`git-unavailable`};let i=await Sl({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{...pn(),applied:!1,reason:`config-write`}}try{let e=K(i.path,`utf-8`);await F7(Ze.documents.get(`__config__/project`)??null,ve,e,Ye.configPersistenceCtx)}catch(e){C.warn({err:e},`[index] generated-index settings reflection deferred to config watcher`)}return we(ve,e),ye(ve),{...pn(),applied:!0}}async function hn(t,i){let a=0,o=t.fullSweep?performance.now():void 0,s=()=>pe().plugins.okf?.generate?.index!==!0;try{if(i.aborted)return{status:`cancelled`,indexCount:0};if(s())return{status:`disabled`,indexCount:0};let c=Zr?.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=uNt({docs:c,docExtension:UH,currentMarkdownFor:()=>null,warningScope:D}),l=QMt({projectDir:r,contentDir:n,generatedDocNames:o.map(({directory:e})=>un(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=un(r),l=W(n,`${o}.md`);ke(l);let u;try{u=K(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&C.warn({err:e,path:FU(l)},`[index] could not read the existing generated index; treating it as absent`),u=null}a+=1;let d=await HMt({docName:o,absPath:l,markdown:c,currentMarkdown:u},ln);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&&rn(J7(r))}}finally{cn&&=(await Ye.waitForPendingCommits(),await Ye.flushContributors(),!1),o!==void 0&&(r4(`generatedIndexSweepMs`,Math.round((performance.now()-o)*100)/100),Wft(`generatedIndexCount`,a))}return{status:`completed`,indexCount:a}}catch(e){return C.warn({err:e},`[index] index regeneration failed`),{status:`failed`,indexCount:a}}}let gn=null,_n=!1,vn=()=>{try{QPt(r,yn.entries())}catch(e){C.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},yn=new UPt(void 0,{onEviction:()=>HQe(),onSizeChange:e=>UQe(e),onMutate:()=>{!_n||gn!==null||(gn=setTimeout(()=>{gn=null,vn()},2e3))}});for(let[e,t]of ZPt(r))yU(e)||o5(e)&&([`.md`,`.mdx`].some(t=>{let r=W(n,`${e}${t}`);return sG(r,W(n))&&G(r)})||yn.restore(e,t));_n=!0;let bn={current:null},xn=new WeakMap,Sn=new Map,Cn=W(n);function wn(e){if(!o5(e))return null;let t=KH(e),n=W(Cn,t);return sG(n,Cn)?n:null}function Tn(e){let t=Zr?.getFileIndex().get(e)?.canonicalPath??wn(e);return t!==null&&KX(e,t,n,Ge)}function En(e){let t=xn.get(e);return t||(t={source:e.getText(`source`).toString(),mutation:void 0,adoption:void 0,pendingRetirement:!1},xn.set(e,t)),t}function Dn(e){for(let t of Sn.get(e)??[])t.namespaceAllowed=!1}function On(e,t){if(De||e.isDestroyed||Ze.documents.get(t)!==e)return;let n=En(e);n.pendingRetirement=!1,n.adoption={};for(let e of Sn.get(t)??[])e.namespaceAllowed=!1,e.residentAllowed=!1}function kn(e){xn.set(e,{source:e.getText(`source`).toString(),mutation:void 0,adoption:void 0,pendingRetirement:!0})}function An(e){if(De)return;Dn(e);let t=Ze.documents.get(e);t&&kn(t),bn.current?.deleted(e)}function jn(e){let t=Ze.documents.get(e),n=t?En(t):void 0,r=n?.adoption;return()=>{De||(Dn(e),t&&Ze.documents.get(e)===t&&xn.get(t)===n&&n?.adoption===r&&kn(t))}}function Mn(e,t){let n=xn.get(e)?.mutation;if(n)return()=>{xn.get(e)===n.occurrence&&On(e,t)}}function Nn(e,t){Tn(e)&&On(t,e)}function Pn(e,t){let n=Ze.documents.get(e),r=()=>(t?.()??!0)&&!Tn(e),i=!De&&r(),a={namespaceAllowed:i,residentAllowed:!De&&n!==void 0&&(i||En(n).pendingRetirement)},o=Sn.get(e)??new Set;return De||(o.add(a),Sn.set(e,o)),{document:n,namespaceCurrent:()=>(a.namespaceAllowed&&!r()&&(a.namespaceAllowed=!1),a.namespaceAllowed),residentCurrent:()=>(a.residentAllowed&&(n===void 0||n.isDestroyed||Ze.documents.get(e)!==n)&&(a.residentAllowed=!1),a.residentAllowed),dispose:()=>{a.namespaceAllowed=!1,a.residentAllowed=!1,o.delete(a),o.size===0&&Sn.delete(e)}}}let Fn=(e,t)=>{yU(e)||yn.setRenamed(e,t)},In=e=>{if(!yU(e)){if(yn.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}yn.setDeleted(e)}},zn=e=>{yU(e)||yn.delete(e)};try{let m=`./`;try{m=ue()}catch(e){C.warn({err:e},`[content-filter] invalid attachment folder at boot — using sibling admission`)}Se=m,Ge=cK({projectDir:r,contentDir:n,isContentScopeExcluded:e=>{if(Oe.kind!==`tree`)return!1;try{let t=YK(e);return Oe.excluded.some(e=>WK({kind:`tree`,path:e,excluded:[]},t))}catch(t){let n=aG(t);if(!(t instanceof CK)&&n!==`EACCES`&&n!==`EPERM`)throw t;return C.warn({path:FU(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=>xct(n,e),skillRootPaths:vct(n),onAfterRebuild:()=>{Ke.refreshContentScope().catch(e=>{q(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),Ytt(Zr).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`)})}}),Ke=new xft({projectDir:r,contentDir:n,contentFilter:Ge,getGlobalSkillRoots:()=>Qgt(Ye.managedArtifactCtx),signalChannel:kt,getLocalTargetInventory:()=>B2(Zr,b),onRecoveredFileTarget:(e,t)=>{Zr&&GPt({watcher:Zr,contentDir:n,relativePath:e,exists:t,invalidateReferencedAssetsCache:st})}}),qe={current:f},Je=s?oPt({getShadow:()=>qe.current??null,getCurrentBranch:T,contentRoot:p??``,projectGitDir:aS(r)??void 0,isWriterLive:e=>{if(!ot&&!Qe)return q(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(ot?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of Qe?.sessionsForConnection(t)??[])return!0;return!1}}):void 0;let _=null;Ye=zPt({contentDir:n,assertContentPath:ke,projectDir:r,conflicts:ce,lifecycleOf:(e,t)=>ce.lifecycleOf(e,t),gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:qe,ephemeral:y,contentRoot:p,derivedDocumentIndex:Ke,configHomedirOverride:u,getCurrentBranch:T,resolveEmbed:He,resolveSize:We,getPrincipal:()=>dt,onAgentCommit:()=>O?.signal(`session-activity`),onFlushCommit:()=>Je?.noteFlushCommit(),capturePublicationReceipt:Mn,onDiskFlush:(e,t,n,r)=>{O?.emitDiskAck(e,t),!yU(e)&&(dNt(r,n,e)&&nn(e),hmt(r,n)&&(st?.(),kt(`files`)))},onConfigRejected:(e,t)=>O?.emitConfigValidationRejected(e,t),onConfigPersisted:e=>{we(e),ye(e)},onManagedSkillPersisted:e=>{let t=N(e);t?.kind===`skill`&&t.scope===`global`&&(_!==null&&clearTimeout(_),_=setTimeout(()=>{_=null;let e=u??wc();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=>yn.has(e),mdManager:e.mdManager,getLossRing:()=>Xe,mergeHistory:wt,ingestDiskAtStore:async(e,t,n)=>{let r;try{r=await Ur({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 Br(r)}},durabilityState:M}),St=e=>Ye.hasHeldSave(e),Ze=new QJe({quiet:i,debounce:a,maxDebounce:o,extensions:[Ye.extension]});let w=Ze.hooks.bind(Ze);Ze.hooks=(e,t,n)=>{if((e===`afterLoadDocument`||e===`onChange`)&&`document`in t&&!yU(t.document.name)){let n=t.document,r=En(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&&!yU(t.documentName)&&Nn(t.documentName,t.connection.document),w(e,t,n)};let D=Ze.openDirectConnection.bind(Ze);function k(e){if(De)throw new JK(!1);if(yU(e)){if(v!==void 0&&e!==`__system__`&&!mU(e))throw new qK;return}if(v!==void 0&&GH(e)!==GH(zH(v)))throw new qK;if(Ee)throw new JK(!1);k3e(Oe,HG(e,n))}Ze.openDirectConnection=(async(e,t)=>{let n=GH(e);return k(n),D(n,t)});let A=Ze;mt.push(hrt(()=>A.documents.size),grt(()=>Ye.getQueueDepths()),vrt(()=>{let e=0;for(let t of A.documents.values())e+=t.directConnectionsCount;return{websocket:A.getConnectionsCount()-e,direct:e}})),brt(),y||(ct=BPt({getLoadedDocuments:()=>A.documents,lifecycleOf:(e,t)=>ce.lifecycleOf(e,t),forceStore:(e,t)=>Ye.forceStore(e,t),isHeldSaveDue:e=>Ye.isHeldSaveDue(e),retryHeldSave:(e,t)=>Ye.retryHeldSave(e,t),getBase:e=>M.getReconciledBase(e),isBatchActive:()=>M.isBatchInProgress(),hasInFlight:e=>M.inFlightFlushCount(e)>0,readDiskBytes:e=>{let t=HG(e,n),r,i;try{r=hc(t),i=yc(r).size}catch(t){let n=aG(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new _9(`symlink cycle at content path: ${e}`):t}if(DK(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(aG(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs})),gt=Ze.shouldUnloadDocument.bind(Ze),Ze.shouldUnloadDocument=e=>{let t=ft.get(e);if(t)return[...t].some(e=>e());if(pt&&!yU(e.name)&&M.isStoreRefused(e.name))return!1;if(pt&&gt(e))return!0;let n=e.name;return yU(n)||F(n)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:gt(e)},ht=async(e,t)=>{let n=()=>Ze.documents.get(e.name)===e&&(t?.()??!0),r=ft.get(e)??new Set;r.add(n),ft.set(e,r);try{await Ze.unloadDocument(e)}finally{r.delete(n),r.size===0&&ft.delete(e)}},O=new v$e(Ze),at=new A8e(Ze),ot=new M8e(Ze),Qe=new oit(Ze,{...e.agentSessionOptions,assertDocumentScope:k,awaitWriteAdmission:()=>M.whenWriteAdmitted()});let j=Qe;mt.push(yrt(()=>({active:j.liveSessionCount,limit:j.sessionLimit})));let P=VNt({derivedDocumentIndex:Ke,onDocumentSettled:e=>bn.current?.changed(e)});Ze.configuration.extensions.push(P);function ee(e,t,n={}){C.warn({reason:e,docName:t,...n},`[auth-rejection] ${e}`)}Ze.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!==Te)throw ee(`server-instance-mismatch`,e.documentName,{claimedServerInstanceId:r,currentServerInstanceId:Te}),new d5(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${Te}`);let i=n?.expectedBranch;if(typeof i==`string`&&i.length>0){let t=await Ot();if(t!==null&&i!==t)throw ee(`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`&&(dt&&n.principalId===dt.id?a.principalId=dt.id:dt?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:dt.id})):a.principalId=n.principalId),typeof n.tabSessionId==`string`&&(a.tabSessionId=n.tabSessionId),a.kind=`human`}}),Ze.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!mU(e.documentName)&&!hU(e.documentName))return;let n=e.request,r=n.socket?.remoteAddress;if(r!==void 0&&!VQ(r,t))throw ee(`config-doc-admission-denied`,e.documentName,{check:`peer`}),Error(`config-doc admission requires loopback peer (peer=${r}, doc=${e.documentName})`);let i=e.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0;if(!HQ(a,t))throw ee(`config-doc-admission-denied`,e.documentName,{check:`host`}),Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${e.documentName})`)}}),Ze.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){if(!yU(e.documentName)){let t=wn(e.documentName);if(t!==null&&!G(t))try{await Promise.race([Tt.promise,yt])}catch(t){throw C.error({err:t,docName:e.documentName},`[removal-guard] missing-document admission refused after startup failure`),t}}await qPt(e.documentName,{recentlyRemovedDocs:yn,resolveFilePath:wn,fileExists:G})}}),Ze.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=f5(e.token);pNt(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Ze.documents.get(e)})}}),Ze.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new JV(e.update);if(t.readVarString(),t.readVarUint()===eH.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${Ue} rejected — server-only channel`)}}),Ze.configuration.extensions.push({async afterUnloadDocument({documentName:e}){M.endRenameCarry(e)}});let I=lTt({mergeHistoryWriter:e.mergeHistoryWriter,docNotices:Ct,declaredGitHubHosts:x,resolveSyncCredentialConfig:S,hocuspocus:Ze,durabilityState:M,ingressPolicy:t,sessionManager:Qe,commentDocHooksRef:bn,onNamespaceCreateAccepted:An,capturePublicationReceipt:Mn,captureNamespaceMove:jn,onResidentAdopted:On,contentDir:n,assertContentPath:ke,assertContentSubtree:Ae,getGeneratedIndexSettingsStatus:pn,setGeneratedIndexEnabled:mn,contentFilter:Ge,serverInstanceId:Te,getFileIndex:()=>Zr?Zr.getFileIndex():new Map,getAttachmentFolderPath:ue,getAllFilesIndex:()=>Zr?Zr.getAllFilesIndex():new Map,getFileIndexGeneration:()=>Zr?.getFileIndexGeneration()??0,mutateFileIndex:e=>{let t=e.kind===`update`?sn(e.docName):void 0;switch(Zr?.mutateFileIndex(e),e.kind){case`update`:fNt(t,e.content,e.docName)&&nn(e.docName);break;case`create`:qn(e.docName,e.content),nn(e.docName);break;case`conflict`:nn(e.docName);break;case`delete`:bn.current?.deleted(e.docName),an(e.docName);break;case`rename`:an(e.oldDocName),nn(e.newDocName);break;case`folder-create`:case`folder-delete`:rn(e.relativePath);break;case`asset-create`:case`asset-delete`:case`file-create`:case`file-update`:case`file-delete`:break;default:cX(e)}},getFolderIndex:()=>Zr?Zr.getFolderIndex():new Map,getAliasMap:()=>Zr?Zr.getAliasMap():new Map,getFolderAliasIndex:()=>Zr?Zr.getFolderAliasIndex():new Map,resolveTrackedFile:Be,rescanFiles:()=>Zr?.rescanFromDisk(),settleDiskEventsForTest:async()=>{await Zr?.settle()},enableTestRoutes:d,shadowRef:qe,flushGitCommit:()=>Ye.flushPendingGitCommit(),flushContributors:()=>Ye.flushContributors(),getCurrentBranch:T,getReportedBranch:E,getDiskAckSVs:()=>O?.getLatestDiskAckSVsAsBase64()??{},getCollabClientCount:e.getCollabClientCount,contentRoot:p,derivedDocumentIndex:Ke,signalChannel:kt,agentFocusBroadcaster:at,agentPresenceBroadcaster:ot,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>ti,conflicts:ce,setBatchInProgress:oe(`conflict-resolve`),refreshDocumentsFromDisk:ei,localOpCliArgs:h,authStreamHeartbeatMs:g,projectDir:r,resolveEmbed:He,getBridgeLossReporter:()=>nt,getPrincipal:()=>dt,agentIntegrations:e.agentIntegrations,acpRegistry:Fe,loadAcpCustomAgents:()=>xH(Pe,q(`acp-registry`)),homeDirOverride:u,resetSettingsForTest:u===void 0?void 0:()=>{for(let e of Vr)bMt(Ze.documents.get(e)??null,e,Ye.configPersistenceCtx),Un.get(e)?.(),we(e)},forceUnloadDocument:ht,ready:yt,recentlyRemovedDocs:yn,serializeDoc:Gn,evictManagedArtifactLkg:e=>{Ye.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:ut,getSemanticSimilarityFloor:()=>he().similarityFloor,getLinterBaseConfig:()=>pe(),getLinkAdvisoryPolicy:me,getProjectConfigEpoch:()=>Ce,getLinkPreviewsEnabled:ge,resolveGitHubToken:Zxt(e.detectGh,e.tokenStore),getConfigDiagnostics:_e,embeddingsSecretsFile:bpt(u),readSemanticProviderConfig:he,ephemeral:y,onReferencedAssetsCacheInvalidator:e=>{st=e}});Ze.configuration.extensions.push(I),Ze.configuration.extensions.push(wNt({clock:e.watcherClock??nX(),refresh:ei})),$e=I.nativeApi,et=I.localApi,tt=I.shutdownLocalOps;let te=pl({absPath:bl(`project`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project config for bridge guards`)}),ne=te.value.bridge.deferGuard.enabled,re=te.value.bridge.fixedPoint.enabled,ie=te.value.bridge.preDrain.enabled;Xe=te.value.lossCapture.enabled?new H8e({projectDir:r,maxBytes:te.value.lossCapture.maxBytes}):void 0,te.value.bridge.lossDetector.enabled&&(nt=E7e({shadow:()=>qe.current,ring:Xe,getBranch:()=>T()??`main`,contentRoot:p??``}),Qe.attachBridgeLossReporter(nt)),Ze.configuration.extensions.push($Pt({mdManager:$a,schema:ka,shadowRef:qe,contentRoot:p,getCurrentBranch:T,resolveEmbed:He,resolveSize:We,deferGuardEnabled:ne,lossDetectorEnabled:te.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:re,preDrainEnabled:ie,lossRing:Xe})),Ze.configuration.extensions.push(uIt()),Ze.configuration.extensions.push({async afterLoadDocument({document:e}){Qtt(e,ce)}})}catch(e){for(let e of mt.splice(0))e();ct?.dispose(),ct=null,Ee=!0,F4(Pe);try{Le.release()}catch(e){C.error({err:e},`[server] construction authority release failed`)}throw e}let Bn=null,Vn=new Map,Hn=[],Un=new Map;function Wn(e,t){let n=W(e,`rescue`),r=KH(t),i=W(n,r);return sG(i,n)?i:null}function Gn(e){let t=Ze.documents.get(e);return t?w$(t):null}let Kn=(e,t)=>{let n=Ze.documents.get(e);m$(M,Ze,e,t,He,We,nt),n&&Tn(e)&&On(n,e)},qn=(e,t)=>{let n=Cat(M,Ze,e,t,He,We,nt),r=Ze.documents.get(e);return n===`revived`&&r&&Tn(e)&&On(r,e),n},Jn=(e,t)=>{let n=0;for(let[r]of Ze.documents){if(yU(r))continue;let i=Ze.documents.get(r);if(!i)continue;let a=i.getText(`source`).toString();if(a.includes(e))try{i.transact(()=>{d$(i,a,He,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},Yn=e=>{e&&Jn(`[[${e}]]`,{reason:`asset-event`,assetBasename:e})},Xn=()=>{try{let e=Jn(`![[`,{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`)}},Zn=null,Qn=e=>{e&&(Zn===null&&(Zn=new Set,setImmediate(()=>{let e=Zn;if(Zn=null,e)try{for(let t of e)Yn(t)}catch(t){C.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Zn.add(e))};function $n(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 er={delete:`external-change-rescue`,rename:`external-change-rescue`,"branch-switch":`external-change-rescue`,"disk-update":`external-change-rescue-disk-update`},tr=(e,t,n,r,i=``,a=!1)=>{if(!qe.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}`),YH(),!1}let o=qe.current;return queueMicrotask(()=>{VJ(o,p??``,{kind:er[r],docName:e,contents:t,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:i}}).then(()=>{mZe(),C.info({docName:e,site:r},`[reconcile] rescue checkpoint saved (${r}): ${e}`)}).catch(t=>{hZe();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},nr=new WeakSet,rr=e.watcherClock??nX(),ir=null,ar=!1,or=e=>{ne.hold(e),M.holdStores(e.docName)},sr=new Set,cr=new Map,R=e=>{ne.release(e),cr.delete(e),sr.delete(e),M.releaseStores(e)},lr=null,ur=0;function dr(){ur+=1,rr.clearTimeout(lr),lr=null}function fr(e){dr(),pr(e,ur,1).catch(t=>{C.error({err:t,branch:e},`[branch-switch] the follow-up re-checks stopped`)})}async function pr(e,t,n){if(!Zr||t!==ur)return;let r;try{r=await Zr.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!==ur||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}o$e();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 ${xIt/1e3} s`),lr=rr.setTimeout(()=>{lr=null,pr(e,t,n+1).catch(t=>{C.error({err:t,branch:e},`[branch-switch] the follow-up re-checks stopped`)})},xIt),lr.unref()}let mr=()=>{ir||ar||ne.size===0||(ir=rr.setTimeout(()=>{ir=null,hr().catch(e=>{C.error({err:e},`[reconcile] the re-check loop for vanished documents failed`)})},1e3),ir.unref())};async function hr(){if(!Zr)return;ar=!0;let e;try{e=await Zr.recheck(`metadata`)}catch(e){C.warn({err:e},`[reconcile] the re-check for vanished documents failed`)}finally{ar=!1}try{ne.size>0&&(e?.status!==`completed`||e.partial)&&C.info({status:e?.status??`failed`,partial:e?.partial===!0},`[reconcile] the re-check for ${ne.size} vanished document(s) did not observe the whole tree; trying again`),await Or()}finally{mr()}}function gr(e){try{return lc(e),!0}catch(t){let n=aG(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 _r(e,t){let r=e=>{let t=aG(e);return t===`ENOENT`||t===`ENOTDIR`?{kind:`absent`}:{kind:`unreadable`,code:t??`unknown`}};try{lc(t),aae(t,ac.R_OK)}catch(e){let t=r(e);if(t.kind===`absent`||aG(e)!==`ELOOP`)return t}if(!KX(e,t,n,Ge))return{kind:`refused`};try{return{kind:`present`,path:t,content:K(t,`utf-8`)}}catch(e){return r(e)}}function vr(e){let t=Zr?.getFileIndex().get(e.docName)?.canonicalPath??wn(e.docName)??e.path;return _r(e.docName,t)}async function yr(e){if(!Zr||gr(e.path))return!1;let t=ott(e),n=F(e.docName),r=new Set;t.lastHash!==void 0&&r.add(t.lastHash),n!==void 0&&r.add(cG(n));let i={docName:e.docName,path:e.path,identity:t.identity,size:t.size,modified:t.modified,hashes:r,text:n??Gn(e.docName)??void 0},a=ne.matchRecentCreate(i,rr.now(),e=>{let t=_r(e.docName,e.path);return t.kind===`present`?t.content:void 0});if(a){let t=_r(a.create.docName,a.create.path);if(t.kind===`present`)return uU(a.by===`identity`?`paired-identity`:`paired-hash`),await Gr({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 or({...i,afterPass:Zr.recoveryPassesStarted(),heldAt:rr.now()}),uU(`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`),mr(),!0}let br=()=>{se()||Ye.flushDeferredStores(`within-branch`).catch(e=>{C.error({err:e},`[persistence] deferred store drain failed after a vanished file resolved`)})};async function xr(e,t){R(e.docName);try{uU(`recreated`),C.info({docName:e.docName},`[reconcile] ${e.docName}: its file is back; taking it in as an update`),await qr({kind:`update`,path:t.path,docName:e.docName,content:t.content})}finally{br()}}async function Sr(e,t){Ye.discardDeferredStore(e.docName,{kind:`deleted-outside`}),R(e.docName),uU(t);let n={kind:`delete`,path:e.path,docName:e.docName};nr.add(n),await qr(n)}function Cr(e,t){sr.has(e.docName)||(sr.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 wr(e,t,n,r){let i=ne.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 Tr(e,t){R(e.docName),br(),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 Er(e,t){if(t)for(let t of ne.dueAfter(e)){let e={action:`checking its path`};try{await Dr(t,e)}catch(n){wr(t,e,n)}}}async function Dr(e,t){let n=vr(e);switch(n.kind){case`present`:t.action=`taking its returned file in`,await xr(e,n);return;case`unreadable`:Cr(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 Sr(e,`deleted`);return;default:throw Error(`unhandled file probe: ${JSON.stringify(n)}`)}}async function Or(){for(let e of ne.heldBefore(rr.now()-F9)){let t={action:`resolving its hold at the limit`};try{await kr(e,t)}catch(n){if(!ne.has(e.docName)){wr(e,t,n);continue}let r=(cr.get(e.docName)??0)+1;cr.set(e.docName,r),wr(e,t,n,r),r>=3&&Tr(e,r)}}}async function kr(e,t){let n=`${F9/1e3} s`,r;try{r=vr(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 xr(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 Sr(e,`unconfirmed`)}function Ar(e,t,n){let r=T()??`main`,i={from:e,to:t,toFile:`${t}${Js(n)}`},a={writerId:PJ.id,displayName:PJ.name,colorSeed:PJ.id};P8({moves:[i],kind:`file`,branch:r,writer:a,shadow:void 0,notices:Ct});let o=qe.current;o&&Mr(o,r,i,a)}async function jr(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 Mr(e,t,n,r){let i=await jr(e,t),a;try{a=P8({moves:[n],kind:`file`,branch:t,writer:r,shadow:e,notices:void 0,anchors:i})}catch(e){i$e(),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 Ye.flushContributors()}catch(e){o=e}let s=N$(e.gitDir).byTo.get(n.to);if(s!==void 0&&s.commitSha===``){a$e(),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 Nr(e,t,n,r,i){let a;try{return a=await Ze.openDirectConnection(e),Kn(e,r),ee(e,n),i!==n&&await Gr({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 Pr(e){for(let[t,r]of Ze.documents)if(!yU(t)&&r.getMap(`lifecycle`).get(`status`)===void 0)try{let i=HG(t,n);if(!G(i)||!DK(i,hc(i),n))continue;Fr(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 Fr=(e,t,n,r=!1)=>{let i=F(e),a=Gn(e)??``,o=i===void 0?a!==``:a!==i;return o&&(tr(e,a,t,n,``,r),o)};function Ir(e){ce.dissolveReconcile(e),ce.dissolveWorkingTree(ce.fileOf(e))}let Lr=(e,t,n,r)=>{(t.kind===`merged`||t.kind===`both-kept`)&&t.dedupSkipped&&(eZe(),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`))},Rr=async(e,t,n)=>{let r=n===void 0;NQe();let i=Gn(e)??``,a=T()??`main`,o=cG(t).slice(0,6),s=i!==``&&i!==t,c=s?ri(e,`disk-authoritative-ingest`):`not-needed`;s&&tr(e,i,a,`disk-update`,o,!0);let l=cG(i).slice(0,6),u=r?`absent`:`blockless`,d,f=!1;try{Kn(e,t),Ir(e),f=!0}catch(s){d=s,PQe(),C.error({err:s,docName:e},`[reconcile] failed to apply disk-authoritative ingest to Y.Doc for ${e}`),tr(e,t,a,`disk-update`,o,!0),Ir(e);let f;try{f=Gn(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?ee(e,t):M.restoreReconciledBase(e,n),c===`lost`&&f!==i&&(FQe(),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`&&FQe(),(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 zr(e,t),s?{kind:`applied`,merge:`disk-replaced`}:{kind:`applied`}}return{kind:`failed`,error:d}},zr=async(e,t)=>{try{await Ke.recordDiskUpsert(e,t)}catch(t){C.warn({err:t,docName:e},`[reconcile] ${e}: the derived index could not record the disk version`)}};function Br(e){throw Error(`unhandled disk intake outcome: ${e.kind}`)}function Hr(e){throw Error(`unhandled reconcile outcome: ${e.kind}`)}async function Ur(e){let{docName:t,content:n}=e;if(zn(t),fNt(e.previousIndexedFields,n,t)&&nn(t),ce.findByDocName(t)?.kind===`merge-native`)try{await ce.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e,docName:t},`[reconcile] conflict prune against git failed`)}let r=Ze.documents.get(t);if(!r)return b$(M,void 0,t,n,ce)||M.refreshReceiptWithoutBase(t,n),await Ke.recordDiskUpsert(t,n),{kind:`nothing-to-take`};if(qn(t,n)!==`not-frozen`)return await Ke.recordDiskUpsert(t,n),{kind:`nothing-to-take`};let i=cG(n),a=Kgt({receiptHash:M.getReceipt(t)?.hash,eventHash:i,isRecentOwnWrite:M.isRecentOwnWrite(t,i),readDiskHash:()=>{try{return cG(K(e.path,`utf-8`))}catch{return null}}}),o=qgt(a);if(o!==null&&M.getStaleExternalWrite(t)===void 0)return dQe(o),C.debug({docName:t,receiptIntake:a},`[reconcile] ${t}: the disk bytes match its receipt (${a}); nothing to take in`),ce.dissolveReconcile(t),await zr(t,n),{kind:`nothing-to-take`};let s=F(t),c=Gn(t)??s??``;if(b$(M,r,t,n,ce,c))return await zr(t,n),{kind:`conflict`};if(s===void 0)return Rr(t,n,void 0);let l=cY({docName:t,base:s,ours:c,theirs:n}),u=cG(s).slice(0,6),d=cG(c).slice(0,6),f=cG(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}${_}`),Lr(t,l,c,n),l.kind){case`noop`:return ce.dissolveReconcile(t),await zr(t,n),{kind:`nothing-to-take`};case`clean`:try{Kn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),ee(t,s),ce.dissolveReconcile(t),{kind:`failed`,error:e}}return ee(t,l.newContent),JH(),ce.dissolveReconcile(t),await zr(t,n),{kind:`applied`,merge:`clean`};case`merged`:try{Kn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),ee(t,s),ce.dissolveReconcile(t),{kind:`failed`,error:e}}return ee(t,n),JH(),ce.dissolveReconcile(t),await zr(t,n),{kind:`applied`,merge:`merged`};case`both-kept`:try{Kn(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`),ee(t,s),$Xe(),ce.raise({kind:`reconcile`,file:ce.fileOf(t),reason:`merged-with-markers`,stages:{base:s,ours:c,theirs:n}}),{kind:`failed`,error:e}}return wt.bothKept(t,{ours:c,theirs:n},l.kept),ee(t,n),JH(),v$(t,l.kept,`watcher`),ce.dissolveReconcile(t),await zr(t,n),{kind:`applied`,merge:`both-kept`};case`refused`:return l.reason===`no-base`?Rr(t,n,s):(_$(t,l,`watcher`),(l.reason===`check-failed`||l.reason===`too-large`)&&await wt.keptLive(t,{side:`theirs`,bytes:n},l.reason)?(ee(t,n),y$(t,l.reason,`watcher`),ce.dissolveReconcile(t),await zr(t,n),{kind:`applied`,merge:`kept-live`}):($Xe(),ce.raise({kind:`reconcile`,file:ce.fileOf(t),reason:Tat(l.reason),stages:{base:s,ours:c,theirs:n}}),{kind:`conflict`}));default:return Hr(l)}}let Wr=new Map;async function Gr(e,t=e.kind===`delete`||e.kind===`rename`?Wr.get(e)??Pn(e.kind===`delete`?e.docName:e.oldDocName,GX(e)):void 0){try{switch(e.kind){case`create`:{let t=ott(e),n=cG(e.content),r=ne.matchCreate({docName:e.docName,identity:t.identity,size:t.size,modified:t.modified,hash:n,content:e.content});if(r){if(R(r.vanished.docName),r.by===`same-name`){uU(`recreated`),C.info({docName:e.docName},`[reconcile] ${e.docName}: its file came back; taking it in as an update`),await Gr({kind:`update`,path:e.path,docName:e.docName,content:e.content}),br();break}let t=M.beginRenameCarry(r.vanished.docName);try{Ye.discardDeferredStore(r.vanished.docName,{kind:`renamed-outside`,to:e.docName,carry:t}),uU(r.by===`identity`?`paired-identity`:`paired-hash`),await Gr({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}ne.rememberCreate({docName:e.docName,path:e.path,identity:t.identity,size:t.size,modified:t.modified,hash:n,at:rr.now()}),C.info({docName:e.docName},`[reconcile] create: ${e.docName}`),qn(e.docName,e.content),await Ke.recordDiskUpsert(e.docName,e.content),kt(`files`),nn(e.docName),zn(e.docName);break}case`update`:await Ur(e);break;case`delete`:{let{docName:n}=e,r=t??Pn(n,GX(e));Wr.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&&!nr.has(e)&&await yr(e))return;t&&(Ir(n),bn.current?.deleted(n));let{document:a}=r,o=i&&a?Fr(n,T()??`main`,`delete`,!0):!1;if(i&&(a?.getMap(`lifecycle`).set(`status`,`deleted-upstream`),M.endRenameCarry(n)),t&&I(n),t&&await Ke.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&&(Ze.closeConnections(n),await ht(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}kt(`files`),In(n),an(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??Pn(n,GX(e));Wr.delete(e),M.beginRenameCarry(n);let o=null,s=!1;try{let t=a.document,c=a.residentCurrent()&&t?t:null,l=c?Gn(n):null,u=c?dG(c):null,d=F(n),f=e=>{let t=e.getMap(`lifecycle`);t.set(`status`,`renamed`),t.set(`newPath`,r)},p=a.residentCurrent()&&t?Fr(n,T()??`main`,`rename`):!1;a.residentCurrent()&&t&&f(t),a.namespaceCurrent()&&(Ir(n),I(n),Ye.forgetObservedFile(n),Fn(n,r)),ee(r,i),C.info({oldDocName:n,newDocName:r,isDirty:p},`[reconcile] rename: ${n} → ${r} (dirty=${p})`),kt(`files`),zn(r);try{a.namespaceCurrent()?await Ke.recordDiskRename(n,r,i):await Ke.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()?Ze.documents.get(n):void 0,h=m===t?void 0:m;h&&f(h),qn(r,i),nn(r),a.namespaceCurrent()&&Ar(n,r,e.newPath),l!==null&&d!==void 0&&(l===d||await Nr(r,e.newPath,d,l,i))&&(o=u);let g=a.residentCurrent()&&t?t:h;if(s=!!g,g){let e=g.getConnectionsCount();Ze.closeConnections(n),await Qe.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`})),an(n)}finally{M.settleRenameCarry(n,o),s||M.endRenameCarry(n),a.dispose()}break}case`conflict`:{let{docName:t}=e;if(!Ze.documents.get(t))return;let n=F(t)??``,r=Gn(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`):ee(t,r),ce.raise({kind:`reconcile`,file:ce.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`:ze.add(e.relativePath),kt(`files`),Qn(Ks(e.relativePath));break;case`asset-delete`:ze.remove(e.relativePath),kt(`files`),Qn(Ks(e.relativePath));break;case`folder-create`:case`folder-delete`:kt(`files`),rn(e.relativePath);break;case`file-create`:case`file-update`:await Ke.recordFileTargetUpsert(e.relativePath),st?.(),kt(`files`),await $r(e.relativePath);break;case`file-delete`:await Ke.recordFileTargetDelete(e.relativePath),st?.(),kt(`files`);break;default:cX(e)}}catch(t){let n=$n(e);C.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let Kr=[];async function qr(e){if(!De){if((e.kind===`delete`||e.kind===`rename`)&&!Wr.has(e)&&Wr.set(e,Pn(e.kind===`delete`?e.docName:e.oldDocName,GX(e))),se()||Jr!==null){Kr.push(e);return}await Gr(e)}}let Jr=null;function Yr(){if(Jr)return Jr;if(Kr.length===0)return Promise.resolve();let e=Promise.withResolvers();return Jr=e.promise,(async()=>{try{for(;Kr.length>0;){let e=Kr.splice(0,Kr.length);for(let t of e)await Gr(t)}e.resolve()}catch(t){e.reject(t)}finally{Jr=null}})(),e.promise}function Xr(){for(let e of Wr.values())e.dispose();Wr.clear()}let Zr=null;function Qr(e){return gU(e)||_U(e)||vU(e)}async function $r(e){if(!Qr(e))return!1;let t=Ze.documents.get(e);return t?await gPt(t,e,Ye.mermaidPersistenceCtx)!==`unchanged`:!1}async function ei(e,t){if(!Zr)return{checked:0,found:0};let r=Zr.getAliasMap(),i=Zr.getFileIndex(),a=[],o={checked:0,found:0};for(let s of new Set(e)){let e=r.get(s)??s;if(yU(e))continue;if(Qr(e)){o.checked++,await $r(e)&&o.found++;continue}let c=i.get(e)?.canonicalPath;if(c!==void 0){a.push(c);continue}try{a.push(HG(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 Zr.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 ti=null,ni=null,ri=(e,t)=>{let n=qe.current;if(!n)return C.warn({docName:e,context:t},`[rescue] shadow repo unavailable — cannot buffer ${e} (${t})`),YH(),`lost`;try{let r=xU(e)?Ze.documents.get(e)?.getText(`source`).toString()??null:Gn(e);if(r===null)return C.warn({docName:e,context:t},`[rescue] skipping ${e} — document dropped from map mid-rescue (${t})`),YH(),`lost`;let i=Wn(n.gitDir,e);return i?(qU(V(i),{recursive:!0}),GU(i,r,`utf-8`),mZe(),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})`),YH(),`lost`)}catch(n){return C.error({err:n,docName:e,context:t},`[rescue] failed to write rescue buffer for ${e} (${t})`),YH(),`lost`}};async function ii(e){if(Ze.documents.size===0)return;let t=!1,n=Date.now()+e,r,i=Promise.withResolvers(),a=bIt(Ze,()=>{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())}};Ze.configuration.extensions.push(o);try{let o=Array.from(Ze.documents.keys());Ze.closeConnections(),Ze.flushPendingStores();for(let e of Ze.documents.values())e.getConnectionsCount()===0&&Ze.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(Ze.documents.values()).some(e=>e.getConnectionsCount()===0&&!gt(e));)await new Promise(e=>setTimeout(e,25));for(let e of M.getRefusedStoreDocNames()){if(yU(e))continue;let t=Ze.documents.get(e);if(!t||!gt(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(ri(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=ht(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(Ze.documents.keys()),r=[],i=[];if(qe.current)for(let e of n)yU(e)||(ri(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)yU(e)||(i.push(e),YH())}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=Ze.configuration.extensions,n=e.indexOf(o);n!==-1&&e.splice(n,1),r&&clearTimeout(r.id)}}async function ai(){return ni||(ni=(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)}};pt=!0;let s=Promise.allSettled([tt()]),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`)}rr.clearTimeout(ir),ir=null,dr();for(let e of ne.all())Ye.discardDeferredStore(e.docName,{kind:`shutdown`}),Fr(e.docName,T()??`main`,`delete`,!0),uU(`shutdown`),M.releaseStores(e.docName);ne.clear(),M.endAllRenameCarries(),sr.clear(),cr.clear(),De=!0,Xr();for(let e of Sn.values())for(let t of e)t.namespaceAllowed=!1,t.residentAllowed=!1;Sn.clear(),xn=new WeakMap;try{await o(tn(),`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 mt.splice(0))e();try{await o(Promise.resolve(ct?.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)})}ct=null;try{I4(Pe)}catch(e){C.warn({err:e},`[server] failed to mark server.lock draining`)}Je?.destroy();try{await o($t(),`shadow-housekeeping`)}catch(e){C.warn({err:e},`[shadow-housekeeping] shutdown drain failed`),t.push({phase:`shadow-housekeeping-drain`,error:String(e)})}if(gn!==null&&(clearTimeout(gn),gn=null),_n)try{QPt(r,yn.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([yt.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(Ze.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=Ze.documents.size,p=async(e,n)=>{if(e!==null)try{await e.unsubscribe()}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),C.error({err:e,watched:n},`[server] shutdown phase-1 watcher unsubscribe failed`)}};try{try{rt&&=(clearTimeout(rt),null),it&&=(clearTimeout(it),null),await p(w,`head`),w=null,await p(Zr,`content`),Zr=null;for(let{docName:e,cleanup:t}of Hn)try{await t()}catch(t){C.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Hn.length=0,Un.clear();try{O?.destroy(),ot?.destroy(),Bn&&=(await Bn.disconnect(),null);for(let[e,t]of Vn)try{await t.disconnect()}catch(t){C.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Vn.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 Qe.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 Cnt()}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 ii(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([Ke.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 Ye.flushPendingGitCommit(),await Ye.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{ti&&=(await ti.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(qe.current){let e;try{await Promise.race([xJ(qe.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 nM({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&xc(W(qe.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{n7e(qe.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){Ee=!0;try{Le.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(Pe,{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 OU()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}if(c?.status===`rejected`)throw c.reason})(),ni)}let oi=[];async function si(){try{dt=await HPt(r),C.info({principalId:dt.id},`[server] principal loaded`)}catch(e){C.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!qe.current)try{qe.current=await AJ(r,{deferGcConfig:!0}),C.info({gitDir:qe.current.gitDir},`[server] history repo initialized at ${qe.current.gitDir}`),Q5e(qe.current)&&!oi.includes(`shadow-excludes`)&&oi.push(`shadow-excludes`)}catch(e){C.error({err:e},`[server] history repo init failed`),oi.push(`shadow-repo`)}if(qe.current)try{let e=Wat(qe.current.gitDir);cot(qe.current.gitDir,e),Yat(qe.current.gitDir,e),Xt=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(qe.current)try{await OJ(qe.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{qe.current=await AJ(r,{deferGcConfig:!0}),Q5e(qe.current)&&!oi.includes(`shadow-excludes`)&&oi.push(`shadow-excludes`)}catch(e){C.error({err:e},`[server] history repo reinit failed`),qe.current=void 0,oi.includes(`shadow-repo`)||oi.push(`shadow-repo`)}}else C.error({err:e},`[server] history repo check failed (transient?)`)}if(qe.current&&ni===null){let e=qe.current,t=oG(U(r,n))||`.`;it=setTimeout(()=>{it=null,NJ(e,t).catch(e=>{C.debug({err:e},`[shadow] fan-out index warm-up failed (non-fatal)`)})},3e3),it.unref?.()}if(qe.current)try{let e=W(qe.current.gitDir,`last-known-head`),t=null;try{t=K(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await nM({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await nM({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(qe.current,p??``,t,n,e),dZe()}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{xc(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=LCt(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`),oi.push(`managed-rename-recovery`)}try{let e=Bmt(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`),oi.push(`upload-tempfile-sweep`)}try{Bn=await Ze.openDirectConnection(Ue),O?.emitServerInfo(Te,E()??void 0)}catch(e){C.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),oi.push(`cc1-push`)}let t=y?[]:Vr;for(let e of t)try{let t=await Ze.openDirectConnection(e);Vn.set(e,t)}catch(t){C.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),oi.push(`config-doc:${e}`)}let i=new Map([[ve,bl(`project`,r)],[Rn,bl(`project-local`,r)],[pne,bl(`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=Ze.documents.get(e),r=xMt(e,t,Ye.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,Ye.configPersistenceCtx);C.info({docName:e,outcome:i,isEcho:r},`[config-file-watcher] applyExternalConfigChange outcome`),we(e),r||ye(e)},r=await Qjt(t,t=>{n(t).catch(t=>{C.warn({err:t,docName:e},`[config-file-watcher] change handler failed`)})});Hn.push({docName:e,cleanup:r}),Un.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}`),oi.push(`config-file-watcher:${e}`)}}if(!y){let e=null,t=t=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,Ke.refreshGlobalSkillNodes().catch(e=>{C.warn({err:e,docName:t},`[backlinks] global skill bundle re-ingest failed`)})},300)},n=async(e,n)=>{let r=n_t(e,Ye.managedArtifactCtx);if(!r)return;let i=await c_t(Ze.documents.get(r)??null,r,n,Ye.managedArtifactCtx);C.info({docName:r,outcome:i},`[managed-artifact-watcher] external change`),kt(`files`),Oo(r)&&t(r)},r=e=>{let n=n_t(e,Ye.managedArtifactCtx);kt(`files`),n&&Oo(n)&&t(n)};try{let e=Qgt(Ye.managedArtifactCtx),t=await sPt(e,n,r);Hn.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`),oi.push(`managed-artifact-watcher:skills`)}try{let e=DQ(t6(Ye.managedArtifactCtx)),t=await Qjt(e,()=>{kt(`files`)});Hn.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`),oi.push(`skill-state-watcher`)}}try{let e=W(n,`.okignore`),t=W(r,`.gitignore`),i=null;try{let e=Ws(`git`,[`rev-parse`,`--git-common-dir`],aW({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 $jt(a,(t,n)=>{(async()=>{if(t===e)try{let e=await F7(Ze.documents.get(`__config__/okignore`)??null,je,n,Ye.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 Ge.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&&(Hn.push({docName:`__ignore-files__`,cleanup:s}),Un.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`),oi.push(`ignore-files-watcher`)}let a=t9(r).branch??`main`;te(a),Et();let o=Ke.beginStartup(a),s=!1,c=performance.now();try{await jU(`ok.boot.indexes`,void 0,async()=>{let t=await o.offlineDeletionsReady,i=0;for(let e of t)yU(e)||yn.peek(e)?.kind!==`renamed`&&(yn.setDeleted(e),i++);i>0&&C.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`),Tt.resolve();let{backlinkIndexDegraded:a}=await o.backlinksReady;a&&oi.push(`backlink-index`);let c=performance.now(),l=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,d=Ge?new Set(U1(n).map(e=>e.dir)):new Set,f=e=>{e.some(e=>l.test(U(b,e).split(Qs).join(`/`)))&&(rt&&clearTimeout(rt),rt=setTimeout(()=>{rt=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=xct(n,d);if(!(e.size!==d.size||[...e].some(e=>!d.has(e))))return;d=e,Ge.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))};Zr=await jU(`ok.boot.seed-walk`,void 0,async()=>qtt(b,qr,Ge,{onRawBatch:f,onRecoveryComplete:()=>Ke.recordInventoryReconciled(),onRecoveryPassCompleted:(e,t)=>Er(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??wc();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 yn.entries()){if(!o5(n))continue;let r=W(e,`${n}${UH(n)}`);sG(r,e)&&G(r)&&(yn.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 Ke.settleStartupAfterWatcherSeed();s=!0,p.tagIndexDegraded&&oi.push(`tag-index`);let m=0;try{v===void 0?await u5({contentDir:n,contentFilter:Ge,basenameIndex:ze,onSkip:(e,t,n)=>{m++,C.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):pTt({contentDir:n,basenameIndex:ze,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`),oi.push(`basename-index-partial`))}catch(e){C.error({err:e},`[basename-index] startup seed failed`),oi.push(`basename-index`)}})}catch(e){if(C.error({err:e},`[server] disk bridge watcher failed to start`),oi.push(`file-watcher`),!s){let e=await Ke.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&oi.push(`tag-index`)}}finally{r4(`indexesMs`,Math.round(performance.now()-c)),Zr&&Wft(`fileCount`,Zr.getFileIndex().size),Xn()}let l=()=>{};try{w=await kNt(r,async({trigger:e})=>{if(C.info({trigger:e},`[batch] begin trigger=${e}`),uZe(),Ze.flushPendingStores(),await Ye.flushPendingGitCommit(),re(`head-watcher`),l(),l=M.holdWriteAdmission(),qe.current){let e=P(),t=t9(r).branch??e,n=[],i=0;for(let[e,t]of Ze.documents){if(yU(e))continue;let r=null;if(t.transact(()=>{r=Gn(e)},SIt),r===null)continue;let a=F(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 v7e(qe.current,e,IJ.id,n,t);r&&(_Ze(),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=Kr.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 Yr()}finally{Xr()}if(e.headMoved&&e.newHead){let t=wIt(r,W(n),e.oldHead,e.newHead);if(t.size>0){fat(t.keys());for(let[e,n]of t)c$(e,Eve(n.email),n.name,n.email,Yve(e));await Ye.flushContributors()}}}finally{try{ie(`head-watcher`)&&await ae()}finally{l()}}try{await ce.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e},`[head-watcher] conflict prune against git failed`)}}else{gZe(),dr();let t=!1,r=!1,a;try{te(i),ce.setBranch(i),le(),a=await Ke.beginBranchSwitch(i),Ge.rebuildDirCount();try{let e=0;ze.clear(),await u5({contentDir:n,contentFilter:Ge,basenameIndex:ze,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`),oi.includes(`basename-index-partial`)||oi.push(`basename-index-partial`))}catch(e){C.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}try{await Ke.settleBranchFromDisk(a)}catch(e){Ke.abortBranchSwitch(a),C.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}try{await Yr();let e=await Zr?.recheck(`full`);e&&(e.status!==`completed`||e.partial)&&(r=!0,o$e(),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 Yr()}finally{Xr()}if(Pr(i),C.info({branch:i,docCount:Ze.documents.size},`[branch-switch] loaded branch ${i} (${Ze.documents.size} docs)`),e.oldBranch?.startsWith(`detached-`)&&qe.current)try{let t=OJ(qe.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await xJ(qe.current).withMutator(async()=>{for(let e of n.split(`
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,ie(`head-watcher`)&&await ae(),O?.emitBranchSwitched(i),r&&fr(i)}finally{try{Ke.abortBranchSwitch(a),!t&&ie(`head-watcher`)&&await ae()}finally{l()}}}if(e.headMoved&&e.newHead&&qe.current&&t>0){let t=p??`.`;try{let n=await RJ(qe.current,t,e.oldHead,e.newHead,i);dZe(),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:()=>{oi.includes(`head-watcher`)||oi.push(`head-watcher`)},onBack:()=>{let e=oi.indexOf(`head-watcher`);e!==-1&&oi.splice(e,1)}})}catch(e){C.error({err:e},`[server] HEAD watcher failed to start`),oi.push(`head-watcher`)}ce.subscribe(e=>{if(e.type!==`raised`||e.conflict.kind===`reconcile`)return;let t=e.docName;if(t===null||!Ze.documents.get(t))return;let n=Gn(t);n===null?C.warn({docName:t,file:e.conflict.file},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):ee(t,n)});try{await ce.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e},`[conflicts] boot prune of merge-native entries failed`)}let d=await S(),f=de(),m=fe();f.mode!==`off`&&C.info({mode:f.mode,source:f.source},`[sync] mode active at boot`);try{ti=new cIt({declaredGitHubHosts:x,projectDir:r,contentDir:n,contentFilter:Ge,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:ce,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:oe(`sync-engine`),onStateChange:e=>{C.info({state:e},`[sync] state → ${e}`)},checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=qe.current;n&&await BJ(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=qe.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 Sl({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||C.error({result:t,reason:e,humanError:Ft(t.error),configPath:bl(`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 ti.start()}catch(e){C.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ti=null}kt(`files`),Ke.announceReadyViews();let h=Uft();h!==void 0&&r4(`readyMs`,h),ye()}return si().then(()=>{Nt=!0,_t(),setImmediate(()=>{let e=A.pruneGone(j);e>0&&C.info({pruned:e},`[disk-receipts] dropped ${e} receipt(s) whose file is gone`)}).unref(),qt(),Qt()},e=>{Pt=!0,It.abort(),Wt({status:`failed`,indexCount:0}),Ke.close(),Et(),vt(e)}),{hocuspocus:Ze,durabilityState:M,sessionManager:Qe,nativeApi:$e,localApi:et,cc1Broadcaster:O,agentFocusBroadcaster:at,agentPresenceBroadcaster:ot,maintenanceCoordinator:Je,contentFilter:Ge,basenameIndex:ze,serverInstanceId:Te,destroy:ai,ready:yt,generatedIndexSweepReady:Ut,degraded:oi,lockDir:Pe,get syncEngine(){return ti},conflicts:ce,getLinkPreviewsEnabled:ge,resolveEmbed:He,resolveTrackedFile:Be,acpRegistry:Fe,acpPermissions:Ie,recheckDisk:()=>Zr?Zr.recheck():Promise.reject(Error(`the file watcher is not running, so there is nothing to re-check`))}}function I9(e){return e/1048576}function EIt(){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 DIt=1e6;let B9=null,V9=null;DU(()=>{L9=null,R9=null,z9=null,B9?.disable(),B9=null,V9=null});function OIt(){if(L9)return;let e=AU().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}=EIt();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 kIt(){if(!R9){let e=AU().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=Rae({resolution:20}),B9.enable();return}e.observe(B9.percentile(50)/DIt,{stat:`p50`}),e.observe(B9.percentile(99)/DIt,{stat:`p99`}),B9.reset()}),R9=e}if(!z9){let e=AU().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 AIt=q(`skill-migrate`);function jIt(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=aN.indexOf(e.host),r=aN.indexOf(t.host);return(n===-1?aN.length:n)-(r===-1?aN.length:r)||e.host.localeCompare(t.host)})}const MIt=jIt(Ne),NIt=jIt(be);function PIt(e,t){return G(W(e,ko(t)))}function FIt(e,t){qU(V(t),{recursive:!0});try{JU(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;YU(e,t,{recursive:!0}),tW(e,{recursive:!0,force:!0})}}function IIt(e,t,n){let r=Vct(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 LIt(e,t){let n;try{n=hc(W(e,`.ok`,`skills`))}catch{n=W(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!hc(W(e,t.dir)).startsWith(n+Qs)}catch{return!0}}).map(e=>e.name))}async function RIt(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??MIt,o={migrated:[],skipped:[]};if(!G(n))return o;let s;try{s=mc(n)}catch{return o}let c=U(t,n).split(Qs).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)||AH.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=ZM(r)?.contentHash;if(s===void 0)continue;let c=hc(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:IIt(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=>PIt(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`?tW(r,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&tW(d.path,{recursive:!0,force:!0}),FIt(r,d.path));for(let e of u)e!==d&&e.state.kind===`store-link`&&(tW(e.path,{recursive:!0,force:!0}),YU(d.path,e.path,{recursive:!0}));await Z1(t,e),o.migrated.push({name:e,to:`${d.root}/${e}`}),AIt.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){o.skipped.push({name:e,reason:`error`}),AIt.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return o}let H9=null,U9=!1;function zIt(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function BIt(e){if(!zIt())return;let t=qJ(e);H9=new Yx({currentPath:W(t,`tolerance-telemetry.jsonl`),previousPath:W(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),_(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(){_(null),await H9?.drain(),H9=null,U9=!1}function VIt(e){let t=W(e,wi);if(!(()=>{if(!G(t))return!0;try{return mc(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 bee){let r=W(e,t);try{G(r)&&yc(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function HIt(e){let t=iS(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 UIt(e){Hft();let t=e.projectDir??e.contentDir,n=Cl(t),r=jTt({projectDir:t});if(r){Ujt(t,{authorityRegistryPath:e.authorityRegistryPath});let n=r.telemetry.attributeDenylist,i=[];for(let e of n){i.push(e);for(let t=1;t<=5;t++)i.push(`${`*.`.repeat(t)}${e}`)}$x.configure({pinoConfig:{fileSink:r.logs,redactPaths:i}})}EU({localSink:r?.telemetry}),BIt(t),OIt(),kIt();let{kind:i,gitdir:a}=HIt(e.projectDir??e.contentDir),o={"ok.worktree.kind":i};a!==null&&(o[`ok.worktree.gitdir`]=FU(a));let s=wTt(t),c=process.env.OK_STARTUP_TRACEPARENT,l=()=>jU(`ok.boot`,{attributes:o},async()=>WIt(e,n)),u=()=>{if(c)try{let e=Io.extract(Mo.active(),{traceparent:c});return Mo.with(e,l)}catch(e){q(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return l()},d;try{d=await u()}catch(e){throw s.uninstall(),e}let f=d.destroy;return d.destroy=async e=>{try{await f(e)}finally{s.uninstall()}},d}async function WIt(e,t){let n=e.skipAutoInit??!1,r=e.log??q(`boot`),i=e.serverRuntime??{...or(e.config),allowExternal:!1},a=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((hee(i)||!gr(a))&&!i.allowExternal)throw new jit(`refusing to start: the server would bind a non-loopback address (${(gr(a)?i.bind:a).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let o=BQ({serverRuntime:i});i.allowExternal&&!i.loopbackOnly&&i.externalUrl===void 0&&(o.bindLiterals.length===0?r.warn({bind:i.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.`):r.info({bind:i.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 s=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,c=e.lockKind??s??`interactive`,{createServer:l}=await import(`node:http`),{markServerLockDraining:u,releaseServerLock:d,updateServerLockPort:f}=await Promise.resolve().then(()=>rmt),p=!1;if(!n&&e.autoInitFn)try{p=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let m=e.projectDir??e.contentDir,h=W(m,`.ok`),g=W(h,`config.yml`);if(!G(g))throw new Rjt(G(h)?`config`:`okdir`,m);let _=W(h,`.gitignore`);G(_)||q(`boot`).warn({path:_},`Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run \`${Jt()} init\` to add the recommended ignore entries.`);let v=e.gitPreflight??lW;try{e.gitEnabled!==!1&&v()}catch(e){if(e instanceof oW||e instanceof sW||e instanceof cW){let t=N6(e);P6(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:t.reason,detectedVersion:t.detectedVersion},t.logMessage),process.stderr.write(`${e.message}\n`)}throw await OU(),await Promise.race([W9(),new Promise(e=>setTimeout(e,G9))]),e}let y=VIt(h);y.length>0&&q(`boot`).warn({files:y},`Found legacy runtime files at .ok/${y.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${wi}/.`);let b=null,x=TIt({authorityRegistryPath:e.authorityRegistryPath,getCollabClientCount:()=>b?.getCount()??0,acpRegistryFetchImpl:e.acpRegistryFetchImpl,contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:o,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:c,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:S,destroy:C,ready:w,degraded:T,lockDir:E,sessionManager:D,agentFocusBroadcaster:O,agentPresenceBroadcaster:k,maintenanceCoordinator:A}=x,j=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),M=e.port??0,N=()=>`http://${j}:${M}`,P=e.ephemeral?void 0:kjt({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>N(),localApi:x.localApi,log:r}),F=l();F.headersTimeout=3e4,F.requestTimeout=6e4;let ee=e.serveContentAssets===!1?void 0:fTt({contentDir:e.contentDir,contentFilter:x.contentFilter,contentSirv:TI(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:nne,assetExtensions:ro,blocklistExtensions:Are,ingressPolicy:o,resolveTrackedFile:x.resolveTrackedFile}),I=e.reactShellDistDir?TI(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0,setHeaders:TTt(e.reactShellDistDir)}):void 0,te=e.ephemeral?null:new h8e({contentDir:e.contentDir,localDir:E,globalDir:ml(),registry:x.acpRegistry,permissions:x.acpPermissions,sessionManager:D,agentPresenceBroadcaster:k,localApi:x.localApi,isExcludedPath:e=>x.contentFilter.isExcluded(e),isIgnoredPath:e=>x.contentFilter.isPathIgnored(e),getLoadedDocText:e=>S.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>N(),getMcpStdioCommand:()=>m8e(e.localOpCliArgs,M,{log:r}),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,probePiAcpBridge:e.probePiAcpBridge,ensurePiAcpBridge:e.ensurePiAcpBridge,terminalAuthAvailable:e.terminalAuthAvailable===!0,hostSnapshot:()=>Pq({env:`local-web`,resolve:e.agentIntegrations?.probe}),autoApproveOkTools:()=>cXe(e.projectDir??e.contentDir,e.configHomedirOverride,r),agentBrowserTools:()=>lXe(e.projectDir??e.contentDir,e.configHomedirOverride,r),log:r});te!==null&&await te.init();let ne=`pending`;w.then(()=>{ne=`ready`},()=>{ne=`failed`});let re=Ijt({httpServer:F,hocuspocus:S,nativeApi:x.nativeApi,mcpHttpHandler:P,ingressPolicy:o,health:{readiness:()=>ne,degraded:()=>T},log:r,sessionManager:D,agentFocusBroadcaster:O,agentPresenceBroadcaster:k,maintenanceCoordinator:A,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ee,reactShellMiddleware:I,ephemeral:e.ephemeral,acpThreadManager:te}),ie=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)};b=m5(F);let ae=null,oe=[...new Set(a)],se=oe[0],ce=async()=>{await C().catch(e=>{r.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),d(E)},le=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await le(F,e.port??0,se??`127.0.0.1`)}catch(e){throw await ce(),e}let ue=F.address(),de=typeof ue==`object`&&ue?ue.port:e.port??0,fe=[];for(let e of oe.slice(1)){let t=l();t.headersTimeout=F.headersTimeout,t.requestTimeout=F.requestTimeout;for(let e of F.listeners(`request`))t.on(`request`,e);for(let e of F.listeners(`upgrade`))t.on(`upgrade`,e);try{await le(t,de,e)}catch(t){r.error({err:t,failedAddress:e,port:de,alreadyBound:fe.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...fe,F])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&r.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await ce(),t}fe.push(t)}let pe=Uft();pe!==void 0&&r4(`httpListenMs`,pe);let me=F.address(),he=typeof me==`object`&&me?me.port:e.port??0;M=he;let ge=N();f(E,he,ge),r.info({event:`server-listening`,pid:process.pid,port:he,addresses:oe,url:ge,lockDir:E},`[boot] listening on ${ge}`);let _e=!1,ve=async(e,t,n)=>{let r,i,a=!1,o=Promise.withResolvers(),s=()=>{a||(a=!0,o.reject(Error(n?`${e} timed out: no document retired for ${G9}ms`:`${e} timed out after ${G9}ms`)))},c=()=>{r=setTimeout(s,G9),r.unref?.()};try{n&&(i=bIt(n,()=>{a||(r!==void 0&&clearTimeout(r),c())}),c());let e=t();n||c(),await Promise.race([e,o.promise])}finally{a=!0,i?.(),r!==void 0&&clearTimeout(r)}};ie=async(e=`unspecified`)=>{if(_e)return;_e=!0;try{let e=lc(t);if(e.isDirectory()&&!e.isSymbolicLink()){let e=new Date;RU(t,e,e)}}catch{}r.info({reason:e,pid:process.pid,lockDir:E},`[server] shutdown initiated (${e})`),ne=`draining`;let n=[],i=async(e,t,i)=>{try{await ve(e,t,i)}catch(t){n.push(t),r.warn({err:t,step:e},`bootServer destroy step failed`)}};try{u(E)}catch(e){r.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{b?.detach()}catch(e){r.warn({err:e,step:`collabClientCounter.detach`},`bootServer destroy step failed`)}try{ae?.detach()}catch(e){n.push(e),r.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(te!==null&&await i(`acpThreads.destroy`,()=>te.destroy()),await i(`secondaryListeners.close`,async()=>{for(let e of fe)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&r.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await i(`mount.shutdown`,()=>re.shutdown()),P!==void 0&&await i(`mcpHttpHandler.close`,()=>P.close()),await i(`mount.wss.close`,()=>new Promise((e,t)=>{re.wss.close(n=>n?t(n):e())})),await i(`httpServer.closeAllConnections`,async()=>{F.closeAllConnections?.()}),await i(`httpServer.close`,()=>new Promise((e,t)=>{F.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await i(`destroyHocuspocus`,()=>C(),S),await i(`shutdownTelemetry`,()=>OU()),await i(`teardownToleranceTelemetry`,()=>W9()),await i(`flushLogFileSinks`,()=>$x.flushAllFileSinks()),n.length>0)throw AggregateError(n,`bootServer destroy completed with errors`)};try{let t=await RIt({projectDir:m,skillsRoot:W(e.contentDir,`.ok`,Ea),inPlaceNames:async()=>LIt(e.contentDir,U1(e.contentDir))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=wc(),t=await RIt({projectDir:e,skillsRoot:W(e,`.ok`,Ea),hostRoots:NIt,inPlaceNames:async()=>LIt(e,await G1(e))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}if(e.idleShutdownMs!==null){let t=e.idleShutdownMs??18e5,n=e.idleShutdownHandler??(e=>async()=>{await e()});ae=ETt({httpServer:F,counter:b,thresholdMs:t,log:r,onShutdown:n(async()=>{await ie(`idle-shutdown`)})})}return{httpServer:F,destroy:ie,lockDir:E,contentDir:e.contentDir,port:he,ready:w,generatedIndexSweepReady:x.generatedIndexSweepReady,degraded:T,didAutoInit:p,serverInstance:x,runtime:Gjt(x,{contentDir:e.contentDir,projectDir:m}),acpThreadManager:te}}const GIt=Se;function KIt(e={}){let t=e.home??wc(),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=Px(S_e(),1);function q9(){return H(ml(),`logs`)}const qIt=[`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 YIt(e){uc(e,{recursive:!0})}function XIt(){return new Date().toISOString().slice(0,10)}function ZIt(e){try{if(yc(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{gc(n,r)}catch{}}try{bc(`${e}.3`)}catch{}}function QIt(e){try{let t=Date.now(),n=6048e5,r=mc(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=yc(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{bc(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{bc(H(e,t.name)),a-=t.size}catch{}}}catch{}}function $It(e){YIt(q9());let t=XIt(),n=e.filePath??H(q9(),`${e.name}.${t}.log`);ZIt(n),(e._setTimeout??setTimeout)(()=>QIt(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:qIt,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 eLt(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 tLt(e){return H(q9(),`${e}.${XIt()}.log`)}function nLt(){return q9()}function rLt(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=Hc(Vs),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 iLt(e,t){try{return await J9(e,[`var`,`GIT_COMMITTER_IDENT`],aW({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function aLt(e,t){try{let{stdout:n}=await J9(e,[`for-each-ref`,`--count=1`,`refs/`],aW({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return Y9.warn({path:t,stderr:sLt(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function oLt(e){let t=W(e,`packed-refs`);if(G(t))try{if(K(t,`utf-8`).split(`
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(!UG(a,t))continue;let s=OX(a,t);i.has(s)||G(a)&&i.set(s,o)}return i}function TIt(e){dIt();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=IG(n,{root:`content`,component:`server-factory`}),x=x6(u),S=Xvt({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=OMt(W(n)),O=null,k=t9(r).branch??`main`,A=new p2e({path:H(qJ(r),`receipts.jsonl`)}),j=d2e(n),M=new EG(k,{persistencePath:H(qJ(r),`stale-external-writes.json`),receipts:A,onStaleExternalWriteChange:()=>{O?.signal(`sync-status`),le()},onStoreRefused:e=>{si(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,HG(e,n)).replaceAll(`\\`,`/`),hasResolvedExtension:WH}),P=()=>M.getActiveBranch(),F=e=>M.getReconciledBase(e),ee=(e,t)=>M.setReconciledBase(e,t),I=e=>M.deleteReconciledBase(e),te=e=>M.switchReconciledBaseScope(e),ne=new yIt,re=e=>M.holdBatch(e),ie=e=>M.releaseBatch(e),ae=async()=>{try{await Yr()}finally{Xr()}await Ye.flushDeferredStores(`within-branch`)},oe=e=>t=>{if(t){re(e);return}ie(e)&&ae().catch(t=>{C.error({err:t,owner:e},`[batch] draining after the batch failed`)})},se=()=>M.isBatchInProgress(),ce=new nnt({projectDir:r,contentDir:n,assertResolutionPath:Ne,branch:k,signal:{signal:e=>O?.signal(e)},io:{gitRaw:async e=>pK(r,{credentialConfig:[],timeoutMs:3e4}).git.raw(e),writeProjectFileUntracked:(e,t)=>{Ne(e),GU(e,t,`utf-8`)},unlinkProjectFileUndeclared:e=>{Ne(e),ZU(e)},deleteResolvedContent:(e,t)=>{ke(t);let n=Get(t);try{ZU(t)}catch(e){throw Ket(n),e}Ge.decrementMdDir(V(e)),bn.current?.deleted(e)},applyResolvedContent:async(e,t,n)=>{ke(t);let r=!G(t);hX(t,cG(n)),await _l(t,n,{fs:Me}),r&&Ge.incrementMdDir(V(e)),Ze.documents.get(e)&&Kn(e,n),ee(e,n),await Ke.recordDiskUpsert(e,n)},readLiveContent:e=>Gn(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`&&Tn(n)){C.debug({docName:n,source:`resolve-delete`,bindingRecreated:!0},`[reconcile] delete skipped: ${n} (binding recreated)`);return}let i=Ze.documents.get(n),a=i?.getMap(`lifecycle`);if(t===`delete`){let e=Pn(n);try{let t=e.residentCurrent()&&i?Fr(n,w?.getLastKnownBranch()??`main`,`delete`,!0):!1;if(e.namespaceCurrent()&&(bn.current?.deleted(n),await Ke.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{Ze.closeConnections(n),await ht(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}I(n),In(n),an(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`));kt(`files`)}}});function le(){for(let e of M.listStaleExternalWrites()){let t=F(e.docName)??e.diskContent;ce.raise({kind:`reconcile`,file:e.file,reason:`stale-external-write`,detectedAt:e.detectedAt,stages:{base:t,ours:e.retainedContent??t,theirs:e.diskContent}})}}le();function ue(e){let t=pl({absPath:bl(`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 de(){let e=pl({absPath:bl(`project-local`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project-local config`)}),t=yie(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=pl({absPath:bl(`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:Die(n.value.autoSync?.default)??`off`,source:`committed-default`}}function fe(){let e=pl({absPath:bl(`project-local`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project-local config`)});return tte(e.value.autoSync)}function pe(){let e=pl({absPath:bl(`project`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules,t=e?Va(e):va;return FNt(r,t.plugins.okf),t}function me(){let e=pl({absPath:bl(`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 he(){return Ept(r,{configHomedirOverride:u,onWarn:e=>C.warn({message:e},`[config] could not read project-local config`)})}function ge(){let e=pl({absPath:bl(`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 _e(){return Ose({cwd:r,homedirOverride:u,warn:e=>C.debug({message:e},`[config] diagnostics read`)})}function ye(e){let t={user:pne,project:ve,"project-local":Rn};for(let n of _e().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 be(e){return`${c4(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function xe(e){return`${e.maxBatchSize}|${e.maxBatchChars}|${e.docTimeoutMs}`}let Se,Ce=0;function we(e,t){let i;if(e===`__config__/project`||e===`__local__/project`){let t=de();i=t.mode,ti?.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=fe();ti?.setIntervals(n.pullIntervalSeconds,n.pushIntervalSeconds)}let a=he();if(ut.applyConfig({enabled:a.enabled,providerFingerprint:be(a),transportFingerprint:xe(a),maxBatchSize:a.maxBatchSize}),e===`__config__/project`){Ce+=1;try{let e=ue({requireValid:!0});Ge?.setAttachmentFolderPath(e),Se!==void 0&&e!==Se&&C.warn({previous:Se,next:e},`[content-filter] attachment folder changed — files under the previous folder no longer sync`),Se=e}catch(e){C.warn({err:e},`[content-filter] project config invalid — keeping previous attachment admission`)}O?.signal(`lint-config`),(t??pe().plugins.okf?.generate?.index===!0)||nNt({projectDir:r,contentDir:n,generatedDocNames:dn(),enabled:!1}).then(e=>{e.ok||C.warn({state:e.status.state},`[index] could not remove Open Knowledge generated-index Git attributes`)}),on()}C.info({docName:e,autoSyncMode:i,semanticEnabled:a.enabled},`[config] applied persisted config to in-process consumers`)}EU();let Te=kc(),Ee=!1,De=!1,Oe=D3e(n,v),ke=e=>{if(Ee)throw new JK(!1);A3e(Oe,e)},Ae=e=>{ke(e),j3e(Oe,e)},Me=E3e(ke);function Ne(e){VY(e,r,{allowShareableOkArtifact:nK});let t=YK(e),n=oG(U(YK(r),t));Oe.kind===`tree`&&!WK({kind:`tree`,path:Oe.path,excluded:[]},t)&&nK(n)||ke(t)}let Pe=qJ(r),Fe=new SXe({localDir:Pe,log:q(`acp-registry`),fetchImpl:e.acpRegistryFetchImpl}),Ie=new mXe(Pe,q(`acp-permissions`)),Le;try{Le=T3e({scope:Oe,projectDir:YK(r),serverInstanceId:Te,registryPath:e.authorityRegistryPath})}catch(e){if(e instanceof RK&&e.existing.projectDir===YK(r)){let t=N4(Pe);if(t?.pid===e.existing.pid)throw new j4(t,H(Pe,`server.lock`))}throw e}Oe=Le.scope;let Re=!1;try{M4(Pe,{port:0,worktreeRoot:r,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),Re=!0,_||aFt({lockDir:Pe,shadowRepoDir:oS(r)})}catch(e){Re&&F4(Pe);try{Le.release()}catch(e){C.error({err:e},`[server] startup authority release failed`)}throw e}let ze=Ln(),Be=qdt(()=>B2(Zr,n)),Ve=Jdt(()=>B2(Zr,n)),He=(e,t)=>{let n=Wut(e);return n===null||!n.includes(`/`)?ze.resolveEmbed(e,t):Ve(n)??null},We=(e,t)=>{let r=He(e,t);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=W(n,r);if(!sG(i,W(n)))return null;try{let e=yc(i);return e.isFile()?e.size:null}catch{return null}},Ge,Ke,qe,Je,Ye,Xe,Ze,Qe,$e,et,tt,nt,rt=null,it=null,at=null,ot=null,st=null,ct=null,lt=he(),ut=new Ppt({loadEmbedder:()=>{let t=he(),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??gpt)(n)},cacheDir:H(qJ(r),`embeddings`),enabled:lt.enabled,providerFingerprint:be(lt),transportFingerprint:xe(lt),maxBatchSize:lt.maxBatchSize}),dt=null,ft=new Map,pt=!1,mt=[],ht,gt,_t,vt,yt=new Promise((e,t)=>{_t=e,vt=t}),bt=!1;yt.then(()=>{bt=!0},()=>{});let xt=e=>W3(e,r,u??wc()),St=()=>!0,Ct=new xNt({projectDir:r,contentDir:n,getShadow:()=>qe?.current,isReady:()=>bt,signal:()=>O?.signal(`sync-status`),isHeld:e=>ne.has(e),isSaveHeld:e=>St(e),resolveFile:e=>{let t;try{if(mU(e))t=M7(e,Ye.configPersistenceCtx);else if(hU(e))t=r6(e,Ye.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:xt(t)}}}),wt=BCt({getShadow:()=>qe?.current,contentRoot:p??``,getBranch:T,writeCheckpoint:e.mergeHistoryWriter,notices:Ct}),Tt=Promise.withResolvers(),Et,Dt=new Promise(e=>{Et=e});async function Ot(){let e,t=Symbol(`branch-scope-gate-timeout`),n=new Promise(n=>{e=setTimeout(()=>n(t),1e4),e.unref?.()});try{if(await Promise.race([Dt,n])!==t)return P()}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 kt(e){O?.signal(e)}let At,jt,Mt,Nt=!1,Pt=!1,It=new AbortController,Lt=new Set,Rt=!1,zt=!1,Bt=!1,Vt=0,Ht,Ut=new Promise(e=>{Ht=e});function Wt(e){Bt||(Bt=!0,Ht(e))}function Gt(){return Rt||Lt.size>0}function Kt(){Pt||!Nt||(At!==void 0&&clearTimeout(At),At=setTimeout(()=>{At=void 0,en()},500),At.unref?.())}function qt(){if(Pt){Wt({status:`cancelled`,indexCount:0});return}Rt=!0,zt=!0,jt=setImmediate(()=>{jt=void 0,en()})}let L,Jt,Yt=!1,Xt=null;async function Zt(){let e=qe.current;if(!e||Yt)return;let t=performance.now();C.info({gitDir:e.gitDir},`[shadow-housekeeping] deferred boot housekeeping started`);try{await t7e(e)}catch(e){C.warn({err:e},`failed to write gc config (non-fatal)`)}if(!Yt){if(Xt)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,Xt,{rebuild:!0})).skipped){n=!0;break}if(r===29)break;if(await new Promise(e=>{setTimeout(e,t).unref?.()}),Yt)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(!Yt){try{await Je?.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 Qt(){Yt||(L=setImmediate(()=>{L=void 0,Jt=Zt().catch(e=>{C.error({err:e},`[shadow-housekeeping] unexpected uncaught failure`)})}))}async function $t(){if(Yt=!0,L!==void 0&&(clearImmediate(L),L=void 0),!Jt)return;let e,t=new Promise(t=>{e=setTimeout(()=>t(`timeout`),m)});try{if(await Promise.race([Jt,t])===`timeout`)throw Error(`shadow housekeeping drain timed out after ${m}ms — abandoning in-flight housekeeping`)}finally{e!==void 0&&clearTimeout(e)}}function en(){if(Pt||!Nt||!Gt())return;if(Mt!==void 0){e.generatedIndexTestHooks?.onKickWhileInFlight?.();return}if(M.isBatchInProgress()){Kt();return}let t=Rt,n=new Set(Lt),r=zt;Rt=!1,Lt.clear(),zt=!1;let i=t?{fullSweep:!0}:{fullSweep:!1,directories:n};Mt=(async()=>{let e=await hn(i,It.signal);if(e.status===`deferred`){Rt=!0,r&&(Vt+=e.indexCount,zt=!0);return}r&&(Vt+=e.indexCount,e.status===`completed`&&Gt()?zt=!0:Wt({...e,indexCount:Vt}))})().catch(e=>{C.warn({err:e},`[index] index regeneration coordinator failed`),r&&Wt({status:`failed`,indexCount:0})}).finally(()=>{if(Mt=void 0,Pt){r&&Wt({status:`cancelled`,indexCount:0});return}Gt()&&At===void 0?Kt():!Gt()&&At===void 0&&e.generatedIndexTestHooks?.onIdle?.()})}async function tn(){if(!Pt){let e=Mt;Pt=!0,It.abort(),At!==void 0&&(clearTimeout(At),At=void 0),jt!==void 0&&(clearImmediate(jt),jt=void 0),Lt.clear(),Rt=!1,zt=!1,e===void 0&&Wt({status:`cancelled`,indexCount:0})}await Mt}function nn(e){Pt||oNt(e)||(Lt.add(J7(e)),Kt())}function rn(e){if(!Pt){for(let t of aNt(e))Lt.add(t);Kt()}}function an(e){let t=Zr?.getFileIndex();if(!t){nn(e);return}let n=J7(e);if(Y7(t.keys()).has(n)){nn(e);return}rn(J7(n))}function on(){Pt||(Rt=!0,Kt())}function sn(e){let t=Zr?.getFileIndex().get(e);if(t)return{title:t.title,description:t.description,type:t.type}}let cn=!1,ln={origin:CIt,writer:d7e,isConflict:e=>ce.has(e),getDocument:e=>Ze.documents.get(e),writeDisk:async(e,t)=>{ke(e),qU(V(e),{recursive:!0}),await _l(e,t,{fs:Me})},registerWrite:(e,t)=>hX(e,cG(t)),noteFileIndex:e=>Zr?.mutateFileIndex({kind:e.kind,path:e.absPath,docName:e.docName,content:e.markdown}),signalFiles:()=>kt(`files`),attribute:async(e,t)=>{c$(e,t.id,t.name,t.id),cn=!0}};function un(e){return e===``?K7:`${e}/${K7}`}function dn(){return[...Zr?Y7(Zr.getFileIndex().keys()):new Set([``])].map(un)}function fn(e){let t=pe().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 pn(){return fn(QMt({projectDir:r,contentDir:n,generatedDocNames:dn()}))}async function mn(e){let t=await nNt({projectDir:r,contentDir:n,generatedDocNames:dn(),enabled:e});if(!t.ok)return{...pn(),applied:!1,reason:t.status.state===`conflict`?`git-conflict`:`git-unavailable`};let i=await Sl({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{...pn(),applied:!1,reason:`config-write`}}try{let e=K(i.path,`utf-8`);await F7(Ze.documents.get(`__config__/project`)??null,ve,e,Ye.configPersistenceCtx)}catch(e){C.warn({err:e},`[index] generated-index settings reflection deferred to config watcher`)}return we(ve,e),ye(ve),{...pn(),applied:!0}}async function hn(t,i){let a=0,o=t.fullSweep?performance.now():void 0,s=()=>pe().plugins.okf?.generate?.index!==!0;try{if(i.aborted)return{status:`cancelled`,indexCount:0};if(s())return{status:`disabled`,indexCount:0};let c=Zr?.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=uNt({docs:c,docExtension:UH,currentMarkdownFor:()=>null,warningScope:D}),l=QMt({projectDir:r,contentDir:n,generatedDocNames:o.map(({directory:e})=>un(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=un(r),l=W(n,`${o}.md`);ke(l);let u;try{u=K(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&C.warn({err:e,path:FU(l)},`[index] could not read the existing generated index; treating it as absent`),u=null}a+=1;let d=await HMt({docName:o,absPath:l,markdown:c,currentMarkdown:u},ln);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&&rn(J7(r))}}finally{cn&&=(await Ye.waitForPendingCommits(),await Ye.flushContributors(),!1),o!==void 0&&(r4(`generatedIndexSweepMs`,Math.round((performance.now()-o)*100)/100),Wft(`generatedIndexCount`,a))}return{status:`completed`,indexCount:a}}catch(e){return C.warn({err:e},`[index] index regeneration failed`),{status:`failed`,indexCount:a}}}let gn=null,_n=!1,vn=()=>{try{QPt(r,yn.entries())}catch(e){C.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},yn=new UPt(void 0,{onEviction:()=>HQe(),onSizeChange:e=>UQe(e),onMutate:()=>{!_n||gn!==null||(gn=setTimeout(()=>{gn=null,vn()},2e3))}});for(let[e,t]of ZPt(r))yU(e)||o5(e)&&([`.md`,`.mdx`].some(t=>{let r=W(n,`${e}${t}`);return sG(r,W(n))&&G(r)})||yn.restore(e,t));_n=!0;let bn={current:null},xn=new WeakMap,Sn=new Map,Cn=W(n);function wn(e){if(!o5(e))return null;let t=KH(e),n=W(Cn,t);return sG(n,Cn)?n:null}function Tn(e){let t=Zr?.getFileIndex().get(e)?.canonicalPath??wn(e);return t!==null&&KX(e,t,n,Ge)}function En(e){let t=xn.get(e);return t||(t={source:e.getText(`source`).toString(),mutation:void 0,adoption:void 0,pendingRetirement:!1},xn.set(e,t)),t}function Dn(e){for(let t of Sn.get(e)??[])t.namespaceAllowed=!1}function On(e,t){if(De||e.isDestroyed||Ze.documents.get(t)!==e)return;let n=En(e);n.pendingRetirement=!1,n.adoption={};for(let e of Sn.get(t)??[])e.namespaceAllowed=!1,e.residentAllowed=!1}function kn(e){xn.set(e,{source:e.getText(`source`).toString(),mutation:void 0,adoption:void 0,pendingRetirement:!0})}function An(e){if(De)return;Dn(e);let t=Ze.documents.get(e);t&&kn(t),bn.current?.deleted(e)}function jn(e){let t=Ze.documents.get(e),n=t?En(t):void 0,r=n?.adoption;return()=>{De||(Dn(e),t&&Ze.documents.get(e)===t&&xn.get(t)===n&&n?.adoption===r&&kn(t))}}function Mn(e,t){let n=xn.get(e)?.mutation;if(n)return()=>{xn.get(e)===n.occurrence&&On(e,t)}}function Nn(e,t){Tn(e)&&On(t,e)}function Pn(e,t){let n=Ze.documents.get(e),r=()=>(t?.()??!0)&&!Tn(e),i=!De&&r(),a={namespaceAllowed:i,residentAllowed:!De&&n!==void 0&&(i||En(n).pendingRetirement)},o=Sn.get(e)??new Set;return De||(o.add(a),Sn.set(e,o)),{document:n,namespaceCurrent:()=>(a.namespaceAllowed&&!r()&&(a.namespaceAllowed=!1),a.namespaceAllowed),residentCurrent:()=>(a.residentAllowed&&(n===void 0||n.isDestroyed||Ze.documents.get(e)!==n)&&(a.residentAllowed=!1),a.residentAllowed),dispose:()=>{a.namespaceAllowed=!1,a.residentAllowed=!1,o.delete(a),o.size===0&&Sn.delete(e)}}}let Fn=(e,t)=>{yU(e)||yn.setRenamed(e,t)},In=e=>{if(!yU(e)){if(yn.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}yn.setDeleted(e)}},zn=e=>{yU(e)||yn.delete(e)};try{let m=`./`;try{m=ue()}catch(e){C.warn({err:e},`[content-filter] invalid attachment folder at boot — using sibling admission`)}Se=m,Ge=cK({projectDir:r,contentDir:n,isContentScopeExcluded:e=>{if(Oe.kind!==`tree`)return!1;try{let t=YK(e);return Oe.excluded.some(e=>WK({kind:`tree`,path:e,excluded:[]},t))}catch(t){let n=aG(t);if(!(t instanceof CK)&&n!==`EACCES`&&n!==`EPERM`)throw t;return C.warn({path:FU(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=>xct(n,e),skillRootPaths:vct(n),onAfterRebuild:()=>{Ke.refreshContentScope().catch(e=>{q(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),Ytt(Zr).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`)})}}),Ke=new xft({projectDir:r,contentDir:n,contentFilter:Ge,getGlobalSkillRoots:()=>Qgt(Ye.managedArtifactCtx),signalChannel:kt,getLocalTargetInventory:()=>B2(Zr,b),onRecoveredFileTarget:(e,t)=>{Zr&&GPt({watcher:Zr,contentDir:n,relativePath:e,exists:t,invalidateReferencedAssetsCache:st})}}),qe={current:f},Je=s?oPt({getShadow:()=>qe.current??null,getCurrentBranch:T,contentRoot:p??``,projectGitDir:aS(r)??void 0,isWriterLive:e=>{if(!ot&&!Qe)return q(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(ot?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of Qe?.sessionsForConnection(t)??[])return!0;return!1}}):void 0;let _=null;Ye=zPt({contentDir:n,assertContentPath:ke,projectDir:r,conflicts:ce,lifecycleOf:(e,t)=>ce.lifecycleOf(e,t),gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:qe,ephemeral:y,contentRoot:p,derivedDocumentIndex:Ke,configHomedirOverride:u,getCurrentBranch:T,resolveEmbed:He,resolveSize:We,getPrincipal:()=>dt,onAgentCommit:()=>O?.signal(`session-activity`),onFlushCommit:()=>Je?.noteFlushCommit(),capturePublicationReceipt:Mn,onDiskFlush:(e,t,n,r)=>{O?.emitDiskAck(e,t),!yU(e)&&(dNt(r,n,e)&&nn(e),hmt(r,n)&&(st?.(),kt(`files`)))},onConfigRejected:(e,t)=>O?.emitConfigValidationRejected(e,t),onConfigPersisted:e=>{we(e),ye(e)},onManagedSkillPersisted:e=>{let t=N(e);t?.kind===`skill`&&t.scope===`global`&&(_!==null&&clearTimeout(_),_=setTimeout(()=>{_=null;let e=u??wc();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=>yn.has(e),mdManager:e.mdManager,getLossRing:()=>Xe,mergeHistory:wt,ingestDiskAtStore:async(e,t,n)=>{let r;try{r=await Ur({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 Br(r)}},durabilityState:M}),St=e=>Ye.hasHeldSave(e),Ze=new QJe({quiet:i,debounce:a,maxDebounce:o,extensions:[Ye.extension]});let w=Ze.hooks.bind(Ze);Ze.hooks=(e,t,n)=>{if((e===`afterLoadDocument`||e===`onChange`)&&`document`in t&&!yU(t.document.name)){let n=t.document,r=En(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&&!yU(t.documentName)&&Nn(t.documentName,t.connection.document),w(e,t,n)};let D=Ze.openDirectConnection.bind(Ze);function k(e){if(De)throw new JK(!1);if(yU(e)){if(v!==void 0&&e!==`__system__`&&!mU(e))throw new qK;return}if(v!==void 0&&GH(e)!==GH(zH(v)))throw new qK;if(Ee)throw new JK(!1);k3e(Oe,HG(e,n))}Ze.openDirectConnection=(async(e,t)=>{let n=GH(e);return k(n),D(n,t)});let A=Ze;mt.push(hrt(()=>A.documents.size),grt(()=>Ye.getQueueDepths()),vrt(()=>{let e=0;for(let t of A.documents.values())e+=t.directConnectionsCount;return{websocket:A.getConnectionsCount()-e,direct:e}})),brt(),y||(ct=BPt({getLoadedDocuments:()=>A.documents,lifecycleOf:(e,t)=>ce.lifecycleOf(e,t),forceStore:(e,t)=>Ye.forceStore(e,t),isHeldSaveDue:e=>Ye.isHeldSaveDue(e),retryHeldSave:(e,t)=>Ye.retryHeldSave(e,t),getBase:e=>M.getReconciledBase(e),isBatchActive:()=>M.isBatchInProgress(),hasInFlight:e=>M.inFlightFlushCount(e)>0,readDiskBytes:e=>{let t=HG(e,n),r,i;try{r=hc(t),i=yc(r).size}catch(t){let n=aG(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new _9(`symlink cycle at content path: ${e}`):t}if(DK(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(aG(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs})),gt=Ze.shouldUnloadDocument.bind(Ze),Ze.shouldUnloadDocument=e=>{let t=ft.get(e);if(t)return[...t].some(e=>e());if(pt&&!yU(e.name)&&M.isStoreRefused(e.name))return!1;if(pt&&gt(e))return!0;let n=e.name;return yU(n)||F(n)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:gt(e)},ht=async(e,t)=>{let n=()=>Ze.documents.get(e.name)===e&&(t?.()??!0),r=ft.get(e)??new Set;r.add(n),ft.set(e,r);try{await Ze.unloadDocument(e)}finally{r.delete(n),r.size===0&&ft.delete(e)}},O=new v$e(Ze),at=new A8e(Ze),ot=new M8e(Ze),Qe=new oit(Ze,{...e.agentSessionOptions,assertDocumentScope:k,awaitWriteAdmission:()=>M.whenWriteAdmitted()});let j=Qe;mt.push(yrt(()=>({active:j.liveSessionCount,limit:j.sessionLimit})));let P=VNt({derivedDocumentIndex:Ke,onDocumentSettled:e=>bn.current?.changed(e)});Ze.configuration.extensions.push(P);function ee(e,t,n={}){C.warn({reason:e,docName:t,...n},`[auth-rejection] ${e}`)}Ze.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!==Te)throw ee(`server-instance-mismatch`,e.documentName,{claimedServerInstanceId:r,currentServerInstanceId:Te}),new d5(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${Te}`);let i=n?.expectedBranch;if(typeof i==`string`&&i.length>0){let t=await Ot();if(t!==null&&i!==t)throw ee(`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`&&(dt&&n.principalId===dt.id?a.principalId=dt.id:dt?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:dt.id})):a.principalId=n.principalId),typeof n.tabSessionId==`string`&&(a.tabSessionId=n.tabSessionId),a.kind=`human`}}),Ze.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!mU(e.documentName)&&!hU(e.documentName))return;let n=e.request,r=n.socket?.remoteAddress;if(r!==void 0&&!VQ(r,t))throw ee(`config-doc-admission-denied`,e.documentName,{check:`peer`}),Error(`config-doc admission requires loopback peer (peer=${r}, doc=${e.documentName})`);let i=e.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0;if(!HQ(a,t))throw ee(`config-doc-admission-denied`,e.documentName,{check:`host`}),Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${e.documentName})`)}}),Ze.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){if(!yU(e.documentName)){let t=wn(e.documentName);if(t!==null&&!G(t))try{await Promise.race([Tt.promise,yt])}catch(t){throw C.error({err:t,docName:e.documentName},`[removal-guard] missing-document admission refused after startup failure`),t}}await qPt(e.documentName,{recentlyRemovedDocs:yn,resolveFilePath:wn,fileExists:G})}}),Ze.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=f5(e.token);pNt(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Ze.documents.get(e)})}}),Ze.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new JV(e.update);if(t.readVarString(),t.readVarUint()===eH.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${Ue} rejected — server-only channel`)}}),Ze.configuration.extensions.push({async afterUnloadDocument({documentName:e}){M.endRenameCarry(e)}});let I=lTt({mergeHistoryWriter:e.mergeHistoryWriter,docNotices:Ct,declaredGitHubHosts:x,resolveSyncCredentialConfig:S,hocuspocus:Ze,durabilityState:M,ingressPolicy:t,sessionManager:Qe,commentDocHooksRef:bn,onNamespaceCreateAccepted:An,capturePublicationReceipt:Mn,captureNamespaceMove:jn,onResidentAdopted:On,contentDir:n,assertContentPath:ke,assertContentSubtree:Ae,getGeneratedIndexSettingsStatus:pn,setGeneratedIndexEnabled:mn,contentFilter:Ge,serverInstanceId:Te,getFileIndex:()=>Zr?Zr.getFileIndex():new Map,getAttachmentFolderPath:ue,getAllFilesIndex:()=>Zr?Zr.getAllFilesIndex():new Map,getFileIndexGeneration:()=>Zr?.getFileIndexGeneration()??0,mutateFileIndex:e=>{let t=e.kind===`update`?sn(e.docName):void 0;switch(Zr?.mutateFileIndex(e),e.kind){case`update`:fNt(t,e.content,e.docName)&&nn(e.docName);break;case`create`:qn(e.docName,e.content),nn(e.docName);break;case`conflict`:nn(e.docName);break;case`delete`:bn.current?.deleted(e.docName),an(e.docName);break;case`rename`:an(e.oldDocName),nn(e.newDocName);break;case`folder-create`:case`folder-delete`:rn(e.relativePath);break;case`asset-create`:case`asset-delete`:case`file-create`:case`file-update`:case`file-delete`:break;default:cX(e)}},getFolderIndex:()=>Zr?Zr.getFolderIndex():new Map,getAliasMap:()=>Zr?Zr.getAliasMap():new Map,getFolderAliasIndex:()=>Zr?Zr.getFolderAliasIndex():new Map,resolveTrackedFile:Be,rescanFiles:()=>Zr?.rescanFromDisk(),settleDiskEventsForTest:async()=>{await Zr?.settle()},enableTestRoutes:d,shadowRef:qe,flushGitCommit:()=>Ye.flushPendingGitCommit(),flushContributors:()=>Ye.flushContributors(),getCurrentBranch:T,getReportedBranch:E,getDiskAckSVs:()=>O?.getLatestDiskAckSVsAsBase64()??{},getCollabClientCount:e.getCollabClientCount,contentRoot:p,derivedDocumentIndex:Ke,signalChannel:kt,agentFocusBroadcaster:at,agentPresenceBroadcaster:ot,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>ti,conflicts:ce,setBatchInProgress:oe(`conflict-resolve`),refreshDocumentsFromDisk:ei,localOpCliArgs:h,authStreamHeartbeatMs:g,projectDir:r,resolveEmbed:He,getBridgeLossReporter:()=>nt,getPrincipal:()=>dt,agentIntegrations:e.agentIntegrations,acpRegistry:Fe,loadAcpCustomAgents:()=>xH(Pe,q(`acp-registry`)),homeDirOverride:u,resetSettingsForTest:u===void 0?void 0:()=>{for(let e of Vr)bMt(Ze.documents.get(e)??null,e,Ye.configPersistenceCtx),Un.get(e)?.(),we(e)},forceUnloadDocument:ht,ready:yt,recentlyRemovedDocs:yn,serializeDoc:Gn,evictManagedArtifactLkg:e=>{Ye.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:ut,getSemanticSimilarityFloor:()=>he().similarityFloor,getLinterBaseConfig:()=>pe(),getLinkAdvisoryPolicy:me,getProjectConfigEpoch:()=>Ce,getLinkPreviewsEnabled:ge,resolveGitHubToken:Zxt(e.detectGh,e.tokenStore),getConfigDiagnostics:_e,embeddingsSecretsFile:bpt(u),readSemanticProviderConfig:he,ephemeral:y,onReferencedAssetsCacheInvalidator:e=>{st=e}});Ze.configuration.extensions.push(I),Ze.configuration.extensions.push(wNt({clock:e.watcherClock??nX(),refresh:ei})),$e=I.nativeApi,et=I.localApi,tt=I.shutdownLocalOps;let te=pl({absPath:bl(`project`,r),sideline:!1,warn:e=>C.warn({message:e},`[config] could not read project config for bridge guards`)}),ne=te.value.bridge.deferGuard.enabled,re=te.value.bridge.fixedPoint.enabled,ie=te.value.bridge.preDrain.enabled;Xe=te.value.lossCapture.enabled?new H8e({projectDir:r,maxBytes:te.value.lossCapture.maxBytes}):void 0,te.value.bridge.lossDetector.enabled&&(nt=E7e({shadow:()=>qe.current,ring:Xe,getBranch:()=>T()??`main`,contentRoot:p??``}),Qe.attachBridgeLossReporter(nt)),Ze.configuration.extensions.push($Pt({mdManager:$a,schema:ka,shadowRef:qe,contentRoot:p,getCurrentBranch:T,resolveEmbed:He,resolveSize:We,deferGuardEnabled:ne,lossDetectorEnabled:te.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:re,preDrainEnabled:ie,lossRing:Xe})),Ze.configuration.extensions.push(uIt()),Ze.configuration.extensions.push({async afterLoadDocument({document:e}){Qtt(e,ce)}})}catch(e){for(let e of mt.splice(0))e();ct?.dispose(),ct=null,Ee=!0,F4(Pe);try{Le.release()}catch(e){C.error({err:e},`[server] construction authority release failed`)}throw e}let Bn=null,Vn=new Map,Hn=[],Un=new Map;function Wn(e,t){let n=W(e,`rescue`),r=KH(t),i=W(n,r);return sG(i,n)?i:null}function Gn(e){let t=Ze.documents.get(e);return t?w$(t):null}let Kn=(e,t)=>{let n=Ze.documents.get(e);m$(M,Ze,e,t,He,We,nt),n&&Tn(e)&&On(n,e)},qn=(e,t)=>{let n=Cat(M,Ze,e,t,He,We,nt),r=Ze.documents.get(e);return n===`revived`&&r&&Tn(e)&&On(r,e),n},Jn=(e,t)=>{let n=0;for(let[r]of Ze.documents){if(yU(r))continue;let i=Ze.documents.get(r);if(!i)continue;let a=i.getText(`source`).toString();if(a.includes(e))try{i.transact(()=>{d$(i,a,He,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},Yn=e=>{e&&Jn(`[[${e}]]`,{reason:`asset-event`,assetBasename:e})},Xn=()=>{try{let e=Jn(`![[`,{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`)}},Zn=null,Qn=e=>{e&&(Zn===null&&(Zn=new Set,setImmediate(()=>{let e=Zn;if(Zn=null,e)try{for(let t of e)Yn(t)}catch(t){C.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Zn.add(e))};function $n(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 er={delete:`external-change-rescue`,rename:`external-change-rescue`,"branch-switch":`external-change-rescue`,"disk-update":`external-change-rescue-disk-update`},tr=(e,t,n,r,i=``,a=!1)=>{if(!qe.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}`),YH(),!1}let o=qe.current;return queueMicrotask(()=>{VJ(o,p??``,{kind:er[r],docName:e,contents:t,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:i}}).then(()=>{mZe(),C.info({docName:e,site:r},`[reconcile] rescue checkpoint saved (${r}): ${e}`)}).catch(t=>{hZe();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},nr=new WeakSet,rr=e.watcherClock??nX(),ir=null,ar=!1,or=e=>{ne.hold(e),M.holdStores(e.docName)},sr=new Set,cr=new Map,R=e=>{ne.release(e),cr.delete(e),sr.delete(e),M.releaseStores(e)},lr=null,ur=0;function dr(){ur+=1,rr.clearTimeout(lr),lr=null}function fr(e){dr(),pr(e,ur,1).catch(t=>{C.error({err:t,branch:e},`[branch-switch] the follow-up re-checks stopped`)})}async function pr(e,t,n){if(!Zr||t!==ur)return;let r;try{r=await Zr.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!==ur||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}o$e();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 ${xIt/1e3} s`),lr=rr.setTimeout(()=>{lr=null,pr(e,t,n+1).catch(t=>{C.error({err:t,branch:e},`[branch-switch] the follow-up re-checks stopped`)})},xIt),lr.unref()}let mr=()=>{ir||ar||ne.size===0||(ir=rr.setTimeout(()=>{ir=null,hr().catch(e=>{C.error({err:e},`[reconcile] the re-check loop for vanished documents failed`)})},1e3),ir.unref())};async function hr(){if(!Zr)return;ar=!0;let e;try{e=await Zr.recheck(`metadata`)}catch(e){C.warn({err:e},`[reconcile] the re-check for vanished documents failed`)}finally{ar=!1}try{ne.size>0&&(e?.status!==`completed`||e.partial)&&C.info({status:e?.status??`failed`,partial:e?.partial===!0},`[reconcile] the re-check for ${ne.size} vanished document(s) did not observe the whole tree; trying again`),await Or()}finally{mr()}}function gr(e){try{return lc(e),!0}catch(t){let n=aG(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 _r(e,t){let r=e=>{let t=aG(e);return t===`ENOENT`||t===`ENOTDIR`?{kind:`absent`}:{kind:`unreadable`,code:t??`unknown`}};try{lc(t),aae(t,ac.R_OK)}catch(e){let t=r(e);if(t.kind===`absent`||aG(e)!==`ELOOP`)return t}if(!KX(e,t,n,Ge))return{kind:`refused`};try{return{kind:`present`,path:t,content:K(t,`utf-8`)}}catch(e){return r(e)}}function vr(e){let t=Zr?.getFileIndex().get(e.docName)?.canonicalPath??wn(e.docName)??e.path;return _r(e.docName,t)}async function yr(e){if(!Zr||gr(e.path))return!1;let t=ott(e),n=F(e.docName),r=new Set;t.lastHash!==void 0&&r.add(t.lastHash),n!==void 0&&r.add(cG(n));let i={docName:e.docName,path:e.path,identity:t.identity,size:t.size,modified:t.modified,hashes:r,text:n??Gn(e.docName)??void 0},a=ne.matchRecentCreate(i,rr.now(),e=>{let t=_r(e.docName,e.path);return t.kind===`present`?t.content:void 0});if(a){let t=_r(a.create.docName,a.create.path);if(t.kind===`present`)return uU(a.by===`identity`?`paired-identity`:`paired-hash`),await Gr({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 or({...i,afterPass:Zr.recoveryPassesStarted(),heldAt:rr.now()}),uU(`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`),mr(),!0}let br=()=>{se()||Ye.flushDeferredStores(`within-branch`).catch(e=>{C.error({err:e},`[persistence] deferred store drain failed after a vanished file resolved`)})};async function xr(e,t){R(e.docName);try{uU(`recreated`),C.info({docName:e.docName},`[reconcile] ${e.docName}: its file is back; taking it in as an update`),await qr({kind:`update`,path:t.path,docName:e.docName,content:t.content})}finally{br()}}async function Sr(e,t){Ye.discardDeferredStore(e.docName,{kind:`deleted-outside`}),R(e.docName),uU(t);let n={kind:`delete`,path:e.path,docName:e.docName};nr.add(n),await qr(n)}function Cr(e,t){sr.has(e.docName)||(sr.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 wr(e,t,n,r){let i=ne.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 Tr(e,t){R(e.docName),br(),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 Er(e,t){if(t)for(let t of ne.dueAfter(e)){let e={action:`checking its path`};try{await Dr(t,e)}catch(n){wr(t,e,n)}}}async function Dr(e,t){let n=vr(e);switch(n.kind){case`present`:t.action=`taking its returned file in`,await xr(e,n);return;case`unreadable`:Cr(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 Sr(e,`deleted`);return;default:throw Error(`unhandled file probe: ${JSON.stringify(n)}`)}}async function Or(){for(let e of ne.heldBefore(rr.now()-F9)){let t={action:`resolving its hold at the limit`};try{await kr(e,t)}catch(n){if(!ne.has(e.docName)){wr(e,t,n);continue}let r=(cr.get(e.docName)??0)+1;cr.set(e.docName,r),wr(e,t,n,r),r>=3&&Tr(e,r)}}}async function kr(e,t){let n=`${F9/1e3} s`,r;try{r=vr(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 xr(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 Sr(e,`unconfirmed`)}function Ar(e,t,n){let r=T()??`main`,i={from:e,to:t,toFile:`${t}${Js(n)}`},a={writerId:PJ.id,displayName:PJ.name,colorSeed:PJ.id};P8({moves:[i],kind:`file`,branch:r,writer:a,shadow:void 0,notices:Ct});let o=qe.current;o&&Mr(o,r,i,a)}async function jr(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 Mr(e,t,n,r){let i=await jr(e,t),a;try{a=P8({moves:[n],kind:`file`,branch:t,writer:r,shadow:e,notices:void 0,anchors:i})}catch(e){i$e(),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 Ye.flushContributors()}catch(e){o=e}let s=N$(e.gitDir).byTo.get(n.to);if(s!==void 0&&s.commitSha===``){a$e(),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 Nr(e,t,n,r,i){let a;try{return a=await Ze.openDirectConnection(e),Kn(e,r),ee(e,n),i!==n&&await Gr({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 Pr(e){for(let[t,r]of Ze.documents)if(!yU(t)&&r.getMap(`lifecycle`).get(`status`)===void 0)try{let i=HG(t,n);if(!G(i)||!DK(i,hc(i),n))continue;Fr(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 Fr=(e,t,n,r=!1)=>{let i=F(e),a=Gn(e)??``,o=i===void 0?a!==``:a!==i;return o&&(tr(e,a,t,n,``,r),o)};function Ir(e){ce.dissolveReconcile(e),ce.dissolveWorkingTree(ce.fileOf(e))}let Lr=(e,t,n,r)=>{(t.kind===`merged`||t.kind===`both-kept`)&&t.dedupSkipped&&(eZe(),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`))},Rr=async(e,t,n)=>{let r=n===void 0;NQe();let i=Gn(e)??``,a=T()??`main`,o=cG(t).slice(0,6),s=i!==``&&i!==t,c=s?si(e,`disk-authoritative-ingest`):`not-needed`;s&&tr(e,i,a,`disk-update`,o,!0);let l=cG(i).slice(0,6),u=r?`absent`:`blockless`,d,f=!1;try{Kn(e,t),Ir(e),f=!0}catch(s){d=s,PQe(),C.error({err:s,docName:e},`[reconcile] failed to apply disk-authoritative ingest to Y.Doc for ${e}`),tr(e,t,a,`disk-update`,o,!0),Ir(e);let f;try{f=Gn(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?ee(e,t):M.restoreReconciledBase(e,n),c===`lost`&&f!==i&&(FQe(),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`&&FQe(),(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 zr(e,t),s?{kind:`applied`,merge:`disk-replaced`}:{kind:`applied`}}return{kind:`failed`,error:d}},zr=async(e,t)=>{try{await Ke.recordDiskUpsert(e,t)}catch(t){C.warn({err:t,docName:e},`[reconcile] ${e}: the derived index could not record the disk version`)}};function Br(e){throw Error(`unhandled disk intake outcome: ${e.kind}`)}function Hr(e){throw Error(`unhandled reconcile outcome: ${e.kind}`)}async function Ur(e){let{docName:t,content:n}=e;if(zn(t),fNt(e.previousIndexedFields,n,t)&&nn(t),ce.findByDocName(t)?.kind===`merge-native`)try{await ce.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e,docName:t},`[reconcile] conflict prune against git failed`)}let r=Ze.documents.get(t);if(!r)return b$(M,void 0,t,n,ce)||M.refreshReceiptWithoutBase(t,n),await Ke.recordDiskUpsert(t,n),{kind:`nothing-to-take`};if(qn(t,n)!==`not-frozen`)return await Ke.recordDiskUpsert(t,n),{kind:`nothing-to-take`};let i=cG(n),a=Kgt({receiptHash:M.getReceipt(t)?.hash,eventHash:i,isRecentOwnWrite:M.isRecentOwnWrite(t,i),readDiskHash:()=>{try{return cG(K(e.path,`utf-8`))}catch{return null}}}),o=qgt(a);if(o!==null&&M.getStaleExternalWrite(t)===void 0)return dQe(o),C.debug({docName:t,receiptIntake:a},`[reconcile] ${t}: the disk bytes match its receipt (${a}); nothing to take in`),ce.dissolveReconcile(t),await zr(t,n),{kind:`nothing-to-take`};let s=F(t),c=Gn(t)??s??``;if(b$(M,r,t,n,ce,c))return await zr(t,n),{kind:`conflict`};if(s===void 0)return Rr(t,n,void 0);let l=cY({docName:t,base:s,ours:c,theirs:n}),u=cG(s).slice(0,6),d=cG(c).slice(0,6),f=cG(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}${_}`),Lr(t,l,c,n),l.kind){case`noop`:return ce.dissolveReconcile(t),await zr(t,n),{kind:`nothing-to-take`};case`clean`:try{Kn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),ee(t,s),ce.dissolveReconcile(t),{kind:`failed`,error:e}}return ee(t,l.newContent),JH(),ce.dissolveReconcile(t),await zr(t,n),{kind:`applied`,merge:`clean`};case`merged`:try{Kn(t,l.newContent)}catch(e){return C.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),ee(t,s),ce.dissolveReconcile(t),{kind:`failed`,error:e}}return ee(t,n),JH(),ce.dissolveReconcile(t),await zr(t,n),{kind:`applied`,merge:`merged`};case`both-kept`:try{Kn(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`),ee(t,s),$Xe(),ce.raise({kind:`reconcile`,file:ce.fileOf(t),reason:`merged-with-markers`,stages:{base:s,ours:c,theirs:n}}),{kind:`failed`,error:e}}return wt.bothKept(t,{ours:c,theirs:n},l.kept),ee(t,n),JH(),v$(t,l.kept,`watcher`),ce.dissolveReconcile(t),await zr(t,n),{kind:`applied`,merge:`both-kept`};case`refused`:return l.reason===`no-base`?Rr(t,n,s):(_$(t,l,`watcher`),(l.reason===`check-failed`||l.reason===`too-large`)&&await wt.keptLive(t,{side:`theirs`,bytes:n},l.reason)?(ee(t,n),y$(t,l.reason,`watcher`),ce.dissolveReconcile(t),await zr(t,n),{kind:`applied`,merge:`kept-live`}):($Xe(),ce.raise({kind:`reconcile`,file:ce.fileOf(t),reason:Tat(l.reason),stages:{base:s,ours:c,theirs:n}}),{kind:`conflict`}));default:return Hr(l)}}let Wr=new Map;async function Gr(e,t=e.kind===`delete`||e.kind===`rename`?Wr.get(e)??Pn(e.kind===`delete`?e.docName:e.oldDocName,GX(e)):void 0){try{switch(e.kind){case`create`:{let t=ott(e),n=cG(e.content),r=ne.matchCreate({docName:e.docName,identity:t.identity,size:t.size,modified:t.modified,hash:n,content:e.content});if(r){if(R(r.vanished.docName),r.by===`same-name`){uU(`recreated`),C.info({docName:e.docName},`[reconcile] ${e.docName}: its file came back; taking it in as an update`),await Gr({kind:`update`,path:e.path,docName:e.docName,content:e.content}),br();break}let t=M.beginRenameCarry(r.vanished.docName);try{Ye.discardDeferredStore(r.vanished.docName,{kind:`renamed-outside`,to:e.docName,carry:t}),uU(r.by===`identity`?`paired-identity`:`paired-hash`),await Gr({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}ne.rememberCreate({docName:e.docName,path:e.path,identity:t.identity,size:t.size,modified:t.modified,hash:n,at:rr.now()}),C.info({docName:e.docName},`[reconcile] create: ${e.docName}`),qn(e.docName,e.content),await Ke.recordDiskUpsert(e.docName,e.content),kt(`files`),nn(e.docName),zn(e.docName);break}case`update`:await Ur(e);break;case`delete`:{let{docName:n}=e,r=t??Pn(n,GX(e));Wr.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&&!nr.has(e)&&await yr(e))return;t&&(Ir(n),bn.current?.deleted(n));let{document:a}=r,o=i&&a?Fr(n,T()??`main`,`delete`,!0):!1;if(i&&(a?.getMap(`lifecycle`).set(`status`,`deleted-upstream`),M.endRenameCarry(n)),t&&I(n),t&&await Ke.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&&(Ze.closeConnections(n),await ht(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}kt(`files`),In(n),an(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??Pn(n,GX(e));Wr.delete(e),M.beginRenameCarry(n);let o=null,s=!1;try{let t=a.document,c=a.residentCurrent()&&t?t:null,l=c?Gn(n):null,u=c?dG(c):null,d=F(n),f=e=>{let t=e.getMap(`lifecycle`);t.set(`status`,`renamed`),t.set(`newPath`,r)},p=a.residentCurrent()&&t?Fr(n,T()??`main`,`rename`):!1;a.residentCurrent()&&t&&f(t),a.namespaceCurrent()&&(Ir(n),I(n),Ye.forgetObservedFile(n),Fn(n,r)),ee(r,i),C.info({oldDocName:n,newDocName:r,isDirty:p},`[reconcile] rename: ${n} → ${r} (dirty=${p})`),kt(`files`),zn(r);try{a.namespaceCurrent()?await Ke.recordDiskRename(n,r,i):await Ke.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()?Ze.documents.get(n):void 0,h=m===t?void 0:m;h&&f(h),qn(r,i),nn(r),a.namespaceCurrent()&&Ar(n,r,e.newPath),l!==null&&d!==void 0&&(l===d||await Nr(r,e.newPath,d,l,i))&&(o=u);let g=a.residentCurrent()&&t?t:h;if(s=!!g,g){let e=g.getConnectionsCount();Ze.closeConnections(n),await Qe.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`})),an(n)}finally{M.settleRenameCarry(n,o),s||M.endRenameCarry(n),a.dispose()}break}case`conflict`:{let{docName:t}=e;if(!Ze.documents.get(t))return;let n=F(t)??``,r=Gn(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`):ee(t,r),ce.raise({kind:`reconcile`,file:ce.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`:ze.add(e.relativePath),kt(`files`),Qn(Ks(e.relativePath));break;case`asset-delete`:ze.remove(e.relativePath),kt(`files`),Qn(Ks(e.relativePath));break;case`folder-create`:case`folder-delete`:kt(`files`),rn(e.relativePath);break;case`file-create`:case`file-update`:await Ke.recordFileTargetUpsert(e.relativePath),st?.(),kt(`files`),await $r(e.relativePath);break;case`file-delete`:await Ke.recordFileTargetDelete(e.relativePath),st?.(),kt(`files`);break;default:cX(e)}}catch(t){let n=$n(e);C.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let Kr=[];async function qr(e){if(!De){if((e.kind===`delete`||e.kind===`rename`)&&!Wr.has(e)&&Wr.set(e,Pn(e.kind===`delete`?e.docName:e.oldDocName,GX(e))),se()||Jr!==null){Kr.push(e);return}await Gr(e)}}let Jr=null;function Yr(){if(Jr)return Jr;if(Kr.length===0)return Promise.resolve();let e=Promise.withResolvers();return Jr=e.promise,(async()=>{try{for(;Kr.length>0;){let e=Kr.splice(0,Kr.length);for(let t of e)await Gr(t)}e.resolve()}catch(t){e.reject(t)}finally{Jr=null}})(),e.promise}function Xr(){for(let e of Wr.values())e.dispose();Wr.clear()}let Zr=null;function Qr(e){return gU(e)||_U(e)||vU(e)}async function $r(e){if(!Qr(e))return!1;let t=Ze.documents.get(e);return t?await gPt(t,e,Ye.mermaidPersistenceCtx)!==`unchanged`:!1}async function ei(e,t){if(!Zr)return{checked:0,found:0};let r=Zr.getAliasMap(),i=Zr.getFileIndex(),a=[],o={checked:0,found:0};for(let s of new Set(e)){let e=r.get(s)??s;if(yU(e))continue;if(Qr(e)){o.checked++,await $r(e)&&o.found++;continue}let c=i.get(e)?.canonicalPath;if(c!==void 0){a.push(c);continue}try{a.push(HG(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 Zr.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 ti=null,ni=null,ri=!1,ii=null;function ai(e,t){let n=ii;if(n===null||n.authorityGateReached){C.error({err:t,watched:e},`[server] late watcher release failed after shutdown`);return}n.phaseErrors.push({phase:`watcher-unsubscribe`,error:t instanceof Error?t.message:String(t)}),C.error({err:t,watched:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}async function oi(e,t,n){if(ri)return;let r=await e();if(ri){try{await r.unsubscribe()}catch(e){ai(n,e)}return}t(r)}let si=(e,t)=>{let n=qe.current;if(!n)return C.warn({docName:e,context:t},`[rescue] shadow repo unavailable — cannot buffer ${e} (${t})`),YH(),`lost`;try{let r=xU(e)?Ze.documents.get(e)?.getText(`source`).toString()??null:Gn(e);if(r===null)return C.warn({docName:e,context:t},`[rescue] skipping ${e} — document dropped from map mid-rescue (${t})`),YH(),`lost`;let i=Wn(n.gitDir,e);return i?(qU(V(i),{recursive:!0}),GU(i,r,`utf-8`),mZe(),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})`),YH(),`lost`)}catch(n){return C.error({err:n,docName:e,context:t},`[rescue] failed to write rescue buffer for ${e} (${t})`),YH(),`lost`}};async function ci(e){if(Ze.documents.size===0)return;let t=!1,n=Date.now()+e,r,i=Promise.withResolvers(),a=bIt(Ze,()=>{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())}};Ze.configuration.extensions.push(o);try{let o=Array.from(Ze.documents.keys());Ze.closeConnections(),Ze.flushPendingStores();for(let e of Ze.documents.values())e.getConnectionsCount()===0&&Ze.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(Ze.documents.values()).some(e=>e.getConnectionsCount()===0&&!gt(e));)await new Promise(e=>setTimeout(e,25));for(let e of M.getRefusedStoreDocNames()){if(yU(e))continue;let t=Ze.documents.get(e);if(!t||!gt(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(si(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=ht(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(Ze.documents.keys()),r=[],i=[];if(qe.current)for(let e of n)yU(e)||(si(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)yU(e)||(i.push(e),YH())}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=Ze.configuration.extensions,n=e.indexOf(o);n!==-1&&e.splice(n,1),r&&clearTimeout(r.id)}}async function li(){return ni||(ri=!0,ni=(async()=>{let e=Date.now(),t=[],n={phaseErrors:t,authorityGateReached:!1};ii=n;let i=Math.min(m,Dne/5),a=Date.now()+i,o=()=>Math.max(1,a-Date.now()),s=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`)),o())})])}finally{clearTimeout(n)}};pt=!0;let c=Promise.allSettled([tt()]),l;try{[l]=await s(c,`mutation-drain`)}catch(e){t.push({phase:`mutation-drain`,error:String(e)}),C.error({err:e},`[server] shutdown mutation drain failed`)}rr.clearTimeout(ir),ir=null,dr();for(let e of ne.all())Ye.discardDeferredStore(e.docName,{kind:`shutdown`}),Fr(e.docName,T()??`main`,`delete`,!0),uU(`shutdown`),M.releaseStores(e.docName);ne.clear(),M.endAllRenameCarries(),sr.clear(),cr.clear(),De=!0,Xr();for(let e of Sn.values())for(let t of e)t.namespaceAllowed=!1,t.residentAllowed=!1;Sn.clear(),xn=new WeakMap;try{await s(tn(),`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 mt.splice(0))e();try{await s(Promise.resolve(ct?.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)})}ct=null;try{I4(Pe)}catch(e){C.warn({err:e},`[server] failed to mark server.lock draining`)}Je?.destroy();try{await s($t(),`shadow-housekeeping`)}catch(e){C.warn({err:e},`[shadow-housekeeping] shutdown drain failed`),t.push({phase:`shadow-housekeeping-drain`,error:String(e)})}if(gn!==null&&(clearTimeout(gn),gn=null),_n)try{QPt(r,yn.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 u,d=await Promise.race([yt.then(()=>`completed`,e=>(C.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{u=setTimeout(()=>e(`timeout`),o())})]);u!==void 0&&clearTimeout(u),d===`timeout`&&(C.warn({},`[server] init did not complete before the pre-flush deadline`),t.push({phase:`initialization-drain`,error:`Initialization remains pending`}));let f;try{await Promise.race([Promise.allSettled(Ze.loadingDocuments.values()),new Promise((e,t)=>{f=setTimeout(()=>t(Error(`Pending document loads did not retire`)),o())})])}catch(e){t.push({phase:`document-load-drain`,error:String(e)}),C.error({err:e},`[server] shutdown document load drain failed`)}finally{clearTimeout(f)}let p=Ze.documents.size,h=async(e,t)=>{if(e!==null)try{await e.unsubscribe()}catch(e){ai(t,e)}};try{try{rt&&=(clearTimeout(rt),null),it&&=(clearTimeout(it),null),await h(w,`head`),w=null,await h(Zr,`content`),Zr=null;for(let{docName:e,cleanup:t}of Hn)try{await t()}catch(t){C.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Hn.length=0,Un.clear();try{O?.destroy(),ot?.destroy(),Bn&&=(await Bn.disconnect(),null);for(let[e,t]of Vn)try{await t.disconnect()}catch(t){C.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Vn.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 Qe.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 Cnt()}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 ci(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([Ke.close(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`derived index close did not settle within ${i}ms`)),i)})])}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 n;try{await Promise.race([(async()=>{await Ye.flushPendingGitCommit(),await Ye.waitForPendingCommits()})(),new Promise((e,t)=>{n=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{n!==void 0&&clearTimeout(n)}try{ti&&=(await ti.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(qe.current){let e;try{await Promise.race([xJ(qe.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 nM({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&xc(W(qe.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{n7e(qe.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(l?.status===`rejected`){let e=l.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 i=Date.now()-e;if(n.authorityGateReached=!0,t.length===0){Ee=!0;try{Le.release()}catch(e){t.push({phase:`authority-release`,error:String(e)}),C.error({err:e},`[server] shutdown authority release failed`)}C.info({documentCount:p,durationMs:i},`[server] shutdown flushed ${p} documents in ${i}ms`)}else C.warn({documentCount:p,durationMs:i,phaseErrors:t},`[server] shutdown flushed ${p} documents in ${i}ms with ${t.length} phase error(s)`)}}finally{try{F4(Pe,{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 OU()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}ii===n&&(ii=null)}if(l?.status===`rejected`)throw l.reason})(),ni)}let ui=[];async function di(){try{dt=await HPt(r),C.info({principalId:dt.id},`[server] principal loaded`)}catch(e){C.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!qe.current)try{qe.current=await AJ(r,{deferGcConfig:!0}),C.info({gitDir:qe.current.gitDir},`[server] history repo initialized at ${qe.current.gitDir}`),Q5e(qe.current)&&!ui.includes(`shadow-excludes`)&&ui.push(`shadow-excludes`)}catch(e){C.error({err:e},`[server] history repo init failed`),ui.push(`shadow-repo`)}if(qe.current)try{let e=Wat(qe.current.gitDir);cot(qe.current.gitDir,e),Yat(qe.current.gitDir,e),Xt=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(qe.current)try{await OJ(qe.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{qe.current=await AJ(r,{deferGcConfig:!0}),Q5e(qe.current)&&!ui.includes(`shadow-excludes`)&&ui.push(`shadow-excludes`)}catch(e){C.error({err:e},`[server] history repo reinit failed`),qe.current=void 0,ui.includes(`shadow-repo`)||ui.push(`shadow-repo`)}}else C.error({err:e},`[server] history repo check failed (transient?)`)}if(qe.current&&ni===null){let e=qe.current,t=oG(U(r,n))||`.`;it=setTimeout(()=>{it=null,NJ(e,t).catch(e=>{C.debug({err:e},`[shadow] fan-out index warm-up failed (non-fatal)`)})},3e3),it.unref?.()}if(qe.current)try{let e=W(qe.current.gitDir,`last-known-head`),t=null;try{t=K(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await nM({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await nM({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(qe.current,p??``,t,n,e),dZe()}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{xc(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=LCt(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`),ui.push(`managed-rename-recovery`)}try{let e=Bmt(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`),ui.push(`upload-tempfile-sweep`)}try{Bn=await Ze.openDirectConnection(Ue),O?.emitServerInfo(Te,E()??void 0)}catch(e){C.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),ui.push(`cc1-push`)}let t=y?[]:Vr;for(let e of t)try{let t=await Ze.openDirectConnection(e);Vn.set(e,t)}catch(t){C.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),ui.push(`config-doc:${e}`)}let i=new Map([[ve,bl(`project`,r)],[Rn,bl(`project-local`,r)],[pne,bl(`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=Ze.documents.get(e),r=xMt(e,t,Ye.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,Ye.configPersistenceCtx);C.info({docName:e,outcome:i,isEcho:r},`[config-file-watcher] applyExternalConfigChange outcome`),we(e),r||ye(e)},r=await Qjt(t,t=>{n(t).catch(t=>{C.warn({err:t,docName:e},`[config-file-watcher] change handler failed`)})});Hn.push({docName:e,cleanup:r}),Un.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}`),ui.push(`config-file-watcher:${e}`)}}if(!y){let e=null,t=t=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,Ke.refreshGlobalSkillNodes().catch(e=>{C.warn({err:e,docName:t},`[backlinks] global skill bundle re-ingest failed`)})},300)},n=async(e,n)=>{let r=n_t(e,Ye.managedArtifactCtx);if(!r)return;let i=await c_t(Ze.documents.get(r)??null,r,n,Ye.managedArtifactCtx);C.info({docName:r,outcome:i},`[managed-artifact-watcher] external change`),kt(`files`),Oo(r)&&t(r)},r=e=>{let n=n_t(e,Ye.managedArtifactCtx);kt(`files`),n&&Oo(n)&&t(n)};try{let e=Qgt(Ye.managedArtifactCtx),t=await sPt(e,n,r);Hn.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`),ui.push(`managed-artifact-watcher:skills`)}try{let e=DQ(t6(Ye.managedArtifactCtx)),t=await Qjt(e,()=>{kt(`files`)});Hn.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`),ui.push(`skill-state-watcher`)}}try{let e=W(n,`.okignore`),t=W(r,`.gitignore`),i=null;try{let e=Ws(`git`,[`rev-parse`,`--git-common-dir`],aW({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 $jt(a,(t,n)=>{(async()=>{if(t===e)try{let e=await F7(Ze.documents.get(`__config__/okignore`)??null,je,n,Ye.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 Ge.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&&(Hn.push({docName:`__ignore-files__`,cleanup:s}),Un.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`),ui.push(`ignore-files-watcher`)}let a=t9(r).branch??`main`;te(a),Et();let o=Ke.beginStartup(a),s=!1,c=performance.now();try{await jU(`ok.boot.indexes`,void 0,async()=>{let t=await o.offlineDeletionsReady,i=0;for(let e of t)yU(e)||yn.peek(e)?.kind!==`renamed`&&(yn.setDeleted(e),i++);i>0&&C.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`),Tt.resolve();let{backlinkIndexDegraded:a}=await o.backlinksReady;a&&ui.push(`backlink-index`);let c=performance.now(),l=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,d=Ge?new Set(U1(n).map(e=>e.dir)):new Set,f=e=>{e.some(e=>l.test(U(b,e).split(Qs).join(`/`)))&&(rt&&clearTimeout(rt),rt=setTimeout(()=>{rt=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=xct(n,d);if(!(e.size!==d.size||[...e].some(e=>!d.has(e))))return;d=e,Ge.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))};await oi(()=>jU(`ok.boot.seed-walk`,void 0,async()=>qtt(b,qr,Ge,{onRawBatch:f,onRecoveryComplete:()=>Ke.recordInventoryReconciled(),onRecoveryPassCompleted:(e,t)=>Er(e,t),nativeBackend:e.watcherBackend,clock:e.watcherClock,freshnessIntervalMs:e.freshnessIntervalMs===void 0?5e3:e.freshnessIntervalMs})),e=>{Zr=e},`content`),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??wc();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 yn.entries()){if(!o5(n))continue;let r=W(e,`${n}${UH(n)}`);sG(r,e)&&G(r)&&(yn.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 Ke.settleStartupAfterWatcherSeed();s=!0,p.tagIndexDegraded&&ui.push(`tag-index`);let m=0;try{v===void 0?await u5({contentDir:n,contentFilter:Ge,basenameIndex:ze,onSkip:(e,t,n)=>{m++,C.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):pTt({contentDir:n,basenameIndex:ze,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`),ui.push(`basename-index-partial`))}catch(e){C.error({err:e},`[basename-index] startup seed failed`),ui.push(`basename-index`)}})}catch(e){if(C.error({err:e},`[server] disk bridge watcher failed to start`),ui.push(`file-watcher`),!s){let e=await Ke.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&ui.push(`tag-index`)}}finally{r4(`indexesMs`,Math.round(performance.now()-c)),Zr&&Wft(`fileCount`,Zr.getFileIndex().size),Xn()}let l=()=>{};try{await oi(()=>kNt(r,async({trigger:e})=>{if(C.info({trigger:e},`[batch] begin trigger=${e}`),uZe(),Ze.flushPendingStores(),await Ye.flushPendingGitCommit(),re(`head-watcher`),l(),l=M.holdWriteAdmission(),qe.current){let e=P(),t=t9(r).branch??e,n=[],i=0;for(let[e,t]of Ze.documents){if(yU(e))continue;let r=null;if(t.transact(()=>{r=Gn(e)},SIt),r===null)continue;let a=F(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 v7e(qe.current,e,IJ.id,n,t);r&&(_Ze(),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=Kr.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 Yr()}finally{Xr()}if(e.headMoved&&e.newHead){let t=wIt(r,W(n),e.oldHead,e.newHead);if(t.size>0){fat(t.keys());for(let[e,n]of t)c$(e,Eve(n.email),n.name,n.email,Yve(e));await Ye.flushContributors()}}}finally{try{ie(`head-watcher`)&&await ae()}finally{l()}}try{await ce.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e},`[head-watcher] conflict prune against git failed`)}}else{gZe(),dr();let t=!1,r=!1,a;try{te(i),ce.setBranch(i),le(),a=await Ke.beginBranchSwitch(i),Ge.rebuildDirCount();try{let e=0;ze.clear(),await u5({contentDir:n,contentFilter:Ge,basenameIndex:ze,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`),ui.includes(`basename-index-partial`)||ui.push(`basename-index-partial`))}catch(e){C.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}try{await Ke.settleBranchFromDisk(a)}catch(e){Ke.abortBranchSwitch(a),C.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}try{await Yr();let e=await Zr?.recheck(`full`);e&&(e.status!==`completed`||e.partial)&&(r=!0,o$e(),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 Yr()}finally{Xr()}if(Pr(i),C.info({branch:i,docCount:Ze.documents.size},`[branch-switch] loaded branch ${i} (${Ze.documents.size} docs)`),e.oldBranch?.startsWith(`detached-`)&&qe.current)try{let t=OJ(qe.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await xJ(qe.current).withMutator(async()=>{for(let e of n.split(`
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,ie(`head-watcher`)&&await ae(),O?.emitBranchSwitched(i),r&&fr(i)}finally{try{Ke.abortBranchSwitch(a),!t&&ie(`head-watcher`)&&await ae()}finally{l()}}}if(e.headMoved&&e.newHead&&qe.current&&t>0){let t=p??`.`;try{let n=await RJ(qe.current,t,e.oldHead,e.newHead,i);dZe(),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:()=>{ui.includes(`head-watcher`)||ui.push(`head-watcher`)},onBack:()=>{let e=ui.indexOf(`head-watcher`);e!==-1&&ui.splice(e,1)}}),e=>{w=e},`head`)}catch(e){C.error({err:e},`[server] HEAD watcher failed to start`),ui.push(`head-watcher`)}ce.subscribe(e=>{if(e.type!==`raised`||e.conflict.kind===`reconcile`)return;let t=e.docName;if(t===null||!Ze.documents.get(t))return;let n=Gn(t);n===null?C.warn({docName:t,file:e.conflict.file},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):ee(t,n)});try{await ce.pruneMergeNativeAgainstGit()}catch(e){C.warn({err:e},`[conflicts] boot prune of merge-native entries failed`)}let d=await S(),f=de(),m=fe();f.mode!==`off`&&C.info({mode:f.mode,source:f.source},`[sync] mode active at boot`);try{ti=new cIt({declaredGitHubHosts:x,projectDir:r,contentDir:n,contentFilter:Ge,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:ce,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:oe(`sync-engine`),onStateChange:e=>{C.info({state:e},`[sync] state → ${e}`)},checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=qe.current;n&&await BJ(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=qe.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 Sl({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||C.error({result:t,reason:e,humanError:Ft(t.error),configPath:bl(`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 ti.start()}catch(e){C.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ti=null}kt(`files`),Ke.announceReadyViews();let h=Uft();h!==void 0&&r4(`readyMs`,h),ye()}return di().then(()=>{Nt=!0,_t(),setImmediate(()=>{let e=A.pruneGone(j);e>0&&C.info({pruned:e},`[disk-receipts] dropped ${e} receipt(s) whose file is gone`)}).unref(),qt(),Qt()},e=>{Pt=!0,It.abort(),Wt({status:`failed`,indexCount:0}),Ke.close(),Et(),vt(e)}),{hocuspocus:Ze,durabilityState:M,sessionManager:Qe,nativeApi:$e,localApi:et,cc1Broadcaster:O,agentFocusBroadcaster:at,agentPresenceBroadcaster:ot,maintenanceCoordinator:Je,contentFilter:Ge,basenameIndex:ze,serverInstanceId:Te,destroy:li,ready:yt,generatedIndexSweepReady:Ut,degraded:ui,lockDir:Pe,get syncEngine(){return ti},conflicts:ce,getLinkPreviewsEnabled:ge,resolveEmbed:He,resolveTrackedFile:Be,acpRegistry:Fe,acpPermissions:Ie,recheckDisk:()=>Zr?Zr.recheck():Promise.reject(Error(`the file watcher is not running, so there is nothing to re-check`))}}function I9(e){return e/1048576}function EIt(){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 DIt=1e6;let B9=null,V9=null;DU(()=>{L9=null,R9=null,z9=null,B9?.disable(),B9=null,V9=null});function OIt(){if(L9)return;let e=AU().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}=EIt();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 kIt(){if(!R9){let e=AU().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=Rae({resolution:20}),B9.enable();return}e.observe(B9.percentile(50)/DIt,{stat:`p50`}),e.observe(B9.percentile(99)/DIt,{stat:`p99`}),B9.reset()}),R9=e}if(!z9){let e=AU().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 AIt=q(`skill-migrate`);function jIt(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=aN.indexOf(e.host),r=aN.indexOf(t.host);return(n===-1?aN.length:n)-(r===-1?aN.length:r)||e.host.localeCompare(t.host)})}const MIt=jIt(Ne),NIt=jIt(be);function PIt(e,t){return G(W(e,ko(t)))}function FIt(e,t){qU(V(t),{recursive:!0});try{JU(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;YU(e,t,{recursive:!0}),tW(e,{recursive:!0,force:!0})}}function IIt(e,t,n){let r=Vct(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 LIt(e,t){let n;try{n=hc(W(e,`.ok`,`skills`))}catch{n=W(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!hc(W(e,t.dir)).startsWith(n+Qs)}catch{return!0}}).map(e=>e.name))}async function RIt(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??MIt,o={migrated:[],skipped:[]};if(!G(n))return o;let s;try{s=mc(n)}catch{return o}let c=U(t,n).split(Qs).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)||AH.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=ZM(r)?.contentHash;if(s===void 0)continue;let c=hc(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:IIt(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=>PIt(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`?tW(r,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&tW(d.path,{recursive:!0,force:!0}),FIt(r,d.path));for(let e of u)e!==d&&e.state.kind===`store-link`&&(tW(e.path,{recursive:!0,force:!0}),YU(d.path,e.path,{recursive:!0}));await Z1(t,e),o.migrated.push({name:e,to:`${d.root}/${e}`}),AIt.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){o.skipped.push({name:e,reason:`error`}),AIt.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return o}let H9=null,U9=!1;function zIt(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function BIt(e){if(!zIt())return;let t=qJ(e);H9=new Yx({currentPath:W(t,`tolerance-telemetry.jsonl`),previousPath:W(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),_(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(){_(null),await H9?.drain(),H9=null,U9=!1}function VIt(e){let t=W(e,wi);if(!(()=>{if(!G(t))return!0;try{return mc(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 bee){let r=W(e,t);try{G(r)&&yc(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function HIt(e){let t=iS(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 UIt(e){Hft();let t=e.projectDir??e.contentDir,n=Cl(t),r=jTt({projectDir:t});if(r){Ujt(t,{authorityRegistryPath:e.authorityRegistryPath});let n=r.telemetry.attributeDenylist,i=[];for(let e of n){i.push(e);for(let t=1;t<=5;t++)i.push(`${`*.`.repeat(t)}${e}`)}$x.configure({pinoConfig:{fileSink:r.logs,redactPaths:i}})}EU({localSink:r?.telemetry}),BIt(t),OIt(),kIt();let{kind:i,gitdir:a}=HIt(e.projectDir??e.contentDir),o={"ok.worktree.kind":i};a!==null&&(o[`ok.worktree.gitdir`]=FU(a));let s=wTt(t),c=process.env.OK_STARTUP_TRACEPARENT,l=()=>jU(`ok.boot`,{attributes:o},async()=>WIt(e,n)),u=()=>{if(c)try{let e=Io.extract(Mo.active(),{traceparent:c});return Mo.with(e,l)}catch(e){q(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return l()},d;try{d=await u()}catch(e){throw s.uninstall(),e}let f=d.destroy;return d.destroy=async e=>{try{await f(e)}finally{s.uninstall()}},d}async function WIt(e,t){let n=e.skipAutoInit??!1,r=e.log??q(`boot`),i=e.serverRuntime??{...or(e.config),allowExternal:!1},a=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((hee(i)||!gr(a))&&!i.allowExternal)throw new jit(`refusing to start: the server would bind a non-loopback address (${(gr(a)?i.bind:a).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let o=BQ({serverRuntime:i});i.allowExternal&&!i.loopbackOnly&&i.externalUrl===void 0&&(o.bindLiterals.length===0?r.warn({bind:i.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.`):r.info({bind:i.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 s=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,c=e.lockKind??s??`interactive`,{createServer:l}=await import(`node:http`),{markServerLockDraining:u,releaseServerLock:d,updateServerLockPort:f}=await Promise.resolve().then(()=>rmt),p=!1;if(!n&&e.autoInitFn)try{p=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let m=e.projectDir??e.contentDir,h=W(m,`.ok`),g=W(h,`config.yml`);if(!G(g))throw new Rjt(G(h)?`config`:`okdir`,m);let _=W(h,`.gitignore`);G(_)||q(`boot`).warn({path:_},`Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run \`${Jt()} init\` to add the recommended ignore entries.`);let v=e.gitPreflight??lW;try{e.gitEnabled!==!1&&v()}catch(e){if(e instanceof oW||e instanceof sW||e instanceof cW){let t=N6(e);P6(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:t.reason,detectedVersion:t.detectedVersion},t.logMessage),process.stderr.write(`${e.message}\n`)}throw await OU(),await Promise.race([W9(),new Promise(e=>setTimeout(e,G9))]),e}let y=VIt(h);y.length>0&&q(`boot`).warn({files:y},`Found legacy runtime files at .ok/${y.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${wi}/.`);let b=null,x=TIt({authorityRegistryPath:e.authorityRegistryPath,getCollabClientCount:()=>b?.getCount()??0,acpRegistryFetchImpl:e.acpRegistryFetchImpl,contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:o,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:c,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:S,destroy:C,ready:w,degraded:T,lockDir:E,sessionManager:D,agentFocusBroadcaster:O,agentPresenceBroadcaster:k,maintenanceCoordinator:A}=x,j=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),M=e.port??0,N=()=>`http://${j}:${M}`,P=e.ephemeral?void 0:kjt({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>N(),localApi:x.localApi,log:r}),F=l();F.headersTimeout=3e4,F.requestTimeout=6e4;let ee=e.serveContentAssets===!1?void 0:fTt({contentDir:e.contentDir,contentFilter:x.contentFilter,contentSirv:TI(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:nne,assetExtensions:ro,blocklistExtensions:Are,ingressPolicy:o,resolveTrackedFile:x.resolveTrackedFile}),I=e.reactShellDistDir?TI(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0,setHeaders:TTt(e.reactShellDistDir)}):void 0,te=e.ephemeral?null:new h8e({contentDir:e.contentDir,localDir:E,globalDir:ml(),registry:x.acpRegistry,permissions:x.acpPermissions,sessionManager:D,agentPresenceBroadcaster:k,localApi:x.localApi,isExcludedPath:e=>x.contentFilter.isExcluded(e),isIgnoredPath:e=>x.contentFilter.isPathIgnored(e),getLoadedDocText:e=>S.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>N(),getMcpStdioCommand:()=>m8e(e.localOpCliArgs,M,{log:r}),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,probePiAcpBridge:e.probePiAcpBridge,ensurePiAcpBridge:e.ensurePiAcpBridge,terminalAuthAvailable:e.terminalAuthAvailable===!0,hostSnapshot:()=>Pq({env:`local-web`,resolve:e.agentIntegrations?.probe}),autoApproveOkTools:()=>cXe(e.projectDir??e.contentDir,e.configHomedirOverride,r),agentBrowserTools:()=>lXe(e.projectDir??e.contentDir,e.configHomedirOverride,r),log:r});te!==null&&await te.init();let ne=`pending`;w.then(()=>{ne=`ready`},()=>{ne=`failed`});let re=Ijt({httpServer:F,hocuspocus:S,nativeApi:x.nativeApi,mcpHttpHandler:P,ingressPolicy:o,health:{readiness:()=>ne,degraded:()=>T},log:r,sessionManager:D,agentFocusBroadcaster:O,agentPresenceBroadcaster:k,maintenanceCoordinator:A,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ee,reactShellMiddleware:I,ephemeral:e.ephemeral,acpThreadManager:te}),ie=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)};b=m5(F);let ae=null,oe=[...new Set(a)],se=oe[0],ce=async()=>{await C().catch(e=>{r.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),d(E)},le=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await le(F,e.port??0,se??`127.0.0.1`)}catch(e){throw await ce(),e}let ue=F.address(),de=typeof ue==`object`&&ue?ue.port:e.port??0,fe=[];for(let e of oe.slice(1)){let t=l();t.headersTimeout=F.headersTimeout,t.requestTimeout=F.requestTimeout;for(let e of F.listeners(`request`))t.on(`request`,e);for(let e of F.listeners(`upgrade`))t.on(`upgrade`,e);try{await le(t,de,e)}catch(t){r.error({err:t,failedAddress:e,port:de,alreadyBound:fe.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...fe,F])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&r.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await ce(),t}fe.push(t)}let pe=Uft();pe!==void 0&&r4(`httpListenMs`,pe);let me=F.address(),he=typeof me==`object`&&me?me.port:e.port??0;M=he;let ge=N();f(E,he,ge),r.info({event:`server-listening`,pid:process.pid,port:he,addresses:oe,url:ge,lockDir:E},`[boot] listening on ${ge}`);let _e=!1,ve=async(e,t,n)=>{let r,i,a=!1,o=Promise.withResolvers(),s=()=>{a||(a=!0,o.reject(Error(n?`${e} timed out: no document retired for ${G9}ms`:`${e} timed out after ${G9}ms`)))},c=()=>{r=setTimeout(s,G9),r.unref?.()};try{n&&(i=bIt(n,()=>{a||(r!==void 0&&clearTimeout(r),c())}),c());let e=t();n||c(),await Promise.race([e,o.promise])}finally{a=!0,i?.(),r!==void 0&&clearTimeout(r)}};ie=async(e=`unspecified`)=>{if(_e)return;_e=!0;try{let e=lc(t);if(e.isDirectory()&&!e.isSymbolicLink()){let e=new Date;RU(t,e,e)}}catch{}r.info({reason:e,pid:process.pid,lockDir:E},`[server] shutdown initiated (${e})`),ne=`draining`;let n=[],i=async(e,t,i)=>{try{await ve(e,t,i)}catch(t){n.push(t),r.warn({err:t,step:e},`bootServer destroy step failed`)}};try{u(E)}catch(e){r.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{b?.detach()}catch(e){r.warn({err:e,step:`collabClientCounter.detach`},`bootServer destroy step failed`)}try{ae?.detach()}catch(e){n.push(e),r.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(te!==null&&await i(`acpThreads.destroy`,()=>te.destroy()),await i(`secondaryListeners.close`,async()=>{for(let e of fe)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&r.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await i(`mount.shutdown`,()=>re.shutdown()),P!==void 0&&await i(`mcpHttpHandler.close`,()=>P.close()),await i(`mount.wss.close`,()=>new Promise((e,t)=>{re.wss.close(n=>n?t(n):e())})),await i(`httpServer.closeAllConnections`,async()=>{F.closeAllConnections?.()}),await i(`httpServer.close`,()=>new Promise((e,t)=>{F.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await i(`destroyHocuspocus`,()=>C(),S),await i(`shutdownTelemetry`,()=>OU()),await i(`teardownToleranceTelemetry`,()=>W9()),await i(`flushLogFileSinks`,()=>$x.flushAllFileSinks()),n.length>0)throw AggregateError(n,`bootServer destroy completed with errors`)};try{let t=await RIt({projectDir:m,skillsRoot:W(e.contentDir,`.ok`,Ea),inPlaceNames:async()=>LIt(e.contentDir,U1(e.contentDir))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=wc(),t=await RIt({projectDir:e,skillsRoot:W(e,`.ok`,Ea),hostRoots:NIt,inPlaceNames:async()=>LIt(e,await G1(e))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}if(e.idleShutdownMs!==null){let t=e.idleShutdownMs??18e5,n=e.idleShutdownHandler??(e=>async()=>{await e()});ae=ETt({httpServer:F,counter:b,thresholdMs:t,log:r,onShutdown:n(async()=>{await ie(`idle-shutdown`)})})}return{httpServer:F,destroy:ie,lockDir:E,contentDir:e.contentDir,port:he,ready:w,generatedIndexSweepReady:x.generatedIndexSweepReady,degraded:T,didAutoInit:p,serverInstance:x,runtime:Gjt(x,{contentDir:e.contentDir,projectDir:m}),acpThreadManager:te}}const GIt=Se;function KIt(e={}){let t=e.home??wc(),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=Px(S_e(),1);function q9(){return H(ml(),`logs`)}const qIt=[`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 YIt(e){uc(e,{recursive:!0})}function XIt(){return new Date().toISOString().slice(0,10)}function ZIt(e){try{if(yc(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{gc(n,r)}catch{}}try{bc(`${e}.3`)}catch{}}function QIt(e){try{let t=Date.now(),n=6048e5,r=mc(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=yc(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{bc(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{bc(H(e,t.name)),a-=t.size}catch{}}}catch{}}function $It(e){YIt(q9());let t=XIt(),n=e.filePath??H(q9(),`${e.name}.${t}.log`);ZIt(n),(e._setTimeout??setTimeout)(()=>QIt(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:qIt,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 eLt(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 tLt(e){return H(q9(),`${e}.${XIt()}.log`)}function nLt(){return q9()}function rLt(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=Hc(Vs),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 iLt(e,t){try{return await J9(e,[`var`,`GIT_COMMITTER_IDENT`],aW({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function aLt(e,t){try{let{stdout:n}=await J9(e,[`for-each-ref`,`--count=1`,`refs/`],aW({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return Y9.warn({path:t,stderr:sLt(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function oLt(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 mc(W(e,`refs/heads`)).length>0}catch{return!1}}function sLt(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 cLt(e,t){if(await aLt(e,t))return;let n=[`commit`,`--allow-empty`,`--no-verify`,`--no-gpg-sign`,`-m`,`Initial commit`],r=await iLt(e,t),i=r?n:[`-c`,`user.name=Open Knowledge`,`-c`,`user.email=noreply@openknowledge.local`,...n];try{await J9(e,i,aW({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:sLt(e)},`could not create initial commit`)}}async function lLt(e,t){try{let{stdout:n}=await J9(e,[`rev-parse`,`--is-inside-work-tree`],aW({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function uLt(e){let t=W(e);Zq(t);let n=W(t,`.git`),r=W(n,`HEAD`),i=!1,a=!1;if(G(n)){if(!yc(n).isDirectory())return{didInit:!1};if(G(r)){if(oLt(n))return{didInit:!1};a=!0}else Y9.info({},`detected partial .git/ — running git init to repair`),i=!0}let o;try{o=lW()}catch(e){if(e instanceof oW||e instanceof sW||e instanceof cW){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 cLt(s,t),{didInit:!1};if(!i&&await lLt(s,t))return{didInit:!1};let c=``;try{c=(await J9(s,[`init`,`--initial-branch=main`,t],aW({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 cLt(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 dLt(e,t){let n;try{n=Bs(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 Pc(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 fLt=[{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 fLt)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 pLt=class extends Error{filePath;constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},mLt=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`}},hLt=class extends Error{filePath;constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function gLt(e,t={}){if(!IH(e))throw new hLt(e);let n;try{n=hc(W(e))}catch(t){throw t.code===`ENOENT`?new pLt(e):t}if(!yc(n).isFile())throw new mLt(e);let r=V(n);if(t.projectRoot!==void 0){let e=W(t.projectRoot);if(!LG(e))throw new $9(e,`no .ok/config.yml there, so it is not an OpenKnowledge project root`);let r=_Lt(e),i=U(r,n);if(i.startsWith(`..`)||Ys(i))throw new $9(e,`${n} is not inside that project's content directory`);return{mode:`project`,projectRoot:e,docName:zH(i.split(Qs).join(`/`)),canonicalFilePath:n}}let i=N2e(r);if(i){let e=i.rootPath,t=_Lt(e);return{mode:`project`,projectRoot:e,docName:zH(U(t,n).split(Qs).join(`/`)),canonicalFilePath:n}}let a=Ks(n);return{mode:`ephemeral`,canonicalFilePath:n,contentDir:r,singleDocRelPath:a,docName:zH(a)}}function _Lt(e){let t=pl({absPath:bl(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`;return W(e,t)}const vLt=`ok-ephemeral-`;function yLt(e,t){let n=W(e,`.ok`);return uc(n,{recursive:!0}),xc(W(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(t)}\n`,`utf-8`),xc(W(n,`.gitignore`),`local/
2231
2231
  `,`utf-8`),e}function bLt(e){return yLt(dc(W(Dc(),vLt)),e)}const xLt=`server-base`;export{rit as $,Pyt as $a,uit as $i,KIt as $n,MQ as $o,gTt as $r,O8e as $t,jit as A,h$e as Aa,_5e as Ai,l$ as An,qU as Ao,iJ as Ar,gl as As,b9 as At,cW as B,qvt as Ba,f5 as Bi,bLt as Bn,O4 as Bo,p5e as Br,yl as Bs,M4 as Bt,HJ as C,hX as Ca,fbt as Ci,jJ as Cn,pat as Co,Tbt as Cr,q as Cs,RK as Ct,wG as D,E4 as Da,D4 as Di,q0 as Dn,KU as Do,qJ as Dr,lve as Ds,pLt as Dt,EG as E,BX as Ea,P4 as Ei,K0 as En,T4 as Eo,zit as Er,Zx as Es,mLt as Et,$8e as F,n8 as Fa,FU as Fi,fTt as Fn,ZU as Fo,Qbt as Fr,Rse as Fs,Awt as Ft,n1 as G,dLt as Ga,Ujt as Gi,i1 as Gn,amt as Go,PTt as Gr,rl as Gs,aFt as Gt,d5 as H,G0 as Ha,pJ as Hi,$It as Hn,CH as Ho,EU as Hr,Sl as Hs,m$ as Ht,Oyt as I,r8 as Ia,OH as Ii,Mjt as In,BU as Io,RQ as Ir,Lse as Is,jwt as It,Fpt as J,mat as Ja,YTt as Ji,TIt as Jn,MU as Jo,Oit as Jr,$ae as Js,s3e as Jt,_5 as K,o1 as Ka,gLt as Ki,zPt as Kn,aW as Ko,Pst as Kr,Aoe as Ks,lW as Kt,FJ as L,J0 as La,r5e as Li,cK as Ln,GU as Lo,ePt as Lr,pl as Ls,A0e as Lt,PJ as M,Ost as Ma,I4 as Mi,tPt as Mn,JU as Mo,m$e as Mr,ll as Ms,gft as Mt,u$ as N,FH as Na,Ljt as Ni,a9 as Nn,tW as No,kU as Nr,Cl as Ns,PH as Nt,upt as O,l5e as Oa,x4 as Oi,nY as On,$U as Oo,tLt as Or,rve as Os,hLt as Ot,h4 as P,KJ as Pa,Ijt as Pi,lTt as Pn,nW as Po,dU as Pr,ml as Ps,bK as Pt,U$e as Q,Tyt as Qa,git as Qi,wpt as Qn,x9 as Qo,t5e as Qr,gJ as Qt,oW as R,u4 as Ra,vTt as Ri,_4e as Rn,dIt as Ro,s$e as Rr,Pse as Rs,ZW as Rt,nnt as S,T5e as Sa,m7e as Si,RJ as Sn,L3e as So,hat as Sr,gve as Ss,U6 as St,lbt as T,F4 as Ta,HPt as Ti,mW as Tn,wH as To,T5 as Tr,$x as Ts,j4 as Tt,mTt as U,eut as Ua,OX as Ui,VNt as Un,Myt as Uo,BIt as Ur,ol as Us,_bt as Ut,hTt as V,JJ as Va,Ajt as Vi,wat as Vn,imt as Vo,AJ as Vr,bse as Vs,CQ as Vt,Q8e as W,K6 as Wa,Sbt as Wi,kjt as Wn,qXe as Wo,NTt as Wr,Foe as Ws,r3e as Wt,t8e as X,$9e as Xa,XTt as Xi,P8e as Xn,Tvt as Xo,$Tt as Xr,i3e as Xt,V8 as Y,eet as Ya,fJ as Yi,$Pt as Yn,dit as Yo,mU as Yr,ioe as Ys,cX as Yt,nit as Z,Eyt as Za,lXe as Zi,eq as Zn,m5e as Zo,yZ as Zr,Zq as Zt,qrt as _,c$ as _a,Est as _i,IU as _n,e8 as _o,N2e as _r,sS as _s,eFt as _t,SXe as a,tmt as aa,tEt as ai,Lst as an,b6 as ao,P6 as ar,aR as as,FXe as at,$bt as b,k6 as ba,nJ as bi,q6 as bn,XJ as bo,Sut as br,eS as bs,T4e as bt,M8e as c,t9 as ca,QW as ci,BQ as cn,UJ as co,P5 as cr,nP as cs,X9 as ct,yTt as d,NQ as da,i8 as di,hbt as dn,yLt as do,Jet as dr,ZN as ds,hW as dt,x6 as ea,e5e as ei,m5 as en,byt as eo,E$e as er,pX as es,T$e as et,MH as f,hit as fa,VQ as fi,NJ as fn,Q9 as fo,Gwt as fr,QN as fs,IJ as ft,v$e as g,cY as ga,qX as gi,utt as gn,OU as go,rLt as gr,cS as gs,G6 as gt,j2 as h,jQ as ha,yU as hi,Xq as hn,OJ as ho,N$e as hr,nM as hs,W6 as ht,mXe as i,k4 as ia,mJ as ii,UIt as in,BJ as io,$lt as ir,Pze as is,d5e as it,hXe as j,L0 as ja,Cpt as ji,i9 as jn,UU as jo,AU as jr,vse as js,xLt as jt,vLt as k,h1 as ka,Hvt as ki,cG as kn,WU as ko,nLt as kr,ive as ks,$9 as kt,EQ as l,Ept as la,UQ as li,m8e as ln,lEt as lo,uLt as lr,eP as ls,bot as lt,kH as m,lit as ma,LG as mi,m4 as mn,Wrt as mo,k2 as mr,Zj as ms,mbt as mt,TXe as n,C6 as na,ubt as ni,qlt as nn,HG as no,_1 as nr,fR as ns,Rjt as nt,h8e as o,dJ as oa,IQ as oi,a5e as on,G$e as oo,N5 as or,cR as os,b4 as ot,NH as p,iFt as pa,tJ as pi,IXe as pn,NU as po,JTt as pr,jN as ps,ast as pt,RNt as q,R5 as qa,Wjt as qi,cEt as qn,jU as qo,Dit as qr,tl as qs,xK as qt,Grt as r,tut as ra,bU as ri,Qtt as rn,Cwt as ro,sEt as rr,WL as rs,fQ as rt,A8e as s,b5 as sa,hU as si,Mkt as sn,VJ as so,gDt as sr,TF as ss,zpt as st,EXe as t,Gvt as ta,HQ as ti,ETt as tn,bEt as to,tFt as tr,sHe as ts,yEt as tt,oit as u,N4 as ua,pQ as ui,JXe as un,u5 as uo,X as ur,tP as us,f5e as ut,Qq as v,a1 as va,pU as vi,vJ as vn,V7e as vo,U0 as vr,mS as vs,q$e as vt,lpt as w,A4 as wa,xH as wi,l7e as wn,W9 as wo,g7e as wr,_ve as ws,zK as wt,GIt as x,Djt as xa,NX as xi,Pq as xn,fH as xo,_Tt as xr,Qx as xs,H6 as xt,R7e as y,N5e as ya,zIt as yi,Tpt as yn,qtt as yo,eLt as yr,oS as ys,E4e as yt,sW as z,VFt as za,uW as zi,Spt as zn,zX as zo,$H as zr,bl as zs,Zpt as zt};