@inkeep/open-knowledge 0.76.0-beta.0 → 0.76.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +6 -6
- package/dist/constants-CqleiXu2.mjs +1 -0
- package/dist/{dist-CmcNpgS2.mjs → dist-BYaz0taZ.mjs} +1 -1
- package/dist/{dist-Cao3SE0M.mjs → dist-D0pUzrgW.mjs} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/init-CzdH5YhF.mjs +1 -0
- package/dist/{init-GCRo0K5W.mjs → init-D35_7qCz.mjs} +2 -2
- package/dist/{launch-json-removal-CJkRZi3K.mjs → launch-json-removal-DfVWRHc2.mjs} +1 -1
- package/dist/{loader-CqW43w1q.mjs → loader-Il_r9h-s.mjs} +1 -1
- package/dist/loader-TircuzL8.mjs +1 -0
- package/dist/{open-browser-BOsYkMjA.mjs → open-browser-5wS5161m.mjs} +1 -1
- package/dist/{preview-BwnUznwj.mjs → preview-B_F6SpZs.mjs} +1 -1
- package/dist/preview-D14ciGsV.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-Y8gSWVUE.js → ActivityModeContent-CdOOmDnv.js} +1 -1
- package/dist/public/assets/{AddPropertiesButton-C-4pht4k.js → AddPropertiesButton-D94DERhh.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-xNIBUX9b.js → AgentDiffPane-BYWv05nU.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-BmJVd5ie.js → CodeMirrorPropInput-BfFHUIPT.js} +1 -1
- package/dist/public/assets/{DocumentContext-3tSfyT4u.js → DocumentContext-CmobwhDV.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-vCyHuxcP.js → EditorModeToggle-Ceb7UENC.js} +1 -1
- package/dist/public/assets/{EnableSyncConfirmDialog-BVl1rWxR.js → EnableSyncConfirmDialog-3Y8YTBbR.js} +1 -1
- package/dist/public/assets/{ExcalidrawDocEditor-BRLL2l_F.js → ExcalidrawDocEditor-BGifKKc5.js} +1 -1
- package/dist/public/assets/FeedbackForm-DcQmM7vN.js +1 -0
- package/dist/public/assets/{ImportSkillDialog-MLKooPR_.js → ImportSkillDialog-uibV-E0W.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-8nbzftWe.js → LintConfigEditor-oHvdt6bD.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-BPFT0XnN.js +1 -0
- package/dist/public/assets/{ManagedArtifactProperties-DSK_y6l8.js → ManagedArtifactProperties-DYixzgyO.js} +1 -1
- package/dist/public/assets/{MermaidDocEditor-VvK21kJ7.js → MermaidDocEditor-BAXy9Wq3.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow--Arw18Ls.js → PropertyDisplayRow-CpY_83p_.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-CB0ciOXE.js → SchemaConfigEditor-eP12D_vE.js} +1 -1
- package/dist/public/assets/{SessionsHost-B_HqzNv8.js → SessionsHost-CzyeLm35.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-C5hX7NBY.js → SettingsDialogBody-C2rIl4ig.js} +1 -1
- package/dist/public/assets/{ShareReceiveMissDialog-5SsxwO0Y.js → ShareReceiveMissDialog-gQIfuuKz.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-BKBcDvQr.js → SkillToolbarControls-BIaHc8_B.js} +1 -1
- package/dist/public/assets/{SourceEditor-CZlo1guK.js → SourceEditor-CFRWKhn6.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-DIOkTapK.js → TerminalWindowApp-BeR-4EEA.js} +1 -1
- package/dist/public/assets/{TextDocEditor-Bx7g-d1v.js → TextDocEditor-DzoiPoBH.js} +1 -1
- package/dist/public/assets/{ThreadView-C0W2YcdF.js → ThreadView-NfCjKVQa.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-DUAuqacD.js → TimelineDiffPane-BY_OH8iK.js} +1 -1
- package/dist/public/assets/{auth-state-cache-DRtxi4oE.js → auth-state-cache-DjjuYX83.js} +1 -1
- package/dist/public/assets/{client-version-CtIheFYi.js → client-version-BEkfNJSO.js} +1 -1
- package/dist/public/assets/{comment-chips-BLtdWJnE.js → comment-chips-Bk3eU3-K.js} +1 -1
- package/dist/public/assets/{config-provider-BMsi12sY.js → config-provider-CMsrN7B5.js} +1 -1
- package/dist/public/assets/{doc-undo-manager-BPMtEL01.js → doc-undo-manager-B9iAscTZ.js} +1 -1
- package/dist/public/assets/{index-PC05Sa-p.js → index-CqL8TQF5.js} +8 -8
- package/dist/public/assets/{pending-receive-nav-store-aX0-Bi4Q.js → pending-receive-nav-store-BIPhAGuN.js} +1 -1
- package/dist/public/assets/{progress-BCKVnfXK.js → progress-65clsNyb.js} +1 -1
- package/dist/public/assets/{selection-context-FjhkYfiH.js → selection-context-Daqo73OD.js} +1 -1
- package/dist/public/assets/{src-D4vpD-On.js → src-CsTdoUyS.js} +1 -1
- package/dist/public/assets/{telemetry-impl-necIgQyy.js → telemetry-impl-D_RVw4yU.js} +1 -1
- package/dist/public/assets/{telemetry-startup-B2Y0fFTN.js → telemetry-startup-DP4JWcg4.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-BeiThJwr.js → typing-burst-detector-CoSim2VF.js} +1 -1
- package/dist/public/assets/{use-activity-panel-2YPwXTEA.js → use-activity-panel-BMVu95Hl.js} +1 -1
- package/dist/public/assets/{use-open-skill-BtF9wYOl.js → use-open-skill-DpbstiSZ.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-_bz1Qovt.js → use-terminal-enabled-3W1PH2lM.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-UEnUD4Is.js → use-timeline-entry-diff-CmQbpKDX.js} +1 -1
- package/dist/public/index.html +17 -17
- package/dist/{registry-probes-S-xgoQk9.mjs → registry-probes-DNinJw94.mjs} +1 -1
- package/dist/{removal-file-path-EFIPuWF7.mjs → removal-file-path-dEH5rj0t.mjs} +1 -1
- package/dist/{repair-launch-json-B8--rr37.mjs → repair-launch-json-C_rI6C8x.mjs} +1 -1
- package/dist/{repair-mcp-configs-CR_NtEo8.mjs → repair-mcp-configs-CrbbtGdf.mjs} +1 -1
- package/dist/{src-Bmyq0TV_.mjs → src-B76XllMS.mjs} +1 -1
- package/dist/src-BRZrtrdn.mjs +1 -0
- package/dist/{start-DQN1j3rU.mjs → start-BJfBxH26.mjs} +3 -3
- package/dist/start-Dyk3zIJw.mjs +1 -0
- package/package.json +5 -5
- package/dist/constants-Dgd7Ce_a.mjs +0 -1
- package/dist/init-il6F84OQ.mjs +0 -1
- package/dist/loader-c-VB4xBM.mjs +0 -1
- package/dist/preview-CEfn7rBE.mjs +0 -1
- package/dist/public/assets/FeedbackForm-C2iTmSw9.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-DnN54IwH.js +0 -1
- package/dist/src-DPqF8mF0.mjs +0 -1
- package/dist/start-CrV21Rpg.mjs +0 -1
|
@@ -2095,7 +2095,7 @@ native-divergence-injected
|
|
|
2095
2095
|
`}}function Dht(e,t){return e.type===`object`?(e.children??[]).filter(e=>e.type===`property`&&e.children?.[0]?.value===t).length:0}function Oht(e,t){let{bom:n,body:r}=D9(e),i=(r.match(/\r\n/g)?.length??0)>(r.match(/(?<!\r)\n/g)?.length??0),a=r.endsWith(`
|
|
2096
2096
|
`),o=t.replace(/\r\n/g,`
|
|
2097
2097
|
`);return o=a?`${o.replace(/\n+$/,``)}\n`:o.replace(/\n+$/,``),i&&(o=o.replace(/\n/g,`\r
|
|
2098
|
-
`)),`${n}${o}`}function kht(e,t){let{bom:n,body:r}=D9(e),i=[],a=KI(r,i,{allowTrailingComma:!0,disallowComments:!1});if(!a||i.length>0||a.type!==`object`)return{kind:`declined`,reason:`unparseable`};if(Dht(a,t.topLevelKey)>1)return{kind:`declined`,reason:`duplicate-container`};let o=[t.topLevelKey,`open-knowledge`],s=qI(a,o);if(!s)return{kind:`no-entry`,raw:e,shell:e};let c=JI(s);if(!T9(c))return{kind:`declined`,reason:`foreign-entry`};let l=Gi(c);if(l.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let u=r,d=t.managedKeys.map(e=>({key:e,node:qI(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(Aht(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 Aht(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 jht(e,t,n){if(!n)return{kind:`declined`,reason:`no-native-writer`};let{bom:r,body:i}=D9(e),a;try{a=n.parseToObject(i)}catch{return{kind:`declined`,reason:`unparseable`}}let o=a[t.topLevelKey],s=T9(o)?o[`open-knowledge`]:void 0;if(s===void 0)return{kind:`no-entry`,raw:e,shell:e};if(!T9(s))return{kind:`declined`,reason:`foreign-entry`};let c=Gi(s);if(c.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let l;try{l=n.upsertEntry(i,`open-knowledge`,Object.fromEntries(t.managedKeys.map(e=>[e,Aht(t,e)])))}catch{return{kind:`declined`,reason:`unparseable`}}let u=Oht(e,l.text);return{kind:`managed`,raw:`${r}${i}`,shell:u,entry:s,descriptor:c.descriptor}}function O9(e,t,n){return e===null?{kind:`absent`}:Buffer.byteLength(e,`utf8`)>10485760?{kind:`declined`,reason:`oversize`}:t.format===`json`?kht(e,t):jht(e,t,n)}function Mht(e,t,n){let{bom:r,body:i}=D9(e),a=i;for(let e of t.managedKeys){let r=KI(a,[],{allowTrailingComma:!0,disallowComments:!1}),o=r?qI(r,[t.topLevelKey,`open-knowledge`,e]):void 0;o&&JSON.stringify(JI(o))===JSON.stringify(n[e])||(a=XI(a,YI(a,[t.topLevelKey,`open-knowledge`,e],n[e],{formattingOptions:Eht(i)})))}return`${r}${a}`}function Nht(e,t,n,r){if(t.format===`json`)return Mht(e,t,n);if(!r)return null;let{body:i}=D9(e),a=Object.fromEntries(t.managedKeys.map(e=>[e,n[e]]));try{return Oht(e,r.upsertEntry(i,`open-knowledge`,a).text)}catch{return null}}function Pht(e){let t=E9(e.target);return t?Nht(e.raw,t,e.entry,e.tomlEditor):null}function Fht(e){let t=E9(e.target);if(!t)return null;let n=O9(e.raw,t,e.tomlEditor);return n.kind===`managed`||n.kind===`no-entry`?n.shell:null}function Iht(e,t,n){return t.shell===n.shell?t.shell:t.shell===e.shell?n.shell:n.shell===e.shell?t.shell:null}function Lht(e){let t=E9(e.target);if(!t)return{kind:`declined`,reason:`unsupported-target`};let n={base:O9(e.layers.base,t,e.tomlEditor),head:O9(e.layers.head,t,e.tomlEditor),index:O9(e.layers.index,t,e.tomlEditor),worktree:O9(e.layers.worktree,t,e.tomlEditor),incoming:O9(e.layers.incoming,t,e.tomlEditor)},r=Object.values(n),i=r.find(e=>e.kind===`declined`);if(i?.kind===`declined`)return i;if(r.some(e=>e.kind===`absent`))return r.every(e=>e.kind===`absent`)?{kind:`unchanged`}:{kind:`declined`,reason:`file-deletion-ambiguity`};if(r.some(e=>e.kind===`no-entry`))return r.every(e=>e.kind===`no-entry`)?{kind:`declined`,reason:`no-entry`}:{kind:`declined`,reason:`entry-deletion-ambiguity`};let a=n;if(a.index.shell!==a.worktree.shell)return{kind:`declined`,reason:`index-worktree-divergence`};let o=Iht(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 t=Gi(e.runningEntry);t.kind===`recognized`&&s.push({entry:e.runningEntry,descriptor:t.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].
|
|
2098
|
+
`)),`${n}${o}`}function kht(e,t){let{bom:n,body:r}=D9(e),i=[],a=KI(r,i,{allowTrailingComma:!0,disallowComments:!1});if(!a||i.length>0||a.type!==`object`)return{kind:`declined`,reason:`unparseable`};if(Dht(a,t.topLevelKey)>1)return{kind:`declined`,reason:`duplicate-container`};let o=[t.topLevelKey,`open-knowledge`],s=qI(a,o);if(!s)return{kind:`no-entry`,raw:e,shell:e};let c=JI(s);if(!T9(c))return{kind:`declined`,reason:`foreign-entry`};let l=Gi(c);if(l.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let u=r,d=t.managedKeys.map(e=>({key:e,node:qI(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(Aht(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 Aht(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 jht(e,t,n){if(!n)return{kind:`declined`,reason:`no-native-writer`};let{bom:r,body:i}=D9(e),a;try{a=n.parseToObject(i)}catch{return{kind:`declined`,reason:`unparseable`}}let o=a[t.topLevelKey],s=T9(o)?o[`open-knowledge`]:void 0;if(s===void 0)return{kind:`no-entry`,raw:e,shell:e};if(!T9(s))return{kind:`declined`,reason:`foreign-entry`};let c=Gi(s);if(c.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let l;try{l=n.upsertEntry(i,`open-knowledge`,Object.fromEntries(t.managedKeys.map(e=>[e,Aht(t,e)])))}catch{return{kind:`declined`,reason:`unparseable`}}let u=Oht(e,l.text);return{kind:`managed`,raw:`${r}${i}`,shell:u,entry:s,descriptor:c.descriptor}}function O9(e,t,n){return e===null?{kind:`absent`}:Buffer.byteLength(e,`utf8`)>10485760?{kind:`declined`,reason:`oversize`}:t.format===`json`?kht(e,t):jht(e,t,n)}function Mht(e,t,n){let{bom:r,body:i}=D9(e),a=i;for(let e of t.managedKeys){let r=KI(a,[],{allowTrailingComma:!0,disallowComments:!1}),o=r?qI(r,[t.topLevelKey,`open-knowledge`,e]):void 0;o&&JSON.stringify(JI(o))===JSON.stringify(n[e])||(a=XI(a,YI(a,[t.topLevelKey,`open-knowledge`,e],n[e],{formattingOptions:Eht(i)})))}return`${r}${a}`}function Nht(e,t,n,r){if(t.format===`json`)return Mht(e,t,n);if(!r)return null;let{body:i}=D9(e),a=Object.fromEntries(t.managedKeys.map(e=>[e,n[e]]));try{return Oht(e,r.upsertEntry(i,`open-knowledge`,a).text)}catch{return null}}function Pht(e){let t=E9(e.target);return t?Nht(e.raw,t,e.entry,e.tomlEditor):null}function Fht(e){let t=E9(e.target);if(!t)return null;let n=O9(e.raw,t,e.tomlEditor);return n.kind===`managed`||n.kind===`no-entry`?n.shell:null}function Iht(e,t,n){return t.shell===n.shell?t.shell:t.shell===e.shell?n.shell:n.shell===e.shell?t.shell:null}function Lht(e){let t=E9(e.target);if(!t)return{kind:`declined`,reason:`unsupported-target`};let n={base:O9(e.layers.base,t,e.tomlEditor),head:O9(e.layers.head,t,e.tomlEditor),index:O9(e.layers.index,t,e.tomlEditor),worktree:O9(e.layers.worktree,t,e.tomlEditor),incoming:O9(e.layers.incoming,t,e.tomlEditor)},r=Object.values(n),i=r.find(e=>e.kind===`declined`);if(i?.kind===`declined`)return i;if(r.some(e=>e.kind===`absent`))return r.every(e=>e.kind===`absent`)?{kind:`unchanged`}:{kind:`declined`,reason:`file-deletion-ambiguity`};if(r.some(e=>e.kind===`no-entry`))return r.every(e=>e.kind===`no-entry`)?{kind:`declined`,reason:`no-entry`}:{kind:`declined`,reason:`entry-deletion-ambiguity`};let a=n;if(a.index.shell!==a.worktree.shell)return{kind:`declined`,reason:`index-worktree-divergence`};let o=Iht(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 t=Gi(e.runningEntry);t.kind===`recognized`&&s.push({entry:e.runningEntry,descriptor:t.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=Nht(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 Rht=q(`github-account`),zht=(e,t)=>{let n=rs(`git`,[`config`,`--get-urlmatch`,`credential`,e],cX({cwd:t,encoding:`utf-8`,timeout:5e3}));return n.error||n.status===null||n.status!==0&&n.status!==1?(Rht.warn({status:n.status,signal:n.signal,err:n.error,stderr:typeof n.stderr==`string`?g8(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 Bht(e){return e.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/]*@/i,`$1`)}function Vht(e){let t;for(let n of e.split(`
|
|
2099
2099
|
`)){let e=n.startsWith(`credential.username `)?n.slice(20).trim():void 0;e&&(t=e)}return t}function Hht(e,t={}){let n=x9e(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??zht)(Bht(e),t.cwd??process.cwd()),a=i?v9e(Vht(i)):void 0;return a?{host:r,login:a,source:`credential-config`}:{host:r,source:`active`}}function Uht(e={}){let t=e.ttlMs??6e4,n=e.now??Date.now,r;return{resolve(i){let a=S9e(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=Hht(a,{cwd:i,_readCredentialUrlMatch:e._readCredentialUrlMatch});return r={projectDir:i,url:a,account:s,expiresAt:o+t},s},invalidate(){r=void 0}}}function Wht(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}function Ght(e,t){return t===`anonymous`?Math.max(180,e):e}const k9=q(`sync-engine`),Kht=new Set(wht),A9=/^[0-9a-f]{40}$/i,qht=ac(ts);var j9=class extends Error{constructor(){super(`Sync paused while a Git operation is in progress or the index has unresolved conflicts`),this.name=`GitOperationInProgressError`}},Jht=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 Yht(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 Xht(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 Zht(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 Qht={syncScope:{pathBase:`content`}},M9={syncScope:{pathBase:`project`}},$ht=/(^|[/\\])index\.lock\b/i,egt=new Set(d);function tgt(e){return egt.has(e)}const ngt=new Set([`diverged-local-commits`,`external-changes-pending`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`]),rgt=[`no-push-permission`,`auth-error`,`git-index-locked`,`git-operation-in-progress`,`no-commits-yet`],igt=new Set(rgt),agt=new Set([...rgt,`external-changes-pending`]);function N9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function ogt(e){return new Promise(t=>{setTimeout(t,e)})}function P9(e){let t=qfe(e);if(t.kind!==`repository`)return!1;let n=t.repository.readHead();return n.kind===`branch`&&t.repository.readRef(n.ref).kind===`absent`}function sgt(e){return e.class===`network`&&e.subclass!==`429`&&e.subclass!==`5xx`}function cgt(e){return e>=8?36e5:e>=5?9e5:e>=3?3e5:0}const lgt=12e4;var ugt=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;rootOkOutsideContentWalk;pullIntervalSeconds;pushIntervalSeconds;mode;credentialConfig;cc1Broadcaster;onStateChange;setBatchInProgress;onAutoDisable;checkpointBeforeStrandedConversion;checkpointBeforeOverlayRestore;beforeRealIndexResetRetry;mcpTomlEditor;detectGh;detectGhAccounts;ghTokenSource;ghAccountResolver;declaredAccountWarnKey;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;authTier=`unknown`;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())uWe(t)&&e++;return e}pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;indexLockHitThisCycle=!1;lastLockNoticeKind;restingIndexLockPause;blockingPaths=[];currentBranch=`main`;cycleInFlight=null;hasRemote=!1;identityUnresolved=!1;statePath;conflicts;unsubscribeConflicts=null;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.rootOkOutsideContentWalk=uX(U(this.contentDir,H(this.projectDir,`.ok`))).startsWith(`..`),this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.mode=e.mode??(e.syncEnabled===!0?`full`:`off`),this.credentialConfig=e.credentialConfig??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.checkpointBeforeStrandedConversion=e.checkpointBeforeStrandedConversion,this.checkpointBeforeOverlayRestore=e.checkpointBeforeOverlayRestore,this.beforeRealIndexResetRetry=e._beforeRealIndexResetRetry,this.mcpTomlEditor=e.mcpTomlEditor,this.detectGh=e.detectGh,this.detectGhAccounts=e.detectGhAccounts,this.ghTokenSource=sht(e.detectGh),this.ghAccountResolver=Uht({_readCredentialUrlMatch:e._readCredentialUrlMatch}),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??_ht,this.statePath=W(eX(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||!J6(i,r)))){this.declaredAccountWarnKey=void 0;return}let a=`${t}\0${r}\0${e.source}\0${n===null?`none`:`fallback`}`;a!==this.declaredAccountWarnKey&&(n===null?k9.warn({host:t,declaredLogin:r,declaredSource:e.source},`[sync] declared GitHub account produced no gh token — git runs with no relayed credential`):k9.warn({host:t,declaredLogin:r,declaredSource:e.source,resolvedLogin:i},`[sync] declared GitHub account did not produce the gh token — using the active account`)),this.declaredAccountWarnKey=a}parkedOnAmbiguousNotFound(){return(this.state===`auth-error`||this.pausedReason===`auth-error`)&&(this.pushErrorCode===`auth-not-found-as-identity`||this.pullErrorCode===`auth-not-found-as-identity`)}activeGhLogin(e){if(this.detectGhAccounts)try{return this.detectGhAccounts(e)?.find(e=>e.active)?.login}catch(t){k9.warn({err:t,host:e},`[sync] detectGhAccounts failed — fallback identity stays unnamed`);return}}gitHandle(e){return Z4(this.projectDir,{credentialConfig:this.credentialConfig,gitIndexFile:e,ghToken:this.resolveRelayGhToken()??void 0,timeoutMs:12e4})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflicts.setBranch(e))}catch{}}catch(e){k9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),k9.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){k9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=dw(this.projectDir),n=t?H(t,`MERGE_HEAD`):null,r=n!==null&&G(n);await this.conflicts.pruneMergeNativeAgainstGit();let i=()=>this.conflicts.list().some(e=>e.kind===`merge-native`);if(r&&!i()){k9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){k9.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.subscribeToConflicts(),i()){this.transitionTo(`conflict`),k9.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}this.mode===`follow`&&await this.refreshAuthTier();let a=Wht(this.lastFetchUtc,this.currentPullIntervalSeconds()),o=Wht(this.lastPushOkUtc,this.pushIntervalSeconds);this.schedulePull(a>0?a:void 0),this.schedulePush(o>0?o:void 0),k9.info({branch:this.currentBranch,pullDelayMs:a,pushDelayMs:o},`[sync] started`)}stop(){this.unsubscribeConflicts?.(),this.unsubscribeConflicts=null,this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}setIntervals(e,t){let n=this.pullIntervalSeconds!==e,r=this.pushIntervalSeconds!==t;!n&&!r||(k9.info({pullFrom:this.pullIntervalSeconds,pullTo:e,pushFrom:this.pushIntervalSeconds,pushTo:t},`[sync] cycle intervals changed`),this.pullIntervalSeconds=e,this.pushIntervalSeconds=t,n&&this.pullTimer!==null&&this.schedulePull(),r&&this.pushTimer!==null&&this.schedulePush())}async setMode(e,t=`config`){if(this.mode===e)return;let n=this.mode;if(this.mode=e,k9.info({from:n,to:e,source:t},`[sync] mode changed`),e===`off`){this.cancelScheduledCycles(),await this.drainInFlightCycles(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}e===`follow`&&(await this.drainInFlightCycles(),this.cancelScheduledCycles(),await this.convertStrandedCommitsToOverlay()),this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(0),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}async setEnabled(e){await this.setMode(e?`full`:`off`)}cancelScheduledCycles(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null)}async drainInFlightCycles(){let e=Date.now();for(;this.cycleInFlight!==null;){if(Date.now()-e>3e4){k9.warn({cycleInFlight:this.cycleInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await _ae(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||P9(this.projectDir)?0:this.unpushedCommitCount(this.gitHandle())}async unpushedCommitCount(e){try{let t=await e.git.status();if(t.tracking)return t.ahead}catch{}try{let t=(await e.git.raw([`rev-list`,`--count`,`origin/${this.currentBranch}..HEAD`])).trim(),n=Number.parseInt(t,10);return Number.isFinite(n)?n:0}catch{return 0}}async convertStrandedCommitsToOverlay(){if(!this.hasRemote||P9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){k9.warn({err:e},`[sync] pull-only: could not probe stranded commits — skipping conversion`);return}if(t!==0){try{await this.checkpointBeforeStrandedConversion?.({branch:this.currentBranch,ahead:t})}catch(e){k9.warn({err:e},`[sync] pull-only: stranded-commit checkpoint failed — proceeding`)}try{let n=(await e.git.raw([`merge-base`,`HEAD`,`origin/${this.currentBranch}`])).trim();this.setBatchInProgress?.(!0);try{await X4(()=>e.git.raw([`reset`,`--mixed`,n]))}finally{this.setBatchInProgress?.(!1)}let r=await e.git.status();this.ahead=r.ahead,this.behind=r.behind,this.pausedReason=void 0,k9.info({ahead:t,behind:this.behind},`[sync] pull-only: folded stranded local commits into a working-tree overlay`)}catch(e){this.pausedReason=`diverged-local-commits`,k9.warn({err:e},`[sync] pull-only: stranded-commit conversion failed — leaving branch as-is`)}}}async notifyCredentialsChanged(){if(this.mode!==`off`&&(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.state===`auth-error`||this.pausedReason===`auth-error`)){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(0),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){if(e===`fetch`){await this.fetchOnly();return}if(this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.consecutiveContentions=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`||this.pausedReason===`git-index-locked`||this.pausedReason===`no-commits-yet`)&&(this.pausedReason=void 0,this.clearPullError()),this.parkedOnAmbiguousNotFound()&&(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()),this.probePushPermissionInternal(`refresh`),e===`pull`){await this.pullOnce();return}if(e===`push`){await this.pushOnce();return}this.state===`dormant`||this.state===`conflict`||this.state===`auth-error`?k9.warn({op:e,state:this.state,mode:this.mode,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):k9.info({op:e,state:this.state},`[sync] trigger(${e}) running`),await this.pushOnce(),await this.pullOnce(`sync`)}async pushOnce(){if(this.mode===`full`){await this.runPushCycle();return}await this.runOneShotPush()}async runOneShotPush(){if(this.cycleInFlight!==null){k9.info({cycleInFlight:this.cycleInFlight},`[sync] one-shot push refused — a cycle is already in flight`);return}if(this.state===`conflict`||this.state===`auth-error`){k9.info({state:this.state},`[sync] one-shot push refused — state=${this.state}`);return}if(this.conflictCount>0){k9.info({conflictCount:this.conflictCount},`[sync] one-shot push refused — unresolved conflicts hold the tree`);return}if(!this.hasRemote){k9.info({hasRemote:!1},`[sync] one-shot push refused — no remote`);return}if(P9(this.projectDir)){this.noteUnbornHeadRefusal();return}this.clearUnbornHeadPause();let e=this.state;this.cycleInFlight=`push`,this.beginIndexLockWatch(`push`);try{await this.doPushCycle(1)}finally{this.cycleInFlight=null,this.settleIndexLockPause(`push`),this.pushCycleLanded&&this.markRun();let t=this.currentState();t!==`conflict`&&t!==`auth-error`&&this.transitionTo(e),this.cc1Broadcaster?.signal(`sync-status`)}}async fetchOnly(){if(!this.hasRemote||P9(this.projectDir)||this.cycleInFlight!==null||this.fetchOnlyInFlight)return!1;this.fetchOnlyInFlight=!0;let e=this.gitHandle();try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.scheduleSaveState()}catch(e){return k9.debug({err:e},`[sync] panel-open fetch failed — counts left as they were`),!1}finally{this.fetchOnlyInFlight=!1}return await this.refreshDivergenceCounts(e),this.cc1Broadcaster?.signal(`sync-status`),!0}async refreshDivergenceCounts(e){try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch(e){k9.debug({err:e},`[sync] divergence-count refresh failed — keeping previous counts`)}}async pullOnce(e=`explicit`){let t=this.mode,n=await this.runOneShotPull(e);return k9.info({mode:t,outcome:n},`[sync] one-shot pull complete`),n}async runOneShotPull(e){if(this.cycleInFlight!==null)return k9.info({cycleInFlight:this.cycleInFlight},`[sync] one-shot pull refused — a cycle is already in flight`),this.recordPullOutcome(`refused`);if(this.state===`conflict`)return k9.info({state:this.state},`[sync] one-shot pull refused — the conflict resolver holds the tree`),this.recordPullOutcome(`refused`);if(!this.hasRemote||P9(this.projectDir))return k9.info({hasRemote:this.hasRemote},`[sync] one-shot pull refused — no remote, or no commits yet`),this.recordPullOutcome(`refused`);this.clearUnbornHeadPause();let t=this.mode,n=this.state,r=this.pausedReason;this.cycleInFlight=`pull`,this.beginIndexLockWatch(`pull`);try{return this.recordPullOutcome(await this.doPullCycle(e))}finally{this.cycleInFlight=null,this.settleIndexLockPause(`pull`),t===`off`?(ngt.has(this.pausedReason)||ngt.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?T9e(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.blockingPathsForStatus().length>0?{blockingPaths:this.blockingPathsForStatus()}:{},...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 X4(async()=>{await this.applyCommitIdentity(t);try{if(await t.git.raw([`add`,...ri(e)]),(await CJ(t.git,[`diff`,`--cached`,`--name-only`,...ri(e)])).length===0)return null;await t.git.raw([`commit`,`-m`,`Commit local changes before syncing`,...ri(e)])}catch(n){throw await t.git.raw([`reset`,...ri(e)]).catch(t=>{k9.warn({resetErr:t,files:e.length},`[sync] blocking-path index reset failed; paths may remain staged`)}),k9.error({err:n,files:e.length},`[sync] commit of blocking paths failed`),n}let n=(await t.git.revparse(`HEAD`)).trim();return this.clearBlockingPause(),k9.info({files:e.length},`[sync] committed overlapping paths at user request`),n})}clearBlockingPause(){this.blockingPaths=[],this.pausedReason=void 0,this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await att(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async applyCommitIdentity(e){let t=await att(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`;b6e(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=Y6(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,Zht(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,k9.info({caller:e,host:t.host,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let{account:n}=this.syncGhTarget(),r;try{r=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,transport:t.transport,account:n,detectGh:this.detectGh,detectGhAccounts:this.detectGhAccounts,tokenStore:this.tokenStore})}catch(t){k9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),r={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let i=Xht(r),a=this.pushPermission;this.pushPermission=i;let o=!1;return i.checkStatus===`denied`&&this.mode===`full`&&this.parkedOnAmbiguousNotFound()&&k9.info({reason:i.deniedReason,caller:e},`[sync] probe denial not applied — repository-not-found park is the more specific diagnosis`),i.checkStatus===`denied`&&this.mode===`full`&&!this.parkedOnAmbiguousNotFound()?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),o=!0,k9.info({reason:i.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):i.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),o=!0,k9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!o&&!Zht(a,i)&&this.cc1Broadcaster?.signal(`sync-status`),i}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,k9.info({mode:this.mode},`[sync] remote detected post-boot — re-evaluating state`),this.mode===`off`?this.transitionTo(`disabled`):(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()))}async probeRemote(){if(!G(H(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return k9.warn({err:e},`[sync] remote detection failed`),!1}}subscribeToConflicts(){this.unsubscribeConflicts===null&&(this.unsubscribeConflicts=this.conflicts.subscribe(()=>{let e=this.conflicts.list().some(e=>e.kind===`merge-native`);if(e&&this.state!==`conflict`){this.transitionTo(`conflict`),this.scheduleSaveState();return}!e&&this.state===`conflict`&&(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush(),this.scheduleSaveState())}))}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflicts.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush(0)))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{k9.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){if(this.mode!==`full`)return;this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??this.effectivePushDelayMs();this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{k9.error({err:e},`[sync] push cycle uncaught error`)})},t)}async resolveAuthTier(){if(this.resolveRelayGhToken()!==null)return`authenticated`;if(this.tokenStore)try{if((await this.tokenStore.get(this.syncGhTarget().host))?.token)return`authenticated`}catch(e){k9.warn({err:e},`[sync] auth-tier token-store lookup threw — treating as anonymous`)}return`anonymous`}async refreshAuthTier(){this.authTier=await this.resolveAuthTier()}currentPullIntervalSeconds(){return this.mode===`follow`?Ght(this.pullIntervalSeconds,this.authTier===`anonymous`?`anonymous`:`authenticated`):this.pullIntervalSeconds}effectivePullDelayMs(){let e=cgt(this.consecutivePullFailures),t=e>0?e/1e3:0;return N9(Math.max(t,this.currentPullIntervalSeconds()))}effectivePushDelayMs(){let e=cgt(this.consecutivePushFailures),t=e>0?e/1e3:0;return N9(Math.max(t,this.pushIntervalSeconds))}logContention(){let e={consecutiveContentions:this.consecutiveContentions,consecutivePushFailures:this.consecutivePushFailures,releasedConnectivityStreak:this.pushStreakIsConnectivity};this.consecutiveContentions>=3?k9.warn(e,`[sync] push repeatedly losing to remote contention — not backing off by design`):k9.info(e,`[sync] push still rejected after retry (contention) — scheduling next push at base cadence`)}bumpFailureCount(e,t=!1){e===`push`?(this.consecutiveContentions=0,this.consecutivePushFailures++,this.pushStreakIsConnectivity=(this.consecutivePushFailures===1||this.pushStreakIsConnectivity)&&t):this.consecutivePullFailures++}async runPullCycle(){if(this.cycleInFlight!==null){this.cycleInFlight===`push`&&this.pullTimer===null&&this.schedulePull();return}if(this.state!==`dormant`&&this.state!==`disabled`&&this.state!==`auth-error`){if(this.state===`conflict`){this.schedulePull();return}if(P9(this.projectDir)){this.schedulePull();return}this.clearUnbornHeadPause(),this.cycleInFlight=`pull`,this.beginIndexLockWatch(`pull`);try{this.mode===`follow`&&await this.refreshAuthTier(),this.recordPullOutcome(await this.doPullCycle(this.mode===`full`?`sync`:`explicit`))}finally{this.cycleInFlight=null,this.settleIndexLockPause(`pull`),this.schedulePull()}}}async doPullCycle(e){if(this.pausedReason===`git-operation-in-progress`)try{await this.assertNoGitOperationInProgress()}catch(e){return e instanceof j9?(this.handleGitOperationRefusal(e,`pull`),`refused`):(this.handleError(C9(e instanceof Error?e:Error(String(e))),`pull`),`error`)}let t=this.gitHandle(),n;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!e||e===`HEAD`)return this.transitionTo(`disabled`),this.pausedReason=`detached-head`,k9.warn({},`[sync] detached HEAD — pausing sync`),`refused`;n=e,this.currentBranch=n}catch(e){return this.handleError(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&&(k9.info({cleared:this.consecutivePushFailures},`[sync] fetch succeeded — releasing connectivity-class push backoff`),this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.schedulePush())}catch(e){let t=C9(e instanceof Error?e:Error(String(e)));return this.handleError(t,`pull`),`error`}if(await this.refreshDivergenceCounts(t),this.behind>0&&e===`explicit`){let e=await this.doPullCycleB1(t,n);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);try{await this.commitDirtyContentFilesToHead(t,`pull`);let e=await this.prepareForMerge(t,n);if(!e.proceed)return`refused`;let r=!0,i=!0;try{await this.applyCommitIdentity(t),await t.git.merge([`origin/${n}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.pausedReason===`external-changes-pending`&&this.clearBlockingPause(),this.transitionTo(`idle`)}finally{e.needsStashPop&&(r=await this.popPreMergeStash(t)),i=this.restoreReconciledMcpOverlays(e.reconciled)}if(!r)throw Error(`failed to replay pre-merge working-tree state`);if(!i)throw Error(`failed to restore reconciled MCP overlays`);return await this.persistReconciledMcpEntries(e.reconciled),this.scheduleSaveState(),`succeeded`}catch(e){if(e instanceof j9)return this.handleGitOperationRefusal(e,`pull`),`refused`;let t=C9(e instanceof Error?e:Error(String(e)));return t.class===`semantic`&&t.subclass===`merge-conflict`?(await this.handleMergeConflict(),this.state===`conflict`?`conflict`:this.pullError?`error`:`succeeded`):(this.handleError(t,`pull`),`error`)}finally{this.setBatchInProgress?.(!1)}}return this.transitionTo(`idle`),this.scheduleSaveState(),this.behind===0?`up-to-date`:`conflict`}async doPullCycleB1(e,t){if(this.transitionTo(`pulling`),this.ahead>0)return this.clearPullError(),this.pausedReason=`diverged-local-commits`,this.transitionTo(`idle`),k9.warn({ahead:this.ahead,behind:this.behind},`[sync] pull-only: local history diverged — not fast-forwardable, skipping cycle`),`refused`;let n,r;try{n=(await e.git.revparse([`HEAD`])).trim();let i=await CJ(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await CJ(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]));r=i.filter(e=>a.has(e))}catch(e){return this.handleError(C9(e instanceof Error?e:Error(String(e))),`pull`),`error`}let i=new Map;for(let e of this.conflicts.list())e.kind===`working-tree`&&i.set(e.file,e);let a;try{a=await this.planOverlapReconciliation(e,t,n,r,i)}catch(e){return this.handleError(C9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.setBatchInProgress?.(!0);try{if(r.length>0){try{await this.checkpointBeforeOverlayRestore?.({branch:t,paths:r.length})}catch(e){k9.warn({err:e,paths:r.length},`[sync] pull-only: overlay checkpoint failed before restore — proceeding`)}try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,...ri(r)])}catch(e){return k9.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 n=await this.fastForwardOnly(e,t);if(!n.ok){try{this.applyOverlayPlan(a.mineRestore,a.deletions)}catch(e){return k9.error({err:e,refusal:n.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 n.timedOut?(k9.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(C9(Error(`git merge --ff-only timed out after ${lgt}ms`)),`pull`),`error`):(n.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),k9.warn({refusal:n.refusal,stderr:n.stderr.slice(0,200)},`[sync] pull-only: fast-forward refused — skipping cycle`),`refused`)}try{this.applyOverlayPlan(a.writes,a.deletions)}catch(e){return k9.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 a.upserts)this.conflicts.raise(e);for(let e of a.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 i=await this.countStandingOverlay(e);return k9.info({created:a.newConflicts.length,autoCombined:a.autoCombined.length,autoDissolved:a.dissolved.length,autoRestored:a.autoRestored.length,overlayStock:i},`[sync] pull-only: fast-forwarded to origin tip`),a.newConflicts.length>0?`conflict`:`succeeded`}finally{this.setBatchInProgress?.(!1)}}async fastForwardOnly(e,t){try{return await qht(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,`origin/${t}`],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:lgt}),{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:Yht({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([`origin/${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),k9.warn({err:e,path:p},`[sync] pull-only: unexpected error probing origin for a deleted overlay — deferring reconcile`);continue}s.push(p),m&&l.push(p);continue}if(!this.isContentConflictPath(p)){s.push(p);continue}f.push(p),m&&l.push(p);continue}let h;try{h=K(H(this.projectDir,p))}catch{continue}o.push({path:p,bytes:h});let g=h.toString(`utf-8`),_=null;try{_=await e.git.raw([`show`,`origin/${t}:${p}`])}catch(e){this.classifyRefReadFailure(e)===`error`&&k9.warn({err:e,path:p},`[sync] pull-only: unexpected error reading origin blob — keeping overlay, deferring reconcile`),_=null}if(_!==null&&_===g){m&&l.push(p);continue}if(_!==null&&Kht.has(p)){let t=await this.readMcpGitBlob(e,n,p),r=Lht({target:p,layers:{base:t,head:t,index:await this.readMcpGitBlob(e,``,p),worktree:g,incoming:_},tomlEditor:this.mcpTomlEditor});if(r.kind===`resolved`){r.raw!==_&&a.push({path:p,bytes:Buffer.from(r.raw,`utf8`)}),k9.info({event:`mcp-config-reconcile`,target:p,outcome:`auto-resolved`},`[sync] pull-only: auto-resolved OpenKnowledge MCP entry overlap`);continue}r.kind===`declined`&&k9.warn({event:`mcp-config-reconcile`,target:p,outcome:`declined`,reason:r.reason},`[sync] pull-only: declined OpenKnowledge MCP entry reconciliation`)}if(_===null||!this.isContentConflictPath(p)){a.push({path:p,bytes:h});continue}let v=m?r.baseSha:await this.gitBlobSha(e,`${n}:${p}`),y=v?await this.gitBlobContent(e,v):``,b=Kee(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,`origin/${t}:${p}`);if(x===void 0){k9.warn({path:p},`[sync] pull-only: could not pin origin blob for a collision — keeping overlay, deferring`);continue}c.push({kind:`working-tree`,file:p,theirsSha:x,...v===void 0?{}:{baseSha:v}}),m||u.push(p)}return{writes:a,mineRestore:o,deletions:s,upserts:c,dissolved:l,newConflicts:u,autoCombined:d,autoRestored:f}}applyOverlayPlan(e,t){let n={allowShareableOkArtifact:SX};for(let{path:t,bytes:r}of e)lJ(gZ(H(this.projectDir,t),this.projectDir,n),r);for(let e of t){let t=H(this.projectDir,e);gZ(t,this.projectDir,n);try{mJ(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=H(this.projectDir,e),n=uX(U(this.contentDir,t));return!n.startsWith(`..`)&&EY(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 CJ(e.git,[`diff-index`,`--name-only`,`HEAD`])).filter(e=>this.isContentConflictPath(e)).length}catch{return null}}async runPushCycle(){if(this.mode===`full`&&this.state!==`dormant`&&this.state!==`disabled`&&this.state!==`conflict`&&this.state!==`auth-error`){if(this.conflictCount>0){this.schedulePush();return}if(P9(this.projectDir)){this.hasRemote&&this.noteUnbornHeadRefusal(),this.schedulePush();return}if(this.clearUnbornHeadPause(),this.cycleInFlight!==null){this.cycleInFlight===`pull`&&this.pushTimer===null&&this.schedulePush();return}this.cycleInFlight=`push`,this.beginIndexLockWatch(`push`);try{await this.doPushCycle(1)}finally{this.cycleInFlight=null,this.settleIndexLockPause(`push`),this.pushCycleLanded&&this.markRun(),this.schedulePush()}}}async doPushCycle(e=0){this.pushCycleLanded=!1;let t=H(Hs(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),n=null;try{let e=this.gatherContentFilesSync(),r=await this.snapshotPromisedPaths(),i=new Set;await X4(async()=>{await this.assertNoGitOperationInProgress(),this.transitionTo(`pushing`);try{let r=this.gitHandle(t);if(P9(this.projectDir)){k9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let a;try{a=(await r.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){k9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(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){k9.info({contentFileCount:e.length,headSha:a},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=a,this.lastSyncUtc=new Date().toISOString(),this.pushCycleLanded=!0,this.consecutivePushFailures=0,this.consecutiveContentions=0,this.pushStreakIsConnectivity=!1,this.clearPushError(),this.transitionTo(`idle`);return}k9.info({headSha:a,upstreamSha:t},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let i=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),i=!0}catch{}i?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=a;return}let f=[],p=[];try{let t=await CJ(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)??uX(U(this.contentDir,H(this.projectDir,e)));t&&!t.startsWith(`..`)&&p.push(t)}}}catch{f=e.map(e=>e.projectRelPath).concat(l),p=e.map(e=>e.contentRelPath)}let m=this.buildCommitMessage(p);await this.applyCommitIdentity(r);let h=(await r.git.raw([`commit-tree`,u,`-p`,a,`-m`,m])).trim();if(!h||!A9.test(h)){k9.warn({raw:h},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await r.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,h,a]),await this.resetRealIndexForPaths(f,`push`);for(let e of f)i.add(e);let g=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),g=!0}catch{}g?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=h}finally{await this.healStaleRealIndex(r,i)}}),n&&(this.lastPushedSha=n,this.lastSyncUtc=new Date().toISOString(),this.pushCycleLanded=!0,this.ahead=0,this.consecutivePushFailures=0,this.consecutiveContentions=0,this.pushStreakIsConnectivity=!1,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){if(t instanceof j9){this.handleGitOperationRefusal(t,`push`);return}let n=t instanceof Error?t:Error(String(t));n instanceof Jht&&k9.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){k9.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);let t=`fetch`;try{await e.git.fetch(`origin`),t=`push`,await this.commitDirtyContentFilesToHead(e,`push`);let n=await this.prepareForMerge(e,this.currentBranch);if(!n.proceed){this.setBatchInProgress?.(!1);return}let r=!0,i=!0;try{await this.applyCommitIdentity(e),t=`merge`,await e.git.merge([`origin/${this.currentBranch}`]),t=`push`}finally{n.needsStashPop&&(r=await this.popPreMergeStash(e)),i=this.restoreReconciledMcpOverlays(n.reconciled)}if(!r)throw Error(`failed to replay pre-merge working-tree state`);if(!i)throw Error(`failed to restore reconciled MCP overlays`);await this.persistReconciledMcpEntries(n.reconciled)}catch(e){if(e instanceof j9){this.handleGitOperationRefusal(e,`push`);return}let n=C9(e instanceof Error?e:Error(String(e)));if(n.class===`semantic`&&n.subclass===`merge-conflict`)await this.handleMergeConflict();else{let r=t===`merge`||t===`fetch`?`pull`:`push`;k9.warn({err:e,stage:t},`[sync] push retry error detail`),this.handleError(n,r)}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{Fs(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(Hs(),`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 CJ(o.git,[`diff-tree`,`--name-only`,`-r`,n,l])}catch{u=r.map(e=>e.projectRelPath).concat(c)}await this.applyCommitIdentity(o);let d=(await o.git.raw([`commit-tree`,l,`-p`,n,`-m`,`Auto-save: interim before merge`])).trim();return!d||!A9.test(d)?(k9.warn({raw:d},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,d,n]),await this.resetRealIndexForPaths(u,t,e),d)}finally{try{Fs(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`,`origin/${t}`])).trim()}catch(e){return k9.warn({err:e,branch: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,`origin/${t}`,n)]),c=null;try{c=K(H(this.projectDir,n),`utf8`)}catch{}return Lht({target:n,layers:{base:i,head:a,index:o,worktree:c,incoming:s},tomlEditor:this.mcpTomlEditor})}async prepareForMerge(e,t){let n=[],r;try{r=await CJ(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return k9.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1,reconciled:n}}if(r.length===0)return{proceed:!0,needsStashPop:!1,reconciled:n};let i;try{i=new Set(await CJ(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return k9.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1,reconciled:n}}let a=r.filter(e=>i.has(e)),o=Kht,s=a.filter(e=>o.has(e));if(s.length>0){let r=await Promise.all(s.map(async n=>({path:n,plan:await this.planTrackedMcpOverlap(e,t,n)}))),i=r.find(({plan:e})=>e.kind===`declined`),c=a.some(e=>!o.has(e));if(!i&&!c){for(let{path:e,plan:t}of r)t.kind===`resolved`&&(n.push({path:e,raw:t.raw,winnerEntry:t.winnerEntry}),k9.info({event:`mcp-config-reconcile`,target:e,outcome:`auto-resolved`},`[sync] auto-resolved OpenKnowledge MCP entry overlap`));a=a.filter(e=>!o.has(e))}else i?k9.warn({event:`mcp-config-reconcile`,target:i.path,outcome:`declined`,reason:i.plan.kind===`declined`?i.plan.reason:void 0},`[sync] declined OpenKnowledge MCP entry reconciliation`):c&&k9.info({event:`mcp-config-reconcile`,targets:s,outcome:`suppressed`,reason:`other-blocking-path`},`[sync] suppressed MCP entry reconciliation because another path blocks the merge`)}if(a.length>0){let e=a.slice(0,3).join(`, `),t=a.length>3?`, +${a.length-3} more`:``;return this.blockingPaths=a,this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutivePullFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),k9.warn({files:a},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1,reconciled:[]}}if(n.length>0)try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,...ri(n.map(e=>e.path))])}catch(e){return k9.warn({err:e},`[sync] could not isolate reconciled MCP paths from pre-merge stash`),this.pullError=`Sync paused — OpenKnowledge could not safely isolate local MCP launcher changes before merging.`,this.pausedReason=`external-changes-pending`,this.blockingPaths=[],this.transitionTo(`idle`),this.scheduleSaveState(),{proceed:!1,needsStashPop:!1,reconciled:[]}}let c=new Set(n.map(e=>e.path));if(r.every(e=>c.has(e)))return{proceed:!0,needsStashPop:!1,reconciled:n};let l=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,l])}catch(e){return k9.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1,reconciled:n}}return{proceed:!0,needsStashPop:!0,reconciled:n}}restoreReconciledMcpOverlays(e){let t=!0;for(let n of e)try{let e=gZ(H(this.projectDir,n.path),this.projectDir),t=null;try{t=K(e,`utf8`)}catch(e){k9.warn({err:e,path:n.path},`[sync] could not read MCP config before restoring reconciled overlay`)}t!==n.raw&&lJ(e,n.raw,`utf8`)}catch(e){t=!1,k9.warn({err:e,path:n.path},`[sync] could not restore reconciled MCP overlay`)}return t}async popPreMergeStash(e){try{return await e.git.raw([`stash`,`pop`]),!0}catch(e){return k9.warn({err:e},`[sync] stash pop failed — stash remains on stack`),!1}}async assertNoGitOperationInProgress(){if(this.hasGitOperationInProgress()||(await CJ(this.gitHandle().git,[`diff`,`--name-only`,`--diff-filter=U`])).length>0||this.hasGitOperationInProgress())throw new j9;this.pausedReason===`git-operation-in-progress`&&(this.pausedReason=void 0,this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}handleGitOperationRefusal(e,t){this.state===`conflict`||this.conflictCount>0?this.transitionTo(`conflict`):(this.pausedReason=`git-operation-in-progress`,t===`push`?this.clearPushError():this.clearPullError(),(this.state===`pushing`||this.state===`pulling`||this.state===`fetching`)&&this.transitionTo(`idle`)),k9.error({event:`git-operation-refusal`,err:e,op:t,branch:this.currentBranch},`[sync] cycle refused because a Git operation holds the tree — finish or abort it to resume sync`),this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}hasGitOperationInProgress(){let e=dw(this.projectDir);return!e||[`MERGE_HEAD`,`CHERRY_PICK_HEAD`,`REVERT_HEAD`,`rebase-merge`,`rebase-apply`].some(t=>G(H(e,t)))}async persistReconciledMcpEntries(e){if(e.length!==0){if(this.hasGitOperationInProgress())throw new j9;await X4(async()=>{let t=H(Hs(),`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=Pht({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,...ri([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),Is(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=Fht({target:o.path,raw:l,tomlEditor:this.mcpTomlEditor}),m=Fht({target:o.path,raw:o.raw,tomlEditor:this.mcpTomlEditor}),h=p!==null&&p===m?l:o.raw,g=`${t}.replay-${r}`;n.push(g),Is(g,h,`utf8`);let _=(await i.git.raw([`hash-object`,`-w`,g])).trim();s.push({path:o.path,mode:u,blobSha:_,raw:h})}let c=(await i.git.raw([`write-tree`])).trim();if(c===(await i.git.raw([`rev-parse`,`${a}^{tree}`])).trim())return;await this.applyCommitIdentity(i);let l=(await i.git.raw([`commit-tree`,c,`-p`,a,`-m`,`Update OpenKnowledge MCP launcher`])).trim();if(!A9.test(l))throw Error(`commit-tree returned an invalid SHA`);try{await i.git.raw([`update-ref`,`refs/heads/${o}`,l,a])}catch(e){k9.info({event:`mcp-config-reconcile`,outcome:`ref-race`,branch:o,err:e},`[sync] skipped MCP launcher commit because the branch moved`);return}try{for(let e of s){await r.git.raw([`update-index`,`--add`,`--cacheinfo`,`${e.mode},${e.blobSha},${e.path}`]);let t=gZ(H(this.projectDir,e.path),this.projectDir);K(t,`utf8`)!==e.raw&&lJ(t,e.raw,`utf8`)}}catch(t){k9.warn({event:`mcp-config-reconcile`,outcome:`overlay-replay-failed`,err:t},`[sync] MCP overlay replay failed; resetting the affected index entries`),await this.resetRealIndexForPaths(s.map(e=>e.path),`mcp-reconcile`),this.restoreReconciledMcpOverlays(e)}k9.info({event:`mcp-config-reconcile`,outcome:`persisted-entry-commit`},`[sync] persisted OpenKnowledge MCP launcher entry commit`)}finally{for(let e of n)try{Fs(e)}catch{}try{Fs(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 CJ(e.git,[`ls-files`,`--others`,`--ignored`,`--exclude-standard`,...ri(a)]);for(let e of t)n.add(e)}catch(e){r=!1,k9.warn({err:e},`[sync] ignored-path probe failed — staging unfiltered without -f`)}}n.size>0&&k9.info({count:n.size,sample:[...n].slice(0,5)},`[sync] skipping gitignored untracked path(s) — in content scope but excluded from git`);let i=r?t.filter(e=>!n.has(e.projectRelPath)):t,a=e=>e.startsWith(`.ok/`)||e.includes(`/.ok/`),o=r?i.filter(e=>a(e.projectRelPath)):[],s=r?i.filter(e=>!a(e.projectRelPath)):i;for(let[t,n]of[[[`add`],s],[[`add`,`-f`],o]])for(let r=0;r<n.length;r+=100){let i=n.slice(r,r+100).map(e=>e.projectRelPath);await e.git.raw([...t,...ri(i)])}return i}gatherContentFilesSync(){let e=[],t=(e,t)=>{throw new Jht(uX(U(this.projectDir,t))||`.`,e)},n=(r,i,a,o)=>{let s;try{s=ks(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=uX(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=uX(U(i,s));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t,a)){let t=uX(U(this.contentDir,s)),n=uX(U(this.projectDir,s));e.push({contentRelPath:t,projectRelPath:n})}}}};if(G(this.contentDir)&&n(this.contentDir,this.contentDir,Qht),this.rootOkOutsideContentWalk){let e=H(this.projectDir,`.ok`);G(e)&&!this.contentFilter.isDirExcluded(`.ok`,M9)&&n(e,this.projectDir,M9,t)}return e}isSyncScopedPath(e){let t=H(this.projectDir,e),n=uX(U(this.contentDir,t)),r=!n.startsWith(`..`)&&!this.contentFilter.isExcluded(n,Qht),i=this.rootOkOutsideContentWalk&&e.startsWith(`.ok/`)&&!this.contentFilter.isExcluded(e,M9);return r||i}async listHeadContentPaths(e,t){let n=new Set;try{let r=await CJ(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`,...ri(r)])}}async snapshotPromisedPaths(){let e,t;try{let{git:n}=this.gitHandle();e=await wJ(n,bJ),t=new Set(await CJ(n,[`diff`,`--name-only`,`--diff-filter=U`]))}catch(e){return k9.warn({event:`snapshot-read-failed`,err:e,branch:this.currentBranch},`[sync] could not read the real index before the push cycle — skipping stale-index self-heal`),[]}let n=[];for(let r of e)if(!t.has(r.path)&&this.isSyncScopedPath(r.path)&&(n.push(r.path),n.length===100))break;return n}async healStaleRealIndex(e,t){let n=new Set(e.filter(e=>!t.has(e)));if(n.size===0)return;if(this.hasGitOperationInProgress()){k9.warn({event:`self-heal-skipped-git-operation`,branch:this.currentBranch,pathCount:n.size,paths:[...n].slice(0,20)},`[sync] self-heal skipped — a Git operation now holds the tree, so the promised paths stay listed until it ends`);return}let r=this.gitHandle(),i,a;try{i=(await TJ(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 CJ(r.git,[`diff`,`--name-only`,`HEAD`])}catch(e){k9.error({event:`self-heal-skipped`,branch:this.currentBranch,pathCount:n.size,paths:[...n].slice(0,20),err:e},`[sync] self-heal could not compare the real index against HEAD — the promised paths stay listed in the real index`);return}let o=new Set(a),s=[...new Set(i.filter(e=>n.has(e)&&!o.has(e)))];s.length!==0&&(await this.resetRealIndexForPaths(s,`push`,r),k9.warn({event:`self-heal-applied`,branch:this.currentBranch,pathCount:s.length,paths:s.slice(0,20)},`[sync] self-heal cleared stale real-index entries left behind by an earlier push cycle`))}async resetRealIndexForPaths(e,t,n){if(e.length===0)return;let r=n??this.gitHandle(),i=[...new Set(e)];for(let e=0;e<i.length;e+=100){let n=i.slice(e,e+100);await this.resetRealIndexBatch(r,n,t)}}async resetRealIndexBatch(e,t,n){let r;try{await e.git.raw([`reset`,`HEAD`,...ri(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 ogt(N9(.05));try{await e.git.raw([`reset`,`HEAD`,...ri(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?k9.warn(s,`[sync] stale-index reset needed a second attempt — it succeeded, so the panel listing is current`):k9.error(s,`[sync] stale-index reset failed — the panel listing may stay stale`),!o&&i.class===`local`&&i.subclass===`index-lock`&&this.noteIndexLockEncountered(n,i)}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=this.gitHandle(),t=[];try{t=await CJ(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){k9.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){k9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t)this.isContentConflictPath(e)?n.push(e):r.push(e);let i=[],a=uX(U(this.projectDir,Sk(`project`,this.projectDir)));for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,...ri([t])]),await e.git.raw([`add`,...ri([t])]),t.toLowerCase()===a.toLowerCase()?k9.warn({file:t},`[sync] auto-resolved .ok/config.yml conflict with theirs: local project config edits were overwritten by the remote version`):k9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){k9.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),i.push({file:t,err:e})}if(i.length>0){let t=i.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){k9.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let n=t.slice(0,3).join(`, `),r=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${n}${r}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutivePullFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),k9.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(n.length>0){for(let e of n)this.conflicts.raise({kind:`merge-native`,file:e});this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),k9.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await this.applyCommitIdentity(e),await e.git.raw([`commit`,`--no-edit`]);let n=dw(this.projectDir);t=n===null||!G(H(n,`MERGE_HEAD`))}catch(e){k9.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),k9.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){k9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullError=`Sync paused — could not finalize the merge. Retry sync to try again.`,this.transitionTo(`idle`),k9.warn({},`[sync] could not finalize merge after auto-resolving conflicts — merge aborted`)}}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){if(e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),k9.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`)this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`;else if(e.class===`semantic`&&e.subclass===`protected-branch`)this.mode=`off`,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`);else if(e.class===`local`&&e.subclass===`index-lock`)this.bumpFailureCount(t),(this.state===`pushing`||this.state===`pulling`||this.state===`fetching`)&&this.transitionTo(`idle`),this.noteIndexLockEncountered(t,e);else if(e.class===`local`&&e.subclass===`dirty-tree`){if(this.state===`conflict`||this.conflictCount>0){this.transitionTo(`conflict`);return}this.bumpFailureCount(t),this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)}else e.retryable?(this.bumpFailureCount(t,sgt(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 $ht.test(`${e.message}\n${e.rawStderr??``}`)}noteIndexLockEncountered(e,t){let n=this.holdsIndexLock(t),r=n?`index-locked`:`git-lock-held`;if(this.lastLockNoticeKind!==r){this.lastLockNoticeKind=r;let i={event:r,op:e,branch:this.currentBranch,errorClass:t.class,errorSubclass:t.subclass};n?k9.error(i,`[sync] index locked — another program is holding .git/index.lock, so sync cannot update it`):k9.error(i,`[sync] a git lock file blocked the operation — the held lock is not .git/index.lock, so the listing is not paused on it`)}n&&(this.indexLockHitThisCycle=!0,this.pausedReason!==`git-index-locked`&&(this.pausedReason=`git-index-locked`,this.cc1Broadcaster?.signal(`sync-status`)))}noteUnbornHeadRefusal(){this.pausedReason!==`no-commits-yet`&&k9.error({event:`unborn-head-refusal`,branch:this.currentBranch},`[sync] push refused — this repository has no commits yet, so there is nothing to send`),this.pausedReason=`no-commits-yet`,this.cc1Broadcaster?.signal(`sync-status`)}clearUnbornHeadPause(){this.pausedReason===`no-commits-yet`&&(this.pausedReason=void 0,this.cc1Broadcaster?.signal(`sync-status`))}settleIndexLockPause(e){this.otherLegInFlight(e)||this.indexLockHitThisCycle||this.pausedReason===`git-index-locked`&&(this.pausedReason=this.restingIndexLockPause,this.cc1Broadcaster?.signal(`sync-status`))}currentState(){return this.state}markRun(){this.lastPushOkUtc=new Date().toISOString(),this.saveStateNow(),this.cc1Broadcaster?.signal(`sync-status`)}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,k9.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null);try{let e=igt.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`;lJ(n,JSON.stringify(t,null,2),`utf-8`),fJ(n,this.statePath)}catch(e){k9.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(G(this.statePath))try{let e=K(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastPullOkUtc=t.lastPullOkUtc??null,this.lastPushOkUtc=t.lastPushOkUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutivePullFailures=t.consecutiveFailures??0,this.consecutivePushFailures=t.consecutivePushFailures??0,this.pushStreakIsConnectivity=t.pushStreakIsConnectivity??!1;let n=typeof t.pausedReason==`string`?t.pausedReason:void 0,r=n!==void 0&&tgt(n)?n:void 0;n!==void 0&&r===void 0&&n.length>0&&k9.warn({event:`paused-reason-unrecognized`,pausedReason:n},`[sync] persisted pause reason is not one this build knows — dropping it and continuing without a pause`),this.pausedReason=agt.has(r)?void 0:r}catch(e){k9.warn({err:e},`[sync] failed to load sync state`)}}};const dgt=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function fgt(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(LY(e)||RY(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&dgt.test(n)&&(r[`mount.id`]=n);try{let e=()=>{zq(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),Ga.with(Ya.extract(Ga.active(),r),e)}else e()}catch(e){q(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let F9=!1;function pgt(){if(F9)return;let e=Aae;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){F9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),F9=!0}catch(e){q(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const mgt=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),hgt=(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function ggt(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=rs(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],cX({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(`
|
|
2100
2100
|
`)){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(!$X(a,t))continue;let s=RZ(a,t);i.has(s)||G(a)&&i.set(s,o)}return i}function _gt(e){pgt();let t=e.ingressPolicy??D1({}),{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=q(`server`),x=Pft(W(n)),S=null,C=o9(r).branch??`main`,w=new Y4(C,{persistencePath:H(eX(r),`stale-external-writes.json`),onStaleExternalWriteChange:()=>{S?.signal(`sync-status`),N()},onStoreRefused:e=>{xn(e,`refused-store-mark`)===`lost`&&b.warn({docName:e},`[rescue] refused-store content for ${e} was not durably buffered at refusal time`)},fileForDocName:e=>U(r,QX(e,n)).replaceAll(`\\`,`/`),hasResolvedExtension:NY}),T=()=>w.getActiveBranch(),E=e=>w.getReconciledBase(e),D=(e,t)=>w.setReconciledBase(e,t),O=e=>w.deleteReconciledBase(e),k=e=>w.switchReconciledBaseScope(e),A=e=>w.setBatchInProgress(e),ee=e=>{A(e),e||Te.flushDeferredStores(`within-branch`).catch(e=>{b.error({err:e},`[persistence] deferred store drain failed after batch`)})},j=()=>w.isBatchInProgress(),M=new KKe({projectDir:r,contentDir:n,branch:C,signal:{signal:e=>S?.signal(e)},io:{gitRaw:async e=>Z4(r,{credentialConfig:[],timeoutMs:3e4}).git.raw(e),writeProjectFileUntracked:(e,t)=>lJ(e,t,`utf-8`),unlinkProjectFile:e=>mJ(e),applyResolvedContent:async(e,t,n)=>{jZ(t,EZ(n)),await vk(t,n,{fs:yJ}),De.documents.get(e)&&tn(e,n),D(e,n),await Se.recordDiskUpsert(e,n)},readLiveContent:e=>en(e),finalizeReconcileResolution:async(e,t,n)=>{e.reason===`stale-external-write`&&(t===`mine`||t===`content`?w.recordDisplacedVersion(n,e.stages.theirs):w.clearDisplacedVersions(n),w.clearStaleExternalWrite(n));let r=De.documents.get(n),i=r?.getMap(`lifecycle`);t===`delete`?(O(n),await Se.recordDiskDelete(n),i?.set(`status`,`deleted-upstream`),i?.delete(`reason`),i?.delete(`detectedAt`),r&&De.closeConnections(n),qt(n),At(n)):i?.get(`reason`)===e.reason&&(i.delete(`status`),i.delete(`reason`),i.delete(`detectedAt`)),et(`files`)}}});function N(){for(let e of w.listStaleExternalWrites()){let t=E(e.docName)??e.diskContent;M.raise({kind:`reconcile`,file:e.file,reason:`stale-external-write`,detectedAt:e.detectedAt,stages:{base:t,ours:e.retainedContent??t,theirs:e.diskContent}})}}N();function te(e){let t=pk({absPath:Sk(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});if(!t.valid){let n=ta(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});b.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return t.value.content.attachmentFolderPath??`./`}function P(){let e=pk({absPath:Sk(`project-local`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)}),t=Bee(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||b.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let n=pk({absPath:Sk(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});return n.valid||b.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:wte(n.value.autoSync?.default)??`off`,source:`committed-default`}}function ne(){let e=pk({absPath:Sk(`project-local`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)});return Pte(e.value.autoSync)}function re(){let e=pk({absPath:Sk(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules,t=e?Nne(e):va;return Apt(r,t.plugins.okf),t}function ie(){let e=pk({absPath:Sk(`project`,r),sideline:!1,warn:e=>b.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 ae(){return y8e(r,{configHomedirOverride:u,onWarn:e=>b.warn({message:e},`[config] could not read project-local config`)})}function oe(){let e=pk({absPath:Sk(`project-local`,r,u),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function se(){return Uxe({cwd:r,homedirOverride:u,warn:e=>b.debug({message:e},`[config] diagnostics read`)})}function ce(e){let t={user:Va,project:Xt,"project-local":ar};for(let n of se().diagnostics)if(e===void 0||t[n.scope]===e){if(n.code===`VALUE_FALLBACK`){for(let e of n.issues)b.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`&&b.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 le(e){return`${f3(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function ue(e){return`${e.maxBatchSize}|${e.maxBatchChars}|${e.docTimeoutMs}`}let de,fe=0;function pe(e,t){let i;if(e===`__config__/project`||e===`__local__/project`){let t=P();i=t.mode,yn?.setMode(t.mode,t.source).catch(n=>{b.warn({err:n,mode:t.mode,docName:e},`[sync] failed to apply autoSync mode from config`)});let n=ne();yn?.setIntervals(n.pullIntervalSeconds,n.pushIntervalSeconds)}let a=ae();if(ze.applyConfig({enabled:a.enabled,providerFingerprint:le(a),transportFingerprint:ue(a),maxBatchSize:a.maxBatchSize}),e===`__config__/project`){fe+=1;try{let e=te({requireValid:!0});xe?.setAttachmentFolderPath(e),de!==void 0&&e!==de&&b.warn({previous:de,next:e},`[content-filter] attachment folder changed — files under the previous folder no longer sync`),de=e}catch(e){b.warn({err:e},`[content-filter] project config invalid — keeping previous attachment admission`)}S?.signal(`lint-config`),(t??re().plugins.okf?.generate?.index===!0)||cpt({projectDir:r,contentDir:n,generatedDocNames:It(),enabled:!1}).then(e=>{e.ok||b.warn({state:e.status.state},`[index] could not remove Open Knowledge generated-index Git attributes`)}),jt()}b.info({docName:e,autoSyncMode:i,semanticEnabled:a.enabled},`[config] applied persisted config to in-process consumers`)}jq();let me=nc(),he=eX(r),ge=new uq({localDir:he,log:q(`acp-registry`),fetchImpl:e.acpRegistryFetchImpl}),_e=new rq(he,q(`acp-permissions`));if(I3(he,{port:0,worktreeRoot:r,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),!_)try{Umt({lockDir:he,shadowRepoDir:fw(r)})}catch(e){throw z3(he),e}let ve=qe(),ye=(e,t)=>ve.resolveEmbed(e,t),be=(e,t)=>{let r=ve.resolveEmbed(e,t);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=W(n,r);if(!dX(i,W(n)))return null;try{let e=Ps(i);return e.isFile()?e.size:null}catch{return null}},xe,Se,Ce,we,Te,Ee,De,Oe,ke,Ae,je,Me=null,Ne=null,Pe=null,Fe=null,Ie=null,Le=null,Re=ae(),ze=new D8e({loadEmbedder:()=>{let t=ae(),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??l8e)(n)},cacheDir:H(eX(r),`embeddings`),enabled:Re.enabled,providerFingerprint:le(Re),transportFingerprint:ue(Re),maxBatchSize:Re.maxBatchSize}),Be=null,He=new Set,Ue=!1,We=[],Ge,Ke,Je,Ye,Xe=new Promise((e,t)=>{Je=e,Ye=t}),Ze,Qe=new Promise(e=>{Ze=e});async function $e(){let e,t=Symbol(`branch-scope-gate-timeout`),n=new Promise(n=>{e=setTimeout(()=>n(t),1e4),e.unref?.()});try{if(await Promise.race([Qe,n])!==t)return T()}finally{e&&clearTimeout(e)}try{return o9(r).branch??null}catch(e){return b.warn({err:e},`[auth] branch scope gate expired and HEAD is unreadable — skipping the branch claim check`),null}}function et(e){S?.signal(e)}let tt,nt,rt,it=!1,at=!1,ot=new AbortController,st=new Set,ct=!1,lt=!1,ut=!1,dt=0,ft,pt=new Promise(e=>{ft=e});function mt(e){ut||(ut=!0,ft(e))}function ht(){return ct||st.size>0}function gt(){at||!it||(tt!==void 0&&clearTimeout(tt),tt=setTimeout(()=>{tt=void 0,Et()},500),tt.unref?.())}function vt(){if(at){mt({status:`cancelled`,indexCount:0});return}ct=!0,lt=!0,nt=setImmediate(()=>{nt=void 0,Et()})}let yt,bt,xt=!1,St=null;async function Ct(){let e=Ce.current;if(!e||xt)return;let t=performance.now();b.info({gitDir:e.gitDir},`[shadow-housekeeping] deferred boot housekeeping started`);try{await fUe(e)}catch(e){b.warn({err:e},`failed to write gc config (non-fatal)`)}if(!xt){if(St)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 x0(e,St,{rebuild:!0})).skipped){n=!0;break}if(r===29)break;if(await new Promise(e=>{setTimeout(e,t).unref?.()}),xt)return}n||b.warn({gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild retry budget exhausted (persistent GC contention); rebuild deferred to next boot`)}catch(t){b.warn({err:t,gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild failed; index loaded without GC`)}if(!xt){try{await we?.runBootMaintenance()}catch(e){b.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}b.info({gitDir:e.gitDir,durationMs:Math.round(performance.now()-t)},`[shadow-housekeeping] deferred boot housekeeping complete`)}}}function wt(){xt||(yt=setImmediate(()=>{yt=void 0,bt=Ct().catch(e=>{b.error({err:e},`[shadow-housekeeping] unexpected uncaught failure`)})}))}async function Tt(){if(xt=!0,yt!==void 0&&(clearImmediate(yt),yt=void 0),!bt)return;let e,t=new Promise(t=>{e=setTimeout(()=>t(`timeout`),m)});try{if(await Promise.race([bt,t])===`timeout`)throw Error(`shadow housekeeping drain timed out after ${m}ms — abandoning in-flight housekeeping`)}finally{e!==void 0&&clearTimeout(e)}}function Et(){if(at||!it||!ht())return;if(rt!==void 0){e.generatedIndexTestHooks?.onKickWhileInFlight?.();return}if(w.isBatchInProgress()){gt();return}let t=ct,n=new Set(st),r=lt;ct=!1,st.clear(),lt=!1;let i=t?{fullSweep:!0}:{fullSweep:!1,directories:n};rt=(async()=>{let e=await Bt(i,ot.signal);if(e.status===`deferred`){ct=!0,r&&(dt+=e.indexCount,lt=!0);return}r&&(dt+=e.indexCount,e.status===`completed`&&ht()?lt=!0:mt({...e,indexCount:dt}))})().catch(e=>{b.warn({err:e},`[index] index regeneration coordinator failed`),r&&mt({status:`failed`,indexCount:0})}).finally(()=>{if(rt=void 0,at){r&&mt({status:`cancelled`,indexCount:0});return}ht()&&tt===void 0?gt():!ht()&&tt===void 0&&e.generatedIndexTestHooks?.onIdle?.()})}async function Dt(){if(!at){let e=rt;at=!0,ot.abort(),tt!==void 0&&(clearTimeout(tt),tt=void 0),nt!==void 0&&(clearImmediate(nt),nt=void 0),st.clear(),ct=!1,lt=!1,e===void 0&&mt({status:`cancelled`,indexCount:0})}await rt}function Ot(e){at||fpt(e)||(st.add(n9(e)),gt())}function kt(e){if(!at){for(let t of dpt(e))st.add(t);gt()}}function At(e){let t=_n?.getFileIndex();if(!t){Ot(e);return}let n=n9(e);if(r9(t.keys()).has(n)){Ot(e);return}kt(n9(n))}function jt(){at||(ct=!0,gt())}function Mt(e){let t=_n?.getFileIndex().get(e);if(t)return{title:t.title,description:t.description,type:t.type}}let Nt=!1,Pt={origin:hgt,writer:SUe,isConflict:e=>M.has(e),getDocument:e=>De.documents.get(e),writeDisk:async(e,t)=>{dJ(V(e),{recursive:!0}),await vk(e,t,{fs:yJ})},registerWrite:(e,t)=>jZ(e,EZ(t)),noteFileIndex:e=>_n?.mutateFileIndex({kind:e.kind,path:e.absPath,docName:e.docName,content:e.markdown}),signalFiles:()=>et(`files`),attribute:async(e,t)=>{q1(e,t.id,t.name,t.id),Nt=!0}};function Ft(e){return e===``?e9:`${e}/${e9}`}function It(){return[..._n?r9(_n.getFileIndex().keys()):new Set([``])].map(Ft)}function Lt(e){let t=re().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 Rt(){return Lt(ipt({projectDir:r,contentDir:n,generatedDocNames:It()}))}async function zt(e){let t=await cpt({projectDir:r,contentDir:n,generatedDocNames:It(),enabled:e});if(!t.ok)return{...Rt(),applied:!1,reason:t.status.state===`conflict`?`git-conflict`:`git-unavailable`};let i=await wk({cwd:r,scope:`project`,patch:{contentRules:{okf:{generate:{index:e}}}}});if(!i.ok){try{await t.rollback()}catch(e){b.error({err:e},`[index] could not roll back generated-index Git attributes`)}return{...Rt(),applied:!1,reason:`config-write`}}try{let e=K(i.path,`utf-8`);U7(De.documents.get(`__config__/project`)??null,Xt,e,Te.configPersistenceCtx)}catch(e){b.warn({err:e},`[index] generated-index settings reflection deferred to config watcher`)}return pe(Xt,e),ce(Xt),{...Rt(),applied:!0}}async function Bt(t,i){let a=0,o=t.fullSweep?performance.now():void 0,s=()=>re().plugins.okf?.generate?.index!==!0;try{if(i.aborted)return{status:`cancelled`,indexCount:0};if(s())return{status:`disabled`,indexCount:0};let c=_n?.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(w.isBatchInProgress())return{status:`deferred`,indexCount:a};let o=gpt({docs:c,docExtension:MY,currentMarkdownFor:()=>null,warningScope:x}),l=ipt({projectDir:r,contentDir:n,generatedDocNames:o.map(({directory:e})=>Ft(e))});if(l.state!==`ready`&&l.state!==`not-applicable`)return b.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(w.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=Ft(r),l=W(n,`${o}.md`),u;try{u=K(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&b.warn({err:e,path:eJ(l)},`[index] could not read the existing generated index; treating it as absent`),u=null}a+=1;let d=await qft({docName:o,absPath:l,markdown:c,currentMarkdown:u},Pt);d===`blocked-conflict`?b.warn({event:`generated-index-regeneration`,outcome:`blocked`,directory:r,reason:`conflict`},`[index] generated index regeneration blocked by active conflict`):b.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&&kt(n9(r))}}finally{Nt&&=(await Te.waitForPendingCommits(),await Te.flushContributors(),!1),o!==void 0&&(s3(`generatedIndexSweepMs`,Math.round((performance.now()-o)*100)/100),L6e(`generatedIndexCount`,a))}return{status:`completed`,indexCount:a}}catch(e){return b.warn({err:e},`[index] index regeneration failed`),{status:`failed`,indexCount:a}}}let Vt=null,Ht=!1,Ut=()=>{try{Imt(r,Wt.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Wt=new Dmt(void 0,{onEviction:()=>RHe(),onSizeChange:e=>zHe(e),onMutate:()=>{!Ht||Vt!==null||(Vt=setTimeout(()=>{Vt=null,Ut()},2e3))}});for(let[e,t]of Fmt(r))UY(e)||N5(e)&&([`.md`,`.mdx`].some(t=>{let r=W(n,`${e}${t}`);return dX(r,W(n))&&G(r)})||Wt.restore(e,t));Ht=!0;let Gt={current:null},Kt=(e,t)=>{UY(e)||Wt.setRenamed(e,t)},qt=e=>{if(!UY(e)){if(Wt.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Wt.setDeleted(e),Gt.current?.deleted(e)}},Jt=e=>{UY(e)||Wt.delete(e)};try{let m=`./`;try{m=te()}catch(e){b.warn({err:e},`[content-filter] invalid attachment folder at boot — using sibling admission`)}de=m,xe=OX({projectDir:r,contentDir:n,singleDocRelPath:v,attachmentFolderPath:m,inPlaceSkillDirs:U2(n),rescanInPlaceSkillDirs:()=>U2(n),skillRootPaths:Y2e(n),onAfterRebuild:()=>{Se.refreshContentScope().catch(e=>{q(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),zKe(_n).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`)})}}),Se=new o6e({projectDir:r,contentDir:n,contentFilter:xe,getGlobalSkillRoots:()=>j9e(Te.managedArtifactCtx),signalChannel:et,getLocalTargetInventory:()=>Lit(_n,n),onRecoveredFileTarget:(e,t)=>{_n&&kmt({watcher:_n,contentDir:n,relativePath:e,exists:t,invalidateReferencedAssetsCache:Ie})}}),Ce={current:f},we=s?tmt({getShadow:()=>Ce.current??null,getCurrentBranch:()=>vn?.getLastKnownBranch()??null,contentRoot:p??``,projectGitDir:dw(r)??void 0,isWriterLive:e=>{if(!Fe&&!Oe)return q(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Fe?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of Oe?.sessionsForConnection(t)??[])return!0;return!1}}):void 0;let _=null;Te=Cmt({contentDir:n,projectDir:r,conflicts:M,lifecycleOf:(e,t)=>M.lifecycleOf(e,t),gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:Ce,ephemeral:y,contentRoot:p,derivedDocumentIndex:Se,configHomedirOverride:u,getCurrentBranch:()=>vn?.getLastKnownBranch()??null,resolveEmbed:ye,resolveSize:be,getPrincipal:()=>Be,onAgentCommit:()=>S?.signal(`session-activity`),onFlushCommit:()=>we?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{S?.emitDiskAck(e,t),!UY(e)&&(_pt(r,n,e)&&Ot(e),Z8e(r,n)&&(Ie?.(),et(`files`)))},onConfigRejected:(e,t)=>S?.emitConfigValidationRejected(e,t),onConfigPersisted:e=>{pe(e),ce(e)},onManagedSkillPersisted:e=>{let t=Vi(e);t?.kind===`skill`&&t.scope===`global`&&(_!==null&&clearTimeout(_),_=setTimeout(()=>{_=null;let e=u??zs();n4(e,e,V2(e)).then(e=>{e>0&&b.info({refreshed:e},`[in-place-skills] post-edit copy re-sync`)}).catch(e=>b.warn({err:e},`[in-place-skills] post-edit copy re-sync failed`))},2e3),_.unref?.())},isRecentlyRemoved:e=>Wt.has(e),mdManager:e.mdManager,getLossRing:()=>Ee,durabilityState:w}),De=new VBe({quiet:i,debounce:a,maxDebounce:o,extensions:[Te.extension]});let x=De.openDirectConnection.bind(De);De.openDirectConnection=((e,t)=>x(PY(e),t));let C=De;We.push(rJe(()=>C.documents.size),iJe(()=>Te.getQueueDepths()),oJe(()=>{let e=0;for(let t of C.documents.values())e+=t.directConnectionsCount;return{websocket:C.getConnectionsCount()-e,direct:e}})),cJe(),y||(Le=wmt({getLoadedDocuments:()=>C.documents,lifecycleOf:(e,t)=>M.lifecycleOf(e,t),forceStore:(e,t)=>Te.forceStore(e,t),getBase:e=>w.getReconciledBase(e),isBatchActive:()=>w.isBatchInProgress(),hasInFlight:e=>w.inFlightFlushCount(e)>0,readDiskBytes:e=>{let t=QX(e,n),r,i;try{r=As(t),i=Ps(r).size}catch(t){let n=tZ(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new _9(`symlink cycle at content path: ${e}`):t}if(!$X(r,n))throw new _9(`symlink-escape: ${t} resolves outside the content dir`);if(i>524288)throw new _9(`document exceeds the open byte limit: ${e}`);try{return K(r,`utf-8`)}catch(e){if(tZ(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs})),Ke=De.shouldUnloadDocument.bind(De),De.shouldUnloadDocument=e=>{if(He.has(e))return!0;if(Ue&&!UY(e.name)&&w.isStoreRefused(e.name))return!1;if(Ue&&Ke(e))return!0;let t=e.name;return UY(t)||E(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:Ke(e)},Ge=async e=>{He.add(e);try{await De.unloadDocument(e)}finally{He.delete(e)}},S=new qUe(De),Pe=new zZe(De),Fe=new VZe(De),Oe=new JJe(De,e.agentSessionOptions);let T=Oe;We.push(sJe(()=>({active:T.liveSessionCount,limit:T.sessionLimit})));let D=Ipt({derivedDocumentIndex:Se,onDocumentSettled:e=>Gt.current?.changed(e)});De.configuration.extensions.push(D);function O(e,t,n={}){b.warn({reason:e,docName:t,...n},`[auth-rejection] ${e}`)}De.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=R5(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==me)throw O(`server-instance-mismatch`,e.documentName,{claimedServerInstanceId:r,currentServerInstanceId:me}),new L5(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${me}`);let i=n?.expectedBranch;if(typeof i==`string`&&i.length>0){let t=await $e();if(t!==null&&i!==t)throw O(`branch-mismatch`,e.documentName,{claimedBranch:i,currentBranch:t}),new L5(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${t}`)}if(!n)return;let a=e.context;typeof n.principalId==`string`&&(Be&&n.principalId===Be.id?a.principalId=Be.id:Be?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:Be.id})):a.principalId=n.principalId),typeof n.tabSessionId==`string`&&(a.tabSessionId=n.tabSessionId),a.kind=`human`}}),De.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!RY(e.documentName)&&!zY(e.documentName))return;let n=e.request,r=n.socket?.remoteAddress;if(r!==void 0&&!O1(r,t))throw O(`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(!k1(a,t))throw O(`config-doc-admission-denied`,e.documentName,{check:`host`}),Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${e.documentName})`)}});let k=W(n);function A(e){if(!N5(e))return null;let t=FY(e),n=W(k,t);return dX(n,k)?n:null}De.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await jmt(e.documentName,{recentlyRemovedDocs:Wt,resolveFilePath:A,fileExists:G})}}),De.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=R5(e.token);ypt(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>De.documents.get(e)})}}),De.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new MK(e.update);if(t.readVarString(),t.readVarUint()===UK.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${Kr} rejected — server-only channel`)}});let j=rot({hocuspocus:De,durabilityState:w,ingressPolicy:t,sessionManager:Oe,commentDocHooksRef:Gt,contentDir:n,getGeneratedIndexSettingsStatus:Rt,setGeneratedIndexEnabled:zt,contentFilter:xe,serverInstanceId:me,getFileIndex:()=>_n?_n.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>_n?_n.getAllFilesIndex():new Map,getFileIndexGeneration:()=>_n?.getFileIndexGeneration()??0,mutateFileIndex:e=>{let t=e.kind===`update`?Mt(e.docName):void 0;switch(_n?.mutateFileIndex(e),e.kind){case`update`:vpt(t,e.content,e.docName)&&Ot(e.docName);break;case`create`:case`conflict`:Ot(e.docName);break;case`delete`:At(e.docName);break;case`rename`:At(e.oldDocName),Ot(e.newDocName);break;case`folder-create`:case`folder-delete`:kt(e.relativePath);break;case`asset-create`:case`asset-delete`:case`file-create`:case`file-update`:case`file-delete`:break;default:OZ(e)}},getFolderIndex:()=>_n?_n.getFolderIndex():new Map,getAliasMap:()=>_n?_n.getAliasMap():new Map,getFolderAliasIndex:()=>_n?_n.getFolderAliasIndex():new Map,rescanFiles:()=>_n?.rescanFromDisk(),enableTestRoutes:d,shadowRef:Ce,flushGitCommit:()=>Te.flushPendingGitCommit(),flushContributors:()=>Te.flushContributors(),getCurrentBranch:()=>vn?.getLastKnownBranch()??null,getDiskAckSVs:()=>S?.getLatestDiskAckSVsAsBase64()??{},getCollabClientCount:e.getCollabClientCount,contentRoot:p,derivedDocumentIndex:Se,signalChannel:et,agentFocusBroadcaster:Pe,agentPresenceBroadcaster:Fe,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>yn,conflicts:M,setBatchInProgress:ee,localOpCliArgs:h,authStreamHeartbeatMs:g,projectDir:r,resolveEmbed:ye,getBridgeLossReporter:()=>je,getPrincipal:()=>Be,agentIntegrations:e.agentIntegrations,acpRegistry:ge,loadAcpCustomAgents:()=>dq(he,q(`acp-registry`)),homeDirOverride:u,forceUnloadDocument:Ge,ready:Xe,recentlyRemovedDocs:Wt,serializeDoc:en,evictManagedArtifactLkg:e=>{Te.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:ze,getSemanticSimilarityFloor:()=>ae().similarityFloor,getLinterBaseConfig:()=>re(),getLinkAdvisoryPolicy:ie,getProjectConfigEpoch:()=>fe,getLinkPreviewsEnabled:oe,getConfigDiagnostics:se,embeddingsSecretsFile:f8e(u),readSemanticProviderConfig:ae,ephemeral:y,onReferencedAssetsCacheInvalidator:e=>{Ie=e}});De.configuration.extensions.push(j),ke=j.nativeApi,Ae=j.localApi;let N=pk({absPath:Sk(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for bridge guards`)}),P=N.value.bridge.deferGuard.enabled,ne=N.value.bridge.fixedPoint.enabled,le=N.value.bridge.preDrain.enabled;Ee=N.value.lossCapture.enabled?new rVe({projectDir:r,maxBytes:N.value.lossCapture.maxBytes}):void 0,N.value.bridge.lossDetector.enabled&&(je=RUe({shadow:()=>Ce.current,ring:Ee,getBranch:()=>vn?.getLastKnownBranch()??`main`,contentRoot:p??``}),Oe.attachBridgeLossReporter(je)),De.configuration.extensions.push(Lmt({mdManager:ma,schema:Xi,shadowRef:Ce,contentRoot:p,getCurrentBranch:()=>vn?.getLastKnownBranch()??null,resolveEmbed:ye,resolveSize:be,deferGuardEnabled:P,lossDetectorEnabled:N.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:ne,preDrainEnabled:le,lossRing:Ee})),De.configuration.extensions.push(fgt()),De.configuration.extensions.push({async afterLoadDocument({document:e}){HKe(e,M)}})}catch(e){for(let e of We.splice(0))e();throw Le?.dispose(),Le=null,z3(he),e}let Yt=null,Zt=new Map,Qt=[];function $t(e,t){let n=W(e,`rescue`),r=FY(t),i=W(n,r);return dX(i,n)?i:null}function en(e){let t=De.documents.get(e);return t?r0(t):null}let tn=(e,t)=>Q1(w,De,e,t,ye,be,je),nn=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of De.documents){if(UY(n))continue;let r=De.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{X1(r,i,ye,n)},Y1)}catch(t){b.error({originalError:i$e(t),docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},rn=null,an=e=>{e&&(rn===null&&(rn=new Set,setImmediate(()=>{let e=rn;if(rn=null,e)try{for(let t of e)nn(t)}catch(t){b.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),rn.add(e))};function on(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 OZ(e)}}let sn={delete:`external-change-rescue`,rename:`external-change-rescue`,"branch-switch":`external-change-rescue`,"disk-update":`external-change-rescue-disk-update`},cn=(e,t,n,r,i=``,a=!1)=>{if(!Ce.current){let t=a?r===`delete`?` — the delete that follows destroys the document content`:` — the overwrite that follows replaces the document content`:``;return b.warn({docName:e,site:r},`[reconcile] rescue checkpoint not minted for ${e} (${r}) — shadow repo unavailable${t}`),VJ(),!1}let o=Ce.current;return queueMicrotask(()=>{xY(o,p??``,{kind:sn[r],docName:e,contents:t,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:i}}).then(()=>{wVe(),b.info({docName:e,site:r},`[reconcile] rescue checkpoint saved (${r}): ${e}`)}).catch(t=>{TVe();let n=a?r===`delete`?` — the delete that follows destroys the document content`:` — the overwrite that follows replaces the document content`:``;b.error({docName:e,site:r,err:t},`[reconcile] rescue checkpoint write failed (${r}): ${e}${n}`)})}),!0},ln=(e,t,n,r=!1)=>{let i=E(e),a=en(e)??``,o=i===void 0?a!==``:a!==i;return o&&(cn(e,a,t,n,``,r),o)};function un(e){M.dissolveReconcile(e),M.dissolveWorkingTree(M.fileOf(e))}let dn=(e,t,n,r)=>{(t.kind===`merged`||t.kind===`conflicts`)&&t.dedupSkipped&&(_Ve(),b.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`))},fn=async(e,t,n)=>{kHe();let r=en(e)??``,i=vn?.getLastKnownBranch()??`main`,a=EZ(t).slice(0,6),o=r!==``&&r!==t,s=o?xn(e,`disk-authoritative-ingest`):`not-needed`;o&&cn(e,r,i,`disk-update`,a,!0);let c=EZ(r).slice(0,6),l=n?`absent`:`blockless`,u=!1;try{tn(e,t),un(e),u=!0}catch(o){AHe(),b.error({err:o,docName:e},`[reconcile] failed to apply disk-authoritative ingest to Y.Doc for ${e}`),D(e,t),cn(e,t,i,`disk-update`,a,!0),un(e);let u;try{u=en(e)??void 0}catch(t){b.error({err:t,docName:e},`[reconcile] unable to read ${e} back after a failed disk-authoritative ingest; treating the live content as lost`)}s===`lost`&&u!==r&&(jHe(),b.warn({docName:e,baseAbsent:n,reason:`no-base`,ours:c,theirs:a,result:`clean-unrescued`,rescue:s,applyFailed:!0},`[reconcile] ${e} base=${l} reason=no-base result=clean-unrescued ours=${c} theirs=${a} rescue=${s} applyFailed=true`))}if(u){let r=s===`lost`?`clean-unrescued`:`clean`;s===`lost`&&jHe(),(s===`lost`?b.warn.bind(b):b.info.bind(b))({docName:e,baseAbsent:n,reason:`no-base`,ours:c,theirs:a,result:r,rescue:s},`[reconcile] ${e} base=${l} reason=no-base result=${r} ours=${c} theirs=${a} rescue=${s}`),await Se.recordDiskUpsert(e,t)}};async function pn(e){try{switch(e.kind){case`create`:b.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await Se.recordDiskUpsert(e.docName,e.content),et(`files`),Ot(e.docName),Jt(e.docName);break;case`update`:{let{docName:t,content:n}=e;if(vpt(e.previousIndexedFields,n,t)&&Ot(t),M.findByDocName(t)?.kind===`merge-native`)try{await M.pruneMergeNativeAgainstGit()}catch(e){b.warn({err:e,docName:t},`[reconcile] conflict prune against git failed`)}let r=De.documents.get(t);if(!r){t0(w,void 0,t,n,M),await Se.recordDiskUpsert(t,n);return}let i=E(t),a=en(t)??i??``;if(t0(w,r,t,n,M,a)){await Se.recordDiskUpsert(t,n);return}if(i===void 0){await fn(t,n,!0);break}let o=FX({docName:t,base:i,ours:a,theirs:n}),s=EZ(i).slice(0,6),c=EZ(a).slice(0,6),l=EZ(n).slice(0,6),u=a.length,d=n.length,f=o.kind===`clean`||o.kind===`merged`||o.kind===`conflicts`?o.newContent.length:void 0,p=f===void 0?void 0:f-Math.max(u,d),m=f===void 0?``:` newLen=${f} delta=${p}`;switch(b.info({docName:t,base:s,ours:c,theirs:l,result:o.kind,oursLen:u,theirsLen:d,...f===void 0?{}:{newLen:f,delta:p}},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind} oursLen=${u} theirsLen=${d}${m}`),dn(t,o,a,n),o.kind){case`noop`:M.dissolveReconcile(t),await Se.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{tn(t,o.newContent),D(t,o.newContent),zJ(),M.dissolveReconcile(t),e=!0}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),D(t,n),M.dissolveReconcile(t)}e&&await Se.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{tn(t,o.newContent),D(t,n),zJ(),M.dissolveReconcile(t),e=!0}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),D(t,n),M.dissolveReconcile(t)}e&&await Se.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{tn(t,o.newContent),D(t,o.newContent),zJ(),BJ(),e=!0}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),D(t,n)}M.raise({kind:`reconcile`,file:M.fileOf(t),reason:`merged-with-markers`,stages:{base:i,ours:a,theirs:n}}),e&&await Se.recordDiskUpsert(t,n);break}case`refused`:if(o.reason===`no-base`){await fn(t,n,!1);break}BJ(),M.raise({kind:`reconcile`,file:M.fileOf(t),reason:o$e(o.reason),stages:{base:i,ours:a,theirs:n}})}break}case`delete`:{let{docName:t}=e;un(t);let n=De.documents.get(t);if(!n){O(t),await Se.recordDiskDelete(t),et(`files`),qt(t),At(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=ln(t,vn?.getLastKnownBranch()??`main`,`delete`,!0);n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),O(t),await Se.recordDiskDelete(t),b.info({docName:t,isDirty:r},`[reconcile] delete: ${t} (dirty=${r})`),De.closeConnections(t),await Ge(n),et(`files`),qt(t),At(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e;un(t);let i=e=>{let t=e.getMap(`lifecycle`);t.set(`status`,`renamed`),t.set(`newPath`,n)},a=De.documents.get(t),o=a?ln(t,vn?.getLastKnownBranch()??`main`,`rename`):!1;a&&i(a),O(t),Te.forgetObservedFile(t),D(n,r),b.info({oldDocName:t,newDocName:n,isDirty:o},`[reconcile] rename: ${t} → ${n} (dirty=${o})`),et(`files`),Jt(n),Kt(t,n);try{await Se.recordDiskRename(t,n,r)}catch(e){b.error({oldDocName:t,newDocName:n,err:e},`[reconcile] rename: index update failed for ${t} → ${n}; completing client teardown anyway`)}let s=De.documents.get(t);s&&s!==a&&i(s);let c=De.documents.get(n);if(c&&c.getMap(`lifecycle`).get(`status`)===`renamed`){let e=c.getMap(`lifecycle`);e.delete(`status`),e.delete(`newPath`),tn(n,r),b.info({newDocName:n},`[reconcile] rename: cleared stale renamed lifecycle on ${n}`)}await Oe.closeAllForDoc(t);let l=s?.getConnectionsCount()??0;De.closeConnections(t),l>0&&b.info({oldDocName:t,newDocName:n,closedConnections:l},`[reconcile] rename: closed ${l} connection(s) on ${t}`),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`})),At(t),Ot(n);break}case`conflict`:{let{docName:t}=e;if(!De.documents.get(t))return;let n=E(t)??``,r=en(t);r===null?b.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):D(t,r),M.raise({kind:`reconcile`,file:M.fileOf(t),reason:`disk-markers`,stages:{base:n,ours:r??n,theirs:e.content}}),b.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ve.add(e.relativePath),et(`files`),an(as(e.relativePath));break;case`asset-delete`:ve.remove(e.relativePath),et(`files`),an(as(e.relativePath));break;case`folder-create`:case`folder-delete`:et(`files`),kt(e.relativePath);break;case`file-create`:case`file-update`:await Se.recordFileTargetUpsert(e.relativePath),Ie?.(),et(`files`);break;case`file-delete`:await Se.recordFileTargetDelete(e.relativePath),Ie?.(),et(`files`);break;default:OZ(e)}}catch(t){let n=on(e);b.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let mn=[];async function hn(e){if(j()){mn.push(e);return}await pn(e)}async function gn(){let e=mn.splice(0,mn.length);for(let t of e)await pn(t)}let _n=null,vn=null,yn=null,bn=null,xn=(e,t)=>{let n=Ce.current;if(!n)return b.warn({docName:e,context:t},`[rescue] shadow repo unavailable — cannot buffer ${e} (${t})`),VJ(),`lost`;try{let r=en(e);if(r===null)return b.warn({docName:e,context:t},`[rescue] skipping ${e} — document dropped from map mid-rescue (${t})`),VJ(),`lost`;let i=$t(n.gitDir,e);return i?(dJ(V(i),{recursive:!0}),lJ(i,r,`utf-8`),wVe(),b.info({docName:e,context:t},`[rescue] rescue buffer saved (${t}): ${e}`),`rescued`):(b.warn({docName:e,gitDir:n.gitDir,context:t},`[rescue] path-traversal guard rejected docName: ${e} (${t})`),VJ(),`lost`)}catch(n){return b.error({err:n,docName:e,context:t},`[rescue] failed to write rescue buffer for ${e} (${t})`),VJ(),`lost`}};async function Sn(e){if(De.documents.size===0)return;let t=!1,n=new Promise(e=>{De.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(De.documents.keys());De.closeConnections(),De.flushPendingStores();for(let e of De.documents.values())e.getConnectionsCount()===0&&De.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let i=Date.now()+e;for(;Date.now()<i-250&&Array.from(De.documents.values()).some(e=>e.getConnectionsCount()===0&&!Ke(e));)await new Promise(e=>setTimeout(e,25));for(let e of w.getRefusedStoreDocNames()){if(UY(e))continue;let t=De.documents.get(e);if(!t||!Ke(t))continue;if(i-Date.now()<50){b.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(xn(e,`refused-store-shutdown`)!==`rescued`){b.warn({docName:e},`[rescue] refused-store doc rescue failed; leaving ${e} to the flush timeout path`);continue}let n=!1,r=!1,a=Ge(t).then(()=>{n=!0}).catch(t=>{r=!0,n=!0,b.warn({docName:e,err:t},`[rescue] refused-store doc unload failed at shutdown: ${e}`)}),o=Math.max(i-Date.now(),50);if(await new Promise(e=>{let t=setTimeout(e,o);a.then(()=>{clearTimeout(t),e()})}),!n){b.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(()=>{r||b.info({docName:e},`[rescue] refused-store doc unload completed after the flush deadline: ${e}`)});continue}r||b.info({docName:e},`[rescue] refused-store doc rescued and unloaded at shutdown: ${e}`)}let a,o=new Promise((n,o)=>{a=setTimeout(()=>{t=!0;let n=Array.from(De.documents.keys()),i=[],a=[];if(Ce.current)for(let e of n)UY(e)||(xn(e,`flush-timeout`)===`rescued`?i.push(e):a.push(e));else{b.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)UY(e)||(a.push(e),VJ())}let s=i.length>0||a.length>0?` — rescued [${i.join(`, `)}]${a.length>0?`, lost [${a.join(`, `)}]`:``}`:``;o(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},Math.max(i-Date.now(),250))});try{await Promise.race([n,o])}finally{a!==void 0&&clearTimeout(a)}}async function Cn(){return bn||(bn=(async()=>{let e=Date.now(),t=[];Ue=!0;try{await Dt()}catch(e){b.warn({err:e},`[index] generated index shutdown drain failed`),t.push({phase:`generated-index-drain`,error:String(e)})}for(let e of We.splice(0))e();try{await Le?.dispose()}catch(e){b.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Le=null;try{B3(he)}catch(e){b.warn({err:e},`[server] failed to mark server.lock draining`)}we?.destroy();try{await Tt()}catch(e){b.warn({err:e},`[shadow-housekeeping] shutdown drain failed`),t.push({phase:`shadow-housekeeping-drain`,error:String(e)})}if(Vt!==null&&(clearTimeout(Vt),Vt=null),Ht)try{Imt(r,Wt.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let n,i=await Promise.race([Xe.then(()=>`completed`,e=>(b.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{n=setTimeout(()=>e(`timeout`),5e3)})]);n!==void 0&&clearTimeout(n),i===`timeout`&&b.warn({},`[server] init did not complete within 5s during shutdown`);let a=De.documents.size;try{try{try{Me&&=(clearTimeout(Me),null),Ne&&=(clearTimeout(Ne),null),vn&&=(await vn.unsubscribe(),null),_n&&=(await _n.unsubscribe(),null);for(let{docName:e,cleanup:t}of Qt)try{await t()}catch(t){b.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Qt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{S?.destroy(),Fe?.destroy(),Yt&&=(await Yt.disconnect(),null);for(let[e,t]of Zt)try{await t.disconnect()}catch(t){b.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Zt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await Oe.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await pqe()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await Sn(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-3 flush failed`)}Se.close();let e;try{await Promise.race([(async()=>{await Te.flushPendingGitCommit(),await Te.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{yn&&=(await yn.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(Ce.current){let e;try{await Promise.race([tY(Ce.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)}),b.error({err:e},`[server] shutdown phase-5 shadow mutator drain failed`)}finally{e!==void 0&&clearTimeout(e)}try{let e=(await CF({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&Is(W(Ce.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{pUe(Ce.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let n=Date.now()-e;t.length===0?b.info({documentCount:a,durationMs:n},`[server] shutdown flushed ${a} documents in ${n}ms`):b.warn({documentCount:a,durationMs:n,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${n}ms with ${t.length} phase error(s)`)}}finally{try{z3(he,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await Fq()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),bn)}let wn=[];async function Tn(){try{Be=await Emt(r),b.info({principalId:Be.id},`[server] principal loaded`)}catch(e){b.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!Ce.current)try{Ce.current=await uY(r,{deferGcConfig:!0}),b.info({gitDir:Ce.current.gitDir},`[server] history repo initialized at ${Ce.current.gitDir}`),lUe(Ce.current)&&!wn.includes(`shadow-excludes`)&&wn.push(`shadow-excludes`)}catch(e){b.error({err:e},`[server] history repo init failed`),wn.push(`shadow-repo`)}if(Ce.current)try{let e=I$e(Ce.current.gitDir);X$e(Ce.current.gitDir,e),z$e(Ce.current.gitDir,e),St=e,b.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){b.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(Ce.current)try{await cY(Ce.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`)){b.warn({},`[server] history repo appears corrupted — reinitializing`);try{Ce.current=await uY(r,{deferGcConfig:!0}),lUe(Ce.current)&&!wn.includes(`shadow-excludes`)&&wn.push(`shadow-excludes`)}catch(e){b.error({err:e},`[server] history repo reinit failed`),Ce.current=void 0,wn.includes(`shadow-repo`)||wn.push(`shadow-repo`)}}else b.error({err:e},`[server] history repo check failed (transient?)`)}if(Ce.current&&bn===null){let e=Ce.current,t=uX(U(r,n))||`.`;Ne=setTimeout(()=>{Ne=null,pY(e,t).catch(e=>{b.debug({err:e},`[shadow] fan-out index warm-up failed (non-fatal)`)})},3e3),Ne.unref?.()}if(Ce.current)try{let e=W(Ce.current.gitDir,`last-known-head`),t=null;try{t=K(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await CF({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await CF({baseDir:r,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}b.info({lastKnownHead:t,currentHead:n,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=import`);try{await vY(Ce.current,p??``,t,n,e),xVe()}catch(e){b.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else b.info({currentHead:n},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=noop`);try{Is(e,n,`utf-8`)}catch(e){b.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){b.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=nat(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;b.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){b.error({err:e},`[server] managed rename recovery failed`),wn.push(`managed-rename-recovery`)}try{let e=C5e(r);(e.deleted>0||e.errors>0)&&b.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){b.error({err:e},`[server] upload-tempfile sweep failed`),wn.push(`upload-tempfile-sweep`)}try{Yt=await De.openDirectConnection(Kr),S?.emitServerInfo(me,T())}catch(e){b.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),wn.push(`cc1-push`)}let t=y?[]:Ve;for(let e of t)try{let t=await De.openDirectConnection(e);Zt.set(e,t)}catch(t){b.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),wn.push(`config-doc:${e}`)}let i=new Map([[Xt,Sk(`project`,r)],[ar,Sk(`project-local`,r)],[Va,Sk(`user`,r,u)]]);for(let e of t){let t=i.get(e);if(t)try{b.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await pft(t,t=>{let n=De.documents.get(e),r=Oft(e,t,Te.configPersistenceCtx);b.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let i=U7(n??null,e,t,Te.configPersistenceCtx);b.info({docName:e,outcome:i,isEcho:r},`[config-file-watcher] applyExternalConfigChange outcome`),pe(e),r||ce(e)});Qt.push({docName:e,cleanup:n}),b.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){b.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),wn.push(`config-file-watcher:${e}`)}}if(!y){let e=null,t=t=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,Se.refreshGlobalSkillNodes().catch(e=>{b.warn({err:e,docName:t},`[backlinks] global skill bundle re-ingest failed`)})},300)},n=(e,n)=>{let r=F9e(e,Te.managedArtifactCtx);if(!r)return;let i=B9e(De.documents.get(r)??null,r,n,Te.managedArtifactCtx);b.info({docName:r,outcome:i},`[managed-artifact-watcher] external change`),et(`files`),Yi(r)&&t(r)},r=e=>{let n=F9e(e,Te.managedArtifactCtx);et(`files`),n&&Yi(n)&&t(n)};try{let e=j9e(Te.managedArtifactCtx),t=await rmt(e,n,r);Qt.push({docName:`__skill-files__`,cleanup:t}),b.info({roots:e},`[managed-artifact-watcher] skills started`)}catch(e){b.warn({err:e},`[managed-artifact-watcher] skills failed to start`),wn.push(`managed-artifact-watcher:skills`)}try{let e=W(Q6(Te.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await pft(e,()=>{et(`files`)});Qt.push({docName:`__skill-state__`,cleanup:t}),b.info({path:e},`[skill-state-watcher] started`)}catch(e){b.warn({err:e},`[skill-state-watcher] failed to start`),wn.push(`skill-state-watcher`)}}try{let e=W(n,`.okignore`),t=W(r,`.gitignore`),i=null;try{let e=rs(`git`,[`rev-parse`,`--git-common-dir`],cX({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=b;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 mft(a,(t,n)=>{(async()=>{if(t===e)try{let e=U7(De.documents.get(`__config__/okignore`)??null,_t,n,Te.configPersistenceCtx);o.info({docName:_t,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 xe.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`),S?.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`),S?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:U(r,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Qt.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:t},`[ignore-watcher] multi-path watcher started`))}catch(e){b.warn({err:e,projectDir:r,contentDir:n},`[ignore-watcher] failed to start multi-path watcher`),wn.push(`ignore-files-watcher`)}let a=o9(r).branch??`main`;k(a),Ze();let o=Se.beginStartup(a),s=!1,c=performance.now();try{await Rq(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:t}=await o.backlinksReady;t&&wn.push(`backlink-index`);let i=0;for(let t of e)UY(t)||Wt.peek(t)?.kind!==`renamed`&&(Wt.setDeleted(t),i++);i>0&&b.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`);let a=performance.now(),c=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,l=xe?U2(n):new Set,d=e=>{e.some(e=>c.test(U(n,e).split(fs).join(`/`)))&&(Me&&clearTimeout(Me),Me=setTimeout(()=>{Me=null;try{n4(r,n).then(e=>{e>0&&(b.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),S?.signal(`files`))}).catch(e=>b.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=U2(n);if(!(e.size!==l.size||[...e].some(e=>!l.has(e))))return;l=e,xe.rebuildIgnorePatterns().then(t=>{t.ok?(b.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),S?.signal(`files`)):b.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>b.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){b.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};_n=await Rq(`ok.boot.seed-walk`,void 0,async()=>RKe(n,hn,xe,{onRawBatch:d})),n4(r,n).then(e=>{e>0&&b.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>b.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=u??zs();n4(e,e,V2(e)).then(e=>{e>0&&b.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>b.warn({err:e},`[in-place-skills] global copy re-sync failed`))}s3(`seedWalkMs`,Math.round(performance.now()-a));{let e=W(n),t=0;for(let[n]of Wt.entries()){if(!N5(n))continue;let r=W(e,`${n}${MY(n)}`);dX(r,e)&&G(r)&&(Wt.delete(n),t++)}t>0&&b.info({count:t},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let f=await Se.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&wn.push(`tag-index`);let p=0;try{v===void 0?await I5({contentDir:n,contentFilter:xe,basenameIndex:ve,onSkip:(e,t,n)=>{p++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):aot({contentDir:n,basenameIndex:ve,onSkip:(e,t,n)=>{p++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),p>0&&(b.warn({count:p},`[basename-index] startup seed completed with ${p} skipped entries — embeds under inaccessible subtrees will not resolve`),wn.push(`basename-index-partial`))}catch(e){b.error({err:e},`[basename-index] startup seed failed`),wn.push(`basename-index`)}})}catch(e){if(b.error({err:e},`[server] disk bridge watcher failed to start`),wn.push(`file-watcher`),!s){let e=await Se.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&wn.push(`tag-index`)}}finally{s3(`indexesMs`,Math.round(performance.now()-c)),_n&&L6e(`fileCount`,_n.getFileIndex().size)}try{vn=await wpt(r,async({trigger:e})=>{if(b.info({trigger:e},`[batch] begin trigger=${e}`),bVe(),De.flushPendingStores(),await Te.flushPendingGitCommit(),A(!0),Ce.current){let e=T(),t=o9(r).branch??e,n=[],i=0;for(let[e,t]of De.documents){if(UY(e))continue;let r=null;if(t.transact(()=>{r=en(e)},mgt),r===null)continue;let a=E(e);if(a===void 0){i++;continue}n.push({docName:e,markdown:r,diskSnapshot:a})}if(i>0&&b.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 kUe(Ce.current,e,gY.id,n,t);r&&(DVe(),b.info({count:n.length,branch:e,sha:r.slice(0,8)},`[history] parked ${n.length} docs on ${e} → ${r.slice(0,8)}`))}catch(e){b.error({err:e},`[shadow] park failed`)}}},async e=>{let t=mn.length,i=e.newBranch??`main`;if(b.info({kind:e.batchKind,headMoved:e.headMoved,docs:t,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${t}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(A(!1),await gn(),e.headMoved&&e.newHead){let t=ggt(r,W(n),e.oldHead,e.newHead);if(t.size>0){qQe(t.keys());for(let[e,n]of t)q1(e,epe(n.email),n.name,n.email,ppe(e));await Te.flushContributors()}}await Te.flushDeferredStores(`within-branch`);try{await M.pruneMergeNativeAgainstGit()}catch(e){b.warn({err:e},`[head-watcher] conflict prune against git failed`)}}else{EVe(),mn.splice(0,mn.length);let t=!1,r;try{k(i),M.setBranch(i),N(),r=await Se.beginBranchSwitch(i),xe.rebuildDirCount();try{let e=0;ve.clear(),await I5({contentDir:n,contentFilter:xe,basenameIndex:ve,onSkip:(t,n,r)=>{e++,b.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(b.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`),wn.includes(`basename-index-partial`)||wn.push(`basename-index-partial`))}catch(e){b.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,t]of De.documents)if(!UY(e))try{let r=QX(e,n);if(!G(r)){ln(e,i,`branch-switch`),t.getMap(`lifecycle`).set(`status`,`deleted-upstream`),b.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=K(r,`utf-8`);if(E(e)===void 0){let t=en(e)??``;t!==``&&t!==a&&ln(e,i,`branch-switch`,!0)}tn(e,a),D(e,a),b.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){b.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}b.info({branch:i,docCount:De.documents.size},`[branch-switch] loaded branch ${i} (${De.documents.size} docs)`);try{await Se.settleBranchFromDisk(r)}catch(e){Se.abortBranchSwitch(r),b.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(Ce.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of De.documents)if(!UY(t))try{let n=await jUe(Ce.current,i,gY.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=E(t);if(!r)continue;let a=FX({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(dn(t,a,n.markdown,r),a.kind){case`merged`:case`clean`:tn(t,a.newContent),D(t,a.newContent),e++;break;case`conflicts`:tn(t,a.newContent),D(t,a.newContent),BJ(),e++,M.raise({kind:`reconcile`,file:M.fileOf(t),reason:`merged-with-markers`,stages:{base:n.diskSnapshot,ours:n.markdown,theirs:r}});break;case`noop`:break;case`refused`:switch(a.reason){case`conflict-markers`:case`no-base`:case`too-large`:b.warn({docName:t,reason:a.reason,branch:i},`[branch-switch] parked WIP not restored for ${t} (reconcile refused: ${a.reason})`);break;default:{let e=a.reason;b.warn({docName:t,reason:String(e),branch:i},`[branch-switch] parked WIP not restored for ${t} (reconcile refused: ${String(e)})`);break}}}}catch(e){b.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&b.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&Ce.current)try{let t=cY(Ce.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await tY(Ce.current).withMutator(async()=>{for(let e of n.split(`
|
|
2101
2101
|
`))e&&await t.raw(`update-ref`,`-d`,e)}),b.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){b.error({err:e},`[branch-switch] detached cleanup failed`)}A(!1),await Te.flushDeferredStores(`discard-stale`),t=!0,S?.emitBranchSwitched(i)}finally{Se.abortBranchSwitch(r),t||(A(!1),await Te.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&Ce.current&&t>0){let t=p??`.`;try{let n=await vY(Ce.current,t,e.oldHead,e.newHead,i);xVe(),b.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){b.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){b.error({err:e},`[server] HEAD watcher failed to start`),wn.push(`head-watcher`)}M.subscribe(e=>{if(e.type!==`raised`||e.conflict.kind===`reconcile`)return;let t=e.docName;if(t===null||!De.documents.get(t))return;let n=en(t);n===null?b.warn({docName:t,file:e.conflict.file},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):D(t,n)});try{await M.pruneMergeNativeAgainstGit()}catch(e){b.warn({err:e},`[conflicts] boot prune of merge-native entries failed`)}let l=X6(r);b.debug({resetAmbientCredentials:l,originKind:Y6(r).kind},`[sync] ambient credential-chain reset decision at boot`);let d=Q4(h,{resetAmbient:l}),f=P(),m=ne();f.mode!==`off`&&b.info({mode:f.mode,source:f.source},`[sync] mode active at boot`);try{yn=new ugt({projectDir:r,contentDir:n,contentFilter:xe,contentRoot:p,mcpTomlEditor:e.mcpTomlEditor,mode:f.mode,pullIntervalSeconds:e.pullIntervalSeconds??m.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds??m.pushIntervalSeconds,credentialConfig:d,cc1Broadcaster:S,conflicts:M,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:ee,onStateChange:e=>{b.info({state:e},`[sync] state → ${e}`)},checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=Ce.current;n&&await bY(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=Ce.current;n&&await bY(n,p??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{b.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await wk({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:dre(t.error),configPath:Sk(`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 yn.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),yn=null}et(`files`),Se.announceReadyViews();let g=I6e();g!==void 0&&s3(`readyMs`,g),ce()}return Tn().then(()=>{it=!0,Je(),vt(),wt()},e=>{at=!0,ot.abort(),mt({status:`failed`,indexCount:0}),Se.close(),Ze(),Ye(e)}),{hocuspocus:De,durabilityState:w,sessionManager:Oe,nativeApi:ke,localApi:Ae,cc1Broadcaster:S,agentFocusBroadcaster:Pe,agentPresenceBroadcaster:Fe,maintenanceCoordinator:we,contentFilter:xe,basenameIndex:ve,serverInstanceId:me,destroy:Cn,ready:Xe,generatedIndexSweepReady:pt,degraded:wn,lockDir:he,get syncEngine(){return yn},conflicts:M,getLinkPreviewsEnabled:oe,resolveEmbed:ye,acpRegistry:ge,acpPermissions:_e}}function I9(e){return e/1048576}function vgt(){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 ygt=1e6;let B9=null,V9=null;Pq(()=>{L9=null,R9=null,z9=null,B9?.disable(),B9=null,V9=null});function bgt(){if(L9)return;let e=Lq().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}=vgt();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 xgt(){if(!R9){let e=Lq().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=pae({resolution:20}),B9.enable();return}e.observe(B9.percentile(50)/ygt,{stat:`p50`}),e.observe(B9.percentile(99)/ygt,{stat:`p99`}),B9.reset()}),R9=e}if(!z9){let e=Lq().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 Sgt=q(`skill-migrate`);function Cgt(e){return[{host:`agents`,root:vn},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=$F.indexOf(e.host),r=$F.indexOf(t.host);return(n===-1?$F.length:n)-(r===-1?$F.length:r)||e.host.localeCompare(t.host)})}const wgt=Cgt(gn),Tgt=Cgt(Ln);function Egt(e,t){return G(W(e,jr(t)))}function Dgt(e,t){dJ(V(t),{recursive:!0});try{fJ(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;pJ(e,t,{recursive:!0}),_J(e,{recursive:!0,force:!0})}}function Ogt(e,t,n){let r=h4e(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 kgt(e,t){let n;try{n=As(W(e,`.ok`,`skills`))}catch{n=W(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!As(W(e,t.dir)).startsWith(n+fs)}catch{return!0}}).map(e=>e.name))}async function Agt(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??wgt,a={migrated:[],skipped:[]};if(!G(n))return a;let o;try{o=ks(n)}catch{return a}let s=U(t,n).split(fs).join(`/`),c=new Set;for(let[e,n]of Object.entries(e4(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Xe.test(e)||u1.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=W(n,e);if(!G(H(o,`SKILL.md`)))continue;let s=qF(o)?.contentHash;if(s===void 0)continue;let l=As(o),u=i.map(({host:n,root:r})=>{let i=W(t,r);return{host:n,root:r,path:H(i,e),escapes:u4(t,i),state:Ogt(H(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>Egt(t,e.root));if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?_J(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&_J(d.path,{recursive:!0,force:!0}),Dgt(o,d.path));for(let e of u)e!==d&&e.state.kind===`store-link`&&(_J(e.path,{recursive:!0,force:!0}),pJ(d.path,e.path,{recursive:!0}));await q2(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),Sgt.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),Sgt.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}let H9=null,U9=!1;function jgt(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function Mgt(e){if(!jgt())return;let t=eX(e);H9=new tw({currentPath:W(t,`tolerance-telemetry.jsonl`),previousPath:W(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),Mt(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(){Mt(null),await H9?.drain(),H9=null,U9=!1}function Ngt(e){let t=W(e,na);if(!(()=>{if(!G(t))return!0;try{return ks(t).length===0}catch{return!0}})())return[];let n=[];for(let t of Ai)G(W(e,t))&&n.push(t);for(let t of Tne){let r=W(e,t);try{G(r)&&Ps(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function Pgt(e){let t=uw(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 Fgt(e){F6e();let t=e.projectDir??e.contentDir,n=Sot({projectDir:t});if(n){let e=n.telemetry.attributeDenylist,t=[];for(let n of e){t.push(n);for(let e=1;e<=5;e++)t.push(`${`*.`.repeat(e)}${n}`)}aw.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}jq({localSink:n?.telemetry}),Mgt(t),bgt(),xgt();let{kind:r,gitdir:i}=Pgt(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=eJ(i));let o=got(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Rq(`ok.boot`,{attributes:a},async()=>Igt(e)),l=()=>{if(s)try{let e=Ya.extract(Ga.active(),{traceparent:s});return Ga.with(e,c)}catch(e){q(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async e=>{try{await d(e)}finally{o.uninstall()}},u}async function Igt(e){let t=e.skipAutoInit??!1,n=e.log??q(`boot`),r=e.serverRuntime??{...lr(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((un(r)||!Hr(i))&&!r.allowExternal)throw new gQe(`refusing to start: the server would bind a non-loopback address (${(Hr(i)?r.bind:i).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let a=D1({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.externalUrl===void 0&&(a.bindLiterals.length===0?n.warn({bind:r.bind},`[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.externalUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.externalUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.`):n.info({bind:r.bind},`[ingress] server.allowExternal is set with no server.externalUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.externalUrl to admit a hostname.`));let o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await Promise.resolve().then(()=>V8e),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=W(p,`.ok`),h=W(m,`config.yml`);if(!G(h))throw new dft(G(m)?`config`:`okdir`,p);let g=W(m,`.gitignore`);G(g)||q(`boot`).warn({path:g},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let _=e.gitPreflight??s$;try{e.gitEnabled!==!1&&_()}catch(e){if(e instanceof a$||e instanceof o$){let t=e instanceof o$?e.detected:``,r=e instanceof o$?`too_old`:`not_available`;b8(e),n.warn({event:`git_preflight_fail`,platform:e.platform,reason:r,detectedVersion:t},r===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await Fq(),await Promise.race([W9(),new Promise(e=>setTimeout(e,G9))]),e}let v=Ngt(m);v.length>0&&q(`boot`).warn({files:v},`Found legacy runtime files at .ok/${v.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${na}/.`);let y=null,b=_gt({getCollabClientCount:()=>y?.getCount()??0,acpRegistryFetchImpl:e.acpRegistryFetchImpl,contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:a,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,mcpTomlEditor:e.mcpTomlEditor,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,agentIntegrations:e.agentIntegrations,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral,configHomedirOverride:e.configHomedirOverride}),{hocuspocus:x,destroy:S,ready:C,degraded:w,lockDir:T,sessionManager:E,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,maintenanceCoordinator:k}=b,A=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ee=e.port??0,j=()=>`http://${A}:${ee}`,M=e.ephemeral?void 0:nft({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>j(),localApi:b.localApi,log:n}),N=c();N.headersTimeout=3e4,N.requestTimeout=6e4;let te=e.serveContentAssets===!1?void 0:iot({contentFilter:b.contentFilter,contentSirv:yz(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:mt,assetExtensions:li,blocklistExtensions:In,ingressPolicy:a}),P=e.reactShellDistDir?yz(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,ne=e.ephemeral?null:new kZe({contentDir:e.contentDir,localDir:T,globalDir:W(zs(),`.ok`),registry:b.acpRegistry,permissions:b.acpPermissions,sessionManager:E,agentPresenceBroadcaster:O,resolveEmbed:b.resolveEmbed,isExcludedPath:e=>b.contentFilter.isExcluded(e),isIgnoredPath:e=>b.contentFilter.isPathIgnored(e),getLoadedDocText:e=>x.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>j(),getMcpStdioCommand:()=>OZe(e.localOpCliArgs,ee,{log:n}),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,probePiAcpBridge:e.probePiAcpBridge,ensurePiAcpBridge:e.ensurePiAcpBridge,hostSnapshot:()=>c1({env:`local-web`,resolve:e.agentIntegrations?.probe}),log:n});ne!==null&&await ne.init();let re=`pending`;C.then(()=>{re=`ready`},()=>{re=`failed`});let ie=lft({httpServer:N,hocuspocus:x,nativeApi:b.nativeApi,mcpHttpHandler:M,ingressPolicy:a,health:{readiness:()=>re,degraded:()=>w},log:n,sessionManager:E,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,maintenanceCoordinator:k,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:te,reactShellMiddleware:P,ephemeral:e.ephemeral,acpThreadManager:ne}),ae=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)};y=B5(N);let oe=null;if(e.idleShutdownMs!==null){let t=e.idleShutdownMs??18e5,r=e.idleShutdownHandler??(e=>async()=>{await e()});oe=_ot({httpServer:N,counter:y,thresholdMs:t,log:n,onShutdown:r(async()=>{await ae(`idle-shutdown`)})})}let se=[...new Set(i)],ce=se[0],le=async()=>{await S().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(T)},ue=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await ue(N,e.port??0,ce??`127.0.0.1`)}catch(e){throw await le(),e}let de=N.address(),fe=typeof de==`object`&&de?de.port:e.port??0,pe=[];for(let e of se.slice(1)){let t=c();t.headersTimeout=N.headersTimeout,t.requestTimeout=N.requestTimeout;for(let e of N.listeners(`request`))t.on(`request`,e);for(let e of N.listeners(`upgrade`))t.on(`upgrade`,e);try{await ue(t,fe,e)}catch(t){n.error({err:t,failedAddress:e,port:fe,alreadyBound:pe.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...pe,N])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await le(),t}pe.push(t)}let me=I6e();me!==void 0&&s3(`httpListenMs`,me);let he=N.address(),ge=typeof he==`object`&&he?he.port:e.port??0;ee=ge;let _e=j();d(T,ge,_e),n.info({event:`server-listening`,pid:process.pid,port:ge,addresses:se,url:_e,lockDir:T},`[boot] listening on ${_e}`);let ve=!1,ye=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${G9}ms`))},G9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};ae=async(e=`unspecified`)=>{if(ve)return;ve=!0,n.info({reason:e,pid:process.pid,lockDir:T},`[server] shutdown initiated (${e})`),re=`draining`;let t=[],r=async(e,r)=>{try{await ye(e,r)}catch(r){t.push(r),n.warn({err:r,step:e},`bootServer destroy step failed`)}};try{l(T)}catch(e){n.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{y?.detach()}catch(e){n.warn({err:e,step:`collabClientCounter.detach`},`bootServer destroy step failed`)}try{oe?.detach()}catch(e){t.push(e),n.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(ne!==null&&await r(`acpThreads.destroy`,()=>ne.destroy()),await r(`secondaryListeners.close`,async()=>{for(let e of pe)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await r(`mount.shutdown`,()=>ie.shutdown()),M!==void 0&&await r(`mcpHttpHandler.close`,()=>M.close()),await r(`mount.wss.close`,()=>new Promise((e,t)=>{ie.wss.close(n=>n?t(n):e())})),await r(`httpServer.closeAllConnections`,async()=>{N.closeAllConnections?.()}),await r(`httpServer.close`,()=>new Promise((e,t)=>{N.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await r(`destroyHocuspocus`,()=>S()),await r(`shutdownTelemetry`,()=>Fq()),await r(`teardownToleranceTelemetry`,()=>W9()),await r(`flushLogFileSinks`,()=>aw.flushAllFileSinks()),t.length>0)throw AggregateError(t,`bootServer destroy completed with errors`)};try{let t=await Agt({projectDir:p,skillsRoot:W(e.contentDir,`.ok`,`skills`),inPlaceNames:kgt(e.contentDir,B2(e.contentDir))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=zs(),t=await Agt({projectDir:e,skillsRoot:W(e,`.ok`,`skills`),hostRoots:Tgt,inPlaceNames:kgt(e,V2(e))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}return{httpServer:N,destroy:ae,lockDir:T,contentDir:e.contentDir,port:ge,ready:C,generatedIndexSweepReady:b.generatedIndexSweepReady,degraded:w,didAutoInit:f,serverInstance:b,runtime:fft(b,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:ne}}const Lgt=Aa;function Rgt(e={}){let t=e.home??zs(),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=BC(Jde(),1);const q9=H(zs(),`.ok`,`logs`),zgt=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function Bgt(){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 Vgt(e){ws(e,{recursive:!0})}function Hgt(){return new Date().toISOString().slice(0,10)}function Ugt(e){try{if(Ps(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{js(n,r)}catch{}}try{Fs(`${e}.3`)}catch{}}function Wgt(e){try{let t=Date.now(),n=6048e5,r=ks(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=Ps(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{Fs(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{Fs(H(e,t.name)),a-=t.size}catch{}}}catch{}}function Ggt(e){Vgt(q9);let t=Hgt(),n=e.filePath??H(q9,`${e.name}.${t}.log`);Ugt(n),(e._setTimeout??setTimeout)(()=>Wgt(q9),5e3).unref();let r=K9.default.destination({dest:n,append:!0,sync:!0}),i=Bgt();return(0,K9.default)({level:i,name:e.name,redact:{paths:zgt,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 Kgt(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 qgt(e){return H(q9,`${e}.${Hgt()}.log`)}function Jgt(){return q9}function Ygt(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=ac(ts),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 Xgt(e,t){try{return await J9(e,[`var`,`GIT_COMMITTER_IDENT`],cX({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function Zgt(e,t){try{let{stdout:n}=await J9(e,[`for-each-ref`,`--count=1`,`refs/`],cX({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return Y9.warn({path:t,stderr:$gt(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function Qgt(e){let t=W(e,`packed-refs`);if(G(t))try{if(K(t,`utf-8`).split(`
|
package/dist/index.mjs
CHANGED
|
@@ -1535,6 +1535,6 @@ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){funct
|
|
|
1535
1535
|
`);re(e,o)}function M9(e,t){let n=S(e,`utf-8`);if(n.trim().length!==0)try{let r=A9(JSON.parse(n),t),i=n.endsWith(`
|
|
1536
1536
|
`)?`
|
|
1537
1537
|
`:``;re(e,`${JSON.stringify(r,null,2)}${i}`)}catch{let r=k9(n,t.contentDir);r!==n&&re(e,r)}}function N9(e,t){let n=S(e,`utf-8`),r=k9(n,t.contentDir);r!==n&&re(e,r)}function P9(e){try{return w(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(t=>N(e,t.name))}catch{return[]}}const KAe=new Set([`agent-presence.json`,`agent-effects.json`,`runtime.json`]);function F9(e){return/\.log\.\d+$/.test(e)}function qAe(e){return e.endsWith(`.jsonl`)||e.endsWith(`.log`)||F9(e)}const JAe=[`telemetry`,`logs`,`process`,`diagnostic-reports`];function YAe(e){let t={contentDir:e.contentDir};for(let n of JAe)for(let r of P9(N(e.stagingDir,n)))qAe(r)?j9(r,t):r.endsWith(`.json`)?M9(r,t):N9(r,t);for(let n of P9(N(e.stagingDir,`state`))){let e=me(n);n.endsWith(`.jsonl`)?j9(n,t):KAe.has(e)?M9(n,t):N9(n,t)}}const I9=[`.ok`,`local`,`telemetry`],L9=[`.ok`,`local`,`logs`],R9=[`.ok`,`local`,`loss-capture`],z9=`spans-current.jsonl`,B9=`spans-prev.jsonl`,V9=`server-current.jsonl`,H9=`server-prev.jsonl`,U9=`loss-current.jsonl`,W9=`loss-prev.jsonl`;function XAe(e){return N(e,...I9,z9)}function ZAe(e){return N(e,...I9,B9)}function QAe(e){return N(e,...L9,V9)}function $Ae(e){return N(e,...L9,H9)}function eje(e){return N(e,...R9,U9)}function tje(e){return N(e,...R9,W9)}const G9=1e3;async function nje(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-presence`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function rje(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/agent-effects`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}async function ije(e){try{let t=await fetch(`http://127.0.0.1:${e}/api/metrics/watcher-recent`,{signal:AbortSignal.timeout(G9)});return t.ok?await t.text():null}catch{return null}}function aje(e){try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return null;let n=t.decisions;return Array.isArray(n)?n.length===0?``:`${n.map(e=>JSON.stringify(e)).join(`
|
|
1538
|
-
`)}\n`:null}catch{return null}}function oje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],W6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function sje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],W6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function cje(){return{nodeVersion:process.version,platform:le(),arch:ae()}}function lje(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!g(e))return{};let t;try{t=(0,tn.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function uje(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return uje(e.maxBytes)}function dje(e){let t=J9(LQ(`project`,e)),n=J9(LQ(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function fje(e){return Ne(`sha256`).update(e).digest(`hex`)}function pje(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const mje=[`"doc.name"`,`"docName"`];function hje(e){let t=S(e,`utf-8`),n=0;for(let e of mje){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(M(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,w7(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=N(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const gje=new Set([`.jsonl`]);function _je(e){let t=e.lastIndexOf(`.`);return t!==-1&&gje.has(e.slice(t))}const vje=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function yje(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&vje.has(e.slice(t))}function bje(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!yje(r))continue;let{redacted:i,patterns:a,lineCount:o}=_B(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return ye(e,t).split(xe).join(`/`)}async function xje(e){let t=be(e.contentDir),n=be(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??nje,a=r.fetchAgentEffects??rje,o=r.fetchWatcherRecent??ije,s=r.readShadowHead??oje,c=r.readCheckpointRefs??sje,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.76.0-beta.
|
|
1538
|
+
`)}\n`:null}catch{return null}}function oje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`log`,`--oneline`,`-50`],W6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function sje(e){let t=N(e,`.git`,`ok`);if(!g(t))return null;let n=l(`git`,[`-C`,t,`for-each-ref`,`--sort=-creatordate`,`--count=50`,`--format=%(refname)%09%(creatordate:iso-strict)%09%(contents:subject)`,`refs/checkpoints/`],W6({encoding:`utf-8`,timeout:2e3}));return n.error||n.status!==0?null:n.stdout??``}function K9(){let e=process.env.OK_DESKTOP_VERSION,t=process.env.OK_DESKTOP_PACKAGED,n=process.env.OK_DESKTOP_CHANNEL;return e===void 0||t===void 0||n===void 0?null:{electronVersion:e,packaged:t===`1`||t.toLowerCase()===`true`,channel:n}}function cje(){return{nodeVersion:process.version,platform:le(),arch:ae()}}function lje(){return process.env.OTEL_SDK_DISABLED===`false`}function q9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J9(e){if(!g(e))return{};let t;try{t=(0,tn.parse)(S(e,`utf-8`))}catch(t){return console.warn(`[ok diagnose bundle] failed to parse ${e} for manifest config; manifest will report schema defaults. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!q9(t))return{};let n=t.telemetry;if(!q9(n))return{};let r=n.localSink;return q9(r)?r:{}}function Y9(e){return typeof e==`boolean`?e:void 0}function uje(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function X9(e){if(q9(e))return uje(e.maxBytes)}function dje(e){let t=J9(LQ(`project`,e)),n=J9(LQ(`project-local`,e));return{enabled:Y9(n.enabled)??Y9(t.enabled)??!0,spansMaxBytes:X9(n.spans)??X9(t.spans)??52428800,logsMaxBytes:X9(n.logs)??X9(t.logs)??26214400}}function fje(e){return Ne(`sha256`).update(e).digest(`hex`)}function pje(e){let t=S(e),n=0;for(let e=0;e<t.length;e++)t[e]===10&&n++;return n}const mje=[`"doc.name"`,`"docName"`];function hje(e){let t=S(e,`utf-8`),n=0;for(let e of mje){let r=t.indexOf(e);for(;r!==-1;)n++,r=t.indexOf(e,r+e.length)}return n}function Z9(e,t){if(!g(e))return!1;try{return v(M(t),{recursive:!0}),e.endsWith(`.ips`)?re(t,w7(S(e,`utf-8`))):m(e,t),!0}catch{return!1}}function Q9(e){let t=[],n=e=>{let r=w(e,{withFileTypes:!0});for(let i of r){let r=N(e,i.name);i.isDirectory()?n(r):i.isFile()&&t.push(r)}};return n(e),t.sort()}const gje=new Set([`.jsonl`]);function _je(e){let t=e.lastIndexOf(`.`);return t!==-1&&gje.has(e.slice(t))}const vje=new Set([`.jsonl`,`.json`,`.txt`,`.log`,`.lock`,`.yaml`,`.yml`,`.ips`]);function yje(e){if(F9(e))return!0;let t=e.lastIndexOf(`.`);return t!==-1&&vje.has(e.slice(t))}function bje(e){let t=[];for(let n of Q9(e)){let r=$9(e,n);if(!yje(r))continue;let{redacted:i,patterns:a,lineCount:o}=_B(S(n,`utf-8`));a.length!==0&&(re(n,i),t.push({file:r,lineCount:o,patterns:a}))}return{redactions:t,redactedLineCount:t.reduce((e,t)=>e+t.lineCount,0)}}function $9(e,t){return ye(e,t).split(xe).join(`/`)}async function xje(e){let t=be(e.contentDir),n=be(e.projectDir??e.contentDir),r=e.deps??{},i=r.fetchAgentPresence??nje,a=r.fetchAgentEffects??rje,o=r.fetchWatcherRecent??ije,s=r.readShadowHead??oje,c=r.readCheckpointRefs??sje,l=r.now??(()=>new Date),u=r.okVersion??(()=>`0.76.0-beta.1`),d=r.readDesktopEnv??K9,f=r.readLanguage??O9,p=r.readRuntime??cje,h=r.isOtlpPushEnabled??lje,_=y(N(A(),`ok-bundle-`));try{v(N(_,`telemetry`),{recursive:!0}),v(N(_,`logs`),{recursive:!0}),v(N(_,`state`),{recursive:!0}),Z9(XAe(n),N(_,`telemetry`,z9)),Z9(ZAe(n),N(_,`telemetry`,B9)),Z9(QAe(n),N(_,`logs`,V9)),Z9($Ae(n),N(_,`logs`,H9));for(let t of e.userLogFiles??[])Z9(t,N(_,`logs`,me(t)));for(let t of e.userStateFiles??[])Z9(t,N(_,VL,me(t)));let y=0;for(let t of e.diagnosticReports?.files??[])Z9(t,N(_,`diagnostic-reports`,me(t)))&&(y+=1);let b=N(n,`.ok`,`local`),x=N(b,`server.lock`),C=`not-running`,w=`no server.lock`,T=null;if(g(x)){Z9(x,N(_,`state`,`server.lock`));try{let e=S(x,`utf-8`),t=JSON.parse(e);typeof t.port==`number`?T=t.port:w=`lock present but no port`}catch{w=`lock present but unparseable`}}if(T!==null){let e=await i(T);e===null?w=`agent-presence endpoint at :${T} unreachable`:(re(N(_,`state`,`agent-presence.json`),e),C=`running`,w=``);let t=await a(T);t!==null&&re(N(_,`state`,`agent-effects.json`),t);let n=await o(T);if(n!==null){let e=aje(n);e!==null&&re(N(_,`state`,`watcher-recent.jsonl`),e)}}let E=s(t);E!==null&&re(N(_,`state`,`shadow-head.txt`),E);let D=c(t);D!==null&&re(N(_,`state`,`checkpoint-refs.txt`),D),Z9(eje(n),N(_,`state`,U9)),Z9(tje(n),N(_,`state`,W9)),Z9(N(b,`last-spawn-error.log`),N(_,`state`,`last-spawn-error.log`)),Z9(N(b,ku),N(_,`state`,ku)),Z9(N(b,Au),N(_,`state`,Au));let ee=p(),ne=d(),ie=f(),ae={ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie}};re(N(_,`state`,`runtime.json`),`${JSON.stringify(ae,null,2)}\n`);let oe=C===`running`?`running
|
|
1539
1539
|
`:`not-running (${w})\n`;re(N(_,`state`,`server-status.txt`),oe);let se=e.diagnosticReports===void 0?`not-collected (no collection attempted)`:C7(e.diagnosticReports,y);if(re(N(_,`state`,`diagnostic-reports-status.txt`),`${se}\n`),e.processDir&&g(e.processDir)){let t=N(_,`process`);v(t,{recursive:!0}),m(e.processDir,t,{recursive:!0})}let k=e.redact===!0;k&&YAe({stagingDir:_,contentDir:t}),e.note&&re(N(_,`note.txt`),e.note);let ce=null;e.scrubSecrets===!0&&(ce=bje(_));for(let t of e.extraFiles??[])Z9(t.sourcePath,N(_,`extra`,t.zipName??me(t.sourcePath)))||r.logger?.warn({sourcePath:t.sourcePath},`extra file missing; omitted from bundle`);let le=dje(n),ue=Q9(_),A=[],j=0,de=0;for(let e of ue){let t=$9(_,e),n=te(e).size,r=_je(t)?pje(e):0;A.push({path:t,bytes:n,lines:r}),j+=n,(t.startsWith(`telemetry/`)||t.startsWith(`logs/`))&&(de+=hje(e))}let fe={applied:k};ce!==null&&(fe.secretScrub=ce);let pe={schemaVersion:2,createdAt:l().toISOString(),ok:{version:u(),nodeVersion:ee.nodeVersion,platform:ee.platform,arch:ee.arch},host:{desktop:ne,language:ie},contentDir:{pathSha256:fje(t),absolutePath:k?`<CONTENT_DIR>`:t},telemetry:{localSink:le,otlpPushEnabled:h()},redaction:fe,serverStatus:C,files:A};re(N(_,`manifest.json`),`${JSON.stringify(pe,null,2)}\n`);let M=ue.some(e=>{try{return S(e,`utf-8`).includes(t)}catch{return!1}}),he={stagedDiagnosticReports:y,totalBytes:j,fileCount:A.length,docNameCount:de,contentDirVisible:M,redacted:k},ge=!1;return{stagingDir:_,manifest:pe,summary:he,cleanup:()=>{ge||(ge=!0,O(_,{recursive:!0,force:!0}))}}}catch(e){throw O(_,{recursive:!0,force:!0}),e}}async function Sje(e){let{collected:t,outputPath:n}=e,r=M(n);if(!g(r))throw Error(`ok diagnose bundle: parent directory does not exist: ${r}. Create it or pass --out with an existing parent.`);let i=new PCe.ZipFile,a=Q9(t.stagingDir);for(let e of a){let n=$9(t.stagingDir,e);i.addFile(e,n)}i.end();let o=h(n);return i.outputStream.pipe(o),await new Promise((e,t)=>{o.on(`close`,e),o.on(`error`,t),i.outputStream.on(`error`,t)}),n}function Cje(e,t){let n=N(e,`.ok`,`config.yml`);if(g(n))try{let t=(0,tn.parse)(S(n,`utf-8`)),r=q8(t)?t.content:void 0,i=q8(r)?r.dir:void 0;if(typeof i==`string`&&i.length>0)return be(e,i)}catch(e){t?.warn({configPath:n,err:e},`bug-report: failed to read .ok/config.yml; falling back to project root as content dir`)}return be(e)}async function wje(e,t,n,r,i){let a=E7(t,e.logger),o=await xje({contentDir:Cje(t,e.logger),projectDir:t,redact:e.redact,scrubSecrets:e.redact,note:e.note,extraFiles:e.extraFiles,userLogFiles:[...Pke(a,e.userLogsDir??N(k(),`.ok`,`logs`)),...O7(e.cachesDir??N(k(),`Library`,`Caches`))],userStateFiles:k7(e.bugReportsDir??T7()),diagnosticReports:i,deps:{readDesktopEnv:n,readLanguage:r,logger:e.logger}});try{v(M(e.outputPath),{recursive:!0}),await Sje({collected:o,outputPath:e.outputPath});let t=o.manifest.redaction.secretScrub;return{zipPath:e.outputPath,summary:{level:`full`,systemWide:!1,projectSlug:a,files:o.manifest.files.map(e=>e.path),redactions:t?.redactions??[],redactedLineCount:t?.redactedLineCount??0,generatedAt:o.manifest.createdAt}}}finally{o.cleanup()}}async function Tje(e){let{projectDir:t}=e,n=e.readDesktopEnv??K9,r=e.readLanguage??O9,i=()=>Ake(e.diagnosticReportsDir??N(k(),`Library`,`Logs`,`DiagnosticReports`),new Date);if(e.level===`full`&&t!==void 0)return wje(e,t,n,r,i());let{zipPath:a,summary:o}=await zke({projectDir:t,redact:e.redact,revealDocNames:e.level===`full`,outputPath:e.outputPath,userLogsDir:e.userLogsDir,shipItLogFiles:O7(e.cachesDir??N(k(),`Library`,`Caches`)),bugReportLedgerFiles:k7(e.bugReportsDir??T7()),diagnosticReports:e.level===`full`?i():void 0,logger:e.logger,note:e.note,extraFiles:e.extraFiles,desktop:n(),language:r()});return{zipPath:a,summary:{level:e.level,systemWide:t===void 0,projectSlug:o.projectSlug,files:o.files,redactions:o.redactions,redactedLineCount:o.redactedLineCount,generatedAt:o.generatedAt}}}export{e5 as ALL_EDITOR_IDS,t5 as EDITOR_LABELS,j5 as EDITOR_TARGETS,XDe as HOSTS_WITH_USER_SKILL_DIR,gke as LAUNCH_CONFIG_NAME,OAe as PATH_SHIM_BEGIN,AAe as PATH_SHIM_BLOCK_RE,kAe as PATH_SHIM_END,JOe as addOkPathsToGitExclude,R5 as assertProjectPathSafe,p5 as buildManagedServerEntry,vAe as buildMcpConfigDeclineEvent,yAe as buildMcpConfigMigrateEvent,b7 as classifyExistingMcpEntry,Tje as collectReportBundle,FAe as createCliProbeResolver,on as createTokenStore,jke as defaultBugReportZipPath,We as detectGh,qe as detectGhAccounts,bke as detectInstalledEditors,S5 as droppedManagedKeys,_Oe as editorConfigPathDisplay,gOe as editorEntryLocator,sAe as ensurePiBridge,Q5 as formatTrackedRemediation,ZOe as getExcludedOkPaths,X5 as getInstalledSkillProjectionPaths,YDe as getNativeTomlMcpEditor,Y5 as getOkArtifactPaths,d5 as isEntryUpToDate,m5 as isOwnManagedEntry,TAe as loadConfig,bee as makeLazyProbeTokenStore,T7 as okBugReportsDir,b9 as parseGitHubBlobUrl,EAe as parseGitHubShareUrl,x9 as parseGitHubTreeUrl,y9 as parseGitUrl,jAe as pathInstallMarkerPath,MOe as previewContent,xke as probeOwnManagedEditorMcpEntry,aAe as probePiBridgeState,Z5 as probeTrackedOkPaths,v7 as readExistingMcpEntry,XOe as readSharingMode,_B as redactContent,YOe as removeOkPathsFromGitExclude,mAe as removeOwnMcpEntry,WOe as removeProjectSkill,LAe as removeUserGlobalSkillBundle,UAe as removeUserSkill,ROe as resolveProjectRoot,SAe as runStop,h9 as truncatePriorEntry,E9 as userGlobalSkillBundleTargets,HAe as userSkillPresentAnywhere,DAe as validateLocalFolderForShare,_7 as writeEditorMcpConfig,BAe as writeProjectAiIntegrations,W5 as writeProjectSkill,yke as writeUserMcpConfigs,VAe as writeUserSkill};
|
|
1540
1540
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./dist-D0pUzrgW.mjs";import{_ as e}from"./init-D35_7qCz.mjs";export{e as runInit};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{Ad as r,Bd as i,Fd as a,Fu as o,Gl as s,Hu as c,Id as l,Iu as u,Mt as d,Nd as f,Nl as p,Vl as m,_s as h,hs as g,jd as _,ju as v,rc as y,zd as b}from"./md-manager-BGnqyqi1-BZhj8566.mjs";import{Co as x,Do as S,Dr as ee,H as te,L as ne,Ln as re,No as ie,Nr as ae,Qt as oe,R as se,So as ce,Tt as le,Ui as ue,Wi as de,Wn as fe,Wr as pe,aa as me,at as he,bo as ge,co as _e,m as ve,oo as ye,qi as be,ro as xe,rt as Se,xo as C,xr as Ce,yo as we,zo as Te}from"./dist-
|
|
1
|
+
import{i as e,o as t,t as n}from"./rolldown-runtime-tZXQYakl.mjs";import{Ad as r,Bd as i,Fd as a,Fu as o,Gl as s,Hu as c,Id as l,Iu as u,Mt as d,Nd as f,Nl as p,Vl as m,_s as h,hs as g,jd as _,ju as v,rc as y,zd as b}from"./md-manager-BGnqyqi1-BZhj8566.mjs";import{Co as x,Do as S,Dr as ee,H as te,L as ne,Ln as re,No as ie,Nr as ae,Qt as oe,R as se,So as ce,Tt as le,Ui as ue,Wi as de,Wn as fe,Wr as pe,aa as me,at as he,bo as ge,co as _e,m as ve,oo as ye,qi as be,ro as xe,rt as Se,xo as C,xr as Ce,yo as we,zo as Te}from"./dist-D0pUzrgW.mjs";import{i as w,n as T,o as E,r as Ee,s as D,t as O}from"./colors-r_owlCuY.mjs";import{t as k}from"./is-object-BGze3w87.mjs";import{t as De}from"./constants-CqleiXu2.mjs";import{t as Oe}from"./preview-B_F6SpZs.mjs";import{createRequire as ke}from"node:module";import{execFileSync as Ae}from"node:child_process";import je,{basename as Me,dirname as A,isAbsolute as Ne,join as j,posix as Pe,relative as M,resolve as N,sep as P,win32 as Fe}from"node:path";import F from"node:process";import{fileURLToPath as Ie}from"node:url";import{cpSync as Le,existsSync as I,lstatSync as Re,mkdirSync as ze,readFileSync as L,readdirSync as Be,readlinkSync as Ve,realpathSync as He,rmSync as Ue,statSync as We,writeFileSync as Ge}from"node:fs";import{homedir as R}from"node:os";import{inspect as Ke,stripVTControlCharacters as qe,styleText as z}from"node:util";import*as Je from"node:readline";import{AsyncLocalStorage as Ye,AsyncResource as Xe}from"node:async_hooks";var Ze=n((e=>{var t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},n=class extends t{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=n})),Qe=n((e=>{let{InvalidArgumentError:t}=Ze();var n=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}e.Argument=n,e.humanReadableArgName=r})),$e=n((e=>{let{humanReadableArgName:t}=Qe();var n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(e=>t(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(n?` `+n:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
|
|
2
2
|
`)}displayWidth(e){return r(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
|
|
3
3
|
`+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
|
|
4
4
|
`)}};function r(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,``)}e.Help=n,e.stripColor=r})),et=n((e=>{let{InvalidArgumentError:t}=Ze();var n=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=a(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,n)=>{if(!this.argChoices.includes(e))throw new t(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,n):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?i(this.name().replace(/^no-/,``)):i(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0&&r;return t.negate===(i===e)}};function i(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function a(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
|
|
@@ -689,5 +689,5 @@ export default function okBridge(pi: {
|
|
|
689
689
|
`));let g=`${s?``:``}${m}`;return g!==o&&S(e,g,{mode:Ca(e)}),a&&g===o?{kind:`unchanged`}:{kind:d?`overwritten`:`written`}}const _o=e=>e!==`project`,vo=e=>e!==`user`;async function yo(){let e=await Ma({message:`Where should the MCP server be configured?
|
|
690
690
|
`,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function bo(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??yo)():`both`}async function xo(e){return La({message:`How do you want to handle OpenKnowledge config files (.ok/, .mcp.json)?`,default:e,choices:[{name:`Share with my team (commit alongside content)`,value:`shared`,description:`OK config gets committed alongside your project content.`},{name:`Local only (keep out of git via .git/info/exclude)`,value:`local-only`,description:"OK config stays on this machine only; teammates do not see it. Safe escape hatch via `ok config-sharing share`."}]})}async function So(e){if(e.sharing!==void 0)return e.sharing;let t=qi(e.projectRoot)===`local-only`||e.freshProject===!0?`local-only`:`shared`;return e.isTTY??process.stdout.isTTY?(e.promptFn??xo)(t):t}var $=class extends Error{constructor(e){super(e),this.name=`ContentDirError`}};function Co(e){if(e===void 0||e===!0)return new Set(Se);if(e===!1)return new Set;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return new Set(le.filter(e=>t.includes(e)))}function wo(e,t,n){let r=N(n,e),i;try{i=We(r)}catch(e){let t=e.code;throw t===`ENOENT`?new $(`--content-dir path does not exist: ${r}`):new $(`--content-dir path is not accessible (${t??`unknown error`}): ${r}`)}if(!i.isDirectory())throw new $(`--content-dir must be a directory: ${r}`);let a=To(t),o=To(r),s=M(a,o);if(s.startsWith(`..`)||Ne(s))throw new $(`--content-dir must be inside the project root (${t}); got ${r}`);return s===``?`.`:s}function To(e){try{return He(e)}catch{return e}}const Eo=`open-knowledge-ui`;function Do(e,t,n){try{let r=e.detectPath?.(t,n)??A(e.configPath(t,n));return I(r)}catch{return!1}}function Oo(e,t,n){try{let r=N(A(e.configPath(t,n))),i=N(e.detectPath?.(t,n)??r);return i===r||r.startsWith(i+P)}catch{return!1}}function ko(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}let s=n.pruneOnly===!0;if(s&&(e.format===`file`||!I(o)))return{editorId:e.id,label:e.label,action:`skipped-flag`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}};let c=!n.skipAvailabilityCheck||e.offerOnlyWhenDetected===!0||Oo(e,t,r);if(!i&&c&&!Do(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{oa(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}if(e.format===`file`)return jo(e,o,a,n,{isProjectScope:i!==void 0});let l;try{l=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}try{s||ze(A(o),{recursive:!0})}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),...i===void 0?{}:{configScope:`project`}}}let u={action:`written`},d;try{ie(`${o}.lock`,()=>{let t=Xa(o).writePath;if(s||ze(A(t),{recursive:!0}),e.format===`toml`){let r=po(Ur(),t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}if(e.format===`yaml`){let r=go(t,e.topLevelKey,a,l,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason);return}let r=fo(t,e.topLevelKey,a,l,e.serverMapSubKey,n.replaceEntry===!0,n.pruneOnly===!0);u.action=r.kind,r.kind===`declined`&&(u.declineReason=r.reason)},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){d=e instanceof Error?e:Error(String(e))}return d?{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:d.message,...i===void 0?{}:{configScope:`project`}}:u.action===`declined`?{editorId:e.id,label:e.label,action:`declined`,configPath:o,serverName:a,declineReason:u.declineReason,...i===void 0?{}:{configScope:`project`}}:{editorId:e.id,label:e.label,action:u.action===`unchanged`?`skipped-flag`:u.action,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}const Ao={pi:Ha};function jo(e,t,n,r,i){let a=i.isProjectScope?{configScope:`project`}:{},o=r=>({editorId:e.id,label:e.label,action:`failed`,configPath:t,serverName:n,error:r instanceof Error?r.message:String(r),...a}),s=Ao[e.id];if(!s)return o(Error(`No managed-file builder registered for editor "${e.id}" (format: 'file' targets need a MANAGED_FILE_BUILDERS entry).`));let c;try{c=s(r)}catch(e){return o(e)}try{ze(A(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{ie(`${t}.lock`,()=>{let e=null;try{e=L(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}S(t,c,e===null?void 0:{mode:Ca(t)}),l.action=e===null?`written`:`overwritten`},{onWarn:(e,t)=>process.stderr.write(`[ok] ${e} ${JSON.stringify(t)}\n`)})}catch(e){return o(e)}return{editorId:e.id,label:e.label,action:l.action,configPath:t,serverName:n,...a}}function Mo(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!I(n)))return{editorId:e.id,label:e.label,path:n}}async function No(e){let t=Bi(e.editors).filter(e=>e.scope===`global`),n={mode:`published`,skipAvailabilityCheck:!0,...e.replaceEntry===!0?{replaceEntry:!0}:{},...e.pruneOnly===!0?{pruneOnly:!0}:{}};return t.map(t=>ko(t,``,n,e.home))}function Po(e,t,n,r){let i=Io(e,t,n,r);return i.kind===`present`?i.entry:null}function Fo(e,t,n,r){let i=uo(e,t,r);if(!k(i))return{kind:`no-entry`};let a=i[n];return k(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function Io(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!I(i))return{kind:`absent`};try{if(We(i).size>io)return{kind:`decline`,reason:`oversize`}}catch(e){return{kind:`decline`,reason:ya(e)}}let a;try{a=L(i,`utf-8`)}catch(e){return{kind:`decline`,reason:ya(e)}}if(a.trim()===``)return{kind:`absent`};if(e.format===`file`)return{kind:`present`,entry:Va(a)};let o=e.serverName(t);if(e.format===`toml`){let t;try{t=Ur().parseToObject(a)}catch{return{kind:`decline`,reason:`unparseable`}}return Fo(t,e.topLevelKey,o,e.serverMapSubKey)}if(e.format===`yaml`){let t=(0,Ar.parseDocument)(a.charCodeAt(0)===65279?a.slice(1):a);return t.errors.length>0?{kind:`decline`,reason:`unparseable`}:Fo(t.toJS()??{},e.topLevelKey,o,e.serverMapSubKey)}let s=$a(a);return s?eo(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:Fo(ge(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}async function Lo(e={}){let t=N(e.cwd??process.cwd()),n=Ga(t,{homeDir:e.home}),r=n.projectRoot;if(ae(r,e.home??R()))throw new te(r);let i=!I(j(r,`.ok`)),a=n.gitRootPromoted?M(r,t):void 0,o=e.contentDir===void 0?n.defaultContentDir:wo(e.contentDir,r,t);n.ancestorPromoted?console.log(`[ok] Opened existing project at ${r}`):n.gitRootPromoted&&i&&o===`.`&&process.stderr.write(`${D(`[ok] Content scope promoted to the git repo root: ${r}`)}\n Ran in ${a}/, but .ok/ lives at the git root (one .ok/ per git repo),\n so the whole repo is now the content scope. To narrow it, re-run with\n \`ok init --content-dir .\`, or set content.dir: ${a} in .ok/config.yml.\n`);let c={mode:e.devMcp?`dev`:`published`},l=await fe(r),u;try{u=Ce(r,{contentDir:o})}catch(t){let i=Q.claude.configPath(r,e.home);return{projectRoot:r,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:l.didInit,rootGitignoreCreated:!1,gitRootPromoted:n.gitRootPromoted,promotedFromDir:a,contentDirRequested:e.contentDir,contentScaffoldFailed:!0,mcpAction:`failed`,mcpPath:i,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`,sharing:{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:!1}}}let d=u.created.includes(De),f=!1;if(l.didInit)try{f=_e(r)===`created`}catch(e){console.warn(`[ok] Skipping .gitignore seed at ${r}: ${e instanceof Error?e.message:String(e)}`)}try{ue(r)===`removed`&&console.warn(`[ok] Removed the OpenKnowledge project-skill lines from .gitignore. The skill is ordinary project content now — commit it if your team wants it on clone.`)}catch(e){console.warn(`[ok] Skipping project-skill .gitignore cleanup at ${r}: ${e instanceof Error?e.message:String(e)}`)}let p=await bo({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),m=e.editors??Uo(r,e.home),h=e.editors??m,g=Bi(m),_=Bi(h),v=e.mcp===!1||p===null,y=Array.from(new Map([...g,...v?[]:_].map(e=>[e.id,e])).values()),b=g.filter(t=>Do(t,r,e.home)),x=[],S=[],ne=new Set;for(let t of y){if(v){let n=``;try{n=t.configPath(r,e.home)}catch{}x.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n,serverName:t.serverName(r)});continue}if(_o(p)&&g.includes(t)&&t.scope===`global`&&x.push(ko(t,r,c,e.home)),vo(p)&&_.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(r),i=ko(t,r,c,e.home,n);x.push(i),(i.action===`written`||i.action===`overwritten`)&&ne.add(n)}}let ie=new Set;for(let t of _){let n=t.projectSkillPath?.(r);!n||ie.has(n)||(ie.add(n),S.push(_a(t,r,{home:e.home})))}let oe=ga(r,_.map(e=>e.id));oe&&S.push(oe);let se=S.filter(e=>e.action===`written`||e.action===`overwritten`).map(e=>e.editorId);if(se.length>0){let t=e.home??R();de({source:s,skills:[ve.project],agents:se,scope:r},{home:t,enabled:me(t).enabled})}let ce=!v&&p!==null&&vo(p)?_.filter(e=>!e.projectConfigPath&&!e.projectSkillPath).map(e=>e.label):void 0,pe=v?[]:b.map(e=>Mo(e,r)).filter(e=>e!==void 0).filter(e=>!ne.has(e.path)),he=e.installUserSkill??ee,ge=e.home??R(),be=Co(e.skills),xe=!1,Se=!1,C=!1,we=!1,Te=!1;for(let t of le){if(!be.has(t))continue;await ye(ge,ve[t],!0).catch(()=>{}),xe=!0;let n=await he({home:e.home,bundleId:t,force:!0});n===`installed`?Se=!0:n===`failed`?C=!0:n===`no-hosts`?Te=!0:we=!0}let w=C?`failed`:Se?`installed`:xe&&we?`skip-current`:xe&&Te?`no-hosts`:`declined`,T=Se?re(ge).map(e=>e.editorId):[],E=v?`skipped-flag`:`skipped-missing`,Ee=x.find(e=>e.editorId===`claude`)??x[0]??{action:E,configPath:Q.claude.configPath(r,e.home)},O=await Ro({projectRoot:r,desiredMode:await So({sharing:e.sharing,projectRoot:r,isTTY:e.isTTY,freshProject:i,promptFn:e.sharingPromptFn}),explicitFlag:e.sharing});return{projectRoot:r,contentCreated:u.created,contentUpdated:u.updated,contentSkipped:u.skipped,editors:x,projectSkills:S,legacyProjectConfigs:pe,skillInstall:w,skillHosts:T,didGitInit:l.didInit,rootGitignoreCreated:f,gitRootPromoted:n.gitRootPromoted,promotedFromDir:a,contentDir:d?o:void 0,contentDirRequested:e.contentDir,contentScaffoldFailed:!1,mcpAction:Ee.action,mcpPath:Ee.configPath,mcpError:`error`in Ee?Ee.error:void 0,projectScopeUnsupportedLabels:ce,sharing:O}}async function Ro(e){let{projectRoot:t,desiredMode:n,explicitFlag:r}=e,i=qi(t);if(i===`no-git`)return{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:r===`local-only`};let a=Ui(t);if(n===`local-only`){let e=Gi(t,a);if(e.kind===`refused-tracked`){let t=e;return{kind:`refused-tracked`,tracked:t.tracked,remediation:t.remediation}}return e.kind===`no-exclude`?{kind:`no-exclude`,reason:e.reason,localOnlyRequested:r===`local-only`}:zo(t,e,`add`)}if(i===`shared`)return{kind:`applied`,mode:`shared`,action:`noop`,appended:[],alreadyPresent:[],removed:[]};let o=Ki(t,a);return o.kind===`no-exclude`?{kind:`no-exclude`,reason:o.reason,localOnlyRequested:!1}:zo(t,o,`remove`)}function zo(e,t,n){let r=qi(e);return n===`add`?{kind:`applied`,mode:r,action:t.appended.length>0?`added`:t.removed.length>0?`cleaned`:`noop`,appended:t.appended,alreadyPresent:t.alreadyPresent,removed:t.removed}:{kind:`applied`,mode:r,action:`removed`,appended:[],alreadyPresent:[],removed:t.removed}}function Bo(e){switch(e){case`permission-denied`:return`permission denied; check file and parent-directory permissions`;case`unresolved-symlink`:return`could not resolve the path or symlink; check permissions and symlink cycles`;case`not-a-file`:return`config path is not a regular file`;case`disappeared`:return`config disappeared while being read; retry to check its current state`;case`unreadable`:return`could not read the config file; check that the path is accessible`;case`unparseable`:return`config could not be parsed`;case`oversize`:return`config too large to edit safely`;case`duplicate-container`:return`duplicate server block`;case`no-native-writer`:return`no format-preserving writer available`;case void 0:return`config not readable`;default:throw Error(`unhandled MCP decline reason: ${e}`)}}function Vo(e,t){let n=[],r=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),i=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),a=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`);e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/ (default branch: main)`),e.rootGitignoreCreated&&n.push(`Seeded .gitignore at ${t}/.gitignore (.DS_Store)`);let s=j(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(O(`Content scaffolded at ${s}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(O(`Content already present at ${s}/`)),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0){if(n.push(O(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`)}else if(a)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(o)n.push(O(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(O(`MCP server configuration:`));for(let r of e.editors){let e=r.configPath.startsWith(t)?M(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),i=r.serverName===`open-knowledge`?``:` (${r.serverName})`,a=r.configScope===`project`?` (project)`:``,o=`${r.label}${a}`,s=` `.repeat(Math.max(1,20-o.length)),c=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${o}${s}${e} ${E(`registered`)}${i}${c}`);break;case`overwritten`:n.push(` ${o}${s}${e} ${E(`updated`)}${i}${c}`);break;case`skipped-missing`:n.push(` ${o}${s}${e} config root missing; skipped`);break;case`failed`:n.push(` ${o}${s}${e} ${Ee(`FAILED`)}: ${r.error}`);break;case`declined`:n.push(` ${o}${s}${e} left unchanged (${Bo(r.declineReason)})`);break;case`skipped-flag`:break;default:r.action}}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}}if(e.projectSkills.length>0){n.push(``),n.push(O(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?M(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${E(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${E(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`skipped-prerequisite`:n.push(` ${e}${i}OpenKnowledge MCP is not configured; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${Ee(`FAILED`)}: ${r.error}`)}}}if(i&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${M(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall)switch(n.push(``),n.push(O(`User-global skill:`)),e.skillInstall){case`installed`:{let t=(e.skillHosts??[]).map(e=>Y[e]??e),r=t.length>0?t.join(`, `):`the shared ~/.agents store`;n.push(` open-knowledge ${E(`installed for ${r}`)}`),n.push(` ${T(`Counted on skills.sh (skill name + source repo, once per machine).`)}`),n.push(` ${T(`Opt out: DO_NOT_TRACK=1, or Settings → User → Preferences.`)}`);break}case`skip-current`:n.push(` open-knowledge ${E(`already installed at current version`)}`);break;case`declined`:n.push(` open-knowledge ${T(`skipped for this run (--no-skills)`)}`),n.push(` ${T(`Nothing was installed or removed. Any built-in skills already on this`)}`),n.push(` ${T(`machine are untouched. Run init without the flag to install them:`)}`),n.push(` ${T(` ok init`)}`);break;case`no-hosts`:n.push(` open-knowledge ${T(`skipped — no supported agent host detected in your home directory`)}`);break;case`failed`:n.push(` ${D(`open-knowledge install failed — MCP still configured; retry with:`)}`),n.push(` ${D(` ok repair-skills`)}`)}if(e.contentDirRequested!==void 0&&e.contentDir===void 0&&!e.contentScaffoldFailed?(n.push(``),n.push(D(`⚠ --content-dir ${e.contentDirRequested} ignored — .ok/config.yml already exists`)),n.push(` Edit .ok/config.yml → content.dir directly to change the content scope.`)):e.contentDir!==void 0&&e.contentDir!==`.`?(n.push(``),n.push(`Content scope set to ${e.contentDir}/ (content.dir in .ok/config.yml).`)):e.gitRootPromoted&&e.contentDir===`.`&&e.contentDirRequested===void 0&&(n.push(``),n.push(D(`⚠ Content scope promoted to the git repo root`)),n.push(` .ok/ was initialized at ${t} because it contains a .git folder (one .ok/ per git repo),`),n.push(` not the sub-folder you ran \`ok init\` in${e.promotedFromDir?` (${e.promotedFromDir})`:``}. The whole repo is now the content scope.`),e.promotedFromDir&&(n.push(" To scope to just that sub-folder, re-run `ok init --content-dir .` from there, or set"),n.push(` content.dir: ${e.promotedFromDir} in .ok/config.yml.`))),e.preview?(n.push(``),n.push(Oe(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),n.push(``),n.push(...Ko(e.sharing,t)),r){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`${E(`✓`)} ${O(`Next steps:`)}`),n.push(` 1. Open your editor (${w(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ${w(`ok seed --list-packs`)} — browse the starter packs`),n.push(` - ${w(`ok seed`)} — scaffold an empty repo`),n.push(` 4. Ask your agent to capture a source, research a topic, or build a wiki —`),n.push(` the procedures ship as skills alongside the MCP tools.`)}return n.join(`
|
|
691
691
|
`)}function Ho(e,t){return{projectRoot:e.projectRoot,gitRootPromoted:e.gitRootPromoted,promotedFromDir:e.promotedFromDir??null,contentDir:t.contentDir,contentDirRequested:e.contentDirRequested??null,contentDirApplied:e.contentDir!==void 0,contentFileCount:t.contentFileCount,previewError:e.previewWarning??null,didGitInit:e.didGitInit,mcpAction:e.mcpAction,editors:e.editors.map(e=>({editorId:e.editorId,label:e.label,action:e.action,configPath:e.configPath,scope:e.configScope===`project`?`project`:`user`}))}}function Uo(e,t){let n=[];for(let r of Gr)r!==`claude-desktop`&&Do(Q[r],e,t)&&n.push(r);return n}function Wo(){let e={log:console.log,info:console.info,debug:console.debug},t=(...e)=>{process.stderr.write(`${e.map(e=>typeof e==`string`?e:Ke(e)).join(` `)}\n`)};return console.log=t,console.info=t,console.debug=t,()=>{console.log=e.log,console.info=e.info,console.debug=e.debug}}function Go(){return new ut(`init`).description(`Scaffold .ok/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the .ok/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging`).option(`--content-dir <dir>`,`Limit content to <dir> instead of the whole project. <dir> is interpreted relative to your current directory (e.g. "." = the folder you run the command in), then saved to .ok/config.yml as content.dir.`).option(`--json`,`Emit a structured JSON summary to stdout (diagnostics stay on stderr)`).option(`--skills <ids>`,`Install only the named user-global skill bundles (comma list: discovery,write-skill)`).option(`--no-skills`,`Do not install any user-global skill bundles`).addOption(new ft(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).addOption(new ft(`--shared`,`Commit OK config alongside content (the default for fresh repos)`).conflicts(`localOnly`)).addOption(new ft(`--local-only`,`Keep OK config out of git via .git/info/exclude (per-clone, not committed)`).conflicts(`shared`)).action(async e=>{let t=process.cwd(),n=e.shared?`shared`:e.localOnly?`local-only`:void 0,r=e.json?Wo():null;try{let r;try{r=await Lo({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope,sharing:n,contentDir:e.contentDir,skills:e.skills})}catch(e){if(e instanceof $||e instanceof te){process.stderr.write(`${e.message}\n`),process.exitCode=64;return}if(e instanceof ne||e instanceof se){process.stderr.write(`${e.message}\n`),process.exitCode=78;return}if(e instanceof he){process.stderr.write(`open-knowledge could not initialize a git repo for this project. Re-run, or run 'git init' yourself in the project folder.
|
|
692
|
-
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-
|
|
692
|
+
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}let i=r.contentDir??`.`,a=null,{loadConfig:o}=await import(`./loader-TircuzL8.mjs`),{resolveContentDir:s}=await import(`./dist-BYaz0taZ.mjs`),c;try{c=o(r.projectRoot).config,i=c.content.dir}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}if(c)try{let{previewContent:e}=await import(`./preview-D14ciGsV.mjs`),t=s(c,r.projectRoot);r.preview=e({projectDir:r.projectRoot,contentDir:t}),a=r.preview.totalCount}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}e.json?process.stdout.write(`${JSON.stringify(Ho(r,{contentDir:i,contentFileCount:a}),null,2)}\n`):process.stdout.write(`${Vo(r,r.projectRoot)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)}finally{r?.()}})}function Ko(e,t){let n=[];switch(e.kind){case`applied`:return n.push(O(`Sharing mode:`)),e.mode===`local-only`?e.action===`added`?(n.push(` ${E(`local-only`)} — appended ${e.appended.length} path(s) to ${O(`${t}/.git/info/exclude`)} (per-clone, not committed).`),e.removed.length>0&&n.push(` cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`)):e.action===`cleaned`?n.push(` ${E(`local-only`)} — already excluded; cleared ${e.removed.length} stale entry(s) left by an older version: ${e.removed.join(`, `)}.`):e.action===`noop`&&e.alreadyPresent.length>0?n.push(` ${E(`local-only`)} — already excluded; nothing to do.`):n.push(` ${E(`local-only`)}`):e.action===`removed`?n.push(` ${E(`shared`)} — removed OK paths from ${O(`${t}/.git/info/exclude`)}; commit the files to share with teammates.`):n.push(` ${E(`shared`)} — OK config will be committed alongside content.`),n;case`refused-tracked`:n.push(D(`Sharing mode: switch to local-only deferred`));for(let t of e.remediation.split(`
|
|
693
693
|
`))n.push(t.length>0?` ${t}`:``);return n.push(` Re-run ${w(`ok config-sharing unshare`)} after resolving to complete the switch.`),n;case`no-exclude`:if(e.localOnlyRequested)n.push(D(`Sharing mode: --local-only requested but no git repo found — option ignored`)),n.push(` Run ${w(`git init`)} (or open this folder via OK Desktop, which can scaffold a repo) and then ${w(`ok config-sharing unshare`)}.`);else if(e.reason===`no-git`)return[];else n.push(D(`Sharing mode unavailable: ${e.reason}.`));return n}}export{yi as $,wa as A,$i as B,Ga as C,ct as Ct,Ma as D,La as E,sa as F,qi as G,Wi as H,va as I,Y as J,Ki as K,ua as L,ya as M,la as N,Ca as O,oa as P,bi as Q,_a as R,Xa as S,ut as St,Ba as T,Ui as U,Ji as V,Yi as W,Kr as X,Q as Y,X as Z,Lo as _,Zt as _t,Ho as a,Z as at,No as b,H as bt,Vo as c,li as ct,Do as d,J as dt,xi as et,Po as f,Nr as ft,So as g,Hn as gt,wo as h,$n as ht,Ro as i,Ci as it,ba as j,Sa as k,Ko as l,Wr as lt,bo as m,Fr as mt,Eo as n,ni as nt,Io as o,wi as ot,Co as p,Mr as pt,Gr as q,Ao as r,ai as rt,Uo as s,Fi as st,$ as t,Si as tt,Go as u,Ur as ut,co as v,Jt as vt,Ha as w,ft as wt,Oo as x,xt,ko as y,qt as yt,Gi as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Co as e,Do as t,bo as n}from"./dist-
|
|
1
|
+
import{Co as e,Do as t,bo as n}from"./dist-D0pUzrgW.mjs";import{A as r,M as i,O as a}from"./init-D35_7qCz.mjs";import{t as o}from"./is-object-BGze3w87.mjs";import{t as s}from"./removal-file-path-dEH5rj0t.mjs";import{join as c}from"node:path";import{readFileSync as l}from"node:fs";const u={allowTrailingComma:!0,disallowComments:!1};function d(e,t){return e.error===1&&e.offset===0&&t.charCodeAt(0)===65279}function f(o){let f=s(c(o,`.claude`,`launch.json`));if(f.kind!==`ready`)return f;let m=f.path,h;try{h=l(m,`utf-8`)}catch(e){return{kind:`declined`,reason:i(e)}}let g=[],_=e(h,g,u)??void 0;if(g.some(e=>!d(e,h))||_?.type!==`object`)return{kind:`declined`,reason:`unparseable`};let v=n(_).configurations;if(!Array.isArray(v))return{kind:`not-present`};let y=v.findIndex(p);if(y===-1)return{kind:`not-present`};let{text:b,changed:x}=r(h,[`configurations`,y]);return x?(t(m,b,{mode:a(m)}),{kind:`removed`}):{kind:`not-present`}}function p(e){if(!o(e))return!1;let t=e;if(t.name!==`open-knowledge-ui`||!Array.isArray(t.runtimeArgs))return!1;let n=t.runtimeArgs;return t.runtimeExecutable===`/bin/sh`?n.length===3&&n[0]===`-l`&&n[1]===`-c`&&typeof n[2]==`string`&&/^# ok-ui-v[1-9]\d*$/.test(n[2].split(/\r?\n/,1)[0]??``):t.runtimeExecutable===`npx`?m.some(e=>h(n,e)):t.runtimeExecutable===`powershell`&&n.length===4&&n[0]===`-NoProfile`&&n[1]===`-NonInteractive`&&n[2]===`-Command`&&typeof n[3]==`string`&&/^# ok-ui-win-v[1-9]\d*$/.test(n[3].split(/\r?\n/,1)[0]??``)}const m=[[`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge@latest`,`ui`]];function h(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}export{f as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{as as e,ju as t,rl as n,tl as r,to as i,ul as a,xl as o}from"./md-manager-BGnqyqi1-BZhj8566.mjs";import{jo as s,ko as c,x as l}from"./dist-
|
|
1
|
+
import{as as e,ju as t,rl as n,tl as r,to as i,ul as a,xl as o}from"./md-manager-BGnqyqi1-BZhj8566.mjs";import{jo as s,ko as c,x as l}from"./dist-D0pUzrgW.mjs";import{t as u}from"./is-object-BGze3w87.mjs";import{t as d}from"./constants-CqleiXu2.mjs";import{resolve as f}from"node:path";import{existsSync as p,readFileSync as m}from"node:fs";import{realpath as h}from"node:fs/promises";var g=t();async function _(e){let t=f(e);try{return await h(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}function v(e){if(!p(e))return{value:null,path:e,source:null,doc:null};let t;try{t=m(e,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`[config] Failed to read ${e}: ${n}`),{value:null,path:e,source:null,doc:null,diagnostic:{code:`UNREADABLE`,detail:`${e}: ${n}`}}}let n=(0,g.parseDocument)(t);if(n.errors.length>0){let r=n.errors.map(e=>e.message).join(`; `);return console.warn(`[config] Failed to parse ${e}: ${r}`),{value:null,path:e,source:t,doc:null,diagnostic:{code:`YAML_PARSE`,detail:`${e}: ${r}`}}}let r=n.toJSON();return u(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function y(e,t){return e.map(e=>{let n=e.path.map(e=>typeof e==`symbol`?String(e):e),r={path:n,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=a({file:t.path,source:t.source,doc:t.doc,path:n});if(e!==void 0)return{...r,source:e}}return r})}function b(t){let a=t??process.cwd(),u=[],p=[],m=[],h=[],g=s(`user`,a),_=c({absPath:g});p.push(..._.diagnostics),!_.valid&&_.sidelinedTo!==void 0&&m.push({from:g,to:_.sidelinedTo}),_.valid&&_.source!==void 0&&u.push(g);let b=(e,t=!1)=>{let n=v(e);if(n.diagnostic!==void 0&&p.push(n.diagnostic),n.value===null)return{};let a=r({value:n.value,file:n.path,source:n.source,doc:n.doc});p.push(...a),u.push(e);let s=a.length>0?o(n.value):n.value;return t&&h.push(...i({value:s,file:n.path,source:n.source,doc:n.doc})),s},x=f(a,`.ok`,d),S=b(x,!0),C=b(s(`project-local`,a)),w=e(_.value,S,C),T=l.safeParse(w);if(!T.success){let e=v(x),t={code:`SCHEMA_INVALID`,issues:y(T.error.issues,e)};throw Error(n(t))}return{config:T.data,sources:u,diagnostics:p,sidelined:m,ignoredCommittedKeys:h}}function x(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??b,r=new Map,i=new Map,a=_(e.startupCwd);return async o=>{let s=await _(o??e.startupCwd),c=Date.now(),l=r.get(s);if(l&&l.expiresAt>c)return l.config;let u=i.get(s);if(u)return await u;let d=(async()=>{if(s===await a)return r.set(s,{config:e.startupConfig,expiresAt:Date.now()+t}),e.startupConfig;let i=n(s).config;return r.set(s,{config:i,expiresAt:Date.now()+t}),i})();i.set(s,d);try{return await d}finally{i.delete(s)}}}export{b as n,x as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./loader-Il_r9h-s.mjs";export{e as loadConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ro as e}from"./dist-
|
|
1
|
+
import{ro as e}from"./dist-D0pUzrgW.mjs";import{execFile as t}from"node:child_process";const n=new Set([`http:`,`https:`]),r=/[\u0000-\u0020\u007F-\u009F"'`\\&|<>^()$;{}[\]*?!~]/;function i(e,t){console.warn(`Could not auto-open browser (${t}); visit ${e} manually`)}function a(a){let o;try{o=new URL(a)}catch{i(a,`invalid URL`);return}if(!n.has(o.protocol)){i(a,`unsupported scheme '${o.protocol}'`);return}if(r.test(a)){i(a,`URL contains unsafe characters`);return}let s=process.platform===`darwin`?`open`:process.platform===`win32`?`cmd`:`xdg-open`,c=process.platform===`win32`?[`/c`,`start`,``,a]:[a];t(s,c,e({}),e=>{e&&console.warn(`Could not auto-open browser (${e.message}); visit ${a} manually`)})}export{a as openBrowser};
|