@inkeep/open-knowledge 0.8.1 → 0.8.2-beta.0

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 (42) hide show
  1. package/dist/assets/skills/discovery/SKILL.md +1 -1
  2. package/dist/assets/skills/project/SKILL.md +1 -1
  3. package/dist/cli.mjs +4 -4
  4. package/dist/constants-Dfx0JjpK.mjs +2 -0
  5. package/dist/{dist-D_gfC1Ni.mjs → dist-DC2tx33E.mjs} +1 -1
  6. package/dist/{dist-xB__nIDC.mjs → dist-ON5FDO_b.mjs} +14 -14
  7. package/dist/{gh-detect-Bh4D_lOI.mjs → gh-detect-C6XwLMEi.mjs} +2 -2
  8. package/dist/index.mjs +1 -1
  9. package/dist/init-aIylwWdF.mjs +1 -0
  10. package/dist/{init-BrjcA5Su.mjs → init-fr_jOyuF.mjs} +4 -4
  11. package/dist/loader-C4wrjt04.mjs +1 -0
  12. package/dist/{loader-DW_tBjup.mjs → loader-C9R7TB-p.mjs} +2 -2
  13. package/dist/{preview-C25q0Hgx.mjs → preview-CG_Ww7f9.mjs} +2 -2
  14. package/dist/preview-z7bX_BMs.mjs +1 -0
  15. package/dist/public/assets/{ActivityModeContent-74fud2PX.js → ActivityModeContent-Cx6CbLSt.js} +1 -1
  16. package/dist/public/assets/{DocumentContext-D0hMZvqt.js → DocumentContext-Cr33tjJS.js} +21 -21
  17. package/dist/public/assets/{GraphPanel-CAKYBrh_.js → GraphPanel-Dmlbdo1u.js} +1 -1
  18. package/dist/public/assets/{SettingsDialogBody-CA5IZw_a.js → SettingsDialogBody-Dvybh9En.js} +2 -2
  19. package/dist/public/assets/{SourceEditor-Y1rYp83q.js → SourceEditor-BiT2vEI_.js} +2 -2
  20. package/dist/public/assets/{config-validation-events-CpTwSaaY.js → config-validation-events-CRmwXb5F.js} +5 -5
  21. package/dist/public/assets/index-DkifPd37.js +1914 -0
  22. package/dist/public/assets/{prop-types-vr6qWjMf.js → prop-types-BLfKJYBj.js} +1 -1
  23. package/dist/public/assets/{target-navigation-intent-BTTe7RwN.js → target-navigation-intent-DINFA28Q.js} +1 -1
  24. package/dist/public/assets/{toggle-group-BKjtvTFY.js → toggle-group-D4mjbvqQ.js} +1 -1
  25. package/dist/public/assets/{typing-burst-detector-RJxLgd3M.js → typing-burst-detector-DcMiqTtE.js} +2 -2
  26. package/dist/public/index.html +7 -7
  27. package/dist/{repair-launch-json-C9O8Oe9q.mjs → repair-launch-json-DLEdDKoD.mjs} +2 -2
  28. package/dist/{repair-mcp-configs-jbwMX9Vb.mjs → repair-mcp-configs-ziIFi7z-.mjs} +2 -2
  29. package/dist/{repair-skills-DoA5FfyG.mjs → repair-skills-BVLn0Rlf.mjs} +2 -2
  30. package/dist/repair-skills-R77pTaUK.mjs +1 -0
  31. package/dist/{src-CTbD2ATc.mjs → src-BawITI5a.mjs} +2 -2
  32. package/dist/start-BBgW41iZ.mjs +1 -0
  33. package/dist/{start-DNVUQi1R.mjs → start-BCWfuBoE.mjs} +2 -2
  34. package/dist/{write-project-skill-tdvNPxGJ.mjs → write-project-skill-ClozZcPj.mjs} +2 -2
  35. package/package.json +1 -1
  36. package/dist/constants-B3sAUrcT.mjs +0 -2
  37. package/dist/init-arEiTnAN.mjs +0 -1
  38. package/dist/loader-B2sL9y5o.mjs +0 -1
  39. package/dist/preview-cCQ9spTm.mjs +0 -1
  40. package/dist/public/assets/index-DC8kiUXp.js +0 -1914
  41. package/dist/repair-skills-DPnST7TD.mjs +0 -1
  42. package/dist/start-uN6JRhPK.mjs +0 -1
@@ -425,7 +425,7 @@ $2`).split(`
425
425
  `;return F.join(H)},table(e,t,S,w){let E=` `,D=S.enter(`table`),O=[],k=[],j=e.children??[];for(let e of j){let t=e.children??[],E=[],D=[];for(let e of t){let t=S.enter(`tableCell`),O=S.enter(`phrasing`),k=S.containerPhrasing(e,{...w,before:` `,after:` `});O(),t(),E.push(k);let j=e.data?.sourcePadding;D.push(j&&typeof j.left==`number`&&typeof j.right==`number`?{left:j.left,right:j.right}:null)}O.push(E),k.push(D)}D();let F=e.align??[],L=e.data?.sourceDashCounts,B=O[0]?.length??0,H=O.slice(1).reduce((e,t)=>Math.max(e,t.length),0),q=Math.max(B,H,F.length),J=[];for(let e=0;e<q;e++){let t=F[e],S=``,w=``;t===`center`?(S=`:`,w=`:`):t===`left`?S=`:`:t===`right`&&(w=`:`);let E=L?.[e],D=typeof E==`number`&&E>=1?E:1;J.push(S+`-`.repeat(D)+w)}let Y=(e,t)=>{let S=[];for(let w=0;w<q;w++){let E=e[w]??``,D=t[w]??{left:1,right:1};S.push(` `.repeat(D.left)+E+` `.repeat(D.right))}return`|${S.join(`|`)}|`},ee=Array.from({length:q},()=>null);if(O.length===0)return Y(J,ee);let te=[];te.push(Y(O[0],k[0]??[])),te.push(Y(J,ee));for(let e=1;e<O.length;e++)te.push(Y(O[e],k[e]??[]));return te.join(`
426
426
  `)},mdxJsxFlowElement(e,t,S,w){let E=e,D=E.data?.sourceRaw;if(typeof D==`string`)return D;let O=E.data?.htmlBoundary;if(O&&typeof O.opener==`string`&&typeof O.closer==`string`){let e=S.containerFlow({type:`root`,children:E.children??[]},w);return`${O.opener}\n\n${e}\n\n${O.closer}`}let k=E.name??``,j=serializeMdxJsxAttrs(E.attributes??[]);if(!E.children||E.children.length===0)return k?j?`<${k} ${j} />`:`<${k} />`:``;let F=j?`<${k} ${j}>`:`<${k}>`,L=`</${k}>`;return`${F}\n\n${S.containerFlow({type:`root`,children:E.children},w)}\n\n${L}`},mark(e,t,S,w){let E=S.createTracker(w),D=S.enter(`mark`),O=E.move(`==`);return O+=S.containerPhrasing(e,{before:O,after:`==`,...E.current()}),O+=E.move(`==`),D(),O},comment(e,t,S,w){let E=e.data?.sourceForm,D=E===`html`?`<!-- `:`%%`,O=E===`html`?` -->`:`%%`,k=S.createTracker(w),j=S.enter(`comment`),F=k.move(D);return F+=S.containerPhrasing(e,{before:F,after:O,...k.current()}),F+=k.move(O),j(),F},commentBlock(e,t,S,w){let E=S.createTracker(w),D=S.enter(`commentBlock`),O=e.children??[],k=e.data?.sourceForm,j=e.data?.sourceLayout,F=O.length===1&&O[0]?.type===`paragraph`;if(k===`html`&&F){let e=O[0],t=S.containerPhrasing(e,{before:`<!-- `,after:` -->`,...E.current()});return D(),`<!-- ${t} -->`}if(j===`inline`&&F){let e=O[0],t=S.containerPhrasing(e,{before:`%% `,after:` %%`,...E.current()});return D(),`%% ${t} %%`}let L=S.containerFlow(e,E.current());return D(),`%%\n\n${L}\n\n%%`},mdxJsxTextElement(e){let t=e.data?.sourceRaw;if(typeof t==`string`)return t;let S=e.name??``,w=serializeMdxJsxAttrs(e.attributes??[]);return w?`<${S} ${w} />`:`<${S}/>`},rawMdxFallback(e){return e.value??``},blockquote(e,t,S,w){let E=S.enter(`blockquote`),D=S.createTracker(w);D.move(`> `),D.shift(2);let O=S.containerFlow(e,D.current());E();let k=e.data?.sourceMarkerSpacings,j=0;return S.indentLines(O,(e,t,S)=>S?`>`:k?.[j++]===`none`?`>${e}`:`> ${e}`)}};function serializeMdxJsxAttrs(e){let t=[];for(let S of e){if(S.type===`mdxJsxExpressionAttribute`){t.push(`{${S.value}}`);continue}let e=S.name;if(S.value===null||S.value===void 0){t.push(e);continue}if(typeof S.value==`string`){if(S.value.includes(`"`)){let w=S.value.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);t.push(`${e}={"${w}"}`)}else t.push(`${e}="${S.value}"`);continue}t.push(`${e}={${S.value.value}}`)}return t.join(` `)}function emitLinkTitle(e,t,S=` `){return t===`single`?`${S}'${e.replace(/'/g,`\\'`)}'`:t===`paren`?`${S}(${e.replace(/[()]/g,`\\$&`)})`:`${S}"${e.replace(/"/g,`\\"`)}"`}function formatLinkUrl(e){if(!e)return``;let t=0,S=!0;for(let w of e)w===`(`?t++:w===`)`&&(t--,t<0&&(S=!1));return t!==0&&(S=!1),S?e:e.replace(/[\\()]/g,`\\$&`)}function escapeEntityAmpersands(e){return e.replace(/(?<!\\)&(?=[A-Za-z][A-Za-z0-9]*;|#[0-9]+;|#[xX][0-9A-Fa-f]+;)/g,`\\&`)}function safeText(e,t,S){let w=e.unsafe;e.unsafe=w.filter(e=>!(e.character===`&`&&e.after===`[#A-Za-z]`||e.character===`<`||e.character===`[`||e.character===`(`||e.character==="`"));let E;try{E=e.safe(t,S)}finally{e.unsafe=w}return escapeEntityAmpersands(E)}function formatFileSize(e){if(!Number.isFinite(e)||e<0)return``;if(e<1024)return`${e} B`;let t=[`KiB`,`MiB`,`GiB`,`TiB`],S=e/1024,w=0;for(;S>=1024&&w<t.length-1;)S/=1024,w+=1;return`${S.toFixed(1).replace(/\.0$/,``)} ${t[w]}`}var MarkdownManager=class{schema;handlers;pmNodeHandlers;pmMarkHandlers;parseProcessor;serializeProcessor;parseCtx={current:{}};constructor(e){this.schema=getSchema(e.extensions),this.handlers=buildMdastToPmHandlers(this.schema,this.parseCtx);let{nodeHandlers:t,markHandlers:S}=buildPmToMdastHandlers(this.schema);this.pmNodeHandlers=t,this.pmMarkHandlers=S,this.parseProcessor=createParseProcessor({schema:this.schema,handlers:this.handlers,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers}),this.serializeProcessor=createSerializeProcessor({schema:this.schema,handlers:this.handlers,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers,toMarkdownHandlers})}parse(e,t){if(!e.trim())return{type:`doc`,content:[{type:`paragraph`,content:[]}]};this.parseCtx.current=t??{};try{return parseMd(e,this.parseProcessor).toJSON()}finally{this.parseCtx.current={}}}parseToMdast(e){return e.trim()?parseMdToMdast(e,this.parseProcessor):{type:`root`,children:[]}}parseWithFallback(e,t){return e.trim()?parseWithFallback(e,{parse:e=>this.parse(e,t)}):{type:`doc`,content:[{type:`paragraph`,content:[]}]}}serialize(e){let t;try{t=this.schema.nodeFromJSON(e)}catch(t){let S=`MarkdownManager.serialize() failed: schema rejected JSONContent (type=${e.type}, childCount=${e.content?.length??0})`;throw Error(S,{cause:t})}return serializeMd(t,this.serializeProcessor,{schema:this.schema,pmNodeHandlers:this.pmNodeHandlers,pmMarkHandlers:this.pmMarkHandlers})}};const registry=createRegistry();function destructureAttrs(e,t){let S=new Map;for(let e of t)S.set(e.name,e);let w={};for(let t of e){if(t.type===`mdxJsxExpressionAttribute`)continue;let e=t.name,E=S.get(e);if(t.value===null||t.value===void 0){w[e]=!0;continue}if(typeof t.value==`string`){if(E?.type===`number`){let S=Number(t.value);w[e]=Number.isNaN(S)?t.value:S}else E?.type===`boolean`?w[e]=t.value===`true`:w[e]=t.value;continue}let D=t.value.value;try{w[e]=JSON.parse(D)}catch{w[e]=D}}return w}function hasDirtyDescendant(e){let t=!1;return e.descendants(e=>t||e.type.name===`jsxInline`?!1:e.type.name===`jsxComponent`&&e.attrs.sourceDirty?(t=!0,!1):!0),t}function effectiveDirty(e){return e.attrs.sourceDirty||hasDirtyDescendant(e)}function isEmptyMdastParagraph(e){if(e.type!==`paragraph`)return!1;let t=e.children??[];return t.length===0?!0:t.every(e=>e.type===`text`&&e.value===``)}function withInlineCodeData(e,t){if(!t)return e;let S={};return t.sourceFenceChar&&(S.sourceFenceChar=t.sourceFenceChar),typeof t.sourceFenceLength==`number`&&(S.sourceFenceLength=t.sourceFenceLength),Object.keys(S).length===0?e:{...e,data:S}}function wrapAsInlineCode(e,t){if(e.length===0)return withInlineCodeData({type:`inlineCode`,value:``},t);if(e.every(e=>e.type===`text`))return withInlineCodeData({type:`inlineCode`,value:e.map(e=>e.value).join(``)},t);if(e.length===1&&`children`in e[0]){let S=e[0];return{...S,children:[wrapAsInlineCode(S.children,t)]}}return withInlineCodeData({type:`inlineCode`,value:extractTextFromMdastNodes(e)},t)}function extractTextFromMdastNodes(e){let t=``;for(let S of e)S.type===`text`?t+=S.value:`children`in S&&Array.isArray(S.children)?t+=extractTextFromMdastNodes(S.children):`value`in S&&typeof S.value==`string`&&(t+=S.value);return t}const WIKI_EMBED_IMAGE_EXTS=IMAGE_EXTENSIONS;function buildMdastToPmHandlers(e,t){let S=e.nodes,w=e.marks,E={};S.paragraph&&(E.paragraph=(e,t,w)=>{let E=w.all(e).flat(),D=E.some(e=>e?.isBlock&&!e?.isInline),O=E.some(e=>e?.isInline||e?.isText||e?.isTextblock);if(D&&!O)return E.length===1?E[0]:E;if(D&&O){let e=E.filter(e=>!e?.isBlock||e?.isInline),t=E.filter(e=>e?.isBlock&&!e?.isInline),w=[],D=S.paragraph.createAndFill(null,e.length>0?e:null);return D&&w.push(D),w.push(...t),w.length===1?w[0]:w}return S.paragraph.createAndFill(null,E.length>0?E:null)}),S.blockquote&&(E.blockquote=toPmNode(S.blockquote,e=>({sourceMarkerSpacings:e.data?.sourceMarkerSpacings??null}))),S.tableCell&&(E.tableCell=(e=>(t,w,E)=>{let D=E.all(t).flat();if(D.length>0&&S.paragraph){let t=S.paragraph.create(null,D);return e.createAndFill(null,[t])}return e.createAndFill(null,null)})(S.tableCell)),S.tableRow&&(E.tableRow=toPmNode(S.tableRow)),S.table&&S.tableRow&&S.tableCell&&(E.table=(e,t,w)=>{let E=e.align??[],D=e.children??[],O=[];for(let e=0;e<D.length;e++){let t=D[e];if(t.type!==`tableRow`)continue;let k=t.children??[],j=[];for(let t=0;t<k.length;t++){let D=k[t];if(D.type!==`tableCell`)continue;let O=w.all(D).flat(),F=O.length>0&&S.paragraph?[S.paragraph.create(null,O)]:null,L=E[t]??null,B=e===0&&S.tableHeader?S.tableHeader:S.tableCell,H=D.data?.sourcePadding??null,q=B.createAndFill({align:L,sourcePadding:H},F);q&&j.push(q)}let F=S.tableRow.createAndFill(null,j.length>0?j:null);F&&O.push(F)}let k=e.data?.sourceDashCounts??null;return S.table.createAndFill({sourceDashCounts:k},O.length>0?O:null)}),S.image&&(E.image=e=>{let w=e.url??``,E=normalizeDocRelativeAssetUrl(w,t.current.sourcePath);return S.image.createAndFill({src:E,alt:e.alt??null,title:e.title??null,sourceUrl:E===w?null:w})},S.imageReference?E.imageReference=e=>S.imageReference.createAndFill({alt:e.alt??``,label:e.label??e.identifier??``,identifier:e.identifier??``,referenceType:e.referenceType??`shortcut`}):E.imageReference=e=>S.image.createAndFill({src:``,alt:e.alt??null,title:null})),w.escapeMark&&(E.text=t=>{let S=t.value??``,E=typeof t.data?.sourceRaw==`string`?t.data.sourceRaw:null;if(!S&&!E)return null;if(E){let t=S.replaceAll(`\xA0`,` `);return w.sourceLiteral?e.text(t,[w.sourceLiteral.create({sourceRaw:E})]):e.text(t)}let D=t.data?.escapedChars,O=t.data?.entityRefSpans;if(!D?.length&&!O?.length)return e.text(S.replaceAll(`\xA0`,` `));let k=[...(D??[]).map(e=>({kind:`escape`,offset:e.offset,length:1})),...(O??[]).map(e=>({kind:`entity`,offset:e.offset,length:e.length,raw:e.raw}))];k.sort((e,t)=>e.offset-t.offset);let j=[],F=0;for(let t of k){if(t.offset>F){let w=S.slice(F,t.offset).replaceAll(`\xA0`,` `);w&&j.push(e.text(w))}if(t.offset<S.length){let E=S.slice(t.offset,t.offset+t.length).replaceAll(`\xA0`,` `);E&&(t.kind===`escape`?j.push(e.text(E,[w.escapeMark.create()])):w.sourceLiteral?j.push(e.text(E,[w.sourceLiteral.create({sourceRaw:t.raw})])):j.push(e.text(E))),F=t.offset+t.length}}if(F<S.length){let t=S.slice(F).replaceAll(`\xA0`,` `);t&&j.push(e.text(t))}return j.length===1?j[0]:j}),w.code&&(E.inlineCode=t=>e.text(t.value,[w.code.create({sourceFenceChar:t.data?.sourceFenceChar??"`",sourceFenceLength:typeof t.data?.sourceFenceLength==`number`?t.data.sourceFenceLength:1})]));let D=w.strike??w.delete;if(D&&(E.delete=toPmMark(D)),w.highlight&&(E.mark=toPmMark(w.highlight)),w.comment&&(E.comment=toPmMark(w.comment,e=>({sourceForm:e.data?.sourceForm??`percent`}))),S.commentBlock&&(E.commentBlock=toPmNode(S.commentBlock,e=>({sourceForm:e.data?.sourceForm??`percent`,sourceLayout:e.data?.sourceLayout??`block`}))),w.emphasis&&(E.emphasis=toPmMark(w.emphasis,e=>({sourceDelimiter:e.data?.sourceDelimiter??`*`}))),w.strong&&(E.strong=toPmMark(w.strong,e=>({sourceDelimiter:e.data?.sourceDelimiter??`**`}))),S.heading&&(E.heading=toPmNode(S.heading,e=>({level:e.depth,headingStyle:e.data?.sourceStyle??`atx`,sourceTrailingHashes:e.data?.sourceTrailingHashes??null,sourceUnderlineLength:e.data?.sourceUnderlineLength??null,sourceContiguousNext:e.data?.sourceContiguousNext??!1}))),S.codeBlock&&(E.code=t=>{let w=t.value?[e.text(t.value)]:[];return S.codeBlock.createAndFill({language:t.lang??null,meta:t.meta??null,fenceDelimiter:t.data?.sourceFenceChar??"`",fenceLength:t.data?.sourceFenceLength??3,sourceStyle:t.data?.sourceStyle??`fenced`},w)}),S.thematicBreak&&(E.thematicBreak=e=>S.thematicBreak.createAndFill({sourceRaw:e.data?.sourceRaw??`---`})),S.hardBreak&&(E.break=e=>S.hardBreak.createAndFill({hardBreakStyle:e.data?.sourceStyle??`spaces`})),S.list&&(E.list=toPmNode(S.list,e=>({ordered:!!e.ordered,start:e.start??1,spread:!!e.spread,bulletMarker:e.data?.bulletMarker??null,listMarkerDelimiter:e.data?.listMarkerDelimiter??null}))),S.listItem&&(E.listItem=toPmNode(S.listItem,e=>({checked:e.checked??null,spread:!!e.spread}))),w.link){let t=w.sourceLiteral;E.link=(S,E,D)=>{if((S.children??[]).length===0){let w=typeof S.data?.sourceRaw==`string`?S.data.sourceRaw:`[](${S.url??``})`;return w?t?e.text(w,[t.create({sourceRaw:w})]):e.text(w):null}let O=D.all(S).flat(),k=w.link.create({href:S.url??``,title:S.title??null,linkStyle:S.data?.sourceStyle??`inline`,refLabel:null,sourceUrlForm:S.data?.sourceUrlForm??null,sourceTitleMarker:S.data?.sourceTitleMarker??null});return O.map(e=>e.mark(k.addToSet(e.marks)))},E.linkReference=(S,E,D)=>{if((S.children??[]).length===0){let w=typeof S.data?.sourceRaw==`string`?S.data.sourceRaw:`[${S.label??``}][${S.identifier??``}]`;return w?t?e.text(w,[t.create({sourceRaw:w})]):e.text(w):null}let O=D.all(S).flat(),k=w.link.create({href:``,title:null,linkStyle:S.referenceType??`shortcut`,refLabel:S.label??S.identifier??null});return O.map(e=>e.mark(k.addToSet(e.marks)))}}S.htmlBlock&&(E.html=e=>S.htmlBlock.createAndFill({content:e.value??``}));let O=S.linkDefinition??S.linkRefDef;if(O){let e=!!O.spec.attrs?.url,t=!!O.spec.attrs?.href,S=!!O.spec.attrs?.identifier,w=!!O.spec.attrs?.sourceLayout,D=!!O.spec.attrs?.sourceTitleMarker;E.definition=E=>{let k={title:E.title??null};return S&&(k.identifier=E.identifier??``),k.label=E.label??E.identifier??``,e?k.url=E.url??``:t&&(k.href=E.url??``),w&&(k.sourceLayout=E.data?.sourceLayout??null),D&&(k.sourceTitleMarker=E.data?.sourceTitleMarker??null),O.createAndFill(k)}}if(S.jsxComponent){let w=e=>{if(e&&typeof e==`object`&&`sourceRaw`in e){let t=e.sourceRaw;if(typeof t==`string`)return t}};E.mdxJsxFlowElement=(e,E,D)=>{let O=e.name??``,k=registry.getOrWildcard(O),j=destructureAttrs(e.attributes,k.props);if(O===`CommonMarkImage`&&typeof j.src==`string`){let e=j.src,S=normalizeDocRelativeAssetUrl(e,t.current.sourcePath);S!==e&&(j.src=S,j.sourceUrl=e)}let F=D.all(e).flat();return S.jsxComponent.createAndFill({componentName:O,kind:`element`,attributes:e.attributes,sourceRaw:w(e.data)??``,sourceDirty:!1,props:j},F.length?F:void 0)};let D=(e,t)=>{let S=e.attributes?.find(e=>e.type===`mdxJsxAttribute`&&e.name===t);return S&&typeof S.value==`string`?S.value:null};E.mdxJsxTextElement=t=>{if(t.name===`InlineMath`&&S.mathInline){let e=D(t,`formula`)??``,w=D(t,`id`);return S.mathInline.create({formula:e,id:w??null})}if(t.name===`Tag`&&S.tag){let e=D(t,`value`)??``;return S.tag.create({value:e})}if(S.jsxInline){let E=w(t.data)??``;return S.jsxInline.createAndFill({},E?[e.text(E)]:null)}return S.jsxComponent.createAndFill({sourceRaw:w(t.data)??``})},E.mdxFlowExpression=e=>{let t=w(e.data)??`{${e.value??``}}`;return S.jsxComponent.createAndFill({kind:`expression`,sourceRaw:t,sourceDirty:!1})},E.mdxTextExpression=t=>{let S=w(t.data)??`{${t.value??``}}`;return e.text(S)}}return S.wikiLink&&(E.wikiLink=e=>S.wikiLink.createAndFill({target:e.data?.target??``,alias:e.data?.alias??null,anchor:e.data?.anchor??null})),S.tag&&(E.tag=e=>S.tag.createAndFill({value:e.value})),S.wikiLinkEmbed&&(E.wikiLinkEmbed=(E,D)=>{let O=E.data?.target??``,k=E.data?.alias??null,j=E.data?.anchor??null,F=extensionOf(O),{resolveEmbed:L,sourcePath:B}=t.current,H=L&&B?L(O,B)??null:null,q=H?`/${H}`:O,J=D?.type===`paragraph`&&Array.isArray(D.children)&&D.children.length===1;if(J&&WIKI_EMBED_IMAGE_EXTS.has(F)&&S.jsxComponent&&registry.has(`WikiEmbedImage`))return S.jsxComponent.createAndFill({componentName:`WikiEmbedImage`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:q,alt:k??O,target:O,anchor:j,alias:k}});if(J&&VIDEO_EXTENSIONS.has(F)&&S.jsxComponent&&registry.has(`WikiEmbedVideo`))return S.jsxComponent.createAndFill({componentName:`WikiEmbedVideo`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:q,title:k??O,target:O,anchor:j,alias:k}});if(J&&AUDIO_EXTENSIONS.has(F)&&S.jsxComponent&&registry.has(`WikiEmbedAudio`))return S.jsxComponent.createAndFill({componentName:`WikiEmbedAudio`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:q,title:k??O,target:O,anchor:j,alias:k}});if(J&&FILE_ATTACHMENT_EXTENSIONS.has(F)&&S.jsxComponent&&registry.has(`WikiEmbedFile`)){let{resolveSize:e}=t.current,w=e&&B?e(O,B)??null:null,E=w===null?null:formatFileSize(w);return S.jsxComponent.createAndFill({componentName:`WikiEmbedFile`,kind:`element`,attributes:[],sourceRaw:``,sourceDirty:!1,props:{src:q,target:O,anchor:j,alias:k,size:E}})}let Y=k||(j?`${O}#${j}`:O);if(WIKI_EMBED_EXTENSIONS.has(F)&&w.link){let t=w.link.create({href:q,title:null,linkStyle:`inline`,refLabel:null,sourceForm:`wikiembed`,target:O,anchor:j,alias:k});return e.text(Y,[t])}if(w.link){let t=w.link.create({href:O,title:null,linkStyle:`inline`,refLabel:null});return e.text(Y,[t])}throw Error("[wikiLinkEmbed handler] schema lacks `link` mark — cannot dispatch without violating the STOP rule against emitting PM wikiLinkEmbed server-side")}),S.mathInline&&(E.inlineMath=e=>S.mathInline.create({formula:e.value??``})),E.math||=t=>{let w=t.value==null?`«unknown:${t.type}»`:t.value;return S.rawMdxFallback?(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.type,reason:`Unhandled block mdast: ${t.type}`})),S.rawMdxFallback.createAndFill({reason:`Unhandled block mdast: ${t.type}`},w?[e.text(w)]:null)):null},E.inlineMath||=t=>(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.type,reason:`Unhandled inline mdast: ${t.type}`})),t.value==null?e.text(`«unknown:${t.type}»`):e.text(t.value)),S.footnoteReference?E.footnoteReference=e=>S.footnoteReference.create({identifier:e.identifier,label:e.label??e.identifier}):E.footnoteReference||=t=>(console.warn(JSON.stringify({event:`unknown-mdast-type`,type:`footnoteReference`,reason:`FootnoteReference extension missing — recovering [^id] source`})),e.text(`[^${t.label??t.identifier}]`)),S.footnoteDefinition?E.footnoteDefinition=toPmNode(S.footnoteDefinition,e=>{let t=e;return{identifier:t.identifier,label:t.label??t.identifier}}):E.footnoteDefinition||=t=>{console.warn(JSON.stringify({event:`unknown-mdast-type`,type:`footnoteDefinition`,reason:`FootnoteDefinition extension missing — recovering [^id]: marker`}));let w=`[^${t.label??t.identifier}]: `;return S.paragraph?S.paragraph.create(null,e.text(w)):null},E.rawMdxFallbackMdast=t=>{if(!S.rawMdxFallback)return null;let w=t.position?{start:t.position.start?.offset??0,end:t.position.end?.offset??0}:{start:0,end:0};return console.warn(JSON.stringify({event:`unknown-mdast-type`,type:t.originalType,reason:`Unhandled mdast: ${t.originalType}`})),S.rawMdxFallback.createAndFill({reason:`Unhandled mdast: ${t.originalType}`,originalSpan:w},t.value?[e.text(t.value)]:null)},E}function buildPmToMdastHandlers(e){let t={},S={},w=e.nodes,E=e.marks;w.paragraph&&(t.paragraph=fromPmNode(`paragraph`)),w.blockquote&&(t.blockquote=fromPmNode(`blockquote`,e=>{let t=e.attrs.sourceMarkerSpacings,S={};return Array.isArray(t)&&t.length>0&&(S.sourceMarkerSpacings=t),Object.keys(S).length>0?{data:S}:{}})),w.heading&&(t.heading=fromPmNode(`heading`,e=>({depth:e.attrs.level,data:{sourceStyle:e.attrs.headingStyle,sourceTrailingHashes:e.attrs.sourceTrailingHashes??void 0,sourceUnderlineLength:e.attrs.sourceUnderlineLength??void 0,sourceContiguousNext:e.attrs.sourceContiguousNext===!0?!0:void 0}}))),w.codeBlock&&(t.codeBlock=e=>{let t=e.attrs.sourceStyle===`indented`?`indented`:`fenced`;return{type:`code`,lang:t===`indented`?null:e.attrs.language??null,meta:t===`indented`?null:e.attrs.meta??null,value:e.textContent??``,data:{sourceFenceChar:e.attrs.fenceDelimiter,sourceFenceLength:e.attrs.fenceLength,sourceStyle:t}}}),w.thematicBreak&&(t.thematicBreak=e=>({type:`thematicBreak`,data:{sourceRaw:e.attrs.sourceRaw}})),w.hardBreak&&(t.hardBreak=e=>({type:`break`,data:{sourceStyle:e.attrs.hardBreakStyle}})),w.list&&(t.list=fromPmNode(`list`,e=>({ordered:e.attrs.ordered??!1,start:e.attrs.ordered?e.attrs.start??1:null,spread:e.attrs.spread??!1,data:{bulletMarker:e.attrs.bulletMarker,listMarkerDelimiter:e.attrs.listMarkerDelimiter}}))),w.listItem&&(t.listItem=(e,t,S)=>{let w=S.all(e),E=w.length>1&&isEmptyMdastParagraph(w[0])?w.slice(1):w;return{type:`listItem`,checked:e.attrs.checked??null,spread:e.attrs.spread??!1,children:E}}),w.table&&(t.table=(e,t,S)=>{let w=S.all(e),E=[],D=e.firstChild;D&&D.forEach(e=>{let t=e.attrs.align;E.push(t===`left`||t===`right`||t===`center`?t:null)});let O=w.filter(e=>e.type===`tableRow`),k=e.attrs.sourceDashCounts,j=Array.isArray(k)&&k.length>0?{sourceDashCounts:k}:void 0,F={type:`table`,align:E,children:O};return j&&(F.data=j),F}),w.tableRow&&(t.tableRow=fromPmNode(`tableRow`));let D=e=>{let t=e.attrs.sourcePadding,S={};return typeof t==`object`&&t&&typeof t.left==`number`&&typeof t.right==`number`&&(S.sourcePadding=t),Object.keys(S).length>0?{data:S}:{}};if(w.tableCell&&(t.tableCell=fromPmNode(`tableCell`,D)),w.tableHeader&&(t.tableHeader=fromPmNode(`tableCell`,D)),w.image&&(t.image=e=>({type:`image`,url:e.attrs.sourceUrl??e.attrs.src,alt:e.attrs.alt,title:e.attrs.title})),w.imageReference&&(t.imageReference=e=>{let t=e.attrs.label??``,S=e.attrs.identifier??t;return{type:`imageReference`,alt:e.attrs.alt??``,identifier:S,label:t||S,referenceType:e.attrs.referenceType??`shortcut`}}),w.htmlBlock&&(t.htmlBlock=e=>({type:`html`,value:e.attrs.content})),w.linkDefinition??w.linkRefDef){let e=w.linkDefinition?`linkDefinition`:`linkRefDef`;t[e]=e=>{let t={},S=e.attrs.sourceLayout;(S===`multiline`||S===`inline`)&&(t.sourceLayout=S);let w=e.attrs.sourceTitleMarker;(w===`single`||w===`double`||w===`paren`)&&(t.sourceTitleMarker=w);let E={type:`definition`,identifier:e.attrs.identifier??e.attrs.label??``,label:e.attrs.label??e.attrs.identifier??``,url:e.attrs.url??e.attrs.href??``,title:e.attrs.title};return Object.keys(t).length>0&&(E.data=t),E}}if(w.jsxComponent&&(t.jsxComponent=(e,t,S)=>{if(e.attrs.kind===`expression`)return{type:`html`,value:e.attrs.sourceRaw??``};let w=e.attrs.componentName||null,E=Array.isArray(e.attrs.attributes)?e.attrs.attributes:[];return!effectiveDirty(e)&&e.attrs.sourceRaw?{type:`mdxJsxFlowElement`,name:w,attributes:E,children:[],data:{sourceRaw:String(e.attrs.sourceRaw)}}:registry.getOrWildcard(w??`*`).serialize(e,{all:e=>S.all(e),registry,serializeChildren:()=>{throw Error(`SerializeContext.serializeChildren is not available in the PM→mdast handler. Compat descriptors that need markdown-byte body rendering must emit a marker mdast node and let the to-markdown handler render the body via state.containerFlow.`)}})}),w.rawMdxFallback&&(t.rawMdxFallback=e=>{let t=e.textContent??``,S=typeof e.attrs.reason==`string`?e.attrs.reason:``,w=e.attrs.originalSpan;return{type:`rawMdxFallback`,value:t,data:{reason:S,originalSpan:w&&typeof w==`object`&&`start`in w&&`end`in w?{start:Number(w.start)||0,end:Number(w.end)||0}:{start:0,end:0}}}}),w.jsxInline&&(t.jsxInline=e=>{let t=e.attrs.sourceRaw||e.textContent||``;return{type:`mdxJsxTextElement`,name:null,attributes:[],children:[],data:{sourceRaw:String(t)}}}),w.mathInline&&(t.mathInline=e=>{let t=e.attrs.formula??``,S=e.attrs.id;return typeof S==`string`&&S.length>0?{type:`mdxJsxTextElement`,name:`InlineMath`,attributes:[{type:`mdxJsxAttribute`,name:`formula`,value:t},{type:`mdxJsxAttribute`,name:`id`,value:S}],children:[]}:{type:`inlineMath`,value:t}}),w.wikiLink&&(t.wikiLink=e=>{let t=e.attrs.target??``,S=e.attrs.anchor??null,w=e.attrs.alias??null,E=w||(S?`${t}#${S}`:t);return{type:`wikiLink`,value:E,data:{target:t,anchor:S,alias:w},children:[{type:`text`,value:E}]}}),w.tag&&(t.tag=e=>({type:`tag`,value:String(e.attrs.value??``)})),w.wikiLinkEmbed&&(t.wikiLinkEmbed=e=>{let t=e.attrs.target??``,S=e.attrs.anchor??null,w=e.attrs.alias??null,E=w||(S?`${t}#${S}`:t);return{type:`wikiLinkEmbed`,value:E,data:{target:t,anchor:S,alias:w},children:[{type:`text`,value:E}]}}),E.emphasis&&(S.emphasis=fromPmMark(`emphasis`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter}}))),E.strong&&(S.strong=fromPmMark(`strong`,e=>({data:{sourceDelimiter:e.attrs.sourceDelimiter}}))),E.code&&(S.code=(e,t,S)=>{let w=e.attrs.sourceFenceChar,E=e.attrs.sourceFenceLength;return wrapAsInlineCode(S,{sourceFenceChar:w,sourceFenceLength:E})}),E.strike??E.delete){let e=E.strike?`strike`:`delete`;S[e]=fromPmMark(`delete`)}return E.highlight&&(S.highlight=fromPmMark(`mark`)),E.comment&&(S.comment=fromPmMark(`comment`,e=>({data:{sourceForm:e.attrs.sourceForm===`html`?`html`:`percent`}}))),w.commentBlock&&(t.commentBlock=fromPmNode(`commentBlock`,e=>({data:{sourceForm:e.attrs.sourceForm===`html`?`html`:`percent`,sourceLayout:e.attrs.sourceLayout===`inline`?`inline`:`block`}}))),w.footnoteReference&&(t.footnoteReference=e=>{let t=String(e.attrs.identifier??``);return{type:`footnoteReference`,identifier:t,label:e.attrs.label?String(e.attrs.label):t}}),w.footnoteDefinition&&(t.footnoteDefinition=fromPmNode(`footnoteDefinition`,e=>({identifier:String(e.attrs.identifier??``),label:e.attrs.label?String(e.attrs.label):String(e.attrs.identifier??``)}))),E.link&&(S.link=(e,t,S)=>{if(e.attrs.sourceForm===`wikiembed`){let t=typeof e.attrs.target==`string`&&e.attrs.target.length>0?e.attrs.target:e.attrs.href??``,S=typeof e.attrs.anchor==`string`&&e.attrs.anchor.length>0?e.attrs.anchor:null,w=typeof e.attrs.alias==`string`&&e.attrs.alias.length>0?e.attrs.alias:null,E=w||(S?`${t}#${S}`:t);return{type:`wikiLinkEmbed`,value:E,data:{target:t,anchor:S,alias:w},children:[{type:`text`,value:E}]}}let w=e.attrs.linkStyle;if(w===`autolink`)return{type:`link`,url:e.attrs.href??``,title:null,children:S,data:{sourceStyle:`autolink`}};if(w===`gfm-autolink`)return{type:`link`,url:e.attrs.href??``,title:null,children:S,data:{sourceStyle:`gfm-autolink`}};if(w===`inline`||!w){let t={};e.attrs.sourceUrlForm===`angle-bracketed`&&(t.sourceUrlForm=`angle-bracketed`);let w=e.attrs.sourceTitleMarker;return(w===`single`||w===`double`||w===`paren`)&&(t.sourceTitleMarker=w),{type:`link`,url:e.attrs.href??``,title:e.attrs.title??null,children:S,...Object.keys(t).length>0?{data:t}:{}}}return{type:`linkReference`,identifier:(e.attrs.refLabel??``).toLowerCase(),label:e.attrs.refLabel,referenceType:w,children:S}}),E.escapeMark&&(S.escapeMark=(e,t,S)=>{for(let e of S)if(e.type===`text`&&e.value){let t=e;t.data=t.data??{},t.data.escapedChars=t.data.escapedChars??[];for(let e=0;e<t.value.length;e++)t.data.escapedChars.push({offset:e,char:t.value[e]})}return S.length===1?S[0]:S}),E.sourceLiteral&&(S.sourceLiteral=(e,t,S)=>{let w=typeof e.attrs.sourceRaw==`string`?e.attrs.sourceRaw:``;if(S.length===1&&S[0]?.type===`text`){let e=S[0],t=w||e.value;return isValidSourceLiteralRaw(t,e.value)&&(e.data=e.data??{},e.data.sourceRaw=t),e}return{type:`text`,value:S.filter(e=>e.type===`text`).map(e=>e.value??``).join(``)||w}}),{nodeHandlers:t,markHandlers:S}}const COMBINING_MARK_RE=/\p{M}+/gu,NON_LETTER_OR_NUMBER_RE=/[^\p{L}\p{N}]+/gu,EDGE_HYPHENS_RE=/^-+|-+$/g;function toWikiLinkSlug(e){return e.trim().normalize(`NFKD`).replace(COMBINING_MARK_RE,``).toLowerCase().replace(NON_LETTER_OR_NUMBER_RE,`-`).replace(EDGE_HYPHENS_RE,``)}function disambiguateSlug(e,t){let S=t.get(e)??0;return t.set(e,S+1),S===0?e:`${e}-${S}`}function getHeadingSlug(e,t){let S=toWikiLinkSlug(e);return S?disambiguateSlug(S,t):``}const MICROMARK_MDX_EXT=mdx(),FROM_MARKDOWN_MDX_EXT=mdxFromMarkdown(),TO_MARKDOWN_MDX_EXT=mdxToMarkdown(),PLACEHOLDER_BODY=`Body content here.`,PLACEHOLDER_MERMAID_FENCE_BODY=`graph LR
427
427
  A --> B`;function getCanonicalDescriptors(){return builtInComponents.filter(e=>e.surface===`canonical`&&e.name!==`*`)}function getAgentCanonicalDescriptors(){return getCanonicalDescriptors().filter(e=>resolveKind(e)!==`fence`)}function resolveKind(e){return e.name===`MermaidFence`?`fence`:e.hasChildren?`jsx-block`:`jsx-void`}function projectLite(e){return{id:e.name,displayName:e.displayName??e.name,description:e.description??``,kind:resolveKind(e)}}function exampleValueFor(e){if(e.hidden!==!0&&e.type!==`reactnode`){if(`defaultValue`in e&&e.defaultValue!==void 0)return e.defaultValue;if(e.type===`enum`)return e.enumValues[0];if(e.type===`string`)return``;if(e.type===`number`)return 0;if(e.type===`boolean`)return!1}}function shouldEmitProp(e,t){return!(e.omitOnDefault===!0&&`defaultValue`in e&&Object.is(e.defaultValue,t)||e.type===`string`&&e.required===!1&&e.defaultValue===void 0&&t===``)}function buildAttributes(e){let t=[];for(let S of e.props){let e=exampleValueFor(S);e!==void 0&&shouldEmitProp(S,e)&&t.push(propToMdxJsxAttribute(S.name,e))}return t}function buildBodyChildren(e){return fromMarkdown(e.exampleBody&&e.exampleBody.trim().length>0?e.exampleBody:PLACEHOLDER_BODY,{extensions:[MICROMARK_MDX_EXT],mdastExtensions:[FROM_MARKDOWN_MDX_EXT]}).children}function synthesizeExample(e){let t=resolveKind(e),S;if(t===`fence`)S={type:`code`,lang:`mermaid`,meta:null,value:e.exampleBody&&e.exampleBody.trim().length>0?e.exampleBody:PLACEHOLDER_MERMAID_FENCE_BODY};else{let w=buildAttributes(e),E=t===`jsx-block`?buildBodyChildren(e):[];S={type:`mdxJsxFlowElement`,name:e.name,attributes:w,children:E}}return toMarkdown({type:`root`,children:[S]},{extensions:[TO_MARKDOWN_MDX_EXT]}).trimEnd()}function projectParams(e){let t=[];for(let S of e.props){if(S.hidden===!0)continue;let e={name:S.name,type:S.type,required:S.required};S.description!==void 0&&(e.description=S.description),S.advanced===!0&&(e.advanced=!0),S.omitOnDefault===!0&&(e.omitOnDefault=!0),S.type===`enum`&&(e.values=S.enumValues,S.defaultValue!==void 0&&(e.defaultValue=S.defaultValue)),S.type===`string`&&(S.defaultValue!==void 0&&(e.defaultValue=S.defaultValue),S.language!==void 0&&(e.language=S.language),S.accept!==void 0&&(e.accept=S.accept)),S.type===`boolean`&&S.defaultValue!==void 0&&(e.defaultValue=S.defaultValue),S.type===`number`&&S.defaultValue!==void 0&&(e.defaultValue=S.defaultValue),t.push(e)}return t}function projectFull(e){return{...projectLite(e),example:synthesizeExample(e),params:projectParams(e)}}function renderInventoryFooter(){return[``,"**Custom canonical components.** OK `.md` / `.mdx` supports the JSX components below — use whichever is semantically useful in any part of the doc. For full source syntax + parameter schemas, call `get_components({ ids })` with the ids you want to use. Fenced code blocks render naturally and don't need a fetch — including ` ```mermaid ` for diagrams and ` ```html preview ` for interactive HTML/JS/CSS pages (the fence info-string `preview` token renders the block as a live iframe; works for `html` / `htm` / `xml`; optional `h=` / `w=` tokens set size, e.g. ` ```html preview h=400px `). Use ` ```html preview ` whenever you want anything interactive or JS-powered (charts, demos, calculators, animations) — just author the standalone HTML page in the fence. Call `get_authoring_palette` for the markdown-native component forms (write `> [!NOTE]`, not `<Callout>`), copy-ready themed `html preview` starters, and the theme tokens (`var(--chart-1)`, `var(--foreground)`, …) an embed should reference so it tracks the reader's light/dark theme. Arbitrary `<TagName>` JSX falls through as raw MDX when no canonical fits.",``,...getAgentCanonicalDescriptors().map(projectLite).map(e=>`- \`${e.id}\` (${e.kind}) — ${e.description}`)].join(`
428
- `)}const AgentWriteRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,content:string$2().optional(),...agentIdentityFields}).loose(),AgentWriteMdRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,markdown:string$2().min(1),position:_enum([`append`,`prepend`,`replace`]).optional(),...agentIdentityFields}).loose(),AgentPatchRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,find:string$2().min(1),replace:string$2(),offset:number$1().int().nonnegative().optional(),...agentIdentityFields}).loose(),AgentUndoRequestSchema=object$1({docName:safeDocNameField,connectionId:string$2().min(1),scope:_enum([`last`,`session`,`file`]).optional(),...agentIdentityFields}).loose(),SummaryResponseFieldSchema=object$1({value:string$2(),truncatedFrom:number$1().int().nonnegative().optional(),hint:string$2().optional()}).loose(),OrphanHintSchema=object$1({type:literal(`orphan`),parentCandidates:array(string$2()),message:string$2()}).loose(),AgentWriteSuccessSchema=object$1({timestamp:string$2().min(1),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentWriteMdSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),hints:array(OrphanHintSchema).optional(),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentPatchSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentUndoSuccessSchema=object$1({docName:string$2().min(1),scope:_enum([`last`,`session`]),undone:boolean$1()}).loose(),FrontmatterPatchRequestSchema=object$1({docName:safeDocNameField,patch:record(string$2(),union([FrontmatterValueSchema,_null()])),types:record(string$2(),_enum(FRONTMATTER_TYPES)).optional(),summary:summaryField,...agentIdentityFields}).loose(),FrontmatterPatchSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),appliedKeys:array(string$2()),summary:SummaryResponseFieldSchema.optional()}).loose(),LifecycleStatusSchema=object$1({status:string$2().min(1),reason:string$2()}).loose(),DocumentReadSuccessSchema=object$1({docName:string$2().min(1),content:string$2(),lifecycle:LifecycleStatusSchema.nullable()}).loose(),DocumentListEntrySchema=object$1({kind:_enum([`document`,`asset`,`folder`]).default(`document`),docName:string$2().min(1).optional(),docExt:string$2().min(1).default(`.md`),size:number$1().int().nonnegative(),modified:string$2().min(1),isSymlink:boolean$1().default(!1),canonicalDocName:string$2().nullable().default(null),targetPath:string$2().nullable().default(null),path:string$2().min(1).optional(),assetExt:string$2().min(1).optional(),mediaKind:_enum([`image`,`video`,`audio`,`pdf`,`text`]).nullable().optional(),referencedBy:array(string$2().min(1)).optional()}).loose().refine(e=>e.kind===`document`?e.docName!==void 0&&e.path===void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.kind===`folder`?e.docName===void 0&&e.path!==void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.path!==void 0&&e.assetExt!==void 0&&e.referencedBy!==void 0,{message:`document/asset/folder kind must match its required fields (document → docName; asset → path+assetExt+referencedBy; folder → path only, no docName)`}),DocumentListSuccessSchema=object$1({documents:array(DocumentListEntrySchema)}).loose(),BacklinkEntrySchema=object$1({source:string$2().min(1),anchor:string$2().nullable(),title:string$2(),snippet:string$2().nullable()}).loose(),BacklinksSuccessSchema=object$1({docName:string$2().min(1),backlinks:array(BacklinkEntrySchema)}).loose(),BacklinkCountsSuccessSchema=object$1({counts:record(string$2().min(1),number$1().int().nonnegative())}).loose(),ForwardLinkDocEntrySchema=object$1({kind:literal(`doc`),docName:string$2().min(1),anchor:string$2().nullable(),title:string$2(),snippet:string$2().nullable()}).loose(),ForwardLinkExternalEntrySchema=object$1({kind:literal(`external`),url:string$2().min(1),title:string$2(),snippet:string$2().nullable()}).loose(),ForwardLinkEntrySchema=discriminatedUnion(`kind`,[ForwardLinkDocEntrySchema,ForwardLinkExternalEntrySchema]),ForwardLinksSuccessSchema=object$1({docName:string$2().min(1),forwardLinks:array(ForwardLinkEntrySchema)}).loose(),LinkGraphDocNodeSchema=object$1({id:string$2().min(1),kind:literal(`doc`),docName:string$2().min(1),anchor:string$2().nullable(),label:string$2(),cluster:string$2().nullable(),category:string$2().nullable(),tags:array(string$2()).nullable()}).loose(),LinkGraphExternalNodeSchema=object$1({id:string$2().min(1),kind:literal(`external`),url:string$2().min(1),label:string$2()}).loose(),LinkGraphNodeSchema=discriminatedUnion(`kind`,[LinkGraphDocNodeSchema,LinkGraphExternalNodeSchema]),LinkGraphEdgeSchema=object$1({source:string$2().min(1),target:string$2().min(1)}).loose(),LinkGraphSuccessSchema=object$1({nodes:array(LinkGraphNodeSchema),links:array(LinkGraphEdgeSchema)}).loose(),SaveVersionWriterSchema=object$1({id:string$2().min(1),name:string$2().optional(),email:string$2().optional()}).loose(),SaveVersionRequestSchema=object$1({writers:array(SaveVersionWriterSchema).optional(),...agentIdentityFields}).loose(),SaveVersionSuccessSchema=object$1({checkpointRef:string$2().min(1)}).loose(),HistoryShadowContributorSchema=object$1({v:number$1().int().optional(),id:string$2().min(1),name:string$2().min(1),colorSeed:string$2().optional(),docs:array(string$2()),summaries:array(string$2()).optional()}).loose(),HistoryEntrySchema=object$1({sha:string$2().min(1),timestamp:string$2().min(1),author:string$2(),authorEmail:string$2(),type:_enum([`checkpoint`,`wip`,`upstream`,`park`]),message:string$2(),contributors:array(HistoryShadowContributorSchema),checkpoint:unknown$2().nullable()}).loose(),HistorySuccessSchema=object$1({entries:array(HistoryEntrySchema),total:number$1().int().nonnegative().optional(),truncated:boolean$1().optional()}).loose(),HistoryVersionSuccessSchema=object$1({sha:string$2().regex(/^[0-9a-f]{40}$/i),content:string$2(),timestamp:string$2(),author:string$2()}).loose(),DiffLineSchema=object$1({type:_enum([`added`,`removed`,`unchanged`]),text:string$2()}).loose(),DiffSuccessSchema=object$1({lines:array(DiffLineSchema),additions:number$1().int().nonnegative(),deletions:number$1().int().nonnegative()}).loose(),WorkspaceSuccessSchema=object$1({contentDir:string$2().min(1),pathSeparator:_enum([`/`,`\\`]),symlinkResolved:boolean$1()}).loose(),RescueEntryFlatSchema=object$1({docName:string$2().min(1),timestamp:string$2().min(1),size:number$1().int().nonnegative(),source:literal(`flat`)}).loose(),RescueEntryTimelineSchema=object$1({docName:string$2().min(1),timestamp:string$2().min(1),source:literal(`timeline`),sha:string$2().min(1)}).loose(),RescueListSuccessSchema=array(discriminatedUnion(`source`,[RescueEntryFlatSchema,RescueEntryTimelineSchema])).meta({description:"Flat array of rescue buffer entries; discriminated via `source`."}),OrphanEntrySchema=object$1({docName:string$2().min(1),title:string$2()}).loose(),OrphansSuccessSchema=object$1({orphans:array(OrphanEntrySchema)}).loose(),HubEntrySchema=object$1({docName:string$2().min(1),title:string$2(),count:number$1().int().nonnegative()}).loose(),HubsSuccessSchema=object$1({hubs:array(HubEntrySchema)}).loose(),DeadLinkSourceSchema=object$1({source:string$2().min(1),title:string$2(),snippet:string$2().nullable()}).loose(),DeadLinkEntrySchema=object$1({target:string$2().min(1),sources:array(DeadLinkSourceSchema)}).loose(),DeadLinksSuccessSchema=object$1({deadLinks:array(DeadLinkEntrySchema)}).loose(),SuggestLinksTargetSchema=object$1({docName:string$2().min(1),title:string$2(),aliases:array(string$2())}).loose(),SuggestLinksMentionSchema=object$1({source:string$2().min(1),excerpt:string$2(),offset:number$1().int().nonnegative()}).loose(),SuggestLinksSuccessSchema=object$1({target:SuggestLinksTargetSchema,mentions:array(SuggestLinksMentionSchema),truncated:boolean$1()}).loose(),LocalOpOpenRequestSchema=object$1({dir:string$2().min(1)}).loose(),LocalOpOpenSuccessSchema=object$1({port:number$1().int().positive()}).loose(),LocalOpOkInitRequestSchema=object$1({projectPath:string$2().min(1)}).loose(),LocalOpOkInitFailureReasonSchema=_enum([`not-a-git-worktree`,`init-failed`]),LocalOpOkInitResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),projectPath:string$2().min(1)}).loose(),object$1({ok:literal(!1),reason:LocalOpOkInitFailureReasonSchema,message:string$2().min(1)}).loose()]),LocalOpAuthHostRequestSchema=object$1({host:string$2().min(1).optional()}).loose(),LocalOpAuthPatRequestSchema=object$1({pat:string$2().min(1),host:string$2().min(1).optional()}).loose(),LocalOpAuthSetIdentityRequestSchema=object$1({name:string$2().refine(e=>e.trim().length>0,{message:`name must be non-empty`}),email:string$2().refine(e=>e.trim().length>0,{message:`email must be non-empty`})}).loose(),LocalOpAuthIdentitySchema=object$1({name:string$2().min(1),email:string$2().min(1)}).loose().nullable(),LocalOpAuthIdentitySuccessSchema=object$1({identity:LocalOpAuthIdentitySchema}).loose(),LocalOpAuthStatusSuccessSchema=object$1({authenticated:boolean$1()}).loose(),LocalOpAuthPatSuccessSchema=object$1({type:literal(`complete`).optional(),login:string$2().min(1).optional()}).loose(),LocalOpAuthEmptySuccessSchema=object$1({}).loose(),ActivityBurstSchema=object$1({stackIndex:number$1().int().min(0),ts:number$1().int().min(0),additions:number$1().int().min(0),deletions:number$1().int().min(0)}).loose(),ActivityFileSchema=object$1({docName:string$2().min(1),additionsTotal:number$1().int().min(0),deletionsTotal:number$1().int().min(0),lastTs:number$1().int().min(0),bursts:array(ActivityBurstSchema)}).loose(),ActivityAgentHeaderSchema=object$1({displayName:string$2().min(1),color:string$2().min(1),icon:string$2().optional(),connectionId:string$2().min(1)}).loose(),AgentActivitySuccessSchema=object$1({sessionAlive:boolean$1(),agent:ActivityAgentHeaderSchema.nullable(),files:array(ActivityFileSchema)}).loose(),AgentBurstDiffSuccessSchema=object$1({diff:string$2(),generatedAt:number$1().int().min(0)}).loose(),TestResetSuccessSchema=object$1({}).loose(),TestRescanBacklinksSuccessSchema=object$1({}).loose(),TestRescanFilesSuccessSchema=object$1({}).loose(),MetricsReconciliationSuccessSchema=object$1({}).loose(),MetricsParseHealthSuccessSchema=object$1({}).loose(),AgentPresenceEntrySchema=object$1({displayName:string$2().min(1),icon:string$2(),color:string$2().min(1),currentDoc:string$2().nullable(),mode:_enum([`idle`,`writing`]),ts:number$1().int().min(0)}).loose(),MetricsAgentPresenceSuccessSchema=object$1({presence:record(string$2().min(1),AgentPresenceEntrySchema)}).loose(),InstalledAgentsSuccessSchema=record(string$2().min(1),boolean$1()).meta({description:`Flat boolean record keyed by agent-scheme name (claude / codex / cursor). True = installed.`}),SpawnCursorRequestSchema=object$1({path:string$2().min(1,`path must be non-empty`)}).loose(),SpawnCursorSuccessSchema=object$1({}).loose(),RenamedDocMappingSchema=object$1({fromDocName:string$2().min(1),toDocName:string$2().min(1)}).loose(),EmptyRequestSchema=object$1({}).loose(),CreatePageRequestSchema=object$1({path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),CreatePageSuccessSchema=object$1({docName:string$2().min(1)}).loose(),CreateFolderRequestSchema=object$1({path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),CreateFolderSuccessSchema=object$1({path:string$2().min(1)}).loose(),DuplicatePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),DuplicatePathSuccessSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),duplicatedDocNames:array(string$2().min(1))}).loose(),PageEntrySchema=object$1({docName:string$2().min(1),title:string$2(),docExt:string$2().min(1),size:number$1().int().nonnegative(),modified:string$2().min(1),icon:string$2().min(1).max(2048).optional()}).loose(),PagesSuccessSchema=object$1({pages:array(PageEntrySchema)}).loose(),HeadingEntrySchema=object$1({level:number$1().int().min(1).max(6),text:string$2(),slug:string$2()}).loose(),PageHeadingsSuccessSchema=object$1({docName:string$2().min(1),headings:array(HeadingEntrySchema)}).loose(),RenameRequestSchema=object$1({docName:string$2().min(1),newDocName:string$2().min(1),summary:summaryField,...agentIdentityFields}).loose(),RenameRewrittenDocSchema=object$1({docName:string$2().min(1),rewrites:number$1().int().nonnegative()}).loose(),RenameSuccessSchema=object$1({renamed:array(RenamedDocMappingSchema),rewrittenDocs:array(RenameRewrittenDocSchema),summary:SummaryResponseFieldSchema.optional()}).loose(),RenamePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),fromPath:string$2().min(1),toPath:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),RenamePathSuccessSchema=object$1({renamed:array(RenamedDocMappingSchema),rewrittenDocs:array(RenameRewrittenDocSchema).optional(),summary:SummaryResponseFieldSchema.optional()}).loose(),DeletePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields}).loose(),DeletePathSuccessSchema=object$1({deletedDocNames:array(string$2().min(1))}).loose(),TrashCleanupRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),TrashCleanupSuccessSchema=object$1({deletedDocNames:array(string$2().min(1))}).loose(),RollbackRequestSchema=object$1({docName:string$2().min(1),commitSha:string$2().regex(/^[0-9a-f]{40}$/i,{message:`commitSha must be a 40-char git SHA`}),summary:summaryField,...agentIdentityFields}).loose(),RollbackSuccessSchema=object$1({restoredFrom:string$2().min(1),timestamp:string$2().min(1),summary:SummaryResponseFieldSchema.optional()}).loose(),SyncStateSchema=_enum([`dormant`,`idle`,`fetching`,`pulling`,`pushing`,`conflict`,`offline`,`auth-error`,`disabled`]),SyncRemoteSchema=object$1({label:string$2().min(1),webUrl:url().nullable()}).loose(),PushPermissionSchema=discriminatedUnion(`checkStatus`,[object$1({checkStatus:literal(`allowed`)}).loose(),object$1({checkStatus:literal(`denied`),deniedReason:_enum([`no-collaborator`,`private-no-access`,`repo-not-found`])}).loose(),object$1({checkStatus:literal(`unknown`),unknownError:_enum([`network`,`timeout`,`rate-limit`,`token-invalid`,`malformed-response`]).optional()}).loose()]),SyncStatusSchema=object$1({state:SyncStateSchema,lastSyncUtc:string$2().nullable(),lastFetchUtc:string$2().nullable(),lastPushedSha:string$2().nullable(),ahead:number$1().int().min(0),behind:number$1().int().min(0),consecutiveFailures:number$1().int().min(0),conflictCount:number$1().int().min(0),hasRemote:boolean$1(),syncEnabled:boolean$1(),identityUnresolved:boolean$1(),remote:SyncRemoteSchema.nullable().optional(),error:string$2().optional(),errorCode:_enum([`auth-403`,`auth-401`,`auth-scope-mismatch`,`semantic-protected-branch`]).optional(),pausedReason:string$2().optional(),pushPermission:PushPermissionSchema.optional()}).loose(),SyncTriggerRequestSchema=object$1({op:_enum([`sync`,`push`,`pull`]).optional()}).loose(),SyncTriggerSuccessSchema=object$1({op:_enum([`sync`,`push`,`pull`])}).loose(),ConflictEntrySchema=object$1({file:string$2().min(1),detectedAt:string$2().min(1),oursSha:string$2().optional(),theirsSha:string$2().optional(),baseSha:string$2().optional()}).loose(),SyncConflictsSuccessSchema=object$1({conflicts:array(ConflictEntrySchema)}).loose(),SyncResolveConflictRequestSchema=object$1({file:string$2().min(1),strategy:_enum([`mine`,`theirs`,`content`,`delete`]),content:string$2().optional()}).loose().refine(e=>e.strategy!==`content`||e.content!==void 0&&e.content!==``,{message:`content must be a non-empty string when strategy is 'content'`,path:[`content`]}),SyncResolveConflictSuccessSchema=object$1({}).loose(),SyncConflictContentSuccessSchema=object$1({file:string$2().min(1),base:string$2(),ours:string$2(),theirs:string$2(),kind:_enum([`both-modified`,`delete-modify`,`modify-delete`]),lifecycleStatus:string$2().nullable()}).loose(),SyncAbortMergeSuccessSchema=object$1({}).loose(),SeedPlanSuccessSchema=object$1({plan:custom(e=>e!==void 0,{message:`plan is required`})}).loose(),SeedApplyRequestSchema=object$1({plan:custom(e=>e!==void 0,{message:`plan is required`})}).loose(),SeedApplySuccessSchema=object$1({result:custom(e=>e!==void 0,{message:`result is required`})}).loose(),SeedPackFolderInfoSchema=object$1({path:string$2().min(1),summary:string$2().min(1)}).loose(),SeedPackEntryCountsSchema=object$1({files:number$1().int().nonnegative(),folders:number$1().int().nonnegative()}).loose(),SeedPackInfoSchema=object$1({id:string$2().min(1),name:string$2().min(1),description:string$2().min(1),defaultSubfolder:string$2().optional(),folders:array(SeedPackFolderInfoSchema),entryCounts:SeedPackEntryCountsSchema}).loose(),SeedListPacksSuccessSchema=object$1({packs:array(SeedPackInfoSchema)}).loose(),InstallSkillRequestSchema=object$1({noOpen:boolean$1().optional(),out:string$2().min(1).optional()}).loose(),InstallSkillHandoffErrorSchema=object$1({reason:_enum([`unsupported-platform`,`spawn-error`]),message:string$2()}).loose(),InstallSkillSuccessSchema=discriminatedUnion(`status`,[object$1({status:literal(`installed`),outputPath:string$2(),size:number$1().int().nonnegative(),sha256:string$2(),skillVersion:string$2()}).loose(),object$1({status:literal(`built`),outputPath:string$2(),size:number$1().int().nonnegative(),sha256:string$2(),skillVersion:string$2(),handoffError:InstallSkillHandoffErrorSchema.optional()}).loose(),object$1({status:literal(`failed`),buildError:string$2()}).loose(),object$1({status:literal(`skip-current`),skillVersion:string$2(),recordedAt:string$2().optional()}).loose()]),TagSummaryEntrySchema=object$1({name:string$2().min(1),count:number$1().int().nonnegative(),isLeaf:boolean$1()}).loose(),TagsListSuccessSchema=object$1({tags:array(TagSummaryEntrySchema)}).loose(),TagsDocEntrySchema=object$1({docName:string$2().min(1),title:string$2(),matchingTags:array(string$2().min(1)),snippet:string$2().nullable()}).loose(),TagsForNameSuccessSchema=object$1({name:string$2().min(1),docs:array(TagsDocEntrySchema)}).loose(),FolderConfigGetSuccessSchema=object$1({folder:unknown$2(),frontmatter_local:record(string$2(),unknown$2()).nullable(),frontmatter_sources:record(string$2(),string$2()).optional(),schema_declarations:record(string$2(),unknown$2()).optional(),schema_sources:record(string$2(),string$2()).optional(),schema_local:record(string$2(),unknown$2()).nullable()}).loose(),FolderConfigPutRequestSchema=object$1({path:string$2(),frontmatter:record(string$2(),unknown$2()).optional(),declarations:record(string$2(),unknown$2()).optional()}).loose(),FolderConfigPutSuccessSchema=object$1({applied:unknown$2()}).loose(),TemplateFrontmatterSchema$1=record(string$2(),unknown$2()).meta({description:`Free-form frontmatter map embedded in template payloads.`}),TemplatePayloadSchema=object$1({name:string$2().min(1),folder:string$2(),scope:_enum([`local`,`inherited`]),path:string$2().min(1),frontmatter:TemplateFrontmatterSchema$1,body:string$2()}).strict(),TemplateGetSuccessSchema=object$1({template:TemplatePayloadSchema}).strict(),TemplatePutRequestSchema=object$1({folder:string$2(),name:string$2(),body:string$2().optional(),frontmatter:TemplateFrontmatterSchema$1.optional()}).strict(),TemplatePutSuccessSchema=object$1({path:string$2().min(1),created:boolean$1(),warnings:array(string$2())}).strict(),TemplateDeleteSuccessSchema=object$1({existed:boolean$1(),path:string$2().min(1)}).strict(),SearchRequestSchema=object$1({query:string$2().optional(),intent:_enum([`autocomplete`,`full_text`,`omnibar`]).optional(),scopes:array(_enum([`page`,`folder`,`content`])).optional(),scope:string$2().optional(),limit:number$1().int().nonnegative().optional()}).loose(),SearchResultEntrySchema=object$1({kind:_enum([`page`,`folder`,`content`]),path:string$2().min(1),title:string$2(),score:number$1(),signals:record(string$2(),unknown$2()),snippet:string$2().optional()}).loose(),SearchSuccessSchema=object$1({query:string$2(),intent:_enum([`autocomplete`,`full_text`,`omnibar`]),results:array(SearchResultEntrySchema),elapsedMs:number$1().nonnegative()}).loose(),SkillInstallTargetStateSchema=object$1({version:string$2().min(1),recordedAt:string$2().min(1)}).loose(),SkillInstallStateSuccessSchema=object$1({currentVersion:string$2().min(1),targets:record(string$2(),SkillInstallTargetStateSchema.nullable())}).loose(),CC1_CHANNEL_SERVER_INFO=`server-info`,CC1_CHANNEL_BRANCH_SWITCHED=`branch-switched`,CC1_CHANNEL_DISK_ACK=`disk-ack`,CC1_CHANNEL_CONFIG_VALIDATION_REJECTED=`config-validation-rejected`,CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR=`config-ignore-nested-error`,DerivedViewChannelSchema=_enum([`files`,`backlinks`,`graph`,`sync-status`,`session-activity`,`tags`]),CC1ServerInfoPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_SERVER_INFO),seq:number$1(),serverInstanceId:string$2().min(1),currentBranch:string$2().min(1).optional()}).loose(),CC1BranchSwitchedPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_BRANCH_SWITCHED),seq:number$1(),branch:string$2().min(1)}).loose(),CC1DerivedViewPayloadSchema=object$1({v:literal(1),ch:DerivedViewChannelSchema,seq:number$1()}).loose(),CC1DiskAckPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_DISK_ACK),seq:number$1(),docName:string$2().min(1),sv:string$2().min(1)}).loose(),CC1ConfigValidationRejectedPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED),seq:number$1(),docName:string$2().min(1),error:ConfigValidationErrorSchema}).loose(),CC1ConfigIgnoreNestedErrorPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR),seq:number$1(),path:string$2().min(1),error:string$2().min(1)}).loose(),WORKSPACE_SEARCH_SCHEMA={id:`string`,kind:`enum`,path:`string`,title:`string`,name:`string`,pathSegments:`string`,content:`string`,modifiedTs:`number`},workspaceSearchIndexes=new WeakMap;function clampLimit(e){return e===void 0||!Number.isFinite(e)?20:Math.max(1,Math.min(100,Math.trunc(e)))}function normalize$2(e){return e.trim().toLowerCase()}function workspaceSearchBasename(e){let t=e.split(`/`).filter(Boolean);return t[t.length-1]??e}function workspaceSearchPathSegments(e){return e.split(`/`).filter(Boolean).join(` `)}function createWorkspaceSearchDocument(e){let t=workspaceSearchBasename(e.path),S=e.title?.trim()||t,w=e.modifiedTs??0;return{id:`${e.kind}:${e.path}`,kind:e.kind,path:e.path,title:S,name:t,pathSegments:workspaceSearchPathSegments(e.path),content:e.content??``,modifiedTs:Number.isFinite(w)?w:0}}function createWorkspaceSearchIndex(e){let t=create$9({schema:WORKSPACE_SEARCH_SCHEMA});return e.length>0&&insertMultiple(t,e),t}function createWorkspaceSearchCorpus(e){let t={documents:e};return workspaceSearchIndexes.set(t,createWorkspaceSearchIndex(e)),t}function getWorkspaceSearchIndex(e){let t=workspaceSearchIndexes.get(e);if(t)return t;let S=createWorkspaceSearchIndex(e.documents);return workspaceSearchIndexes.set(e,S),S}function defaultScopes(e){return e===`autocomplete`?[`page`]:e===`full_text`?[`page`,`content`]:[`page`,`folder`]}function scopeAllows(e,t){return t.has(e.kind)?!0:e.kind===`page`&&t.has(`content`)}function lexicalScore(e,t){let S=normalize$2(t);if(!S)return 0;let w=normalize$2(e.title),E=normalize$2(e.name),D=normalize$2(e.path),O=D.split(`/`);return w===S||E===S?700:D===S?650:w.startsWith(S)||E.startsWith(S)?600:O.some(e=>e.startsWith(S))?550:w.includes(S)||E.includes(S)?500:D.includes(S)?450:-1}function recencyScores(e){let t=e.map(e=>e.modifiedTs).filter(e=>Number.isFinite(e)&&e>0);if(t.length===0)return new Map;let S=1/0,w=-1/0;for(let e of t)e<S&&(S=e),e>w&&(w=e);let E=Math.max(1,w-S);return new Map(e.map(e=>[e.id,e.modifiedTs>0?(e.modifiedTs-S)/E*50:0]))}function searchProperties(e){return e===`full_text`?[`title`,`name`,`path`,`pathSegments`,`content`]:[`title`,`name`,`path`,`pathSegments`]}function searchBoost(e){return e===`full_text`?{title:8,name:7,path:5,pathSegments:4,content:1}:e===`autocomplete`?{title:10,name:9,path:5,pathSegments:4}:{title:8,name:7,path:5,pathSegments:4}}function toleranceFor(e,t){return normalize$2(t).length<4?0:e===`full_text`?1:0}function searchWorkspaceCorpus(e,t,S={}){let w=S.intent??`omnibar`,E=clampLimit(S.limit),D=new Set(S.scopes??defaultScopes(w)),O=e.documents.filter(e=>scopeAllows(e,D)),k=normalize$2(t);if(!k)return O.slice().sort((e,t)=>e.path.localeCompare(t.path)).slice(0,E).map(e=>({document:e,score:0,signals:{lexical:0,fullText:0,recency:0}}));let j=search(getWorkspaceSearchIndex(e),{term:k,properties:searchProperties(w),boost:searchBoost(w),tolerance:toleranceFor(w,k),limit:Math.max(E*4,40)}),F=new Map(j.hits.filter(e=>scopeAllows(e.document,D)).map(e=>[e.document.id,e.score])),L=recencyScores(O),B=new Map;for(let e of O)lexicalScore(e,k)>=0&&B.set(e.id,e);for(let e of j.hits)scopeAllows(e.document,D)&&B.set(e.document.id,e.document);return[...B.values()].map(e=>{let t=Math.max(0,lexicalScore(e,k)),S=F.get(e.id)??0,w=L.get(e.id)??0;return{document:e,score:t+S*20+w,signals:{lexical:t,fullText:S,recency:w}}}).sort((e,t)=>e.score===t.score?e.document.path.localeCompare(t.document.path):t.score-e.score).slice(0,E)}const SHARE_URL_VERSION_V1=1;function encodeShareUrl(e){let t=new TextEncoder().encode(e),S=new Uint8Array(1+t.length);return S[0]=SHARE_URL_VERSION_V1,S.set(t,1),uint8ArrayToBase64Url(S)}function uint8ArrayToBase64Url(e){let t=``;for(let S=0;S<e.length;S++)t+=String.fromCharCode(e[S]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}const SINGLETON_KEY=Symbol.for(`@inkeep/open-knowledge/skill-state-field-registry`),g=globalThis;g[SINGLETON_KEY]===void 0&&(g[SINGLETON_KEY]=registry$1());const skillStateFieldRegistry=g[SINGLETON_KEY],SKILL_STATE_FILENAME=`skill-state.yml`,SKILL_STATE_REL=[`.ok`,SKILL_STATE_FILENAME],SKILL_STATE_TARGETS=[`claude-cowork`,`cli-hosts`],SKILL_STATE_SURFACES=[`server-build-and-open`,`electron-build-and-open`,`cli-npx-skills-add`,`desktop-direct`,`cli-start`],SKILL_STATE_VERSION_RE=/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/,TargetEntrySchema=looseObject({version:string$2().regex(SKILL_STATE_VERSION_RE,`version must match /^\\d+\\.\\d+\\.\\d+(?:[-+][\\w.-]+)?$/`).register(skillStateFieldRegistry,{description:`Recorded skill version for this target.`}),recordedAt:datetime().register(skillStateFieldRegistry,{description:`ISO 8601 timestamp of the most recent successful write. Updated on every write, including reinstalls of the same version.`}),surface:_enum(SKILL_STATE_SURFACES).register(skillStateFieldRegistry,{description:`Install-source surface that recorded this entry.`}).optional()}),SkillStateSchema=looseObject({schema:literal(1).register(skillStateFieldRegistry,{description:`Schema major version. Bumped only on breaking shape changes.`}),targets:looseObject({"claude-cowork":TargetEntrySchema.optional(),"cli-hosts":TargetEntrySchema.optional()}).register(skillStateFieldRegistry,{description:`Per-target install-state entries. Absent target = no recorded install.`}).default({})});function emptySkillState(){return{schema:1,targets:{}}}function createCodeFenceTracker(){let e=!1,t=``,S=0;return w=>{let E=parseCodeFenceLine(w);return e?(E&&E.char===t&&E.len>=S&&!E.hasInfo&&(e=!1,t=``,S=0),!0):E?(e=!0,t=E.char,S=E.len,!0):!1}}function parseCodeFenceLine(e){let t=(e.endsWith(`\r`)?e.slice(0,-1):e).match(/^ {0,3}([`~])(\1{2,})(.*)$/);return t?{char:t[1],len:1+t[2].length,hasInfo:t[3].trim()!==``}:null}const AGENT_COLORS=[`#D97757`,`#1B1912`,`#F9F3E9`,`#7A9DFF`,`#8534F3`,`#9663F0`,`#727CF3`],AGENT_ICON_COLORS={claude:`#D97757`,cursor:`#1B1912`,windsurf:`#0B100F`,openai:`#7A9DFF`,github:`#8534F3`,cline:`#9663F0`,bot:`#727CF3`};function colorFromSeed(e,t=AGENT_COLORS){let S=0;for(let t of e)S=(S<<5)-S+t.charCodeAt(0)|0;return t[Math.abs(S)%t.length]}const ICON_MAP={"claude-code":`claude`,"claude-ai":`claude`,cursor:`cursor`,"cursor-vscode":`cursor`,cascade:`windsurf`,codex:`openai`,"codex-mcp-client":`openai`,copilot:`github`,cline:`cline`};function iconFromClientName(e){return e?ICON_MAP[e]||(e.startsWith(`local-agent-mode-`)?`claude`:`bot`):`bot`}const BRAND_NAME={claude:`Claude`,cursor:`Cursor`,windsurf:`Windsurf`,openai:`Codex`,github:`Copilot`,cline:`Cline`};function displayNameFromClientName(e){let t=e?.trim();return t?BRAND_NAME[iconFromClientName(t)]??t:`Agent`}function resolveInternalHref(e,t){let S=e.trim();if(!S||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(S)||S.startsWith(`//`)||S.startsWith(`/`)||S.startsWith(`#`))return null;let w=S.indexOf(`#`),E=w>=0?S.slice(0,w):S,D=w>=0?S.slice(w+1):null,O=(E.split(`?`)[0]??``).trim();if(!O)return null;let k=(O.split(`/`).pop()??``).match(/\.([a-z0-9]+)$/i);if(k){let e=(k[1]??``).toLowerCase();if(e!==`md`&&e!==`mdx`)return null}let j=O.toLowerCase(),F=j.endsWith(`.mdx`)?O.slice(0,-4):j.endsWith(`.md`)?O.slice(0,-3):O,L=t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of F.split(`/`))if(e===`..`){if(L.length===0)return null;L.pop()}else e!==`.`&&e!==``&&L.push(e);return L.length===0?null:{docName:L.join(`/`),anchor:D||null}}const URI_SCHEME_RE=/^[a-zA-Z][a-zA-Z\d+\-.]*:/;function extractAssetExtension(e){let t=(e.split(/[?#]/)[0]??e).match(/\.([a-z0-9]+)$/i);return t?(t[1]??``).toLowerCase():null}function isExternalHref(e){let t=e.trim();return URI_SCHEME_RE.test(t)||t.startsWith(`//`)}function classifyMarkdownHref(e,t){let S=e.trim();if(!S)return null;if(S.startsWith(`#`)){let e=S.slice(1).trim();return e?{kind:`anchor`,anchor:e}:null}let w=resolveInternalHref(S,t);if(w)return{kind:`doc`,docName:w.docName,anchor:w.anchor};if(isExternalHref(S)||S.startsWith(`/`))return{kind:`external`,url:S};let E=extractAssetExtension(S);return E&&E!==`md`&&E!==`mdx`?{kind:`asset`,url:S,ext:E}:null}function classifyWikiLinkTarget(e,t){let S=e.trim();if(!S)return null;if(isExternalHref(S))return{kind:`external`,url:t?`${S}#${t}`:S};let w=extractAssetExtension(S);return w&&w!==`md`&&w!==`mdx`?{kind:`asset`,url:S,ext:w}:{kind:`doc`,docName:S,anchor:t?.trim()||null}}function resolveAssetProjectPath(e,t){let S=e.trim();if(!S||URI_SCHEME_RE.test(S)||S.startsWith(`//`)||S.startsWith(`#`))return null;let w=S.indexOf(`#`),E=((w>=0?S.slice(0,w):S).split(`?`)[0]??``).trim();if(!E)return null;let D=E.startsWith(`/`),O=D?E.slice(1):E,k=D?[]:t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of O.split(`/`))if(e===`..`){if(k.length===0)return null;k.pop()}else e!==`.`&&e!==``&&k.push(e);return k.length===0?null:k.join(`/`)}function normalizePath(e){let t=e;return t.startsWith(`./`)&&(t=t.slice(2)),t.startsWith(`/`)&&(t=t.slice(1)),t}function basenameOf(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function dirnameOf(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function splitSegments(e){return e.split(`/`).filter(e=>e!==``)}function isInSubtree(e,t){let S=dirnameOf(t);return e===``||S===e?!0:S.startsWith(`${e}/`)}function depthInSubtree(e,t){let S=dirnameOf(t);if(e===S)return 0;let w=e===``?S:S.slice(e.length+1);return w===``?0:splitSegments(w).length}function relativeHops(e,t){let S=splitSegments(e),w=splitSegments(t),E=0;for(;E<S.length&&E<w.length&&S[E]===w[E];)E++;return S.length-E+(w.length-E)}function createBasenameIndex(){let e=new Map;function t(t){let S=normalizePath(t);if(S===``)return;let w=basenameOf(S);if(w===``)return;let E=w.toLowerCase(),D=e.get(E);if(!D){e.set(E,[S]);return}D.includes(S)||D.push(S)}function S(t){let S=normalizePath(t),w=basenameOf(S).toLowerCase(),E=e.get(w);if(!E)return;let D=E.indexOf(S);D!==-1&&(E.splice(D,1),E.length===0&&e.delete(w))}function w(e,w){S(e),t(w)}function E(t,S){let w=t.toLowerCase(),E=e.get(w);if(!E||E.length===0)return null;if(E.length===1)return E[0];let D=dirnameOf(normalizePath(S)),O=[],k=[];for(let e of E)isInSubtree(D,e)?O.push(e):k.push(e);return O.length>0?(e=>{let t=e[0],S=depthInSubtree(D,t);for(let w=1;w<e.length;w++){let E=e[w],O=depthInSubtree(D,E);(O<S||O===S&&E<t)&&(t=E,S=O)}return t})(O):(e=>{let t=e[0],S=relativeHops(D,dirnameOf(t));for(let w=1;w<e.length;w++){let E=e[w],O=relativeHops(D,dirnameOf(E));(O<S||O===S&&E<t)&&(t=E,S=O)}return t})(k)}function D(){let t=new Map;for(let[S,w]of e)t.set(S,[...w]);return t}function O(){e.clear()}return{add:t,remove:S,rename:w,resolveEmbed:E,clear:O,snapshot:D,size:()=>e.size}}const TAG_HIERARCHY_SEPARATOR=`/`;function expandTagToHierarchy(e){if(!e)return[];let t=e.split(TAG_HIERARCHY_SEPARATOR),S=[],w=``;for(let e of t)w=w?`${w}${TAG_HIERARCHY_SEPARATOR}${e}`:e,S.push(w);return S}function tagsMatchingPrefix(e,t){if(e.size===0)return new Set;if(t===``)return new Set(e);let S=new Set,w=`${t}${TAG_HIERARCHY_SEPARATOR}`;for(let E of e)(E===t||E.startsWith(w))&&S.add(E);return S}const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,S){let w;try{w=statSync(e)}catch(t){let S=t.code;return S===`ENOENT`||S===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let E=computeProjectSubPath(t,S);if(w.isDirectory())return{kind:`directory`,path:e,projectSubPath:E};if(w.isFile()){let S;try{S=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let w=S.match(/^gitdir:\s*(.+)$/);return w?{kind:`linked`,path:resolve(t,w[1]),gitPath:e,projectSubPath:E}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let S=relative(e,t);return S===``||S===`.`||S.startsWith(`..`)||isAbsolute(S)?``:S}function findAncestorGitEntry(e){let t=homedir(),S=resolve(e),w=64;for(let e=0;e<64;e++){if(S===t)return null;let e=dirname(S);if(e===S||e===t)return null;let w=resolve(e,`.git`);try{let t=statSync(w);if(t.isDirectory()||t.isFile())return{gitPath:w,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${w} (${t??`unknown`}); skipping ancestor`)}S=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),S=classifyGitEntry(resolve(t,`.git`),t,t);if(S.kind!==`absent`)return S;let w=findAncestorGitEntry(t);return w===null?{kind:`absent`}:classifyGitEntry(w.gitPath,w.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),S=64;if(t.length<=64)return t||`sub`;let w=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${w}`}function djb2(e){let t=5381;for(let S=0;S<e.length;S++)t=t*33+e.charCodeAt(S)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,S){let w=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${w}. Run \`git worktree prune\` from the source repo and try again.`,S),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let S=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${S}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let S of e.split(`
428
+ `)}const AgentWriteRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,content:string$2().optional(),...agentIdentityFields}).loose(),AgentWriteMdRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,markdown:string$2().min(1),position:_enum([`append`,`prepend`,`replace`]).optional(),...agentIdentityFields}).loose(),AgentPatchRequestSchema=object$1({docName:safeDocNameField,summary:summaryField,find:string$2().min(1),replace:string$2(),offset:number$1().int().nonnegative().optional(),...agentIdentityFields}).loose(),AgentUndoRequestSchema=object$1({docName:safeDocNameField,connectionId:string$2().min(1),scope:_enum([`last`,`session`,`file`]).optional(),...agentIdentityFields}).loose(),SummaryResponseFieldSchema=object$1({value:string$2(),truncatedFrom:number$1().int().nonnegative().optional(),hint:string$2().optional()}).loose(),OrphanHintSchema=object$1({type:literal(`orphan`),parentCandidates:array(string$2()),message:string$2()}).loose(),AgentWriteSuccessSchema=object$1({timestamp:string$2().min(1),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentWriteMdSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),hints:array(OrphanHintSchema).optional(),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentPatchSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),summary:SummaryResponseFieldSchema.optional()}).loose(),AgentUndoSuccessSchema=object$1({docName:string$2().min(1),scope:_enum([`last`,`session`]),undone:boolean$1()}).loose(),FrontmatterPatchRequestSchema=object$1({docName:safeDocNameField,patch:record(string$2(),union([FrontmatterValueSchema,_null()])),types:record(string$2(),_enum(FRONTMATTER_TYPES)).optional(),summary:summaryField,...agentIdentityFields}).loose(),FrontmatterPatchSuccessSchema=object$1({timestamp:string$2().min(1),subscriberCount:number$1().int().nonnegative(),systemSubscriberCount:number$1().int().nonnegative(),appliedKeys:array(string$2()),summary:SummaryResponseFieldSchema.optional()}).loose(),LifecycleStatusSchema=object$1({status:string$2().min(1),reason:string$2()}).loose(),DocumentReadSuccessSchema=object$1({docName:string$2().min(1),content:string$2(),lifecycle:LifecycleStatusSchema.nullable()}).loose(),DocumentListEntrySchema=object$1({kind:_enum([`document`,`asset`,`folder`]).default(`document`),docName:string$2().min(1).optional(),docExt:string$2().min(1).default(`.md`),size:number$1().int().nonnegative(),modified:string$2().min(1),isSymlink:boolean$1().default(!1),canonicalDocName:string$2().nullable().default(null),targetPath:string$2().nullable().default(null),path:string$2().min(1).optional(),assetExt:string$2().min(1).optional(),mediaKind:_enum([`image`,`video`,`audio`,`pdf`,`text`]).nullable().optional(),referencedBy:array(string$2().min(1)).optional()}).loose().refine(e=>e.kind===`document`?e.docName!==void 0&&e.path===void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.kind===`folder`?e.docName===void 0&&e.path!==void 0&&e.assetExt===void 0&&e.mediaKind===void 0&&e.referencedBy===void 0:e.path!==void 0&&e.assetExt!==void 0&&e.referencedBy!==void 0,{message:`document/asset/folder kind must match its required fields (document → docName; asset → path+assetExt+referencedBy; folder → path only, no docName)`}),DocumentListSuccessSchema=object$1({documents:array(DocumentListEntrySchema)}).loose(),BacklinkEntrySchema=object$1({source:string$2().min(1),anchor:string$2().nullable(),title:string$2(),snippet:string$2().nullable()}).loose(),BacklinksSuccessSchema=object$1({docName:string$2().min(1),backlinks:array(BacklinkEntrySchema)}).loose(),BacklinkCountsSuccessSchema=object$1({counts:record(string$2().min(1),number$1().int().nonnegative())}).loose(),ForwardLinkDocEntrySchema=object$1({kind:literal(`doc`),docName:string$2().min(1),anchor:string$2().nullable(),title:string$2(),snippet:string$2().nullable()}).loose(),ForwardLinkExternalEntrySchema=object$1({kind:literal(`external`),url:string$2().min(1),title:string$2(),snippet:string$2().nullable()}).loose(),ForwardLinkEntrySchema=discriminatedUnion(`kind`,[ForwardLinkDocEntrySchema,ForwardLinkExternalEntrySchema]),ForwardLinksSuccessSchema=object$1({docName:string$2().min(1),forwardLinks:array(ForwardLinkEntrySchema)}).loose(),LinkGraphDocNodeSchema=object$1({id:string$2().min(1),kind:literal(`doc`),docName:string$2().min(1),anchor:string$2().nullable(),label:string$2(),cluster:string$2().nullable(),category:string$2().nullable(),tags:array(string$2()).nullable()}).loose(),LinkGraphExternalNodeSchema=object$1({id:string$2().min(1),kind:literal(`external`),url:string$2().min(1),label:string$2()}).loose(),LinkGraphNodeSchema=discriminatedUnion(`kind`,[LinkGraphDocNodeSchema,LinkGraphExternalNodeSchema]),LinkGraphEdgeSchema=object$1({source:string$2().min(1),target:string$2().min(1)}).loose(),LinkGraphSuccessSchema=object$1({nodes:array(LinkGraphNodeSchema),links:array(LinkGraphEdgeSchema)}).loose(),SaveVersionWriterSchema=object$1({id:string$2().min(1),name:string$2().optional(),email:string$2().optional()}).loose(),SaveVersionRequestSchema=object$1({writers:array(SaveVersionWriterSchema).optional(),...agentIdentityFields}).loose(),SaveVersionSuccessSchema=object$1({checkpointRef:string$2().min(1)}).loose(),HistoryShadowContributorSchema=object$1({v:number$1().int().optional(),id:string$2().min(1),name:string$2().min(1),colorSeed:string$2().optional(),docs:array(string$2()),summaries:array(string$2()).optional()}).loose(),HistoryEntrySchema=object$1({sha:string$2().min(1),timestamp:string$2().min(1),author:string$2(),authorEmail:string$2(),type:_enum([`checkpoint`,`wip`,`upstream`,`park`]),message:string$2(),contributors:array(HistoryShadowContributorSchema),checkpoint:unknown$2().nullable()}).loose(),HistorySuccessSchema=object$1({entries:array(HistoryEntrySchema),total:number$1().int().nonnegative().optional(),truncated:boolean$1().optional()}).loose(),HistoryVersionSuccessSchema=object$1({sha:string$2().regex(/^[0-9a-f]{40}$/i),content:string$2(),timestamp:string$2(),author:string$2()}).loose(),DiffLineSchema=object$1({type:_enum([`added`,`removed`,`unchanged`]),text:string$2()}).loose(),DiffSuccessSchema=object$1({lines:array(DiffLineSchema),additions:number$1().int().nonnegative(),deletions:number$1().int().nonnegative()}).loose(),WorkspaceSuccessSchema=object$1({contentDir:string$2().min(1),pathSeparator:_enum([`/`,`\\`]),symlinkResolved:boolean$1()}).loose(),RescueEntryFlatSchema=object$1({docName:string$2().min(1),timestamp:string$2().min(1),size:number$1().int().nonnegative(),source:literal(`flat`)}).loose(),RescueEntryTimelineSchema=object$1({docName:string$2().min(1),timestamp:string$2().min(1),source:literal(`timeline`),sha:string$2().min(1)}).loose(),RescueListSuccessSchema=array(discriminatedUnion(`source`,[RescueEntryFlatSchema,RescueEntryTimelineSchema])).meta({description:"Flat array of rescue buffer entries; discriminated via `source`."}),OrphanEntrySchema=object$1({docName:string$2().min(1),title:string$2()}).loose(),OrphansSuccessSchema=object$1({orphans:array(OrphanEntrySchema)}).loose(),HubEntrySchema=object$1({docName:string$2().min(1),title:string$2(),count:number$1().int().nonnegative()}).loose(),HubsSuccessSchema=object$1({hubs:array(HubEntrySchema)}).loose(),DeadLinkSourceSchema=object$1({source:string$2().min(1),title:string$2(),snippet:string$2().nullable()}).loose(),DeadLinkEntrySchema=object$1({target:string$2().min(1),sources:array(DeadLinkSourceSchema)}).loose(),DeadLinksSuccessSchema=object$1({deadLinks:array(DeadLinkEntrySchema)}).loose(),SuggestLinksTargetSchema=object$1({docName:string$2().min(1),title:string$2(),aliases:array(string$2())}).loose(),SuggestLinksMentionSchema=object$1({source:string$2().min(1),excerpt:string$2(),offset:number$1().int().nonnegative()}).loose(),SuggestLinksSuccessSchema=object$1({target:SuggestLinksTargetSchema,mentions:array(SuggestLinksMentionSchema),truncated:boolean$1()}).loose(),LocalOpOpenRequestSchema=object$1({dir:string$2().min(1)}).loose(),LocalOpOpenSuccessSchema=object$1({port:number$1().int().positive()}).loose(),LocalOpOkInitRequestSchema=object$1({projectPath:string$2().min(1)}).loose(),LocalOpOkInitFailureReasonSchema=_enum([`not-a-git-worktree`,`init-failed`]),LocalOpOkInitResponseSchema=discriminatedUnion(`ok`,[object$1({ok:literal(!0),projectPath:string$2().min(1)}).loose(),object$1({ok:literal(!1),reason:LocalOpOkInitFailureReasonSchema,message:string$2().min(1)}).loose()]),LocalOpAuthHostRequestSchema=object$1({host:string$2().min(1).optional()}).loose(),LocalOpAuthPatRequestSchema=object$1({pat:string$2().min(1),host:string$2().min(1).optional()}).loose(),LocalOpAuthSetIdentityRequestSchema=object$1({name:string$2().refine(e=>e.trim().length>0,{message:`name must be non-empty`}),email:string$2().refine(e=>e.trim().length>0,{message:`email must be non-empty`})}).loose(),LocalOpAuthIdentitySchema=object$1({name:string$2().min(1),email:string$2().min(1)}).loose().nullable(),LocalOpAuthIdentitySuccessSchema=object$1({identity:LocalOpAuthIdentitySchema}).loose(),LocalOpAuthStatusSuccessSchema=object$1({authenticated:boolean$1()}).loose(),LocalOpAuthPatSuccessSchema=object$1({type:literal(`complete`).optional(),login:string$2().min(1).optional()}).loose(),LocalOpAuthEmptySuccessSchema=object$1({}).loose(),ActivityBurstSchema=object$1({stackIndex:number$1().int().min(0),ts:number$1().int().min(0),additions:number$1().int().min(0),deletions:number$1().int().min(0)}).loose(),ActivityFileSchema=object$1({docName:string$2().min(1),additionsTotal:number$1().int().min(0),deletionsTotal:number$1().int().min(0),lastTs:number$1().int().min(0),bursts:array(ActivityBurstSchema)}).loose(),ActivityAgentHeaderSchema=object$1({displayName:string$2().min(1),color:string$2().min(1),icon:string$2().optional(),connectionId:string$2().min(1)}).loose(),AgentActivitySuccessSchema=object$1({sessionAlive:boolean$1(),agent:ActivityAgentHeaderSchema.nullable(),files:array(ActivityFileSchema)}).loose(),AgentBurstDiffSuccessSchema=object$1({diff:string$2(),generatedAt:number$1().int().min(0)}).loose(),TestResetSuccessSchema=object$1({}).loose(),TestRescanBacklinksSuccessSchema=object$1({}).loose(),TestRescanFilesSuccessSchema=object$1({}).loose(),MetricsReconciliationSuccessSchema=object$1({}).loose(),MetricsParseHealthSuccessSchema=object$1({}).loose(),AgentPresenceEntrySchema=object$1({displayName:string$2().min(1),icon:string$2(),color:string$2().min(1),currentDoc:string$2().nullable(),mode:_enum([`idle`,`writing`]),ts:number$1().int().min(0)}).loose(),MetricsAgentPresenceSuccessSchema=object$1({presence:record(string$2().min(1),AgentPresenceEntrySchema)}).loose(),InstalledAgentsSuccessSchema=record(string$2().min(1),boolean$1()).meta({description:`Flat boolean record keyed by agent-scheme name (claude / codex / cursor). True = installed.`}),SpawnCursorRequestSchema=object$1({path:string$2().min(1,`path must be non-empty`)}).loose(),SpawnCursorSuccessSchema=object$1({}).loose(),RenamedDocMappingSchema=object$1({fromDocName:string$2().min(1),toDocName:string$2().min(1)}).loose(),RenamedAssetMappingSchema=object$1({fromPath:string$2().min(1),toPath:string$2().min(1)}).loose(),EmptyRequestSchema=object$1({}).loose(),CreatePageRequestSchema=object$1({path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),CreatePageSuccessSchema=object$1({docName:string$2().min(1)}).loose(),CreateFolderRequestSchema=object$1({path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),CreateFolderSuccessSchema=object$1({path:string$2().min(1)}).loose(),DuplicatePathRequestSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),DuplicatePathSuccessSchema=object$1({kind:_enum([`file`,`folder`]),path:string$2().min(1),duplicatedDocNames:array(string$2().min(1))}).loose(),PageEntrySchema=object$1({docName:string$2().min(1),title:string$2(),docExt:string$2().min(1),size:number$1().int().nonnegative(),modified:string$2().min(1),icon:string$2().min(1).max(2048).optional()}).loose(),PagesSuccessSchema=object$1({pages:array(PageEntrySchema)}).loose(),HeadingEntrySchema=object$1({level:number$1().int().min(1).max(6),text:string$2(),slug:string$2()}).loose(),PageHeadingsSuccessSchema=object$1({docName:string$2().min(1),headings:array(HeadingEntrySchema)}).loose(),RenameRequestSchema=object$1({docName:string$2().min(1),newDocName:string$2().min(1),summary:summaryField,...agentIdentityFields}).loose(),RenameRewrittenDocSchema=object$1({docName:string$2().min(1),rewrites:number$1().int().nonnegative()}).loose(),RenameSuccessSchema=object$1({renamed:array(RenamedDocMappingSchema),rewrittenDocs:array(RenameRewrittenDocSchema),summary:SummaryResponseFieldSchema.optional()}).loose(),RenamePathRequestSchema=object$1({kind:_enum([`file`,`folder`,`asset`]),fromPath:string$2().min(1),toPath:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),RenamePathSuccessSchema=object$1({renamed:array(RenamedDocMappingSchema),renamedAssets:array(RenamedAssetMappingSchema),rewrittenDocs:array(RenameRewrittenDocSchema).optional(),summary:SummaryResponseFieldSchema.optional()}).loose(),DeletePathRequestSchema=object$1({kind:_enum([`file`,`folder`,`asset`]),path:string$2().min(1),...agentIdentityFields}).loose(),DeletePathSuccessSchema=object$1({deletedDocNames:array(string$2().min(1))}).loose(),TrashCleanupRequestSchema=object$1({kind:_enum([`file`,`folder`,`asset`]),path:string$2().min(1),...agentIdentityFields,summary:summaryField}).loose(),TrashCleanupSuccessSchema=object$1({deletedDocNames:array(string$2().min(1))}).loose(),RollbackRequestSchema=object$1({docName:string$2().min(1),commitSha:string$2().regex(/^[0-9a-f]{40}$/i,{message:`commitSha must be a 40-char git SHA`}),summary:summaryField,...agentIdentityFields}).loose(),RollbackSuccessSchema=object$1({restoredFrom:string$2().min(1),timestamp:string$2().min(1),summary:SummaryResponseFieldSchema.optional()}).loose(),SyncStateSchema=_enum([`dormant`,`idle`,`fetching`,`pulling`,`pushing`,`conflict`,`offline`,`auth-error`,`disabled`]),SyncRemoteSchema=object$1({label:string$2().min(1),webUrl:url().nullable()}).loose(),PushPermissionSchema=discriminatedUnion(`checkStatus`,[object$1({checkStatus:literal(`allowed`)}).loose(),object$1({checkStatus:literal(`denied`),deniedReason:_enum([`no-collaborator`,`private-no-access`,`repo-not-found`])}).loose(),object$1({checkStatus:literal(`unknown`),unknownError:_enum([`network`,`timeout`,`rate-limit`,`token-invalid`,`malformed-response`]).optional()}).loose()]),SyncStatusSchema=object$1({state:SyncStateSchema,lastSyncUtc:string$2().nullable(),lastFetchUtc:string$2().nullable(),lastPushedSha:string$2().nullable(),ahead:number$1().int().min(0),behind:number$1().int().min(0),consecutiveFailures:number$1().int().min(0),conflictCount:number$1().int().min(0),hasRemote:boolean$1(),syncEnabled:boolean$1(),identityUnresolved:boolean$1(),remote:SyncRemoteSchema.nullable().optional(),error:string$2().optional(),errorCode:_enum([`auth-403`,`auth-401`,`auth-scope-mismatch`,`semantic-protected-branch`]).optional(),pausedReason:string$2().optional(),pushPermission:PushPermissionSchema.optional()}).loose(),SyncTriggerRequestSchema=object$1({op:_enum([`sync`,`push`,`pull`]).optional()}).loose(),SyncTriggerSuccessSchema=object$1({op:_enum([`sync`,`push`,`pull`])}).loose(),ConflictEntrySchema=object$1({file:string$2().min(1),detectedAt:string$2().min(1),oursSha:string$2().optional(),theirsSha:string$2().optional(),baseSha:string$2().optional()}).loose(),SyncConflictsSuccessSchema=object$1({conflicts:array(ConflictEntrySchema)}).loose(),SyncResolveConflictRequestSchema=object$1({file:string$2().min(1),strategy:_enum([`mine`,`theirs`,`content`,`delete`]),content:string$2().optional()}).loose().refine(e=>e.strategy!==`content`||e.content!==void 0&&e.content!==``,{message:`content must be a non-empty string when strategy is 'content'`,path:[`content`]}),SyncResolveConflictSuccessSchema=object$1({}).loose(),SyncConflictContentSuccessSchema=object$1({file:string$2().min(1),base:string$2(),ours:string$2(),theirs:string$2(),kind:_enum([`both-modified`,`delete-modify`,`modify-delete`]),lifecycleStatus:string$2().nullable()}).loose(),SyncAbortMergeSuccessSchema=object$1({}).loose(),SeedPlanSuccessSchema=object$1({plan:custom(e=>e!==void 0,{message:`plan is required`})}).loose(),SeedApplyRequestSchema=object$1({plan:custom(e=>e!==void 0,{message:`plan is required`})}).loose(),SeedApplySuccessSchema=object$1({result:custom(e=>e!==void 0,{message:`result is required`})}).loose(),SeedPackFolderInfoSchema=object$1({path:string$2().min(1),summary:string$2().min(1)}).loose(),SeedPackEntryCountsSchema=object$1({files:number$1().int().nonnegative(),folders:number$1().int().nonnegative()}).loose(),SeedPackInfoSchema=object$1({id:string$2().min(1),name:string$2().min(1),description:string$2().min(1),defaultSubfolder:string$2().optional(),folders:array(SeedPackFolderInfoSchema),entryCounts:SeedPackEntryCountsSchema}).loose(),SeedListPacksSuccessSchema=object$1({packs:array(SeedPackInfoSchema)}).loose(),InstallSkillRequestSchema=object$1({noOpen:boolean$1().optional(),out:string$2().min(1).optional()}).loose(),InstallSkillHandoffErrorSchema=object$1({reason:_enum([`unsupported-platform`,`spawn-error`]),message:string$2()}).loose(),InstallSkillSuccessSchema=discriminatedUnion(`status`,[object$1({status:literal(`installed`),outputPath:string$2(),size:number$1().int().nonnegative(),sha256:string$2(),skillVersion:string$2()}).loose(),object$1({status:literal(`built`),outputPath:string$2(),size:number$1().int().nonnegative(),sha256:string$2(),skillVersion:string$2(),handoffError:InstallSkillHandoffErrorSchema.optional()}).loose(),object$1({status:literal(`failed`),buildError:string$2()}).loose(),object$1({status:literal(`skip-current`),skillVersion:string$2(),recordedAt:string$2().optional()}).loose()]),TagSummaryEntrySchema=object$1({name:string$2().min(1),count:number$1().int().nonnegative(),isLeaf:boolean$1()}).loose(),TagsListSuccessSchema=object$1({tags:array(TagSummaryEntrySchema)}).loose(),TagsDocEntrySchema=object$1({docName:string$2().min(1),title:string$2(),matchingTags:array(string$2().min(1)),snippet:string$2().nullable()}).loose(),TagsForNameSuccessSchema=object$1({name:string$2().min(1),docs:array(TagsDocEntrySchema)}).loose(),FolderConfigGetSuccessSchema=object$1({folder:unknown$2(),frontmatter_local:record(string$2(),unknown$2()).nullable(),frontmatter_sources:record(string$2(),string$2()).optional(),schema_declarations:record(string$2(),unknown$2()).optional(),schema_sources:record(string$2(),string$2()).optional(),schema_local:record(string$2(),unknown$2()).nullable()}).loose(),FolderConfigPutRequestSchema=object$1({path:string$2(),frontmatter:record(string$2(),unknown$2()).optional(),declarations:record(string$2(),unknown$2()).optional()}).loose(),FolderConfigPutSuccessSchema=object$1({applied:unknown$2()}).loose(),TemplateFrontmatterSchema$1=record(string$2(),unknown$2()).meta({description:`Free-form frontmatter map embedded in template payloads.`}),TemplatePayloadSchema=object$1({name:string$2().min(1),folder:string$2(),scope:_enum([`local`,`inherited`]),path:string$2().min(1),frontmatter:TemplateFrontmatterSchema$1,body:string$2()}).strict(),TemplateGetSuccessSchema=object$1({template:TemplatePayloadSchema}).strict(),TemplatePutRequestSchema=object$1({folder:string$2(),name:string$2(),body:string$2().optional(),frontmatter:TemplateFrontmatterSchema$1.optional()}).strict(),TemplatePutSuccessSchema=object$1({path:string$2().min(1),created:boolean$1(),warnings:array(string$2())}).strict(),TemplateDeleteSuccessSchema=object$1({existed:boolean$1(),path:string$2().min(1)}).strict(),SearchRequestSchema=object$1({query:string$2().optional(),intent:_enum([`autocomplete`,`full_text`,`omnibar`]).optional(),scopes:array(_enum([`page`,`folder`,`content`])).optional(),scope:string$2().optional(),limit:number$1().int().nonnegative().optional()}).loose(),SearchResultEntrySchema=object$1({kind:_enum([`page`,`folder`,`content`]),path:string$2().min(1),title:string$2(),score:number$1(),signals:record(string$2(),unknown$2()),snippet:string$2().optional()}).loose(),SearchSuccessSchema=object$1({query:string$2(),intent:_enum([`autocomplete`,`full_text`,`omnibar`]),results:array(SearchResultEntrySchema),elapsedMs:number$1().nonnegative()}).loose(),SkillInstallTargetStateSchema=object$1({version:string$2().min(1),recordedAt:string$2().min(1)}).loose(),SkillInstallStateSuccessSchema=object$1({currentVersion:string$2().min(1),targets:record(string$2(),SkillInstallTargetStateSchema.nullable())}).loose(),CC1_CHANNEL_SERVER_INFO=`server-info`,CC1_CHANNEL_BRANCH_SWITCHED=`branch-switched`,CC1_CHANNEL_DISK_ACK=`disk-ack`,CC1_CHANNEL_CONFIG_VALIDATION_REJECTED=`config-validation-rejected`,CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR=`config-ignore-nested-error`,DerivedViewChannelSchema=_enum([`files`,`backlinks`,`graph`,`sync-status`,`session-activity`,`tags`]),CC1ServerInfoPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_SERVER_INFO),seq:number$1(),serverInstanceId:string$2().min(1),currentBranch:string$2().min(1).optional()}).loose(),CC1BranchSwitchedPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_BRANCH_SWITCHED),seq:number$1(),branch:string$2().min(1)}).loose(),CC1DerivedViewPayloadSchema=object$1({v:literal(1),ch:DerivedViewChannelSchema,seq:number$1()}).loose(),CC1DiskAckPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_DISK_ACK),seq:number$1(),docName:string$2().min(1),sv:string$2().min(1)}).loose(),CC1ConfigValidationRejectedPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_CONFIG_VALIDATION_REJECTED),seq:number$1(),docName:string$2().min(1),error:ConfigValidationErrorSchema}).loose(),CC1ConfigIgnoreNestedErrorPayloadSchema=object$1({v:literal(1),ch:literal(CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR),seq:number$1(),path:string$2().min(1),error:string$2().min(1)}).loose(),WORKSPACE_SEARCH_SCHEMA={id:`string`,kind:`enum`,path:`string`,title:`string`,name:`string`,pathSegments:`string`,content:`string`,modifiedTs:`number`},workspaceSearchIndexes=new WeakMap;function clampLimit(e){return e===void 0||!Number.isFinite(e)?20:Math.max(1,Math.min(100,Math.trunc(e)))}function normalize$2(e){return e.trim().toLowerCase()}function workspaceSearchBasename(e){let t=e.split(`/`).filter(Boolean);return t[t.length-1]??e}function workspaceSearchPathSegments(e){return e.split(`/`).filter(Boolean).join(` `)}function createWorkspaceSearchDocument(e){let t=workspaceSearchBasename(e.path),S=e.title?.trim()||t,w=e.modifiedTs??0;return{id:`${e.kind}:${e.path}`,kind:e.kind,path:e.path,title:S,name:t,pathSegments:workspaceSearchPathSegments(e.path),content:e.content??``,modifiedTs:Number.isFinite(w)?w:0}}function createWorkspaceSearchIndex(e){let t=create$9({schema:WORKSPACE_SEARCH_SCHEMA});return e.length>0&&insertMultiple(t,e),t}function createWorkspaceSearchCorpus(e){let t={documents:e};return workspaceSearchIndexes.set(t,createWorkspaceSearchIndex(e)),t}function getWorkspaceSearchIndex(e){let t=workspaceSearchIndexes.get(e);if(t)return t;let S=createWorkspaceSearchIndex(e.documents);return workspaceSearchIndexes.set(e,S),S}function defaultScopes(e){return e===`autocomplete`?[`page`]:e===`full_text`?[`page`,`content`]:[`page`,`folder`]}function scopeAllows(e,t){return t.has(e.kind)?!0:e.kind===`page`&&t.has(`content`)}function lexicalScore(e,t){let S=normalize$2(t);if(!S)return 0;let w=normalize$2(e.title),E=normalize$2(e.name),D=normalize$2(e.path),O=D.split(`/`);return w===S||E===S?700:D===S?650:w.startsWith(S)||E.startsWith(S)?600:O.some(e=>e.startsWith(S))?550:w.includes(S)||E.includes(S)?500:D.includes(S)?450:-1}function recencyScores(e){let t=e.map(e=>e.modifiedTs).filter(e=>Number.isFinite(e)&&e>0);if(t.length===0)return new Map;let S=1/0,w=-1/0;for(let e of t)e<S&&(S=e),e>w&&(w=e);let E=Math.max(1,w-S);return new Map(e.map(e=>[e.id,e.modifiedTs>0?(e.modifiedTs-S)/E*50:0]))}function searchProperties(e){return e===`full_text`?[`title`,`name`,`path`,`pathSegments`,`content`]:[`title`,`name`,`path`,`pathSegments`]}function searchBoost(e){return e===`full_text`?{title:8,name:7,path:5,pathSegments:4,content:1}:e===`autocomplete`?{title:10,name:9,path:5,pathSegments:4}:{title:8,name:7,path:5,pathSegments:4}}function toleranceFor(e,t){return normalize$2(t).length<4?0:e===`full_text`?1:0}function searchWorkspaceCorpus(e,t,S={}){let w=S.intent??`omnibar`,E=clampLimit(S.limit),D=new Set(S.scopes??defaultScopes(w)),O=e.documents.filter(e=>scopeAllows(e,D)),k=normalize$2(t);if(!k)return O.slice().sort((e,t)=>e.path.localeCompare(t.path)).slice(0,E).map(e=>({document:e,score:0,signals:{lexical:0,fullText:0,recency:0}}));let j=search(getWorkspaceSearchIndex(e),{term:k,properties:searchProperties(w),boost:searchBoost(w),tolerance:toleranceFor(w,k),limit:Math.max(E*4,40)}),F=new Map(j.hits.filter(e=>scopeAllows(e.document,D)).map(e=>[e.document.id,e.score])),L=recencyScores(O),B=new Map;for(let e of O)lexicalScore(e,k)>=0&&B.set(e.id,e);for(let e of j.hits)scopeAllows(e.document,D)&&B.set(e.document.id,e.document);return[...B.values()].map(e=>{let t=Math.max(0,lexicalScore(e,k)),S=F.get(e.id)??0,w=L.get(e.id)??0;return{document:e,score:t+S*20+w,signals:{lexical:t,fullText:S,recency:w}}}).sort((e,t)=>e.score===t.score?e.document.path.localeCompare(t.document.path):t.score-e.score).slice(0,E)}const SHARE_URL_VERSION_V1=1;function encodeShareUrl(e){let t=new TextEncoder().encode(e),S=new Uint8Array(1+t.length);return S[0]=SHARE_URL_VERSION_V1,S.set(t,1),uint8ArrayToBase64Url(S)}function uint8ArrayToBase64Url(e){let t=``;for(let S=0;S<e.length;S++)t+=String.fromCharCode(e[S]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}const SINGLETON_KEY=Symbol.for(`@inkeep/open-knowledge/skill-state-field-registry`),g=globalThis;g[SINGLETON_KEY]===void 0&&(g[SINGLETON_KEY]=registry$1());const skillStateFieldRegistry=g[SINGLETON_KEY],SKILL_STATE_FILENAME=`skill-state.yml`,SKILL_STATE_REL=[`.ok`,SKILL_STATE_FILENAME],SKILL_STATE_TARGETS=[`claude-cowork`,`cli-hosts`],SKILL_STATE_SURFACES=[`server-build-and-open`,`electron-build-and-open`,`cli-npx-skills-add`,`desktop-direct`,`cli-start`],SKILL_STATE_VERSION_RE=/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/,TargetEntrySchema=looseObject({version:string$2().regex(SKILL_STATE_VERSION_RE,`version must match /^\\d+\\.\\d+\\.\\d+(?:[-+][\\w.-]+)?$/`).register(skillStateFieldRegistry,{description:`Recorded skill version for this target.`}),recordedAt:datetime().register(skillStateFieldRegistry,{description:`ISO 8601 timestamp of the most recent successful write. Updated on every write, including reinstalls of the same version.`}),surface:_enum(SKILL_STATE_SURFACES).register(skillStateFieldRegistry,{description:`Install-source surface that recorded this entry.`}).optional()}),SkillStateSchema=looseObject({schema:literal(1).register(skillStateFieldRegistry,{description:`Schema major version. Bumped only on breaking shape changes.`}),targets:looseObject({"claude-cowork":TargetEntrySchema.optional(),"cli-hosts":TargetEntrySchema.optional()}).register(skillStateFieldRegistry,{description:`Per-target install-state entries. Absent target = no recorded install.`}).default({})});function emptySkillState(){return{schema:1,targets:{}}}function createCodeFenceTracker(){let e=!1,t=``,S=0;return w=>{let E=parseCodeFenceLine(w);return e?(E&&E.char===t&&E.len>=S&&!E.hasInfo&&(e=!1,t=``,S=0),!0):E?(e=!0,t=E.char,S=E.len,!0):!1}}function parseCodeFenceLine(e){let t=(e.endsWith(`\r`)?e.slice(0,-1):e).match(/^ {0,3}([`~])(\1{2,})(.*)$/);return t?{char:t[1],len:1+t[2].length,hasInfo:t[3].trim()!==``}:null}const AGENT_COLORS=[`#D97757`,`#1B1912`,`#F9F3E9`,`#7A9DFF`,`#8534F3`,`#9663F0`,`#727CF3`],AGENT_ICON_COLORS={claude:`#D97757`,cursor:`#1B1912`,windsurf:`#0B100F`,openai:`#7A9DFF`,github:`#8534F3`,cline:`#9663F0`,bot:`#727CF3`};function colorFromSeed(e,t=AGENT_COLORS){let S=0;for(let t of e)S=(S<<5)-S+t.charCodeAt(0)|0;return t[Math.abs(S)%t.length]}const ICON_MAP={"claude-code":`claude`,"claude-ai":`claude`,cursor:`cursor`,"cursor-vscode":`cursor`,cascade:`windsurf`,codex:`openai`,"codex-mcp-client":`openai`,copilot:`github`,cline:`cline`};function iconFromClientName(e){return e?ICON_MAP[e]||(e.startsWith(`local-agent-mode-`)?`claude`:`bot`):`bot`}const BRAND_NAME={claude:`Claude`,cursor:`Cursor`,windsurf:`Windsurf`,openai:`Codex`,github:`Copilot`,cline:`Cline`};function displayNameFromClientName(e){let t=e?.trim();return t?BRAND_NAME[iconFromClientName(t)]??t:`Agent`}function resolveInternalHref(e,t){let S=e.trim();if(!S||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(S)||S.startsWith(`//`)||S.startsWith(`/`)||S.startsWith(`#`))return null;let w=S.indexOf(`#`),E=w>=0?S.slice(0,w):S,D=w>=0?S.slice(w+1):null,O=(E.split(`?`)[0]??``).trim();if(!O)return null;let k=(O.split(`/`).pop()??``).match(/\.([a-z0-9]+)$/i);if(k){let e=(k[1]??``).toLowerCase();if(e!==`md`&&e!==`mdx`)return null}let j=O.toLowerCase(),F=j.endsWith(`.mdx`)?O.slice(0,-4):j.endsWith(`.md`)?O.slice(0,-3):O,L=t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of F.split(`/`))if(e===`..`){if(L.length===0)return null;L.pop()}else e!==`.`&&e!==``&&L.push(e);return L.length===0?null:{docName:L.join(`/`),anchor:D||null}}const URI_SCHEME_RE=/^[a-zA-Z][a-zA-Z\d+\-.]*:/;function extractAssetExtension(e){let t=(e.split(/[?#]/)[0]??e).match(/\.([a-z0-9]+)$/i);return t?(t[1]??``).toLowerCase():null}function isExternalHref(e){let t=e.trim();return URI_SCHEME_RE.test(t)||t.startsWith(`//`)}function classifyMarkdownHref(e,t){let S=e.trim();if(!S)return null;if(S.startsWith(`#`)){let e=S.slice(1).trim();return e?{kind:`anchor`,anchor:e}:null}let w=resolveInternalHref(S,t);if(w)return{kind:`doc`,docName:w.docName,anchor:w.anchor};if(isExternalHref(S)||S.startsWith(`/`))return{kind:`external`,url:S};let E=extractAssetExtension(S);return E&&E!==`md`&&E!==`mdx`?{kind:`asset`,url:S,ext:E}:null}function classifyWikiLinkTarget(e,t){let S=e.trim();if(!S)return null;if(isExternalHref(S))return{kind:`external`,url:t?`${S}#${t}`:S};let w=extractAssetExtension(S);return w&&w!==`md`&&w!==`mdx`?{kind:`asset`,url:S,ext:w}:{kind:`doc`,docName:S,anchor:t?.trim()||null}}function resolveAssetProjectPath(e,t){let S=e.trim();if(!S||URI_SCHEME_RE.test(S)||S.startsWith(`//`)||S.startsWith(`#`))return null;let w=S.indexOf(`#`),E=((w>=0?S.slice(0,w):S).split(`?`)[0]??``).trim();if(!E)return null;let D=E.startsWith(`/`),O=D?E.slice(1):E,k=D?[]:t.includes(`/`)?t.split(`/`).slice(0,-1):[];for(let e of O.split(`/`))if(e===`..`){if(k.length===0)return null;k.pop()}else e!==`.`&&e!==``&&k.push(e);return k.length===0?null:k.join(`/`)}function normalizePath(e){let t=e;return t.startsWith(`./`)&&(t=t.slice(2)),t.startsWith(`/`)&&(t=t.slice(1)),t}function basenameOf(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function dirnameOf(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function splitSegments(e){return e.split(`/`).filter(e=>e!==``)}function isInSubtree(e,t){let S=dirnameOf(t);return e===``||S===e?!0:S.startsWith(`${e}/`)}function depthInSubtree(e,t){let S=dirnameOf(t);if(e===S)return 0;let w=e===``?S:S.slice(e.length+1);return w===``?0:splitSegments(w).length}function relativeHops(e,t){let S=splitSegments(e),w=splitSegments(t),E=0;for(;E<S.length&&E<w.length&&S[E]===w[E];)E++;return S.length-E+(w.length-E)}function createBasenameIndex(){let e=new Map;function t(t){let S=normalizePath(t);if(S===``)return;let w=basenameOf(S);if(w===``)return;let E=w.toLowerCase(),D=e.get(E);if(!D){e.set(E,[S]);return}D.includes(S)||D.push(S)}function S(t){let S=normalizePath(t),w=basenameOf(S).toLowerCase(),E=e.get(w);if(!E)return;let D=E.indexOf(S);D!==-1&&(E.splice(D,1),E.length===0&&e.delete(w))}function w(e,w){S(e),t(w)}function E(t,S){let w=t.toLowerCase(),E=e.get(w);if(!E||E.length===0)return null;if(E.length===1)return E[0];let D=dirnameOf(normalizePath(S)),O=[],k=[];for(let e of E)isInSubtree(D,e)?O.push(e):k.push(e);return O.length>0?(e=>{let t=e[0],S=depthInSubtree(D,t);for(let w=1;w<e.length;w++){let E=e[w],O=depthInSubtree(D,E);(O<S||O===S&&E<t)&&(t=E,S=O)}return t})(O):(e=>{let t=e[0],S=relativeHops(D,dirnameOf(t));for(let w=1;w<e.length;w++){let E=e[w],O=relativeHops(D,dirnameOf(E));(O<S||O===S&&E<t)&&(t=E,S=O)}return t})(k)}function D(){let t=new Map;for(let[S,w]of e)t.set(S,[...w]);return t}function O(){e.clear()}return{add:t,remove:S,rename:w,resolveEmbed:E,clear:O,snapshot:D,size:()=>e.size}}const TAG_HIERARCHY_SEPARATOR=`/`;function expandTagToHierarchy(e){if(!e)return[];let t=e.split(TAG_HIERARCHY_SEPARATOR),S=[],w=``;for(let e of t)w=w?`${w}${TAG_HIERARCHY_SEPARATOR}${e}`:e,S.push(w);return S}function tagsMatchingPrefix(e,t){if(e.size===0)return new Set;if(t===``)return new Set(e);let S=new Set,w=`${t}${TAG_HIERARCHY_SEPARATOR}`;for(let E of e)(E===t||E.startsWith(w))&&S.add(E);return S}const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function classifyGitEntry(e,t,S){let w;try{w=statSync(e)}catch(t){let S=t.code;return S===`ENOENT`||S===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let E=computeProjectSubPath(t,S);if(w.isDirectory())return{kind:`directory`,path:e,projectSubPath:E};if(w.isFile()){let S;try{S=readFileSync(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let w=S.match(/^gitdir:\s*(.+)$/);return w?{kind:`linked`,path:resolve(t,w[1]),gitPath:e,projectSubPath:E}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function computeProjectSubPath(e,t){let S=relative(e,t);return S===``||S===`.`||S.startsWith(`..`)||isAbsolute(S)?``:S}function findAncestorGitEntry(e){let t=homedir(),S=resolve(e),w=64;for(let e=0;e<64;e++){if(S===t)return null;let e=dirname(S);if(e===S||e===t)return null;let w=resolve(e,`.git`);try{let t=statSync(w);if(t.isDirectory()||t.isFile())return{gitPath:w,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${w} (${t??`unknown`}); skipping ancestor`)}S=e}return null}function resolveGitDirDetailed(e){let t=resolve(e),S=classifyGitEntry(resolve(t,`.git`),t,t);if(S.kind!==`absent`)return S;let w=findAncestorGitEntry(t);return w===null?{kind:`absent`}:classifyGitEntry(w.gitPath,w.workTreeRoot,t)}function resolveGitDir(e){let t=resolveGitDirDetailed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function resolveShadowDir(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return resolve(t.path,shadowSubdirName(t.projectSubPath));case`linked`:if(!existsSync(t.path))throw new MalformedGitPointerError(t.gitPath,t.path);return resolve(t.path,shadowSubdirName(t.projectSubPath));case`malformed-pointer`:throw new MalformedGitPointerError(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new GitDirAccessError(t.gitPath,{cause:t.cause});case`absent`:return resolve(e,`.git/ok`)}}function shadowSubdirName(e){return e===``?`ok`:`ok-${slugifyShadowSubPath(e)}`}function slugifyShadowSubPath(e){let t=e.split(sep).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`),S=64;if(t.length<=64)return t||`sub`;let w=djb2(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${w}`}function djb2(e){let t=5381;for(let S=0;S<e.length;S++)t=t*33+e.charCodeAt(S)>>>0;return t}var MalformedGitPointerError=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,S){let w=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${w}. Run \`git worktree prune\` from the source repo and try again.`,S),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},GitDirAccessError=class extends Error{gitPath;constructor(e,t){let S=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${S}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function getShadowRepoPath(e){let t;try{t=resolveShadowDir(e)}catch(e){if(e instanceof MalformedGitPointerError||e instanceof GitDirAccessError)return null;throw e}return existsSync(resolve(t,`HEAD`))?t:null}function getWipRefPattern(e){return`refs/wip/${e}/`}const OK_CONTRIBUTORS_PREFIX=`ok-contributors: `;function parseContributors(e){if(!e)return[];let t=[];for(let S of e.split(`
429
429
  `)){let e=S.trim();if(e.startsWith(OK_CONTRIBUTORS_PREFIX))try{let S=JSON.parse(e.slice(17));if(typeof S==`object`&&S&&`id`in S&&typeof S.id==`string`&&`name`in S&&typeof S.name==`string`&&`docs`in S&&Array.isArray(S.docs)&&S.docs.every(e=>typeof e==`string`)&&(!(`colorSeed`in S)||typeof S.colorSeed==`string`)){let e=S;if(`summaries`in e){let t=e.summaries;(!Array.isArray(t)||!t.every(e=>typeof e==`string`))&&delete e.summaries}t.push(S)}}catch{}}return t}const OK_CHECKPOINT_PREFIX=`ok-checkpoint-v1: `;function parseCheckpoint(e){if(!e)return null;for(let t of e.split(`
430
430
  `)){let e=t.trim();if(!e.startsWith(OK_CHECKPOINT_PREFIX))continue;let S;try{S=JSON.parse(e.slice(18))}catch{return null}if(typeof S!=`object`||!S)return null;let w=S,E=w.kind,D=w.metadata;if(typeof D!=`object`||!D)return null;let O=typeof w.docName==`string`?w.docName:null,k=typeof w.size==`number`&&Number.isFinite(w.size)?w.size:null;if(E===`bridge-merge-loss`){let e=D;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:O,size:k,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(E===`external-change-rescue`){let e=D;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:O,size:k,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}return null}return null}function formatCheckpointBodyLine(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${OK_CHECKPOINT_PREFIX}${JSON.stringify(t)}`}const OK_ACTOR_PREFIX=`ok-actor: `;function formatOkActor(e){let{summaries:t,previous_paths:S,...w}=e,E={...w};return t&&t.length>0&&(E.summaries=t),S&&S.length>0&&(E.previous_paths=S),`${OK_ACTOR_PREFIX}${JSON.stringify(E)}`}function parseOkActorObject(e){if(e.v!==1||!(`display_name`in e)||typeof e.display_name!=`string`||!(`docs`in e)||!Array.isArray(e.docs))return null;let t=typeof e.principal==`string`?e.principal:null,S=typeof e.agent_session==`string`?e.agent_session:null,w;if(typeof e.writer_id==`string`&&e.writer_id.length>0)w=e.writer_id;else if(S)w=`agent-${S}`;else if(t)w=t;else switch(e.display_name){case`File System`:w=`file-system`;break;case`Git (upstream)`:w=`git-upstream`;break;default:w=`openknowledge-service`}let E=`summaries`in e&&Array.isArray(e.summaries)&&e.summaries.every(e=>typeof e==`string`)?e.summaries:void 0,D=parsePreviousPaths(e);return{v:1,writer_id:w,principal:t,agent_session:S,agent_type:typeof e.agent_type==`string`?e.agent_type:null,client_name:typeof e.client_name==`string`?e.client_name:null,client_version:typeof e.client_version==`string`?e.client_version:null,label:typeof e.label==`string`?e.label:null,display_name:e.display_name,color_seed:typeof e.color_seed==`string`?e.color_seed:`unknown`,docs:e.docs.filter(e=>typeof e==`string`),...E&&E.length>0?{summaries:E}:{},...D&&D.length>0?{previous_paths:D}:{}}}function parsePreviousPaths(e){if(!(`previous_paths`in e)||!Array.isArray(e.previous_paths))return;let t=[];for(let S of e.previous_paths){if(typeof S!=`object`||!S)continue;let e=S;typeof e.from!=`string`||typeof e.to!=`string`||t.push({from:e.from,to:e.to})}return t}function parseOkActors(e){if(!e)return[];let t=[];for(let S of e.split(`
431
431
  `)){let e=S.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let w;try{w=JSON.parse(e.slice(10))}catch{continue}if(typeof w!=`object`||!w)continue;let E=parseOkActorObject(w);E&&t.push(E)}return t}function okActorToShadowContributor(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function readContributors(e){let t=parseOkActors(e);return t.length>0?t.map(okActorToShadowContributor):parseContributors(e)}function formatWipSubject(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function formatReconcileSubject(e){return`reconcile: ${e}`}function formatRollbackSubject(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function formatParkSubject(e,t){return`park: ${e} -> ${t}`}function formatRenameSubject(e,t){return`rename: ${e} -> ${t}`}function formatCheckpointSubject(e){return`checkpoint: ${e}`}function formatImportSubject(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const SUBJECT_LINE_BREAK_RE=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function stripLineBreaks(e){return e.replace(SUBJECT_LINE_BREAK_RE,` `)}function composeCommitSubject(e,t){let S=stripLineBreaks(e);if(t.length===0)return S;if(t.length>=2)return`${S} (${t.length} edits)`;let[w]=t;if(w===void 0)return S;let E=stripLineBreaks(w),D=`${S} — ${E}`;if(D.length<=72)return D;let O=`${S} — `,k=72-O.length-1;return k<=0?D.slice(0,72):`${O}${E.slice(0,k)}…`}function parseWriterId(e){return WRITER_ID_RE.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}const create$8=()=>new Map,copy=e=>{let t=create$8();return e.forEach((e,S)=>{t.set(S,e)}),t},setIfUndefined$1=(e,t,S)=>{let w=e.get(t);return w===void 0&&e.set(t,w=S()),w},any=(e,t)=>{for(let[S,w]of e)if(t(w,S))return!0;return!1},create$7=()=>new Set,last=e=>e[e.length-1],appendTo=(e,t)=>{for(let S=0;S<t.length;S++)e.push(t[S])},from$1=Array.from,some=(e,t)=>{for(let S=0;S<e.length;S++)if(t(e[S],S,e))return!0;return!1},isArray$1=Array.isArray;var ObservableV2=class{constructor(){this._observers=create$8()}on(e,t){return setIfUndefined$1(this._observers,e,create$7).add(t),t}once(e,t){let S=(...w)=>{this.off(e,S),t(...w)};this.on(e,S)}off(e,t){let S=this._observers.get(e);S!==void 0&&(S.delete(t),S.size===0&&this._observers.delete(e))}emit(e,t){return from$1((this._observers.get(e)||create$8()).values()).forEach(e=>e(...t))}destroy(){this._observers=create$8()}};const floor$2=Math.floor,abs=Math.abs,min$2=(e,t)=>e<t?e:t,max$2=(e,t)=>e>t?e:t,isNaN$2=Number.isNaN,isNegativeZero=e=>e===0?1/e<0:e<0,BIT1=1,BIT2=2,BIT3=4,BIT4=8,BIT6=32,BIT7=64,BIT8$2=128,BIT18$2=1<<17,BIT19$2=1<<18,BIT20$2=1<<19,BIT21$2=1<<20,BIT22$2=1<<21,BIT23$2=1<<22,BIT24$2=1<<23,BIT25$2=1<<24,BIT26$2=1<<25,BIT27$2=1<<26,BIT28$2=1<<27,BIT29$2=1<<28,BIT30$2=1<<29,BIT31$2=1<<30,BITS5=31,BITS6=63,BITS7$2=127,BITS17=BIT18$2-1,BITS18=BIT19$2-1,BITS19=BIT20$2-1,BITS20=BIT21$2-1,BITS21=BIT22$2-1,BITS22=BIT23$2-1,BITS23=BIT24$2-1,BITS24=BIT25$2-1,BITS25=BIT26$2-1,BITS26=BIT27$2-1,BITS27=BIT28$2-1,BITS28=BIT29$2-1,BITS29=BIT30$2-1,BITS30=BIT31$2-1,BITS31=2147483647,BITS32=4294967295,MAX_SAFE_INTEGER$2=2**53-1,MIN_SAFE_INTEGER=-(2**53-1),HIGHEST_INT32=BITS31,HIGHEST_UINT32=BITS32,isInteger=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&floor$2(e)===e),isNaN$1=Number.isNaN,parseInt$1=Number.parseInt,fromCharCode$2=String.fromCharCode,fromCodePoint=String.fromCodePoint,MAX_UTF16_CHARACTER=fromCharCode$2(65535),toLowerCase=e=>e.toLowerCase(),trimLeftRegex=/^\s*/g,trimLeft=e=>e.replace(trimLeftRegex,``),fromCamelCaseRegex=/([A-Z])/g,fromCamelCase=(e,t)=>trimLeft(e.replace(fromCamelCaseRegex,e=>`${t}${toLowerCase(e)}`)),_encodeUtf8Polyfill$2=e=>{let t=unescape(encodeURIComponent(e)),S=t.length,w=new Uint8Array(S);for(let e=0;e<S;e++)w[e]=t.codePointAt(e);return w},utf8TextEncoder$2=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native$2=e=>utf8TextEncoder$2.encode(e),encodeUtf8$2=utf8TextEncoder$2?_encodeUtf8Native$2:_encodeUtf8Polyfill$2;let utf8TextDecoder$2=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder$2&&utf8TextDecoder$2.decode(new Uint8Array).length===1&&(utf8TextDecoder$2=null);var Encoder$1=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const createEncoder$1=()=>new Encoder$1,encode=e=>{let t=createEncoder$1();return e(t),toUint8Array$1(t)},length$1=e=>{let t=e.cpos;for(let S=0;S<e.bufs.length;S++)t+=e.bufs[S].length;return t},toUint8Array$1=e=>{let t=new Uint8Array(length$1(e)),S=0;for(let w=0;w<e.bufs.length;w++){let E=e.bufs[w];t.set(E,S),S+=E.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),S),t},verifyLen=(e,t)=>{let S=e.cbuf.length;S-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(max$2(S,t)*2),e.cpos=0)},write$2=(e,t)=>{let S=e.cbuf.length;e.cpos===S&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(S*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeUint8=write$2,writeVarUint$2=(e,t)=>{for(;t>127;)write$2(e,128|127&t),t=floor$2(t/128);write$2(e,127&t)},writeVarInt=(e,t)=>{let S=isNegativeZero(t);for(S&&(t=-t),write$2(e,(t>63?128:0)|(S?64:0)|63&t),t=floor$2(t/64);t>0;)write$2(e,(t>127?128:0)|127&t),t=floor$2(t/128)},_strBuffer$2=new Uint8Array(3e4),_maxStrBSize$2=_strBuffer$2.length/3,_writeVarStringNative$2=(e,t)=>{if(t.length<_maxStrBSize$2){let S=utf8TextEncoder$2.encodeInto(t,_strBuffer$2).written||0;writeVarUint$2(e,S);for(let t=0;t<S;t++)write$2(e,_strBuffer$2[t])}else writeVarUint8Array$2(e,encodeUtf8$2(t))},_writeVarStringPolyfill$2=(e,t)=>{let S=unescape(encodeURIComponent(t)),w=S.length;writeVarUint$2(e,w);for(let t=0;t<w;t++)write$2(e,S.codePointAt(t))},writeVarString$2=utf8TextEncoder$2&&utf8TextEncoder$2.encodeInto?_writeVarStringNative$2:_writeVarStringPolyfill$2,writeUint8Array$2=(e,t)=>{let S=e.cbuf.length,w=e.cpos,E=min$2(S-w,t.length),D=t.length-E;e.cbuf.set(t.subarray(0,E),w),e.cpos+=E,D>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max$2(S*2,D)),e.cbuf.set(t.subarray(E)),e.cpos=D)},writeVarUint8Array$2=(e,t)=>{writeVarUint$2(e,t.byteLength),writeUint8Array$2(e,t)},writeOnDataView=(e,t)=>{verifyLen(e,t);let S=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,S},writeFloat32=(e,t)=>writeOnDataView(e,4).setFloat32(0,t,!1),writeFloat64=(e,t)=>writeOnDataView(e,8).setFloat64(0,t,!1),writeBigInt64=(e,t)=>writeOnDataView(e,8).setBigInt64(0,t,!1),floatTestBed=new DataView(new ArrayBuffer(4)),isFloat32=e=>(floatTestBed.setFloat32(0,e),floatTestBed.getFloat32(0)===e),writeAny=(e,t)=>{switch(typeof t){case`string`:write$2(e,119),writeVarString$2(e,t);break;case`number`:isInteger(t)&&abs(t)<=2147483647?(write$2(e,125),writeVarInt(e,t)):isFloat32(t)?(write$2(e,124),writeFloat32(e,t)):(write$2(e,123),writeFloat64(e,t));break;case`bigint`:write$2(e,122),writeBigInt64(e,t);break;case`object`:if(t===null)write$2(e,126);else if(isArray$1(t)){write$2(e,117),writeVarUint$2(e,t.length);for(let S=0;S<t.length;S++)writeAny(e,t[S])}else if(t instanceof Uint8Array)write$2(e,116),writeVarUint8Array$2(e,t);else{write$2(e,118);let S=Object.keys(t);writeVarUint$2(e,S.length);for(let w=0;w<S.length;w++){let E=S[w];writeVarString$2(e,E),writeAny(e,t[E])}}break;case`boolean`:write$2(e,t?120:121);break;default:write$2(e,127)}};var RleEncoder=class extends Encoder$1{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&writeVarUint$2(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};const flushUintOptRleEncoder=e=>{e.count>0&&(writeVarInt(e.encoder,e.count===1?e.s:-e.s),e.count>1&&writeVarUint$2(e.encoder,e.count-2))};var UintOptRleEncoder=class{constructor(){this.encoder=new Encoder$1,this.s=0,this.count=0}write(e){this.s===e?this.count++:(flushUintOptRleEncoder(this),this.count=1,this.s=e)}toUint8Array(){return flushUintOptRleEncoder(this),toUint8Array$1(this.encoder)}};const flushIntDiffOptRleEncoder=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);writeVarInt(e.encoder,t),e.count>1&&writeVarUint$2(e.encoder,e.count-2)}};var IntDiffOptRleEncoder=class{constructor(){this.encoder=new Encoder$1,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(flushIntDiffOptRleEncoder(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return flushIntDiffOptRleEncoder(this),toUint8Array$1(this.encoder)}},StringEncoder=class{constructor(){this.sarr=[],this.s=``,this.lensE=new UintOptRleEncoder}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(e.length)}toUint8Array(){let e=new Encoder$1;return this.sarr.push(this.s),this.s=``,writeVarString$2(e,this.sarr.join(``)),writeUint8Array$2(e,this.lensE.toUint8Array()),toUint8Array$1(e)}};const create$6=e=>Error(e),methodUnimplemented=()=>{throw create$6(`Method unimplemented`)},unexpectedCase=()=>{throw create$6(`Unexpected case`)},errorUnexpectedEndOfArray$2=create$6(`Unexpected end of array`),errorIntegerOutOfRange$2=create$6(`Integer out of Range`);var Decoder$1=class{constructor(e){this.arr=e,this.pos=0}};const createDecoder$1=e=>new Decoder$1(e),hasContent$1=e=>e.pos!==e.arr.length,readUint8Array$1=(e,t)=>{let S=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,S},readVarUint8Array$1=e=>readUint8Array$1(e,readVarUint$1(e)),readUint8$1=e=>e.arr[e.pos++],readVarUint$1=e=>{let t=0,S=1,w=e.arr.length;for(;e.pos<w;){let w=e.arr[e.pos++];if(t+=(w&127)*S,S*=128,w<128)return t;if(t>MAX_SAFE_INTEGER$2)throw errorIntegerOutOfRange$2}throw errorUnexpectedEndOfArray$2},readVarInt=e=>{let t=e.arr[e.pos++],S=t&63,w=64,E=(t&64)>0?-1:1;if(!(t&128))return E*S;let D=e.arr.length;for(;e.pos<D;){if(t=e.arr[e.pos++],S+=(t&127)*w,w*=128,t<128)return E*S;if(S>MAX_SAFE_INTEGER$2)throw errorIntegerOutOfRange$2}throw errorUnexpectedEndOfArray$2},_readVarStringPolyfill$1=e=>{let t=readVarUint$1(e);if(t===0)return``;{let S=String.fromCodePoint(readUint8$1(e));if(--t<100)for(;t--;)S+=String.fromCodePoint(readUint8$1(e));else for(;t>0;){let w=t<1e4?t:1e4,E=e.arr.subarray(e.pos,e.pos+w);e.pos+=w,S+=String.fromCodePoint.apply(null,E),t-=w}return decodeURIComponent(escape(S))}},_readVarStringNative$1=e=>utf8TextDecoder$2.decode(readVarUint8Array$1(e)),readVarString$1=utf8TextDecoder$2?_readVarStringNative$1:_readVarStringPolyfill$1,readFromDataView=(e,t)=>{let S=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,S},readFloat32=e=>readFromDataView(e,4).getFloat32(0,!1),readFloat64=e=>readFromDataView(e,8).getFloat64(0,!1),readBigInt64=e=>readFromDataView(e,8).getBigInt64(0,!1),readAnyLookupTable=[e=>void 0,e=>null,readVarInt,readFloat32,readFloat64,readBigInt64,e=>!1,e=>!0,readVarString$1,e=>{let t=readVarUint$1(e),S={};for(let w=0;w<t;w++){let t=readVarString$1(e);S[t]=readAny(e)}return S},e=>{let t=readVarUint$1(e),S=[];for(let w=0;w<t;w++)S.push(readAny(e));return S},readVarUint8Array$1],readAny=e=>readAnyLookupTable[127-readUint8$1(e)](e);var RleDecoder=class extends Decoder$1{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),hasContent$1(this)?this.count=readVarUint$1(this)+1:this.count=-1),this.count--,this.s}},UintOptRleDecoder=class extends Decoder$1{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=readVarInt(this);let e=isNegativeZero(this.s);this.count=1,e&&(this.s=-this.s,this.count=readVarUint$1(this)+2)}return this.count--,this.s}},IntDiffOptRleDecoder=class extends Decoder$1{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=readVarInt(this),t=e&1;this.diff=floor$2(e/2),this.count=1,t&&(this.count=readVarUint$1(this)+2)}return this.s+=this.diff,this.count--,this.s}},StringDecoder=class{constructor(e){this.decoder=new UintOptRleDecoder(e),this.str=readVarString$1(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}};const subtle=webcrypto.subtle,getRandomValues=webcrypto.getRandomValues.bind(webcrypto),uint32=()=>getRandomValues(new Uint32Array(1))[0],uuidv4Template=`10000000-1000-4000-8000-100000000000`,uuidv4=()=>uuidv4Template.replace(/[018]/g,e=>(e^uint32()&15>>e/4).toString(16)),getUnixTime$1=Date.now,create$5=e=>new Promise(e),all=Promise.all.bind(Promise),undefinedToNull=e=>e===void 0?null:e;var VarStoragePolyfill=class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}};let _localStorage=new VarStoragePolyfill,usePolyfill=!0;try{typeof localStorage<`u`&&localStorage&&(_localStorage=localStorage)}catch{}const varStorage=_localStorage,EqualityTraitSymbol$1=Symbol(`Equality`),equals=(e,t)=>e===t||!!e?.[EqualityTraitSymbol$1]?.(t)||!1,assign=Object.assign,keys$1=Object.keys,forEach=(e,t)=>{for(let S in e)t(e[S],S)},size$1=e=>keys$1(e).length,isEmpty$2=e=>{for(let t in e)return!1;return!0},every=(e,t)=>{for(let S in e)if(!t(e[S],S))return!1;return!0},hasProperty$1=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),equalFlat=(e,t)=>e===t||size$1(e)===size$1(t)&&every(e,(e,S)=>(e!==void 0||hasProperty$1(t,S))&&equals(t[S],e)),freeze=Object.freeze,deepFreeze=e=>{for(let t in e){let S=e[t];(typeof S==`object`||typeof S==`function`)&&deepFreeze(e[t])}return freeze(e)},callAll=(e,t,S=0)=>{try{for(;S<e.length;S++)e[S](...t)}finally{S<e.length&&callAll(e,t,S+1)}},id=e=>e,isOneOf=(e,t)=>t.includes(e),isArray=isArray$1,isNode=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,isBrowser=typeof window<`u`&&typeof document<`u`&&!isNode,isMac=typeof navigator<`u`?/Mac/.test(navigator.platform):!1;let params;const args=[],computeParams=()=>{if(params===void 0)if(isNode){params=create$8();let e=process.argv,t=null;for(let S=0;S<e.length;S++){let w=e[S];w[0]===`-`?(t!==null&&params.set(t,``),t=w):t===null?args.push(w):(params.set(t,w),t=null)}t!==null&&params.set(t,``)}else typeof location==`object`?(params=create$8(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,S]=e.split(`=`);params.set(`--${fromCamelCase(t,`-`)}`,S),params.set(`-${fromCamelCase(t,`-`)}`,S)}})):params=create$8();return params},hasParam=e=>computeParams().has(e),getVariable=e=>undefinedToNull(isNode?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:varStorage.getItem(e)),hasConf=e=>hasParam(`--`+e)||getVariable(e)!==null,production=hasConf(`production`),forceColor=isNode&&isOneOf(process.env.FORCE_COLOR,[`true`,`1`,`2`]),supportsColor=forceColor||!hasParam(`--no-colors`)&&!hasConf(`no-color`)&&(!isNode||process.stdout.isTTY)&&(!isNode||hasParam(`--color`)||getVariable(`COLORTERM`)!==null||(getVariable(`TERM`)||``).includes(`color`)),createUint8ArrayFromLen=e=>new Uint8Array(e),createUint8ArrayViewFromArrayBuffer=(e,t,S)=>new Uint8Array(e,t,S),toBase64Browser=e=>{let t=``;for(let S=0;S<e.byteLength;S++)t+=fromCharCode$2(e[S]);return btoa(t)},toBase64Node=e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),fromBase64Browser=e=>{let t=atob(e),S=createUint8ArrayFromLen(t.length);for(let e=0;e<t.length;e++)S[e]=t.charCodeAt(e);return S},fromBase64Node=e=>{let t=Buffer.from(e,`base64`);return createUint8ArrayViewFromArrayBuffer(t.buffer,t.byteOffset,t.byteLength)},toBase64=isBrowser?toBase64Browser:toBase64Node,fromBase64=isBrowser?fromBase64Browser:fromBase64Node,copyUint8Array=e=>{let t=createUint8ArrayFromLen(e.byteLength);return t.set(e),t},encodeAny=e=>encode(t=>writeAny(t,e)),create$4=Symbol,BOLD=create$4(),UNBOLD=create$4(),BLUE=create$4(),GREY=create$4(),GREEN=create$4(),RED=create$4(),PURPLE=create$4(),ORANGE=create$4(),UNCOLOR=create$4(),computeNoColorLoggingArgs=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],S=[],w=0;for(;w<e.length;w++){let S=e[w];if(S===void 0)break;if(S.constructor===String||S.constructor===Number)t.push(S);else if(S.constructor===Object)break}for(w>0&&S.push(t.join(``));w<e.length;w++){let t=e[w];t instanceof Symbol||S.push(t)}return S};let lastLoggingTime=getUnixTime$1();const _nodeStyleMap={[BOLD]:`\x1B[1m`,[UNBOLD]:`\x1B[2m`,[BLUE]:`\x1B[34m`,[GREEN]:`\x1B[32m`,[GREY]:`\x1B[37m`,[RED]:`\x1B[31m`,[PURPLE]:`\x1B[35m`,[ORANGE]:`\x1B[38;5;208m`,[UNCOLOR]:`\x1B[0m`},computeNodeLoggingArgs=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],S=[],w=0;for(;w<e.length;w++){let S=e[w],E=_nodeStyleMap[S];if(E!==void 0)t.push(E);else if(S===void 0)break;else if(S.constructor===String||S.constructor===Number)t.push(S);else break}for(w>0&&(t.push(`\x1B[0m`),S.push(t.join(``)));w<e.length;w++){let t=e[w];t instanceof Symbol||S.push(t)}return S},computeLoggingArgs=supportsColor?computeNodeLoggingArgs:computeNoColorLoggingArgs,print=(...e)=>{console.log(...computeLoggingArgs(e))},warn=(...e)=>{console.warn(...computeLoggingArgs(e))},createIterator=e=>({[Symbol.iterator](){return this},next:e}),iteratorFilter=(e,t)=>createIterator(()=>{let S;do S=e.next();while(!S.done&&!t(S.value));return S}),iteratorMap=(e,t)=>createIterator(()=>{let{done:S,value:w}=e.next();return{done:S,value:S?void 0:t(w)}});var DeleteItem=class{constructor(e,t){this.clock=e,this.len=t}},DeleteSet=class{constructor(){this.clients=new Map}};const iterateDeletedStructs=(e,t,S)=>t.clients.forEach((t,w)=>{let E=e.doc.store.clients.get(w);if(E!=null){let w=E[E.length-1],D=w.id.clock+w.length;for(let w=0,O=t[w];w<t.length&&O.clock<D;O=t[++w])iterateStructs(e,E,O.clock,O.len,S)}}),findIndexDS=(e,t)=>{let S=0,w=e.length-1;for(;S<=w;){let E=floor$2((S+w)/2),D=e[E],O=D.clock;if(O<=t){if(t<O+D.len)return E;S=E+1}else w=E-1}return null},isDeleted=(e,t)=>{let S=e.clients.get(t.client);return S!==void 0&&findIndexDS(S,t.clock)!==null},sortAndMergeDeleteSet=e=>{e.clients.forEach(e=>{e.sort((e,t)=>e.clock-t.clock);let t,S;for(t=1,S=1;t<e.length;t++){let w=e[S-1],E=e[t];w.clock+w.len>=E.clock?e[S-1]=new DeleteItem(w.clock,max$2(w.len,E.clock+E.len-w.clock)):(S<t&&(e[S]=E),S++)}e.length=S})},mergeDeleteSets=e=>{let t=new DeleteSet;for(let S=0;S<e.length;S++)e[S].clients.forEach((w,E)=>{if(!t.clients.has(E)){let D=w.slice();for(let t=S+1;t<e.length;t++)appendTo(D,e[t].clients.get(E)||[]);t.clients.set(E,D)}});return sortAndMergeDeleteSet(t),t},addToDeleteSet=(e,t,S,w)=>{setIfUndefined$1(e.clients,t,()=>[]).push(new DeleteItem(S,w))},createDeleteSet=()=>new DeleteSet,createDeleteSetFromStructStore=e=>{let t=createDeleteSet();return e.clients.forEach((e,S)=>{let w=[];for(let t=0;t<e.length;t++){let S=e[t];if(S.deleted){let E=S.id.clock,D=S.length;if(t+1<e.length)for(let S=e[t+1];t+1<e.length&&S.deleted;S=e[++t+1])D+=S.length;w.push(new DeleteItem(E,D))}}w.length>0&&t.clients.set(S,w)}),t},writeDeleteSet=(e,t)=>{writeVarUint$2(e.restEncoder,t.clients.size),from$1(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,S])=>{e.resetDsCurVal(),writeVarUint$2(e.restEncoder,t);let w=S.length;writeVarUint$2(e.restEncoder,w);for(let t=0;t<w;t++){let w=S[t];e.writeDsClock(w.clock),e.writeDsLen(w.len)}})},readDeleteSet=e=>{let t=new DeleteSet,S=readVarUint$1(e.restDecoder);for(let w=0;w<S;w++){e.resetDsCurVal();let S=readVarUint$1(e.restDecoder),w=readVarUint$1(e.restDecoder);if(w>0){let E=setIfUndefined$1(t.clients,S,()=>[]);for(let t=0;t<w;t++)E.push(new DeleteItem(e.readDsClock(),e.readDsLen()))}}return t},readAndApplyDeleteSet=(e,t,S)=>{let w=new DeleteSet,E=readVarUint$1(e.restDecoder);for(let D=0;D<E;D++){e.resetDsCurVal();let E=readVarUint$1(e.restDecoder),D=readVarUint$1(e.restDecoder),O=S.clients.get(E)||[],k=getState(S,E);for(let S=0;S<D;S++){let S=e.readDsClock(),D=S+e.readDsLen();if(S<k){k<D&&addToDeleteSet(w,E,k,D-k);let e=findIndexSS(O,S),j=O[e];for(!j.deleted&&j.id.clock<S&&(O.splice(e+1,0,splitItem(t,j,S-j.id.clock)),e++);e<O.length&&(j=O[e++],j.id.clock<D);)j.deleted||(D<j.id.clock+j.length&&O.splice(e,0,splitItem(t,j,D-j.id.clock)),j.delete(t))}else addToDeleteSet(w,E,S,D-S)}}if(w.clients.size>0){let e=new UpdateEncoderV2;return writeVarUint$2(e.restEncoder,0),writeDeleteSet(e,w),e.toUint8Array()}return null},equalDeleteSets=(e,t)=>{if(e.clients.size!==t.clients.size)return!1;for(let[S,w]of e.clients.entries()){let e=t.clients.get(S);if(e===void 0||w.length!==e.length)return!1;for(let t=0;t<w.length;t++){let S=w[t],E=e[t];if(S.clock!==E.clock||S.len!==E.len)return!1}}return!0},generateNewClientId=uint32;var Doc=class e extends ObservableV2{constructor({guid:e=uuidv4(),collectionid:t=null,gc:S=!0,gcFilter:w=()=>!0,meta:E=null,autoLoad:D=!1,shouldLoad:O=!0}={}){super(),this.gc=S,this.gcFilter=w,this.clientID=generateNewClientId(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new StructStore,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=O,this.autoLoad=D,this.meta=E,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=create$5(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let k=()=>create$5(e=>{let t=S=>{(S===void 0||S===!0)&&(this.off(`sync`,t),e())};this.on(`sync`,t)});this.on(`sync`,e=>{e===!1&&this.isSynced&&(this.whenSynced=k()),this.isSynced=e===void 0||e===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=k()}load(){let e=this._item;e!==null&&!this.shouldLoad&&transact(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(from$1(this.subdocs).map(e=>e.guid))}transact(e,t=null){return transact(this,e,t)}get(e,t=AbstractType){let S=setIfUndefined$1(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),w=S.constructor;if(t!==AbstractType&&w!==t)if(w===AbstractType){let w=new t;w._map=S._map,S._map.forEach(e=>{for(;e!==null;e=e.left)e.parent=w}),w._start=S._start;for(let e=w._start;e!==null;e=e.right)e.parent=w;return w._length=S._length,this.share.set(e,w),w._integrate(this,null),w}else throw Error(`Type with the name ${e} has already been defined with a different constructor`);return S}getArray(e=``){return this.get(e,YArray)}getText(e=``){return this.get(e,YText)}getMap(e=``){return this.get(e,YMap)}getXmlElement(e=``){return this.get(e,YXmlElement)}getXmlFragment(e=``){return this.get(e,YXmlFragment)}toJSON(){let e={};return this.share.forEach((t,S)=>{e[S]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,from$1(this.subdocs).forEach(e=>e.destroy());let t=this._item;if(t!==null){this._item=null;let S=t.content;S.doc=new e({guid:this.guid,...S.opts,shouldLoad:!1}),S.doc._item=t,transact(t.parent.doc,e=>{let w=S.doc;t.deleted||e.subdocsAdded.add(w),e.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}},DSDecoderV1=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return readVarUint$1(this.restDecoder)}readDsLen(){return readVarUint$1(this.restDecoder)}},UpdateDecoderV1=class extends DSDecoderV1{readLeftID(){return createID(readVarUint$1(this.restDecoder),readVarUint$1(this.restDecoder))}readRightID(){return createID(readVarUint$1(this.restDecoder),readVarUint$1(this.restDecoder))}readClient(){return readVarUint$1(this.restDecoder)}readInfo(){return readUint8$1(this.restDecoder)}readString(){return readVarString$1(this.restDecoder)}readParentInfo(){return readVarUint$1(this.restDecoder)===1}readTypeRef(){return readVarUint$1(this.restDecoder)}readLen(){return readVarUint$1(this.restDecoder)}readAny(){return readAny(this.restDecoder)}readBuf(){return copyUint8Array(readVarUint8Array$1(this.restDecoder))}readJSON(){return JSON.parse(readVarString$1(this.restDecoder))}readKey(){return readVarString$1(this.restDecoder)}},DSDecoderV2=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=readVarUint$1(this.restDecoder),this.dsCurrVal}readDsLen(){let e=readVarUint$1(this.restDecoder)+1;return this.dsCurrVal+=e,e}},UpdateDecoderV2=class extends DSDecoderV2{constructor(e){super(e),this.keys=[],readVarUint$1(e),this.keyClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.clientDecoder=new UintOptRleDecoder(readVarUint8Array$1(e)),this.leftClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.rightClockDecoder=new IntDiffOptRleDecoder(readVarUint8Array$1(e)),this.infoDecoder=new RleDecoder(readVarUint8Array$1(e),readUint8$1),this.stringDecoder=new StringDecoder(readVarUint8Array$1(e)),this.parentInfoDecoder=new RleDecoder(readVarUint8Array$1(e),readUint8$1),this.typeRefDecoder=new UintOptRleDecoder(readVarUint8Array$1(e)),this.lenDecoder=new UintOptRleDecoder(readVarUint8Array$1(e))}readLeftID(){return new ID(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new ID(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return readAny(this.restDecoder)}readBuf(){return readVarUint8Array$1(this.restDecoder)}readJSON(){return readAny(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{let e=this.stringDecoder.read();return this.keys.push(e),e}}},DSEncoderV1=class{constructor(){this.restEncoder=createEncoder$1()}toUint8Array(){return toUint8Array$1(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){writeVarUint$2(this.restEncoder,e)}writeDsLen(e){writeVarUint$2(this.restEncoder,e)}},UpdateEncoderV1=class extends DSEncoderV1{writeLeftID(e){writeVarUint$2(this.restEncoder,e.client),writeVarUint$2(this.restEncoder,e.clock)}writeRightID(e){writeVarUint$2(this.restEncoder,e.client),writeVarUint$2(this.restEncoder,e.clock)}writeClient(e){writeVarUint$2(this.restEncoder,e)}writeInfo(e){writeUint8(this.restEncoder,e)}writeString(e){writeVarString$2(this.restEncoder,e)}writeParentInfo(e){writeVarUint$2(this.restEncoder,e?1:0)}writeTypeRef(e){writeVarUint$2(this.restEncoder,e)}writeLen(e){writeVarUint$2(this.restEncoder,e)}writeAny(e){writeAny(this.restEncoder,e)}writeBuf(e){writeVarUint8Array$2(this.restEncoder,e)}writeJSON(e){writeVarString$2(this.restEncoder,JSON.stringify(e))}writeKey(e){writeVarString$2(this.restEncoder,e)}},DSEncoderV2=class{constructor(){this.restEncoder=createEncoder$1(),this.dsCurrVal=0}toUint8Array(){return toUint8Array$1(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,writeVarUint$2(this.restEncoder,t)}writeDsLen(e){e===0&&unexpectedCase(),writeVarUint$2(this.restEncoder,e-1),this.dsCurrVal+=e}},UpdateEncoderV2=class extends DSEncoderV2{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new IntDiffOptRleEncoder,this.clientEncoder=new UintOptRleEncoder,this.leftClockEncoder=new IntDiffOptRleEncoder,this.rightClockEncoder=new IntDiffOptRleEncoder,this.infoEncoder=new RleEncoder(writeUint8),this.stringEncoder=new StringEncoder,this.parentInfoEncoder=new RleEncoder(writeUint8),this.typeRefEncoder=new UintOptRleEncoder,this.lenEncoder=new UintOptRleEncoder}toUint8Array(){let e=createEncoder$1();return writeVarUint$2(e,0),writeVarUint8Array$2(e,this.keyClockEncoder.toUint8Array()),writeVarUint8Array$2(e,this.clientEncoder.toUint8Array()),writeVarUint8Array$2(e,this.leftClockEncoder.toUint8Array()),writeVarUint8Array$2(e,this.rightClockEncoder.toUint8Array()),writeVarUint8Array$2(e,toUint8Array$1(this.infoEncoder)),writeVarUint8Array$2(e,this.stringEncoder.toUint8Array()),writeVarUint8Array$2(e,toUint8Array$1(this.parentInfoEncoder)),writeVarUint8Array$2(e,this.typeRefEncoder.toUint8Array()),writeVarUint8Array$2(e,this.lenEncoder.toUint8Array()),writeUint8Array$2(e,toUint8Array$1(this.restEncoder)),toUint8Array$1(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){writeAny(this.restEncoder,e)}writeBuf(e){writeVarUint8Array$2(this.restEncoder,e)}writeJSON(e){writeAny(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}};const writeStructs=(e,t,S,w)=>{w=max$2(w,t[0].id.clock);let E=findIndexSS(t,w);writeVarUint$2(e.restEncoder,t.length-E),e.writeClient(S),writeVarUint$2(e.restEncoder,w);let D=t[E];D.write(e,w-D.id.clock);for(let S=E+1;S<t.length;S++)t[S].write(e,0)},writeClientsStructs=(e,t,S)=>{let w=new Map;S.forEach((e,S)=>{getState(t,S)>e&&w.set(S,e)}),getStateVector(t).forEach((e,t)=>{S.has(t)||w.set(t,0)}),writeVarUint$2(e.restEncoder,w.size),from$1(w.entries()).sort((e,t)=>t[0]-e[0]).forEach(([S,w])=>{writeStructs(e,t.clients.get(S),S,w)})},readClientsStructRefs=(e,t)=>{let S=create$8(),w=readVarUint$1(e.restDecoder);for(let E=0;E<w;E++){let w=readVarUint$1(e.restDecoder),E=Array(w),D=e.readClient(),O=readVarUint$1(e.restDecoder);S.set(D,{i:0,refs:E});for(let S=0;S<w;S++){let w=e.readInfo();switch(31&w){case 0:{let t=e.readLen();E[S]=new GC(createID(D,O),t),O+=t;break}case 10:{let t=readVarUint$1(e.restDecoder);E[S]=new Skip(createID(D,O),t),O+=t;break}default:{let k=(w&192)==0,j=new Item(createID(D,O),null,(w&128)==128?e.readLeftID():null,null,(w&64)==64?e.readRightID():null,k?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,k&&(w&32)==32?e.readString():null,readItemContent(e,w));E[S]=j,O+=j.length}}}}return S},integrateStructs=(e,t,S)=>{let w=[],E=from$1(S.keys()).sort((e,t)=>e-t);if(E.length===0)return null;let D=()=>{if(E.length===0)return null;let e=S.get(E[E.length-1]);for(;e.refs.length===e.i;)if(E.pop(),E.length>0)e=S.get(E[E.length-1]);else return null;return e},O=D();if(O===null)return null;let k=new StructStore,j=new Map,F=(e,t)=>{let S=j.get(e);(S==null||S>t)&&j.set(e,t)},L=O.refs[O.i++],B=new Map,H=()=>{for(let e of w){let t=e.id.client,w=S.get(t);w?(w.i--,k.clients.set(t,w.refs.slice(w.i)),S.delete(t),w.i=0,w.refs=[]):k.clients.set(t,[e]),E=E.filter(e=>e!==t)}w.length=0};for(;;){if(L.constructor!==Skip){let E=setIfUndefined$1(B,L.id.client,()=>getState(t,L.id.client))-L.id.clock;if(E<0)w.push(L),F(L.id.client,L.id.clock-1),H();else{let D=L.getMissing(e,t);if(D!==null){w.push(L);let e=S.get(D)||{refs:[],i:0};if(e.refs.length===e.i)F(D,getState(t,D)),H();else{L=e.refs[e.i++];continue}}else (E===0||E<L.length)&&(L.integrate(e,E),B.set(L.id.client,L.id.clock+L.length))}}if(w.length>0)L=w.pop();else if(O!==null&&O.i<O.refs.length)L=O.refs[O.i++];else{if(O=D(),O===null)break;L=O.refs[O.i++]}}if(k.clients.size>0){let e=new UpdateEncoderV2;return writeClientsStructs(e,k,new Map),writeVarUint$2(e.restEncoder,0),{missing:j,update:e.toUint8Array()}}return null},writeStructsFromTransaction=(e,t)=>writeClientsStructs(e,t.doc.store,t.beforeState),readUpdateV2=(e,t,S,w=new UpdateDecoderV2(e))=>transact(t,e=>{e.local=!1;let t=!1,S=e.doc,E=S.store,D=integrateStructs(e,E,readClientsStructRefs(w,S)),O=E.pendingStructs;if(O){for(let[e,S]of O.missing)if(S<getState(E,e)){t=!0;break}if(D){for(let[e,t]of D.missing){let S=O.missing.get(e);(S==null||S>t)&&O.missing.set(e,t)}O.update=mergeUpdatesV2([O.update,D.update])}}else E.pendingStructs=D;let k=readAndApplyDeleteSet(w,e,E);if(E.pendingDs){let t=new UpdateDecoderV2(createDecoder$1(E.pendingDs));readVarUint$1(t.restDecoder);let S=readAndApplyDeleteSet(t,e,E);k&&S?E.pendingDs=mergeUpdatesV2([k,S]):E.pendingDs=k||S}else E.pendingDs=k;if(t){let t=E.pendingStructs.update;E.pendingStructs=null,applyUpdateV2(e.doc,t)}},S,!1),applyUpdateV2=(e,t,S,w=UpdateDecoderV2)=>{let E=createDecoder$1(t);readUpdateV2(E,e,S,new w(E))},applyUpdate=(e,t,S)=>applyUpdateV2(e,t,S,UpdateDecoderV1),writeStateAsUpdate=(e,t,S=new Map)=>{writeClientsStructs(e,t.store,S),writeDeleteSet(e,createDeleteSetFromStructStore(t.store))},encodeStateAsUpdateV2=(e,t=new Uint8Array([0]),S=new UpdateEncoderV2)=>{writeStateAsUpdate(S,e,decodeStateVector(t));let w=[S.toUint8Array()];if(e.store.pendingDs&&w.push(e.store.pendingDs),e.store.pendingStructs&&w.push(diffUpdateV2(e.store.pendingStructs.update,t)),w.length>1){if(S.constructor===UpdateEncoderV1)return mergeUpdates(w.map((e,t)=>t===0?e:convertUpdateFormatV2ToV1(e)));if(S.constructor===UpdateEncoderV2)return mergeUpdatesV2(w)}return w[0]},encodeStateAsUpdate=(e,t)=>encodeStateAsUpdateV2(e,t,new UpdateEncoderV1),readStateVector=e=>{let t=new Map,S=readVarUint$1(e.restDecoder);for(let w=0;w<S;w++){let S=readVarUint$1(e.restDecoder),w=readVarUint$1(e.restDecoder);t.set(S,w)}return t},decodeStateVector=e=>readStateVector(new DSDecoderV1(createDecoder$1(e))),writeStateVector=(e,t)=>(writeVarUint$2(e.restEncoder,t.size),from$1(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,S])=>{writeVarUint$2(e.restEncoder,t),writeVarUint$2(e.restEncoder,S)}),e),writeDocumentStateVector=(e,t)=>writeStateVector(e,getStateVector(t.store)),encodeStateVectorV2=(e,t=new DSEncoderV2)=>(e instanceof Map?writeStateVector(t,e):writeDocumentStateVector(t,e),t.toUint8Array()),encodeStateVector=e=>encodeStateVectorV2(e,new DSEncoderV1);var EventHandler=class{constructor(){this.l=[]}};const createEventHandler=()=>new EventHandler,addEventHandlerListener=(e,t)=>e.l.push(t),removeEventHandlerListener=(e,t)=>{let S=e.l,w=S.length;e.l=S.filter(e=>t!==e),w===e.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},callEventHandlerListeners=(e,t,S)=>callAll(e.l,[t,S]);var ID=class{constructor(e,t){this.client=e,this.clock=t}};const compareIDs=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,createID=(e,t)=>new ID(e,t),findRootTypeKey=e=>{for(let[t,S]of e.doc.share.entries())if(S===e)return t;throw unexpectedCase()},isParentOf=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};var Snapshot=class{constructor(e,t){this.ds=e,this.sv=t}};const createSnapshot=(e,t)=>new Snapshot(e,t),emptySnapshot=createSnapshot(createDeleteSet(),new Map),snapshot=e=>createSnapshot(createDeleteSetFromStructStore(e.store),getStateVector(e.store)),isVisible$1=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!isDeleted(t.ds,e.id),splitSnapshotAffectedStructs=(e,t)=>{let S=setIfUndefined$1(e.meta,splitSnapshotAffectedStructs,create$7),w=e.doc.store;S.has(t)||(t.sv.forEach((t,S)=>{t<getState(w,S)&&getItemCleanStart(e,createID(S,t))}),iterateDeletedStructs(e,t.ds,e=>{}),S.add(t))},snapshotContainsUpdateV2=(e,t,S=UpdateDecoderV2)=>{let w=new S(createDecoder$1(t)),E=new LazyStructReader(w,!1);for(let t=E.curr;t!==null;t=E.next())if((e.sv.get(t.id.client)||0)<t.id.clock+t.length)return!1;let D=mergeDeleteSets([e.ds,readDeleteSet(w)]);return equalDeleteSets(e.ds,D)},snapshotContainsUpdate=(e,t)=>snapshotContainsUpdateV2(e,t,UpdateDecoderV1);var StructStore=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}};const getStateVector=e=>{let t=new Map;return e.clients.forEach((e,S)=>{let w=e[e.length-1];t.set(S,w.id.clock+w.length)}),t},getState=(e,t)=>{let S=e.clients.get(t);if(S===void 0)return 0;let w=S[S.length-1];return w.id.clock+w.length},addStruct=(e,t)=>{let S=e.clients.get(t.id.client);if(S===void 0)S=[],e.clients.set(t.id.client,S);else{let e=S[S.length-1];if(e.id.clock+e.length!==t.id.clock)throw unexpectedCase()}S.push(t)},findIndexSS=(e,t)=>{let S=0,w=e.length-1,E=e[w],D=E.id.clock;if(D===t)return w;let O=floor$2(t/(D+E.length-1)*w);for(;S<=w;){if(E=e[O],D=E.id.clock,D<=t){if(t<D+E.length)return O;S=O+1}else w=O-1;O=floor$2((S+w)/2)}throw unexpectedCase()},find=(e,t)=>{let S=e.clients.get(t.client);return S[findIndexSS(S,t.clock)]},getItem=find,findIndexCleanStart=(e,t,S)=>{let w=findIndexSS(t,S),E=t[w];return E.id.clock<S&&E instanceof Item?(t.splice(w+1,0,splitItem(e,E,S-E.id.clock)),w+1):w},getItemCleanStart=(e,t)=>{let S=e.doc.store.clients.get(t.client);return S[findIndexCleanStart(e,S,t.clock)]},getItemCleanEnd=(e,t,S)=>{let w=t.clients.get(S.client),E=findIndexSS(w,S.clock),D=w[E];return S.clock!==D.id.clock+D.length-1&&D.constructor!==GC&&w.splice(E+1,0,splitItem(e,D,S.clock-D.id.clock+1)),D},replaceStruct=(e,t,S)=>{let w=e.clients.get(t.id.client);w[findIndexSS(w,t.id.clock)]=S},iterateStructs=(e,t,S,w,E)=>{if(w===0)return;let D=S+w,O=findIndexCleanStart(e,t,S),k;do k=t[O++],D<k.id.clock+k.length&&findIndexCleanStart(e,t,D),E(k);while(O<t.length&&t[O].id.clock<D)};var Transaction=class{constructor(e,t,S){this.doc=e,this.deleteSet=new DeleteSet,this.beforeState=getStateVector(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=S,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}};const writeUpdateMessageFromTransaction=(e,t)=>t.deleteSet.clients.size===0&&!any(t.afterState,(e,S)=>t.beforeState.get(S)!==e)?!1:(sortAndMergeDeleteSet(t.deleteSet),writeStructsFromTransaction(e,t),writeDeleteSet(e,t.deleteSet),!0),addChangedTypeToTransaction=(e,t,S)=>{let w=t._item;(w===null||w.id.clock<(e.beforeState.get(w.id.client)||0)&&!w.deleted)&&setIfUndefined$1(e.changed,t,create$7).add(S)},tryToMergeWithLefts=(e,t)=>{let S=e[t],w=e[t-1],E=t;for(;E>0;S=w,w=e[--E-1]){if(w.deleted===S.deleted&&w.constructor===S.constructor&&w.mergeWith(S)){S instanceof Item&&S.parentSub!==null&&S.parent._map.get(S.parentSub)===S&&S.parent._map.set(S.parentSub,w);continue}break}let D=t-E;return D&&e.splice(t+1-D,D),D},tryGcDeleteSet=(e,t,S)=>{for(let[w,E]of e.clients.entries()){let e=t.clients.get(w);for(let w=E.length-1;w>=0;w--){let D=E[w],O=D.clock+D.len;for(let w=findIndexSS(e,D.clock),E=e[w];w<e.length&&E.id.clock<O;E=e[++w]){let E=e[w];if(D.clock+D.len<=E.id.clock)break;E instanceof Item&&E.deleted&&!E.keep&&S(E)&&E.gc(t,!1)}}}},tryMergeDeleteSet=(e,t)=>{e.clients.forEach((e,S)=>{let w=t.clients.get(S);for(let t=e.length-1;t>=0;t--){let S=e[t],E=min$2(w.length-1,1+findIndexSS(w,S.clock+S.len-1));for(let e=E,t=w[e];e>0&&t.id.clock>=S.clock;t=w[e])e-=1+tryToMergeWithLefts(w,e)}})},cleanupTransactions=(e,t)=>{if(t<e.length){let S=e[t],w=S.doc,E=w.store,D=S.deleteSet,O=S._mergeStructs;try{sortAndMergeDeleteSet(D),S.afterState=getStateVector(S.doc.store),w.emit(`beforeObserverCalls`,[S,w]);let e=[];S.changed.forEach((t,w)=>e.push(()=>{(w._item===null||!w._item.deleted)&&w._callObserver(S,t)})),e.push(()=>{S.changedParentTypes.forEach((t,w)=>{w._dEH.l.length>0&&(w._item===null||!w._item.deleted)&&(t=t.filter(e=>e.target._item===null||!e.target._item.deleted),t.forEach(e=>{e.currentTarget=w,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{callEventHandlerListeners(w._dEH,t,S)}))}),e.push(()=>w.emit(`afterTransaction`,[S,w])),e.push(()=>{S._needFormattingCleanup&&cleanupYTextAfterTransaction(S)})}),callAll(e,[])}finally{w.gc&&tryGcDeleteSet(D,E,w.gcFilter),tryMergeDeleteSet(D,E),S.afterState.forEach((e,t)=>{let w=S.beforeState.get(t)||0;if(w!==e){let e=E.clients.get(t),S=max$2(findIndexSS(e,w),1);for(let t=e.length-1;t>=S;)t-=1+tryToMergeWithLefts(e,t)}});for(let e=O.length-1;e>=0;e--){let{client:t,clock:S}=O[e].id,w=E.clients.get(t),D=findIndexSS(w,S);D+1<w.length&&tryToMergeWithLefts(w,D+1)>1||D>0&&tryToMergeWithLefts(w,D)}if(!S.local&&S.afterState.get(w.clientID)!==S.beforeState.get(w.clientID)&&(print(ORANGE,BOLD,`[yjs] `,UNBOLD,RED,`Changed the client-id because another client seems to be using it.`),w.clientID=generateNewClientId()),w.emit(`afterTransactionCleanup`,[S,w]),w._observers.has(`update`)){let e=new UpdateEncoderV1;writeUpdateMessageFromTransaction(e,S)&&w.emit(`update`,[e.toUint8Array(),S.origin,w,S])}if(w._observers.has(`updateV2`)){let e=new UpdateEncoderV2;writeUpdateMessageFromTransaction(e,S)&&w.emit(`updateV2`,[e.toUint8Array(),S.origin,w,S])}let{subdocsAdded:k,subdocsLoaded:j,subdocsRemoved:F}=S;(k.size>0||F.size>0||j.size>0)&&(k.forEach(e=>{e.clientID=w.clientID,e.collectionid??=w.collectionid,w.subdocs.add(e)}),F.forEach(e=>w.subdocs.delete(e)),w.emit(`subdocs`,[{loaded:j,added:k,removed:F},w,S]),F.forEach(e=>e.destroy())),e.length<=t+1?(w._transactionCleanups=[],w.emit(`afterAllTransactions`,[w,e])):cleanupTransactions(e,t+1)}}},transact=(e,t,S=null,w=!0)=>{let E=e._transactionCleanups,D=!1,O=null;e._transaction===null&&(D=!0,e._transaction=new Transaction(e,S,w),E.push(e._transaction),E.length===1&&e.emit(`beforeAllTransactions`,[e]),e.emit(`beforeTransaction`,[e._transaction,e]));try{O=t(e._transaction)}finally{if(D){let t=e._transaction===E[0];e._transaction=null,t&&cleanupTransactions(E,0)}}return O};var StackItem=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}};const clearUndoManagerStackItem=(e,t,S)=>{iterateDeletedStructs(e,S.deletions,S=>{S instanceof Item&&t.scope.some(t=>t===e.doc||isParentOf(t,S))&&keepItem(S,!1)})},popStackItem=(e,t,S)=>{let w=null,E=e.doc,D=e.scope;transact(E,S=>{for(;t.length>0&&e.currStackItem===null;){let w=E.store,O=t.pop(),k=new Set,j=[],F=!1;iterateDeletedStructs(S,O.insertions,e=>{if(e instanceof Item){if(e.redone!==null){let{item:t,diff:E}=followRedone(w,e.id);E>0&&(t=getItemCleanStart(S,createID(t.id.client,t.id.clock+E))),e=t}!e.deleted&&D.some(t=>t===S.doc||isParentOf(t,e))&&j.push(e)}}),iterateDeletedStructs(S,O.deletions,e=>{e instanceof Item&&D.some(t=>t===S.doc||isParentOf(t,e))&&!isDeleted(O.insertions,e.id)&&k.add(e)}),k.forEach(t=>{F=redoItem(S,t,k,O.insertions,e.ignoreRemoteMapChanges,e)!==null||F});for(let t=j.length-1;t>=0;t--){let w=j[t];e.deleteFilter(w)&&(w.delete(S),F=!0)}e.currStackItem=F?O:null}S.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),w=S},e);let O=e.currStackItem;if(O!=null){let t=w.changedParentTypes;e.emit(`stack-item-popped`,[{stackItem:O,type:S,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return O};var UndoManager=class extends ObservableV2{constructor(e,{captureTimeout:t=500,captureTransaction:S=e=>!0,deleteFilter:w=()=>!0,trackedOrigins:E=new Set([null]),ignoreRemoteMapChanges:D=!1,doc:O=isArray$1(e)?e[0].doc:e instanceof Doc?e:e.doc}={}){super(),this.scope=[],this.doc=O,this.addToScope(e),this.deleteFilter=w,E.add(this),this.trackedOrigins=E,this.captureTransaction=S,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=D,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!this.captureTransaction(e)||!this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)||!this.trackedOrigins.has(e.origin)&&(!e.origin||!this.trackedOrigins.has(e.origin.constructor)))return;let t=this.undoing,S=this.redoing,w=t?this.redoStack:this.undoStack;t?this.stopCapturing():S||this.clear(!1,!0);let E=new DeleteSet;e.afterState.forEach((t,S)=>{let w=e.beforeState.get(S)||0,D=t-w;D>0&&addToDeleteSet(E,S,w,D)});let D=getUnixTime$1(),O=!1;if(this.lastChange>0&&D-this.lastChange<this.captureTimeout&&w.length>0&&!t&&!S){let t=w[w.length-1];t.deletions=mergeDeleteSets([t.deletions,e.deleteSet]),t.insertions=mergeDeleteSets([t.insertions,E])}else w.push(new StackItem(e.deleteSet,E)),O=!0;!t&&!S&&(this.lastChange=D),iterateDeletedStructs(e,e.deleteSet,t=>{t instanceof Item&&this.scope.some(S=>S===e.doc||isParentOf(S,t))&&keepItem(t,!0)});let k=[{stackItem:w[w.length-1],origin:e.origin,type:t?`redo`:`undo`,changedParentTypes:e.changedParentTypes},this];O?this.emit(`stack-item-added`,k):this.emit(`stack-item-updated`,k)},this.doc.on(`afterTransaction`,this.afterTransactionHandler),this.doc.on(`destroy`,()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=isArray$1(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof AbstractType?e.doc!==this.doc:e!==this.doc)&&warn(`[yjs#509] Not same Y.Doc`),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(S=>{e&&(this.undoStack.forEach(e=>clearUndoManagerStackItem(S,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>clearUndoManagerStackItem(S,this,e)),this.redoStack=[]),this.emit(`stack-cleared`,[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=popStackItem(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=popStackItem(this,this.redoStack,`redo`)}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off(`afterTransaction`,this.afterTransactionHandler),super.destroy()}};function*lazyStructReaderGenerator(e){let t=readVarUint$1(e.restDecoder);for(let S=0;S<t;S++){let t=readVarUint$1(e.restDecoder),S=e.readClient(),w=readVarUint$1(e.restDecoder);for(let E=0;E<t;E++){let t=e.readInfo();if(t===10){let t=readVarUint$1(e.restDecoder);yield new Skip(createID(S,w),t),w+=t}else if(31&t){let E=(t&192)==0,D=new Item(createID(S,w),null,(t&128)==128?e.readLeftID():null,null,(t&64)==64?e.readRightID():null,E?e.readParentInfo()?e.readString():e.readLeftID():null,E&&(t&32)==32?e.readString():null,readItemContent(e,t));yield D,w+=D.length}else{let t=e.readLen();yield new GC(createID(S,w),t),w+=t}}}}var LazyStructReader=class{constructor(e,t){this.gen=lazyStructReaderGenerator(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===Skip);return this.curr}},LazyStructWriter=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const mergeUpdates=e=>mergeUpdatesV2(e,UpdateDecoderV1,UpdateEncoderV1),sliceStruct=(e,t)=>{if(e.constructor===GC){let{client:S,clock:w}=e.id;return new GC(createID(S,w+t),e.length-t)}else if(e.constructor===Skip){let{client:S,clock:w}=e.id;return new Skip(createID(S,w+t),e.length-t)}else{let S=e,{client:w,clock:E}=S.id;return new Item(createID(w,E+t),null,createID(w,E+t-1),null,S.rightOrigin,S.parent,S.parentSub,S.content.splice(t))}},mergeUpdatesV2=(e,t=UpdateDecoderV2,S=UpdateEncoderV2)=>{if(e.length===1)return e[0];let w=e.map(e=>new t(createDecoder$1(e))),E=w.map(e=>new LazyStructReader(e,!0)),D=null,O=new S,k=new LazyStructWriter(O);for(;E=E.filter(e=>e.curr!==null),E.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){let S=e.curr.id.clock-t.curr.id.clock;return S===0?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===Skip?1:-1:S}else return t.curr.id.client-e.curr.id.client}),E.length!==0;){let e=E[0],t=e.curr.id.client;if(D!==null){let S=e.curr,w=!1;for(;S!==null&&S.id.clock+S.length<=D.struct.id.clock+D.struct.length&&S.id.client>=D.struct.id.client;)S=e.next(),w=!0;if(S===null||S.id.client!==t||w&&S.id.clock>D.struct.id.clock+D.struct.length)continue;if(t!==D.struct.id.client)writeStructToLazyStructWriter(k,D.struct,D.offset),D={struct:S,offset:0},e.next();else if(D.struct.id.clock+D.struct.length<S.id.clock)if(D.struct.constructor===Skip)D.struct.length=S.id.clock+S.length-D.struct.id.clock;else{writeStructToLazyStructWriter(k,D.struct,D.offset);let e=S.id.clock-D.struct.id.clock-D.struct.length;D={struct:new Skip(createID(t,D.struct.id.clock+D.struct.length),e),offset:0}}else{let t=D.struct.id.clock+D.struct.length-S.id.clock;t>0&&(D.struct.constructor===Skip?D.struct.length-=t:S=sliceStruct(S,t)),D.struct.mergeWith(S)||(writeStructToLazyStructWriter(k,D.struct,D.offset),D={struct:S,offset:0},e.next())}}else D={struct:e.curr,offset:0},e.next();for(let S=e.curr;S!==null&&S.id.client===t&&S.id.clock===D.struct.id.clock+D.struct.length&&S.constructor!==Skip;S=e.next())writeStructToLazyStructWriter(k,D.struct,D.offset),D={struct:S,offset:0}}return D!==null&&(writeStructToLazyStructWriter(k,D.struct,D.offset),D=null),finishLazyStructWriting(k),writeDeleteSet(O,mergeDeleteSets(w.map(e=>readDeleteSet(e)))),O.toUint8Array()},diffUpdateV2=(e,t,S=UpdateDecoderV2,w=UpdateEncoderV2)=>{let E=decodeStateVector(t),D=new w,O=new LazyStructWriter(D),k=new S(createDecoder$1(e)),j=new LazyStructReader(k,!1);for(;j.curr;){let e=j.curr,t=e.id.client,S=E.get(t)||0;if(j.curr.constructor===Skip){j.next();continue}if(e.id.clock+e.length>S)for(writeStructToLazyStructWriter(O,e,max$2(S-e.id.clock,0)),j.next();j.curr&&j.curr.id.client===t;)writeStructToLazyStructWriter(O,j.curr,0),j.next();else for(;j.curr&&j.curr.id.client===t&&j.curr.id.clock+j.curr.length<=S;)j.next()}return finishLazyStructWriting(O),writeDeleteSet(D,readDeleteSet(k)),D.toUint8Array()},flushLazyStructWriter=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:toUint8Array$1(e.encoder.restEncoder)}),e.encoder.restEncoder=createEncoder$1(),e.written=0)},writeStructToLazyStructWriter=(e,t,S)=>{e.written>0&&e.currClient!==t.id.client&&flushLazyStructWriter(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),writeVarUint$2(e.encoder.restEncoder,t.id.clock+S)),t.write(e.encoder,S),e.written++},finishLazyStructWriting=e=>{flushLazyStructWriter(e);let t=e.encoder.restEncoder;writeVarUint$2(t,e.clientStructs.length);for(let S=0;S<e.clientStructs.length;S++){let w=e.clientStructs[S];writeVarUint$2(t,w.written),writeUint8Array$2(t,w.restEncoder)}},convertUpdateFormat=(e,t,S,w)=>{let E=new S(createDecoder$1(e)),D=new LazyStructReader(E,!1),O=new w,k=new LazyStructWriter(O);for(let e=D.curr;e!==null;e=D.next())writeStructToLazyStructWriter(k,t(e),0);return finishLazyStructWriting(k),writeDeleteSet(O,readDeleteSet(E)),O.toUint8Array()},convertUpdateFormatV2ToV1=e=>convertUpdateFormat(e,id,UpdateDecoderV2,UpdateEncoderV1),errorComputeChanges=`You must not compute changes after the event-handler fired.`;var YEvent=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||=getPathTo(this.currentTarget,this.target)}deletes(e){return isDeleted(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw create$6(errorComputeChanges);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(S=>{if(S!==null){let w=t._map.get(S),E,D;if(this.adds(w)){let e=w.left;for(;e!==null&&this.adds(e);)e=e.left;if(this.deletes(w))if(e!==null&&this.deletes(e))E=`delete`,D=last(e.content.getContent());else return;else e!==null&&this.deletes(e)?(E=`update`,D=last(e.content.getContent())):(E=`add`,D=void 0)}else if(this.deletes(w))E=`delete`,D=last(w.content.getContent());else return;e.set(S,{action:E,oldValue:D})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw create$6(errorComputeChanges);let t=this.target,S=create$7(),w=create$7(),E=[];if(e={added:S,deleted:w,delta:E,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null,D=()=>{e&&E.push(e)};for(let E=t._start;E!==null;E=E.right)E.deleted?this.deletes(E)&&!this.adds(E)&&((e===null||e.delete===void 0)&&(D(),e={delete:0}),e.delete+=E.length,w.add(E)):this.adds(E)?((e===null||e.insert===void 0)&&(D(),e={insert:[]}),e.insert=e.insert.concat(E.content.getContent()),S.add(E)):((e===null||e.retain===void 0)&&(D(),e={retain:0}),e.retain+=E.length);e!==null&&e.retain===void 0&&D()}this._changes=e}return e}};const getPathTo=(e,t)=>{let S=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)S.unshift(t._item.parentSub);else{let e=0,w=t._item.parent._start;for(;w!==t._item&&w!==null;)!w.deleted&&w.countable&&(e+=w.length),w=w.right;S.unshift(e)}t=t._item.parent}return S},warnPrematureAccess=()=>{warn(`Invalid access: Add Yjs type to a document before reading data.`)},maxSearchMarker=80;let globalSearchMarkerTimestamp=0;var ArraySearchMarker=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=globalSearchMarkerTimestamp++}};const refreshMarkerTimestamp=e=>{e.timestamp=globalSearchMarkerTimestamp++},overwriteMarker=(e,t,S)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=S,e.timestamp=globalSearchMarkerTimestamp++},markPosition=(e,t,S)=>{if(e.length>=maxSearchMarker){let w=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return overwriteMarker(w,t,S),w}else{let w=new ArraySearchMarker(t,S);return e.push(w),w}},findMarker=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;let S=e._searchMarker.length===0?null:e._searchMarker.reduce((e,S)=>abs(t-e.index)<abs(t-S.index)?e:S),w=e._start,E=0;for(S!==null&&(w=S.p,E=S.index,refreshMarkerTimestamp(S));w.right!==null&&E<t;){if(!w.deleted&&w.countable){if(t<E+w.length)break;E+=w.length}w=w.right}for(;w.left!==null&&E>t;)w=w.left,!w.deleted&&w.countable&&(E-=w.length);for(;w.left!==null&&w.left.id.client===w.id.client&&w.left.id.clock+w.left.length===w.id.clock;)w=w.left,!w.deleted&&w.countable&&(E-=w.length);return S!==null&&abs(S.index-E)<w.parent.length/maxSearchMarker?(overwriteMarker(S,w,E),S):markPosition(e._searchMarker,w,E)},updateMarkerChanges=(e,t,S)=>{for(let w=e.length-1;w>=0;w--){let E=e[w];if(S>0){let t=E.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(E.index-=t.length);if(t===null||t.marker===!0){e.splice(w,1);continue}E.p=t,t.marker=!0}(t<E.index||S>0&&t===E.index)&&(E.index=max$2(t,E.index+S))}},callTypeObservers=(e,t,S)=>{let w=e,E=t.changedParentTypes;for(;setIfUndefined$1(E,e,()=>[]).push(S),e._item!==null;)e=e._item.parent;callEventHandlerListeners(w._eH,S,t)};var AbstractType=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=createEventHandler(),this._dEH=createEventHandler(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw methodUnimplemented()}clone(){throw methodUnimplemented()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){addEventHandlerListener(this._eH,e)}observeDeep(e){addEventHandlerListener(this._dEH,e)}unobserve(e){removeEventHandlerListener(this._eH,e)}unobserveDeep(e){removeEventHandlerListener(this._dEH,e)}toJSON(){}};const typeListSlice=(e,t,S)=>{e.doc??warnPrematureAccess(),t<0&&(t=e._length+t),S<0&&(S=e._length+S);let w=S-t,E=[],D=e._start;for(;D!==null&&w>0;){if(D.countable&&!D.deleted){let e=D.content.getContent();if(e.length<=t)t-=e.length;else{for(let S=t;S<e.length&&w>0;S++)E.push(e[S]),w--;t=0}}D=D.right}return E},typeListToArray=e=>{e.doc??warnPrematureAccess();let t=[],S=e._start;for(;S!==null;){if(S.countable&&!S.deleted){let e=S.content.getContent();for(let S=0;S<e.length;S++)t.push(e[S])}S=S.right}return t},typeListToArraySnapshot=(e,t)=>{let S=[],w=e._start;for(;w!==null;){if(w.countable&&isVisible$1(w,t)){let e=w.content.getContent();for(let t=0;t<e.length;t++)S.push(e[t])}w=w.right}return S},typeListForEach=(e,t)=>{let S=0,w=e._start;for(e.doc??warnPrematureAccess();w!==null;){if(w.countable&&!w.deleted){let E=w.content.getContent();for(let w=0;w<E.length;w++)t(E[w],S++,e)}w=w.right}},typeListMap=(e,t)=>{let S=[];return typeListForEach(e,(w,E)=>{S.push(t(w,E,e))}),S},typeListCreateIterator=e=>{let t=e._start,S=null,w=0;return{[Symbol.iterator](){return this},next:()=>{if(S===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};S=t.content.getContent(),w=0,t=t.right}let e=S[w++];return S.length<=w&&(S=null),{done:!1,value:e}}}},typeListGet=(e,t)=>{e.doc??warnPrematureAccess();let S=findMarker(e,t),w=e._start;for(S!==null&&(w=S.p,t-=S.index);w!==null;w=w.right)if(!w.deleted&&w.countable){if(t<w.length)return w.content.getContent()[t];t-=w.length}},typeListInsertGenericsAfter=(e,t,S,w)=>{let E=S,D=e.doc,O=D.clientID,k=D.store,j=S===null?t._start:S.right,F=[],L=()=>{F.length>0&&(E=new Item(createID(O,getState(k,O)),E,E&&E.lastId,j,j&&j.id,t,null,new ContentAny(F)),E.integrate(e,0),F=[])};w.forEach(S=>{if(S===null)F.push(S);else switch(S.constructor){case Number:case Object:case Boolean:case Array:case String:F.push(S);break;default:switch(L(),S.constructor){case Uint8Array:case ArrayBuffer:E=new Item(createID(O,getState(k,O)),E,E&&E.lastId,j,j&&j.id,t,null,new ContentBinary(new Uint8Array(S))),E.integrate(e,0);break;case Doc:E=new Item(createID(O,getState(k,O)),E,E&&E.lastId,j,j&&j.id,t,null,new ContentDoc(S)),E.integrate(e,0);break;default:if(S instanceof AbstractType)E=new Item(createID(O,getState(k,O)),E,E&&E.lastId,j,j&&j.id,t,null,new ContentType(S)),E.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),L()},lengthExceeded=()=>create$6(`Length exceeded!`),typeListInsertGenerics=(e,t,S,w)=>{if(S>t._length)throw lengthExceeded();if(S===0)return t._searchMarker&&updateMarkerChanges(t._searchMarker,S,w.length),typeListInsertGenericsAfter(e,t,null,w);let E=S,D=findMarker(t,S),O=t._start;for(D!==null&&(O=D.p,S-=D.index,S===0&&(O=O.prev,S+=O&&O.countable&&!O.deleted?O.length:0));O!==null;O=O.right)if(!O.deleted&&O.countable){if(S<=O.length){S<O.length&&getItemCleanStart(e,createID(O.id.client,O.id.clock+S));break}S-=O.length}return t._searchMarker&&updateMarkerChanges(t._searchMarker,E,w.length),typeListInsertGenericsAfter(e,t,O,w)},typeListPushGenerics=(e,t,S)=>{let w=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(w)for(;w.right;)w=w.right;return typeListInsertGenericsAfter(e,t,w,S)},typeListDelete=(e,t,S,w)=>{if(w===0)return;let E=S,D=w,O=findMarker(t,S),k=t._start;for(O!==null&&(k=O.p,S-=O.index);k!==null&&S>0;k=k.right)!k.deleted&&k.countable&&(S<k.length&&getItemCleanStart(e,createID(k.id.client,k.id.clock+S)),S-=k.length);for(;w>0&&k!==null;)k.deleted||(w<k.length&&getItemCleanStart(e,createID(k.id.client,k.id.clock+w)),k.delete(e),w-=k.length),k=k.right;if(w>0)throw lengthExceeded();t._searchMarker&&updateMarkerChanges(t._searchMarker,E,-D+w)},typeMapDelete=(e,t,S)=>{let w=t._map.get(S);w!==void 0&&w.delete(e)},typeMapSet=(e,t,S,w)=>{let E=t._map.get(S)||null,D=e.doc,O=D.clientID,k;if(w==null)k=new ContentAny([w]);else switch(w.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:k=new ContentAny([w]);break;case Uint8Array:k=new ContentBinary(w);break;case Doc:k=new ContentDoc(w);break;default:if(w instanceof AbstractType)k=new ContentType(w);else throw Error(`Unexpected content type`)}new Item(createID(O,getState(D.store,O)),E,E&&E.lastId,null,null,t,S,k).integrate(e,0)},typeMapGet=(e,t)=>{e.doc??warnPrematureAccess();let S=e._map.get(t);return S!==void 0&&!S.deleted?S.content.getContent()[S.length-1]:void 0},typeMapGetAll=e=>{let t={};return e.doc??warnPrematureAccess(),e._map.forEach((e,S)=>{e.deleted||(t[S]=e.content.getContent()[e.length-1])}),t},typeMapHas=(e,t)=>{e.doc??warnPrematureAccess();let S=e._map.get(t);return S!==void 0&&!S.deleted},typeMapGetAllSnapshot=(e,t)=>{let S={};return e._map.forEach((e,w)=>{let E=e;for(;E!==null&&(!t.sv.has(E.id.client)||E.id.clock>=(t.sv.get(E.id.client)||0));)E=E.left;E!==null&&isVisible$1(E,t)&&(S[w]=E.content.getContent()[E.length-1])}),S},createMapIterator=e=>(e.doc??warnPrematureAccess(),iteratorFilter(e._map.entries(),e=>!e[1].deleted));var YArrayEvent=class extends YEvent{},YArray=class e extends AbstractType{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let S=new e;return S.push(t),S}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof AbstractType?e.clone():e)),t}get length(){return this.doc??warnPrematureAccess(),this._length}_callObserver(e,t){super._callObserver(e,t),callTypeObservers(this,e,new YArrayEvent(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):transact(this.doc,S=>{typeListInsertGenerics(S,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):transact(this.doc,t=>{typeListPushGenerics(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):transact(this.doc,S=>{typeListDelete(S,this,e,t)})}get(e){return typeListGet(this,e)}toArray(){return typeListToArray(this)}slice(e=0,t=this.length){return typeListSlice(this,e,t)}toJSON(){return this.map(e=>e instanceof AbstractType?e.toJSON():e)}map(e){return typeListMap(this,e)}forEach(e){typeListForEach(this,e)}[Symbol.iterator](){return typeListCreateIterator(this)}_write(e){e.writeTypeRef(YArrayRefID)}};const readYArray=e=>new YArray;var YMapEvent=class extends YEvent{constructor(e,t,S){super(e,t),this.keysChanged=S}},YMap=class e extends AbstractType{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return this.forEach((e,S)=>{t.set(S,e instanceof AbstractType?e.clone():e)}),t}_callObserver(e,t){callTypeObservers(this,e,new YMapEvent(this,e,t))}toJSON(){this.doc??warnPrematureAccess();let e={};return this._map.forEach((t,S)=>{if(!t.deleted){let w=t.content.getContent()[t.length-1];e[S]=w instanceof AbstractType?w.toJSON():w}}),e}get size(){return[...createMapIterator(this)].length}keys(){return iteratorMap(createMapIterator(this),e=>e[0])}values(){return iteratorMap(createMapIterator(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return iteratorMap(createMapIterator(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??warnPrematureAccess(),this._map.forEach((t,S)=>{t.deleted||e(t.content.getContent()[t.length-1],S,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc===null?this._prelimContent.delete(e):transact(this.doc,t=>{typeMapDelete(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):transact(this.doc,S=>{typeMapSet(S,this,e,t)}),t}get(e){return typeMapGet(this,e)}has(e){return typeMapHas(this,e)}clear(){this.doc===null?this._prelimContent.clear():transact(this.doc,e=>{this.forEach(function(t,S,w){typeMapDelete(e,w,S)})})}_write(e){e.writeTypeRef(YMapRefID)}};const readYMap=e=>new YMap,equalAttrs$1=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&equalFlat(e,t);var ItemTextListPosition=class{constructor(e,t,S,w){this.left=e,this.right=t,this.index=S,this.currentAttributes=w}forward(){switch(this.right===null&&unexpectedCase(),this.right.content.constructor){case ContentFormat:this.right.deleted||updateCurrentAttributes(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}};const findNextPosition=(e,t,S)=>{for(;t.right!==null&&S>0;){switch(t.right.content.constructor){case ContentFormat:t.right.deleted||updateCurrentAttributes(t.currentAttributes,t.right.content);break;default:t.right.deleted||(S<t.right.length&&getItemCleanStart(e,createID(t.right.id.client,t.right.id.clock+S)),t.index+=t.right.length,S-=t.right.length);break}t.left=t.right,t.right=t.right.right}return t},findPosition=(e,t,S,w)=>{let E=new Map,D=w?findMarker(t,S):null;return D?findNextPosition(e,new ItemTextListPosition(D.p.left,D.p,D.index,E),S-D.index):findNextPosition(e,new ItemTextListPosition(null,t._start,0,E),S)},insertNegatedAttributes=(e,t,S,w)=>{for(;S.right!==null&&(S.right.deleted===!0||S.right.content.constructor===ContentFormat&&equalAttrs$1(w.get(S.right.content.key),S.right.content.value));)S.right.deleted||w.delete(S.right.content.key),S.forward();let E=e.doc,D=E.clientID;w.forEach((w,O)=>{let k=S.left,j=S.right,F=new Item(createID(D,getState(E.store,D)),k,k&&k.lastId,j,j&&j.id,t,null,new ContentFormat(O,w));F.integrate(e,0),S.right=F,S.forward()})},updateCurrentAttributes=(e,t)=>{let{key:S,value:w}=t;w===null?e.delete(S):e.set(S,w)},minimizeAttributeChanges=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===ContentFormat&&equalAttrs$1(t[e.right.content.key]??null,e.right.content.value));)e.forward()},insertAttributes=(e,t,S,w)=>{let E=e.doc,D=E.clientID,O=new Map;for(let k in w){let j=w[k],F=S.currentAttributes.get(k)??null;if(!equalAttrs$1(F,j)){O.set(k,F);let{left:w,right:L}=S;S.right=new Item(createID(D,getState(E.store,D)),w,w&&w.lastId,L,L&&L.id,t,null,new ContentFormat(k,j)),S.right.integrate(e,0),S.forward()}}return O},insertText=(e,t,S,w,E)=>{S.currentAttributes.forEach((e,t)=>{E[t]===void 0&&(E[t]=null)});let D=e.doc,O=D.clientID;minimizeAttributeChanges(S,E);let k=insertAttributes(e,t,S,E),j=w.constructor===String?new ContentString(w):w instanceof AbstractType?new ContentType(w):new ContentEmbed(w),{left:F,right:L,index:B}=S;t._searchMarker&&updateMarkerChanges(t._searchMarker,S.index,j.getLength()),L=new Item(createID(O,getState(D.store,O)),F,F&&F.lastId,L,L&&L.id,t,null,j),L.integrate(e,0),S.right=L,S.index=B,S.forward(),insertNegatedAttributes(e,t,S,k)},formatText=(e,t,S,w,E)=>{let D=e.doc,O=D.clientID;minimizeAttributeChanges(S,E);let k=insertAttributes(e,t,S,E);iterationLoop:for(;S.right!==null&&(w>0||k.size>0&&(S.right.deleted||S.right.content.constructor===ContentFormat));){if(!S.right.deleted)switch(S.right.content.constructor){case ContentFormat:{let{key:t,value:D}=S.right.content,O=E[t];if(O!==void 0){if(equalAttrs$1(O,D))k.delete(t);else{if(w===0)break iterationLoop;k.set(t,D)}S.right.delete(e)}else S.currentAttributes.set(t,D);break}default:w<S.right.length&&getItemCleanStart(e,createID(S.right.id.client,S.right.id.clock+w)),w-=S.right.length;break}S.forward()}if(w>0){let E=``;for(;w>0;w--)E+=`
@@ -1222,7 +1222,7 @@ caused by: `+E(O,t)):D},D=e=>E(e,new Set),O=(e,t,E)=>{if(!S(e))return``;let D=E?
1222
1222
  `)){let t=e.trim();t.length===40&&k.add(t)}}w.scanned=t.byTo.size;let j=[];for(let{entry:e,observedSha:S}of D)k.has(S)||t.byTo.get(e.to)===e&&e.commitSha===S&&j.push(e);for(let e of j)t.byTo.get(e.to)===e&&indexRemove(t,e);if(w.dropped=j.length,w.retained=t.byTo.size,S?.rebuild){let S;try{S=await E.raw(`log`,`--all`,`--grep=^rename: `,`--format=%H%x00%cI%x00%B%x1e`)}catch(e){console.warn(`[rename-log] WARN: gcRenameLog rebuild: git log --grep failed; skipping reconstruction:`,e),S=``}let D=await buildBranchReachabilityMap(e,O);for(let e of S.split(``)){let S=e.trimStart();if(!S)continue;let E=S.split(`\0`),O=(E[0]??``).trim(),j=(E[1]??``).trim(),F=E[2]??``;if(O.length!==40||!k.has(O))continue;let L=parseOkActors(F),B=0;for(let e of L)B+=e.previous_paths?.length??0;if(B===0)continue;let H=B>1?`folder`:`file`,q=lookupBranchInMap(D,O),J=deriveGroupId(O,``,``);for(let e of L)if(!(!e.previous_paths||e.previous_paths.length===0))for(let S of e.previous_paths)t.byTo.has(S.to)||(indexInsert(t,{v:1,from:S.from,to:S.to,at:j||new Date(0).toISOString(),commitSha:O,branch:q,groupId:J,kind:H,actor:{writerId:e.writer_id,displayName:e.display_name}}),w.rebuilt+=1,w.retained+=1)}}return(w.dropped>0||w.rebuilt>0)&&rewriteJsonlAtomically(e.gitDir,t),w.dropped>0&&(console.warn(`[rename-log] gc swept ${w.dropped} dead entries (${w.retained} live remain)`),gcDroppedCounter().add(w.dropped),liveEntriesGauge().add(-w.dropped)),w.rebuilt>0&&liveEntriesGauge().add(w.rebuilt),w}function deriveGroupId(e,t,S){let w=createHash(`sha256`);w.update(`${e}\0${t}\0${S}`);let E=w.digest(`hex`);return`${E.slice(0,8)}-${E.slice(8,12)}-${E.slice(12,16)}-${E.slice(16,20)}-${E.slice(20,32)}`}async function buildBranchReachabilityMap(e,t){let S=new Map;for(let e of[...t].sort()){let t=/^refs\/(?:wip|checkpoints)\/([^/]+)\//.exec(e);if(!t?.[1])continue;let w=S.get(t[1])??[];w.push(e),S.set(t[1],w)}let w=new Map;for(let[t,E]of S){let S;try{S=await revListReachable(e,E)}catch(e){console.warn(`[rename-log] WARN: gcRenameLog rebuild: rev-list failed for branch ${t}; reconstructed entries on this branch will fall back to 'main':`,e);continue}let D=new Set;for(let e of S.split(`
1223
1223
  `)){let t=e.trim();t.length===40&&D.add(t)}w.set(t,D)}return w}function lookupBranchInMap(e,t){for(let[S,w]of e)if(w.has(t))return S;return`main`}async function resolveDocPathAtCommit(e,t,S,w,E,D,O,k){let{chain:j}=expandPredecessors(t,w,E),F=await Promise.all(j.map(async t=>{if(t.renameCommit===null)return null;let S=await buildSeeds(e,t.renameCommit,w,k);return S.length===0?new Set:buildAncestorShaSet(e,S,w,O)})),L=[];for(let e=j.length-1;e>=0;e--){let t=j[e],w=F[e];w!==null&&!w.has(S)||L.push({sha:S,path:D(t.path)})}if(L.length===0)return null;let B=await batchCheckExistence(e,L);for(let e=0;e<L.length;e++)if(B[e])return L[e].path;return null}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:S,ytext:w,mdManager:E,schema:D}=e,O=(t,S)=>{let w=process.env.OK_TELEMETRY_VERBOSE===`1`;console.warn(JSON.stringify({...t.toLog({verbose:w}),docName:e.docName??null,timestamp:new Date().toISOString()})),incrementBridgeMergeContentLoss();let E=e.shadow?.();if(!E||!e.docName)return;let D=e.getBranch?.()??`main`,O=e.contentRoot??``;queueMicrotask(()=>{saveInMemoryCheckpoint(E,O,{kind:`bridge-merge-loss`,docName:e.docName,contents:S,label:`Before concurrent merge @ ${new Date().toISOString()}`,branch:D,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(`
1224
1224
  `).slice(0,4).join(`
1225
- `)})})})},k=``,j=!1,F=!1,L=()=>stripFrontmatter(w.toString()).frontmatter;try{let e=yXmlFragmentToProseMirrorRootNode(S,D).toJSON(),t=E.serialize(e);k=prependFrontmatter(L(),t)}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),k=``}let B=()=>{try{let j=yXmlFragmentToProseMirrorRootNode(S,D).toJSON(),F=E.serialize(j),B=prependFrontmatter(L(),F);if(k===B)return;let H=w.toString();if(normalizeBridge(H)===normalizeBridge(B)){k=B;return}let q=k,J={mergedText:null};t.transact(()=>{if(H===k)applyIncrementalDiff(w,H,B);else try{let e=mergeThreeWay(k,B,H);applyFastDiff(w,H,e),J.mergedText=e}catch(e){if(!(e instanceof BridgeMergeContentLossError)||(O(e,q),shouldRethrowBridgeMergeLoss()))throw e;applyFastDiff(w,H,e.info.result),J.mergedText=e.info.result}},OBSERVER_SYNC_ORIGIN),J.mergedText!==null&&emitObserverAPathBFired(e.docName)&&(incrementObserverAPathBFires(),console.warn(JSON.stringify({event:`observer-a-path-b-fired`,"doc.name":e.docName??null,xmlFragmentAdvanced:!0,ytextDiverged:!0,mergeBytesChanged:Math.abs(J.mergedText.length-H.length)}))),incrementServerObserverFire(`a`),k=w.toString()}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,e);try{k=w.toString()}catch(e){console.warn(`[Server Observer A] Baseline recovery also failed:`,e)}}},H=()=>{withSpanSync(`observer.runASync`,{attributes:{"doc.name":e.docName??``}},B)},q=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=L();k=w.toString(),J=e}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),j=!0}return}j=!0}};if(S.length>0&&w.length===0)try{let e=yXmlFragmentToProseMirrorRootNode(S,D).toJSON(),O=E.serialize(e),j=prependFrontmatter(L(),O);t.transact(()=>{w.insert(0,j)},OBSERVER_SYNC_ORIGIN),k=j}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),k=``}let J=L(),Y=()=>{try{let D=w.toString(),{frontmatter:O,body:j}=stripFrontmatter(D);if(normalizeBridge(k)===normalizeBridge(D)){J!==O&&(recordFrontmatterEditSurface(`source-mode`),J=O);return}let F=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.docName}:void 0,L=E.parseWithFallback(j,F),B=e.schema.nodeFromJSON(L);t.transact(()=>{updateYFragment(t,S,B,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN),J!==O&&(recordFrontmatterEditSurface(`source-mode`),J=O),incrementServerObserverFire(`b`);try{let t=prependFrontmatter(O,E.serialize(L));assertBridgeInvariant(w.toString(),t,{site:`observer-b`,docName:e.docName}),k=t}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),k=prependFrontmatter(O,j)}}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;incrementServerObserverError(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=yXmlFragmentToProseMirrorRootNode(S,D).toJSON(),t=E.serialize(e);k=prependFrontmatter(L(),t)}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},ee=()=>{withSpanSync(`observer.runBSync`,{attributes:{"doc.name":e.docName??``}},Y)},te=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=L();k=w.toString(),J=e}catch(e){incrementServerObserverError(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),F=!0}return}F=!0}},ne=(t,S)=>{withSpanSync(`observer.dispatch`,{attributes:{"doc.name":e.docName??``}},t=>{if(!j&&!F){t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}if(S.every(e=>e.origin===OBSERVER_SYNC_ORIGIN)){j=!1,F=!1,t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}let w=j,E=F;j&&(j=!1,e.onDispatch?.(`a`),H()),F&&(F=!1,e.onDispatch?.(`b`),ee()),t.setAttribute(`observer.dispatch`,w&&E?`a-then-b`:w?`a`:E?`b`:`none`)})};S.observeDeep(q),w.observe(te),t.on(`afterAllTransactions`,ne);let ae=attachQuiescenceTracker(t);return()=>{ae(),t.off(`afterAllTransactions`,ne),S.unobserveDeep(q),w.unobserve(te)}}const log$7=getLogger(`persistence`);var DocumentOpenSizeLimitError=class extends Error{docName;size;limit;constructor(e,t,S=DOCUMENT_OPEN_BYTE_LIMIT){super(`Document "${e}" is ${formatFileSize(t)}; Open Knowledge opens documents up to ${formatFileSize(S)}.`),this.name=`DocumentOpenSizeLimitError`,this.docName=e,this.size=t,this.limit=S}};function resolveWriterFromOrigin(e,t){if(!e||typeof e!=`object`)return null;let S=e;if(S.source===`local`){let e=S.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?FILE_SYSTEM_WRITER:e.origin===`upstream-import`||e.origin===`git-upstream`?GIT_UPSTREAM_WRITER:SERVICE_WRITER}if(S.source===`connection`){let e=S.connection?.context;if(typeof e?.principalId==`string`){let S=e.principalId,w=t?.();return w&&w.id===S&&w.display_name&&w.display_email?{id:w.id,name:w.display_name,email:w.display_email}:{id:S,name:`Local User`,email:`${S}@openknowledge.local`}}return SERVICE_WRITER}return null}const ERRNO_FS_CODES=new Set([`EACCES`,`EBADF`,`EBUSY`,`EEXIST`,`EISDIR`,`ELOOP`,`EMFILE`,`ENFILE`,`ENOENT`,`ENOSPC`,`ENOTDIR`,`EPERM`,`EROFS`,`ETXTBSY`,`EXDEV`]);function classifyDeferredStoreError(e){if(typeof e!=`object`||!e)return`unknown`;let t=e,S=typeof t.message==`string`?t.message:``;return S.startsWith(`symlink-escape:`)?`disk-write`:typeof t.code==`string`&&ERRNO_FS_CODES.has(t.code)?S.includes(`rename`)?`traced-rename`:`disk-write`:e instanceof BridgeInvariantViolationError?`serialize`:`unknown`}function captureDocSnapshotForPersistence(e){return{sv:encodeStateVector(e),json:yXmlFragmentToProseMirrorRootNode(e.getXmlFragment(`default`),schema).toJSON()}}function safeContentPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let S=resolve(t,`${e}${getDocExtension(e)}`);if(!S.startsWith(`${t}/`))throw Error(`Invalid document name: ${e}`);return S}function isWithinContentDir(e,t){return e===t||e.startsWith(t+sep)}const reconciledBaseByBranch=new Map;let activeBranch=`main`;function switchReconciledBaseScope(e){activeBranch=e,reconciledBaseByBranch.has(e)||reconciledBaseByBranch.set(e,new Map)}function getActiveBranch(){return activeBranch}function getReconciledBase(e){return reconciledBaseByBranch.get(activeBranch)?.get(e)}function setReconciledBase(e,t){reconciledBaseByBranch.has(activeBranch)||reconciledBaseByBranch.set(activeBranch,new Map),reconciledBaseByBranch.get(activeBranch)?.set(e,t)}function deleteReconciledBase(e){reconciledBaseByBranch.get(activeBranch)?.delete(e)}let batchInProgress=!1;function setBatchInProgress(e){batchInProgress=e}function isBatchInProgress(){return batchInProgress}function createPersistenceExtension(e){let t=e?.contentDir??process.cwd(),S;try{S=realpathSync(t)}catch{S=t}let w=e?.projectDir??process.cwd(),E=e?.shadowRef,D=e?.contentRoot??(relative(w,S)||`.`),O=e?.backlinkIndex,k=e?.getPrincipal,j=e?.onAgentCommit,F=e?.onDiskFlush,L=e?.mdManager??mdManager,B={projectDir:w,contentDir:S,lkgCache:new Map,homedirOverride:e?.configHomedirOverride,onConfigRejected:e?.onConfigRejected},H=new Set,q=e?.applyDiskContentToDoc??applyDiskContentToDoc,J=null,Y=8,ee=new Map,te=e?.gitEnabled??!0,ne=e?.commitDebounceMs??15e3,ae=e?.wipRef??`refs/wip/main`,oe=e?.getCurrentBranch,se=null,ce=0,ue=null,de=!1,fe=null,me=new Map;async function ge(){Me();let e=Date.now();return withSpan(`persistence.commitToWipRef`,void 0,async()=>await _e()).finally(()=>{je?.record((Date.now()-e)/1e3)})}async function _e(){let e=E?.current;if(e){let t=swapContributors(),S=oe?.()??`main`;if(t.size===0){let t={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},w=`${formatWipSubject([])}\n\n${formatOkActor(t)}`;try{let t=await commitWip(e,SERVICE_WRITER,D,w,S);ce=0,log$7.info({sha:t.slice(0,8),writer:SERVICE_WRITER.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${SERVICE_WRITER.id}`);try{backfillRenameLogCommitSha(e.gitDir,SERVICE_WRITER.id,t,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$7.warn({err:e},`[rename-log] service-writer backfill failed`)}}catch(e){ce++,incrementGitAutoSaveFailure(),log$7.error({err:e,attempt:ce},`[persistence] Shadow commit failed (attempt ${ce})`),ce>=3&&log$7.error({attempt:ce},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let w;try{w=await buildWipTree(e,D)}catch(e){restoreContributors(t),ce++,incrementGitAutoSaveFailure(),log$7.error({err:e,attempt:ce},`[persistence] Shadow WIP tree build failed (attempt ${ce})`);return}let E=!1;for(let[D,O]of t){let t={id:D,name:O.displayName,email:`${D}@openknowledge.local`},k=[...O.docs],F=O.actor,L=[...O.summaries],B=[...O.previousPaths],H={v:1,writer_id:D,principal:F?.principalId??null,agent_session:D.startsWith(`agent-`)?D.slice(6):null,agent_type:F?.agentType??null,client_name:F?.clientName??null,client_version:F?.clientVersion??null,label:F?.label??null,display_name:O.displayName,color_seed:O.colorSeed,docs:k,...L.length>0?{summaries:L}:{},...B.length>0?{previous_paths:B}:{}},q=`${composeCommitSubject(O.subjectOverride??formatWipSubject(k),L)}\n\n${formatOkActor(H)}`;try{let O=await commitWipFromTree(e,t,w,q,S);E=!0,log$7.info({sha:O.slice(0,8),writer:D,tree:w.slice(0,8)},`[persistence] Shadow WIP commit: ${O.slice(0,8)} on refs/wip/${D}`);try{backfillRenameLogCommitSha(e.gitDir,D,O,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$7.warn({err:e},`[rename-log] backfill failed; will retry next commit`)}D.startsWith(`agent-`)&&j?.()}catch(e){restoreContributorEntry(D,O),incrementGitWriterCommitFailure(),log$7.error({err:e,writer:D},`[persistence] Per-writer shadow commit failed for ${D}`)}}E?ce=0:(ce++,incrementGitAutoSaveFailure(),ce>=3&&log$7.error({attempt:ce},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=shadowGit({gitDir:resolve(w,`.git`),workTree:w}),S=resolve(w,`.git/index-wip`),O={GIT_INDEX_FILE:S};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(O).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?log$7.info({},`[persistence] Empty repo — starting with empty index`):log$7.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(O).raw(`add`,D);let e=(await t.env(O).raw(`write-tree`)).trim(),S=null;try{S=(await t.raw(`rev-parse`,ae)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let w=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];S&&w.push(`-p`,S);let E=(await t.raw(...w)).trim();await t.raw(`update-ref`,ae,E),ce=0,log$7.info({sha:E.slice(0,8),wipRef:ae},`[persistence] Git commit: ${E.slice(0,8)} on ${ae}`)}catch(e){ce++,incrementGitAutoSaveFailure(),log$7.error({err:e,attempt:ce},`[persistence] Git commit failed (attempt ${ce})`),ce>=3&&log$7.error({attempt:ce},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{tracedUnlinkSync(S)}catch{}}}function ve(e){if(e<=0)return ne;let t=2**Math.min(e,5),S=Math.random()*.25*ne;return ne*t+S}function ye(){te&&(isBatchInProgress()||(se&&clearTimeout(se),se=setTimeout(()=>{if(se=null,ue){de=!0;return}ue=ge().finally(()=>{ue=null,de&&(de=!1,ye())})},ve(ce))))}async function Ce(){se&&(clearTimeout(se),se=null,ue||=ge().finally(()=>{ue=null,de&&(de=!1,ye())})),ue&&await ue}function we(t,S,w){try{let E=t.getXmlFragment(`default`),D=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:w}:void 0,O=mdManager.parseWithFallback(S,D),k=schema.nodeFromJSON(O);t.transact(()=>{updateYFragment(t,E,k,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN)}catch(e){incrementPersistenceReconciliationFailures(),log$7.warn({err:e,documentName:w},`[persistence] reconcileFragmentNow failed for ${w}`)}}let Te=null,De=null,je=null;function Me(){if(Te)return;let e=getMeter();Te=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),De=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),je=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}async function Pe({document:e,documentName:t,lastTransactionOrigin:w}){Me();let E=Date.now();return withSpan(`persistence.onStoreDocument`,{attributes:{"doc.name":t}},async()=>{let E=e.getMap(`lifecycle`).get(`status`);if(E===`deleted-upstream`||E===`renamed`||E===`conflict`){log$7.info({documentName:t,lifecycleStatus:E},`[persistence] Skipped store for ${t}: lifecycle=${E}`),ee.delete(t),H.delete(t);return}if(!isDocQuiescent(e)){let S=ee.get(t)??0;if(S<8){let w=getMsSinceLastUserTx(e);console.warn(JSON.stringify({event:`persistence-skip-non-quiescent`,"doc.name":t,wallClockMsSinceLastTransaction:w??null,deferCount:S})),incrementPersistenceSkipNonQuiescent(),ee.set(t,S+1);return}console.warn(JSON.stringify({event:`persistence-force-flush-during-burst`,"doc.name":t,wallClockMsSinceLastTransaction:getMsSinceLastUserTx(e)??null,deferCount:S})),incrementPersistenceForceFlushDuringBurst()}let{sv:D,json:j}=captureDocSnapshotForPersistence(e),{frontmatter:B,body:J}=stripFrontmatter(e.getText(`source`).toString()),Y=prependFrontmatter(B,J),te;try{te=assertBridgeInvariant(Y,prependFrontmatter(B,L.serialize(j)),{site:`persistence`,docName:t,suppressDevThrow:!0})}catch(e){incrementPersistenceSanityCheckSerializeFailures(),console.warn(JSON.stringify({event:`persistence-sanity-check-serialize-failed`,"doc.name":t,"error.type":e instanceof Error?e.constructor.name:typeof e,timestamp:new Date().toISOString()})),log$7.warn({err:e,documentName:t},`[persistence] Sanity-check serialize failed for ${t}; proceeding with ytext bytes`),te=!1}te||we(e,J,t);let ne=getReconciledBase(t);if(ne!==void 0&&normalizeBridge(Y)===normalizeBridge(ne)){contributorCount()>0&&ye(),ee.delete(t);return}if(ne===void 0&&normalizeBridge(Y)===``){log$7.warn({documentName:t},`[persistence] Skipped phantom write for ${t}: empty Y.Doc with no reconciled base`),ee.delete(t);return}let ae=resolveWriterFromOrigin(w,k);if(ae&&ae.id!==SERVICE_WRITER.id&&(hasContributor(ae.id)||recordContributor(t,ae.id,ae.name,ae.id)),ne!==void 0){let w=classifyDuplication(Y,ne);if(w.kind===`block`){if(H.has(t)){log$7.warn({documentName:t},`[persistence] Tripwire breaker active — skipping duplicate store for ${t}`);return}let E=e.getXmlFragment(`default`).length;console.warn(JSON.stringify({event:`ok-persistence-duplication-blocked`,"doc.name":t,candidateBytes:Y.length,baseBytes:ne.length,fragmentChildren:E,copies:w.copies,reason:w.reason}));try{let w=safeContentPath(t,S),E;if(existsSync(w)){let e=null;try{e=realpathSync(w)}catch(e){log$7.warn({err:e,documentName:t},`[persistence] Tripwire reset realpath failed for ${t}; using currentBase`)}if(e&&isWithinContentDir(e,S))try{E=readFileSync(e,`utf-8`)}catch(S){log$7.warn({err:S,documentName:t,canonical:e},`[persistence] Tripwire reset readFileSync failed for ${t}; using currentBase`),E=ne}else e&&console.warn(`[persistence] symlink-escape on tripwire reset: ${w} → ${e}, using currentBase`,{docName:t,originalPath:w,canonical:e,contentDir:S}),E=ne}else E=ne;e.transact(()=>{q(e,E)},FILE_WATCHER_ORIGIN),H.delete(t)}catch(e){H.add(t),log$7.error({err:e,documentName:t},`[persistence] Tripwire reset failed for ${t}`)}ee.delete(t);return}}let oe=safeContentPath(t,S);await tracedMkdir(dirname(oe),{recursive:!0});let se;try{se=await realpath(oe)}catch(e){let S=e.code;if(S===`ENOENT`){let e=!1;try{e=lstatSync(oe).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&log$7.warn({err:e,path:oe},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:t,reason:`broken-symlink`}),se=oe}else if(S===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${oe}`),Error(`Symlink cycle detected at ${oe}`);else throw e}if(!isWithinContentDir(se,S)){let e=`symlink-escape: ${oe} resolves to ${se} outside ${S}`;throw console.error(`[persistence] ${e}`,{docName:t,originalPath:oe,canonical:se,contentDir:S}),Error(e)}let ce=`${se}.tmp.${crypto.randomUUID()}`;try{await tracedWriteFile(ce,Y,`utf-8`),await tracedRename(ce,se),registerWrite(se,contentHash(Y)),incrementPersistenceDiskWrite();try{F?.(t,D)}catch(e){log$7.warn({err:e,documentName:t},`[persistence] onDiskFlush callback failed for ${t}`)}}catch(e){try{tracedUnlinkSync(ce)}catch{}throw ee.delete(t),log$7.error({err:e,documentName:t},`[persistence] Failed to save ${t}`),e}log$7.info({filePath:se,bytes:Y.length},`[persistence] Wrote ${se} (${Y.length} bytes)`),setReconciledBase(t,Y),H.delete(t),ee.delete(t),O&&(O.updateDocumentFromMarkdown(t,Y),O.saveToDisk().catch(e=>{log$7.warn({err:e,documentName:t},`[backlinks] Failed to persist cache for ${t}`)})),setActiveSpanAttributes({"persistence.bytes":Y.length}),ye()}).finally(()=>{De?.record((Date.now()-E)/1e3)})}function Ie({document:e,documentName:t,lastTransactionOrigin:S}){me.set(t,{branch:getActiveBranch(),document:e,lastTransactionOrigin:S})}async function Re(e=`within-branch`){return fe?(J=J===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,fe):(fe=(async()=>{let t=e;for(;;){let e=[...me.entries()];if(me.clear(),t!==`discard-stale`){for(let[t,S]of e)if(S.branch===getActiveBranch())try{await Pe({document:S.document,documentName:t,lastTransactionOrigin:S.lastTransactionOrigin})}catch(e){let S=process.env.OK_TELEMETRY_VERBOSE===`1`,w=``;try{w=String(e?.message??``)}catch{w=``}let E=fnv1aDigest(w),D;try{D=classifyDeferredStoreError(e)}catch(e){let w=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":t,classifyErrorHash:fnv1aDigest(w),errorMessageHash:E,...S?{classifyErrorMessage:w}:{},timestamp:new Date().toISOString()})),D=`unknown`}incrementDeferredStoreFailures(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":t,errorClass:D,errorMessageHash:E,...S?{errorMessage:w}:{},timestamp:new Date().toISOString()})),log$7.error({err:e,documentName:t},`[persistence] Deferred store failed for ${t}`)}}let S=J;if(J=null,me.size===0&&S===null)break;t=S??`within-branch`}})().finally(()=>{fe=null}),fe)}let ze={async onLoadDocument({document:t,documentName:w,context:E}){if(isSystemDoc(w))return;if(isConfigDoc(w)){loadConfigDoc(t,w,B);return}Me();let D=Date.now();return withSpan(`persistence.onLoadDocument`,{attributes:{"doc.name":w}},async()=>{log$7.info({documentName:w,connections:t.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${w} (connections: ${t.getConnectionsCount?.()??`?`})`);let E=safeContentPath(w,S);if(!existsSync(E))return;let D=E;try{let e=realpathSync(E);if(!isWithinContentDir(e,S)){console.warn(`[persistence] symlink-escape on load: ${E} → ${e}, refusing`);return}D=e}catch(e){if(e.code===`ELOOP`){console.warn(`[persistence] Symlink cycle on load: ${E}, refusing`);return}}let O=statSync(D).size;if(O>524288)throw log$7.warn({documentName:w,fileSize:O,limit:DOCUMENT_OPEN_BYTE_LIMIT},`[persistence] Document exceeds open byte limit; refusing to load`),new DocumentOpenSizeLimitError(w,O);let k=readFileSync(E,`utf-8`),j=t.getXmlFragment(`default`);log$7.info({documentName:w,fragmentLength:j.length},`[persistence] onLoadDocument ${w}: fragment.length=${j.length} before update`),j.length===0?(t.transact(()=>{applyDiskContentToDoc(t,k,e?.resolveEmbed,w,e?.resolveSize)},FILE_WATCHER_ORIGIN),log$7.info({filePath:E,children:j.length},`[persistence] Loaded ${E} into Y.Doc (${j.length} children)`),j.observeDeep(()=>{log$7.info({documentName:w,fragmentLength:j.length},`[persistence] MUTATION on ${w}: fragment.length=${j.length}`)})):log$7.info({documentName:w,children:j.length},`[persistence] Skipped load for ${w} — fragment already has ${j.length} children`),setReconciledBase(w,k)}).finally(()=>{Te?.record((Date.now()-D)/1e3)})},async onStoreDocument({document:e,documentName:t,lastTransactionOrigin:S,lastContext:w}){if(!isSystemDoc(t)){if(isConfigDoc(t)){await storeConfigDoc(e,t,S,B);return}if(isBatchInProgress()){Ie({document:e,documentName:t,lastTransactionOrigin:S});return}return Pe({document:e,documentName:t,lastTransactionOrigin:S})}}};async function Be(){ue&&await ue}async function Ve(){if(ue){await ue;return}contributorCount()!==0&&(ue=ge().finally(()=>{ue=null,de&&(de=!1,ye())}),await ue)}return{extension:ze,flushDeferredStores:Re,flushPendingGitCommit:Ce,flushContributors:Ve,waitForPendingCommits:Be,configPersistenceCtx:B}}const MARKDOWN_LINK_OR_IMAGE_RE=/!?\[[^\]\n]*(?:\][^[\]\n]*)?\]\((?:<([^>\n]+)>|([^)\s]+))(?:\s+['"][^'"]*['"])?\)/g,WIKI_LINK_OR_EMBED_RE=/!?\[\[([^[\]|#]+?)(?:#[^\]|]+?)?(?:\|[^\]]+?)?\]\]/g,HTML_LINK_ATTR_RE=/<[\w:-]+\b[^>]*?\s+(?:href|src)\s*=\s*(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function isRemoteOrOpaqueHref(e){return e.startsWith(`#`)||e.startsWith(`//`)||e.startsWith(`data:`)||/^[a-z][a-z0-9+.-]*:/i.test(e)}function stripHrefDecorations(e){let t=e.trim().replace(/^<(.+)>$/,`$1`),S=t.indexOf(`#`),w=S>=0?t.slice(0,S):t,E=w.indexOf(`?`);return E>=0?w.slice(0,E):w}function decodeHrefPath(e){let t=stripHrefDecorations(e);try{return decodeURI(t)}catch{return t}}function mediaKindForAssetPath(e){return mediaKindForSidebarAssetExtension(extname(e).slice(1).toLowerCase())}function errnoCode$1(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`?e.code:null}function collectHrefsFromLine(e,t){for(let S of e.matchAll(MARKDOWN_LINK_OR_IMAGE_RE)){let e=S[1]??S[2];e&&t.add(e)}for(let S of e.matchAll(WIKI_LINK_OR_EMBED_RE)){let e=S[1];e&&t.add(e)}for(let S of e.matchAll(HTML_LINK_ATTR_RE)){let e=S[1]??S[2]??S[3]??S[4];e&&t.add(e)}}function stripHtmlComments(e,t){let S=e,w=``;for(;S.length>0;){if(t.inComment){let e=S.indexOf(`-->`);if(e===-1)return w;S=S.slice(e+3),t.inComment=!1;continue}let e=S.indexOf(`<!--`);if(e===-1)return w+S;w+=S.slice(0,e),S=S.slice(e+4),t.inComment=!0}return w}function extractLocalAssetHrefs(e){let t=new Set,S=createCodeFenceTracker(),w={inComment:!1};for(let E of e.replaceAll(`\r
1225
+ `)})})})},k=``,j=!1,F=!1,L=()=>stripFrontmatter(w.toString()).frontmatter;try{let e=yXmlFragmentToProseMirrorRootNode(S,D).toJSON(),t=E.serialize(e);k=prependFrontmatter(L(),t)}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),k=``}let B=()=>{try{let j=yXmlFragmentToProseMirrorRootNode(S,D).toJSON(),F=E.serialize(j),B=prependFrontmatter(L(),F);if(k===B)return;let H=w.toString();if(normalizeBridge(H)===normalizeBridge(B)){k=B;return}let q=k,J={mergedText:null};t.transact(()=>{if(H===k)applyIncrementalDiff(w,H,B);else try{let e=mergeThreeWay(k,B,H);applyFastDiff(w,H,e),J.mergedText=e}catch(e){if(!(e instanceof BridgeMergeContentLossError)||(O(e,q),shouldRethrowBridgeMergeLoss()))throw e;applyFastDiff(w,H,e.info.result),J.mergedText=e.info.result}},OBSERVER_SYNC_ORIGIN),J.mergedText!==null&&emitObserverAPathBFired(e.docName)&&(incrementObserverAPathBFires(),console.warn(JSON.stringify({event:`observer-a-path-b-fired`,"doc.name":e.docName??null,xmlFragmentAdvanced:!0,ytextDiverged:!0,mergeBytesChanged:Math.abs(J.mergedText.length-H.length)}))),incrementServerObserverFire(`a`),k=w.toString()}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,e);try{k=w.toString()}catch(e){console.warn(`[Server Observer A] Baseline recovery also failed:`,e)}}},H=()=>{withSpanSync(`observer.runASync`,{attributes:{"doc.name":e.docName??``}},B)},q=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=L();k=w.toString(),J=e}catch(e){incrementServerObserverError(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),j=!0}return}j=!0}};if(S.length>0&&w.length===0)try{let e=yXmlFragmentToProseMirrorRootNode(S,D).toJSON(),O=E.serialize(e),j=prependFrontmatter(L(),O);t.transact(()=>{w.insert(0,j)},OBSERVER_SYNC_ORIGIN),k=j}catch(e){incrementServerObserverError(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),k=``}let J=L(),Y=()=>{try{let D=w.toString(),{frontmatter:O,body:j}=stripFrontmatter(D);if(normalizeBridge(k)===normalizeBridge(D)){J!==O&&(recordFrontmatterEditSurface(`source-mode`),J=O);return}let F=e.resolveEmbed&&e.docName?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.docName}:void 0,L=E.parseWithFallback(j,F),B=e.schema.nodeFromJSON(L);t.transact(()=>{updateYFragment(t,S,B,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN),J!==O&&(recordFrontmatterEditSurface(`source-mode`),J=O),incrementServerObserverFire(`b`);try{let t=prependFrontmatter(O,E.serialize(L));assertBridgeInvariant(w.toString(),t,{site:`observer-b`,docName:e.docName}),k=t}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),k=prependFrontmatter(O,j)}}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;incrementServerObserverError(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=yXmlFragmentToProseMirrorRootNode(S,D).toJSON(),t=E.serialize(e);k=prependFrontmatter(L(),t)}catch(e){if(e instanceof BridgeInvariantViolationError)throw e;console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},ee=()=>{withSpanSync(`observer.runBSync`,{attributes:{"doc.name":e.docName??``}},Y)},te=(e,t)=>{if(t.origin!==OBSERVER_SYNC_ORIGIN){if(isPairedWriteOrigin(t.origin)){try{let e=L();k=w.toString(),J=e}catch(e){incrementServerObserverError(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),F=!0}return}F=!0}},ne=(t,S)=>{withSpanSync(`observer.dispatch`,{attributes:{"doc.name":e.docName??``}},t=>{if(!j&&!F){t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}if(S.every(e=>e.origin===OBSERVER_SYNC_ORIGIN)){j=!1,F=!1,t.setAttribute(`observer.dispatch`,`none`),e.onDispatch?.(`none`);return}let w=j,E=F;j&&(j=!1,e.onDispatch?.(`a`),H()),F&&(F=!1,e.onDispatch?.(`b`),ee()),t.setAttribute(`observer.dispatch`,w&&E?`a-then-b`:w?`a`:E?`b`:`none`)})};S.observeDeep(q),w.observe(te),t.on(`afterAllTransactions`,ne);let ae=attachQuiescenceTracker(t);return()=>{ae(),t.off(`afterAllTransactions`,ne),S.unobserveDeep(q),w.unobserve(te)}}const log$7=getLogger(`persistence`);var DocumentOpenSizeLimitError=class extends Error{docName;size;limit;constructor(e,t,S=DOCUMENT_OPEN_BYTE_LIMIT){super(`Document "${e}" is ${formatFileSize(t)}; Open Knowledge opens documents up to ${formatFileSize(S)}.`),this.name=`DocumentOpenSizeLimitError`,this.docName=e,this.size=t,this.limit=S}};function resolveWriterFromOrigin(e,t){if(!e||typeof e!=`object`)return null;let S=e;if(S.source===`local`){let e=S.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?FILE_SYSTEM_WRITER:e.origin===`upstream-import`||e.origin===`git-upstream`?GIT_UPSTREAM_WRITER:SERVICE_WRITER}if(S.source===`connection`){let e=S.connection?.context;if(typeof e?.principalId==`string`){let S=e.principalId,w=t?.();return w&&w.id===S&&w.display_name&&w.display_email?{id:w.id,name:w.display_name,email:w.display_email}:{id:S,name:`Local User`,email:`${S}@openknowledge.local`}}return SERVICE_WRITER}return null}const ERRNO_FS_CODES=new Set([`EACCES`,`EBADF`,`EBUSY`,`EEXIST`,`EISDIR`,`ELOOP`,`EMFILE`,`ENFILE`,`ENOENT`,`ENOSPC`,`ENOTDIR`,`EPERM`,`EROFS`,`ETXTBSY`,`EXDEV`]);function classifyDeferredStoreError(e){if(typeof e!=`object`||!e)return`unknown`;let t=e,S=typeof t.message==`string`?t.message:``;return S.startsWith(`symlink-escape:`)?`disk-write`:typeof t.code==`string`&&ERRNO_FS_CODES.has(t.code)?S.includes(`rename`)?`traced-rename`:`disk-write`:e instanceof BridgeInvariantViolationError?`serialize`:`unknown`}function captureDocSnapshotForPersistence(e){return{sv:encodeStateVector(e),json:yXmlFragmentToProseMirrorRootNode(e.getXmlFragment(`default`),schema).toJSON()}}function safeContentPath(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let S=resolve(t,`${e}${getDocExtension(e)}`);if(!S.startsWith(`${t}/`))throw Error(`Invalid document name: ${e}`);return S}function isWithinContentDir(e,t){return e===t||e.startsWith(t+sep)}const reconciledBaseByBranch=new Map;let activeBranch=`main`;function switchReconciledBaseScope(e){activeBranch=e,reconciledBaseByBranch.has(e)||reconciledBaseByBranch.set(e,new Map)}function getActiveBranch(){return activeBranch}function getReconciledBase(e){return reconciledBaseByBranch.get(activeBranch)?.get(e)}function setReconciledBase(e,t){reconciledBaseByBranch.has(activeBranch)||reconciledBaseByBranch.set(activeBranch,new Map),reconciledBaseByBranch.get(activeBranch)?.set(e,t)}function deleteReconciledBase(e){reconciledBaseByBranch.get(activeBranch)?.delete(e)}let batchInProgress=!1;function setBatchInProgress(e){batchInProgress=e}function isBatchInProgress(){return batchInProgress}function createPersistenceExtension(e){let t=e?.contentDir??process.cwd(),S;try{S=realpathSync(t)}catch{S=t}let w=e?.projectDir??process.cwd(),E=e?.shadowRef,D=e?.contentRoot??(relative(w,S)||`.`),O=e?.backlinkIndex,k=e?.getPrincipal,j=e?.onAgentCommit,F=e?.onDiskFlush,L=e?.mdManager??mdManager,B={projectDir:w,contentDir:S,lkgCache:new Map,homedirOverride:e?.configHomedirOverride,onConfigRejected:e?.onConfigRejected},H=new Set,q=e?.applyDiskContentToDoc??applyDiskContentToDoc,J=null,Y=8,ee=new Map,te=e?.gitEnabled??!0,ne=e?.commitDebounceMs??15e3,ae=e?.wipRef??`refs/wip/main`,oe=e?.getCurrentBranch,se=null,ce=0,ue=null,de=!1,fe=null,me=new Map;async function ge(){Me();let e=Date.now();return withSpan(`persistence.commitToWipRef`,void 0,async()=>await _e()).finally(()=>{je?.record((Date.now()-e)/1e3)})}async function _e(){let e=E?.current;if(e){let t=swapContributors(),S=oe?.()??`main`;if(t.size===0){let t={v:1,writer_id:SERVICE_WRITER.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:SERVICE_WRITER.name,color_seed:SERVICE_WRITER.id,docs:[]},w=`${formatWipSubject([])}\n\n${formatOkActor(t)}`;try{let t=await commitWip(e,SERVICE_WRITER,D,w,S);ce=0,log$7.info({sha:t.slice(0,8),writer:SERVICE_WRITER.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${SERVICE_WRITER.id}`);try{backfillRenameLogCommitSha(e.gitDir,SERVICE_WRITER.id,t,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$7.warn({err:e},`[rename-log] service-writer backfill failed`)}}catch(e){ce++,incrementGitAutoSaveFailure(),log$7.error({err:e,attempt:ce},`[persistence] Shadow commit failed (attempt ${ce})`),ce>=3&&log$7.error({attempt:ce},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let w;try{w=await buildWipTree(e,D)}catch(e){restoreContributors(t),ce++,incrementGitAutoSaveFailure(),log$7.error({err:e,attempt:ce},`[persistence] Shadow WIP tree build failed (attempt ${ce})`);return}let E=!1;for(let[D,O]of t){let t={id:D,name:O.displayName,email:`${D}@openknowledge.local`},k=[...O.docs],F=O.actor,L=[...O.summaries],B=[...O.previousPaths],H={v:1,writer_id:D,principal:F?.principalId??null,agent_session:D.startsWith(`agent-`)?D.slice(6):null,agent_type:F?.agentType??null,client_name:F?.clientName??null,client_version:F?.clientVersion??null,label:F?.label??null,display_name:O.displayName,color_seed:O.colorSeed,docs:k,...L.length>0?{summaries:L}:{},...B.length>0?{previous_paths:B}:{}},q=`${composeCommitSubject(O.subjectOverride??formatWipSubject(k),L)}\n\n${formatOkActor(H)}`;try{let O=await commitWipFromTree(e,t,w,q,S);E=!0,log$7.info({sha:O.slice(0,8),writer:D,tree:w.slice(0,8)},`[persistence] Shadow WIP commit: ${O.slice(0,8)} on refs/wip/${D}`);try{backfillRenameLogCommitSha(e.gitDir,D,O,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$7.warn({err:e},`[rename-log] backfill failed; will retry next commit`)}D.startsWith(`agent-`)&&j?.()}catch(e){restoreContributorEntry(D,O),incrementGitWriterCommitFailure(),log$7.error({err:e,writer:D},`[persistence] Per-writer shadow commit failed for ${D}`)}}E?ce=0:(ce++,incrementGitAutoSaveFailure(),ce>=3&&log$7.error({attempt:ce},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=shadowGit({gitDir:resolve(w,`.git`),workTree:w}),S=resolve(w,`.git/index-wip`),O={GIT_INDEX_FILE:S};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(O).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?log$7.info({},`[persistence] Empty repo — starting with empty index`):log$7.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(O).raw(`add`,D);let e=(await t.env(O).raw(`write-tree`)).trim(),S=null;try{S=(await t.raw(`rev-parse`,ae)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let w=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];S&&w.push(`-p`,S);let E=(await t.raw(...w)).trim();await t.raw(`update-ref`,ae,E),ce=0,log$7.info({sha:E.slice(0,8),wipRef:ae},`[persistence] Git commit: ${E.slice(0,8)} on ${ae}`)}catch(e){ce++,incrementGitAutoSaveFailure(),log$7.error({err:e,attempt:ce},`[persistence] Git commit failed (attempt ${ce})`),ce>=3&&log$7.error({attempt:ce},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{tracedUnlinkSync(S)}catch{}}}function ve(e){if(e<=0)return ne;let t=2**Math.min(e,5),S=Math.random()*.25*ne;return ne*t+S}function ye(){te&&(isBatchInProgress()||(se&&clearTimeout(se),se=setTimeout(()=>{if(se=null,ue){de=!0;return}ue=ge().finally(()=>{ue=null,de&&(de=!1,ye())})},ve(ce))))}async function Ce(){se&&(clearTimeout(se),se=null,ue||=ge().finally(()=>{ue=null,de&&(de=!1,ye())})),ue&&await ue}function we(t,S,w){try{let E=t.getXmlFragment(`default`),D=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:w}:void 0,O=mdManager.parseWithFallback(S,D),k=schema.nodeFromJSON(O);t.transact(()=>{updateYFragment(t,E,k,{mapping:new Map,isOMark:new Map})},OBSERVER_SYNC_ORIGIN)}catch(e){incrementPersistenceReconciliationFailures(),log$7.warn({err:e,documentName:w},`[persistence] reconcileFragmentNow failed for ${w}`)}}let Te=null,De=null,je=null;function Me(){if(Te)return;let e=getMeter();Te=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),De=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),je=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}async function Pe({document:e,documentName:t,lastTransactionOrigin:w}){Me();let E=Date.now();return withSpan(`persistence.onStoreDocument`,{attributes:{"doc.name":t}},async()=>{let E=e.getMap(`lifecycle`).get(`status`);if(E===`deleted-upstream`||E===`renamed`||E===`conflict`){log$7.info({documentName:t,lifecycleStatus:E},`[persistence] Skipped store for ${t}: lifecycle=${E}`),ee.delete(t),H.delete(t);return}if(!isDocQuiescent(e)){let S=ee.get(t)??0;if(S<8){let w=getMsSinceLastUserTx(e);console.warn(JSON.stringify({event:`persistence-skip-non-quiescent`,"doc.name":t,wallClockMsSinceLastTransaction:w??null,deferCount:S})),incrementPersistenceSkipNonQuiescent(),ee.set(t,S+1);return}console.warn(JSON.stringify({event:`persistence-force-flush-during-burst`,"doc.name":t,wallClockMsSinceLastTransaction:getMsSinceLastUserTx(e)??null,deferCount:S})),incrementPersistenceForceFlushDuringBurst()}let{sv:D,json:j}=captureDocSnapshotForPersistence(e),{frontmatter:B,body:J}=stripFrontmatter(e.getText(`source`).toString()),Y=prependFrontmatter(B,J),te;try{te=assertBridgeInvariant(Y,prependFrontmatter(B,L.serialize(j)),{site:`persistence`,docName:t,suppressDevThrow:!0})}catch(e){incrementPersistenceSanityCheckSerializeFailures(),console.warn(JSON.stringify({event:`persistence-sanity-check-serialize-failed`,"doc.name":t,"error.type":e instanceof Error?e.constructor.name:typeof e,timestamp:new Date().toISOString()})),log$7.warn({err:e,documentName:t},`[persistence] Sanity-check serialize failed for ${t}; proceeding with ytext bytes`),te=!1}te||we(e,J,t);let ne=getReconciledBase(t);if(ne!==void 0&&normalizeBridge(Y)===normalizeBridge(ne)){contributorCount()>0&&ye(),ee.delete(t);return}if(ne===void 0&&normalizeBridge(Y)===``){log$7.warn({documentName:t},`[persistence] Skipped phantom write for ${t}: empty Y.Doc with no reconciled base`),ee.delete(t);return}let ae=resolveWriterFromOrigin(w,k);if(ae&&ae.id!==SERVICE_WRITER.id&&(hasContributor(ae.id)||recordContributor(t,ae.id,ae.name,ae.id)),ne!==void 0){let w=classifyDuplication(Y,ne);if(w.kind===`block`){if(H.has(t)){log$7.warn({documentName:t},`[persistence] Tripwire breaker active — skipping duplicate store for ${t}`);return}let E=e.getXmlFragment(`default`).length;console.warn(JSON.stringify({event:`ok-persistence-duplication-blocked`,"doc.name":t,candidateBytes:Y.length,baseBytes:ne.length,fragmentChildren:E,copies:w.copies,reason:w.reason}));try{let w=safeContentPath(t,S),E;if(existsSync(w)){let e=null;try{e=realpathSync(w)}catch(e){log$7.warn({err:e,documentName:t},`[persistence] Tripwire reset realpath failed for ${t}; using currentBase`)}if(e&&isWithinContentDir(e,S))try{E=readFileSync(e,`utf-8`)}catch(S){log$7.warn({err:S,documentName:t,canonical:e},`[persistence] Tripwire reset readFileSync failed for ${t}; using currentBase`),E=ne}else e&&console.warn(`[persistence] symlink-escape on tripwire reset: ${w} → ${e}, using currentBase`,{docName:t,originalPath:w,canonical:e,contentDir:S}),E=ne}else E=ne;e.transact(()=>{q(e,E)},FILE_WATCHER_ORIGIN),H.delete(t)}catch(e){H.add(t),log$7.error({err:e,documentName:t},`[persistence] Tripwire reset failed for ${t}`)}ee.delete(t);return}}let oe=safeContentPath(t,S);await tracedMkdir(dirname(oe),{recursive:!0});let se;try{se=await realpath(oe)}catch(e){let S=e.code;if(S===`ENOENT`){let e=!1;try{e=lstatSync(oe).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&log$7.warn({err:e,path:oe},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:t,reason:`broken-symlink`}),se=oe}else if(S===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${oe}`),Error(`Symlink cycle detected at ${oe}`);else throw e}if(!isWithinContentDir(se,S)){let e=`symlink-escape: ${oe} resolves to ${se} outside ${S}`;throw console.error(`[persistence] ${e}`,{docName:t,originalPath:oe,canonical:se,contentDir:S}),Error(e)}let ce=`${se}.tmp.${crypto.randomUUID()}`;try{await tracedWriteFile(ce,Y,`utf-8`),await tracedRename(ce,se),registerWrite(se,contentHash(Y)),incrementPersistenceDiskWrite();try{F?.(t,D,Y,ne??null)}catch(e){log$7.warn({err:e,documentName:t},`[persistence] onDiskFlush callback failed for ${t}`)}}catch(e){try{tracedUnlinkSync(ce)}catch{}throw ee.delete(t),log$7.error({err:e,documentName:t},`[persistence] Failed to save ${t}`),e}log$7.info({filePath:se,bytes:Y.length},`[persistence] Wrote ${se} (${Y.length} bytes)`),setReconciledBase(t,Y),H.delete(t),ee.delete(t),O&&(O.updateDocumentFromMarkdown(t,Y),O.saveToDisk().catch(e=>{log$7.warn({err:e,documentName:t},`[backlinks] Failed to persist cache for ${t}`)})),setActiveSpanAttributes({"persistence.bytes":Y.length}),ye()}).finally(()=>{De?.record((Date.now()-E)/1e3)})}function Ie({document:e,documentName:t,lastTransactionOrigin:S}){me.set(t,{branch:getActiveBranch(),document:e,lastTransactionOrigin:S})}async function Re(e=`within-branch`){return fe?(J=J===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,fe):(fe=(async()=>{let t=e;for(;;){let e=[...me.entries()];if(me.clear(),t!==`discard-stale`){for(let[t,S]of e)if(S.branch===getActiveBranch())try{await Pe({document:S.document,documentName:t,lastTransactionOrigin:S.lastTransactionOrigin})}catch(e){let S=process.env.OK_TELEMETRY_VERBOSE===`1`,w=``;try{w=String(e?.message??``)}catch{w=``}let E=fnv1aDigest(w),D;try{D=classifyDeferredStoreError(e)}catch(e){let w=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":t,classifyErrorHash:fnv1aDigest(w),errorMessageHash:E,...S?{classifyErrorMessage:w}:{},timestamp:new Date().toISOString()})),D=`unknown`}incrementDeferredStoreFailures(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":t,errorClass:D,errorMessageHash:E,...S?{errorMessage:w}:{},timestamp:new Date().toISOString()})),log$7.error({err:e,documentName:t},`[persistence] Deferred store failed for ${t}`)}}let S=J;if(J=null,me.size===0&&S===null)break;t=S??`within-branch`}})().finally(()=>{fe=null}),fe)}let ze={async onLoadDocument({document:t,documentName:w,context:E}){if(isSystemDoc(w))return;if(isConfigDoc(w)){loadConfigDoc(t,w,B);return}Me();let D=Date.now();return withSpan(`persistence.onLoadDocument`,{attributes:{"doc.name":w}},async()=>{log$7.info({documentName:w,connections:t.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${w} (connections: ${t.getConnectionsCount?.()??`?`})`);let E=safeContentPath(w,S);if(!existsSync(E))return;let D=E;try{let e=realpathSync(E);if(!isWithinContentDir(e,S)){console.warn(`[persistence] symlink-escape on load: ${E} → ${e}, refusing`);return}D=e}catch(e){if(e.code===`ELOOP`){console.warn(`[persistence] Symlink cycle on load: ${E}, refusing`);return}}let O=statSync(D).size;if(O>524288)throw log$7.warn({documentName:w,fileSize:O,limit:DOCUMENT_OPEN_BYTE_LIMIT},`[persistence] Document exceeds open byte limit; refusing to load`),new DocumentOpenSizeLimitError(w,O);let k=readFileSync(E,`utf-8`),j=t.getXmlFragment(`default`);log$7.info({documentName:w,fragmentLength:j.length},`[persistence] onLoadDocument ${w}: fragment.length=${j.length} before update`),j.length===0?(t.transact(()=>{applyDiskContentToDoc(t,k,e?.resolveEmbed,w,e?.resolveSize)},FILE_WATCHER_ORIGIN),log$7.info({filePath:E,children:j.length},`[persistence] Loaded ${E} into Y.Doc (${j.length} children)`),j.observeDeep(()=>{log$7.info({documentName:w,fragmentLength:j.length},`[persistence] MUTATION on ${w}: fragment.length=${j.length}`)})):log$7.info({documentName:w,children:j.length},`[persistence] Skipped load for ${w} — fragment already has ${j.length} children`),setReconciledBase(w,k)}).finally(()=>{Te?.record((Date.now()-D)/1e3)})},async onStoreDocument({document:e,documentName:t,lastTransactionOrigin:S,lastContext:w}){if(!isSystemDoc(t)){if(isConfigDoc(t)){await storeConfigDoc(e,t,S,B);return}if(isBatchInProgress()){Ie({document:e,documentName:t,lastTransactionOrigin:S});return}return Pe({document:e,documentName:t,lastTransactionOrigin:S})}}};async function Be(){ue&&await ue}async function Ve(){if(ue){await ue;return}contributorCount()!==0&&(ue=ge().finally(()=>{ue=null,de&&(de=!1,ye())}),await ue)}return{extension:ze,flushDeferredStores:Re,flushPendingGitCommit:Ce,flushContributors:Ve,waitForPendingCommits:Be,configPersistenceCtx:B}}const MARKDOWN_LINK_OR_IMAGE_RE=/!?\[[^\]\n]*(?:\][^[\]\n]*)?\]\((?:<([^>\n]+)>|([^)\s]+))(?:\s+['"][^'"]*['"])?\)/g,WIKI_LINK_OR_EMBED_RE=/!?\[\[([^[\]|#]+?)(?:#[^\]|]+?)?(?:\|[^\]]+?)?\]\]/g,HTML_LINK_ATTR_RE=/<[\w:-]+\b[^>]*?\s+(?:href|src)\s*=\s*(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function isRemoteOrOpaqueHref(e){return e.startsWith(`#`)||e.startsWith(`//`)||e.startsWith(`data:`)||/^[a-z][a-z0-9+.-]*:/i.test(e)}function stripHrefDecorations(e){let t=e.trim().replace(/^<(.+)>$/,`$1`),S=t.indexOf(`#`),w=S>=0?t.slice(0,S):t,E=w.indexOf(`?`);return E>=0?w.slice(0,E):w}function isLocalAssetReferenceHref(e){let t=stripHrefDecorations(e);return!t||isRemoteOrOpaqueHref(t)?!1:ASSET_EXTENSIONS.has(extname(t).slice(1).toLowerCase())}function assetReferenceSignature(e){return e?[...new Set(extractLocalAssetHrefs(e).filter(isLocalAssetReferenceHref))].sort().join(`\0`):``}function assetReferencesChanged(e,t){return assetReferenceSignature(e)!==assetReferenceSignature(t)}function decodeHrefPath(e){let t=stripHrefDecorations(e);try{return decodeURI(t)}catch{return t}}function mediaKindForAssetPath(e){return mediaKindForSidebarAssetExtension(extname(e).slice(1).toLowerCase())}function errnoCode$1(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`?e.code:null}function collectHrefsFromLine(e,t){for(let S of e.matchAll(MARKDOWN_LINK_OR_IMAGE_RE)){let e=S[1]??S[2];e&&t.add(e)}for(let S of e.matchAll(WIKI_LINK_OR_EMBED_RE)){let e=S[1];e&&t.add(e)}for(let S of e.matchAll(HTML_LINK_ATTR_RE)){let e=S[1]??S[2]??S[3]??S[4];e&&t.add(e)}}function stripHtmlComments(e,t){let S=e,w=``;for(;S.length>0;){if(t.inComment){let e=S.indexOf(`-->`);if(e===-1)return w;S=S.slice(e+3),t.inComment=!1;continue}let e=S.indexOf(`<!--`);if(e===-1)return w+S;w+=S.slice(0,e),S=S.slice(e+4),t.inComment=!0}return w}function extractLocalAssetHrefs(e){let t=new Set,S=createCodeFenceTracker(),w={inComment:!1};for(let E of e.replaceAll(`\r
1226
1226
  `,`
1227
1227
  `).replaceAll(`\r`,`
1228
1228
  `).split(`
@@ -1249,7 +1249,7 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
1249
1249
  `).map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e--)try{let S=JSON.parse(t[e]);if(S&&typeof S==`object`&&!Array.isArray(S))return S}catch{}return null}function parseOwnersEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`owners`&&Array.isArray(e.owners)){let t=[];for(let S of e.owners){if(!S||typeof S!=`object`)continue;let e=S,w=typeof e.login==`string`?e.login:null,E=e.kind===`user`||e.kind===`org`?e.kind:null;if(w===null||E===null)continue;let D=typeof e.avatarUrl==`string`?e.avatarUrl:void 0;t.push({login:w,kind:E,...D?{avatarUrl:D}:{}})}return{ok:!0,owners:t}}return e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function isOwnersErrorCode(e){return e===`auth-required`||e===`network`}function parseNameCheckEvent(e){return e===null?{ok:!1,error:`network`}:e.type===`name-check`&&typeof e.available==`boolean`?{ok:!0,available:e.available}:e.type===`error`?{ok:!1,error:isOwnersErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}const PUBLISH_ERROR_CODES=new Set([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]);function isPublishErrorCode(e){return typeof e==`string`&&PUBLISH_ERROR_CODES.has(e)}function parsePublishEvent(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`publish`){let t=typeof e.ownerLogin==`string`?e.ownerLogin:null,S=typeof e.repoName==`string`?e.repoName:null,w=typeof e.cloneUrl==`string`?e.cloneUrl:null,E=typeof e.defaultBranch==`string`?e.defaultBranch:null;return t!==null&&S!==null&&w!==null&&E!==null?{ok:!0,ownerLogin:t,repoName:S,cloneUrl:w,defaultBranch:E}:{ok:!1,error:`network`}}return e.type===`error`?{ok:!1,error:isPublishErrorCode(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function emitSharePublishLog(e,t,S){let w=[`action=${e}`,`result=${t}`];S?.count!==void 0&&w.push(`count=${S.count}`),S?.available!==void 0&&w.push(`available=${S.available}`),console.log(`[share] ${w.join(` `)}`)}function redactShareSubprocessStderr(e){return e.replace(/(https?:\/\/)([^:@\s/]+):([^@\s/]+)@/g,`$1$2:***@`)}const MAX_ZIP_BYTES=102400,BUNDLE_SKILL_NAME={discovery:`open-knowledge-discovery`,project:`open-knowledge`},DESKTOP_SKILLS_REL=`Open Knowledge.app/Contents/Resources/cli/dist/assets/skills`;function resolveBundledSkillDir(e,t={}){let S=t.platform??process.platform,w=t.checkDesktop??!1,E=t.home??homedir(),D=[];w&&S===`darwin`&&(D.push(join(`/Applications`,DESKTOP_SKILLS_REL,e)),D.push(join(E,`Applications`,DESKTOP_SKILLS_REL,e))),D.push(fileURLToPath(new URL(`../dist/assets/skills/${e}`,import.meta.url))),D.push(fileURLToPath(new URL(`../assets/skills/${e}`,import.meta.url))),D.push(fileURLToPath(new URL(`./assets/skills/${e}`,import.meta.url)));for(let e of D)if(existsSync(e))return e;throw Error(`Bundled skill asset directory not found for bundle '${e}'. Tried: ${D.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*walkFiles(e,t=e){let S=await readdir(e,{withFileTypes:!0});for(let w of S){let S=join(e,w.name);w.isDirectory()?yield*walkFiles(S,t):w.isFile()&&(yield relative(t,S))}}function computeWrapperFolderName(e,t=basename){return t(e)||`open-knowledge`}function toPosixZipPath(e,t=sep){return t===`/`?e:e.split(t).join(`/`)}async function zipDirectory(e,t,S=computeWrapperFolderName(e)){let w=new import_yazl.ZipFile;w.addEmptyDirectory(`${S}/`);let E=[];for await(let t of walkFiles(e))E.push(t);E.sort();for(let t of E){let E=join(e,t),D=`${S}/${toPosixZipPath(t)}`;w.addFile(E,D)}w.end(),await new Promise((e,S)=>{let E=createWriteStream(t);w.outputStream.pipe(E),E.on(`close`,()=>e()),E.on(`error`,S),w.outputStream.on(`error`,S)})}async function sha256OfFile(e){return new Promise((t,S)=>{let w=createHash(`sha256`),E=createReadStream(e);E.on(`data`,e=>w.update(e)),E.on(`end`,()=>t(w.digest(`hex`))),E.on(`error`,S)})}function extractMetadataVersion(e){let t=e.indexOf(`
1250
1250
  ---`,4);if(!e.startsWith(`---
1251
1251
  `)||t<0)return;let S=e.slice(4,t),w=S.search(/^metadata:/m);if(w<0)return;let E=S.slice(w).split(`
1252
- `).slice(1);for(let e of E){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,S={}){let w=S.bundle??`project`,E=statSync(e).size;if(E>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${E} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let D=await sha256OfFile(e),O=await readFile$1(join(S.sourceDir??resolveBundledSkillDir(w,{checkDesktop:!1}),`SKILL.md`),`utf-8`),k=BUNDLE_SKILL_NAME[w];if(!RegExp(`^name:\\s+${k}$`,`m`).test(O.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${k}'. Check packages/server/assets/skills/${w}/SKILL.md frontmatter.`);let j=extractMetadataVersion(O);if(t!==void 0){if(!j)throw Error(`SKILL.md metadata.version missing. Add it to packages/server/assets/skills/${w}/SKILL.md.`);if(j!==t)throw Error(`SKILL.md metadata.version (${j}) does not match expected version (${t}).`)}return{size:E,sha256:D,skillVersion:j}}async function buildSkillZip(e={}){let t=e.bundle??`project`,S=e.sourceDir??resolveBundledSkillDir(t,{checkDesktop:e.checkDesktop??!1}),w=e.outputPath??join(process.cwd(),`openknowledge.skill`);await zipDirectory(S,w,BUNDLE_SKILL_NAME[t]);let{size:E,sha256:D,skillVersion:O}=await validateSkillZip(w,e.expectedSkillVersion,{bundle:t,sourceDir:S});return{outputPath:w,size:E,sha256:D,skillVersion:O}}const SKILL_INSTALL_EVENTS_FILE_REL=[`.ok`,`skill-install-events.jsonl`];async function recordSkillInstallEvent(e,t){let S=t?.homedir??(()=>process.env.HOME??``),w=t?.warn??((e,t)=>{console.warn(t,e)}),E=S();if(!E){w({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let D=join(E,...SKILL_INSTALL_EVENTS_FILE_REL),O=`${JSON.stringify(e)}\n`;try{await tracedMkdir(dirname(D),{recursive:!0})}catch(e){w({event:`skill-install-events.mkdir-failed`,error:String(e)},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await tracedWriteFile(D,O,{flag:`a`,encoding:`utf-8`})}catch(e){w({event:`skill-install-events.append-failed`,error:String(e)},`[skill-install-events] append failed; telemetry skipped`)}}const readFileAsync=promisify(readFile);function skillStateYamlPath(e){return join(e,...SKILL_STATE_REL)}const DEFAULT_LOGGER={warn:(e,t)=>console.warn(t,e)},TRACED_FS_ADAPTER={writeFile:(e,t,S)=>tracedWriteFile(e,t,S),rename:(e,t)=>tracedRename(e,t)};async function readSkillStateFile(e,t=DEFAULT_LOGGER){let S=skillStateYamlPath(e),w;try{w=await readFileAsync(S,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let E=(0,import_dist$1.parseDocument)(w);if(E.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:S,errors:E.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let D=SkillStateSchema.safeParse(E.toJSON());if(!D.success){let e=D.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:S,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:S,issues:D.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return D.data}async function writeSkillStateFile(e,t){let S=SkillStateSchema.safeParse(t);if(!S.success)throw Error(`Refusing to write invalid skill-state: ${S.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let w=skillStateYamlPath(e);await tracedMkdir(dirname(w),{recursive:!0});let E=(0,import_dist$1.parseDocument)(``);E.contents=E.createNode(S.data),await atomicWriteFile(w,E.toString(),{fs:TRACED_FS_ADAPTER})}async function readTargetVersion(e,t,S){let w=await readSkillStateFile(e,S);return w===null?null:w.targets[t]?.version??null}async function readTargetRecordedAt(e,t,S){let w=await readSkillStateFile(e,S);return w===null?null:w.targets[t]?.recordedAt??null}async function writeTargetVersion(e,t,S,w,E){if(!SKILL_STATE_VERSION_RE.test(S))throw Error(`Refusing to write invalid version string: ${S}`);let D=await readSkillStateFile(e,E)??emptySkillState(),O=new Date().toISOString(),k=D.targets[t],j=w===void 0?k?.surface??void 0:w,F=j===void 0?{version:S,recordedAt:O}:{version:S,recordedAt:O,surface:j};await writeSkillStateFile(e,{...D,targets:{...D.targets,[t]:F}})}async function readServerPackageVersion(){let e=await readFileAsync(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}async function readSkillInstallStateSnapshot(e,t){let[S,w]=await Promise.all([readServerPackageVersion(),readAllTargets(e,t)]);return{currentVersion:S,targets:w}}async function readAllTargets(e,t=DEFAULT_LOGGER){let S=null;try{S=await readSkillStateFile(e,t)}catch(w){t.warn({event:`skill-state.read-error`,path:skillStateYamlPath(e),error:String(w)},`non-ENOENT error reading skill-state.yml; treating as absent`),S=null}let w=SKILL_STATE_TARGETS.map(e=>{let t=S?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(w)}const CENTRAL_SKILL_DIR_REL=[`.agents`,`skills`,`open-knowledge-discovery`],LEGACY_USER_SKILL_NAME=`open-knowledge`,LEGACY_USER_SKILL_HOST_DIRS=[`.claude`,`.cursor`,`.agents`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS$3=6e4;function centralSkillDir(e){return join(e,...CENTRAL_SKILL_DIR_REL)}async function centralSkillExists(e){try{return(await stat$1(centralSkillDir(e))).isDirectory()}catch{return!1}}function runSpawn(e,t,S,w,E){return new Promise(D=>{let O;try{O=e(t,S,{env:w,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){D({kind:`spawn-error`,stderr:``,error:e});return}let k=``,j=!1,F=e=>{j||(j=!0,clearTimeout(L),D(e))};O.stderr?.on(`data`,e=>{k+=typeof e==`string`?e:e.toString(`utf-8`)}),O.on(`error`,e=>{F({kind:`spawn-error`,stderr:k,error:e})}),O.on(`exit`,e=>{F(e===0?{kind:`ok`,exitCode:e,stderr:k}:{kind:`nonzero`,exitCode:e,stderr:k})});let L=setTimeout(()=>{try{O.kill(`SIGTERM`)}catch{}F({kind:`timeout`,stderr:k})},E)})}async function anyLegacyUserSkillExists(e){for(let t of LEGACY_USER_SKILL_HOST_DIRS)try{if((await stat$1(join(e,t,`skills`,LEGACY_USER_SKILL_NAME))).isDirectory())return!0}catch{}return!1}async function removeLegacyUserSkill(e,t,S,w,E){if(!await anyLegacyUserSkillExists(e))return;let D=await runSpawn(t,`npx`,[`-y`,SKILLS_CLI_SPEC,`remove`,`--agent`,`*`,`-g`,LEGACY_USER_SKILL_NAME],S,w);D.kind!==`ok`&&E.warn({event:`skill-install.legacy-remove-failed`,reason:D.kind,exitCode:D.exitCode,stderr:D.stderr},"Legacy `open-knowledge` skill removal did not exit cleanly; continuing with install.")}async function installUserSkill(e={}){let t=e.home??homedir(),S=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},w=e.spawn??spawn,E=e.timeoutMs??DEFAULT_TIMEOUT_MS$3,D=e.surface??`cli-npx-skills-add`,O=async(e,w,E)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:D,target:`cli-hosts`,bundle:`discovery`,outcome:e,...w===void 0?{}:{version:w},...E===void 0?{}:{reason:E}},{homedir:()=>t,warn:S.warn})},k;try{k=await readServerPackageVersion()}catch(e){return S.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await O(`failed`,void 0,`version-read-failed`),`failed`}let j=await readTargetVersion(t,`cli-hosts`,S).catch(e=>(S.warn({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(j!==null&&j===k){if(await centralSkillExists(t))return S.info?.({event:`skill-install.skip-current`,version:k},`Open Knowledge skill already installed at current version; skipping.`),await O(`skip-current`,k),`skip-current`;S.info?.({event:`skill-install.reinstall-missing`,version:k,path:centralSkillDir(t)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let F;try{F=resolveBundledSkillDir(`discovery`,{checkDesktop:!1})}catch(e){return S.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled discovery SKILL.md asset not found.`),await O(`failed`,k,`bundled-asset-missing`),`failed`}let L={...process.env,HOME:t};await removeLegacyUserSkill(t,w,L,E,S);let B=await runSpawn(w,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,F,`--agent`,`*`,`-g`,`-y`,`--copy`],L,E);if(B.kind===`ok`){try{await writeTargetVersion(t,`cli-hosts`,k,D,S)}catch(e){return S.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),await O(`failed`,k,`sidecar-write-failed`),`failed`}return S.info?.({event:`skill-install.installed`,version:k},`Open Knowledge skill installed to detected agent hosts.`),await O(`installed`,k),`installed`}return B.kind===`timeout`?(S.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:E,stderr:B.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`timeout`),`failed`):B.kind===`spawn-error`?(S.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(B.error),stderr:B.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`spawn-error`),`failed`):(S.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:B.exitCode,stderr:B.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`nonzero-exit:${B.exitCode??`unknown`}`),`failed`)}const DOWNLOADS_DIR=`Downloads`,SKILL_FILENAME=`openknowledge.skill`;function defaultDownloadsPath(e){return join(e,DOWNLOADS_DIR,SKILL_FILENAME)}function invokeFileAssociation(e,t,S){let w={detached:!0,stdio:`ignore`};try{return t===`darwin`?(S(`open`,[e],w).unref(),{ok:!0}):t===`win32`?(S(`cmd`,[`/c`,`start`,`""`,e],w).unref(),{ok:!0}):t===`linux`?(S(`xdg-open`,[e],w).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function buildAndOpenSkill(e={}){let t=e.home??homedir(),S=resolve(e.out??defaultDownloadsPath(t)),w=e.platformName??platform(),E=e.spawnFn??spawn,D=e.logger,O=async(e,S,w)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...S===void 0?{}:{version:S},...w===void 0?{}:{reason:w}},{homedir:()=>t,warn:D?.warn})};if(!e.force){let e=null;try{e=await readServerPackageVersion()}catch(e){D?.warn?.({event:`skill-install.gate.version-read-failed`,error:String(e)},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let S=null,w=null;try{[S,w]=await Promise.all([readTargetVersion(t,`claude-cowork`,D),readTargetRecordedAt(t,`claude-cowork`,D)])}catch(e){D?.warn?.({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read claude-cowork install-state; rebuilding.`)}if(S!==null&&S===e)return D?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`Open Knowledge skill already delivered at current version; skipping rebuild.`),await O(`skip-current`,e),{status:`skip-current`,skillVersion:e,...w===null?{}:{recordedAt:w}}}}try{await tracedMkdir(dirname(S),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await O(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let k;try{k=await buildSkillZip({outputPath:S,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await O(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let j={status:`built`,outputPath:k.outputPath,size:k.size,sha256:k.sha256,skillVersion:k.skillVersion};if(k.skillVersion)try{await writeTargetVersion(t,`claude-cowork`,k.skillVersion,`server-build-and-open`,D)}catch(e){D?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:k.skillVersion,error:String(e)},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await O(`built`,k.skillVersion),j;let F=invokeFileAssociation(k.outputPath,w,E);return F.ok?(await O(`installed`,k.skillVersion),{...j,status:`installed`}):(await O(`built`,k.skillVersion,`handoff-${F.reason}`),{...j,handoffError:{reason:F.reason,message:F.message}})}var UiLockCollisionError=class extends ProcessLockCollisionError{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function acquireUiLock(e,t){try{return acquireProcessLock({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof ProcessLockCollisionError&&e.lockName===`ui`?new UiLockCollisionError(e.existing,e.lockPath):e}}function updateUiLockPort(e,t){updateProcessLockPort({lockName:`ui`,lockDir:e,port:t})}function readUiLock(e){return readProcessLock({lockName:`ui`,lockDir:e})}function releaseUiLock(e){releaseProcessLock({lockName:`ui`,lockDir:e})}var UploadWriteError=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function uploadStatusFor(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return assertNeverProblemType(e)}}function classifyUploadErrno(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function uploadTitleFor(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return assertNeverProblemType(e)}}const log$5=getLogger(`upload-streaming`);var HashingPassThrough=class extends Transform{hash=createHash(`sha256`);bytes=0;digested=!1;_transform(e,t,S){this.hash.update(e),this.bytes+=e.length,S(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function tmpUploadDir(e){return resolve(getLocalDir(e),`tmp`)}function mintTempUploadPath(e){let t=tmpUploadDir(e);return tracedMkdirSync(t,{recursive:!0}),resolve(t,`upload-${randomUUID()}`)}function linkTempToFinalWithCollisionRetry(e,t,S){let w=extname(S),E=S.slice(0,S.length-w.length),D=[S,...Array.from({length:99},(e,t)=>`${E}-${t+1}${w}`)];for(let S of D){let w=resolve(t,S);try{tracedLinkSync(e,w);try{tracedUnlinkSync(e)}catch{}return S}catch(t){let S=t.code;if(S===`EEXIST`)continue;try{tracedUnlinkSync(e)}catch{}throw S===`ENOSPC`||S===`EDQUOT`?new UploadWriteError(`urn:ok:error:storage-full`,t):S===`EROFS`||S===`EACCES`||S===`EPERM`?new UploadWriteError(`urn:ok:error:storage-readonly`,t):new UploadWriteError(`urn:ok:error:storage-error`,t)}}try{tracedUnlinkSync(e)}catch{}throw new UploadWriteError(`urn:ok:error:collision-exhaustion`)}function cleanupOrphanUploadTempfiles(e,{ageMs:t=1440*60*1e3}={}){let S=tmpUploadDir(e),w={scanned:0,deleted:0,errors:0};if(!existsSync(S))return w;let E;try{E=readdirSync(S)}catch(e){return log$5.warn({err:e,dir:S},`[upload-tempfile-sweep] readdir failed`),w.errors++,w}let D=Date.now()-t;for(let e of E){if(!e.startsWith(`upload-`))continue;w.scanned++;let t=resolve(S,e);try{if(statSync(t).mtimeMs>=D)continue;tracedUnlinkSync(t),w.deleted++}catch(e){log$5.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),w.errors++}}return(w.deleted>0||w.errors>0)&&log$5.info({dir:S,scanned:w.scanned,deleted:w.deleted,errors:w.errors},`[upload-tempfile-sweep] swept ${w.deleted}/${w.scanned} (errors: ${w.errors})`),w}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let S=t[1],w=S[0];return w!=="`"&&w!==`~`?null:{char:w,length:S.length}}function isFenceClose$2(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$2(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$2(e,t){let S=0;for(;e[t+S]==="`";)S++;if(S===0)return null;let w=t+S,E=w;for(;E<e.length;){if(e[E]!=="`"){E++;continue}let t=0;for(;e[E+t]==="`";)t++;if(t===S)return{nextIndex:E+S};E+=t}return{nextIndex:w}}function readWikiLink$2(e,t){let S=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!S)return null;let w=S[1]?.trim(),E=S[2]?.trim()||null,D=S[3]?.trim()||null;return w?{target:w,alias:D,anchor:E,nextIndex:t+S[0].length}:null}function readMarkdownLink$2(e,t){let S=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!S)return null;let w=S[2]??``;return{text:S[1]??``,hrefRaw:w,href:w.startsWith(`<`)&&w.endsWith(`>`)?w.slice(1,-1):w,titleSuffix:S[3]??``,nextIndex:t+S[0].length}}function readImageRef(e,t){let S=/^!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!S)return null;let w=S[2]??``;return{alt:S[1]??``,hrefRaw:w,href:w.startsWith(`<`)&&w.endsWith(`>`)?w.slice(1,-1):w,titleSuffix:S[3]??``,nextIndex:t+S[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),S=[];for(let e=0;e<t.length;e+=2)S.push({line:t[e]??``,ending:t[e+1]??``});return S}function rewriteWikiLinksInLine(e,t,S){let w=``,E=0,D=0,O=leadingMarkdownPrefixLength$2(e);for(O>0&&(w+=e.slice(0,O),D=O);D<e.length;){if(e[D]===`\\`&&D+1<e.length){w+=e.slice(D,D+2),D+=2;continue}if(e[D]==="`"){let t=readInlineCode$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`&&e[D+1]===`[`){let O=readWikiLink$2(e,D);if(O){O.target===t?(w+=`[[${S}${O.anchor?`#${O.anchor}`:``}${O.alias?`|${O.alias}`:``}]]`,E++):w+=e.slice(D,O.nextIndex),D=O.nextIndex;continue}}w+=e[D],D++}return{markdown:w,rewrites:E}}function recomputeRelativeImageHref(e,t,S){let w=e.indexOf(`#`),E=w>=0?e.slice(w):``,D=w>=0?e.slice(0,w):e,O=D.indexOf(`?`),k=O>=0?D.slice(O):``,j=O>=0?D.slice(0,O):D;if(j.startsWith(`/`)||j.startsWith(`//`)||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(j))return null;let F=posix.dirname(t),L=posix.dirname(S);if(F===L)return null;let B=F===`.`?`/`:`/${F}/`,H=posix.resolve(B,j).slice(1),q=posix.relative(L===`.`?``:L,H);return q||=posix.basename(H),j.startsWith(`./`)&&!q.startsWith(`./`)&&!q.startsWith(`../`)&&(q=`./${q}`),`${q}${k}${E}`}function recomputeRelativeMarkdownHref(e,t,S){let w=e.indexOf(`#`),E=w>=0?e.slice(w):``,D=w>=0?e.slice(0,w):e,O=D.indexOf(`?`),k=O>=0?D.slice(O):``,j=O>=0?D.slice(0,O):D,F=posix.dirname(t),L=posix.relative(F===`.`?``:F,S);return L||=posix.basename(S),j.endsWith(`.mdx`)?L+=`.mdx`:j.endsWith(`.md`)&&(L+=`.md`),j.startsWith(`./`)&&!L.startsWith(`./`)&&!L.startsWith(`../`)&&(L=`./${L}`),`${L}${k}${E}`}function rewriteMarkdownLinksInLine(e,t,S,w){let E=``,D=0,O=0,k=leadingMarkdownPrefixLength$2(e);for(k>0&&(E+=e.slice(0,k),O=k);O<e.length;){if(e[O]===`\\`&&O+1<e.length){E+=e.slice(O,O+2),O+=2;continue}if(e[O]==="`"){let t=readInlineCode$2(e,O);if(t){E+=e.slice(O,t.nextIndex),O=t.nextIndex;continue}}if(e[O]===`[`&&e[O+1]===`[`){let t=readWikiLink$2(e,O);if(t){E+=e.slice(O,t.nextIndex),O=t.nextIndex;continue}}if(e[O]===`!`&&e[O+1]===`[`){let k=readImageRef(e,O);if(k){let j=t===S&&S!==w?recomputeRelativeImageHref(k.href,S,w):null;if(j!==null){let e=k.hrefRaw.startsWith(`<`)&&k.hrefRaw.endsWith(`>`)?`<${j}>`:j;E+=`![${k.alt}](${e}${k.titleSuffix})`,D++}else E+=e.slice(O,k.nextIndex);O=k.nextIndex;continue}}if(e[O]===`[`){let k=readMarkdownLink$2(e,O);if(k){if(resolveInternalHref(k.href,t)?.docName===S){let e=recomputeRelativeMarkdownHref(k.href,t,w),S=k.hrefRaw.startsWith(`<`)&&k.hrefRaw.endsWith(`>`)?`<${e}>`:e;E+=`[${k.text}](${S}${k.titleSuffix})`,D++}else E+=e.slice(O,k.nextIndex);O=k.nextIndex;continue}}E+=e[O],O++}return{markdown:E,rewrites:D}}const MIRROR_TAG_RE=/<Mirror\b([^>]*)\/>/g,MIRROR_SRC_ATTR_RE=/(\bsrc=)(["'])([^"']*)\2/g;function rewriteMirrorSrcInLine(e,t,S){let w=``,E=0,D=0;for(;D<e.length;){if(e[D]===`\\`&&D+1<e.length){w+=e.slice(D,D+2),D+=2;continue}if(e[D]==="`"){let t=readInlineCode$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`<`){let O=new RegExp(MIRROR_TAG_RE.source),k=e.slice(D),j=O.exec(k);if(j&&j.index===0){let[e,O]=j,k=new RegExp(MIRROR_SRC_ATTR_RE.source,MIRROR_SRC_ATTR_RE.flags),F=O.replace(k,(e,w,D,O)=>O===t?(E++,`${w}${D}${S}${D}`):e);w+=`<Mirror${F}/>`,D+=e.length;continue}}w+=e[D],D++}return{markdown:w,rewrites:E}}function rewriteMirrorSrcForDocumentRename(e,t,S){let w=null,E=0;return{markdown:splitLines(e).map(({line:e,ending:D})=>{if(w)return isFenceClose$2(e,w)&&(w=null),`${e}${D}`;let O=matchFence$2(e);if(O)return w=O,`${e}${D}`;let k=rewriteMirrorSrcInLine(e,t,S);return E+=k.rewrites,`${k.markdown}${D}`}).join(``),rewrites:E}}function rewriteWikiLinksForDocumentRename(e,t,S){let w=null,E=0;return{markdown:splitLines(e).map(({line:e,ending:D})=>{if(w)return isFenceClose$2(e,w)&&(w=null),`${e}${D}`;let O=matchFence$2(e);if(O)return w=O,`${e}${D}`;let k=rewriteWikiLinksInLine(e,t,S);return E+=k.rewrites,`${k.markdown}${D}`}).join(``),rewrites:E}}function rewriteMarkdownLinksForDocumentRename(e,t,S,w){let E=null,D=0;return{markdown:splitLines(e).map(({line:e,ending:O})=>{if(E)return isFenceClose$2(e,E)&&(E=null),`${e}${O}`;let k=matchFence$2(e);if(k)return E=k,`${e}${O}`;let j=rewriteMarkdownLinksInLine(e,t,S,w);return D+=j.rewrites,`${j.markdown}${O}`}).join(``),rewrites:D}}function rewriteOutboundMarkdownLinksInLine(e,t,S){let w=``,E=0,D=0,O=leadingMarkdownPrefixLength$2(e);for(O>0&&(w+=e.slice(0,O),D=O);D<e.length;){if(e[D]===`\\`&&D+1<e.length){w+=e.slice(D,D+2),D+=2;continue}if(e[D]==="`"){let t=readInlineCode$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`&&e[D+1]===`[`){let t=readWikiLink$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`!`&&e[D+1]===`[`){let t=readImageRef(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`){let O=readMarkdownLink$2(e,D);if(O){let k=resolveInternalHref(O.href,t);if(k!==null){let t=recomputeRelativeMarkdownHref(O.href,S,k.docName);if(t!==O.href){let e=O.hrefRaw.startsWith(`<`)&&O.hrefRaw.endsWith(`>`)?`<${t}>`:t;w+=`[${O.text}](${e}${O.titleSuffix})`,E++}else w+=e.slice(D,O.nextIndex)}else w+=e.slice(D,O.nextIndex);D=O.nextIndex;continue}}w+=e[D],D++}return{markdown:w,rewrites:E}}function rewriteOutboundMarkdownLinksForSourceMove(e,t,S){if(posix.dirname(t)===posix.dirname(S))return{markdown:e,rewrites:0};let w=null,E=0;return{markdown:splitLines(e).map(({line:e,ending:D})=>{if(w)return isFenceClose$2(e,w)&&(w=null),`${e}${D}`;let O=matchFence$2(e);if(O)return w=O,`${e}${D}`;let k=rewriteOutboundMarkdownLinksInLine(e,t,S);return E+=k.rewrites,`${k.markdown}${D}`}).join(``),rewrites:E}}var ManagedRenameCollisionError=class extends Error{colliding;constructor(e){super(`Managed rename collision: ${e.map(e=>`'${e.existing}' and '${e.incoming}' both target '${e.to}'`).join(`; `)}`),this.name=`ManagedRenameCollisionError`,this.colliding=e}},ManagedRenameSourceNotFoundError=class extends Error{kind;constructor(e){super(`${e} does not exist`),this.name=`ManagedRenameSourceNotFoundError`,this.kind=e}},ManagedRenameDestinationExistsError=class extends Error{constructor(){super(`Destination already exists`),this.name=`ManagedRenameDestinationExistsError`}},ManagedRenameSourceTypeMismatchError=class extends Error{kind;constructor(e){super(`Source path is not a ${e}`),this.name=`ManagedRenameSourceTypeMismatchError`,this.kind=e}},SymlinkEscapeError=class extends Error{constructor(e){super(`symlink-escape: ${e}`),this.name=`SymlinkEscapeError`}},BacklinkIndexRequiredError=class extends Error{constructor(){super(`Managed rename requires backlink index support`),this.name=`BacklinkIndexRequiredError`}},ManagedRenameSnapshotMissingError=class extends Error{docName;constructor(e){super(`Cannot snapshot missing document: ${e}`),this.name=`ManagedRenameSnapshotMissingError`,this.docName=e}},ManagedRenameMissingDocumentError=class extends Error{docName;constructor(e){super(`Cannot rename missing document: ${e}`),this.name=`ManagedRenameMissingDocumentError`,this.docName=e}};function buildRenameMap(e){let t=new Map,S=[];for(let{from:w,to:E}of e){for(let[e,D]of t)e!==w&&D===E&&S.push({existing:e,incoming:w,to:E});t.set(w,E)}if(S.length>0)throw new ManagedRenameCollisionError(S);return t}function rewriteSupportedLinksForRename(e,t,S,w){let{frontmatter:E,body:D}=stripFrontmatter(e),O=rewriteWikiLinksForDocumentRename(D,S,w),k=rewriteMarkdownLinksForDocumentRename(O.markdown,t,S,w),j=rewriteMirrorSrcForDocumentRename(k.markdown,S,w);return{markdown:prependFrontmatter(E,j.markdown),rewrites:O.rewrites+k.rewrites+j.rewrites}}function applyRenameMap(e,t,S){let w=e,E=0,D,O=[];for(let[e,w]of S)e!==w&&(e===t?D=w:O.push([e,w]));if(D!==void 0){let e=rewriteSupportedLinksForRename(w,t,t,D);w=e.markdown,E+=e.rewrites;let{frontmatter:S,body:O}=stripFrontmatter(w),k=rewriteOutboundMarkdownLinksForSourceMove(O,t,D);w=prependFrontmatter(S,k.markdown),E+=k.rewrites}let k=D??t,j=new Map;for(let[e,t]of O){let S=`__OK_RENAME_${randomUUID().replaceAll(`-`,``)}__`,D=rewriteSupportedLinksForRename(w,k,e,S);D.rewrites>0&&(w=D.markdown,E+=D.rewrites,j.set(S,t))}for(let[e,t]of j)w=rewriteSupportedLinksForRename(w,k,e,t).markdown;return{markdown:w,rewrites:E}}const WIKI_LINK_RE$1=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE$1=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function createEmptyState$1(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function mergeLinkMeta(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function getRepresentativeAnchor(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function externalNodeId(e){return`external:${e}`}function externalUrlFromNodeId(e){return e.startsWith(`external:`)?e.slice(9):null}function normalizeSnippet$1(e){return e.replace(/\s+/g,` `).trim()}function snippetAround$1(e,t,S){if(!normalizeSnippet$1(e))return null;let w=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
1252
+ `).slice(1);for(let e of E){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function validateSkillZip(e,t,S={}){let w=S.bundle??`project`,E=statSync(e).size;if(E>MAX_ZIP_BYTES)throw Error(`Built ${e} is ${E} bytes, exceeds ${MAX_ZIP_BYTES}-byte ceiling`);let D=await sha256OfFile(e),O=await readFile$1(join(S.sourceDir??resolveBundledSkillDir(w,{checkDesktop:!1}),`SKILL.md`),`utf-8`),k=BUNDLE_SKILL_NAME[w];if(!RegExp(`^name:\\s+${k}$`,`m`).test(O.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${k}'. Check packages/server/assets/skills/${w}/SKILL.md frontmatter.`);let j=extractMetadataVersion(O);if(t!==void 0){if(!j)throw Error(`SKILL.md metadata.version missing. Add it to packages/server/assets/skills/${w}/SKILL.md.`);if(j!==t)throw Error(`SKILL.md metadata.version (${j}) does not match expected version (${t}).`)}return{size:E,sha256:D,skillVersion:j}}async function buildSkillZip(e={}){let t=e.bundle??`project`,S=e.sourceDir??resolveBundledSkillDir(t,{checkDesktop:e.checkDesktop??!1}),w=e.outputPath??join(process.cwd(),`openknowledge.skill`);await zipDirectory(S,w,BUNDLE_SKILL_NAME[t]);let{size:E,sha256:D,skillVersion:O}=await validateSkillZip(w,e.expectedSkillVersion,{bundle:t,sourceDir:S});return{outputPath:w,size:E,sha256:D,skillVersion:O}}const SKILL_INSTALL_EVENTS_FILE_REL=[`.ok`,`skill-install-events.jsonl`];async function recordSkillInstallEvent(e,t){let S=t?.homedir??(()=>process.env.HOME??``),w=t?.warn??((e,t)=>{console.warn(t,e)}),E=S();if(!E){w({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let D=join(E,...SKILL_INSTALL_EVENTS_FILE_REL),O=`${JSON.stringify(e)}\n`;try{await tracedMkdir(dirname(D),{recursive:!0})}catch(e){w({event:`skill-install-events.mkdir-failed`,error:String(e)},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await tracedWriteFile(D,O,{flag:`a`,encoding:`utf-8`})}catch(e){w({event:`skill-install-events.append-failed`,error:String(e)},`[skill-install-events] append failed; telemetry skipped`)}}const readFileAsync=promisify(readFile);function skillStateYamlPath(e){return join(e,...SKILL_STATE_REL)}const DEFAULT_LOGGER={warn:(e,t)=>console.warn(t,e)},TRACED_FS_ADAPTER={writeFile:(e,t,S)=>tracedWriteFile(e,t,S),rename:(e,t)=>tracedRename(e,t)};async function readSkillStateFile(e,t=DEFAULT_LOGGER){let S=skillStateYamlPath(e),w;try{w=await readFileAsync(S,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let E=(0,import_dist$1.parseDocument)(w);if(E.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:S,errors:E.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let D=SkillStateSchema.safeParse(E.toJSON());if(!D.success){let e=D.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:S,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:S,issues:D.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return D.data}async function writeSkillStateFile(e,t){let S=SkillStateSchema.safeParse(t);if(!S.success)throw Error(`Refusing to write invalid skill-state: ${S.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let w=skillStateYamlPath(e);await tracedMkdir(dirname(w),{recursive:!0});let E=(0,import_dist$1.parseDocument)(``);E.contents=E.createNode(S.data),await atomicWriteFile(w,E.toString(),{fs:TRACED_FS_ADAPTER})}async function readTargetVersion(e,t,S){let w=await readSkillStateFile(e,S);return w===null?null:w.targets[t]?.version??null}async function readTargetRecordedAt(e,t,S){let w=await readSkillStateFile(e,S);return w===null?null:w.targets[t]?.recordedAt??null}async function writeTargetVersion(e,t,S,w,E){if(!SKILL_STATE_VERSION_RE.test(S))throw Error(`Refusing to write invalid version string: ${S}`);let D=await readSkillStateFile(e,E)??emptySkillState(),O=new Date().toISOString(),k=D.targets[t],j=w===void 0?k?.surface??void 0:w,F=j===void 0?{version:S,recordedAt:O}:{version:S,recordedAt:O,surface:j};await writeSkillStateFile(e,{...D,targets:{...D.targets,[t]:F}})}async function readServerPackageVersion(){let e=await readFileAsync(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}async function readSkillInstallStateSnapshot(e,t){let[S,w]=await Promise.all([readServerPackageVersion(),readAllTargets(e,t)]);return{currentVersion:S,targets:w}}async function readAllTargets(e,t=DEFAULT_LOGGER){let S=null;try{S=await readSkillStateFile(e,t)}catch(w){t.warn({event:`skill-state.read-error`,path:skillStateYamlPath(e),error:String(w)},`non-ENOENT error reading skill-state.yml; treating as absent`),S=null}let w=SKILL_STATE_TARGETS.map(e=>{let t=S?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(w)}const CENTRAL_SKILL_DIR_REL=[`.agents`,`skills`,`open-knowledge-discovery`],LEGACY_USER_SKILL_NAME=`open-knowledge`,LEGACY_USER_SKILL_HOST_DIRS=[`.claude`,`.cursor`,`.agents`],SKILLS_CLI_SPEC=`skills@~1.5.0`,DEFAULT_TIMEOUT_MS$3=6e4;function centralSkillDir(e){return join(e,...CENTRAL_SKILL_DIR_REL)}async function centralSkillExists(e){try{return(await stat$1(centralSkillDir(e))).isDirectory()}catch{return!1}}function runSpawn(e,t,S,w,E){return new Promise(D=>{let O;try{O=e(t,S,{env:w,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){D({kind:`spawn-error`,stderr:``,error:e});return}let k=``,j=!1,F=e=>{j||(j=!0,clearTimeout(L),D(e))};O.stderr?.on(`data`,e=>{k+=typeof e==`string`?e:e.toString(`utf-8`)}),O.on(`error`,e=>{F({kind:`spawn-error`,stderr:k,error:e})}),O.on(`exit`,e=>{F(e===0?{kind:`ok`,exitCode:e,stderr:k}:{kind:`nonzero`,exitCode:e,stderr:k})});let L=setTimeout(()=>{try{O.kill(`SIGTERM`)}catch{}F({kind:`timeout`,stderr:k})},E)})}async function anyLegacyUserSkillExists(e){for(let t of LEGACY_USER_SKILL_HOST_DIRS)try{if((await stat$1(join(e,t,`skills`,LEGACY_USER_SKILL_NAME))).isDirectory())return!0}catch{}return!1}async function removeLegacyUserSkill(e,t,S,w,E){if(!await anyLegacyUserSkillExists(e))return;let D=await runSpawn(t,`npx`,[`-y`,SKILLS_CLI_SPEC,`remove`,`--agent`,`*`,`-g`,LEGACY_USER_SKILL_NAME],S,w);D.kind!==`ok`&&E.warn({event:`skill-install.legacy-remove-failed`,reason:D.kind,exitCode:D.exitCode,stderr:D.stderr},"Legacy `open-knowledge` skill removal did not exit cleanly; continuing with install.")}async function installUserSkill(e={}){let t=e.home??homedir(),S=e.logger??{warn:(e,t)=>console.warn(t,e),info:(e,t)=>console.info(t,e)},w=e.spawn??spawn,E=e.timeoutMs??DEFAULT_TIMEOUT_MS$3,D=e.surface??`cli-npx-skills-add`,O=async(e,w,E)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:D,target:`cli-hosts`,bundle:`discovery`,outcome:e,...w===void 0?{}:{version:w},...E===void 0?{}:{reason:E}},{homedir:()=>t,warn:S.warn})},k;try{k=await readServerPackageVersion()}catch(e){return S.warn({event:`skill-install.failed`,reason:`version-read-failed`,error:String(e)},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await O(`failed`,void 0,`version-read-failed`),`failed`}let j=await readTargetVersion(t,`cli-hosts`,S).catch(e=>(S.warn({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(j!==null&&j===k){if(await centralSkillExists(t))return S.info?.({event:`skill-install.skip-current`,version:k},`Open Knowledge skill already installed at current version; skipping.`),await O(`skip-current`,k),`skip-current`;S.info?.({event:`skill-install.reinstall-missing`,version:k,path:centralSkillDir(t)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let F;try{F=resolveBundledSkillDir(`discovery`,{checkDesktop:!1})}catch(e){return S.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,error:String(e)},`Skill install aborted — bundled discovery SKILL.md asset not found.`),await O(`failed`,k,`bundled-asset-missing`),`failed`}let L={...process.env,HOME:t};await removeLegacyUserSkill(t,w,L,E,S);let B=await runSpawn(w,`npx`,[`-y`,SKILLS_CLI_SPEC,`add`,F,`--agent`,`*`,`-g`,`-y`,`--copy`],L,E);if(B.kind===`ok`){try{await writeTargetVersion(t,`cli-hosts`,k,D,S)}catch(e){return S.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,error:String(e)},`Skill install succeeded but sidecar write failed.`),await O(`failed`,k,`sidecar-write-failed`),`failed`}return S.info?.({event:`skill-install.installed`,version:k},`Open Knowledge skill installed to detected agent hosts.`),await O(`installed`,k),`installed`}return B.kind===`timeout`?(S.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:E,stderr:B.stderr},`Skill install subprocess timed out. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`timeout`),`failed`):B.kind===`spawn-error`?(S.warn({event:`skill-install.failed`,reason:`spawn-error`,error:String(B.error),stderr:B.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`spawn-error`),`failed`):(S.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:B.exitCode,stderr:B.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${SKILLS_CLI_SPEC} add ${F} --agent '*' -g -y --copy`),await O(`failed`,k,`nonzero-exit:${B.exitCode??`unknown`}`),`failed`)}const DOWNLOADS_DIR=`Downloads`,SKILL_FILENAME=`openknowledge.skill`;function defaultDownloadsPath(e){return join(e,DOWNLOADS_DIR,SKILL_FILENAME)}function invokeFileAssociation(e,t,S){let w={detached:!0,stdio:`ignore`};try{return t===`darwin`?(S(`open`,[e],w).unref(),{ok:!0}):t===`win32`?(S(`cmd`,[`/c`,`start`,`""`,e],w).unref(),{ok:!0}):t===`linux`?(S(`xdg-open`,[e],w).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function buildAndOpenSkill(e={}){let t=e.home??homedir(),S=resolve(e.out??defaultDownloadsPath(t)),w=e.platformName??platform(),E=e.spawnFn??spawn,D=e.logger,O=async(e,S,w)=>{await recordSkillInstallEvent({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...S===void 0?{}:{version:S},...w===void 0?{}:{reason:w}},{homedir:()=>t,warn:D?.warn})};if(!e.force){let e=null;try{e=await readServerPackageVersion()}catch(e){D?.warn?.({event:`skill-install.gate.version-read-failed`,error:String(e)},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let S=null,w=null;try{[S,w]=await Promise.all([readTargetVersion(t,`claude-cowork`,D),readTargetRecordedAt(t,`claude-cowork`,D)])}catch(e){D?.warn?.({event:`skill-install.gate.read-failed`,error:String(e)},`Could not read claude-cowork install-state; rebuilding.`)}if(S!==null&&S===e)return D?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`Open Knowledge skill already delivered at current version; skipping rebuild.`),await O(`skip-current`,e),{status:`skip-current`,skillVersion:e,...w===null?{}:{recordedAt:w}}}}try{await tracedMkdir(dirname(S),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await O(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let k;try{k=await buildSkillZip({outputPath:S,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await O(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let j={status:`built`,outputPath:k.outputPath,size:k.size,sha256:k.sha256,skillVersion:k.skillVersion};if(k.skillVersion)try{await writeTargetVersion(t,`claude-cowork`,k.skillVersion,`server-build-and-open`,D)}catch(e){D?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:k.skillVersion,error:String(e)},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await O(`built`,k.skillVersion),j;let F=invokeFileAssociation(k.outputPath,w,E);return F.ok?(await O(`installed`,k.skillVersion),{...j,status:`installed`}):(await O(`built`,k.skillVersion,`handoff-${F.reason}`),{...j,handoffError:{reason:F.reason,message:F.message}})}var UiLockCollisionError=class extends ProcessLockCollisionError{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function acquireUiLock(e,t){try{return acquireProcessLock({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof ProcessLockCollisionError&&e.lockName===`ui`?new UiLockCollisionError(e.existing,e.lockPath):e}}function updateUiLockPort(e,t){updateProcessLockPort({lockName:`ui`,lockDir:e,port:t})}function readUiLock(e){return readProcessLock({lockName:`ui`,lockDir:e})}function releaseUiLock(e){releaseProcessLock({lockName:`ui`,lockDir:e})}var UploadWriteError=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function uploadStatusFor(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return assertNeverProblemType(e)}}function classifyUploadErrno(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function uploadTitleFor(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return assertNeverProblemType(e)}}const log$5=getLogger(`upload-streaming`);var HashingPassThrough=class extends Transform{hash=createHash(`sha256`);bytes=0;digested=!1;_transform(e,t,S){this.hash.update(e),this.bytes+=e.length,S(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function tmpUploadDir(e){return resolve(getLocalDir(e),`tmp`)}function mintTempUploadPath(e){let t=tmpUploadDir(e);return tracedMkdirSync(t,{recursive:!0}),resolve(t,`upload-${randomUUID()}`)}function linkTempToFinalWithCollisionRetry(e,t,S){let w=extname(S),E=S.slice(0,S.length-w.length),D=[S,...Array.from({length:99},(e,t)=>`${E}-${t+1}${w}`)];for(let S of D){let w=resolve(t,S);try{tracedLinkSync(e,w);try{tracedUnlinkSync(e)}catch{}return S}catch(t){let S=t.code;if(S===`EEXIST`)continue;try{tracedUnlinkSync(e)}catch{}throw S===`ENOSPC`||S===`EDQUOT`?new UploadWriteError(`urn:ok:error:storage-full`,t):S===`EROFS`||S===`EACCES`||S===`EPERM`?new UploadWriteError(`urn:ok:error:storage-readonly`,t):new UploadWriteError(`urn:ok:error:storage-error`,t)}}try{tracedUnlinkSync(e)}catch{}throw new UploadWriteError(`urn:ok:error:collision-exhaustion`)}function cleanupOrphanUploadTempfiles(e,{ageMs:t=1440*60*1e3}={}){let S=tmpUploadDir(e),w={scanned:0,deleted:0,errors:0};if(!existsSync(S))return w;let E;try{E=readdirSync(S)}catch(e){return log$5.warn({err:e,dir:S},`[upload-tempfile-sweep] readdir failed`),w.errors++,w}let D=Date.now()-t;for(let e of E){if(!e.startsWith(`upload-`))continue;w.scanned++;let t=resolve(S,e);try{if(statSync(t).mtimeMs>=D)continue;tracedUnlinkSync(t),w.deleted++}catch(e){log$5.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),w.errors++}}return(w.deleted>0||w.errors>0)&&log$5.info({dir:S,scanned:w.scanned,deleted:w.deleted,errors:w.errors},`[upload-tempfile-sweep] swept ${w.deleted}/${w.scanned} (errors: ${w.errors})`),w}function matchFence$2(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let S=t[1],w=S[0];return w!=="`"&&w!==`~`?null:{char:w,length:S.length}}function isFenceClose$2(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$2(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$2(e,t){let S=0;for(;e[t+S]==="`";)S++;if(S===0)return null;let w=t+S,E=w;for(;E<e.length;){if(e[E]!=="`"){E++;continue}let t=0;for(;e[E+t]==="`";)t++;if(t===S)return{nextIndex:E+S};E+=t}return{nextIndex:w}}function readWikiLink$2(e,t){let S=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!S)return null;let w=S[1]?.trim(),E=S[2]?.trim()||null,D=S[3]?.trim()||null;return w?{target:w,alias:D,anchor:E,nextIndex:t+S[0].length}:null}function readWikiLinkOrEmbed(e,t){if(e[t]===`!`&&e[t+1]===`[`&&e[t+2]===`[`){let S=readWikiLink$2(e,t+1);return S?{...S,embed:!0}:null}if(e[t]===`[`&&e[t+1]===`[`){let S=readWikiLink$2(e,t);return S?{...S,embed:!1}:null}return null}function readMarkdownLink$2(e,t){let S=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!S)return null;let w=S[2]??``;return{text:S[1]??``,hrefRaw:w,href:w.startsWith(`<`)&&w.endsWith(`>`)?w.slice(1,-1):w,titleSuffix:S[3]??``,nextIndex:t+S[0].length}}function readImageRef(e,t){let S=/^!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!S)return null;let w=S[2]??``;return{alt:S[1]??``,hrefRaw:w,href:w.startsWith(`<`)&&w.endsWith(`>`)?w.slice(1,-1):w,titleSuffix:S[3]??``,nextIndex:t+S[0].length}}function splitLines(e){let t=e.split(/(\r\n|\r|\n)/),S=[];for(let e=0;e<t.length;e+=2)S.push({line:t[e]??``,ending:t[e+1]??``});return S}function rewriteWikiLinksInLine(e,t,S){let w=``,E=0,D=0,O=leadingMarkdownPrefixLength$2(e);for(O>0&&(w+=e.slice(0,O),D=O);D<e.length;){if(e[D]===`\\`&&D+1<e.length){w+=e.slice(D,D+2),D+=2;continue}if(e[D]==="`"){let t=readInlineCode$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`&&e[D+1]===`[`){let O=readWikiLink$2(e,D);if(O){O.target===t?(w+=`[[${S}${O.anchor?`#${O.anchor}`:``}${O.alias?`|${O.alias}`:``}]]`,E++):w+=e.slice(D,O.nextIndex),D=O.nextIndex;continue}}w+=e[D],D++}return{markdown:w,rewrites:E}}function recomputeRelativeImageHref(e,t,S){let w=e.indexOf(`#`),E=w>=0?e.slice(w):``,D=w>=0?e.slice(0,w):e,O=D.indexOf(`?`),k=O>=0?D.slice(O):``,j=O>=0?D.slice(0,O):D;if(j.startsWith(`/`)||j.startsWith(`//`)||/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(j))return null;let F=posix.dirname(t),L=posix.dirname(S);if(F===L)return null;let B=F===`.`?`/`:`/${F}/`,H=posix.resolve(B,j).slice(1),q=posix.relative(L===`.`?``:L,H);return q||=posix.basename(H),j.startsWith(`./`)&&!q.startsWith(`./`)&&!q.startsWith(`../`)&&(q=`./${q}`),`${q}${k}${E}`}function decodeHrefForAssetResolution(e){try{return decodeURI(e)}catch{return e}}function splitHrefPathAndSuffix(e){let t=e.indexOf(`#`),S=t>=0?e.slice(t):``,w=t>=0?e.slice(0,t):e,E=w.indexOf(`?`),D=E>=0?w.slice(E):``;return{pathPart:E>=0?w.slice(0,E):w,suffix:`${D}${S}`}}function buildAssetHrefFromSource(e,t,S,w={}){let E=w.encodePath??!0,D=e=>E?encodeURI(e):e,{pathPart:O,suffix:k}=splitHrefPathAndSuffix(e);if(O.startsWith(`/`))return`/${D(S)}${k}`;let j=posix.dirname(t),F=posix.relative(j===`.`?``:j,S);return F||=posix.basename(S),O.startsWith(`./`)&&!F.startsWith(`./`)&&!F.startsWith(`../`)&&(F=`./${F}`),`${D(F)}${k}`}function rewriteAssetHrefForRename(e,t,S,w,E={}){return resolveAssetProjectPath(decodeHrefForAssetResolution(e),t)===S?buildAssetHrefFromSource(e,t,w,E):null}function recomputeRelativeMarkdownHref(e,t,S){let w=e.indexOf(`#`),E=w>=0?e.slice(w):``,D=w>=0?e.slice(0,w):e,O=D.indexOf(`?`),k=O>=0?D.slice(O):``,j=O>=0?D.slice(0,O):D,F=posix.dirname(t),L=posix.relative(F===`.`?``:F,S);return L||=posix.basename(S),j.endsWith(`.mdx`)?L+=`.mdx`:j.endsWith(`.md`)&&(L+=`.md`),j.startsWith(`./`)&&!L.startsWith(`./`)&&!L.startsWith(`../`)&&(L=`./${L}`),`${L}${k}${E}`}function rewriteMarkdownLinksInLine(e,t,S,w){let E=``,D=0,O=0,k=leadingMarkdownPrefixLength$2(e);for(k>0&&(E+=e.slice(0,k),O=k);O<e.length;){if(e[O]===`\\`&&O+1<e.length){E+=e.slice(O,O+2),O+=2;continue}if(e[O]==="`"){let t=readInlineCode$2(e,O);if(t){E+=e.slice(O,t.nextIndex),O=t.nextIndex;continue}}if(e[O]===`[`&&e[O+1]===`[`){let t=readWikiLink$2(e,O);if(t){E+=e.slice(O,t.nextIndex),O=t.nextIndex;continue}}if(e[O]===`!`&&e[O+1]===`[`){let k=readImageRef(e,O);if(k){let j=t===S&&S!==w?recomputeRelativeImageHref(k.href,S,w):null;if(j!==null){let e=k.hrefRaw.startsWith(`<`)&&k.hrefRaw.endsWith(`>`)?`<${j}>`:j;E+=`![${k.alt}](${e}${k.titleSuffix})`,D++}else E+=e.slice(O,k.nextIndex);O=k.nextIndex;continue}}if(e[O]===`[`){let k=readMarkdownLink$2(e,O);if(k){if(resolveInternalHref(k.href,t)?.docName===S){let e=recomputeRelativeMarkdownHref(k.href,t,w),S=k.hrefRaw.startsWith(`<`)&&k.hrefRaw.endsWith(`>`)?`<${e}>`:e;E+=`[${k.text}](${S}${k.titleSuffix})`,D++}else E+=e.slice(O,k.nextIndex);O=k.nextIndex;continue}}E+=e[O],O++}return{markdown:E,rewrites:D}}function renderWikiLinkOrEmbed(e,t){return`${e.embed?`!`:``}[[${t}${e.anchor?`#${e.anchor}`:``}${e.alias?`|${e.alias}`:``}]]`}const HTML_ASSET_ATTR_RE=/(\s(?:href|src)\s*=\s*)(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function rewriteHtmlAssetAttrsInTag(e,t,S,w){let E=0;return{markdown:e.replace(HTML_ASSET_ATTR_RE,(e,D,O,k,j,F)=>{let L=O??k??j??F;if(typeof L!=`string`)return e;let B=rewriteAssetHrefForRename(L,t,S,w);return B===null?e:(E++,O===void 0?k===void 0?j===void 0?`${D}${B}`:`${D}“${B}”`:`${D}'${B}'`:`${D}"${B}"`)}),rewrites:E}}function rewriteAssetReferencesInLine(e,t,S,w){let E=``,D=0,O=0,k=leadingMarkdownPrefixLength$2(e);for(k>0&&(E+=e.slice(0,k),O=k);O<e.length;){if(e[O]===`\\`&&O+1<e.length){E+=e.slice(O,O+2),O+=2;continue}if(e[O]==="`"){let t=readInlineCode$2(e,O);if(t){E+=e.slice(O,t.nextIndex),O=t.nextIndex;continue}}let k=readWikiLinkOrEmbed(e,O);if(k){let j=rewriteAssetHrefForRename(k.target,t,S,w,{encodePath:!1});j===null?E+=e.slice(O,k.nextIndex):(E+=renderWikiLinkOrEmbed(k,j),D++),O=k.nextIndex;continue}if(e.startsWith(`<!--`,O)){let t=e.indexOf(`-->`,O+4);if(t===-1){E+=e.slice(O);break}E+=e.slice(O,t+3),O=t+3;continue}if(e[O]===`<`){let k=e.indexOf(`>`,O+1);if(k!==-1){let j=rewriteHtmlAssetAttrsInTag(e.slice(O,k+1),t,S,w);if(j.rewrites>0){E+=j.markdown,D+=j.rewrites,O=k+1;continue}}}if(e[O]===`!`&&e[O+1]===`[`){let k=readImageRef(e,O);if(k){let j=rewriteAssetHrefForRename(k.href,t,S,w);if(j!==null){let e=k.hrefRaw.startsWith(`<`)&&k.hrefRaw.endsWith(`>`)?`<${j}>`:j;E+=`![${k.alt}](${e}${k.titleSuffix})`,D++}else E+=e.slice(O,k.nextIndex);O=k.nextIndex;continue}}if(e[O]===`[`){let k=readMarkdownLink$2(e,O);if(k){let j=rewriteAssetHrefForRename(k.href,t,S,w);if(j!==null){let e=k.hrefRaw.startsWith(`<`)&&k.hrefRaw.endsWith(`>`)?`<${j}>`:j;E+=`[${k.text}](${e}${k.titleSuffix})`,D++}else E+=e.slice(O,k.nextIndex);O=k.nextIndex;continue}}E+=e[O],O++}return{markdown:E,rewrites:D}}const MIRROR_TAG_RE=/<Mirror\b([^>]*)\/>/g,MIRROR_SRC_ATTR_RE=/(\bsrc=)(["'])([^"']*)\2/g;function rewriteMirrorSrcInLine(e,t,S){let w=``,E=0,D=0;for(;D<e.length;){if(e[D]===`\\`&&D+1<e.length){w+=e.slice(D,D+2),D+=2;continue}if(e[D]==="`"){let t=readInlineCode$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`<`){let O=new RegExp(MIRROR_TAG_RE.source),k=e.slice(D),j=O.exec(k);if(j&&j.index===0){let[e,O]=j,k=new RegExp(MIRROR_SRC_ATTR_RE.source,MIRROR_SRC_ATTR_RE.flags),F=O.replace(k,(e,w,D,O)=>O===t?(E++,`${w}${D}${S}${D}`):e);w+=`<Mirror${F}/>`,D+=e.length;continue}}w+=e[D],D++}return{markdown:w,rewrites:E}}function rewriteMirrorSrcForDocumentRename(e,t,S){let w=null,E=0;return{markdown:splitLines(e).map(({line:e,ending:D})=>{if(w)return isFenceClose$2(e,w)&&(w=null),`${e}${D}`;let O=matchFence$2(e);if(O)return w=O,`${e}${D}`;let k=rewriteMirrorSrcInLine(e,t,S);return E+=k.rewrites,`${k.markdown}${D}`}).join(``),rewrites:E}}function rewriteWikiLinksForDocumentRename(e,t,S){let w=null,E=0;return{markdown:splitLines(e).map(({line:e,ending:D})=>{if(w)return isFenceClose$2(e,w)&&(w=null),`${e}${D}`;let O=matchFence$2(e);if(O)return w=O,`${e}${D}`;let k=rewriteWikiLinksInLine(e,t,S);return E+=k.rewrites,`${k.markdown}${D}`}).join(``),rewrites:E}}function rewriteMarkdownLinksForDocumentRename(e,t,S,w){let E=null,D=0;return{markdown:splitLines(e).map(({line:e,ending:O})=>{if(E)return isFenceClose$2(e,E)&&(E=null),`${e}${O}`;let k=matchFence$2(e);if(k)return E=k,`${e}${O}`;let j=rewriteMarkdownLinksInLine(e,t,S,w);return D+=j.rewrites,`${j.markdown}${O}`}).join(``),rewrites:D}}function rewriteAssetReferencesForRename(e,t,S,w){let E=null,D=0;return{markdown:splitLines(e).map(({line:e,ending:O})=>{if(E)return isFenceClose$2(e,E)&&(E=null),`${e}${O}`;let k=matchFence$2(e);if(k)return E=k,`${e}${O}`;let j=rewriteAssetReferencesInLine(e,t,S,w);return D+=j.rewrites,`${j.markdown}${O}`}).join(``),rewrites:D}}function rewriteOutboundMarkdownLinksInLine(e,t,S){let w=``,E=0,D=0,O=leadingMarkdownPrefixLength$2(e);for(O>0&&(w+=e.slice(0,O),D=O);D<e.length;){if(e[D]===`\\`&&D+1<e.length){w+=e.slice(D,D+2),D+=2;continue}if(e[D]==="`"){let t=readInlineCode$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`&&e[D+1]===`[`){let t=readWikiLink$2(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`!`&&e[D+1]===`[`){let t=readImageRef(e,D);if(t){w+=e.slice(D,t.nextIndex),D=t.nextIndex;continue}}if(e[D]===`[`){let O=readMarkdownLink$2(e,D);if(O){let k=resolveInternalHref(O.href,t);if(k!==null){let t=recomputeRelativeMarkdownHref(O.href,S,k.docName);if(t!==O.href){let e=O.hrefRaw.startsWith(`<`)&&O.hrefRaw.endsWith(`>`)?`<${t}>`:t;w+=`[${O.text}](${e}${O.titleSuffix})`,E++}else w+=e.slice(D,O.nextIndex)}else w+=e.slice(D,O.nextIndex);D=O.nextIndex;continue}}w+=e[D],D++}return{markdown:w,rewrites:E}}function rewriteOutboundMarkdownLinksForSourceMove(e,t,S){if(posix.dirname(t)===posix.dirname(S))return{markdown:e,rewrites:0};let w=null,E=0;return{markdown:splitLines(e).map(({line:e,ending:D})=>{if(w)return isFenceClose$2(e,w)&&(w=null),`${e}${D}`;let O=matchFence$2(e);if(O)return w=O,`${e}${D}`;let k=rewriteOutboundMarkdownLinksInLine(e,t,S);return E+=k.rewrites,`${k.markdown}${D}`}).join(``),rewrites:E}}var ManagedRenameCollisionError=class extends Error{colliding;constructor(e){super(`Managed rename collision: ${e.map(e=>`'${e.existing}' and '${e.incoming}' both target '${e.to}'`).join(`; `)}`),this.name=`ManagedRenameCollisionError`,this.colliding=e}},ManagedRenameSourceNotFoundError=class extends Error{kind;constructor(e,t=`${e} does not exist`){super(t),this.name=`ManagedRenameSourceNotFoundError`,this.kind=e}},ManagedRenameDestinationExistsError=class extends Error{constructor(){super(`Destination already exists`),this.name=`ManagedRenameDestinationExistsError`}},ManagedRenameSourceTypeMismatchError=class extends Error{kind;constructor(e,t=`Source path is not a ${e}`){super(t),this.name=`ManagedRenameSourceTypeMismatchError`,this.kind=e}},ManagedRenameInvalidRequestError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameInvalidRequestError`}},ManagedRenameReservedPathError=class extends Error{constructor(e){super(e),this.name=`ManagedRenameReservedPathError`}},SymlinkEscapeError=class extends Error{constructor(e){super(`symlink-escape: ${e}`),this.name=`SymlinkEscapeError`}},BacklinkIndexRequiredError=class extends Error{constructor(){super(`Managed rename requires backlink index support`),this.name=`BacklinkIndexRequiredError`}},ManagedRenameSnapshotMissingError=class extends Error{docName;constructor(e){super(`Cannot snapshot missing document: ${e}`),this.name=`ManagedRenameSnapshotMissingError`,this.docName=e}},ManagedRenameMissingDocumentError=class extends Error{docName;constructor(e){super(`Cannot rename missing document: ${e}`),this.name=`ManagedRenameMissingDocumentError`,this.docName=e}};function buildRenameMap(e){let t=new Map,S=[];for(let{from:w,to:E}of e){for(let[e,D]of t)e!==w&&D===E&&S.push({existing:e,incoming:w,to:E});t.set(w,E)}if(S.length>0)throw new ManagedRenameCollisionError(S);return t}function rewriteSupportedLinksForRename(e,t,S,w){let{frontmatter:E,body:D}=stripFrontmatter(e),O=rewriteWikiLinksForDocumentRename(D,S,w),k=rewriteMarkdownLinksForDocumentRename(O.markdown,t,S,w),j=rewriteMirrorSrcForDocumentRename(k.markdown,S,w);return{markdown:prependFrontmatter(E,j.markdown),rewrites:O.rewrites+k.rewrites+j.rewrites}}function applyRenameMap(e,t,S){let w=e,E=0,D,O=[];for(let[e,w]of S)e!==w&&(e===t?D=w:O.push([e,w]));if(D!==void 0){let e=rewriteSupportedLinksForRename(w,t,t,D);w=e.markdown,E+=e.rewrites;let{frontmatter:S,body:O}=stripFrontmatter(w),k=rewriteOutboundMarkdownLinksForSourceMove(O,t,D);w=prependFrontmatter(S,k.markdown),E+=k.rewrites}let k=D??t,j=new Map;for(let[e,t]of O){let S=`__OK_RENAME_${randomUUID().replaceAll(`-`,``)}__`,D=rewriteSupportedLinksForRename(w,k,e,S);D.rewrites>0&&(w=D.markdown,E+=D.rewrites,j.set(S,t))}for(let[e,t]of j)w=rewriteSupportedLinksForRename(w,k,e,t).markdown;return{markdown:w,rewrites:E}}const WIKI_LINK_RE$1=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE$1=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function createEmptyState$1(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function mergeLinkMeta(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function getRepresentativeAnchor(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function externalNodeId(e){return`external:${e}`}function externalUrlFromNodeId(e){return e.startsWith(`external:`)?e.slice(9):null}function normalizeSnippet$1(e){return e.replace(/\s+/g,` `).trim()}function snippetAround$1(e,t,S){if(!normalizeSnippet$1(e))return null;let w=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
1253
1253
  `,t-1)),E=[e.indexOf(`.`,S),e.indexOf(`?`,S),e.indexOf(`!`,S),e.indexOf(`
1254
1254
  `,S)].filter(e=>e>=0),D=w>=0?w+1:Math.max(0,t-60),O=E.length>0?Math.min(...E)+1:Math.min(e.length,S+60),k=D>0?`…`:``,j=O<e.length?`…`:``,F=normalizeSnippet$1(e.slice(D,O));return F?`${k}${F}${j}`:null}function matchFence$1(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let S=t[1],w=S[0];return w!=="`"&&w!==`~`?null:{char:w,length:S.length}}function isFenceClose$1(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function leadingMarkdownPrefixLength$1(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function readInlineCode$1(e,t){let S=0;for(;e[t+S]==="`";)S++;if(S===0)return null;let w=t+S,E=w;for(;E<e.length;){if(e[E]!=="`"){E++;continue}let t=0;for(;e[E+t]==="`";)t++;if(t===S)return{text:e.slice(w,E),nextIndex:E+S};E+=t}return{text:e.slice(t,w),nextIndex:w}}function readWikiLink$1(e,t){WIKI_LINK_RE$1.lastIndex=t;let S=WIKI_LINK_RE$1.exec(e);if(!S)return null;let w=S[1]?.trim(),E=S[2]?.trim()||null,D=S[3]?.trim()||null;return w?{target:w,alias:D,anchor:E,nextIndex:t+S[0].length}:null}function extractWikiLinksFromLine(e){let t=``,S=[],w=leadingMarkdownPrefixLength$1(e);for(;w<e.length;){if(e[w]===`\\`&&w+1<e.length){t+=e[w+1],w+=2;continue}if(e[w]==="`"){let S=readInlineCode$1(e,w);if(S){t+=S.text,w=S.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let E=readWikiLink$1(e,w);if(E){let e=getWikiLinkText(E),D=t.length;t+=e;let O=classifyWikiLinkTarget(E.target,E.anchor);O?.kind===`doc`&&S.push({target:O.docName,anchor:O.anchor,start:D,end:D+e.length}),w=E.nextIndex;continue}}t+=e[w],w++}return{text:t,occurrences:S}}function extractExternalWikiLinksFromLine(e){let t=``,S=[],w=leadingMarkdownPrefixLength$1(e);for(;w<e.length;){if(e[w]===`\\`&&w+1<e.length){t+=e[w+1],w+=2;continue}if(e[w]==="`"){let S=readInlineCode$1(e,w);if(S){t+=S.text,w=S.nextIndex;continue}}if(e[w]===`[`&&e[w+1]===`[`){let E=readWikiLink$1(e,w);if(E){let e=getWikiLinkText(E),D=t.length;t+=e;let O=classifyWikiLinkTarget(E.target,E.anchor);O?.kind===`external`&&S.push({url:O.url,label:e,start:D,end:D+e.length}),w=E.nextIndex;continue}}t+=e[w],w++}return{text:t,occurrences:S}}function normalizeMarkdownHref$1(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function readMarkdownLink$1(e,t){MD_LINK_RE$1.lastIndex=t;let S=MD_LINK_RE$1.exec(e);return S?{text:S[1]??``,href:normalizeMarkdownHref$1(S[2]??``),nextIndex:t+S[0].length}:null}function extractMarkdownLinksFromLine(e,t){let S=``,w=[],E=leadingMarkdownPrefixLength$1(e);for(;E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e[E+1],E+=2;continue}if(e[E]==="`"){let t=readInlineCode$1(e,E);if(t){S+=t.text,E=t.nextIndex;continue}}if(e[E]===`[`&&e[E+1]===`[`){let t=readWikiLink$1(e,E);if(t){S+=getWikiLinkText(t),E=t.nextIndex;continue}}if(e[E]===`[`&&e[E-1]!==`!`){let D=readMarkdownLink$1(e,E);if(D){let e=classifyMarkdownHref(D.href,t);if(e?.kind===`doc`){let t=S.length;S+=D.text,w.push({target:e.docName,anchor:e.anchor,start:t,end:t+D.text.length})}else S+=D.text;E=D.nextIndex;continue}}S+=e[E],E++}return{text:S,occurrences:w}}function extractExternalMarkdownLinksFromLine(e,t){let S=``,w=[],E=leadingMarkdownPrefixLength$1(e);for(;E<e.length;){if(e[E]===`\\`&&E+1<e.length){S+=e[E+1],E+=2;continue}if(e[E]==="`"){let t=readInlineCode$1(e,E);if(t){S+=t.text,E=t.nextIndex;continue}}if(e[E]===`[`&&e[E+1]===`[`){let t=readWikiLink$1(e,E);if(t){S+=getWikiLinkText(t),E=t.nextIndex;continue}}if(e[E]===`[`&&e[E-1]!==`!`){let D=readMarkdownLink$1(e,E);if(D){let e=classifyMarkdownHref(D.href,t);if(S+=D.text,e?.kind===`external`){let t=S.length-D.text.length;w.push({url:e.url,label:D.text||null,start:t,end:t+D.text.length})}E=D.nextIndex;continue}}S+=e[E],E++}return{text:S,occurrences:w}}function extractMarkdownLinksFromMarkdown(e,t){let S=e.replaceAll(`\r
1255
1255
  `,`
@@ -2367,17 +2367,17 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
2367
2367
  `).filter(e=>e.length===40);ne.push(...e)}catch{}let se=[];if(oe)try{se=(await te.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/main/`)).trim().split(`
2368
2368
  `).filter(e=>e.length===40)}catch{}try{let e=(await te.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/${E}/`)).trim().split(`
2369
2369
  `).filter(Boolean);ae.push(...e)}catch{}if(oe&&ae.length===0)try{let e=(await te.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/main/`)).trim().split(`
2370
- `).filter(Boolean);ae.push(...e)}catch{}if(ae.length===0&&ne.length===0&&se.length===0)return EMPTY;let ce=[...ne,...se],ue=[];if(ce.length>0){let t=parseGitLogOutput(await te.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...ce)).map(e=>({...e,type:`checkpoint`}));if(H&&(t=await filterEntriesByChain(e,t,L,E,B,ee,Y)),oe&&ne.length>0&&se.length>0){let e=new Set(ne),S=t.filter(t=>e.has(t.sha)),w=t.filter(t=>!e.has(t.sha)),E=S.reduce((e,t)=>{let S=new Date(t.timestamp).getTime();return S<e?S:e},1/0);ue=[...S,...w.filter(e=>new Date(e.timestamp).getTime()<E)]}else ue=t}let de=[...ae];for(let e of ce)de.push(e);let fe=[];if(de.length>0&&(fe=parseGitLogOutput(await te.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...de,...H?[`--`,H]:[])),J))for(let t=0;t<L.length-1;t++){let S=L[t];if(S.renameCommit!==null)try{let t=await buildSeeds(e,S.renameCommit,E,Y);if(t.length===0)continue;let w=B(S.path),D=await logSeededReachable(e,[`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`],t,w);fe=[...fe,...parseGitLogOutput(D)]}catch(e){console.warn(`[timeline] predecessor walk failed for step ${t} (${S.path}); skipping:`,e)}}let me=[...ue,...fe],ge=new Set,_e=[];for(let e of me)ge.has(e.sha)||(ge.add(e.sha),_e.push(e));let ve=_e;_e.length>0&&L.length>0&&(ve=filterEntriesByOkActorDocs(_e,L,await Promise.all(L.map(async t=>{if(t.renameCommit===null)return null;let S=await buildSeeds(e,t.renameCommit,E,Y);return S.length===0?new Set:buildAncestorShaSet(e,S,E,ee)})))),ve.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let ye=ve;ye=ye.filter(e=>e.type!==`park`),k.length>0&&(ye=ye.filter(e=>k.includes(e.type))),j.length>0&&(ye=ye.filter(e=>matchesAuthor(e,j))),F.length>0&&(ye=ye.filter(e=>!matchesAuthor(e,F)));let Ce=ye.length;return{entries:ye.slice(O,O+D).map(({rawBody:e,...t})=>t),total:Ce,hasMore:O+D<Ce}}catch(e){return console.warn(`[timeline] getDocumentHistory failed, returning empty result:`,e),EMPTY}}let _httpDurationHist=null;function httpDurationHist(){return _httpDurationHist||=getMeter().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),_httpDurationHist}let _hintEmittedCounter=null;function hintEmittedCounter(){return _hintEmittedCounter||=getMeter().createCounter(`ok.preview_attach.hint_emitted`,{description:`Count of preview-attach hints emitted on write-tool responses when no editor is attached to __system__. Covers both attach-preview-once (URL exists, no browser) and start-ui (no UI running anywhere) variants — the tool side disambiguates via the warning action; the metric name is retained as-is so existing dashboards keep working.`}),_hintEmittedCounter}let _agentPatchFmTouchCounter=null;function agentPatchFmTouchCounter(){return _agentPatchFmTouchCounter||=getMeter().createCounter(`ok.frontmatter.agent_patch_fm_touch_total`,{description:`Count of agent-patch calls whose find string targets the frontmatter region. Measures incidence during the soft-deprecation window before agent-patch FM-intersecting calls are enforced as 400. Bounded label: result ∈ {rejected, pre_deprecation_passthrough}.`}),_agentPatchFmTouchCounter}function findLooksLikeFrontmatter(e){return!!(/(^|\n)---(\s|\n|$)/.test(e)||/^\s*[\w-]+:\s+\S/.test(e))}let _renameAttributionCounter=null;function renameAttributionCounter(){return _renameAttributionCounter||=getMeter().createCounter(`ok.rename.attribution_kind`,{description:`Count of rename and rollback handler dispatches by attribution kind (agent | principal | anonymous)`}),_renameAttributionCounter}const ROLLBACK_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},MANAGED_RENAME_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},log$3=getLogger(`api`);function ytextHasConflictMarkers(e){return/^<{7} /m.test(e)&&/^={7}$/m.test(e)&&/^>{7} /m.test(e)}function safeDocPath(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name.`};let S=t===`.`?``:t.replace(/^\.\//,``),w=getDocExtension(e);return{path:S?`${S}/${e}${w}`:`${e}${w}`}}const GENERIC_PASTE_NAMES=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i,SAFE_FILENAME_CHARS=/[^\p{L}\p{N}\p{M}\p{Extended_Pictographic}.\-_ ]/gu,STRIP_ON_SIGHT=/[/\\\x00-\x1f\x7f]/g;function sanitizeFilename(e){let t=e.replace(STRIP_ON_SIGHT,``);if(t=t.replace(SAFE_FILENAME_CHARS,`_`),t=t.replace(/_+/g,`_`).replace(/\.{2,}/g,`.`),t=t.replace(/^[._]+/,``),t=t.replace(/\.+$/,``),t===``)return`upload`;let S=255,w=new TextEncoder;if(w.encode(t).length>255){let e=t.lastIndexOf(`.`),S=e>=0?t.slice(e):``,E=e>=0?t.slice(0,e):t;for(;w.encode(E+S).length>255&&E.length>0;)E=E.slice(0,-1);t=(E||`upload`)+S,w.encode(t).length>255&&(t=`upload`)}return t}function resolveUploadDestDir(e,t,S){let w=t.trim();return w===``||w===`./`?resolve(S,dirname(e)):w===`/`?S:w.startsWith(`./`)?resolve(S,dirname(e),w.slice(2)):resolve(S,w)}function readTempFileHead(e,t){let S=openSync(e,`r`);try{let e=Buffer.alloc(t),w=readSync(S,e,0,t,0);return e.subarray(0,w)}finally{closeSync(S)}}const MAX_DEDUP_SCAN_CANDIDATES=1e3;async function streamingHashFile(e){let t=createHash(`sha256`);return await pipeline(createReadStream(e),t),t.digest(`hex`)}async function findDuplicateAsset(e,t,S){let w;try{w=await readdir(e)}catch{return null}let E=getLogger(`upload`),D=0;for(let O of w){let w=extname(O).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(w))continue;let k=resolve(e,O),j;try{j=await stat$1(k)}catch{continue}if(!j.isFile()||j.size!==S)continue;if(D++,D>MAX_DEDUP_SCAN_CANDIDATES)return E.warn({event:`upload-dedup-skip`,reason:`scan-cap-exceeded`,destDir:e,scanned:MAX_DEDUP_SCAN_CANDIDATES,expectedSize:S},`[upload-dedup] candidate scan exceeded ${MAX_DEDUP_SCAN_CANDIDATES} same-size siblings — degrading to no-dedup for this upload`),null;let F;try{F=await streamingHashFile(k)}catch(e){let t=e.code;t!==`ENOENT`&&E.warn({event:`upload-dedup-skip`,reason:`read-failed`,code:t,entry:O},`[upload-dedup] skipped candidate — read failed`);continue}if(F===t)return O}return null}function readUploadBody(e,t){return new Promise((S,w)=>{let E;try{E=(0,import_lib.default)({headers:e.headers,limits:{files:1,fields:10,fieldSize:2*1024}})}catch(e){w(new UploadWriteError(`urn:ok:error:malformed-upload`,e));return}let D=!1,O=`upload`,k=``,j=``,F,L,B=!1,H=(e,t)=>{if(!D){if(D=!0,F)try{unlinkSync(F)}catch{}w(t instanceof UploadWriteError?t:new UploadWriteError(e,t))}},q=classifyUploadErrno;E.on(`field`,(e,t)=>{e===`parentDocName`&&(j=t)}),E.on(`file`,(e,w,E)=>{B=!0,O=E.filename||`upload`,k=E.mimeType||``;let J;try{J=mintTempUploadPath(t)}catch(e){H(q(e),e),w.resume();return}F=J;let Y=new HashingPassThrough;pipeline(w,Y,createWriteStream(J)).then(()=>{D||(D=!0,S({filename:O,mimeType:k,parentDocName:j,tempPath:J,sha:Y.digest(),byteLength:Y.byteLength()}))}).catch(e=>{L=e,H(q(e),e)})}),E.on(`error`,e=>{H(`urn:ok:error:malformed-upload`,e)}),E.on(`close`,()=>{D||L||B||(D=!0,S({filename:``,mimeType:``,parentDocName:j,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{D||L||e.complete||H(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(E)})}function safeSubdir(e,t){let S=resolve(e,t);if(S!==e&&!S.startsWith(`${e}/`))throw Error(`Invalid directory: ${t}`);return S}function synthesizeShowAllAssetExt(e){let t=extname(e);return t?t.slice(1).toLowerCase():e.startsWith(`.`)&&e.length>1?e.slice(1).toLowerCase():`file`}async function walkContentDirForShowAll(e){let{contentDir:t,contentFilter:S,dirFilter:w,documents:E,getDocExtension:D}=e,O=e=>w?e===w||e.startsWith(`${w}/`):!0,k;try{k=await realpath(t)}catch{k=t}let j=e=>e===k?!0:e.startsWith(`${k}/`);async function F(e,t){let w;try{w=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[document-list][showAll] readdir failed for ${e}:`,t);return}for(let k of w){let w=t?`${t}/${k.name}`:k.name;if(k.isDirectory()){if(S.isDirExcluded(w,{bypassFilters:!0}))continue;let t=`${e}/${k.name}`,D;try{D=await realpath(t)}catch(e){console.warn(`[document-list][showAll] realpath failed for ${t}:`,e);continue}if(!j(D)){console.warn(`[document-list][showAll] refusing symlink-escape ${t} -> ${D}`);continue}if(O(w)){let e=null;try{e=await stat$1(t)}catch(e){console.warn(`[document-list][showAll] stat failed for ${t}:`,e)}E.push({kind:`folder`,path:w,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null})}await F(t,w);continue}if(!k.isFile()||S.isExcluded(w,{bypassFilters:!0})||!O(w))continue;let L=null;try{L=await stat$1(`${e}/${k.name}`)}catch(t){console.warn(`[document-list][showAll] stat failed for ${e}/${k.name}:`,t);continue}if(isSupportedDocFile(k.name)){let e=w.replace(/\.(md|mdx)$/i,``),t=D(e);E.push({kind:`document`,docName:e,docExt:t,size:L.size,modified:L.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null});continue}let B=synthesizeShowAllAssetExt(k.name),H=ASSET_EXTENSIONS.has(B)?mediaKindForSidebarAssetExtension(B):null;E.push({kind:`asset`,docName:w,docExt:B,path:w,assetExt:B,mediaKind:H,referencedBy:[],size:L.size,modified:L.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null})}}await F(w?`${t}/${w}`:t,w??``)}function isValidRelativeContentPath(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function isReservedSyntheticFolderPath(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function listAffectedDocNames(e,t,S){let w=[...e.keys()].filter(e=>t===`file`?e===S:e===S||e.startsWith(`${S}/`));return w.sort((e,t)=>e.localeCompare(t)),w}function remapDocNameForRename(e,t,S,w){return t===`file`||e===S?w:`${w}${e.slice(S.length)}`}function assertNoSymlinkEscape(e,t){let S;try{S=realpathSync(t)}catch(e){throw e.code===`ENOENT`?new SymlinkEscapeError(`content directory does not exist`):e}let w=e;for(;;)try{if(!isWithinContentDir(realpathSync(w),S))throw new SymlinkEscapeError(`path resolves outside content directory`);return}catch(e){let S=e.code;if(S===`ELOOP`)throw new SymlinkEscapeError(`symlink cycle in path`);if(S!==`ENOENT`)throw e;let E=dirname(w);if(E===w||E!==t&&!E.startsWith(`${t}${sep}`))throw e;w=E}}function resolveContentEntryPath(e,t,S){if(!isValidRelativeContentPath(S))throw Error(`path must be a relative content path`);let w=resolve(e),E=resolve(w,t===`file`?isSupportedDocFile(S)?S:`${S}${getDocExtension(S)}`:S);if(E!==w&&!E.startsWith(`${w}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(E,w),E}function splitContentPath(e){let t=e.lastIndexOf(`/`);return t===-1?{parent:``,basename:e}:{parent:e.slice(0,t),basename:e.slice(t+1)}}function joinContentPath(e,t){return e?`${e}/${t}`:t}function duplicateBasename(e,t){return t===1?`${e} copy`:`${e} copy ${t}`}var DuplicateNameExhaustedError=class extends Error{constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};function isAlreadyExistsError(e){let t=e.code;return t===`EEXIST`||t===`ERR_FS_CP_EEXIST`}function classifyDuplicatePathFilesystemProblem(e){let t=e.code;return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function docNameExistsWithAnySupportedExtension(e,t){return SUPPORTED_DOC_EXTENSIONS.some(S=>existsSync(resolve(e,`${t}${S}`)))}function resolveDuplicateDocPath(e,t,S){if(!isValidRelativeContentPath(t))throw Error(`path must be a relative content path`);let w=resolve(e),E=resolve(w,`${t}${S}`);if(E!==w&&!E.startsWith(`${w}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(E,w),E}function nextAvailableDuplicateDocName(e,t){let{parent:S,basename:w}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let E=joinContentPath(S,duplicateBasename(w,t));if(!docNameExistsWithAnySupportedExtension(e,E))return{docName:E,attempt:t}}throw new DuplicateNameExhaustedError(t)}function nextAvailableDuplicateFolderPath(e,t){let{parent:S,basename:w}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let E=joinContentPath(S,duplicateBasename(w,t));if(!existsSync(resolveContentEntryPath(e,`folder`,E)))return{folderPath:E,attempt:t}}throw new DuplicateNameExhaustedError(t)}function collectMarkdownCopies(e,t){let S=resolveContentEntryPath(e,`folder`,t),w=[];function E(e,t){for(let S of readdirSync(e,{withFileTypes:!0})){let D=resolve(e,S.name),O=t?`${t}/${S.name}`:S.name;if(S.isDirectory()){E(D,O);continue}!S.isFile()||!isSupportedDocFile(O)||w.push({docName:stripDocExtension(O),fullPath:D,content:readFileSync(D,`utf-8`)})}}return E(S,t),w.sort((e,t)=>e.docName.localeCompare(t.docName)),w}function collectFolderPaths(e,t){let S=resolveContentEntryPath(e,`folder`,t),w=[t];function E(e,t){for(let S of readdirSync(e,{withFileTypes:!0})){if(!S.isDirectory())continue;let D=resolve(e,S.name),O=t?`${t}/${S.name}`:S.name;w.push(O),E(D,O)}}return E(S,t),w.sort((e,t)=>e.localeCompare(t)),w}function probeAndRegisterSourceFileExtension(e,t){if(!isValidRelativeContentPath(t))return;let S=resolve(e);for(let e of SUPPORTED_DOC_EXTENSIONS){let w=resolve(S,`${t}${e}`);if(!(w!==S&&!w.startsWith(`${S}${sep}`))&&existsSync(w)){registerDocExtension(t,e);return}}}function toGitRelativePath(e,t){let S=resolve(e),w=resolve(t);return w!==S&&!w.startsWith(`${S}${sep}`)?null:relative(S,w).split(sep).join(`/`)}async function renameTrackedPathInGit(e,t,S){if(!e)return!1;let w=toGitRelativePath(e,t),E=toGitRelativePath(e,S);return!w||!E?!1:await withParentLock(async()=>{let t=esm_default({baseDir:e,timeout:{block:15e3}}),D=``;try{D=(await t.raw(`ls-files`,`--`,w)).trim()}catch(e){return console.warn(`[renameTrackedPathInGit] git ls-files failed, falling back to fs rename:`,e),!1}if(!D)return!1;mkdirSync(dirname(S),{recursive:!0});try{return await t.raw(`mv`,`--`,w,E),!0}catch(e){return console.warn(`[renameTrackedPathInGit] git mv failed, falling back to fs rename:`,e),!1}})}const workspaceSearchCaches=new Map;function extractHeadings(e){let t=e;if(e.startsWith(`---
2370
+ `).filter(Boolean);ae.push(...e)}catch{}if(ae.length===0&&ne.length===0&&se.length===0)return EMPTY;let ce=[...ne,...se],ue=[];if(ce.length>0){let t=parseGitLogOutput(await te.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...ce)).map(e=>({...e,type:`checkpoint`}));if(H&&(t=await filterEntriesByChain(e,t,L,E,B,ee,Y)),oe&&ne.length>0&&se.length>0){let e=new Set(ne),S=t.filter(t=>e.has(t.sha)),w=t.filter(t=>!e.has(t.sha)),E=S.reduce((e,t)=>{let S=new Date(t.timestamp).getTime();return S<e?S:e},1/0);ue=[...S,...w.filter(e=>new Date(e.timestamp).getTime()<E)]}else ue=t}let de=[...ae];for(let e of ce)de.push(e);let fe=[];if(de.length>0&&(fe=parseGitLogOutput(await te.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...de,...H?[`--`,H]:[])),J))for(let t=0;t<L.length-1;t++){let S=L[t];if(S.renameCommit!==null)try{let t=await buildSeeds(e,S.renameCommit,E,Y);if(t.length===0)continue;let w=B(S.path),D=await logSeededReachable(e,[`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`],t,w);fe=[...fe,...parseGitLogOutput(D)]}catch(e){console.warn(`[timeline] predecessor walk failed for step ${t} (${S.path}); skipping:`,e)}}let me=[...ue,...fe],ge=new Set,_e=[];for(let e of me)ge.has(e.sha)||(ge.add(e.sha),_e.push(e));let ve=_e;_e.length>0&&L.length>0&&(ve=filterEntriesByOkActorDocs(_e,L,await Promise.all(L.map(async t=>{if(t.renameCommit===null)return null;let S=await buildSeeds(e,t.renameCommit,E,Y);return S.length===0?new Set:buildAncestorShaSet(e,S,E,ee)})))),ve.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let ye=ve;ye=ye.filter(e=>e.type!==`park`),k.length>0&&(ye=ye.filter(e=>k.includes(e.type))),j.length>0&&(ye=ye.filter(e=>matchesAuthor(e,j))),F.length>0&&(ye=ye.filter(e=>!matchesAuthor(e,F)));let Ce=ye.length;return{entries:ye.slice(O,O+D).map(({rawBody:e,...t})=>t),total:Ce,hasMore:O+D<Ce}}catch(e){return console.warn(`[timeline] getDocumentHistory failed, returning empty result:`,e),EMPTY}}let _httpDurationHist=null;function httpDurationHist(){return _httpDurationHist||=getMeter().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),_httpDurationHist}let _hintEmittedCounter=null;function hintEmittedCounter(){return _hintEmittedCounter||=getMeter().createCounter(`ok.preview_attach.hint_emitted`,{description:`Count of preview-attach hints emitted on write-tool responses when no editor is attached to __system__. Covers both attach-preview-once (URL exists, no browser) and start-ui (no UI running anywhere) variants — the tool side disambiguates via the warning action; the metric name is retained as-is so existing dashboards keep working.`}),_hintEmittedCounter}let _agentPatchFmTouchCounter=null;function agentPatchFmTouchCounter(){return _agentPatchFmTouchCounter||=getMeter().createCounter(`ok.frontmatter.agent_patch_fm_touch_total`,{description:`Count of agent-patch calls whose find string targets the frontmatter region. Measures incidence during the soft-deprecation window before agent-patch FM-intersecting calls are enforced as 400. Bounded label: result ∈ {rejected, pre_deprecation_passthrough}.`}),_agentPatchFmTouchCounter}function findLooksLikeFrontmatter(e){return!!(/(^|\n)---(\s|\n|$)/.test(e)||/^\s*[\w-]+:\s+\S/.test(e))}let _renameAttributionCounter=null;function renameAttributionCounter(){return _renameAttributionCounter||=getMeter().createCounter(`ok.rename.attribution_kind`,{description:`Count of rename and rollback handler dispatches by attribution kind (agent | principal | anonymous)`}),_renameAttributionCounter}const ROLLBACK_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},MANAGED_RENAME_ORIGIN={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},log$3=getLogger(`api`);function ytextHasConflictMarkers(e){return/^<{7} /m.test(e)&&/^={7}$/m.test(e)&&/^>{7} /m.test(e)}function safeDocPath(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name.`};let S=t===`.`?``:t.replace(/^\.\//,``),w=getDocExtension(e);return{path:S?`${S}/${e}${w}`:`${e}${w}`}}const GENERIC_PASTE_NAMES=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i,SAFE_FILENAME_CHARS=/[^\p{L}\p{N}\p{M}\p{Extended_Pictographic}.\-_ ]/gu,STRIP_ON_SIGHT=/[/\\\x00-\x1f\x7f]/g;function sanitizeFilename(e){let t=e.replace(STRIP_ON_SIGHT,``);if(t=t.replace(SAFE_FILENAME_CHARS,`_`),t=t.replace(/_+/g,`_`).replace(/\.{2,}/g,`.`),t=t.replace(/^[._]+/,``),t=t.replace(/\.+$/,``),t===``)return`upload`;let S=255,w=new TextEncoder;if(w.encode(t).length>255){let e=t.lastIndexOf(`.`),S=e>=0?t.slice(e):``,E=e>=0?t.slice(0,e):t;for(;w.encode(E+S).length>255&&E.length>0;)E=E.slice(0,-1);t=(E||`upload`)+S,w.encode(t).length>255&&(t=`upload`)}return t}function resolveUploadDestDir(e,t,S){let w=t.trim();return w===``||w===`./`?resolve(S,dirname(e)):w===`/`?S:w.startsWith(`./`)?resolve(S,dirname(e),w.slice(2)):resolve(S,w)}function readTempFileHead(e,t){let S=openSync(e,`r`);try{let e=Buffer.alloc(t),w=readSync(S,e,0,t,0);return e.subarray(0,w)}finally{closeSync(S)}}const MAX_DEDUP_SCAN_CANDIDATES=1e3;async function streamingHashFile(e){let t=createHash(`sha256`);return await pipeline(createReadStream(e),t),t.digest(`hex`)}async function findDuplicateAsset(e,t,S){let w;try{w=await readdir(e)}catch{return null}let E=getLogger(`upload`),D=0;for(let O of w){let w=extname(O).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(w))continue;let k=resolve(e,O),j;try{j=await stat$1(k)}catch{continue}if(!j.isFile()||j.size!==S)continue;if(D++,D>MAX_DEDUP_SCAN_CANDIDATES)return E.warn({event:`upload-dedup-skip`,reason:`scan-cap-exceeded`,destDir:e,scanned:MAX_DEDUP_SCAN_CANDIDATES,expectedSize:S},`[upload-dedup] candidate scan exceeded ${MAX_DEDUP_SCAN_CANDIDATES} same-size siblings — degrading to no-dedup for this upload`),null;let F;try{F=await streamingHashFile(k)}catch(e){let t=e.code;t!==`ENOENT`&&E.warn({event:`upload-dedup-skip`,reason:`read-failed`,code:t,entry:O},`[upload-dedup] skipped candidate — read failed`);continue}if(F===t)return O}return null}function readUploadBody(e,t){return new Promise((S,w)=>{let E;try{E=(0,import_lib.default)({headers:e.headers,limits:{files:1,fields:10,fieldSize:2*1024}})}catch(e){w(new UploadWriteError(`urn:ok:error:malformed-upload`,e));return}let D=!1,O=`upload`,k=``,j=``,F,L,B=!1,H=(e,t)=>{if(!D){if(D=!0,F)try{unlinkSync(F)}catch{}w(t instanceof UploadWriteError?t:new UploadWriteError(e,t))}},q=classifyUploadErrno;E.on(`field`,(e,t)=>{e===`parentDocName`&&(j=t)}),E.on(`file`,(e,w,E)=>{B=!0,O=E.filename||`upload`,k=E.mimeType||``;let J;try{J=mintTempUploadPath(t)}catch(e){H(q(e),e),w.resume();return}F=J;let Y=new HashingPassThrough;pipeline(w,Y,createWriteStream(J)).then(()=>{D||(D=!0,S({filename:O,mimeType:k,parentDocName:j,tempPath:J,sha:Y.digest(),byteLength:Y.byteLength()}))}).catch(e=>{L=e,H(q(e),e)})}),E.on(`error`,e=>{H(`urn:ok:error:malformed-upload`,e)}),E.on(`close`,()=>{D||L||B||(D=!0,S({filename:``,mimeType:``,parentDocName:j,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{D||L||e.complete||H(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(E)})}function safeSubdir(e,t){let S=resolve(e,t);if(S!==e&&!S.startsWith(`${e}/`))throw Error(`Invalid directory: ${t}`);return S}function synthesizeShowAllAssetExt(e){let t=extname(e);return t?t.slice(1).toLowerCase():e.startsWith(`.`)&&e.length>1?e.slice(1).toLowerCase():`file`}async function walkContentDirForShowAll(e){let{contentDir:t,contentFilter:S,dirFilter:w,documents:E,getDocExtension:D}=e,O=e=>w?e===w||e.startsWith(`${w}/`):!0,k;try{k=await realpath(t)}catch{k=t}let j=e=>e===k?!0:e.startsWith(`${k}/`);async function F(e,t){let w;try{w=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[document-list][showAll] readdir failed for ${e}:`,t);return}for(let k of w){let w=t?`${t}/${k.name}`:k.name;if(k.isDirectory()){if(S.isDirExcluded(w,{bypassFilters:!0}))continue;let t=`${e}/${k.name}`,D;try{D=await realpath(t)}catch(e){console.warn(`[document-list][showAll] realpath failed for ${t}:`,e);continue}if(!j(D)){console.warn(`[document-list][showAll] refusing symlink-escape ${t} -> ${D}`);continue}if(O(w)){let e=null;try{e=await stat$1(t)}catch(e){console.warn(`[document-list][showAll] stat failed for ${t}:`,e)}E.push({kind:`folder`,path:w,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null})}await F(t,w);continue}if(!k.isFile()||S.isExcluded(w,{bypassFilters:!0})||!O(w))continue;let L=null;try{L=await stat$1(`${e}/${k.name}`)}catch(t){console.warn(`[document-list][showAll] stat failed for ${e}/${k.name}:`,t);continue}if(isSupportedDocFile(k.name)){let e=w.replace(/\.(md|mdx)$/i,``),t=D(e);E.push({kind:`document`,docName:e,docExt:t,size:L.size,modified:L.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null});continue}let B=synthesizeShowAllAssetExt(k.name),H=ASSET_EXTENSIONS.has(B)?mediaKindForSidebarAssetExtension(B):null;E.push({kind:`asset`,docName:w,docExt:B,path:w,assetExt:B,mediaKind:H,referencedBy:[],size:L.size,modified:L.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null})}}await F(w?`${t}/${w}`:t,w??``)}function isValidRelativeContentPath(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function isReservedProjectStatePath(e){return e===`.ok`||e.startsWith(`.ok/`)||e===`.git`||e.startsWith(`.git/`)}function isReservedSyntheticFolderPath(e){return e===`__system__`||e===`__config__`||e===`__user__`||e===`__local__`||e.startsWith(`__system__/`)||e.startsWith(`__config__/`)||e.startsWith(`__user__/`)||e.startsWith(`__local__/`)}function listAffectedDocNames(e,t,S){let w=[...e.keys()].filter(e=>t===`file`?e===S:e===S||e.startsWith(`${S}/`));return w.sort((e,t)=>e.localeCompare(t)),w}function remapDocNameForRename(e,t,S,w){return t===`file`||e===S?w:`${w}${e.slice(S.length)}`}function assertNoSymlinkEscape(e,t){let S;try{S=realpathSync(t)}catch(e){throw e.code===`ENOENT`?new SymlinkEscapeError(`content directory does not exist`):e}let w=e;for(;;)try{if(!isWithinContentDir(realpathSync(w),S))throw new SymlinkEscapeError(`path resolves outside content directory`);return}catch(e){let S=e.code;if(S===`ELOOP`)throw new SymlinkEscapeError(`symlink cycle in path`);if(S!==`ENOENT`)throw e;let E=dirname(w);if(E===w||E!==t&&!E.startsWith(`${t}${sep}`))throw e;w=E}}function resolveContentEntryPath(e,t,S){if(!isValidRelativeContentPath(S))throw Error(`path must be a relative content path`);let w=resolve(e),E=resolve(w,t===`file`?isSupportedDocFile(S)?S:`${S}${getDocExtension(S)}`:S);if(E!==w&&!E.startsWith(`${w}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(E,w),E}function splitContentPath(e){let t=e.lastIndexOf(`/`);return t===-1?{parent:``,basename:e}:{parent:e.slice(0,t),basename:e.slice(t+1)}}function joinContentPath(e,t){return e?`${e}/${t}`:t}function duplicateBasename(e,t){return t===1?`${e} copy`:`${e} copy ${t}`}var DuplicateNameExhaustedError=class extends Error{constructor(e){super(`Could not find an available duplicate name for ${e}`),this.sourcePath=e,this.name=`DuplicateNameExhaustedError`}};function isAlreadyExistsError(e){let t=e.code;return t===`EEXIST`||t===`ERR_FS_CP_EEXIST`}function classifyDuplicatePathFilesystemProblem(e){let t=e.code;return t===`ENOSPC`||t===`EDQUOT`?{status:507,type:`urn:ok:error:storage-full`,title:`Could not duplicate path because storage is full.`}:t===`EPERM`||t===`EACCES`||t===`EROFS`?{status:500,type:`urn:ok:error:storage-readonly`,title:`Could not duplicate path because storage is not writable.`}:null}function docNameExistsWithAnySupportedExtension(e,t){return SUPPORTED_DOC_EXTENSIONS.some(S=>existsSync(resolve(e,`${t}${S}`)))}function resolveDuplicateDocPath(e,t,S){if(!isValidRelativeContentPath(t))throw Error(`path must be a relative content path`);let w=resolve(e),E=resolve(w,`${t}${S}`);if(E!==w&&!E.startsWith(`${w}${sep}`))throw Error(`path must not escape content directory`);return assertNoSymlinkEscape(E,w),E}function nextAvailableDuplicateDocName(e,t){let{parent:S,basename:w}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let E=joinContentPath(S,duplicateBasename(w,t));if(!docNameExistsWithAnySupportedExtension(e,E))return{docName:E,attempt:t}}throw new DuplicateNameExhaustedError(t)}function nextAvailableDuplicateFolderPath(e,t){let{parent:S,basename:w}=splitContentPath(t);for(let t=1;t<=1e4;t+=1){let E=joinContentPath(S,duplicateBasename(w,t));if(!existsSync(resolveContentEntryPath(e,`folder`,E)))return{folderPath:E,attempt:t}}throw new DuplicateNameExhaustedError(t)}function collectMarkdownCopies(e,t){let S=resolveContentEntryPath(e,`folder`,t),w=[];function E(e,t){for(let S of readdirSync(e,{withFileTypes:!0})){let D=resolve(e,S.name),O=t?`${t}/${S.name}`:S.name;if(S.isDirectory()){E(D,O);continue}!S.isFile()||!isSupportedDocFile(O)||w.push({docName:stripDocExtension(O),fullPath:D,content:readFileSync(D,`utf-8`)})}}return E(S,t),w.sort((e,t)=>e.docName.localeCompare(t.docName)),w}function collectFolderPaths(e,t){let S=resolveContentEntryPath(e,`folder`,t),w=[t];function E(e,t){for(let S of readdirSync(e,{withFileTypes:!0})){if(!S.isDirectory())continue;let D=resolve(e,S.name),O=t?`${t}/${S.name}`:S.name;w.push(O),E(D,O)}}return E(S,t),w.sort((e,t)=>e.localeCompare(t)),w}function probeAndRegisterSourceFileExtension(e,t){if(!isValidRelativeContentPath(t))return;let S=resolve(e);for(let e of SUPPORTED_DOC_EXTENSIONS){let w=resolve(S,`${t}${e}`);if(!(w!==S&&!w.startsWith(`${S}${sep}`))&&existsSync(w)){registerDocExtension(t,e);return}}}function toGitRelativePath(e,t){let S=resolve(e),w=resolve(t);return w!==S&&!w.startsWith(`${S}${sep}`)?null:relative(S,w).split(sep).join(`/`)}async function renameTrackedPathInGit(e,t,S){if(!e)return!1;let w=toGitRelativePath(e,t),E=toGitRelativePath(e,S);return!w||!E?!1:await withParentLock(async()=>{let t=esm_default({baseDir:e,timeout:{block:15e3}}),D=``;try{D=(await t.raw(`ls-files`,`--`,w)).trim()}catch(e){return console.warn(`[renameTrackedPathInGit] git ls-files failed, falling back to fs rename:`,e),!1}if(!D)return!1;mkdirSync(dirname(S),{recursive:!0});try{return await t.raw(`mv`,`--`,w,E),!0}catch(e){return console.warn(`[renameTrackedPathInGit] git mv failed, falling back to fs rename:`,e),!1}})}const workspaceSearchCaches=new Map;function extractHeadings(e){let t=e;if(e.startsWith(`---
2371
2371
  `)||e.startsWith(`---\r
2372
2372
  `)){let S=e.indexOf(`
2373
2373
  ---`,3);S!==-1&&(t=e.slice(S+4))}let S=[],w=new Map,E=createCodeFenceTracker();for(let e of t.split(`
2374
- `)){if(E(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),E=getHeadingSlug(e,w);E&&S.push({level:t[1].length,text:e,slug:E})}}return S}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function createApiExtension(e){let{hocuspocus:t,sessionManager:S,contentDir:w,serverInstanceId:E,getFileIndex:D,getFolderIndex:O,getAliasMap:k,rescanFiles:j,enableTestRoutes:F=!1,shadowRef:L,flushGitCommit:B,flushContributors:H,getCurrentBranch:q,getDiskAckSVs:J,contentRoot:Y,backlinkIndex:ee,tagIndex:te,signalChannel:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,onAgentWrite:se,getSyncEngine:ce,localOpCliArgs:ue=[`open-knowledge`],projectDir:de,getPrincipal:fe,contentFilter:me,installedAgentsProbe:ge,forceUnloadDocument:_e,ready:ve,recentlyRemovedDocs:ye,serializeDoc:Ce}=e,we=createConcurrencyGuard(),Te=null;function De(){let e=O?.();return e instanceof Map?e:null}function je(e){let t=De();if(t)try{upsertFolderIndexEntry(t,w,e,statSync(e),e)}catch(t){console.warn(`[api-extension] folder index stat failed for ${e}:`,t)}}function Me(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)je(resolve(w,t.slice(0,e).join(`/`)))}function Pe(e){let t=De();t&&removeFolderIndexEntries(t,e)}function Ie(e,t){let S=De();if(!S)return;let E=[];for(let[w,D]of S.entries()){if(w!==e&&!w.startsWith(`${e}/`))continue;S.delete(w);let O=w.slice(e.length);E.push([`${t}${O}`,D])}if(E.length===0){let e=resolveContentEntryPath(w,`folder`,t);existsSync(e)&&je(e);return}for(let[e,t]of E)S.set(e,{...t,modified:new Date().toISOString(),canonicalPath:resolve(w,e)})}function Re(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
2375
- `)}let ze=createInstalledAgentsProbe({probe:ge??createOsProbe(process.platform)});function Be(e){if(!isSafeDocName(e))return null;let t=resolve(w),S=resolve(t,`${e}${getDocExtension(e)}`);return!S.startsWith(`${t}/`)&&S!==t?null:S}function Ve(e){let t=Be(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Ue(e,t){return t.has(e)?Ve(e):e}let We={cluster:void 0,category:void 0,tags:void 0};function Ge(e){try{let S=t.documents.get(e);if(S){let e=readFmMap(S.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,S=typeof e.category==`string`?e.category:void 0,w;return Array.isArray(e.tags)?w=e.tags.length>0?e.tags:void 0:typeof e.tags==`string`&&e.tags&&(w=[e.tags]),{cluster:t,category:S,tags:w}}}}catch{}try{let t=Be(e);if(!t||!existsSync(t))return We;let{frontmatter:S}=stripFrontmatter(readFileSync(t,`utf-8`));return S?parseFrontmatterMetadata(S):We}catch{return We}}function Ke(e,t){return t.has(e)?Ge(e):We}function Xe(e){if(ee)try{if(ee.getBacklinks(e).length>0)return;let t=performance.now(),S=findHubCandidates(e,D()),w=performance.now()-t;return w>5&&log$3.debug({docName:e,elapsedMs:w,candidateCount:S.length},`[orphan-hint] findHubCandidates slow`),S.length===0?void 0:[{type:`orphan`,parentCandidates:S,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): ${S.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function $e(e){return k?.().get(e)??e}function nt(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function rt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function it(e,S){let w=`onStoreDocument-${e}`;(t.debouncer.isDebounced(w)?t.debouncer.executeNow(w):Promise.resolve()).then(()=>B?.()).catch(e=>{log$3.warn({err:e},`[${S}] post-write flush failed`)})}function at(){let e=new Set;for(let[t,S]of D()){e.add(t);for(let t of S.aliases)e.add(t)}return e}function st(){let e=Promise.resolve();return async function(t){let S=e,w=()=>{};e=new Promise(e=>{w=e}),await S;try{return await t()}finally{w()}}}let vt=st(),Tt=e=>e.endsWith(`.`)?e:`${e}.`;function Et(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:Tt(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:Tt(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError?{status:400,type:`urn:ok:error:invalid-request`,error:Tt(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:Tt(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:Tt(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:Tt(e.message)}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}}async function Dt(e){let w=new Map;for(let S of e){let e=t.documents.get(S);e&&w.set(S,e.getText(`source`).toString())}for(let t of e)await S.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let S of e){let e=t.documents.get(S);deleteReconciledBase(S),e&&(t.closeConnections(S),await(_e??t.unloadDocument.bind(t))(e))}return w}function jt(e,t){for(let{fromDocName:S,toDocName:E}of e){let e=safeContentPath(E,w),D=t.get(S);typeof D==`string`&&tracedWriteFileSync(e,D,`utf-8`);let O=typeof D==`string`?D:existsSync(e)?readFileSync(e,`utf-8`):null;typeof O==`string`&&registerWrite(e,contentHash(O))}}function Mt(e,t){return e.map(e=>{let S=t.get(e);if(typeof S==`string`)return{docName:e,content:S};let E=safeContentPath(e,w);if(!existsSync(E))throw new ManagedRenameSnapshotMissingError(e);return{docName:e,content:readFileSync(E,`utf-8`)}})}function Ft(e){let S=t.documents.get(e);if(S)return S.getText(`source`).toString();let E=resolveContentEntryPath(w,`file`,e);return existsSync(E)?readFileSync(E,`utf-8`):null}function It(e,t){let S=resolveContentEntryPath(w,`file`,e);tracedMkdirSync(dirname(S),{recursive:!0}),tracedWriteFileSync(S,t,`utf-8`),registerWrite(S,contentHash(t)),setReconciledBase(e,t);let E=D();E instanceof Map&&updateFileIndex({kind:`update`,path:S,docName:e,content:t},E)}function Lt(e,S){let w=t.documents.get(e);if(!w)throw Error(`Document is not loaded: ${e}`);let E={markdown:``,rewrites:0};return w.transact(()=>{E=applyRenameMap(w.getText(`source`).toString(),e,S),E.rewrites!==0&&composeAndWriteRawBody(w,E.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),E}async function Rt(e,S,E,O){return vt(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":E}},async k=>{if(!ee)throw new BacklinkIndexRequiredError;let j=resolveContentEntryPath(w,E,e),F=resolveContentEntryPath(w,E,S);if(j===F)return{renamed:[],rewrittenDocs:[]};if(!existsSync(j))throw new ManagedRenameSourceNotFoundError(E);if(existsSync(F))throw new ManagedRenameDestinationExistsError;let B=statSync(j);if(E===`file`&&!B.isFile()||E===`folder`&&!B.isDirectory())throw new ManagedRenameSourceTypeMismatchError(E);let H=(E===`file`?[stripDocExtension(e)]:listAffectedDocNames(D(),E,e)).map(t=>({from:t,to:E===`file`?stripDocExtension(S):remapDocNameForRename(t,E,e,S)}));if(k.setAttribute(`rename.affected_docs`,H.length),H.length===0)return E===`folder`&&(await renameTrackedPathInGit(de,j,F)||(tracedMkdirSync(dirname(F),{recursive:!0}),tracedRenameSync(j,F)),Ie(e,S),ne?.(`files`)),{renamed:[],rewrittenDocs:[]};let J=buildRenameMap(H),Y=H.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),te=new Set;for(let{from:e}of H)for(let t of ee.getBacklinks(e))J.has(t.source)||te.add(t.source);let ae=[...te].sort((e,t)=>e.localeCompare(t)),oe=new Map,se=[],ce=[];for(let e of[...J.keys(),...ae]){if(oe.has(e))continue;if(!J.has(e)&&!existsSync(resolveContentEntryPath(w,`file`,e))){ce.push(e);continue}let t=Ft(e);typeof t==`string`?(oe.set(e,t),J.has(e)||se.push(e)):J.has(e)||ce.push(e)}for(let{from:e}of H)if(typeof oe.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ue=createManagedRenameRecoveryJournal({fromPath:e,toPath:S,affectedDocs:[...H],snapshots:Mt([...oe.keys()],oe)}),fe=[];return await withManagedRenameRecovery(de??w,ue,async()=>{for(let e of ce)ee.deleteDocument(e);for(let e of se){let S=t.documents.get(e)?Lt(e,J):applyRenameMap(oe.get(e)??``,e,J);S.rewrites>0&&(It(e,S.markdown),fe.push({docName:e,rewrites:S.rewrites})),ee.updateDocumentFromMarkdown(e,S.markdown)}if(ye)for(let{from:e,to:t}of H)isSystemDoc(e)||isConfigDoc(e)||(ye.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let k=resolveContentEntryPath(w,E,e),j=resolveContentEntryPath(w,E,S);await renameTrackedPathInGit(de,k,j)||(tracedMkdirSync(dirname(j),{recursive:!0}),tracedRenameSync(k,j)),E===`folder`&&Ie(e,S);let F=await Dt([...J.keys()]);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(L?.current){let e=L.current;withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":E}},t=>{let S=randomUUID(),w=new Date().toISOString(),D=q?.()??`main`,k=getOrLoadRenameLogIndex(e.gitDir),j=O?.actor?{writerId:O.actor.writerId,displayName:O.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},F=0;for(let{from:t,to:L}of H){let B={v:1,from:t,to:L,at:w,commitSha:``,branch:D,groupId:S,kind:E,actor:j};appendRenameLogEntry(e.gitDir,B,k,e),F+=1,O?.actor?recordContributor(L,O.actor.writerId,O.actor.displayName,O.actor.colorSeed,formatRenameSubject(t,L),O.actor.actorMetadata,void 0,[{from:t,to:L}]):recordContributor(L,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(t,L),void 0,void 0,[{from:t,to:L}])}t.setAttribute(`rename.entries_appended`,F)})}let B=E===`file`&&isSupportedDocFile(S)?extname(S):null;for(let{from:e,to:t}of H){let S=getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,B??S)}let Y=[...H].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of Y){let S=resolveContentEntryPath(w,`file`,e),E=resolveContentEntryPath(w,`file`,t),O=applyRenameMap(F.get(e)??oe.get(e)??readFileSync(E,`utf-8`),e,J);jt([{fromDocName:e,toDocName:t}],new Map([[e,O.markdown]])),setReconciledBase(t,O.markdown);let k=D();k instanceof Map&&updateFileIndex({kind:`rename`,oldPath:S,newPath:E,oldDocName:e,newDocName:t,content:O.markdown},k),ee.renameDocument(e,t,O.markdown),O.rewrites>0&&fe.push({docName:t,rewrites:O.rewrites})}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-journal-clear`)throw Error(`OK_TEST_RENAME_FAULT=pre-journal-clear`)}),ee.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${S}:`,t)}),ne?.(`files`),ne?.(`backlinks`),ne?.(`graph`),fe.sort((e,t)=>e.docName.localeCompare(t.docName)),k.setAttribute(`rename.rewrite_count`,fe.length),{renamed:Y,rewrittenDocs:fe}}))}function zt(e){let t=parseAgentBodyFields(e),S=t.writerId??`claude-1`;return{rawAgentId:t.rawAgentId,agentId:S,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??S,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function Bt(e){return{principalId:fe?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Vt(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 Ht(e){return{value:e.value}}function Ut(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}let Wt=withValidation(AgentWriteRequestSchema,async(t,w,E)=>{try{let t=$e(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:D,agentName:O,colorSeed:k,clientName:j,clientVersion:F,label:L}=zt(E);if(isSystemDoc(t)||isConfigDoc(t)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${t}' is a reserved document name.`,{handler:`agent-write`});return}let B=normalizeSummary(E.summary),H=await S.getSession(t,D,{displayName:O,colorSeed:k,clientName:j}),q=new Date().toISOString(),J=typeof E.content==`string`?E.content:`Hello from the agent! ${q}`,{response:Y,stored:ee}=Vt(B);try{let S=iconFromClientName(j),w=AGENT_ICON_COLORS[S]??colorFromSeed(k??D);oe?.setPresence(D,{displayName:O,icon:S,color:w,currentDoc:t,mode:`writing`,ts:Date.now()}),captureEffect(H.dc.document.getText(`source`),D,k,j),H.dc.document.transact(()=>{applyAgentMarkdownWrite(H.dc.document,`${J}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:t}:void 0),H.dc.document.getMap(`agent-flash`).set(D,{agentId:D,timestamp:Date.now(),type:`insert`,description:`Added (${O}): ${J.slice(0,50)}`})},H.origin),recordContributor(t,D,O,k,void 0,Bt({clientName:j,clientVersion:F,label:L}),ee),incrementAgentWriteCalls(),Ut(B)}finally{oe?.touchMode(D,`idle`)}it(t,`agent-write`),se?.(),successResponse(w,200,AgentWriteSuccessSchema,{timestamp:q,...Y?{summary:Y}:{}},{handler:`agent-write`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$3.error({err:e},`[agent-write] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),Kt=withValidation(AgentWriteMdRequestSchema,async(t,w,E)=>{try{let t=E.position??`append`,D=$e(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=zt(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write-md`});return}let H=normalizeSummary(E.summary),{response:q,stored:J}=Vt(H),Y=await S.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=new Date().toISOString();try{let S=iconFromClientName(F),w=AGENT_ICON_COLORS[S]??colorFromSeed(j??O);oe?.setPresence(O,{displayName:k,icon:S,color:w,currentDoc:D,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),O,j,F),Y.dc.document.transact(()=>{applyAgentMarkdownWrite(Y.dc.document,E.markdown,t,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),Y.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),recordContributor(D,O,k,j,void 0,Bt({clientName:F,clientVersion:L,label:B}),J),incrementAgentWriteCalls(),Ut(H)}finally{oe?.touchMode(O,`idle`)}it(D,`agent-write-md`),ae?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),se?.();let te=Xe(D),ne=nt(D),ce=rt();ce===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)}),successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ee,subscriberCount:ne,systemSubscriberCount:ce,...te?{hints:te}:{},...q?{summary:q}:{}},{handler:`agent-write-md`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write-md`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write-md`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write-md`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$3.error({err:e},`[agent-write-md] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-md`,cause:e})}},{handler:`agent-write-md`,method:`POST`}),$t=withValidation(FrontmatterPatchRequestSchema,async(e,t,w)=>{try{let e=$e(w.docName!==void 0&&w.docName.length>0?w.docName:`test-doc`),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=zt(w);if(isSystemDoc(e)||isConfigDoc(e)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${e}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let L=w.patch??{},B=Object.keys(L),H=normalizeSummary(w.summary),{response:q,stored:J}=Vt(H),Y=await S.getSession(e,E,{displayName:D,colorSeed:O,clientName:k}),ee=new Date().toISOString(),te,ne=!1,ce=[];try{let t=iconFromClientName(k),S=AGENT_ICON_COLORS[t]??colorFromSeed(O??E);oe?.setPresence(E,{displayName:D,icon:t,color:S,currentDoc:e,mode:`writing`,ts:Date.now()}),withSpanSync(`ok.frontmatter_patch`,{attributes:{"doc.name":e,"frontmatter_patch.keys":B.length}},()=>{Y.dc.document.transact(()=>{let{fenced:e,body:t}=detectFmRegion(Y.dc.document.getText(`source`).toString()),S=applyPatchToFm(e,L);if(!S.ok){te=S.error;return}for(let e of Object.keys(L))ce.push(e);if(S.nextFenced!==e){let e=S.nextFenced+t;composeAndWriteRawBody(Y.dc.document,e,`agent`),recordFrontmatterEditSurface(`mcp-write`)}ne=!0},Y.origin)})}finally{oe?.touchMode(E,`idle`)}if(te){let e;switch(te.kind){case`invalid_value`:e={[te.key]:te.reason};break;case`reserved_key`:e={[te.key]:`'${te.key}' is reserved`};break;case`unknown_key`:e={[te.key]:`'${te.key}' is not a recognized key`};break;case`duplicate_target`:e={[te.key]:`'${te.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${te.expected.join(`, `)}; got: ${te.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${te.bytes} > ${te.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${te.reason}`};break;default:e={__region__:`unhandled frontmatter edit error (${String(te)})`}}errorResponse(t,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}ne&&ce.length>0&&(recordContributor(e,E,D,O,void 0,Bt({clientName:k,clientVersion:j,label:F}),J),incrementAgentWriteCalls(),Ut(H),it(e,`frontmatter-patch`)),ae?.setFocus(E,{agentName:D,currentDoc:e,writeKind:`write`,ts:Date.now()}),se?.();let ue=nt(e),de=rt();de===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(k)}),successResponse(t,200,FrontmatterPatchSuccessSchema,{timestamp:ee,subscriberCount:ue,systemSubscriberCount:de,appliedKeys:ce,...q?{summary:q}:{}},{handler:`frontmatter-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(t,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$3.error({err:e},`[frontmatter-patch] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function en(e){let t=e.getMap(`lifecycle`),S=t.get(`status`);if(typeof S!=`string`||S.length===0)return null;let w=t.get(`reason`);return{status:S,reason:typeof w==`string`?w:``}}let jr=withValidation(EmptyRequestSchema,async(e,S)=>{try{let E=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(E)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let D=$e(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`document-read`});return}let O=t.documents.get(D);if(O){successResponse(S,200,DocumentReadSuccessSchema,{docName:D,content:O.getText(`source`).toString(),lifecycle:en(O)},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(w,`file`,D))){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Document not found: ${D}.`,{handler:`document-read`});return}let k=await t.openDirectConnection(D);try{let e=k.document;if(!e){errorResponse(S,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}successResponse(S,200,DocumentReadSuccessSchema,{docName:D,content:e.getText(`source`).toString(),lifecycle:en(e)},{handler:`document-read`})}finally{await k.disconnect()}}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),Mr=withValidation(EmptyRequestSchema,async(e,t)=>{try{ve&&await ve.catch(e=>{log$3.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=S.searchParams.get(`dir`),k=S.searchParams.get(`showAll`)===`true`;if(E)try{safeSubdir(w,E)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(k&&me){let e=[];try{await walkContentDirForShowAll({contentDir:w,contentFilter:me,dirFilter:E,documents:e,getDocExtension}),e.sort((e,t)=>{let S=e.kind===`folder`?e.path??``:e.docName??e.path??``,w=t.kind===`folder`?t.path??``:t.docName??t.path??``;return S.localeCompare(w)}),successResponse(t,200,DocumentListSuccessSchema,{documents:e},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}return}let j=D(),F=O?.()??new Map,L=[];for(let[e,t]of F)E&&!e.startsWith(`${E}/`)&&e!==E||L.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let[e,t]of j){if(E&&!e.startsWith(`${E}/`)&&e!==E)continue;let S=getDocExtension(e);L.push({kind:`document`,docName:e,docExt:S,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let D of t.aliases){if(E&&!D.startsWith(`${E}/`)&&D!==E)continue;let O=relative(w,t.canonicalPath);L.push({kind:`document`,docName:D,docExt:S,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:O})}}let B=[];try{let e=Re(j);Te?.signature!==e&&(Te={signature:e,assets:collectReferencedAssets({contentDir:w,fileIndex:j,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:me?e=>me.isPathIgnored(e):void 0})}),B=Te?.assets??[]}catch(e){Te=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}for(let e of B)E&&!e.path.startsWith(`${E}/`)&&e.path!==E||L.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});L.sort((e,t)=>{let S=e.kind===`folder`?e.path??``:e.docName??e.path??``,w=t.kind===`folder`?t.path??``:t.docName??t.path??``;return S.localeCompare(w)}),successResponse(t,200,DocumentListSuccessSchema,{documents:L},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),Fr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}successResponse(t,200,BacklinksSuccessSchema,{docName:S,backlinks:ee.getBacklinks(S).map(e=>({source:e.source,anchor:e.anchor,title:Ve(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),Ir=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let w={};for(let e of S.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(w[t]=ee.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:w},{handler:`backlink-counts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),Lr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let w=at();successResponse(t,200,ForwardLinksSuccessSchema,{docName:S,forwardLinks:ee.getForwardLinkEntries(S).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Ue(e.target,w),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),zr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`docName`);if(w&&!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let E=S.searchParams.get(`degrees`);if(E&&!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let D,O;if(E&&w){let e=Number.parseInt(E,10);if(!Number.isFinite(e)||e<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:D,links:O}=ee.getLinkGraphNeighborhood(w,e))}else ({nodes:D,links:O}=ee.getLinkGraph());let k=at();successResponse(t,200,LinkGraphSuccessSchema,{nodes:D.map(e=>{if(e.kind===`doc`){let t=Ke(e.docName,k);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Ue(e.docName,k),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},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),Br=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}successResponse(t,200,OrphansSuccessSchema,{orphans:ee.getOrphans([...D().keys()],S).map(e=>({docName:e,title:Ve(e)}))},{handler:`orphans`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),Vr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),w=S?Number.parseInt(S,10):20,E=Number.isFinite(w)&&w>0?w:20,D=at();successResponse(t,200,HubsSuccessSchema,{hubs:ee.getHubs(E).map(e=>({docName:e.docName,title:Ue(e.docName,D),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),Hr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(S.some(e=>e.length===0||!isSafeDocName(e))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let w=S.length?[...new Set(S.map(e=>$e(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ee.getDeadLinks(at(),w).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:Ve(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),Ur=withValidation(AgentPatchRequestSchema,async(t,w,E)=>{try{let{find:t,replace:D,offset:O}=E,k=$e(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:j,agentName:F,colorSeed:L,clientName:B,clientVersion:H,label:q}=zt(E);if(findLooksLikeFrontmatter(t)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via edit_document. Use write_document with position:"replace" to rewrite the document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(k)||isConfigDoc(k)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${k}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await S.getSession(k,j,{displayName:F,colorSeed:L,clientName:B}),ee=new Date().toISOString(),te=!1,ne=!1,ce=!1;try{let S=iconFromClientName(B),w=AGENT_ICON_COLORS[S]??colorFromSeed(L??j);if(oe?.setPresence(j,{displayName:F,icon:S,color:w,currentDoc:k,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),j,L,B),Y.dc.document.transact(()=>{let{frontmatter:S,body:w}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),E=prependFrontmatter(S,w),L=O==null?E.indexOf(t):E.slice(O,O+t.length)===t?O:-1;if(L===-1){O==null?te=!0:ne=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":k,findLength:t.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(L<S.length){ce=!0;return}let{body:B}=stripFrontmatter(E.slice(0,L)+D+E.slice(L+t.length));applyAgentMarkdownWrite(Y.dc.document,B,`replace`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:k}:void 0),Y.dc.document.getMap(`agent-flash`).set(j,{agentId:j,timestamp:Date.now(),type:`insert`,description:`Patched (${F}): ${t.slice(0,50)}`})},Y.origin),!te&&!ne&&!ce){let{stored:e}=Vt(J);recordContributor(k,j,F,L,void 0,Bt({clientName:B,clientVersion:H,label:q}),e),incrementAgentWriteCalls(),Ut(J)}}finally{oe?.touchMode(j,`idle`)}if(ne){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(te){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(ce){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via edit_document. Use write_document with position:"replace" to rewrite the document including its YAML block.`,{handler:`agent-patch`});return}it(k,`agent-patch`),ae?.setFocus(j,{agentName:F,currentDoc:k,writeKind:`edit`,ts:Date.now()}),se?.();let ue=nt(k),de=rt();de===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(B)});let{response:fe}=Vt(J);successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ee,subscriberCount:ue,systemSubscriberCount:de,...fe?{summary:fe}:{}},{handler:`agent-patch`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-patch`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-patch`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$3.error({err:e},`[agent-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),Wr=withValidation(AgentUndoRequestSchema,async(t,w,E)=>{try{let{agentId:t,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=zt(E),L=$e(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`);if(isSystemDoc(L)||isConfigDoc(L)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${L}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:B}=E,H=E.scope===`session`||E.scope===`file`?`session`:`last`;if(!S.hasSession(L,B)){errorResponse(w,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let q=await S.getSession(L,B),J=!1;try{let S=iconFromClientName(k),w=AGENT_ICON_COLORS[S]??colorFromSeed(O??t);oe?.setPresence(t,{displayName:D,icon:S,color:w,currentDoc:L,mode:`writing`,ts:Date.now()}),J=applyAgentUndo(q,H,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:L}:void 0),J&&recordContributor(L,B,D,O,void 0,Bt({clientName:k,clientVersion:j,label:F}))}finally{oe?.touchMode(t,`idle`)}J&&it(L,`agent-undo`),ae?.setFocus(B,{agentName:B,currentDoc:L,writeKind:`undo`,ts:Date.now()}),successResponse(w,200,AgentUndoSuccessSchema,{docName:L,scope:H,undone:J},{handler:`agent-undo`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-undo`);return}log$3.error({err:e},`[agent-undo] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),Gr=withValidation(EmptyRequestSchema,async(e,t)=>{try{let w=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(S,w),{handler:`agent-activity`})}catch(e){log$3.error({err:e},`[agent-activity] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),Kr=withValidation(EmptyRequestSchema,async(e,t)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=validateAgentId(w.searchParams.get(`agentId`)),D=w.searchParams.get(`docName`),O=w.searchParams.get(`stackIndex`);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!D||D.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(D)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let k=$e(D);if(isSystemDoc(k)||isConfigDoc(k)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${k}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!O||Number.isNaN(Number(O))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let j=Number(O);if(!Number.isInteger(j)||j<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let F=S.getLiveSession(k,E);if(!F){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let L=F.um;if(j>=L.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${j} out of range (stack has ${L.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let B=L.undoStack[j];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(B,F.dc.document.getText(`source`),k),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$3.error({err:e},`[agent-burst-diff] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),qr=withValidation(EmptyRequestSchema,async(e,E)=>{try{let D=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),O=$e(D.searchParams.get(`docName`)??`test-doc`),k;try{k=safeContentPath(O,w)}catch(e){log$3.error({err:e,docName:O},`[test-reset] safeContentPath rejected docName`),errorResponse(E,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await S.closeAll(O),t.closeConnections(O);let j=`onStoreDocument-${O}`;t.debouncer.isDebounced(j)&&await t.debouncer.executeNow(j);let F=t.documents.get(O);if(F&&await(_e??t.unloadDocument.bind(t))(F),writeFileSync(k,``,`utf-8`),ee&&(ee.deleteDocument(O),ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${O}:`,e)}),ne?.(`backlinks`),ne?.(`graph`)),D.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(w,`.okignore`),S=t.documents.get(CONFIG_DOC_NAME_OKIGNORE);if(S){let e=S.getText(`source`);e.length>0&&S.transact(()=>{e.delete(0,e.length)},CONFIG_VALIDATION_REVERT_ORIGIN)}existsSync(e)&&writeFileSync(e,``,`utf-8`),me&&await me.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}ne?.(`files`),successResponse(E,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(E,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),Jr=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ee){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ee.rebuildFromDisk(),ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),ne?.(`backlinks`),ne?.(`graph`),successResponse(t,200,TestRescanBacklinksSuccessSchema,{},{handler:`test-rescan-backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),Yr=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!j){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}j(),ne?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),Xr=withValidation(SaveVersionRequestSchema,async(e,t,S)=>{try{let{rawAgentId:e,agentId:w,agentName:E,clientName:D}=zt(S),O=L?.current;if(!O){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let k=/^[a-zA-Z0-9_-]+$/,j=[];if(Array.isArray(S.writers))try{j=S.writers.map(e=>{let t=e.id??`unknown`;if(!k.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,``)}})}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}j.length===0&&(j=e===void 0?[SERVICE_WRITER]:[{id:w,name:D?`${E} (${D})`:E,email:`${w}@openknowledge.local`}]);let F=await saveVersion(O,Y??`.`,j);console.log(`[history] checkpoint ${F.checkpointRef}`);try{await gcRenameLog(O,getOrLoadRenameLogIndex(O.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:F.checkpointRef},{handler:`save-version`})}catch(e){log$3.error({err:e},`[save-version] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),Zr=withValidation(EmptyRequestSchema,async(e,t)=>{let S=L?.current;if(!S){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=w.searchParams.get(`docName`)??``,D=w.searchParams.get(`branch`)??q?.()??`main`;if(!E){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName query parameter is required.`,{handler:`history`});return}if(D.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(D)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}let O=Y??`.`,k=safeDocPath(E,O);if(`error`in k){errorResponse(t,400,`urn:ok:error:invalid-request`,k.error,{handler:`history`});return}let j=Number(w.searchParams.get(`limit`)??`50`),F=Number(w.searchParams.get(`offset`)??`0`),B=Math.min(200,Number.isFinite(j)?j:50),H=Number.isFinite(F)?F:0,J=w.searchParams.get(`type`)??void 0,ee=w.searchParams.get(`author`)??void 0,te=w.searchParams.get(`excludeAuthor`)??void 0,ne=Date.now();try{let e=await getDocumentHistory(S,{docName:E,branch:D,limit:B,offset:H,type:J,author:ee,excludeAuthor:te},O),w=Date.now()-ne;console.log(`[timeline] query docName=${E} entries=${e.entries.length} duration=${w}ms`),successResponse(t,200,HistorySuccessSchema,{...e},{handler:`history`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function Qr(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let w=L?.current;if(!w){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let E=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,D=Y??`.`,O=safeDocPath(E,D);if(`error`in O){errorResponse(t,400,`urn:ok:error:invalid-request`,O.error,{handler:`history-version`});return}let k=shadowGit(w),j=q?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await resolveDocPathAtCommit(w,E,S,j,getOrLoadRenameLogIndex(w.gitDir),e=>{let t=safeDocPath(e,D);return`error`in t?`${e}.md`:t.path},createAncestorShaSetCache());if(e===null){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let O=await k.raw(`show`,`${S}:${e}`),[F=``,L=``]=(await k.raw(`log`,`-1`,`--format=%aI%x00%an`,S)).trim().split(`\0`);successResponse(t,200,HistoryVersionSuccessSchema,{sha:S,content:O,timestamp:F,author:L},{handler:`history-version`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let ji=withValidation(EmptyRequestSchema,async(e,S)=>{let w=L?.current;if(!w){errorResponse(S,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`diff`});return}let E=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),D=E.searchParams.get(`docName`)??``,O=E.searchParams.get(`from`)??``,k=E.searchParams.get(`to`)??``;if(!k||!/^[0-9a-f]{40}$/i.test(k)){errorResponse(S,400,`urn:ok:error:invalid-request`,`'to' must be a valid 40-char commit SHA.`,{handler:`diff`});return}let j=Y??`.`,F=safeDocPath(D,j);if(`error`in F){errorResponse(S,400,`urn:ok:error:invalid-request`,F.error,{handler:`diff`});return}let B=shadowGit(w),H=q?.()??`main`,J=getOrLoadRenameLogIndex(w.gitDir),ee=createAncestorShaSetCache(),te=e=>{let t=safeDocPath(e,j);return`error`in t?`${e}.md`:t.path};try{let e=await resolveDocPathAtCommit(w,D,k,H,J,te,ee);if(e===null){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Document did not exist at the target version.`,{handler:`diff`});return}let E=await B.raw(`show`,`${k}:${e}`),j;if(O&&/^[0-9a-f]{40}$/i.test(O)){let e=await resolveDocPathAtCommit(w,D,O,H,J,te,ee);if(e===null){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Document did not exist at the source version.`,{handler:`diff`});return}j=await B.raw(`show`,`${O}:${e}`)}else{let e=t.documents.get(D);if(!e){errorResponse(S,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`diff`});return}j=e.getText(`source`).toString()}let F=stripFrontmatter(j).body,L=stripFrontmatter(E).body,q=diffLines(F,L),Y=[],ne=0,ae=0;for(let e of q){let t=e.value.replace(/\n$/,``).split(`
2376
- `),S=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)Y.push({type:S,text:e});e.added&&(ne+=t.length),e.removed&&(ae+=t.length)}successResponse(S,200,DiffSuccessSchema,{lines:Y,additions:ne,deletions:ae},{handler:`diff`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`diff`,cause:e})}},{handler:`diff`,method:`GET`,skipBodyParse:!0}),Hi=withValidation(RollbackRequestSchema,async(S,w,E)=>{let D=extractActorIdentity(E,fe);if(D.kind===`invalid-summary`){errorResponse(w,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let O=t.documents.get(E.docName);if(O&&isDocInConflict(O)){respondDocInConflict(w,new DocInConflictError({file:`${E.docName}${getDocExtension(E.docName)}`}),`rollback`);return}let k=L?.current;if(!k){errorResponse(w,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:j,commitSha:F}=E,B=Y??`.`,H=safeDocPath(j,B);if(`error`in H){errorResponse(w,400,`urn:ok:error:invalid-request`,H.error,{handler:`rollback`});return}let J=shadowGit(k),ee=Date.now();try{let S=getOrLoadRenameLogIndex(k.gitDir),E=createAncestorShaSetCache(),O=await resolveDocPathAtCommit(k,j,F,q?.()??`main`,S,e=>{let t=safeDocPath(e,B);return`error`in t?`${e}.md`:t.path},E);if(O===null){errorResponse(w,404,`urn:ok:error:doc-not-found`,`Commit ${F.slice(0,7)} does not contain document ${j} at any known historical path.`,{handler:`rollback`});return}let L=await J.raw(`show`,`${F}:${O}`),H=new Date().toISOString();await safetyCheckpoint(k,B,{action:`rollback`,context:{docName:j,targetSha:F}});let Y=t.documents.get(j);if(!Y){errorResponse(w,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let te=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0;Y.transact(()=>{replaceRawBody(Y,L,te)},ROLLBACK_ORIGIN);let ne;switch(D.kind){case`agent`:{let e=F.slice(0,8),t=D.summary.kind===`value`,S=t?D.summary:normalizeSummary(`Restored to ${e}`),w=Vt(S);ne=t||!w.response?w.response:Ht(w.response),recordContributor(j,D.writerId,D.displayName,D.colorSeed,formatRollbackSubject(j,F),D.actor,w.stored),incrementAgentWriteCalls(),Ut(S,!t);break}case`principal`:{let e=Vt(D.summary);ne=e.response,recordContributor(j,D.writerId,D.displayName,D.colorSeed,formatRollbackSubject(j,F),D.actor,e.stored),Ut(D.summary,!1);break}case`anonymous`:log$3.debug({docName:j,commitSha:F.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(D.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:D.kind}),it(j,`rollback`);let oe=Date.now()-ee;console.log(`[rollback] docName=${j} from=${F.slice(0,8)} duration=${oe}ms`),D.kind===`agent`&&ae?.setFocus(D.writerId,{agentName:D.displayName,currentDoc:j,writeKind:`rollback-apply`,ts:Date.now()}),successResponse(w,200,RollbackSuccessSchema,{restoredFrom:F,timestamp:H,...ne?{summary:ne}:{}},{handler:`rollback`})}catch(e){errorResponse(w,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),Ui=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$3.error({err:e},`[metrics-reconciliation] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),Gi=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$3.error({err:e},`[metrics-parse-health] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),Ki=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=getActiveBranch(),S=J?.();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:E,currentBranch:e,...S===void 0?{}:{currentDiskAckSVs:S}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function Yi(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let S=fe?.()??null;if(!S){errorResponse(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}successResponse(t,200,PrincipalSuccessSchema,S,{handler:`principal`})}async function Xi(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=oe?.getPresenceMap()??{},S=Date.now(),w={};for(let[t,E]of Object.entries(e))S-E.ts<2e4&&(w[t]=E);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:w},{handler:`metrics-agent-presence`})}catch(e){log$3.error({err:e},`[metrics-agent-presence] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function Zi(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let S=resolve(w),E=S,D=!0;try{E=realpathSync(S)}catch(e){let w=e?.code;if(w===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:S}),D=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:S,err:e}),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:w??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:E,pathSeparator:sep,symlinkResolved:D},{handler:`workspace`})}let ka=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!S||S.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let E=assetContentTypeForPath(S),D=extname(S).slice(1).toLowerCase();if(!E||!ASSET_EXTENSIONS.has(D)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let O=realpathSync(w),k=resolve(O,S),j;try{j=realpathSync(k)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(j,O)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let F;try{F=statSync(j)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!F.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let L=toContentRelativePath(O,j);if(L!==S.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(me?.isPathIgnored(L)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let B={"Content-Type":E,"Content-Length":String(F.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(D)?`inline`:`attachment`,"Cache-Control":`no-store`};D===`svg`&&(B[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`),t.writeHead(200,B);try{await pipeline(createReadStream(j),t)}catch(e){log$3.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:S,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),_s=1048576,xs=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!S||S.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let E=realpathSync(w),D=resolve(E,S),O;try{O=realpathSync(D)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!isWithinContentDir(O,E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let k;try{k=statSync(O)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!k.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(toContentRelativePath(E,O)!==S.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(k.size>_s){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${_s}-byte text-viewer cap.`,{handler:`asset-text`});return}let j=(await readFile$1(O)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(j)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),Cs=1440*60*1e3,Ts=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!L?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),S=[],w=resolve(L.current.gitDir,`rescue`);if(existsSync(w))try{let t=readdirSync(w).filter(e=>isSupportedDocFile(e));for(let E of t){let t=resolve(w,E),D=statSync(t);if(e-D.mtimeMs>Cs){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}S.push({docName:stripDocExtension(E),timestamp:D.mtime.toISOString(),size:D.size,source:`flat`})}}catch(e){log$3.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=q?.()??`main`,t=await listRescueCheckpoints(L.current,e);for(let e of t)S.push({...e,source:`timeline`})}catch(e){log$3.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}successResponse(t,200,RescueListSuccessSchema,S,{handler:`rescue-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0});async function Ds(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`rescue-get`,extraHeaders:{Allow:`GET`}});return}if(!L?.current){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`rescue-get`});return}let w=resolve(L.current.gitDir,`rescue`),E=resolve(w,`${S}${getDocExtension(S)}`);if(!E.startsWith(`${w}/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid document name.`,{handler:`rescue-get`});return}if(existsSync(E)){let e=statSync(E);if(Date.now()-e.mtimeMs>Cs)try{unlinkSync(E)}catch{}else{let e=readFileSync(E,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=q?.()??`main`,w=(await listRescueCheckpoints(L.current,e)).filter(e=>e.docName===S).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(w){let e=shadowGit(L.current),S=((await e.raw(`ls-tree`,`-r`,w.sha)).trim().split(`
2377
- `)[0]??``).split(/\s+/)[2];if(S){let w=await e.raw(`cat-file`,`-p`,S);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(w);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`rescue-get`})}let Os=withValidation(CreatePageRequestSchema,async(e,t,S)=>{try{let e=extractActorIdentity(S,fe);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let E=S.path;if(!isSupportedDocFile(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(E.includes(`..`)||E.startsWith(`/`)||E.includes(`\0`)||E.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let O=resolve(w),k=resolve(O,E);if(!k.startsWith(`${O}/`)&&k!==O){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let j=stripDocExtension(E);if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`create-page`});return}let F=typeof S.template==`string`?S.template.trim():``,L=``,B;if(F.length>0){if(!/^[A-Za-z0-9_-]+$/.test(F)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let S=E.includes(`/`)?E.slice(0,E.lastIndexOf(`/`)):``,w=resolveTemplatesAvailable(O,S),D=w.find(e=>e.name===F);if(!D){let e=w.length===0?`(none)`:w.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${F}" does not resolve for folder "${S||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let k=resolve(O,D.path),j;try{j=readFileSync(k,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${D.path}.`,{handler:`create-page`,cause:e});return}let{body:H}=stripFrontmatter(j),q=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;L=applySubstitution(H,{date:todayIsoUtc(),user:q}),B=D.scope}mkdirSync(dirname(k),{recursive:!0});try{writeFileSync(k,L,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let H=stripDocExtension(E);switch(ye?.delete(H),me&&me.incrementMdDir(dirname(H)),registerWrite(k,contentHash(L)),e.kind){case`agent`:case`principal`:recordContributor(H,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}let q=typeof D==`function`?D():null;q instanceof Map&&updateFileIndex({kind:`create`,path:k,docName:H,content:L},q),ee&&(ee.updateDocumentFromMarkdown(H,L),ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${H}:`,e)}),ne?.(`backlinks`),ne?.(`graph`)),ne?.(`files`),B!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:F,templateScope:B,docName:H})),successResponse(t,200,CreatePageSuccessSchema,{docName:H},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),ks=withValidation(CreateFolderRequestSchema,async(e,t,S)=>{try{if(extractActorIdentity(S,fe).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=S.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(me?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let E=resolveContentEntryPath(w,`folder`,e);if(existsSync(E)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(E,{recursive:!0}),Me(e),ne?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),As=withValidation(DuplicatePathRequestSchema,async(e,S,E)=>{try{let e=extractActorIdentity(E,fe);if(e.kind===`invalid-summary`){errorResponse(S,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:O}=E,k=O===`file`?stripDocExtension(E.path):E.path;if(!isValidRelativeContentPath(k)){errorResponse(S,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(k===`.ok`||k.startsWith(`.ok/`)||O===`file`&&(isSystemDoc(k)||isConfigDoc(k))||O===`folder`&&isReservedSyntheticFolderPath(k)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}O===`file`&&probeAndRegisterSourceFileExtension(w,k);let j=resolveContentEntryPath(w,O,k);if(!existsSync(j)){if(O===`file`){let e=resolveContentEntryPath(w,`folder`,k);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(S,400,`urn:ok:error:invalid-request`,`Target path is not a ${O}.`,{handler:`duplicate-path`});return}}errorResponse(S,404,`urn:ok:error:doc-not-found`,`${O} does not exist.`,{handler:`duplicate-path`});return}let F=statSync(j);if(O===`file`&&!F.isFile()||O===`folder`&&!F.isDirectory()){errorResponse(S,400,`urn:ok:error:invalid-request`,`Target path is not a ${O}.`,{handler:`duplicate-path`});return}let L=O===`file`?[k]:listAffectedDocNames(D(),O,k),B=ce?.(),H=new Set(B?B.getConflicts().map(e=>e.file):[]);for(let e of L){let w=stripDocExtension(e),E=t.documents.get(w),D=`${w}${getDocExtension(w)}`,O=E!==void 0&&isDocInConflict(E),k=H.has(D);if(O||k){respondDocInConflict(S,new DocInConflictError({file:D}),`duplicate-path`);return}}let q=typeof D==`function`?D():null,J,Y=[];if(O===`file`){let e=extname(j);if(J=nextAvailableDuplicateDocName(w,k).docName,isSystemDoc(J)||isConfigDoc(J)||me?.isExcluded(`${J}${e}`)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let t=resolveDuplicateDocPath(w,J,e),E=readFileSync(j,`utf-8`),D=dirname(t),O=existsSync(D);try{tracedMkdirSync(D,{recursive:!0}),tracedWriteFileSync(t,E,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(S,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!O)try{tracedRmdirSync(D)}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTEMPTY`&&console.warn(`[duplicate-path] failed to clean duplicate parent directory:`,{destinationDir:D,err:e})}throw e}let F=!1;try{registerDocExtension(J,e),ye?.delete(J),me&&(me.incrementMdDir(dirname(J)),F=!0),registerWrite(t,contentHash(E)),q instanceof Map&&updateFileIndex({kind:`create`,path:t,docName:J,content:E},q),ee?.updateDocumentFromMarkdown(J,E),Y=[J]}catch(e){try{tracedRmSync(t,{force:!0})}catch(e){console.warn(`[duplicate-path] failed to clean partial file duplicate:`,{destinationPath:t,err:e})}throw forgetDocExtension(J),me&&F&&me.decrementMdDir(dirname(J)),q instanceof Map&&updateFileIndex({kind:`delete`,path:t,docName:J},q),e}}else{if(J=nextAvailableDuplicateFolderPath(w,k).folderPath,me?.isDirExcluded(J)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=resolveContentEntryPath(w,`folder`,J);try{tracedCpSync(j,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(isAlreadyExistsError(e)){errorResponse(S,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of collectFolderPaths(w,J))Me(e);let e=collectMarkdownCopies(w,J);Y=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(t.docName,e),ye?.delete(t.docName),me&&me.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),q instanceof Map&&updateFileIndex({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content},q),ee?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{tracedRmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[duplicate-path] failed to clean partial folder duplicate:`,{destinationPath:e,err:t})}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of Y)recordContributor(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}ee&&Y.length>0&&(ee.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),ne?.(`backlinks`),ne?.(`graph`)),ne?.(`files`),successResponse(S,200,DuplicatePathSuccessSchema,{kind:O,path:J,duplicatedDocNames:Y},{handler:`duplicate-path`})}catch(e){if(e instanceof DuplicateNameExhaustedError){errorResponse(S,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=classifyDuplicatePathFilesystemProblem(e);if(t){errorResponse(S,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),Ns=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S||S.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let w=Be(S);if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:S,headings:extractHeadings(readFileSync(w,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),Ps=withValidation(RenamePathRequestSchema,async(e,S,E)=>{try{let e=extractActorIdentity(E,fe);if(e.kind===`invalid-summary`){errorResponse(S,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:O,fromPath:k,toPath:j}=E;if(!isValidRelativeContentPath(k)||!isValidRelativeContentPath(j)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(O===`file`&&(isSystemDoc(k)||isSystemDoc(j)||isConfigDoc(k)||isConfigDoc(j))){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(k===`.ok`||k.startsWith(`.ok/`)||j===`.ok`||j.startsWith(`.ok/`)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(k===j){successResponse(S,200,RenamePathSuccessSchema,{renamed:[],rewrittenDocs:[]},{handler:`rename-path`});return}let F=O===`file`?[stripDocExtension(k)]:listAffectedDocNames(D(),O,k),L=ce?.(),B=new Set(L?L.getConflicts().map(e=>e.file):[]);for(let e of F){let w=stripDocExtension(e),E=t.documents.get(w),D=O===`file`?k:`${w}${getDocExtension(e)}`,j=E!==void 0&&isDocInConflict(E),F=B.has(D);if(j||F){respondDocInConflict(S,new DocInConflictError({file:D}),`rename-path`);return}}if(k.toLowerCase()===j.toLowerCase()){errorResponse(S,400,`urn:ok:error:invalid-request`,`Case-only renames are not supported.`,{handler:`rename-path`});return}if(O===`file`&&probeAndRegisterSourceFileExtension(w,k),me&&(O===`file`?me.isExcluded(isSupportedDocFile(j)?j:`${j}${getDocExtension(k)}`):me.isDirExcluded(j))){errorResponse(S,400,`urn:ok:error:invalid-request`,`Destination ${O===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}let q=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,J;try{J=await Rt(k,j,O,q?{actor:q}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(S,409,`urn:ok:error:doc-already-exists`,Tt(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(J.renamed.length===0){successResponse(S,200,RenamePathSuccessSchema,{renamed:[],rewrittenDocs:[]},{handler:`rename-path`});return}let Y;switch(e.kind){case`agent`:{let t=e.summary.kind===`value`,S=t?e.summary:normalizeSummary(`Renamed ${k} → ${j}`),w=Vt(S);Y=t||!w.response?w.response:Ht(w.response);for(let t=0;t<J.renamed.length;t++){let{fromDocName:S,toDocName:E}=J.renamed[t];recordContributor(E,e.writerId,e.displayName,e.colorSeed,formatRenameSubject(S,E),e.actor,t===0?w.stored:void 0)}incrementAgentWriteCalls(),Ut(S,!t);for(let{toDocName:e}of J.renamed)it(e,`rename-path`);break}case`principal`:{let t=Vt(e.summary);Y=t.response;for(let S=0;S<J.renamed.length;S++){let{fromDocName:w,toDocName:E}=J.renamed[S];recordContributor(E,e.writerId,e.displayName,e.colorSeed,formatRenameSubject(w,E),e.actor,S===0?t.stored:void 0)}Ut(e.summary,!1);for(let{toDocName:e}of J.renamed)it(e,`rename-path`);break}case`anonymous`:log$3.debug({kind:O,fromPath:k,toPath:j,affectedDocs:J.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRenamePath: ${String(e.kind)}`)}if(renameAttributionCounter().add(1,{kind:`rename-${O}`,attribution_kind:e.kind}),H)try{await H()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(S,200,RenamePathSuccessSchema,{renamed:J.renamed,rewrittenDocs:J.rewrittenDocs,...Y?{summary:Y}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:w,error:E}=Et(e);errorResponse(S,t,w,E,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Is=withValidation(DeletePathRequestSchema,async(e,S,E)=>{try{zt(E);let{kind:e,path:O}=E;if(!isValidRelativeContentPath(O)){errorResponse(S,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let k=resolveContentEntryPath(w,e,O);if(!existsSync(k)){errorResponse(S,404,`urn:ok:error:doc-not-found`,`${e} does not exist.`,{handler:`delete-path`});return}let j=statSync(k);if(e===`file`&&!j.isFile()||e===`folder`&&!j.isDirectory()){errorResponse(S,400,`urn:ok:error:invalid-request`,`Target path is not a ${e}.`,{handler:`delete-path`});return}let F=e===`file`?[O]:listAffectedDocNames(D(),e,O),L=ce?.(),B=new Set(L?L.getConflicts().map(e=>e.file):[]);for(let w of F){let E=stripDocExtension(w),D=t.documents.get(E),O=e===`file`?w:`${E}${getDocExtension(E)}`,k=D!==void 0&&isDocInConflict(D),j=B.has(O);if(k||j){respondDocInConflict(S,new DocInConflictError({file:O}),`delete-path`);return}}if(await Dt(F),ye)for(let e of F)isSystemDoc(e)||isConfigDoc(e)||(ye.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));e===`file`?unlinkSync(k):(tracedRmSync(k,{recursive:!0,force:!1}),Pe(O));let H=D();if(H instanceof Map)for(let e of F)updateFileIndex({kind:`delete`,path:resolve(w,`${e}${getDocExtension(e)}`),docName:e},H);successResponse(S,200,DeletePathSuccessSchema,{deletedDocNames:F},{handler:`delete-path`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Rs=withValidation(TrashCleanupRequestSchema,async(e,t,S)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":S.kind,"ok.cleanup.path":normalizeFsPath(S.path),"ok.cleanup.path.role":classifyFsPath(S.path)}},async()=>{try{if(extractActorIdentity(S,fe).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:E}=S;if(!isValidRelativeContentPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let O=e===`folder`&&isReservedSyntheticFolderPath(E);if(e===`file`&&(isSystemDoc(E)||isConfigDoc(E))||O){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${E}' is a reserved document name.`,{handler:`trash-cleanup`});return}let k=D(),j=e===`file`?k.has(E)?[E]:[]:listAffectedDocNames(k,e,E);if(j.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Dt(j),ye)for(let e of j)isSystemDoc(e)||isConfigDoc(e)||(ye.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));let F=D();if(F instanceof Map)for(let e of j)updateFileIndex({kind:`delete`,path:resolve(w,`${e}${getDocExtension(e)}`),docName:e},F);e===`folder`&&Pe(E),ne?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:j},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),$s=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=D(),S=[];for(let[t,E]of e){let e=t,D,O=getDocExtension(t);try{let S=readFileSync(resolve(w,`${t}${O}`),`utf-8`);e=extractPageTitle(S,t),D=extractPageIcon(S)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}S.push({docName:t,title:e,docExt:O,size:E.size,modified:E.modified,icon:D})}S.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:S},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),ec=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!w){errorResponse(S,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(w)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(S,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:D(),docName:w}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function tc(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let S;try{S=await readUploadBody(e,de??w)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:E,tempPath:D,sha:O,byteLength:k,parentDocName:j}=S,F=()=>{if(existsSync(D))try{unlinkSync(D)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:j},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B}=L.value,{agentId:H,agentName:q}=zt(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(k===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(w),Y=resolveUploadDestDir(B,`./`,J);if(!isWithinContentDir(Y,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(Y,J)}catch(e){if(F(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$3.error({err:e,destDir:Y},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(Y,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){F();let S=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(S),S,uploadTitleFor(S),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(Y),S;try{S=realpathSync(J)}catch{S=J}if(!isWithinContentDir(e,S)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ee=await fileTypeFromFile(D),te=ee?.mime,ne=ee?.ext;if(!te){let e=readTempFileHead(D,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(te=`image/svg+xml`,ne=`svg`)}{let S=await findDuplicateAsset(Y,O,k);if(S){F();let E=relative(w,resolve(Y,S));log$3.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,dedup:!0,mime:te??null,size:k,destPath:E,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:S,path:E,deduped:!0},{handler:`upload-asset`});return}}let ae;if(!E||E===`upload`||GENERIC_PASTE_NAMES.test(E)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=E?extname(E).slice(1):``,S=ne??t??``;ae=S===``?`pasted-${e}`:`pasted-${e}.${S}`}else ae=sanitizeFilename(E);try{let S=linkTempToFinalWithCollisionRetry(D,Y,ae),E=relative(w,resolve(Y,S));log$3.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,dedup:!1,mime:te??null,size:k,destPath:E,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:S,path:E,deduped:!1},{handler:`upload-asset`})}catch(S){let w=S instanceof UploadWriteError?S.reason:`urn:ok:error:storage-error`;log$3.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,filename:ae,size:k,reason:w,httpStatus:uploadStatusFor(w),err:S},`[upload] write failed`),errorResponse(t,uploadStatusFor(w),w,uploadTitleFor(w),{handler:`upload-asset`,cause:S})}}let nc=`/api/local-op/clone`,rc=`/api/local-op/open`,ic=`/api/local-op/ok-init`,ac=600*1e3,oc=45e3,sc=`local-op-clone`,cc=withValidation(LocalOpCloneRequestSchema,lc,{handler:sc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:sc})});async function lc(e,t,S){let{url:w,dir:E,branch:D}=S;if(!isAllowedGitUrl(w)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:sc,cause:Error(`url=${w}`)});return}if(!isSafeLocalPath(E)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:sc,cause:Error(`dir=${E}`)});return}if(!we.tryAcquire(nc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:sc,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let O=createStreamingErrorWriter(t,sc),k=null,j=runCloneSubprocess({cliArgs:ue,url:w,dir:E,branch:D,timeoutMs:ac,onEvent:e=>{if(e.type===`complete`){k=e.dir;return}if(e.type===`error`){e.message&&log$3.warn({stderr:redactShareSubprocessStderr(e.message),url:w,dir:E},`[local-op/clone] clone failed`);let t=classifyCloneError(e.message??``);O(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(redactShareSubprocessStderr(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await j.done,k&&!t.writableEnded&&!t.destroyed){let e=await uc(k);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:k})}\n`):O(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?O(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$3.error({err:e,handler:sc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),we.release(nc)}})(),t.on(`close`,()=>{j.cancel()})}async function uc(e){let t=resolve(expandTilde(e)),S=getLocalDir(t),w=readUiLock(S);if(w&&w.port>0)return{port:w.port};let E=readServerLock(S),[D,...O]=ue,k=E&&E.port>0?`ui`:`start`,j=spawn(D,[...O,k],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),F=[];j.stderr?.on(`data`,e=>{F.push(e),log$3.warn({cwd:t,cliCmd:k,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let L=null;j.on(`exit`,e=>{L=e??-1}),j.unref();let B=Date.now()+45e3;for(;Date.now()<B;){await setTimeout$1(500);let e=readUiLock(S);if(e&&e.port>0)return{port:e.port};if(L!==null){let e=Buffer.concat(F).toString(`utf-8`).trim();return{error:`\`ok ${k}\` exited (code ${L})${e?` — ${e}`:``}`}}}let H=Buffer.concat(F).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${H?` — ${H}`:``}`}}let dc=`local-op-open`,fc=withValidation(LocalOpOpenRequestSchema,async(e,t,S)=>{let{dir:w}=S;if(!isSafeLocalPath(w)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`dir must be within the user home directory.`,{handler:dc,cause:Error(`dir=${w}`)});return}if(!we.tryAcquire(rc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A server-open operation is already in progress.`,{handler:dc,extraHeaders:{"Retry-After":`5`}});return}try{let e=await uc(w);`port`in e?successResponse(t,200,LocalOpOpenSuccessSchema,{port:e.port},{handler:dc}):errorResponse(t,504,`urn:ok:error:server-open-failed`,`Failed to open project server.`,{handler:dc,cause:Error(e.error)})}finally{we.release(rc)}},{handler:dc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:dc})}),pc=`local-op-ok-init`,mc=withValidation(LocalOpOkInitRequestSchema,async(e,t,S)=>{let{projectPath:w}=S;if(!isAbsolute(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:pc,cause:Error(`projectPath=${w}`)});return}let E;try{E=realpathSync(w)}catch(e){successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:pc});return}if(!isSafeLocalPath(E)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:pc,cause:Error(`projectPath=${w}`)});return}let D=resolveGitDirDetailed(E).kind;if(D!==`directory`&&D!==`linked`){console.warn(`[ok-init] action=init project=${basename(E)} result=not-a-git-worktree kind=${D}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${D}).`},{handler:pc});return}if(isProjectRoot(E)){console.warn(`[ok-init] action=init project=${basename(E)} result=already-initialized`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:E},{handler:pc});return}if(!we.tryAcquire(ic)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:pc,extraHeaders:{"Retry-After":`2`}});return}try{await withParentLock(async()=>{initContent(E)}),console.warn(`[ok-init] action=init project=${basename(E)} result=success`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:E},{handler:pc})}catch(e){let S=e instanceof Error?e.message:String(e);console.warn(`[ok-init] action=init project=${basename(E)} result=failed reason=${S}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`init-failed`,message:S},{handler:pc})}finally{we.release(ic)}},{handler:pc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:pc})}),hc=`/api/local-op/auth/login`,gc=`/api/local-op/auth/status`,_c=`/api/local-op/auth/repos`,vc=`/api/local-op/auth/signout`,yc=`/api/local-op/auth/pat`,bc=null,xc=`local-op-auth-login`,Sc=withValidation(LocalOpAuthHostRequestSchema,Cc,{handler:xc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:xc})});async function Cc(e,t,S){let w=S.host??`github.com`;if(!we.tryAcquire(hc)){let e=bc;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-login-slot-no-controller`,channel:`auth`,transport:`http`})),errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:xc,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),bc=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,xc),D=runDeviceFlowSubprocess({cliArgs:ue,host:w,timeoutMs:ac,onEvent:e=>{if(e.type===`error`){E(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});bc=D;let O=()=>{D.cancel(),bc===D&&(bc=null,we.release(hc))};t.on(`close`,O),D.done.finally(()=>{if(t.off(`close`,O),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}bc===D&&(bc=null,we.release(hc))})}let wc=`local-op-auth-status`,Tc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!we.tryAcquire(gc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:wc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=ue,E=[...S,`auth`,`status`,`--json`,`--host`,w],D=(await new Promise((t,S)=>{let w=spawn(e,E,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),D=!1,O=setTimeout(()=>{D=!0,w.kill(`SIGTERM`)},3e4),k=[];w.stdout.on(`data`,e=>k.push(e)),w.on(`close`,()=>{if(clearTimeout(O),D){S(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(k).toString(`utf-8`))}),w.on(`error`,e=>{clearTimeout(O),S(e)})})).split(`
2378
- `).map(e=>e.trim()).filter(Boolean),O=null;for(let e=D.length-1;e>=0;e--)try{O=JSON.parse(D[e]);break}catch{}O===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:wc}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,O,{handler:wc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:wc,cause:e})}finally{we.release(gc)}},{handler:wc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:wc})}),Ec=`local-op-auth-repos`,Dc=withValidation(LocalOpAuthHostRequestSchema,Oc,{handler:Ec,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Ec})});async function Oc(e,t,S){let w=S.host??`github.com`;if(!we.tryAcquire(_c)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Ec,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,Ec),[D,...O]=ue,k=[...O,`auth`,`repos`,`--json`,`--host`,w],j=!1,F=``,L=spawn(D,k,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),B=setTimeout(()=>{L.kill(`SIGTERM`)},ac);L.stdout.on(`data`,e=>{F+=e.toString(`utf-8`);let S=F.split(`
2379
- `);F=S.pop()??``;for(let e of S){if(!e.trim())continue;let S=null;try{S=JSON.parse(e)}catch{}if(S&&S.type===`error`){E(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof S.message==`string`?S.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),L.stderr.on(`data`,e=>{log$3.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),L.on(`close`,e=>{clearTimeout(B),j||(j=!0,e!==0&&!t.writableEnded&&E(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),we.release(_c))}),L.on(`error`,e=>{clearTimeout(B),j||(j=!0,t.writableEnded||(E(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),we.release(_c))}),t.on(`close`,()=>{j||(j=!0,clearTimeout(B),L.kill(`SIGTERM`),we.release(_c))})}let kc=`local-op-auth-signout`,Ac=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!we.tryAcquire(vc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:kc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=ue,E=[...S,`auth`,`signout`,`--host`,w];await new Promise((t,S)=>{let w=spawn(e,E,{stdio:`ignore`,env:{...process.env}}),D=setTimeout(()=>{w.kill(`SIGTERM`)},3e4);w.on(`close`,()=>{clearTimeout(D),t()}),w.on(`error`,e=>{clearTimeout(D),S(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:kc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:kc,cause:e})}finally{we.release(vc)}},{handler:kc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:kc})}),jc=`local-op-auth-pat`,Mc=withValidation(LocalOpAuthPatRequestSchema,async(e,t,S)=>{let{pat:w,host:E}=S,D=E??`github.com`;if(!we.tryAcquire(yc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth pat operation is already in progress.`,{handler:jc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=ue,E=[...S,`auth`,`pat`,`--json`,`--host`,D],O=(await new Promise((t,S)=>{let D=spawn(e,E,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),O=setTimeout(()=>{D.kill(`SIGTERM`)},3e4);D.stdin.write(`${w}\n`),D.stdin.end();let k=[];D.stdout.on(`data`,e=>k.push(e)),D.on(`close`,e=>{clearTimeout(O),e===0?t(Buffer.concat(k).toString(`utf-8`)):S(Error(`auth pat exited with code ${e}`))}),D.on(`error`,e=>{clearTimeout(O),S(e)})})).split(`
2380
- `).map(e=>e.trim()).filter(Boolean),k=null;for(let e=O.length-1;e>=0;e--)try{k=JSON.parse(O[e]);break}catch{}k===null?successResponse(t,200,LocalOpAuthPatSuccessSchema,{},{handler:jc}):successResponse(t,200,LocalOpAuthPatSuccessSchema,k,{handler:jc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth pat failed.`,{handler:jc,cause:e})}finally{we.release(yc)}},{handler:jc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:jc})}),Nc=`local-op-auth-identity`;async function Pc(e,t){if(checkLocalOpSecurity(e,t,{handler:Nc})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:Nc,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Nc});return}try{successResponse(t,200,LocalOpAuthIdentitySuccessSchema,{identity:await resolveGitIdentity(de)},{handler:Nc})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Identity resolution failed.`,{handler:Nc,cause:e})}}}let Fc=`/api/local-op/auth/set-identity`,Ic=`local-op-auth-set-identity`,Lc=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,S)=>{let w=S.name.trim(),E=S.email.trim();if(!de){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Ic});return}if(!we.tryAcquire(Fc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Ic,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(de,w,E),ce?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Ic})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Ic,cause:e})}finally{we.release(Fc)}},{handler:Ic,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Ic})});async function Rc(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let zc=withValidation(SyncTriggerRequestSchema,async(e,t,S)=>{let w=ce?.();if(!w){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let E=S.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:E},{handler:`sync-trigger`}),w.trigger(E)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ce?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Bc(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Vc=withValidation(SyncResolveConflictRequestSchema,async(e,t,S)=>{let w=ce?.();if(!w){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:E,strategy:D,content:O}=S;try{await w.resolveConflict(E,D,O),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ce?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Hc(e,S){if(!checkLocalOpSecurity(e,S,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(S,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(S,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=w.searchParams.get(`file`);if(!E){errorResponse(S,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(E.includes(`..`)||E.startsWith(`/`)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let D=stripDocExtension(E),O=t.documents.get(D)?.getMap(`lifecycle`).get(`status`)===`conflict`,k=ce?.(),j=k?k.getConflicts().some(e=>e.file===E):!1;if(!O&&!j){errorResponse(S,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:E}});return}let F=w.searchParams.get(`source`),L=esm_default({baseDir:de,timeout:{block:15e3}});async function B(e){try{return{present:!0,content:await L.raw([`show`,`:${e}:${E}`])}}catch(t){let S=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(S))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:E,detail:S,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,w,D]=await Promise.all([B(1),B(2),B(3)]),O=e.present?e.content:``,k=D.present?D.content:``,j=w.present&&D.present?`both-modified`:!w.present&&D.present?`delete-modify`:w.present&&!D.present?`modify-delete`:`both-modified`,L=w.present?w.content:``,H=null;if(F===`ytext`){let e=stripDocExtension(E),S=t.documents.get(e);if(S){let t=S.getMap(`lifecycle`).get(`status`);if(H=typeof t==`string`&&t.length>0?t:null,j!==`delete-modify`){let t=Ce?Ce(e):null;t!==null&&!ytextHasConflictMarkers(t)?L=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(S,200,SyncConflictContentSuccessSchema,{file:E,base:O,ours:L,theirs:k,kind:j,lifecycleStatus:H},{handler:`sync-conflict-content`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Uc(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let S=new URL(e.url??`/`,`http://localhost`),E=S.searchParams.get(`rootDir`)??void 0,D=S.searchParams.get(`packId`),O=coercePackId(D);if(D!==null&&D!==``&&O===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${D}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:w,rootDir:E,packId:O})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Wc=withValidation(SeedApplyRequestSchema,async(e,t,S)=>{let E=S.plan;if(!E||typeof E!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let D=E,O=S.packId,k=coercePackId(O);if(typeof O==`string`&&O.length>0&&k===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${O}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(D,{projectDir:w,packId:k})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function Gc(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let Kc=withValidation(InstallSkillRequestSchema,async(e,t,S)=>{if(S.out!==void 0&&!isSafeLocalPath(S.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...S.noOpen===void 0?{}:{noOpen:S.noOpen},...S.out===void 0?{}:{out:S.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function qc(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,ze.probeAll)}catch(e){t.headersSent||(log$3.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}async function Jc(e,t){if(!checkLocalOpSecurity(e,t,{handler:`sync-abort-merge`}))return;if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-abort-merge`,extraHeaders:{Allow:`POST`}});return}let S=ce?.();if(!S){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-abort-merge`});return}try{await S.abortMerge(),successResponse(t,200,SyncAbortMergeSuccessSchema,{},{handler:`sync-abort-merge`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to abort merge.`,{handler:`sync-abort-merge`,cause:e})}}let Yc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!te){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:te.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Xc(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!te){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let w;try{w=decodeURIComponent(S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=te.getDocsForTagWithMatches(w).map(({docName:e,matchingTags:t})=>({docName:e,title:Ve(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:w,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function Zc(e,t,S=`path`,E=`folder-config`){let D=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(D.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${S}: must be project-root-relative.`,{handler:E}),null;let O=resolve(w),k=D===``?O:resolve(O,D);return k!==O&&!k.startsWith(`${O}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:E}),null):{folderRel:D,resolvedContentDir:O}}let Qc=/^[A-Za-z0-9_-]+$/;function $c(e,t,S=`template`){return!e||!Qc.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:S}),!1):!0}function nl(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[S,w]of Object.entries(e))w!==void 0&&(t[S]=w);return t}function il(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return{patch:t,badField:null};for(let[S,w]of Object.entries(e)){if(w===void 0)continue;if(w===null){t[S]=null;continue}let e=DeclarationSchema.safeParse(w);if(!e.success)return{patch:null,badField:S};t[S]=e.data}return{patch:t,badField:null}}async function al(e,t){if(e.method===`GET`)return cl(e,t);if(e.method===`PUT`)return ll(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let cl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=Zc(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!S)return;let w=await enrichDirectory(S.folderRel,{projectDir:S.resolvedContentDir}),E=resolve(S.resolvedContentDir,S.folderRel,`.ok`),D=resolve(E,`frontmatter.yml`),O=null;if(existsSync(D))try{let e=(0,import_dist$1.parse)(await readFile$1(D,`utf-8`));O=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${D}: ${t}`),O=null}let k=resolveNestedFrontmatterWithSources(S.resolvedContentDir,S.folderRel),j=resolve(E,`schema.yml`),F=null;if(existsSync(j))try{let e=(0,import_dist$1.parse)(await readFile$1(j,`utf-8`)),t=FolderSchemaSchema.safeParse(e);t.success?F=t.data.declarations:(console.warn(`[ok-folder-schema] invalid shape at ${j}: ${t.error.message}`),F=null)}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[ok-folder-schema] malformed YAML in ${j}: ${t}`),F=null}let L=Object.keys(k.declarations).length>0;successResponse(t,200,FolderConfigGetSuccessSchema,{folder:w,frontmatter_local:O,...Object.keys(k.sources).length>0?{frontmatter_sources:k.sources}:{},...L?{schema_declarations:k.declarations,schema_sources:k.declarationSources}:{},schema_local:F},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),ll=withValidation(FolderConfigPutRequestSchema,async(e,t,S)=>{try{let e=Zc(S.path,t,`path`,`folder-config-put`);if(!e)return;let w=e.folderRel===``?`**`:`${e.folderRel}/**`,E;if(S.declarations!==void 0){let e=il(S.declarations);if(e.patch===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid declaration for field "${e.badField}": must be { type: text|number|boolean|date|list } or null.`,{handler:`folder-config-put`,detail:`INVALID_DECLARATION`});return}E=e.patch}let D=[];if(S.frontmatter!==void 0){let E=applyNestedFolderRulesUpsert({projectDir:e.resolvedContentDir,rules:[{match:w,frontmatter:nl(S.frontmatter)}]});if(!E.ok){let e=E.error.code===`WRITE_ERROR`||E.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:`Invalid folder config request.`,{handler:`folder-config-put`,detail:E.error.code,cause:Error(E.error.message)});return}D.push(...E.applied)}if(E!==void 0&&Object.keys(E).length>0){let S=applyNestedFolderSchemaUpsert({projectDir:e.resolvedContentDir,rules:[{match:w,declarations:E}]});if(!S.ok){let e=S.error.code===`WRITE_ERROR`||S.error.code===`BAD_PROJECT_DIR`?500:400,w=e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,E=e===500?`Failed to write folder schema.`:`Invalid folder schema request.`,O=D.length>0?{partiallyApplied:D}:void 0;errorResponse(t,e,w,E,{handler:`folder-config-put`,detail:S.error.code,cause:Error(S.error.message),...O?{extensions:O}:{}});return}D.push(...S.applied)}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:D},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function ul(e,S,w,E){if(!S)return!1;let D=e===``?`.ok/templates/${S}`:`${e.replace(/\/$/,``)}/.ok/templates/${S}`,O=t.documents.get(D);return O&&isDocInConflict(O)?(respondDocInConflict(E,new DocInConflictError({file:`${D}.md`}),w),!0):!1}async function dl(e,t){if(e.method===`GET`)return ml(e,t);if(e.method===`PUT`)return hl(e,t);if(e.method===`DELETE`)return gl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let fl=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,pl=e=>{let t=e.match(fl),S={},w=e;if(t){try{let e=(0,import_dist$1.parse)(t[1]??``);e&&typeof e==`object`&&!Array.isArray(e)&&(S=e)}catch{}w=e.slice(t[0].length)}return{frontmatter:S,body:w}},ml=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!$c(w,t,`template-get`))return;let E=Zc(S.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!E)return;let{folderRel:D,resolvedContentDir:O}=E,k=D===``?[]:D.split(`/`),j=null,F=null,L=null;for(let e=k.length;e>=0;e--){let t=e===0?``:k.slice(0,e).join(`/`),S=t===``?O:resolve(O,t);if(S!==O&&!S.startsWith(`${O}${sep}`))continue;let E=resolve(S,`.ok`,`templates`,`${w}.md`);if(existsSync(E)){j=E,F=t,L=e===k.length?`local`:`inherited`;break}}if(!j||F===null||L===null){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${w}" not found for folder "${D||`.`}". Walked leaf → root.`});return}let{frontmatter:B,body:H}=pl(await readFile$1(j,`utf-8`)),q=relative(O,j).split(/[\\/]/).filter(Boolean).join(`/`);successResponse(t,200,TemplateGetSuccessSchema,{template:{name:w,folder:F,scope:L,path:q,frontmatter:B,body:H}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),hl=withValidation(TemplatePutRequestSchema,async(e,t,S)=>{try{let e=S.name;if(!$c(e,t,`template-put`))return;let w=Zc(S.folder,t,`folder`,`template-put`);if(!w||ul(w.folderRel,e,`template-put`,t))return;let E=applyTemplateWrite({projectDir:w.resolvedContentDir,folder:w.folderRel,name:e,body:typeof S.body==`string`?S.body:``,frontmatter:nl(S.frontmatter)});if(!E.ok){let e=E.error.code===`WRITE_ERROR`||E.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write template.`:`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}successResponse(t,200,TemplatePutSuccessSchema,{path:E.path,created:E.created,warnings:E.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),gl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!$c(w,t,`template-delete`))return;let E=Zc(S.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!E||ul(E.folderRel,w,`template-delete`,t))return;let D=applyTemplateDelete({projectDir:E.resolvedContentDir,folder:E.folderRel,name:w});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0});function _l(e){let t=new Map;for(let S of e){let e=S.path.split(`/`).filter(Boolean);e.pop();for(let w=1;w<=e.length;w++){let E=e.slice(0,w).join(`/`);t.set(E,Math.max(t.get(E)??0,S.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function vl(e,t){let S=t.trim().toLowerCase();if(!S||!e)return;let w=e.toLowerCase().indexOf(S);if(w<0)return;let E=Math.max(0,w-80),D=Math.min(e.length,w+S.length+120),O=E>0?`…`:``,k=D<e.length?`…`:``;return`${O}${e.slice(E,D).replace(/\s+/g,` `).trim()}${k}`}function yl(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function xl(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let S=t.filter(e=>e===`page`||e===`folder`||e===`content`);return S.length>0?S:void 0}async function Cl(){let e=[];for(let[t,S]of D()){if(isSystemDoc(t)||isConfigDoc(t))continue;let w=``,E=t;try{w=await readFile$1(S.canonicalPath,`utf-8`),E=extractPageTitle(w,t)}catch(e){console.warn(`[search] Failed to index ${t}:`,e)}e.push(createWorkspaceSearchDocument({kind:`page`,path:t,title:E,content:w,modifiedTs:Date.parse(S.modified)}))}return[...e,..._l(e)]}function Tl(){return[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}${t.modified}${t.size}${t.canonicalPath}${t.inode}${t.aliases.join(`,`)}`).join(``)}async function El(){let e=`${w}${de??``}`,t=Tl(),S=workspaceSearchCaches.get(e);if(S?.fingerprint===t&&S.corpus)return S.corpus;if(S?.fingerprint===t&&S.pending)return S.pending;let E=Cl().then(e=>createWorkspaceSearchCorpus(e));workspaceSearchCaches.set(e,{fingerprint:t,pending:E});try{let S=await E;return workspaceSearchCaches.get(e)?.pending===E&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:S}),S}catch(t){throw workspaceSearchCaches.get(e)?.pending===E&&workspaceSearchCaches.delete(e),t}}function Dl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{El().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}Dl();async function Ol(e,t){if(e.method===`GET`)return kl(e,t);if(e.method===`POST`)return jl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let kl=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`limit`),E=S.searchParams.get(`query`)??``,D=yl(S.searchParams.get(`intent`)),O=xl(S.searchParams.get(`scope`)??S.searchParams.get(`scopes`)),k=w===null?void 0:Number(w);if(E.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:E,intent:D,results:searchWorkspaceCorpus(await El(),E,{intent:D,scopes:O,limit:k}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?vl(e.document.content,E):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),jl=withValidation(SearchRequestSchema,async(e,t,S)=>{let w=typeof S.query==`string`?S.query:``,E=yl(S.intent),D=xl(S.scopes??S.scope),O=typeof S.limit==`number`?S.limit:void 0;if(w.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:w,intent:E,results:searchWorkspaceCorpus(await El(),w,{intent:E,scopes:D,limit:O}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?vl(e.document.content,w):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),Ml=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function Pl(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$3.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function Fl(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$3.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let Il=withValidation(ShareConstructUrlRequestSchema,async(e,t,S)=>{try{if(!de){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!isValidShareDocPath(S.docPath)){emitShareConstructUrlLog(`invalid-path`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=readGitHeadBranch(de);if(e===null){if(readOriginGitHubRepo(de).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=readOriginGitHubRepo(de);if(w.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(w.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(de,e)){emitShareConstructUrlLog(`branch-not-on-origin`,!1),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let E=buildGitHubBlobUrl(w.owner,w.repo,e,S.docPath),D=`${SHARE_BASE_URL}${encodeShareUrl(E)}`;emitShareConstructUrlLog(`ok`,!0),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:D,blobUrl:E,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}),Ll=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!de){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`branch`),E=S.searchParams.get(`path`);if(!isValidBranchName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoDocPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(de,w,E),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),Rl=withValidation(CheckoutRequestSchema,async(e,t,S)=>{if(extractActorIdentity(S,fe).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!de){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(de,S.branch)),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function zl(e){let[t,...S]=ue,w=[...S,...e];return await new Promise((e,S)=>{let E=spawn(t,w,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),D=!1,O=setTimeout(()=>{D=!0,E.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),k=[],j=[];E.stdout.on(`data`,e=>k.push(e)),E.stderr.on(`data`,e=>j.push(e)),E.on(`close`,t=>{if(clearTimeout(O),D){S(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let w=Buffer.concat(k).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(j).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:w,code:t})}),E.on(`error`,e=>{clearTimeout(O),S(e)})})}let Bl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!we.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await zl([`share`,`owners`,`--json`]),S=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,S.ok?`ok`:S.error,S.ok?{count:S.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,S,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{we.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),Vl=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`owner`)??``,E=S.searchParams.get(`name`)??``;if(!isValidShareOwnerName(w)||!isValidShareRepoName(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!we.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await zl([`share`,`name-check`,`--owner`,w,`--name`,E,`--json`]),S=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,S.ok?`ok`:S.error,S.ok?{available:S.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,S,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{we.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),Hl=withValidation(SharePublishRequestSchema,async(e,t,S)=>{if(!de){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(S.owner)||!isValidShareRepoName(S.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!we.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,S.owner,`--name`,S.name,`--visibility`,S.visibility,`--project-dir`,de,`--json`];S.description!==void 0&&S.description.length>0&&e.push(`--description`,S.description);let{stdout:w}=await zl(e),E=parsePublishEvent(pickTerminalJsonLine(w));emitSharePublishLog(`publish-create`,E.ok?`ok`:E.error),successResponse(t,200,SharePublishResponseSchema,E,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{we.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),Ul={"/api/asset":ka,"/api/asset-text":xs,"/api/document":jr,"/api/documents":Mr,"/api/backlinks":Fr,"/api/backlink-counts":Ir,"/api/forward-links":Lr,"/api/link-graph":zr,"/api/dead-links":Hr,"/api/orphans":Br,"/api/hubs":Vr,"/api/tags":Yc,"/api/pages":$s,"/api/folder-config":al,"/api/template":dl,"/api/search":Ol,"/api/suggest-links":ec,"/api/page-headings":Ns,"/api/create-page":Os,"/api/create-folder":ks,"/api/duplicate-path":As,"/api/rename-path":Ps,"/api/delete-path":Is,"/api/trash/cleanup":Rs,"/api/upload":tc,"/api/agent-write":Wt,"/api/agent-write-md":Kt,"/api/frontmatter-patch":$t,"/api/agent-patch":Ur,"/api/agent-undo":Wr,"/api/agent-activity":Gr,"/api/agent-burst-diff":Kr,"/api/save-version":Xr,"/api/history":Zr,"/api/diff":ji,"/api/rollback":Hi,"/api/metrics/reconciliation":Ui,"/api/metrics/parse-health":Gi,"/api/metrics/agent-presence":Xi,"/api/server-info":Ki,"/api/share/construct-url":Il,"/api/git/branch-info":Ll,"/api/git/checkout":Rl,"/api/share/publish/owners":Bl,"/api/share/publish/name-check":Vl,"/api/share/publish":Hl,"/api/principal":Yi,"/api/rescue":Ts,"/api/workspace":Zi,"/api/sync/status":Rc,"/api/sync/trigger":zc,"/api/sync/conflicts":Bc,"/api/sync/conflict-content":Hc,"/api/sync/resolve-conflict":Vc,"/api/sync/abort-merge":Jc,"/api/local-op/clone":cc,"/api/local-op/open":fc,"/api/local-op/ok-init":mc,"/api/local-op/auth/login":Sc,"/api/local-op/auth/status":Tc,"/api/local-op/auth/repos":Dc,"/api/local-op/auth/signout":Ac,"/api/local-op/auth/pat":Mc,"/api/local-op/auth/identity":Pc,"/api/local-op/auth/set-identity":Lc,"/api/installed-agents":qc,"/api/spawn-cursor":Fl,"/api/handoff":Pl,"/api/install-skill":Kc,"/api/skill/install-state":Ml,"/api/seed/plan":Uc,"/api/seed/apply":Wc,"/api/seed/packs":Gc};F&&(Ul[`/api/test-reset`]=qr,Ul[`/api/test-rescan-backlinks`]=Jr,Ul[`/api/test-rescan-files`]=Yr);let Wl=new Set([`/api/upload`,`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/agent-write`,`/api/agent-write-md`,`/api/frontmatter-patch`,`/api/agent-patch`,`/api/agent-undo`,`/api/save-version`,`/api/rollback`,`/api/sync/trigger`,`/api/sync/resolve-conflict`,`/api/sync/abort-merge`,`/api/git/checkout`,`/api/test-reset`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`,`/api/install-skill`,`/api/folder-config`,`/api/template`,`/api/seed/apply`]),Gl=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let S=e.url?.split(`?`)[0];if(!S)return;if(S.startsWith(`/api/`)){let S=e.headers.origin;if(S!==void 0&&!isAllowedApiOrigin(S)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(S!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,S),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(Wl.has(S)||Gl.some(e=>S.startsWith(e))){let S=e.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(!S.startsWith(`/api/`))return;let w=propagation.extract(context.active(),e.headers),E=e.method??`GET`,D=S;S.startsWith(`/api/rescue/`)?D=`/api/rescue/:docName`:S.startsWith(`/api/history/`)?D=`/api/history/:sha`:S.startsWith(`/api/tags/`)?D=`/api/tags/:name`:Ul[S]||(D=`/api/*`);let O=getTracer(),k=Date.now();await context.with(w,()=>O.startActiveSpan(`HTTP ${E} ${D}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:E,[ATTR_HTTP_ROUTE]:D,[ATTR_URL_PATH]:S,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async w=>{try{let D=Ul[S],O=!1;if(D)O=!0,await D(e,t);else if(S.startsWith(`/api/rescue/`)){let w=decodeURIComponent(S.slice(12));w&&(O=!0,await Ds(e,t,w))}else if(S.startsWith(`/api/history/`)){let w=decodeURIComponent(S.slice(13));w&&(O=!0,await Qr(e,t,w))}else if(S.startsWith(`/api/tags/`)){let w=S.slice(10);w&&(O=!0,await Xc(e,t,w))}O||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${E} ${S}`});let k=t.statusCode;w.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,k),k>=500&&w.setStatus({code:SpanStatusCode.ERROR,message:`status ${k}`})}catch(e){throw w.recordException(e),w.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:D,cause:e}),e}finally{w.end();let e=(Date.now()-k)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:E,[ATTR_HTTP_ROUTE]:D,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function isWithinDir(e,t){return e===t?!0:e.startsWith(`${t}${sep}`)}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedBasenameIndex(e){let t=e.contentDir,S=new Set;function w(E){let D;try{D=readdirSync(E,{withFileTypes:!0})}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`read-failed`,S,E);return}for(let O of D){let D=join(E,O.name),k=relative(t,D);if(k.startsWith(`..`)||e.contentFilter?.isDirExcluded(k)&&O.isDirectory())continue;let j;try{j=lstatSync(D)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`lstat-failed`,S,D);continue}if(j.isSymbolicLink()){let E;try{E=realpathSync(D)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`realpath-failed`,S,D);continue}if(!isWithinDir(E,t)){e.onSkip?.(`symlink-escape`,void 0,D);continue}let O;try{O=statSync(E)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,S,E);continue}if(S.has(O.ino))continue;S.add(O.ino),O.isDirectory()?w(E):O.isFile()&&isSupportedAssetFile(D,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(k)&&e.basenameIndex.add(k);continue}if(j.isDirectory()){if(S.has(j.ino))continue;S.add(j.ino),w(D);continue}j.isFile()&&isSupportedAssetFile(D,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(k)&&e.basenameIndex.add(k)}}w(t)}const HocuspocusAuthTokenSchema=object$1({principalId:string$2().optional(),tabSessionId:string$2().optional(),expectedServerInstanceId:string$2().optional(),expectedBranch:string$2().optional()}).loose(),HOCUSPOCUS_AUTH_REJECTION_REASONS=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`];function isHocuspocusAuthRejectionReason(e){return HOCUSPOCUS_AUTH_REJECTION_REASONS.includes(e)}const WIRE_PAYLOAD_SEPARATOR=`:`;function formatAuthRejectionWire(e,t){return typeof t!=`string`||t.length===0?e:`${e}${WIRE_PAYLOAD_SEPARATOR}${t}`}function parseAuthRejectionWire(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(WIRE_PAYLOAD_SEPARATOR),S=t===-1?e:e.slice(0,t);if(!isHocuspocusAuthRejectionReason(S))return{kind:null,payload:void 0};if(t===-1)return{kind:S,payload:void 0};let w=e.slice(t+1);return{kind:S,payload:w.length>0?w:void 0}}var HocuspocusAuthRejection=class extends Error{kind;payload;reason;constructor(e,t,S){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof S==`string`&&S.length>0?S:void 0,this.reason=formatAuthRejectionWire(e,this.payload)}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let S=HocuspocusAuthTokenSchema.safeParse(t);return S.success?S.data:void 0}const log$2=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$2.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$2.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$2.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,S,w=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&S===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:E}=await import(`./git-handle-BJwB5EBp-D5YTDzvd.mjs`),D=E(this.projectDir,{credentialArgs:w});switch(t){case`mine`:await D.git.raw([`checkout`,`--ours`,`--`,e]),await D.git.raw([`add`,`--`,e]);break;case`theirs`:await D.git.raw([`checkout`,`--theirs`,`--`,e]),await D.git.raw([`add`,`--`,e]);break;case`content`:{if(S===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),w=resolve(t,e);if(w!==t&&!w.startsWith(`${t}/`))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(w,S,`utf-8`),await D.git.raw([`add`,`--`,e]);break}case`delete`:await D.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await D.git.raw([`commit`,`--no-edit`]),log$2.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let S=new Date().toISOString(),w=!1;try{let e=(await D.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
2374
+ `)){if(E(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),E=getHeadingSlug(e,w);E&&S.push({level:t[1].length,text:e,slug:E})}}return S}function isSafeDocName(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function createApiExtension(e){let{hocuspocus:t,sessionManager:S,contentDir:w,serverInstanceId:E,getFileIndex:D,getFolderIndex:O,onReferencedAssetsCacheInvalidator:k,getAliasMap:j,rescanFiles:F,enableTestRoutes:L=!1,shadowRef:B,flushGitCommit:H,flushContributors:q,getCurrentBranch:J,getDiskAckSVs:Y,contentRoot:ee,backlinkIndex:te,tagIndex:ne,signalChannel:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se,onAgentWrite:ce,getSyncEngine:ue,localOpCliArgs:de=[`open-knowledge`],projectDir:fe,getPrincipal:me,contentFilter:ge,installedAgentsProbe:_e,forceUnloadDocument:ve,ready:ye,recentlyRemovedDocs:Ce,serializeDoc:we}=e,Te=createConcurrencyGuard(),De=null;function je(){let e=O?.();return e instanceof Map?e:null}function Me(e){let t=je();if(t)try{upsertFolderIndexEntry(t,w,e,statSync(e),e)}catch(t){console.warn(`[api-extension] folder index stat failed for ${e}:`,t)}}function Pe(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)Me(resolve(w,t.slice(0,e).join(`/`)))}function Ie(e){let t=je();t&&removeFolderIndexEntries(t,e)}function Re(e,t){let S=je();if(!S)return;let E=[];for(let[w,D]of S.entries()){if(w!==e&&!w.startsWith(`${e}/`))continue;S.delete(w);let O=w.slice(e.length);E.push([`${t}${O}`,D])}if(E.length===0){let e=resolveContentEntryPath(w,`folder`,t);existsSync(e)&&Me(e);return}for(let[e,t]of E)S.set(e,{...t,modified:new Date().toISOString(),canonicalPath:resolve(w,e)})}function ze(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
2375
+ `)}function Be(){De=null}k?.(Be);let Ve=createInstalledAgentsProbe({probe:_e??createOsProbe(process.platform)});function Ue(e){if(!isSafeDocName(e))return null;let t=resolve(w),S=resolve(t,`${e}${getDocExtension(e)}`);return!S.startsWith(`${t}/`)&&S!==t?null:S}function We(e){let t=Ue(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Ge(e,t){return t.has(e)?We(e):e}let Ke={cluster:void 0,category:void 0,tags:void 0};function Xe(e){try{let S=t.documents.get(e);if(S){let e=readFmMap(S.getText(`source`).toString());if(Object.keys(e).length>0){let t=typeof e.cluster==`string`?e.cluster:void 0,S=typeof e.category==`string`?e.category:void 0,w;return Array.isArray(e.tags)?w=e.tags.length>0?e.tags:void 0:typeof e.tags==`string`&&e.tags&&(w=[e.tags]),{cluster:t,category:S,tags:w}}}}catch{}try{let t=Ue(e);if(!t||!existsSync(t))return Ke;let{frontmatter:S}=stripFrontmatter(readFileSync(t,`utf-8`));return S?parseFrontmatterMetadata(S):Ke}catch{return Ke}}function $e(e,t){return t.has(e)?Xe(e):Ke}function nt(e){if(te)try{if(te.getBacklinks(e).length>0)return;let t=performance.now(),S=findHubCandidates(e,D()),w=performance.now()-t;return w>5&&log$3.debug({docName:e,elapsedMs:w,candidateCount:S.length},`[orphan-hint] findHubCandidates slow`),S.length===0?void 0:[{type:`orphan`,parentCandidates:S,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): ${S.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function rt(e){return j?.().get(e)??e}function it(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function at(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function st(e,S){let w=`onStoreDocument-${e}`;(t.debouncer.isDebounced(w)?t.debouncer.executeNow(w):Promise.resolve()).then(()=>H?.()).catch(e=>{log$3.warn({err:e},`[${S}] post-write flush failed`)})}function vt(){let e=new Set;for(let[t,S]of D()){e.add(t);for(let t of S.aliases)e.add(t)}return e}function Tt(){let e=Promise.resolve();return async function(t){let S=e,w=()=>{};e=new Promise(e=>{w=e}),await S;try{return await t()}finally{w()}}}let Et=Tt(),Dt=e=>e.endsWith(`.`)?e:`${e}.`;function jt(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:Dt(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:Dt(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:Dt(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Dt(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:Dt(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:Dt(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:Dt(e.message)}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}:{status:500,type:`urn:ok:error:internal-server-error`,error:`Failed to rename document.`}}async function Mt(e){let w=new Map;for(let S of e){let e=t.documents.get(S);e&&w.set(S,e.getText(`source`).toString())}for(let t of e)await S.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let S of e){let e=t.documents.get(S);deleteReconciledBase(S),e&&(t.closeConnections(S),await(ve??t.unloadDocument.bind(t))(e))}return w}function Ft(e,t){for(let{fromDocName:S,toDocName:E}of e){let e=safeContentPath(E,w),D=t.get(S);typeof D==`string`&&tracedWriteFileSync(e,D,`utf-8`);let O=typeof D==`string`?D:existsSync(e)?readFileSync(e,`utf-8`):null;typeof O==`string`&&registerWrite(e,contentHash(O))}}function It(e,t){return e.map(e=>{let S=t.get(e);if(typeof S==`string`)return{docName:e,content:S};let E=safeContentPath(e,w);if(!existsSync(E))throw new ManagedRenameSnapshotMissingError(e);return{docName:e,content:readFileSync(E,`utf-8`)}})}function Lt(e){let S=t.documents.get(e);if(S)return S.getText(`source`).toString();let E=resolveContentEntryPath(w,`file`,e);return existsSync(E)?readFileSync(E,`utf-8`):null}function Rt(e,t){let S=resolveContentEntryPath(w,`file`,e);tracedMkdirSync(dirname(S),{recursive:!0}),tracedWriteFileSync(S,t,`utf-8`),registerWrite(S,contentHash(t)),setReconciledBase(e,t);let E=D();E instanceof Map&&updateFileIndex({kind:`update`,path:S,docName:e,content:t},E)}function zt(e,S,w=[]){let E=t.documents.get(e);if(!E)throw Error(`Document is not loaded: ${e}`);let D={markdown:``,rewrites:0};return E.transact(()=>{D=Vt(E.getText(`source`).toString(),e,S.get(e)??e,S,w),D.rewrites!==0&&composeAndWriteRawBody(E,D.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),D}function Bt(e,t,S){let w=e,E=0;for(let{fromPath:e,toPath:D}of S){let S=rewriteAssetReferencesForRename(w,t,e,D);w=S.markdown,E+=S.rewrites}return{markdown:w,rewrites:E}}function Vt(e,t,S,w,E){let D=applyRenameMap(e,t,w),O=Bt(D.markdown,S,E);return{markdown:O.markdown,rewrites:O.markdown===e?0:D.rewrites+O.rewrites}}function Ht(e,S){let w=t.documents.get(e);if(!w)throw Error(`Document is not loaded: ${e}`);let E={markdown:``,rewrites:0};return w.transact(()=>{E=Bt(w.getText(`source`).toString(),e,S),E.rewrites!==0&&composeAndWriteRawBody(w,E.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),E}function Ut(e){let t=[];if(e.length===0)return t;let S=[...D().keys()].sort((e,t)=>e.localeCompare(t));for(let w of S){let S=Lt(w);if(typeof S!=`string`)continue;let E=Bt(S,w,e);E.rewrites!==0&&t.push({docName:w,markdown:E.markdown,rewrites:E.rewrites})}return t}function Wt(e){let S=ue?.(),w=new Set(S?S.getConflicts().map(e=>e.file):[]);for(let S of e){let e=t.documents.get(S),E=`${S}${getDocExtension(S)}`,D=e!==void 0&&isDocInConflict(e),O=w.has(E);if(D||O)throw new DocInConflictError({file:E})}}function Kt(e,S){let w=[];for(let E of e){let e=t.documents.get(E.docName)?Ht(E.docName,S):E;e.rewrites!==0&&(Rt(E.docName,e.markdown),te?.updateDocumentFromMarkdown(E.docName,e.markdown),w.push({docName:E.docName,rewrites:e.rewrites}))}return w}function $t(e){if(extname(e))return{path:e,ambiguous:!1};let t=e.lastIndexOf(`/`),S=t===-1?``:e.slice(0,t),E=t===-1?e:e.slice(t+1),D=S?resolveContentEntryPath(w,`folder`,S):w,O;try{O=readdirSync(D,{withFileTypes:!0})}catch(t){let S=t.code;if(S===`ENOENT`||S===`ENOTDIR`)return{path:e,ambiguous:!1};throw t}let k=O.filter(e=>e.isFile()&&e.name.startsWith(`${E}.`)).map(e=>S?`${S}/${e.name}`:e.name).filter(e=>isSupportedAssetFile(e,ASSET_EXTENSIONS));return k.length===1?{path:k[0],ambiguous:!1}:{path:e,ambiguous:k.length>1}}function en(e,t,S){let E=[];function D(e){for(let O of readdirSync(e,{withFileTypes:!0})){let k=resolve(e,O.name),j=relative(w,k).split(sep).join(`/`);if(!isReservedProjectStatePath(j)){if(O.isDirectory()){if(ge?.isDirExcluded(j))continue;D(k);continue}!O.isFile()||isSupportedDocFile(j)||ge?.isExcluded(j)||(j===t?E.push({fromPath:j,toPath:S}):j.startsWith(`${t}/`)&&E.push({fromPath:j,toPath:`${S}${j.slice(t.length)}`}))}}}return D(e),E.sort((e,t)=>e.fromPath.localeCompare(t.fromPath)),E}async function jr(e,t){return Et(async()=>withSpan(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async S=>{if(!te)throw new BacklinkIndexRequiredError;let E=extname(t)?t:`${t}${extname(e)}`;if(isSupportedDocFile(e)||isSupportedDocFile(E))throw new ManagedRenameInvalidRequestError(`Asset operations do not support markdown documents.`);if(!isSupportedAssetFile(e,ASSET_EXTENSIONS)||!isSupportedAssetFile(E,ASSET_EXTENSIONS))throw new ManagedRenameInvalidRequestError(`Asset operations require supported asset extensions.`);if(isReservedProjectStatePath(e)||isReservedProjectStatePath(E))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(ge?.isPathIgnored(E))throw new ManagedRenameInvalidRequestError(`Destination asset is excluded by the project content config.`);let D=resolveContentEntryPath(w,`folder`,e),O=resolveContentEntryPath(w,`folder`,E);if(D===O)return{renamedAssets:[],rewrittenDocs:[]};if(!existsSync(D))throw new ManagedRenameSourceNotFoundError(`asset`,`Asset does not exist.`);if(existsSync(O))throw new ManagedRenameDestinationExistsError;if(!statSync(D).isFile())throw new ManagedRenameSourceTypeMismatchError(`asset`,`Source path is not an asset file.`);let k=[{fromPath:e,toPath:E}],j=Ut(k);S.setAttribute(`rename.rewrite_candidates`,j.length),Wt(j.map(e=>e.docName)),await renameTrackedPathInGit(fe,D,O)||(tracedMkdirSync(dirname(O),{recursive:!0}),tracedRenameSync(D,O));let F=Kt(j,k);return te.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist asset rename cache for ${e} -> ${E}:`,t)}),ae?.(`files`),F.length>0&&(ae?.(`backlinks`),ae?.(`graph`)),F.sort((e,t)=>e.docName.localeCompare(t.docName)),S.setAttribute(`rename.rewrite_count`,F.length),{renamedAssets:k,rewrittenDocs:F}}))}async function Mr(e,S,E,O){return Et(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":E}},async k=>{if(!te)throw new BacklinkIndexRequiredError;let j=resolveContentEntryPath(w,E,e),F=resolveContentEntryPath(w,E,S);if(j===F)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!existsSync(j))throw new ManagedRenameSourceNotFoundError(E);if(existsSync(F))throw new ManagedRenameDestinationExistsError;let L=statSync(j);if(E===`file`&&!L.isFile()||E===`folder`&&!L.isDirectory())throw new ManagedRenameSourceTypeMismatchError(E);let H=E===`folder`?en(j,e,S):[];k.setAttribute(`rename.affected_assets`,H.length);let q=(E===`file`?[stripDocExtension(e)]:listAffectedDocNames(D(),E,e)).map(t=>({from:t,to:E===`file`?stripDocExtension(S):remapDocNameForRename(t,E,e,S)}));if(k.setAttribute(`rename.affected_docs`,q.length),q.length===0){let t=Ut(H);Wt(t.map(e=>e.docName));let w=[];return E===`folder`&&(await renameTrackedPathInGit(fe,j,F)||(tracedMkdirSync(dirname(F),{recursive:!0}),tracedRenameSync(j,F)),Re(e,S),ae?.(`files`)),w.push(...Kt(t,H)),w.length>0&&(te.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${S}:`,t)}),ae?.(`backlinks`),ae?.(`graph`)),w.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:[],renamedAssets:H,rewrittenDocs:w}}let Y=buildRenameMap(q),ee=q.map(({from:e,to:t})=>({fromDocName:e,toDocName:t})),ne=new Set;for(let{from:e}of q)for(let t of te.getBacklinks(e))Y.has(t.source)||ne.add(t.source);let oe=[...ne].sort((e,t)=>e.localeCompare(t)),se=new Map,ce=new Set,ue=new Set,de=[];for(let e of[...Y.keys(),...oe]){if(se.has(e))continue;if(!Y.has(e)&&!existsSync(resolveContentEntryPath(w,`file`,e))){de.push(e);continue}let t=Lt(e);typeof t==`string`?(se.set(e,t),Y.has(e)||ce.add(e)):Y.has(e)||de.push(e)}if(H.length>0){let e=[...D().keys()].sort((e,t)=>e.localeCompare(t));for(let t of e){let e=se.get(t)??Lt(t);typeof e==`string`&&Vt(e,t,Y.get(t)??t,Y,H).rewrites!==0&&(se.has(t)||se.set(t,e),ue.add(t),Y.has(t)||ce.add(t))}}Wt(ue);for(let{from:e}of q)if(typeof se.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let me=createManagedRenameRecoveryJournal({fromPath:e,toPath:S,affectedDocs:[...q],snapshots:It([...se.keys()],se)}),ge=[],_e=[...ce].sort((e,t)=>e.localeCompare(t));return await withManagedRenameRecovery(fe??w,me,async()=>{for(let e of de)te.deleteDocument(e);for(let e of _e){let S=t.documents.get(e)?zt(e,Y,H):Vt(se.get(e)??``,e,e,Y,H);S.rewrites>0&&(Rt(e,S.markdown),ge.push({docName:e,rewrites:S.rewrites})),te.updateDocumentFromMarkdown(e,S.markdown)}if(Ce)for(let{from:e,to:t}of q)isSystemDoc(e)||isConfigDoc(e)||(Ce.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let k=resolveContentEntryPath(w,E,e),j=resolveContentEntryPath(w,E,S);await renameTrackedPathInGit(fe,k,j)||(tracedMkdirSync(dirname(j),{recursive:!0}),tracedRenameSync(k,j)),E===`folder`&&Re(e,S);let F=await Mt([...Y.keys()]);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(B?.current){let e=B.current;withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":E}},t=>{let S=randomUUID(),w=new Date().toISOString(),D=J?.()??`main`,k=getOrLoadRenameLogIndex(e.gitDir),j=O?.actor?{writerId:O.actor.writerId,displayName:O.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},F=0;for(let{from:t,to:L}of q){let B={v:1,from:t,to:L,at:w,commitSha:``,branch:D,groupId:S,kind:E,actor:j};appendRenameLogEntry(e.gitDir,B,k,e),F+=1,O?.actor?recordContributor(L,O.actor.writerId,O.actor.displayName,O.actor.colorSeed,formatRenameSubject(t,L),O.actor.actorMetadata,void 0,[{from:t,to:L}]):recordContributor(L,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(t,L),void 0,void 0,[{from:t,to:L}])}t.setAttribute(`rename.entries_appended`,F)})}let L=E===`file`&&isSupportedDocFile(S)?extname(S):null;for(let{from:e,to:t}of q){let S=getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,L??S)}let ee=[...q].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of ee){let S=resolveContentEntryPath(w,`file`,e),E=resolveContentEntryPath(w,`file`,t),O=Vt(F.get(e)??se.get(e)??readFileSync(E,`utf-8`),e,t,Y,H);Ft([{fromDocName:e,toDocName:t}],new Map([[e,O.markdown]])),setReconciledBase(t,O.markdown);let k=D();k instanceof Map&&updateFileIndex({kind:`rename`,oldPath:S,newPath:E,oldDocName:e,newDocName:t,content:O.markdown},k),te.renameDocument(e,t,O.markdown),O.rewrites>0&&ge.push({docName:t,rewrites:O.rewrites})}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-journal-clear`)throw Error(`OK_TEST_RENAME_FAULT=pre-journal-clear`)}),te.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${S}:`,t)}),ae?.(`files`),ae?.(`backlinks`),ae?.(`graph`),ge.sort((e,t)=>e.docName.localeCompare(t.docName)),k.setAttribute(`rename.rewrite_count`,ge.length),{renamed:ee,renamedAssets:H,rewrittenDocs:ge}}))}function Fr(e){let t=parseAgentBodyFields(e),S=t.writerId??`claude-1`;return{rawAgentId:t.rawAgentId,agentId:S,agentName:t.displayName,colorSeed:t.colorSeed??t.rawAgentId??S,clientName:t.clientName,clientVersion:t.clientVersion,label:t.label}}function Ir(e){return{principalId:me?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function Lr(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 zr(e){return{value:e.value}}function Br(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function Vr(e,t,S,w){if(S.length!==0)switch(e.kind){case`agent`:{let w=e.summary.kind===`value`,E=w?e.summary:normalizeSummary(t),D=Lr(E),O=w||!D.response?D.response:zr(D.response);for(let t=0;t<S.length;t++){let{docName:w,subject:E}=S[t];recordContributor(w,e.writerId,e.displayName,e.colorSeed,E,e.actor,t===0?D.stored:void 0)}incrementAgentWriteCalls(),Br(E,!w);for(let{docName:e}of S)st(e,`rename-path`);return O}case`principal`:{let t=Lr(e.summary);for(let w=0;w<S.length;w++){let{docName:E,subject:D}=S[w];recordContributor(E,e.writerId,e.displayName,e.colorSeed,D,e.actor,w===0?t.stored:void 0)}Br(e.summary,!1);for(let{docName:e}of S)st(e,`rename-path`);return t.response}case`anonymous`:w.onAnonymous?.();return;default:{let t=e;throw Error(`Unhandled actor kind in ${w.context}: ${String(t.kind)}`)}}}let Hr=withValidation(AgentWriteRequestSchema,async(t,w,E)=>{try{let t=rt(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:D,agentName:O,colorSeed:k,clientName:j,clientVersion:F,label:L}=Fr(E);if(isSystemDoc(t)||isConfigDoc(t)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${t}' is a reserved document name.`,{handler:`agent-write`});return}let B=normalizeSummary(E.summary),H=await S.getSession(t,D,{displayName:O,colorSeed:k,clientName:j}),q=new Date().toISOString(),J=typeof E.content==`string`?E.content:`Hello from the agent! ${q}`,{response:Y,stored:ee}=Lr(B);try{let S=iconFromClientName(j),w=AGENT_ICON_COLORS[S]??colorFromSeed(k??D);se?.setPresence(D,{displayName:O,icon:S,color:w,currentDoc:t,mode:`writing`,ts:Date.now()}),captureEffect(H.dc.document.getText(`source`),D,k,j),H.dc.document.transact(()=>{applyAgentMarkdownWrite(H.dc.document,`${J}\n`,`append`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:t}:void 0),H.dc.document.getMap(`agent-flash`).set(D,{agentId:D,timestamp:Date.now(),type:`insert`,description:`Added (${O}): ${J.slice(0,50)}`})},H.origin),recordContributor(t,D,O,k,void 0,Ir({clientName:j,clientVersion:F,label:L}),ee),incrementAgentWriteCalls(),Br(B)}finally{se?.touchMode(D,`idle`)}st(t,`agent-write`),ce?.(),successResponse(w,200,AgentWriteSuccessSchema,{timestamp:q,...Y?{summary:Y}:{}},{handler:`agent-write`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$3.error({err:e},`[agent-write] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write`,cause:e})}},{handler:`agent-write`,method:`POST`}),Ur=withValidation(AgentWriteMdRequestSchema,async(t,w,E)=>{try{let t=E.position??`append`,D=rt(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Fr(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`agent-write-md`});return}let H=normalizeSummary(E.summary),{response:q,stored:J}=Lr(H),Y=await S.getSession(D,O,{displayName:k,colorSeed:j,clientName:F}),ee=new Date().toISOString();try{let S=iconFromClientName(F),w=AGENT_ICON_COLORS[S]??colorFromSeed(j??O);se?.setPresence(O,{displayName:k,icon:S,color:w,currentDoc:D,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),O,j,F),Y.dc.document.transact(()=>{applyAgentMarkdownWrite(Y.dc.document,E.markdown,t,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:D}:void 0),Y.dc.document.getMap(`agent-flash`).set(O,{agentId:O,timestamp:Date.now(),type:`insert`,description:`Added (${k}): ${E.markdown.trim().slice(0,50)}`})},Y.origin),recordContributor(D,O,k,j,void 0,Ir({clientName:F,clientVersion:L,label:B}),J),incrementAgentWriteCalls(),Br(H)}finally{se?.touchMode(O,`idle`)}st(D,`agent-write-md`),oe?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),ce?.();let te=nt(D),ne=it(D),ae=at();ae===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)}),successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ee,subscriberCount:ne,systemSubscriberCount:ae,...te?{hints:te}:{},...q?{summary:q}:{}},{handler:`agent-write-md`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-write-md`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-write-md`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-write-md`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$3.error({err:e},`[agent-write-md] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-write-md`,cause:e})}},{handler:`agent-write-md`,method:`POST`}),Wr=withValidation(FrontmatterPatchRequestSchema,async(e,t,w)=>{try{let e=rt(w.docName!==void 0&&w.docName.length>0?w.docName:`test-doc`),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Fr(w);if(isSystemDoc(e)||isConfigDoc(e)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${e}' is a reserved document name.`,{handler:`frontmatter-patch`});return}let L=w.patch??{},B=Object.keys(L),H=normalizeSummary(w.summary),{response:q,stored:J}=Lr(H),Y=await S.getSession(e,E,{displayName:D,colorSeed:O,clientName:k}),ee=new Date().toISOString(),te,ne=!1,ae=[];try{let t=iconFromClientName(k),S=AGENT_ICON_COLORS[t]??colorFromSeed(O??E);se?.setPresence(E,{displayName:D,icon:t,color:S,currentDoc:e,mode:`writing`,ts:Date.now()}),withSpanSync(`ok.frontmatter_patch`,{attributes:{"doc.name":e,"frontmatter_patch.keys":B.length}},()=>{Y.dc.document.transact(()=>{let{fenced:e,body:t}=detectFmRegion(Y.dc.document.getText(`source`).toString()),S=applyPatchToFm(e,L);if(!S.ok){te=S.error;return}for(let e of Object.keys(L))ae.push(e);if(S.nextFenced!==e){let e=S.nextFenced+t;composeAndWriteRawBody(Y.dc.document,e,`agent`),recordFrontmatterEditSurface(`mcp-write`)}ne=!0},Y.origin)})}finally{se?.touchMode(E,`idle`)}if(te){let e;switch(te.kind){case`invalid_value`:e={[te.key]:te.reason};break;case`reserved_key`:e={[te.key]:`'${te.key}' is reserved`};break;case`unknown_key`:e={[te.key]:`'${te.key}' is not a recognized key`};break;case`duplicate_target`:e={[te.key]:`'${te.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${te.expected.join(`, `)}; got: ${te.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${te.bytes} > ${te.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${te.reason}`};break;default:e={__region__:`unhandled frontmatter edit error (${String(te)})`}}errorResponse(t,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}ne&&ae.length>0&&(recordContributor(e,E,D,O,void 0,Ir({clientName:k,clientVersion:j,label:F}),J),incrementAgentWriteCalls(),Br(H),st(e,`frontmatter-patch`)),oe?.setFocus(E,{agentName:D,currentDoc:e,writeKind:`write`,ts:Date.now()}),ce?.();let ue=it(e),de=at();de===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(k)}),successResponse(t,200,FrontmatterPatchSuccessSchema,{timestamp:ee,subscriberCount:ue,systemSubscriberCount:de,appliedKeys:ae,...q?{summary:q}:{}},{handler:`frontmatter-patch`})}catch(e){if(e instanceof AgentSessionCapacityError){errorResponse(t,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$3.error({err:e},`[frontmatter-patch] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Gr(e){let t=e.getMap(`lifecycle`),S=t.get(`status`);if(typeof S!=`string`||S.length===0)return null;let w=t.get(`reason`);return{status:S,reason:typeof w==`string`?w:``}}let Kr=withValidation(EmptyRequestSchema,async(e,S)=>{try{let E=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!isSafeDocName(E)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let D=rt(E);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`document-read`});return}let O=t.documents.get(D);if(O){successResponse(S,200,DocumentReadSuccessSchema,{docName:D,content:O.getText(`source`).toString(),lifecycle:Gr(O)},{handler:`document-read`});return}if(!existsSync(resolveContentEntryPath(w,`file`,D))){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Document not found: ${D}.`,{handler:`document-read`});return}let k=await t.openDirectConnection(D);try{let e=k.document;if(!e){errorResponse(S,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}successResponse(S,200,DocumentReadSuccessSchema,{docName:D,content:e.getText(`source`).toString(),lifecycle:Gr(e)},{handler:`document-read`})}finally{await k.disconnect()}}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),qr=withValidation(EmptyRequestSchema,async(e,t)=>{try{ye&&await ye.catch(e=>{log$3.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=S.searchParams.get(`dir`),k=S.searchParams.get(`showAll`)===`true`;if(E)try{safeSubdir(w,E)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(k&&ge){let e=[];try{await walkContentDirForShowAll({contentDir:w,contentFilter:ge,dirFilter:E,documents:e,getDocExtension}),e.sort((e,t)=>{let S=e.kind===`folder`?e.path??``:e.docName??e.path??``,w=t.kind===`folder`?t.path??``:t.docName??t.path??``;return S.localeCompare(w)}),successResponse(t,200,DocumentListSuccessSchema,{documents:e},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}return}let j=D(),F=O?.()??new Map,L=[];for(let[e,t]of F)E&&!e.startsWith(`${E}/`)&&e!==E||L.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let[e,t]of j){if(E&&!e.startsWith(`${E}/`)&&e!==E)continue;let S=getDocExtension(e);L.push({kind:`document`,docName:e,docExt:S,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let D of t.aliases){if(E&&!D.startsWith(`${E}/`)&&D!==E)continue;let O=relative(w,t.canonicalPath);L.push({kind:`document`,docName:D,docExt:S,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:O})}}let B=[];try{let e=ze(j);De?.signature!==e&&(De={signature:e,assets:collectReferencedAssets({contentDir:w,fileIndex:j,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:ge?e=>ge.isPathIgnored(e):void 0})}),B=De?.assets??[]}catch(e){De=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}for(let e of B)E&&!e.path.startsWith(`${E}/`)&&e.path!==E||L.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});L.sort((e,t)=>{let S=e.kind===`folder`?e.path??``:e.docName??e.path??``,w=t.kind===`folder`?t.path??``:t.docName??t.path??``;return S.localeCompare(w)}),successResponse(t,200,DocumentListSuccessSchema,{documents:L},{handler:`document-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),Jr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!te){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}successResponse(t,200,BacklinksSuccessSchema,{docName:S,backlinks:te.getBacklinks(S).map(e=>({source:e.source,anchor:e.anchor,title:We(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),Yr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!te){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let w={};for(let e of S.split(`,`)){let t=e.trim();!t||!isSafeDocName(t)||(w[t]=te.getBacklinkCount(t))}successResponse(t,200,BacklinkCountsSuccessSchema,{counts:w},{handler:`backlink-counts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),Xr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!te){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let w=vt();successResponse(t,200,ForwardLinksSuccessSchema,{docName:S,forwardLinks:te.getForwardLinkEntries(S).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Ge(e.target,w),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),Zr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!te){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`docName`);if(w&&!isSafeDocName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let E=S.searchParams.get(`degrees`);if(E&&!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let D,O;if(E&&w){let e=Number.parseInt(E,10);if(!Number.isFinite(e)||e<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:D,links:O}=te.getLinkGraphNeighborhood(w,e))}else ({nodes:D,links:O}=te.getLinkGraph());let k=vt();successResponse(t,200,LinkGraphSuccessSchema,{nodes:D.map(e=>{if(e.kind===`doc`){let t=$e(e.docName,k);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Ge(e.docName,k),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},{handler:`link-graph`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),Qr=withValidation(EmptyRequestSchema,async(e,t)=>{if(!te){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!isOrphanMode(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}successResponse(t,200,OrphansSuccessSchema,{orphans:te.getOrphans([...D().keys()],S).map(e=>({docName:e,title:We(e)}))},{handler:`orphans`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),ji=withValidation(EmptyRequestSchema,async(e,t)=>{if(!te){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),w=S?Number.parseInt(S,10):20,E=Number.isFinite(w)&&w>0?w:20,D=vt();successResponse(t,200,HubsSuccessSchema,{hubs:te.getHubs(E).map(e=>({docName:e.docName,title:Ge(e.docName,D),count:e.count}))},{handler:`hubs`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),Hi=withValidation(EmptyRequestSchema,async(e,t)=>{if(!te){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let S=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(S.some(e=>e.length===0||!isSafeDocName(e))){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let w=S.length?[...new Set(S.map(e=>rt(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:te.getDeadLinks(vt(),w).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:We(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),Ui=withValidation(AgentPatchRequestSchema,async(t,w,E)=>{try{let{find:t,replace:D,offset:O}=E,k=rt(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`),{agentId:j,agentName:F,colorSeed:L,clientName:B,clientVersion:H,label:q}=Fr(E);if(findLooksLikeFrontmatter(t)){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via edit_document. Use write_document with position:"replace" to rewrite the document including its YAML block.`,{handler:`agent-patch`});return}if(isSystemDoc(k)||isConfigDoc(k)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${k}' is a reserved document name.`,{handler:`agent-patch`});return}let J=normalizeSummary(E.summary),Y=await S.getSession(k,j,{displayName:F,colorSeed:L,clientName:B}),ee=new Date().toISOString(),te=!1,ne=!1,ae=!1;try{let S=iconFromClientName(B),w=AGENT_ICON_COLORS[S]??colorFromSeed(L??j);if(se?.setPresence(j,{displayName:F,icon:S,color:w,currentDoc:k,mode:`writing`,ts:Date.now()}),captureEffect(Y.dc.document.getText(`source`),j,L,B),Y.dc.document.transact(()=>{let{frontmatter:S,body:w}=stripFrontmatter(Y.dc.document.getText(`source`).toString()),E=prependFrontmatter(S,w),L=O==null?E.indexOf(t):E.slice(O,O+t.length)===t?O:-1;if(L===-1){O==null?te=!0:ne=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":k,findLength:t.length,replaceLength:D.length,hadOffset:O!=null})),incrementAgentPatchFindMismatches();return}if(L<S.length){ae=!0;return}let{body:B}=stripFrontmatter(E.slice(0,L)+D+E.slice(L+t.length));applyAgentMarkdownWrite(Y.dc.document,B,`replace`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:k}:void 0),Y.dc.document.getMap(`agent-flash`).set(j,{agentId:j,timestamp:Date.now(),type:`insert`,description:`Patched (${F}): ${t.slice(0,50)}`})},Y.origin),!te&&!ne&&!ae){let{stored:e}=Lr(J);recordContributor(k,j,F,L,void 0,Ir({clientName:B,clientVersion:H,label:q}),e),incrementAgentWriteCalls(),Br(J)}}finally{se?.touchMode(j,`idle`)}if(ne){errorResponse(w,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(te){errorResponse(w,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(ae){agentPatchFmTouchCounter().add(1,{result:`rejected`}),errorResponse(w,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via edit_document. Use write_document with position:"replace" to rewrite the document including its YAML block.`,{handler:`agent-patch`});return}st(k,`agent-patch`),oe?.setFocus(j,{agentName:F,currentDoc:k,writeKind:`edit`,ts:Date.now()}),ce?.();let ue=it(k),de=at();de===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(B)});let{response:fe}=Lr(J);successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ee,subscriberCount:ue,systemSubscriberCount:de,...fe?{summary:fe}:{}},{handler:`agent-patch`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-patch`);return}if(e instanceof FrontmatterMalformedError){respondFrontmatterMalformed(w,e,`agent-patch`);return}if(e instanceof AgentSessionCapacityError){errorResponse(w,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}log$3.error({err:e},`[agent-patch] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),Gi=withValidation(AgentUndoRequestSchema,async(t,w,E)=>{try{let{agentId:t,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Fr(E),L=rt(E.docName!==void 0&&E.docName.length>0?E.docName:`test-doc`);if(isSystemDoc(L)||isConfigDoc(L)){errorResponse(w,400,`urn:ok:error:reserved-doc-name`,`'${L}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:B}=E,H=E.scope===`session`||E.scope===`file`?`session`:`last`;if(!S.hasSession(L,B)){errorResponse(w,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let q=await S.getSession(L,B),J=!1;try{let S=iconFromClientName(k),w=AGENT_ICON_COLORS[S]??colorFromSeed(O??t);se?.setPresence(t,{displayName:D,icon:S,color:w,currentDoc:L,mode:`writing`,ts:Date.now()}),J=applyAgentUndo(q,H,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:L}:void 0),J&&recordContributor(L,B,D,O,void 0,Ir({clientName:k,clientVersion:j,label:F}))}finally{se?.touchMode(t,`idle`)}J&&st(L,`agent-undo`),oe?.setFocus(B,{agentName:B,currentDoc:L,writeKind:`undo`,ts:Date.now()}),successResponse(w,200,AgentUndoSuccessSchema,{docName:L,scope:H,undone:J},{handler:`agent-undo`})}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(w,e,`agent-undo`);return}log$3.error({err:e},`[agent-undo] handler failed`),errorResponse(w,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),Ki=withValidation(EmptyRequestSchema,async(e,t)=>{try{let w=validateAgentId(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(w===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}successResponse(t,200,AgentActivitySuccessSchema,listAgentActivity(S,w),{handler:`agent-activity`})}catch(e){log$3.error({err:e},`[agent-activity] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),Yi=withValidation(EmptyRequestSchema,async(e,t)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=validateAgentId(w.searchParams.get(`agentId`)),D=w.searchParams.get(`docName`),O=w.searchParams.get(`stackIndex`);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!D||D.trim()===``){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!isSafeDocName(D)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let k=rt(D);if(isSystemDoc(k)||isConfigDoc(k)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${k}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!O||Number.isNaN(Number(O))){errorResponse(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let j=Number(O);if(!Number.isInteger(j)||j<0){errorResponse(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let F=S.getLiveSession(k,E);if(!F){errorResponse(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let L=F.um;if(j>=L.undoStack.length){errorResponse(t,404,`urn:ok:error:not-found`,`stackIndex ${j} out of range (stack has ${L.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let B=L.undoStack[j];successResponse(t,200,AgentBurstDiffSuccessSchema,{diff:synthesizeStackItemDiffText(B,F.dc.document.getText(`source`),k),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){log$3.error({err:e},`[agent-burst-diff] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),Xi=withValidation(EmptyRequestSchema,async(e,E)=>{try{let D=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),O=rt(D.searchParams.get(`docName`)??`test-doc`),k;try{k=safeContentPath(O,w)}catch(e){log$3.error({err:e,docName:O},`[test-reset] safeContentPath rejected docName`),errorResponse(E,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await S.closeAll(O),t.closeConnections(O);let j=`onStoreDocument-${O}`;t.debouncer.isDebounced(j)&&await t.debouncer.executeNow(j);let F=t.documents.get(O);if(F&&await(ve??t.unloadDocument.bind(t))(F),writeFileSync(k,``,`utf-8`),te&&(te.deleteDocument(O),te.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${O}:`,e)}),ae?.(`backlinks`),ae?.(`graph`)),D.searchParams.get(`reset-okignore`)!==`false`)try{let e=resolve(w,`.okignore`),S=t.documents.get(CONFIG_DOC_NAME_OKIGNORE);if(S){let e=S.getText(`source`);e.length>0&&S.transact(()=>{e.delete(0,e.length)},CONFIG_VALIDATION_REVERT_ORIGIN)}existsSync(e)&&writeFileSync(e,``,`utf-8`),ge&&await ge.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}ae?.(`files`),successResponse(E,200,TestResetSuccessSchema,{},{handler:`test-reset`})}catch(e){errorResponse(E,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),Zi=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!te){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await te.rebuildFromDisk(),te.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),ae?.(`backlinks`),ae?.(`graph`),successResponse(t,200,TestRescanBacklinksSuccessSchema,{},{handler:`test-rescan-backlinks`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),ka=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!F){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}F(),ae?.(`files`),successResponse(t,200,TestRescanFilesSuccessSchema,{},{handler:`test-rescan-files`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),_s=withValidation(SaveVersionRequestSchema,async(e,t,S)=>{try{let{rawAgentId:e,agentId:w,agentName:E,clientName:D}=Fr(S),O=B?.current;if(!O){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let k=/^[a-zA-Z0-9_-]+$/,j=[];if(Array.isArray(S.writers))try{j=S.writers.map(e=>{let t=e.id??`unknown`;if(!k.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,``)}})}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}j.length===0&&(j=e===void 0?[SERVICE_WRITER]:[{id:w,name:D?`${E} (${D})`:E,email:`${w}@openknowledge.local`}]);let F=await saveVersion(O,ee??`.`,j);console.log(`[history] checkpoint ${F.checkpointRef}`);try{await gcRenameLog(O,getOrLoadRenameLogIndex(O.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}successResponse(t,200,SaveVersionSuccessSchema,{checkpointRef:F.checkpointRef},{handler:`save-version`})}catch(e){log$3.error({err:e},`[save-version] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),xs=withValidation(EmptyRequestSchema,async(e,t)=>{let S=B?.current;if(!S){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=w.searchParams.get(`docName`)??``,D=w.searchParams.get(`branch`)??J?.()??`main`;if(!E){errorResponse(t,400,`urn:ok:error:invalid-request`,`docName query parameter is required.`,{handler:`history`});return}if(D.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(D)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}let O=ee??`.`,k=safeDocPath(E,O);if(`error`in k){errorResponse(t,400,`urn:ok:error:invalid-request`,k.error,{handler:`history`});return}let j=Number(w.searchParams.get(`limit`)??`50`),F=Number(w.searchParams.get(`offset`)??`0`),L=Math.min(200,Number.isFinite(j)?j:50),H=Number.isFinite(F)?F:0,q=w.searchParams.get(`type`)??void 0,Y=w.searchParams.get(`author`)??void 0,te=w.searchParams.get(`excludeAuthor`)??void 0,ne=Date.now();try{let e=await getDocumentHistory(S,{docName:E,branch:D,limit:L,offset:H,type:q,author:Y,excludeAuthor:te},O),w=Date.now()-ne;console.log(`[timeline] query docName=${E} entries=${e.entries.length} duration=${w}ms`),successResponse(t,200,HistorySuccessSchema,{...e},{handler:`history`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function Cs(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let w=B?.current;if(!w){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let E=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,D=ee??`.`,O=safeDocPath(E,D);if(`error`in O){errorResponse(t,400,`urn:ok:error:invalid-request`,O.error,{handler:`history-version`});return}let k=shadowGit(w),j=J?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await resolveDocPathAtCommit(w,E,S,j,getOrLoadRenameLogIndex(w.gitDir),e=>{let t=safeDocPath(e,D);return`error`in t?`${e}.md`:t.path},createAncestorShaSetCache());if(e===null){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let O=await k.raw(`show`,`${S}:${e}`),[F=``,L=``]=(await k.raw(`log`,`-1`,`--format=%aI%x00%an`,S)).trim().split(`\0`);successResponse(t,200,HistoryVersionSuccessSchema,{sha:S,content:O,timestamp:F,author:L},{handler:`history-version`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let Ts=withValidation(EmptyRequestSchema,async(e,S)=>{let w=B?.current;if(!w){errorResponse(S,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`diff`});return}let E=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),D=E.searchParams.get(`docName`)??``,O=E.searchParams.get(`from`)??``,k=E.searchParams.get(`to`)??``;if(!k||!/^[0-9a-f]{40}$/i.test(k)){errorResponse(S,400,`urn:ok:error:invalid-request`,`'to' must be a valid 40-char commit SHA.`,{handler:`diff`});return}let j=ee??`.`,F=safeDocPath(D,j);if(`error`in F){errorResponse(S,400,`urn:ok:error:invalid-request`,F.error,{handler:`diff`});return}let L=shadowGit(w),H=J?.()??`main`,q=getOrLoadRenameLogIndex(w.gitDir),Y=createAncestorShaSetCache(),te=e=>{let t=safeDocPath(e,j);return`error`in t?`${e}.md`:t.path};try{let e=await resolveDocPathAtCommit(w,D,k,H,q,te,Y);if(e===null){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Document did not exist at the target version.`,{handler:`diff`});return}let E=await L.raw(`show`,`${k}:${e}`),j;if(O&&/^[0-9a-f]{40}$/i.test(O)){let e=await resolveDocPathAtCommit(w,D,O,H,q,te,Y);if(e===null){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Document did not exist at the source version.`,{handler:`diff`});return}j=await L.raw(`show`,`${O}:${e}`)}else{let e=t.documents.get(D);if(!e){errorResponse(S,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`diff`});return}j=e.getText(`source`).toString()}let F=stripFrontmatter(j).body,B=stripFrontmatter(E).body,J=diffLines(F,B),ee=[],ne=0,ae=0;for(let e of J){let t=e.value.replace(/\n$/,``).split(`
2376
+ `),S=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)ee.push({type:S,text:e});e.added&&(ne+=t.length),e.removed&&(ae+=t.length)}successResponse(S,200,DiffSuccessSchema,{lines:ee,additions:ne,deletions:ae},{handler:`diff`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`diff`,cause:e})}},{handler:`diff`,method:`GET`,skipBodyParse:!0}),Ds=withValidation(RollbackRequestSchema,async(S,w,E)=>{let D=extractActorIdentity(E,me);if(D.kind===`invalid-summary`){errorResponse(w,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let O=t.documents.get(E.docName);if(O&&isDocInConflict(O)){respondDocInConflict(w,new DocInConflictError({file:`${E.docName}${getDocExtension(E.docName)}`}),`rollback`);return}let k=B?.current;if(!k){errorResponse(w,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:j,commitSha:F}=E,L=ee??`.`,H=safeDocPath(j,L);if(`error`in H){errorResponse(w,400,`urn:ok:error:invalid-request`,H.error,{handler:`rollback`});return}let q=shadowGit(k),Y=Date.now();try{let S=getOrLoadRenameLogIndex(k.gitDir),E=createAncestorShaSetCache(),O=await resolveDocPathAtCommit(k,j,F,J?.()??`main`,S,e=>{let t=safeDocPath(e,L);return`error`in t?`${e}.md`:t.path},E);if(O===null){errorResponse(w,404,`urn:ok:error:doc-not-found`,`Commit ${F.slice(0,7)} does not contain document ${j} at any known historical path.`,{handler:`rollback`});return}let B=await q.raw(`show`,`${F}:${O}`),H=new Date().toISOString();await safetyCheckpoint(k,L,{action:`rollback`,context:{docName:j,targetSha:F}});let ee=t.documents.get(j);if(!ee){errorResponse(w,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let te=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:j}:void 0;ee.transact(()=>{replaceRawBody(ee,B,te)},ROLLBACK_ORIGIN);let ne;switch(D.kind){case`agent`:{let e=F.slice(0,8),t=D.summary.kind===`value`,S=t?D.summary:normalizeSummary(`Restored to ${e}`),w=Lr(S);ne=t||!w.response?w.response:zr(w.response),recordContributor(j,D.writerId,D.displayName,D.colorSeed,formatRollbackSubject(j,F),D.actor,w.stored),incrementAgentWriteCalls(),Br(S,!t);break}case`principal`:{let e=Lr(D.summary);ne=e.response,recordContributor(j,D.writerId,D.displayName,D.colorSeed,formatRollbackSubject(j,F),D.actor,e.stored),Br(D.summary,!1);break}case`anonymous`:log$3.debug({docName:j,commitSha:F.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(D.kind)}`)}renameAttributionCounter().add(1,{kind:`rollback`,attribution_kind:D.kind}),st(j,`rollback`);let ae=Date.now()-Y;console.log(`[rollback] docName=${j} from=${F.slice(0,8)} duration=${ae}ms`),D.kind===`agent`&&oe?.setFocus(D.writerId,{agentName:D.displayName,currentDoc:j,writeKind:`rollback-apply`,ts:Date.now()}),successResponse(w,200,RollbackSuccessSchema,{restoredFrom:F,timestamp:H,...ne?{summary:ne}:{}},{handler:`rollback`})}catch(e){errorResponse(w,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),Os=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$3.error({err:e},`[metrics-reconciliation] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),ks=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$3.error({err:e},`[metrics-parse-health] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),As=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=getActiveBranch(),S=Y?.();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:E,currentBranch:e,...S===void 0?{}:{currentDiskAckSVs:S}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function Ns(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let S=me?.()??null;if(!S){errorResponse(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}successResponse(t,200,PrincipalSuccessSchema,S,{handler:`principal`})}async function Ps(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=se?.getPresenceMap()??{},S=Date.now(),w={};for(let[t,E]of Object.entries(e))S-E.ts<2e4&&(w[t]=E);successResponse(t,200,MetricsAgentPresenceSuccessSchema,{presence:w},{handler:`metrics-agent-presence`})}catch(e){log$3.error({err:e},`[metrics-agent-presence] handler failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function Is(e,t){if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let S=resolve(w),E=S,D=!0;try{E=realpathSync(S)}catch(e){let w=e?.code;if(w===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:S}),D=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:S,err:e}),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:w??void 0,cause:e});return}}successResponse(t,200,WorkspaceSuccessSchema,{contentDir:E,pathSeparator:sep,symlinkResolved:D},{handler:`workspace`})}let Rs=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!S||S.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let E=assetContentTypeForPath(S),D=extname(S).slice(1).toLowerCase();if(!E||!ASSET_EXTENSIONS.has(D)){errorResponse(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let O=realpathSync(w),k=resolve(O,S),j;try{j=realpathSync(k)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!isWithinContentDir(j,O)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let F;try{F=statSync(j)}catch{errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!F.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let L=toContentRelativePath(O,j);if(L!==S.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(ge?.isPathIgnored(L)){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let B={"Content-Type":E,"Content-Length":String(F.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":INLINE_RENDERABLE_EXTENSIONS.has(D)?`inline`:`attachment`,"Cache-Control":`no-store`};D===`svg`&&(B[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`),t.writeHead(200,B);try{await pipeline(createReadStream(j),t)}catch(e){log$3.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:S,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),$s=1048576,ec=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!S||S.includes(`\0`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let E=realpathSync(w),D=resolve(E,S),O;try{O=realpathSync(D)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!isWithinContentDir(O,E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let k;try{k=statSync(O)}catch(e){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!k.isFile()){errorResponse(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(toContentRelativePath(E,O)!==S.split(`\\`).join(`/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(k.size>$s){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${$s}-byte text-viewer cap.`,{handler:`asset-text`});return}let j=(await readFile$1(O)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(j)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),tc=1440*60*1e3,nc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!B?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),S=[],w=resolve(B.current.gitDir,`rescue`);if(existsSync(w))try{let t=readdirSync(w).filter(e=>isSupportedDocFile(e));for(let E of t){let t=resolve(w,E),D=statSync(t);if(e-D.mtimeMs>tc){try{unlinkSync(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}S.push({docName:stripDocExtension(E),timestamp:D.mtime.toISOString(),size:D.size,source:`flat`})}}catch(e){log$3.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=J?.()??`main`,t=await listRescueCheckpoints(B.current,e);for(let e of t)S.push({...e,source:`timeline`})}catch(e){log$3.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}successResponse(t,200,RescueListSuccessSchema,S,{handler:`rescue-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0});async function rc(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`rescue-get`,extraHeaders:{Allow:`GET`}});return}if(!B?.current){errorResponse(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`rescue-get`});return}let w=resolve(B.current.gitDir,`rescue`),E=resolve(w,`${S}${getDocExtension(S)}`);if(!E.startsWith(`${w}/`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid document name.`,{handler:`rescue-get`});return}if(existsSync(E)){let e=statSync(E);if(Date.now()-e.mtimeMs>tc)try{unlinkSync(E)}catch{}else{let e=readFileSync(E,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=J?.()??`main`,w=(await listRescueCheckpoints(B.current,e)).filter(e=>e.docName===S).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(w){let e=shadowGit(B.current),S=((await e.raw(`ls-tree`,`-r`,w.sha)).trim().split(`
2377
+ `)[0]??``).split(/\s+/)[2];if(S){let w=await e.raw(`cat-file`,`-p`,S);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(w);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`rescue-get`})}let ic=withValidation(CreatePageRequestSchema,async(e,t,S)=>{try{let e=extractActorIdentity(S,me);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let E=S.path;if(!isSupportedDocFile(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(E.includes(`..`)||E.startsWith(`/`)||E.includes(`\0`)||E.includes(`\\`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let O=resolve(w),k=resolve(O,E);if(!k.startsWith(`${O}/`)&&k!==O){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let j=stripDocExtension(E);if(isSystemDoc(j)||isConfigDoc(j)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${j}' is a reserved document name.`,{handler:`create-page`});return}let F=typeof S.template==`string`?S.template.trim():``,L=``,B;if(F.length>0){if(!/^[A-Za-z0-9_-]+$/.test(F)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let S=E.includes(`/`)?E.slice(0,E.lastIndexOf(`/`)):``,w=resolveTemplatesAvailable(O,S),D=w.find(e=>e.name===F);if(!D){let e=w.length===0?`(none)`:w.map(e=>`"${e.name}" (${e.scope})`).join(`, `);errorResponse(t,400,`urn:ok:error:invalid-request`,`Template "${F}" does not resolve for folder "${S||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let k=resolve(O,D.path),j;try{j=readFileSync(k,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${D.path}.`,{handler:`create-page`,cause:e});return}let{body:H}=stripFrontmatter(j),q=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;L=applySubstitution(H,{date:todayIsoUtc(),user:q}),B=D.scope}mkdirSync(dirname(k),{recursive:!0});try{writeFileSync(k,L,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let H=stripDocExtension(E);switch(Ce?.delete(H),ge&&ge.incrementMdDir(dirname(H)),registerWrite(k,contentHash(L)),e.kind){case`agent`:case`principal`:recordContributor(H,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}let q=typeof D==`function`?D():null;q instanceof Map&&updateFileIndex({kind:`create`,path:k,docName:H,content:L},q),te&&(te.updateDocumentFromMarkdown(H,L),te.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${H}:`,e)}),ae?.(`backlinks`),ae?.(`graph`)),ae?.(`files`),B!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:F,templateScope:B,docName:H})),successResponse(t,200,CreatePageSuccessSchema,{docName:H},{handler:`create-page`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),ac=withValidation(CreateFolderRequestSchema,async(e,t,S)=>{try{if(extractActorIdentity(S,me).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=S.path;if(!isValidRelativeContentPath(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(e===`.ok`||e.startsWith(`.ok/`)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'.ok' is a reserved directory.`,{handler:`create-folder`});return}if(ge?.isDirExcluded(e)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let E=resolveContentEntryPath(w,`folder`,e);if(existsSync(E)){errorResponse(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}tracedMkdirSync(E,{recursive:!0}),Pe(e),ae?.(`files`),successResponse(t,200,CreateFolderSuccessSchema,{path:e},{handler:`create-folder`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),oc=withValidation(DuplicatePathRequestSchema,async(e,S,E)=>{try{let e=extractActorIdentity(E,me);if(e.kind===`invalid-summary`){errorResponse(S,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:O}=E,k=O===`file`?stripDocExtension(E.path):E.path;if(!isValidRelativeContentPath(k)){errorResponse(S,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(k===`.ok`||k.startsWith(`.ok/`)||O===`file`&&(isSystemDoc(k)||isConfigDoc(k))||O===`folder`&&isReservedSyntheticFolderPath(k)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}O===`file`&&probeAndRegisterSourceFileExtension(w,k);let j=resolveContentEntryPath(w,O,k);if(!existsSync(j)){if(O===`file`){let e=resolveContentEntryPath(w,`folder`,k);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(S,400,`urn:ok:error:invalid-request`,`Target path is not a ${O}.`,{handler:`duplicate-path`});return}}errorResponse(S,404,`urn:ok:error:doc-not-found`,`${O} does not exist.`,{handler:`duplicate-path`});return}let F=statSync(j);if(O===`file`&&!F.isFile()||O===`folder`&&!F.isDirectory()){errorResponse(S,400,`urn:ok:error:invalid-request`,`Target path is not a ${O}.`,{handler:`duplicate-path`});return}let L=O===`file`?[k]:listAffectedDocNames(D(),O,k),B=ue?.(),H=new Set(B?B.getConflicts().map(e=>e.file):[]);for(let e of L){let w=stripDocExtension(e),E=t.documents.get(w),D=`${w}${getDocExtension(w)}`,O=E!==void 0&&isDocInConflict(E),k=H.has(D);if(O||k){respondDocInConflict(S,new DocInConflictError({file:D}),`duplicate-path`);return}}let q=typeof D==`function`?D():null,J,Y=[];if(O===`file`){let e=extname(j);if(J=nextAvailableDuplicateDocName(w,k).docName,isSystemDoc(J)||isConfigDoc(J)||ge?.isExcluded(`${J}${e}`)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let t=resolveDuplicateDocPath(w,J,e),E=readFileSync(j,`utf-8`),D=dirname(t),O=existsSync(D);try{tracedMkdirSync(D,{recursive:!0}),tracedWriteFileSync(t,E,{encoding:`utf-8`,flag:`wx`})}catch(e){if(isAlreadyExistsError(e)){errorResponse(S,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!O)try{tracedRmdirSync(D)}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTEMPTY`&&console.warn(`[duplicate-path] failed to clean duplicate parent directory:`,{destinationDir:D,err:e})}throw e}let F=!1;try{registerDocExtension(J,e),Ce?.delete(J),ge&&(ge.incrementMdDir(dirname(J)),F=!0),registerWrite(t,contentHash(E)),q instanceof Map&&updateFileIndex({kind:`create`,path:t,docName:J,content:E},q),te?.updateDocumentFromMarkdown(J,E),Y=[J]}catch(e){try{tracedRmSync(t,{force:!0})}catch(e){console.warn(`[duplicate-path] failed to clean partial file duplicate:`,{destinationPath:t,err:e})}throw forgetDocExtension(J),ge&&F&&ge.decrementMdDir(dirname(J)),q instanceof Map&&updateFileIndex({kind:`delete`,path:t,docName:J},q),e}}else{if(J=nextAvailableDuplicateFolderPath(w,k).folderPath,ge?.isDirExcluded(J)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=resolveContentEntryPath(w,`folder`,J);try{tracedCpSync(j,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(isAlreadyExistsError(e)){errorResponse(S,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of collectFolderPaths(w,J))Pe(e);let e=collectMarkdownCopies(w,J);Y=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(t.docName,e),Ce?.delete(t.docName),ge&&ge.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),q instanceof Map&&updateFileIndex({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content},q),te?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{tracedRmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[duplicate-path] failed to clean partial folder duplicate:`,{destinationPath:e,err:t})}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of Y)recordContributor(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}te&&Y.length>0&&(te.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),ae?.(`backlinks`),ae?.(`graph`)),ae?.(`files`),successResponse(S,200,DuplicatePathSuccessSchema,{kind:O,path:J,duplicatedDocNames:Y},{handler:`duplicate-path`})}catch(e){if(e instanceof DuplicateNameExhaustedError){errorResponse(S,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=classifyDuplicatePathFilesystemProblem(e);if(t){errorResponse(S,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),sc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!S||S.length===0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!isSafeDocName(S)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let w=Ue(S);if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}successResponse(t,200,PageHeadingsSuccessSchema,{docName:S,headings:extractHeadings(readFileSync(w,`utf-8`))},{handler:`page-headings`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),cc=withValidation(RenamePathRequestSchema,async(e,S,E)=>{try{let e=extractActorIdentity(E,me);if(e.kind===`invalid-summary`){errorResponse(S,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:O,fromPath:k,toPath:j}=E;if(!isValidRelativeContentPath(k)||!isValidRelativeContentPath(j)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(O===`file`&&(isSystemDoc(k)||isSystemDoc(j)||isConfigDoc(k)||isConfigDoc(j))){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(k===`.ok`||k.startsWith(`.ok/`)||j===`.ok`||j.startsWith(`.ok/`)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`.ok is a reserved directory.`,{handler:`rename-path`});return}if(k===j){successResponse(S,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}if(k.toLowerCase()===j.toLowerCase()){errorResponse(S,400,`urn:ok:error:invalid-request`,`Case-only renames are not supported.`,{handler:`rename-path`});return}if(O===`asset`){let t;try{t=await jr(k,j)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(S,e,`rename-path`);return}let{status:t,type:w,error:E}=jt(e);errorResponse(S,t,w,E,{handler:`rename-path`,cause:e});return}let w;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let S=`Renamed asset ${k} → ${j}`;w=Vr(e,S,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:S})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$3.debug({kind:`asset`,fromPath:k,toPath:j,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(renameAttributionCounter().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),q)try{await q()}catch(e){console.warn(`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred):`,e)}successResponse(S,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...w?{summary:w}:{}},{handler:`rename-path`});return}let F=O===`file`?[stripDocExtension(k)]:listAffectedDocNames(D(),O,k),L=ue?.(),B=new Set(L?L.getConflicts().map(e=>e.file):[]);for(let e of F){let w=stripDocExtension(e),E=t.documents.get(w),D=O===`file`?k:`${w}${getDocExtension(e)}`,j=E!==void 0&&isDocInConflict(E),F=B.has(D);if(j||F){respondDocInConflict(S,new DocInConflictError({file:D}),`rename-path`);return}}if(O===`file`&&probeAndRegisterSourceFileExtension(w,k),ge&&(O===`file`?ge.isExcluded(isSupportedDocFile(j)?j:`${j}${getDocExtension(k)}`):ge.isDirExcluded(j))){errorResponse(S,400,`urn:ok:error:invalid-request`,`Destination ${O===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}let H=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,J;try{J=await Mr(k,j,O,H?{actor:H}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(S,409,`urn:ok:error:doc-already-exists`,Dt(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(J.renamed.length===0&&J.renamedAssets.length===0){successResponse(S,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}J.renamedAssets.length>0&&Be();let Y;if(J.renamed.length>0&&(Y=Vr(e,`Renamed ${k} → ${j}`,J.renamed.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$3.debug({kind:O,fromPath:k,toPath:j,affectedDocs:J.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${O}`,attribution_kind:e.kind}),q)try{await q()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(S,200,RenamePathSuccessSchema,{renamed:J.renamed,renamedAssets:J.renamedAssets,rewrittenDocs:J.rewrittenDocs,...Y?{summary:Y}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:w,error:E}=jt(e);errorResponse(S,t,w,E,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),lc=withValidation(DeletePathRequestSchema,async(e,S,E)=>{try{Fr(E);let{kind:e,path:O}=E;if(!isValidRelativeContentPath(O)){errorResponse(S,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let k=e===`asset`?$t(O):{path:O,ambiguous:!1};if(k.ambiguous){errorResponse(S,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let j=k.path;if(e===`asset`&&(isSupportedDocFile(j)||isReservedProjectStatePath(j))){errorResponse(S,400,isReservedProjectStatePath(j)?`urn:ok:error:reserved-doc-name`:`urn:ok:error:invalid-request`,isReservedProjectStatePath(j)?`.ok and .git are reserved directories.`:`Asset operations do not support markdown documents.`,{handler:`delete-path`});return}let F=e===`asset`?resolveContentEntryPath(w,`folder`,j):resolveContentEntryPath(w,e,j);if(!existsSync(F)){errorResponse(S,404,`urn:ok:error:doc-not-found`,`${e} does not exist.`,{handler:`delete-path`});return}let L=statSync(F);if(e===`file`&&!L.isFile()||e===`asset`&&!L.isFile()||e===`folder`&&!L.isDirectory()){errorResponse(S,400,`urn:ok:error:invalid-request`,`Target path is not a ${e}.`,{handler:`delete-path`});return}let B=e===`asset`?[]:e===`file`?[O]:listAffectedDocNames(D(),e,O),H=ue?.(),q=new Set(H?H.getConflicts().map(e=>e.file):[]);for(let w of B){let E=stripDocExtension(w),D=t.documents.get(E),O=e===`file`?w:`${E}${getDocExtension(E)}`,k=D!==void 0&&isDocInConflict(D),j=q.has(O);if(k||j){respondDocInConflict(S,new DocInConflictError({file:O}),`delete-path`);return}}if(await Mt(B),Ce)for(let e of B)isSystemDoc(e)||isConfigDoc(e)||(Ce.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));e===`file`||e===`asset`?tracedUnlinkSync(F):(tracedRmSync(F,{recursive:!0,force:!1}),Ie(O)),Be();let J=D();if(J instanceof Map)for(let e of B)updateFileIndex({kind:`delete`,path:resolve(w,`${e}${getDocExtension(e)}`),docName:e},J);ae?.(`files`),successResponse(S,200,DeletePathSuccessSchema,{deletedDocNames:B},{handler:`delete-path`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),uc=withValidation(TrashCleanupRequestSchema,async(e,t,S)=>withSpan(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":S.kind,"ok.cleanup.path":normalizeFsPath(S.path),"ok.cleanup.path.role":classifyFsPath(S.path)}},async()=>{try{if(extractActorIdentity(S,me).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:E}=S;if(!isValidRelativeContentPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let O=e===`folder`&&isReservedSyntheticFolderPath(E),k=e===`asset`&&isReservedProjectStatePath(E),j=e===`asset`&&isSupportedDocFile(E);if(e===`file`&&(isSystemDoc(E)||isConfigDoc(E))||O||k||j){errorResponse(t,400,j?`urn:ok:error:invalid-request`:`urn:ok:error:reserved-doc-name`,j?`Asset operations do not support markdown documents.`:`'${E}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(e===`asset`){Be(),ae?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let F=D(),L=e===`file`?F.has(E)?[E]:[]:listAffectedDocNames(F,e,E);if(Be(),L.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Mt(L),Ce)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ce.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));let B=D();if(B instanceof Map)for(let e of L)updateFileIndex({kind:`delete`,path:resolve(w,`${e}${getDocExtension(e)}`),docName:e},B);e===`folder`&&Ie(E),ae?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:L},{handler:`trash-cleanup`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),dc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=D(),S=[];for(let[t,E]of e){let e=t,D,O=getDocExtension(t);try{let S=readFileSync(resolve(w,`${t}${O}`),`utf-8`);e=extractPageTitle(S,t),D=extractPageIcon(S)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}S.push({docName:t,title:e,docExt:O,size:E.size,modified:E.modified,icon:D})}S.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:S},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),fc=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!w){errorResponse(S,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!isSafeDocName(w)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(isSystemDoc(w)||isConfigDoc(w)){errorResponse(S,400,`urn:ok:error:reserved-doc-name`,`'${w}' is a reserved document name.`,{handler:`suggest-links`});return}successResponse(S,200,SuggestLinksSuccessSchema,await suggestLinks({hocuspocus:t,fileIndex:D(),docName:w}),{handler:`suggest-links`})}catch(e){if(e instanceof SuggestLinksTargetNotFoundError){errorResponse(S,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function pc(e,t){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let S;try{S=await readUploadBody(e,fe??w)}catch(e){if(e instanceof UploadWriteError){errorResponse(t,uploadStatusFor(e.reason),e.reason,uploadTitleFor(e.reason),{handler:`upload-asset`,cause:e});return}errorResponse(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:E,tempPath:D,sha:O,byteLength:k,parentDocName:j}=S,F=()=>{if(existsSync(D))try{unlinkSync(D)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:j},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B}=L.value,{agentId:H,agentName:q}=Fr(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(k===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(w),Y=resolveUploadDestDir(B,`./`,J);if(!isWithinContentDir(Y,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(Y,J)}catch(e){if(F(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}log$3.error({err:e,destDir:Y},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(Y,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){F();let S=classifyUploadErrno(e);errorResponse(t,uploadStatusFor(S),S,uploadTitleFor(S),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=realpathSync(Y),S;try{S=realpathSync(J)}catch{S=J}if(!isWithinContentDir(e,S)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ee=await fileTypeFromFile(D),te=ee?.mime,ne=ee?.ext;if(!te){let e=readTempFileHead(D,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(te=`image/svg+xml`,ne=`svg`)}{let S=await findDuplicateAsset(Y,O,k);if(S){F();let E=relative(w,resolve(Y,S));log$3.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,dedup:!0,mime:te??null,size:k,destPath:E,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:S,path:E,deduped:!0},{handler:`upload-asset`});return}}let ae;if(!E||E===`upload`||GENERIC_PASTE_NAMES.test(E)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=E?extname(E).slice(1):``,S=ne??t??``;ae=S===``?`pasted-${e}`:`pasted-${e}.${S}`}else ae=sanitizeFilename(E);try{let S=linkTempToFinalWithCollisionRetry(D,Y,ae),E=relative(w,resolve(Y,S));log$3.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,dedup:!1,mime:te??null,size:k,destPath:E,httpStatus:200},`[upload] write ok`),successResponse(t,200,UploadAssetSuccessSchema,{src:S,path:E,deduped:!1},{handler:`upload-asset`})}catch(S){let w=S instanceof UploadWriteError?S.reason:`urn:ok:error:storage-error`;log$3.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:H,agentName:q,filename:ae,size:k,reason:w,httpStatus:uploadStatusFor(w),err:S},`[upload] write failed`),errorResponse(t,uploadStatusFor(w),w,uploadTitleFor(w),{handler:`upload-asset`,cause:S})}}let mc=`/api/local-op/clone`,hc=`/api/local-op/open`,gc=`/api/local-op/ok-init`,_c=600*1e3,vc=45e3,yc=`local-op-clone`,bc=withValidation(LocalOpCloneRequestSchema,xc,{handler:yc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:yc})});async function xc(e,t,S){let{url:w,dir:E,branch:D}=S;if(!isAllowedGitUrl(w)){errorResponse(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:yc,cause:Error(`url=${w}`)});return}if(!isSafeLocalPath(E)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:yc,cause:Error(`dir=${E}`)});return}if(!Te.tryAcquire(mc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:yc,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let O=createStreamingErrorWriter(t,yc),k=null,j=runCloneSubprocess({cliArgs:de,url:w,dir:E,branch:D,timeoutMs:_c,onEvent:e=>{if(e.type===`complete`){k=e.dir;return}if(e.type===`error`){e.message&&log$3.warn({stderr:redactShareSubprocessStderr(e.message),url:w,dir:E},`[local-op/clone] clone failed`);let t=classifyCloneError(e.message??``);O(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(redactShareSubprocessStderr(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await j.done,k&&!t.writableEnded&&!t.destroyed){let e=await Sc(k);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:k})}\n`):O(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?O(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):log$3.error({err:e,handler:yc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Te.release(mc)}})(),t.on(`close`,()=>{j.cancel()})}async function Sc(e){let t=resolve(expandTilde(e)),S=getLocalDir(t),w=readUiLock(S);if(w&&w.port>0)return{port:w.port};let E=readServerLock(S),[D,...O]=de,k=E&&E.port>0?`ui`:`start`,j=spawn(D,[...O,k],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,OK_LOCK_KIND:`interactive`}}),F=[];j.stderr?.on(`data`,e=>{F.push(e),log$3.warn({cwd:t,cliCmd:k,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let L=null;j.on(`exit`,e=>{L=e??-1}),j.unref();let B=Date.now()+45e3;for(;Date.now()<B;){await setTimeout$1(500);let e=readUiLock(S);if(e&&e.port>0)return{port:e.port};if(L!==null){let e=Buffer.concat(F).toString(`utf-8`).trim();return{error:`\`ok ${k}\` exited (code ${L})${e?` — ${e}`:``}`}}}let H=Buffer.concat(F).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${H?` — ${H}`:``}`}}let Cc=`local-op-open`,wc=withValidation(LocalOpOpenRequestSchema,async(e,t,S)=>{let{dir:w}=S;if(!isSafeLocalPath(w)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`dir must be within the user home directory.`,{handler:Cc,cause:Error(`dir=${w}`)});return}if(!Te.tryAcquire(hc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A server-open operation is already in progress.`,{handler:Cc,extraHeaders:{"Retry-After":`5`}});return}try{let e=await Sc(w);`port`in e?successResponse(t,200,LocalOpOpenSuccessSchema,{port:e.port},{handler:Cc}):errorResponse(t,504,`urn:ok:error:server-open-failed`,`Failed to open project server.`,{handler:Cc,cause:Error(e.error)})}finally{Te.release(hc)}},{handler:Cc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Cc})}),Tc=`local-op-ok-init`,Ec=withValidation(LocalOpOkInitRequestSchema,async(e,t,S)=>{let{projectPath:w}=S;if(!isAbsolute(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:Tc,cause:Error(`projectPath=${w}`)});return}let E;try{E=realpathSync(w)}catch(e){successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:Tc});return}if(!isSafeLocalPath(E)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Tc,cause:Error(`projectPath=${w}`)});return}let D=resolveGitDirDetailed(E).kind;if(D!==`directory`&&D!==`linked`){console.warn(`[ok-init] action=init project=${basename(E)} result=not-a-git-worktree kind=${D}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${D}).`},{handler:Tc});return}if(isProjectRoot(E)){console.warn(`[ok-init] action=init project=${basename(E)} result=already-initialized`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:E},{handler:Tc});return}if(!Te.tryAcquire(gc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Tc,extraHeaders:{"Retry-After":`2`}});return}try{await withParentLock(async()=>{initContent(E)}),console.warn(`[ok-init] action=init project=${basename(E)} result=success`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!0,projectPath:E},{handler:Tc})}catch(e){let S=e instanceof Error?e.message:String(e);console.warn(`[ok-init] action=init project=${basename(E)} result=failed reason=${S}`),successResponse(t,200,LocalOpOkInitResponseSchema,{ok:!1,reason:`init-failed`,message:S},{handler:Tc})}finally{Te.release(gc)}},{handler:Tc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Tc})}),Dc=`/api/local-op/auth/login`,Oc=`/api/local-op/auth/status`,kc=`/api/local-op/auth/repos`,Ac=`/api/local-op/auth/signout`,jc=`/api/local-op/auth/pat`,Mc=null,Nc=`local-op-auth-login`,Pc=withValidation(LocalOpAuthHostRequestSchema,Fc,{handler:Nc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Nc})});async function Fc(e,t,S){let w=S.host??`github.com`;if(!Te.tryAcquire(Dc)){let e=Mc;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-login-slot-no-controller`,channel:`auth`,transport:`http`})),errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:Nc,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),Mc=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,Nc),D=runDeviceFlowSubprocess({cliArgs:de,host:w,timeoutMs:_c,onEvent:e=>{if(e.type===`error`){E(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});Mc=D;let O=()=>{D.cancel(),Mc===D&&(Mc=null,Te.release(Dc))};t.on(`close`,O),D.done.finally(()=>{if(t.off(`close`,O),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}Mc===D&&(Mc=null,Te.release(Dc))})}let Ic=`local-op-auth-status`,Lc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!Te.tryAcquire(Oc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Ic,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=de,E=[...S,`auth`,`status`,`--json`,`--host`,w],D=(await new Promise((t,S)=>{let w=spawn(e,E,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),D=!1,O=setTimeout(()=>{D=!0,w.kill(`SIGTERM`)},3e4),k=[];w.stdout.on(`data`,e=>k.push(e)),w.on(`close`,()=>{if(clearTimeout(O),D){S(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(k).toString(`utf-8`))}),w.on(`error`,e=>{clearTimeout(O),S(e)})})).split(`
2378
+ `).map(e=>e.trim()).filter(Boolean),O=null;for(let e=D.length-1;e>=0;e--)try{O=JSON.parse(D[e]);break}catch{}O===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:Ic}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,O,{handler:Ic})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:Ic,cause:e})}finally{Te.release(Oc)}},{handler:Ic,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Ic})}),Rc=`local-op-auth-repos`,zc=withValidation(LocalOpAuthHostRequestSchema,Bc,{handler:Rc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Rc})});async function Bc(e,t,S){let w=S.host??`github.com`;if(!Te.tryAcquire(kc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Rc,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,Rc),[D,...O]=de,k=[...O,`auth`,`repos`,`--json`,`--host`,w],j=!1,F=``,L=spawn(D,k,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),B=setTimeout(()=>{L.kill(`SIGTERM`)},_c);L.stdout.on(`data`,e=>{F+=e.toString(`utf-8`);let S=F.split(`
2379
+ `);F=S.pop()??``;for(let e of S){if(!e.trim())continue;let S=null;try{S=JSON.parse(e)}catch{}if(S&&S.type===`error`){E(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof S.message==`string`?S.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),L.stderr.on(`data`,e=>{log$3.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),L.on(`close`,e=>{clearTimeout(B),j||(j=!0,e!==0&&!t.writableEnded&&E(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Te.release(kc))}),L.on(`error`,e=>{clearTimeout(B),j||(j=!0,t.writableEnded||(E(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),Te.release(kc))}),t.on(`close`,()=>{j||(j=!0,clearTimeout(B),L.kill(`SIGTERM`),Te.release(kc))})}let Vc=`local-op-auth-signout`,Hc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!Te.tryAcquire(Ac)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Vc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=de,E=[...S,`auth`,`signout`,`--host`,w];await new Promise((t,S)=>{let w=spawn(e,E,{stdio:`ignore`,env:{...process.env}}),D=setTimeout(()=>{w.kill(`SIGTERM`)},3e4);w.on(`close`,()=>{clearTimeout(D),t()}),w.on(`error`,e=>{clearTimeout(D),S(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Vc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Vc,cause:e})}finally{Te.release(Ac)}},{handler:Vc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Vc})}),Uc=`local-op-auth-pat`,Wc=withValidation(LocalOpAuthPatRequestSchema,async(e,t,S)=>{let{pat:w,host:E}=S,D=E??`github.com`;if(!Te.tryAcquire(jc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth pat operation is already in progress.`,{handler:Uc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=de,E=[...S,`auth`,`pat`,`--json`,`--host`,D],O=(await new Promise((t,S)=>{let D=spawn(e,E,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),O=setTimeout(()=>{D.kill(`SIGTERM`)},3e4);D.stdin.write(`${w}\n`),D.stdin.end();let k=[];D.stdout.on(`data`,e=>k.push(e)),D.on(`close`,e=>{clearTimeout(O),e===0?t(Buffer.concat(k).toString(`utf-8`)):S(Error(`auth pat exited with code ${e}`))}),D.on(`error`,e=>{clearTimeout(O),S(e)})})).split(`
2380
+ `).map(e=>e.trim()).filter(Boolean),k=null;for(let e=O.length-1;e>=0;e--)try{k=JSON.parse(O[e]);break}catch{}k===null?successResponse(t,200,LocalOpAuthPatSuccessSchema,{},{handler:Uc}):successResponse(t,200,LocalOpAuthPatSuccessSchema,k,{handler:Uc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth pat failed.`,{handler:Uc,cause:e})}finally{Te.release(jc)}},{handler:Uc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Uc})}),Gc=`local-op-auth-identity`;async function Kc(e,t){if(checkLocalOpSecurity(e,t,{handler:Gc})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:Gc,extraHeaders:{Allow:`GET`}});return}if(!fe){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Gc});return}try{successResponse(t,200,LocalOpAuthIdentitySuccessSchema,{identity:await resolveGitIdentity(fe)},{handler:Gc})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Identity resolution failed.`,{handler:Gc,cause:e})}}}let qc=`/api/local-op/auth/set-identity`,Jc=`local-op-auth-set-identity`,Yc=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,S)=>{let w=S.name.trim(),E=S.email.trim();if(!fe){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Jc});return}if(!Te.tryAcquire(qc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Jc,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(fe,w,E),ue?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Jc})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Jc,cause:e})}finally{Te.release(qc)}},{handler:Jc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Jc})});async function Xc(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ue?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Zc=withValidation(SyncTriggerRequestSchema,async(e,t,S)=>{let w=ue?.();if(!w){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let E=S.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:E},{handler:`sync-trigger`}),w.trigger(E)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ue?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Qc(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ue?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let $c=withValidation(SyncResolveConflictRequestSchema,async(e,t,S)=>{let w=ue?.();if(!w){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:E,strategy:D,content:O}=S;try{await w.resolveConflict(E,D,O),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ue?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function nl(e,S){if(!checkLocalOpSecurity(e,S,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(S,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!fe){errorResponse(S,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=w.searchParams.get(`file`);if(!E){errorResponse(S,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(E.includes(`..`)||E.startsWith(`/`)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let D=stripDocExtension(E),O=t.documents.get(D)?.getMap(`lifecycle`).get(`status`)===`conflict`,k=ue?.(),j=k?k.getConflicts().some(e=>e.file===E):!1;if(!O&&!j){errorResponse(S,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:E}});return}let F=w.searchParams.get(`source`),L=esm_default({baseDir:fe,timeout:{block:15e3}});async function B(e){try{return{present:!0,content:await L.raw([`show`,`:${e}:${E}`])}}catch(t){let S=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(S))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:E,detail:S,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,w,D]=await Promise.all([B(1),B(2),B(3)]),O=e.present?e.content:``,k=D.present?D.content:``,j=w.present&&D.present?`both-modified`:!w.present&&D.present?`delete-modify`:w.present&&!D.present?`modify-delete`:`both-modified`,L=w.present?w.content:``,H=null;if(F===`ytext`){let e=stripDocExtension(E),S=t.documents.get(e);if(S){let t=S.getMap(`lifecycle`).get(`status`);if(H=typeof t==`string`&&t.length>0?t:null,j!==`delete-modify`){let t=we?we(e):null;t!==null&&!ytextHasConflictMarkers(t)?L=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(S,200,SyncConflictContentSuccessSchema,{file:E,base:O,ours:L,theirs:k,kind:j,lifecycleStatus:H},{handler:`sync-conflict-content`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function il(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let S=new URL(e.url??`/`,`http://localhost`),E=S.searchParams.get(`rootDir`)??void 0,D=S.searchParams.get(`packId`),O=coercePackId(D);if(D!==null&&D!==``&&O===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${D}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:w,rootDir:E,packId:O})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let al=withValidation(SeedApplyRequestSchema,async(e,t,S)=>{let E=S.plan;if(!E||typeof E!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let D=E,O=S.packId,k=coercePackId(O);if(typeof O==`string`&&O.length>0&&k===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${O}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(D,{projectDir:w,packId:k})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function cl(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let ll=withValidation(InstallSkillRequestSchema,async(e,t,S)=>{if(S.out!==void 0&&!isSafeLocalPath(S.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...S.noOpen===void 0?{}:{noOpen:S.noOpen},...S.out===void 0?{}:{out:S.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function ul(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Ve.probeAll)}catch(e){t.headersSent||(log$3.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}async function dl(e,t){if(!checkLocalOpSecurity(e,t,{handler:`sync-abort-merge`}))return;if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-abort-merge`,extraHeaders:{Allow:`POST`}});return}let S=ue?.();if(!S){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-abort-merge`});return}try{await S.abortMerge(),successResponse(t,200,SyncAbortMergeSuccessSchema,{},{handler:`sync-abort-merge`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to abort merge.`,{handler:`sync-abort-merge`,cause:e})}}let fl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ne){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:ne.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function pl(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!ne){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let w;try{w=decodeURIComponent(S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=ne.getDocsForTagWithMatches(w).map(({docName:e,matchingTags:t})=>({docName:e,title:We(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:w,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function ml(e,t,S=`path`,E=`folder-config`){let D=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(D.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${S}: must be project-root-relative.`,{handler:E}),null;let O=resolve(w),k=D===``?O:resolve(O,D);return k!==O&&!k.startsWith(`${O}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:E}),null):{folderRel:D,resolvedContentDir:O}}let hl=/^[A-Za-z0-9_-]+$/;function gl(e,t,S=`template`){return!e||!hl.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:S}),!1):!0}function _l(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[S,w]of Object.entries(e))w!==void 0&&(t[S]=w);return t}function vl(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return{patch:t,badField:null};for(let[S,w]of Object.entries(e)){if(w===void 0)continue;if(w===null){t[S]=null;continue}let e=DeclarationSchema.safeParse(w);if(!e.success)return{patch:null,badField:S};t[S]=e.data}return{patch:t,badField:null}}async function yl(e,t){if(e.method===`GET`)return xl(e,t);if(e.method===`PUT`)return Cl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let xl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=ml(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!S)return;let w=await enrichDirectory(S.folderRel,{projectDir:S.resolvedContentDir}),E=resolve(S.resolvedContentDir,S.folderRel,`.ok`),D=resolve(E,`frontmatter.yml`),O=null;if(existsSync(D))try{let e=(0,import_dist$1.parse)(await readFile$1(D,`utf-8`));O=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${D}: ${t}`),O=null}let k=resolveNestedFrontmatterWithSources(S.resolvedContentDir,S.folderRel),j=resolve(E,`schema.yml`),F=null;if(existsSync(j))try{let e=(0,import_dist$1.parse)(await readFile$1(j,`utf-8`)),t=FolderSchemaSchema.safeParse(e);t.success?F=t.data.declarations:(console.warn(`[ok-folder-schema] invalid shape at ${j}: ${t.error.message}`),F=null)}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[ok-folder-schema] malformed YAML in ${j}: ${t}`),F=null}let L=Object.keys(k.declarations).length>0;successResponse(t,200,FolderConfigGetSuccessSchema,{folder:w,frontmatter_local:O,...Object.keys(k.sources).length>0?{frontmatter_sources:k.sources}:{},...L?{schema_declarations:k.declarations,schema_sources:k.declarationSources}:{},schema_local:F},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),Cl=withValidation(FolderConfigPutRequestSchema,async(e,t,S)=>{try{let e=ml(S.path,t,`path`,`folder-config-put`);if(!e)return;let w=e.folderRel===``?`**`:`${e.folderRel}/**`,E;if(S.declarations!==void 0){let e=vl(S.declarations);if(e.patch===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid declaration for field "${e.badField}": must be { type: text|number|boolean|date|list } or null.`,{handler:`folder-config-put`,detail:`INVALID_DECLARATION`});return}E=e.patch}let D=[];if(S.frontmatter!==void 0){let E=applyNestedFolderRulesUpsert({projectDir:e.resolvedContentDir,rules:[{match:w,frontmatter:_l(S.frontmatter)}]});if(!E.ok){let e=E.error.code===`WRITE_ERROR`||E.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:`Invalid folder config request.`,{handler:`folder-config-put`,detail:E.error.code,cause:Error(E.error.message)});return}D.push(...E.applied)}if(E!==void 0&&Object.keys(E).length>0){let S=applyNestedFolderSchemaUpsert({projectDir:e.resolvedContentDir,rules:[{match:w,declarations:E}]});if(!S.ok){let e=S.error.code===`WRITE_ERROR`||S.error.code===`BAD_PROJECT_DIR`?500:400,w=e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,E=e===500?`Failed to write folder schema.`:`Invalid folder schema request.`,O=D.length>0?{partiallyApplied:D}:void 0;errorResponse(t,e,w,E,{handler:`folder-config-put`,detail:S.error.code,cause:Error(S.error.message),...O?{extensions:O}:{}});return}D.push(...S.applied)}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:D},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function Tl(e,S,w,E){if(!S)return!1;let D=e===``?`.ok/templates/${S}`:`${e.replace(/\/$/,``)}/.ok/templates/${S}`,O=t.documents.get(D);return O&&isDocInConflict(O)?(respondDocInConflict(E,new DocInConflictError({file:`${D}.md`}),w),!0):!1}async function El(e,t){if(e.method===`GET`)return kl(e,t);if(e.method===`PUT`)return jl(e,t);if(e.method===`DELETE`)return Ml(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Dl=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Ol=e=>{let t=e.match(Dl),S={},w=e;if(t){try{let e=(0,import_dist$1.parse)(t[1]??``);e&&typeof e==`object`&&!Array.isArray(e)&&(S=e)}catch{}w=e.slice(t[0].length)}return{frontmatter:S,body:w}},kl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!gl(w,t,`template-get`))return;let E=ml(S.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!E)return;let{folderRel:D,resolvedContentDir:O}=E,k=D===``?[]:D.split(`/`),j=null,F=null,L=null;for(let e=k.length;e>=0;e--){let t=e===0?``:k.slice(0,e).join(`/`),S=t===``?O:resolve(O,t);if(S!==O&&!S.startsWith(`${O}${sep}`))continue;let E=resolve(S,`.ok`,`templates`,`${w}.md`);if(existsSync(E)){j=E,F=t,L=e===k.length?`local`:`inherited`;break}}if(!j||F===null||L===null){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${w}" not found for folder "${D||`.`}". Walked leaf → root.`});return}let{frontmatter:B,body:H}=Ol(await readFile$1(j,`utf-8`)),q=relative(O,j).split(/[\\/]/).filter(Boolean).join(`/`);successResponse(t,200,TemplateGetSuccessSchema,{template:{name:w,folder:F,scope:L,path:q,frontmatter:B,body:H}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),jl=withValidation(TemplatePutRequestSchema,async(e,t,S)=>{try{let e=S.name;if(!gl(e,t,`template-put`))return;let w=ml(S.folder,t,`folder`,`template-put`);if(!w||Tl(w.folderRel,e,`template-put`,t))return;let E=applyTemplateWrite({projectDir:w.resolvedContentDir,folder:w.folderRel,name:e,body:typeof S.body==`string`?S.body:``,frontmatter:_l(S.frontmatter)});if(!E.ok){let e=E.error.code===`WRITE_ERROR`||E.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write template.`:`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}successResponse(t,200,TemplatePutSuccessSchema,{path:E.path,created:E.created,warnings:E.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),Ml=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!gl(w,t,`template-delete`))return;let E=ml(S.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!E||Tl(E.folderRel,w,`template-delete`,t))return;let D=applyTemplateDelete({projectDir:E.resolvedContentDir,folder:E.folderRel,name:w});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0});function Pl(e){let t=new Map;for(let S of e){let e=S.path.split(`/`).filter(Boolean);e.pop();for(let w=1;w<=e.length;w++){let E=e.slice(0,w).join(`/`);t.set(E,Math.max(t.get(E)??0,S.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function Fl(e,t){let S=t.trim().toLowerCase();if(!S||!e)return;let w=e.toLowerCase().indexOf(S);if(w<0)return;let E=Math.max(0,w-80),D=Math.min(e.length,w+S.length+120),O=E>0?`…`:``,k=D<e.length?`…`:``;return`${O}${e.slice(E,D).replace(/\s+/g,` `).trim()}${k}`}function Il(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Ll(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let S=t.filter(e=>e===`page`||e===`folder`||e===`content`);return S.length>0?S:void 0}async function Rl(){let e=[];for(let[t,S]of D()){if(isSystemDoc(t)||isConfigDoc(t))continue;let w=``,E=t;try{w=await readFile$1(S.canonicalPath,`utf-8`),E=extractPageTitle(w,t)}catch(e){console.warn(`[search] Failed to index ${t}:`,e)}e.push(createWorkspaceSearchDocument({kind:`page`,path:t,title:E,content:w,modifiedTs:Date.parse(S.modified)}))}return[...e,...Pl(e)]}function zl(){return[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}${t.modified}${t.size}${t.canonicalPath}${t.inode}${t.aliases.join(`,`)}`).join(``)}async function Bl(){let e=`${w}${fe??``}`,t=zl(),S=workspaceSearchCaches.get(e);if(S?.fingerprint===t&&S.corpus)return S.corpus;if(S?.fingerprint===t&&S.pending)return S.pending;let E=Rl().then(e=>createWorkspaceSearchCorpus(e));workspaceSearchCaches.set(e,{fingerprint:t,pending:E});try{let S=await E;return workspaceSearchCaches.get(e)?.pending===E&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:S}),S}catch(t){throw workspaceSearchCaches.get(e)?.pending===E&&workspaceSearchCaches.delete(e),t}}function Vl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{Bl().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}Vl();async function Hl(e,t){if(e.method===`GET`)return Ul(e,t);if(e.method===`POST`)return Wl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let Ul=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`limit`),E=S.searchParams.get(`query`)??``,D=Il(S.searchParams.get(`intent`)),O=Ll(S.searchParams.get(`scope`)??S.searchParams.get(`scopes`)),k=w===null?void 0:Number(w);if(E.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:E,intent:D,results:searchWorkspaceCorpus(await Bl(),E,{intent:D,scopes:O,limit:k}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Fl(e.document.content,E):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),Wl=withValidation(SearchRequestSchema,async(e,t,S)=>{let w=typeof S.query==`string`?S.query:``,E=Il(S.intent),D=Ll(S.scopes??S.scope),O=typeof S.limit==`number`?S.limit:void 0;if(w.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:w,intent:E,results:searchWorkspaceCorpus(await Bl(),w,{intent:E,scopes:D,limit:O}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Fl(e.document.content,w):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),Gl=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function Kl(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$3.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function ql(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$3.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let Jl=withValidation(ShareConstructUrlRequestSchema,async(e,t,S)=>{try{if(!fe){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!isValidShareDocPath(S.docPath)){emitShareConstructUrlLog(`invalid-path`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=readGitHeadBranch(fe);if(e===null){if(readOriginGitHubRepo(fe).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=readOriginGitHubRepo(fe);if(w.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(w.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(fe,e)){emitShareConstructUrlLog(`branch-not-on-origin`,!1),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let E=buildGitHubBlobUrl(w.owner,w.repo,e,S.docPath),D=`${SHARE_BASE_URL}${encodeShareUrl(E)}`;emitShareConstructUrlLog(`ok`,!0),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:D,blobUrl:E,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}),Yl=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!fe){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`branch`),E=S.searchParams.get(`path`);if(!isValidBranchName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoDocPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(fe,w,E),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),Xl=withValidation(CheckoutRequestSchema,async(e,t,S)=>{if(extractActorIdentity(S,me).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!fe){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(fe,S.branch)),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function Zl(e){let[t,...S]=de,w=[...S,...e];return await new Promise((e,S)=>{let E=spawn(t,w,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),D=!1,O=setTimeout(()=>{D=!0,E.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),k=[],j=[];E.stdout.on(`data`,e=>k.push(e)),E.stderr.on(`data`,e=>j.push(e)),E.on(`close`,t=>{if(clearTimeout(O),D){S(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let w=Buffer.concat(k).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(j).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:w,code:t})}),E.on(`error`,e=>{clearTimeout(O),S(e)})})}let Ql=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Te.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Zl([`share`,`owners`,`--json`]),S=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,S.ok?`ok`:S.error,S.ok?{count:S.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,S,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{Te.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),$l=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`owner`)??``,E=S.searchParams.get(`name`)??``;if(!isValidShareOwnerName(w)||!isValidShareRepoName(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!Te.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Zl([`share`,`name-check`,`--owner`,w,`--name`,E,`--json`]),S=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,S.ok?`ok`:S.error,S.ok?{available:S.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,S,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{Te.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),eu=withValidation(SharePublishRequestSchema,async(e,t,S)=>{if(!fe){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(S.owner)||!isValidShareRepoName(S.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!Te.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,S.owner,`--name`,S.name,`--visibility`,S.visibility,`--project-dir`,fe,`--json`];S.description!==void 0&&S.description.length>0&&e.push(`--description`,S.description);let{stdout:w}=await Zl(e),E=parsePublishEvent(pickTerminalJsonLine(w));emitSharePublishLog(`publish-create`,E.ok?`ok`:E.error),successResponse(t,200,SharePublishResponseSchema,E,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{Te.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),tu={"/api/asset":Rs,"/api/asset-text":ec,"/api/document":Kr,"/api/documents":qr,"/api/backlinks":Jr,"/api/backlink-counts":Yr,"/api/forward-links":Xr,"/api/link-graph":Zr,"/api/dead-links":Hi,"/api/orphans":Qr,"/api/hubs":ji,"/api/tags":fl,"/api/pages":dc,"/api/folder-config":yl,"/api/template":El,"/api/search":Hl,"/api/suggest-links":fc,"/api/page-headings":sc,"/api/create-page":ic,"/api/create-folder":ac,"/api/duplicate-path":oc,"/api/rename-path":cc,"/api/delete-path":lc,"/api/trash/cleanup":uc,"/api/upload":pc,"/api/agent-write":Hr,"/api/agent-write-md":Ur,"/api/frontmatter-patch":Wr,"/api/agent-patch":Ui,"/api/agent-undo":Gi,"/api/agent-activity":Ki,"/api/agent-burst-diff":Yi,"/api/save-version":_s,"/api/history":xs,"/api/diff":Ts,"/api/rollback":Ds,"/api/metrics/reconciliation":Os,"/api/metrics/parse-health":ks,"/api/metrics/agent-presence":Ps,"/api/server-info":As,"/api/share/construct-url":Jl,"/api/git/branch-info":Yl,"/api/git/checkout":Xl,"/api/share/publish/owners":Ql,"/api/share/publish/name-check":$l,"/api/share/publish":eu,"/api/principal":Ns,"/api/rescue":nc,"/api/workspace":Is,"/api/sync/status":Xc,"/api/sync/trigger":Zc,"/api/sync/conflicts":Qc,"/api/sync/conflict-content":nl,"/api/sync/resolve-conflict":$c,"/api/sync/abort-merge":dl,"/api/local-op/clone":bc,"/api/local-op/open":wc,"/api/local-op/ok-init":Ec,"/api/local-op/auth/login":Pc,"/api/local-op/auth/status":Lc,"/api/local-op/auth/repos":zc,"/api/local-op/auth/signout":Hc,"/api/local-op/auth/pat":Wc,"/api/local-op/auth/identity":Kc,"/api/local-op/auth/set-identity":Yc,"/api/installed-agents":ul,"/api/spawn-cursor":ql,"/api/handoff":Kl,"/api/install-skill":ll,"/api/skill/install-state":Gl,"/api/seed/plan":il,"/api/seed/apply":al,"/api/seed/packs":cl};L&&(tu[`/api/test-reset`]=Xi,tu[`/api/test-rescan-backlinks`]=Zi,tu[`/api/test-rescan-files`]=ka);let nu=new Set([`/api/upload`,`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/agent-write`,`/api/agent-write-md`,`/api/frontmatter-patch`,`/api/agent-patch`,`/api/agent-undo`,`/api/save-version`,`/api/rollback`,`/api/sync/trigger`,`/api/sync/resolve-conflict`,`/api/sync/abort-merge`,`/api/git/checkout`,`/api/test-reset`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`,`/api/install-skill`,`/api/folder-config`,`/api/template`,`/api/seed/apply`]),ru=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let S=e.url?.split(`?`)[0];if(!S)return;if(S.startsWith(`/api/`)){let S=e.headers.origin;if(S!==void 0&&!isAllowedApiOrigin(S)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(S!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,S),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(nu.has(S)||ru.some(e=>S.startsWith(e))){let S=e.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(!S.startsWith(`/api/`))return;let w=propagation.extract(context.active(),e.headers),E=e.method??`GET`,D=S;S.startsWith(`/api/rescue/`)?D=`/api/rescue/:docName`:S.startsWith(`/api/history/`)?D=`/api/history/:sha`:S.startsWith(`/api/tags/`)?D=`/api/tags/:name`:tu[S]||(D=`/api/*`);let O=getTracer(),k=Date.now();await context.with(w,()=>O.startActiveSpan(`HTTP ${E} ${D}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:E,[ATTR_HTTP_ROUTE]:D,[ATTR_URL_PATH]:S,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async w=>{try{let D=tu[S],O=!1;if(D)O=!0,await D(e,t);else if(S.startsWith(`/api/rescue/`)){let w=decodeURIComponent(S.slice(12));w&&(O=!0,await rc(e,t,w))}else if(S.startsWith(`/api/history/`)){let w=decodeURIComponent(S.slice(13));w&&(O=!0,await Cs(e,t,w))}else if(S.startsWith(`/api/tags/`)){let w=S.slice(10);w&&(O=!0,await pl(e,t,w))}O||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${E} ${S}`});let k=t.statusCode;w.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,k),k>=500&&w.setStatus({code:SpanStatusCode.ERROR,message:`status ${k}`})}catch(e){throw w.recordException(e),w.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:D,cause:e}),e}finally{w.end();let e=(Date.now()-k)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:E,[ATTR_HTTP_ROUTE]:D,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function isWithinDir(e,t){return e===t?!0:e.startsWith(`${t}${sep}`)}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedBasenameIndex(e){let t=e.contentDir,S=new Set;function w(E){let D;try{D=readdirSync(E,{withFileTypes:!0})}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`read-failed`,S,E);return}for(let O of D){let D=join(E,O.name),k=relative(t,D);if(k.startsWith(`..`)||e.contentFilter?.isDirExcluded(k)&&O.isDirectory())continue;let j;try{j=lstatSync(D)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`lstat-failed`,S,D);continue}if(j.isSymbolicLink()){let E;try{E=realpathSync(D)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`realpath-failed`,S,D);continue}if(!isWithinDir(E,t)){e.onSkip?.(`symlink-escape`,void 0,D);continue}let O;try{O=statSync(E)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,S,E);continue}if(S.has(O.ino))continue;S.add(O.ino),O.isDirectory()?w(E):O.isFile()&&isSupportedAssetFile(D,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(k)&&e.basenameIndex.add(k);continue}if(j.isDirectory()){if(S.has(j.ino))continue;S.add(j.ino),w(D);continue}j.isFile()&&isSupportedAssetFile(D,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(k)&&e.basenameIndex.add(k)}}w(t)}const HocuspocusAuthTokenSchema=object$1({principalId:string$2().optional(),tabSessionId:string$2().optional(),expectedServerInstanceId:string$2().optional(),expectedBranch:string$2().optional()}).loose(),HOCUSPOCUS_AUTH_REJECTION_REASONS=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`];function isHocuspocusAuthRejectionReason(e){return HOCUSPOCUS_AUTH_REJECTION_REASONS.includes(e)}const WIRE_PAYLOAD_SEPARATOR=`:`;function formatAuthRejectionWire(e,t){return typeof t!=`string`||t.length===0?e:`${e}${WIRE_PAYLOAD_SEPARATOR}${t}`}function parseAuthRejectionWire(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(WIRE_PAYLOAD_SEPARATOR),S=t===-1?e:e.slice(0,t);if(!isHocuspocusAuthRejectionReason(S))return{kind:null,payload:void 0};if(t===-1)return{kind:S,payload:void 0};let w=e.slice(t+1);return{kind:S,payload:w.length>0?w:void 0}}var HocuspocusAuthRejection=class extends Error{kind;payload;reason;constructor(e,t,S){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof S==`string`&&S.length>0?S:void 0,this.reason=formatAuthRejectionWire(e,this.payload)}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let S=HocuspocusAuthTokenSchema.safeParse(t);return S.success?S.data:void 0}const log$2=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$2.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$2.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$2.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,S,w=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&S===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:E}=await import(`./git-handle-BJwB5EBp-D5YTDzvd.mjs`),D=E(this.projectDir,{credentialArgs:w});switch(t){case`mine`:await D.git.raw([`checkout`,`--ours`,`--`,e]),await D.git.raw([`add`,`--`,e]);break;case`theirs`:await D.git.raw([`checkout`,`--theirs`,`--`,e]),await D.git.raw([`add`,`--`,e]);break;case`content`:{if(S===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),w=resolve(t,e);if(w!==t&&!w.startsWith(`${t}/`))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(w,S,`utf-8`),await D.git.raw([`add`,`--`,e]);break}case`delete`:await D.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await D.git.raw([`commit`,`--no-edit`]),log$2.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let S=new Date().toISOString(),w=!1;try{let e=(await D.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
2381
2381
  `).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:S});w=e.length>0}catch(e){log$2.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}w||this.addConflict({file:e,detectedAt:S}),log$2.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let E=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${w?`unmerged files re-added`:`original file re-added`} — ${E}`,{cause:t})}}};const MIN_GIT_VERSION=`2.31.0`,PROBE_TIMEOUT_MS$1=5e3;var GitNotAvailableError=class extends Error{code=`GIT_NOT_AVAILABLE`;platform;guidance;constructor(e,t,S){super(buildMissingMessage(t),S),this.name=`GitNotAvailableError`,this.platform=e,this.guidance=t}},GitTooOldError=class extends Error{code=`GIT_TOO_OLD`;platform;detected;required;resolvedPath;guidance;constructor(e,t,S,w,E,D){super(buildTooOldMessage(t,S,w,E),D),this.name=`GitTooOldError`,this.platform=e,this.detected=t,this.required=S,this.resolvedPath=w,this.guidance=E}};function detectGit(){let e=probeGit(`git`);if(e.kind===`ok`)return{ok:!0,version:e.version,resolvedPath:e.resolvedPath,source:`PATH`};for(let e of fallbackPaths(process.platform)){if(!existsSync(e))continue;let t=probeGit(e);if(t.kind===`ok`)return{ok:!0,version:t.version,resolvedPath:e,source:`fallback`}}throw new GitNotAvailableError(process.platform,buildGuidance(process.platform))}function assertGitAvailable(){let e=detectGit();if(compareSemver(e.version,`2.31.0`)<0)throw new GitTooOldError(process.platform,e.version,MIN_GIT_VERSION,e.resolvedPath,buildGuidance(process.platform));return e}function probeGit(e){let t=spawnSync(e,[`--version`],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1,env:{...process.env,LANG:`C`,LC_ALL:`C`}});if(t.error)return`signal`in t&&t.signal===`SIGTERM`?{kind:`fail`,reason:`timeout`}:{kind:`fail`,reason:`enoent`};if(t.status!==0)return{kind:`fail`,reason:`nonzero`};let S=parseGitVersion(typeof t.stdout==`string`?t.stdout:``);return S===null?{kind:`fail`,reason:`unparseable`}:{kind:`ok`,version:S,resolvedPath:e===`git`?resolveOnPath(`git`)??e:e}}function parseGitVersion(e){let t=e.match(/git version (\d+)\.(\d+)\.(\d+)/);return t?`${t[1]}.${t[2]}.${t[3]}`:null}const SAFE_COMMAND_NAME_RE=/^[a-zA-Z0-9_.-]+$/,resolveOnPathCache=new Map;function resolveOnPath(e){if(!SAFE_COMMAND_NAME_RE.test(e))return null;let t=resolveOnPathCache.get(e);if(t!==void 0)return t;let S;if(process.platform===`win32`){let t=spawnSync(`where`,[e],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1});S=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}else{let t=spawnSync(`/bin/sh`,[`-c`,`command -v ${e}`],{encoding:`utf-8`,timeout:PROBE_TIMEOUT_MS$1});S=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}return S!==null&&resolveOnPathCache.set(e,S),S}function fallbackPaths(e){switch(e){case`darwin`:return[`/opt/homebrew/bin/git`,`/usr/local/bin/git`,`/Library/Developer/CommandLineTools/usr/bin/git`,`/usr/bin/git`];case`win32`:return[`C:\\Program Files\\Git\\cmd\\git.exe`,`C:\\Program Files (x86)\\Git\\cmd\\git.exe`,join(homedir(),`scoop`,`apps`,`git`,`current`,`cmd`,`git.exe`)];default:return[`/usr/bin/git`,`/usr/local/bin/git`,join(homedir(),`.local`,`bin`,`git`),`/snap/bin/git`]}}function buildGuidance(e){switch(e){case`darwin`:{let e=[];return hasBrew()&&e.push({label:`Install with Homebrew (recommended; no admin needed)`,command:`brew install git`,requiresAdmin:!1}),e.push({label:`Install Xcode Command Line Tools`,command:`xcode-select --install`,requiresAdmin:!0}),{product:`Git`,url:`https://git-scm.com/download/mac`,options:e}}case`win32`:{let e=[];return hasWinget()&&e.push({label:`Install with winget`,command:`winget install --id Git.Git -e --source winget`,requiresAdmin:!0}),hasScoop()&&e.push({label:`Install with Scoop (no admin)`,command:`scoop install git`,requiresAdmin:!1}),hasChoco()&&e.push({label:`Install with Chocolatey`,command:`choco install git -y`,requiresAdmin:!0}),e.push({label:`Download the official installer`,command:`Open https://gitforwindows.org/ in your browser`,requiresAdmin:!1}),{product:`Git for Windows`,url:`https://gitforwindows.org/`,options:e}}default:return{product:`Git`,url:`https://git-scm.com/download/linux`,options:linuxInstallOptions()}}}function linuxInstallOptions(){switch(detectLinuxFamily()){case`debian`:return[{label:`Install with apt`,command:`sudo apt install git`,requiresAdmin:!0}];case`fedora`:return[{label:`Install with dnf`,command:`sudo dnf install git`,requiresAdmin:!0}];case`arch`:return[{label:`Install with pacman`,command:`sudo pacman -S git`,requiresAdmin:!0}];case`opensuse`:return[{label:`Install with zypper`,command:`sudo zypper install git`,requiresAdmin:!0}];case`alpine`:return[{label:`Install with apk`,command:`sudo apk add git`,requiresAdmin:!0}];default:return[{label:`Use your distribution's package manager`,command:`apt / dnf / pacman / zypper / apk install git (one of these will fit your system)`,requiresAdmin:!0}]}}function detectLinuxFamily(e){let t=e;if(t===void 0)try{t=readFileSync(`/etc/os-release`,`utf-8`)}catch{return`unknown`}let S=[/^ID=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``),...(/^ID_LIKE=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``)??``).split(/\s+/)].filter(e=>!!e);return S.some(e=>/^(debian|ubuntu|mint|pop)$/i.test(e))?`debian`:S.some(e=>/^(fedora|rhel|centos|alma|rocky)$/i.test(e))?`fedora`:S.some(e=>/^(arch|manjaro|endeavouros)$/i.test(e))?`arch`:S.some(e=>/^opensuse/i.test(e))||S.includes(`suse`)?`opensuse`:S.some(e=>/^alpine$/i.test(e))?`alpine`:`unknown`}function hasCommand(e){return resolveOnPath(e)!==null}function hasBrew(){return hasCommand(`brew`)}function hasWinget(){return hasCommand(`winget`)}function hasScoop(){return hasCommand(`scoop`)}function hasChoco(){return hasCommand(`choco`)}function buildMissingMessage(e){let t=[];if(t.push(`Open Knowledge needs ${e.product} to track changes to your knowledge base, but it isn't installed (or isn't on PATH).`),t.push(``),e.options.length>0){t.push(`Install ${e.product}:`);for(let S of e.options){let e=S.requiresAdmin?` (admin required)`:``;t.push(` • ${S.label}${e}`),t.push(` ${S.command}`)}t.push(``)}return t.push(`Or download from: ${e.url}`),t.push(``),t.push(`After installing, re-run Open Knowledge.`),t.push("Run `ok diagnose health --check git` to verify your installation."),t.join(`
2382
2382
  `)}function buildTooOldMessage(e,t,S,w){let E=[];if(E.push(`Open Knowledge requires ${w.product} ${t} or newer (detected ${e} at ${S}).`),E.push(``),w.options.length>0){E.push(`Update ${w.product}:`);for(let e of w.options){let t=e.requiresAdmin?` (admin required)`:``;E.push(` • ${e.label}${t}`),E.push(` ${e.command}`)}E.push(``)}return E.push(`Or download from: ${w.url}`),E.push(``),E.push(`After updating, re-run Open Knowledge.`),E.push("Run `ok diagnose health --check git` to verify your installation."),E.join(`
2383
2383
  `)}function compareSemver(e,t){let S=e.split(`.`).map(e=>Number.parseInt(e,10)||0),w=t.split(`.`).map(e=>Number.parseInt(e,10)||0);for(let e=0;e<3;e++){let t=S[e]??0,E=w[e]??0;if(t!==E)return t-E}return 0}const GIT_PREFLIGHT_FAIL_SPAN_NAME=`ok.preflight.git.fail`;function emitPreflightFailureSpan(e){let t=e instanceof GitTooOldError?`too_old`:`not_available`,S=e instanceof GitTooOldError?e.detected:``;withSpanSync(GIT_PREFLIGHT_FAIL_SPAN_NAME,{attributes:{"ok.platform":e.platform,"ok.preflight.git.reason":t,"ok.preflight.git.detected_version":S}},()=>{})}const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,S=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,w=0,E=null,D=null,O=!1,k=!1;function j(){E!==null&&(t.clearTimeout(E),E=null),D!==null&&(t.clearTimeout(D),D=null)}function F(){j(),!(k||O)&&w===0&&(S>0&&S<e.thresholdMs&&(D=t.setTimeout(()=>{D=null,w===0&&!O&&e.log?.warn({msUntilShutdown:S,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-S)),E=t.setTimeout(()=>{if(E=null,!(k||O)&&w===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 L=(e,t)=>{e.url?.startsWith(`/collab`)&&(w++,j(),t.once(`close`,()=>{w--,w<0&&(w=0),w===0&&F()}))};return e.httpServer.on(`upgrade`,L),F(),{detach:()=>{k||(k=!0,e.httpServer.off(`upgrade`,L),j())}}}const MCP_SERVER_NAME=`open-knowledge`,MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let S=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return S?S.slice(0,128):t}function buildInstructions(e){return'Open Knowledge is a markdown-CRDT knowledge base exposed via MCP.\n\n## STOP — native tools on in-scope `.md` / `.mdx`\n\nWhen this workspace has Open Knowledge MCP configured, do **not** use your host\'s native file tools on markdown paths inside the content directory. The ban covers every common rationalization:\n\n- **Native `Read` / `Grep` / `Glob` on in-scope `.md` / `.mdx`** — the original case.\n- **`Bash ls` / `Bash find` / `Bash cat` on dirs containing in-scope markdown** — use `exec("ls -A …")` / `exec("find … -name \'*.md\'")` / `exec("cat …")` instead. Native returns bare names; `exec` returns frontmatter, backlink counts, and recent activity per child. `-A` shows hidden entries (`.ok/`, `.okignore`) which OK projects carry; omit `.` and `..` rows that `-a` would add.\n- **Glob patterns that target markdown** (`**/*.md`, any dir known to be markdown-heavy like `specs/**`, `reports/**`, `docs/**`) — use `exec` with `find`, or `exec("ls -A <dir>")`.\n- **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native `Read` / `Grep` / `Glob` internally and bypass Open Knowledge entirely. Do markdown exploration yourself via `exec` / `search`. Subagents remain appropriate for **source-code** exploration.\n- **Native `Read` / `Grep` on any in-scope markdown inside `.ok/`** — the `.ok/` directory is in-scope; if it carries `.md` / `.mdx`, treat those the same as any other knowledge-base file.\n\nWhy: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK\'s tools return for every matched knowledge-base file. `exec` is the primary read surface; it runs read-only bash (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut` — pipes OK) and returns raw stdout plus enriched metadata per file.\n\n**MCP tool visibility — not seeing `exec` is NOT the escape hatch.** MCP wiring varies by client. Claude Code, Cursor, Codex, Windsurf, VS Code — each surfaces MCP differently. Server labels are user-defined; tools may not appear as top-level symbols named `exec` in your specific UI. If Open Knowledge is registered as an MCP server in this workspace, route markdown reads through its `exec` / `search` via your client\'s documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.\n\n**Escape hatch.** Native `Read` / `Grep` / `Glob` on `.md` / `.mdx` is allowed **only** when no Open Knowledge MCP server is registered for this project, **or** immediately after you tried an MCP call and it failed — then begin a user-visible sentence with `Open Knowledge MCP unavailable:`. Never use the hatch because you skipped your client\'s MCP path, didn\'t see `exec` as a top-level tool, or rationalized the skill wasn\'t necessary.\n\n**Source code and non-markdown files** (`.ts`, `.py`, `package.json`, …): native `Read` / `Grep` / `Glob` always.\n\n## Reads — examples\n\n- Read a file: `exec("cat <path>.md")` — contents + full rich enrichment.\n- List a directory: `exec("ls -A <dir>")` — per-child frontmatter, recursive markdown counts, most-recently-updated doc per subdir, folder-level `frontmatter_defaults` + `templates_available`. Prefer `-A` over plain `ls` to surface dot-prefixed entries (`.ok/`, `.okignore`) without the noisy `.`/`..` rows that `-a` adds.\n- Literal search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files.\n- Ranked search: `search({ query })` — cmd-K parity (title boost + body BM25 + recency); use when picking the best doc, not when listing every occurrence.\n\n## Preview — open the browser at session start\n\nThe user watches your edits land in a live browser preview. Open it once at session start, then keep working. Re-navigate only when the user asks to open a different doc, or to land them on a finished deliverable (see below) — not to re-check your own edits.\n\n**End a turn on the deliverable, not your scratch space.** Keep the preview steady *during* a multi-doc task — don\'t yank it around to re-check your own edits. But when a turn created or substantially changed user-facing docs, navigate the preview to the primary deliverable before you hand back: the hub / overview / index page when you created several docs, or the changed doc when you changed one. Don\'t step the user through every supporting source card — the user is watching, so leave them on the result.\n\n**`previewUrl` is a route, not a URL to open.** Every read response (per-doc, on `exec` / `search` / `links` rows) and every write response carries a `previewUrl` — a route fragment like `/#/specs/foo/SPEC`, with **no scheme, host, or port**. It identifies *which doc* to preview, not a URL to hand a browser by itself. Never construct or guess preview URLs.\n\n**Pick how to open the preview by tool capability — not by host name.** Look at the tools actually available to you this session. If a tool can navigate to a URL, it counts as an in-app browser — match on the capability, not on what your host is called.\n\n- **You have a `preview_*` tool** (e.g. `preview_start`) → call `preview_start("open-knowledge-ui")` and nothing else. The pane supplies its own origin; you never need a URL. Do NOT also call `get_preview_url`. Do NOT read, diagnose, or edit `.claude/launch.json` — that file is host-managed, and the OK lock-collision proxy handles the UI-already-running case automatically. If `preview_start` fails, report it to the user; do not try to "fix" `launch.json`.\n- **No `preview_*` tool, but you have an in-app / built-in browser tool** — including Codex\'s built-in browser, and any host tool whose contract is "navigate to a URL" (`browser`, `view_url`, `open_url`, `web.browse`, host-specific names, etc.) → call `get_preview_url` once to get the full browser URL (`{ url, baseUrl, running }`), then navigate your **in-app browser** to `url`. Pass a `docName` to `get_preview_url` to jump straight to a doc, or omit it for the UI root.\n- **Truly no browser-capable tool — if you have ANY tool that navigates to a URL, use the in-app branch above** (a pure stdio host with no URL-navigation tool at all) → call `get_preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly to the user ("opening the preview in your system browser — this host has no in-app browser"). The system browser is the fallback, never the default.\n- **Honor `autoOpen`** (on `get_preview_url`, or on `warning` for write tools). If `false`, do not open or refresh any preview UI; surface the URL only if asked.\n\n**Opening or reading a file IS a preview navigation.** On any "open `<file>`" / "read `<file>`" request, navigate the browser to that doc\'s `previewUrl` route from the tool response — not a separate fetch, not a fresh system-browser launch.\n\n**Four signals to check if the preview is already attached** (read these from each write response):\n\n1. You opened/navigated earlier this session → don\'t reopen.\n2. Write response has `previewUrl` (non-null route) and NO `warning` → a browser is attached somewhere; do nothing.\n3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot (`preview_start`, or `get_preview_url` → in-app browser).\n4. `warning: { action: "start-ui", previewUrl: null, message }` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don\'t loop on retries.\n\nWarnings fire at most once per session in the fresh-start case.\n\n**`previewUrl: null` only means "no UI reachable" on the three attach-warning tools: `write_document` / `edit_document` / `edit_frontmatter`.** Workflow tools return prose and don\'t carry `previewUrl`. `delete_document` / `rename` emit `previousPreviewUrl` (different field, for closing stale tabs) and don\'t fire attach warnings. `get_preview_url` reports `running: false` + `url: null` when no UI is running.\n\nIf you see `"Hocuspocus server is not running"`, run `ok start` and retry.\n\nOK Electron and `ok ui` share `ui.lock`; when a second UI binds a different port, the OK lock-collision proxy bridges it to the live server transparently. That is exactly why `previewUrl` is route-only — the port behind the proxy is not the agent\'s to use. **Do not nudge the user to quit OK Electron to free a port** — the proxy handles it, and quitting tears down a UI in active use.\n\n**The preview is read-only for the agent — it is the user\'s view, not a surface you read back.** You cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).\n\n**No screenshots to confirm edits, no generic verification loop.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after a write, and do not run a generic snapshot/eval/screenshot verification loop — OK\'s preview is a read-only, one-way mirror, so the CRDT tool response *is* the confirmation that an edit landed. Screenshot only when debugging a visual rendering issue or when the user explicitly asks to see the preview — never to confirm an edit landed.\n\n## Scope recap\n\nOpen Knowledge looks for documents under the resolved `content.dir` (discoverable at runtime via `get_config({ path: [\'content\', \'dir\'] })`). `.gitignore` and `.okignore` (at the project root and at any folder depth) define exclusions. Folder defaults + templates live in nested `<folder>/.ok/frontmatter.yml` + `<folder>/.ok/templates/` files — NOT in `.ok/config.yml`.\n\nDefault mental model (no jargon): **every `.md` and `.mdx` under `content.dir`** not excluded by `.gitignore` or `.okignore` is an Open Knowledge document — including under `specs/`, `reports/`, `docs/`, etc. Read `.okignore` (and any nested `.okignore` files) once per turn to know what\'s excluded.\n\n**First session in this project?** If `frontmatter_defaults` and `templates_available` are empty for substantial folders, the project hasn\'t been onboarded yet — invoke `discover` (Workflow tools table) before writing. Once onboarded, the cascade carries the discipline.\n\n\nFull guidance lives in the bundled `open-knowledge` skill at `~/.ok/skills/open-knowledge/SKILL.md`.\n'}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let S=t.validateToolInput;if(typeof S!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,w){if(!e.inputSchema||!isZodSchema(e.inputSchema))return S.call(this,e,t,w);let E=await e.inputSchema.safeParseAsync(t);if(E.success)return E.data;let D=prettifyError(E.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${w}:\n${D}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const loggerContext=new AsyncLocalStorage;var McpLogger=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??randomUUID().slice(0,12),this.corrId=randomUUID().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,S={}){let w=t?{error:t instanceof Error?t.message:String(t),...S}:S;this.emit(`error`,e,w)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,S){let w={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...S},E=`${JSON.stringify(w)}\n`;process.stderr.write(E);let D=process.env.OK_LOG_FILE;if(D)try{appendFileSync(D,E)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function runWithMcpLogger(e,t){return loggerContext.run(e,t)}function getCurrentMcpLogger(){return loggerContext.getStore()}const REDACTED_STRING_KEYS=new Set([`find`,`markdown`,`replace`]),COMMON_ARRAY_KEYS=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],COMMON_SCALAR_KEYS=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isToolExtraLike(e){return isPlainObject(e)&&`requestId`in e}function summarizeStringForLog(e,t){if(REDACTED_STRING_KEYS.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
@@ -3503,7 +3503,7 @@ In headless mode, write the recap into the research article's "Further reading"
3503
3503
  `).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.errorCode=void 0,this.error=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let S=[],w=[];for(let e of t){let t=join(this.projectDir,e),E=relative(this.contentDir,t);!E.startsWith(`..`)&&isSupportedDocFile(E)&&!this.contentFilter.isExcluded(E)?S.push(e):w.push(e)}let E=[];for(let t of w)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] non-content auto-resolve failed — will abort merge and pause sync`),E.push({file:t,err:e})}if(E.length>0){let t=E.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let S=t.slice(0,3).join(`, `),w=t.length>3?`, +${t.length-3} more`:``;this.errorCode=void 0,this.error=`Sync paused — couldn't auto-resolve ${S}${w}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(S.length>0){for(let e of S)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(S),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),log.warn({files:S},`[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 notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){log.warn({err:t,files:e},`[sync] content conflict callback failed`)}}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){e.userFacingCode===null?(this.errorCode=void 0,this.error=e.message):(this.errorCode=e.userFacingCode,this.error=void 0),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`,this.onAutoDisable?.(`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=this.pausedReason===`no-push-permission`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};writeFileSync(this.statePath,JSON.stringify(t,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===`no-push-permission`?void 0:t.pausedReason;let S=t.inflightConflicts??[];if(S.length>0){for(let e of S)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 MOUNT_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function createSyncHandshakeSpanExtension(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(isSystemDoc(e)||isConfigDoc(e))return;let S=t?.get(`mountId`)??void 0,w={"doc.name":e};S!==void 0&&MOUNT_ID_PATTERN.test(S)&&(w[`mount.id`]=S);try{withSpanSync(`sync.handshake`,{attributes:w},()=>{})}catch(e){console.warn(`[sync-handshake-span] emission failed:`,e instanceof Error?e:String(e))}}}}const TAG_VALUE_RE=createTagInTextRegex();function createEmptyState(){return{byTag:new Map,byDoc:new Map,byDocLiteral:new Map}}function stripInlineCodeSpans(e){return e.replace(/`[^`]*`/g,``)}function extractInlineTagsFromBody(e){let t=e.replaceAll(`\r
3504
3504
  `,`
3505
3505
  `).split(`
3506
- `),S=[],w=!1,E=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){w?RegExp(`^\\s{0,3}${E[0]==="`"?"`":`~`}{${E.length},}\\s*$`).test(e)&&(w=!1,E=``):(w=!0,E=t[1]);continue}if(w)continue;let D=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(D);if(e===null)break;let t=e[2];t&&S.push(t)}}return S}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:S,body:w}=stripFrontmatter(t),E=extractFrontmatterTags(S?unwrapFrontmatterFences(S):``),D=extractInlineTagsFromBody(w),O=new Set([...E,...D]),k=new Set;for(let e of O)for(let t of expandTagToHierarchy(e))k.add(t);this.applyDocSnapshot(e,O,k)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let S of t){let t=this.state.byTag.get(S);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(S))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,S){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,S)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let S=[];for(let w of t){let t=this.state.byDocLiteral.get(w);if(!t)continue;let E=tagsMatchingPrefix(t,e);S.push({docName:w,matchingTags:[...E].sort((e,t)=>e.localeCompare(t))})}return S.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),S=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&S.add(e.slice(0,t));let w=t;for(;w>0;)S.add(e.slice(0,w)),w=e.indexOf(`/`,w+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!S.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:S}of e)try{let e=readFileSync(S,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,S){let w=this.state.byDoc.get(e)??new Set;for(let t of w){if(S.has(t))continue;let w=this.state.byTag.get(t);w&&(w.delete(e),w.size===0&&this.state.byTag.delete(t))}for(let t of S){let S=this.state.byTag.get(t);S||(S=new Set,this.state.byTag.set(t,S)),S.add(e)}S.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,S),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let w of S){let S=join(e,w.name);if(w.isDirectory()){let e=relative(this.contentDir,S);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(S,t);continue}if(!w.isFile()||!isSupportedDocFile(w.name))continue;let E=relative(this.contentDir,S);this.contentFilter?.isExcluded(E)||t.push({docName:stripDocExtension(E),filePath:S})}}};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:S=t,quiet:w=!0,debounce:E=2e3,maxDebounce:D=1e4,gitEnabled:O=!0,commitDebounceMs:k=3e4,wipRef:j=`refs/wip/main`,configHomedirOverride:F,enableTestRoutes:L=!1,shadowRepo:B,contentRoot:H,destroyTimeoutMs:q=1e4,localOpCliArgs:J,skipStateManifestCheck:Y=!1}=e,ee=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||ee.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ne=randomUUID(),ae=getLocalDir(S);if(acquireServerLock(ae,{port:e.port??0,worktreeRoot:S,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!Y)try{assertCompatibleStateManifest({lockDir:ae,shadowRepoDir:resolveShadowDir(S)})}catch(e){throw releaseServerLock(ae),e}let oe=createBasenameIndex(),se=(e,t)=>oe.resolveEmbed(e,t),ce=(e,S)=>{let w=oe.resolveEmbed(e,S);if(!w&&e.includes(`/`)&&(w=e.replace(/^\.?\//,``)),!w)return null;let E=resolve(t,w),D=resolve(t);if(E!==D&&!E.startsWith(`${D}/`))return null;try{let e=statSync(E);return e.isFile()?e.size:null}catch{return null}},ue,de,fe,me,ge,_e,ve,ye=null,Ce=null,we=null,Te=null,De=new Set,je=!1,Me,Pe,Ie,Re=new Promise((e,t)=>{Pe=e,Ie=t});function ze(e){ye?.signal(e)}let Be=2e3,Ve=null;function Ue(){Ve!==null&&clearTimeout(Ve),Ve=setTimeout(()=>{Ve=null,de.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let We=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),Ge=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||We.setRenamed(e,t)},Ke=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(We.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}We.setDeleted(e)}},Xe=e=>{isSystemDoc(e)||isConfigDoc(e)||We.delete(e)};try{ue=createContentFilter({projectDir:S,contentDir:t,onAfterRebuild:()=>{de.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{fe.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let{prunedFiles:e,prunedFolders:t}=reconcileFileIndexAfterFilterRebuild(Rt),S=e+t;S>0?getLogger(`server-factory`).info({pruned:S,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):getLogger(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)}}}),de=new BacklinkIndex({projectDir:S,contentDir:t,contentFilter:ue}),fe=new TagIndex({contentDir:t,contentFilter:ue});try{fe.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}me={current:B},ge=createPersistenceExtension({contentDir:t,projectDir:S,gitEnabled:O,commitDebounceMs:k,wipRef:j,shadowRef:me,contentRoot:H,backlinkIndex:de,configHomedirOverride:F,getCurrentBranch:()=>zt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce,getPrincipal:()=>Te,onAgentCommit:()=>ye?.signal(`session-activity`),onDiskFlush:(e,t)=>ye?.emitDiskAck(e,t),onConfigRejected:(e,t)=>ye?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),_e=new Hocuspocus({quiet:w,debounce:E,maxDebounce:D,extensions:[ge.extension]});let q=_e.shouldUnloadDocument.bind(_e);_e.shouldUnloadDocument=e=>{if(De.has(e)||je&&q(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:q(e)},Me=async e=>{De.add(e);try{await _e.unloadDocument(e)}finally{De.delete(e)}},ye=new CC1Broadcaster(_e),Ce=new AgentFocusBroadcaster(_e),we=new AgentPresenceBroadcaster(_e),ve=new AgentSessionManager(_e);let Y=createLiveDerivedIndexExtension({backlinkIndex:de,tagIndex:fe,signalChannel:ze});_e.configuration.extensions.push(Y),_e.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,S=parseHocuspocusAuthToken(t),w=S?.expectedServerInstanceId;if(typeof w==`string`&&w.length>0&&w!==ne)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${w}, this server is ${ne}`);let E=S?.expectedBranch,D=getActiveBranch();if(typeof E==`string`&&E.length>0&&E!==D)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${E}, server is on ${D}`);if(!S)return;let O=e.context;typeof S.principalId==`string`&&(Te&&S.principalId===Te.id?O.principalId=Te.id:Te?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:S.principalId,loaded:Te.id})):O.principalId=S.principalId),typeof S.tabSessionId==`string`&&(O.tabSessionId=S.tabSessionId),O.kind=`human`}}),_e.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,S=t.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S))throw Error(`config-doc admission requires loopback peer (peer=${S}, doc=${e.documentName})`);let w=e.requestHeaders,E=(w&&typeof w.get==`function`?w.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(E))throw Error(`config-doc admission requires loopback Host header (host=${E??`<absent>`}, doc=${e.documentName})`)}});let ee=resolve(t);function te(e){if(!isSafeDocName(e))return null;let t=resolve(ee,`${e}${getDocExtension(e)}`);return!t.startsWith(`${ee}/`)&&t!==ee?null:t}_e.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:We,resolveFilePath:te,fileExists:existsSync})}}),_e.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 ae=createApiExtension({hocuspocus:_e,sessionManager:ve,contentDir:t,contentFilter:ue,serverInstanceId:ne,getFileIndex:()=>Rt?Rt.getFileIndex():new Map,getFolderIndex:()=>Rt?Rt.getFolderIndex():new Map,getAliasMap:()=>Rt?Rt.getAliasMap():new Map,rescanFiles:()=>Rt?.rescanFromDisk(),enableTestRoutes:L,shadowRef:me,flushGitCommit:()=>ge.flushPendingGitCommit(),flushContributors:()=>ge.flushContributors(),getCurrentBranch:()=>zt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ye?.getLatestDiskAckSVsAsBase64()??{},contentRoot:H,backlinkIndex:de,tagIndex:fe,signalChannel:ze,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Bt,localOpCliArgs:J,projectDir:S,resolveEmbed:se,getPrincipal:()=>Te,forceUnloadDocument:Me,ready:Re,recentlyRemovedDocs:We,serializeDoc:at});_e.configuration.extensions.push(ae),_e.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:me,contentRoot:H,getCurrentBranch:()=>zt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce})),_e.configuration.extensions.push(createSyncHandshakeSpanExtension()),_e.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>Bt,projectDir:S,contentDir:t}))}catch(e){throw releaseServerLock(ae),e}let $e=null,nt=new Map,rt=[];function it(e,t){let S=resolve(e,`rescue`),w=resolve(S,`${t}${getDocExtension(t)}`);return w.startsWith(`${S}/`)?w:null}function at(e){let t=_e.documents.get(e);if(!t)return null;let{frontmatter:S,body:w}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(S,w)}let st=(e,t)=>applyExternalChange(_e,e,t,se,ce);function vt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Tt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[S]of _e.documents){if(isSystemDoc(S)||isConfigDoc(S))continue;let w=_e.documents.get(S);if(!w)continue;let E=w.getText(`source`).toString();if(E.includes(t))try{w.transact(()=>{applyDiskContentToDoc(w,E,se,S)},FILE_WATCHER_ORIGIN)}catch(t){ee.error({err:t,docName:S,assetBasename:e},`[asset-event] failed to re-render ${S} for asset basename ${e}`)}}},Et=null,Dt=e=>{e&&(Et===null&&(Et=new Set,setImmediate(()=>{let e=Et;if(Et=null,e)try{for(let t of e)Tt(t)}catch(t){ee.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Et.add(e))};function jt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Mt(e){try{switch(e.kind){case`create`:ee.info({docName:e.docName},`[reconcile] create: ${e.docName}`),de.updateDocumentFromMarkdown(e.docName,e.content),Ue(),fe.updateDocumentFromMarkdown(e.docName,e.content),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Xe(e.docName);break;case`update`:{let{docName:t,content:S}=e,w=_e.documents.get(t);if(!w){de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);return}let E=getReconciledBase(t)??``,D=at(t)??E,O=reconcile({docName:t,base:E,ours:D,theirs:S}),k=contentHash(E).slice(0,6),j=contentHash(D).slice(0,6),F=contentHash(S).slice(0,6);switch(ee.info({docName:t,base:k,ours:j,theirs:F,result:O.kind},`[reconcile] ${t} base=${k} ours=${j} theirs=${F} result=${O.kind}`),O.kind){case`noop`:vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);break;case`clean`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,S),vt(w)}break;case`merged`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,S),vt(w)}break;case`conflicts`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),incrementConflict(),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,S)}{let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{incrementConflict();let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,O.reason);break}}break}case`delete`:{let{docName:t}=e,S=_e.documents.get(t);if(!S){de.deleteDocument(t),Ue(),fe.deleteDocument(t),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let w=getReconciledBase(t)??``,E=at(t)??``,D=E!==w;if(D&&me.current){let e=me.current,S=zt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,H??``,{kind:`external-change-rescue`,docName:t,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{ee.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),de.deleteDocument(t),Ue(),fe.deleteDocument(t),ee.info({docName:t,isDirty:D},`[reconcile] delete: ${t} (dirty=${D})`),_e.closeConnections(t),await Me(S),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:S,content:w}=e,E=_e.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(S,w),de.renameDocument(t,S,w),Ue(),fe.renameDocument(t,S,w),E){let e=E.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,S)}ee.info({oldDocName:t,newDocName:S},`[reconcile] rename: ${t} → ${S}`),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ge(t,S),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:S,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,S=_e.documents.get(t);if(!S)return;let w=at(t);w===null?ee.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,w);let E=S.getMap(`lifecycle`);E.set(`status`,`conflict`),E.set(`reason`,`conflict-markers`),ee.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:oe.add(e.relativePath),ze(`files`),Dt(basename(e.relativePath));break;case`asset-delete`:oe.remove(e.relativePath),ze(`files`),Dt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:ze(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let S=jt(e);ee.error({err:t,kind:e.kind,label:S},`[reconcile] failed to handle ${e.kind} for ${S}`)}}let Ft=[];async function It(e){if(isBatchInProgress()){Ft.push(e);return}await Mt(e)}async function Lt(){let e=Ft.splice(0,Ft.length);for(let t of e)await Mt(t)}let Rt=null,zt=null,Bt=null,Vt=null;async function Ht(e){if(_e.documents.size===0)return;let t=!1,S=new Promise(e=>{_e.configuration.extensions.push({async afterUnloadDocument({instance:S}){!t&&S.getDocumentsCount()===0&&(t=!0,e())}})}),w=Array.from(_e.documents.keys());_e.closeConnections(),_e.flushPendingStores();for(let e of _e.documents.values())e.getConnectionsCount()===0&&_e.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let E,D=new Promise((S,D)=>{E=setTimeout(()=>{t=!0;let S=Array.from(_e.documents.keys()),E=[],O=[];if(me.current){for(let e of S)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=at(e);if(t===null){ee.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),O.push(e);continue}let S=it(me.current.gitDir,e);if(!S){ee.warn({docName:e,gitDir:me.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),O.push(e);continue}mkdirSync(dirname(S),{recursive:!0}),writeFileSync(S,t,`utf-8`),incrementRescueBuffer(),E.push(e),ee.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){O.push(e),ee.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else ee.warn({stillLoadedCount:S.length},`[rescue] shadow repo unavailable at flush timeout — ${S.length} doc(s) will be lost: [${S.join(`, `)}]`),O.push(...S);let k=E.length>0||O.length>0?` — rescued [${E.join(`, `)}]${O.length>0?`, lost [${O.join(`, `)}]`:``}`:``;D(Error(`flushAllStoresAndWait timeout after ${e}ms — ${S.length}/${w.length} docs did not unload: [${S.join(`, `)}]${k}`))},e)});try{await Promise.race([S,D])}finally{E!==void 0&&clearTimeout(E)}}async function Ut(){return Vt||(Vt=(async()=>{let e=Date.now(),t=[];je=!0,Ve!==null&&(clearTimeout(Ve),Ve=null);let w,E=await Promise.race([Re.then(()=>`completed`,e=>(ee.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{w=setTimeout(()=>e(`timeout`),5e3)})]);w!==void 0&&clearTimeout(w),E===`timeout`&&ee.warn({},`[server] init did not complete within 5s during shutdown`);let D=_e.documents.size;try{try{try{zt&&=(await zt.unsubscribe(),null),Rt&&=(await Rt.unsubscribe(),null);for(let{docName:e,cleanup:t}of rt)try{await t()}catch(t){ee.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}rt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ye?.destroy(),we?.destroy(),$e&&=(await $e.disconnect(),null);for(let[e,t]of nt)try{await t.disconnect()}catch(t){ee.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}nt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ve.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Ht(q)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ge.flushPendingGitCommit(),await ge.waitForPendingCommits()})(),new Promise((t,S)=>{e=setTimeout(()=>S(Error(`L2 git flush timeout`)),q)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Bt&&=(await Bt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(me.current){try{let e=(await esm_default({baseDir:S,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(me.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(me.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let w=Date.now()-e;t.length===0?ee.info({documentCount:D,durationMs:w},`[server] shutdown flushed ${D} documents in ${w}ms`):ee.warn({documentCount:D,durationMs:w,phaseErrors:t},`[server] shutdown flushed ${D} documents in ${w}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ae)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),ee.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)})}}})(),Vt)}let Wt=[];async function Kt(){try{Te=await loadPrincipal(S),ee.info({principalId:Te.id},`[server] principal loaded`)}catch(e){ee.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!me.current)try{me.current=await initShadowRepo(S),ee.info({gitDir:me.current.gitDir},`[server] history repo initialized at ${me.current.gitDir}`)}catch(e){ee.error({err:e},`[server] history repo init failed`),Wt.push(`shadow-repo`)}if(me.current){let e=null;try{e=loadRenameLogIndex(me.current.gitDir),sweepLazyPopOrphans(me.current.gitDir,e),setRenameLogIndex(me.current.gitDir,e),ee.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){ee.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(me.current,e,{rebuild:!0}),new Promise((e,S)=>setTimeout(()=>S(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){ee.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(me.current)try{await shadowGit(me.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`)){ee.warn({},`[server] history repo appears corrupted — reinitializing`);try{me.current=await initShadowRepo(S)}catch(e){ee.error({err:e},`[server] history repo reinit failed`),me.current=void 0,Wt.includes(`shadow-repo`)||Wt.push(`shadow-repo`)}}else ee.error({err:e},`[server] history repo check failed (transient?)`)}if(me.current)try{let e=resolve(me.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let w=null;try{w=(await esm_default({baseDir:S,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(w!==null){if(w!==t){let e=`main`;try{let t=(await esm_default({baseDir:S,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}ee.info({lastKnownHead:t,currentHead:w,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=import`);try{await commitUpstreamImport(me.current,H??``,t,w,e),incrementUpstreamImport()}catch(e){ee.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else ee.info({currentHead:w},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=noop`);try{writeFileSync(e,w,`utf-8`)}catch(e){ee.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){ee.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,S);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,S=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;ee.warn({journalVersion:e.journal.version,fromPath:t,toPath:S,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${S}`)}}catch(e){ee.error({err:e},`[server] managed rename recovery failed`),Wt.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(S);(e.deleted>0||e.errors>0)&&ee.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){ee.error({err:e},`[server] upload-tempfile sweep failed`),Wt.push(`upload-tempfile-sweep`)}try{$e=await _e.openDirectConnection(SYSTEM_DOC_NAME),ye?.emitServerInfo(ne,getActiveBranch())}catch(e){ee.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Wt.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await _e.openDirectConnection(e);nt.set(e,t)}catch(t){ee.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Wt.push(`config-doc:${e}`)}let w=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,S)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,S)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,S,F)]]);for(let e of CONFIG_DOC_NAMES){let t=w.get(e);if(t)try{ee.info({docName:e,path:t},`[config-file-watcher] starting`);let S=await startConfigFileWatcher(t,t=>{let S=_e.documents.get(e);ee.info({docName:e,hasDocument:S!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let w=applyExternalConfigChange(S??null,e,t,ge.configPersistenceCtx);if(ee.info({docName:e,outcome:w},`[config-file-watcher] applyExternalConfigChange outcome`),e===`__config__/project`||e===`__local__/project`){let e=te();Bt?.setEnabled(e).catch(t=>{ee.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});rt.push({docName:e,cleanup:S}),ee.info({docName:e,path:t},`[config-file-watcher] started`)}catch(S){ee.warn({err:S,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Wt.push(`config-file-watcher:${e}`)}}try{let e=resolve(t,`.okignore`),w=resolve(S,`.gitignore`),E=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:S,encoding:`utf-8`,timeout:5e3});if(e.status===0&&e.stdout){let t=join(resolve(S,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(E=t)}}catch{}let D=E?[e,w,E]:[e,w],O=ee;O.info({okignorePath:e,gitignorePath:w,gitInfoExcludePath:E},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let k=await startMultiPathConfigFileWatcher(D,(t,w)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(_e.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,w,ge.configPersistenceCtx);O.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){O.error({err:e,changedPath:relative(S,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let E=await ue.rebuildIgnorePatterns();if(E.ok)O.info({changedPath:relative(S,t),patternCount:E.patternCount,nestedFileCount:E.nestedFileCount,durationMs:E.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ye?.signal(`files`);else{let e=relative(S,t)||`.`;O.warn({changedPath:e,error:E.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ye?.emitConfigIgnoreNestedError(e,E.error.message)}})().catch(e=>{O.error({err:e,changedPath:relative(S,t)||`.`},`[ignore-watcher] handler threw`)})});rt.push({docName:`__ignore-files__`,cleanup:k}),O.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] multi-path watcher started`)}catch(e){ee.warn({err:e,projectDir:S,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Wt.push(`ignore-files-watcher`)}let E=resolveGitDir(S),D=E?readBranchFromHead(E)??`main`:`main`;switchReconciledBaseScope(D),de.switchBranch(D);try{{let e=getActiveBranch();try{if(await de.loadFromDisk(e)){let t=await de.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&ee.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await de.rebuildFromDisk(e);de.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){ee.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Rt=await startWatcher(t,It,ue),fe.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,w)=>{e++,ee.warn({reason:t,code:S,path:w},`[basename-index] skipped entry during seed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Wt.push(`basename-index-partial`))}catch(e){ee.error({err:e},`[basename-index] startup seed failed`),Wt.push(`basename-index`)}}catch(e){ee.error({err:e},`[server] disk bridge watcher failed to start`),Wt.push(`file-watcher`)}try{zt=await startHeadWatcher(S,async({trigger:e})=>{if(ee.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),_e.flushPendingStores(),await ge.flushPendingGitCommit(),setBatchInProgress(!0),me.current){let e=getActiveBranch(),t=resolveGitDir(S),w=t?readBranchFromHead(t)??e:e,E=[];for(let[e,t]of _e.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let S=null;if(t.transact(()=>{S=at(e)},PARK_SNAPSHOT_ORIGIN),S===null)continue;let w=getReconciledBase(e)??S;E.push({docName:e,markdown:S,diskSnapshot:w})}if(E.length>0)try{let t=await parkBranch(me.current,e,SERVICE_WRITER.id,E,w);t&&(incrementPark(),ee.info({count:E.length,branch:e,sha:t.slice(0,8)},`[history] parked ${E.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){ee.error({err:e},`[shadow] park failed`)}}},async e=>{let S=Ft.length,w=e.newBranch??`main`;if(ee.info({kind:e.batchKind,headMoved:e.headMoved,docs:S,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${S}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await Lt(),await ge.flushDeferredStores(`within-branch`),Bt!==null)try{await Bt.reconcileConflictsFromGit()}catch(e){ee.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),Ft.splice(0,Ft.length),switchReconciledBaseScope(w),Ve!==null&&(clearTimeout(Ve),Ve=null),de.switchBranch(w),ue.rebuildDirCount();try{let e=0;oe.clear(),seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,E)=>{e++,ee.warn({reason:t,code:S,path:E,branch:w},`[basename-index] skipped entry during branch-switch reseed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e,branch:w},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Wt.includes(`basename-index-partial`)||Wt.push(`basename-index-partial`))}catch(e){ee.error({err:e,branch:w},`[basename-index] branch-switch reseed failed`)}for(let[e,S]of _e.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let E=safeContentPath(e,t);if(!existsSync(E)){let t=getReconciledBase(e)??``,E=at(e)??``;if(E!==t&&me.current){let t=me.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,H??``,{kind:`external-change-rescue`,docName:e,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:w,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{ee.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),ee.info({docName:e,branch:w},`[branch-switch] tombstone: ${e} (not on ${w})`);continue}let D=readFileSync(E,`utf-8`);st(e,D),setReconciledBase(e,D),ee.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){ee.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}ee.info({branch:w,docCount:_e.documents.size},`[branch-switch] loaded branch ${w} (${_e.documents.size} docs)`);try{if(await de.loadFromDisk(w)){let e=await de.reconcileWithDisk(w);(e.added>0||e.updated>0||e.deleted>0)&&ee.info(e,`[backlinks] branch-switch reconcile for ${w}`)}else await de.rebuildFromDisk(w);de.saveToDisk(w).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${w}:`,e)})}catch(e){ee.error({err:e,branch:w},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(fe.init(),me.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of _e.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let S=await readParkedState(me.current,w,SERVICE_WRITER.id,t);if(!S||S.markdown===S.diskSnapshot)continue;let E=getReconciledBase(t);if(!E)continue;let D=reconcile({docName:t,base:S.diskSnapshot,ours:S.markdown,theirs:E});switch(D.kind){case`merged`:case`clean`:st(t,D.newContent),setReconciledBase(t,D.newContent),e++;break;case`conflicts`:st(t,D.newContent),setReconciledBase(t,D.newContent),incrementConflict(),e++;{let e=_e.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){ee.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&ee.info({count:e,branch:w},`[branch-switch] restored ${e} parked docs on ${w}`)}if(e.oldBranch?.startsWith(`detached-`)&&me.current)try{let t=shadowGit(me.current),S=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(S){for(let e of S.split(`
3507
- `))e&&await t.raw(`update-ref`,`-d`,e);ee.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){ee.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ge.flushDeferredStores(`discard-stale`),ye?.emitBranchSwitched(w)}if(e.headMoved&&e.newHead&&me.current&&S>0){let t=H??`.`;try{let S=await commitUpstreamImport(me.current,t,e.oldHead,e.newHead,w);incrementUpstreamImport(),ee.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:S.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${S.slice(0,8)}`)}catch(e){ee.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){ee.error({err:e},`[server] HEAD watcher failed to start`),Wt.push(`head-watcher`)}function O(e){for(let w of e)try{let e=relative(t,join(S,w));if(e.startsWith(`..`))continue;let E=stripDocExtension(e),D=_e.documents.get(E);if(!D)continue;let O=at(E);O===null?ee.warn({docName:E,file:w},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(E,O);let k=D.getMap(`lifecycle`);k.set(`status`,`conflict`),k.set(`reason`,`sync-merge-conflict`),ee.info({docName:E,file:w},`[sync] marked loaded content conflict`)}catch(e){ee.warn({err:e,file:w},`[sync] failed to mark loaded content conflict`)}}let k=J?.[0]??`open-knowledge`,j=[`-c`,`credential.helper=!${J&&J.length>1?J.join(` `):k} auth git-credential`];try{Bt=new SyncEngine({projectDir:S,contentDir:t,contentFilter:ue,contentRoot:H,syncEnabled:te(),credentialArgs:j,cc1Broadcaster:ye,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||ge.flushDeferredStores(`within-branch`).catch(e=>{ee.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{ee.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:O,onAutoDisable:async e=>{ee.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:S,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||ee.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,S)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await Bt.start()}catch(e){ee.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Bt=null}ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`)}return Kt().then(Pe,Ie),{hocuspocus:_e,sessionManager:ve,cc1Broadcaster:ye,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,contentFilter:ue,basenameIndex:oe,serverInstanceId:ne,destroy:Ut,ready:Re,degraded:Wt,lockDir:ae,get syncEngine(){return Bt}}}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let S=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&S.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let w=resolve(e,t);try{existsSync(w)&&statSync(w).isDirectory()&&S.push(`${t}/`)}catch{}}return S}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3;async function bootServer(e){initTelemetry();let{kind:t,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":t};return S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S)),withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,S=e.attachUiSibling??!0,w=e.idleShutdownMs,E=e.log??getLogger(`boot`),D=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,O=e.lockKind??D??`interactive`,{createServer:k}=await import(`node:http`),{updateServerLockPort:j}=await import(`./server-lock-v2ktHD7l-C-3wEnoU.mjs`),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){E.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let H=e.gitPreflight??assertGitAvailable;try{H()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,S=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),E.warn({event:`git_preflight_fail`,platform:e.platform,reason:S,detectedVersion:t},S===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),e}let q=findLegacyRuntimeFiles(B);q.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${q.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let J=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,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:O,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore}),{hocuspocus:Y,destroy:ee,ready:te,degraded:ne,lockDir:ae,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce}=J,ue=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),de=e.port??0,fe=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ue}:${de}`,log:E}),me=k();me.headersTimeout=3e4,me.requestTimeout=6e4;let ge=e.serveContentAssets?createAssetServeMiddleware({contentFilter:J.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,_e=!1;if(e.reactShellDistDir)try{acquireUiLock(ae,{port:0,worktreeRoot:e.projectDir??e.contentDir}),_e=!0}catch(e){if(e instanceof UiLockCollisionError)E.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:ae},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await ee().catch(()=>{}),e}let ve=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ye=mountMcpAndApi({httpServer:me,hocuspocus:Y,mcpHttpHandler:fe,log:E,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ge,reactShellMiddleware:ve}),Ce=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},we=null;w!==null&&(we=attachIdleShutdown({httpServer:me,thresholdMs:w??DEFAULT_IDLE_THRESHOLD_MS,log:E,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await Ce()})})),await restoreLifecycleFromConflictsJson({hocuspocus:Y,projectDir:e.projectDir??e.contentDir,log:E});try{await new Promise((t,S)=>{let w=e=>S(e);me.once(`error`,w),me.listen(e.port,e.host,()=>{me.removeListener(`error`,w),t()})})}catch(e){if(_e)try{releaseUiLock(ae)}catch(e){E.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await ee().catch(()=>{}),e}let Te=me.address(),De=typeof Te==`object`&&Te?Te.port:e.port??0;if(de=De,j(ae,De),_e&&updateUiLockPort(ae,De),S&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ae,log:E})}catch(e){E.warn({err:e},`spawnUiSiblingFn failed`)}let je=!1,Me=async(e,t)=>{let S;try{await Promise.race([t(),new Promise((t,w)=>{S=setTimeout(()=>{w(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),S.unref?.()})])}finally{S!==void 0&&clearTimeout(S)}};return Ce=async()=>{if(je)return;je=!0;let e=[],t=async(t,S)=>{try{await Me(t,S)}catch(S){e.push(S),E.warn({err:S,step:t},`bootServer destroy step failed`)}};try{we?.detach()}catch(t){e.push(t),E.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ye.shutdown()),await t(`mcpHttpHandler.close`,()=>fe.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ye.wss.close(S=>S?t(S):e())})),await t(`httpServer.closeAllConnections`,async()=>{me.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{me.close(S=>S&&S.code!==`ERR_SERVER_NOT_RUNNING`?t(S):e())})),await t(`destroyHocuspocus`,()=>ee()),_e&&await t(`releaseUiLock`,async()=>releaseUiLock(ae)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:me,destroy:Ce,lockDir:ae,contentDir:e.contentDir,port:De,ready:te,degraded:ne,didAutoInit:F,serverInstance:J}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:S,log:w}=e,E,D;try{E=new ConflictStore(S),D=E.list()}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(D.length===0)return;let O=null;try{let e=resolveGitDir(S),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){E.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:D.length}));return}let w=(await simpleGit({baseDir:S,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();O=new Set(w?w.split(`
3506
+ `),S=[],w=!1,E=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){w?RegExp(`^\\s{0,3}${E[0]==="`"?"`":`~`}{${E.length},}\\s*$`).test(e)&&(w=!1,E=``):(w=!0,E=t[1]);continue}if(w)continue;let D=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(D);if(e===null)break;let t=e[2];t&&S.push(t)}}return S}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:S,body:w}=stripFrontmatter(t),E=extractFrontmatterTags(S?unwrapFrontmatterFences(S):``),D=extractInlineTagsFromBody(w),O=new Set([...E,...D]),k=new Set;for(let e of O)for(let t of expandTagToHierarchy(e))k.add(t);this.applyDocSnapshot(e,O,k)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let S of t){let t=this.state.byTag.get(S);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(S))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,S){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,S)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let S=[];for(let w of t){let t=this.state.byDocLiteral.get(w);if(!t)continue;let E=tagsMatchingPrefix(t,e);S.push({docName:w,matchingTags:[...E].sort((e,t)=>e.localeCompare(t))})}return S.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),S=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&S.add(e.slice(0,t));let w=t;for(;w>0;)S.add(e.slice(0,w)),w=e.indexOf(`/`,w+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!S.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:S}of e)try{let e=readFileSync(S,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,S){let w=this.state.byDoc.get(e)??new Set;for(let t of w){if(S.has(t))continue;let w=this.state.byTag.get(t);w&&(w.delete(e),w.size===0&&this.state.byTag.delete(t))}for(let t of S){let S=this.state.byTag.get(t);S||(S=new Set,this.state.byTag.set(t,S)),S.add(e)}S.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,S),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let w of S){let S=join(e,w.name);if(w.isDirectory()){let e=relative(this.contentDir,S);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(S,t);continue}if(!w.isFile()||!isSupportedDocFile(w.name))continue;let E=relative(this.contentDir,S);this.contentFilter?.isExcluded(E)||t.push({docName:stripDocExtension(E),filePath:S})}}};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:S=t,quiet:w=!0,debounce:E=2e3,maxDebounce:D=1e4,gitEnabled:O=!0,commitDebounceMs:k=3e4,wipRef:j=`refs/wip/main`,configHomedirOverride:F,enableTestRoutes:L=!1,shadowRepo:B,contentRoot:H,destroyTimeoutMs:q=1e4,localOpCliArgs:J,skipStateManifestCheck:Y=!1}=e,ee=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||ee.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ne=randomUUID(),ae=getLocalDir(S);if(acquireServerLock(ae,{port:e.port??0,worktreeRoot:S,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!Y)try{assertCompatibleStateManifest({lockDir:ae,shadowRepoDir:resolveShadowDir(S)})}catch(e){throw releaseServerLock(ae),e}let oe=createBasenameIndex(),se=(e,t)=>oe.resolveEmbed(e,t),ce=(e,S)=>{let w=oe.resolveEmbed(e,S);if(!w&&e.includes(`/`)&&(w=e.replace(/^\.?\//,``)),!w)return null;let E=resolve(t,w),D=resolve(t);if(E!==D&&!E.startsWith(`${D}/`))return null;try{let e=statSync(E);return e.isFile()?e.size:null}catch{return null}},ue,de,fe,me,ge,_e,ve,ye=null,Ce=null,we=null,Te=null,De=null,je=new Set,Me=!1,Pe,Ie,Re,ze=new Promise((e,t)=>{Ie=e,Re=t});function Be(e){ye?.signal(e)}let Ve=2e3,Ue=null;function We(){Ue!==null&&clearTimeout(Ue),Ue=setTimeout(()=>{Ue=null,de.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let Ge=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),Ke=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||Ge.setRenamed(e,t)},Xe=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(Ge.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Ge.setDeleted(e)}},$e=e=>{isSystemDoc(e)||isConfigDoc(e)||Ge.delete(e)};try{ue=createContentFilter({projectDir:S,contentDir:t,onAfterRebuild:()=>{de.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{fe.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let{prunedFiles:e,prunedFolders:t}=reconcileFileIndexAfterFilterRebuild(zt),S=e+t;S>0?getLogger(`server-factory`).info({pruned:S,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):getLogger(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)}}}),de=new BacklinkIndex({projectDir:S,contentDir:t,contentFilter:ue}),fe=new TagIndex({contentDir:t,contentFilter:ue});try{fe.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}me={current:B},ge=createPersistenceExtension({contentDir:t,projectDir:S,gitEnabled:O,commitDebounceMs:k,wipRef:j,shadowRef:me,contentRoot:H,backlinkIndex:de,configHomedirOverride:F,getCurrentBranch:()=>Bt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce,getPrincipal:()=>De,onAgentCommit:()=>ye?.signal(`session-activity`),onDiskFlush:(e,t,S,w)=>{ye?.emitDiskAck(e,t),!(isSystemDoc(e)||isConfigDoc(e))&&assetReferencesChanged(w,S)&&(Te?.(),Be(`files`))},onConfigRejected:(e,t)=>ye?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),_e=new Hocuspocus({quiet:w,debounce:E,maxDebounce:D,extensions:[ge.extension]});let q=_e.shouldUnloadDocument.bind(_e);_e.shouldUnloadDocument=e=>{if(je.has(e)||Me&&q(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:q(e)},Pe=async e=>{je.add(e);try{await _e.unloadDocument(e)}finally{je.delete(e)}},ye=new CC1Broadcaster(_e),Ce=new AgentFocusBroadcaster(_e),we=new AgentPresenceBroadcaster(_e),ve=new AgentSessionManager(_e);let Y=createLiveDerivedIndexExtension({backlinkIndex:de,tagIndex:fe,signalChannel:Be});_e.configuration.extensions.push(Y),_e.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,S=parseHocuspocusAuthToken(t),w=S?.expectedServerInstanceId;if(typeof w==`string`&&w.length>0&&w!==ne)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${w}, this server is ${ne}`);let E=S?.expectedBranch,D=getActiveBranch();if(typeof E==`string`&&E.length>0&&E!==D)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${E}, server is on ${D}`);if(!S)return;let O=e.context;typeof S.principalId==`string`&&(De&&S.principalId===De.id?O.principalId=De.id:De?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:S.principalId,loaded:De.id})):O.principalId=S.principalId),typeof S.tabSessionId==`string`&&(O.tabSessionId=S.tabSessionId),O.kind=`human`}}),_e.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,S=t.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S))throw Error(`config-doc admission requires loopback peer (peer=${S}, doc=${e.documentName})`);let w=e.requestHeaders,E=(w&&typeof w.get==`function`?w.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(E))throw Error(`config-doc admission requires loopback Host header (host=${E??`<absent>`}, doc=${e.documentName})`)}});let ee=resolve(t);function te(e){if(!isSafeDocName(e))return null;let t=resolve(ee,`${e}${getDocExtension(e)}`);return!t.startsWith(`${ee}/`)&&t!==ee?null:t}_e.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:Ge,resolveFilePath:te,fileExists:existsSync})}}),_e.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 ae=createApiExtension({hocuspocus:_e,sessionManager:ve,contentDir:t,contentFilter:ue,serverInstanceId:ne,getFileIndex:()=>zt?zt.getFileIndex():new Map,getFolderIndex:()=>zt?zt.getFolderIndex():new Map,getAliasMap:()=>zt?zt.getAliasMap():new Map,rescanFiles:()=>zt?.rescanFromDisk(),enableTestRoutes:L,shadowRef:me,flushGitCommit:()=>ge.flushPendingGitCommit(),flushContributors:()=>ge.flushContributors(),getCurrentBranch:()=>Bt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ye?.getLatestDiskAckSVsAsBase64()??{},contentRoot:H,backlinkIndex:de,tagIndex:fe,signalChannel:Be,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Vt,localOpCliArgs:J,projectDir:S,resolveEmbed:se,getPrincipal:()=>De,forceUnloadDocument:Pe,ready:ze,recentlyRemovedDocs:Ge,serializeDoc:st,onReferencedAssetsCacheInvalidator:e=>{Te=e}});_e.configuration.extensions.push(ae),_e.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:me,contentRoot:H,getCurrentBranch:()=>Bt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce})),_e.configuration.extensions.push(createSyncHandshakeSpanExtension()),_e.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>Vt,projectDir:S,contentDir:t}))}catch(e){throw releaseServerLock(ae),e}let nt=null,rt=new Map,it=[];function at(e,t){let S=resolve(e,`rescue`),w=resolve(S,`${t}${getDocExtension(t)}`);return w.startsWith(`${S}/`)?w:null}function st(e){let t=_e.documents.get(e);if(!t)return null;let{frontmatter:S,body:w}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(S,w)}let vt=(e,t)=>applyExternalChange(_e,e,t,se,ce);function Tt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Et=e=>{if(!e)return;let t=`[[${e}]]`;for(let[S]of _e.documents){if(isSystemDoc(S)||isConfigDoc(S))continue;let w=_e.documents.get(S);if(!w)continue;let E=w.getText(`source`).toString();if(E.includes(t))try{w.transact(()=>{applyDiskContentToDoc(w,E,se,S)},FILE_WATCHER_ORIGIN)}catch(t){ee.error({err:t,docName:S,assetBasename:e},`[asset-event] failed to re-render ${S} for asset basename ${e}`)}}},Dt=null,jt=e=>{e&&(Dt===null&&(Dt=new Set,setImmediate(()=>{let e=Dt;if(Dt=null,e)try{for(let t of e)Et(t)}catch(t){ee.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Dt.add(e))};function Mt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Ft(e){try{switch(e.kind){case`create`:ee.info({docName:e.docName},`[reconcile] create: ${e.docName}`),de.updateDocumentFromMarkdown(e.docName,e.content),We(),fe.updateDocumentFromMarkdown(e.docName,e.content),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),$e(e.docName);break;case`update`:{let{docName:t,content:S}=e,w=_e.documents.get(t);if(!w){de.updateDocumentFromMarkdown(t,S),We(),fe.updateDocumentFromMarkdown(t,S),Be(`backlinks`),Be(`graph`),Be(`tags`);return}let E=getReconciledBase(t)??``,D=st(t)??E,O=reconcile({docName:t,base:E,ours:D,theirs:S}),k=contentHash(E).slice(0,6),j=contentHash(D).slice(0,6),F=contentHash(S).slice(0,6);switch(ee.info({docName:t,base:k,ours:j,theirs:F,result:O.kind},`[reconcile] ${t} base=${k} ours=${j} theirs=${F} result=${O.kind}`),O.kind){case`noop`:Tt(w),de.updateDocumentFromMarkdown(t,S),We(),fe.updateDocumentFromMarkdown(t,S),Be(`backlinks`),Be(`graph`),Be(`tags`);break;case`clean`:try{vt(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),Tt(w),de.updateDocumentFromMarkdown(t,S),We(),fe.updateDocumentFromMarkdown(t,S),Be(`backlinks`),Be(`graph`),Be(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,S),Tt(w)}break;case`merged`:try{vt(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),Tt(w),de.updateDocumentFromMarkdown(t,S),We(),fe.updateDocumentFromMarkdown(t,S),Be(`backlinks`),Be(`graph`),Be(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,S),Tt(w)}break;case`conflicts`:try{vt(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),incrementConflict(),de.updateDocumentFromMarkdown(t,S),We(),fe.updateDocumentFromMarkdown(t,S),Be(`backlinks`),Be(`graph`),Be(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,S)}{let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{incrementConflict();let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,O.reason);break}}break}case`delete`:{let{docName:t}=e,S=_e.documents.get(t);if(!S){de.deleteDocument(t),We(),fe.deleteDocument(t),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),Xe(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let w=getReconciledBase(t)??``,E=st(t)??``,D=E!==w;if(D&&me.current){let e=me.current,S=Bt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,H??``,{kind:`external-change-rescue`,docName:t,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{ee.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),de.deleteDocument(t),We(),fe.deleteDocument(t),ee.info({docName:t,isDirty:D},`[reconcile] delete: ${t} (dirty=${D})`),_e.closeConnections(t),await Pe(S),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),Xe(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:S,content:w}=e,E=_e.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(S,w),de.renameDocument(t,S,w),We(),fe.renameDocument(t,S,w),E){let e=E.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,S)}ee.info({oldDocName:t,newDocName:S},`[reconcile] rename: ${t} → ${S}`),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),Ke(t,S),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:S,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,S=_e.documents.get(t);if(!S)return;let w=st(t);w===null?ee.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,w);let E=S.getMap(`lifecycle`);E.set(`status`,`conflict`),E.set(`reason`,`conflict-markers`),ee.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:oe.add(e.relativePath),Be(`files`),jt(basename(e.relativePath));break;case`asset-delete`:oe.remove(e.relativePath),Be(`files`),jt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:Be(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let S=Mt(e);ee.error({err:t,kind:e.kind,label:S},`[reconcile] failed to handle ${e.kind} for ${S}`)}}let It=[];async function Lt(e){if(isBatchInProgress()){It.push(e);return}await Ft(e)}async function Rt(){let e=It.splice(0,It.length);for(let t of e)await Ft(t)}let zt=null,Bt=null,Vt=null,Ht=null;async function Ut(e){if(_e.documents.size===0)return;let t=!1,S=new Promise(e=>{_e.configuration.extensions.push({async afterUnloadDocument({instance:S}){!t&&S.getDocumentsCount()===0&&(t=!0,e())}})}),w=Array.from(_e.documents.keys());_e.closeConnections(),_e.flushPendingStores();for(let e of _e.documents.values())e.getConnectionsCount()===0&&_e.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let E,D=new Promise((S,D)=>{E=setTimeout(()=>{t=!0;let S=Array.from(_e.documents.keys()),E=[],O=[];if(me.current){for(let e of S)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=st(e);if(t===null){ee.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),O.push(e);continue}let S=at(me.current.gitDir,e);if(!S){ee.warn({docName:e,gitDir:me.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),O.push(e);continue}mkdirSync(dirname(S),{recursive:!0}),writeFileSync(S,t,`utf-8`),incrementRescueBuffer(),E.push(e),ee.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){O.push(e),ee.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else ee.warn({stillLoadedCount:S.length},`[rescue] shadow repo unavailable at flush timeout — ${S.length} doc(s) will be lost: [${S.join(`, `)}]`),O.push(...S);let k=E.length>0||O.length>0?` — rescued [${E.join(`, `)}]${O.length>0?`, lost [${O.join(`, `)}]`:``}`:``;D(Error(`flushAllStoresAndWait timeout after ${e}ms — ${S.length}/${w.length} docs did not unload: [${S.join(`, `)}]${k}`))},e)});try{await Promise.race([S,D])}finally{E!==void 0&&clearTimeout(E)}}async function Wt(){return Ht||(Ht=(async()=>{let e=Date.now(),t=[];Me=!0,Ue!==null&&(clearTimeout(Ue),Ue=null);let w,E=await Promise.race([ze.then(()=>`completed`,e=>(ee.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{w=setTimeout(()=>e(`timeout`),5e3)})]);w!==void 0&&clearTimeout(w),E===`timeout`&&ee.warn({},`[server] init did not complete within 5s during shutdown`);let D=_e.documents.size;try{try{try{Bt&&=(await Bt.unsubscribe(),null),zt&&=(await zt.unsubscribe(),null);for(let{docName:e,cleanup:t}of it)try{await t()}catch(t){ee.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}it.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ye?.destroy(),we?.destroy(),nt&&=(await nt.disconnect(),null);for(let[e,t]of rt)try{await t.disconnect()}catch(t){ee.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}rt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ve.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Ut(q)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ge.flushPendingGitCommit(),await ge.waitForPendingCommits()})(),new Promise((t,S)=>{e=setTimeout(()=>S(Error(`L2 git flush timeout`)),q)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Vt&&=(await Vt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(me.current){try{let e=(await esm_default({baseDir:S,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(me.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(me.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let w=Date.now()-e;t.length===0?ee.info({documentCount:D,durationMs:w},`[server] shutdown flushed ${D} documents in ${w}ms`):ee.warn({documentCount:D,durationMs:w,phaseErrors:t},`[server] shutdown flushed ${D} documents in ${w}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ae)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),ee.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)})}}})(),Ht)}let Kt=[];async function $t(){try{De=await loadPrincipal(S),ee.info({principalId:De.id},`[server] principal loaded`)}catch(e){ee.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!me.current)try{me.current=await initShadowRepo(S),ee.info({gitDir:me.current.gitDir},`[server] history repo initialized at ${me.current.gitDir}`)}catch(e){ee.error({err:e},`[server] history repo init failed`),Kt.push(`shadow-repo`)}if(me.current){let e=null;try{e=loadRenameLogIndex(me.current.gitDir),sweepLazyPopOrphans(me.current.gitDir,e),setRenameLogIndex(me.current.gitDir,e),ee.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){ee.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(me.current,e,{rebuild:!0}),new Promise((e,S)=>setTimeout(()=>S(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){ee.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(me.current)try{await shadowGit(me.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`)){ee.warn({},`[server] history repo appears corrupted — reinitializing`);try{me.current=await initShadowRepo(S)}catch(e){ee.error({err:e},`[server] history repo reinit failed`),me.current=void 0,Kt.includes(`shadow-repo`)||Kt.push(`shadow-repo`)}}else ee.error({err:e},`[server] history repo check failed (transient?)`)}if(me.current)try{let e=resolve(me.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let w=null;try{w=(await esm_default({baseDir:S,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(w!==null){if(w!==t){let e=`main`;try{let t=(await esm_default({baseDir:S,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}ee.info({lastKnownHead:t,currentHead:w,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=import`);try{await commitUpstreamImport(me.current,H??``,t,w,e),incrementUpstreamImport()}catch(e){ee.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else ee.info({currentHead:w},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=noop`);try{writeFileSync(e,w,`utf-8`)}catch(e){ee.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){ee.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,S);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,S=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;ee.warn({journalVersion:e.journal.version,fromPath:t,toPath:S,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${S}`)}}catch(e){ee.error({err:e},`[server] managed rename recovery failed`),Kt.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(S);(e.deleted>0||e.errors>0)&&ee.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){ee.error({err:e},`[server] upload-tempfile sweep failed`),Kt.push(`upload-tempfile-sweep`)}try{nt=await _e.openDirectConnection(SYSTEM_DOC_NAME),ye?.emitServerInfo(ne,getActiveBranch())}catch(e){ee.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Kt.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await _e.openDirectConnection(e);rt.set(e,t)}catch(t){ee.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Kt.push(`config-doc:${e}`)}let w=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,S)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,S)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,S,F)]]);for(let e of CONFIG_DOC_NAMES){let t=w.get(e);if(t)try{ee.info({docName:e,path:t},`[config-file-watcher] starting`);let S=await startConfigFileWatcher(t,t=>{let S=_e.documents.get(e);ee.info({docName:e,hasDocument:S!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let w=applyExternalConfigChange(S??null,e,t,ge.configPersistenceCtx);if(ee.info({docName:e,outcome:w},`[config-file-watcher] applyExternalConfigChange outcome`),e===`__config__/project`||e===`__local__/project`){let e=te();Vt?.setEnabled(e).catch(t=>{ee.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});it.push({docName:e,cleanup:S}),ee.info({docName:e,path:t},`[config-file-watcher] started`)}catch(S){ee.warn({err:S,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),Kt.push(`config-file-watcher:${e}`)}}try{let e=resolve(t,`.okignore`),w=resolve(S,`.gitignore`),E=null;try{let e=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:S,encoding:`utf-8`,timeout:5e3});if(e.status===0&&e.stdout){let t=join(resolve(S,e.stdout.trim()),`info`,`exclude`);existsSync(dirname(t))&&(E=t)}}catch{}let D=E?[e,w,E]:[e,w],O=ee;O.info({okignorePath:e,gitignorePath:w,gitInfoExcludePath:E},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let k=await startMultiPathConfigFileWatcher(D,(t,w)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(_e.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,w,ge.configPersistenceCtx);O.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){O.error({err:e,changedPath:relative(S,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let E=await ue.rebuildIgnorePatterns();if(E.ok)O.info({changedPath:relative(S,t),patternCount:E.patternCount,nestedFileCount:E.nestedFileCount,durationMs:E.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ye?.signal(`files`);else{let e=relative(S,t)||`.`;O.warn({changedPath:e,error:E.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ye?.emitConfigIgnoreNestedError(e,E.error.message)}})().catch(e=>{O.error({err:e,changedPath:relative(S,t)||`.`},`[ignore-watcher] handler threw`)})});it.push({docName:`__ignore-files__`,cleanup:k}),O.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] multi-path watcher started`)}catch(e){ee.warn({err:e,projectDir:S,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Kt.push(`ignore-files-watcher`)}let E=resolveGitDir(S),D=E?readBranchFromHead(E)??`main`:`main`;switchReconciledBaseScope(D),de.switchBranch(D);try{{let e=getActiveBranch();try{if(await de.loadFromDisk(e)){let t=await de.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&ee.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await de.rebuildFromDisk(e);de.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){ee.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}zt=await startWatcher(t,Lt,ue),fe.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,w)=>{e++,ee.warn({reason:t,code:S,path:w},`[basename-index] skipped entry during seed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Kt.push(`basename-index-partial`))}catch(e){ee.error({err:e},`[basename-index] startup seed failed`),Kt.push(`basename-index`)}}catch(e){ee.error({err:e},`[server] disk bridge watcher failed to start`),Kt.push(`file-watcher`)}try{Bt=await startHeadWatcher(S,async({trigger:e})=>{if(ee.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),_e.flushPendingStores(),await ge.flushPendingGitCommit(),setBatchInProgress(!0),me.current){let e=getActiveBranch(),t=resolveGitDir(S),w=t?readBranchFromHead(t)??e:e,E=[];for(let[e,t]of _e.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let S=null;if(t.transact(()=>{S=st(e)},PARK_SNAPSHOT_ORIGIN),S===null)continue;let w=getReconciledBase(e)??S;E.push({docName:e,markdown:S,diskSnapshot:w})}if(E.length>0)try{let t=await parkBranch(me.current,e,SERVICE_WRITER.id,E,w);t&&(incrementPark(),ee.info({count:E.length,branch:e,sha:t.slice(0,8)},`[history] parked ${E.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){ee.error({err:e},`[shadow] park failed`)}}},async e=>{let S=It.length,w=e.newBranch??`main`;if(ee.info({kind:e.batchKind,headMoved:e.headMoved,docs:S,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${S}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await Rt(),await ge.flushDeferredStores(`within-branch`),Vt!==null)try{await Vt.reconcileConflictsFromGit()}catch(e){ee.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),It.splice(0,It.length),switchReconciledBaseScope(w),Ue!==null&&(clearTimeout(Ue),Ue=null),de.switchBranch(w),ue.rebuildDirCount();try{let e=0;oe.clear(),seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,E)=>{e++,ee.warn({reason:t,code:S,path:E,branch:w},`[basename-index] skipped entry during branch-switch reseed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e,branch:w},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Kt.includes(`basename-index-partial`)||Kt.push(`basename-index-partial`))}catch(e){ee.error({err:e,branch:w},`[basename-index] branch-switch reseed failed`)}for(let[e,S]of _e.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let E=safeContentPath(e,t);if(!existsSync(E)){let t=getReconciledBase(e)??``,E=st(e)??``;if(E!==t&&me.current){let t=me.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,H??``,{kind:`external-change-rescue`,docName:e,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:w,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{ee.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),ee.info({docName:e,branch:w},`[branch-switch] tombstone: ${e} (not on ${w})`);continue}let D=readFileSync(E,`utf-8`);vt(e,D),setReconciledBase(e,D),ee.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){ee.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}ee.info({branch:w,docCount:_e.documents.size},`[branch-switch] loaded branch ${w} (${_e.documents.size} docs)`);try{if(await de.loadFromDisk(w)){let e=await de.reconcileWithDisk(w);(e.added>0||e.updated>0||e.deleted>0)&&ee.info(e,`[backlinks] branch-switch reconcile for ${w}`)}else await de.rebuildFromDisk(w);de.saveToDisk(w).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${w}:`,e)})}catch(e){ee.error({err:e,branch:w},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(fe.init(),me.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of _e.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let S=await readParkedState(me.current,w,SERVICE_WRITER.id,t);if(!S||S.markdown===S.diskSnapshot)continue;let E=getReconciledBase(t);if(!E)continue;let D=reconcile({docName:t,base:S.diskSnapshot,ours:S.markdown,theirs:E});switch(D.kind){case`merged`:case`clean`:vt(t,D.newContent),setReconciledBase(t,D.newContent),e++;break;case`conflicts`:vt(t,D.newContent),setReconciledBase(t,D.newContent),incrementConflict(),e++;{let e=_e.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){ee.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&ee.info({count:e,branch:w},`[branch-switch] restored ${e} parked docs on ${w}`)}if(e.oldBranch?.startsWith(`detached-`)&&me.current)try{let t=shadowGit(me.current),S=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(S){for(let e of S.split(`
3507
+ `))e&&await t.raw(`update-ref`,`-d`,e);ee.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){ee.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ge.flushDeferredStores(`discard-stale`),ye?.emitBranchSwitched(w)}if(e.headMoved&&e.newHead&&me.current&&S>0){let t=H??`.`;try{let S=await commitUpstreamImport(me.current,t,e.oldHead,e.newHead,w);incrementUpstreamImport(),ee.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:S.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${S.slice(0,8)}`)}catch(e){ee.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){ee.error({err:e},`[server] HEAD watcher failed to start`),Kt.push(`head-watcher`)}function O(e){for(let w of e)try{let e=relative(t,join(S,w));if(e.startsWith(`..`))continue;let E=stripDocExtension(e),D=_e.documents.get(E);if(!D)continue;let O=st(E);O===null?ee.warn({docName:E,file:w},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(E,O);let k=D.getMap(`lifecycle`);k.set(`status`,`conflict`),k.set(`reason`,`sync-merge-conflict`),ee.info({docName:E,file:w},`[sync] marked loaded content conflict`)}catch(e){ee.warn({err:e,file:w},`[sync] failed to mark loaded content conflict`)}}let k=J?.[0]??`open-knowledge`,j=[`-c`,`credential.helper=!${J&&J.length>1?J.join(` `):k} auth git-credential`];try{Vt=new SyncEngine({projectDir:S,contentDir:t,contentFilter:ue,contentRoot:H,syncEnabled:te(),credentialArgs:j,cc1Broadcaster:ye,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||ge.flushDeferredStores(`within-branch`).catch(e=>{ee.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{ee.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:O,onAutoDisable:async e=>{ee.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:S,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||ee.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,S)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await Vt.start()}catch(e){ee.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Vt=null}Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`)}return $t().then(Ie,Re),{hocuspocus:_e,sessionManager:ve,cc1Broadcaster:ye,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,contentFilter:ue,basenameIndex:oe,serverInstanceId:ne,destroy:Wt,ready:ze,degraded:Kt,lockDir:ae,get syncEngine(){return Vt}}}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let S=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&S.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let w=resolve(e,t);try{existsSync(w)&&statSync(w).isDirectory()&&S.push(`${t}/`)}catch{}}return S}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3;async function bootServer(e){initTelemetry();let{kind:t,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":t};return S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S)),withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,S=e.attachUiSibling??!0,w=e.idleShutdownMs,E=e.log??getLogger(`boot`),D=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,O=e.lockKind??D??`interactive`,{createServer:k}=await import(`node:http`),{updateServerLockPort:j}=await import(`./server-lock-v2ktHD7l-C-3wEnoU.mjs`),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){E.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let H=e.gitPreflight??assertGitAvailable;try{H()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,S=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),E.warn({event:`git_preflight_fail`,platform:e.platform,reason:S,detectedVersion:t},S===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),e}let q=findLegacyRuntimeFiles(B);q.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${q.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let J=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,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:O,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore}),{hocuspocus:Y,destroy:ee,ready:te,degraded:ne,lockDir:ae,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce}=J,ue=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),de=e.port??0,fe=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ue}:${de}`,log:E}),me=k();me.headersTimeout=3e4,me.requestTimeout=6e4;let ge=e.serveContentAssets?createAssetServeMiddleware({contentFilter:J.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,_e=!1;if(e.reactShellDistDir)try{acquireUiLock(ae,{port:0,worktreeRoot:e.projectDir??e.contentDir}),_e=!0}catch(e){if(e instanceof UiLockCollisionError)E.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:ae},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await ee().catch(()=>{}),e}let ve=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ye=mountMcpAndApi({httpServer:me,hocuspocus:Y,mcpHttpHandler:fe,log:E,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ge,reactShellMiddleware:ve}),Ce=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},we=null;w!==null&&(we=attachIdleShutdown({httpServer:me,thresholdMs:w??DEFAULT_IDLE_THRESHOLD_MS,log:E,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await Ce()})})),await restoreLifecycleFromConflictsJson({hocuspocus:Y,projectDir:e.projectDir??e.contentDir,log:E});try{await new Promise((t,S)=>{let w=e=>S(e);me.once(`error`,w),me.listen(e.port,e.host,()=>{me.removeListener(`error`,w),t()})})}catch(e){if(_e)try{releaseUiLock(ae)}catch(e){E.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await ee().catch(()=>{}),e}let Te=me.address(),De=typeof Te==`object`&&Te?Te.port:e.port??0;if(de=De,j(ae,De),_e&&updateUiLockPort(ae,De),S&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ae,log:E})}catch(e){E.warn({err:e},`spawnUiSiblingFn failed`)}let je=!1,Me=async(e,t)=>{let S;try{await Promise.race([t(),new Promise((t,w)=>{S=setTimeout(()=>{w(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),S.unref?.()})])}finally{S!==void 0&&clearTimeout(S)}};return Ce=async()=>{if(je)return;je=!0;let e=[],t=async(t,S)=>{try{await Me(t,S)}catch(S){e.push(S),E.warn({err:S,step:t},`bootServer destroy step failed`)}};try{we?.detach()}catch(t){e.push(t),E.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ye.shutdown()),await t(`mcpHttpHandler.close`,()=>fe.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ye.wss.close(S=>S?t(S):e())})),await t(`httpServer.closeAllConnections`,async()=>{me.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{me.close(S=>S&&S.code!==`ERR_SERVER_NOT_RUNNING`?t(S):e())})),await t(`destroyHocuspocus`,()=>ee()),_e&&await t(`releaseUiLock`,async()=>releaseUiLock(ae)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:me,destroy:Ce,lockDir:ae,contentDir:e.contentDir,port:De,ready:te,degraded:ne,didAutoInit:F,serverInstance:J}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:S,log:w}=e,E,D;try{E=new ConflictStore(S),D=E.list()}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(D.length===0)return;let O=null;try{let e=resolveGitDir(S),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){E.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:D.length}));return}let w=(await simpleGit({baseDir:S,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();O=new Set(w?w.split(`
3508
3508
  `).map(e=>e.trim()).filter(Boolean):[])}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(O!==null){let e=0;for(let t of D)O.has(t.file)||(E.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:D.length-e})),D=D.filter(e=>O?.has(e.file)),D.length===0)return}for(let e of D){let S=stripDocExtension(e.file),E=null,D=!1;try{E=await t.openDirectConnection(S);let e=E.document;if(!e)continue;let w=e.getMap(`lifecycle`);w.set(`status`,`conflict`),w.set(`reason`,`conflict-markers`),D=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":S}))}catch(e){w.warn({err:e,docName:S},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(E)try{await E.disconnect()}catch(e){w.warn({err:e,docName:S,restored:D},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),S=e.platformName??process.platform,w=e.env??process.env;return S===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):S===`win32`?existsSync(join(w.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],S=e.toLowerCase();if(t.includes(S))return S}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let S=t===1?e:`${e}.${t-1}`,w=`${e}.${t}`;try{renameSync(S,w)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),S=MAX_AGE_DAYS*24*60*60*1e3,w=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let S=statSync(join(e,t));return{name:t,mtime:S.mtimeMs,size:S.size}}catch{return null}}).filter(Boolean);for(let E of w)if(t-E.mtime>S)try{unlinkSync(join(e,E.name))}catch{}let E=w.filter(e=>t-e.mtime<=S).sort((e,t)=>e.mtime-t.mtime),D=E.reduce((e,t)=>e+t.size,0);for(let t of E){if(D<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),D-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),S=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(S),setTimeout(()=>pruneLogsDir(OK_LOGS_DIR),5e3);let w=import_pino.default.destination({dest:S,append:!0,sync:!1});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},w)}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),S=0;for(;S<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:S};let w=dirname(t);if(w===t)return null;t=w,S+=1}return null}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,S){super(e,S),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),S=resolve(t,`.git`),w=resolve(S,`HEAD`),E=!1;if(existsSync(S)){if(!statSync(S).isDirectory()||existsSync(w))return{didInit:!1};console.log(`[project-git] detected partial .git/ — running git init to repair`),E=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let D=``;try{D=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let S=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)}`,S,{cause:e})}if(!existsSync(w))throw new ProjectGitInitError(`git init reported success but ${S}/HEAD is missing (partial init detected)`,D);return E?(console.log(`[project-git] backfilled missing .git/HEAD at ${t}`),{didInit:!0,repaired:!0}):(console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0})}async function resolvePackageVersion(e,t){let S;try{S=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(S),w=0;w<32;w+=1){let S=join(t,`package.json`);if(existsSync(S))try{let t=JSON.parse(await readFile$1(S,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let w=dirname(t);if(w===t)return;t=w}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:S}of HOME_PATH_PATTERNS)t=t.replace(e,S);return t}function serializeError(e,t=0,S=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(S.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};S.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,S)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let w=e;return{name:String(w.name??`ObjectError`),message:scrubPaths(String(w.message??``))??``,stack:scrubPaths(w.stack),code:w.code,cause:w.cause===void 0?void 0:serializeError(w.cause,t+1,S)}}return{name:`UnknownError`,message:String(e)}}export{UiLockCollisionError as $,_coercedNumber as $i,reconcile as $n,validateAgentId as $r,formatContributors as $t,MCP_CONNECTION_ID_HEADER as A,ORPHAN_MODES as Ai,isSystemDoc as An,serializeError as Ar,createContentFilterAsync as At,ROLLBACK_ORIGIN as B,isOrphanMode as Bi,parseGitVersion as Bn,tracedAppendFileSync as Br,createTestLogger as Bt,HocuspocusAuthRejection as C,CC1_CONTRACT_VERSION as Ci,isHocuspocusAuthRejectionReason as Cn,safeContentPath as Cr,compareSemver as Ct,LOG_MD_TEMPLATE as D,EDITOR_LABELS as Di,isPathWithinDir as Dn,saveInMemoryCheckpoint as Dr,createApiExtension as Dt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as E,DEFAULT_SIGTERM_GRACE_MS as Ei,isPairedWriteOrigin as En,sanitizeClientName as Er,contributorCount as Et,MissingOkConfigError as F,colorFromSeed as Fi,loggerFactory as Fn,splitMarkdownBlocks as Fr,createOsProbe as Ft,STARTER_PACKS as G,array as Gi,readAllTargets as Gn,tracedRenameSync as Gr,ensureProjectGit as Gt,SKILL_INSTALL_EVENTS_FILE_REL as H,locateIssue as Hi,parseKeepaliveConnectionId as Hn,tracedMkdir as Hr,detectGit as Ht,OBSERVER_SYNC_ORIGIN as I,defaultScheduler as Ii,mountMcpAndApi as In,startWatcher as Ir,createPersistenceExtension as It,STATE_MANIFEST_FILENAME as J,looseObject as Ji,readSkillInstallStateSnapshot as Jn,tracedUnlinkSync as Jr,extractWikiLinksFromMarkdown as Jt,STARTER_PACK_IDS as K,boolean$1 as Ki,readBranchFromHead as Kn,tracedRmSync as Kr,errorResponse as Kt,OK_OKIGNORE_TEMPLATE as L,humanFormat as Li,normalizeFsPath as Ln,streamingProblemEvent as Lr,createServer$1 as Lt,MIN_GIT_VERSION as M,SKILL_STATE_TARGETS as Mi,listRescueCheckpoints as Mn,shadowGit as Mr,createFileLogger as Mt,MISSING_OK_CONFIG_MESSAGE as N,SPAWN_ERROR_LOG as Ni,listStarterPacks as Nn,shutdownTelemetry as Nr,createLiveDerivedIndexExtension as Nt,MANAGED_RENAME_ORIGIN as O,EXECUTABLE_BLOCKLIST_EXTENSIONS as Oi,isProjectRoot as On,saveVersion as Or,createAssetServeMiddleware as Ot,McpLogger as P,SYSTEM_DOC_NAME as Pi,loadPrincipal as Pn,spawnDetached as Pr,createMcpHttpHandler as Pt,TagIndex as Q,url as Qi,readUiLock as Qn,updateUiLockPort as Qr,formatAuthRejectionWire as Qt,PinoLogger as R,iconFromClientName as Ri,packageVersionMajorMinor as Rn,swapContributors as Rr,createServerObserverExtension as Rt,HOCUSPOCUS_AUTH_REJECTION_REASONS as S,ASSET_EXTENSIONS as Si,isConfigDoc as Sn,runWithMcpLogger as Sr,commitWipFromTree as St,INSTALLED_AGENTS_SCHEMES as T,DEFAULT_SERVER_HOST as Ti,isLoopbackAddress as Tn,safetyCheckpoint as Tr,contentHash as Tt,STARTER_FOLDERS as U,ZodNumber$1 as Ui,pathToDocName as Un,tracedMkdirSync as Ur,detectProjectShape as Ut,SERVICE_WRITER as V,OK_PROJECT_MARKER as Vi,parseHocuspocusAuthToken as Vn,tracedLinkSync as Vr,detectClaudeDesktopPresence as Vt,STARTER_FOLDER_FRONTMATTER_FILENAME as W,any$1 as Wi,planSeed as Wn,tracedRename as Wr,emitPreflightFailureSpan as Wt,SeedRootDirError as X,object$1 as Xi,readTargetRecordedAt as Xn,tracedWriteFileSync as Xr,findEnclosingGitRoot as Xt,SeedPrerequisiteError as Y,number$1 as Yi,readStateManifest as Yn,tracedWriteFile as Yr,fallbackPaths as Yt,StateManifestError as Z,string$2 as Zi,readTargetVersion as Zn,updateLastKnownHash as Zr,findEnclosingProjectRoot as Zt,FILE_WATCHER_ORIGIN as _,writeConfigPatch as _i,installPrettyZodErrors as _n,rewriteWikiLinksForDocumentRename as _r,classifyFsPath as _t,AgentPresenceBroadcaster as a,writeTargetVersion as ai,getLogger as an,removeLastKnownHash as ar,assertGitAvailable as at,GitNotAvailableError as b,resolveShadowDir as bi,isAllowedApiOrigin as bn,runCloneSubprocess as br,commitUpstreamImport as bt,BacklinkIndex as c,JSONRPCMessageSchema as ci,getMetrics as cn,resolveContentDir as cr,bootServer as ct,CONFLICT_MARKER_RE as d,isJSONRPCRequest as di,handleSpawnCursor as dn,resolveLockDir as dr,buildExecResult as dt,NEVER as ea,validateCloneInputs as ei,formatContributorsFrom as en,recordContributor as er,acquireUiLock as et,CURSOR_BUNDLE_PATHS_BY_PLATFORM as f,isJSONRPCResultResponse as fi,incrementCollabSocketFilteredError as fn,resolvePack as fr,buildInstructions as ft,FILE_SYSTEM_WRITER as g,withFileLockSync as gi,initTelemetry as gn,rewriteMarkdownLinksForDocumentRename as gr,classifyEvents as gt,DEFAULT_PACK_ID as h,resolveConfigPath as hi,initShadowRepo as hn,restoreLifecycleFromConflictsJson as hr,buildWipTree as ht,AgentFocusBroadcaster as i,writeStateManifest as ii,getLogFilePath as in,releaseUiLock as ir,assertCompatibleStateManifest as it,MCP_SERVER_NAME as j,ProblemDetailsSchema as ji,lastKnownHash as jn,setActiveSpanAttributes as jr,createExternalChangeHandler as jt,MAX_AGENT_SESSIONS as k,INLINE_RENDERABLE_EXTENSIONS as ki,isSelfWrite as kn,seedBasenameIndex as kr,createContentFilter as kt,CC1Broadcaster as l,LATEST_PROTOCOL_VERSION as li,getTracer as ln,resolveCursorBinaryDefault as lr,buildAndOpenSkill as lt,DEFAULT_CHECKPOINT_RETENTION as m,readConfigSafely as mi,initContent as mn,restoreContributors as mr,buildStarterFolderFrontmatterYaml as mt,AGENT_ID_RE as n,withSpan as ni,getCurrentMcpLogger as nn,registerAllTools as nr,applyExternalChange as nt,AgentSessionCapacityError as o,writeTracker as oi,getLogsDir as on,resetMetrics as or,assertNeverDiskEvent as ot,ConfigSchema as p,atomicWriteFileSync as pi,incrementServerObserverFire as pn,resolvePackageVersion as pr,buildSkillZip as pt,STARTER_TEMPLATES as q,literal as qi,readServerPackageVersion as qn,tracedRmdirSync as qr,evictStaleTrackerEntries as qt,AGENT_WRITE_ORIGIN as r,withSpanSync as ri,getLocalDir as rn,registerWrite as rr,applySeed as rt,AgentSessionManager as s,McpServer as si,getMeter as sn,resolveBundledSkillDir as sr,attachIdleShutdown as st,AGENT_ID_MAX_LEN as t,require_dist$1 as ta,validateSkillZip as ti,gcCheckpointRefs as tn,recordSkillInstallEvent as tr,applyAgentMarkdownWrite as tt,CONFIG_FILENAME as u,isInitializedNotification as ui,handleCollabSocketError as un,resolveCursorSpawnInvocation as ur,buildConfigYmlContent as ut,GIT_PREFLIGHT_FAIL_SPAN_NAME as v,GitDirAccessError as vi,installTestLoggers as vn,runAuthReposSubprocess as vr,clearContributors as vt,HocuspocusAuthTokenSchema as w,DEFAULT_GITHUB_OAUTH_CLIENT_ID as wi,isKnownPackId as wn,safeSubdir as wr,containsConflictMarkers as wt,GitTooOldError as x,ALL_EDITOR_IDS as xi,isAllowedWorkspaceHostHeader as xn,runDeviceFlowSubprocess as xr,commitWip as xt,GIT_UPSTREAM_WRITER as y,MalformedGitPointerError as yi,installUserSkill as yn,runAuthStatusSubprocess as yr,coercePackId as yt,ProjectGitInitError as z,isBranchNotFoundGitError as zi,parseAuthRejectionWire as zn,toBroadcasterKey as zr,createStreamingErrorWriter as zt};
3509
- //# sourceMappingURL=dist-xB__nIDC.mjs.map
3509
+ //# sourceMappingURL=dist-ON5FDO_b.mjs.map