@inkeep/open-knowledge 0.5.0-beta.7 → 0.5.0-beta.8

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.
@@ -799,7 +799,7 @@ ${e.terminator}`}function Qa(e){return`(${Ee(e.body)})${ke(e.redirections)}`}fun
799
799
  `,`
800
800
  `).replaceAll(`\r`,`
801
801
  `).split(`
802
- `))s(S)||collectHrefsFromLine(stripHtmlComments(S,g).replace(/`[^`]*`/g,``),t);return[...t]}function resolveReferencedAssetWithinContentDir(e){let t=decodeHrefPath(e.href);if(!t||isRemoteOrOpaqueHref(t))return null;let s=extname(t).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(s))return null;let g=resolveAssetProjectPath(t,e.fromDocName);if(!g)return null;let S=resolve(e.contentDir,g),w,E;try{if(w=normalize(realpathSync(S)),!isWithinContentDir(w,e.contentDir))return null;E=statSync(w)}catch(t){let s=errnoCode$1(t);return s!==`ENOENT`&&s!==`ENOTDIR`&&console.warn(`[asset-references] unexpected error resolving asset:`,e.href,t),null}return E.isFile()?{absolutePath:w,relativePath:toContentRelativePath(e.contentDir,w),stat:E}:null}function toContentRelativePath(e,t){let s=normalize(realpathSync(e));return normalize(t).slice(s.length+(s.endsWith(sep)?0:1)).split(sep).join(`/`)}function collectReferencedAssets(e){let t;try{t=normalize(realpathSync(e.contentDir))}catch(e){return console.warn(`[asset-references] could not resolve content directory:`,e),[]}let s=new Map;for(let[g,S]of e.fileIndex){let w=e.readMarkdown(S.canonicalPath);if(w!==null)for(let S of extractLocalAssetHrefs(w)){let w=resolveReferencedAssetWithinContentDir({contentDir:t,fromDocName:g,href:S});if(!w||e.isExcluded?.(w.relativePath))continue;let E=mediaKindForAssetPath(w.absolutePath),D=s.get(w.relativePath);if(D){D.referencedBy.includes(g)||D.referencedBy.push(g);continue}s.set(w.relativePath,{kind:`asset`,path:w.relativePath,assetExt:extname(w.relativePath).toLowerCase(),mediaKind:E,size:w.stat.size,modified:w.stat.mtime.toISOString(),referencedBy:[g]})}}return[...s.values()].sort((e,t)=>e.path.localeCompare(t.path))}Object.assign(mimes,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`});function assetContentTypeForPath(e){return mimes[extname(e).slice(1).toLowerCase()]??null}function createAssetServeMiddleware(e){let{contentFilter:t,contentSirv:s,inlineExtensions:g,assetExtensions:S,blocklistExtensions:w}=e;return(e,E,D)=>{let O;try{O=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return D()}let k=extname(O).slice(1).toLowerCase(),j=k===`md`||k===`mdx`;if(!O||t.isPathIgnored(O)||!j&&!S.has(k))return D();E.setHeader(`X-Content-Type-Options`,`nosniff`),j||(g.has(k)?E.setHeader(`Content-Disposition`,`inline`):E.setHeader(`Content-Disposition`,`attachment`)),k===`svg`&&E.setHeader(`Content-Security-Policy`,`sandbox; default-src 'none'; style-src 'unsafe-inline'`),s(e,E,()=>{if(!E.headersSent){if(S.has(k)||w.has(k)){E.statusCode=404,E.end();return}D()}})}}function resolveContentDir(e,t){return resolve(t,e.content.dir)}function getLocalDir(e){return resolve(e,`.ok`,LOCAL_DIR)}function resolveLockDir(e){return getLocalDir(e)}function resolveWithinRoot(e,t){if(typeof e!=`string`||!isAbsolute(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let s=resolve(e),g=resolve(s,t),S=relative(s,g);return S===``?{ok:!0,abs:g,rel:``}:S===`..`||S.startsWith(`../`)||isAbsolute(S)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:g,rel:S}}const ROUTED_CWD_DESCRIPTION="Absolute host path inside the target Open Knowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).",summaryArgSchema=string().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`);function textResult(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}function textPlusStructured(e,t,s){return{content:[{type:`text`,text:e}],structuredContent:t,...s?{isError:!0}:{}}}const HOCUSPOCUS_NOT_RUNNING_ERROR="Error: Hocuspocus server is not running. Start it with `open-knowledge start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.",ROLE_LABEL={ingest:`raw-sources layer (preserve external material, no analysis)`,research:`wiki layer, provisional (synthesize findings that can still change)`,consolidate:`wiki layer, canonical (promote stabilized research to source-of-truth)`},ROLE_BEFORE={ingest:"user shares a URL or file they want preserved, or `research` needs raw sources",research:"`ingest` has captured the relevant sources (or the user points at one)",consolidate:"`research` has produced a provisional article AND a decision has actually been made"},ROLE_AFTER={ingest:"often `research` on the same topic — or just stop; raw preservation is frequently enough on its own",research:"usually stop (research lives as provisional indefinitely) or `consolidate` once a decision lands",consolidate:"update 2–3 neighbor docs to link the new canonical article; research articles it supersedes gain a `superseded_by` pointer"};function buildWorkflowFrame(e){return`## Where this fits
802
+ `))s(S)||collectHrefsFromLine(stripHtmlComments(S,g).replace(/`[^`]*`/g,``),t);return[...t]}function resolveReferencedAssetWithinContentDir(e){let t=decodeHrefPath(e.href);if(!t||isRemoteOrOpaqueHref(t))return null;let s=extname(t).slice(1).toLowerCase();if(!ASSET_EXTENSIONS.has(s))return null;let g=resolveAssetProjectPath(t,e.fromDocName);if(!g)return null;let S=resolve(e.contentDir,g),w,E;try{if(w=normalize(realpathSync(S)),!isWithinContentDir(w,e.contentDir))return null;E=statSync(w)}catch(t){let s=errnoCode$1(t);return s!==`ENOENT`&&s!==`ENOTDIR`&&console.warn(`[asset-references] unexpected error resolving asset:`,e.href,t),null}return E.isFile()?{absolutePath:w,relativePath:toContentRelativePath(e.contentDir,w),stat:E}:null}function toContentRelativePath(e,t){let s=normalize(realpathSync(e));return normalize(t).slice(s.length+(s.endsWith(sep)?0:1)).split(sep).join(`/`)}function collectReferencedAssets(e){let t;try{t=normalize(realpathSync(e.contentDir))}catch(e){return console.warn(`[asset-references] could not resolve content directory:`,e),[]}let s=new Map;for(let[g,S]of e.fileIndex){let w=e.readMarkdown(S.canonicalPath);if(w!==null)for(let S of extractLocalAssetHrefs(w)){let w=resolveReferencedAssetWithinContentDir({contentDir:t,fromDocName:g,href:S});if(!w||e.isExcluded?.(w.relativePath))continue;let E=mediaKindForAssetPath(w.absolutePath),D=s.get(w.relativePath);if(D){D.referencedBy.includes(g)||D.referencedBy.push(g);continue}s.set(w.relativePath,{kind:`asset`,path:w.relativePath,assetExt:extname(w.relativePath).toLowerCase(),mediaKind:E,size:w.stat.size,modified:w.stat.mtime.toISOString(),referencedBy:[g]})}}return[...s.values()].sort((e,t)=>e.path.localeCompare(t.path))}Object.assign(mimes,{m4v:`video/mp4`,mkv:`video/x-matroska`,flac:`audio/flac`});function assetContentTypeForPath(e){return mimes[extname(e).slice(1).toLowerCase()]??null}function createAssetServeMiddleware(e){let{contentFilter:t,contentSirv:s,inlineExtensions:g,assetExtensions:S,blocklistExtensions:w}=e;return(e,E,D)=>{let O;try{O=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return D()}let k=extname(O).slice(1).toLowerCase(),j=k===`md`||k===`mdx`;if(!O||t.isPathIgnored(O)||!j&&!S.has(k))return D();E.setHeader(`X-Content-Type-Options`,`nosniff`),j||(g.has(k)?E.setHeader(`Content-Disposition`,`inline`):E.setHeader(`Content-Disposition`,`attachment`)),k===`svg`&&E.setHeader(`Content-Security-Policy`,`sandbox; default-src 'none'; style-src 'unsafe-inline'`),s(e,E,()=>{if(!E.headersSent){if(S.has(k)||w.has(k)){E.statusCode=404,E.end();return}D()}})}}function resolveContentDir(e,t){return resolve(t,e.content.dir)}function getLocalDir(e){return resolve(e,`.ok`,LOCAL_DIR)}function resolveLockDir(e){return getLocalDir(e)}function resolveWithinRoot(e,t){if(typeof e!=`string`||!isAbsolute(e))return{ok:!1,reason:`root path is not absolute: ${String(e)}`};if(typeof t!=`string`)return{ok:!1,reason:`path must be a string`};if(t.includes(`\0`))return{ok:!1,reason:`path contains a NUL byte`};let s=resolve(e),g=resolve(s,t),S=relative(s,g);return S===``?{ok:!0,abs:g,rel:``}:S===`..`||S.startsWith(`../`)||isAbsolute(S)?{ok:!1,reason:`path "${t}" escapes the configured root`}:{ok:!0,abs:g,rel:S}}const ROUTED_CWD_DESCRIPTION="Absolute host path inside the target Open Knowledge project. Required when the MCP server is registered globally (e.g. `npx @inkeep/open-knowledge mcp` once at the host level, routing per call), unless the MCP client advertises exactly one root via the `roots` capability — that single root is then used as the implicit `cwd`. Optional when the server is anchored to a single project (the per-project HTTP MCP server defaults to its configured project root).",summaryArgSchema=string().max(200).optional().describe(`Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline.`);function textResult(e,t){return{content:[{type:`text`,text:e}],...t?{isError:!0}:{}}}function textPlusStructured(e,t,s){let g={_text:e,...t};return{content:[{type:`text`,text:e}],structuredContent:g,...s?{isError:!0}:{}}}const HOCUSPOCUS_NOT_RUNNING_ERROR="Error: Hocuspocus server is not running. Start it with `open-knowledge start`, then retry.\nFor disk-only writes without real-time sync, use your native Edit tool directly.",ROLE_LABEL={ingest:`raw-sources layer (preserve external material, no analysis)`,research:`wiki layer, provisional (synthesize findings that can still change)`,consolidate:`wiki layer, canonical (promote stabilized research to source-of-truth)`},ROLE_BEFORE={ingest:"user shares a URL or file they want preserved, or `research` needs raw sources",research:"`ingest` has captured the relevant sources (or the user points at one)",consolidate:"`research` has produced a provisional article AND a decision has actually been made"},ROLE_AFTER={ingest:"often `research` on the same topic — or just stop; raw preservation is frequently enough on its own",research:"usually stop (research lives as provisional indefinitely) or `consolidate` once a decision lands",consolidate:"update 2–3 neighbor docs to link the new canonical article; research articles it supersedes gain a `superseded_by` pointer"};function buildWorkflowFrame(e){return`## Where this fits
803
803
 
804
804
  Open Knowledge accretes a persistent wiki through three workflow tools, mapped to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f):
805
805
 
@@ -816,7 +816,7 @@ Open Knowledge accretes a persistent wiki through three workflow tools, mapped t
816
816
 
817
817
  Karpathy's insight: "The tedious part of maintaining a knowledge base is not the reading or the thinking — it's the bookkeeping." Humans abandon wikis because maintenance costs exceed perceived value. These tools exist so an agent can do the bookkeeping (fetching, summarizing, cross-linking, superseding) without fatigue. Follow the steps below faithfully — skipping the cross-linking, supersedes chains, or raw-source preservation is what turns a useful wiki back into an abandoned one.
818
818
 
819
- `}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 g;try{g=await e(s)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}try{let e=await resolveConfig(t,g);return{ok:!0,cwd:g,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function resolveProjectServerContext(e,t,s,g){let S=await resolveProjectConfigContext(e,t,g);if(!S.ok)return S;let{cwd:w,config:E}=S;try{return{ok:!0,cwd:w,config:E,url:await resolveServerUrl(s,w)}}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:g,instance:S,detail:w,...E}=s;return{...E,ok:!1,error:t,type:e,...typeof g==`number`?{status:g}:{},...typeof S==`string`?{instance:S}:{},...typeof w==`string`?{detail:w}:{}}}let{ok:g,error:S,...w}=s,E=typeof S==`string`?S:typeof s.message==`string`?s.message:`Server returned HTTP ${e.status}`;return{...w,ok:!1,error:E}}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 g;try{g=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,g)}async function httpPost(e,t,s){let g;if(s!==void 0)try{g=JSON.stringify(s)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}let S;try{S=await fetch(`${e}${t}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:g,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)}function parseRenameCollidingPairs(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:s,to:g}=e;return typeof t==`string`&&typeof s==`string`&&typeof g==`string`?[{existing:t,incoming:s,to:g}]:[]}):[]}function mergeCascade(e,t){let s={...e},g=new Map;for(let[e,S]of Object.entries(t))if(S!==void 0)if(Array.isArray(S)){let t=Array.isArray(s[e])?[...s[e]]:[],w=g.get(e)??new Set(t.map(toDedupKey));g.set(e,w);for(let e of S){let s=toDedupKey(e);w.has(s)||(w.add(s),t.push(e))}s[e]=t}else s[e]=S;return s}function mergePatch(e,t){let s={...e};for(let[e,g]of Object.entries(t))if(g!==void 0){if(isEmpty$1(g)){delete s[e];continue}s[e]=g}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(/\/+$/,``),g=s===``||s===`.`?[]:s.split(`/`).filter(e=>e.length>0),S={},w={},E=!1;for(let t=0;t<=g.length;t++){let s=t===0?``:g.slice(0,t).join(`/`),D=t===0?resolve(e,`.ok`,`frontmatter.yml`):resolve(e,s,`.ok`,`frontmatter.yml`);if(!existsSync(D))continue;let O=readFrontmatterYaml(D);if(O!=null){S=mergeCascade(S,O);for(let e of Object.keys(O))O[e]!==void 0&&(w[e]=s);E=!0}}return E?{merged:coerceWellKnown(S),sources:w}:{merged:{},sources:{}}}function coerceWellKnown(e){let t={};for(let[s,g]of Object.entries(e))t[s]=g;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 g=openProjectGit(e),S=``;try{S=await g.raw(`log`,`-${Math.max(1,s)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let w=[];for(let e of S.split(`
819
+ `}function buildWorkflowHandler(e,t,s,g){return async S=>{let w=typeof S.cwd==`string`?S.cwd:void 0,E=await resolveProjectConfigContext(t.resolveCwd,t.config,w);if(!E.ok)return textResult(`Error: ${E.error}`,!0);let D=S[s],O=typeof D==`string`?D:``;return textPlusStructured(`${buildWorkflowFrame(e)}${g(O,E.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 g;try{g=await e(s)}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}try{let e=await resolveConfig(t,g);return{ok:!0,cwd:g,config:e}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function resolveProjectServerContext(e,t,s,g){let S=await resolveProjectConfigContext(e,t,g);if(!S.ok)return S;let{cwd:w,config:E}=S;try{return{ok:!0,cwd:w,config:E,url:await resolveServerUrl(s,w)}}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:g,instance:S,detail:w,...E}=s;return{...E,ok:!1,error:t,type:e,...typeof g==`number`?{status:g}:{},...typeof S==`string`?{instance:S}:{},...typeof w==`string`?{detail:w}:{}}}let{ok:g,error:S,...w}=s,E=typeof S==`string`?S:typeof s.message==`string`?s.message:`Server returned HTTP ${e.status}`;return{...w,ok:!1,error:E}}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 g;try{g=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,g)}async function httpPost(e,t,s){let g;if(s!==void 0)try{g=JSON.stringify(s)}catch(e){return{ok:!1,error:`Request body is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`}}let S;try{S=await fetch(`${e}${t}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:g,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)}function parseRenameCollidingPairs(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{existing:t,incoming:s,to:g}=e;return typeof t==`string`&&typeof s==`string`&&typeof g==`string`?[{existing:t,incoming:s,to:g}]:[]}):[]}function mergeCascade(e,t){let s={...e},g=new Map;for(let[e,S]of Object.entries(t))if(S!==void 0)if(Array.isArray(S)){let t=Array.isArray(s[e])?[...s[e]]:[],w=g.get(e)??new Set(t.map(toDedupKey));g.set(e,w);for(let e of S){let s=toDedupKey(e);w.has(s)||(w.add(s),t.push(e))}s[e]=t}else s[e]=S;return s}function mergePatch(e,t){let s={...e};for(let[e,g]of Object.entries(t))if(g!==void 0){if(isEmpty$1(g)){delete s[e];continue}s[e]=g}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(/\/+$/,``),g=s===``||s===`.`?[]:s.split(`/`).filter(e=>e.length>0),S={},w={},E=!1;for(let t=0;t<=g.length;t++){let s=t===0?``:g.slice(0,t).join(`/`),D=t===0?resolve(e,`.ok`,`frontmatter.yml`):resolve(e,s,`.ok`,`frontmatter.yml`);if(!existsSync(D))continue;let O=readFrontmatterYaml(D);if(O!=null){S=mergeCascade(S,O);for(let e of Object.keys(O))O[e]!==void 0&&(w[e]=s);E=!0}}return E?{merged:coerceWellKnown(S),sources:w}:{merged:{},sources:{}}}function coerceWellKnown(e){let t={};for(let[s,g]of Object.entries(e))t[s]=g;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 g=openProjectGit(e),S=``;try{S=await g.raw(`log`,`-${Math.max(1,s)}`,`--format=%H|%aI|%an|%s`,`--follow`,`--`,t)}catch{return{commits:[],source:`git`}}let w=[];for(let e of S.split(`
820
820
  `)){if(!e)continue;let t=e.indexOf(`|`);if(t<0)continue;let s=e.indexOf(`|`,t+1);if(s<0)continue;let g=e.indexOf(`|`,s+1);g<0||w.push({hash:e.slice(0,t),date:e.slice(t+1,s),authorName:e.slice(s+1,g),subject:e.slice(g+1)})}return{commits:w,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,g,S){let w=``;try{w=await e.raw(`log`,t,`-${Math.max(1,S*2)}`,`--format=%H%x00%aI%x00%an%x00%s%x00%B%x1e`,`--`,s)}catch{return[]}let E=writerIdFromRef(t,g),D=parseWriterId(E),O=[];for(let e of w.split(``)){let t=e.trimStart();if(!t)continue;let[s=``,S=``,w=``,k=``,j=``]=t.split(`\0`),F=s.trim();F.length===40&&O.push({hash:F,date:S,writerName:w,message:k,contributors:readContributors(j),writerId:E,isAgent:D.isAgent,writerClassification:D.classification,branch:g})}return O}async function readShadowLog(e,t,s=5){let g=getShadowRepoPath(e);if(!g)return{commits:[],source:`shadow-repo-absent`};let S=await currentProjectBranch(e);if(!S)return{commits:[],source:`shadow-repo`};let w=openShadowGit(g,resolve(e)),E=``;try{E=await w.raw(`for-each-ref`,getWipRefPattern(S),`--format=%(refname)`)}catch{return{commits:[],source:`shadow-repo`}}let D=E.split(`
821
821
  `).map(e=>e.trim()).filter(Boolean);return D.length===0?{commits:[],source:`shadow-repo`}:{commits:(await Promise.all(D.map(e=>logOnRef(w,e,t,S,s)))).flat().sort((e,t)=>t.date.localeCompare(e.date)).slice(0,s),source:`shadow-repo`}}const defaultProvider=()=>{try{return homedir()}catch{return null}};let userHomeProvider=defaultProvider;const USER_TEMPLATES_SOURCE_LABEL=`~/.ok`;function getUserHome(){return userHomeProvider()}function getUserTemplatesDir(){let e=userHomeProvider();return e?join(e,`.ok`,`templates`):null}function resolveTemplatesAvailable(e,t,s={}){let g=normalizeFolderPath(t),S=g===``?[]:g.split(`/`),w=new Set,E=[];collectFromFolder(e,g,`local`,w,E);for(let t=S.length-1;t>=1;t--)collectFromFolder(e,S.slice(0,t).join(`/`),`inherited`,w,E);return S.length>0&&collectFromFolder(e,``,`inherited`,w,E),collectUserTemplates(w,E),E}function collectUserTemplates(e,t){let s=getUserTemplatesDir();if(!s||!existsSync(s))return;let g;try{g=readdirSync(s)}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[ok-templates] failed to read user templates directory at ${s}: ${t}`);return}for(let S of g){if(!S.endsWith(`.md`))continue;let g=S.slice(0,-3);if(e.has(g))continue;let w=join(s,S),E;try{E=statSync(w)}catch{continue}if(!E.isFile())continue;let D=readTemplateMeta(w),O={name:g,path:w.split(/\\/g).join(`/`),source_folder:USER_TEMPLATES_SOURCE_LABEL,scope:`user`};D.title!==void 0&&(O.title=D.title),D.description!==void 0&&(O.description=D.description),e.add(g),t.push(O)}}function collectFromFolder(e,t,s,g,S){let w=t?join(e,t,`.ok`,`templates`):join(e,`.ok`,`templates`);if(!existsSync(w))return;let E;try{E=readdirSync(w)}catch{return}for(let e of E){if(!e.endsWith(`.md`))continue;let E=e.slice(0,-3);if(g.has(E))continue;let D=join(w,e),O;try{O=statSync(D)}catch{continue}if(!O.isFile())continue;let k=readTemplateMeta(D),j={name:E,path:t?posix.join(t,`.ok`,`templates`,e):posix.join(`.ok`,`templates`,e),source_folder:t,scope:s};k.title!==void 0&&(j.title=k.title),k.description!==void 0&&(j.description=k.description),g.add(E),S.push(j)}}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 g;try{g=(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 g!=`object`||!g)return{};let S=g,w={};return typeof S.title==`string`&&(w.title=S.title),typeof S.description==`string`&&(w.description=S.description),w}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 g=s.backlinks??s.results??s.links;if(!Array.isArray(g))return[];let S=[];for(let e of g){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&&S.push({source:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}const BACKLINK_COUNT_CHUNK=100;async function fetchBacklinkCountsBatch(e,t){if(!e||t.length===0)return null;let s=[...new Set(t)],g=[];for(let e=0;e<s.length;e+=BACKLINK_COUNT_CHUNK)g.push(s.slice(e,e+BACKLINK_COUNT_CHUNK));let S=await Promise.all(g.map(async t=>{let s=await httpGet(e,`/api/backlink-counts?docNames=${encodeURIComponent(t.join(`,`))}`);return s.ok?s.counts??{}:null})),w=new Map,E=!1;for(let e of S)if(e){E=!0;for(let[t,s]of Object.entries(e))typeof s==`number`&&Number.isFinite(s)&&w.set(t,s)}return E?w: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 g=s.forwardLinks??s.links??s.results;if(!Array.isArray(g))return[];let S=[];for(let e of g){if(typeof e!=`object`||!e)continue;let t=e;if(t.kind===`external`&&typeof t.url==`string`){S.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&&S.push({kind:`doc`,docName:s,title:typeof t.title==`string`?t.title:void 0,snippet:typeof t.snippet==`string`?t.snippet:null})}return S}function mergeFileAndFolder(e,t,s){let g=mergeCascade(s?resolveNestedFrontmatter(s,parentFolderOf(t)):{},e??{});return{title:typeof g.title==`string`?g.title:void 0,description:typeof g.description==`string`?g.description:void 0,tags:Array.isArray(g.tags)?g.tags.filter(e=>typeof e==`string`):[],frontmatter:g}}async function enrichPath(e,t,s={}){let g=resolveWithinRoot(t.projectDir,e);if(!g.ok)throw Error(`enrichPath: ${g.reason}`);let S=g.rel,w=g.abs,E=t.historyDepth??5,D=s.includeRichFields===!0,O=readFrontmatter(w);if(!D){let e=mergeFileAndFolder(await O,S,t.projectDir);return{path:S,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[k,j,F,L,B]=await Promise.all([O,fetchBacklinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),fetchForwardLinks(t.serverUrl,pathToDocName$1(S)).catch(()=>null),readShadowLog(t.projectDir,S,E).catch(()=>({commits:[],source:`shadow-repo`})),readProjectGitLog(t.projectDir,S,E).catch(()=>({commits:[],source:`git`}))]),H=mergeFileAndFolder(k,S,t.projectDir);return{path:S,title:H.title,description:H.description,tags:H.tags,frontmatter:H.frontmatter,backlinkCount:j?.length??null,backlinks:j,forwardLinkCount:F?.length??null,forwardLinks:F,history:L.commits,historySource:L.source,projectHistory:B.commits,projectHistorySource:B.source}}async function scanDirectory(e,t){let s={directMdCount:0,recursiveMdCount:0,childDirCount:0,mostRecent:null,truncated:!1},g=0,S=[{path:e,depth:0}];for(;S.length>0;){let e=S.shift();if(!e)break;if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}let w;try{w=await readdir(e.path,{withFileTypes:!0})}catch{continue}for(let E of w){if(g>=DIRECTORY_SCAN_CAP){s.truncated=!0;break}g++;let w=E.name;if(E.isDirectory()){if(DIR_SKIP.has(w)||w.startsWith(`.`))continue;e.depth===0&&s.childDirCount++,S.push({path:`${e.path}/${w}`,depth:e.depth+1})}else if(E.isFile()&&WIKI_EXT_RE.test(w)){s.recursiveMdCount++,e.depth===0&&s.directMdCount++;let g=`${e.path}/${w}`;try{let e=await stat$1(g);(!s.mostRecent||e.mtimeMs>s.mostRecent.mtimeMs)&&(s.mostRecent={absPath:g,relPath:relative(t,g).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 g=s.rel,S=s.abs,w=await scanDirectory(S,t.projectDir),E;if(w.mostRecent){let e=await readFrontmatter(w.mostRecent.absPath),t=typeof e?.title==`string`?e.title:void 0;E={path:w.mostRecent.relPath,title:t??basename(w.mostRecent.relPath),updatedAt:new Date(w.mostRecent.mtimeMs).toISOString()}}let D={path:g,type:`directory`,directMdCount:w.directMdCount,recursiveMdCount:w.recursiveMdCount,childDirCount:w.childDirCount,mostRecentMd:E,truncated:w.truncated},O=resolveNestedFrontmatter(t.projectDir,g),k=O.title,j=O.description,F=O.tags??[];k!==void 0&&(D.title=k),j!==void 0&&(D.description=j),F.length>0&&(D.tags=F),Object.keys(O).length>0&&(D.frontmatter_defaults=O);let L=resolveTemplatesAvailable(t.projectDir,g);return L.length>0&&(D.templates_available=L),D}async function enrichDirectoryRecursive(e,t,s){let g=await enrichDirectory(e,s);if(t<=1)return g;let S=g.path,w=resolve(s.projectDir,S),E;try{E=await readdir(w,{withFileTypes:!0})}catch{return g}let D=[];for(let e of E){if(!e.isDirectory()||RECURSIVE_LISTING_SKIP_DIRS.has(e.name)||e.name.startsWith(`.`))continue;let g=await enrichDirectoryRecursive(S?`${S}/${e.name}`:e.name,t-1,s);D.push(g)}return D.length>0&&(g.subfolders=D),g}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 g=resolveTargetFolderFromMatch(s.new_match??s.match);if(!g.ok)return{ok:!1,error:{code:`MULTI_FOLDER_GLOB`,message:g.message,rule:s.match}};let S=g.folder?resolve(e.projectDir,g.folder):e.projectDir,w=resolve(e.projectDir);if(!S.startsWith(w+sep)&&S!==w)return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved target folder escapes projectDir: ${S}`,rule:s.match}};let E=null,D=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(E=t.folder,D=t.folder?resolve(e.projectDir,t.folder):e.projectDir,!D.startsWith(w+sep)&&D!==w)return{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved source folder escapes projectDir: ${D}`,rule:s.match}}}t.push({targetFolder:g.folder,targetAbs:S,sourceFolder:E,sourceAbs:D,rule:s})}let s=[];for(let g of t)try{if(g.sourceAbs&&g.sourceAbs!==g.targetAbs){let t=join(g.sourceAbs,`.ok`,`frontmatter.yml`);existsSync(t)&&(unlinkSync(t),autoCleanOkDir(join(g.sourceAbs,`.ok`)),s.push({match:g.rule.match,path:relPathOf$1(e.projectDir,t),action:`deleted`}))}let t=join(g.targetAbs,`.ok`),S=join(t,`frontmatter.yml`),w=readExistingFrontmatter(S),E=Object.keys(g.rule.frontmatter).length===0?{}:mergePatch(w,g.rule.frontmatter);if(Object.keys(E).length===0){existsSync(S)&&(unlinkSync(S),autoCleanOkDir(t),s.push({match:g.rule.new_match??g.rule.match,path:relPathOf$1(e.projectDir,S),action:`deleted`}));continue}mkdirSync(t,{recursive:!0});let D=(0,import_dist$1.stringify)(E),O=`${S}.tmp.${process.pid}.${Date.now()}`;writeFileSync(O,D,`utf-8`),renameSync(O,S),s.push({match:g.rule.new_match??g.rule.match,path:relPathOf$1(e.projectDir,S),action:`written`})}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write nested frontmatter for ${g.rule.match}: ${e.message}`,rule:g.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=[],g=!1;for(let S of t){let t=/[*?[\]{}]/.test(S);if(g&&!t)return{ok:!1,message:`Glob "${e}" matches multiple folders (literal segment "${S}" appears after a glob). Split it into one rule per folder, e.g. set_folder_rule({ rules: [{ match: "specs/foo/${S}/**", ... }, ...] }).`};if(t){if(g=!0,S!==`**`&&S!==`*`)return{ok:!1,message:`Glob "${e}" uses an unsupported pattern segment "${S}". Only "*" and "**" are supported in nested folder rules.`};continue}s.push(S)}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 g=s.trim();return isAllowedToken(g)?t[g]: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=e.target??`project`,s=resolveRootForTarget(t,e.projectDir);if(!s.ok)return{ok:!1,error:s.error};let g=t===`user`?``:e.folder,S=validateInputs(s.rootDir,g,e.name);if(!S.ok)return{ok:!1,error:S.error};let w=validateTitle(e.frontmatter.title);if(!w.ok)return{ok:!1,error:w.error};let E=validateSubstitutionAllowlist(e.body);if(!E.ok)return{ok:!1,error:E.error};let{templatesDir:D,filePath:O}=templatePaths(s.rootDir,S.folderRel,e.name),k=serializeFrontmatter(e.frontmatter),j=k?`---\n${k}---\n${e.body}`:e.body;try{mkdirSync(D,{recursive:!0})}catch(e){return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to create template directory at ${displayPath(t,s.rootDir,D)}: ${e.message}`}}}let F=!existsSync(O),L=`${O}.tmp.${process.pid}.${Date.now()}`;try{writeFileSync(L,j,`utf-8`),renameSync(L,O)}catch(e){try{unlinkSync(L)}catch{}return{ok:!1,error:{code:`WRITE_ERROR`,message:`Failed to write template at ${displayPath(t,s.rootDir,O)}: ${e.message}`}}}let B=[];return(e.frontmatter.description===void 0||typeof e.frontmatter.description!=`string`||e.frontmatter.description.length===0)&&B.push("Template frontmatter.description is missing — `description` disambiguates between similarly-named templates in the menu. Recommended but not required."),{ok:!0,path:displayPath(t,s.rootDir,O),created:F,warnings:B}}function applyTemplateDelete(e){let t=e.target??`project`,s=resolveRootForTarget(t,e.projectDir);if(!s.ok)return{ok:!1,error:s.error};let g=t===`user`?``:e.folder,S=validateInputs(s.rootDir,g,e.name);if(!S.ok)return{ok:!1,error:S.error};let{templatesDir:w,okDir:E,filePath:D}=templatePaths(s.rootDir,S.folderRel,e.name),O=existsSync(D);if(O)try{unlinkSync(D)}catch(e){return{ok:!1,error:{code:`UNLINK_FAILED`,message:`Failed to delete template at ${displayPath(t,s.rootDir,D)}: ${e.message}`}}}let k=!1,j=!1;if(existsSync(w)&&isEmpty(w))try{rmdirSync(w),k=!0}catch{}if(existsSync(E)&&isEmpty(E))try{rmdirSync(E),j=!0}catch{}return{ok:!0,path:displayPath(t,s.rootDir,D),existed:O,cleanedEmpty:{templatesDir:k,okDir:j}}}function resolveRootForTarget(e,t){if(e===`user`){let e=getUserHome();return e?{ok:!0,rootDir:e}:{ok:!1,error:{code:`USER_HOME_UNAVAILABLE`,message:`User home directory could not be resolved. User templates require a writable home directory at ~/.ok/templates/.`}}}return{ok:!0,rootDir:t}}function displayPath(e,t,s){return e===`user`?s.startsWith(t+sep)?`~/${s.slice(t.length+1).split(sep).join(`/`)}`:s.split(sep).join(`/`):relPathOf(t,s)}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 g=t.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``).replace(/^\.$/,``);if(g.includes(`..`))return{ok:!1,error:{code:`PATH_TRAVERSAL`,message:`Folder path may not contain "..": ${JSON.stringify(t)}`}};let S=g?resolve(e,g):e,w=resolve(e);return!S.startsWith(w+sep)&&S!==w?{ok:!1,error:{code:`PATH_ESCAPE`,message:`Resolved folder path escapes projectDir: ${S}`}}:{ok:!0,folderRel:g}}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 g=t?join(e,t,`.ok`):join(e,`.ok`),S=join(g,`templates`);return{okDir:g,templatesDir:S,filePath:join(S,`${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$6=()=>getLogger(`http`);let _apiErrorCounter=null;function apiErrorCounter(){return _apiErrorCounter||=getMeter().createCounter(`ok.api.error.count`,{description:`API error responses by problem type and handler`,unit:`1`}),_apiErrorCounter}function errorResponse(e,t,s,g,S={}){let w=S.instance??`urn:uuid:${randomUUID()}`;if(e.headersSent||e.writableEnded||e.destroyed){log$6().error({event:`api.error.double-write`,instance:w,type:s,status:t,handler:S.handler},`errorResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}});return}let E={type:s,title:g,status:t,instance:w,detail:S.detail??void 0},D=ProblemDetailsSchema.safeParse(E);if(!D.success){log$6().error({event:`api.error.malformed-envelope`,issues:D.error.issues,body:E,handler:S.handler,originalStatus:t},`errorResponse produced an invalid ProblemDetails body — emitting fallback`);let s=500;apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:w}));return}let O=S.extensions?{...S.extensions,...E}:E;apiErrorCounter().add(1,{type:s,...S.handler?{handler:S.handler}:{}});let k=t>=500?`error`:`warn`;log$6()[k]({event:`api.error`,instance:w,type:s,status:t,handler:S.handler,detail:S.detail,err:S.cause},g);let j;try{j=JSON.stringify(O)}catch(s){log$6().error({event:`api.error.unserializable-body`,bodyKeys:Object.keys(O),handler:S.handler,originalStatus:t,instance:w,err:s},`errorResponse wireBody is not JSON-serializable — emitting hardcoded fallback`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:w}));return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`}),e.end(j)}function streamingProblemEvent(e,t,s,g={}){let S=g.instance??`urn:uuid:${randomUUID()}`,w={type:`error`,problem:{type:t,title:s,status:e,instance:S,detail:g.detail??void 0}},E=StreamingProblemEventSchema.safeParse(w);if(!E.success){log$6().error({event:`api.streaming.malformed-envelope`,issues:E.error.issues,body:w,handler:g.handler,originalStatus:e},`streamingProblemEvent produced an invalid StreamingProblemEvent — returning fallback`);let t=500;return apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...g.handler?{handler:g.handler}:{}}),{type:`error`,problem:{type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:S}}}apiErrorCounter().add(1,{type:t,...g.handler?{handler:g.handler}:{}});let D=e>=500?`error`:`warn`;return log$6()[D]({event:`api.streaming.error`,instance:S,type:t,status:e,handler:g.handler,detail:g.detail,err:g.cause},s),w}function createStreamingErrorWriter(e,t){return(s,g,S,w={})=>{if(e.writableEnded||e.destroyed){log$6().error({event:`api.streaming.error.suppressed`,type:g,status:s,handler:t,detail:w.detail,err:w.cause},`createStreamingErrorWriter called after writableEnded/destroyed — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...t?{handler:t}:{}});return}let E=streamingProblemEvent(s,g,S,{handler:t,...w});try{e.write(`${JSON.stringify(E)}\n`)}catch(e){log$6().error({event:`api.streaming.error.write-failed`,type:g,status:s,handler:t,err:w.cause,writeErr:e},`createStreamingErrorWriter: res.write threw — original error preserved in log`)}}}const log$5=()=>getLogger(`http`);function successResponse(e,t,s,g,S={}){if(e.headersSent||e.writableEnded||e.destroyed){log$5().error({event:`api.success.double-write`,status:t,handler:S.handler},`successResponse called after headers already sent — suppressed`),apiErrorCounter().add(1,{type:`urn:ok:error:internal-server-error`,...S.handler?{handler:S.handler}:{}});return}let w=s.safeParse(g);if(!w.success){log$5().error({event:`api.success.malformed-body`,issues:w.error.issues,bodyKeys:typeof g==`object`&&g?Object.keys(g):null,handler:S.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:S.handler});return}let E;try{E=JSON.stringify(w.data)}catch(s){log$5().error({event:`api.success.unserializable-body`,bodyKeys:typeof w.data==`object`&&w.data!==null?Object.keys(w.data):null,handler:S.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:S.handler});return}e.writeHead(t,{...S.extraHeaders,"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(E)}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,g=e.ttlMs??6e4;async function S(S){let w=t.get(S);if(w?.status===`resolved`&&w.expiresAt>s())return w.installed;if(w?.status===`inflight`)return w.promise;let E=(async()=>{try{let w=await e.probe(S);return t.set(S,{status:`resolved`,installed:w,expiresAt:s()+g}),w}catch{return t.set(S,{status:`resolved`,installed:!1,expiresAt:s()+g}),!1}})();return t.set(S,{status:`inflight`,promise:E}),E}async function w(){let e=await Promise.all(INSTALLED_AGENTS_SCHEMES.map(async e=>[e,await S(e)]));return Object.fromEntries(e)}return{probeAll:w,probeWithCache:S}}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,await s(),{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 g(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 g(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=[],g=0,S=AbortSignal.timeout(t.timeoutMs),w=()=>e.destroy(new RequestBodyTimeoutError(t.timeoutMs));S.addEventListener(`abort`,w,{once:!0});try{for await(let S of e){if(g+=S.length,g>t.maxBytes)throw new PayloadTooLargeError(t.maxBytes);s.push(S)}return Buffer.concat(s)}finally{S.removeEventListener(`abort`,w)}}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,g={}){let S=e.safeParse(t);if(S.success)return{ok:!0,value:S.data};let w=S.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `);return errorResponse(s,400,`urn:ok:error:invalid-request`,`Request body is invalid.`,{handler:g.handler,detail:w}),{ok:!1}}function withValidation(e,t,s={}){return async(g,S)=>{if(s.method!==void 0&&g.method!==s.method){errorResponse(S,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(g,S)){!S.headersSent&&!S.writableEnded&&!S.destroyed&&errorResponse(S,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 w=validateBody(e,{},S,s);if(!w.ok)return;await t(g,S,w.value);return}let w;try{w=await readRequestBody(g)}catch(e){if(e instanceof PayloadTooLargeError){errorResponse(S,413,`urn:ok:error:payload-too-large`,`Payload too large.`,{handler:s.handler,cause:e});return}if(e instanceof RequestBodyTimeoutError){errorResponse(S,408,`urn:ok:error:request-timeout`,`Request body read timed out.`,{handler:s.handler,cause:e});return}errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read request body.`,{handler:s.handler,cause:e});return}let E;try{E=w.length===0?{}:JSON.parse(w.toString(`utf8`))}catch(e){errorResponse(S,400,`urn:ok:error:invalid-request`,`Request body is not valid JSON.`,{handler:s.handler,cause:e});return}let D=validateBody(e,E,S,s);D.ok&&await t(g,S,D.value)}}function spawnDetached(e,t,s){return new Promise(g=>{let S=!1,w=e=>{S||(S=!0,g(e))},E=setTimeout(()=>w({ok:!1,reason:`timeout`}),s);try{let s=spawn(e,[...t],{detached:!0,stdio:`ignore`,shell:!1});s.once(`error`,e=>{clearTimeout(E);let t=e instanceof Error?e.message:String(e);w(/ENOENT|EACCES|EPERM/.test(t)?{ok:!1,reason:`not-installed`}:{ok:!1,reason:`spawn-error`})}),queueMicrotask(()=>{if(!S){try{s.unref()}catch{}clearTimeout(E),w({ok:!0})}})}catch(e){console.warn(`[spawn-detached] synchronous spawn throw:`,e),clearTimeout(E),w({ok:!1,reason:`spawn-error`})}})}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 g;try{g=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 S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER$1,cause:e});return}let w=typeof S.path==`string`?S.path:``;if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,"Missing or empty `path` field.",{handler:HANDLER$1});return}if(!isPathWithinDir(w,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER$1});return}let E=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(SPAWN_CURSOR_WHICH_TIMEOUT_MS);if(!E){errorResponse(t,422,`urn:ok:error:cursor-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER$1});return}let D=resolveCursorSpawnInvocation(E,w,s.platform),O=await(s.spawnDetached??spawnDetached)(D.exec,D.args,SPAWN_CURSOR_SPAWN_TIMEOUT_MS);if(O.ok){successResponse(t,200,SpawnCursorSuccessSchema,{},{handler:HANDLER$1});return}switch(O.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(O.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 g=s.split(/\r?\n/)[0]?.trim();t(g&&g.length>0?g: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 g=s===`win32`?win32:posix;try{let S=g.resolve(e),w=g.resolve(t);if(s===`win32`){let e=g.parse(S).root.toLowerCase(),t=g.parse(w).root.toLowerCase();if(!e||!t||e!==t)return!1}if(S===w)return!0;let E=g.relative(w,S);return E===``||E===`.`?!0:!(E===`..`||E.startsWith(`..${g.sep}`)||s===`win32`&&(/^[a-zA-Z]:[\\/]/.test(E)||E.startsWith(`\\\\`))||s!==`win32`&&E.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().min(1).max(4096),workspacePath:string().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 g;try{g=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 S;try{S=JSON.parse(g.toString(`utf-8`))}catch(e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Malformed JSON body.`,{handler:HANDLER,cause:e});return}let w=HandoffRequestSchema.safeParse(S);if(!w.success){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid request body.`,{handler:HANDLER});return}let{target:E,url:D,workspacePath:O}=w.data,k=RECIPES[E];if(!D.startsWith(k.urlScheme)){errorResponse(t,400,`urn:ok:error:invalid-request`,`URL scheme must be ${k.urlScheme} for target ${E}.`,{handler:HANDLER});return}let j=s.sleep??defaultSleep,F=s.spawnDetached??spawnDetached;if(k.type===`app-bundle`){k.quitFirst&&(await F(`/usr/bin/osascript`,[`-e`,`tell application "${k.appName}" to quit`],SPAWN_TIMEOUT_MS).catch(()=>void 0),await j(QUIT_SETTLE_MS));let e=await F(`/usr/bin/open`,[`-a`,k.appName],SPAWN_TIMEOUT_MS);if(!e.ok){emitSpawnFailure(t,E,e.reason);return}await j(APP_BUNDLE_SETTLE_MS);let s=await F(`/usr/bin/open`,[D],SPAWN_TIMEOUT_MS);if(!s.ok){emitSpawnFailure(t,E,s.reason);return}successResponse(t,200,HandoffSuccessSchema,{},{handler:HANDLER});return}if(!O){errorResponse(t,400,`urn:ok:error:invalid-request`,`workspacePath is required for cursor handoff.`,{handler:HANDLER});return}if(!isPathWithinDir(O,s.contentDir,s.platform)){errorResponse(t,403,`urn:ok:error:path-escape`,`Path escapes the content directory.`,{handler:HANDLER});return}let L=await(s.resolveCursorBinary??resolveCursorBinaryDefault)(WHICH_TIMEOUT_MS);if(!L){errorResponse(t,422,`urn:ok:error:handoff-target-not-installed`,`Cursor CLI not found on this machine.`,{handler:HANDLER,extensions:{target:`cursor`}});return}let B=resolveCursorSpawnInvocation(L,O,s.platform),H=await F(B.exec,B.args,SPAWN_TIMEOUT_MS);if(!H.ok){emitSpawnFailure(t,E,H.reason);return}await j(CURSOR_SETTLE_MS);let q=await F(`/usr/bin/open`,[D],SPAWN_TIMEOUT_MS);if(!q.ok){emitSpawnFailure(t,E,q.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=[],g=new Set,S=t=>{!t||g.has(t)||t!==e&&(g.add(t),s.push(t))},w=buildLowerDocNameIndex(t),E=parentFolder(e);for(;;){for(let e of FIXED_HUB_BASENAMES)if(S(lookup$1(t,w,joinDocName(E,e))),s.length>=MAX_CANDIDATES)return s;let e=E===``?null:basename$1(E);if(e&&(S(lookup$1(t,w,joinDocName(E,e))),s.length>=MAX_CANDIDATES))return s;if(E===``)break;E=parentFolder(E)}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=``,g=null;for(let S of e){if(g){s+=S,S===g&&(g=null);continue}if(S===`"`||S===`'`){g=S,s+=S;continue}if(S===`,`){let e=normalizeFrontmatterScalar(s);e&&t.push(e),s=``;continue}s+=S}let S=normalizeFrontmatterScalar(s);return S&&t.push(S),t}function dedupeExact(e){let t=[],s=new Set;for(let g of e)!g||s.has(g)||(s.add(g),t.push(g));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 g=t[1]?.trim()??``;if(g){if(g.startsWith(`[`)&&g.endsWith(`]`))return dedupeExact(parseInlineAliases(g.slice(1,-1)));let e=normalizeFrontmatterScalar(g);return e?[e]:[]}let S=[];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&&S.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return dedupeExact(S)}return[]}function extractPageTitle(e,t){let{frontmatter:s,body:g}=stripFrontmatter(e),S=extractFrontmatterScalar(s,`title`);if(S)return S;let w=g.match(/^# (.+)$/m);return w?w[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}:`,g=splitFrontmatterLines(e);for(let e=0;e<g.length;e+=1){let t=g[e];if(!t?.startsWith(s))continue;let S=t.slice(s.length).trim();if(S){if(S.startsWith(`[`)&&S.endsWith(`]`)){let e=parseInlineAliases(S.slice(1,-1));return e.length>0?e:void 0}let e=normalizeFrontmatterScalar(S);return e?[e]:void 0}let w=[];for(let t=e+1;t<g.length;t+=1){let e=g[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=normalizeFrontmatterScalar(e.replace(/^\s*-\s+/,``));t&&w.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return w.length>0?w:void 0}}function extractPageIdentity(e,t){let s=extractPageTitle(e,t),g=extractPageAliases(e),S=dedupeExact([s,...g]),w=[],E=new Set;for(let e of S){let t=toWikiLinkSlug(e);!t||E.has(t)||(E.add(t),w.push(t))}return{docName:t,title:s,aliases:g,matchLabels:S,normalizedMatchLabels:w}}const MAX_ZIP_BYTES=102400;function resolveBundledSkillDir(){let e=[`../assets/skills/open-knowledge`,`./assets/skills/open-knowledge`],t=[];for(let s of e){let e=fileURLToPath(new URL(s,import.meta.url));if(existsSync(e))return e;t.push(e)}throw Error(`Bundled skill asset directory not found. Tried: ${t.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function*walkFiles(e,t=e){let s=await readdir(e,{withFileTypes:!0});for(let g of s){let s=join(e,g.name);g.isDirectory()?yield*walkFiles(s,t):g.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){let s=computeWrapperFolderName(e),g=new import_yazl.ZipFile;g.addEmptyDirectory(`${s}/`);let S=[];for await(let t of walkFiles(e))S.push(t);S.sort();for(let t of S){let S=join(e,t),w=`${s}/${toPosixZipPath(t)}`;g.addFile(S,w)}g.end(),await new Promise((e,s)=>{let S=createWriteStream(t);g.outputStream.pipe(S),S.on(`close`,()=>e()),S.on(`error`,s),g.outputStream.on(`error`,s)})}async function sha256OfFile(e){return new Promise((t,s)=>{let g=createHash(`sha256`),S=createReadStream(e);S.on(`data`,e=>g.update(e)),S.on(`end`,()=>t(g.digest(`hex`))),S.on(`error`,s)})}function extractMetadataVersion(e){let t=e.indexOf(`
822
822
  ---`,4);if(!e.startsWith(`---
@@ -1941,7 +1941,7 @@ Detailed conventions (wiki-link authoring, frontmatter, anti-patterns) live in t
1941
1941
 
1942
1942
  **Escape hatch.** Native \`Read\`/\`Grep\`/\`Glob\` on \`.md\` is allowed when the project has no \`.ok/\`, when no OK MCP is registered, or right after a failed OK MCP call (then prefix with \`Open Knowledge MCP unavailable:\`). Non-markdown: native tools always.
1943
1943
  `}const loggerContext=new AsyncLocalStorage;var McpLogger=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??randomUUID().slice(0,12),this.corrId=randomUUID().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,s={}){let g=t?{error:t instanceof Error?t.message:String(t),...s}:s;this.emit(`error`,e,g)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,s){let g={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...s},S=`${JSON.stringify(g)}\n`;process.stderr.write(S);let w=process.env.OK_LOG_FILE;if(w)try{appendFileSync(w,S)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function runWithMcpLogger(e,t){return loggerContext.run(e,t)}function getCurrentMcpLogger(){return loggerContext.getStore()}const REDACTED_STRING_KEYS=new Set([`find`,`markdown`,`replace`]),COMMON_ARRAY_KEYS=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],COMMON_SCALAR_KEYS=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isToolExtraLike(e){return isPlainObject(e)&&`requestId`in e}function summarizeStringForLog(e,t){if(REDACTED_STRING_KEYS.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
1944
- `).length};let s=e===`command`?240:120;return t.length<=s?t:{type:`string`,length:t.length,preview:`${t.slice(0,s)}...`}}function summarizeArgValue(e,t){if(t===null)return null;if(typeof t==`string`)return summarizeStringForLog(e,t);if(typeof t==`number`||typeof t==`boolean`)return t;if(Array.isArray(t))return{type:`array`,length:t.length};if(isPlainObject(t)){let e=Object.keys(t).sort();return{type:`object`,keyCount:e.length,keys:e.slice(0,12)}}if(t!==void 0)return{type:typeof t}}function summarizeArgsForLog(e,t){return isPlainObject(t)?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,summarizeArgValue(e,t)])):summarizeArgValue(e,t)}function summarizeStructuredContentForLog(e){let t={structuredKeys:Object.keys(e).sort()};for(let s of COMMON_SCALAR_KEYS)s in e&&(t[s]=e[s]);for(let s of COMMON_ARRAY_KEYS){let g=e[s];Array.isArray(g)&&(t[`${s}Count`]=g.length)}return`previewUrl`in e&&(t.previewUrl=e.previewUrl??null),`previewUrlSource`in e&&(t.previewUrlSource=e.previewUrlSource),typeof e.stdout==`string`&&(t.stdoutChars=e.stdout.length),Array.isArray(e.warnings)&&(t.warningsCount=e.warnings.length),isPlainObject(e.warning)&&(t.warning=!0,`previewUrl`in e.warning&&(t.warningPreviewUrl=e.warning.previewUrl??null)),isPlainObject(e.ui)&&(t.uiBaseUrl=typeof e.ui.baseUrl==`string`||e.ui.baseUrl===null?e.ui.baseUrl:void 0,t.uiPort=typeof e.ui.port==`number`||e.ui.port===null?e.ui.port:void 0),t}function summarizeToolResultForLog(e){if(!isPlainObject(e))return{resultType:typeof e};let t={isError:e.isError===!0};return Array.isArray(e.content)&&(t.contentItems=e.content.length,t.contentTextChars=e.content.reduce((e,t)=>isPlainObject(t)&&typeof t.text==`string`?e+t.text.length:e,0)),isPlainObject(e.structuredContent)&&Object.assign(t,summarizeStructuredContentForLog(e.structuredContent)),t}function summarizeIdentityForLog(e){return{connectionId:e.connectionId.slice(0,8),displayName:e.displayName,...e.clientInfo?.name?{clientName:e.clientInfo.name}:{}}}function splitInvocationArgs(e){let t=e.at(-1);return isToolExtraLike(t)?{toolArgs:e.length>1?e[0]:void 0,extra:t}:{toolArgs:e[0],extra:void 0}}function wrapToolHandlerForLogging(e,t,s){let g=s.logger;return g?async(...S)=>{let w=g.child(),E=Date.now(),{toolArgs:D,extra:O}=splitInvocationArgs(S);w.info(`tool start`,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},...O?.sessionId?{transportSessionId:O.sessionId}:{},...s.identityRef?.current?{agent:summarizeIdentityForLog(s.identityRef.current)}:{},...D===void 0?{}:{args:summarizeArgsForLog(e,D)}});try{let s=await runWithMcpLogger(w,async()=>await t(...S));return w.info(`tool finish`,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},durationMs:Date.now()-E,result:summarizeToolResultForLog(s)}),s}catch(t){throw w.error(`tool error`,t,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},durationMs:Date.now()-E}),t}}:t}function createLoggedServer(e,t){if(!t.logger)return e;let s=e.tool.bind(e),g=e.registerTool,S=typeof g==`function`?g.bind(e):void 0,w=Object.create(e);return w.tool=((...e)=>{let g=String(e[0]),S=e.at(-1);if(typeof S!=`function`)return s(...e);let w=[...e];return w[w.length-1]=wrapToolHandlerForLogging(g,S,t),s(...w)}),S&&(w.registerTool=((e,s,g)=>typeof g==`function`?S(e,s,wrapToolHandlerForLogging(e,g,t)):S(e,s,g))),w}function buildBody$2(e,t){return`${buildWorkflowFrame(`consolidate`)}Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
1944
+ `).length};let s=e===`command`?240:120;return t.length<=s?t:{type:`string`,length:t.length,preview:`${t.slice(0,s)}...`}}function summarizeArgValue(e,t){if(t===null)return null;if(typeof t==`string`)return summarizeStringForLog(e,t);if(typeof t==`number`||typeof t==`boolean`)return t;if(Array.isArray(t))return{type:`array`,length:t.length};if(isPlainObject(t)){let e=Object.keys(t).sort();return{type:`object`,keyCount:e.length,keys:e.slice(0,12)}}if(t!==void 0)return{type:typeof t}}function summarizeArgsForLog(e,t){return isPlainObject(t)?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,summarizeArgValue(e,t)])):summarizeArgValue(e,t)}function summarizeStructuredContentForLog(e){let t={structuredKeys:Object.keys(e).sort()};for(let s of COMMON_SCALAR_KEYS)s in e&&(t[s]=e[s]);for(let s of COMMON_ARRAY_KEYS){let g=e[s];Array.isArray(g)&&(t[`${s}Count`]=g.length)}return`previewUrl`in e&&(t.previewUrl=e.previewUrl??null),`previewUrlSource`in e&&(t.previewUrlSource=e.previewUrlSource),typeof e.stdout==`string`&&(t.stdoutChars=e.stdout.length),Array.isArray(e.warnings)&&(t.warningsCount=e.warnings.length),isPlainObject(e.warning)&&(t.warning=!0,`previewUrl`in e.warning&&(t.warningPreviewUrl=e.warning.previewUrl??null)),isPlainObject(e.ui)&&(t.uiBaseUrl=typeof e.ui.baseUrl==`string`||e.ui.baseUrl===null?e.ui.baseUrl:void 0,t.uiPort=typeof e.ui.port==`number`||e.ui.port===null?e.ui.port:void 0),t}function summarizeToolResultForLog(e){if(!isPlainObject(e))return{resultType:typeof e};let t={isError:e.isError===!0};return Array.isArray(e.content)&&(t.contentItems=e.content.length,t.contentTextChars=e.content.reduce((e,t)=>isPlainObject(t)&&typeof t.text==`string`?e+t.text.length:e,0)),isPlainObject(e.structuredContent)&&Object.assign(t,summarizeStructuredContentForLog(e.structuredContent)),t}function summarizeIdentityForLog(e){return{connectionId:e.connectionId.slice(0,8),displayName:e.displayName,...e.clientInfo?.name?{clientName:e.clientInfo.name}:{}}}function splitInvocationArgs(e){let t=e.at(-1);return isToolExtraLike(t)?{toolArgs:e.length>1?e[0]:void 0,extra:t}:{toolArgs:e[0],extra:void 0}}function wrapToolHandlerForLogging(e,t,s){let g=s.logger;return g?async(...S)=>{let w=g.child(),E=Date.now(),{toolArgs:D,extra:O}=splitInvocationArgs(S);w.info(`tool start`,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},...O?.sessionId?{transportSessionId:O.sessionId}:{},...s.identityRef?.current?{agent:summarizeIdentityForLog(s.identityRef.current)}:{},...D===void 0?{}:{args:summarizeArgsForLog(e,D)}});try{let s=await runWithMcpLogger(w,async()=>await t(...S));return w.info(`tool finish`,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},durationMs:Date.now()-E,result:summarizeToolResultForLog(s)}),s}catch(t){throw w.error(`tool error`,t,{tool:e,...O?.requestId===void 0?{}:{requestId:O.requestId},durationMs:Date.now()-E}),t}}:t}function createLoggedServer(e,t){if(!t.logger)return e;let s=e.tool.bind(e),g=e.registerTool,S=typeof g==`function`?g.bind(e):void 0,w=Object.create(e);return w.tool=((...e)=>{let g=String(e[0]),S=e.at(-1);if(typeof S!=`function`)return s(...e);let w=[...e];return w[w.length-1]=wrapToolHandlerForLogging(g,S,t),s(...w)}),S&&(w.registerTool=((e,s,g)=>typeof g==`function`?S(e,s,wrapToolHandlerForLogging(e,g,t)):S(e,s,g))),w}function buildBody$2(e,t){return`Promote existing research on this topic into a canonical article inside the project content directory. **Canonical, not provisional** — the output is the source of truth for future agents.
1945
1945
 
1946
1946
  Topic: ${e}
1947
1947
 
@@ -2089,7 +2089,7 @@ superseded_by: <path-to-new-canonical-article>.md
2089
2089
  - **Don't rewrite research prose verbatim** — canonical articles have a different voice (direct, decided) than research (exploratory, provisional)
2090
2090
  - **Don't skip the supersedes / superseded_by links** — the audit trail matters for future readers
2091
2091
  `}const DESCRIPTION$25=[`Promote research into a canonical article inside the project content directory. Canonical, not provisional — the output is the source of truth for future agents.`,``,`**Use when:**`,`- A team has made a decision after research and wants the outcome committed as canonical knowledge`,`- Compacting several provisional research notes into one authoritative article`,`- A developer asks to "consolidate" or "finalize" knowledge on a topic`,``,`**Triggers on:**`,`- "consolidate", "finalize", "promote to canonical", "make this official"`,`- User says the team has decided and wants the outcome written as canonical`,`- Research has stabilized and a destination article is needed`].join(`
2092
- `);function register$25(e,t){e.tool(`consolidate`,DESCRIPTION$25,{topic:string().describe(`The topic to consolidate into a canonical article`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);return s.ok?textPlusStructured(buildBody$2(e.topic,s.config.content.dir),{previewUrl:null}):textResult(`Error: ${s.error}`,!0)})}const PREVIEW_URL_SOURCES=[`electron-protocol`,`lock`],ELECTRON_PROTOCOL_ENV_VAR=`OK_ELECTRON_PROTOCOL_HOST`;function encodeDocName(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}async function resolvePreviewUrlForTool(e,t,s){let g=s??await t.resolveCwd(),S=resolveContentDir(await resolveConfig(t.config,g),g);return resolvePreviewUrl(e,{lockDir:resolveLockDir(g),contentDir:S})}function resolveUiInfo(e){try{let t=readUiLock(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`,port:t.port}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while building ui block: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null,port:null}}async function buildListResolver(e,t){let s=t??await e.resolveCwd(),g=resolveContentDir(await resolveConfig(e.config,s),s),S={lockDir:resolveLockDir(s),contentDir:g};return{resolve:e=>resolvePreviewUrl(e,S),ui:resolveUiInfo(S)}}function docNameFromPath(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function resolvePreviewUrl(e,t){let s=`/#/${encodeDocName(e)}`;if(process.env[ELECTRON_PROTOCOL_ENV_VAR]===`1`&&t.contentDir)try{let s=realpathSync(t.contentDir);return{url:`openknowledge://open?project=${encodeURIComponent(s)}&doc=${encodeURIComponent(e)}`,source:`electron-protocol`}}catch(e){process.stderr.write(`[preview-url] realpathSync failed for ${t.contentDir}, falling through to http sources: ${e instanceof Error?e.message:String(e)}\n`)}try{let e=readUiLock(t.lockDir);if(e&&e.port>0)return{url:`http://localhost:${e.port}${s}`,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}: ${e instanceof Error?e.message:String(e)}\n`)}return null}const DESCRIPTION$24=["[Requires: Hocuspocus server] Delete a document through the managed delete flow at `POST /api/delete-path` (kind: file).",`Closes all open agent sessions for the doc, unloads it from Hocuspocus, and removes the file from disk.`,``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.",``,`**Notes:**`,'- Inbound wiki-links to the deleted doc become dead links (redlinks) — they are NOT rewritten. Call `get_backlinks({ docName: "your-doc" })` BEFORE deleting to see which docs link here, then update or remove those references first.',"- Deletion is irreversible from this tool. Use `save_version` beforehand if you may need to roll back.","- The structured response includes `previousPreviewUrl` (when a preview source resolves) so agents can close any stale preview tab pointing at the deleted doc.",``,`**Errors:**`,"- 400 — `docName` is not a valid relative content path.",`- 404 — document does not exist.`].join(`
2092
+ `);function register$25(e,t){e.tool(`consolidate`,DESCRIPTION$25,{topic:string().describe(`The topic to consolidate into a canonical article`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},buildWorkflowHandler(`consolidate`,t,`topic`,buildBody$2))}const PREVIEW_URL_SOURCES=[`electron-protocol`,`lock`],ELECTRON_PROTOCOL_ENV_VAR=`OK_ELECTRON_PROTOCOL_HOST`;function encodeDocName(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}async function resolvePreviewUrlForTool(e,t,s){let g=s??await t.resolveCwd(),S=resolveContentDir(await resolveConfig(t.config,g),g);return resolvePreviewUrl(e,{lockDir:resolveLockDir(g),contentDir:S})}function resolveUiInfo(e){try{let t=readUiLock(e.lockDir);if(t&&t.port>0)return{baseUrl:`http://localhost:${t.port}`,port:t.port}}catch(t){process.stderr.write(`[preview-url] readUiLock failed at ${e.lockDir} while building ui block: ${t instanceof Error?t.message:String(t)}\n`)}return{baseUrl:null,port:null}}async function buildListResolver(e,t){let s=t??await e.resolveCwd(),g=resolveContentDir(await resolveConfig(e.config,s),s),S={lockDir:resolveLockDir(s),contentDir:g};return{resolve:e=>resolvePreviewUrl(e,S),ui:resolveUiInfo(S)}}function docNameFromPath(e){let t=e.toLowerCase();return t.endsWith(`.md`)?e.slice(0,-3):t.endsWith(`.mdx`)?e.slice(0,-4):e}function resolvePreviewUrl(e,t){let s=`/#/${encodeDocName(e)}`;if(process.env[ELECTRON_PROTOCOL_ENV_VAR]===`1`&&t.contentDir)try{let s=realpathSync(t.contentDir);return{url:`openknowledge://open?project=${encodeURIComponent(s)}&doc=${encodeURIComponent(e)}`,source:`electron-protocol`}}catch(e){process.stderr.write(`[preview-url] realpathSync failed for ${t.contentDir}, falling through to http sources: ${e instanceof Error?e.message:String(e)}\n`)}try{let e=readUiLock(t.lockDir);if(e&&e.port>0)return{url:`http://localhost:${e.port}${s}`,source:`lock`}}catch(e){process.stderr.write(`[preview-url] readUiLock failed at ${t.lockDir}: ${e instanceof Error?e.message:String(e)}\n`)}return null}const DESCRIPTION$24=["[Requires: Hocuspocus server] Delete a document through the managed delete flow at `POST /api/delete-path` (kind: file).",`Closes all open agent sessions for the doc, unloads it from Hocuspocus, and removes the file from disk.`,``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.",``,`**Notes:**`,'- Inbound wiki-links to the deleted doc become dead links (redlinks) — they are NOT rewritten. Call `get_backlinks({ docName: "your-doc" })` BEFORE deleting to see which docs link here, then update or remove those references first.',"- Deletion is irreversible from this tool. Use `save_version` beforehand if you may need to roll back.","- The structured response includes `previousPreviewUrl` (when a preview source resolves) so agents can close any stale preview tab pointing at the deleted doc.",``,`**Errors:**`,"- 400 — `docName` is not a valid relative content path.",`- 404 — document does not exist.`].join(`
2093
2093
  `);function parseDeletedDocNames(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function register$24(e,t){e.tool(`delete_document`,DESCRIPTION$24,{docName:string().describe(`Document name to delete`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=normalizeDocName(e.docName);if(!w.ok)return textResult(w.error,!0);let E=t.identityRef?.current,D=await httpPost(S,`/api/delete-path`,{kind:`file`,path:w.docName,...E?{agentId:E.connectionId,agentName:E.displayName,clientName:E.clientInfo?.name,colorSeed:E.colorSeed}:{}});if(!D.ok){let e=D.error,t={ok:!1,error:e};return textPlusStructured(`Error: ${e}`,t,!0)}let O=parseDeletedDocNames(D.deletedDocNames),k=await resolvePreviewUrlForTool(w.docName,{config:t.config,resolveCwd:t.resolveCwd},g),j={ok:!0,deletedDocNames:O.length>0?O:[w.docName],...k?{previousPreviewUrl:k.url}:{}};return textPlusStructured(j.deletedDocNames.length===1?`Deleted ${j.deletedDocNames[0]}.`:`Deleted ${j.deletedDocNames.length} documents: ${j.deletedDocNames.join(`, `)}.`,j)})}const DESCRIPTION$23=[`[Operates on disk; no running OK server required] Delete a template.`,``,"**Targets.** Mirrors `write_template`:",'- `target: "project"` (default) — deletes `<folder>/.ok/templates/<name>.md` from the current project.','- `target: "user"` — deletes `~/.ok/templates/<name>.md` from the user-global library. The `folder` argument is ignored.',``,"Idempotent: deleting a template that does not exist returns success with `existed: false`. Auto-cleans empty `<folder>/.ok/templates/` and `<folder>/.ok/` directories.",``,`**Parameters:**`,'- `folder` — Project-root-relative folder. Empty / `.` means project root. Ignored when `target: "user"`.',"- `name` — Template filename without `.md` extension.",'- `target` (optional) — `"project"` (default) or `"user"`.'].join(`
2094
2094
  `),InputSchema$5={folder:string().describe('Project-root-relative folder. Empty / `.` means project root. Ignored when `target: "user"`.'),name:string().min(1).regex(/^[A-Za-z0-9_-]+$/,"Template name must use letters, digits, `_`, or `-` only.").describe("Template filename without `.md` extension."),target:_enum([`project`,`user`]).optional().describe('Where the template lives. `"project"` (default) deletes from `<folder>/.ok/templates/`; `"user"` deletes from `~/.ok/templates/` (folder ignored).'),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},OutputSchema$5={result:union([object$1({ok:literal(!0),path:string(),existed:boolean(),cleanedEmpty:object$1({templatesDir:boolean(),okDir:boolean()})}),object$1({ok:literal(!1),error:object$1({code:string(),message:string()})})])};function register$23(e,t){e.registerTool(`delete_template`,{description:DESCRIPTION$23,inputSchema:InputSchema$5,outputSchema:OutputSchema$5,annotations:{readOnlyHint:!1,idempotentHint:!0,destructiveHint:!0}},async e=>{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);if(!s.ok)return{isError:!0,content:[{type:`text`,text:`Error: ${s.error}`}]};let{cwd:g}=s,S={projectDir:g,folder:e.folder,name:e.name};e.target!==void 0&&(S.target=e.target);let w=applyTemplateDelete(S);if(!w.ok)return{isError:!0,structuredContent:{result:w},content:[{type:`text`,text:`${w.error.code}: ${w.error.message}`}]};let E=[w.existed?`Deleted template at ${w.path}`:`Template at ${w.path} did not exist (no-op)`];return w.cleanedEmpty.templatesDir&&E.push(`Removed empty .ok/templates/ directory`),w.cleanedEmpty.okDir&&E.push(`Removed empty .ok/ directory`),textPlusStructured(E.join(`
2095
2095
  `),{result:w})})}const DESCRIPTION$22=[`[Requires: Hocuspocus server] Find-and-replace on a live document via the CRDT layer.`,`The patch is applied through Hocuspocus and propagated to all connected editors in real-time.`,"Use `offset` when you need to patch an exact occurrence; omit it to preserve first-match behavior.",``,'**Body-only.** Frontmatter-intersecting find/replace calls are rejected with HTTP 400. Frontmatter editing via MCP is currently unavailable — to change frontmatter, use `write_document` with `position: "replace"` and a payload that includes the new YAML block.',``,"**When rewriting prose, add `[[wiki-links]]` aggressively.** If the replacement mentions other documents or entities that should have their own page, link them as `[[Page Name]]`. Over-linking is the goal; underlinked documents lose their value in backlink-driven navigation.",``,`**Parameters:**`,"- `docName` — Document name, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `find` — Text to find (exact match)","- `replace` — Replacement text","- `offset` (optional) — Exact occurrence to patch, as a JavaScript string offset in the current markdown. If the document changed and the text no longer matches there, the server returns a stale-target error; re-run `suggest_links` to get fresh offsets.",'- `summary` — Optional one-line user-outcome description of this edit (≤80 chars). Appears as a bullet in the document timeline so readers can scan intent without opening every diff. Prefer outcome phrasing ("Fixed token-refresh race") over structural ("Changed 1 line"). Avoid including secrets or PII — summaries are persisted to git history.'].join(`
@@ -2114,7 +2114,7 @@ superseded_by: <path-to-new-canonical-article>.md
2114
2114
  `);function register$14(e,t){e.tool(`get_orphans`,DESCRIPTION$14,{mode:_enum(ORPHAN_MODES).optional().describe(`Filter which type of graph disconnection to surface`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=await httpGet(S,`/api/orphans${e.mode?`?mode=${encodeURIComponent(e.mode)}`:``}`);if(!w.ok)return textResult(`Error: ${w.error}`,!0);let{ok:E,...D}=w,O=D,{resolve:k,ui:j}=await buildListResolver(t,g),F=(O.orphans??[]).map(e=>{let t=typeof e.docName==`string`?e.docName:null,s=t?k(t):null;return{...e,previewUrl:s?.url??null,...s?{previewUrlSource:s.source}:{}}}),L={...O,orphans:F,ui:j,cwd:g};return textPlusStructured(JSON.stringify(L,null,2),L)})}const BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`Library`,`Applications`,`.Trash`]),IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function createContentFilter(e){let{projectDir:t,contentDir:s,onAfterRebuild:g}=e,S=relative(t,s),w=S.startsWith(`..`),E,D,O,k=0,j=0,F=0;function L(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[],L=0,B=0;for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=readFileSync(S,`utf-8`);L+=t.length;let s=parseIgnorePatterns(t);g.push(...s),e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${S}:`,e)}}if(S&&!w)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=readFileSync(g,`utf-8`);L+=t.length,B++;let s=parseIgnorePatterns(t).map(e=>prefixPattern(e,S));e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let H={value:L};B+=loadNestedIgnoreFiles(s,t,e,H),L=H.value;let q=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`));return E=e,D=g,O=q,k=g.length,j=B,F=L,{patternCount:k,nestedFileCount:j,bytes:F}}L();let B=new Map;function H(e){if(w)return!1;let t=S?`${S}/${e}`:e;return E.ignores(t)}populateDirCount(s,``,H,B);function q(e){let t=stripDocExtension(e);if(isSystemDoc(t)||isConfigDoc(t))return!0;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return w?!1:H(e)}return{isExcluded(e){if(q(e))return!0;if(isSupportedDocFile(e))return!1;let t=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(t)){let t=dirname(e),s=t===`.`?``:t;if((B.get(s)??0)>0)return!1}return!0},isDirExcluded(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(w)return!1;let t=S?`${S}/${e}`:e;return E.ignores(t)||E.ignores(`${t}/`)},isPathIgnored(e){return q(e)},getWatcherIgnoreGlobs(){return O},incrementMdDir(e){let t=e===`.`?``:e;B.set(t,(B.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=B.get(t)??0;s<=1?B.delete(t):B.set(t,s-1)},rebuildDirCount(){let e=new Map(B);B.clear();try{populateDirCount(s,``,H,B)}catch(t){for(let[t,s]of e)B.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=E,S=D,w=O,q=k,J=j,Y=F,ee=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async te=>{try{let t=L();B.clear(),populateDirCount(s,``,H,B);let S=Date.now()-ee;if(te.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:S},`content-filter rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:S}}catch(g){E=t,D=S,O=w,k=q,j=J,F=Y,B.clear();try{populateDirCount(s,``,H,B)}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let L=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(L)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:L}}}})}}}function populateDirCount(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let w of S){let S=t?`${t}/${w.name}`:w.name;if(w.isDirectory()){if(BUILTIN_SKIP_DIRS.has(w.name)||s(S)||s(`${S}/`))continue;populateDirCount(join(e,w.name),S,s,g)}else w.isFile()&&isSupportedDocFile(w.name)&&!s(S)&&g.set(t,(g.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
2115
2115
  `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function prefixPattern(e,t){return e.startsWith(`!`)?`!${t}/${e.slice(1)}`:`${t}/${e}`}function loadNestedIgnoreFiles(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){return console.warn(`[content-filter] Failed to read directory ${e}:`,t),0}let w=0;for(let E of S){if(!E.isDirectory()||BUILTIN_SKIP_DIRS.has(E.name))continue;let S=join(e,E.name),D=relative(t,S);if(!D.startsWith(`..`)&&!(s.ignores(D)||s.ignores(`${D}/`))){for(let e of IGNORE_FILE_NAMES){let t=join(S,e);if(existsSync(t))try{let e=readFileSync(t,`utf-8`);g.value+=e.length;let S=parseIgnorePatterns(e).map(e=>prefixPattern(e,D));s.add(S),w++}catch(s){console.warn(`[content-filter] Failed to read nested ${e} at ${t}:`,s)}}w+=loadNestedIgnoreFiles(S,t,s,g)}}return w}async function initContentDirStateAsync(e,t,s,g,S,w,E){let D;try{D=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let O of D){let D=t?`${t}/${O.name}`:O.name;if(O.isDirectory()){if(BUILTIN_SKIP_DIRS.has(O.name))continue;let t=join(e,O.name);if(!w){let e=relative(s,t);if(e.startsWith(`..`)||g.ignores(e)||g.ignores(`${e}/`))continue;for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.add(t.map(t=>prefixPattern(t,e)))}catch(e){console.warn(`[content-filter] Failed to read nested ${s} at ${S}:`,e)}}}await initContentDirStateAsync(t,D,s,g,S,w,E)}else if(O.isFile()&&isSupportedDocFile(O.name)){if(!w){let e=S?`${S}/${D}`:D;if(g.ignores(e))continue}E.set(t,(E.get(t)??0)+1)}}}async function createContentFilterAsync(e){let{projectDir:t,contentDir:s,onAfterRebuild:g}=e,S=relative(t,s),w=S.startsWith(`..`),E=(0,import_ignore.default)(),D=[],O=new Map;function k(e){if(w)return!1;let t=S?`${S}/${e}`:e;return E.ignores(t)}function j(e){let t=stripDocExtension(e);if(isSystemDoc(t)||isConfigDoc(t))return!0;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return w?!1:k(e)}async function F(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[];for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.push(...t),e.add(t)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${S}:`,e)}}if(S&&!w)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=parseIgnorePatterns(await readFile$1(g,`utf-8`));e.add(t.map(e=>prefixPattern(e,S)))}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let k=new Map;await initContentDirStateAsync(s,``,t,e,S,w,k),E=e,D=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),O.clear();for(let[e,t]of k)O.set(e,t)}return await F(),{isExcluded(e){if(j(e))return!0;if(isSupportedDocFile(e))return!1;let t=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(t)){let t=dirname(e),s=t===`.`?``:t;if((O.get(s)??0)>0)return!1}return!0},isDirExcluded(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(w)return!1;let t=S?`${S}/${e}`:e;return E.ignores(t)||E.ignores(`${t}/`)},isPathIgnored(e){return j(e)},getWatcherIgnoreGlobs(){return D},incrementMdDir(e){let t=e===`.`?``:e;O.set(t,(O.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=O.get(t)??0;s<=1?O.delete(t):O.set(t,s-1)},rebuildDirCount(){let e=new Map(O);O.clear();try{populateDirCount(s,``,k,O)}catch(t){for(let[t,s]of e)O.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=E,s=D,S=new Map(O),w=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async k=>{try{await F();let t=Date.now()-w;if(k.setAttributes({"ok.ignore.pattern_count":D.length,"ok.ignore.nested_file_count":0,"ok.ignore.bytes":0}),e.info({durationMs:t},`content-filter async rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:D.length,nestedFileCount:0,bytes:0,durationMs:t}}catch(g){E=t,D=s,O.clear();for(let[e,t]of S)O.set(e,t);let w=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(w)},`content-filter async rebuild failed — rolled back`),{ok:!1,error:{message:w}}}})}}}const DESCRIPTION$13=["Find every line that literally contains a string, grouped by file with frontmatter metadata. For ranked retrieval that mirrors cmd-K, use `search`.",``,`Matches are grouped by file; each file is annotated with its title, description, and tags so you can judge relevance without opening it first.`,``,`**Use when:**`,`- Finding every occurrence of a literal phrase across the wiki`,`- Auditing a term, identifier, or quote — coverage matters more than ranking`,``,"**When the project has `.ok/`**, strongly prefer this over your native `Grep` for wiki search — results include article metadata so you can skip irrelevant matches without extra reads. In projects without `.ok/`, use native `Grep` as usual.",``,`**Parameters:**`,"- `query` — Literal text to search for (fixed-string match, no regex)","- `case_sensitive` (optional, default false) — case-sensitive match","- `cwd` (optional) — Project root the grep runs against. Defaults only when the MCP client advertises exactly one root."].join(`
2116
2116
  `);function groupByFile(e){let t=new Map;for(let s of e){let e=t.get(s.path);e?e.push(s):t.set(s.path,[s])}return[...t.entries()].map(([e,t])=>({path:e,matches:t}))}async function buildGrepResult(e,t){let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)throw Error(s.error);let{cwd:g,config:S,url:w}=s,E=50,D=await grep(e.query,g,{caseInsensitive:!(e.case_sensitive??!1),include:[`**/*.md`,`**/*.mdx`],exclude:[`node_modules`,`.git`,`.claude`,`.changeset`,`.ok`],maxResults:51}),O=resolveContentDir(S,g),k=createContentFilter({projectDir:g,contentDir:O}),j=D.filter(e=>{let t=relative(O,resolve(g,e.path));return t.startsWith(`..`)?!1:!k.isExcluded(t)}),F=D.length>50,L=j.slice(0,50),{resolve:B,ui:H}=await buildListResolver({config:S,resolveCwd:async()=>g},g);if(L.length===0)return{text:`No matches for "${e.query}".`,structured:{query:e.query,matchCount:0,fileCount:0,truncated:!1,results:[],ui:H,cwd:g}};let q=groupByFile(L),J=new Map;await Promise.all(q.map(async e=>{try{let t=await enrichPath(e.path,{projectDir:g,serverUrl:w});J.set(e.path,t)}catch{}}));let Y=[];Y.push(`## Grep results for "${e.query}" (${L.length} match${L.length===1?``:`es`} in ${q.length} file${q.length===1?``:`s`})`,``);let ee=[];for(let e of q){let t=J.get(e.path),s=t?.title??e.path;Y.push(`### ${s} (${e.path})`),t?.tags?.length&&Y.push(`Tags: ${t.tags.join(`, `)}`),t?.description&&Y.push(`${t.description}`);for(let t of e.matches)Y.push(`- Line ${t.line}: ${t.text}`);Y.push(``);let g=docNameFromPath(e.path),S=B(g);ee.push({path:e.path,docName:g,title:t?.title??null,description:t?.description??null,tags:t?.tags??[],matches:e.matches.map(e=>({line:e.line,text:e.text})),previewUrl:S?.url??null,...S?{previewUrlSource:S.source}:{}})}return F&&Y.push(`_${L.length} of ${D.length}+ matches shown (max 50). Refine your query to narrow results._`),{text:Y.join(`
2117
- `),structured:{query:e.query,matchCount:L.length,fileCount:q.length,truncated:F,results:ee,ui:H,cwd:g}}}const InputSchema$3={query:string().describe(`Literal text to search for`),case_sensitive:boolean().optional().describe(`Case-sensitive search (default false)`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},GrepResultRowSchema=object$1({path:string(),docName:string(),title:string().nullable(),description:string().nullable(),tags:array(string()),matches:array(object$1({line:number().int(),text:string()})),previewUrl:string().nullable(),previewUrlSource:_enum(PREVIEW_URL_SOURCES).optional()}),OutputSchema$3={cwd:string(),query:string(),matchCount:number().int(),fileCount:number().int(),truncated:boolean(),results:array(GrepResultRowSchema),ui:object$1({baseUrl:string().nullable(),port:number().nullable()})};function register$13(e,t){e.registerTool(`grep`,{description:DESCRIPTION$13,inputSchema:InputSchema$3,outputSchema:OutputSchema$3,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async e=>{try{let{text:s,structured:g}=await buildGrepResult(e,t);return g?textPlusStructured(s,g):textResult(s)}catch(e){return textResult(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}function buildBody$1(e,t){return`${buildWorkflowFrame(`ingest`)}Capture this external source into the project knowledge base as raw reference material. The KB is **closed-loop**: external sources are pulled INTO the knowledge base here so downstream docs cite local paths, never bare web URLs. This applies whether a user shared the source OR you fetched it yourself to ground a knowledge-base claim — agent-initiated fetches are not exempt. **Raw preservation only** — no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
2117
+ `),structured:{query:e.query,matchCount:L.length,fileCount:q.length,truncated:F,results:ee,ui:H,cwd:g}}}const InputSchema$3={query:string().describe(`Literal text to search for`),case_sensitive:boolean().optional().describe(`Case-sensitive search (default false)`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},GrepResultRowSchema=object$1({path:string(),docName:string(),title:string().nullable(),description:string().nullable(),tags:array(string()),matches:array(object$1({line:number().int(),text:string()})),previewUrl:string().nullable(),previewUrlSource:_enum(PREVIEW_URL_SOURCES).optional()}),OutputSchema$3={cwd:string(),query:string(),matchCount:number().int(),fileCount:number().int(),truncated:boolean(),results:array(GrepResultRowSchema),ui:object$1({baseUrl:string().nullable(),port:number().nullable()})};function register$13(e,t){e.registerTool(`grep`,{description:DESCRIPTION$13,inputSchema:InputSchema$3,outputSchema:OutputSchema$3,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async e=>{try{let{text:s,structured:g}=await buildGrepResult(e,t);return g?textPlusStructured(s,g):textResult(s)}catch(e){return textResult(`Error: ${e instanceof Error?e.message:String(e)}`,!0)}})}function buildBody$1(e,t){return`Capture this external source into the project knowledge base as raw reference material. The KB is **closed-loop**: external sources are pulled INTO the knowledge base here so downstream docs cite local paths, never bare web URLs. This applies whether a user shared the source OR you fetched it yourself to ground a knowledge-base claim — agent-initiated fetches are not exempt. **Raw preservation only** — no summary, no analysis, no interpretation. Summarizing is the job of the \`research\` tool later.
2118
2118
 
2119
2119
  Source: ${e}
2120
2120
 
@@ -2196,7 +2196,7 @@ If the source is directly relevant to an existing article or research doc, updat
2196
2196
  - **No silent chaining into research** — ingest completes on its own; the user explicitly opts into \`research\`
2197
2197
  - **No synthesis inside the raw file** — the takeaways live in chat or a separate summary doc, never mixed into the preserved source
2198
2198
  `}const DESCRIPTION$12=[`Fetch an external source (URL or local file) and save raw content as reference material in the project content directory.`,`Raw preservation only — no analysis or interpretation.`,`The knowledge base is closed-loop: web sources cited by KB docs MUST resolve to a local doc captured here, not bare URLs.`,``,`**Use when:**`,`- Capturing reference material for the project knowledge base`,`- Saving a URL or document for later research`,`- Archiving an external source alongside the codebase`,`- The user shares a URL or document they want preserved`,"- **You yourself fetched a URL (`WebFetch` / `WebSearch` / equivalent) to ground a claim that is about to land in a knowledge-base doc** — agent-initiated fetches are not exempt from the closed-loop rule",``,`**Triggers on:**`,`- "ingest", "save this source", "capture this URL", "add to external sources"`,`- User shares a URL, article, or document to preserve in the knowledge base`,`- Agent fetches a URL via WebFetch/WebSearch to support a knowledge-base claim — preserve the source before citing it`,`- Research workflow needs raw sources before analysis`].join(`
2199
- `);function register$12(e,t){e.tool(`ingest`,DESCRIPTION$12,{source:string().describe(`URL, file path, or identifier of the source to ingest`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);return s.ok?textPlusStructured(buildBody$1(e.source,s.config.content.dir),{previewUrl:null}):textResult(`Error: ${s.error}`,!0)})}const DESCRIPTION$11=[`[Requires: Hocuspocus server] List available documents from the Hocuspocus server.`,"Returns document names, optionally filtered by directory. When `dir` is set,","also surfaces folder-level metadata: `frontmatter_defaults` (merged folder","defaults that new docs in this folder will inherit) and `templates_available`","(menu of starter shapes for `write_document({ template })`). Pass `depth: N`","to also enrich subfolders up to N levels deep — mirrors `find -maxdepth N`.",``,`**Parameters:**`,"- `dir` (optional) — Filter to documents in this directory","- `depth` (optional, default `1`) — Subfolder enrichment depth. `1` = this"," folder only; `2` = direct children's folder metadata too; `Infinity` =",` full subtree. Walk-up ancestors' templates always show regardless.`].join(`
2199
+ `);function register$12(e,t){e.tool(`ingest`,DESCRIPTION$12,{source:string().describe(`URL, file path, or identifier of the source to ingest`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},buildWorkflowHandler(`ingest`,t,`source`,buildBody$1))}const DESCRIPTION$11=[`[Requires: Hocuspocus server] List available documents from the Hocuspocus server.`,"Returns document names, optionally filtered by directory. When `dir` is set,","also surfaces folder-level metadata: `frontmatter_defaults` (merged folder","defaults that new docs in this folder will inherit) and `templates_available`","(menu of starter shapes for `write_document({ template })`). Pass `depth: N`","to also enrich subfolders up to N levels deep — mirrors `find -maxdepth N`.",``,`**Parameters:**`,"- `dir` (optional) — Filter to documents in this directory","- `depth` (optional, default `1`) — Subfolder enrichment depth. `1` = this"," folder only; `2` = direct children's folder metadata too; `Infinity` =",` full subtree. Walk-up ancestors' templates always show regardless.`].join(`
2200
2200
  `);function register$11(e,t){e.tool(`list_documents`,DESCRIPTION$11,{dir:string().optional().describe(`Optional directory to filter documents`),depth:number().int().min(1).optional().describe("Subfolder enrichment depth (find -maxdepth semantics). Default 1. Only meaningful when `dir` is also set."),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=null;if(e.dir!==void 0){let t=resolveWithinRoot(g,e.dir);if(!t.ok)return textResult(`Error: ${t.reason}`,!0);w=t.rel}let E=await httpGet(S,`/api/documents${w===null?``:`?dir=${encodeURIComponent(w)}`}`);if(!E.ok)return textResult(`Error: ${E.error}`,!0);let{ok:D,...O}=E,k=O,{resolve:j,ui:F}=await buildListResolver(t,g),L=(k.documents??[]).filter(e=>e.kind!==`folder`).map(e=>{let t=typeof e.docName==`string`?e.docName:null,s=t?j(t):null;return{...e,previewUrl:s?.url??null,...s?{previewUrlSource:s.source}:{}}}),B;if(w!==null){let t=e.depth??1;try{B=await enrichDirectoryRecursive(w,t,{projectDir:g})}catch{B=void 0}}let H={...k,documents:L,ui:F,cwd:g,...B?{folder:B}:{}};return textPlusStructured(JSON.stringify(H,null,2),H)})}const DESCRIPTION$10=[`Read a wiki file with enriched context: contents + frontmatter metadata + recent shadow-repo activity (agent vs human attribution) + backlink/forward-link context.`,``,`**Use when:**`,`- Loading an article for context`,`- Understanding who changed a file recently and whether it was an agent or human`,`- Seeing how this page links out and what links back to it`,``,"**When the project has `.ok/`**, strongly prefer this over your native `Read` for wiki files — one call returns what otherwise takes 3-4. In projects without `.ok/`, use native `Read` as usual.",``,`**Parameters:**`,"- `path` — Project-root-relative path to the file, including extension (e.g. `articles/auth/sso.md`). To pass this document to `edit_document` / `write_document` / `get_backlinks`, strip the extension (they take extension-less `docName`).","- `since` (reserved) — Reserved for shadow-log since-filter; currently unused."].join(`
2201
2201
  `);function formatShadowHistory(e){if(!e||e.length===0)return``;let t=[``,`### Recent activity (OK edits)`,``];for(let s of e){let e=s.writerClassification===`agent`?`agent: ${s.writerName}`:s.writerClassification===`principal`?`human: ${s.writerName}`:`${s.writerClassification}: ${s.writerName}`,g=s.hash.slice(0,7);t.push(`- ${g} ${s.date} [${e}] ${s.message}`)}return t.join(`
2202
2202
  `)}function formatProjectHistory(e){if(!e||e.length===0)return``;let t=[``,`### Commit history (project git)`,``];for(let s of e){let e=s.hash.slice(0,7);t.push(`- ${e} ${s.date} ${s.authorName} — ${s.subject}`)}return t.join(`
@@ -2207,7 +2207,7 @@ If the source is directly relevant to an existing article or research doc, updat
2207
2207
  `);function parseRenameMappings$1(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromDocName:t,toDocName:s}=e;return typeof t==`string`&&typeof s==`string`?[{fromDocName:t,toDocName:s}]:[]}):[]}function parseRewrittenDocs$1(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{docName:t,rewrites:s}=e;return typeof t==`string`&&typeof s==`number`?[{docName:t,rewrites:s}]:[]}):[]}function pluralize(e,t,s=`${t}s`){return e===1?t:s}function register$9(e,t){e.tool(`rename_document`,DESCRIPTION$9,{docName:string().describe(`Current document name`),newDocName:string().describe(`New document name`),summary:summaryArgSchema.describe(`Optional one-line user-outcome description (≤80 chars). Defaults to "Renamed X → Y" when omitted. Appears as a bullet in the timeline.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=normalizeDocName(e.docName);if(!w.ok)return textResult(w.error,!0);let E=normalizeDocName(e.newDocName);if(!E.ok)return textResult(E.error,!0);let D=t.identityRef?.current,O=await httpPost(S,`/api/rename-path`,{kind:`file`,fromPath:w.docName,toPath:E.docName,...e.summary===void 0?{}:{summary:e.summary},...D?{agentId:D.connectionId,agentName:D.displayName,clientName:D.clientInfo?.name,colorSeed:D.colorSeed}:{}});if(!O.ok){let e=O.error,t=parseRenameCollidingPairs(O.colliding),s={ok:!1,error:e,...t.length>0?{colliding:t}:{}};return textPlusStructured(`Error: ${e}`,s,!0)}let k=parseRenameMappings$1(O.renamed),j=parseRewrittenDocs$1(O.rewrittenDocs),F=k.map(({fromDocName:e,toDocName:t})=>`${e} -> ${t}`).join(`, `)||`${w.docName} -> ${E.docName}`,L=j.length===0?`No inbound links required updates.`:`Rewrote ${j.length} ${pluralize(j.length,`document`)}.`,B={config:t.config,resolveCwd:t.resolveCwd},H=await resolvePreviewUrlForTool(E.docName,B,g),q=await resolvePreviewUrlForTool(w.docName,B,g),J=O.summary&&typeof O.summary==`object`?O.summary:void 0,Y=typeof J?.hint==`string`?J.hint:void 0,ee={ok:!0,renamed:k,rewrittenDocs:j,previewUrl:H?.url??null,...H?{previewUrlSource:H.source}:{},...q?{previousPreviewUrl:q.url}:{},...J?{summary:J}:{}},te=[`Renamed ${F}. ${L}`];return Y&&te.push(Y),textPlusStructured(te.join(`
2208
2208
  `),ee)})}const DESCRIPTION$8=["[Requires: Hocuspocus server] Rename a folder through the managed rename flow at `POST /api/rename-path` (kind: folder).",`Atomically moves the folder and rewrites inbound wiki-links + supported internal inline Markdown links across every affected doc. One call replaces N rename_document calls.`,``,`**Parameters:**`,"- `fromFolder` — Current folder path relative to the content directory (no leading or trailing slash). Example: `articles` or `notes/drafts`.","- `toFolder` — New folder path relative to the content directory. Example: `essays` or `notes/published`. Parent directories are auto-created.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Applied to every affected-doc contributor entry. If omitted, a default like "Renamed X → Y" is generated. Provide your own summary to explain the why. Avoid including secrets or PII — summaries are persisted to git history.',``,`**Errors:**`,"- 400 — case-only renames (e.g. `Articles` → `articles`) are not supported.","- 400 — destination folder is excluded by `.gitignore` / `.okignore` rules.",`- 404 — source folder does not exist.`,`- 409 — destination folder already exists or rename would collide.`].join(`
2209
2209
  `);function isValidFolderPath(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`..`))}function parseRenameMappings(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromDocName:t,toDocName:s}=e;return typeof t==`string`&&typeof s==`string`?[{fromDocName:t,toDocName:s}]:[]}):[]}function parseRewrittenDocs(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{docName:t,rewrites:s}=e;return typeof t==`string`&&typeof s==`number`?[{docName:t,rewrites:s}]:[]}):[]}function register$8(e,t){e.tool(`rename_folder`,DESCRIPTION$8,{fromFolder:string().describe(`Current folder path (relative, no trailing slash)`),toFolder:string().describe(`New folder path (relative, no trailing slash)`),summary:summaryArgSchema.describe(`Optional one-line user-outcome description (≤80 chars). Applied to every affected-doc contributor entry.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);if(!isValidFolderPath(e.fromFolder))return textResult(`fromFolder must be a relative path with no leading/trailing slash`,!0);if(!isValidFolderPath(e.toFolder))return textResult(`toFolder must be a relative path with no leading/trailing slash`,!0);let w=t.identityRef?.current,E=await httpPost(S,`/api/rename-path`,{kind:`folder`,fromPath:e.fromFolder,toPath:e.toFolder,...e.summary===void 0?{}:{summary:e.summary},...w?{agentId:w.connectionId,agentName:w.displayName,clientName:w.clientInfo?.name,colorSeed:w.colorSeed}:{}});if(!E.ok){let e=E.error,t=parseRenameCollidingPairs(E.colliding),s={ok:!1,error:e,...t.length>0?{colliding:t}:{}};return textPlusStructured(`Error: ${e}`,s,!0)}let D=parseRenameMappings(E.renamed),O=parseRewrittenDocs(E.rewrittenDocs),k={config:t.config,resolveCwd:t.resolveCwd},j={},F;for(let{toDocName:e}of D){let t=await resolvePreviewUrlForTool(e,k,g);t&&(j[e]=t.url,F??=t.source)}let L=E.summary&&typeof E.summary==`object`?E.summary:void 0,B=typeof L?.hint==`string`?L.hint:void 0,H={ok:!0,renamed:D,rewrittenDocs:O,previewUrls:j,...F?{previewUrlSource:F}:{},...L?{summary:L}:{}},q=[];return D.length===0?q.push(`No managed docs under ${e.fromFolder}/ — nothing to rename. Empty folders are not tracked; create a doc inside the folder first.`):q.push(`Renamed folder ${e.fromFolder}/ → ${e.toFolder}/ (${D.length} doc${D.length===1?``:`s`}, ${O.length} rewrite${O.length===1?``:`s`}).`),B&&q.push(B),textPlusStructured(q.join(`
2210
- `),H)})}function buildBody(e,t){return`${buildWorkflowFrame(`research`)}Conduct **evidence-driven research** on this topic and produce a provisional research article in the Open Knowledge content directory. This workflow mirrors the discipline of the \`eng:research\` skill, scoped to Open Knowledge's wiki-provisional layer.
2210
+ `),H)})}function buildBody(e,t){return`Conduct **evidence-driven research** on this topic and produce a provisional research article in the Open Knowledge content directory. This workflow mirrors the discipline of the \`eng:research\` skill, scoped to Open Knowledge's wiki-provisional layer.
2211
2211
 
2212
2212
  Topic: ${e}
2213
2213
  Content directory: \`${t}\` (from \`.ok/config.yml\`)
@@ -2558,7 +2558,7 @@ In headless mode, write the recap into the research article's "Further reading"
2558
2558
  - **Don't mix 1P codebase analysis into the article unless asked.** Findings drift from factual synthesis to opinion when you do.
2559
2559
  - **Don't overwrite existing research silently.** If the topic was researched before, either iterate (Path C) or create a clearly-named successor (\`crdt-alternatives-2.md\`) and mark the old one as superseded.
2560
2560
  `}const DESCRIPTION$7=[`Analyze a topic by gathering sources via ingest and writing provisional findings into the project content directory.`,`Provisional, not canonical — findings live here until decisions solidify.`,``,`**Use when:**`,`- Researching a topic before committing to an approach`,`- Exploring a decision space or comparing alternatives`,`- Synthesizing multiple sources into structured analysis`,`- Spec conversations and exploratory work that is not yet canonical`,``,`**Triggers on:**`,`- "research", "investigate", "compare options for", "analyze alternatives"`,`- User asks to explore trade-offs, gather evidence, or evaluate approaches`,`- A decision needs structured analysis grounded in external sources`].join(`
2561
- `);function register$7(e,t){e.tool(`research`,DESCRIPTION$7,{topic:string().describe(`The topic, question, or anchor URL to research`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let s=await resolveProjectConfigContext(t.resolveCwd,t.config,e.cwd);return s.ok?textPlusStructured(buildBody(e.topic,s.config.content.dir),{previewUrl:null}):textResult(`Error: ${s.error}`,!0)})}const DESCRIPTION$6=[`[Requires: Hocuspocus server] Restore a document to a historical version via the CRDT layer.`,`The restore is append-only — it creates a new version with the old content,`,`preserving all history. All connected editors see the change in real-time.`,``,`**Parameters:**`,"- `docName` — Document name to restore, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `commitSha` — The 40-character SHA of the shadow repo commit to restore to."," Use `get_history` to find available versions.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline. If omitted, a default like "Restored to <sha-short>" is generated. Provide your own summary to explain the why. Avoid including secrets or PII — summaries are persisted to git history.'].join(`
2561
+ `);function register$7(e,t){e.tool(`research`,DESCRIPTION$7,{topic:string().describe(`The topic, question, or anchor URL to research`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},buildWorkflowHandler(`research`,t,`topic`,buildBody))}const DESCRIPTION$6=[`[Requires: Hocuspocus server] Restore a document to a historical version via the CRDT layer.`,`The restore is append-only — it creates a new version with the old content,`,`preserving all history. All connected editors see the change in real-time.`,``,`**Parameters:**`,"- `docName` — Document name to restore, typically without extension. A trailing `.md` or `.mdx` is stripped automatically.","- `commitSha` — The 40-character SHA of the shadow repo commit to restore to."," Use `get_history` to find available versions.",'- `summary` — Optional one-line user-outcome description (≤80 chars). Appears as a bullet in the timeline. If omitted, a default like "Restored to <sha-short>" is generated. Provide your own summary to explain the why. Avoid including secrets or PII — summaries are persisted to git history.'].join(`
2562
2562
  `);function register$6(e,t){e.tool(`rollback_to_version`,DESCRIPTION$6,{docName:string().describe(`Document name to restore`),commitSha:string().length(40).regex(/^[0-9a-f]+$/i).describe(`40-character commit SHA from the shadow repo timeline`),summary:summaryArgSchema.describe(`Optional one-line user-outcome description (≤80 chars). Defaults to "Restored to <sha-short>" when omitted. Appears as a bullet in the timeline.`),cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,url:S}=s;if(!S)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let w=normalizeDocName(e.docName);if(!w.ok)return textResult(w.error,!0);let E=w.docName,D=await httpGet(S,`/api/history/${e.commitSha}?docName=${encodeURIComponent(E)}`);if(!D.ok)return textResult(`Error: ${D.error??`Version not found`}`,!0);let O=t.identityRef?.current,k=await httpPost(S,`/api/rollback`,{docName:E,commitSha:e.commitSha,...e.summary===void 0?{}:{summary:e.summary},...O?{agentId:O.connectionId,agentName:O.displayName,clientName:O.clientInfo?.name,colorSeed:O.colorSeed}:{}});if(!k.ok)return textResult(`Error: ${k.error}`,!0);let j=k.summary&&typeof k.summary==`object`?k.summary:void 0,F=typeof j?.hint==`string`?j.hint:void 0,L=[`Restored "${E}" to version ${e.commitSha.slice(0,8)} (${D.author}, ${D.timestamp}). The change has been applied to all connected editors.`];F&&L.push(F);let B=await resolvePreviewUrlForTool(E,{config:t.config,resolveCwd:t.resolveCwd},g);return textPlusStructured(L.join(`
2563
2563
  `),{previewUrl:B?.url??null,...B?{previewUrlSource:B.source}:{},...j?{summary:j}:{}})})}const DESCRIPTION$5=[`[Requires: Hocuspocus server] Save a version checkpoint of all documents.`,`Creates a checkpoint commit in the shadow repo and project repo,`,`preserving the current state of all documents. The checkpoint can later`,"be found via `get_history` and restored via `rollback_to_version`."].join(`
2564
2564
  `);function register$5(e,t,s,g,S){e.tool(`save_version`,DESCRIPTION$5,{cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},async(e={})=>{let w=await resolveProjectServerContext(g,t,s,e.cwd);if(!w.ok)return textResult(`Error: ${w.error}`,!0);if(!w.url)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let{url:E}=w,D=S?.current,O=await httpPost(E,`/api/save-version`,{...D?{writers:[{id:`agent-${D.connectionId}`,name:D.displayName,email:`agent-${D.connectionId}@openknowledge.local`}]}:{}});return O.ok?textPlusStructured(`Checkpoint saved. Checkpoint ref: ${O.checkpointRef}`,{checkpointRef:O.checkpointRef,previewUrl:null}):textResult(`Error: ${O.error}`,!0)})}const DESCRIPTION$4=["Find the most relevant pages for a query (ranked: title boost + body BM25 + recency). For literal-string matching across every line, use `grep`.",``,"Same engine and ranking the cmd-K palette uses. Returns a sorted list of page (and folder, with `omnibar` intent) hits with score signals plus a body snippet per page.",``,`**Use when:**`,`- Hunting for the canonical page on a topic`,`- Locating a doc by partial title or path segments`,`- Picking the best entry point before reading`,``,`**Parameters:**`,"- `query` — Search query (free-form; tokenized across title, name, path segments, and optionally body content).","- `intent` (optional) — `'omnibar'` searches title/path/folders only (fast); `'full_text'` includes body content. Default `'full_text'`.","- `scopes` (optional) — Override the result scope. Members: `'page'`, `'folder'`, `'content'`. Defaults derive from `intent`.","- `limit` (optional) — Max rows; default 20, max 100.","- `cwd` (optional) — Project root the query runs against.",``,"**Server requirement:** the Hocuspocus server must be running (`open-knowledge start`). If not, this tool returns a recovery hint; use `grep` as a server-free fallback."].join(`
@@ -2581,4 +2581,4 @@ In headless mode, write the recap into the research article's "Further reading"
2581
2581
  `).split(`
2582
2582
  `),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);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:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}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 g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].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 g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+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 g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.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 g of s){let s=join(e,g.name);if(g.isDirectory()){let e=relative(this.contentDir,s);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=relative(this.contentDir,s);this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),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:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1}=e,J=getLogger(`server`);function Y(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>J.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||J.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>J.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ee=randomUUID(),te=getLocalDir(s);if(acquireServerLock(te,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:te,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(te),e}let ne=createBasenameIndex(),ae=(e,t)=>ne.resolveEmbed(e,t),oe=(e,s)=>{let g=ne.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g),w=resolve(t);if(S!==w&&!S.startsWith(`${w}/`))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},se,ce,ue,de,fe,me,ge,_e=null,ve=null,ye=null,Ce=null,we=new Set,Te=!1,De,je,Me,Pe=new Promise((e,t)=>{je=e,Me=t});function Ie(e){_e?.signal(e)}let Re=2e3,ze=null;function Be(){ze!==null&&clearTimeout(ze),ze=setTimeout(()=>{ze=null,ce.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let Ve=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),Ue=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||Ve.setRenamed(e,t)},We=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(Ve.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Ve.setDeleted(e)}},Ge=e=>{isSystemDoc(e)||isConfigDoc(e)||Ve.delete(e)};try{se=createContentFilter({projectDir:s,contentDir:t,onAfterRebuild:()=>{ce.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{ue.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let e=Ft?.pruneFileIndexNowExcluded()??0;e>0&&getLogger(`server-factory`).info({pruned:e},`[content-filter] pruned now-excluded entries from fileIndex`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] fileIndex prune failed after onAfterRebuild`)}}}),ce=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:se}),ue=new TagIndex({contentDir:t,contentFilter:se});try{ue.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}de={current:F},fe=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:de,contentRoot:L,backlinkIndex:ce,configHomedirOverride:k,getCurrentBranch:()=>It?.getLastKnownBranch()??null,resolveEmbed:ae,resolveSize:oe,getPrincipal:()=>Ce,onAgentCommit:()=>_e?.signal(`session-activity`),onDiskFlush:(e,t)=>_e?.emitDiskAck(e,t),onConfigRejected:(e,t)=>_e?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),me=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[fe.extension]});let B=me.shouldUnloadDocument.bind(me);me.shouldUnloadDocument=e=>{if((Te||we.has(e))&&B(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:B(e)},De=async e=>{we.add(e);try{await me.unloadDocument(e)}finally{we.delete(e)}},_e=new CC1Broadcaster(me),ve=new AgentFocusBroadcaster(me),ye=new AgentPresenceBroadcaster(me),ge=new AgentSessionManager(me);let q=createLiveDerivedIndexExtension({backlinkIndex:ce,tagIndex:ue,signalChannel:Ie});me.configuration.extensions.push(q),me.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,s=parseHocuspocusAuthToken(t),g=s?.expectedServerInstanceId;if(typeof g==`string`&&g.length>0&&g!==ee)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ee}`);let S=s?.expectedBranch,w=getActiveBranch();if(typeof S==`string`&&S.length>0&&S!==w)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${S}, server is on ${w}`);if(!s)return;let E=e.context;typeof s.principalId==`string`&&(Ce&&s.principalId===Ce.id?E.principalId=Ce.id:Ce?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Ce.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),me.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 g=e.requestHeaders,S=(g&&typeof g.get==`function`?g.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(S))throw Error(`config-doc admission requires loopback Host header (host=${S??`<absent>`}, doc=${e.documentName})`)}});let J=resolve(t);function Y(e){if(!isSafeDocName(e))return null;let t=resolve(J,`${e}${getDocExtension(e)}`);return!t.startsWith(`${J}/`)&&t!==J?null:t}me.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:Ve,resolveFilePath:Y,fileExists:existsSync})}}),me.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 te=createApiExtension({hocuspocus:me,sessionManager:ge,contentDir:t,contentFilter:se,serverInstanceId:ee,getFileIndex:()=>Ft?Ft.getFileIndex():new Map,getFolderIndex:()=>Ft?Ft.getFolderIndex():new Map,getAliasMap:()=>Ft?Ft.getAliasMap():new Map,enableTestRoutes:j,shadowRef:de,flushGitCommit:()=>fe.flushPendingGitCommit(),flushContributors:()=>fe.flushContributors(),getCurrentBranch:()=>It?.getLastKnownBranch()??null,getDiskAckSVs:()=>_e?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:ce,tagIndex:ue,signalChannel:Ie,agentFocusBroadcaster:ve,agentPresenceBroadcaster:ye,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Lt,localOpCliArgs:H,projectDir:s,resolveEmbed:ae,getPrincipal:()=>Ce,forceUnloadDocument:De,ready:Pe,recentlyRemovedDocs:Ve});me.configuration.extensions.push(te),me.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:de,contentRoot:L,getCurrentBranch:()=>It?.getLastKnownBranch()??null,resolveEmbed:ae,resolveSize:oe}))}catch(e){throw releaseServerLock(te),e}let Ke=null,Xe=new Map,$e=[];function nt(e,t){let s=resolve(e,`rescue`),g=resolve(s,`${t}${getDocExtension(t)}`);return g.startsWith(`${s}/`)?g:null}function rt(e){let t=me.documents.get(e);if(!t)return null;let{frontmatter:s,body:g}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(s,g)}let it=(e,t)=>applyExternalChange(me,e,t,ae,oe),at=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of me.documents){if(isSystemDoc(s)||isConfigDoc(s))continue;let g=me.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,ae,s)},FILE_WATCHER_ORIGIN)}catch(t){J.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},st=null,vt=e=>{e&&(st===null&&(st=new Set,setImmediate(()=>{let e=st;if(st=null,e)try{for(let t of e)at(t)}catch(t){J.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),st.add(e))};function Tt(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 Et(e){try{switch(e.kind){case`create`:J.info({docName:e.docName},`[reconcile] create: ${e.docName}`),ce.updateDocumentFromMarkdown(e.docName,e.content),Be(),ue.updateDocumentFromMarkdown(e.docName,e.content),Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`),Ge(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=me.documents.get(t);if(!g){ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`);return}let S=getReconciledBase(t)??``,w=rt(t)??S,E=reconcile({docName:t,base:S,ours:w,theirs:s}),D=contentHash(S).slice(0,6),O=contentHash(w).slice(0,6),k=contentHash(s).slice(0,6);switch(J.info({docName:t,base:D,ours:O,theirs:k,result:E.kind},`[reconcile] ${t} base=${D} ours=${O} theirs=${k} result=${E.kind}`),E.kind){case`noop`:ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`);break;case`clean`:try{it(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`merged`:try{it(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`conflicts`:try{it(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`refused`:{incrementConflict();let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,E.reason);break}}break}case`delete`:{let{docName:t}=e,s=me.documents.get(t);if(!s){ce.deleteDocument(t),Be(),ue.deleteDocument(t),Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`),We(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=rt(t)??``,w=S!==g;if(w&&de.current){let e=de.current,s=It?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,L??``,{kind:`external-change-rescue`,docName:t,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:s,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),J.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{J.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),ce.deleteDocument(t),Be(),ue.deleteDocument(t),J.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),me.closeConnections(t),await De(s),Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`),We(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:g}=e,S=me.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),ce.renameDocument(t,s,g),Be(),ue.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}J.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`),Ue(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=me.documents.get(t);if(!s)return;let g=s.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),J.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ne.add(e.relativePath),Ie(`files`),vt(basename(e.relativePath));break;case`asset-delete`:ne.remove(e.relativePath),Ie(`files`),vt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:Ie(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Tt(e);J.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let Dt=[];async function jt(e){if(isBatchInProgress()){Dt.push(e);return}await Et(e)}async function Mt(){let e=Dt.splice(0,Dt.length);for(let t of e)await Et(t)}let Ft=null,It=null,Lt=null,Rt=null;async function zt(e){if(me.documents.size===0)return;let t=!1,s=new Promise(e=>{me.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(me.documents.keys());me.closeConnections(),me.flushPendingStores();for(let e of me.documents.values())e.getConnectionsCount()===0&&me.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 S,w=new Promise((s,w)=>{S=setTimeout(()=>{t=!0;let s=Array.from(me.documents.keys()),S=[],E=[];if(de.current){for(let e of s)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=rt(e);if(t===null){J.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=nt(de.current.gitDir,e);if(!s){J.warn({docName:e,gitDir:de.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),E.push(e);continue}mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,t,`utf-8`),incrementRescueBuffer(),S.push(e),J.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),J.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else J.warn({stillLoadedCount:s.length},`[rescue] shadow repo unavailable at flush timeout — ${s.length} doc(s) will be lost: [${s.join(`, `)}]`),E.push(...s);let D=S.length>0||E.length>0?` — rescued [${S.join(`, `)}]${E.length>0?`, lost [${E.join(`, `)}]`:``}`:``;w(Error(`flushAllStoresAndWait timeout after ${e}ms — ${s.length}/${g.length} docs did not unload: [${s.join(`, `)}]${D}`))},e)});try{await Promise.race([s,w])}finally{S!==void 0&&clearTimeout(S)}}async function Bt(){return Rt||(Rt=(async()=>{let e=Date.now(),t=[];Te=!0,ze!==null&&(clearTimeout(ze),ze=null);let g,S=await Promise.race([Pe.then(()=>`completed`,e=>(J.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&J.warn({},`[server] init did not complete within 5s during shutdown`);let w=me.documents.size;try{try{try{It&&=(await It.unsubscribe(),null),Ft&&=(await Ft.unsubscribe(),null);for(let{docName:e,cleanup:t}of $e)try{await t()}catch(t){J.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}$e.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{_e?.destroy(),ye?.destroy(),Ke&&=(await Ke.disconnect(),null);for(let[e,t]of Xe)try{await t.disconnect()}catch(t){J.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Xe.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ge.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await zt(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await fe.flushPendingGitCommit(),await fe.waitForPendingCommits()})(),new Promise((t,s)=>{e=setTimeout(()=>s(Error(`L2 git flush timeout`)),B)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Lt&&=(await Lt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(de.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(de.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(de.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?J.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):J.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(te)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),J.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)})}}})(),Rt)}let Vt=[];async function Ht(){try{Ce=await loadPrincipal(s),J.info({principalId:Ce.id},`[server] principal loaded`)}catch(e){J.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!de.current)try{de.current=await initShadowRepo(s),J.info({gitDir:de.current.gitDir},`[server] history repo initialized at ${de.current.gitDir}`)}catch(e){J.error({err:e},`[server] history repo init failed`),Vt.push(`shadow-repo`)}if(de.current){let e=null;try{e=loadRenameLogIndex(de.current.gitDir),sweepLazyPopOrphans(de.current.gitDir,e),setRenameLogIndex(de.current.gitDir,e),J.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){J.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(de.current,e,{rebuild:!0}),new Promise((e,s)=>setTimeout(()=>s(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){J.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(de.current)try{await shadowGit(de.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`)){J.warn({},`[server] history repo appears corrupted — reinitializing`);try{de.current=await initShadowRepo(s)}catch(e){J.error({err:e},`[server] history repo reinit failed`),de.current=void 0,Vt.includes(`shadow-repo`)||Vt.push(`shadow-repo`)}}else J.error({err:e},`[server] history repo check failed (transient?)`)}if(de.current)try{let e=resolve(de.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let g=null;try{g=(await esm_default({baseDir:s,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(g!==null){if(g!==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{}J.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(de.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){J.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else J.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){J.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){J.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;J.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){J.error({err:e},`[server] managed rename recovery failed`),Vt.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(s);(e.deleted>0||e.errors>0)&&J.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){J.error({err:e},`[server] upload-tempfile sweep failed`),Vt.push(`upload-tempfile-sweep`)}try{Ke=await me.openDirectConnection(SYSTEM_DOC_NAME),_e?.emitServerInfo(ee,getActiveBranch())}catch(e){J.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Vt.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await me.openDirectConnection(e);Xe.set(e,t)}catch(t){J.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Vt.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,k)]]);for(let t of CONFIG_DOC_NAMES){let s=e.get(t);if(s)try{J.info({docName:t,path:s},`[config-file-watcher] starting`);let e=await startConfigFileWatcher(s,e=>{let s=me.documents.get(t);J.info({docName:t,hasDocument:s!==void 0,contentLength:e.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,t,e,fe.configPersistenceCtx);if(J.info({docName:t,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),t===`__config__/project`||t===`__local__/project`){let e=Y();Lt?.setEnabled(e).catch(t=>{J.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});$e.push({docName:t,cleanup:e}),J.info({docName:t,path:s},`[config-file-watcher] started`)}catch(e){J.warn({err:e,docName:t,path:s},`[config-file-watcher] failed to start for ${t}`),Vt.push(`config-file-watcher:${t}`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=J;S.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore`);let w=await startMultiPathConfigFileWatcher([e,g],(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(me.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,fe.configPersistenceCtx);S.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){S.error({err:e,changedPath:relative(s,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let w=await se.rebuildIgnorePatterns();if(w.ok)S.info({changedPath:relative(s,t),patternCount:w.patternCount,nestedFileCount:w.nestedFileCount,durationMs:w.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),_e?.signal(`files`);else{let e=relative(s,t)||`.`;S.warn({changedPath:e,error:w.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),_e?.emitConfigIgnoreNestedError(e,w.error.message)}})().catch(e=>{S.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});$e.push({docName:`__ignore-files__`,cleanup:w}),S.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`)}catch(e){J.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Vt.push(`ignore-files-watcher`)}let g=resolveGitDir(s),S=g?readBranchFromHead(g)??`main`:`main`;switchReconciledBaseScope(S),ce.switchBranch(S);try{{let e=getActiveBranch();try{if(await ce.loadFromDisk(e)){let t=await ce.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&J.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await ce.rebuildFromDisk(e);ce.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){J.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Ft=await startWatcher(t,jt,se),ue.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:se,basenameIndex:ne,onSkip:(t,s,g)=>{e++,J.warn({reason:t,code:s,path:g},`[basename-index] skipped entry during seed (${t}${s?` ${s}`:``})`)}}),e>0&&(J.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Vt.push(`basename-index-partial`))}catch(e){J.error({err:e},`[basename-index] startup seed failed`),Vt.push(`basename-index`)}}catch(e){J.error({err:e},`[server] disk bridge watcher failed to start`),Vt.push(`file-watcher`)}try{It=await startHeadWatcher(s,async({trigger:e})=>{if(J.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),me.flushPendingStores(),await fe.flushPendingGitCommit(),setBatchInProgress(!0),de.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of me.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let s=null;if(t.transact(()=>{s=rt(e)},PARK_SNAPSHOT_ORIGIN),s===null)continue;let g=getReconciledBase(e)??s;S.push({docName:e,markdown:s,diskSnapshot:g})}if(S.length>0)try{let t=await parkBranch(de.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),J.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){J.error({err:e},`[shadow] park failed`)}}},async e=>{let s=Dt.length,g=e.newBranch??`main`;if(J.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`)setBatchInProgress(!1),await Mt(),await fe.flushDeferredStores(`within-branch`);else{incrementBranchSwitch(),Dt.splice(0,Dt.length),switchReconciledBaseScope(g),ze!==null&&(clearTimeout(ze),ze=null),ce.switchBranch(g),se.rebuildDirCount();try{let e=0;ne.clear(),seedBasenameIndex({contentDir:t,contentFilter:se,basenameIndex:ne,onSkip:(t,s,S)=>{e++,J.warn({reason:t,code:s,path:S,branch:g},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(J.warn({count:e,branch:g},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Vt.includes(`basename-index-partial`)||Vt.push(`basename-index-partial`))}catch(e){J.error({err:e,branch:g},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of me.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let S=safeContentPath(e,t);if(!existsSync(S)){let t=getReconciledBase(e)??``,S=rt(e)??``;if(S!==t&&de.current){let t=de.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:g,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),J.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{J.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),J.info({docName:e,branch:g},`[branch-switch] tombstone: ${e} (not on ${g})`);continue}let w=readFileSync(S,`utf-8`);it(e,w),setReconciledBase(e,w),J.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){J.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}J.info({branch:g,docCount:me.documents.size},`[branch-switch] loaded branch ${g} (${me.documents.size} docs)`);try{if(await ce.loadFromDisk(g)){let e=await ce.reconcileWithDisk(g);(e.added>0||e.updated>0||e.deleted>0)&&J.info(e,`[backlinks] branch-switch reconcile for ${g}`)}else await ce.rebuildFromDisk(g);ce.saveToDisk(g).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${g}:`,e)})}catch(e){J.error({err:e,branch:g},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(ue.init(),de.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of me.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let s=await readParkedState(de.current,g,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let S=getReconciledBase(t);if(!S)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:S});switch(w.kind){case`merged`:case`clean`:it(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:it(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){J.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&J.info({count:e,branch:g},`[branch-switch] restored ${e} parked docs on ${g}`)}if(e.oldBranch?.startsWith(`detached-`)&&de.current)try{let t=shadowGit(de.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
2583
2583
  `))e&&await t.raw(`update-ref`,`-d`,e);J.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){J.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await fe.flushDeferredStores(`discard-stale`),_e?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&de.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(de.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),J.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){J.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){J.error({err:e},`[server] HEAD watcher failed to start`),Vt.push(`head-watcher`)}let w=H?.[0]??`open-knowledge`,E=[`-c`,`credential.helper=!${H&&H.length>1?H.join(` `):w} auth git-credential`];try{Lt=new SyncEngine({projectDir:s,contentDir:t,contentFilter:se,contentRoot:L,syncEnabled:Y(),credentialArgs:E,cc1Broadcaster:_e,setBatchInProgress:e=>{setBatchInProgress(e),e||fe.flushDeferredStores(`within-branch`).catch(e=>{J.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{J.info({state:e},`[sync] state → ${e}`)},onAutoDisable:async e=>{J.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||J.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 Lt.start()}catch(e){J.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Lt=null}Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`)}return Ht().then(je,Me),{hocuspocus:me,sessionManager:ge,cc1Broadcaster:_e,agentFocusBroadcaster:ve,agentPresenceBroadcaster:ye,contentFilter:se,basenameIndex:ne,serverInstanceId:ee,destroy:Bt,ready:Pe,degraded:Vt,lockDir:te,get syncEngine(){return Lt}}}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 g=resolve(e,t);try{existsSync(g)&&statSync(g).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),g={"ok.worktree.kind":t};return s!==null&&(g[`ok.worktree.gitdir`]=normalizeFsPath(s)),withSpan(`ok.boot`,{attributes:g},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-D7DXNVql-B5nINglj.mjs`).then(e=>e.a),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.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 L=findLegacyRuntimeFiles(F);L.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${L.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let B=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:E,skipStateManifestCheck:e.skipStateManifestCheck}),{hocuspocus:H,destroy:q,ready:J,degraded:Y,lockDir:ee,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:ae}=B,oe=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),se=e.port??0,ce=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${oe}:${se}`,log:S}),ue=D();ue.headersTimeout=3e4,ue.requestTimeout=6e4;let de=e.serveContentAssets?createAssetServeMiddleware({contentFilter:B.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,fe=mountMcpAndApi({httpServer:ue,hocuspocus:H,mcpHttpHandler:ce,log:S,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:ae,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:de}),me=null;g!==null&&(me=attachIdleShutdown({httpServer:ue,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await q()})})),await new Promise((t,s)=>{let g=e=>s(e);ue.once(`error`,g),ue.listen(e.port,e.host,()=>{ue.removeListener(`error`,g),t()})});let ge=ue.address(),_e=typeof ge==`object`&&ge?ge.port:e.port??0;if(se=_e,O(ee,_e),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ee,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let ve=!1,ye=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};return{httpServer:ue,destroy:async()=>{if(ve)return;ve=!0;let e=[],t=async(t,s)=>{try{await ye(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{me?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>fe.shutdown()),await t(`mcpHttpHandler.close`,()=>ce.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{fe.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{ue.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ue.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>q()),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},lockDir:ee,contentDir:e.contentDir,port:_e,ready:J,degraded:Y,didAutoInit:k,serverInstance:B}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const ANCESTOR_WALK_DEPTH_LIMIT$1=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT$1;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const ANCESTOR_WALK_DEPTH_LIMIT=30,OK_CONFIG_MARKER=`.ok/config.yml`;function findEnclosingProjectRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,OK_CONFIG_MARKER))}catch{e=!1}if(e)return{rootPath:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,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`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};console.log(`[project-git] detected partial .git/ — running git init to repair`),S=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let w=``;try{w=(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(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,w);return S?(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),g=0;g<32;g+=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 g=dirname(t);if(g===t)return;t=g}}export{applySeed as $,runAuthReposSubprocess as $n,incrementCollabSocketFilteredError as $t,MissingOkConfigError as A,readServerPackageVersion as An,updateUiLockPort as Ar,createServer$1 as At,STARTER_FOLDER_FRONTMATTER_FILENAME as B,registerWrite as Bn,McpServer as Br,findEnclosingGitRoot as Bt,LOG_MD_TEMPLATE as C,parseHocuspocusAuthToken as Cn,tracedRenameSync as Cr,createContentFilter as Ct,MCP_SERVER_NAME as D,planSeed as Dn,tracedWriteFile as Dr,createMcpHttpHandler as Dt,MCP_CONNECTION_ID_HEADER as E,planPersonalTemplates as En,tracedUnlinkSync as Er,createLiveDerivedIndexExtension as Et,ProjectGitInitError as F,readUiLock as Fn,withSpanSync as Fr,detectProjectShape as Ft,SeedPrerequisiteError as G,resolveContentDir as Gn,isJSONRPCResultResponse as Gr,getCurrentMcpLogger as Gt,STARTER_PACK_IDS as H,removeLastKnownHash as Hn,LATEST_PROTOCOL_VERSION as Hr,formatAuthRejectionWire as Ht,ROLLBACK_ORIGIN as I,reconcile as In,writePersonalTemplates as Ir,ensureProjectGit as It,TagIndex as J,resolveLockDir as Jn,writeConfigPatch as Jr,getMeter as Jt,SeedRootDirError as K,resolveCursorBinaryDefault as Kn,readConfigSafely as Kr,getLocalDir as Kt,SERVICE_WRITER as L,recordContributor as Ln,writeStateManifest as Lr,errorResponse as Lt,PERSONAL_TEMPLATES as M,readStateManifest as Mn,validateCloneInputs as Mr,createStreamingErrorWriter as Mt,PERSONAL_TEMPLATE_NAMES as N,readTargetRecordedAt as Nn,validateSkillZip as Nr,createTestLogger as Nt,MISSING_OK_CONFIG_MESSAGE as O,readAllTargets as On,tracedWriteFileSync as Or,createOsProbe as Ot,PinoLogger as P,readTargetVersion as Pn,withSpan as Pr,detectClaudeDesktopPresence as Pt,applyExternalChange as Q,rewriteWikiLinksForDocumentRename as Qn,handleSpawnCursor as Qt,SKILL_INSTALL_EVENTS_FILE_REL as R,recordSkillInstallEvent as Rn,writeTargetVersion as Rr,evictStaleTrackerEntries as Rt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as S,parseAuthRejectionWire as Sn,tracedRename as Sr,createAssetServeMiddleware as St,MAX_AGENT_SESSIONS as T,pathToDocName as Tn,tracedRmdirSync as Tr,createExternalChangeHandler as Tt,STARTER_TEMPLATES as U,resetMetrics as Un,isInitializedNotification as Ur,formatContributors as Ut,STARTER_PACKS as V,releaseUiLock as Vn,JSONRPCMessageSchema as Vr,findEnclosingProjectRoot as Vt,STATE_MANIFEST_FILENAME as W,resolveBundledSkillDir as Wn,isJSONRPCRequest as Wr,gcCheckpointRefs as Wt,acquireUiLock as X,resolvePackageVersion as Xn,MalformedGitPointerError as Xr,getTracer as Xt,UiLockCollisionError as Y,resolvePack as Yn,GitDirAccessError as Yr,getMetrics as Yt,applyAgentMarkdownWrite as Z,rewriteMarkdownLinksForDocumentRename as Zn,handleCollabSocketError as Zt,GIT_UPSTREAM_WRITER as _,listStarterPacks as _n,toBroadcasterKey as _r,commitWipFromTree as _t,AgentPresenceBroadcaster as a,isAllowedApiOrigin as an,safeSubdir as ar,buildExecResult as at,HocuspocusAuthTokenSchema as b,mountMcpAndApi as bn,tracedMkdir as br,contributorCount as bt,BacklinkIndex as c,isHocuspocusAuthRejectionReason as cn,saveInMemoryCheckpoint as cr,buildSkillZip as ct,CURSOR_BUNDLE_PATHS_BY_PLATFORM as d,isPairedWriteOrigin as dn,setActiveSpanAttributes as dr,classifyEvents as dt,incrementServerObserverFire as en,runAuthStatusSubprocess as er,assertCompatibleStateManifest as et,ConfigSchema as f,isPathWithinDir as fn,shadowGit as fr,classifyFsPath as ft,FILE_WATCHER_ORIGIN as g,listRescueCheckpoints as gn,streamingProblemEvent as gr,commitWip as gt,FILE_SYSTEM_WRITER as h,lastKnownHash as hn,startWatcher as hr,commitUpstreamImport as ht,AgentFocusBroadcaster as i,installUserSkill as in,safeContentPath as ir,buildAndOpenSkill as it,OBSERVER_SYNC_ORIGIN as j,readSkillInstallStateSnapshot as jn,validateAgentId as jr,createServerObserverExtension as jt,McpLogger as k,readBranchFromHead as kn,updateLastKnownHash as kr,createPersistenceExtension as kt,CC1Broadcaster as l,isKnownPackId as ln,saveVersion as lr,buildStarterFolderFrontmatterYaml as lt,DEFAULT_PACK_ID as m,isSystemDoc as mn,splitMarkdownBlocks as mr,coercePackId as mt,AGENT_ID_RE as n,initTelemetry as nn,runDeviceFlowSubprocess as nr,attachIdleShutdown as nt,AgentSessionCapacityError as o,isAllowedWorkspaceHostHeader as on,safetyCheckpoint as or,buildInstructions as ot,DEFAULT_CHECKPOINT_RETENTION as p,isSelfWrite as pn,shutdownTelemetry as pr,clearContributors as pt,StateManifestError as q,resolveCursorSpawnInvocation as qn,resolveConfigPath as qr,getLogger as qt,AGENT_WRITE_ORIGIN as r,installTestLoggers as rn,runWithMcpLogger as rr,bootServer as rt,AgentSessionManager as s,isConfigDoc as sn,sanitizeClientName as sr,buildReadResult as st,AGENT_ID_MAX_LEN as t,initShadowRepo as tn,runCloneSubprocess as tr,assertNeverDiskEvent as tt,CONFLICT_MARKER_RE as u,isLoopbackAddress as un,seedBasenameIndex as ur,buildWipTree as ut,HOCUSPOCUS_AUTH_REJECTION_REASONS as v,loadPrincipal as vn,tracedAppendFileSync as vr,containsConflictMarkers as vt,MANAGED_RENAME_ORIGIN as w,parseKeepaliveConnectionId as wn,tracedRmSync as wr,createContentFilterAsync as wt,INSTALLED_AGENTS_SCHEMES as x,normalizeFsPath as xn,tracedMkdirSync as xr,createApiExtension as xt,HocuspocusAuthRejection as y,loggerFactory as yn,tracedLinkSync as yr,contentHash as yt,STARTER_FOLDERS as z,registerAllTools as zn,writeTracker as zr,extractWikiLinksFromMarkdown as zt};
2584
- //# sourceMappingURL=dist-BYmxMXZg.mjs.map
2584
+ //# sourceMappingURL=dist-BNcUlEj1.mjs.map
@@ -1 +1 @@
1
- import{Bn as e,Ct as t,Ft as n,Lt as r,Rn as i,Sn as a,k as o}from"./dist-B74wAiOa.mjs";import{_ as s,a as c,c as l,d as u,f as d,g as f,i as p,l as m,m as h,n as g,o as _,p as v,r as y,s as b,t as x,u as S}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{$ as C,$n as w,$t as T,A as E,An as D,Ar as O,At as k,B as A,Bn as j,Bt as M,C as N,Cn as P,Cr as F,Ct as I,D as L,Dn as R,Dr as z,Dt as B,E as V,En as H,Er as U,Et as W,F as G,Fn as K,Fr as q,Ft as J,G as Y,Gn as X,Gt as Z,H as Q,Hn as $,Ht as ee,I as te,In as ne,Ir as re,It as ie,J as ae,Jn as oe,Jt as se,K as ce,Kn as le,Kt as ue,L as de,Ln as fe,Lr as pe,Lt as me,M as he,Mn as ge,Mr as _e,Mt as ve,N as ye,Nn as be,Nr as xe,Nt as Se,O as Ce,On as we,Or as Te,Ot as Ee,P as De,Pn as Oe,Pr as ke,Pt as Ae,Q as je,Qn as Me,Qt as Ne,R as Pe,Rn as Fe,Rr as Ie,Rt as Le,S as Re,Sn as ze,Sr as Be,St as Ve,T as He,Tn as Ue,Tr as We,Tt as Ge,U as Ke,Un as qe,Ut as Je,V as Ye,Vn as Xe,Vt as Ze,W as Qe,Wn as $e,Wt as et,X as tt,Xn as nt,Xr as rt,Xt as it,Y as at,Yn as ot,Yr as st,Yt as ct,Z as lt,Zn as ut,Zt as dt,_ as ft,_n as pt,_r as mt,_t as ht,a as gt,an as _t,ar as vt,at as yt,b as bt,bn as xt,br as St,bt as Ct,c as wt,cn as Tt,cr as Et,ct as Dt,d as Ot,dn as kt,dr as At,dt as jt,en as Mt,er as Nt,et as Pt,f as Ft,fn as It,fr as Lt,ft as Rt,g as zt,gn as Bt,gr as Vt,gt as Ht,h as Ut,hn as Wt,hr as Gt,ht as Kt,i as qt,in as Jt,ir as Yt,it as Xt,j as Zt,jn as Qt,jr as $t,jt as en,k as tn,kn as nn,kr as rn,kt as an,l as on,ln as sn,lr as cn,lt as ln,m as un,mn as dn,mr as fn,mt as pn,n as mn,nn as hn,nr as gn,nt as _n,o as vn,on as yn,or as bn,ot as xn,p as Sn,pn as Cn,pr as wn,pt as Tn,q as En,qn as Dn,qt as On,r as kn,rn as An,rr as jn,rt as Mn,s as Nn,sn as Pn,sr as Fn,st as In,t as Ln,tn as Rn,tr as zn,tt as Bn,u as Vn,un as Hn,ur as Un,ut as Wn,v as Gn,vn as Kn,vr as qn,vt as Jn,w as Yn,wn as Xn,wr as Zn,wt as Qn,x as $n,xn as er,xr as tr,xt as nr,y as rr,yn as ir,yr as ar,yt as or,z as sr,zn as cr,zr as lr,zt as ur}from"./dist-BYmxMXZg.mjs";export{Ln as AGENT_ID_MAX_LEN,mn as AGENT_ID_RE,kn as AGENT_WRITE_ORIGIN,qt as AgentFocusBroadcaster,gt as AgentPresenceBroadcaster,vn as AgentSessionCapacityError,Nn as AgentSessionManager,wt as BacklinkIndex,on as CC1Broadcaster,o as CC1_CONTRACT_VERSION,Vn as CONFLICT_MARKER_RE,Ot as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Ft as ConfigSchema,Sn as DEFAULT_CHECKPOINT_RETENTION,un as DEFAULT_PACK_ID,Ut as FILE_SYSTEM_WRITER,zt as FILE_WATCHER_ORIGIN,ft as GIT_UPSTREAM_WRITER,st as GitDirAccessError,Gn as HOCUSPOCUS_AUTH_REJECTION_REASONS,rr as HocuspocusAuthRejection,bt as HocuspocusAuthTokenSchema,$n as INSTALLED_AGENTS_SCHEMES,Re as LIVE_DERIVED_INDEX_DEBOUNCE_MS,N as LOG_MD_TEMPLATE,Yn as MANAGED_RENAME_ORIGIN,He as MAX_AGENT_SESSIONS,V as MCP_CONNECTION_ID_HEADER,L as MCP_SERVER_NAME,Ce as MISSING_OK_CONFIG_MESSAGE,rt as MalformedGitPointerError,tn as McpLogger,E as MissingOkConfigError,Zt as OBSERVER_SYNC_ORIGIN,t as ORPHAN_MODES,he as PERSONAL_TEMPLATES,ye as PERSONAL_TEMPLATE_NAMES,De as PinoLogger,x as ProcessLockCollisionError,G as ProjectGitInitError,te as ROLLBACK_ORIGIN,g as RUNTIME_VERSION,de as SERVICE_WRITER,Pe as SKILL_INSTALL_EVENTS_FILE_REL,n as SKILL_STATE_TARGETS,sr as STARTER_FOLDERS,A as STARTER_FOLDER_FRONTMATTER_FILENAME,Ye as STARTER_PACKS,Q as STARTER_PACK_IDS,Ke as STARTER_TEMPLATES,Qe as STATE_MANIFEST_FILENAME,y as STATE_SCHEMA_VERSION,r as SYSTEM_DOC_NAME,Y as SeedPrerequisiteError,ce as SeedRootDirError,p as ServerLockCollisionError,En as StateManifestError,ae as TagIndex,at as UiLockCollisionError,c as acquireProcessLock,_ as acquireServerLock,tt as acquireUiLock,lt as applyAgentMarkdownWrite,je as applyExternalChange,C as applySeed,Pt as assertCompatibleStateManifest,Bn as assertNeverDiskEvent,_n as attachIdleShutdown,Mn as bootServer,Xt as buildAndOpenSkill,yt as buildExecResult,xn as buildInstructions,In as buildReadResult,Dt as buildSkillZip,ln as buildStarterFolderFrontmatterYaml,Wn as buildWipTree,jt as classifyEvents,Rt as classifyFsPath,Tn as clearContributors,pn as coercePackId,a as colorFromSeed,Kt as commitUpstreamImport,Ht as commitWip,ht as commitWipFromTree,Jn as containsConflictMarkers,or as contentHash,Ct as contributorCount,nr as createApiExtension,Ve as createAssetServeMiddleware,I as createContentFilter,Qn as createContentFilterAsync,Ge as createExternalChangeHandler,W as createLiveDerivedIndexExtension,B as createMcpHttpHandler,Ee as createOsProbe,an as createPersistenceExtension,k as createServer,en as createServerObserverExtension,ve as createStreamingErrorWriter,Se as createTestLogger,Ae as detectClaudeDesktopPresence,J as detectProjectShape,ie as ensureProjectGit,me as errorResponse,Le as evictStaleTrackerEntries,ur as extractWikiLinksFromMarkdown,M as findEnclosingGitRoot,Ze as findEnclosingProjectRoot,ee as formatAuthRejectionWire,Je as formatContributors,et as gcCheckpointRefs,Z as getCurrentMcpLogger,ue as getLocalDir,On as getLogger,se as getMeter,ct as getMetrics,it as getTracer,dt as handleCollabSocketError,Ne as handleSpawnCursor,i as iconFromClientName,T as incrementCollabSocketFilteredError,Mt as incrementServerObserverFire,Rn as initShadowRepo,hn as initTelemetry,An as installTestLoggers,Jt as installUserSkill,_t as isAllowedApiOrigin,yn as isAllowedWorkspaceHostHeader,Pn as isConfigDoc,Tt as isHocuspocusAuthRejectionReason,sn as isKnownPackId,Hn as isLoopbackAddress,e as isOrphanMode,kt as isPairedWriteOrigin,It as isPathWithinDir,b as isProcessAlive,Cn as isSelfWrite,dn as isSystemDoc,l as isValidLockPid,Wt as lastKnownHash,Bt as listRescueCheckpoints,pt as listStarterPacks,Kn as loadPrincipal,m as lockFilePath,ir as loggerFactory,xt as mountMcpAndApi,er as normalizeFsPath,ze as parseAuthRejectionWire,P as parseHocuspocusAuthToken,Xn as parseKeepaliveConnectionId,Ue as pathToDocName,H as planPersonalTemplates,R as planSeed,we as readAllTargets,nn as readBranchFromHead,S as readProcessLock,u as readProcessLockDetailed,d as readServerLock,D as readServerPackageVersion,Qt as readSkillInstallStateSnapshot,ge as readStateManifest,be as readTargetRecordedAt,Oe as readTargetVersion,K as readUiLock,ne as reconcile,fe as recordContributor,Fe as recordSkillInstallEvent,cr as registerAllTools,j as registerWrite,v as releaseProcessLock,h as releaseServerLock,Xe as releaseUiLock,$ as removeLastKnownHash,qe as resetMetrics,$e as resolveBundledSkillDir,X as resolveContentDir,le as resolveCursorBinaryDefault,Dn as resolveCursorSpawnInvocation,oe as resolveLockDir,ot as resolvePack,nt as resolvePackageVersion,ut as rewriteMarkdownLinksForDocumentRename,Me as rewriteWikiLinksForDocumentRename,w as runAuthReposSubprocess,Nt as runAuthStatusSubprocess,zn as runCloneSubprocess,gn as runDeviceFlowSubprocess,jn as runWithMcpLogger,Yt as safeContentPath,vt as safeSubdir,bn as safetyCheckpoint,Fn as sanitizeClientName,Et as saveInMemoryCheckpoint,cn as saveVersion,Un as seedBasenameIndex,At as setActiveSpanAttributes,Lt as shadowGit,wn as shutdownTelemetry,fn as splitMarkdownBlocks,Gt as startWatcher,Vt as streamingProblemEvent,mt as toBroadcasterKey,qn as tracedAppendFileSync,ar as tracedLinkSync,St as tracedMkdir,tr as tracedMkdirSync,Be as tracedRename,F as tracedRenameSync,Zn as tracedRmSync,We as tracedRmdirSync,U as tracedUnlinkSync,z as tracedWriteFile,Te as tracedWriteFileSync,rn as updateLastKnownHash,f as updateProcessLockPort,s as updateServerLockPort,O as updateUiLockPort,$t as validateAgentId,_e as validateCloneInputs,xe as validateSkillZip,ke as withSpan,q as withSpanSync,re as writePersonalTemplates,pe as writeStateManifest,Ie as writeTargetVersion,lr as writeTracker};
1
+ import{Bn as e,Ct as t,Ft as n,Lt as r,Rn as i,Sn as a,k as o}from"./dist-B74wAiOa.mjs";import{_ as s,a as c,c as l,d as u,f as d,g as f,i as p,l as m,m as h,n as g,o as _,p as v,r as y,s as b,t as x,u as S}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{$ as C,$n as w,$t as T,A as E,An as D,Ar as O,At as k,B as A,Bn as j,Bt as M,C as N,Cn as P,Cr as F,Ct as I,D as L,Dn as R,Dr as z,Dt as B,E as V,En as H,Er as U,Et as W,F as G,Fn as K,Fr as q,Ft as J,G as Y,Gn as X,Gt as Z,H as Q,Hn as $,Ht as ee,I as te,In as ne,Ir as re,It as ie,J as ae,Jn as oe,Jt as se,K as ce,Kn as le,Kt as ue,L as de,Ln as fe,Lr as pe,Lt as me,M as he,Mn as ge,Mr as _e,Mt as ve,N as ye,Nn as be,Nr as xe,Nt as Se,O as Ce,On as we,Or as Te,Ot as Ee,P as De,Pn as Oe,Pr as ke,Pt as Ae,Q as je,Qn as Me,Qt as Ne,R as Pe,Rn as Fe,Rr as Ie,Rt as Le,S as Re,Sn as ze,Sr as Be,St as Ve,T as He,Tn as Ue,Tr as We,Tt as Ge,U as Ke,Un as qe,Ut as Je,V as Ye,Vn as Xe,Vt as Ze,W as Qe,Wn as $e,Wt as et,X as tt,Xn as nt,Xr as rt,Xt as it,Y as at,Yn as ot,Yr as st,Yt as ct,Z as lt,Zn as ut,Zt as dt,_ as ft,_n as pt,_r as mt,_t as ht,a as gt,an as _t,ar as vt,at as yt,b as bt,bn as xt,br as St,bt as Ct,c as wt,cn as Tt,cr as Et,ct as Dt,d as Ot,dn as kt,dr as At,dt as jt,en as Mt,er as Nt,et as Pt,f as Ft,fn as It,fr as Lt,ft as Rt,g as zt,gn as Bt,gr as Vt,gt as Ht,h as Ut,hn as Wt,hr as Gt,ht as Kt,i as qt,in as Jt,ir as Yt,it as Xt,j as Zt,jn as Qt,jr as $t,jt as en,k as tn,kn as nn,kr as rn,kt as an,l as on,ln as sn,lr as cn,lt as ln,m as un,mn as dn,mr as fn,mt as pn,n as mn,nn as hn,nr as gn,nt as _n,o as vn,on as yn,or as bn,ot as xn,p as Sn,pn as Cn,pr as wn,pt as Tn,q as En,qn as Dn,qt as On,r as kn,rn as An,rr as jn,rt as Mn,s as Nn,sn as Pn,sr as Fn,st as In,t as Ln,tn as Rn,tr as zn,tt as Bn,u as Vn,un as Hn,ur as Un,ut as Wn,v as Gn,vn as Kn,vr as qn,vt as Jn,w as Yn,wn as Xn,wr as Zn,wt as Qn,x as $n,xn as er,xr as tr,xt as nr,y as rr,yn as ir,yr as ar,yt as or,z as sr,zn as cr,zr as lr,zt as ur}from"./dist-BNcUlEj1.mjs";export{Ln as AGENT_ID_MAX_LEN,mn as AGENT_ID_RE,kn as AGENT_WRITE_ORIGIN,qt as AgentFocusBroadcaster,gt as AgentPresenceBroadcaster,vn as AgentSessionCapacityError,Nn as AgentSessionManager,wt as BacklinkIndex,on as CC1Broadcaster,o as CC1_CONTRACT_VERSION,Vn as CONFLICT_MARKER_RE,Ot as CURSOR_BUNDLE_PATHS_BY_PLATFORM,Ft as ConfigSchema,Sn as DEFAULT_CHECKPOINT_RETENTION,un as DEFAULT_PACK_ID,Ut as FILE_SYSTEM_WRITER,zt as FILE_WATCHER_ORIGIN,ft as GIT_UPSTREAM_WRITER,st as GitDirAccessError,Gn as HOCUSPOCUS_AUTH_REJECTION_REASONS,rr as HocuspocusAuthRejection,bt as HocuspocusAuthTokenSchema,$n as INSTALLED_AGENTS_SCHEMES,Re as LIVE_DERIVED_INDEX_DEBOUNCE_MS,N as LOG_MD_TEMPLATE,Yn as MANAGED_RENAME_ORIGIN,He as MAX_AGENT_SESSIONS,V as MCP_CONNECTION_ID_HEADER,L as MCP_SERVER_NAME,Ce as MISSING_OK_CONFIG_MESSAGE,rt as MalformedGitPointerError,tn as McpLogger,E as MissingOkConfigError,Zt as OBSERVER_SYNC_ORIGIN,t as ORPHAN_MODES,he as PERSONAL_TEMPLATES,ye as PERSONAL_TEMPLATE_NAMES,De as PinoLogger,x as ProcessLockCollisionError,G as ProjectGitInitError,te as ROLLBACK_ORIGIN,g as RUNTIME_VERSION,de as SERVICE_WRITER,Pe as SKILL_INSTALL_EVENTS_FILE_REL,n as SKILL_STATE_TARGETS,sr as STARTER_FOLDERS,A as STARTER_FOLDER_FRONTMATTER_FILENAME,Ye as STARTER_PACKS,Q as STARTER_PACK_IDS,Ke as STARTER_TEMPLATES,Qe as STATE_MANIFEST_FILENAME,y as STATE_SCHEMA_VERSION,r as SYSTEM_DOC_NAME,Y as SeedPrerequisiteError,ce as SeedRootDirError,p as ServerLockCollisionError,En as StateManifestError,ae as TagIndex,at as UiLockCollisionError,c as acquireProcessLock,_ as acquireServerLock,tt as acquireUiLock,lt as applyAgentMarkdownWrite,je as applyExternalChange,C as applySeed,Pt as assertCompatibleStateManifest,Bn as assertNeverDiskEvent,_n as attachIdleShutdown,Mn as bootServer,Xt as buildAndOpenSkill,yt as buildExecResult,xn as buildInstructions,In as buildReadResult,Dt as buildSkillZip,ln as buildStarterFolderFrontmatterYaml,Wn as buildWipTree,jt as classifyEvents,Rt as classifyFsPath,Tn as clearContributors,pn as coercePackId,a as colorFromSeed,Kt as commitUpstreamImport,Ht as commitWip,ht as commitWipFromTree,Jn as containsConflictMarkers,or as contentHash,Ct as contributorCount,nr as createApiExtension,Ve as createAssetServeMiddleware,I as createContentFilter,Qn as createContentFilterAsync,Ge as createExternalChangeHandler,W as createLiveDerivedIndexExtension,B as createMcpHttpHandler,Ee as createOsProbe,an as createPersistenceExtension,k as createServer,en as createServerObserverExtension,ve as createStreamingErrorWriter,Se as createTestLogger,Ae as detectClaudeDesktopPresence,J as detectProjectShape,ie as ensureProjectGit,me as errorResponse,Le as evictStaleTrackerEntries,ur as extractWikiLinksFromMarkdown,M as findEnclosingGitRoot,Ze as findEnclosingProjectRoot,ee as formatAuthRejectionWire,Je as formatContributors,et as gcCheckpointRefs,Z as getCurrentMcpLogger,ue as getLocalDir,On as getLogger,se as getMeter,ct as getMetrics,it as getTracer,dt as handleCollabSocketError,Ne as handleSpawnCursor,i as iconFromClientName,T as incrementCollabSocketFilteredError,Mt as incrementServerObserverFire,Rn as initShadowRepo,hn as initTelemetry,An as installTestLoggers,Jt as installUserSkill,_t as isAllowedApiOrigin,yn as isAllowedWorkspaceHostHeader,Pn as isConfigDoc,Tt as isHocuspocusAuthRejectionReason,sn as isKnownPackId,Hn as isLoopbackAddress,e as isOrphanMode,kt as isPairedWriteOrigin,It as isPathWithinDir,b as isProcessAlive,Cn as isSelfWrite,dn as isSystemDoc,l as isValidLockPid,Wt as lastKnownHash,Bt as listRescueCheckpoints,pt as listStarterPacks,Kn as loadPrincipal,m as lockFilePath,ir as loggerFactory,xt as mountMcpAndApi,er as normalizeFsPath,ze as parseAuthRejectionWire,P as parseHocuspocusAuthToken,Xn as parseKeepaliveConnectionId,Ue as pathToDocName,H as planPersonalTemplates,R as planSeed,we as readAllTargets,nn as readBranchFromHead,S as readProcessLock,u as readProcessLockDetailed,d as readServerLock,D as readServerPackageVersion,Qt as readSkillInstallStateSnapshot,ge as readStateManifest,be as readTargetRecordedAt,Oe as readTargetVersion,K as readUiLock,ne as reconcile,fe as recordContributor,Fe as recordSkillInstallEvent,cr as registerAllTools,j as registerWrite,v as releaseProcessLock,h as releaseServerLock,Xe as releaseUiLock,$ as removeLastKnownHash,qe as resetMetrics,$e as resolveBundledSkillDir,X as resolveContentDir,le as resolveCursorBinaryDefault,Dn as resolveCursorSpawnInvocation,oe as resolveLockDir,ot as resolvePack,nt as resolvePackageVersion,ut as rewriteMarkdownLinksForDocumentRename,Me as rewriteWikiLinksForDocumentRename,w as runAuthReposSubprocess,Nt as runAuthStatusSubprocess,zn as runCloneSubprocess,gn as runDeviceFlowSubprocess,jn as runWithMcpLogger,Yt as safeContentPath,vt as safeSubdir,bn as safetyCheckpoint,Fn as sanitizeClientName,Et as saveInMemoryCheckpoint,cn as saveVersion,Un as seedBasenameIndex,At as setActiveSpanAttributes,Lt as shadowGit,wn as shutdownTelemetry,fn as splitMarkdownBlocks,Gt as startWatcher,Vt as streamingProblemEvent,mt as toBroadcasterKey,qn as tracedAppendFileSync,ar as tracedLinkSync,St as tracedMkdir,tr as tracedMkdirSync,Be as tracedRename,F as tracedRenameSync,Zn as tracedRmSync,We as tracedRmdirSync,U as tracedUnlinkSync,z as tracedWriteFile,Te as tracedWriteFileSync,rn as updateLastKnownHash,f as updateProcessLockPort,s as updateServerLockPort,O as updateUiLockPort,$t as validateAgentId,_e as validateCloneInputs,xe as validateSkillZip,ke as withSpan,q as withSpanSync,re as writePersonalTemplates,pe as writeStateManifest,Ie as writeTargetVersion,lr as writeTracker};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{c as e,d as t,f as n,i as r,l as i,m as a,p as o,t as s,u as c}from"./init-CYYdmMOG.mjs";import{n as l}from"./loader-CH-v-Qtm.mjs";import{n as u}from"./preview-SlVh3iib.mjs";import{t as d}from"./src-_ZBGqS72.mjs";export{c as ALL_EDITOR_IDS,t as EDITOR_LABELS,n as EDITOR_TARGETS,s as detectInstalledEditors,a as initContent,l as loadConfig,u as previewContent,r as readExistingMcpEntry,o as resolveProjectRoot,e as writeEditorMcpConfig,d as writeProjectAiIntegrations,i as writeUserMcpConfigs};
1
+ import{c as e,d as t,f as n,i as r,l as i,m as a,p as o,t as s,u as c}from"./init-BrWqVdft.mjs";import{n as l}from"./loader-_lQm3Y9F.mjs";import{n as u}from"./preview-C_pt82TJ.mjs";import{t as d}from"./src-BeG9DGuF.mjs";export{c as ALL_EDITOR_IDS,t as EDITOR_LABELS,n as EDITOR_TARGETS,s as detectInstalledEditors,a as initContent,l as loadConfig,u as previewContent,r as readExistingMcpEntry,o as resolveProjectRoot,e as writeEditorMcpConfig,d as writeProjectAiIntegrations,i as writeUserMcpConfigs};