@inkeep/open-knowledge 0.6.0 → 0.6.1-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.
- package/dist/THIRD_PARTY_NOTICES.md +5 -0
- package/dist/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +1 -1
- package/dist/cli.mjs +4 -4
- package/dist/constants-BM26wr_I.mjs +2 -0
- package/dist/{dist-C3d5vMka.mjs → dist-B5HqGe-T.mjs} +4 -4
- package/dist/{dist-DHCla-dZ.mjs → dist-D63H1tUT.mjs} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/init-C78yg1RT.mjs +1 -0
- package/dist/{init-DbKyc-NP.mjs → init-CQfnd-3b.mjs} +4 -4
- package/dist/loader-BhsLldPr.mjs +1 -0
- package/dist/{loader-DPtC9EX7.mjs → loader-Cjqy0gPl.mjs} +2 -2
- package/dist/preview-Bwb0FGD8.mjs +1 -0
- package/dist/{preview-DKceAysF.mjs → preview-EmjNeNJ2.mjs} +2 -2
- package/dist/public/assets/{ActivityModeContent-f87lu1R1.js → ActivityModeContent-C4c01qOn.js} +1 -1
- package/dist/public/assets/DocumentContext-uhIlIpEe.js +58 -0
- package/dist/public/assets/{GraphPanel-0aB3TF2C.js → GraphPanel-DtgS21kH.js} +9 -9
- package/dist/public/assets/{SettingsDialogBody-B_UH7Jye.js → SettingsDialogBody-B8fXoAN4.js} +2 -2
- package/dist/public/assets/{SourceEditor-C3ri5HiW.js → SourceEditor-D_Q7A0Ko.js} +2 -2
- package/dist/public/assets/config-validation-events-DxvmZCch.js +11 -0
- package/dist/public/assets/index-BxMSLdLS.css +1 -0
- package/dist/public/assets/index-IfVKoHR8.js +1915 -0
- package/dist/public/assets/{prop-types-C7ZcPhvT.js → prop-types-7zN8Zjxn.js} +1 -1
- package/dist/public/assets/{target-navigation-intent-B_XxwO2E.js → target-navigation-intent-P0Afv_xR.js} +1 -1
- package/dist/public/assets/{toggle-group-vVm0xmLD.js → toggle-group-Dy8vmQqh.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-CC-taYRN.js → typing-burst-detector-BCw2SXdM.js} +2 -2
- package/dist/public/index.html +8 -8
- package/dist/{repair-launch-json-C0A-MS1q.mjs → repair-launch-json-CenWWWSb.mjs} +2 -2
- package/dist/{repair-mcp-configs-C-anXKkD.mjs → repair-mcp-configs-GcOosvF9.mjs} +2 -2
- package/dist/{src-D4AydmJF.mjs → src-On1YQHmr.mjs} +2 -2
- package/dist/{start-BW-lqkFX.mjs → start-CVtbImgg.mjs} +2 -2
- package/dist/start-sSCTFYRL.mjs +1 -0
- package/package.json +1 -1
- package/dist/constants-BqW_5Zct.mjs +0 -2
- package/dist/init-_Gb8p_KN.mjs +0 -1
- package/dist/loader-BorPcYdC.mjs +0 -1
- package/dist/preview-BSw2DxmP.mjs +0 -1
- package/dist/public/assets/DocumentContext-BVFYhVUK.js +0 -58
- package/dist/public/assets/config-validation-events-BQa42yM4.js +0 -11
- package/dist/public/assets/index-7FUClmdK.css +0 -1
- package/dist/public/assets/index-ItRM_S62.js +0 -1915
- package/dist/start-CK8Xftdg.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&®istry.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&®istry.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&®istry.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&®istry.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(),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)}).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(),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(),pausedReason:string$2().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`]),content:string$2().optional()}).loose().refine(e=>e.strategy!==`content`||e.content!==void 0,{message:`content is required 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(),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()}).loose(),FolderConfigPutRequestSchema=object$1({path:string$2(),frontmatter: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`],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(),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(),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(),pausedReason:string$2().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`]),content:string$2().optional()}).loose().refine(e=>e.strategy!==`content`||e.content!==void 0,{message:`content is required 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(),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()}).loose(),FolderConfigPutRequestSchema=object$1({path:string$2(),frontmatter: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`],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}}var require_err_helpers=__commonJSMin$1(((e,t)=>{let S=e=>e&&typeof e.message==`string`,w=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return S(t)?t:void 0}else return S(t)?t:void 0},E=(e,t)=>{if(!S(e))return``;let D=e.stack||``;if(t.has(e))return D+`
|
|
@@ -1245,7 +1245,7 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
|
|
|
1245
1245
|
|
|
1246
1246
|
`}function buildWorkflowHandler(e,t,S,w){return async E=>{let D=typeof E.cwd==`string`?E.cwd:void 0,O=await resolveProjectConfigContext(t.resolveCwd,t.config,D);if(!O.ok)return textResult(`Error: ${O.error}`,!0);let k=E[S],j=typeof k==`string`?k:``;return textPlusStructured(`${buildWorkflowFrame(e)}${w(j,O.config.content.dir)}`,{previewUrl:null})}}async function resolveServerUrl(e,t){return typeof e==`function`?await e(t):e}async function resolveConfig(e,t){return typeof e==`function`?await e(t):e}async function resolveProjectConfigContext(e,t,S){let w;try{w=await e(S)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}try{let e=await resolveConfig(t,w);return{ok:!0,cwd:w,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function resolveProjectServerContext(e,t,S,w){let E=await resolveProjectConfigContext(e,t,w);if(!E.ok)return E;let{cwd:D,config:O}=E;try{return{ok:!0,cwd:D,config:O,url:await resolveServerUrl(S,D)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function normalizeDocName(e){let t=e.toLowerCase();return t.endsWith(`.md`)?{ok:!0,docName:e.slice(0,-3)}:t.endsWith(`.mdx`)?{ok:!0,docName:e.slice(0,-4)}:t.endsWith(`.markdown`)?{ok:!1,error:`Error: docName "${e}" ends in ".markdown", which is not a supported extension. Use ".md" or ".mdx", or strip the extension to let the server auto-detect.`}:{ok:!0,docName:e}}function normalizeResponse(e,t){if(e.ok){if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!0,data:t};let{ok:e,...S}=t;return{ok:!0,...S}}if(typeof t!=`object`||!t||Array.isArray(t))return{ok:!1,error:`Server returned HTTP ${e.status} with non-object body`};let S=t;if(typeof S.type==`string`&&typeof S.title==`string`){let{type:e,title:t,status:w,instance:E,detail:D,...O}=S;return{...O,ok:!1,error:t,type:e,...typeof w==`number`?{status:w}:{},...typeof E==`string`?{instance:E}:{},...typeof D==`string`?{detail:D}:{}}}let{ok:w,error:E,...D}=S,O=typeof E==`string`?E:typeof S.message==`string`?S.message:`Server returned HTTP ${e.status}`;return{...D,ok:!1,error:O}}async function httpGet(e,t){let S;try{S=await fetch(`${e}${t}`,{signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let w;try{w=await S.json()}catch(e){let t=e instanceof Error?e.message:String(e);return S.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${S.status} with non-JSON body: ${t}`}}return normalizeResponse(S,w)}async function httpPost(e,t,S){let w;if(S!==void 0)try{w=JSON.stringify(S)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}let E;try{E=await fetch(`${e}${t}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:w,signal:AbortSignal.timeout(3e4)})}catch(e){return{ok:!1,error:`Server unreachable: ${e instanceof Error?e.message:e}`}}let D;try{D=await E.json()}catch(e){let t=e instanceof Error?e.message:String(e);return E.ok?{ok:!1,error:`Server returned 2xx response with non-JSON body: ${t}`}:{ok:!1,error:`Server returned HTTP ${E.status} with non-JSON body: ${t}`}}return normalizeResponse(E,D)}function parseRenameCollidingPairs(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:S,to:w}=e;return typeof t==`string`&&typeof S==`string`&&typeof w==`string`?[{existing:t,incoming:S,to:w}]:[]}):[]}function mergeCascade(e,t){let S={...e},w=new Map;for(let[e,E]of Object.entries(t))if(E!==void 0)if(Array.isArray(E)){let t=Array.isArray(S[e])?[...S[e]]:[],D=w.get(e)??new Set(t.map(toDedupKey));w.set(e,D);for(let e of E){let S=toDedupKey(e);D.has(S)||(D.add(S),t.push(e))}S[e]=t}else S[e]=E;return S}function mergePatch(e,t){let S={...e};for(let[e,w]of Object.entries(t))if(w!==void 0){if(isEmpty$1(w)){delete S[e];continue}S[e]=w}return S}function isEmpty$1(e){return!!(e===null||typeof e==`string`&&e===``||Array.isArray(e)&&e.length===0)}function toDedupKey(e){return typeof e==`string`?`s:${e}`:typeof e==`number`?`n:${e}`:typeof e==`boolean`?`b:${e}`:e===null?`null`:e===void 0?`undefined`:`j:${JSON.stringify(e)}`}function resolveNestedFrontmatter(e,t){return resolveNestedFrontmatterWithSources(e,t).merged}function resolveNestedFrontmatterWithSources(e,t){let S=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``),w=S===``||S===`.`?[]:S.split(`/`).filter(e=>e.length>0),E={},D={},O=!1;for(let t=0;t<=w.length;t++){let S=t===0?``:w.slice(0,t).join(`/`),k=t===0?resolve(e,`.ok`,`frontmatter.yml`):resolve(e,S,`.ok`,`frontmatter.yml`);if(!existsSync(k))continue;let j=readFrontmatterYaml(k);if(j!=null){E=mergeCascade(E,j);for(let e of Object.keys(j))j[e]!==void 0&&(D[e]=S);O=!0}}return O?{merged:coerceWellKnown(E),sources:D}:{merged:{},sources:{}}}function coerceWellKnown(e){let t={};for(let[S,w]of Object.entries(e))t[S]=w;return typeof e.title==`string`?t.title=e.title:delete t.title,typeof e.description==`string`?t.description=e.description:delete t.description,Array.isArray(e.tags)?t.tags=e.tags.filter(e=>typeof e==`string`):delete t.tags,t}const warnedPaths=new Set;function readFrontmatterYaml(e){let t;try{t=readFileSync(e,`utf-8`)}catch{return null}let S;try{S=(0,import_dist$1.parse)(t)}catch(t){if(!warnedPaths.has(e)){warnedPaths.add(e);let S=t instanceof Error?t.message:String(t);console.warn(`[ok-folder-frontmatter] malformed YAML at ${e} — folder defaults skipped. Fix the file or delete it. Reason: ${S}`)}return null}return typeof S!=`object`||!S||Array.isArray(S)?null:S}function parentFolderOf(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}const GIT_TIMEOUT_MS$2=5e3;function projectHasGitDir(e){try{return statSync(resolve(e,`.git`)).isDirectory()}catch{return!1}}function openProjectGit(e){return esm_default({baseDir:resolve(e),timeout:{block:GIT_TIMEOUT_MS$2}})}async function readProjectGitLog(e,t,S=5){if(!projectHasGitDir(e))return{commits:[],source:`git-absent`};let w=openProjectGit(e),E=``;try{E=await w.raw(`log`,`-${Math.max(1,S)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let D=[];for(let e of E.split(`
|
|
1247
1247
|
`)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let S=e.indexOf(`|`,t+1);if(S<0)continue;let w=e.indexOf(`|`,S+1);w<0||D.push({hash:e.slice(0,t),date:e.slice(t+1,S),authorName:e.slice(S+1,w),subject:e.slice(w+1)})}return{commits:D,source:`git`}}const GIT_TIMEOUT_MS$1=5e3;async function currentProjectBranch(e){try{let t=(await esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS$1}}).revparse([`--abbrev-ref`,`HEAD`])).trim();return t&&t!==`HEAD`?t:null}catch{return null}}function openShadowGit(e,t){return esm_default({baseDir:t,timeout:{block:GIT_TIMEOUT_MS$1}}).env({GIT_DIR:e,GIT_WORK_TREE:t})}function writerIdFromRef(e,t){let S=getWipRefPattern(t);return e.startsWith(S)?e.slice(S.length):e}async function logOnRef(e,t,S,w,E){let D=``;try{D=await e.raw(`log`,t,`-${Math.max(1,E*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,S)}catch{return[]}let O=writerIdFromRef(t,w),k=parseWriterId(O),j=[];for(let e of D.split(``)){let t=e.trimStart();if(!t)continue;let[S=``,E=``,D=``,F=``,L=``]=t.split(`\0`),B=S.trim();B.length===40&&j.push({hash:B,date:E,writerName:D,message:F,contributors:readContributors(L),writerId:O,isAgent:k.isAgent,writerClassification:k.classification,branch:w})}return j}async function readShadowLog(e,t,S=5){let w=getShadowRepoPath(e);if(!w)return{commits:[],source:`shadow-repo-absent`};let E=await currentProjectBranch(e);if(!E)return{commits:[],source:`shadow-repo`};let D=openShadowGit(w,resolve(e)),O=``;try{O=await D.raw(`for-each-ref`,getWipRefPattern(E),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let k=O.split(`
|
|
1248
|
-
`).map(e=>e.trim()).filter(Boolean);return k.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(k.map(e=>logOnRef(D,e,t,E,S)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,S),source:`shadow-repo`}}function resolveTemplatesAvailable(e,t,S={}){let w=normalizeFolderPath(t),E=w===``?[]:w.split(`/`),D=new Set,O=[];collectFromFolder(e,w,`local`,D,O);for(let t=E.length-1;t>=1;t--)collectFromFolder(e,E.slice(0,t).join(`/`),`inherited`,D,O);return E.length>0&&collectFromFolder(e,``,`inherited`,D,O),O}function collectFromFolder(e,t,S,w,E){let D=t?join(e,t,`.ok`,`templates`):join(e,`.ok`,`templates`);if(!existsSync(D))return;let O;try{O=readdirSync(D)}catch{return}for(let e of O){if(!e.endsWith(`.md`))continue;let O=e.slice(0,-3);if(w.has(O))continue;let k=join(D,e),j;try{j=statSync(k)}catch{continue}if(!j.isFile())continue;let F=readTemplateMeta(k),L={name:O,path:t?posix.join(t,`.ok`,`templates`,e):posix.join(`.ok`,`templates`,e),source_folder:t,scope:S};F.title!==void 0&&(L.title=F.title),F.description!==void 0&&(L.description=F.description),w.add(O),E.push(L)}}function normalizeFolderPath(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const templateMetaWarnedPaths=new Set;function readTemplateMeta(e){let t;try{t=readFileSync(e,`utf-8`)}catch(t){if(t?.code!==`ENOENT`&&!templateMetaWarnedPaths.has(e)){templateMetaWarnedPaths.add(e);let S=t instanceof Error?t.message:String(t);console.warn(`[ok-templates] failed to read template at ${e} — metadata skipped. Reason: ${S}`)}return{}}let S=extractFrontmatterYaml(t);if(S===null)return{};let w;try{w=(0,import_dist$1.parse)(S)}catch(t){if(!templateMetaWarnedPaths.has(e)){templateMetaWarnedPaths.add(e);let S=t instanceof Error?t.message:String(t);console.warn(`[ok-templates] malformed YAML frontmatter at ${e} — title/description unavailable. Reason: ${S}`)}return{}}if(typeof w!=`object`||!w)return{};let E=w,D={};return typeof E.title==`string`&&(D.title=E.title),typeof E.description==`string`&&(D.description=E.description),D}function extractFrontmatterYaml(e){let t=e.replace(/^/,``),S=/^[ \t]*---\r?\n([\s\S]*?)\r?\n[ \t]*---(\r?\n|$)/.exec(t);return S?S[1]??null:null}const FRONTMATTER_RE=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function parseFrontmatterRaw(e){let t=e.match(FRONTMATTER_RE);if(!t)return null;try{let e=(0,import_dist$1.parse)(t[1]);if(typeof e==`object`&&e&&!Array.isArray(e))return e}catch{}return null}const DIRECTORY_SCAN_CAP=1e3,DIR_SKIP=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),WIKI_EXT_RE=/\.(md|mdx)$/i;function pathToDocName$1(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const fmReadWarnedPaths=new Set;async function readFrontmatter(e){try{return parseFrontmatterRaw(await readFile$1(e,`utf-8`))??{}}catch(t){if(t?.code!==`ENOENT`&&!fmReadWarnedPaths.has(e)){fmReadWarnedPaths.add(e);let S=t instanceof Error?t.message:String(t);console.warn(`[ok-enrich] failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${S}`)}return null}}async function fetchBacklinks(e,t){if(!e)return null;let S=await httpGet(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!S.ok)return null;let w=S.backlinks??S.results??S.links;if(!Array.isArray(w))return[];let E=[];for(let e of w){if(typeof e!=`object`||!e)continue;let t=e,S=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;S&&E.push({source:S,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return E}const BACKLINK_COUNT_CHUNK=100;async function fetchBacklinkCountsBatch(e,t){if(!e||t.length===0)return null;let S=[...new Set(t)],w=[];for(let e=0;e<S.length;e+=BACKLINK_COUNT_CHUNK)w.push(S.slice(e,e+BACKLINK_COUNT_CHUNK));let E=await Promise.all(w.map(async t=>{let S=await httpGet(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return S.ok?S.counts??{}:null})),D=new Map,O=!1;for(let e of E)if(e){O=!0;for(let[t,S]of Object.entries(e))typeof S==`number`&&Number.isFinite(S)&&D.set(t,S)}return O?D:null}async function fetchForwardLinks(e,t){if(!e)return null;let S=await httpGet(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!S.ok)return null;let w=S.forwardLinks??S.links??S.results;if(!Array.isArray(w))return[];let E=[];for(let e of w){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){E.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let S=typeof t.docName==`string`?t.docName:void 0;S&&E.push({kind:`doc`,docName:S,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return E}function mergeFileAndFolder(e,t,S){let w=mergeCascade(S?resolveNestedFrontmatter(S,parentFolderOf(t)):{},e??{});return{title:typeof w.title==`string`?w.title:void 0,description:typeof w.description==`string`?w.description:void 0,tags:Array.isArray(w.tags)?w.tags.filter(e=>typeof e==`string`):[],frontmatter:w}}async function enrichPath(e,t,S={}){let w=resolveWithinRoot(t.projectDir,e);if(!w.ok)throw Error(`enrichPath: ${w.reason}`);let E=w.rel,D=w.abs,O=t.historyDepth??5,k=S.includeRichFields===!0,j=readFrontmatter(D);if(!k){let e=mergeFileAndFolder(await j,E,t.projectDir);return{path:E,title:e.title,description:e.description,tags:e.tags,frontmatter:e.frontmatter,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[F,L,B,H,q]=await Promise.all([j,fetchBacklinks(t.serverUrl,pathToDocName$1(E)).catch(()=>null),fetchForwardLinks(t.serverUrl,pathToDocName$1(E)).catch(()=>null),readShadowLog(t.projectDir,E,O).catch(()=>({commits:[],source:`shadow-repo`})),readProjectGitLog(t.projectDir,E,O).catch(()=>({commits:[],source:`git`}))]),J=mergeFileAndFolder(F,E,t.projectDir);return{path:E,title:J.title,description:J.description,tags:J.tags,frontmatter:J.frontmatter,backlinkCount:L?.length??null,backlinks:L,forwardLinkCount:B?.length??null,forwardLinks:B,history:H.commits,historySource:H.source,projectHistory:q.commits,projectHistorySource:q.source}}async function scanDirectory(e,t){let S={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},w=0,E=[{path:e,depth:0}];for(;E.length>0;){let e=E.shift();if(!e)break;if(w>=DIRECTORY_SCAN_CAP){S.truncated=!0;break}let D;try{D=await readdir(e.path,{withFileTypes:!0})}catch{continue}for(let O of D){if(w>=DIRECTORY_SCAN_CAP){S.truncated=!0;break}w++;let D=O.name;if(O.isDirectory()){if(DIR_SKIP.has(D)||D.startsWith(`.`))continue;e.depth===0&&S.childDirCount++,E.push({path:`${e.path}/${D}`,depth:e.depth+1})}else if(O.isFile()&&WIKI_EXT_RE.test(D)){S.recursiveMdCount++,e.depth===0&&S.directMdCount++;let w=`${e.path}/${D}`;try{let e=await stat$1(w);(!S.mostRecent||e.mtimeMs>S.mostRecent.mtimeMs)&&(S.mostRecent={absPath:w,relPath:relative(t,w).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return S}async function enrichDirectory(e,t){let S=resolveWithinRoot(t.projectDir,e);if(!S.ok)throw Error(`enrichDirectory: ${S.reason}`);let w=S.rel,E=S.abs,D=await scanDirectory(E,t.projectDir),O;if(D.mostRecent){let e=await readFrontmatter(D.mostRecent.absPath),t=typeof e?.title==`string`?e.title:void 0;O={path:D.mostRecent.relPath,title:t??basename(D.mostRecent.relPath),updatedAt:new Date(D.mostRecent.mtimeMs).toISOString()}}let k={path:w,type:`directory`,directMdCount:D.directMdCount,recursiveMdCount:D.recursiveMdCount,childDirCount:D.childDirCount,mostRecentMd:O,truncated:D.truncated},j=resolveNestedFrontmatter(t.projectDir,w),F=j.title,L=j.description,B=j.tags??[];F!==void 0&&(k.title=F),L!==void 0&&(k.description=L),B.length>0&&(k.tags=B),Object.keys(j).length>0&&(k.frontmatter_defaults=j);let H=resolveTemplatesAvailable(t.projectDir,w);return H.length>0&&(k.templates_available=H),k}async function enrichDirectoryRecursive(e,t,S){let w=await enrichDirectory(e,S);if(t<=1)return w;let E=w.path,D=resolve(S.projectDir,E),O;try{O=await readdir(D,{withFileTypes:!0})}catch{return w}let k=[];for(let e of O){if(!e.isDirectory()||RECURSIVE_LISTING_SKIP_DIRS.has(e.name)||e.name.startsWith(`.`))continue;let w=await enrichDirectoryRecursive(E?`${E}/${e.name}`:e.name,t-1,S);k.push(w)}return k.length>0&&(w.subfolders=k),w}const RECURSIVE_LISTING_SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function applyNestedFolderRulesUpsert(e){if(!isAbsolute(e.projectDir))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};let t=[];for(let S of e.rules){let w=resolveTargetFolderFromMatch(S.new_match??S.match);if(!w.ok)return{ok:!1,error:{code:`MULTI_FOLDER_GLOB`,message:w.message,rule:S.match}};let E=w.folder?resolve(e.projectDir,w.folder):e.projectDir,D=resolve(e.projectDir);if(!E.startsWith(D+sep)&&E!==D)return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved target folder escapes projectDir: ${E}`,rule:S.match}};let O=null,k=null;if(S.new_match!==void 0&&S.new_match!==S.match){let t=resolveTargetFolderFromMatch(S.match);if(!t.ok)return{ok:!1,error:{code:`MULTI_FOLDER_GLOB`,message:t.message,rule:S.match}};if(O=t.folder,k=t.folder?resolve(e.projectDir,t.folder):e.projectDir,!k.startsWith(D+sep)&&k!==D)return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved source folder escapes projectDir: ${k}`,rule:S.match}}}t.push({targetFolder:w.folder,targetAbs:E,sourceFolder:O,sourceAbs:k,rule:S})}let S=[];for(let w of t)try{if(w.sourceAbs&&w.sourceAbs!==w.targetAbs){let t=join(w.sourceAbs,`.ok`,`frontmatter.yml`);existsSync(t)&&(unlinkSync(t),autoCleanOkDir(join(w.sourceAbs,`.ok`)),S.push({match:w.rule.match,path:relPathOf$1(e.projectDir,t),action:`deleted`}))}let t=join(w.targetAbs,`.ok`),E=join(t,`frontmatter.yml`),D=readExistingFrontmatter(E),O=Object.keys(w.rule.frontmatter).length===0?{}:mergePatch(D,w.rule.frontmatter);if(Object.keys(O).length===0){existsSync(E)&&(unlinkSync(E),autoCleanOkDir(t),S.push({match:w.rule.new_match??w.rule.match,path:relPathOf$1(e.projectDir,E),action:`deleted`}));continue}mkdirSync(t,{recursive:!0});let k=(0,import_dist$1.stringify)(O),j=`${E}.tmp.${process.pid}.${Date.now()}`;writeFileSync(j,k,`utf-8`),renameSync(j,E),S.push({match:w.rule.new_match??w.rule.match,path:relPathOf$1(e.projectDir,E),action:`written`})}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write nested frontmatter for ${w.rule.match}: ${e.message}`,rule:w.rule.match},...S.length>0?{partiallyApplied:S}:{}}}return{ok:!0,applied:S}}function resolveTargetFolderFromMatch(e){let t=e.split(`/`).filter(e=>e.length>0),S=[],w=!1;for(let E of t){let t=/[*?[\]{}]/.test(E);if(w&&!t)return{ok:!1,message:`Glob "${e}" matches multiple folders (literal segment "${E}" appears after a glob). Split it into one rule per folder, e.g. folder_config({ action: "set-rule", rules: [{ match: "specs/foo/${E}/**", ... }, ...] }).`};if(t){if(w=!0,E!==`**`&&E!==`*`)return{ok:!1,message:`Glob "${e}" uses an unsupported pattern segment "${E}". Only "*" and "**" are supported in nested folder rules.`};continue}S.push(E)}return{ok:!0,folder:S.join(`/`)}}function readExistingFrontmatter(e){if(!existsSync(e))return{};let t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`));return typeof t!=`object`||!t||Array.isArray(t)?{}:{...t}}function autoCleanOkDir(e){if(!existsSync(e))return;let t;try{t=readdirSync(e)}catch{return}if(t.length===0)try{rmdirSync(e)}catch{}}function relPathOf$1(e,t){let S=resolve(e);return t.startsWith(S+sep)?t.slice(S.length+1).split(sep).join(`/`):t}const SUBSTITUTION_ALLOWLIST=[`date`,`user`],TOKEN_PATTERN=/\{\{([^{}\n]+?)\}\}/g;function validateSubstitution(e){let t=[];for(let S of e.matchAll(TOKEN_PATTERN)){let e=(S[1]??``).trim();isAllowedToken(e)||t.push({token:e,offset:S.index??0})}return t}function applySubstitution(e,t){return e.replace(TOKEN_PATTERN,(e,S)=>{let w=S.trim();return isAllowedToken(w)?t[w]:e})}function isAllowedToken(e){return SUBSTITUTION_ALLOWLIST.includes(e)}function todayIsoUtc(e=new Date){return`${e.getUTCFullYear().toString().padStart(4,`0`)}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}const NAME_RE=/^[A-Za-z0-9_-]+$/;function applyTemplateWrite(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let S=validateTitle(e.frontmatter.title);if(!S.ok)return{ok:!1,error:S.error};let w=validateSubstitutionAllowlist(e.body);if(!w.ok)return{ok:!1,error:w.error};let{templatesDir:E,filePath:D}=templatePaths(e.projectDir,t.folderRel,e.name),O=serializeFrontmatter(e.frontmatter),k=O?`---\n${O}---\n${e.body}`:e.body;try{mkdirSync(E,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${relPathOf(e.projectDir,E)}: ${t.message}`}}}let j=!existsSync(D),F=`${D}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(F,k,`utf-8`),renameSync(F,D)}catch(t){try{unlinkSync(F)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${relPathOf(e.projectDir,D)}: ${t.message}`}}}let L=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&L.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,path:relPathOf(e.projectDir,D),created:j,warnings:L}}function applyTemplateDelete(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let{templatesDir:S,okDir:w,filePath:E}=templatePaths(e.projectDir,t.folderRel,e.name),D=existsSync(E);if(D)try{unlinkSync(E)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete template at ${relPathOf(e.projectDir,E)}: ${t.message}`}}}let O=!1,k=!1;if(existsSync(S)&&isEmpty(S))try{rmdirSync(S),O=!0}catch{}if(existsSync(w)&&isEmpty(w))try{rmdirSync(w),k=!0}catch{}return{ok:!0,path:relPathOf(e.projectDir,E),existed:D,cleanedEmpty:{templatesDir:O,okDir:k}}}function validateInputs(e,t,S){if(!isAbsolute(e))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};if(!NAME_RE.test(S))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(S)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let w=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``);if(w.includes(`..`))return{ok:!1,error:{code:`PATH_TRAVERSAL`,message:`Folder path may not contain "..": ${JSON.stringify(t)}`}};let E=w?resolve(e,w):e,D=resolve(e);return!E.startsWith(D+sep)&&E!==D?{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder path escapes projectDir: ${E}`}}:{ok:!0,folderRel:w}}function validateTitle(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`TEMPLATE_TITLE_REQUIRED`,message:"Template frontmatter.title is required. `title` is the menu surface — agents pick templates by name+title; a title-less template is effectively invisible. Set a non-empty `title` and retry."}}:{ok:!0}}function validateSubstitutionAllowlist(e){let t=validateSubstitution(e);return t.length===0?{ok:!0}:{ok:!1,error:{code:`TEMPLATE_UNKNOWN_VARIABLE`,message:`Template body contains unknown substitution token(s): ${t.map(e=>`\`{{${e.token}}}\` at offset ${e.offset}`).join(`, `)}. v1 allowlist: \`{{date}}\`, \`{{user}}\`. Remove or rename the offending tokens and retry.`}}}function templatePaths(e,t,S){let w=t?join(e,t,`.ok`):join(e,`.ok`),E=join(w,`templates`);return{okDir:w,templatesDir:E,filePath:join(E,`${S}.md`)}}function relPathOf(e,t){return normalize(t.startsWith(e+sep)?t.slice(e.length+1):t).split(sep).join(`/`)}function serializeFrontmatter(e){let t={};return e.title!==void 0&&(t.title=e.title),e.description!==void 0&&(t.description=e.description),Array.isArray(e.tags)&&e.tags.length>0&&(t.tags=e.tags),Object.keys(t).length===0?``:(0,import_dist$1.stringify)(t)}function isEmpty(e){try{return readdirSync(e).length===0}catch{return!1}}const log$5=()=>getLogger(`http`);function successResponse(e,t,S,w,E={}){if(e.headersSent||e.writableEnded||e.destroyed){log$5().error({event:`api.success.double-write`,status:t,handler:E.handler},`successResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...E.handler?{handler:E.handler}:{}});return}let D=S.safeParse(w);if(!D.success){log$5().error({event:`api.success.malformed-body`,issues:D.error.issues,bodyKeys:typeof w==`object`&&w?Object.keys(w):null,handler:E.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E.handler});return}let O;try{O=JSON.stringify(D.data)}catch(S){log$5().error({event:`api.success.unserializable-body`,bodyKeys:typeof D.data==`object`&&D.data!==null?Object.keys(D.data):null,handler:E.handler,originalStatus:t,err:S},`successResponse parsed body is not JSON-serializable — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E.handler});return}e.writeHead(t,{...E.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(O)}const INSTALLED_AGENTS_SCHEMES=[`claude`,`codex`,`cursor`],INSTALLED_AGENTS_PROBE_TIMEOUT_MS=2e3,MACOS_APP_NAMES={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function createInstalledAgentsProbe(e){let t=new Map,S=e.now??Date.now,w=e.ttlMs??6e4;async function E(E){let D=t.get(E);if(D?.status===`resolved`&&D.expiresAt>S())return D.installed;if(D?.status===`inflight`)return D.promise;let O=(async()=>{try{let D=await e.probe(E);return t.set(E,{status:`resolved`,installed:D,expiresAt:S()+w}),D}catch{return t.set(E,{status:`resolved`,installed:!1,expiresAt:S()+w}),!1}})();return t.set(E,{status:`inflight`,promise:O}),O}async function D(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await E(e)]));return Object.fromEntries(e)}return{probeAll:D,probeWithCache:E}}function isLocalWebHost(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return isLoopbackHostname(e)}catch{}let S=e.headers.origin;if(typeof S==`string`&&S.length>0)try{return isLoopbackHostname(new URL(S).hostname)}catch{return!1}return!0}function isLoopbackHostname(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function handleInstalledAgents(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{successResponse(t,200,InstalledAgentsSuccessSchema,isLocalWebHost(e)?await S():Object.fromEntries(INSTALLED_AGENTS_SCHEMES.map(e=>[e,!0])),{handler:`installed-agents`})}catch(e){console.error(`[installed-agents]`,e),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function createOsProbe(e,t=execFile){return S=>e===`darwin`?probeMacOs(S,t):e===`win32`?probeWindows(S,t):probeLinux(S,t)}function probeMacOs(e,t){let S=MACOS_APP_NAMES[e];function w(e){return new Promise(S=>{t(`osascript`,[`-e`,`id of app "${e}"`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){S(!1);return}S(t.trim().length>0)})})}return(async()=>{for(let e of S)if(await w(e))return!0;return!1})()}function probeWindows(e,t){return new Promise(S=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},e=>{S(!e)})})}function probeLinux(e,t){return new Promise(S=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){S(!1);return}S(t.trim().length>0)})})}const MAX_BODY_BYTES=1048576,REQUEST_BODY_TIMEOUT_MS=3e4;function readRequestBody(e){return readBoundedJsonBody(e,{maxBytes:MAX_BODY_BYTES,timeoutMs:REQUEST_BODY_TIMEOUT_MS})}async function readBoundedJsonBody(e,t){let S=[],w=0,E=AbortSignal.timeout(t.timeoutMs),D=()=>e.destroy(new RequestBodyTimeoutError(t.timeoutMs));E.addEventListener(`abort`,D,{once:!0});try{for await(let E of e){if(w+=E.length,w>t.maxBytes)throw new PayloadTooLargeError(t.maxBytes);S.push(E)}return Buffer.concat(S)}finally{E.removeEventListener(`abort`,D)}}var PayloadTooLargeError=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${formatBytes(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},RequestBodyTimeoutError=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function formatBytes(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function validateBody(e,t,S,w={}){let E=e.safeParse(t);if(E.success)return{ok:!0,value:E.data};let D=E.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return errorResponse(S,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:w.handler,detail:D}),{ok:!1}}function withValidation(e,t,S={}){return async(w,E)=>{if(S.method!==void 0&&w.method!==S.method){errorResponse(E,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:S.handler,extraHeaders:{Allow:S.method}});return}if(S.preBodyGate!==void 0&&!S.preBodyGate(w,E)){!E.headersSent&&!E.writableEnded&&!E.destroyed&&errorResponse(E,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(S.skipBodyParse){let D=validateBody(e,{},E,S);if(!D.ok)return;await t(w,E,D.value);return}let D;try{D=await readRequestBody(w)}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(E,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:S.handler,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(E,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:S.handler,cause:e});return}errorResponse(E,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:S.handler,cause:e});return}let O;try{O=D.length===0?{}:JSON.parse(D.toString(`utf8`))}catch(e){errorResponse(E,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:S.handler,cause:e});return}let k=validateBody(e,O,E,S);k.ok&&await t(w,E,k.value)}}function classifySpawnError(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function spawnDetached(e,t,S){return new Promise(w=>{let E=!1,D=e=>{E||(E=!0,w(e))},O=setTimeout(()=>D({ok:!1,reason:`timeout`}),S);try{let S=spawn(e,[...t],{detached:!0,stdio:`ignore`,shell:!1});S.once(`error`,e=>{clearTimeout(O),D(classifySpawnError(e))}),S.once(`spawn`,()=>{if(!E){try{S.unref()}catch{}clearTimeout(O),D({ok:!0})}})}catch(e){console.warn(`[spawn-detached] synchronous spawn throw:`,e),clearTimeout(O),D(classifySpawnError(e))}})}const SPAWN_CURSOR_WHICH_TIMEOUT_MS=500,SPAWN_CURSOR_SPAWN_TIMEOUT_MS=2e3,SPAWN_CURSOR_MAX_BODY_BYTES=4*1024,SPAWN_CURSOR_BODY_READ_TIMEOUT_MS=5e3,HANDLER$1=`spawn-cursor`;function assertNeverSpawnReason(e){throw Error(`Unhandled spawn-cursor outcome.reason: ${String(e)}`)}async function handleSpawnCursor(e,t,S){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER$1,extraHeaders:{Allow:`POST`}});return}let w;try{w=await readBoundedJsonBody(e,{maxBytes:SPAWN_CURSOR_MAX_BODY_BYTES,timeoutMs:SPAWN_CURSOR_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER$1,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER$1,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER$1,cause:e});return}let E;try{E=JSON.parse(w.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER$1,cause:e});return}let D=typeof E.path==`string`?E.path:``;if(!D){errorResponse(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:HANDLER$1});return}if(!isPathWithinDir(D,S.contentDir,S.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return}let O=await(S.resolveCursorBinary??resolveCursorBinaryDefault)(SPAWN_CURSOR_WHICH_TIMEOUT_MS);if(!O){errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return}let k=resolveCursorSpawnInvocation(O,D,S.platform),j=await(S.spawnDetached??spawnDetached)(k.exec,k.args,SPAWN_CURSOR_SPAWN_TIMEOUT_MS);if(j.ok){successResponse(t,200,SpawnCursorSuccessSchema,{},{handler:HANDLER$1});return}switch(j.reason){case`not-installed`:errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return;case`timeout`:errorResponse(t,504,`urn:ok:error:cursor-spawn-timeout`,`Cursor spawn exceeded the deadline.`,{handler:HANDLER$1});return;case`spawn-error`:errorResponse(t,502,`urn:ok:error:cursor-spawn-failed`,`Cursor spawn failed.`,{handler:HANDLER$1});return;case`invalid-path`:errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return;default:return assertNeverSpawnReason(j.reason)}}const CURSOR_BUNDLE_PATHS_BY_PLATFORM={darwin:[()=>`/Applications/Cursor.app/Contents/Resources/app/bin/cursor`,e=>`${e}/Applications/Cursor.app/Contents/Resources/app/bin/cursor`],win32:[e=>`${e}\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd`,()=>`C:\\Program Files\\Cursor\\resources\\app\\bin\\cursor.cmd`]};async function resolveCursorBinaryDefault(e){let t=CURSOR_BUNDLE_PATHS_BY_PLATFORM[process.platform];if(t&&t.length>0){let e=homedir();for(let S of t){let t=S(e);try{return await access(t,constants.X_OK),t}catch(e){let S=e?.code;S!==`ENOENT`&&S!==`EACCES`&&S!==`EPERM`&&console.warn(`[spawn-cursor] unexpected fs.access error on bundle probe:`,S,t)}}}return new Promise(t=>{execFile(process.platform===`win32`?`where`:`which`,[`cursor`],{timeout:e,encoding:`utf-8`},(e,S)=>{if(e){t(null);return}let w=S.split(/\r?\n/)[0]?.trim();t(w&&w.length>0?w:null)})})}function resolveCursorSpawnInvocation(e,t,S){return S===`darwin`&&/\.app\/?$/.test(e)?{exec:`/usr/bin/open`,args:[`-a`,e.replace(/\/$/,``),t]}:{exec:e,args:[t]}}function isPathWithinDir(e,t,S){if(!e||typeof e!=`string`||e.includes(`\0`)||!t||typeof t!=`string`)return!1;if(S===`win32`){if(!/^([a-zA-Z]:[\\/]|\\\\)/.test(e)||!/^([a-zA-Z]:[\\/]|\\\\)/.test(t))return!1}else if(!e.startsWith(`/`)||!t.startsWith(`/`))return!1;let w=S===`win32`?win32:posix;try{let E=w.resolve(e),D=w.resolve(t);if(S===`win32`){let e=w.parse(E).root.toLowerCase(),t=w.parse(D).root.toLowerCase();if(!e||!t||e!==t)return!1}if(E===D)return!0;let O=w.relative(D,E);return O===``||O===`.`?!0:!(O===`..`||O.startsWith(`..${w.sep}`)||S===`win32`&&(/^[a-zA-Z]:[\\/]/.test(O)||O.startsWith(`\\\\`))||S!==`win32`&&O.startsWith(`/`))}catch(e){return console.warn(`[spawn-cursor] unexpected path-resolution error:`,e),!1}}const HANDLER=`handoff`,HANDOFF_MAX_BODY_BYTES=4*1024,HANDOFF_BODY_READ_TIMEOUT_MS=5e3,SPAWN_TIMEOUT_MS=2e3,WHICH_TIMEOUT_MS=500,QUIT_SETTLE_MS=3e3,APP_BUNDLE_SETTLE_MS=5e3,CURSOR_SETTLE_MS=1500,RECIPES={"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}},TARGET_VALUES=Object.keys(RECIPES),HandoffRequestSchema=object$1({target:_enum(TARGET_VALUES),url:string$2().min(1).max(4096),workspacePath:string$2().optional()}),HandoffSuccessSchema=object$1({}).loose();function defaultSleep(e){return new Promise(t=>setTimeout(t,e))}async function handleHandoffDispatch(e,t,S){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER,extraHeaders:{Allow:`POST`}});return}if(S.platform!==`darwin`){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Handoff is currently macOS-only.`,{handler:HANDLER});return}let w;try{w=await readBoundedJsonBody(e,{maxBytes:HANDOFF_MAX_BODY_BYTES,timeoutMs:HANDOFF_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER,cause:e});return}let E;try{E=JSON.parse(w.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER,cause:e});return}let D=HandoffRequestSchema.safeParse(E);if(!D.success){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid request body.`,{handler:HANDLER});return}let{target:O,url:k,workspacePath:j}=D.data,F=RECIPES[O];if(!k.startsWith(F.urlScheme)){errorResponse(t,400,`urn:ok:error:invalid-request`,`URL scheme must be ${F.urlScheme} for target ${O}.`,{handler:HANDLER});return}let L=S.sleep??defaultSleep,B=S.spawnDetached??spawnDetached;if(F.type===`app-bundle`){F.quitFirst&&(await B(`/usr/bin/osascript`,[`-e`,`tell application "${F.appName}" to quit`],SPAWN_TIMEOUT_MS).catch(()=>void 0),await L(QUIT_SETTLE_MS));let e=await B(`/usr/bin/open`,[`-a`,F.appName],SPAWN_TIMEOUT_MS);if(!e.ok){emitSpawnFailure(t,O,e.reason);return}await L(APP_BUNDLE_SETTLE_MS);let S=await B(`/usr/bin/open`,[k],SPAWN_TIMEOUT_MS);if(!S.ok){emitSpawnFailure(t,O,S.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER});return}if(!j){errorResponse(t,400,`urn:ok:error:invalid-request`,`workspacePath is required for cursor handoff.`,{handler:HANDLER});return}if(!isPathWithinDir(j,S.contentDir,S.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER});return}let H=await(S.resolveCursorBinary??resolveCursorBinaryDefault)(WHICH_TIMEOUT_MS);if(!H){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER,extensions:{target:`cursor`}});return}let q=resolveCursorSpawnInvocation(H,j,S.platform),J=await B(q.exec,q.args,SPAWN_TIMEOUT_MS);if(!J.ok){emitSpawnFailure(t,O,J.reason);return}await L(CURSOR_SETTLE_MS);let Y=await B(`/usr/bin/open`,[k],SPAWN_TIMEOUT_MS);if(!Y.ok){emitSpawnFailure(t,O,Y.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER})}function emitSpawnFailure(e,t,S){switch(S){case`not-installed`:errorResponse(e,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:HANDLER,extensions:{target:t}});return;case`timeout`:errorResponse(e,504,`urn:ok:error:handoff-spawn-timeout`,`Handoff spawn exceeded the deadline.`,{handler:HANDLER,extensions:{target:t}});return;case`spawn-error`:errorResponse(e,502,`urn:ok:error:handoff-spawn-failed`,`Handoff spawn failed.`,{handler:HANDLER,extensions:{target:t}});return;default:assertNeverReason(S)}}function assertNeverReason(e){throw Error(`Unhandled spawn reason: ${String(e)}`)}const FIXED_HUB_BASENAMES=[`INDEX`,`README`,`REPORT`,`SPEC`],MAX_CANDIDATES=3;function findHubCandidates(e,t){let S=[],w=new Set,E=t=>{!t||w.has(t)||t!==e&&(w.add(t),S.push(t))},D=buildLowerDocNameIndex(t),O=parentFolder(e);for(;;){for(let e of FIXED_HUB_BASENAMES)if(E(lookup$1(t,D,joinDocName(O,e))),S.length>=MAX_CANDIDATES)return S;let e=O===``?null:basename$1(O);if(e&&(E(lookup$1(t,D,joinDocName(O,e))),S.length>=MAX_CANDIDATES))return S;if(O===``)break;O=parentFolder(O)}return S}function lookup$1(e,t,S){return e.has(S)?S:t.get(S.toLowerCase())??null}function buildLowerDocNameIndex(e){let t=new Map;for(let S of e.keys()){let e=S.toLowerCase();t.has(e)||t.set(e,S)}return t}function parentFolder(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function basename$1(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function joinDocName(e,t){return e===``?t:`${e}/${t}`}function splitFrontmatterLines(e){return e?e.replace(/^---\r?\n/,``).replace(/\r?\n---(?:\r?\n)?$/,``).split(/\r?\n/):[]}function normalizeFrontmatterScalar(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function extractFrontmatterScalar(e,t){let S=`${t}:`;for(let t of splitFrontmatterLines(e))if(t.startsWith(S))return normalizeFrontmatterScalar(t.slice(S.length))||null;return null}function parseInlineAliases(e){let t=[],S=``,w=null;for(let E of e){if(w){S+=E,E===w&&(w=null);continue}if(E===`"`||E===`'`){w=E,S+=E;continue}if(E===`,`){let e=normalizeFrontmatterScalar(S);e&&t.push(e),S=``;continue}S+=E}let E=normalizeFrontmatterScalar(S);return E&&t.push(E),t}function dedupeExact(e){let t=[],S=new Set;for(let w of e)!w||S.has(w)||(S.add(w),t.push(w));return t}function extractPageAliases(e){let{frontmatter:t}=stripFrontmatter(e);if(!t)return[];let S=splitFrontmatterLines(t);for(let e=0;e<S.length;e+=1){let t=S[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let w=t[1]?.trim()??``;if(w){if(w.startsWith(`[`)&&w.endsWith(`]`))return dedupeExact(parseInlineAliases(w.slice(1,-1)));let e=normalizeFrontmatterScalar(w);return e?[e]:[]}let E=[];for(let t=e+1;t<S.length;t+=1){let e=S[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&E.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return dedupeExact(E)}return[]}function extractPageTitle(e,t){let{frontmatter:S,body:w}=stripFrontmatter(e),E=extractFrontmatterScalar(S,`title`);if(E)return E;let D=w.match(/^# (.+)$/m);return D?D[1].trim():t}function parseFrontmatterMetadata(e){return e?.trim()?{cluster:extractFrontmatterScalar(e,`cluster`)??void 0,category:extractFrontmatterScalar(e,`category`)??void 0,tags:extractFrontmatterArray(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function extractFrontmatterArray(e,t){let S=`${t}:`,w=splitFrontmatterLines(e);for(let e=0;e<w.length;e+=1){let t=w[e];if(!t?.startsWith(S))continue;let E=t.slice(S.length).trim();if(E){if(E.startsWith(`[`)&&E.endsWith(`]`)){let e=parseInlineAliases(E.slice(1,-1));return e.length>0?e:void 0}let e=normalizeFrontmatterScalar(E);return e?[e]:void 0}let D=[];for(let t=e+1;t<w.length;t+=1){let e=w[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&D.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return D.length>0?D:void 0}}function extractPageIdentity(e,t){let S=extractPageTitle(e,t),w=extractPageAliases(e),E=dedupeExact([S,...w]),D=[],O=new Set;for(let e of E){let t=toWikiLinkSlug(e);!t||O.has(t)||(O.add(t),D.push(t))}return{docName:t,title:S,aliases:w,matchLabels:E,normalizedMatchLabels:D}}const SHARE_BASE_URL=`https://openknowledge.ai/d/`,SHARE_CONSTRUCT_URL_HANDLER_TAG=`share-construct-url`;function isValidShareDocPath(e){if(e.length===0||e.startsWith(`/`)||e.startsWith(`\\`))return!1;for(let t of e.split(/[/\\]/))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function buildGitHubBlobUrl(e,t,S,w){return`https://github.com/${e}/${t}/blob/${encodeURIComponent(S)}/${w.split(`/`).map(encodeURIComponent).join(`/`)}`}function emitShareConstructUrlLog(e,t){let S=t===void 0?``:` branch_exists=${t}`;console.log(`[share] action=construct-url result=${e}${S}`)}function resolveGitDir$1(e){let t=resolve(e,`.git`);if(!existsSync(t))return null;let S;try{S=statSync(t)}catch{return null}if(S.isDirectory())return t;if(S.isFile()){let S;try{S=readFileSync(t,`utf-8`)}catch{return null}let w=/^gitdir:\s*(.+)$/m.exec(S.trim());if(!w)return null;let E=w[1].trim(),D=isAbsolute(E)?E:resolve(e,E);return existsSync(D)?D:null}return null}function readGitHeadBranch(e){let t=resolveGitDir$1(e);if(!t)return null;let S=join(t,`HEAD`);if(!existsSync(S))return null;let w;try{w=readFileSync(S,`utf-8`)}catch{return null}let E=/^ref:\s*refs\/heads\/(.+)$/.exec(w.trim());return E?E[1]:null}function stripCommentAndTrim(e){let t=e.indexOf(`#`),S=e.indexOf(`;`),w=-1;return t>=0&&S>=0?w=Math.min(t,S):t>=0?w=t:S>=0&&(w=S),(w===-1?e:e.slice(0,w)).trim()}function extractOriginUrl(e){let t=!1;for(let S of e.split(/\r?\n/)){let e=stripCommentAndTrim(S);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let w=/^url\s*=\s*(.+)$/.exec(e);if(!w)continue;let E=w[1].trim();if((E.startsWith(`"`)&&E.endsWith(`"`)||E.startsWith(`'`)&&E.endsWith(`'`))&&(E=E.slice(1,-1)),E.length>0)return E}return null}function parseGitHubOriginUrl(e){let t=e.trim();if(!t)return null;let S=/^https?:\/\/(?:www\.)?github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return S||(S=/^ssh:\/\/(?:[\w.-]+@)?github\.com(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),S)||(S=/^[\w.-]+@github\.com:([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),S)||(S=/^git:\/\/github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),S)?{owner:S[1],repo:S[2]}:null}function readParsedOrigin(e){let t=resolveGitDir$1(e);if(!t)return null;let S=join(t,`config`);if(!existsSync(S))return null;let w;try{w=readFileSync(S,`utf-8`)}catch{return null}let E=extractOriginUrl(w);return E?{originUrl:E,github:parseGitHubOriginUrl(E)}:null}function readOriginGitHubRepo(e){let t=readParsedOrigin(e);return t?t.github?{kind:`ok`,owner:t.github.owner,repo:t.github.repo}:{kind:`non-github`}:{kind:`no-remote`}}function readSyncRemoteInfo(e){let t=readParsedOrigin(e);return t?t.github?{label:`${t.github.owner}/${t.github.repo}`,webUrl:`https://github.com/${t.github.owner}/${t.github.repo}`}:{label:labelFromNonGitHubUrl(t.originUrl),webUrl:null}:null}function labelFromNonGitHubUrl(e){let t=e.trim().replace(/\.git$/,``),S=/^[\w.-]+@([^:/]+):(.+)$/.exec(t);if(S)return`${S[1]}/${S[2]}`;let w=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)*(.+)$/i.exec(t);return w?w[1]:t}function branchExistsOnOrigin(e,t){let S=resolveGitDir$1(e);if(!S)return!1;if(existsSync(join(S,`refs`,`remotes`,`origin`,t)))return!0;let w=join(S,`packed-refs`);if(!existsSync(w))return!1;let E;try{E=readFileSync(w,`utf-8`)}catch{return!1}let D=`refs/remotes/origin/${t}`;for(let e of E.split(/\r?\n/)){let t=e.trim();if(t.length===0||t.startsWith(`#`)||t.startsWith(`^`))continue;let S=t.split(/\s+/);if(S.length===2&&S[1]===D)return!0}return!1}const SHARE_PUBLISH_OWNERS_HANDLER_TAG=`share-publish-owners`,SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG=`share-publish-name-check`,SHARE_PUBLISH_HANDLER_TAG=`share-publish`,SHARE_PUBLISH_OWNERS_KEY=`/api/share/publish/owners`,SHARE_PUBLISH_NAME_CHECK_KEY=`/api/share/publish/name-check`,SHARE_PUBLISH_KEY=`/api/share/publish`,SHARE_PUBLISH_TIMEOUT_MS=3e4;function isValidShareRepoName(e){return e.length===0||e.length>100||e.startsWith(`.`)||e.startsWith(`-`)||/^-+$/.test(e)?!1:/^[A-Za-z0-9._-]+$/.test(e)}function isValidShareOwnerName(e){return e.length===0||e.length>39||e.startsWith(`-`)||e.endsWith(`-`)?!1:/^[A-Za-z0-9-]+$/.test(e)}function pickTerminalJsonLine(e){let t=e.split(`
|
|
1248
|
+
`).map(e=>e.trim()).filter(Boolean);return k.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(k.map(e=>logOnRef(D,e,t,E,S)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,S),source:`shadow-repo`}}function resolveTemplatesAvailable(e,t,S={}){let w=normalizeFolderPath(t),E=w===``?[]:w.split(`/`),D=new Set,O=[];collectFromFolder(e,w,`local`,D,O);for(let t=E.length-1;t>=1;t--)collectFromFolder(e,E.slice(0,t).join(`/`),`inherited`,D,O);return E.length>0&&collectFromFolder(e,``,`inherited`,D,O),O}function collectFromFolder(e,t,S,w,E){let D=t?join(e,t,`.ok`,`templates`):join(e,`.ok`,`templates`);if(!existsSync(D))return;let O;try{O=readdirSync(D)}catch{return}for(let e of O){if(!e.endsWith(`.md`))continue;let O=e.slice(0,-3);if(w.has(O))continue;let k=join(D,e),j;try{j=statSync(k)}catch{continue}if(!j.isFile())continue;let F=readTemplateMeta(k),L={name:O,path:t?posix.join(t,`.ok`,`templates`,e):posix.join(`.ok`,`templates`,e),source_folder:t,scope:S};F.title!==void 0&&(L.title=F.title),F.description!==void 0&&(L.description=F.description),w.add(O),E.push(L)}}function normalizeFolderPath(e){return e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``)}const templateMetaWarnedPaths=new Set;function readTemplateMeta(e){let t;try{t=readFileSync(e,`utf-8`)}catch(t){if(t?.code!==`ENOENT`&&!templateMetaWarnedPaths.has(e)){templateMetaWarnedPaths.add(e);let S=t instanceof Error?t.message:String(t);console.warn(`[ok-templates] failed to read template at ${e} — metadata skipped. Reason: ${S}`)}return{}}let S=extractFrontmatterYaml(t);if(S===null)return{};let w;try{w=(0,import_dist$1.parse)(S)}catch(t){if(!templateMetaWarnedPaths.has(e)){templateMetaWarnedPaths.add(e);let S=t instanceof Error?t.message:String(t);console.warn(`[ok-templates] malformed YAML frontmatter at ${e} — title/description unavailable. Reason: ${S}`)}return{}}if(typeof w!=`object`||!w)return{};let E=w,D={};return typeof E.title==`string`&&(D.title=E.title),typeof E.description==`string`&&(D.description=E.description),D}function extractFrontmatterYaml(e){let t=e.replace(/^/,``),S=/^[ \t]*---\r?\n([\s\S]*?)\r?\n[ \t]*---(\r?\n|$)/.exec(t);return S?S[1]??null:null}const FRONTMATTER_RE=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function parseFrontmatterRaw(e){let t=e.match(FRONTMATTER_RE);if(!t)return null;try{let e=(0,import_dist$1.parse)(t[1]);if(typeof e==`object`&&e&&!Array.isArray(e))return e}catch{}return null}const DIRECTORY_SCAN_CAP=1e3,DIR_SKIP=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]),WIKI_EXT_RE=/\.(md|mdx)$/i;function pathToDocName$1(e){return e.replace(/\.md$/,``).replace(/\.mdx$/,``)}const fmReadWarnedPaths=new Set;async function readFrontmatter(e){try{return parseFrontmatterRaw(await readFile$1(e,`utf-8`))??{}}catch(t){if(t?.code!==`ENOENT`&&!fmReadWarnedPaths.has(e)){fmReadWarnedPaths.add(e);let S=t instanceof Error?t.message:String(t);console.warn(`[ok-enrich] failed to read frontmatter at ${e} — enrichment degraded for this file. Reason: ${S}`)}return null}}async function fetchBacklinks(e,t){if(!e)return null;let S=await httpGet(e,`/api/backlinks?docName=${encodeURIComponent(t)}`);if(!S.ok)return null;let w=S.backlinks??S.results??S.links;if(!Array.isArray(w))return[];let E=[];for(let e of w){if(typeof e!=`object`||!e)continue;let t=e,S=typeof t.docName==`string`?t.docName:typeof t.source==`string`?t.source:typeof t.page==`string`?t.page:void 0;S&&E.push({source:S,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return E}const BACKLINK_COUNT_CHUNK=100;async function fetchBacklinkCountsBatch(e,t){if(!e||t.length===0)return null;let S=[...new Set(t)],w=[];for(let e=0;e<S.length;e+=BACKLINK_COUNT_CHUNK)w.push(S.slice(e,e+BACKLINK_COUNT_CHUNK));let E=await Promise.all(w.map(async t=>{let S=await httpGet(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return S.ok?S.counts??{}:null})),D=new Map,O=!1;for(let e of E)if(e){O=!0;for(let[t,S]of Object.entries(e))typeof S==`number`&&Number.isFinite(S)&&D.set(t,S)}return O?D:null}async function fetchForwardLinks(e,t){if(!e)return null;let S=await httpGet(e,`/api/forward-links?docName=${encodeURIComponent(t)}`);if(!S.ok)return null;let w=S.forwardLinks??S.links??S.results;if(!Array.isArray(w))return[];let E=[];for(let e of w){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){E.push({kind:`external`,url:t.url,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null});continue}let S=typeof t.docName==`string`?t.docName:void 0;S&&E.push({kind:`doc`,docName:S,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return E}function mergeFileAndFolder(e,t,S){let w=mergeCascade(S?resolveNestedFrontmatter(S,parentFolderOf(t)):{},e??{});return{title:typeof w.title==`string`?w.title:void 0,description:typeof w.description==`string`?w.description:void 0,tags:Array.isArray(w.tags)?w.tags.filter(e=>typeof e==`string`):[],frontmatter:w}}async function enrichPath(e,t,S={}){let w=resolveWithinRoot(t.projectDir,e);if(!w.ok)throw Error(`enrichPath: ${w.reason}`);let E=w.rel,D=w.abs,O=t.historyDepth??5,k=S.includeRichFields===!0,j=readFrontmatter(D);if(!k){let e=mergeFileAndFolder(await j,E,t.projectDir);return{path:E,title:e.title,description:e.description,tags:e.tags,frontmatter:e.frontmatter,backlinkCount:null,backlinks:null,forwardLinkCount:null,forwardLinks:null,history:null,historySource:null,projectHistory:null,projectHistorySource:null}}let[F,L,B,H,q]=await Promise.all([j,fetchBacklinks(t.serverUrl,pathToDocName$1(E)).catch(()=>null),fetchForwardLinks(t.serverUrl,pathToDocName$1(E)).catch(()=>null),readShadowLog(t.projectDir,E,O).catch(()=>({commits:[],source:`shadow-repo`})),readProjectGitLog(t.projectDir,E,O).catch(()=>({commits:[],source:`git`}))]),J=mergeFileAndFolder(F,E,t.projectDir);return{path:E,title:J.title,description:J.description,tags:J.tags,frontmatter:J.frontmatter,backlinkCount:L?.length??null,backlinks:L,forwardLinkCount:B?.length??null,forwardLinks:B,history:H.commits,historySource:H.source,projectHistory:q.commits,projectHistorySource:q.source}}async function scanDirectory(e,t){let S={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},w=0,E=[{path:e,depth:0}];for(;E.length>0;){let e=E.shift();if(!e)break;if(w>=DIRECTORY_SCAN_CAP){S.truncated=!0;break}let D;try{D=await readdir(e.path,{withFileTypes:!0})}catch{continue}for(let O of D){if(w>=DIRECTORY_SCAN_CAP){S.truncated=!0;break}w++;let D=O.name;if(O.isDirectory()){if(DIR_SKIP.has(D)||D.startsWith(`.`))continue;e.depth===0&&S.childDirCount++,E.push({path:`${e.path}/${D}`,depth:e.depth+1})}else if(O.isFile()&&WIKI_EXT_RE.test(D)){S.recursiveMdCount++,e.depth===0&&S.directMdCount++;let w=`${e.path}/${D}`;try{let e=await stat$1(w);(!S.mostRecent||e.mtimeMs>S.mostRecent.mtimeMs)&&(S.mostRecent={absPath:w,relPath:relative(t,w).split(/[\\/]/).filter(Boolean).join(`/`),mtimeMs:e.mtimeMs})}catch{}}}}return S}async function enrichDirectory(e,t){let S=resolveWithinRoot(t.projectDir,e);if(!S.ok)throw Error(`enrichDirectory: ${S.reason}`);let w=S.rel,E=S.abs,D=await scanDirectory(E,t.projectDir),O;if(D.mostRecent){let e=await readFrontmatter(D.mostRecent.absPath),t=typeof e?.title==`string`?e.title:void 0;O={path:D.mostRecent.relPath,title:t??basename(D.mostRecent.relPath),updatedAt:new Date(D.mostRecent.mtimeMs).toISOString()}}let k={path:w,type:`directory`,directMdCount:D.directMdCount,recursiveMdCount:D.recursiveMdCount,childDirCount:D.childDirCount,mostRecentMd:O,truncated:D.truncated},j=resolveNestedFrontmatter(t.projectDir,w),F=j.title,L=j.description,B=j.tags??[];F!==void 0&&(k.title=F),L!==void 0&&(k.description=L),B.length>0&&(k.tags=B),Object.keys(j).length>0&&(k.frontmatter_defaults=j);let H=resolveTemplatesAvailable(t.projectDir,w);return H.length>0&&(k.templates_available=H),k}async function enrichDirectoryRecursive(e,t,S){let w=await enrichDirectory(e,S);if(t<=1)return w;let E=w.path,D=resolve(S.projectDir,E),O;try{O=await readdir(D,{withFileTypes:!0})}catch{return w}let k=[];for(let e of O){if(!e.isDirectory()||RECURSIVE_LISTING_SKIP_DIRS.has(e.name)||e.name.startsWith(`.`))continue;let w=await enrichDirectoryRecursive(E?`${E}/${e.name}`:e.name,t-1,S);k.push(w)}return k.length>0&&(w.subfolders=k),w}const RECURSIVE_LISTING_SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`]);function applyNestedFolderRulesUpsert(e){if(!isAbsolute(e.projectDir))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};let t=[];for(let S of e.rules){let w=resolveTargetFolderFromMatch(S.new_match??S.match);if(!w.ok)return{ok:!1,error:{code:`MULTI_FOLDER_GLOB`,message:w.message,rule:S.match}};let E=w.folder?resolve(e.projectDir,w.folder):e.projectDir,D=resolve(e.projectDir);if(!E.startsWith(D+sep)&&E!==D)return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved target folder escapes projectDir: ${E}`,rule:S.match}};let O=null,k=null;if(S.new_match!==void 0&&S.new_match!==S.match){let t=resolveTargetFolderFromMatch(S.match);if(!t.ok)return{ok:!1,error:{code:`MULTI_FOLDER_GLOB`,message:t.message,rule:S.match}};if(O=t.folder,k=t.folder?resolve(e.projectDir,t.folder):e.projectDir,!k.startsWith(D+sep)&&k!==D)return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved source folder escapes projectDir: ${k}`,rule:S.match}}}t.push({targetFolder:w.folder,targetAbs:E,sourceFolder:O,sourceAbs:k,rule:S})}let S=[];for(let w of t)try{if(w.sourceAbs&&w.sourceAbs!==w.targetAbs){let t=join(w.sourceAbs,`.ok`,`frontmatter.yml`);existsSync(t)&&(unlinkSync(t),autoCleanOkDir(join(w.sourceAbs,`.ok`)),S.push({match:w.rule.match,path:relPathOf$1(e.projectDir,t),action:`deleted`}))}let t=join(w.targetAbs,`.ok`),E=join(t,`frontmatter.yml`),D=readExistingFrontmatter(E),O=Object.keys(w.rule.frontmatter).length===0?{}:mergePatch(D,w.rule.frontmatter);if(Object.keys(O).length===0){existsSync(E)&&(unlinkSync(E),autoCleanOkDir(t),S.push({match:w.rule.new_match??w.rule.match,path:relPathOf$1(e.projectDir,E),action:`deleted`}));continue}mkdirSync(t,{recursive:!0});let k=(0,import_dist$1.stringify)(O),j=`${E}.tmp.${process.pid}.${Date.now()}`;writeFileSync(j,k,`utf-8`),renameSync(j,E),S.push({match:w.rule.new_match??w.rule.match,path:relPathOf$1(e.projectDir,E),action:`written`})}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write nested frontmatter for ${w.rule.match}: ${e.message}`,rule:w.rule.match},...S.length>0?{partiallyApplied:S}:{}}}return{ok:!0,applied:S}}function resolveTargetFolderFromMatch(e){let t=e.split(`/`).filter(e=>e.length>0),S=[],w=!1;for(let E of t){let t=/[*?[\]{}]/.test(E);if(w&&!t)return{ok:!1,message:`Glob "${e}" matches multiple folders (literal segment "${E}" appears after a glob). Split it into one rule per folder, e.g. folder_config({ action: "set-rule", rules: [{ match: "specs/foo/${E}/**", ... }, ...] }).`};if(t){if(w=!0,E!==`**`&&E!==`*`)return{ok:!1,message:`Glob "${e}" uses an unsupported pattern segment "${E}". Only "*" and "**" are supported in nested folder rules.`};continue}S.push(E)}return{ok:!0,folder:S.join(`/`)}}function readExistingFrontmatter(e){if(!existsSync(e))return{};let t=(0,import_dist$1.parse)(readFileSync(e,`utf-8`));return typeof t!=`object`||!t||Array.isArray(t)?{}:{...t}}function autoCleanOkDir(e){if(!existsSync(e))return;let t;try{t=readdirSync(e)}catch{return}if(t.length===0)try{rmdirSync(e)}catch{}}function relPathOf$1(e,t){let S=resolve(e);return t.startsWith(S+sep)?t.slice(S.length+1).split(sep).join(`/`):t}const SUBSTITUTION_ALLOWLIST=[`date`,`user`],TOKEN_PATTERN=/\{\{([^{}\n]+?)\}\}/g;function validateSubstitution(e){let t=[];for(let S of e.matchAll(TOKEN_PATTERN)){let e=(S[1]??``).trim();isAllowedToken(e)||t.push({token:e,offset:S.index??0})}return t}function applySubstitution(e,t){return e.replace(TOKEN_PATTERN,(e,S)=>{let w=S.trim();return isAllowedToken(w)?t[w]:e})}function isAllowedToken(e){return SUBSTITUTION_ALLOWLIST.includes(e)}function todayIsoUtc(e=new Date){return`${e.getUTCFullYear().toString().padStart(4,`0`)}-${(e.getUTCMonth()+1).toString().padStart(2,`0`)}-${e.getUTCDate().toString().padStart(2,`0`)}`}const NAME_RE=/^[A-Za-z0-9_-]+$/;function applyTemplateWrite(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let S=validateTitle(e.frontmatter.title);if(!S.ok)return{ok:!1,error:S.error};let w=validateSubstitutionAllowlist(e.body);if(!w.ok)return{ok:!1,error:w.error};let{templatesDir:E,filePath:D}=templatePaths(e.projectDir,t.folderRel,e.name),O=serializeFrontmatter(e.frontmatter),k=O?`---\n${O}---\n${e.body}`:e.body;try{mkdirSync(E,{recursive:!0})}catch(t){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${relPathOf(e.projectDir,E)}: ${t.message}`}}}let j=!existsSync(D),F=`${D}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(F,k,`utf-8`),renameSync(F,D)}catch(t){try{unlinkSync(F)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${relPathOf(e.projectDir,D)}: ${t.message}`}}}let L=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&L.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,path:relPathOf(e.projectDir,D),created:j,warnings:L}}function applyTemplateDelete(e){let t=validateInputs(e.projectDir,e.folder,e.name);if(!t.ok)return{ok:!1,error:t.error};let{templatesDir:S,okDir:w,filePath:E}=templatePaths(e.projectDir,t.folderRel,e.name),D=existsSync(E);if(D)try{unlinkSync(E)}catch(t){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete template at ${relPathOf(e.projectDir,E)}: ${t.message}`}}}let O=!1,k=!1;if(existsSync(S)&&isEmpty(S))try{rmdirSync(S),O=!0}catch{}if(existsSync(w)&&isEmpty(w))try{rmdirSync(w),k=!0}catch{}return{ok:!0,path:relPathOf(e.projectDir,E),existed:D,cleanedEmpty:{templatesDir:O,okDir:k}}}function validateInputs(e,t,S){if(!isAbsolute(e))return{ok:!1,error:{code:`BAD_PROJECT_DIR`,message:`projectDir must be absolute`}};if(!NAME_RE.test(S))return{ok:!1,error:{code:`BAD_NAME`,message:`Template name must match /^[A-Za-z0-9_-]+$/ (got: ${JSON.stringify(S)}). Use letters, digits, underscores, or hyphens — no slashes, dots, or spaces.`}};let w=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``);if(w.includes(`..`))return{ok:!1,error:{code:`PATH_TRAVERSAL`,message:`Folder path may not contain "..": ${JSON.stringify(t)}`}};let E=w?resolve(e,w):e,D=resolve(e);return!E.startsWith(D+sep)&&E!==D?{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder path escapes projectDir: ${E}`}}:{ok:!0,folderRel:w}}function validateTitle(e){return typeof e!=`string`||e.length===0?{ok:!1,error:{code:`TEMPLATE_TITLE_REQUIRED`,message:"Template frontmatter.title is required. `title` is the menu surface — agents pick templates by name+title; a title-less template is effectively invisible. Set a non-empty `title` and retry."}}:{ok:!0}}function validateSubstitutionAllowlist(e){let t=validateSubstitution(e);return t.length===0?{ok:!0}:{ok:!1,error:{code:`TEMPLATE_UNKNOWN_VARIABLE`,message:`Template body contains unknown substitution token(s): ${t.map(e=>`\`{{${e.token}}}\` at offset ${e.offset}`).join(`, `)}. v1 allowlist: \`{{date}}\`, \`{{user}}\`. Remove or rename the offending tokens and retry.`}}}function templatePaths(e,t,S){let w=t?join(e,t,`.ok`):join(e,`.ok`),E=join(w,`templates`);return{okDir:w,templatesDir:E,filePath:join(E,`${S}.md`)}}function relPathOf(e,t){return normalize(t.startsWith(e+sep)?t.slice(e.length+1):t).split(sep).join(`/`)}function serializeFrontmatter(e){let t={};return e.title!==void 0&&(t.title=e.title),e.description!==void 0&&(t.description=e.description),Array.isArray(e.tags)&&e.tags.length>0&&(t.tags=e.tags),Object.keys(t).length===0?``:(0,import_dist$1.stringify)(t)}function isEmpty(e){try{return readdirSync(e).length===0}catch{return!1}}const log$5=()=>getLogger(`http`);function successResponse(e,t,S,w,E={}){if(e.headersSent||e.writableEnded||e.destroyed){log$5().error({event:`api.success.double-write`,status:t,handler:E.handler},`successResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...E.handler?{handler:E.handler}:{}});return}let D=S.safeParse(w);if(!D.success){log$5().error({event:`api.success.malformed-body`,issues:D.error.issues,bodyKeys:typeof w==`object`&&w?Object.keys(w):null,handler:E.handler,originalStatus:t},`successResponse produced an invalid body for the supplied schema — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E.handler});return}let O;try{O=JSON.stringify(D.data)}catch(S){log$5().error({event:`api.success.unserializable-body`,bodyKeys:typeof D.data==`object`&&D.data!==null?Object.keys(D.data):null,handler:E.handler,originalStatus:t,err:S},`successResponse parsed body is not JSON-serializable — emitting fallback`),errorResponse(e,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:E.handler});return}e.writeHead(t,{...E.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(O)}const INSTALLED_AGENTS_SCHEMES=[`claude`,`codex`,`cursor`],INSTALLED_AGENTS_PROBE_TIMEOUT_MS=2e3,MACOS_APP_NAMES={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function createInstalledAgentsProbe(e){let t=new Map,S=e.now??Date.now,w=e.ttlMs??6e4;async function E(E){let D=t.get(E);if(D?.status===`resolved`&&D.expiresAt>S())return D.installed;if(D?.status===`inflight`)return D.promise;let O=(async()=>{try{let D=await e.probe(E);return t.set(E,{status:`resolved`,installed:D,expiresAt:S()+w}),D}catch{return t.set(E,{status:`resolved`,installed:!1,expiresAt:S()+w}),!1}})();return t.set(E,{status:`inflight`,promise:O}),O}async function D(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await E(e)]));return Object.fromEntries(e)}return{probeAll:D,probeWithCache:E}}function isLocalWebHost(e){let t=e.headers.host;if(typeof t==`string`&&t.length>0)try{let{hostname:e}=new URL(`http://${t}/`);return isLoopbackHostname(e)}catch{}let S=e.headers.origin;if(typeof S==`string`&&S.length>0)try{return isLoopbackHostname(new URL(S).hostname)}catch{return!1}return!0}function isLoopbackHostname(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`||e===`::1`}async function handleInstalledAgents(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`installed-agents`,extraHeaders:{Allow:`GET`}});return}try{successResponse(t,200,InstalledAgentsSuccessSchema,isLocalWebHost(e)?await S():Object.fromEntries(INSTALLED_AGENTS_SCHEMES.map(e=>[e,!0])),{handler:`installed-agents`})}catch(e){console.error(`[installed-agents]`,e),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e})}}function createOsProbe(e,t=execFile){return S=>e===`darwin`?probeMacOs(S,t):e===`win32`?probeWindows(S,t):probeLinux(S,t)}function probeMacOs(e,t){let S=MACOS_APP_NAMES[e];function w(e){return new Promise(S=>{t(`osascript`,[`-e`,`id of app "${e}"`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){S(!1);return}S(t.trim().length>0)})})}return(async()=>{for(let e of S)if(await w(e))return!0;return!1})()}function probeWindows(e,t){return new Promise(S=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},e=>{S(!e)})})}function probeLinux(e,t){return new Promise(S=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],{timeout:INSTALLED_AGENTS_PROBE_TIMEOUT_MS,encoding:`utf-8`},(e,t)=>{if(e){S(!1);return}S(t.trim().length>0)})})}const MAX_BODY_BYTES=1048576,REQUEST_BODY_TIMEOUT_MS=3e4;function readRequestBody(e){return readBoundedJsonBody(e,{maxBytes:MAX_BODY_BYTES,timeoutMs:REQUEST_BODY_TIMEOUT_MS})}async function readBoundedJsonBody(e,t){let S=[],w=0,E=AbortSignal.timeout(t.timeoutMs),D=()=>e.destroy(new RequestBodyTimeoutError(t.timeoutMs));E.addEventListener(`abort`,D,{once:!0});try{for await(let E of e){if(w+=E.length,w>t.maxBytes)throw new PayloadTooLargeError(t.maxBytes);S.push(E)}return Buffer.concat(S)}finally{E.removeEventListener(`abort`,D)}}var PayloadTooLargeError=class extends Error{maxBytes;constructor(e){super(e===void 0?`Request body exceeded cap`:`Request body exceeded ${formatBytes(e)} cap`),this.name=`PayloadTooLargeError`,this.maxBytes=e}},RequestBodyTimeoutError=class extends Error{timeoutMs;constructor(e){super(e===void 0?`Request body read exceeded timeout`:`Request body read exceeded ${e}ms timeout`),this.name=`RequestBodyTimeoutError`,this.timeoutMs=e}};function formatBytes(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function validateBody(e,t,S,w={}){let E=e.safeParse(t);if(E.success)return{ok:!0,value:E.data};let D=E.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return errorResponse(S,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:w.handler,detail:D}),{ok:!1}}function withValidation(e,t,S={}){return async(w,E)=>{if(S.method!==void 0&&w.method!==S.method){errorResponse(E,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:S.handler,extraHeaders:{Allow:S.method}});return}if(S.preBodyGate!==void 0&&!S.preBodyGate(w,E)){!E.headersSent&&!E.writableEnded&&!E.destroyed&&errorResponse(E,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:S.handler,cause:Error(`preBodyGate returned false without writing a response`)});return}if(S.skipBodyParse){let D=validateBody(e,{},E,S);if(!D.ok)return;await t(w,E,D.value);return}let D;try{D=await readRequestBody(w)}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(E,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:S.handler,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(E,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:S.handler,cause:e});return}errorResponse(E,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:S.handler,cause:e});return}let O;try{O=D.length===0?{}:JSON.parse(D.toString(`utf8`))}catch(e){errorResponse(E,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:S.handler,cause:e});return}let k=validateBody(e,O,E,S);k.ok&&await t(w,E,k.value)}}function classifySpawnError(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`}}function spawnDetached(e,t,S){return new Promise(w=>{let E=!1,D=e=>{E||(E=!0,w(e))},O=setTimeout(()=>D({ok:!1,reason:`timeout`}),S);try{let S=spawn(e,[...t],{detached:!0,stdio:`ignore`,shell:!1});S.once(`error`,e=>{clearTimeout(O),D(classifySpawnError(e))}),S.once(`spawn`,()=>{if(!E){try{S.unref()}catch{}clearTimeout(O),D({ok:!0})}})}catch(e){console.warn(`[spawn-detached] synchronous spawn throw:`,e),clearTimeout(O),D(classifySpawnError(e))}})}const SPAWN_CURSOR_WHICH_TIMEOUT_MS=500,SPAWN_CURSOR_SPAWN_TIMEOUT_MS=2e3,SPAWN_CURSOR_MAX_BODY_BYTES=4*1024,SPAWN_CURSOR_BODY_READ_TIMEOUT_MS=5e3,HANDLER$1=`spawn-cursor`;function assertNeverSpawnReason(e){throw Error(`Unhandled spawn-cursor outcome.reason: ${String(e)}`)}async function handleSpawnCursor(e,t,S){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER$1,extraHeaders:{Allow:`POST`}});return}let w;try{w=await readBoundedJsonBody(e,{maxBytes:SPAWN_CURSOR_MAX_BODY_BYTES,timeoutMs:SPAWN_CURSOR_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER$1,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER$1,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER$1,cause:e});return}let E;try{E=JSON.parse(w.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER$1,cause:e});return}let D=typeof E.path==`string`?E.path:``;if(!D){errorResponse(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:HANDLER$1});return}if(!isPathWithinDir(D,S.contentDir,S.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return}let O=await(S.resolveCursorBinary??resolveCursorBinaryDefault)(SPAWN_CURSOR_WHICH_TIMEOUT_MS);if(!O){errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return}let k=resolveCursorSpawnInvocation(O,D,S.platform),j=await(S.spawnDetached??spawnDetached)(k.exec,k.args,SPAWN_CURSOR_SPAWN_TIMEOUT_MS);if(j.ok){successResponse(t,200,SpawnCursorSuccessSchema,{},{handler:HANDLER$1});return}switch(j.reason){case`not-installed`:errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return;case`timeout`:errorResponse(t,504,`urn:ok:error:cursor-spawn-timeout`,`Cursor spawn exceeded the deadline.`,{handler:HANDLER$1});return;case`spawn-error`:errorResponse(t,502,`urn:ok:error:cursor-spawn-failed`,`Cursor spawn failed.`,{handler:HANDLER$1});return;case`invalid-path`:errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return;default:return assertNeverSpawnReason(j.reason)}}const CURSOR_BUNDLE_PATHS_BY_PLATFORM={darwin:[()=>`/Applications/Cursor.app/Contents/Resources/app/bin/cursor`,e=>`${e}/Applications/Cursor.app/Contents/Resources/app/bin/cursor`],win32:[e=>`${e}\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd`,()=>`C:\\Program Files\\Cursor\\resources\\app\\bin\\cursor.cmd`]};async function resolveCursorBinaryDefault(e){let t=CURSOR_BUNDLE_PATHS_BY_PLATFORM[process.platform];if(t&&t.length>0){let e=homedir();for(let S of t){let t=S(e);try{return await access(t,constants.X_OK),t}catch(e){let S=e?.code;S!==`ENOENT`&&S!==`EACCES`&&S!==`EPERM`&&console.warn(`[spawn-cursor] unexpected fs.access error on bundle probe:`,S,t)}}}return new Promise(t=>{execFile(process.platform===`win32`?`where`:`which`,[`cursor`],{timeout:e,encoding:`utf-8`},(e,S)=>{if(e){t(null);return}let w=S.split(/\r?\n/)[0]?.trim();t(w&&w.length>0?w:null)})})}function resolveCursorSpawnInvocation(e,t,S){return S===`darwin`&&/\.app\/?$/.test(e)?{exec:`/usr/bin/open`,args:[`-a`,e.replace(/\/$/,``),t]}:{exec:e,args:[t]}}function isPathWithinDir(e,t,S){if(!e||typeof e!=`string`||e.includes(`\0`)||!t||typeof t!=`string`)return!1;if(S===`win32`){if(!/^([a-zA-Z]:[\\/]|\\\\)/.test(e)||!/^([a-zA-Z]:[\\/]|\\\\)/.test(t))return!1}else if(!e.startsWith(`/`)||!t.startsWith(`/`))return!1;let w=S===`win32`?win32:posix;try{let E=w.resolve(e),D=w.resolve(t);if(S===`win32`){let e=w.parse(E).root.toLowerCase(),t=w.parse(D).root.toLowerCase();if(!e||!t||e!==t)return!1}if(E===D)return!0;let O=w.relative(D,E);return O===``||O===`.`?!0:!(O===`..`||O.startsWith(`..${w.sep}`)||S===`win32`&&(/^[a-zA-Z]:[\\/]/.test(O)||O.startsWith(`\\\\`))||S!==`win32`&&O.startsWith(`/`))}catch(e){return console.warn(`[spawn-cursor] unexpected path-resolution error:`,e),!1}}const HANDLER=`handoff`,HANDOFF_MAX_BODY_BYTES=4*1024,HANDOFF_BODY_READ_TIMEOUT_MS=5e3,SPAWN_TIMEOUT_MS=2e3,WHICH_TIMEOUT_MS=500,QUIT_SETTLE_MS=3e3,APP_BUNDLE_SETTLE_MS=5e3,CURSOR_SETTLE_MS=1500,RECIPES={"claude-cowork":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,quitFirst:!1},"claude-code":{type:`app-bundle`,appName:`Claude`,urlScheme:`claude:`,quitFirst:!1},codex:{type:`app-bundle`,appName:`Codex`,urlScheme:`codex:`,quitFirst:!0},cursor:{type:`cli-binary`,binaryName:`cursor`,urlScheme:`cursor:`}},TARGET_VALUES=Object.keys(RECIPES),HandoffRequestSchema=object$1({target:_enum(TARGET_VALUES),url:string$2().min(1).max(4096),workspacePath:string$2().optional()}),HandoffSuccessSchema=object$1({}).loose();function defaultSleep(e){return new Promise(t=>setTimeout(t,e))}async function handleHandoffDispatch(e,t,S){if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:HANDLER,extraHeaders:{Allow:`POST`}});return}if(S.platform!==`darwin`){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Handoff is currently macOS-only.`,{handler:HANDLER});return}let w;try{w=await readBoundedJsonBody(e,{maxBytes:HANDOFF_MAX_BODY_BYTES,timeoutMs:HANDOFF_BODY_READ_TIMEOUT_MS})}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(t,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:HANDLER,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(t,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:HANDLER,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:HANDLER,cause:e});return}let E;try{E=JSON.parse(w.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER,cause:e});return}let D=HandoffRequestSchema.safeParse(E);if(!D.success){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid request body.`,{handler:HANDLER});return}let{target:O,url:k,workspacePath:j}=D.data,F=RECIPES[O];if(!k.startsWith(F.urlScheme)){errorResponse(t,400,`urn:ok:error:invalid-request`,`URL scheme must be ${F.urlScheme} for target ${O}.`,{handler:HANDLER});return}let L=S.sleep??defaultSleep,B=S.spawnDetached??spawnDetached;if(F.type===`app-bundle`){F.quitFirst&&(await B(`/usr/bin/osascript`,[`-e`,`tell application "${F.appName}" to quit`],SPAWN_TIMEOUT_MS).catch(()=>void 0),await L(QUIT_SETTLE_MS));let e=await B(`/usr/bin/open`,[`-a`,F.appName],SPAWN_TIMEOUT_MS);if(!e.ok){emitSpawnFailure(t,O,e.reason);return}await L(APP_BUNDLE_SETTLE_MS);let S=await B(`/usr/bin/open`,[k],SPAWN_TIMEOUT_MS);if(!S.ok){emitSpawnFailure(t,O,S.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER});return}if(!j){errorResponse(t,400,`urn:ok:error:invalid-request`,`workspacePath is required for cursor handoff.`,{handler:HANDLER});return}if(!isPathWithinDir(j,S.contentDir,S.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER});return}let H=await(S.resolveCursorBinary??resolveCursorBinaryDefault)(WHICH_TIMEOUT_MS);if(!H){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER,extensions:{target:`cursor`}});return}let q=resolveCursorSpawnInvocation(H,j,S.platform),J=await B(q.exec,q.args,SPAWN_TIMEOUT_MS);if(!J.ok){emitSpawnFailure(t,O,J.reason);return}await L(CURSOR_SETTLE_MS);let Y=await B(`/usr/bin/open`,[k],SPAWN_TIMEOUT_MS);if(!Y.ok){emitSpawnFailure(t,O,Y.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER})}function emitSpawnFailure(e,t,S){switch(S){case`not-installed`:errorResponse(e,422,`urn:ok:error:handoff-target-not-installed`,`Required binary or application not found.`,{handler:HANDLER,extensions:{target:t}});return;case`timeout`:errorResponse(e,504,`urn:ok:error:handoff-spawn-timeout`,`Handoff spawn exceeded the deadline.`,{handler:HANDLER,extensions:{target:t}});return;case`spawn-error`:errorResponse(e,502,`urn:ok:error:handoff-spawn-failed`,`Handoff spawn failed.`,{handler:HANDLER,extensions:{target:t}});return;default:assertNeverReason(S)}}function assertNeverReason(e){throw Error(`Unhandled spawn reason: ${String(e)}`)}const FIXED_HUB_BASENAMES=[`INDEX`,`README`,`REPORT`,`SPEC`],MAX_CANDIDATES=3;function findHubCandidates(e,t){let S=[],w=new Set,E=t=>{!t||w.has(t)||t!==e&&(w.add(t),S.push(t))},D=buildLowerDocNameIndex(t),O=parentFolder(e);for(;;){for(let e of FIXED_HUB_BASENAMES)if(E(lookup$1(t,D,joinDocName(O,e))),S.length>=MAX_CANDIDATES)return S;let e=O===``?null:basename$1(O);if(e&&(E(lookup$1(t,D,joinDocName(O,e))),S.length>=MAX_CANDIDATES))return S;if(O===``)break;O=parentFolder(O)}return S}function lookup$1(e,t,S){return e.has(S)?S:t.get(S.toLowerCase())??null}function buildLowerDocNameIndex(e){let t=new Map;for(let S of e.keys()){let e=S.toLowerCase();t.has(e)||t.set(e,S)}return t}function parentFolder(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function basename$1(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function joinDocName(e,t){return e===``?t:`${e}/${t}`}function splitFrontmatterLines(e){return e?e.replace(/^---\r?\n/,``).replace(/\r?\n---(?:\r?\n)?$/,``).split(/\r?\n/):[]}function normalizeFrontmatterScalar(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function extractFrontmatterScalar(e,t){let S=`${t}:`;for(let t of splitFrontmatterLines(e))if(t.startsWith(S))return normalizeFrontmatterScalar(t.slice(S.length))||null;return null}function parseInlineAliases(e){let t=[],S=``,w=null;for(let E of e){if(w){S+=E,E===w&&(w=null);continue}if(E===`"`||E===`'`){w=E,S+=E;continue}if(E===`,`){let e=normalizeFrontmatterScalar(S);e&&t.push(e),S=``;continue}S+=E}let E=normalizeFrontmatterScalar(S);return E&&t.push(E),t}function dedupeExact(e){let t=[],S=new Set;for(let w of e)!w||S.has(w)||(S.add(w),t.push(w));return t}function extractPageAliases(e){let{frontmatter:t}=stripFrontmatter(e);if(!t)return[];let S=splitFrontmatterLines(t);for(let e=0;e<S.length;e+=1){let t=S[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let w=t[1]?.trim()??``;if(w){if(w.startsWith(`[`)&&w.endsWith(`]`))return dedupeExact(parseInlineAliases(w.slice(1,-1)));let e=normalizeFrontmatterScalar(w);return e?[e]:[]}let E=[];for(let t=e+1;t<S.length;t+=1){let e=S[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&E.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return dedupeExact(E)}return[]}function extractPageTitle(e,t){let{frontmatter:S,body:w}=stripFrontmatter(e),E=extractFrontmatterScalar(S,`title`);if(E)return E;let D=w.match(/^# (.+)$/m);return D?D[1].trim():t}const ICON_VALUE_LENGTH_CAP=2048;function extractPageIcon(e){let{frontmatter:t}=stripFrontmatter(e),S=extractFrontmatterScalar(t,`icon`);if(!(!S||S.length>ICON_VALUE_LENGTH_CAP))return S}function parseFrontmatterMetadata(e){return e?.trim()?{cluster:extractFrontmatterScalar(e,`cluster`)??void 0,category:extractFrontmatterScalar(e,`category`)??void 0,tags:extractFrontmatterArray(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function extractFrontmatterArray(e,t){let S=`${t}:`,w=splitFrontmatterLines(e);for(let e=0;e<w.length;e+=1){let t=w[e];if(!t?.startsWith(S))continue;let E=t.slice(S.length).trim();if(E){if(E.startsWith(`[`)&&E.endsWith(`]`)){let e=parseInlineAliases(E.slice(1,-1));return e.length>0?e:void 0}let e=normalizeFrontmatterScalar(E);return e?[e]:void 0}let D=[];for(let t=e+1;t<w.length;t+=1){let e=w[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&D.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return D.length>0?D:void 0}}function extractPageIdentity(e,t){let S=extractPageTitle(e,t),w=extractPageAliases(e),E=dedupeExact([S,...w]),D=[],O=new Set;for(let e of E){let t=toWikiLinkSlug(e);!t||O.has(t)||(O.add(t),D.push(t))}return{docName:t,title:S,aliases:w,matchLabels:E,normalizedMatchLabels:D}}const SHARE_BASE_URL=`https://openknowledge.ai/d/`,SHARE_CONSTRUCT_URL_HANDLER_TAG=`share-construct-url`;function isValidShareDocPath(e){if(e.length===0||e.startsWith(`/`)||e.startsWith(`\\`))return!1;for(let t of e.split(/[/\\]/))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function buildGitHubBlobUrl(e,t,S,w){return`https://github.com/${e}/${t}/blob/${encodeURIComponent(S)}/${w.split(`/`).map(encodeURIComponent).join(`/`)}`}function emitShareConstructUrlLog(e,t){let S=t===void 0?``:` branch_exists=${t}`;console.log(`[share] action=construct-url result=${e}${S}`)}function resolveGitDir$1(e){let t=resolve(e,`.git`);if(!existsSync(t))return null;let S;try{S=statSync(t)}catch{return null}if(S.isDirectory())return t;if(S.isFile()){let S;try{S=readFileSync(t,`utf-8`)}catch{return null}let w=/^gitdir:\s*(.+)$/m.exec(S.trim());if(!w)return null;let E=w[1].trim(),D=isAbsolute(E)?E:resolve(e,E);return existsSync(D)?D:null}return null}function readGitHeadBranch(e){let t=resolveGitDir$1(e);if(!t)return null;let S=join(t,`HEAD`);if(!existsSync(S))return null;let w;try{w=readFileSync(S,`utf-8`)}catch{return null}let E=/^ref:\s*refs\/heads\/(.+)$/.exec(w.trim());return E?E[1]:null}function stripCommentAndTrim(e){let t=e.indexOf(`#`),S=e.indexOf(`;`),w=-1;return t>=0&&S>=0?w=Math.min(t,S):t>=0?w=t:S>=0&&(w=S),(w===-1?e:e.slice(0,w)).trim()}function extractOriginUrl(e){let t=!1;for(let S of e.split(/\r?\n/)){let e=stripCommentAndTrim(S);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let w=/^url\s*=\s*(.+)$/.exec(e);if(!w)continue;let E=w[1].trim();if((E.startsWith(`"`)&&E.endsWith(`"`)||E.startsWith(`'`)&&E.endsWith(`'`))&&(E=E.slice(1,-1)),E.length>0)return E}return null}function parseGitHubOriginUrl(e){let t=e.trim();if(!t)return null;let S=/^https?:\/\/(?:www\.)?github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return S||(S=/^ssh:\/\/(?:[\w.-]+@)?github\.com(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),S)||(S=/^[\w.-]+@github\.com:([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),S)||(S=/^git:\/\/github\.com\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),S)?{owner:S[1],repo:S[2]}:null}function readParsedOrigin(e){let t=resolveGitDir$1(e);if(!t)return null;let S=join(t,`config`);if(!existsSync(S))return null;let w;try{w=readFileSync(S,`utf-8`)}catch{return null}let E=extractOriginUrl(w);return E?{originUrl:E,github:parseGitHubOriginUrl(E)}:null}function readOriginGitHubRepo(e){let t=readParsedOrigin(e);return t?t.github?{kind:`ok`,owner:t.github.owner,repo:t.github.repo}:{kind:`non-github`}:{kind:`no-remote`}}function readSyncRemoteInfo(e){let t=readParsedOrigin(e);return t?t.github?{label:`${t.github.owner}/${t.github.repo}`,webUrl:`https://github.com/${t.github.owner}/${t.github.repo}`}:{label:labelFromNonGitHubUrl(t.originUrl),webUrl:null}:null}function labelFromNonGitHubUrl(e){let t=e.trim().replace(/\.git$/,``),S=/^[\w.-]+@([^:/]+):(.+)$/.exec(t);if(S)return`${S[1]}/${S[2]}`;let w=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)*(.+)$/i.exec(t);return w?w[1]:t}function branchExistsOnOrigin(e,t){let S=resolveGitDir$1(e);if(!S)return!1;if(existsSync(join(S,`refs`,`remotes`,`origin`,t)))return!0;let w=join(S,`packed-refs`);if(!existsSync(w))return!1;let E;try{E=readFileSync(w,`utf-8`)}catch{return!1}let D=`refs/remotes/origin/${t}`;for(let e of E.split(/\r?\n/)){let t=e.trim();if(t.length===0||t.startsWith(`#`)||t.startsWith(`^`))continue;let S=t.split(/\s+/);if(S.length===2&&S[1]===D)return!0}return!1}const SHARE_PUBLISH_OWNERS_HANDLER_TAG=`share-publish-owners`,SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG=`share-publish-name-check`,SHARE_PUBLISH_HANDLER_TAG=`share-publish`,SHARE_PUBLISH_OWNERS_KEY=`/api/share/publish/owners`,SHARE_PUBLISH_NAME_CHECK_KEY=`/api/share/publish/name-check`,SHARE_PUBLISH_KEY=`/api/share/publish`,SHARE_PUBLISH_TIMEOUT_MS=3e4;function isValidShareRepoName(e){return e.length===0||e.length>100||e.startsWith(`.`)||e.startsWith(`-`)||/^-+$/.test(e)?!1:/^[A-Za-z0-9._-]+$/.test(e)}function isValidShareOwnerName(e){return e.length===0||e.length>39||e.startsWith(`-`)||e.endsWith(`-`)?!1:/^[A-Za-z0-9-]+$/.test(e)}function pickTerminalJsonLine(e){let t=e.split(`
|
|
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??!0,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(`
|
|
@@ -2171,7 +2171,7 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
|
|
|
2171
2171
|
`)){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(`
|
|
2172
2172
|
`)}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$2.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$2.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`&®isterWrite(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 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$2.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 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$2.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$2.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$2.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 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$2.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$2.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$2.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$2.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$2.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$2.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(`
|
|
2173
2173
|
`),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$2.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$2.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$2.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$2.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$2.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$2.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$2.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(`
|
|
2174
|
-
`)[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$2.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=getDocExtension(t);try{e=extractPageTitle(readFileSync(resolve(w,`${t}${D}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}S.push({docName:t,title:e,docExt:D,size:E.size,modified:E.modified})}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$2.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$2.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$2.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$2.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=600*1e3,ac=45e3,oc=`local-op-clone`,sc=withValidation(LocalOpCloneRequestSchema,cc,{handler:oc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:oc})});async function cc(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:oc,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:oc,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:oc,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,oc),k=null,j=runCloneSubprocess({cliArgs:ue,url:w,dir:E,branch:D,timeoutMs:ic,onEvent:e=>{if(e.type===`complete`){k=e.dir;return}if(e.type===`error`){e.message&&log$2.warn({stderr:e.message,url:w,dir:E},`[local-op/clone] clone failed`),O(500,`urn:ok:error:clone-failed`,`Clone 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{}}});(async()=>{try{if(await j.done,k&&!t.writableEnded&&!t.destroyed){let e=await lc(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$2.error({err:e,handler:oc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),we.release(nc)}})(),t.on(`close`,()=>{j.cancel()})}async function lc(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$2.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 uc=`local-op-open`,dc=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:uc,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:uc,extraHeaders:{"Retry-After":`5`}});return}try{let e=await lc(w);`port`in e?successResponse(t,200,LocalOpOpenSuccessSchema,{port:e.port},{handler:uc}):errorResponse(t,504,`urn:ok:error:server-open-failed`,`Failed to open project server.`,{handler:uc,cause:Error(e.error)})}finally{we.release(rc)}},{handler:uc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:uc})}),fc=`/api/local-op/auth/login`,pc=`/api/local-op/auth/status`,mc=`/api/local-op/auth/repos`,hc=`/api/local-op/auth/signout`,gc=`/api/local-op/auth/pat`,_c=null,vc=`local-op-auth-login`,yc=withValidation(LocalOpAuthHostRequestSchema,bc,{handler:vc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:vc})});async function bc(e,t,S){let w=S.host??`github.com`;if(!we.tryAcquire(fc)){let e=_c;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:vc,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),_c=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,vc),D=runDeviceFlowSubprocess({cliArgs:ue,host:w,timeoutMs:ic,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{}}});_c=D;let O=()=>{D.cancel(),_c===D&&(_c=null,we.release(fc))};t.on(`close`,O),D.done.finally(()=>{if(t.off(`close`,O),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}_c===D&&(_c=null,we.release(fc))})}let xc=`local-op-auth-status`,Sc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!we.tryAcquire(pc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:xc,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(`
|
|
2174
|
+
`)[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$2.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$2.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$2.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$2.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$2.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=600*1e3,ac=45e3,oc=`local-op-clone`,sc=withValidation(LocalOpCloneRequestSchema,cc,{handler:oc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:oc})});async function cc(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:oc,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:oc,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:oc,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,oc),k=null,j=runCloneSubprocess({cliArgs:ue,url:w,dir:E,branch:D,timeoutMs:ic,onEvent:e=>{if(e.type===`complete`){k=e.dir;return}if(e.type===`error`){e.message&&log$2.warn({stderr:e.message,url:w,dir:E},`[local-op/clone] clone failed`),O(500,`urn:ok:error:clone-failed`,`Clone 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{}}});(async()=>{try{if(await j.done,k&&!t.writableEnded&&!t.destroyed){let e=await lc(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$2.error({err:e,handler:oc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),we.release(nc)}})(),t.on(`close`,()=>{j.cancel()})}async function lc(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$2.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 uc=`local-op-open`,dc=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:uc,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:uc,extraHeaders:{"Retry-After":`5`}});return}try{let e=await lc(w);`port`in e?successResponse(t,200,LocalOpOpenSuccessSchema,{port:e.port},{handler:uc}):errorResponse(t,504,`urn:ok:error:server-open-failed`,`Failed to open project server.`,{handler:uc,cause:Error(e.error)})}finally{we.release(rc)}},{handler:uc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:uc})}),fc=`/api/local-op/auth/login`,pc=`/api/local-op/auth/status`,mc=`/api/local-op/auth/repos`,hc=`/api/local-op/auth/signout`,gc=`/api/local-op/auth/pat`,_c=null,vc=`local-op-auth-login`,yc=withValidation(LocalOpAuthHostRequestSchema,bc,{handler:vc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:vc})});async function bc(e,t,S){let w=S.host??`github.com`;if(!we.tryAcquire(fc)){let e=_c;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:vc,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),_c=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,vc),D=runDeviceFlowSubprocess({cliArgs:ue,host:w,timeoutMs:ic,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{}}});_c=D;let O=()=>{D.cancel(),_c===D&&(_c=null,we.release(fc))};t.on(`close`,O),D.done.finally(()=>{if(t.off(`close`,O),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}_c===D&&(_c=null,we.release(fc))})}let xc=`local-op-auth-status`,Sc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!we.tryAcquire(pc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:xc,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(`
|
|
2175
2175
|
`).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:xc}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,O,{handler:xc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:xc,cause:e})}finally{we.release(pc)}},{handler:xc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:xc})}),Cc=`local-op-auth-repos`,wc=withValidation(LocalOpAuthHostRequestSchema,Tc,{handler:Cc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Cc})});async function Tc(e,t,S){let w=S.host??`github.com`;if(!we.tryAcquire(mc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Cc,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,Cc),[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`)},ic);L.stdout.on(`data`,e=>{F+=e.toString(`utf-8`);let S=F.split(`
|
|
2176
2176
|
`);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$2.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(mc))}),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(mc))}),t.on(`close`,()=>{j||(j=!0,clearTimeout(B),L.kill(`SIGTERM`),we.release(mc))})}let Ec=`local-op-auth-signout`,Dc=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!we.tryAcquire(hc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Ec,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:Ec})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Ec,cause:e})}finally{we.release(hc)}},{handler:Ec,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Ec})}),Oc=`local-op-auth-pat`,kc=withValidation(LocalOpAuthPatRequestSchema,async(e,t,S)=>{let{pat:w,host:E}=S,D=E??`github.com`;if(!we.tryAcquire(gc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth pat operation is already in progress.`,{handler:Oc,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(`
|
|
2177
2177
|
`).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:Oc}):successResponse(t,200,LocalOpAuthPatSuccessSchema,k,{handler:Oc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth pat failed.`,{handler:Oc,cause:e})}finally{we.release(gc)}},{handler:Oc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Oc})}),Ac=`local-op-auth-identity`;async function jc(e,t){if(checkLocalOpSecurity(e,t,{handler:Ac})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:Ac,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Ac});return}try{successResponse(t,200,LocalOpAuthIdentitySuccessSchema,{identity:await resolveGitIdentity(de)},{handler:Ac})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Identity resolution failed.`,{handler:Ac,cause:e})}}}let Mc=`/api/local-op/auth/set-identity`,Nc=`local-op-auth-set-identity`,Pc=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:Nc});return}if(!we.tryAcquire(Mc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Nc,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(de,w,E),ce?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Nc})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Nc,cause:e})}finally{we.release(Mc)}},{handler:Nc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Nc})});async function Fc(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 Ic=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 Lc(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 Rc=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 zc(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 await L.raw([`show`,`:${e}:${E}`])}catch{return``}}try{let[e,w,D]=await Promise.all([B(1),B(2),B(3)]),O=w,k=null;if(F===`ytext`){let e=stripDocExtension(E),S=t.documents.get(e);if(S){let t=S.getMap(`lifecycle`).get(`status`);k=typeof t==`string`&&t.length>0?t:null;let w=Ce?Ce(e):null;w!==null&&!ytextHasConflictMarkers(w)?O=w:w!==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:e,ours:O,theirs:D,lifecycleStatus:k},{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 Bc(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 Vc=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 Hc(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 Uc=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 Wc(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,ze.probeAll)}catch(e){t.headersSent||(log$2.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 Gc(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 Kc=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 qc(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 Jc(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 Yc=/^[A-Za-z0-9_-]+$/;function Xc(e,t,S=`template`){return!e||!Yc.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 Zc(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}async function Qc(e,t){if(e.method===`GET`)return $c(e,t);if(e.method===`PUT`)return nl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let $c=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=Jc(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`,`frontmatter.yml`),D=null;if(existsSync(E))try{let e=(0,import_dist$1.parse)(await readFile$1(E,`utf-8`));D=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 ${E}: ${t}`),D=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:w,frontmatter_local:D},{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}),nl=withValidation(FolderConfigPutRequestSchema,async(e,t,S)=>{try{let e=Jc(S.path,t,`path`,`folder-config-put`);if(!e)return;let w=e.folderRel===``?`**`:`${e.folderRel}/**`,E=applyNestedFolderRulesUpsert({projectDir:e.resolvedContentDir,rules:[{match:w,frontmatter:Zc(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}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:E.applied},{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 il(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 al(e,t){if(e.method===`GET`)return ul(e,t);if(e.method===`PUT`)return dl(e,t);if(e.method===`DELETE`)return fl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let cl=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,ll=e=>{let t=e.match(cl),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}},ul=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!Xc(w,t,`template-get`))return;let E=Jc(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}=ll(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}),dl=withValidation(TemplatePutRequestSchema,async(e,t,S)=>{try{let e=S.name;if(!Xc(e,t,`template-put`))return;let w=Jc(S.folder,t,`folder`,`template-put`);if(!w||il(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:Zc(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`}),fl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!Xc(w,t,`template-delete`))return;let E=Jc(S.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!E||il(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 ml(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 hl(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function gl(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 _l(){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 vl(){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 yl(){let e=`${w}${de??``}`,t=vl(),S=workspaceSearchCaches.get(e);if(S?.fingerprint===t&&S.corpus)return S.corpus;if(S?.fingerprint===t&&S.pending)return S.pending;let E=_l().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 xl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{yl().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}xl();async function Cl(e,t){if(e.method===`GET`)return Tl(e,t);if(e.method===`POST`)return El(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let Tl=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`limit`),E=S.searchParams.get(`query`)??``,D=hl(S.searchParams.get(`intent`)),O=gl(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 yl(),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`?ml(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}),El=withValidation(SearchRequestSchema,async(e,t,S)=>{let w=typeof S.query==`string`?S.query:``,E=hl(S.intent),D=gl(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 yl(),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`?ml(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`}),Dl=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 Ol(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$2.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 kl(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$2.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(!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})}),Ml=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}),Pl=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 Fl(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 Il=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 Fl([`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})}),Ll=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 Fl([`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})}),Rl=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 Fl(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})}),zl={"/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":Kc,"/api/pages":$s,"/api/folder-config":Qc,"/api/template":al,"/api/search":Cl,"/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":jl,"/api/git/branch-info":Ml,"/api/git/checkout":Pl,"/api/share/publish/owners":Il,"/api/share/publish/name-check":Ll,"/api/share/publish":Rl,"/api/principal":Yi,"/api/rescue":Ts,"/api/workspace":Zi,"/api/sync/status":Fc,"/api/sync/trigger":Ic,"/api/sync/conflicts":Lc,"/api/sync/conflict-content":zc,"/api/sync/resolve-conflict":Rc,"/api/sync/abort-merge":Gc,"/api/local-op/clone":sc,"/api/local-op/open":dc,"/api/local-op/auth/login":yc,"/api/local-op/auth/status":Sc,"/api/local-op/auth/repos":wc,"/api/local-op/auth/signout":Dc,"/api/local-op/auth/pat":kc,"/api/local-op/auth/identity":jc,"/api/local-op/auth/set-identity":Pc,"/api/installed-agents":Wc,"/api/spawn-cursor":kl,"/api/handoff":Ol,"/api/install-skill":Uc,"/api/skill/install-state":Dl,"/api/seed/plan":Bc,"/api/seed/apply":Vc,"/api/seed/packs":Hc};F&&(zl[`/api/test-reset`]=qr,zl[`/api/test-rescan-backlinks`]=Jr,zl[`/api/test-rescan-files`]=Yr);let Bl=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`]),Vl=[`/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(Bl.has(S)||Vl.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`:zl[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=zl[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 qc(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$1=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$1.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$1.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$1.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-CjyGVy33-DVACqhWk.mjs`).then(e=>e.n),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)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}default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await D.git.raw([`commit`,`--no-edit`]),log$1.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(`
|
|
@@ -3299,4 +3299,4 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
3299
3299
|
`),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 e=Rt?.pruneFileIndexNowExcluded()??0,t=Rt?.pruneFolderIndexNowExcluded()??0,S=e+t;S>0&&getLogger(`server-factory`).info({pruned:S,prunedFiles:e,prunedFolders:t},`[content-filter] pruned now-excluded entries from file indexes`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] file index prune 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())}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 e=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 t of CONFIG_DOC_NAMES){let S=e.get(t);if(S)try{ee.info({docName:t,path:S},`[config-file-watcher] starting`);let e=await startConfigFileWatcher(S,e=>{let S=_e.documents.get(t);ee.info({docName:t,hasDocument:S!==void 0,contentLength:e.length},`[config-file-watcher] file changed`);let w=applyExternalConfigChange(S??null,t,e,ge.configPersistenceCtx);if(ee.info({docName:t,outcome:w},`[config-file-watcher] applyExternalConfigChange outcome`),t===`__config__/project`||t===`__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:t,cleanup:e}),ee.info({docName:t,path:S},`[config-file-watcher] started`)}catch(e){ee.warn({err:e,docName:t,path:S},`[config-file-watcher] failed to start for ${t}`),Wt.push(`config-file-watcher:${t}`)}}try{let e=resolve(t,`.okignore`),w=resolve(S,`.gitignore`),E=ee;E.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore`);let D=await startMultiPathConfigFileWatcher([e,w],(t,w)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(_e.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,w,ge.configPersistenceCtx);E.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){E.error({err:e,changedPath:relative(S,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let D=await ue.rebuildIgnorePatterns();if(D.ok)E.info({changedPath:relative(S,t),patternCount:D.patternCount,nestedFileCount:D.nestedFileCount,durationMs:D.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ye?.signal(`files`);else{let e=relative(S,t)||`.`;E.warn({changedPath:e,error:D.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ye?.emitConfigIgnoreNestedError(e,D.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(S,t)||`.`},`[ignore-watcher] handler threw`)})});rt.push({docName:`__ignore-files__`,cleanup:D}),E.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 w=resolveGitDir(S),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),de.switchBranch(E);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(`
|
|
3300
3300
|
`))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`)}let D=J?.[0]??`open-knowledge`,O=[`-c`,`credential.helper=!${J&&J.length>1?J.join(` `):D} auth git-credential`];try{Bt=new SyncEngine({projectDir:S,contentDir:t,contentFilter:ue,contentRoot:H,syncEnabled:te(),credentialArgs:O,cc1Broadcaster:ye,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}`)},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-BniQ3qki-DjKtnzVr.mjs`).then(e=>e.a),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=findLegacyRuntimeFiles(B);H.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${H.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let q=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}),{hocuspocus:J,destroy:Y,ready:ee,degraded:te,lockDir:ne,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se}=q,ce=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ue=e.port??0,de=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:E}),fe=k();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:q.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0;if(e.reactShellDistDir)try{acquireUiLock(ne,{port:0,worktreeRoot:e.projectDir??e.contentDir})}catch(e){throw await Y().catch(()=>{}),e}let ge=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,_e=mountMcpAndApi({httpServer:fe,hocuspocus:J,mcpHttpHandler:de,log:E,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:ge}),ve=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ye=null;w!==null&&(ye=attachIdleShutdown({httpServer:fe,thresholdMs:w??DEFAULT_IDLE_THRESHOLD_MS,log:E,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ve()})})),await restoreLifecycleFromConflictsJson({hocuspocus:J,projectDir:e.projectDir??e.contentDir,log:E});try{await new Promise((t,S)=>{let w=e=>S(e);fe.once(`error`,w),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,w),t()})})}catch(t){if(e.reactShellDistDir)try{releaseUiLock(ne)}catch(e){E.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await Y().catch(()=>{}),t}let Ce=fe.address(),we=typeof Ce==`object`&&Ce?Ce.port:e.port??0;if(ue=we,j(ne,we),e.reactShellDistDir&&updateUiLockPort(ne,we),S&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ne,log:E})}catch(e){E.warn({err:e},`spawnUiSiblingFn failed`)}let Te=!1,De=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 ve=async()=>{if(Te)return;Te=!0;let t=[],S=async(e,S)=>{try{await De(e,S)}catch(S){t.push(S),E.warn({err:S,step:e},`bootServer destroy step failed`)}};try{ye?.detach()}catch(e){t.push(e),E.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await S(`mount.shutdown`,()=>_e.shutdown()),await S(`mcpHttpHandler.close`,()=>de.close()),await S(`mount.wss.close`,()=>new Promise((e,t)=>{_e.wss.close(S=>S?t(S):e())})),await S(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await S(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(S=>S&&S.code!==`ERR_SERVER_NOT_RUNNING`?t(S):e())})),await S(`destroyHocuspocus`,()=>Y()),e.reactShellDistDir&&await S(`releaseUiLock`,async()=>releaseUiLock(ne)),await S(`shutdownTelemetry`,()=>shutdownTelemetry()),t.length>0)throw AggregateError(t,`bootServer destroy completed with errors`)},{httpServer:fe,destroy:ve,lockDir:ne,contentDir:e.contentDir,port:we,ready:ee,degraded:te,didAutoInit:F,serverInstance:q}}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(`
|
|
3301
3301
|
`).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 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}}export{assertNeverDiskEvent as $,rewriteWikiLinksForDocumentRename as $n,ALL_EDITOR_IDS as $r,initShadowRepo as $t,MissingOkConfigError as A,url as Ai,readSkillInstallStateSnapshot as An,tracedWriteFile as Ar,createTestLogger as At,STARTER_PACK_IDS as B,releaseUiLock as Bn,writeTargetVersion as Br,formatContributors as Bt,LOG_MD_TEMPLATE as C,array as Ci,parseHocuspocusAuthToken as Cn,tracedMkdir as Cr,createLiveDerivedIndexExtension as Ct,MCP_SERVER_NAME as D,number$1 as Di,readAllTargets as Dn,tracedRmSync as Dr,createServer$1 as Dt,MCP_CONNECTION_ID_HEADER as E,looseObject as Ei,planSeed as En,tracedRenameSync as Er,createPersistenceExtension as Et,SERVICE_WRITER as F,reconcile as Fn,validateCloneInputs as Fr,evictStaleTrackerEntries as Ft,StateManifestError as G,resolveCursorBinaryDefault as Gn,isInitializedNotification as Gr,getLogger as Gt,STATE_MANIFEST_FILENAME as H,resetMetrics as Hn,McpServer as Hr,gcCheckpointRefs as Ht,SKILL_INSTALL_EVENTS_FILE_REL as I,recordContributor as In,validateSkillZip as Ir,extractWikiLinksFromMarkdown as It,acquireUiLock as J,resolvePack as Jn,readConfigSafely as Jr,getTracer as Jt,TagIndex as K,resolveCursorSpawnInvocation as Kn,isJSONRPCRequest as Kr,getMeter as Kt,STARTER_FOLDERS as L,recordSkillInstallEvent as Ln,withSpan as Lr,findEnclosingGitRoot as Lt,PinoLogger as M,NEVER as Mi,readTargetRecordedAt as Mn,updateLastKnownHash as Mr,detectProjectShape as Mt,ProjectGitInitError as N,require_dist$2 as Ni,readTargetVersion as Nn,updateUiLockPort as Nr,ensureProjectGit as Nt,MISSING_OK_CONFIG_MESSAGE as O,object$1 as Oi,readBranchFromHead as On,tracedRmdirSync as Or,createServerObserverExtension as Ot,ROLLBACK_ORIGIN as P,readUiLock as Pn,validateAgentId as Pr,errorResponse as Pt,assertCompatibleStateManifest as Q,rewriteMarkdownLinksForDocumentRename as Qn,MalformedGitPointerError as Qr,incrementServerObserverFire as Qt,STARTER_FOLDER_FRONTMATTER_FILENAME as R,registerAllTools as Rn,withSpanSync as Rr,findEnclosingProjectRoot as Rt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as S,any$1 as Si,parseAuthRejectionWire as Sn,tracedLinkSync as Sr,createExternalChangeHandler as St,MAX_AGENT_SESSIONS as T,literal as Ti,pathToDocName as Tn,tracedRename as Tr,createOsProbe as Tt,SeedPrerequisiteError as U,resolveBundledSkillDir as Un,JSONRPCMessageSchema as Ur,getCurrentMcpLogger as Ut,STARTER_TEMPLATES as V,removeLastKnownHash as Vn,writeTracker as Vr,formatContributorsFrom as Vt,SeedRootDirError as W,resolveContentDir as Wn,LATEST_PROTOCOL_VERSION as Wr,getLocalDir as Wt,applyExternalChange as X,restoreContributors as Xn,writeConfigPatch as Xr,handleSpawnCursor as Xt,applyAgentMarkdownWrite as Y,resolvePackageVersion as Yn,resolveConfigPath as Yr,handleCollabSocketError as Yt,applySeed as Z,restoreLifecycleFromConflictsJson as Zn,GitDirAccessError as Zr,incrementCollabSocketFilteredError as Zt,GIT_UPSTREAM_WRITER as _,CONFIG_SCHEMA_MAJOR_PATH as _i,listStarterPacks as _n,startWatcher as _r,contributorCount as _t,AgentPresenceBroadcaster as a,EXECUTABLE_BLOCKLIST_EXTENSIONS as ai,isAllowedWorkspaceHostHeader as an,safeContentPath as ar,buildSkillZip as at,HocuspocusAuthTokenSchema as b,locateIssue as bi,mountMcpAndApi as bn,toBroadcasterKey as br,createContentFilter as bt,BacklinkIndex as c,ProblemDetailsSchema as ci,isKnownPackId as cn,sanitizeClientName as cr,classifyEvents as ct,CURSOR_BUNDLE_PATHS_BY_PLATFORM as d,colorFromSeed as di,isPathWithinDir as dn,seedBasenameIndex as dr,coercePackId as dt,ASSET_EXTENSIONS as ei,initTelemetry as en,runAuthReposSubprocess as er,attachIdleShutdown as et,ConfigSchema as f,defaultScheduler as fi,isProjectRoot as fn,setActiveSpanAttributes as fr,commitUpstreamImport as ft,FILE_WATCHER_ORIGIN as g,isOrphanMode as gi,listRescueCheckpoints as gn,splitMarkdownBlocks as gr,contentHash as gt,FILE_SYSTEM_WRITER as h,isBranchNotFoundGitError as hi,lastKnownHash as hn,spawnDetached as hr,containsConflictMarkers as ht,AgentFocusBroadcaster as i,EDITOR_LABELS as ii,isAllowedApiOrigin as in,runWithMcpLogger as ir,buildInstructions as it,OBSERVER_SYNC_ORIGIN as j,_coercedNumber as ji,readStateManifest as jn,tracedWriteFileSync as jr,detectClaudeDesktopPresence as jt,McpLogger as k,string$2 as ki,readServerPackageVersion as kn,tracedUnlinkSync as kr,createStreamingErrorWriter as kt,CC1Broadcaster as l,SKILL_STATE_TARGETS as li,isLoopbackAddress as ln,saveInMemoryCheckpoint as lr,classifyFsPath as lt,DEFAULT_PACK_ID as m,iconFromClientName as mi,isSystemDoc as mn,shutdownTelemetry as mr,commitWipFromTree as mt,AGENT_ID_RE as n,DEFAULT_GITHUB_OAUTH_CLIENT_ID as ni,installTestLoggers as nn,runCloneSubprocess as nr,buildAndOpenSkill as nt,AgentSessionCapacityError as o,INLINE_RENDERABLE_EXTENSIONS as oi,isConfigDoc as on,safeSubdir as or,buildStarterFolderFrontmatterYaml as ot,DEFAULT_CHECKPOINT_RETENTION as p,humanFormat as pi,isSelfWrite as pn,shadowGit as pr,commitWip as pt,UiLockCollisionError as q,resolveLockDir as qn,isJSONRPCResultResponse as qr,getMetrics as qt,AGENT_WRITE_ORIGIN as r,DEFAULT_SERVER_HOST as ri,installUserSkill as rn,runDeviceFlowSubprocess as rr,buildExecResult as rt,AgentSessionManager as s,ORPHAN_MODES as si,isHocuspocusAuthRejectionReason as sn,safetyCheckpoint as sr,buildWipTree as st,AGENT_ID_MAX_LEN as t,CC1_CONTRACT_VERSION as ti,installPrettyZodErrors as tn,runAuthStatusSubprocess as tr,bootServer as tt,CONFLICT_MARKER_RE as u,SYSTEM_DOC_NAME as ui,isPairedWriteOrigin as un,saveVersion as ur,clearContributors as ut,HOCUSPOCUS_AUTH_REJECTION_REASONS as v,LOCAL_DIR as vi,loadPrincipal as vn,streamingProblemEvent as vr,createApiExtension as vt,MANAGED_RENAME_ORIGIN as w,boolean$1 as wi,parseKeepaliveConnectionId as wn,tracedMkdirSync as wr,createMcpHttpHandler as wt,INSTALLED_AGENTS_SCHEMES as x,ZodNumber$1 as xi,normalizeFsPath as xn,tracedAppendFileSync as xr,createContentFilterAsync as xt,HocuspocusAuthRejection as y,OK_PROJECT_MARKER as yi,loggerFactory as yn,swapContributors as yr,createAssetServeMiddleware as yt,STARTER_PACKS as z,registerWrite as zn,writeStateManifest as zr,formatAuthRejectionWire as zt};
|
|
3302
|
-
//# sourceMappingURL=dist-
|
|
3302
|
+
//# sourceMappingURL=dist-B5HqGe-T.mjs.map
|