@inkeep/open-knowledge 0.0.0-dev-20260428211426 → 0.0.0-dev-20260429030631

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/cli.mjs +235 -232
  2. package/dist/constants-B-gLpuaA.mjs +2 -0
  3. package/dist/{dist-Ct-gJ7iD.mjs → dist-B7U9dfgx.mjs} +1 -1
  4. package/dist/{dist-0qFIeeXA.mjs → dist-D6sXBEzw.mjs} +11 -11
  5. package/dist/index.mjs +1 -1
  6. package/dist/{init-CMkePWjl.mjs → init-BBiPSV-w.mjs} +22 -7
  7. package/dist/init-BEo-n_Uy.mjs +1 -0
  8. package/dist/{init-D0YdyLe_.mjs → init-DktmtY_7.mjs} +4 -4
  9. package/dist/init-yNwtj9hS.mjs +1 -0
  10. package/dist/loader-CX_sYqFb.mjs +1 -0
  11. package/dist/{loader-BJU3jneI.mjs → loader-E7RjFMCP.mjs} +2 -2
  12. package/dist/paths-CIFllhl9.mjs +1 -0
  13. package/dist/{paths-CNpYe27Q.mjs → paths-t5fX6xpy.mjs} +2 -2
  14. package/dist/preview-B3wdzX-m.mjs +1 -0
  15. package/dist/{preview-CXP9kBv6.mjs → preview-CfwdEokP.mjs} +2 -2
  16. package/dist/public/assets/{ActivityModeContent-Ccu_n0bV.js → ActivityModeContent-DB-Anrff.js} +1 -1
  17. package/dist/public/assets/{DocumentContext-C1msvcHp.js → DocumentContext-BQEvrOdm.js} +1 -1
  18. package/dist/public/assets/McpConsentDialogBody-KLtPoa1G.js +1 -0
  19. package/dist/public/assets/{SourceEditor-OFesfBB2.js → SourceEditor-pg77Ty2h.js} +1 -1
  20. package/dist/public/assets/{clipboard-DAcKCHl1.js → clipboard-DO2TbwyY.js} +1 -1
  21. package/dist/public/assets/{index-CwFTGDhe.js → index-Did2wKqz.js} +63 -63
  22. package/dist/public/index.html +3 -3
  23. package/dist/src-C0IVz8Sw.mjs +1 -0
  24. package/dist/start-B8Duv9Ct.mjs +2 -0
  25. package/dist/start-BDCAyg0c.mjs +1 -0
  26. package/package.json +1 -1
  27. package/dist/constants-DCJlLBSi.mjs +0 -2
  28. package/dist/init-D-5Gc0uq.mjs +0 -1
  29. package/dist/init-DUA_XKK1.mjs +0 -1
  30. package/dist/loader-1GTY76cQ.mjs +0 -1
  31. package/dist/paths-fx16Ahvg.mjs +0 -1
  32. package/dist/preview-CHvLSbhb.mjs +0 -1
  33. package/dist/public/assets/McpConsentDialogBody-Csjet19t.js +0 -1
  34. package/dist/src-BIqAAP5m.mjs +0 -1
  35. package/dist/start-BOjBm-nL.mjs +0 -2
  36. package/dist/start-CZFHRjtT.mjs +0 -1
@@ -0,0 +1,2 @@
1
+ import"./dist-CXdg7KnM.mjs";var e=`0.0.0-dev-20260429030631`;const t=`config.yml`,n=`cache`,r=e,i=`open-knowledge`;export{r as i,t as n,i as r,n as t};
2
+ //# sourceMappingURL=constants-B-gLpuaA.mjs.map
@@ -1 +1 @@
1
- import"./dist-CXdg7KnM.mjs";import{l as e,o as t}from"./server-lock-n3Y5JWNv-3o7br8XE.mjs";import{Ct as n,D as r,Dt as i,E as a,Gt as o,N as s,Z as c,_ as l,et as u}from"./dist-0qFIeeXA.mjs";export{l as ProjectGitInitError,a as UiLockCollisionError,r as acquireUiLock,s as bootServer,c as ensureProjectGit,u as getLogger,t as isProcessAlive,e as readServerLock,n as readUiLock,i as releaseUiLock,o as updateUiLockPort};
1
+ import"./dist-CXdg7KnM.mjs";import{l as e,o as t}from"./server-lock-n3Y5JWNv-3o7br8XE.mjs";import{Ct as n,D as r,Dt as i,E as a,Gt as o,N as s,Z as c,_ as l,et as u}from"./dist-D6sXBEzw.mjs";export{l as ProjectGitInitError,a as UiLockCollisionError,r as acquireUiLock,s as bootServer,c as ensureProjectGit,u as getLogger,t as isProcessAlive,e as readServerLock,n as readUiLock,i as releaseUiLock,o as updateUiLockPort};
@@ -117,14 +117,14 @@ What to log:
117
117
  `)||e.startsWith(`---\r
118
118
  `)){let n=e.indexOf(`
119
119
  ---`,3);n!==-1&&(t=e.slice(n+4))}let n=[],r=new Map,i=createCodeFenceTracker();for(let e of t.split(`
120
- `)){if(i(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),i=getHeadingSlug(e,r);i&&n.push({level:t[1].length,text:e,slug:i})}}return n}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function createApiExtension(e){let{hocuspocus:t,sessionManager:n,contentDir:r,serverInstanceId:i,getFileIndex:a,getAliasMap:o,enableTestRoutes:s=!1,shadowRef:c,flushGitCommit:l,getCurrentBranch:u,getDiskAckSVs:d,contentRoot:f,backlinkIndex:p,signalChannel:m,agentFocusBroadcaster:h,agentPresenceBroadcaster:g,onAgentWrite:_,getSyncEngine:v,localOpCliArgs:y=[`open-knowledge`],projectDir:b,getPrincipal:x,installedAgentsProbe:S}=e,C=createConcurrencyGuard(),w=createInstalledAgentsProbe({probe:S??createOsProbe(process.platform)});function T(e){if(!isSafeDocName(e))return null;let t=resolve(r),n=resolve(t,`${e}${getDocExtension(e)}`);return!n.startsWith(`${t}/`)&&n!==t?null:n}function E(e){let t=T(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}let D={cluster:void 0,category:void 0,tags:void 0};function O(e){try{let n=t.documents.get(e);if(n){let e=n.getMap(`metadata`).get(`frontmatter`);if(typeof e==`string`&&e)return parseFrontmatterMetadata(e)}}catch{}try{let t=T(e);if(!t||!existsSync(t))return D;let{frontmatter:n}=stripFrontmatter(readFileSync(t,`utf-8`));return n?parseFrontmatterMetadata(n):D}catch{return D}}function k(e){if(p)try{if(p.getBacklinks(e).length>0)return;let t=performance.now(),n=findHubCandidates(e,a()),r=performance.now()-t;return r>5&&log$2.debug({docName:e,elapsedMs:r,candidateCount:n.length},`[orphan-hint] findHubCandidates slow`),n.length===0?void 0:[{type:`orphan`,parentCandidates:n,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${n.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function A(e){return o?.().get(e)??e}function j(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function M(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function N(e,n){let r=`onStoreDocument-${e}`;(t.debouncer.isDebounced(r)?t.debouncer.executeNow(r):Promise.resolve()).then(()=>l?.()).catch(e=>{log$2.warn({err:e},`[${n}] post-write flush failed`)})}function P(){let e=new Set;for(let[t,n]of a()){e.add(t);for(let t of n.aliases)e.add(t)}return e}function F(){let e=Promise.resolve();return async function(t){let n=e,r=()=>{};e=new Promise(e=>{r=e}),await n;try{return await t()}finally{r()}}}let I=F();function L(e){return e instanceof Error&&(e.message===`Managed rename requires backlink index support`||e.message.startsWith(`Cannot rename missing document:`)||e.message.startsWith(`symlink-escape:`))?e.message:`Failed to rename document`}async function R(e){let r=new Map;for(let n of e){let e=t.documents.get(n);e&&r.set(n,e.getText(`source`).toString())}for(let t of e)await n.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let n of e){let e=t.documents.get(n);deleteReconciledBase(n),e&&(t.closeConnections(n),await t.unloadDocument(e))}return r}function z(e,t){for(let{fromDocName:n,toDocName:i}of e){let e=safeContentPath(i,r),a=t.get(n);typeof a==`string`&&writeFileSync(e,a,`utf-8`);let o=typeof a==`string`?a:existsSync(e)?readFileSync(e,`utf-8`):null;typeof o==`string`&&registerWrite(e,contentHash(o))}}function B(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let i=safeContentPath(e,r);if(!existsSync(i))throw Error(`Cannot snapshot missing document: ${e}`);return{docName:e,content:readFileSync(i,`utf-8`)}})}function V(e){let n=t.documents.get(e);if(n)return n.getText(`source`).toString();let i=resolveContentEntryPath(r,`file`,e);return existsSync(i)?readFileSync(i,`utf-8`):null}function H(e,t){let n=resolveContentEntryPath(r,`file`,e);mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,t,`utf-8`),registerWrite(n,contentHash(t)),setReconciledBase(e,t);let i=a();i instanceof Map&&updateFileIndex({kind:`update`,path:n,docName:e,content:t},i)}function U(e,n,r){let i=t.documents.get(e);if(!i)throw Error(`Document is not loaded: ${e}`);let a={markdown:``,rewrites:0};return i.transact(()=>{let t=i.getXmlFragment(`default`),o=i.getText(`source`),s=o.toString();if(a=rewriteSupportedLinksForDocumentRename(s,e,n,r),a.rewrites===0)return;let{body:c}=stripFrontmatter(a.markdown),l=mdManager.parseWithFallback(c);updateYFragment(i,t,schema.nodeFromJSON(l),{mapping:new Map,isOMark:new Map}),applyFastDiff(o,s,a.markdown)},MANAGED_RENAME_ORIGIN),a}async function W(e,n){return I(async()=>{if(!p)throw Error(`Managed rename requires backlink index support`);let i=resolveContentEntryPath(r,`file`,e),o=resolveContentEntryPath(r,`file`,n),s=[{fromDocName:e,toDocName:n}],c=[...new Set(p.getBacklinks(e).map(e=>e.source))].sort((e,t)=>e.localeCompare(t)),l=new Map,u=[],d=[];for(let t of[e,...c]){if(l.has(t))continue;let n=V(t);typeof n==`string`?(l.set(t,n),t!==e&&u.push(t)):t!==e&&d.push(t)}if(typeof l.get(e)!=`string`)throw Error(`Cannot rename missing document: ${e}`);let f=createManagedRenameRecoveryJournal({sourceDocName:e,destinationDocName:n,snapshots:B([...l.keys()],l)}),h=[];return await withManagedRenameRecovery(r,f,async()=>{for(let e of d)p.deleteDocument(e);for(let r of u){let i=t.documents.get(r)?U(r,e,n):rewriteSupportedLinksForDocumentRename(l.get(r)??``,r,e,n);i.rewrites>0&&(H(r,i.markdown),h.push({docName:r,rewrites:i.rewrites})),p.updateDocumentFromMarkdown(r,i.markdown)}let r=rewriteSupportedLinksForDocumentRename((await R([e])).get(e)??l.get(e)??readFileSync(i,`utf-8`),e,e,n);await renameTrackedPathInGit(b,i,o)||(mkdirSync(dirname(o),{recursive:!0}),renameSync(i,o)),z(s,new Map([[e,r.markdown]])),setReconciledBase(n,r.markdown);let c=a();c instanceof Map&&updateFileIndex({kind:`rename`,oldPath:i,newPath:o,oldDocName:e,newDocName:n,content:r.markdown},c),p.renameDocument(e,n,r.markdown),r.rewrites>0&&h.push({docName:n,rewrites:r.rewrites})}),p.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${n}:`,t)}),m?.(`files`),m?.(`backlinks`),m?.(`graph`),h.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:s,rewrittenDocs:h}})}let G=128;function K(e){let t=typeof e.agentId==`string`?e.agentId:void 0;t!==void 0&&!AGENT_ID_RE.test(t)&&(t=void 0);let n=t?toBroadcasterKey(t):`claude-1`,r=typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,i=typeof e.clientName==`string`?e.clientName:void 0;i!==void 0&&(i=sanitizeGitIdentity(i));let a=typeof e.clientVersion==`string`?e.clientVersion:void 0;a!==void 0&&(a=sanitizeGitIdentity(a));let o=typeof e.label==`string`?e.label:void 0;o!==void 0&&(o=sanitizeGitIdentity(o));let s=typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):t??n;return{rawAgentId:t,agentId:n,agentName:r,colorSeed:s,clientName:i,clientVersion:a,label:o}}function q(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function J(e){return{principalId:x?.()?.id,agentType:q(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Y(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function X(e){return{value:e.value}}function Z(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}async function Q(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}let a=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!isSafeDocName(a)){json(t,400,{ok:!1,error:`Invalid docName`});return}let o=A(a);if(isSystemDoc(o)){json(t,400,{ok:!1,error:`'${o}' is a reserved document name`});return}let{agentId:s,agentName:c,colorSeed:l,clientName:u,clientVersion:d,label:f}=K(i),p=normalizeSummary(i.summary);if(p.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let m=await n.getSession(o,s,{displayName:c,colorSeed:l,clientName:u}),h=new Date().toISOString(),v=typeof i.content==`string`?i.content:`Hello from the agent! ${h}`,{response:y,stored:b}=Y(p);try{let e=iconFromClientName(u),t=AGENT_ICON_COLORS[e]??colorFromSeed(l??s);g?.setPresence(s,{displayName:c,icon:e,color:t,currentDoc:o,mode:`writing`,ts:Date.now()}),captureEffect(m.dc.document.getText(`source`),s,l,u),m.dc.document.transact(()=>{applyAgentMarkdownWrite(m.dc.document,`${v}\n`,`append`),m.dc.document.getMap(`agent-flash`).set(s,{agentId:s,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${v.slice(0,50)}`})},m.origin),recordContributor(o,s,c,l,void 0,J({clientName:u,clientVersion:d,label:f}),b),incrementAgentWriteCalls(),Z(p)}finally{g?.touchMode(s,`idle`)}N(o,`agent-write`),_?.(),json(t,200,{ok:!0,timestamp:h,...y?{summary:y}:{}})}catch(e){log$2.error({err:e},`[agent-write] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function ee(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{markdown:a,position:o}=i;if(!a||typeof a!=`string`){json(t,400,{ok:!1,error:`markdown field required`});return}let s=o===`prepend`?`prepend`:o===`replace`?`replace`:`append`,c=i.docName,l=typeof c==`string`&&c.length>0?c:`test-doc`;if(!isSafeDocName(l)){json(t,400,{ok:!1,error:`Invalid docName`});return}let u=A(l);if(isSystemDoc(u)){json(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}let{agentId:d,agentName:f,colorSeed:p,clientName:m,clientVersion:v,label:y}=K(i),b=normalizeSummary(i.summary);if(b.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let{response:x,stored:S}=Y(b),C=await n.getSession(u,d,{displayName:f,colorSeed:p,clientName:m}),w=new Date().toISOString();try{let e=iconFromClientName(m),t=AGENT_ICON_COLORS[e]??colorFromSeed(p??d);g?.setPresence(d,{displayName:f,icon:e,color:t,currentDoc:u,mode:`writing`,ts:Date.now()}),captureEffect(C.dc.document.getText(`source`),d,p,m),C.dc.document.transact(()=>{applyAgentMarkdownWrite(C.dc.document,a,s),C.dc.document.getMap(`agent-flash`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Added (${f}): ${a.trim().slice(0,50)}`})},C.origin),recordContributor(u,d,f,p,void 0,J({clientName:m,clientVersion:v,label:y}),S),incrementAgentWriteCalls(),Z(b)}finally{g?.touchMode(d,`idle`)}N(u,`agent-write-md`),h?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`write`,ts:Date.now()}),_?.();let T=k(u),E=j(u),D=M();D===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":q(m)}),json(t,200,{ok:!0,timestamp:w,subscriberCount:E,systemSubscriberCount:D,...T?{hints:T}:{},...x?{summary:x}:{}})}catch(e){log$2.error({err:e},`[agent-write-md] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function te(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(r)){json(n,400,{ok:!1,error:`Invalid docName`});return}let i=A(r);if(isSystemDoc(i)){json(n,400,{ok:!1,error:`'${i}' is a reserved document name`});return}let a=await t.openDirectConnection(i);try{let e=a.document;if(!e){json(n,500,{ok:!1,error:`Document not available`});return}json(n,200,{ok:!0,docName:i,content:e.getText(`source`).toString()})}finally{await a.disconnect()}}catch(e){console.error(`[document-read]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function ne(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`dir`);if(n)try{safeSubdir(r,n)}catch{json(t,400,{ok:!1,error:`Invalid directory parameter`});return}let i=a(),o=[];for(let[e,t]of i)if(!(n&&!e.startsWith(`${n}/`)&&e!==n)){o.push({docName:e,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(n&&!i.startsWith(`${n}/`)&&i!==n)continue;let a=relative(r,t.canonicalPath);o.push({docName:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}o.sort((e,t)=>e.docName.localeCompare(t.docName)),json(t,200,{ok:!0,documents:o})}catch(e){console.error(`[document-list]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function re(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}json(t,200,{ok:!0,docName:n,backlinks:p.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:E(e.source),snippet:e.snippet}))})}catch(e){console.error(`[backlinks]`,e),json(t,500,{ok:!1,error:`Failed to read backlinks`})}}async function ie(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){json(t,400,{ok:!1,error:`Missing docNames parameter`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(r[t]=p.getBacklinkCount(t))}json(t,200,{ok:!0,counts:r})}catch(e){console.error(`[backlink-counts]`,e),json(t,500,{ok:!1,error:`Failed to read backlink counts`})}}async function ae(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}json(t,200,{ok:!0,docName:n,forwardLinks:p.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:E(e.target),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})})}catch(e){console.error(`[forward-links]`,e),json(t,500,{ok:!1,error:`Failed to read forward links`})}}async function oe(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`docName`);if(r&&!isSafeDocName(r)){json(t,400,{ok:!1,error:`Invalid docName`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){json(t,400,{ok:!1,error:`docName is required when degrees is provided`});return}let a,o;if(i&&r){let e=Number.parseInt(i,10);if(!Number.isFinite(e)||e<0){json(t,400,{ok:!1,error:`degrees must be a non-negative integer`});return}({nodes:a,links:o}=p.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=p.getLinkGraph());json(t,200,{ok:!0,nodes:a.map(e=>{if(e.kind===`doc`){let t=O(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:E(e.docName),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:o})}catch(e){console.error(`[link-graph]`,e),json(t,500,{ok:!1,error:`Failed to read link graph`})}}async function se(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(n)){json(t,400,{ok:!1,error:`Invalid orphan mode. Allowed values: incoming, outgoing, both`});return}json(t,200,{ok:!0,orphans:p.getOrphans([...a().keys()],n).map(e=>({docName:e,title:E(e)}))})}catch(e){console.error(`[orphans]`,e),json(t,500,{ok:!1,error:`Failed to read orphan pages`})}}async function ce(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20;json(t,200,{ok:!0,hubs:p.getHubs(i).map(e=>({docName:e.docName,title:E(e.docName),count:e.count}))})}catch(e){console.error(`[hubs]`,e),json(t,500,{ok:!1,error:`Failed to read hub pages`})}}async function le(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(n.some(e=>e.length===0||!isSafeDocName(e))){json(t,400,{ok:!1,error:`Invalid sourceDocName`});return}let r=n.length?[...new Set(n.map(e=>A(e)))]:void 0;json(t,200,{ok:!0,deadLinks:p.getDeadLinks(P(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:E(e.source),snippet:e.snippet}))}))})}catch(e){console.error(`[dead-links]`,e),json(t,500,{ok:!1,error:`Failed to read dead links`})}}async function ue(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{find:a,replace:o,docName:s,offset:c}=i;if(typeof a!=`string`||a.length===0){json(t,400,{ok:!1,error:`find field required`});return}if(typeof o!=`string`){json(t,400,{ok:!1,error:`replace field required`});return}let l=Object.hasOwn(i,`offset`),u;if(l){if(typeof c!=`number`||!Number.isInteger(c)||c<0){json(t,400,{ok:!1,error:`offset must be a non-negative integer`});return}u=c}let d=typeof s==`string`&&s.length>0?s:`test-doc`;if(!isSafeDocName(d)){json(t,400,{ok:!1,error:`Invalid docName`});return}let f=A(d);if(isSystemDoc(f)){json(t,400,{ok:!1,error:`'${f}' is a reserved document name`});return}let{agentId:p,agentName:m,colorSeed:v,clientName:y,clientVersion:b,label:x}=K(i),S=normalizeSummary(i.summary);if(S.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let C=await n.getSession(f,p,{displayName:m,colorSeed:v,clientName:y}),w=new Date().toISOString(),T=!1,E=!1;try{let e=iconFromClientName(y),t=AGENT_ICON_COLORS[e]??colorFromSeed(v??p);if(g?.setPresence(p,{displayName:m,icon:e,color:t,currentDoc:f,mode:`writing`,ts:Date.now()}),captureEffect(C.dc.document.getText(`source`),p,v,y),C.dc.document.transact(()=>{let e=C.dc.document.getXmlFragment(`default`),t=C.dc.document.getMap(`metadata`),n=t.get(`frontmatter`)??``,r=prependFrontmatter(n,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(e,schema).toJSON())),i=u==null?r.indexOf(a):r.slice(u,u+a.length)===a?u:-1;if(i===-1){u==null?T=!0:E=!0;return}let{frontmatter:s,body:c}=stripFrontmatter(r.slice(0,i)+o+r.slice(i+a.length));s!==n&&t.set(`frontmatter`,s),applyAgentMarkdownWrite(C.dc.document,c,`replace`),C.dc.document.getMap(`agent-flash`).set(p,{agentId:p,timestamp:Date.now(),type:`insert`,description:`Patched (${m}): ${a.slice(0,50)}`})},C.origin),!T&&!E){let{stored:e}=Y(S);recordContributor(f,p,m,v,void 0,J({clientName:y,clientVersion:b,label:x}),e),incrementAgentWriteCalls(),Z(S)}}finally{g?.touchMode(p,`idle`)}if(E){json(t,409,{ok:!1,error:`Target text no longer matches at the requested offset`});return}if(T){json(t,404,{ok:!1,error:`Text not found in document`});return}N(f,`agent-patch`),h?.setFocus(p,{agentName:m,currentDoc:f,writeKind:`edit`,ts:Date.now()}),_?.();let D=j(f),O=M();O===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":q(y)});let{response:k}=Y(S);json(t,200,{ok:!0,timestamp:w,subscriberCount:D,systemSubscriberCount:O,...k?{summary:k}:{}})}catch(e){log$2.error({err:e},`[agent-patch] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function de(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=K(i),d=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!isSafeDocName(d)){json(t,400,{ok:!1,error:`Invalid docName`});return}let f=A(d);if(isSystemDoc(f)){json(t,400,{ok:!1,error:`'${f}' is a reserved document name`});return}let p=typeof i.connectionId==`string`?i.connectionId:void 0;if(!p){json(t,400,{ok:!1,error:`connectionId required`});return}let m=i.scope,_=m===`session`||m===`file`?`session`:`last`;if(!n.hasSession(f,p)){json(t,404,{ok:!1,error:`No active session for this connectionId and docName`});return}let v=await n.getSession(f,p),y=!1;try{let e=iconFromClientName(c),t=AGENT_ICON_COLORS[e]??colorFromSeed(s??a);g?.setPresence(a,{displayName:o,icon:e,color:t,currentDoc:f,mode:`writing`,ts:Date.now()}),y=applyAgentUndo(v,_),y&&recordContributor(f,p,o,s,void 0,J({clientName:c,clientVersion:l,label:u}))}finally{g?.touchMode(a,`idle`)}y&&N(f,`agent-undo`),h?.setFocus(p,{agentName:p,currentDoc:f,writeKind:`undo`,ts:Date.now()}),json(t,200,{ok:!0,docName:f,scope:_,undone:y})}catch(e){log$2.error({err:e},`[agent-undo] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function fe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(r===null){json(t,400,{ok:!1,error:`agentId required (alphanumeric/_/- only)`});return}json(t,200,{ok:!0,...listAgentActivity(n,r)})}catch(e){log$2.error({err:e},`[agent-activity] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function pe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=validateAgentId(r.searchParams.get(`agentId`)),a=r.searchParams.get(`docName`),o=r.searchParams.get(`stackIndex`);if(i===null){json(t,400,{ok:!1,error:`agentId required (alphanumeric/_/- only)`});return}if(!a||a.trim()===``){json(t,400,{ok:!1,error:`docName required`});return}if(!isSafeDocName(a)){json(t,400,{ok:!1,error:`Invalid docName`});return}let s=A(a);if(isSystemDoc(s)){json(t,400,{ok:!1,error:`'${s}' is a reserved document name`});return}if(!o||Number.isNaN(Number(o))){json(t,400,{ok:!1,error:`stackIndex must be a number`});return}let c=Number(o);if(!Number.isInteger(c)||c<0){json(t,400,{ok:!1,error:`stackIndex must be a non-negative integer`});return}let l=n.getLiveSession(s,i);if(!l){json(t,404,{ok:!1,error:`No active session for this agentId and docName`});return}let u=l.um;if(c>=u.undoStack.length){json(t,404,{ok:!1,error:`stackIndex ${c} out of range (stack has ${u.undoStack.length} items)`});return}let d=u.undoStack[c];json(t,200,{ok:!0,diff:synthesizeStackItemDiffText(d,l.dc.document.getText(`source`),s),generatedAt:Date.now()})}catch(e){log$2.error({err:e},`[agent-burst-diff] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function me(e,i){if(e.method!==`POST`){i.writeHead(405),i.end(`Method not allowed`);return}try{let a=A(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??`test-doc`),o;try{o=safeContentPath(a,r)}catch(e){console.error(`[test-reset] safeContentPath rejected docName:`,a,e),json(i,400,{ok:!1,error:`Invalid docName`});return}await n.closeAll(a),t.closeConnections(a);let s=`onStoreDocument-${a}`;t.debouncer.isDebounced(s)&&await t.debouncer.executeNow(s);let c=t.documents.get(a);c&&await t.unloadDocument(c),writeFileSync(o,``,`utf-8`),p&&(p.deleteDocument(a),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${a}:`,e)}),m?.(`backlinks`),m?.(`graph`)),m?.(`files`),json(i,200,{ok:!0})}catch(e){console.error(`[test-reset]`,e),json(i,500,{ok:!1,error:`Internal server error`})}}async function he(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}p.rebuildFromDisk(),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),m?.(`backlinks`),m?.(`graph`),json(t,200,{ok:!0})}catch(e){console.error(`[test-rescan-backlinks]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function ge(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n=c?.current;if(!n){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i=/^[a-zA-Z0-9_-]+$/,a=[],o,s={},c,l;if(r.length>0){let e;try{e=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}s=e,typeof e.message==`string`&&e.message.trim()&&(o=e.message.replace(/[\r\n]/g,` `).slice(0,256)),Array.isArray(e.writers)&&(a=e.writers.map(e=>{let t=e.id??`unknown`;if(!i.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}}));let n=e.principal;if(n&&typeof n==`object`&&!Array.isArray(n)){let e=n;typeof e.name==`string`&&e.name.trim()&&(c=sanitizeGitIdentity(e.name.trim())),typeof e.email==`string`&&e.email.trim()&&(l=sanitizeGitIdentity(e.email.trim()))}}let{rawAgentId:u,agentId:d,agentName:p,clientName:m}=K(s);a.length===0&&(a=u===void 0?[SERVICE_WRITER]:[{id:d,name:m?`${p} (${m})`:p,email:`${d}@openknowledge.local`}]);let h=f??`.`,g=await saveVersion(n,h,a);console.log(`[history] checkpoint ${g.checkpointRef}`);let _=swapContributors(),v;if(b){let e=!1;try{await esm_default({baseDir:b,timeout:{block:5e3}}).revparse([`--git-dir`]),e=!0}catch(e){console.warn(`[save-version] parent-git unavailable: ${e instanceof Error?e.message:String(e)}`)}if(e)try{v=await withParentLock(async()=>{let e=esm_default({baseDir:b,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,n=`ok/v${t}`,r=`openknowledge`,i=`noreply@openknowledge.local`;if(c&&l)r=c,i=l;else try{let e=await resolveGitIdentity(b);e&&(r=e.name,i=e.email)}catch{}let a=[];for(let e of _.values())if(e.writerId.startsWith(`agent-`)||e.writerId.startsWith(`principal-`)){let t=`${e.writerId}@openknowledge.local`;a.push(`Co-Authored-By: ${e.displayName} <${t}>`)}let s=formatCheckpointSubject(o??`Checkpoint v${t}`),u=a.length>0?`${s}\n\n${a.join(`
121
- `)}`:s,d=h||`.`;return await e.add(d),await e.env({GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i}).commit(u,[`--allow-empty`]),await e.addTag(n),console.log(`[checkpoint] parent-git commit + tag ${n}`),n})}catch(e){console.warn(`[checkpoint] parent-git commit failed (non-fatal):`,e)}}json(t,200,{ok:!0,checkpointRef:g.checkpointRef,...v?{versionTag:v}:{}})}catch(e){console.error(`[save-version]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function _e(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=c?.current;if(!n){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`branch`)??u?.()??`main`;if(!i){json(t,400,{ok:!1,error:`docName query parameter is required`});return}if(a.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(a)){json(t,400,{ok:!1,error:`Invalid branch name`});return}let o=Number(r.searchParams.get(`limit`)??`50`),s=Number(r.searchParams.get(`offset`)??`0`),l=Math.min(200,Number.isFinite(o)?o:50),d=Number.isFinite(s)?s:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=Date.now();try{let e=await getDocumentHistory(n,{docName:i,branch:a,limit:l,offset:d,type:p,author:m,excludeAuthor:h},f??`.`),r=Date.now()-g;console.log(`[timeline] query docName=${i} entries=${e.entries.length} duration=${r}ms`),json(t,200,{ok:!0,...e})}catch(e){console.error(`[shadow]`,e),json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function ve(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let r=c?.current;if(!r){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}let i=safeDocPath(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,f??`.`);if(`error`in i){json(t,400,{ok:!1,error:i.error});return}let a=i.path,o=shadowGit(r);if(!/^[0-9a-f]{40}$/i.test(n)){json(t,400,{ok:!1,error:`Invalid commit SHA`});return}try{try{await o.raw(`cat-file`,`-e`,`${n}:${a}`)}catch{json(t,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await o.raw(`show`,`${n}:${a}`),[r=``,i=``]=(await o.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);json(t,200,{ok:!0,sha:n,content:e,timestamp:r,author:i})}catch(e){console.error(`[shadow-version]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function ye(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}let r=c?.current;if(!r){json(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`docName`)??``,o=i.searchParams.get(`from`)??``,s=i.searchParams.get(`to`)??``;if(!s||!/^[0-9a-f]{40}$/i.test(s)){json(n,400,{ok:!1,error:`'to' must be a valid 40-char commit SHA`});return}let l=safeDocPath(a,f??`.`);if(`error`in l){json(n,400,{ok:!1,error:l.error});return}let u=l.path,d=shadowGit(r);try{let e;try{e=await d.raw(`show`,`${s}:${u}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at the target version`});return}let r;if(o&&/^[0-9a-f]{40}$/i.test(o))try{r=await d.raw(`show`,`${o}:${u}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at the source version`});return}else{let e=t.documents.get(a);if(!e){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}r=e.getText(`source`).toString()}let i=stripFrontmatter(r).body,c=stripFrontmatter(e).body,l=diffLines(i,c),f=[],p=0,m=0;for(let e of l){let t=e.value.replace(/\n$/,``).split(`
122
- `),n=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)f.push({type:n,text:e});e.added&&(p+=t.length),e.removed&&(m+=t.length)}json(n,200,{ok:!0,lines:f,additions:p,deletions:m})}catch(e){console.error(`[diff]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function be(e,n){if(e.method!==`POST`){n.writeHead(405),n.end(`Method not allowed`);return}let r=c?.current;if(!r){json(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i;try{i=await readBody(e)}catch{json(n,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{json(n,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(n,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:l,clientName:u,clientVersion:d,label:p}=K(a),{docName:m,commitSha:g,versionTag:_}=a,v=typeof m==`string`?m:``,y=typeof g==`string`?g:``,x=typeof _==`string`?_:void 0;if(!v){json(n,400,{ok:!1,error:`docName required`});return}if(!y||!/^[0-9a-f]{40}$/i.test(y)){json(n,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let S=a,C=typeof S.agentId==`string`&&S.agentId.length>0,w=normalizeSummary(S.summary);if(w.kind===`invalid`){json(n,400,{ok:!1,error:`summary must be a string`});return}let T=f??`.`,E=safeDocPath(v,T);if(`error`in E){json(n,400,{ok:!1,error:E.error});return}let D=E.path,O=shadowGit(r),k=Date.now();try{try{await O.raw(`cat-file`,`-e`,`${y}:${D}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await O.raw(`show`,`${y}:${D}`),i=new Date().toISOString();await safetyCheckpoint(r,T,{action:`rollback`,context:{docName:v,targetSha:y}});let a=t.documents.get(v);if(!a){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{frontmatter:c,body:m}=stripFrontmatter(e),g=mdManager.parseWithFallback(m),_=schema.nodeFromJSON(g),S=a.getXmlFragment(`default`);a.transact(()=>{updateYFragment(a,S,_,{mapping:new Map,isOMark:new Map});let t=a.getText(`source`),n=t.toString();n!==e&&(t.delete(0,n.length),t.insert(0,e)),a.getMap(`metadata`).set(`frontmatter`,c)},ROLLBACK_ORIGIN);let E;if(C){let e=y.slice(0,8),t=w.kind===`value`,n=t?w:normalizeSummary(`Restored to ${e}`),r=Y(n);E=t||!r.response?r.response:X(r.response),recordContributor(v,o,s,l,formatRollbackSubject(v,y),J({clientName:u,clientVersion:d,label:p}),r.stored),incrementAgentWriteCalls(),Z(n,!t)}N(v,`rollback`);let A=Date.now()-k;if(console.log(`[rollback] docName=${v} from=${y.slice(0,8)} duration=${A}ms`),b){let e=`Restored to ${x??y.slice(0,8)}: ${v}`,t=f??`.`;withParentLock(async()=>{let n=esm_default({baseDir:b,timeout:{block:15e3}}),r=t||`.`;await n.add(r),await n.commit(e,{"--allow-empty":null}),console.log(`[rollback] parent-git commit: ${e}`)}).catch(e=>{console.warn(`[rollback] parent-git commit failed (non-fatal):`,e)})}C&&h?.setFocus(o,{agentName:s,currentDoc:v,writeKind:`rollback-apply`,ts:Date.now()}),json(n,200,{ok:!0,restoredFrom:y,timestamp:i,...E?{summary:E}:{}})}catch(e){console.error(`[rollback]`,e),json(n,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function xe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getMetrics())}async function Se(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getParseHealth())}async function Ce(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=getActiveBranch(),r=d?.();json(t,200,{ok:!0,serverInstanceId:i,currentBranch:n,...r===void 0?{}:{currentDiskAckSVs:r}},{"Cache-Control":`no-store`})}async function we(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=x?.()??null;if(!n){json(t,404,{error:`Principal not available`});return}json(t,200,n)}async function Te(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=g?.getPresenceMap()??{},r=Date.now(),i={};for(let[e,t]of Object.entries(n))r-t.ts<2e4&&(i[e]=t);json(t,200,{presence:i})}async function Ee(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=resolve(r),i=n,a=!0;try{i=realpathSync(n)}catch(e){let r=e?.code;if(r===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:n}),a=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:n,err:e}),json(t,500,{ok:!1,error:`workspace-realpath-failed`,code:r??null});return}}json(t,200,{ok:!0,contentDir:i,pathSeparator:sep,symlinkResolved:a})}let De=1440*60*1e3;async function Oe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!c?.current){json(t,200,[]);return}let n=Date.now(),r=[],i=resolve(c.current.gitDir,`rescue`);if(existsSync(i))try{let e=readdirSync(i).filter(e=>isSupportedDocFile(e));for(let t of e){let e=resolve(i,t),a=statSync(e);if(n-a.mtimeMs>De){try{unlinkSync(e)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}r.push({docName:stripDocExtension(t),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){console.error(`[rescue] Failed to list flat-file rescue buffers:`,e)}try{let e=u?.()??`main`,t=await listRescueCheckpoints(c.current,e);for(let e of t)r.push({...e,source:`timeline`})}catch(e){console.error(`[rescue] Failed to list timeline-ref rescue checkpoints:`,e)}json(t,200,r)}async function ke(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!c?.current){t.writeHead(404),t.end(`Not found`);return}let r=resolve(c.current.gitDir,`rescue`),i=resolve(r,`${n}${getDocExtension(n)}`);if(!i.startsWith(`${r}/`)){t.writeHead(400),t.end(`Invalid document name`);return}if(existsSync(i)){let e=statSync(i);if(Date.now()-e.mtimeMs>De)try{unlinkSync(i)}catch{}else{let e=readFileSync(i,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=u?.()??`main`,r=(await listRescueCheckpoints(c.current,e)).filter(e=>e.docName===n).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(r){let e=shadowGit(c.current),n=((await e.raw(`ls-tree`,`-r`,r.sha)).trim().split(`
123
- `)[0]??``).split(/\s+/)[2];if(n){let r=await e.raw(`cat-file`,`-p`,n);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(r);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}t.writeHead(404),t.end(`Not found`)}async function Ae(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:d}=K(i),{path:f}=i;if(!f||typeof f!=`string`||f.length===0){json(t,400,{ok:!1,error:`path is required`});return}if(!isSupportedDocFile(f)){json(t,400,{ok:!1,error:`path must end with .md or .mdx`});return}if(f.includes(`..`)||f.startsWith(`/`)||f.includes(`\0`)||f.includes(`\\`)){json(t,400,{ok:!1,error:`path must not contain .. or start with /`});return}let h=resolve(r),g=resolve(h,f);if(!g.startsWith(`${h}/`)&&g!==h){json(t,400,{ok:!1,error:`path must not escape content directory`});return}let _=stripDocExtension(f);if(isSystemDoc(_)){json(t,400,{ok:!1,error:`'${_}' is a reserved document name`});return}mkdirSync(dirname(g),{recursive:!0});let v=``;try{writeFileSync(g,``,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){json(t,409,{ok:!1,error:`File already exists`});return}throw e}let y=stripDocExtension(f);recordContributor(y,o,s,c,void 0,J({clientName:l,clientVersion:u,label:d}));let b=typeof a==`function`?a():null;b instanceof Map&&updateFileIndex({kind:`create`,path:g,docName:y,content:``},b),p&&(p.updateDocumentFromMarkdown(y,``),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${y}:`,e)}),m?.(`backlinks`),m?.(`graph`)),m?.(`files`),json(t,200,{ok:!0,docName:y})}catch(e){console.error(`[create-page]`,e),json(t,500,{ok:!1,error:`Failed to create page`})}}async function je(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||typeof n!=`string`||n.length===0){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}let r=T(n);if(!r){json(t,400,{ok:!1,error:`Invalid docName`});return}if(!existsSync(r)){json(t,404,{ok:!1,error:`Page not found`});return}json(t,200,{ok:!0,docName:n,headings:extractHeadings(readFileSync(r,`utf-8`))})}catch(e){console.error(`[page-headings]`,e),json(t,500,{ok:!1,error:`Failed to read headings`})}}async function Me(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=K(i),{docName:d,newDocName:f}=i;if(typeof d!=`string`||typeof f!=`string`){json(t,400,{ok:!1,error:`docName and newDocName are required`});return}if(!isValidRelativeContentPath(d)||!isValidRelativeContentPath(f)){json(t,400,{ok:!1,error:`Document names must be relative content paths`});return}if(isSystemDoc(d)||isSystemDoc(f)){json(t,400,{ok:!1,error:`Reserved document names cannot be renamed`});return}if(d===f){json(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}if(!p){json(t,503,{ok:!1,error:`Backlink index unavailable`});return}let m=i,h=typeof m.agentId==`string`&&m.agentId.length>0,g=normalizeSummary(m.summary);if(g.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let _=resolveContentEntryPath(r,`file`,d),v=resolveContentEntryPath(r,`file`,f);if(!existsSync(_)){json(t,404,{ok:!1,error:`Document does not exist`});return}if(existsSync(v)){json(t,409,{ok:!1,error:`Destination already exists`});return}let y=await W(d,f),b;if(h){let e=g.kind===`value`,t=e?g:normalizeSummary(`Renamed ${d} → ${f}`),n=Y(t);b=e||!n.response?n.response:X(n.response),recordContributor(f,a,o,s,formatRenameSubject(d,f),J({clientName:c,clientVersion:l,label:u}),n.stored),incrementAgentWriteCalls(),Z(t,!e),N(f,`rename`)}json(t,200,{ok:!0,renamed:y.renamed,rewrittenDocs:y.rewrittenDocs,...b?{summary:b}:{}})}catch(e){console.error(`[rename]`,e),json(t,500,{ok:!1,error:L(e)})}}async function Ne(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}K(i);let{kind:o,fromPath:s,toPath:c}=i;if(o!==`file`&&o!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||typeof c!=`string`){json(t,400,{ok:!1,error:`fromPath and toPath are required`});return}if(!isValidRelativeContentPath(s)||!isValidRelativeContentPath(c)){json(t,400,{ok:!1,error:`Paths must be relative content paths`});return}if(s===c){json(t,200,{ok:!0,renamed:[]});return}let l=resolveContentEntryPath(r,o,s),u=resolveContentEntryPath(r,o,c);if(!existsSync(l)){json(t,404,{ok:!1,error:`${o} does not exist`});return}if(existsSync(u)){json(t,409,{ok:!1,error:`Destination already exists`});return}let d=statSync(l);if(o===`file`&&!d.isFile()||o===`folder`&&!d.isDirectory()){json(t,400,{ok:!1,error:`Source path is not a ${o}`});return}let f=listAffectedDocNames(a(),o,s),h=o===`file`?[{fromDocName:s,toDocName:c}]:f.map(e=>({fromDocName:e,toDocName:remapDocNameForRename(e,o,s,c)})),g=await R(h.map(({fromDocName:e})=>e)),_=async()=>{await renameTrackedPathInGit(b,l,u)||(mkdirSync(dirname(u),{recursive:!0}),renameSync(l,u)),z(h,g)};if(o===`file`)await withManagedRenameRecovery(r,createManagedRenameRecoveryJournal({sourceDocName:s,destinationDocName:c,snapshots:B(h.map(({fromDocName:e})=>e),g)}),_);else{await _();let e=a();for(let{fromDocName:t,toDocName:n}of h)updateFileIndex({kind:`rename`,oldPath:resolveContentEntryPath(r,`file`,t),newPath:resolveContentEntryPath(r,`file`,n),oldDocName:t,newDocName:n,content:g.get(t)??readFileSync(resolveContentEntryPath(r,`file`,n),`utf-8`)},e);if(p){for(let{fromDocName:e,toDocName:t}of h)p.renameDocument(e,t,g.get(e)??readFileSync(resolveContentEntryPath(r,`file`,t),`utf-8`));p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist folder rename cache for ${s} -> ${c}:`,e)}),m?.(`backlinks`),m?.(`graph`)}m?.(`files`)}json(t,200,{ok:!0,renamed:h})}catch(e){console.error(`[rename-path]`,e),json(t,500,{ok:!1,error:`Failed to rename path`})}}async function Pe(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}K(i);let{kind:o,path:s}=i;if(o!==`file`&&o!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||!isValidRelativeContentPath(s)){json(t,400,{ok:!1,error:`path must be a relative content path`});return}let c=resolveContentEntryPath(r,o,s);if(!existsSync(c)){json(t,404,{ok:!1,error:`${o} does not exist`});return}let l=statSync(c);if(o===`file`&&!l.isFile()||o===`folder`&&!l.isDirectory()){json(t,400,{ok:!1,error:`Target path is not a ${o}`});return}let u=o===`file`?[s]:listAffectedDocNames(a(),o,s);await R(u),o===`file`?unlinkSync(c):rmSync(c,{recursive:!0,force:!1}),json(t,200,{ok:!0,deletedDocNames:u})}catch(e){console.error(`[delete-path]`,e),json(t,500,{ok:!1,error:`Failed to delete path`})}}async function Fe(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let e=a(),n=[];for(let[t,i]of e){let e=t;try{e=extractPageTitle(readFileSync(resolve(r,`${t}${getDocExtension(t)}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,size:i.size,modified:i.modified})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),json(t,200,{ok:!0,pages:n})}catch(e){console.error(`[pages]`,e),json(t,500,{ok:!1,error:`Failed to list pages`})}}async function Ie(e,n){if(e.method!==`GET`){json(n,405,{ok:!1,error:`Method not allowed`});return}try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){json(n,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(r)){json(n,400,{ok:!1,error:`Invalid docName`});return}if(isSystemDoc(r)){json(n,400,{ok:!1,error:`'${r}' is a reserved document name`});return}json(n,200,{ok:!0,...await suggestLinks({hocuspocus:t,fileIndex:a(),docName:r})})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){json(n,404,{ok:!1,error:`Page not found`});return}console.error(`[suggest-links]`,e),json(n,500,{ok:!1,error:`Failed to suggest links`})}}async function Le(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n;try{n=await readUploadBody(e,MAX_UPLOAD_BYTES)}catch(e){let n=e instanceof Error?e.message:String(e);n===`Payload too large`?json(t,413,{ok:!1,error:`Payload too large`}):n===`No file received`?json(t,400,{ok:!1,error:`No file received`}):json(t,400,{ok:!1,error:`Failed to parse upload: ${n}`});return}let{filename:i,buffer:a,parentDocName:o}=n;if(K(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries())),!o){json(t,400,{ok:!1,error:`parentDocName is required`});return}if(o.includes(`\0`)||o.includes(`..`)||o.startsWith(`/`)){json(t,400,{ok:!1,error:`path-escape`});return}let s=resolve(r),c=resolve(s,dirname(o));if(!isWithinContentDir(c,s)){json(t,400,{ok:!1,error:`path-escape`});return}try{let e=realpathSync(c),n;try{n=realpathSync(s)}catch{n=s}if(!isWithinContentDir(e,n)){json(t,400,{ok:!1,error:`path-escape`});return}}catch(e){if(e.code!==`ENOENT`){json(t,400,{ok:!1,error:`path-escape`});return}}let l=await fileTypeFromBuffer(a),u=l?.mime,d=l?.ext;if(!u){let e=a.subarray(0,256).toString(`utf-8`).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(u=`image/svg+xml`,d=`svg`)}if(!u||!d||!ALLOWED_MIME_TYPES.has(u)){json(t,400,{ok:!1,error:`Unsupported file type${u?`: ${u}`:``}`});return}let f;f=!i||i===`upload`||GENERIC_PASTE_NAMES.test(i)?`pasted-${new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`)}.${d}`:sanitizeFilename(i),mkdirSync(c,{recursive:!0});try{let e=writeUploadAtomic(c,f,a),n=relative(r,resolve(c,e));console.log(`[upload] ok ${n} ${a.length}`),json(t,200,{ok:!0,src:e})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`[upload] error ${f} ${a.length} ${n}`),json(t,500,{ok:!1,error:`Failed to save file`})}}let Re=`/api/local-op/clone`,ze=`/api/local-op/open`,Be=600*1e3,Ve=45e3;async function He(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.url!=`string`||!a.url){json(t,400,{ok:!1,error:`Missing or invalid url`});return}if(typeof a.dir!=`string`||!a.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=a.url,r=a.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isAllowedGitUrl(n)){json(t,400,{ok:!1,error:`URL protocol not allowed`});return}if(!isSafeLocalPath(r)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!C.tryAcquire(Re)){json(t,429,{ok:!1,error:`A clone operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=expandTilde(r),[a,...o]=y,s=[...o,`clone`,`--json`,n,i],c=!1,l=!1,u=null,d=``,f=spawn(a,s,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),p=setTimeout(()=>{c=!0,f.kill(`SIGTERM`)},Be);f.stdout.on(`data`,e=>{d+=e.toString(`utf-8`);let n=d.split(`
124
- `);d=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`complete`&&typeof n.dir==`string`){u=n.dir;continue}t.writableEnded||t.write(`${e}\n`)}});let m=[];f.stderr.on(`data`,e=>{m.push(e),log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/clone] stderr`)}),f.on(`close`,e=>{clearTimeout(p);let i=Buffer.concat(m).toString(`utf-8`).trim();if(l){C.release(Re);return}l=!0,(async()=>{try{if(c&&!t.writableEnded)t.write(`${JSON.stringify({type:`error`,message:`Clone timed out after 10 minutes`})}\n`);else if(e!==0&&!t.writableEnded){i&&log$2.warn({code:e,stderr:i,url:n,dir:r},`[local-op/clone] clone failed`);let a=i?` — ${i}`:``;t.write(`${JSON.stringify({type:`error`,message:`Clone process exited with code ${e}${a}`})}\n`)}else if(e===0&&u&&!t.writableEnded){let e=await Ue(u);t.writableEnded||(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port})}\n`):t.write(`${JSON.stringify({type:`error`,message:e.error})}\n`))}}finally{t.writableEnded||t.end(),C.release(Re)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),C.release(Re)})}async function Ue(e){let t=resolve(expandTilde(e)),n=resolve(t,`.open-knowledge`),r=readUiLock(n);if(r&&r.port>0)return{port:r.port};let i=readServerLock(n),[a,...o]=y,s=i&&i.port>0?`ui`:`start`,c=spawn(a,[...o,s],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`,OK_PARENT_PID:String(process.pid)}}),l=[];c.stderr?.on(`data`,e=>{l.push(e),log$2.warn({cwd:t,cliCmd:s,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let u=null;c.on(`exit`,e=>{u=e??-1}),c.unref();let d=Date.now()+45e3;for(;Date.now()<d;){await setTimeout$1(500);let e=readUiLock(n);if(e&&e.port>0)return{port:e.port};if(u!==null){let e=Buffer.concat(l).toString(`utf-8`).trim();return{error:`\`ok ${s}\` exited (code ${u})${e?` — ${e}`:``}`}}}let f=Buffer.concat(l).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${f?` — ${f}`:``}`}}async function We(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await readBody(e),i=JSON.parse(r.toString());if(typeof i.dir!=`string`||!i.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=i.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isSafeLocalPath(n)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!C.tryAcquire(ze)){json(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await Ue(n);`port`in e?json(t,200,{port:e.port}):json(t,504,{ok:!1,error:e.error})}finally{C.release(ze)}}let Ge=`/api/local-op/auth/login`,Ke=`/api/local-op/auth/status`,qe=`/api/local-op/auth/repos`,Je=`/api/local-op/auth/signout`,Ye=`/api/local-op/auth/pat`;async function Xe(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await readBody(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!C.tryAcquire(Ge)){json(t,429,{ok:!1,error:`An auth login operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=y,a=[...i,`auth`,`login`,`--json`,`--host`,n],o=!1,s=!1,c=``,l=spawn(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),u=setTimeout(()=>{l.kill(`SIGTERM`)},Be),d=()=>{l.killed||l.kill(`SIGTERM`)};t.on(`close`,d),l.stdout.on(`data`,e=>{t.writableEnded||t.write(e),c+=e.toString(`utf-8`);let n=c.split(`
125
- `);c=n.pop()??``;for(let e of n)if(e.trim())try{let t=JSON.parse(e);(t.type===`complete`||t.type===`error`)&&(s=!0)}catch{}}),l.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/login] stderr`)}),l.on(`close`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(e===0&&!s?t.write(`${JSON.stringify({type:`complete`,host:n,login:``})}\n`):e!==0&&t.write(`${JSON.stringify({type:`error`,message:`auth login exited with code ${e}`})}\n`)),t.end()),C.release(Ge)}),l.on(`error`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),C.release(Ge)})}async function Ze(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await readBody(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!C.tryAcquire(Ke)){json(t,429,{ok:!1,error:`An auth status operation is already in progress`});return}try{let[e,...r]=y,i=[...r,`auth`,`status`,`--json`,`--host`,n],a=(await new Promise((t,n)=>{let r=spawn(e,i,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4),o=[];r.stdout.on(`data`,e=>o.push(e)),r.on(`close`,()=>{clearTimeout(a),t(Buffer.concat(o).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(a),n(e)})})).split(`
126
- `).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}o===null?json(t,200,{authenticated:!1}):json(t,200,o)}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth status failed`})}finally{C.release(Ke)}}async function Qe(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await readBody(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!C.tryAcquire(qe)){json(t,429,{ok:!1,error:`An auth repos operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=y,a=[...i,`auth`,`repos`,`--json`,`--host`,n],o=!1,s=spawn(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),c=setTimeout(()=>{s.kill(`SIGTERM`)},Be);s.stdout.on(`data`,e=>{t.writableEnded||t.write(e)}),s.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),s.on(`close`,e=>{clearTimeout(c),o||(o=!0,e!==0&&!t.writableEnded&&t.write(`${JSON.stringify({type:`error`,message:`auth repos exited with code ${e}`})}\n`),t.end()),C.release(qe)}),s.on(`error`,e=>{clearTimeout(c),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),C.release(qe)})}async function $e(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await readBody(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!C.tryAcquire(Je)){json(t,429,{ok:!1,error:`An auth signout operation is already in progress`});return}try{let[e,...r]=y,i=[...r,`auth`,`signout`,`--host`,n];await new Promise((t,n)=>{let r=spawn(e,i,{stdio:`ignore`,env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth signout failed`})}finally{C.release(Je)}}async function et(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.pat!=`string`||!a.pat){json(t,400,{ok:!1,error:`Missing or invalid pat`});return}r=a.pat,typeof a.host==`string`&&a.host&&(n=a.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!C.tryAcquire(Ye)){json(t,429,{ok:!1,error:`An auth pat operation is already in progress`});return}try{let[e,...i]=y,a=[...i,`auth`,`pat`,`--json`,`--host`,n],o=(await new Promise((t,n)=>{let i=spawn(e,a,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),o=setTimeout(()=>{i.kill(`SIGTERM`)},3e4);i.stdin.write(`${r}\n`),i.stdin.end();let s=[];i.stdout.on(`data`,e=>s.push(e)),i.on(`close`,e=>{clearTimeout(o),e===0?t(Buffer.concat(s).toString(`utf-8`)):n(Error(`auth pat exited with code ${e}`))}),i.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
127
- `).map(e=>e.trim()).filter(Boolean),s=null;for(let e=o.length-1;e>=0;e--)try{s=JSON.parse(o[e]);break}catch{}s===null?json(t,200,{ok:!0}):json(t,200,s)}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth pat failed`})}finally{C.release(Ye)}}async function tt(e,t){if(checkLocalOpSecurity(e,t,json)){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!b){json(t,400,{ok:!1,error:`No project directory configured`});return}try{json(t,200,{ok:!0,identity:await resolveGitIdentity(b)})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`identity resolution failed`})}}}let nt=`/api/local-op/auth/set-identity`;async function rt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.name!=`string`||!a.name.trim()){json(t,400,{ok:!1,error:`Missing or invalid name`});return}if(typeof a.email!=`string`||!a.email.trim()){json(t,400,{ok:!1,error:`Missing or invalid email`});return}n=a.name.trim(),r=a.email.trim()}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!b){json(t,400,{ok:!1,error:`No project directory configured`});return}if(!C.tryAcquire(nt)){json(t,429,{ok:!1,error:`A set-identity operation is already in progress`});return}try{writeGitIdentity(b,n,r),v?.()?.refreshIdentity().catch(()=>{}),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`set-identity failed`})}finally{C.release(nt)}}async function it(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,200,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1});return}json(t,200,n.getStatus())}async function at(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r=`sync`;try{let t=await readBody(e);if(t.length>0){let e=JSON.parse(t.toString());(e.op===`push`||e.op===`pull`||e.op===`sync`)&&(r=e.op)}}catch{}json(t,202,{ok:!0,op:r}),n.trigger(r)}async function ot(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let n=await readBody(e),i=JSON.parse(n.toString());if(typeof i.enabled!=`boolean`){json(t,400,{ok:!1,error:`enabled must be a boolean`});return}r=i.enabled}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}await n.setEnabled(r),json(t,200,{ok:!0,status:n.getStatus()})}async function st(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();json(t,200,{conflicts:n?n.getConflicts():[]})}async function ct(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let t=await readBody(e);r=JSON.parse(t.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}let{file:i,strategy:a,content:o}=r;if(!i||typeof i!=`string`){json(t,400,{ok:!1,error:`Missing required field: file`});return}if(a!==`mine`&&a!==`theirs`&&a!==`content`){json(t,400,{ok:!1,error:`Invalid strategy: must be 'mine', 'theirs', or 'content'`});return}try{await n.resolveConflict(i,a,o),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function lt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!b){json(t,503,{ok:!1,error:`Project repo not configured`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`file`);if(!n){json(t,400,{ok:!1,error:`Missing required query param: file`});return}if(n.includes(`..`)||n.startsWith(`/`)){json(t,400,{ok:!1,error:`Invalid file path`});return}let r=esm_default({baseDir:b,timeout:{block:15e3}});async function i(e){try{return await r.raw([`show`,`:${e}:${n}`])}catch{return``}}try{let[e,r,a]=await Promise.all([i(1),i(2),i(3)]);json(t,200,{ok:!0,file:n,base:e,ours:r,theirs:a})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function ut(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=new URL(e.url??`/`,`http://localhost`).searchParams.get(`rootDir`)??void 0;try{json(t,200,{ok:!0,plan:await planSeed({projectDir:r,rootDir:n})})}catch(e){if(e instanceof SeedPrerequisiteError){json(t,200,{ok:!1,error:{kind:`prerequisite-missing`,message:e.message}});return}if(e instanceof SeedRootDirError){json(t,200,{ok:!1,error:{kind:`invalid-root`,message:e.message}});return}json(t,500,{ok:!1,error:{kind:`internal`,message:e instanceof Error?e.message:String(e)}})}}async function dt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await readBody(e),i=JSON.parse(r.toString());if(!i.plan||typeof i.plan!=`object`){json(t,400,{ok:!1,error:`Missing or invalid plan`});return}n=i.plan}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}try{json(t,200,{ok:!0,result:await applySeed(n,{projectDir:r})})}catch(e){json(t,500,{ok:!1,error:{kind:`internal`,message:e instanceof Error?e.message:String(e)}})}}async function ft(e,t){if(checkLocalOpSecurity(e,t,json))return handleInstalledAgents(e,t,w.probeAll)}async function pt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}try{await n.abortMerge(),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}let mt={"/api/document":te,"/api/documents":ne,"/api/backlinks":re,"/api/backlink-counts":ie,"/api/forward-links":ae,"/api/link-graph":oe,"/api/dead-links":le,"/api/orphans":se,"/api/hubs":ce,"/api/pages":Fe,"/api/suggest-links":Ie,"/api/page-headings":je,"/api/create-page":Ae,"/api/rename":Me,"/api/rename-path":Ne,"/api/delete-path":Pe,"/api/upload-image":Le,"/api/agent-write":Q,"/api/agent-write-md":ee,"/api/agent-patch":ue,"/api/agent-undo":de,"/api/agent-activity":fe,"/api/agent-burst-diff":pe,"/api/save-version":ge,"/api/history":_e,"/api/diff":ye,"/api/rollback":be,"/api/metrics/reconciliation":xe,"/api/metrics/parse-health":Se,"/api/metrics/agent-presence":Te,"/api/server-info":Ce,"/api/principal":we,"/api/rescue":Oe,"/api/workspace":Ee,"/api/sync/status":it,"/api/sync/trigger":at,"/api/sync/set-enabled":ot,"/api/sync/conflicts":st,"/api/sync/conflict-content":lt,"/api/sync/resolve-conflict":ct,"/api/sync/abort-merge":pt,"/api/local-op/clone":He,"/api/local-op/open":We,"/api/local-op/auth/login":Xe,"/api/local-op/auth/status":Ze,"/api/local-op/auth/repos":Qe,"/api/local-op/auth/signout":$e,"/api/local-op/auth/pat":et,"/api/local-op/auth/identity":tt,"/api/local-op/auth/set-identity":rt,"/api/installed-agents":ft,"/api/seed/plan":ut,"/api/seed/apply":dt};return s&&(mt[`/api/test-reset`]=me,mt[`/api/test-rescan-backlinks`]=he),{priority:100,async onRequest({request:e,response:t}){let n=e.url?.split(`?`)[0];if(!n)return;if(n.startsWith(`/api/`)){let n=e.headers.origin;if(n!==void 0&&!isAllowedApiOrigin(n)){typeof t.setHeader==`function`&&t.setHeader(`Content-Type`,`application/json`),t.writeHead(403),t.end(JSON.stringify({ok:!1,error:`origin-not-allowed`}));return}if(typeof t.setHeader==`function`&&(n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(!n.startsWith(`/api/`))return;let r=propagation.extract(context.active(),e.headers),i=e.method??`GET`,a=n;n.startsWith(`/api/rescue/`)?a=`/api/rescue/:docName`:n.startsWith(`/api/history/`)&&(a=`/api/history/:sha`);let o=getTracer(),s=Date.now();await context.with(r,()=>o.startActiveSpan(`HTTP ${i} ${a}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:i,[ATTR_HTTP_ROUTE]:a,[ATTR_URL_PATH]:n,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async r=>{try{let i=mt[n];if(i)await i(e,t);else if(n.startsWith(`/api/rescue/`)){let r=decodeURIComponent(n.slice(12));r&&await ke(e,t,r)}else if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&await ve(e,t,r)}let a=t.statusCode;r.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,a),a>=500&&r.setStatus({code:SpanStatusCode.ERROR,message:`status ${a}`})}catch(e){throw r.recordException(e),r.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),e}finally{r.end();let e=(Date.now()-s)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:i,[ATTR_HTTP_ROUTE]:a,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}const HocuspocusAuthTokenSchema=object({principalId:string().optional(),tabSessionId:string().optional(),expectedServerInstanceId:string().optional(),expectedBranch:string().optional()}).loose();var HocuspocusAuthRejection=class extends Error{reason;constructor(e,t){super(t),this.name=`HocuspocusAuthRejection`,this.reason=e}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=HocuspocusAuthTokenSchema.safeParse(t);return n.success?n.data:void 0}const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,n=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}const BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`]);function createContentFilter(e){let{projectDir:t,contentDir:n,includePatterns:r,excludePatterns:i}=e,a=(0,import_picomatch.default)(r,{dot:!0}),o=(0,import_ignore.default)();o.add(`.git`);let s=join(t,`.gitignore`),c=[];if(existsSync(s))try{let e=parseGitignorePatterns(readFileSync(s,`utf-8`));c.push(...e),o.add(e)}catch(e){console.warn(`[content-filter] Failed to read .gitignore at ${s}:`,e)}let l=relative(t,n),u=l.startsWith(`..`);if(i.length>0&&(l?o.add(i.map(e=>`${l}/${e}`)):o.add(i)),l){let e=join(n,`.gitignore`);if(existsSync(e))try{let t=parseGitignorePatterns(readFileSync(e,`utf-8`)).map(e=>e.startsWith(`!`)?`!${l}/${e.slice(1)}`:`${l}/${e}`);o.add(t)}catch(t){console.warn(`[content-filter] Failed to read .gitignore at ${e}:`,t)}}loadNestedGitignores(n,t,o);let d=[...c,...i].filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),f=new Map;function p(e){if(u)return!1;let t=l?`${l}/${e}`:e;return o.ignores(t)}return populateDirCount(n,``,a,p,f),{isExcluded(e){if(isSystemDoc(stripDocExtension(e))||!u&&p(e))return!0;if(a(e))return!1;let t=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(t)){let t=dirname(e),n=t===`.`?``:t;if((f.get(n)??0)>0)return!1}return!0},isDirExcluded(e){let t=e.split(`/`)[0];if(BUILTIN_SKIP_DIRS.has(t))return!0;if(u)return!1;let n=l?`${l}/${e}`:e;return o.ignores(n)||o.ignores(`${n}/`)},getWatcherIgnoreGlobs(){return d},incrementMdDir(e){let t=e===`.`?``:e;f.set(t,(f.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,n=f.get(t)??0;n<=1?f.delete(t):f.set(t,n-1)}}}function populateDirCount(e,t,n,r,i){let a;try{a=readdirSync(e,{withFileTypes:!0})}catch{return}for(let o of a){let a=t?`${t}/${o.name}`:o.name;if(o.isDirectory()){if(BUILTIN_SKIP_DIRS.has(o.name)||r(a)||r(`${a}/`))continue;populateDirCount(join(e,o.name),a,n,r,i)}else if(o.isFile()&&isSupportedDocFile(o.name)&&n(a)&&!r(a)){let e=t===``?``:t;i.set(e,(i.get(e)??0)+1)}}}function parseGitignorePatterns(e){return e.split(`
120
+ `)){if(i(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),i=getHeadingSlug(e,r);i&&n.push({level:t[1].length,text:e,slug:i})}}return n}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function isAllowedApiOrigin(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function createApiExtension(e){let{hocuspocus:t,sessionManager:n,contentDir:r,serverInstanceId:i,getFileIndex:a,getAliasMap:o,enableTestRoutes:s=!1,shadowRef:c,flushGitCommit:l,getCurrentBranch:u,getDiskAckSVs:d,contentRoot:f,backlinkIndex:p,signalChannel:m,agentFocusBroadcaster:h,agentPresenceBroadcaster:g,onAgentWrite:_,getSyncEngine:v,localOpCliArgs:y=[`open-knowledge`],projectDir:b,getPrincipal:x,installedAgentsProbe:S,forceUnloadDocument:C}=e,w=createConcurrencyGuard(),T=createInstalledAgentsProbe({probe:S??createOsProbe(process.platform)});function E(e){if(!isSafeDocName(e))return null;let t=resolve(r),n=resolve(t,`${e}${getDocExtension(e)}`);return!n.startsWith(`${t}/`)&&n!==t?null:n}function D(e){let t=E(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}let O={cluster:void 0,category:void 0,tags:void 0};function k(e){try{let n=t.documents.get(e);if(n){let e=n.getMap(`metadata`).get(`frontmatter`);if(typeof e==`string`&&e)return parseFrontmatterMetadata(e)}}catch{}try{let t=E(e);if(!t||!existsSync(t))return O;let{frontmatter:n}=stripFrontmatter(readFileSync(t,`utf-8`));return n?parseFrontmatterMetadata(n):O}catch{return O}}function A(e){if(p)try{if(p.getBacklinks(e).length>0)return;let t=performance.now(),n=findHubCandidates(e,a()),r=performance.now()-t;return r>5&&log$2.debug({docName:e,elapsedMs:r,candidateCount:n.length},`[orphan-hint] findHubCandidates slow`),n.length===0?void 0:[{type:`orphan`,parentCandidates:n,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${n.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function j(e){return o?.().get(e)??e}function M(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function N(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function P(e,n){let r=`onStoreDocument-${e}`;(t.debouncer.isDebounced(r)?t.debouncer.executeNow(r):Promise.resolve()).then(()=>l?.()).catch(e=>{log$2.warn({err:e},`[${n}] post-write flush failed`)})}function F(){let e=new Set;for(let[t,n]of a()){e.add(t);for(let t of n.aliases)e.add(t)}return e}function I(){let e=Promise.resolve();return async function(t){let n=e,r=()=>{};e=new Promise(e=>{r=e}),await n;try{return await t()}finally{r()}}}let L=I();function R(e){return e instanceof Error&&(e.message===`Managed rename requires backlink index support`||e.message.startsWith(`Cannot rename missing document:`)||e.message.startsWith(`symlink-escape:`))?e.message:`Failed to rename document`}async function z(e){let r=new Map;for(let n of e){let e=t.documents.get(n);e&&r.set(n,e.getText(`source`).toString())}for(let t of e)await n.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let n of e){let e=t.documents.get(n);deleteReconciledBase(n),e&&(t.closeConnections(n),await(C??t.unloadDocument.bind(t))(e))}return r}function B(e,t){for(let{fromDocName:n,toDocName:i}of e){let e=safeContentPath(i,r),a=t.get(n);typeof a==`string`&&writeFileSync(e,a,`utf-8`);let o=typeof a==`string`?a:existsSync(e)?readFileSync(e,`utf-8`):null;typeof o==`string`&&registerWrite(e,contentHash(o))}}function V(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let i=safeContentPath(e,r);if(!existsSync(i))throw Error(`Cannot snapshot missing document: ${e}`);return{docName:e,content:readFileSync(i,`utf-8`)}})}function H(e){let n=t.documents.get(e);if(n)return n.getText(`source`).toString();let i=resolveContentEntryPath(r,`file`,e);return existsSync(i)?readFileSync(i,`utf-8`):null}function U(e,t){let n=resolveContentEntryPath(r,`file`,e);mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,t,`utf-8`),registerWrite(n,contentHash(t)),setReconciledBase(e,t);let i=a();i instanceof Map&&updateFileIndex({kind:`update`,path:n,docName:e,content:t},i)}function W(e,n,r){let i=t.documents.get(e);if(!i)throw Error(`Document is not loaded: ${e}`);let a={markdown:``,rewrites:0};return i.transact(()=>{let t=i.getXmlFragment(`default`),o=i.getText(`source`),s=o.toString();if(a=rewriteSupportedLinksForDocumentRename(s,e,n,r),a.rewrites===0)return;let{body:c}=stripFrontmatter(a.markdown),l=mdManager.parseWithFallback(c);updateYFragment(i,t,schema.nodeFromJSON(l),{mapping:new Map,isOMark:new Map}),applyFastDiff(o,s,a.markdown)},MANAGED_RENAME_ORIGIN),a}async function G(e,n){return L(async()=>{if(!p)throw Error(`Managed rename requires backlink index support`);let i=resolveContentEntryPath(r,`file`,e),o=resolveContentEntryPath(r,`file`,n),s=[{fromDocName:e,toDocName:n}],c=[...new Set(p.getBacklinks(e).map(e=>e.source))].sort((e,t)=>e.localeCompare(t)),l=new Map,u=[],d=[];for(let t of[e,...c]){if(l.has(t))continue;let n=H(t);typeof n==`string`?(l.set(t,n),t!==e&&u.push(t)):t!==e&&d.push(t)}if(typeof l.get(e)!=`string`)throw Error(`Cannot rename missing document: ${e}`);let f=createManagedRenameRecoveryJournal({sourceDocName:e,destinationDocName:n,snapshots:V([...l.keys()],l)}),h=[];return await withManagedRenameRecovery(r,f,async()=>{for(let e of d)p.deleteDocument(e);for(let r of u){let i=t.documents.get(r)?W(r,e,n):rewriteSupportedLinksForDocumentRename(l.get(r)??``,r,e,n);i.rewrites>0&&(U(r,i.markdown),h.push({docName:r,rewrites:i.rewrites})),p.updateDocumentFromMarkdown(r,i.markdown)}let r=rewriteSupportedLinksForDocumentRename((await z([e])).get(e)??l.get(e)??readFileSync(i,`utf-8`),e,e,n);await renameTrackedPathInGit(b,i,o)||(mkdirSync(dirname(o),{recursive:!0}),renameSync(i,o)),B(s,new Map([[e,r.markdown]])),setReconciledBase(n,r.markdown);let c=a();c instanceof Map&&updateFileIndex({kind:`rename`,oldPath:i,newPath:o,oldDocName:e,newDocName:n,content:r.markdown},c),p.renameDocument(e,n,r.markdown),r.rewrites>0&&h.push({docName:n,rewrites:r.rewrites})}),p.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${n}:`,t)}),m?.(`files`),m?.(`backlinks`),m?.(`graph`),h.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:s,rewrittenDocs:h}})}let K=128;function q(e){let t=typeof e.agentId==`string`?e.agentId:void 0;t!==void 0&&!AGENT_ID_RE.test(t)&&(t=void 0);let n=t?toBroadcasterKey(t):`claude-1`,r=typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,i=typeof e.clientName==`string`?e.clientName:void 0;i!==void 0&&(i=sanitizeGitIdentity(i));let a=typeof e.clientVersion==`string`?e.clientVersion:void 0;a!==void 0&&(a=sanitizeGitIdentity(a));let o=typeof e.label==`string`?e.label:void 0;o!==void 0&&(o=sanitizeGitIdentity(o));let s=typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):t??n;return{rawAgentId:t,agentId:n,agentName:r,colorSeed:s,clientName:i,clientVersion:a,label:o}}function J(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function Y(e){return{principalId:x?.()?.id,agentType:J(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function X(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function Z(e){return{value:e.value}}function Q(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}async function ee(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}let a=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!isSafeDocName(a)){json(t,400,{ok:!1,error:`Invalid docName`});return}let o=j(a);if(isSystemDoc(o)){json(t,400,{ok:!1,error:`'${o}' is a reserved document name`});return}let{agentId:s,agentName:c,colorSeed:l,clientName:u,clientVersion:d,label:f}=q(i),p=normalizeSummary(i.summary);if(p.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let m=await n.getSession(o,s,{displayName:c,colorSeed:l,clientName:u}),h=new Date().toISOString(),v=typeof i.content==`string`?i.content:`Hello from the agent! ${h}`,{response:y,stored:b}=X(p);try{let e=iconFromClientName(u),t=AGENT_ICON_COLORS[e]??colorFromSeed(l??s);g?.setPresence(s,{displayName:c,icon:e,color:t,currentDoc:o,mode:`writing`,ts:Date.now()}),captureEffect(m.dc.document.getText(`source`),s,l,u),m.dc.document.transact(()=>{applyAgentMarkdownWrite(m.dc.document,`${v}\n`,`append`),m.dc.document.getMap(`agent-flash`).set(s,{agentId:s,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${v.slice(0,50)}`})},m.origin),recordContributor(o,s,c,l,void 0,Y({clientName:u,clientVersion:d,label:f}),b),incrementAgentWriteCalls(),Q(p)}finally{g?.touchMode(s,`idle`)}P(o,`agent-write`),_?.(),json(t,200,{ok:!0,timestamp:h,...y?{summary:y}:{}})}catch(e){log$2.error({err:e},`[agent-write] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function te(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{markdown:a,position:o}=i;if(!a||typeof a!=`string`){json(t,400,{ok:!1,error:`markdown field required`});return}let s=o===`prepend`?`prepend`:o===`replace`?`replace`:`append`,c=i.docName,l=typeof c==`string`&&c.length>0?c:`test-doc`;if(!isSafeDocName(l)){json(t,400,{ok:!1,error:`Invalid docName`});return}let u=j(l);if(isSystemDoc(u)){json(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}let{agentId:d,agentName:f,colorSeed:p,clientName:m,clientVersion:v,label:y}=q(i),b=normalizeSummary(i.summary);if(b.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let{response:x,stored:S}=X(b),C=await n.getSession(u,d,{displayName:f,colorSeed:p,clientName:m}),w=new Date().toISOString();try{let e=iconFromClientName(m),t=AGENT_ICON_COLORS[e]??colorFromSeed(p??d);g?.setPresence(d,{displayName:f,icon:e,color:t,currentDoc:u,mode:`writing`,ts:Date.now()}),captureEffect(C.dc.document.getText(`source`),d,p,m),C.dc.document.transact(()=>{applyAgentMarkdownWrite(C.dc.document,a,s),C.dc.document.getMap(`agent-flash`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Added (${f}): ${a.trim().slice(0,50)}`})},C.origin),recordContributor(u,d,f,p,void 0,Y({clientName:m,clientVersion:v,label:y}),S),incrementAgentWriteCalls(),Q(b)}finally{g?.touchMode(d,`idle`)}P(u,`agent-write-md`),h?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`write`,ts:Date.now()}),_?.();let T=A(u),E=M(u),D=N();D===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":J(m)}),json(t,200,{ok:!0,timestamp:w,subscriberCount:E,systemSubscriberCount:D,...T?{hints:T}:{},...x?{summary:x}:{}})}catch(e){log$2.error({err:e},`[agent-write-md] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function ne(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(r)){json(n,400,{ok:!1,error:`Invalid docName`});return}let i=j(r);if(isSystemDoc(i)){json(n,400,{ok:!1,error:`'${i}' is a reserved document name`});return}let a=await t.openDirectConnection(i);try{let e=a.document;if(!e){json(n,500,{ok:!1,error:`Document not available`});return}json(n,200,{ok:!0,docName:i,content:e.getText(`source`).toString()})}finally{await a.disconnect()}}catch(e){console.error(`[document-read]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function re(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`dir`);if(n)try{safeSubdir(r,n)}catch{json(t,400,{ok:!1,error:`Invalid directory parameter`});return}let i=a(),o=[];for(let[e,t]of i)if(!(n&&!e.startsWith(`${n}/`)&&e!==n)){o.push({docName:e,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(n&&!i.startsWith(`${n}/`)&&i!==n)continue;let a=relative(r,t.canonicalPath);o.push({docName:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}o.sort((e,t)=>e.docName.localeCompare(t.docName)),json(t,200,{ok:!0,documents:o})}catch(e){console.error(`[document-list]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function ie(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}json(t,200,{ok:!0,docName:n,backlinks:p.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:D(e.source),snippet:e.snippet}))})}catch(e){console.error(`[backlinks]`,e),json(t,500,{ok:!1,error:`Failed to read backlinks`})}}async function ae(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){json(t,400,{ok:!1,error:`Missing docNames parameter`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(r[t]=p.getBacklinkCount(t))}json(t,200,{ok:!0,counts:r})}catch(e){console.error(`[backlink-counts]`,e),json(t,500,{ok:!1,error:`Failed to read backlink counts`})}}async function oe(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}json(t,200,{ok:!0,docName:n,forwardLinks:p.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:D(e.target),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})})}catch(e){console.error(`[forward-links]`,e),json(t,500,{ok:!1,error:`Failed to read forward links`})}}async function se(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`docName`);if(r&&!isSafeDocName(r)){json(t,400,{ok:!1,error:`Invalid docName`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){json(t,400,{ok:!1,error:`docName is required when degrees is provided`});return}let a,o;if(i&&r){let e=Number.parseInt(i,10);if(!Number.isFinite(e)||e<0){json(t,400,{ok:!1,error:`degrees must be a non-negative integer`});return}({nodes:a,links:o}=p.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=p.getLinkGraph());json(t,200,{ok:!0,nodes:a.map(e=>{if(e.kind===`doc`){let t=k(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:D(e.docName),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:o})}catch(e){console.error(`[link-graph]`,e),json(t,500,{ok:!1,error:`Failed to read link graph`})}}async function ce(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(n)){json(t,400,{ok:!1,error:`Invalid orphan mode. Allowed values: incoming, outgoing, both`});return}json(t,200,{ok:!0,orphans:p.getOrphans([...a().keys()],n).map(e=>({docName:e,title:D(e)}))})}catch(e){console.error(`[orphans]`,e),json(t,500,{ok:!1,error:`Failed to read orphan pages`})}}async function le(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20;json(t,200,{ok:!0,hubs:p.getHubs(i).map(e=>({docName:e.docName,title:D(e.docName),count:e.count}))})}catch(e){console.error(`[hubs]`,e),json(t,500,{ok:!1,error:`Failed to read hub pages`})}}async function ue(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(n.some(e=>e.length===0||!isSafeDocName(e))){json(t,400,{ok:!1,error:`Invalid sourceDocName`});return}let r=n.length?[...new Set(n.map(e=>j(e)))]:void 0;json(t,200,{ok:!0,deadLinks:p.getDeadLinks(F(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:D(e.source),snippet:e.snippet}))}))})}catch(e){console.error(`[dead-links]`,e),json(t,500,{ok:!1,error:`Failed to read dead links`})}}async function de(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{find:a,replace:o,docName:s,offset:c}=i;if(typeof a!=`string`||a.length===0){json(t,400,{ok:!1,error:`find field required`});return}if(typeof o!=`string`){json(t,400,{ok:!1,error:`replace field required`});return}let l=Object.hasOwn(i,`offset`),u;if(l){if(typeof c!=`number`||!Number.isInteger(c)||c<0){json(t,400,{ok:!1,error:`offset must be a non-negative integer`});return}u=c}let d=typeof s==`string`&&s.length>0?s:`test-doc`;if(!isSafeDocName(d)){json(t,400,{ok:!1,error:`Invalid docName`});return}let f=j(d);if(isSystemDoc(f)){json(t,400,{ok:!1,error:`'${f}' is a reserved document name`});return}let{agentId:p,agentName:m,colorSeed:v,clientName:y,clientVersion:b,label:x}=q(i),S=normalizeSummary(i.summary);if(S.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let C=await n.getSession(f,p,{displayName:m,colorSeed:v,clientName:y}),w=new Date().toISOString(),T=!1,E=!1;try{let e=iconFromClientName(y),t=AGENT_ICON_COLORS[e]??colorFromSeed(v??p);if(g?.setPresence(p,{displayName:m,icon:e,color:t,currentDoc:f,mode:`writing`,ts:Date.now()}),captureEffect(C.dc.document.getText(`source`),p,v,y),C.dc.document.transact(()=>{let e=C.dc.document.getXmlFragment(`default`),t=C.dc.document.getMap(`metadata`),n=t.get(`frontmatter`)??``,r=prependFrontmatter(n,mdManager.serialize(yXmlFragmentToProseMirrorRootNode(e,schema).toJSON())),i=u==null?r.indexOf(a):r.slice(u,u+a.length)===a?u:-1;if(i===-1){u==null?T=!0:E=!0;return}let{frontmatter:s,body:c}=stripFrontmatter(r.slice(0,i)+o+r.slice(i+a.length));s!==n&&t.set(`frontmatter`,s),applyAgentMarkdownWrite(C.dc.document,c,`replace`),C.dc.document.getMap(`agent-flash`).set(p,{agentId:p,timestamp:Date.now(),type:`insert`,description:`Patched (${m}): ${a.slice(0,50)}`})},C.origin),!T&&!E){let{stored:e}=X(S);recordContributor(f,p,m,v,void 0,Y({clientName:y,clientVersion:b,label:x}),e),incrementAgentWriteCalls(),Q(S)}}finally{g?.touchMode(p,`idle`)}if(E){json(t,409,{ok:!1,error:`Target text no longer matches at the requested offset`});return}if(T){json(t,404,{ok:!1,error:`Text not found in document`});return}P(f,`agent-patch`),h?.setFocus(p,{agentName:m,currentDoc:f,writeKind:`edit`,ts:Date.now()}),_?.();let D=M(f),O=N();O===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":J(y)});let{response:k}=X(S);json(t,200,{ok:!0,timestamp:w,subscriberCount:D,systemSubscriberCount:O,...k?{summary:k}:{}})}catch(e){log$2.error({err:e},`[agent-patch] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function fe(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=q(i),d=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!isSafeDocName(d)){json(t,400,{ok:!1,error:`Invalid docName`});return}let f=j(d);if(isSystemDoc(f)){json(t,400,{ok:!1,error:`'${f}' is a reserved document name`});return}let p=typeof i.connectionId==`string`?i.connectionId:void 0;if(!p){json(t,400,{ok:!1,error:`connectionId required`});return}let m=i.scope,_=m===`session`||m===`file`?`session`:`last`;if(!n.hasSession(f,p)){json(t,404,{ok:!1,error:`No active session for this connectionId and docName`});return}let v=await n.getSession(f,p),y=!1;try{let e=iconFromClientName(c),t=AGENT_ICON_COLORS[e]??colorFromSeed(s??a);g?.setPresence(a,{displayName:o,icon:e,color:t,currentDoc:f,mode:`writing`,ts:Date.now()}),y=applyAgentUndo(v,_),y&&recordContributor(f,p,o,s,void 0,Y({clientName:c,clientVersion:l,label:u}))}finally{g?.touchMode(a,`idle`)}y&&P(f,`agent-undo`),h?.setFocus(p,{agentName:p,currentDoc:f,writeKind:`undo`,ts:Date.now()}),json(t,200,{ok:!0,docName:f,scope:_,undone:y})}catch(e){log$2.error({err:e},`[agent-undo] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function pe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(r===null){json(t,400,{ok:!1,error:`agentId required (alphanumeric/_/- only)`});return}json(t,200,{ok:!0,...listAgentActivity(n,r)})}catch(e){log$2.error({err:e},`[agent-activity] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function me(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=validateAgentId(r.searchParams.get(`agentId`)),a=r.searchParams.get(`docName`),o=r.searchParams.get(`stackIndex`);if(i===null){json(t,400,{ok:!1,error:`agentId required (alphanumeric/_/- only)`});return}if(!a||a.trim()===``){json(t,400,{ok:!1,error:`docName required`});return}if(!isSafeDocName(a)){json(t,400,{ok:!1,error:`Invalid docName`});return}let s=j(a);if(isSystemDoc(s)){json(t,400,{ok:!1,error:`'${s}' is a reserved document name`});return}if(!o||Number.isNaN(Number(o))){json(t,400,{ok:!1,error:`stackIndex must be a number`});return}let c=Number(o);if(!Number.isInteger(c)||c<0){json(t,400,{ok:!1,error:`stackIndex must be a non-negative integer`});return}let l=n.getLiveSession(s,i);if(!l){json(t,404,{ok:!1,error:`No active session for this agentId and docName`});return}let u=l.um;if(c>=u.undoStack.length){json(t,404,{ok:!1,error:`stackIndex ${c} out of range (stack has ${u.undoStack.length} items)`});return}let d=u.undoStack[c];json(t,200,{ok:!0,diff:synthesizeStackItemDiffText(d,l.dc.document.getText(`source`),s),generatedAt:Date.now()})}catch(e){log$2.error({err:e},`[agent-burst-diff] handler failed`),json(t,500,{ok:!1,error:`Internal server error`})}}async function he(e,i){if(e.method!==`POST`){i.writeHead(405),i.end(`Method not allowed`);return}try{let a=j(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??`test-doc`),o;try{o=safeContentPath(a,r)}catch(e){console.error(`[test-reset] safeContentPath rejected docName:`,a,e),json(i,400,{ok:!1,error:`Invalid docName`});return}await n.closeAll(a),t.closeConnections(a);let s=`onStoreDocument-${a}`;t.debouncer.isDebounced(s)&&await t.debouncer.executeNow(s);let c=t.documents.get(a);c&&await(C??t.unloadDocument.bind(t))(c),writeFileSync(o,``,`utf-8`),p&&(p.deleteDocument(a),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${a}:`,e)}),m?.(`backlinks`),m?.(`graph`)),m?.(`files`),json(i,200,{ok:!0})}catch(e){console.error(`[test-reset]`,e),json(i,500,{ok:!1,error:`Internal server error`})}}async function ge(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{if(!p){json(t,503,{ok:!1,error:`Backlink index not configured`});return}p.rebuildFromDisk(),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),m?.(`backlinks`),m?.(`graph`),json(t,200,{ok:!0})}catch(e){console.error(`[test-rescan-backlinks]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function _e(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n=c?.current;if(!n){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}try{let r;try{r=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i=/^[a-zA-Z0-9_-]+$/,a=[],o,s={},c,l;if(r.length>0){let e;try{e=JSON.parse(r.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}s=e,typeof e.message==`string`&&e.message.trim()&&(o=e.message.replace(/[\r\n]/g,` `).slice(0,256)),Array.isArray(e.writers)&&(a=e.writers.map(e=>{let t=e.id??`unknown`;if(!i.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}}));let n=e.principal;if(n&&typeof n==`object`&&!Array.isArray(n)){let e=n;typeof e.name==`string`&&e.name.trim()&&(c=sanitizeGitIdentity(e.name.trim())),typeof e.email==`string`&&e.email.trim()&&(l=sanitizeGitIdentity(e.email.trim()))}}let{rawAgentId:u,agentId:d,agentName:p,clientName:m}=q(s);a.length===0&&(a=u===void 0?[SERVICE_WRITER]:[{id:d,name:m?`${p} (${m})`:p,email:`${d}@openknowledge.local`}]);let h=f??`.`,g=await saveVersion(n,h,a);console.log(`[history] checkpoint ${g.checkpointRef}`);let _=swapContributors(),v;if(b){let e=!1;try{await esm_default({baseDir:b,timeout:{block:5e3}}).revparse([`--git-dir`]),e=!0}catch(e){console.warn(`[save-version] parent-git unavailable: ${e instanceof Error?e.message:String(e)}`)}if(e)try{v=await withParentLock(async()=>{let e=esm_default({baseDir:b,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,n=`ok/v${t}`,r=`openknowledge`,i=`noreply@openknowledge.local`;if(c&&l)r=c,i=l;else try{let e=await resolveGitIdentity(b);e&&(r=e.name,i=e.email)}catch{}let a=[];for(let e of _.values())if(e.writerId.startsWith(`agent-`)||e.writerId.startsWith(`principal-`)){let t=`${e.writerId}@openknowledge.local`;a.push(`Co-Authored-By: ${e.displayName} <${t}>`)}let s=formatCheckpointSubject(o??`Checkpoint v${t}`),u=a.length>0?`${s}\n\n${a.join(`
121
+ `)}`:s,d=h||`.`;return await e.add(d),await e.env({GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i}).commit(u,[`--allow-empty`]),await e.addTag(n),console.log(`[checkpoint] parent-git commit + tag ${n}`),n})}catch(e){console.warn(`[checkpoint] parent-git commit failed (non-fatal):`,e)}}json(t,200,{ok:!0,checkpointRef:g.checkpointRef,...v?{versionTag:v}:{}})}catch(e){console.error(`[save-version]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function ve(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=c?.current;if(!n){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`branch`)??u?.()??`main`;if(!i){json(t,400,{ok:!1,error:`docName query parameter is required`});return}if(a.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(a)){json(t,400,{ok:!1,error:`Invalid branch name`});return}let o=Number(r.searchParams.get(`limit`)??`50`),s=Number(r.searchParams.get(`offset`)??`0`),l=Math.min(200,Number.isFinite(o)?o:50),d=Number.isFinite(s)?s:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=Date.now();try{let e=await getDocumentHistory(n,{docName:i,branch:a,limit:l,offset:d,type:p,author:m,excludeAuthor:h},f??`.`),r=Date.now()-g;console.log(`[timeline] query docName=${i} entries=${e.entries.length} duration=${r}ms`),json(t,200,{ok:!0,...e})}catch(e){console.error(`[shadow]`,e),json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function ye(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let r=c?.current;if(!r){json(t,400,{ok:!1,error:`Shadow repo not configured`});return}let i=safeDocPath(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,f??`.`);if(`error`in i){json(t,400,{ok:!1,error:i.error});return}let a=i.path,o=shadowGit(r);if(!/^[0-9a-f]{40}$/i.test(n)){json(t,400,{ok:!1,error:`Invalid commit SHA`});return}try{try{await o.raw(`cat-file`,`-e`,`${n}:${a}`)}catch{json(t,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await o.raw(`show`,`${n}:${a}`),[r=``,i=``]=(await o.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);json(t,200,{ok:!0,sha:n,content:e,timestamp:r,author:i})}catch(e){console.error(`[shadow-version]`,e),json(t,500,{ok:!1,error:`Internal server error`})}}async function be(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}let r=c?.current;if(!r){json(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`docName`)??``,o=i.searchParams.get(`from`)??``,s=i.searchParams.get(`to`)??``;if(!s||!/^[0-9a-f]{40}$/i.test(s)){json(n,400,{ok:!1,error:`'to' must be a valid 40-char commit SHA`});return}let l=safeDocPath(a,f??`.`);if(`error`in l){json(n,400,{ok:!1,error:l.error});return}let u=l.path,d=shadowGit(r);try{let e;try{e=await d.raw(`show`,`${s}:${u}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at the target version`});return}let r;if(o&&/^[0-9a-f]{40}$/i.test(o))try{r=await d.raw(`show`,`${o}:${u}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at the source version`});return}else{let e=t.documents.get(a);if(!e){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}r=e.getText(`source`).toString()}let i=stripFrontmatter(r).body,c=stripFrontmatter(e).body,l=diffLines(i,c),f=[],p=0,m=0;for(let e of l){let t=e.value.replace(/\n$/,``).split(`
122
+ `),n=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)f.push({type:n,text:e});e.added&&(p+=t.length),e.removed&&(m+=t.length)}json(n,200,{ok:!0,lines:f,additions:p,deletions:m})}catch(e){console.error(`[diff]`,e),json(n,500,{ok:!1,error:`Internal server error`})}}async function xe(e,n){if(e.method!==`POST`){n.writeHead(405),n.end(`Method not allowed`);return}let r=c?.current;if(!r){json(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i;try{i=await readBody(e)}catch{json(n,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{json(n,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){json(n,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:l,clientName:u,clientVersion:d,label:p}=q(a),{docName:m,commitSha:g,versionTag:_}=a,v=typeof m==`string`?m:``,y=typeof g==`string`?g:``,x=typeof _==`string`?_:void 0;if(!v){json(n,400,{ok:!1,error:`docName required`});return}if(!y||!/^[0-9a-f]{40}$/i.test(y)){json(n,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let S=a,C=typeof S.agentId==`string`&&S.agentId.length>0,w=normalizeSummary(S.summary);if(w.kind===`invalid`){json(n,400,{ok:!1,error:`summary must be a string`});return}let T=f??`.`,E=safeDocPath(v,T);if(`error`in E){json(n,400,{ok:!1,error:E.error});return}let D=E.path,O=shadowGit(r),k=Date.now();try{try{await O.raw(`cat-file`,`-e`,`${y}:${D}`)}catch{json(n,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await O.raw(`show`,`${y}:${D}`),i=new Date().toISOString();await safetyCheckpoint(r,T,{action:`rollback`,context:{docName:v,targetSha:y}});let a=t.documents.get(v);if(!a){json(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{frontmatter:c,body:m}=stripFrontmatter(e),g=mdManager.parseWithFallback(m),_=schema.nodeFromJSON(g),S=a.getXmlFragment(`default`);a.transact(()=>{updateYFragment(a,S,_,{mapping:new Map,isOMark:new Map});let t=a.getText(`source`),n=t.toString();n!==e&&(t.delete(0,n.length),t.insert(0,e)),a.getMap(`metadata`).set(`frontmatter`,c)},ROLLBACK_ORIGIN);let E;if(C){let e=y.slice(0,8),t=w.kind===`value`,n=t?w:normalizeSummary(`Restored to ${e}`),r=X(n);E=t||!r.response?r.response:Z(r.response),recordContributor(v,o,s,l,formatRollbackSubject(v,y),Y({clientName:u,clientVersion:d,label:p}),r.stored),incrementAgentWriteCalls(),Q(n,!t)}P(v,`rollback`);let A=Date.now()-k;if(console.log(`[rollback] docName=${v} from=${y.slice(0,8)} duration=${A}ms`),b){let e=`Restored to ${x??y.slice(0,8)}: ${v}`,t=f??`.`;withParentLock(async()=>{let n=esm_default({baseDir:b,timeout:{block:15e3}}),r=t||`.`;await n.add(r),await n.commit(e,{"--allow-empty":null}),console.log(`[rollback] parent-git commit: ${e}`)}).catch(e=>{console.warn(`[rollback] parent-git commit failed (non-fatal):`,e)})}C&&h?.setFocus(o,{agentName:s,currentDoc:v,writeKind:`rollback-apply`,ts:Date.now()}),json(n,200,{ok:!0,restoredFrom:y,timestamp:i,...E?{summary:E}:{}})}catch(e){console.error(`[rollback]`,e),json(n,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Se(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getMetrics())}async function Ce(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}json(t,200,getParseHealth())}async function we(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=getActiveBranch(),r=d?.();json(t,200,{ok:!0,serverInstanceId:i,currentBranch:n,...r===void 0?{}:{currentDiskAckSVs:r}},{"Cache-Control":`no-store`})}async function Te(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=x?.()??null;if(!n){json(t,404,{error:`Principal not available`});return}json(t,200,n)}async function Ee(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=g?.getPresenceMap()??{},r=Date.now(),i={};for(let[e,t]of Object.entries(n))r-t.ts<2e4&&(i[e]=t);json(t,200,{presence:i})}async function De(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){json(t,403,{ok:!1,error:`loopback-required`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){json(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=resolve(r),i=n,a=!0;try{i=realpathSync(n)}catch(e){let r=e?.code;if(r===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:n}),a=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:n,err:e}),json(t,500,{ok:!1,error:`workspace-realpath-failed`,code:r??null});return}}json(t,200,{ok:!0,contentDir:i,pathSeparator:sep,symlinkResolved:a})}let Oe=1440*60*1e3;async function ke(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!c?.current){json(t,200,[]);return}let n=Date.now(),r=[],i=resolve(c.current.gitDir,`rescue`);if(existsSync(i))try{let e=readdirSync(i).filter(e=>isSupportedDocFile(e));for(let t of e){let e=resolve(i,t),a=statSync(e);if(n-a.mtimeMs>Oe){try{unlinkSync(e)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}r.push({docName:stripDocExtension(t),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){console.error(`[rescue] Failed to list flat-file rescue buffers:`,e)}try{let e=u?.()??`main`,t=await listRescueCheckpoints(c.current,e);for(let e of t)r.push({...e,source:`timeline`})}catch(e){console.error(`[rescue] Failed to list timeline-ref rescue checkpoints:`,e)}json(t,200,r)}async function Ae(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!c?.current){t.writeHead(404),t.end(`Not found`);return}let r=resolve(c.current.gitDir,`rescue`),i=resolve(r,`${n}${getDocExtension(n)}`);if(!i.startsWith(`${r}/`)){t.writeHead(400),t.end(`Invalid document name`);return}if(existsSync(i)){let e=statSync(i);if(Date.now()-e.mtimeMs>Oe)try{unlinkSync(i)}catch{}else{let e=readFileSync(i,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=u?.()??`main`,r=(await listRescueCheckpoints(c.current,e)).filter(e=>e.docName===n).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(r){let e=shadowGit(c.current),n=((await e.raw(`ls-tree`,`-r`,r.sha)).trim().split(`
123
+ `)[0]??``).split(/\s+/)[2];if(n){let r=await e.raw(`cat-file`,`-p`,n);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(r);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}t.writeHead(404),t.end(`Not found`)}async function je(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:d}=q(i),{path:f}=i;if(!f||typeof f!=`string`||f.length===0){json(t,400,{ok:!1,error:`path is required`});return}if(!isSupportedDocFile(f)){json(t,400,{ok:!1,error:`path must end with .md or .mdx`});return}if(f.includes(`..`)||f.startsWith(`/`)||f.includes(`\0`)||f.includes(`\\`)){json(t,400,{ok:!1,error:`path must not contain .. or start with /`});return}let h=resolve(r),g=resolve(h,f);if(!g.startsWith(`${h}/`)&&g!==h){json(t,400,{ok:!1,error:`path must not escape content directory`});return}let _=stripDocExtension(f);if(isSystemDoc(_)){json(t,400,{ok:!1,error:`'${_}' is a reserved document name`});return}mkdirSync(dirname(g),{recursive:!0});let v=``;try{writeFileSync(g,``,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){json(t,409,{ok:!1,error:`File already exists`});return}throw e}let y=stripDocExtension(f);recordContributor(y,o,s,c,void 0,Y({clientName:l,clientVersion:u,label:d}));let b=typeof a==`function`?a():null;b instanceof Map&&updateFileIndex({kind:`create`,path:g,docName:y,content:``},b),p&&(p.updateDocumentFromMarkdown(y,``),p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${y}:`,e)}),m?.(`backlinks`),m?.(`graph`)),m?.(`files`),json(t,200,{ok:!0,docName:y})}catch(e){console.error(`[create-page]`,e),json(t,500,{ok:!1,error:`Failed to create page`})}}async function Me(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||typeof n!=`string`||n.length===0){json(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(n)){json(t,400,{ok:!1,error:`Invalid docName`});return}let r=E(n);if(!r){json(t,400,{ok:!1,error:`Invalid docName`});return}if(!existsSync(r)){json(t,404,{ok:!1,error:`Page not found`});return}json(t,200,{ok:!0,docName:n,headings:extractHeadings(readFileSync(r,`utf-8`))})}catch(e){console.error(`[page-headings]`,e),json(t,500,{ok:!1,error:`Failed to read headings`})}}async function Ne(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=q(i),{docName:d,newDocName:f}=i;if(typeof d!=`string`||typeof f!=`string`){json(t,400,{ok:!1,error:`docName and newDocName are required`});return}if(!isValidRelativeContentPath(d)||!isValidRelativeContentPath(f)){json(t,400,{ok:!1,error:`Document names must be relative content paths`});return}if(isSystemDoc(d)||isSystemDoc(f)){json(t,400,{ok:!1,error:`Reserved document names cannot be renamed`});return}if(d===f){json(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}if(!p){json(t,503,{ok:!1,error:`Backlink index unavailable`});return}let m=i,h=typeof m.agentId==`string`&&m.agentId.length>0,g=normalizeSummary(m.summary);if(g.kind===`invalid`){json(t,400,{ok:!1,error:`summary must be a string`});return}let _=resolveContentEntryPath(r,`file`,d),v=resolveContentEntryPath(r,`file`,f);if(!existsSync(_)){json(t,404,{ok:!1,error:`Document does not exist`});return}if(existsSync(v)){json(t,409,{ok:!1,error:`Destination already exists`});return}let y=await G(d,f),b;if(h){let e=g.kind===`value`,t=e?g:normalizeSummary(`Renamed ${d} → ${f}`),n=X(t);b=e||!n.response?n.response:Z(n.response),recordContributor(f,a,o,s,formatRenameSubject(d,f),Y({clientName:c,clientVersion:l,label:u}),n.stored),incrementAgentWriteCalls(),Q(t,!e),P(f,`rename`)}json(t,200,{ok:!0,renamed:y.renamed,rewrittenDocs:y.rewrittenDocs,...b?{summary:b}:{}})}catch(e){console.error(`[rename]`,e),json(t,500,{ok:!1,error:R(e)})}}async function Pe(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}q(i);let{kind:o,fromPath:s,toPath:c}=i;if(o!==`file`&&o!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||typeof c!=`string`){json(t,400,{ok:!1,error:`fromPath and toPath are required`});return}if(!isValidRelativeContentPath(s)||!isValidRelativeContentPath(c)){json(t,400,{ok:!1,error:`Paths must be relative content paths`});return}if(s===c){json(t,200,{ok:!0,renamed:[]});return}let l=resolveContentEntryPath(r,o,s),u=resolveContentEntryPath(r,o,c);if(!existsSync(l)){json(t,404,{ok:!1,error:`${o} does not exist`});return}if(existsSync(u)){json(t,409,{ok:!1,error:`Destination already exists`});return}let d=statSync(l);if(o===`file`&&!d.isFile()||o===`folder`&&!d.isDirectory()){json(t,400,{ok:!1,error:`Source path is not a ${o}`});return}let f=listAffectedDocNames(a(),o,s),h=o===`file`?[{fromDocName:s,toDocName:c}]:f.map(e=>({fromDocName:e,toDocName:remapDocNameForRename(e,o,s,c)})),g=await z(h.map(({fromDocName:e})=>e)),_=async()=>{await renameTrackedPathInGit(b,l,u)||(mkdirSync(dirname(u),{recursive:!0}),renameSync(l,u)),B(h,g)};if(o===`file`)await withManagedRenameRecovery(r,createManagedRenameRecoveryJournal({sourceDocName:s,destinationDocName:c,snapshots:V(h.map(({fromDocName:e})=>e),g)}),_);else{await _();let e=a();for(let{fromDocName:t,toDocName:n}of h)updateFileIndex({kind:`rename`,oldPath:resolveContentEntryPath(r,`file`,t),newPath:resolveContentEntryPath(r,`file`,n),oldDocName:t,newDocName:n,content:g.get(t)??readFileSync(resolveContentEntryPath(r,`file`,n),`utf-8`)},e);if(p){for(let{fromDocName:e,toDocName:t}of h)p.renameDocument(e,t,g.get(e)??readFileSync(resolveContentEntryPath(r,`file`,t),`utf-8`));p.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist folder rename cache for ${s} -> ${c}:`,e)}),m?.(`backlinks`),m?.(`graph`)}m?.(`files`)}json(t,200,{ok:!0,renamed:h})}catch(e){console.error(`[rename-path]`,e),json(t,500,{ok:!1,error:`Failed to rename path`})}}async function Fe(e,t){if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await readBody(e)}catch{json(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){json(t,400,{ok:!1,error:`Body must be a JSON object`});return}q(i);let{kind:o,path:s}=i;if(o!==`file`&&o!==`folder`){json(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||!isValidRelativeContentPath(s)){json(t,400,{ok:!1,error:`path must be a relative content path`});return}let c=resolveContentEntryPath(r,o,s);if(!existsSync(c)){json(t,404,{ok:!1,error:`${o} does not exist`});return}let l=statSync(c);if(o===`file`&&!l.isFile()||o===`folder`&&!l.isDirectory()){json(t,400,{ok:!1,error:`Target path is not a ${o}`});return}let u=o===`file`?[s]:listAffectedDocNames(a(),o,s);await z(u),o===`file`?unlinkSync(c):rmSync(c,{recursive:!0,force:!1}),json(t,200,{ok:!0,deletedDocNames:u})}catch(e){console.error(`[delete-path]`,e),json(t,500,{ok:!1,error:`Failed to delete path`})}}async function Ie(e,t){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}try{let e=a(),n=[];for(let[t,i]of e){let e=t;try{e=extractPageTitle(readFileSync(resolve(r,`${t}${getDocExtension(t)}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,size:i.size,modified:i.modified})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),json(t,200,{ok:!0,pages:n})}catch(e){console.error(`[pages]`,e),json(t,500,{ok:!1,error:`Failed to list pages`})}}async function Le(e,n){if(e.method!==`GET`){json(n,405,{ok:!1,error:`Method not allowed`});return}try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){json(n,400,{ok:!1,error:`Missing docName parameter`});return}if(!isSafeDocName(r)){json(n,400,{ok:!1,error:`Invalid docName`});return}if(isSystemDoc(r)){json(n,400,{ok:!1,error:`'${r}' is a reserved document name`});return}json(n,200,{ok:!0,...await suggestLinks({hocuspocus:t,fileIndex:a(),docName:r})})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){json(n,404,{ok:!1,error:`Page not found`});return}console.error(`[suggest-links]`,e),json(n,500,{ok:!1,error:`Failed to suggest links`})}}async function Re(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n;try{n=await readUploadBody(e,MAX_UPLOAD_BYTES)}catch(e){let n=e instanceof Error?e.message:String(e);n===`Payload too large`?json(t,413,{ok:!1,error:`Payload too large`}):n===`No file received`?json(t,400,{ok:!1,error:`No file received`}):json(t,400,{ok:!1,error:`Failed to parse upload: ${n}`});return}let{filename:i,buffer:a,parentDocName:o}=n;if(q(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries())),!o){json(t,400,{ok:!1,error:`parentDocName is required`});return}if(o.includes(`\0`)||o.includes(`..`)||o.startsWith(`/`)){json(t,400,{ok:!1,error:`path-escape`});return}let s=resolve(r),c=resolve(s,dirname(o));if(!isWithinContentDir(c,s)){json(t,400,{ok:!1,error:`path-escape`});return}try{let e=realpathSync(c),n;try{n=realpathSync(s)}catch{n=s}if(!isWithinContentDir(e,n)){json(t,400,{ok:!1,error:`path-escape`});return}}catch(e){if(e.code!==`ENOENT`){json(t,400,{ok:!1,error:`path-escape`});return}}let l=await fileTypeFromBuffer(a),u=l?.mime,d=l?.ext;if(!u){let e=a.subarray(0,256).toString(`utf-8`).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(u=`image/svg+xml`,d=`svg`)}if(!u||!d||!ALLOWED_MIME_TYPES.has(u)){json(t,400,{ok:!1,error:`Unsupported file type${u?`: ${u}`:``}`});return}let f;f=!i||i===`upload`||GENERIC_PASTE_NAMES.test(i)?`pasted-${new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`)}.${d}`:sanitizeFilename(i),mkdirSync(c,{recursive:!0});try{let e=writeUploadAtomic(c,f,a),n=relative(r,resolve(c,e));console.log(`[upload] ok ${n} ${a.length}`),json(t,200,{ok:!0,src:e})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`[upload] error ${f} ${a.length} ${n}`),json(t,500,{ok:!1,error:`Failed to save file`})}}let ze=`/api/local-op/clone`,Be=`/api/local-op/open`,Ve=600*1e3,He=45e3;async function Ue(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.url!=`string`||!a.url){json(t,400,{ok:!1,error:`Missing or invalid url`});return}if(typeof a.dir!=`string`||!a.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=a.url,r=a.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isAllowedGitUrl(n)){json(t,400,{ok:!1,error:`URL protocol not allowed`});return}if(!isSafeLocalPath(r)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!w.tryAcquire(ze)){json(t,429,{ok:!1,error:`A clone operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=expandTilde(r),[a,...o]=y,s=[...o,`clone`,`--json`,n,i],c=!1,l=!1,u=null,d=``,f=spawn(a,s,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),p=setTimeout(()=>{c=!0,f.kill(`SIGTERM`)},Ve);f.stdout.on(`data`,e=>{d+=e.toString(`utf-8`);let n=d.split(`
124
+ `);d=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`complete`&&typeof n.dir==`string`){u=n.dir;continue}t.writableEnded||t.write(`${e}\n`)}});let m=[];f.stderr.on(`data`,e=>{m.push(e),log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/clone] stderr`)}),f.on(`close`,e=>{clearTimeout(p);let i=Buffer.concat(m).toString(`utf-8`).trim();if(l){w.release(ze);return}l=!0,(async()=>{try{if(c&&!t.writableEnded)t.write(`${JSON.stringify({type:`error`,message:`Clone timed out after 10 minutes`})}\n`);else if(e!==0&&!t.writableEnded){i&&log$2.warn({code:e,stderr:i,url:n,dir:r},`[local-op/clone] clone failed`);let a=i?` — ${i}`:``;t.write(`${JSON.stringify({type:`error`,message:`Clone process exited with code ${e}${a}`})}\n`)}else if(e===0&&u&&!t.writableEnded){let e=await We(u);t.writableEnded||(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port})}\n`):t.write(`${JSON.stringify({type:`error`,message:e.error})}\n`))}}finally{t.writableEnded||t.end(),w.release(ze)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),w.release(ze)})}async function We(e){let t=resolve(expandTilde(e)),n=resolve(t,`.open-knowledge`),r=readUiLock(n);if(r&&r.port>0)return{port:r.port};let i=readServerLock(n),[a,...o]=y,s=i&&i.port>0?`ui`:`start`,c=spawn(a,[...o,s],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`,OK_PARENT_PID:String(process.pid)}}),l=[];c.stderr?.on(`data`,e=>{l.push(e),log$2.warn({cwd:t,cliCmd:s,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let u=null;c.on(`exit`,e=>{u=e??-1}),c.unref();let d=Date.now()+45e3;for(;Date.now()<d;){await setTimeout$1(500);let e=readUiLock(n);if(e&&e.port>0)return{port:e.port};if(u!==null){let e=Buffer.concat(l).toString(`utf-8`).trim();return{error:`\`ok ${s}\` exited (code ${u})${e?` — ${e}`:``}`}}}let f=Buffer.concat(l).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${f?` — ${f}`:``}`}}async function Ge(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await readBody(e),i=JSON.parse(r.toString());if(typeof i.dir!=`string`||!i.dir){json(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=i.dir}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!isSafeLocalPath(n)){json(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!w.tryAcquire(Be)){json(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await We(n);`port`in e?json(t,200,{port:e.port}):json(t,504,{ok:!1,error:e.error})}finally{w.release(Be)}}let Ke=`/api/local-op/auth/login`,qe=`/api/local-op/auth/status`,Je=`/api/local-op/auth/repos`,Ye=`/api/local-op/auth/signout`,Xe=`/api/local-op/auth/pat`;async function Ze(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await readBody(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!w.tryAcquire(Ke)){json(t,429,{ok:!1,error:`An auth login operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=y,a=[...i,`auth`,`login`,`--json`,`--host`,n],o=!1,s=!1,c=``,l=spawn(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),u=setTimeout(()=>{l.kill(`SIGTERM`)},Ve),d=()=>{l.killed||l.kill(`SIGTERM`)};t.on(`close`,d),l.stdout.on(`data`,e=>{t.writableEnded||t.write(e),c+=e.toString(`utf-8`);let n=c.split(`
125
+ `);c=n.pop()??``;for(let e of n)if(e.trim())try{let t=JSON.parse(e);(t.type===`complete`||t.type===`error`)&&(s=!0)}catch{}}),l.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/login] stderr`)}),l.on(`close`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(e===0&&!s?t.write(`${JSON.stringify({type:`complete`,host:n,login:``})}\n`):e!==0&&t.write(`${JSON.stringify({type:`error`,message:`auth login exited with code ${e}`})}\n`)),t.end()),w.release(Ke)}),l.on(`error`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),w.release(Ke)})}async function Qe(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await readBody(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!w.tryAcquire(qe)){json(t,429,{ok:!1,error:`An auth status operation is already in progress`});return}try{let[e,...r]=y,i=[...r,`auth`,`status`,`--json`,`--host`,n],a=(await new Promise((t,n)=>{let r=spawn(e,i,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4),o=[];r.stdout.on(`data`,e=>o.push(e)),r.on(`close`,()=>{clearTimeout(a),t(Buffer.concat(o).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(a),n(e)})})).split(`
126
+ `).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}o===null?json(t,200,{authenticated:!1}):json(t,200,o)}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth status failed`})}finally{w.release(qe)}}async function $e(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await readBody(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!w.tryAcquire(Je)){json(t,429,{ok:!1,error:`An auth repos operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=y,a=[...i,`auth`,`repos`,`--json`,`--host`,n],o=!1,s=spawn(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),c=setTimeout(()=>{s.kill(`SIGTERM`)},Ve);s.stdout.on(`data`,e=>{t.writableEnded||t.write(e)}),s.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),s.on(`close`,e=>{clearTimeout(c),o||(o=!0,e!==0&&!t.writableEnded&&t.write(`${JSON.stringify({type:`error`,message:`auth repos exited with code ${e}`})}\n`),t.end()),w.release(Je)}),s.on(`error`,e=>{clearTimeout(c),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),w.release(Je)})}async function et(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await readBody(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!w.tryAcquire(Ye)){json(t,429,{ok:!1,error:`An auth signout operation is already in progress`});return}try{let[e,...r]=y,i=[...r,`auth`,`signout`,`--host`,n];await new Promise((t,n)=>{let r=spawn(e,i,{stdio:`ignore`,env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth signout failed`})}finally{w.release(Ye)}}async function tt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.pat!=`string`||!a.pat){json(t,400,{ok:!1,error:`Missing or invalid pat`});return}r=a.pat,typeof a.host==`string`&&a.host&&(n=a.host)}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!w.tryAcquire(Xe)){json(t,429,{ok:!1,error:`An auth pat operation is already in progress`});return}try{let[e,...i]=y,a=[...i,`auth`,`pat`,`--json`,`--host`,n],o=(await new Promise((t,n)=>{let i=spawn(e,a,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),o=setTimeout(()=>{i.kill(`SIGTERM`)},3e4);i.stdin.write(`${r}\n`),i.stdin.end();let s=[];i.stdout.on(`data`,e=>s.push(e)),i.on(`close`,e=>{clearTimeout(o),e===0?t(Buffer.concat(s).toString(`utf-8`)):n(Error(`auth pat exited with code ${e}`))}),i.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
127
+ `).map(e=>e.trim()).filter(Boolean),s=null;for(let e=o.length-1;e>=0;e--)try{s=JSON.parse(o[e]);break}catch{}s===null?json(t,200,{ok:!0}):json(t,200,s)}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`auth pat failed`})}finally{w.release(Xe)}}async function nt(e,t){if(checkLocalOpSecurity(e,t,json)){if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!b){json(t,400,{ok:!1,error:`No project directory configured`});return}try{json(t,200,{ok:!0,identity:await resolveGitIdentity(b)})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`identity resolution failed`})}}}let rt=`/api/local-op/auth/set-identity`;async function it(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await readBody(e),a=JSON.parse(i.toString());if(typeof a.name!=`string`||!a.name.trim()){json(t,400,{ok:!1,error:`Missing or invalid name`});return}if(typeof a.email!=`string`||!a.email.trim()){json(t,400,{ok:!1,error:`Missing or invalid email`});return}n=a.name.trim(),r=a.email.trim()}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!b){json(t,400,{ok:!1,error:`No project directory configured`});return}if(!w.tryAcquire(rt)){json(t,429,{ok:!1,error:`A set-identity operation is already in progress`});return}try{writeGitIdentity(b,n,r),v?.()?.refreshIdentity().catch(()=>{}),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:`set-identity failed`})}finally{w.release(rt)}}async function at(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,200,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1});return}json(t,200,n.getStatus())}async function ot(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r=`sync`;try{let t=await readBody(e);if(t.length>0){let e=JSON.parse(t.toString());(e.op===`push`||e.op===`pull`||e.op===`sync`)&&(r=e.op)}}catch{}json(t,202,{ok:!0,op:r}),n.trigger(r)}async function st(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let n=await readBody(e),i=JSON.parse(n.toString());if(typeof i.enabled!=`boolean`){json(t,400,{ok:!1,error:`enabled must be a boolean`});return}r=i.enabled}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}await n.setEnabled(r),json(t,200,{ok:!0,status:n.getStatus()})}async function ct(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();json(t,200,{conflicts:n?n.getConflicts():[]})}async function lt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let t=await readBody(e);r=JSON.parse(t.toString())}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}let{file:i,strategy:a,content:o}=r;if(!i||typeof i!=`string`){json(t,400,{ok:!1,error:`Missing required field: file`});return}if(a!==`mine`&&a!==`theirs`&&a!==`content`){json(t,400,{ok:!1,error:`Invalid strategy: must be 'mine', 'theirs', or 'content'`});return}try{await n.resolveConflict(i,a,o),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function ut(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}if(!b){json(t,503,{ok:!1,error:`Project repo not configured`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`file`);if(!n){json(t,400,{ok:!1,error:`Missing required query param: file`});return}if(n.includes(`..`)||n.startsWith(`/`)){json(t,400,{ok:!1,error:`Invalid file path`});return}let r=esm_default({baseDir:b,timeout:{block:15e3}});async function i(e){try{return await r.raw([`show`,`:${e}:${n}`])}catch{return``}}try{let[e,r,a]=await Promise.all([i(1),i(2),i(3)]);json(t,200,{ok:!0,file:n,base:e,ours:r,theirs:a})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function dt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`GET`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=new URL(e.url??`/`,`http://localhost`).searchParams.get(`rootDir`)??void 0;try{json(t,200,{ok:!0,plan:await planSeed({projectDir:r,rootDir:n})})}catch(e){if(e instanceof SeedPrerequisiteError){json(t,200,{ok:!1,error:{kind:`prerequisite-missing`,message:e.message}});return}if(e instanceof SeedRootDirError){json(t,200,{ok:!1,error:{kind:`invalid-root`,message:e.message}});return}json(t,500,{ok:!1,error:{kind:`internal`,message:e instanceof Error?e.message:String(e)}})}}async function ft(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await readBody(e),i=JSON.parse(r.toString());if(!i.plan||typeof i.plan!=`object`){json(t,400,{ok:!1,error:`Missing or invalid plan`});return}n=i.plan}catch{json(t,400,{ok:!1,error:`Invalid JSON body`});return}try{json(t,200,{ok:!0,result:await applySeed(n,{projectDir:r})})}catch(e){json(t,500,{ok:!1,error:{kind:`internal`,message:e instanceof Error?e.message:String(e)}})}}async function pt(e,t){if(checkLocalOpSecurity(e,t,json))return handleInstalledAgents(e,t,T.probeAll)}async function mt(e,t){if(!checkLocalOpSecurity(e,t,json))return;if(e.method!==`POST`){json(t,405,{ok:!1,error:`Method not allowed`});return}let n=v?.();if(!n){json(t,503,{ok:!1,error:`Sync engine not active`});return}try{await n.abortMerge(),json(t,200,{ok:!0})}catch(e){json(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}let ht={"/api/document":ne,"/api/documents":re,"/api/backlinks":ie,"/api/backlink-counts":ae,"/api/forward-links":oe,"/api/link-graph":se,"/api/dead-links":ue,"/api/orphans":ce,"/api/hubs":le,"/api/pages":Ie,"/api/suggest-links":Le,"/api/page-headings":Me,"/api/create-page":je,"/api/rename":Ne,"/api/rename-path":Pe,"/api/delete-path":Fe,"/api/upload-image":Re,"/api/agent-write":ee,"/api/agent-write-md":te,"/api/agent-patch":de,"/api/agent-undo":fe,"/api/agent-activity":pe,"/api/agent-burst-diff":me,"/api/save-version":_e,"/api/history":ve,"/api/diff":be,"/api/rollback":xe,"/api/metrics/reconciliation":Se,"/api/metrics/parse-health":Ce,"/api/metrics/agent-presence":Ee,"/api/server-info":we,"/api/principal":Te,"/api/rescue":ke,"/api/workspace":De,"/api/sync/status":at,"/api/sync/trigger":ot,"/api/sync/set-enabled":st,"/api/sync/conflicts":ct,"/api/sync/conflict-content":ut,"/api/sync/resolve-conflict":lt,"/api/sync/abort-merge":mt,"/api/local-op/clone":Ue,"/api/local-op/open":Ge,"/api/local-op/auth/login":Ze,"/api/local-op/auth/status":Qe,"/api/local-op/auth/repos":$e,"/api/local-op/auth/signout":et,"/api/local-op/auth/pat":tt,"/api/local-op/auth/identity":nt,"/api/local-op/auth/set-identity":it,"/api/installed-agents":pt,"/api/seed/plan":dt,"/api/seed/apply":ft};return s&&(ht[`/api/test-reset`]=he,ht[`/api/test-rescan-backlinks`]=ge),{priority:100,async onRequest({request:e,response:t}){let n=e.url?.split(`?`)[0];if(!n)return;if(n.startsWith(`/api/`)){let n=e.headers.origin;if(n!==void 0&&!isAllowedApiOrigin(n)){typeof t.setHeader==`function`&&t.setHeader(`Content-Type`,`application/json`),t.writeHead(403),t.end(JSON.stringify({ok:!1,error:`origin-not-allowed`}));return}if(typeof t.setHeader==`function`&&(n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(!n.startsWith(`/api/`))return;let r=propagation.extract(context.active(),e.headers),i=e.method??`GET`,a=n;n.startsWith(`/api/rescue/`)?a=`/api/rescue/:docName`:n.startsWith(`/api/history/`)&&(a=`/api/history/:sha`);let o=getTracer(),s=Date.now();await context.with(r,()=>o.startActiveSpan(`HTTP ${i} ${a}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:i,[ATTR_HTTP_ROUTE]:a,[ATTR_URL_PATH]:n,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async r=>{try{let i=ht[n];if(i)await i(e,t);else if(n.startsWith(`/api/rescue/`)){let r=decodeURIComponent(n.slice(12));r&&await Ae(e,t,r)}else if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&await ye(e,t,r)}let a=t.statusCode;r.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,a),a>=500&&r.setStatus({code:SpanStatusCode.ERROR,message:`status ${a}`})}catch(e){throw r.recordException(e),r.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),e}finally{r.end();let e=(Date.now()-s)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:i,[ATTR_HTTP_ROUTE]:a,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}const HocuspocusAuthTokenSchema=object({principalId:string().optional(),tabSessionId:string().optional(),expectedServerInstanceId:string().optional(),expectedBranch:string().optional()}).loose();var HocuspocusAuthRejection=class extends Error{reason;constructor(e,t){super(t),this.name=`HocuspocusAuthRejection`,this.reason=e}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=HocuspocusAuthTokenSchema.safeParse(t);return n.success?n.data:void 0}const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,n=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}const BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`]);function createContentFilter(e){let{projectDir:t,contentDir:n,includePatterns:r,excludePatterns:i}=e,a=(0,import_picomatch.default)(r,{dot:!0}),o=(0,import_ignore.default)();o.add(`.git`);let s=join(t,`.gitignore`),c=[];if(existsSync(s))try{let e=parseGitignorePatterns(readFileSync(s,`utf-8`));c.push(...e),o.add(e)}catch(e){console.warn(`[content-filter] Failed to read .gitignore at ${s}:`,e)}let l=relative(t,n),u=l.startsWith(`..`);if(i.length>0&&(l?o.add(i.map(e=>`${l}/${e}`)):o.add(i)),l){let e=join(n,`.gitignore`);if(existsSync(e))try{let t=parseGitignorePatterns(readFileSync(e,`utf-8`)).map(e=>e.startsWith(`!`)?`!${l}/${e.slice(1)}`:`${l}/${e}`);o.add(t)}catch(t){console.warn(`[content-filter] Failed to read .gitignore at ${e}:`,t)}}loadNestedGitignores(n,t,o);let d=[...c,...i].filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),f=new Map;function p(e){if(u)return!1;let t=l?`${l}/${e}`:e;return o.ignores(t)}return populateDirCount(n,``,a,p,f),{isExcluded(e){if(isSystemDoc(stripDocExtension(e))||!u&&p(e))return!0;if(a(e))return!1;let t=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(t)){let t=dirname(e),n=t===`.`?``:t;if((f.get(n)??0)>0)return!1}return!0},isDirExcluded(e){let t=e.split(`/`)[0];if(BUILTIN_SKIP_DIRS.has(t))return!0;if(u)return!1;let n=l?`${l}/${e}`:e;return o.ignores(n)||o.ignores(`${n}/`)},getWatcherIgnoreGlobs(){return d},incrementMdDir(e){let t=e===`.`?``:e;f.set(t,(f.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,n=f.get(t)??0;n<=1?f.delete(t):f.set(t,n-1)}}}function populateDirCount(e,t,n,r,i){let a;try{a=readdirSync(e,{withFileTypes:!0})}catch{return}for(let o of a){let a=t?`${t}/${o.name}`:o.name;if(o.isDirectory()){if(BUILTIN_SKIP_DIRS.has(o.name)||r(a)||r(`${a}/`))continue;populateDirCount(join(e,o.name),a,n,r,i)}else if(o.isFile()&&isSupportedDocFile(o.name)&&n(a)&&!r(a)){let e=t===``?``:t;i.set(e,(i.get(e)??0)+1)}}}function parseGitignorePatterns(e){return e.split(`
128
128
  `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function loadNestedGitignores(e,t,n){let r;try{r=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let i of r){if(!i.isDirectory()||BUILTIN_SKIP_DIRS.has(i.name))continue;let r=join(e,i.name),a=relative(t,r);if(a.startsWith(`..`)||n.ignores(a)||n.ignores(`${a}/`))continue;let o=join(r,`.gitignore`);if(existsSync(o))try{let e=parseGitignorePatterns(readFileSync(o,`utf-8`)).map(e=>e.startsWith(`!`)?`!${a}/${e.slice(1)}`:`${a}/${e}`);n.add(e)}catch(e){console.warn(`[content-filter] Failed to read nested .gitignore at ${o}:`,e)}loadNestedGitignores(r,t,n)}}const FILE_WATCHER_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function applyExternalChange(e,t,n){if(isSystemDoc(t))return;let r=e.documents.get(t);if(!r)return;let{frontmatter:i,body:a}=stripFrontmatter(n),o=mdManager.parseWithFallback(a),s=schema.nodeFromJSON(o),c=r.getXmlFragment(`default`);r.transact(()=>{updateYFragment(r,c,s,{mapping:new Map,isOMark:new Map}),r.getMap(`metadata`).set(`frontmatter`,i);let e=r.getText(`source`),t=e.toString();t!==n&&applyFastDiff(e,t,n)},FILE_WATCHER_ORIGIN),recordContributor(t,FILE_SYSTEM_WRITER.id,FILE_SYSTEM_WRITER.name,FILE_SYSTEM_WRITER.id,formatReconcileSubject(t)),setReconciledBase(t,n)}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function resolveGitDir(e){let t=resolve(e,`.git`);try{let n=statSync(t);if(n.isDirectory())return t;if(n.isFile()){let n=readFileSync(t,`utf-8`).trim().match(/^gitdir:\s*(.+)$/);if(n)return resolve(e,n[1])}}catch{}return null}function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let n=resolve(e,t.slice(5));try{return readFileSync(n,`utf-8`).trim()}catch{try{let n=readFileSync(resolve(e,`packed-refs`),`utf-8`),r=t.slice(5),i=n.split(`
129
129
  `).find(e=>e.endsWith(` ${r}`));if(i)return i.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function readBranchFromHead(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}async function startHeadWatcher(e,t,n){let r=resolveGitDir(e);if(!r)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let i=r,a=!1,o=null,s=null,c=null,l=null;async function u(e){if(f&&await f,!a)return;o&&=(clearTimeout(o),null),s&&=(clearTimeout(s),null);let t=readHeadSha(i),r=c!==t,u=readBranchFromHead(i),d;d=u?.startsWith(`detached-`)?`detached-head`:l===u?`within-branch`:`cross-branch`;let p=l;try{await n({headMoved:r,oldHead:c,newHead:t,timeout:e,batchKind:d,oldBranch:p,newBranch:u})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{a=!1,c=t,l=u}}function d(){o&&clearTimeout(o),o=setTimeout(()=>{o=null,u(!1)},QUIET_WINDOW_MS)}let f=null;async function p(e){if(!a){a=!0,c=readHeadSha(i);let n=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();f=n,await n,f=null,s=setTimeout(()=>{s=null,u(!0)},BATCH_TIMEOUT_MS)}d()}let m,h;try{h=await import(`@parcel/watcher`)}catch(e){throw Error(`@parcel/watcher unavailable for HEAD watching: ${e instanceof Error?e.message:e}`)}try{let e=await h.subscribe(i,(e,t)=>{if(e){console.error(`[head-watcher]`,e);return}for(let e of t){let t=e.path.split(`/`).pop()??``;if(WATCHED_FILES.has(t)){p(t);break}}});m=()=>e.unsubscribe()}catch(e){throw Error(`@parcel/watcher subscribe failed for HEAD watching: ${e instanceof Error?e.message:e}`)}return c=readHeadSha(i),l=readBranchFromHead(i),console.log(`[head-watcher] Watching ${i} for HEAD changes`),{unsubscribe:async()=>{a&&await u(!1),o&&clearTimeout(o),s&&clearTimeout(s),await m()},getLastKnownBranch:()=>l}}function isLocalOriginLike(e){return typeof e!=`object`||!e?!1:e.source===`local`}function serializeLiveDocument(e){let t=e.getXmlFragment(`default`),n=mdManager.serialize(yXmlFragmentToProseMirrorRootNode(t,schema).toJSON()),r=e.getMap(`metadata`).get(`frontmatter`);return prependFrontmatter(typeof r==`string`?r:``,n)}function createLiveDerivedIndexExtension(e){let{backlinkIndex:t,signalChannel:n,debounceMs:r=100}=e,i=new Map;function a(e){let t=i.get(e);t&&(clearTimeout(t),i.delete(e))}function o(e,o){a(e),i.set(e,setTimeout(()=>{i.delete(e);try{t.updateDocumentFromMarkdown(e,serializeLiveDocument(o)),n?.(`backlinks`),n?.(`graph`)}catch(t){console.error(`[live-derived-index] Failed to update backlinks for ${e}:`,t)}},r))}return{async onChange({documentName:e,document:t,transactionOrigin:n}){isSystemDoc(e)||isLocalOriginLike(n)&&n.context?.origin===`file-watcher`||o(e,t)},async beforeUnloadDocument({documentName:e}){a(e)},async onDestroy(){for(let e of i.values())clearTimeout(e);i.clear()}}}const PRINCIPAL_FILE=`principal.json`,GIT_TIMEOUT_MS=3e3;async function readGitConfig(e){try{let t=esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function loadPrincipal(e){let t=resolve(e,OK_DIR),n=resolve(t,PRINCIPAL_FILE),{name:r,email:i}=await readGitConfig(e);if(existsSync(n)){let e;try{e=JSON.parse(readFileSync(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${randomUUID()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?sanitizeGitIdentity(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?sanitizeGitIdentity(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return writeFileSync(n,JSON.stringify(s,null,2),`utf-8`),s}mkdirSync(t,{recursive:!0});let a=`principal-${randomUUID()}`,o=a.slice(10,18),s={id:a,display_name:r?sanitizeGitIdentity(r):`Local User`,display_email:i?sanitizeGitIdentity(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return writeFileSync(n,JSON.stringify(s,null,2),`utf-8`),s}const OBSERVER_SYNC_ORIGIN={source:`local`,skipStoreHooks:!0,context:{origin:`observer-sync`}},isPairedWriteOrigin=e=>typeof e!=`object`||!e?!1:e.context?.paired===!0;function shouldRethrowBridgeMergeLoss(e=process.env){return e.NODE_ENV===`test`||e.OK_RETHROW_BRIDGE_LOSS===`1`}function setupServerObservers(e){let{doc:t,xmlFragment:n,ytext:r,mdManager:i,schema:a}=e,o=(t,n)=>{let r=process.env.OK_TELEMETRY_VERBOSE===`1`;console.warn(JSON.stringify({...t.toLog({verbose:r}),docName:e.docName??null,timestamp:new Date().toISOString()})),incrementBridgeMergeContentLoss();let i=e.shadow?.();if(!i||!e.docName)return;let a=e.getBranch?.()??`main`,o=e.contentRoot??``;queueMicrotask(()=>{saveInMemoryCheckpoint(i,o,{kind:`bridge-merge-loss`,docName:e.docName,contents:n,label:`Before concurrent merge @ ${new Date().toISOString()}`,branch:a,metadata:{lostSubstrings:t.info.lostSubstrings}}).then(t=>{incrementBridgeMergeCheckpointCreated(),console.warn(JSON.stringify({event:`bridge-merge-checkpoint-created`,docName:e.docName,sha:t,kind:`bridge-merge-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{let t=e instanceof Error?e:Error(String(e));console.warn(`[Server Observer A] Silent checkpoint write failed:`,{name:t.name,message:t.message,stack:t.stack?.split(`
130
130
  `).slice(0,4).join(`
@@ -134,9 +134,9 @@ What to log:
134
134
  `):[]){let t=e.trim();if(!t)continue;let n=join(this.projectDir,t),r=relative(this.contentDir,n);!r.startsWith(`..`)&&!this.contentFilter.isExcluded(r)&&a.add(t)}}catch{}if(t.length>0){let n=100;for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...r])}}let o=new Set(t.map(e=>e.projectRelPath)),s=[...a].filter(e=>!o.has(e));s.length>0&&await e.git.raw([`rm`,`--cached`,`--`,...s]);let c=(await e.git.raw([`write-tree`])).trim(),l=``;try{l=(await e.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(l&&l===c){let n=null;try{n=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(n===i){log.info({contentFileCount:t.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.transitionTo(`idle`);return}log.info({headSha:i,upstreamSha:n},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=i;return}let u=[];try{let n=(await e.git.raw([`diff-tree`,`--name-only`,`-r`,i,c])).trim();if(n){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of n.split(`
135
135
  `)){let n=t.trim();if(!n)continue;let r=e.get(n)??relative(this.contentDir,join(this.projectDir,n));r&&!r.startsWith(`..`)&&u.push(r)}}}catch{u=t.map(e=>e.contentRelPath)}let d=this.buildCommitMessage(u),f=await resolveGitIdentity(this.projectDir),p=f===null;this.identityUnresolved!==p&&(this.identityUnresolved=p,this.cc1Broadcaster?.signal(`sync-status`));let m=f?.name??`Open Knowledge`,h=f?.email??`sync@open-knowledge.local`;e.git.env({GIT_AUTHOR_NAME:m,GIT_AUTHOR_EMAIL:h,GIT_COMMITTER_NAME:m,GIT_COMMITTER_EMAIL:h});let g=(await e.git.raw([`commit-tree`,c,`-p`,i,`-m`,d])).trim();if(!g||!SHA_HEX_40.test(g)){log.warn({raw:g},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}if(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,g,i]),t.length>0){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),n=100;for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...r])}catch{}}}let _=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),_=!0}catch{}_?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=g}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.error=void 0,this.schedulePull(0)))}catch(t){let n=classifyGitError(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){log.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});this.setBatchInProgress?.(!0);try{if(await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e),!await this.pauseIfNonContentDirty(e)){this.setBatchInProgress?.(!1);return}await e.git.merge([`origin/${this.currentBranch}`])}catch(e){let t=classifyGitError(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}log.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n)}finally{try{unlinkSync(n)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync();if(n.length===0)return null;let r=join(tmpdir(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),i=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:r});try{await i.git.raw([`read-tree`,t]);let r=100;for(let e=0;e<n.length;e+=100){let t=n.slice(e,e+100).map(e=>e.projectRelPath);await i.git.raw([`add`,`--`,...t])}let a=(await i.git.raw([`write-tree`])).trim();if(a===(await i.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let o=await resolveGitIdentity(this.projectDir),s=o?.name??`Open Knowledge`,c=o?.email??`sync@open-knowledge.local`;i.git.env({GIT_AUTHOR_NAME:s,GIT_AUTHOR_EMAIL:c,GIT_COMMITTER_NAME:s,GIT_COMMITTER_EMAIL:c});let l=(await i.git.raw([`commit-tree`,a,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();if(!l||!SHA_HEX_40.test(l))return log.warn({raw:l},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null;await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,l,t]);for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...r])}catch{}}return l}finally{try{unlinkSync(r)}catch{}}}async pauseIfNonContentDirty(e){let t=``;try{t=(await e.git.raw([`diff-index`,`--name-only`,`HEAD`])).trim()}catch{return!0}if(!t)return!0;let n=t.split(`
136
136
  `).map(e=>e.trim()).filter(Boolean);return n.length===0?!0:(this.error=`External changes pending: ${n.slice(0,3).join(`, `)}${n.length>3?`, +${n.length-3} more`:``}`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log.warn({files:n},`[sync] paused — non-content tracked files dirty`),!1)}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=join(n,i.name);if(i.isDirectory()){if(i.name===`node_modules`||i.name===`.git`||i.name.startsWith(`.`)&&i.name!==`.open-knowledge`)continue;t(r)}else if(i.isFile()){let t=relative(this.contentDir,r);if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=relative(this.projectDir,r);e.push({contentRelPath:t,projectRelPath:n})}}}};return existsSync(this.contentDir)&&t(this.contentDir),e}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=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),t=[];try{let n=(await e.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();t=n?n.split(`
137
- `).map(e=>e.trim()).filter(Boolean):[]}catch(t){log.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){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.error=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=join(this.projectDir,e),i=relative(this.contentDir,t);!i.startsWith(`..`)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log.warn({err:e,file:t},`[sync] auto-resolve failed — escalating to content conflict`),n.push(t)}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),log.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async abortMerge(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),log.info({},`[sync] merge aborted`)}catch(e){log.warn({err:e},`[sync] git merge --abort failed — conflicts.json still cleared`)}this.conflictStore.clear(),this.conflictCount=0,this.transitionTo(`idle`),this.scheduleSaveState()}handleError(e){this.error=e.message,log.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,log.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:this.pausedReason,pausedSinceUtc:this.pausedReason?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file),syncEnabled:this.syncEnabled};writeFileSync(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){log.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason,t.syncEnabled!==void 0&&(this.syncEnabled=t.syncEnabled);let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log.warn({err:e},`[sync] failed to load sync state`)}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,enableTestRoutes:l=!1,shadowRepo:u,contentRoot:d,includePatterns:f=[`**/*.md`,`**/*.mdx`],excludePatterns:p=[],destroyTimeoutMs:m=1e4,localOpCliArgs:h,skipStateManifestCheck:g=!1}=e,_=getLogger(`server`);initTelemetry();let v=randomUUID(),y=resolve(t,`.open-knowledge`);if(acquireServerLock(y,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,...e.parentPid!==void 0&&{parentPid:e.parentPid},capabilities:[`http`,`ws`]}),!g)try{assertCompatibleStateManifest({lockDir:y,shadowRepoDir:resolveShadowDir(n)})}catch(e){throw releaseServerLock(y),e}let b,x,S,C,w,T,E=null,D=null,O=null,k=null;function A(e){E?.signal(e)}try{b=createContentFilter({projectDir:n,contentDir:t,includePatterns:f,excludePatterns:p}),x=new BacklinkIndex({projectDir:n,contentDir:t,contentFilter:b}),S={current:u},C=createPersistenceExtension({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:S,contentRoot:d,backlinkIndex:x,getCurrentBranch:()=>V?.getLastKnownBranch()??null,getPrincipal:()=>k,onAgentCommit:()=>E?.signal(`session-activity`),onDiskFlush:(e,t)=>E?.emitDiskAck(e,t)}),w=new Hocuspocus({quiet:r,debounce:i,maxDebounce:a,extensions:[C.extension]}),E=new CC1Broadcaster(w),D=new AgentFocusBroadcaster(w),O=new AgentPresenceBroadcaster(w),T=new AgentSessionManager(w);let m=createLiveDerivedIndexExtension({backlinkIndex:x,signalChannel:A});w.configuration.extensions.push(m),w.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=parseHocuspocusAuthToken(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==v)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${v}`);let i=n?.expectedBranch,a=getActiveBranch();if(typeof i==`string`&&i.length>0&&i!==a)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(k&&n.principalId===k.id?o.principalId=k.id:k?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:k.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),w.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let g=createApiExtension({hocuspocus:w,sessionManager:T,contentDir:t,serverInstanceId:v,getFileIndex:()=>B?B.getFileIndex():new Map,getAliasMap:()=>B?B.getAliasMap():new Map,enableTestRoutes:l,shadowRef:S,flushGitCommit:()=>C.flushPendingGitCommit(),getCurrentBranch:()=>V?.getLastKnownBranch()??null,getDiskAckSVs:()=>E?.getLatestDiskAckSVsAsBase64()??{},contentRoot:d,backlinkIndex:x,signalChannel:A,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>H,localOpCliArgs:h,projectDir:n,getPrincipal:()=>k});w.configuration.extensions.push(g),w.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:S,contentRoot:d,getCurrentBranch:()=>V?.getLastKnownBranch()??null}))}catch(e){throw releaseServerLock(y),e}let j=null;function M(e,t){let n=resolve(e,`rescue`),r=resolve(n,`${t}${getDocExtension(t)}`);return r.startsWith(`${n}/`)?r:null}function N(e){let t=w.documents.get(e);if(!t)return null;let n=yXmlFragmentToProseMirrorRootNode(t.getXmlFragment(`default`),schema).toJSON(),r=mdManager.serialize(n),i=t.getMap(`metadata`).get(`frontmatter`);return prependFrontmatter(typeof i==`string`?i:``,r)}let P=(e,t)=>applyExternalChange(w,e,t);function F(e){return e.kind===`rename`?e.newDocName:e.docName}async function I(e){try{switch(e.kind){case`create`:_.info({docName:e.docName},`[reconcile] create: ${e.docName}`),x.updateDocumentFromMarkdown(e.docName,e.content),x.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),A(`files`),A(`backlinks`),A(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=w.documents.get(t);if(!r){x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),A(`backlinks`),A(`graph`);return}let i=getReconciledBase(t)??``,a=N(t)??i,o=reconcile({docName:t,base:i,ours:a,theirs:n}),s=contentHash(i).slice(0,6),c=contentHash(a).slice(0,6),l=contentHash(n).slice(0,6);switch(_.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),A(`backlinks`),A(`graph`);break;case`clean`:try{P(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),A(`backlinks`),A(`graph`)}catch(e){_.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`merged`:try{P(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),A(`backlinks`),A(`graph`)}catch(e){_.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`conflicts`:try{P(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),incrementConflict(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),A(`backlinks`),A(`graph`)}catch(e){_.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`refused`:{incrementConflict();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=w.documents.get(t);if(!n){x.deleteDocument(t),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),A(`files`),A(`backlinks`),A(`graph`);return}let r=getReconciledBase(t)??``,i=N(t)??``,a=i!==r;if(a&&S.current){let e=S.current,n=V?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,d??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),_.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{_.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),x.deleteDocument(t),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),_.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),w.closeConnections(t),await w.unloadDocument(n),A(`files`),A(`backlinks`),A(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=w.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(n,r),x.renameDocument(t,n,r),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist rename for ${t} -> ${n}:`,e)}),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}_.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),A(`files`),A(`backlinks`),A(`graph`);break}case`conflict`:{let{docName:t}=e,n=w.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),_.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}}}catch(t){_.error({err:t,kind:e.kind,docName:F(e)},`[reconcile] failed to handle ${e.kind} for ${F(e)}`)}}let L=[];async function R(e){if(isBatchInProgress()){L.push(e);return}await I(e)}async function z(){let e=L.splice(0,L.length);for(let t of e)await I(t)}let B=null,V=null,H=null,U=null;async function W(e){if(w.documents.size===0)return;let t=!1,n=new Promise(e=>{w.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(w.documents.keys());w.closeConnections(),w.flushPendingStores();let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(w.documents.keys()),i=[],o=[];if(S.current){for(let e of n)if(!isSystemDoc(e))try{let t=N(e);if(t===null){_.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=M(S.current.gitDir,e);if(!n){_.warn({docName:e,gitDir:S.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,t,`utf-8`),incrementRescueBuffer(),i.push(e),_.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),_.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else _.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function G(){return U||(U=(async()=>{let e=Date.now(),t=[],r,i=await Promise.race([J.then(()=>`completed`,e=>(_.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&_.warn({},`[server] init did not complete within 5s during shutdown`);let a=w.documents.size;try{try{try{V&&=(await V.unsubscribe(),null),B&&=(await B.unsubscribe(),null)}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{E?.destroy(),O?.destroy(),j&&=(await j.disconnect(),null)}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await T.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await W(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await C.flushPendingGitCommit(),await C.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)}),_.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{H&&=(await H.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(S.current){try{let e=(await esm_default({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(S.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(S.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?_.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):_.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(y)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),U)}let K=[];async function q(){try{k=await loadPrincipal(t),_.info({principalId:k.id},`[server] principal loaded`)}catch(e){_.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!S.current)try{S.current=await initShadowRepo(n),_.info({gitDir:S.current.gitDir},`[server] history repo initialized at ${S.current.gitDir}`)}catch(e){_.error({err:e},`[server] history repo init failed`),K.push(`shadow-repo`)}if(S.current)try{await shadowGit(S.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`)){_.warn({},`[server] history repo appears corrupted — reinitializing`);try{S.current=await initShadowRepo(n)}catch(e){_.error({err:e},`[server] history repo reinit failed`),S.current=void 0,K.includes(`shadow-repo`)||K.push(`shadow-repo`)}}else _.error({err:e},`[server] history repo check failed (transient?)`)}if(S.current)try{let e=resolve(S.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await esm_default({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await esm_default({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}_.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await commitUpstreamImport(S.current,d??``,t,r,e),incrementUpstreamImport()}catch(e){_.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else _.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{writeFileSync(e,r,`utf-8`)}catch(e){_.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){_.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t);e.recovered&&e.journal&&_.warn({sourceDocName:e.journal.sourceDocName,destinationDocName:e.journal.destinationDocName,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${e.journal.sourceDocName} -> ${e.journal.destinationDocName}`)}catch(e){_.error({err:e},`[server] managed rename recovery failed`),K.push(`managed-rename-recovery`)}try{j=await w.openDirectConnection(SYSTEM_DOC_NAME),E?.emitServerInfo(v,getActiveBranch())}catch(e){_.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),K.push(`cc1-push`)}let e=resolveGitDir(n),r=e?readBranchFromHead(e)??`main`:`main`;switchReconciledBaseScope(r),x.switchBranch(r);try{B=await startWatcher(t,R,b),x.rebuildFromDisk(getActiveBranch()),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${getActiveBranch()}:`,e)})}catch(e){_.error({err:e},`[server] disk bridge watcher failed to start`),K.push(`file-watcher`)}try{V=await startHeadWatcher(n,async({trigger:e})=>{if(_.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),w.flushPendingStores(),await C.flushPendingGitCommit(),setBatchInProgress(!0),S.current){let e=getActiveBranch(),t=resolveGitDir(n),r=t?readBranchFromHead(t)??e:e,i=[];for(let[e,t]of w.documents){if(isSystemDoc(e))continue;let n=null;if(t.transact(()=>{n=N(e)},PARK_SNAPSHOT_ORIGIN),n===null)continue;let r=getReconciledBase(e)??n;i.push({docName:e,markdown:n,diskSnapshot:r})}if(i.length>0)try{let t=await parkBranch(S.current,e,SERVICE_WRITER.id,i,r);t&&(incrementPark(),_.info({count:i.length,branch:e,sha:t.slice(0,8)},`[history] parked ${i.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){_.error({err:e},`[shadow] park failed`)}}},async e=>{let n=L.length,r=e.newBranch??`main`;if(setBatchInProgress(!1),_.info({kind:e.batchKind,headMoved:e.headMoved,docs:n,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${n}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)await z();else{incrementBranchSwitch(),L.splice(0,L.length),switchReconciledBaseScope(r),x.switchBranch(r);for(let[e,n]of w.documents)if(!isSystemDoc(e))try{let i=safeContentPath(e,t);if(!existsSync(i)){let t=getReconciledBase(e)??``,i=N(e)??``;if(i!==t&&S.current){let t=S.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,d??``,{kind:`external-change-rescue`,docName:e,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:r,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),_.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{_.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),_.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=readFileSync(i,`utf-8`);P(e,a),setReconciledBase(e,a),_.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){_.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(_.info({branch:r,docCount:w.documents.size},`[branch-switch] loaded branch ${r} (${w.documents.size} docs)`),x.rebuildFromDisk(r),x.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),S.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of w.documents)if(!isSystemDoc(t))try{let n=await readParkedState(S.current,r,SERVICE_WRITER.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let i=getReconciledBase(t);if(!i)continue;let a=reconcile({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:i});switch(a.kind){case`merged`:case`clean`:P(t,a.newContent),setReconciledBase(t,a.newContent),e++;break;case`conflicts`:P(t,a.newContent),setReconciledBase(t,a.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){_.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&_.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&S.current)try{let t=shadowGit(S.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(n){for(let e of n.split(`
138
- `))e&&await t.raw(`update-ref`,`-d`,e);_.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){_.error({err:e},`[branch-switch] detached cleanup failed`)}E?.emitBranchSwitched(r)}if(e.headMoved&&e.newHead&&S.current&&n>0){let t=d??`.`;try{let n=await commitUpstreamImport(S.current,t,e.oldHead,e.newHead,r);incrementUpstreamImport(),_.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){_.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){_.error({err:e},`[server] HEAD watcher failed to start`),K.push(`head-watcher`)}let i=h?.[0]??`open-knowledge`,a=[`-c`,`credential.helper=!${h&&h.length>1?h.join(` `):i} auth git-credential`];try{H=new SyncEngine({projectDir:n,contentDir:t,contentFilter:b,contentRoot:d,credentialArgs:a,cc1Broadcaster:E,setBatchInProgress,onStateChange:e=>{_.info({state:e},`[sync] state → ${e}`)}}),await H.start()}catch(e){_.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),H=null}}let J=q();return{hocuspocus:w,sessionManager:T,cc1Broadcaster:E,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,contentFilter:b,serverInstanceId:v,destroy:G,ready:J,degraded:K,lockDir:y,get syncEngine(){return H}}}const DEFAULT_PARENT_DEATH_POLL_MS=5e3,DEFAULT_IDLE_THRESHOLD_MS=1800*1e3;async function bootServer(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??getLogger(`boot`),a=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,o=process.env.OK_PARENT_PID,s=typeof o==`string`&&/^[0-9]+$/.test(o)?Number.parseInt(o,10):void 0,c=e.lockKind??a??`interactive`,l=e.parentPid??s;initTelemetry();let{createServer:u}=await import(`node:http`),{WebSocketServer:d}=await import(`./wrapper-BTT6637Z.mjs`),{updateServerLockPort:f}=await import(`./server-lock-n3Y5JWNv-DXpg9_eU.mjs`).then(e=>e.a),p=!1;!t&&e.ensureProjectGitFn&&(p=!!(await e.ensureProjectGitFn()).didInit);let m=!1;if(!t&&e.autoInitFn)try{m=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let h=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,includePatterns:e.includePatterns,excludePatterns:e.excludePatterns,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:c,parentPid:l,skipStateManifestCheck:e.skipStateManifestCheck}),{hocuspocus:g,destroy:_,ready:v,degraded:y,lockDir:b,agentPresenceBroadcaster:x}=h,S=u((e,t)=>{let n=e.url?.split(`?`)[0];if(n?.startsWith(`/api/`)){g.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||(t.statusCode=404,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({error:`API route not found`,path:n})))}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?(t.writeHead(500),t.end(`Internal server error`)):t.writableEnded||t.end()});return}t.writeHead(404,{"Content-Type":`application/json`}),t.end(JSON.stringify({error:"Not found. The React UI is served by `ok ui` (default port 3000).",path:n??`/`}))}),C=new d({noServer:!0});C.on(`error`,e=>{i.error({err:e},`WebSocketServer error`)});let w=e.keepaliveGraceMs??1e4,T=new Map,E=new Set,D=!1;S.on(`upgrade`,(e,t,n)=>{if(e.url?.startsWith(`/collab/keepalive`)){t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`MCP keepalive socket error`)}),C.handleUpgrade(e,t,n,t=>{let n=parseKeepaliveConnectionId(e.url);if(n){let e=T.get(n);e!==void 0&&(clearTimeout(e),T.delete(n),i.info({connectionId:n},`[keepalive] reconnect during grace — timer cancelled`))}let r=setInterval(()=>{try{t.ping()}catch{}},3e4);r.unref?.();let a=n?setInterval(()=>{x?.bumpPresenceTs(toBroadcasterKey(n))},3e3):null;a?.unref?.(),t.on(`close`,()=>{if(clearInterval(r),a!==null&&clearInterval(a),!n)return;let e=setTimeout(()=>{if(T.delete(n),D)return;let e=(async()=>{i.info({connectionId:n},`[keepalive] grace expired — cleaning up sessions`);try{await h.sessionManager.closeAllForAgent(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] closeAllForAgent failed`)}try{h.agentFocusBroadcaster?.clearFocus(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearFocus failed`)}try{x?.clearPresence(toBroadcasterKey(n))}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearPresence failed`)}})();E.add(e),e.finally(()=>E.delete(e))},w);e.unref?.(),T.set(n,e),i.info({connectionId:n,graceMs:w},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}e.url?.startsWith(`/collab`)&&(t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`Upgrade socket error`)}),C.handleUpgrade(e,t,n,t=>{let n=g.handleConnection(t,e);t.on(`message`,e=>{n.handleMessage((e instanceof ArrayBuffer,new Uint8Array(e)))}),t.on(`close`,(e,t)=>{n.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`WebSocket error`),t.terminate()})}))});let O=null;r!==null&&(O=attachIdleShutdown({httpServer:S,thresholdMs:r??DEFAULT_IDLE_THRESHOLD_MS,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await _()})})),await new Promise((t,n)=>{let r=e=>n(e);S.once(`error`,r),S.listen(e.port,e.host,()=>{S.removeListener(`error`,r),t()})});let k=S.address(),A=typeof k==`object`&&k?k.port:e.port??0;if(f(b,A),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:b,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let j=!1,M=null,N=async()=>{if(!j){j=!0,D=!0,M!==null&&(clearInterval(M),M=null),O?.detach();for(let e of T.values())clearTimeout(e);T.clear(),E.size>0&&await Promise.allSettled([...E]),await new Promise(e=>{S.close(()=>e())}),await _(),await shutdownTelemetry()}};if(l!==void 0){let t=e.parentDeathPollMs??DEFAULT_PARENT_DEATH_POLL_MS,n=e.parentAliveCheck??isProcessAlive;M=setInterval(()=>{j||n(l)||(i.warn({parentPid:l,lockKind:c},`[boot] parent process gone — initiating graceful shutdown`),N().catch(e=>{i.error({err:e,parentPid:l},`[boot] parent-death shutdown failed`)}))},t),M.unref?.()}return{httpServer:S,destroy:N,lockDir:b,contentDir:e.contentDir,port:A,ready:v,degraded:y,didAutoInit:m,didGitInit:p,serverInstance:h}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_ZIP_BYTES=102400;function resolveBundledSkillDir(){let e=[`../assets/skills/open-knowledge`,`./assets/skills/open-knowledge`],t=[];for(let n of e){let e=fileURLToPath(new URL(n,import.meta.url));if(existsSync(e))return e;t.push(e)}throw Error(`Bundled skill asset directory not found. Tried: ${t.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function readCliVersion(){for(let e of[`../../cli/package.json`,`../package.json`]){let t=fileURLToPath(new URL(e,import.meta.url));if(!existsSync(t))continue;let n=await readFile(t,`utf-8`),r=JSON.parse(n);if(r.name===`@inkeep/open-knowledge`&&typeof r.version==`string`)return r.version}throw Error(`Could not resolve @inkeep/open-knowledge CLI version — no package.json with matching name found in candidate paths.`)}async function*walkFiles(e,t=e){let n=await readdir(e,{withFileTypes:!0});for(let r of n){let n=join(e,r.name);r.isDirectory()?yield*walkFiles(n,t):r.isFile()&&(yield relative(t,n))}}async function zipDirectory(e,t){let n=e.split(`/`).pop()??`open-knowledge`,r=new import_yazl.ZipFile;r.addEmptyDirectory(`${n}/`);let i=[];for await(let t of walkFiles(e))i.push(t);i.sort();for(let t of i){let i=join(e,t),a=`${n}/${t}`;r.addFile(i,a)}r.end(),await new Promise((e,n)=>{let i=createWriteStream(t);r.outputStream.pipe(i),i.on(`close`,()=>e()),i.on(`error`,n),r.outputStream.on(`error`,n)})}async function sha256OfFile(e){return new Promise((t,n)=>{let r=createHash(`sha256`),i=createReadStream(e);i.on(`data`,e=>r.update(e)),i.on(`end`,()=>t(r.digest(`hex`))),i.on(`error`,n)})}function extractMetadataVersion(e){let t=e.indexOf(`
137
+ `).map(e=>e.trim()).filter(Boolean):[]}catch(t){log.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){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.error=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=join(this.projectDir,e),i=relative(this.contentDir,t);!i.startsWith(`..`)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log.warn({err:e,file:t},`[sync] auto-resolve failed — escalating to content conflict`),n.push(t)}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),log.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async abortMerge(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),log.info({},`[sync] merge aborted`)}catch(e){log.warn({err:e},`[sync] git merge --abort failed — conflicts.json still cleared`)}this.conflictStore.clear(),this.conflictCount=0,this.transitionTo(`idle`),this.scheduleSaveState()}handleError(e){this.error=e.message,log.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,log.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:this.pausedReason,pausedSinceUtc:this.pausedReason?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file),syncEnabled:this.syncEnabled};writeFileSync(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){log.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason,t.syncEnabled!==void 0&&(this.syncEnabled=t.syncEnabled);let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log.warn({err:e},`[sync] failed to load sync state`)}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,enableTestRoutes:l=!1,shadowRepo:u,contentRoot:d,includePatterns:f=[`**/*.md`,`**/*.mdx`],excludePatterns:p=[],destroyTimeoutMs:m=1e4,localOpCliArgs:h,skipStateManifestCheck:g=!1}=e,_=getLogger(`server`);initTelemetry();let v=randomUUID(),y=resolve(t,`.open-knowledge`);if(acquireServerLock(y,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,...e.parentPid!==void 0&&{parentPid:e.parentPid},capabilities:[`http`,`ws`]}),!g)try{assertCompatibleStateManifest({lockDir:y,shadowRepoDir:resolveShadowDir(n)})}catch(e){throw releaseServerLock(y),e}let b,x,S,C,w,T,E=null,D=null,O=null,k=null,A=new Set,j=!1,M;function N(e){E?.signal(e)}try{b=createContentFilter({projectDir:n,contentDir:t,includePatterns:f,excludePatterns:p}),x=new BacklinkIndex({projectDir:n,contentDir:t,contentFilter:b}),S={current:u},C=createPersistenceExtension({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:S,contentRoot:d,backlinkIndex:x,getCurrentBranch:()=>W?.getLastKnownBranch()??null,getPrincipal:()=>k,onAgentCommit:()=>E?.signal(`session-activity`),onDiskFlush:(e,t)=>E?.emitDiskAck(e,t)}),w=new Hocuspocus({quiet:r,debounce:i,maxDebounce:a,extensions:[C.extension]});let m=w.shouldUnloadDocument.bind(w);w.shouldUnloadDocument=e=>(j||A.has(e))&&m(e),M=async e=>{A.add(e);try{await w.unloadDocument(e)}finally{A.delete(e)}},E=new CC1Broadcaster(w),D=new AgentFocusBroadcaster(w),O=new AgentPresenceBroadcaster(w),T=new AgentSessionManager(w);let g=createLiveDerivedIndexExtension({backlinkIndex:x,signalChannel:N});w.configuration.extensions.push(g),w.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=parseHocuspocusAuthToken(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==v)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${v}`);let i=n?.expectedBranch,a=getActiveBranch();if(typeof i==`string`&&i.length>0&&i!==a)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(k&&n.principalId===k.id?o.principalId=k.id:k?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:k.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),w.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let _=createApiExtension({hocuspocus:w,sessionManager:T,contentDir:t,serverInstanceId:v,getFileIndex:()=>U?U.getFileIndex():new Map,getAliasMap:()=>U?U.getAliasMap():new Map,enableTestRoutes:l,shadowRef:S,flushGitCommit:()=>C.flushPendingGitCommit(),getCurrentBranch:()=>W?.getLastKnownBranch()??null,getDiskAckSVs:()=>E?.getLatestDiskAckSVsAsBase64()??{},contentRoot:d,backlinkIndex:x,signalChannel:N,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>G,localOpCliArgs:h,projectDir:n,getPrincipal:()=>k,forceUnloadDocument:M});w.configuration.extensions.push(_),w.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:S,contentRoot:d,getCurrentBranch:()=>W?.getLastKnownBranch()??null}))}catch(e){throw releaseServerLock(y),e}let P=null;function F(e,t){let n=resolve(e,`rescue`),r=resolve(n,`${t}${getDocExtension(t)}`);return r.startsWith(`${n}/`)?r:null}function I(e){let t=w.documents.get(e);if(!t)return null;let n=yXmlFragmentToProseMirrorRootNode(t.getXmlFragment(`default`),schema).toJSON(),r=mdManager.serialize(n),i=t.getMap(`metadata`).get(`frontmatter`);return prependFrontmatter(typeof i==`string`?i:``,r)}let L=(e,t)=>applyExternalChange(w,e,t);function R(e){return e.kind===`rename`?e.newDocName:e.docName}async function z(e){try{switch(e.kind){case`create`:_.info({docName:e.docName},`[reconcile] create: ${e.docName}`),x.updateDocumentFromMarkdown(e.docName,e.content),x.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),N(`files`),N(`backlinks`),N(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=w.documents.get(t);if(!r){x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),N(`backlinks`),N(`graph`);return}let i=getReconciledBase(t)??``,a=I(t)??i,o=reconcile({docName:t,base:i,ours:a,theirs:n}),s=contentHash(i).slice(0,6),c=contentHash(a).slice(0,6),l=contentHash(n).slice(0,6);switch(_.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),N(`backlinks`),N(`graph`);break;case`clean`:try{L(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),N(`backlinks`),N(`graph`)}catch(e){_.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`merged`:try{L(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),N(`backlinks`),N(`graph`)}catch(e){_.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`conflicts`:try{L(t,o.newContent),setReconciledBase(t,o.newContent),incrementReconcile(),incrementConflict(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),N(`backlinks`),N(`graph`)}catch(e){_.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,n)}break;case`refused`:{incrementConflict();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=w.documents.get(t);if(!n){x.deleteDocument(t),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),N(`files`),N(`backlinks`),N(`graph`);return}let r=getReconciledBase(t)??``,i=I(t)??``,a=i!==r;if(a&&S.current){let e=S.current,n=W?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,d??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),_.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{_.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),x.deleteDocument(t),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),_.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),w.closeConnections(t),await M(n),N(`files`),N(`backlinks`),N(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=w.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(n,r),x.renameDocument(t,n,r),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist rename for ${t} -> ${n}:`,e)}),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}_.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),N(`files`),N(`backlinks`),N(`graph`);break}case`conflict`:{let{docName:t}=e,n=w.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),_.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}}}catch(t){_.error({err:t,kind:e.kind,docName:R(e)},`[reconcile] failed to handle ${e.kind} for ${R(e)}`)}}let B=[];async function V(e){if(isBatchInProgress()){B.push(e);return}await z(e)}async function H(){let e=B.splice(0,B.length);for(let t of e)await z(t)}let U=null,W=null,G=null,K=null;async function q(e){if(w.documents.size===0)return;let t=!1,n=new Promise(e=>{w.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(w.documents.keys());w.closeConnections(),w.flushPendingStores();for(let e of w.documents.values())e.getConnectionsCount()===0&&w.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(w.documents.keys()),i=[],o=[];if(S.current){for(let e of n)if(!isSystemDoc(e))try{let t=I(e);if(t===null){_.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=F(S.current.gitDir,e);if(!n){_.warn({docName:e,gitDir:S.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}mkdirSync(dirname(n),{recursive:!0}),writeFileSync(n,t,`utf-8`),incrementRescueBuffer(),i.push(e),_.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),_.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else _.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function J(){return K||(K=(async()=>{let e=Date.now(),t=[];j=!0;let r,i=await Promise.race([Z.then(()=>`completed`,e=>(_.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&_.warn({},`[server] init did not complete within 5s during shutdown`);let a=w.documents.size;try{try{try{W&&=(await W.unsubscribe(),null),U&&=(await U.unsubscribe(),null)}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{E?.destroy(),O?.destroy(),P&&=(await P.disconnect(),null)}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await T.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await q(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await C.flushPendingGitCommit(),await C.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)}),_.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{G&&=(await G.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(S.current){try{let e=(await esm_default({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(S.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(S.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?_.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):_.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(y)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),_.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),K)}let Y=[];async function X(){try{k=await loadPrincipal(t),_.info({principalId:k.id},`[server] principal loaded`)}catch(e){_.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!S.current)try{S.current=await initShadowRepo(n),_.info({gitDir:S.current.gitDir},`[server] history repo initialized at ${S.current.gitDir}`)}catch(e){_.error({err:e},`[server] history repo init failed`),Y.push(`shadow-repo`)}if(S.current)try{await shadowGit(S.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`)){_.warn({},`[server] history repo appears corrupted — reinitializing`);try{S.current=await initShadowRepo(n)}catch(e){_.error({err:e},`[server] history repo reinit failed`),S.current=void 0,Y.includes(`shadow-repo`)||Y.push(`shadow-repo`)}}else _.error({err:e},`[server] history repo check failed (transient?)`)}if(S.current)try{let e=resolve(S.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await esm_default({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await esm_default({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}_.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await commitUpstreamImport(S.current,d??``,t,r,e),incrementUpstreamImport()}catch(e){_.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else _.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{writeFileSync(e,r,`utf-8`)}catch(e){_.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){_.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t);e.recovered&&e.journal&&_.warn({sourceDocName:e.journal.sourceDocName,destinationDocName:e.journal.destinationDocName,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${e.journal.sourceDocName} -> ${e.journal.destinationDocName}`)}catch(e){_.error({err:e},`[server] managed rename recovery failed`),Y.push(`managed-rename-recovery`)}try{P=await w.openDirectConnection(SYSTEM_DOC_NAME),E?.emitServerInfo(v,getActiveBranch())}catch(e){_.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Y.push(`cc1-push`)}let e=resolveGitDir(n),r=e?readBranchFromHead(e)??`main`:`main`;switchReconciledBaseScope(r),x.switchBranch(r);try{U=await startWatcher(t,V,b),x.rebuildFromDisk(getActiveBranch()),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${getActiveBranch()}:`,e)})}catch(e){_.error({err:e},`[server] disk bridge watcher failed to start`),Y.push(`file-watcher`)}try{W=await startHeadWatcher(n,async({trigger:e})=>{if(_.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),w.flushPendingStores(),await C.flushPendingGitCommit(),setBatchInProgress(!0),S.current){let e=getActiveBranch(),t=resolveGitDir(n),r=t?readBranchFromHead(t)??e:e,i=[];for(let[e,t]of w.documents){if(isSystemDoc(e))continue;let n=null;if(t.transact(()=>{n=I(e)},PARK_SNAPSHOT_ORIGIN),n===null)continue;let r=getReconciledBase(e)??n;i.push({docName:e,markdown:n,diskSnapshot:r})}if(i.length>0)try{let t=await parkBranch(S.current,e,SERVICE_WRITER.id,i,r);t&&(incrementPark(),_.info({count:i.length,branch:e,sha:t.slice(0,8)},`[history] parked ${i.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){_.error({err:e},`[shadow] park failed`)}}},async e=>{let n=B.length,r=e.newBranch??`main`;if(setBatchInProgress(!1),_.info({kind:e.batchKind,headMoved:e.headMoved,docs:n,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${n}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)await H();else{incrementBranchSwitch(),B.splice(0,B.length),switchReconciledBaseScope(r),x.switchBranch(r);for(let[e,n]of w.documents)if(!isSystemDoc(e))try{let i=safeContentPath(e,t);if(!existsSync(i)){let t=getReconciledBase(e)??``,i=I(e)??``;if(i!==t&&S.current){let t=S.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,d??``,{kind:`external-change-rescue`,docName:e,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:r,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),_.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{_.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),_.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=readFileSync(i,`utf-8`);L(e,a),setReconciledBase(e,a),_.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){_.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(_.info({branch:r,docCount:w.documents.size},`[branch-switch] loaded branch ${r} (${w.documents.size} docs)`),x.rebuildFromDisk(r),x.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),S.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of w.documents)if(!isSystemDoc(t))try{let n=await readParkedState(S.current,r,SERVICE_WRITER.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let i=getReconciledBase(t);if(!i)continue;let a=reconcile({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:i});switch(a.kind){case`merged`:case`clean`:L(t,a.newContent),setReconciledBase(t,a.newContent),e++;break;case`conflicts`:L(t,a.newContent),setReconciledBase(t,a.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){_.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&_.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&S.current)try{let t=shadowGit(S.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(n){for(let e of n.split(`
138
+ `))e&&await t.raw(`update-ref`,`-d`,e);_.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){_.error({err:e},`[branch-switch] detached cleanup failed`)}E?.emitBranchSwitched(r)}if(e.headMoved&&e.newHead&&S.current&&n>0){let t=d??`.`;try{let n=await commitUpstreamImport(S.current,t,e.oldHead,e.newHead,r);incrementUpstreamImport(),_.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){_.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){_.error({err:e},`[server] HEAD watcher failed to start`),Y.push(`head-watcher`)}let i=h?.[0]??`open-knowledge`,a=[`-c`,`credential.helper=!${h&&h.length>1?h.join(` `):i} auth git-credential`];try{G=new SyncEngine({projectDir:n,contentDir:t,contentFilter:b,contentRoot:d,credentialArgs:a,cc1Broadcaster:E,setBatchInProgress,onStateChange:e=>{_.info({state:e},`[sync] state → ${e}`)}}),await G.start()}catch(e){_.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),G=null}}let Z=X();return{hocuspocus:w,sessionManager:T,cc1Broadcaster:E,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,contentFilter:b,serverInstanceId:v,destroy:J,ready:Z,degraded:Y,lockDir:y,get syncEngine(){return G}}}const DEFAULT_PARENT_DEATH_POLL_MS=5e3,DEFAULT_IDLE_THRESHOLD_MS=1800*1e3;async function bootServer(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??getLogger(`boot`),a=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,o=process.env.OK_PARENT_PID,s=typeof o==`string`&&/^[0-9]+$/.test(o)?Number.parseInt(o,10):void 0,c=e.lockKind??a??`interactive`,l=e.parentPid??s;initTelemetry();let{createServer:u}=await import(`node:http`),{WebSocketServer:d}=await import(`./wrapper-BTT6637Z.mjs`),{updateServerLockPort:f}=await import(`./server-lock-n3Y5JWNv-DXpg9_eU.mjs`).then(e=>e.a),p=!1;!t&&e.ensureProjectGitFn&&(p=!!(await e.ensureProjectGitFn()).didInit);let m=!1;if(!t&&e.autoInitFn)try{m=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let h=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,includePatterns:e.includePatterns,excludePatterns:e.excludePatterns,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:c,parentPid:l,skipStateManifestCheck:e.skipStateManifestCheck}),{hocuspocus:g,destroy:_,ready:v,degraded:y,lockDir:b,agentPresenceBroadcaster:x}=h,S=u((e,t)=>{let n=e.url?.split(`?`)[0];if(n?.startsWith(`/api/`)){g.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||(t.statusCode=404,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({error:`API route not found`,path:n})))}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?(t.writeHead(500),t.end(`Internal server error`)):t.writableEnded||t.end()});return}t.writeHead(404,{"Content-Type":`application/json`}),t.end(JSON.stringify({error:"Not found. The React UI is served by `ok ui` (default port 3000).",path:n??`/`}))}),C=new d({noServer:!0});C.on(`error`,e=>{i.error({err:e},`WebSocketServer error`)});let w=e.keepaliveGraceMs??1e4,T=new Map,E=new Set,D=!1;S.on(`upgrade`,(e,t,n)=>{if(e.url?.startsWith(`/collab/keepalive`)){t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`MCP keepalive socket error`)}),C.handleUpgrade(e,t,n,t=>{let n=parseKeepaliveConnectionId(e.url);if(n){let e=T.get(n);e!==void 0&&(clearTimeout(e),T.delete(n),i.info({connectionId:n},`[keepalive] reconnect during grace — timer cancelled`))}let r=setInterval(()=>{try{t.ping()}catch{}},3e4);r.unref?.();let a=n?setInterval(()=>{x?.bumpPresenceTs(toBroadcasterKey(n))},3e3):null;a?.unref?.(),t.on(`close`,()=>{if(clearInterval(r),a!==null&&clearInterval(a),!n)return;let e=setTimeout(()=>{if(T.delete(n),D)return;let e=(async()=>{i.info({connectionId:n},`[keepalive] grace expired — cleaning up sessions`);try{await h.sessionManager.closeAllForAgent(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] closeAllForAgent failed`)}try{h.agentFocusBroadcaster?.clearFocus(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearFocus failed`)}try{x?.clearPresence(toBroadcasterKey(n))}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearPresence failed`)}})();E.add(e),e.finally(()=>E.delete(e))},w);e.unref?.(),T.set(n,e),i.info({connectionId:n,graceMs:w},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}e.url?.startsWith(`/collab`)&&(t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`Upgrade socket error`)}),C.handleUpgrade(e,t,n,t=>{let n=g.handleConnection(t,e);t.on(`message`,e=>{n.handleMessage((e instanceof ArrayBuffer,new Uint8Array(e)))}),t.on(`close`,(e,t)=>{n.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{handleCollabSocketError(e)||i.error({err:e},`WebSocket error`),t.terminate()})}))});let O=null;r!==null&&(O=attachIdleShutdown({httpServer:S,thresholdMs:r??DEFAULT_IDLE_THRESHOLD_MS,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await _()})})),await new Promise((t,n)=>{let r=e=>n(e);S.once(`error`,r),S.listen(e.port,e.host,()=>{S.removeListener(`error`,r),t()})});let k=S.address(),A=typeof k==`object`&&k?k.port:e.port??0;if(f(b,A),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:b,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let j=!1,M=null,N=async()=>{if(!j){j=!0,D=!0,M!==null&&(clearInterval(M),M=null),O?.detach();for(let e of T.values())clearTimeout(e);T.clear(),E.size>0&&await Promise.allSettled([...E]),await new Promise(e=>{S.close(()=>e())}),await _(),await shutdownTelemetry()}};if(l!==void 0){let t=e.parentDeathPollMs??DEFAULT_PARENT_DEATH_POLL_MS,n=e.parentAliveCheck??isProcessAlive;M=setInterval(()=>{j||n(l)||(i.warn({parentPid:l,lockKind:c},`[boot] parent process gone — initiating graceful shutdown`),N().catch(e=>{i.error({err:e,parentPid:l},`[boot] parent-death shutdown failed`)}))},t),M.unref?.()}return{httpServer:S,destroy:N,lockDir:b,contentDir:e.contentDir,port:A,ready:v,degraded:y,didAutoInit:m,didGitInit:p,serverInstance:h}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_ZIP_BYTES=102400;function resolveBundledSkillDir(){let e=[`../assets/skills/open-knowledge`,`./assets/skills/open-knowledge`],t=[];for(let n of e){let e=fileURLToPath(new URL(n,import.meta.url));if(existsSync(e))return e;t.push(e)}throw Error(`Bundled skill asset directory not found. Tried: ${t.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function readCliVersion(){for(let e of[`../../cli/package.json`,`../package.json`]){let t=fileURLToPath(new URL(e,import.meta.url));if(!existsSync(t))continue;let n=await readFile(t,`utf-8`),r=JSON.parse(n);if(r.name===`@inkeep/open-knowledge`&&typeof r.version==`string`)return r.version}throw Error(`Could not resolve @inkeep/open-knowledge CLI version — no package.json with matching name found in candidate paths.`)}async function*walkFiles(e,t=e){let n=await readdir(e,{withFileTypes:!0});for(let r of n){let n=join(e,r.name);r.isDirectory()?yield*walkFiles(n,t):r.isFile()&&(yield relative(t,n))}}async function zipDirectory(e,t){let n=e.split(`/`).pop()??`open-knowledge`,r=new import_yazl.ZipFile;r.addEmptyDirectory(`${n}/`);let i=[];for await(let t of walkFiles(e))i.push(t);i.sort();for(let t of i){let i=join(e,t),a=`${n}/${t}`;r.addFile(i,a)}r.end(),await new Promise((e,n)=>{let i=createWriteStream(t);r.outputStream.pipe(i),i.on(`close`,()=>e()),i.on(`error`,n),r.outputStream.on(`error`,n)})}async function sha256OfFile(e){return new Promise((t,n)=>{let r=createHash(`sha256`),i=createReadStream(e);i.on(`data`,e=>r.update(e)),i.on(`end`,()=>t(r.digest(`hex`))),i.on(`error`,n)})}function extractMetadataVersion(e){let t=e.indexOf(`
139
139
  ---`,4);if(!e.startsWith(`---
140
140
  `)||t<0)return;let n=e.slice(4,t),r=n.search(/^metadata:/m);if(r<0)return;let i=n.slice(r).split(`
141
141
  `).slice(1);for(let e of i){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,n={}){let r=statSync(e).size;if(r>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${r} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let i=await sha256OfFile(e),a=await readFile(join(resolveBundledSkillDir(),`SKILL.md`),`utf-8`);if(!/^name:\s+open-knowledge$/m.test(a.slice(0,1e3)))throw Error("SKILL.md frontmatter `name:` does not match 'open-knowledge'. Check packages/server/assets/skills/open-knowledge/SKILL.md frontmatter.");let o=extractMetadataVersion(a);if(!n.skipVersionCheck){if(!o)throw Error("SKILL.md metadata.version missing. Add it to packages/server/assets/skills/open-knowledge/SKILL.md or run `bash scripts/sync-skill-version.sh`.");if(o!==t)throw Error(`SKILL.md metadata.version (${o}) does not match CLI version (${t}). Run \`bash scripts/sync-skill-version.sh\` after bumping package versions.`)}return{size:r,sha256:i,skillVersion:o}}async function buildSkillZip(e={}){let t=e.sourceDir??resolveBundledSkillDir(),n=e.outputPath??join(process.cwd(),`openknowledge.skill`),r=await readCliVersion();await zipDirectory(t,n);let{size:i,sha256:a,skillVersion:o}=await validateSkillZip(n,r,{skipVersionCheck:e.skipVersionCheck});return{outputPath:n,size:i,sha256:a,cliVersion:r,skillVersion:o}}function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):n===`win32`?existsSync(join(r.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function ensureProjectGit(e){let t=resolve(e),n=resolve(t,`.git`);if(existsSync(n))return{didInit:!1};let r=``;try{r=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!existsSync(resolve(n,`HEAD`)))throw new ProjectGitInitError(`git init reported success but ${n}/HEAD is missing (partial init detected)`,r);return console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0}}const SIDECAR_FILENAME=`skill-installed-version`,SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS=6e4,VERSION_RE=/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/;async function readServerPackageVersion(){let e=await readFile(fileURLToPath(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}function sidecarPath(e){return join(e,`.open-knowledge`,SIDECAR_FILENAME)}async function readSidecarVersion(e){try{let t=(await readFile(sidecarPath(e),`utf-8`)).trim();return t.length===0||!VERSION_RE.test(t)?null:t}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function writeSidecarVersion(e,t){let n=sidecarPath(e);await mkdir(dirname(n),{recursive:!0}),await writeFile(n,`${t}\n`,`utf-8`)}function runSpawn(e,t,n,r,i){return new Promise(a=>{let o;try{o=e(t,n,{env:r,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){a({kind:`spawn-error`,stderr:``,error:e});return}let s=``,c=!1,l=e=>{c||(c=!0,clearTimeout(u),a(e))};o.stderr?.on(`data`,e=>{s+=typeof e==`string`?e:e.toString(`utf-8`)}),o.on(`error`,e=>{l({kind:`spawn-error`,stderr:s,error:e})}),o.on(`exit`,e=>{l(e===0?{kind:`ok`,exitCode:e,stderr:s}:{kind:`nonzero`,exitCode:e,stderr:s})});let u=setTimeout(()=>{try{o.kill(`SIGTERM`)}catch{}l({kind:`timeout`,stderr:s})},i)})}async function installUserSkill(e={}){let t=e.home??homedir(),n=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},r=e.spawn??spawn,i=e.timeoutMs??DEFAULT_TIMEOUT_MS,a;try{a=await readServerPackageVersion()}catch(e){return n.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),`failed`}let o=await readSidecarVersion(t).catch(()=>null);if(o!==null&&o===a)return n.info?.({event:`skill-install.skip-current`,version:a},`Open Knowledge skill already installed at current version; skipping.`),`skip-current`;let s;try{s=resolveBundledSkillDir()}catch(e){return n.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled SKILL.md asset not found.`),`failed`}let c=await runSpawn(r,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,s,`--agent`,`*`,`-g`,`-y`,`--copy`],{...process.env,HOME:t},i);if(c.kind===`ok`){try{await writeSidecarVersion(t,a)}catch(e){return n.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),`failed`}return n.info?.({event:`skill-install.installed`,version:a},`Open Knowledge skill installed to detected agent hosts.`),`installed`}return c.kind===`timeout`?(n.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:i,stderr:c.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`):c.kind===`spawn-error`?(n.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(c.error),stderr:c.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`):(n.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:c.exitCode,stderr:c.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${s} --agent '*' -g -y --copy`),`failed`)}export{extractWikiLinksFromMarkdown as $,getShadowRepoPath as $t,applySeed as A,rewriteMarkdownLinksForDocumentRename as At,containsConflictMarkers as B,splitMarkdownBlocks as Bt,SeedPrerequisiteError as C,readUiLock as Ct,acquireUiLock as D,releaseUiLock as Dt,UiLockCollisionError as E,registerWrite as Et,buildWipTree as F,saveInMemoryCheckpoint as Ft,createLiveDerivedIndexExtension as G,updateUiLockPort as Gt,contributorCount as H,starterFolderRule as Ht,classifyEvents as I,saveVersion as It,createServerObserverExtension as J,withSpan as Jt,createPersistenceExtension as K,validateAgentId as Kt,commitUpstreamImport as L,setActiveSpanAttributes as Lt,attachIdleShutdown as M,safeContentPath as Mt,bootServer as N,safeSubdir as Nt,applyAgentMarkdownWrite as O,removeLastKnownHash as Ot,buildSkillZip as P,safetyCheckpoint as Pt,evictStaleTrackerEntries as Q,require_picomatch as Qt,commitWip as R,shadowGit as Rt,STATE_MANIFEST_FILENAME as S,readStateManifest as St,StateManifestError as T,recordContributor as Tt,createApiExtension as U,toBroadcasterKey as Ut,contentHash as V,startWatcher as Vt,createContentFilter as W,updateLastKnownHash as Wt,detectProjectShape as X,writeStateManifest as Xt,detectClaudeDesktopPresence as Y,withSpanSync as Yt,ensureProjectGit as Z,writeTracker as Zt,ProjectGitInitError as _,parseHocuspocusAuthToken as _t,BacklinkIndex as a,incrementCollabSocketFilteredError as at,SERVICE_WRITER as b,planSeed as bt,FILE_SYSTEM_WRITER as c,initTelemetry as ct,HocuspocusAuthRejection as d,isSelfWrite as dt,getWipRefPattern as en,getLogger as et,HocuspocusAuthTokenSchema as f,isSystemDoc as ft,PinoLogger as g,loggerFactory as gt,OBSERVER_SYNC_ORIGIN as h,loadPrincipal as ht,AgentSessionManager as i,handleCollabSocketError as it,assertCompatibleStateManifest as j,rewriteWikiLinksForDocumentRename as jt,applyExternalChange as k,resolveBundledSkillDir as kt,FILE_WATCHER_ORIGIN as l,installUserSkill as lt,MANAGED_RENAME_ORIGIN as m,listRescueCheckpoints as mt,AgentFocusBroadcaster as n,readContributors as nn,getMetrics as nt,CC1Broadcaster as o,incrementServerObserverFire as ot,LOG_MD_TEMPLATE as p,lastKnownHash as pt,createServer$1 as q,validateSkillZip as qt,AgentPresenceBroadcaster as r,getTracer as rt,CONFLICT_MARKER_RE as s,initShadowRepo as st,AGENT_ID_RE as t,parseWriterId as tn,getMeter as tt,GIT_UPSTREAM_WRITER as u,isPairedWriteOrigin as ut,ROLLBACK_ORIGIN as v,parseKeepaliveConnectionId as vt,SeedRootDirError as w,reconcile as wt,STARTER_FOLDERS as x,readBranchFromHead as xt,SEED_CONFIG_FILENAME as y,pathToDocName as yt,commitWipFromTree as z,shutdownTelemetry as zt};
142
- //# sourceMappingURL=dist-0qFIeeXA.mjs.map
142
+ //# sourceMappingURL=dist-D6sXBEzw.mjs.map