@inkeep/open-knowledge 0.6.0-beta.21 → 0.6.0-beta.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +7 -4
- package/dist/cli.mjs +4 -4
- package/dist/constants-D-G-Sg9K.mjs +2 -0
- package/dist/{dist-DRLITAOV.mjs → dist-Dg6O3Q9A.mjs} +7 -7
- package/dist/{dist-BJWJRYPN.mjs → dist-wHpPmyBq.mjs} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/init-3sq3de7t.mjs +1 -0
- package/dist/{init-ODP7H2_D.mjs → init-zVplvoPG.mjs} +4 -4
- package/dist/{loader-WypjL6D-.mjs → loader-BZGdcbd-.mjs} +2 -2
- package/dist/loader-CaFjlmB7.mjs +1 -0
- package/dist/preview-BvtZ3joj.mjs +1 -0
- package/dist/{preview-DLoNOk0M.mjs → preview-Czwk2dja.mjs} +2 -2
- package/dist/public/assets/{index-D7awTFRW.js → index-D20xlk9K.js} +79 -79
- package/dist/public/index.html +1 -1
- package/dist/{repair-launch-json-55ssuDzZ.mjs → repair-launch-json-BHgVOnqI.mjs} +2 -2
- package/dist/{repair-mcp-configs-CIvcZke3.mjs → repair-mcp-configs-D1O4kw7y.mjs} +2 -2
- package/dist/{src-BtjvV77A.mjs → src-CfuREFd9.mjs} +2 -2
- package/dist/{start-DHqoq5kh.mjs → start-B61qdwvT.mjs} +2 -2
- package/dist/start-CbUZfK0T.mjs +1 -0
- package/package.json +1 -1
- package/dist/constants-BkjoNZLk.mjs +0 -2
- package/dist/init-Dfka2b6b.mjs +0 -1
- package/dist/loader-BlZXyEZs.mjs +0 -1
- package/dist/preview-CjUoxpAO.mjs +0 -1
- package/dist/start-BndZl5gJ.mjs +0 -1
|
@@ -2088,7 +2088,7 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
|
|
|
2088
2088
|
|
|
2089
2089
|
## Monthly
|
|
2090
2090
|
|
|
2091
|
-
- Run OK's \`links({ kind: "dead" })\` across the vault. Triage redlinks into new entities (gbrain creates dossiers), typo fixes (OK edits in place), or
|
|
2091
|
+
- Run OK's \`links({ kind: "dead" })\` across the vault. Triage redlinks into new entities (gbrain creates dossiers), typo fixes (OK edits in place), or removal (drop the link; a tracked task captures any future-doc intent).
|
|
2092
2092
|
|
|
2093
2093
|
`,STARTER_PACKS={"knowledge-base":{id:`knowledge-base`,name:`Knowledge base`,description:`Source-grounded canonical articles. Three layers (sources → research → articles) wired to the ingest / research / consolidate MCP tools.`,defaultSubfolder:`brain`,folders:KNOWLEDGE_BASE_FOLDERS,templates:KNOWLEDGE_BASE_TEMPLATES,rootFiles:{"log.md":KNOWLEDGE_BASE_LOG_MD}},"software-lifecycle":{id:`software-lifecycle`,name:`Software lifecycle`,description:`Proposals, decisions, specs, postmortems, guides. The doc lifecycle for an engineering team or OSS project.`,defaultSubfolder:`project-docs`,folders:SOFTWARE_LIFECYCLE_FOLDERS,templates:SOFTWARE_LIFECYCLE_TEMPLATES},"plain-notes":{id:`plain-notes`,name:`Plain notes`,description:`Just notes/ + daily/. The "I just want to write" escape hatch. No posture imposed, link freely.`,defaultSubfolder:void 0,folders:PLAIN_NOTES_FOLDERS,templates:PLAIN_NOTES_TEMPLATES},worldbuilding:{id:`worldbuilding`,name:`Worldbuilding`,description:`Encyclopedia for fiction: characters, settings, themes, factions, lore. The graph is the product; agent excels at auto-stub creation and dead-link sweeps.`,defaultSubfolder:`world`,folders:WORLDBUILDING_FOLDERS,templates:WORLDBUILDING_TEMPLATES},"writing-pipeline":{id:`writing-pipeline`,name:`Writing pipeline`,description:`Three-stage drafting flow: ideas → drafts → published. Lean by default; CRDT history covers per-file revisions.`,defaultSubfolder:`writing`,folders:WRITING_PIPELINE_FOLDERS,templates:WRITING_PIPELINE_TEMPLATES},gbrain:{id:`gbrain`,name:`Gbrain`,description:`Track people, companies, and meetings. Each gets a dossier with a rewritable summary and an append-only timeline. Inspired by Garry Tan's gbrain.`,defaultSubfolder:`vault`,folders:GBRAIN_FOLDERS,templates:GBRAIN_TEMPLATES,rootFiles:{"log.md":GBRAIN_LOG_MD,"USER.md":GBRAIN_USER_MD,"SOUL.md":GBRAIN_SOUL_MD,"ACCESS_POLICY.md":GBRAIN_ACCESS_POLICY_MD,"HEARTBEAT.md":GBRAIN_HEARTBEAT_MD}}},STARTER_PACK_IDS=Object.keys(STARTER_PACKS);function resolvePack(e){return e&&STARTER_PACKS[e]||STARTER_PACKS[DEFAULT_PACK_ID]}function isKnownPackId(e){return typeof e==`string`&&STARTER_PACK_IDS.includes(e)}function coercePackId(e){return isKnownPackId(e)?e:void 0}function deriveFolderSummary(e){let t=e.trim(),S=(/^([^.!?]+[.!?])/.exec(t)?.[1]??t).trim();return S.length<=140?S:`${S.slice(0,137)}…`}function listStarterPacks(){return STARTER_PACK_IDS.map(e=>{let t=STARTER_PACKS[e];return{id:t.id,name:t.name,description:t.description,defaultSubfolder:t.defaultSubfolder,folders:t.folders.map(e=>({path:e.path,summary:deriveFolderSummary(e.description)})),entryCounts:computePackEntryCounts(t)}})}function computePackEntryCounts(e){let t=e.folders.length,S=0;for(let t of e.folders)S+=1+(t.extraTemplates?.length??0);return S+=e.rootFiles?Object.keys(e.rootFiles).length:0,{files:S,folders:t}}const STARTER_FOLDERS=KNOWLEDGE_BASE_FOLDERS,STARTER_TEMPLATES=KNOWLEDGE_BASE_TEMPLATES,LOG_MD_TEMPLATE=KNOWLEDGE_BASE_LOG_MD,STARTER_FOLDER_FRONTMATTER_FILENAME=`frontmatter.yml`;function buildStarterFolderFrontmatterYaml(e){let t=[];t.push(`title: ${yamlScalar(e.title)}`),t.push(`description: ${yamlScalar(e.description)}`),t.push(`tags:`);for(let S of e.tags)t.push(` - ${yamlScalar(S)}`);return`${t.join(`
|
|
2094
2094
|
`)}\n`}function yamlScalar(e){return e===``?`""`:/[:#\n"'\\]|^\s|\s$/.test(e)?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e}function resolveFileContent(e,t){let S=/^([^/]+)\/\.ok\/frontmatter\.yml$/.exec(e);if(S){let e=t.folders.find(e=>e.path===S[1]);return e?buildStarterFolderFrontmatterYaml(e):void 0}let w=/^([^/]+)\/\.ok\/templates\/([^/]+)\.md$/.exec(e);if(w){let e=w[2]??``;return t.templates[e]}if(!e.includes(`/`)&&t.rootFiles?.[e]!==void 0)return t.rootFiles[e]}async function applySeed(e,t={}){let S=Date.now(),w=resolve(t.projectDir??process.cwd()),E=resolvePack(t.packId??`knowledge-base`),D=0,O=[],k=[];for(let t of e.created)try{let e=assertEntryPathInProject(w,t.path);k.push({entry:t,absPath:e})}catch(e){O.push({path:typeof t.path==`string`?t.path:String(t.path),error:e instanceof SeedRootDirError||e instanceof Error?e.message:String(e)})}for(let{entry:e,absPath:t}of k.filter(e=>e.entry.kind===`folder`))try{mkdirSync(t,{recursive:!0}),D+=1}catch(t){O.push({path:e.path,error:t instanceof Error?t.message:String(t)})}for(let{entry:e,absPath:t}of k.filter(e=>e.entry.kind===`file`)){let S=e.template??e.path,w=resolveFileContent(S,E);if(w===void 0){O.push({path:e.path,error:`No content template registered for template id "${S}" in pack "${E.id}"`});continue}if(!existsSync(t))try{writeFileSync(t,w,`utf-8`),D+=1}catch(t){O.push({path:e.path,error:t instanceof Error?t.message:String(t)})}}return{applied:D,errors:O,durationMs:Date.now()-S}}const ANCESTOR_WALK_DEPTH_LIMIT$1=30;function isProjectRoot(e){try{return statSync(resolve(e,OK_PROJECT_MARKER)).isFile()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function findEnclosingProjectRoot(e){let t=resolve(e),S=0;for(;S<ANCESTOR_WALK_DEPTH_LIMIT$1;){let e=!1;try{e=isProjectRoot(t)}catch{e=!1}if(e)return{rootPath:t,distance:S};let w=dirname(t);if(w===t)return null;t=w,S+=1}return null}function frontmatterTemplateId(e){return`${e}/.ok/frontmatter.yml`}function templateFileTemplateId(e,t){return`${e}/.ok/templates/${t}.md`}function normalizeRootDir(e,t){if(!e)return``;let S=e.trim();if(S===``||S===`.`||S===`./`)return``;if(S.startsWith(`/`))throw new SeedRootDirError(`rootDir must be relative to the project directory, got: ${e}`);let w=S.replace(/\\/g,`/`).replace(/^\.\//,``).replace(/\/+$/,``);if(w.split(`/`).some(e=>e===`..`))throw new SeedRootDirError(`rootDir must not contain '..' segments, got: ${e}`);return assertEntryPathInProject(t,w),w}function joinRelative(e,t){return e===``?t:`${e}/${t}`}async function planSeed(e={}){let t=resolve(e.projectDir??process.cwd());if(!isProjectRoot(t))throw new SeedPrerequisiteError(`No ${OK_PROJECT_MARKER} found at ${t}. Run \`ok init\` first to scaffold the tool config.`);let S=normalizeRootDir(e.rootDir,t),w=resolvePack(e.packId??`knowledge-base`),E=[],D=[],O=[];S!==``&&(existsSync(join(t,S))?D.push({path:S,reason:`already-exists`}):E.push({path:S,kind:`folder`}));for(let e of w.folders){let k=joinRelative(S,e.path);existsSync(join(t,k))?D.push({path:k,reason:`already-exists`}):E.push({path:k,kind:`folder`});let j=`${k}/.ok`;existsSync(join(t,j))?D.push({path:j,reason:`already-exists`}):E.push({path:j,kind:`folder`});let F=`${j}/${STARTER_FOLDER_FRONTMATTER_FILENAME}`;existsSync(join(t,F))?D.push({path:F,reason:`already-exists`}):E.push({path:F,kind:`file`,template:frontmatterTemplateId(e.path)});let L=`${j}/templates`;existsSync(join(t,L))?D.push({path:L,reason:`already-exists`}):E.push({path:L,kind:`folder`});let B=[e.starterTemplate,...e.extraTemplates??[]];for(let S of B){let k=`${L}/${S}.md`;if(existsSync(join(t,k))){D.push({path:k,reason:`already-exists`});continue}if(w.templates[S]===void 0){let t=S===e.starterTemplate;O.push(t?`No starter template body registered for "${S}" in pack "${w.id}". The folder will land without a pre-selected template.`:`No body registered for extra template "${S}" in pack "${w.id}". The folder will land without that optional variant.`);continue}E.push({path:k,kind:`file`,template:templateFileTemplateId(e.path,S)})}}if(w.rootFiles)for(let e of Object.keys(w.rootFiles)){let w=joinRelative(S,e);existsSync(join(t,w))?D.push({path:w,reason:`already-exists`}):E.push({path:w,kind:`file`,template:e})}return{created:E,skipped:D,warnings:O}}const log$3=getLogger(`suggest-links`),WORD_CHAR_RE=/[\p{L}\p{N}]/u,WIKI_LINK_RE=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,MD_LINK_RE=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y,MD_IMAGE_RE=/!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;var SuggestLinksTargetNotFoundError=class extends Error{constructor(e){super(`Document not found: ${e}`),this.name=`SuggestLinksTargetNotFoundError`}};function normalizeSnippet(e){return e.replace(/\s+/g,` `).trim()}function snippetAround(e,t,S){if(!normalizeSnippet(e))return null;let w=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
|
|
@@ -2112,7 +2112,7 @@ description: When the agent does scheduled work: daily briefings, end-of-day dos
|
|
|
2112
2112
|
`).map(e=>e.trim()).filter(Boolean),O=null;for(let e=D.length-1;e>=0;e--)try{O=JSON.parse(D[e]);break}catch{}O===null?successResponse(t,200,LocalOpAuthStatusSuccessSchema,{authenticated:!1},{handler:bc}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,O,{handler:bc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:bc,cause:e})}finally{we.release(pc)}},{handler:bc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:bc})}),Sc=`local-op-auth-repos`,Cc=withValidation(LocalOpAuthHostRequestSchema,wc,{handler:Sc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Sc})});async function wc(e,t,S){let w=S.host??`github.com`;if(!we.tryAcquire(mc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Sc,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let E=createStreamingErrorWriter(t,Sc),[D,...O]=ue,k=[...O,`auth`,`repos`,`--json`,`--host`,w],j=!1,F=``,L=spawn(D,k,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),B=setTimeout(()=>{L.kill(`SIGTERM`)},ic);L.stdout.on(`data`,e=>{F+=e.toString(`utf-8`);let S=F.split(`
|
|
2113
2113
|
`);F=S.pop()??``;for(let e of S){if(!e.trim())continue;let S=null;try{S=JSON.parse(e)}catch{}if(S&&S.type===`error`){E(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof S.message==`string`?S.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),L.stderr.on(`data`,e=>{log$2.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),L.on(`close`,e=>{clearTimeout(B),j||(j=!0,e!==0&&!t.writableEnded&&E(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),we.release(mc))}),L.on(`error`,e=>{clearTimeout(B),j||(j=!0,t.writableEnded||(E(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),we.release(mc))}),t.on(`close`,()=>{j||(j=!0,clearTimeout(B),L.kill(`SIGTERM`),we.release(mc))})}let Tc=`local-op-auth-signout`,Ec=withValidation(LocalOpAuthHostRequestSchema,async(e,t,S)=>{let w=S.host??`github.com`;if(!we.tryAcquire(hc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Tc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=ue,E=[...S,`auth`,`signout`,`--host`,w];await new Promise((t,S)=>{let w=spawn(e,E,{stdio:`ignore`,env:{...process.env}}),D=setTimeout(()=>{w.kill(`SIGTERM`)},3e4);w.on(`close`,()=>{clearTimeout(D),t()}),w.on(`error`,e=>{clearTimeout(D),S(e)})}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Tc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Tc,cause:e})}finally{we.release(hc)}},{handler:Tc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Tc})}),Dc=`local-op-auth-pat`,Oc=withValidation(LocalOpAuthPatRequestSchema,async(e,t,S)=>{let{pat:w,host:E}=S,D=E??`github.com`;if(!we.tryAcquire(gc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth pat operation is already in progress.`,{handler:Dc,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...S]=ue,E=[...S,`auth`,`pat`,`--json`,`--host`,D],O=(await new Promise((t,S)=>{let D=spawn(e,E,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),O=setTimeout(()=>{D.kill(`SIGTERM`)},3e4);D.stdin.write(`${w}\n`),D.stdin.end();let k=[];D.stdout.on(`data`,e=>k.push(e)),D.on(`close`,e=>{clearTimeout(O),e===0?t(Buffer.concat(k).toString(`utf-8`)):S(Error(`auth pat exited with code ${e}`))}),D.on(`error`,e=>{clearTimeout(O),S(e)})})).split(`
|
|
2114
2114
|
`).map(e=>e.trim()).filter(Boolean),k=null;for(let e=O.length-1;e>=0;e--)try{k=JSON.parse(O[e]);break}catch{}k===null?successResponse(t,200,LocalOpAuthPatSuccessSchema,{},{handler:Dc}):successResponse(t,200,LocalOpAuthPatSuccessSchema,k,{handler:Dc})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth pat failed.`,{handler:Dc,cause:e})}finally{we.release(gc)}},{handler:Dc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Dc})}),kc=`local-op-auth-identity`;async function Ac(e,t){if(checkLocalOpSecurity(e,t,{handler:kc})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:kc,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:kc});return}try{successResponse(t,200,LocalOpAuthIdentitySuccessSchema,{identity:await resolveGitIdentity(de)},{handler:kc})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Identity resolution failed.`,{handler:kc,cause:e})}}}let jc=`/api/local-op/auth/set-identity`,Mc=`local-op-auth-set-identity`,Nc=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,S)=>{let w=S.name.trim(),E=S.email.trim();if(!de){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Mc});return}if(!we.tryAcquire(jc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Mc,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(de,w,E),ce?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:Mc})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Mc,cause:e})}finally{we.release(jc)}},{handler:Mc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Mc})});async function Pc(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-status`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.();if(!e){successResponse(t,200,SyncStatusSchema,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),successResponse(t,200,SyncStatusSchema,e.getStatus(),{handler:`sync-status`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Fc=withValidation(SyncTriggerRequestSchema,async(e,t,S)=>{let w=ce?.();if(!w){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let E=S.op??`sync`;successResponse(t,202,SyncTriggerSuccessSchema,{op:E},{handler:`sync-trigger`}),w.trigger(E)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-trigger`})?ce?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Ic(e,t){if(checkLocalOpSecurity(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.();successResponse(t,200,SyncConflictsSuccessSchema,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Lc=withValidation(SyncResolveConflictRequestSchema,async(e,t,S)=>{let w=ce?.();if(!w){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:E,strategy:D,content:O}=S;try{await w.resolveConflict(E,D,O),successResponse(t,200,SyncResolveConflictSuccessSchema,{},{handler:`sync-resolve-conflict`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`sync-resolve-conflict`})?ce?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Rc(e,S){if(!checkLocalOpSecurity(e,S,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){errorResponse(S,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!de){errorResponse(S,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=w.searchParams.get(`file`);if(!E){errorResponse(S,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(E.includes(`..`)||E.startsWith(`/`)){errorResponse(S,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let D=stripDocExtension(E),O=t.documents.get(D)?.getMap(`lifecycle`).get(`status`)===`conflict`,k=ce?.(),j=k?k.getConflicts().some(e=>e.file===E):!1;if(!O&&!j){errorResponse(S,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:E}});return}let F=w.searchParams.get(`source`),L=esm_default({baseDir:de,timeout:{block:15e3}});async function B(e){try{return await L.raw([`show`,`:${e}:${E}`])}catch{return``}}try{let[e,w,D]=await Promise.all([B(1),B(2),B(3)]),O=w,k=null;if(F===`ytext`){let e=stripDocExtension(E),S=t.documents.get(e);if(S){let t=S.getMap(`lifecycle`).get(`status`);k=typeof t==`string`&&t.length>0?t:null;let w=Ce?Ce(e):null;w!==null&&!ytextHasConflictMarkers(w)?O=w:w!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}successResponse(S,200,SyncConflictContentSuccessSchema,{file:E,base:e,ours:O,theirs:D,lifecycleStatus:k},{handler:`sync-conflict-content`})}catch(e){errorResponse(S,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function zc(e,t){if(!checkLocalOpSecurity(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let S=new URL(e.url??`/`,`http://localhost`),E=S.searchParams.get(`rootDir`)??void 0,D=S.searchParams.get(`packId`),O=coercePackId(D);if(D!==null&&D!==``&&O===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${D}" is not registered.`});return}try{successResponse(t,200,SeedPlanSuccessSchema,{plan:await planSeed({projectDir:w,rootDir:E,packId:O})},{handler:`seed-plan`})}catch(e){if(e instanceof SeedPrerequisiteError){errorResponse(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SeedRootDirError){errorResponse(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Bc=withValidation(SeedApplyRequestSchema,async(e,t,S)=>{let E=S.plan;if(!E||typeof E!=`object`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let D=E,O=S.packId,k=coercePackId(O);if(typeof O==`string`&&O.length>0&&k===void 0){errorResponse(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${O}" is not registered.`});return}try{successResponse(t,200,SeedApplySuccessSchema,{result:await applySeed(D,{projectDir:w,packId:k})},{handler:`seed-apply`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`seed-apply`})});async function Vc(e,t){if(checkLocalOpSecurity(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}successResponse(t,200,SeedListPacksSuccessSchema,{packs:listStarterPacks()},{handler:`seed-packs`})}}let Hc=withValidation(InstallSkillRequestSchema,async(e,t,S)=>{if(S.out!==void 0&&!isSafeLocalPath(S.out)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{successResponse(t,200,InstallSkillSuccessSchema,await buildAndOpenSkill({...S.noOpen===void 0?{}:{noOpen:S.noOpen},...S.out===void 0?{}:{out:S.out}}),{handler:`install-skill`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`install-skill`})});async function Uc(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,ze.probeAll)}catch(e){t.headersSent||(log$2.error({err:e},`[installed-agents] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}async function Wc(e,t){if(!checkLocalOpSecurity(e,t,{handler:`sync-abort-merge`}))return;if(e.method!==`POST`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-abort-merge`,extraHeaders:{Allow:`POST`}});return}let S=ce?.();if(!S){errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-abort-merge`});return}try{await S.abortMerge(),successResponse(t,200,SyncAbortMergeSuccessSchema,{},{handler:`sync-abort-merge`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to abort merge.`,{handler:`sync-abort-merge`,cause:e})}}let Gc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!te){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:te.getAllTags()},{handler:`tags-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Kc(e,t,S){if(e.method!==`GET`){errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!te){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let w;try{w=decodeURIComponent(S)}catch{errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!w){errorResponse(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=te.getDocsForTagWithMatches(w).map(({docName:e,matchingTags:t})=>({docName:e,title:Ve(e),matchingTags:t,snippet:null}));successResponse(t,200,TagsForNameSuccessSchema,{name:w,docs:e},{handler:`tags-for-name`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function qc(e,t,S=`path`,E=`folder-config`){let D=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(D.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid ${S}: must be project-root-relative.`,{handler:E}),null;let O=resolve(w),k=D===``?O:resolve(O,D);return k!==O&&!k.startsWith(`${O}${sep}`)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:E}),null):{folderRel:D,resolvedContentDir:O}}let Jc=/^[A-Za-z0-9_-]+$/;function Yc(e,t,S=`template`){return!e||!Jc.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:S}),!1):!0}function Xc(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[S,w]of Object.entries(e))w!==void 0&&(t[S]=w);return t}async function Zc(e,t){if(e.method===`GET`)return Qc(e,t);if(e.method===`PUT`)return $c(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Qc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=qc(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!S)return;let w=await enrichDirectory(S.folderRel,{projectDir:S.resolvedContentDir}),E=resolve(S.resolvedContentDir,S.folderRel,`.ok`,`frontmatter.yml`),D=null;if(existsSync(E))try{let e=(0,import_dist$1.parse)(await readFile$1(E,`utf-8`));D=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${E}: ${t}`),D=null}successResponse(t,200,FolderConfigGetSuccessSchema,{folder:w,frontmatter_local:D},{handler:`folder-config-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),$c=withValidation(FolderConfigPutRequestSchema,async(e,t,S)=>{try{let e=qc(S.path,t,`path`,`folder-config-put`);if(!e)return;let w=e.folderRel===``?`**`:`${e.folderRel}/**`,E=applyNestedFolderRulesUpsert({projectDir:e.resolvedContentDir,rules:[{match:w,frontmatter:Xc(S.frontmatter)}]});if(!E.ok){let e=E.error.code===`WRITE_ERROR`||E.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:`Invalid folder config request.`,{handler:`folder-config-put`,detail:E.error.code,cause:Error(E.error.message)});return}successResponse(t,200,FolderConfigPutSuccessSchema,{applied:E.applied},{handler:`folder-config-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function nl(e,S,w,E){if(!S)return!1;let D=e===``?`.ok/templates/${S}`:`${e.replace(/\/$/,``)}/.ok/templates/${S}`,O=t.documents.get(D);return O&&isDocInConflict(O)?(respondDocInConflict(E,new DocInConflictError({file:`${D}.md`}),w),!0):!1}async function il(e,t){if(e.method===`GET`)return ll(e,t);if(e.method===`PUT`)return ul(e,t);if(e.method===`DELETE`)return dl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let al=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,cl=e=>{let t=e.match(al),S={},w=e;if(t){try{let e=(0,import_dist$1.parse)(t[1]??``);e&&typeof e==`object`&&!Array.isArray(e)&&(S=e)}catch{}w=e.slice(t[0].length)}return{frontmatter:S,body:w}},ll=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!Yc(w,t,`template-get`))return;let E=qc(S.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!E)return;let{folderRel:D,resolvedContentDir:O}=E,k=D===``?[]:D.split(`/`),j=null,F=null,L=null;for(let e=k.length;e>=0;e--){let t=e===0?``:k.slice(0,e).join(`/`),S=t===``?O:resolve(O,t);if(S!==O&&!S.startsWith(`${O}${sep}`))continue;let E=resolve(S,`.ok`,`templates`,`${w}.md`);if(existsSync(E)){j=E,F=t,L=e===k.length?`local`:`inherited`;break}}if(!j||F===null||L===null){errorResponse(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${w}" not found for folder "${D||`.`}". Walked leaf → root.`});return}let{frontmatter:B,body:H}=cl(await readFile$1(j,`utf-8`)),q=relative(O,j).split(/[\\/]/).filter(Boolean).join(`/`);successResponse(t,200,TemplateGetSuccessSchema,{template:{name:w,folder:F,scope:L,path:q,frontmatter:B,body:H}},{handler:`template-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),ul=withValidation(TemplatePutRequestSchema,async(e,t,S)=>{try{let e=S.name;if(!Yc(e,t,`template-put`))return;let w=qc(S.folder,t,`folder`,`template-put`);if(!w||nl(w.folderRel,e,`template-put`,t))return;let E=applyTemplateWrite({projectDir:w.resolvedContentDir,folder:w.folderRel,name:e,body:typeof S.body==`string`?S.body:``,frontmatter:Xc(S.frontmatter)});if(!E.ok){let e=E.error.code===`WRITE_ERROR`||E.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write template.`:`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}successResponse(t,200,TemplatePutSuccessSchema,{path:E.path,created:E.created,warnings:E.warnings},{handler:`template-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),dl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`name`)??``;if(!Yc(w,t,`template-delete`))return;let E=qc(S.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!E||nl(E.folderRel,w,`template-delete`,t))return;let D=applyTemplateDelete({projectDir:E.resolvedContentDir,folder:E.folderRel,name:w});if(!D.ok){let e=D.error.code===`WRITE_ERROR`||D.error.code===`UNLINK_FAILED`||D.error.code===`BAD_PROJECT_DIR`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:D.error.code,cause:Error(D.error.message)});return}successResponse(t,200,TemplateDeleteSuccessSchema,{existed:D.existed,path:D.path},{handler:`template-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0});function fl(e){let t=new Map;for(let S of e){let e=S.path.split(`/`).filter(Boolean);e.pop();for(let w=1;w<=e.length;w++){let E=e.slice(0,w).join(`/`);t.set(E,Math.max(t.get(E)??0,S.modifiedTs))}}return[...t.entries()].map(([e,t])=>createWorkspaceSearchDocument({kind:`folder`,path:e,modifiedTs:t}))}function pl(e,t){let S=t.trim().toLowerCase();if(!S||!e)return;let w=e.toLowerCase().indexOf(S);if(w<0)return;let E=Math.max(0,w-80),D=Math.min(e.length,w+S.length+120),O=E>0?`…`:``,k=D<e.length?`…`:``;return`${O}${e.slice(E,D).replace(/\s+/g,` `).trim()}${k}`}function ml(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function hl(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let S=t.filter(e=>e===`page`||e===`folder`||e===`content`);return S.length>0?S:void 0}async function gl(){let e=[];for(let[t,S]of D()){if(isSystemDoc(t)||isConfigDoc(t))continue;let w=``,E=t;try{w=await readFile$1(S.canonicalPath,`utf-8`),E=extractPageTitle(w,t)}catch(e){console.warn(`[search] Failed to index ${t}:`,e)}e.push(createWorkspaceSearchDocument({kind:`page`,path:t,title:E,content:w,modifiedTs:Date.parse(S.modified)}))}return[...e,...fl(e)]}function _l(){return[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}${t.modified}${t.size}${t.canonicalPath}${t.inode}${t.aliases.join(`,`)}`).join(``)}async function vl(){let e=`${w}${de??``}`,t=_l(),S=workspaceSearchCaches.get(e);if(S?.fingerprint===t&&S.corpus)return S.corpus;if(S?.fingerprint===t&&S.pending)return S.pending;let E=gl().then(e=>createWorkspaceSearchCorpus(e));workspaceSearchCaches.set(e,{fingerprint:t,pending:E});try{let S=await E;return workspaceSearchCaches.get(e)?.pending===E&&workspaceSearchCaches.set(e,{fingerprint:t,corpus:S}),S}catch(t){throw workspaceSearchCaches.get(e)?.pending===E&&workspaceSearchCaches.delete(e),t}}function yl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{vl().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}yl();async function xl(e,t){if(e.method===`GET`)return Cl(e,t);if(e.method===`POST`)return Tl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let Cl=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`limit`),E=S.searchParams.get(`query`)??``,D=ml(S.searchParams.get(`intent`)),O=hl(S.searchParams.get(`scope`)??S.searchParams.get(`scopes`)),k=w===null?void 0:Number(w);if(E.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:E,intent:D,results:searchWorkspaceCorpus(await vl(),E,{intent:D,scopes:O,limit:k}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?pl(e.document.content,E):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{handler:`search-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),Tl=withValidation(SearchRequestSchema,async(e,t,S)=>{let w=typeof S.query==`string`?S.query:``,E=ml(S.intent),D=hl(S.scopes??S.scope),O=typeof S.limit==`number`?S.limit:void 0;if(w.length>200){errorResponse(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{let e=performance.now();successResponse(t,200,SearchSuccessSchema,{query:w,intent:E,results:searchWorkspaceCorpus(await vl(),w,{intent:E,scopes:D,limit:O}).map(e=>({kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?pl(e.document.content,w):void 0})),elapsedMs:Math.max(0,performance.now()-e)},{handler:`search-post`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),El=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,SkillInstallStateSuccessSchema,{...await readSkillInstallStateSnapshot(homedir())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:`skill-install-state`})});async function Dl(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$2.error({err:e},`[handoff] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function Ol(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:w,platform:process.platform})}catch(e){t.headersSent||(log$2.error({err:e},`[spawn-cursor] route wrapper failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let kl=withValidation(ShareConstructUrlRequestSchema,async(e,t,S)=>{try{if(!de){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!isValidShareDocPath(S.docPath)){emitShareConstructUrlLog(`invalid-path`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=readGitHeadBranch(de);if(e===null){if(readOriginGitHubRepo(de).kind===`no-remote`){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}emitShareConstructUrlLog(`detached-head`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`detached-head`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=readOriginGitHubRepo(de);if(w.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(w.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(de,e)){emitShareConstructUrlLog(`branch-not-on-origin`,!1),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let E=buildGitHubBlobUrl(w.owner,w.repo,e,S.docPath),D=`${SHARE_BASE_URL}${encodeShareUrl(E)}`;emitShareConstructUrlLog(`ok`,!0),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:D,blobUrl:E,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}),jl=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!de){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:BRANCH_INFO_HANDLER_TAG});return}let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`branch`),E=S.searchParams.get(`path`);if(!isValidBranchName(w)){errorResponse(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}if(!isValidBranchInfoDocPath(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:BRANCH_INFO_HANDLER_TAG});return}successResponse(t,200,BranchInfoResponseSchema,await computeBranchInfo(de,w,E),{handler:BRANCH_INFO_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BRANCH_INFO_HANDLER_TAG,cause:e})}},{handler:BRANCH_INFO_HANDLER_TAG,method:`GET`,skipBodyParse:!0}),Ml=withValidation(CheckoutRequestSchema,async(e,t,S)=>{if(extractActorIdentity(S,fe).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!de){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CHECKOUT_HANDLER_TAG});return}try{successResponse(t,200,CheckoutResponseSchema,await withParentLock(()=>runCheckoutFlow(de,S.branch)),{handler:CHECKOUT_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CHECKOUT_HANDLER_TAG,cause:e})}},{handler:CHECKOUT_HANDLER_TAG,method:`POST`});async function Pl(e){let[t,...S]=ue,w=[...S,...e];return await new Promise((e,S)=>{let E=spawn(t,w,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),D=!1,O=setTimeout(()=>{D=!0,E.kill(`SIGTERM`)},SHARE_PUBLISH_TIMEOUT_MS),k=[],j=[];E.stdout.on(`data`,e=>k.push(e)),E.stderr.on(`data`,e=>j.push(e)),E.on(`close`,t=>{if(clearTimeout(O),D){S(Error(`share subprocess timed out after ${SHARE_PUBLISH_TIMEOUT_MS}ms`));return}let w=Buffer.concat(k).toString(`utf-8`);if(t!==0){let e=redactShareSubprocessStderr(Buffer.concat(j).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:w,code:t})}),E.on(`error`,e=>{clearTimeout(O),S(e)})})}let Fl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!we.tryAcquire(`/api/share/publish/owners`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Pl([`share`,`owners`,`--json`]),S=parseOwnersEvent(pickTerminalJsonLine(e));emitSharePublishLog(`owners-list`,S.ok?`ok`:S.error,S.ok?{count:S.owners.length}:void 0),successResponse(t,200,SharePublishOwnersResponseSchema,S,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,cause:e})}finally{we.release(SHARE_PUBLISH_OWNERS_KEY)}},{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_OWNERS_HANDLER_TAG})}),Il=withValidation(EmptyRequestSchema,async(e,t)=>{let S=new URL(e.url??``,`http://localhost`),w=S.searchParams.get(`owner`)??``,E=S.searchParams.get(`name`)??``;if(!isValidShareOwnerName(w)||!isValidShareRepoName(E)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG});return}if(!we.tryAcquire(`/api/share/publish/name-check`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Pl([`share`,`name-check`,`--owner`,w,`--name`,E,`--json`]),S=parseNameCheckEvent(pickTerminalJsonLine(e));emitSharePublishLog(`name-check`,S.ok?`ok`:S.error,S.ok?{available:S.available}:void 0),successResponse(t,200,SharePublishNameCheckResponseSchema,S,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,cause:e})}finally{we.release(SHARE_PUBLISH_NAME_CHECK_KEY)}},{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_NAME_CHECK_HANDLER_TAG})}),Ll=withValidation(SharePublishRequestSchema,async(e,t,S)=>{if(!de){emitSharePublishLog(`publish-create`,`no-project`),successResponse(t,200,SharePublishResponseSchema,{ok:!1,error:`no-project`},{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!isValidShareOwnerName(S.owner)||!isValidShareRepoName(S.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:SHARE_PUBLISH_HANDLER_TAG});return}if(!we.tryAcquire(`/api/share/publish`)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:SHARE_PUBLISH_HANDLER_TAG,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,S.owner,`--name`,S.name,`--visibility`,S.visibility,`--project-dir`,de,`--json`];S.description!==void 0&&S.description.length>0&&e.push(`--description`,S.description);let{stdout:w}=await Pl(e),E=parsePublishEvent(pickTerminalJsonLine(w));emitSharePublishLog(`publish-create`,E.ok?`ok`:E.error),successResponse(t,200,SharePublishResponseSchema,E,{handler:SHARE_PUBLISH_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_PUBLISH_HANDLER_TAG,cause:e})}finally{we.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),Rl={"/api/asset":ka,"/api/asset-text":xs,"/api/document":jr,"/api/documents":Mr,"/api/backlinks":Fr,"/api/backlink-counts":Ir,"/api/forward-links":Lr,"/api/link-graph":zr,"/api/dead-links":Hr,"/api/orphans":Br,"/api/hubs":Vr,"/api/tags":Gc,"/api/pages":$s,"/api/folder-config":Zc,"/api/template":il,"/api/search":xl,"/api/suggest-links":ec,"/api/page-headings":Ns,"/api/create-page":Os,"/api/create-folder":ks,"/api/duplicate-path":As,"/api/rename-path":Ps,"/api/delete-path":Is,"/api/trash/cleanup":Rs,"/api/upload":tc,"/api/agent-write":Wt,"/api/agent-write-md":Kt,"/api/frontmatter-patch":$t,"/api/agent-patch":Ur,"/api/agent-undo":Wr,"/api/agent-activity":Gr,"/api/agent-burst-diff":Kr,"/api/save-version":Xr,"/api/history":Zr,"/api/diff":ji,"/api/rollback":Hi,"/api/metrics/reconciliation":Ui,"/api/metrics/parse-health":Gi,"/api/metrics/agent-presence":Xi,"/api/server-info":Ki,"/api/share/construct-url":kl,"/api/git/branch-info":jl,"/api/git/checkout":Ml,"/api/share/publish/owners":Fl,"/api/share/publish/name-check":Il,"/api/share/publish":Ll,"/api/principal":Yi,"/api/rescue":Ts,"/api/workspace":Zi,"/api/sync/status":Pc,"/api/sync/trigger":Fc,"/api/sync/conflicts":Ic,"/api/sync/conflict-content":Rc,"/api/sync/resolve-conflict":Lc,"/api/sync/abort-merge":Wc,"/api/local-op/clone":sc,"/api/local-op/open":dc,"/api/local-op/auth/login":vc,"/api/local-op/auth/status":xc,"/api/local-op/auth/repos":Cc,"/api/local-op/auth/signout":Ec,"/api/local-op/auth/pat":Oc,"/api/local-op/auth/identity":Ac,"/api/local-op/auth/set-identity":Nc,"/api/installed-agents":Uc,"/api/spawn-cursor":Ol,"/api/handoff":Dl,"/api/install-skill":Hc,"/api/skill/install-state":El,"/api/seed/plan":zc,"/api/seed/apply":Bc,"/api/seed/packs":Vc};F&&(Rl[`/api/test-reset`]=qr,Rl[`/api/test-rescan-backlinks`]=Jr,Rl[`/api/test-rescan-files`]=Yr);let zl=new Set([`/api/upload`,`/api/create-page`,`/api/create-folder`,`/api/duplicate-path`,`/api/rename-path`,`/api/delete-path`,`/api/trash/cleanup`,`/api/agent-write`,`/api/agent-write-md`,`/api/frontmatter-patch`,`/api/agent-patch`,`/api/agent-undo`,`/api/save-version`,`/api/rollback`,`/api/sync/trigger`,`/api/sync/resolve-conflict`,`/api/sync/abort-merge`,`/api/git/checkout`,`/api/test-reset`,`/api/test-rescan-backlinks`,`/api/test-rescan-files`,`/api/install-skill`,`/api/folder-config`,`/api/template`,`/api/seed/apply`]),Bl=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let S=e.url?.split(`?`)[0];if(!S)return;if(S.startsWith(`/api/`)){let S=e.headers.origin;if(S!==void 0&&!isAllowedApiOrigin(S)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(S!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,S),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(zl.has(S)||Bl.some(e=>S.startsWith(e))){let S=e.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(!S.startsWith(`/api/`))return;let w=propagation.extract(context.active(),e.headers),E=e.method??`GET`,D=S;S.startsWith(`/api/rescue/`)?D=`/api/rescue/:docName`:S.startsWith(`/api/history/`)?D=`/api/history/:sha`:S.startsWith(`/api/tags/`)?D=`/api/tags/:name`:Rl[S]||(D=`/api/*`);let O=getTracer(),k=Date.now();await context.with(w,()=>O.startActiveSpan(`HTTP ${E} ${D}`,{kind:SpanKind.SERVER,attributes:{[ATTR_HTTP_REQUEST_METHOD]:E,[ATTR_HTTP_ROUTE]:D,[ATTR_URL_PATH]:S,[ATTR_URL_SCHEME]:`http`,[ATTR_USER_AGENT_ORIGINAL]:e.headers[`user-agent`]??``}},async w=>{try{let D=Rl[S],O=!1;if(D)O=!0,await D(e,t);else if(S.startsWith(`/api/rescue/`)){let w=decodeURIComponent(S.slice(12));w&&(O=!0,await Ds(e,t,w))}else if(S.startsWith(`/api/history/`)){let w=decodeURIComponent(S.slice(13));w&&(O=!0,await Qr(e,t,w))}else if(S.startsWith(`/api/tags/`)){let w=S.slice(10);w&&(O=!0,await Kc(e,t,w))}O||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${E} ${S}`});let k=t.statusCode;w.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,k),k>=500&&w.setStatus({code:SpanStatusCode.ERROR,message:`status ${k}`})}catch(e){throw w.recordException(e),w.setStatus({code:SpanStatusCode.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:D,cause:e}),e}finally{w.end();let e=(Date.now()-k)/1e3;httpDurationHist().record(e,{[ATTR_HTTP_REQUEST_METHOD]:E,[ATTR_HTTP_ROUTE]:D,[ATTR_HTTP_RESPONSE_STATUS_CODE]:t.statusCode})}}))}}}function isWithinDir(e,t){return e===t?!0:e.startsWith(`${t}${sep}`)}function errnoCode(e){let t=e?.code;return typeof t==`string`?t:void 0}function seedBasenameIndex(e){let t=e.contentDir,S=new Set;function w(E){let D;try{D=readdirSync(E,{withFileTypes:!0})}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`read-failed`,S,E);return}for(let O of D){let D=join(E,O.name),k=relative(t,D);if(k.startsWith(`..`)||e.contentFilter?.isDirExcluded(k)&&O.isDirectory())continue;let j;try{j=lstatSync(D)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`lstat-failed`,S,D);continue}if(j.isSymbolicLink()){let E;try{E=realpathSync(D)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`realpath-failed`,S,D);continue}if(!isWithinDir(E,t)){e.onSkip?.(`symlink-escape`,void 0,D);continue}let O;try{O=statSync(E)}catch(t){let S=errnoCode(t);S!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,S,E);continue}if(S.has(O.ino))continue;S.add(O.ino),O.isDirectory()?w(E):O.isFile()&&isSupportedAssetFile(D,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(k)&&e.basenameIndex.add(k);continue}if(j.isDirectory()){if(S.has(j.ino))continue;S.add(j.ino),w(D);continue}j.isFile()&&isSupportedAssetFile(D,ASSET_EXTENSIONS)&&!e.contentFilter?.isExcluded(k)&&e.basenameIndex.add(k)}}w(t)}const HocuspocusAuthTokenSchema=object$1({principalId:string$2().optional(),tabSessionId:string$2().optional(),expectedServerInstanceId:string$2().optional(),expectedBranch:string$2().optional()}).loose(),HOCUSPOCUS_AUTH_REJECTION_REASONS=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`];function isHocuspocusAuthRejectionReason(e){return HOCUSPOCUS_AUTH_REJECTION_REASONS.includes(e)}const WIRE_PAYLOAD_SEPARATOR=`:`;function formatAuthRejectionWire(e,t){return typeof t!=`string`||t.length===0?e:`${e}${WIRE_PAYLOAD_SEPARATOR}${t}`}function parseAuthRejectionWire(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(WIRE_PAYLOAD_SEPARATOR),S=t===-1?e:e.slice(0,t);if(!isHocuspocusAuthRejectionReason(S))return{kind:null,payload:void 0};if(t===-1)return{kind:S,payload:void 0};let w=e.slice(t+1);return{kind:S,payload:w.length>0?w:void 0}}var HocuspocusAuthRejection=class extends Error{kind;payload;reason;constructor(e,t,S){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof S==`string`&&S.length>0?S:void 0,this.reason=formatAuthRejectionWire(e,this.payload)}};function parseHocuspocusAuthToken(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let S=HocuspocusAuthTokenSchema.safeParse(t);return S.success?S.data:void 0}const log$1=getLogger(`conflict-storage`);var ConflictStore=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=join(getLocalDir(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!existsSync(this.storePath)){this.conflicts=[];return}try{let e=readFileSync(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){log$1.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){log$1.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=dirname(this.storePath);existsSync(e)||mkdirSync(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};writeFileSync(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){log$1.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,S,w=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&S===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:E}=await import(`./git-handle-CjyGVy33-DVACqhWk.mjs`).then(e=>e.n),D=E(this.projectDir,{credentialArgs:w});switch(t){case`mine`:await D.git.raw([`checkout`,`--ours`,`--`,e]),await D.git.raw([`add`,`--`,e]);break;case`theirs`:await D.git.raw([`checkout`,`--theirs`,`--`,e]),await D.git.raw([`add`,`--`,e]);break;case`content`:{if(!S)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=resolve(this.projectDir),w=resolve(t,e);if(w!==t&&!w.startsWith(`${t}/`))throw Error(`[conflicts] file path escapes project directory: ${e}`);writeFileSync(w,S,`utf-8`),await D.git.raw([`add`,`--`,e]);break}default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await D.git.raw([`commit`,`--no-edit`]),log$1.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let S=new Date().toISOString(),w=!1;try{let e=(await D.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
|
|
2115
|
-
`).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:S});w=e.length>0}catch(e){log$1.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}w||this.addConflict({file:e,detectedAt:S}),log$1.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let E=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${w?`unmerged files re-added`:`original file re-added`} — ${E}`,{cause:t})}}};const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,S=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,w=0,E=null,D=null,O=!1,k=!1;function j(){E!==null&&(t.clearTimeout(E),E=null),D!==null&&(t.clearTimeout(D),D=null)}function F(){j(),!(k||O)&&w===0&&(S>0&&S<e.thresholdMs&&(D=t.setTimeout(()=>{D=null,w===0&&!O&&e.log?.warn({msUntilShutdown:S,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-S)),E=t.setTimeout(()=>{if(E=null,!(k||O)&&w===0){O=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let L=(e,t)=>{e.url?.startsWith(`/collab`)&&(w++,j(),t.once(`close`,()=>{w--,w<0&&(w=0),w===0&&F()}))};return e.httpServer.on(`upgrade`,L),F(),{detach:()=>{k||(k=!0,e.httpServer.off(`upgrade`,L),j())}}}const MCP_SERVER_NAME=`open-knowledge`,MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let S=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return S?S.slice(0,128):t}function buildInstructions(e){return'Open Knowledge is a markdown-CRDT knowledge base exposed via MCP.\n\n## STOP — native tools on in-scope `.md` / `.mdx`\n\nWhen this workspace has Open Knowledge MCP configured, do **not** use your host\'s native file tools on markdown paths inside the content directory. The ban covers every common rationalization:\n\n- **Native `Read` / `Grep` / `Glob` on in-scope `.md` / `.mdx`** — the original case.\n- **`Bash ls` / `Bash find` / `Bash cat` on dirs containing in-scope markdown** — use `exec("ls -A …")` / `exec("find … -name \'*.md\'")` / `exec("cat …")` instead. Native returns bare names; `exec` returns frontmatter, backlink counts, and recent activity per child. `-A` shows hidden entries (`.ok/`, `.okignore`) which OK projects carry; omit `.` and `..` rows that `-a` would add.\n- **Glob patterns that target markdown** (`**/*.md`, any dir known to be markdown-heavy like `specs/**`, `reports/**`, `docs/**`) — use `exec` with `find`, or `exec("ls -A <dir>")`.\n- **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native `Read` / `Grep` / `Glob` internally and bypass Open Knowledge entirely. Do markdown exploration yourself via `exec` / `search`. Subagents remain appropriate for **source-code** exploration.\n- **Native `Read` / `Grep` on any in-scope markdown inside `.ok/`** — the `.ok/` directory is in-scope; if it carries `.md` / `.mdx`, treat those the same as any other knowledge-base file.\n\nWhy: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK\'s tools return for every matched knowledge-base file. `exec` is the primary read surface; it runs read-only bash (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut` — pipes OK) and returns raw stdout plus enriched metadata per file.\n\n**MCP tool visibility — not seeing `exec` is NOT the escape hatch.** MCP wiring varies by client. Claude Code, Cursor, Codex, Windsurf, VS Code — each surfaces MCP differently. Server labels are user-defined; tools may not appear as top-level symbols named `exec` in your specific UI. If Open Knowledge is registered as an MCP server in this workspace, route markdown reads through its `exec` / `search` via your client\'s documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.\n\n**Escape hatch.** Native `Read` / `Grep` / `Glob` on `.md` / `.mdx` is allowed **only** when no Open Knowledge MCP server is registered for this project, **or** immediately after you tried an MCP call and it failed — then begin a user-visible sentence with `Open Knowledge MCP unavailable:`. Never use the hatch because you skipped your client\'s MCP path, didn\'t see `exec` as a top-level tool, or rationalized the skill wasn\'t necessary.\n\n**Source code and non-markdown files** (`.ts`, `.py`, `package.json`, …): native `Read` / `Grep` / `Glob` always.\n\n## Reads — examples\n\n- Read a file: `exec("cat <path>.md")` — contents + full rich enrichment.\n- List a directory: `exec("ls -A <dir>")` — per-child frontmatter, recursive markdown counts, most-recently-updated doc per subdir, folder-level `frontmatter_defaults` + `templates_available`. Prefer `-A` over plain `ls` to surface dot-prefixed entries (`.ok/`, `.okignore`) without the noisy `.`/`..` rows that `-a` adds.\n- Literal search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files.\n- Ranked search: `search({ query })` — cmd-K parity (title boost + body BM25 + recency); use when picking the best doc, not when listing every occurrence.\n\n## Preview — open the browser at session start\n\nThe user watches your edits land in a live browser preview. Open it once at session start, then keep working. Re-navigate only when the user asks to open a different doc, not to re-check your own edits.\n\n**`previewUrl` is a route, not a URL to open.** Every read response (per-doc, on `exec` / `search` / `links` rows) and every write response carries a `previewUrl` — a route fragment like `/#/specs/foo/SPEC`, with **no scheme, host, or port**. It identifies *which doc* to preview, not a URL to hand a browser by itself. Never construct or guess preview URLs.\n\n**Pick how to open the preview by tool capability — not by host name.** Look at the tools actually available to you this session:\n\n- **You have a `preview_*` tool** (e.g. `preview_start`) → call `preview_start("open-knowledge-ui")` and nothing else. The pane supplies its own origin; you never need a URL. Do NOT also call `get_preview_url`. Do NOT read, diagnose, or edit `.claude/launch.json` — that file is host-managed, and the OK lock-collision proxy handles the UI-already-running case automatically. If `preview_start` fails, report it to the user; do not try to "fix" `launch.json`.\n- **No `preview_*` tool, but you have an in-app / built-in browser tool** → call `get_preview_url` once to get the full browser URL (`{ url, baseUrl, running }`), then navigate your **in-app browser** to `url`. Pass a `docName` to `get_preview_url` to jump straight to a doc, or omit it for the UI root.\n- **No browser tool at all** (a stdio host such as the Codex CLI, which has no embedded browser) → call `get_preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly to the user ("opening the preview in your system browser — this host has no in-app browser"). The system browser is the fallback, never the default.\n\n**Opening or reading a file IS a preview navigation.** On any "open `<file>`" / "read `<file>`" request, navigate the browser to that doc\'s `previewUrl` route from the tool response — not a separate fetch, not a fresh system-browser launch.\n\n**Four signals to check if the preview is already attached** (read these from each write response):\n\n1. You opened/navigated earlier this session → don\'t reopen.\n2. Write response has `previewUrl` (non-null route) and NO `warning` → a browser is attached somewhere; do nothing.\n3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot (`preview_start`, or `get_preview_url` → in-app browser).\n4. `warning: { action: "start-ui", previewUrl: null, message }` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don\'t loop on retries.\n\nWarnings fire at most once per session in the fresh-start case.\n\n**`previewUrl: null` only means "no UI reachable" on the three attach-warning tools: `write_document` / `edit_document` / `edit_frontmatter`.** Workflow tools return prose and don\'t carry `previewUrl`. `delete_document` / `rename` emit `previousPreviewUrl` (different field, for closing stale tabs) and don\'t fire attach warnings. `get_preview_url` reports `running: false` + `url: null` when no UI is running.\n\nIf you see `"Hocuspocus server is not running"`, run `ok start` and retry.\n\nOK Electron and `ok ui` share `ui.lock`; when a second UI binds a different port, the OK lock-collision proxy bridges it to the live server transparently. That is exactly why `previewUrl` is route-only — the port behind the proxy is not the agent\'s to use. **Do not nudge the user to quit OK Electron to free a port** — the proxy handles it, and quitting tears down a UI in active use.\n\n**The preview is read-only for the agent — it is the user\'s view, not a surface you read back.** You cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).\n\n**No screenshots to confirm edits, no generic verification loop.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after a write, and do not run a generic snapshot/eval/screenshot verification loop — OK\'s preview is a read-only, one-way mirror, so the CRDT tool response *is* the confirmation that an edit landed. Screenshot only when debugging a visual rendering issue or when the user explicitly asks to see the preview — never to confirm an edit landed.\n\n## Scope recap\n\nOpen Knowledge looks for documents under the resolved `content.dir` (discoverable at runtime via `get_config({ path: [\'content\', \'dir\'] })`). `.gitignore` and `.okignore` (at the project root and at any folder depth) define exclusions. Folder defaults + templates live in nested `<folder>/.ok/frontmatter.yml` + `<folder>/.ok/templates/` files — NOT in `.ok/config.yml`.\n\nDefault mental model (no jargon): **every `.md` and `.mdx` under `content.dir`** not excluded by `.gitignore` or `.okignore` is an Open Knowledge document — including under `specs/`, `reports/`, `docs/`, etc. Read `.okignore` (and any nested `.okignore` files) once per turn to know what\'s excluded.\n\n**First session in this project?** If `frontmatter_defaults` and `templates_available` are empty for substantial folders, the project hasn\'t been onboarded yet — invoke `discover` (Workflow tools table) before writing. Once onboarded, the cascade carries the discipline.\n\n\nFull guidance lives in the bundled `open-knowledge` skill at `~/.ok/skills/open-knowledge/SKILL.md`.\n'}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let S=t.validateToolInput;if(typeof S!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,w){if(!e.inputSchema||!isZodSchema(e.inputSchema))return S.call(this,e,t,w);let E=await e.inputSchema.safeParseAsync(t);if(E.success)return E.data;let D=prettifyError(E.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${w}:\n${D}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const loggerContext=new AsyncLocalStorage;var McpLogger=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??randomUUID().slice(0,12),this.corrId=randomUUID().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,S={}){let w=t?{error:t instanceof Error?t.message:String(t),...S}:S;this.emit(`error`,e,w)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,S){let w={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...S},E=`${JSON.stringify(w)}\n`;process.stderr.write(E);let D=process.env.OK_LOG_FILE;if(D)try{appendFileSync(D,E)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function runWithMcpLogger(e,t){return loggerContext.run(e,t)}function getCurrentMcpLogger(){return loggerContext.getStore()}const REDACTED_STRING_KEYS=new Set([`find`,`markdown`,`replace`]),COMMON_ARRAY_KEYS=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],COMMON_SCALAR_KEYS=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isToolExtraLike(e){return isPlainObject(e)&&`requestId`in e}function summarizeStringForLog(e,t){if(REDACTED_STRING_KEYS.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
|
|
2115
|
+
`).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:S});w=e.length>0}catch(e){log$1.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}w||this.addConflict({file:e,detectedAt:S}),log$1.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let E=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${w?`unmerged files re-added`:`original file re-added`} — ${E}`,{cause:t})}}};const DEFAULT_WARN_BEFORE_MS=300*1e3;function attachIdleShutdown(e){let t=e.scheduler??defaultScheduler,S=e.warnBeforeMs??DEFAULT_WARN_BEFORE_MS,w=0,E=null,D=null,O=!1,k=!1;function j(){E!==null&&(t.clearTimeout(E),E=null),D!==null&&(t.clearTimeout(D),D=null)}function F(){j(),!(k||O)&&w===0&&(S>0&&S<e.thresholdMs&&(D=t.setTimeout(()=>{D=null,w===0&&!O&&e.log?.warn({msUntilShutdown:S,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-S)),E=t.setTimeout(()=>{if(E=null,!(k||O)&&w===0){O=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let L=(e,t)=>{e.url?.startsWith(`/collab`)&&(w++,j(),t.once(`close`,()=>{w--,w<0&&(w=0),w===0&&F()}))};return e.httpServer.on(`upgrade`,L),F(),{detach:()=>{k||(k=!0,e.httpServer.off(`upgrade`,L),j())}}}const MCP_SERVER_NAME=`open-knowledge`,MCP_CONNECTION_ID_HEADER=`x-ok-connection-id`;function sanitizeClientName(e,t){let S=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return S?S.slice(0,128):t}function buildInstructions(e){return'Open Knowledge is a markdown-CRDT knowledge base exposed via MCP.\n\n## STOP — native tools on in-scope `.md` / `.mdx`\n\nWhen this workspace has Open Knowledge MCP configured, do **not** use your host\'s native file tools on markdown paths inside the content directory. The ban covers every common rationalization:\n\n- **Native `Read` / `Grep` / `Glob` on in-scope `.md` / `.mdx`** — the original case.\n- **`Bash ls` / `Bash find` / `Bash cat` on dirs containing in-scope markdown** — use `exec("ls -A …")` / `exec("find … -name \'*.md\'")` / `exec("cat …")` instead. Native returns bare names; `exec` returns frontmatter, backlink counts, and recent activity per child. `-A` shows hidden entries (`.ok/`, `.okignore`) which OK projects carry; omit `.` and `..` rows that `-a` would add.\n- **Glob patterns that target markdown** (`**/*.md`, any dir known to be markdown-heavy like `specs/**`, `reports/**`, `docs/**`) — use `exec` with `find`, or `exec("ls -A <dir>")`.\n- **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native `Read` / `Grep` / `Glob` internally and bypass Open Knowledge entirely. Do markdown exploration yourself via `exec` / `search`. Subagents remain appropriate for **source-code** exploration.\n- **Native `Read` / `Grep` on any in-scope markdown inside `.ok/`** — the `.ok/` directory is in-scope; if it carries `.md` / `.mdx`, treat those the same as any other knowledge-base file.\n\nWhy: native tools skip frontmatter, backlinks, shadow-repo activity, and project git history that OK\'s tools return for every matched knowledge-base file. `exec` is the primary read surface; it runs read-only bash (`cat`, `ls`, `grep`, `find`, `head`, `tail`, `wc`, `sort`, `uniq`, `cut` — pipes OK) and returns raw stdout plus enriched metadata per file.\n\n**MCP tool visibility — not seeing `exec` is NOT the escape hatch.** MCP wiring varies by client. Claude Code, Cursor, Codex, Windsurf, VS Code — each surfaces MCP differently. Server labels are user-defined; tools may not appear as top-level symbols named `exec` in your specific UI. If Open Knowledge is registered as an MCP server in this workspace, route markdown reads through its `exec` / `search` via your client\'s documented MCP invocation (including any generic "call MCP tool" flow). Registration is the test, not top-level-symbol visibility.\n\n**Escape hatch.** Native `Read` / `Grep` / `Glob` on `.md` / `.mdx` is allowed **only** when no Open Knowledge MCP server is registered for this project, **or** immediately after you tried an MCP call and it failed — then begin a user-visible sentence with `Open Knowledge MCP unavailable:`. Never use the hatch because you skipped your client\'s MCP path, didn\'t see `exec` as a top-level tool, or rationalized the skill wasn\'t necessary.\n\n**Source code and non-markdown files** (`.ts`, `.py`, `package.json`, …): native `Read` / `Grep` / `Glob` always.\n\n## Reads — examples\n\n- Read a file: `exec("cat <path>.md")` — contents + full rich enrichment.\n- List a directory: `exec("ls -A <dir>")` — per-child frontmatter, recursive markdown counts, most-recently-updated doc per subdir, folder-level `frontmatter_defaults` + `templates_available`. Prefer `-A` over plain `ls` to surface dot-prefixed entries (`.ok/`, `.okignore`) without the noisy `.`/`..` rows that `-a` adds.\n- Literal search: `exec("grep -rn <term> <dir> | head -5")` — matches + enrichment on matched files.\n- Ranked search: `search({ query })` — cmd-K parity (title boost + body BM25 + recency); use when picking the best doc, not when listing every occurrence.\n\n## Preview — open the browser at session start\n\nThe user watches your edits land in a live browser preview. Open it once at session start, then keep working. Re-navigate only when the user asks to open a different doc, or to land them on a finished deliverable (see below) — not to re-check your own edits.\n\n**End a turn on the deliverable, not your scratch space.** Keep the preview steady *during* a multi-doc task — don\'t yank it around to re-check your own edits. But when a turn created or substantially changed user-facing docs, navigate the preview to the primary deliverable before you hand back: the hub / overview / index page when you created several docs, or the changed doc when you changed one. Don\'t step the user through every supporting source card — the user is watching, so leave them on the result.\n\n**`previewUrl` is a route, not a URL to open.** Every read response (per-doc, on `exec` / `search` / `links` rows) and every write response carries a `previewUrl` — a route fragment like `/#/specs/foo/SPEC`, with **no scheme, host, or port**. It identifies *which doc* to preview, not a URL to hand a browser by itself. Never construct or guess preview URLs.\n\n**Pick how to open the preview by tool capability — not by host name.** Look at the tools actually available to you this session:\n\n- **You have a `preview_*` tool** (e.g. `preview_start`) → call `preview_start("open-knowledge-ui")` and nothing else. The pane supplies its own origin; you never need a URL. Do NOT also call `get_preview_url`. Do NOT read, diagnose, or edit `.claude/launch.json` — that file is host-managed, and the OK lock-collision proxy handles the UI-already-running case automatically. If `preview_start` fails, report it to the user; do not try to "fix" `launch.json`.\n- **No `preview_*` tool, but you have an in-app / built-in browser tool** → call `get_preview_url` once to get the full browser URL (`{ url, baseUrl, running }`), then navigate your **in-app browser** to `url`. Pass a `docName` to `get_preview_url` to jump straight to a doc, or omit it for the UI root.\n- **No browser tool at all** (a stdio host such as the Codex CLI, which has no embedded browser) → call `get_preview_url`, then `open <url>` in the system browser as a last resort, and say so plainly to the user ("opening the preview in your system browser — this host has no in-app browser"). The system browser is the fallback, never the default.\n\n**Opening or reading a file IS a preview navigation.** On any "open `<file>`" / "read `<file>`" request, navigate the browser to that doc\'s `previewUrl` route from the tool response — not a separate fetch, not a fresh system-browser launch.\n\n**Four signals to check if the preview is already attached** (read these from each write response):\n\n1. You opened/navigated earlier this session → don\'t reopen.\n2. Write response has `previewUrl` (non-null route) and NO `warning` → a browser is attached somewhere; do nothing.\n3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot (`preview_start`, or `get_preview_url` → in-app browser).\n4. `warning: { action: "start-ui", previewUrl: null, message }` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don\'t loop on retries.\n\nWarnings fire at most once per session in the fresh-start case.\n\n**`previewUrl: null` only means "no UI reachable" on the three attach-warning tools: `write_document` / `edit_document` / `edit_frontmatter`.** Workflow tools return prose and don\'t carry `previewUrl`. `delete_document` / `rename` emit `previousPreviewUrl` (different field, for closing stale tabs) and don\'t fire attach warnings. `get_preview_url` reports `running: false` + `url: null` when no UI is running.\n\nIf you see `"Hocuspocus server is not running"`, run `ok start` and retry.\n\nOK Electron and `ok ui` share `ui.lock`; when a second UI binds a different port, the OK lock-collision proxy bridges it to the live server transparently. That is exactly why `previewUrl` is route-only — the port behind the proxy is not the agent\'s to use. **Do not nudge the user to quit OK Electron to free a port** — the proxy handles it, and quitting tears down a UI in active use.\n\n**The preview is read-only for the agent — it is the user\'s view, not a surface you read back.** You cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).\n\n**No screenshots to confirm edits, no generic verification loop.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after a write, and do not run a generic snapshot/eval/screenshot verification loop — OK\'s preview is a read-only, one-way mirror, so the CRDT tool response *is* the confirmation that an edit landed. Screenshot only when debugging a visual rendering issue or when the user explicitly asks to see the preview — never to confirm an edit landed.\n\n## Scope recap\n\nOpen Knowledge looks for documents under the resolved `content.dir` (discoverable at runtime via `get_config({ path: [\'content\', \'dir\'] })`). `.gitignore` and `.okignore` (at the project root and at any folder depth) define exclusions. Folder defaults + templates live in nested `<folder>/.ok/frontmatter.yml` + `<folder>/.ok/templates/` files — NOT in `.ok/config.yml`.\n\nDefault mental model (no jargon): **every `.md` and `.mdx` under `content.dir`** not excluded by `.gitignore` or `.okignore` is an Open Knowledge document — including under `specs/`, `reports/`, `docs/`, etc. Read `.okignore` (and any nested `.okignore` files) once per turn to know what\'s excluded.\n\n**First session in this project?** If `frontmatter_defaults` and `templates_available` are empty for substantial folders, the project hasn\'t been onboarded yet — invoke `discover` (Workflow tools table) before writing. Once onboarded, the cascade carries the discipline.\n\n\nFull guidance lives in the bundled `open-knowledge` skill at `~/.ok/skills/open-knowledge/SKILL.md`.\n'}function installPrettyZodErrors(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let S=t.validateToolInput;if(typeof S!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,w){if(!e.inputSchema||!isZodSchema(e.inputSchema))return S.call(this,e,t,w);let E=await e.inputSchema.safeParseAsync(t);if(E.success)return E.data;let D=prettifyError(E.error);throw new McpError(ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${w}:\n${D}`)},t.__prettyZodErrorsInstalled=!0}function isZodSchema(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const loggerContext=new AsyncLocalStorage;var McpLogger=class e{sessionId;corrId;component;constructor(e=`mcp`,t){this.sessionId=t??randomUUID().slice(0,12),this.corrId=randomUUID().slice(0,8),this.component=e}info(e,t={}){this.emit(`info`,e,t)}warn(e,t={}){this.emit(`warn`,e,t)}error(e,t,S={}){let w=t?{error:t instanceof Error?t.message:String(t),...S}:S;this.emit(`error`,e,w)}debug(e,t={}){(process.env.MCP_DEBUG===`1`||process.env.DEBUG?.includes(`mcp`))&&this.emit(`debug`,e,t)}child(t){return new e(t??this.component,this.sessionId)}asCallback(){return e=>this.info(e)}emit(e,t,S){let w={ts:new Date().toISOString(),level:e,sessionId:this.sessionId,corrId:this.corrId,component:this.component,msg:t,...S},E=`${JSON.stringify(w)}\n`;process.stderr.write(E);let D=process.env.OK_LOG_FILE;if(D)try{appendFileSync(D,E)}catch(e){console.warn(`[mcp-logger] Failed to write to OK_LOG_FILE: ${e instanceof Error?e.message:e}`)}}};function runWithMcpLogger(e,t){return loggerContext.run(e,t)}function getCurrentMcpLogger(){return loggerContext.getStore()}const REDACTED_STRING_KEYS=new Set([`find`,`markdown`,`replace`]),COMMON_ARRAY_KEYS=[`backlinks`,`deadLinks`,`documents`,`enrichedPaths`,`entries`,`forwardLinks`,`hints`,`hubs`,`orphans`,`results`],COMMON_SCALAR_KEYS=[`checkpointRef`,`cwd`,`fileCount`,`matchCount`,`ok`,`query`,`stdoutTruncated`,`truncated`];function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isToolExtraLike(e){return isPlainObject(e)&&`requestId`in e}function summarizeStringForLog(e,t){if(REDACTED_STRING_KEYS.has(e))return{redacted:!0,type:`string`,length:t.length,lines:t.length===0?0:t.split(`
|
|
2116
2116
|
`).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 w=e[S];Array.isArray(w)&&(t[`${S}Count`]=w.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)),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 w=S.logger;return w?async(...E)=>{let D=w.child(),O=Date.now(),{toolArgs:k,extra:j}=splitInvocationArgs(E);D.info(`tool start`,{tool:e,...j?.requestId===void 0?{}:{requestId:j.requestId},...j?.sessionId?{transportSessionId:j.sessionId}:{},...S.identityRef?.current?{agent:summarizeIdentityForLog(S.identityRef.current)}:{},...k===void 0?{}:{args:summarizeArgsForLog(e,k)}});try{let S=await runWithMcpLogger(D,async()=>await t(...E));return D.info(`tool finish`,{tool:e,...j?.requestId===void 0?{}:{requestId:j.requestId},durationMs:Date.now()-O,result:summarizeToolResultForLog(S)}),S}catch(t){throw D.error(`tool error`,t,{tool:e,...j?.requestId===void 0?{}:{requestId:j.requestId},durationMs:Date.now()-O}),t}}:t}function createLoggedServer(e,t){if(!t.logger)return e;let S=e.tool.bind(e),w=e.registerTool,E=typeof w==`function`?w.bind(e):void 0,D=Object.create(e);return D.tool=((...e)=>{let w=String(e[0]),E=e.at(-1);if(typeof E!=`function`)return S(...e);let D=[...e];return D[D.length-1]=wrapToolHandlerForLogging(w,E,t),S(...D)}),E&&(D.registerTool=((e,S,w)=>typeof w==`function`?E(e,S,wrapToolHandlerForLogging(e,w,t)):E(e,S,w))),D}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.
|
|
2117
2117
|
|
|
2118
2118
|
Topic: ${e}
|
|
@@ -2232,7 +2232,7 @@ Structure:
|
|
|
2232
2232
|
Canonical articles are destinations — they should be **linked heavily from everywhere they're relevant** and link **out to every related page** themselves. Underlinked canonical articles lose most of their value.
|
|
2233
2233
|
|
|
2234
2234
|
- **Inside this article:** every noun-phrase that names another document (other canonical articles, related research, external-source pages, sibling topics) should be a standard markdown link \`[text](./relative/path.md)\`, not plain prose. (Wiki-link syntax \`[[Page]]\` is still parsed for legacy content but no longer the default; matches the OK skill guidance.)
|
|
2235
|
-
- **
|
|
2235
|
+
- **Every link must resolve.** Only link to docs that exist. If you mention a concept that *should* have its own page but doesn't yet, do NOT emit a broken link — either create that page in this pass, or record it as a tracked task (\`TaskCreate\` / your host's task tool; if the host has none, tell the user) and leave the mention as plain prose. A broken link is debt, not a to-do marker.
|
|
2236
2236
|
- **Update neighbors.** After writing, find 2–3 closely-related existing pages (via \`exec("grep -rn <topic> ${t}")\`) and add a link to the new article from each — usually under a "See also" section or inline where the new article is relevant. This makes the article discoverable via backlinks, not just by remembering the path.
|
|
2237
2237
|
- **Link to the sources and superseded research** from "Further reading" — readers who want the trail can follow.
|
|
2238
2238
|
|
|
@@ -2438,7 +2438,7 @@ Six sub-passes, each with its own STOP gate.
|
|
|
2438
2438
|
### 5c. Dead-link sweep (⛔ STOP gate 5c)
|
|
2439
2439
|
|
|
2440
2440
|
1. Run \`links({ kind: "dead" })\` (no \`sourceDocNames\` → audits the whole corpus).
|
|
2441
|
-
2. For each dead link, propose: fix candidate (via \`search\` for the correct target),
|
|
2441
|
+
2. For each dead link, propose: fix candidate (via \`search\` for the correct target), or delete (remove the link, or the prose around it). Leaving it as an "intentional redlink" is not an option — every dead link is fixed or removed.
|
|
2442
2442
|
3. Confirm per dead-link. Apply confirmed fixes via \`edit_document\`.
|
|
2443
2443
|
|
|
2444
2444
|
### 5d. Untextualized-reference detection (⛔ STOP gate 5d)
|
|
@@ -2520,7 +2520,7 @@ Templates added (<folder>/.ok/templates/<name>.md):
|
|
|
2520
2520
|
Link-graph activation:
|
|
2521
2521
|
Orphan triage: 7 orphans triaged (4 adopted, 3 left as intentional standalones)
|
|
2522
2522
|
Hub identification: 3 existing hubs surfaced; 2 templates updated with \`## Related\` sections
|
|
2523
|
-
Dead-link sweep: 5 dead links — 4 fixed, 1
|
|
2523
|
+
Dead-link sweep: 5 dead links — 4 fixed, 1 removed
|
|
2524
2524
|
Untextualized refs: 12 prose mentions linked (across 8 source docs)
|
|
2525
2525
|
Vague-referential: 5 semantic cross-references added (across 4 source docs)
|
|
2526
2526
|
Link-style: standardized 42 wiki-links to relative-markdown
|
|
@@ -3152,7 +3152,7 @@ Run this checklist before marking complete:
|
|
|
3152
3152
|
- [ ] File exists at the chosen path under the content directory
|
|
3153
3153
|
- [ ] Frontmatter has \`title\`, \`description\`, \`status: provisional\`, \`date\`, and a \`sources:\` list
|
|
3154
3154
|
- [ ] \`exec("ls <dir>")\` lists the new file with frontmatter enrichment
|
|
3155
|
-
- [ ] \`links({ kind: 'dead', sourceDocNames: ['<path-without-ext>'] })\` returns clean
|
|
3155
|
+
- [ ] \`links({ kind: 'dead', sourceDocNames: ['<path-without-ext>'] })\` returns clean — zero dead links (fix or remove every one)
|
|
3156
3156
|
- [ ] Every factual claim in Findings cites a source inline
|
|
3157
3157
|
- [ ] Linked source files from Step 3 all exist (broken source links → \`ingest\` went wrong somewhere)
|
|
3158
3158
|
- [ ] At least 1–2 neighbor docs now link to this research (per Step 6's "After writing, update ..." rule)
|
|
@@ -3218,4 +3218,4 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
3218
3218
|
`),S=[],w=!1,E=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){w?RegExp(`^\\s{0,3}${E[0]==="`"?"`":`~`}{${E.length},}\\s*$`).test(e)&&(w=!1,E=``):(w=!0,E=t[1]);continue}if(w)continue;let D=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(D);if(e===null)break;let t=e[2];t&&S.push(t)}}return S}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:S,body:w}=stripFrontmatter(t),E=extractFrontmatterTags(S?unwrapFrontmatterFences(S):``),D=extractInlineTagsFromBody(w),O=new Set([...E,...D]),k=new Set;for(let e of O)for(let t of expandTagToHierarchy(e))k.add(t);this.applyDocSnapshot(e,O,k)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let S of t){let t=this.state.byTag.get(S);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(S))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,S){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,S)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let S=[];for(let w of t){let t=this.state.byDocLiteral.get(w);if(!t)continue;let E=tagsMatchingPrefix(t,e);S.push({docName:w,matchingTags:[...E].sort((e,t)=>e.localeCompare(t))})}return S.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),S=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&S.add(e.slice(0,t));let w=t;for(;w>0;)S.add(e.slice(0,w)),w=e.indexOf(`/`,w+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!S.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:S}of e)try{let e=readFileSync(S,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,S){let w=this.state.byDoc.get(e)??new Set;for(let t of w){if(S.has(t))continue;let w=this.state.byTag.get(t);w&&(w.delete(e),w.size===0&&this.state.byTag.delete(t))}for(let t of S){let S=this.state.byTag.get(t);S||(S=new Set,this.state.byTag.set(t,S)),S.add(e)}S.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,S),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let w of S){let S=join(e,w.name);if(w.isDirectory()){let e=relative(this.contentDir,S);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(S,t);continue}if(!w.isFile()||!isSupportedDocFile(w.name))continue;let E=relative(this.contentDir,S);this.contentFilter?.isExcluded(E)||t.push({docName:stripDocExtension(E),filePath:S})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:S=t,quiet:w=!0,debounce:E=2e3,maxDebounce:D=1e4,gitEnabled:O=!0,commitDebounceMs:k=3e4,wipRef:j=`refs/wip/main`,configHomedirOverride:F,enableTestRoutes:L=!1,shadowRepo:B,contentRoot:H,destroyTimeoutMs:q=1e4,localOpCliArgs:J,skipStateManifestCheck:Y=!1}=e,ee=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||ee.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ne=randomUUID(),ae=getLocalDir(S);if(acquireServerLock(ae,{port:e.port??0,worktreeRoot:S,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!Y)try{assertCompatibleStateManifest({lockDir:ae,shadowRepoDir:resolveShadowDir(S)})}catch(e){throw releaseServerLock(ae),e}let oe=createBasenameIndex(),se=(e,t)=>oe.resolveEmbed(e,t),ce=(e,S)=>{let w=oe.resolveEmbed(e,S);if(!w&&e.includes(`/`)&&(w=e.replace(/^\.?\//,``)),!w)return null;let E=resolve(t,w),D=resolve(t);if(E!==D&&!E.startsWith(`${D}/`))return null;try{let e=statSync(E);return e.isFile()?e.size:null}catch{return null}},ue,de,fe,me,ge,_e,ve,ye=null,Ce=null,we=null,Te=null,De=new Set,je=!1,Me,Pe,Ie,Re=new Promise((e,t)=>{Pe=e,Ie=t});function ze(e){ye?.signal(e)}let Be=2e3,Ve=null;function Ue(){Ve!==null&&clearTimeout(Ve),Ve=setTimeout(()=>{Ve=null,de.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let We=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),Ge=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||We.setRenamed(e,t)},Ke=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(We.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}We.setDeleted(e)}},Xe=e=>{isSystemDoc(e)||isConfigDoc(e)||We.delete(e)};try{ue=createContentFilter({projectDir:S,contentDir:t,onAfterRebuild:()=>{de.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{fe.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let e=Rt?.pruneFileIndexNowExcluded()??0,t=Rt?.pruneFolderIndexNowExcluded()??0,S=e+t;S>0&&getLogger(`server-factory`).info({pruned:S,prunedFiles:e,prunedFolders:t},`[content-filter] pruned now-excluded entries from file indexes`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] file index prune failed after onAfterRebuild`)}}}),de=new BacklinkIndex({projectDir:S,contentDir:t,contentFilter:ue}),fe=new TagIndex({contentDir:t,contentFilter:ue});try{fe.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}me={current:B},ge=createPersistenceExtension({contentDir:t,projectDir:S,gitEnabled:O,commitDebounceMs:k,wipRef:j,shadowRef:me,contentRoot:H,backlinkIndex:de,configHomedirOverride:F,getCurrentBranch:()=>zt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce,getPrincipal:()=>Te,onAgentCommit:()=>ye?.signal(`session-activity`),onDiskFlush:(e,t)=>ye?.emitDiskAck(e,t),onConfigRejected:(e,t)=>ye?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),_e=new Hocuspocus({quiet:w,debounce:E,maxDebounce:D,extensions:[ge.extension]});let q=_e.shouldUnloadDocument.bind(_e);_e.shouldUnloadDocument=e=>{if(De.has(e)||je&&q(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:q(e)},Me=async e=>{De.add(e);try{await _e.unloadDocument(e)}finally{De.delete(e)}},ye=new CC1Broadcaster(_e),Ce=new AgentFocusBroadcaster(_e),we=new AgentPresenceBroadcaster(_e),ve=new AgentSessionManager(_e);let Y=createLiveDerivedIndexExtension({backlinkIndex:de,tagIndex:fe,signalChannel:ze});_e.configuration.extensions.push(Y),_e.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,S=parseHocuspocusAuthToken(t),w=S?.expectedServerInstanceId;if(typeof w==`string`&&w.length>0&&w!==ne)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${w}, this server is ${ne}`);let E=S?.expectedBranch,D=getActiveBranch();if(typeof E==`string`&&E.length>0&&E!==D)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${E}, server is on ${D}`);if(!S)return;let O=e.context;typeof S.principalId==`string`&&(Te&&S.principalId===Te.id?O.principalId=Te.id:Te?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:S.principalId,loaded:Te.id})):O.principalId=S.principalId),typeof S.tabSessionId==`string`&&(O.tabSessionId=S.tabSessionId),O.kind=`human`}}),_e.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,S=t.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S))throw Error(`config-doc admission requires loopback peer (peer=${S}, doc=${e.documentName})`);let w=e.requestHeaders,E=(w&&typeof w.get==`function`?w.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(E))throw Error(`config-doc admission requires loopback Host header (host=${E??`<absent>`}, doc=${e.documentName})`)}});let ee=resolve(t);function te(e){if(!isSafeDocName(e))return null;let t=resolve(ee,`${e}${getDocExtension(e)}`);return!t.startsWith(`${ee}/`)&&t!==ee?null:t}_e.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:We,resolveFilePath:te,fileExists:existsSync})}}),_e.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let ae=createApiExtension({hocuspocus:_e,sessionManager:ve,contentDir:t,contentFilter:ue,serverInstanceId:ne,getFileIndex:()=>Rt?Rt.getFileIndex():new Map,getFolderIndex:()=>Rt?Rt.getFolderIndex():new Map,getAliasMap:()=>Rt?Rt.getAliasMap():new Map,rescanFiles:()=>Rt?.rescanFromDisk(),enableTestRoutes:L,shadowRef:me,flushGitCommit:()=>ge.flushPendingGitCommit(),flushContributors:()=>ge.flushContributors(),getCurrentBranch:()=>zt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ye?.getLatestDiskAckSVsAsBase64()??{},contentRoot:H,backlinkIndex:de,tagIndex:fe,signalChannel:ze,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Bt,localOpCliArgs:J,projectDir:S,resolveEmbed:se,getPrincipal:()=>Te,forceUnloadDocument:Me,ready:Re,recentlyRemovedDocs:We,serializeDoc:at});_e.configuration.extensions.push(ae),_e.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:me,contentRoot:H,getCurrentBranch:()=>zt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce})),_e.configuration.extensions.push(createSyncHandshakeSpanExtension())}catch(e){throw releaseServerLock(ae),e}let $e=null,nt=new Map,rt=[];function it(e,t){let S=resolve(e,`rescue`),w=resolve(S,`${t}${getDocExtension(t)}`);return w.startsWith(`${S}/`)?w:null}function at(e){let t=_e.documents.get(e);if(!t)return null;let{frontmatter:S,body:w}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(S,w)}let st=(e,t)=>applyExternalChange(_e,e,t,se,ce);function vt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Tt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[S]of _e.documents){if(isSystemDoc(S)||isConfigDoc(S))continue;let w=_e.documents.get(S);if(!w)continue;let E=w.getText(`source`).toString();if(E.includes(t))try{w.transact(()=>{applyDiskContentToDoc(w,E,se,S)},FILE_WATCHER_ORIGIN)}catch(t){ee.error({err:t,docName:S,assetBasename:e},`[asset-event] failed to re-render ${S} for asset basename ${e}`)}}},Et=null,Dt=e=>{e&&(Et===null&&(Et=new Set,setImmediate(()=>{let e=Et;if(Et=null,e)try{for(let t of e)Tt(t)}catch(t){ee.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Et.add(e))};function jt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Mt(e){try{switch(e.kind){case`create`:ee.info({docName:e.docName},`[reconcile] create: ${e.docName}`),de.updateDocumentFromMarkdown(e.docName,e.content),Ue(),fe.updateDocumentFromMarkdown(e.docName,e.content),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Xe(e.docName);break;case`update`:{let{docName:t,content:S}=e,w=_e.documents.get(t);if(!w){de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);return}let E=getReconciledBase(t)??``,D=at(t)??E,O=reconcile({docName:t,base:E,ours:D,theirs:S}),k=contentHash(E).slice(0,6),j=contentHash(D).slice(0,6),F=contentHash(S).slice(0,6);switch(ee.info({docName:t,base:k,ours:j,theirs:F,result:O.kind},`[reconcile] ${t} base=${k} ours=${j} theirs=${F} result=${O.kind}`),O.kind){case`noop`:vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);break;case`clean`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,S),vt(w)}break;case`merged`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,S),vt(w)}break;case`conflicts`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),incrementConflict(),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,S)}{let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{incrementConflict();let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,O.reason);break}}break}case`delete`:{let{docName:t}=e,S=_e.documents.get(t);if(!S){de.deleteDocument(t),Ue(),fe.deleteDocument(t),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let w=getReconciledBase(t)??``,E=at(t)??``,D=E!==w;if(D&&me.current){let e=me.current,S=zt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,H??``,{kind:`external-change-rescue`,docName:t,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{ee.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),de.deleteDocument(t),Ue(),fe.deleteDocument(t),ee.info({docName:t,isDirty:D},`[reconcile] delete: ${t} (dirty=${D})`),_e.closeConnections(t),await Me(S),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:S,content:w}=e,E=_e.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(S,w),de.renameDocument(t,S,w),Ue(),fe.renameDocument(t,S,w),E){let e=E.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,S)}ee.info({oldDocName:t,newDocName:S},`[reconcile] rename: ${t} → ${S}`),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ge(t,S),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:S,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,S=_e.documents.get(t);if(!S)return;let w=at(t);w===null?ee.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,w);let E=S.getMap(`lifecycle`);E.set(`status`,`conflict`),E.set(`reason`,`conflict-markers`),ee.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:oe.add(e.relativePath),ze(`files`),Dt(basename(e.relativePath));break;case`asset-delete`:oe.remove(e.relativePath),ze(`files`),Dt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:ze(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let S=jt(e);ee.error({err:t,kind:e.kind,label:S},`[reconcile] failed to handle ${e.kind} for ${S}`)}}let Ft=[];async function It(e){if(isBatchInProgress()){Ft.push(e);return}await Mt(e)}async function Lt(){let e=Ft.splice(0,Ft.length);for(let t of e)await Mt(t)}let Rt=null,zt=null,Bt=null,Vt=null;async function Ht(e){if(_e.documents.size===0)return;let t=!1,S=new Promise(e=>{_e.configuration.extensions.push({async afterUnloadDocument({instance:S}){!t&&S.getDocumentsCount()===0&&(t=!0,e())}})}),w=Array.from(_e.documents.keys());_e.closeConnections(),_e.flushPendingStores();for(let e of _e.documents.values())e.getConnectionsCount()===0&&_e.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let E,D=new Promise((S,D)=>{E=setTimeout(()=>{t=!0;let S=Array.from(_e.documents.keys()),E=[],O=[];if(me.current){for(let e of S)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=at(e);if(t===null){ee.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),O.push(e);continue}let S=it(me.current.gitDir,e);if(!S){ee.warn({docName:e,gitDir:me.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),O.push(e);continue}mkdirSync(dirname(S),{recursive:!0}),writeFileSync(S,t,`utf-8`),incrementRescueBuffer(),E.push(e),ee.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){O.push(e),ee.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else ee.warn({stillLoadedCount:S.length},`[rescue] shadow repo unavailable at flush timeout — ${S.length} doc(s) will be lost: [${S.join(`, `)}]`),O.push(...S);let k=E.length>0||O.length>0?` — rescued [${E.join(`, `)}]${O.length>0?`, lost [${O.join(`, `)}]`:``}`:``;D(Error(`flushAllStoresAndWait timeout after ${e}ms — ${S.length}/${w.length} docs did not unload: [${S.join(`, `)}]${k}`))},e)});try{await Promise.race([S,D])}finally{E!==void 0&&clearTimeout(E)}}async function Ut(){return Vt||(Vt=(async()=>{let e=Date.now(),t=[];je=!0,Ve!==null&&(clearTimeout(Ve),Ve=null);let w,E=await Promise.race([Re.then(()=>`completed`,e=>(ee.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{w=setTimeout(()=>e(`timeout`),5e3)})]);w!==void 0&&clearTimeout(w),E===`timeout`&&ee.warn({},`[server] init did not complete within 5s during shutdown`);let D=_e.documents.size;try{try{try{zt&&=(await zt.unsubscribe(),null),Rt&&=(await Rt.unsubscribe(),null);for(let{docName:e,cleanup:t}of rt)try{await t()}catch(t){ee.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}rt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ye?.destroy(),we?.destroy(),$e&&=(await $e.disconnect(),null);for(let[e,t]of nt)try{await t.disconnect()}catch(t){ee.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}nt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ve.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Ht(q)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ge.flushPendingGitCommit(),await ge.waitForPendingCommits()})(),new Promise((t,S)=>{e=setTimeout(()=>S(Error(`L2 git flush timeout`)),q)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Bt&&=(await Bt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(me.current){try{let e=(await esm_default({baseDir:S,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(me.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(me.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let w=Date.now()-e;t.length===0?ee.info({documentCount:D,durationMs:w},`[server] shutdown flushed ${D} documents in ${w}ms`):ee.warn({documentCount:D,durationMs:w,phaseErrors:t},`[server] shutdown flushed ${D} documents in ${w}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ae)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Vt)}let Wt=[];async function Kt(){try{Te=await loadPrincipal(S),ee.info({principalId:Te.id},`[server] principal loaded`)}catch(e){ee.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!me.current)try{me.current=await initShadowRepo(S),ee.info({gitDir:me.current.gitDir},`[server] history repo initialized at ${me.current.gitDir}`)}catch(e){ee.error({err:e},`[server] history repo init failed`),Wt.push(`shadow-repo`)}if(me.current){let e=null;try{e=loadRenameLogIndex(me.current.gitDir),sweepLazyPopOrphans(me.current.gitDir,e),setRenameLogIndex(me.current.gitDir,e),ee.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){ee.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(me.current,e,{rebuild:!0}),new Promise((e,S)=>setTimeout(()=>S(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){ee.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(me.current)try{await shadowGit(me.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){ee.warn({},`[server] history repo appears corrupted — reinitializing`);try{me.current=await initShadowRepo(S)}catch(e){ee.error({err:e},`[server] history repo reinit failed`),me.current=void 0,Wt.includes(`shadow-repo`)||Wt.push(`shadow-repo`)}}else ee.error({err:e},`[server] history repo check failed (transient?)`)}if(me.current)try{let e=resolve(me.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let w=null;try{w=(await esm_default({baseDir:S,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(w!==null){if(w!==t){let e=`main`;try{let t=(await esm_default({baseDir:S,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}ee.info({lastKnownHead:t,currentHead:w,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=import`);try{await commitUpstreamImport(me.current,H??``,t,w,e),incrementUpstreamImport()}catch(e){ee.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else ee.info({currentHead:w},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=noop`);try{writeFileSync(e,w,`utf-8`)}catch(e){ee.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){ee.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,S);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,S=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;ee.warn({journalVersion:e.journal.version,fromPath:t,toPath:S,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${S}`)}}catch(e){ee.error({err:e},`[server] managed rename recovery failed`),Wt.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(S);(e.deleted>0||e.errors>0)&&ee.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){ee.error({err:e},`[server] upload-tempfile sweep failed`),Wt.push(`upload-tempfile-sweep`)}try{$e=await _e.openDirectConnection(SYSTEM_DOC_NAME),ye?.emitServerInfo(ne,getActiveBranch())}catch(e){ee.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Wt.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await _e.openDirectConnection(e);nt.set(e,t)}catch(t){ee.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Wt.push(`config-doc:${e}`)}let e=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,S)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,S)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,S,F)]]);for(let t of CONFIG_DOC_NAMES){let S=e.get(t);if(S)try{ee.info({docName:t,path:S},`[config-file-watcher] starting`);let e=await startConfigFileWatcher(S,e=>{let S=_e.documents.get(t);ee.info({docName:t,hasDocument:S!==void 0,contentLength:e.length},`[config-file-watcher] file changed`);let w=applyExternalConfigChange(S??null,t,e,ge.configPersistenceCtx);if(ee.info({docName:t,outcome:w},`[config-file-watcher] applyExternalConfigChange outcome`),t===`__config__/project`||t===`__local__/project`){let e=te();Bt?.setEnabled(e).catch(t=>{ee.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});rt.push({docName:t,cleanup:e}),ee.info({docName:t,path:S},`[config-file-watcher] started`)}catch(e){ee.warn({err:e,docName:t,path:S},`[config-file-watcher] failed to start for ${t}`),Wt.push(`config-file-watcher:${t}`)}}try{let e=resolve(t,`.okignore`),w=resolve(S,`.gitignore`),E=ee;E.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore`);let D=await startMultiPathConfigFileWatcher([e,w],(t,w)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(_e.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,w,ge.configPersistenceCtx);E.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){E.error({err:e,changedPath:relative(S,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let D=await ue.rebuildIgnorePatterns();if(D.ok)E.info({changedPath:relative(S,t),patternCount:D.patternCount,nestedFileCount:D.nestedFileCount,durationMs:D.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ye?.signal(`files`);else{let e=relative(S,t)||`.`;E.warn({changedPath:e,error:D.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ye?.emitConfigIgnoreNestedError(e,D.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(S,t)||`.`},`[ignore-watcher] handler threw`)})});rt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] multi-path watcher started`)}catch(e){ee.warn({err:e,projectDir:S,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Wt.push(`ignore-files-watcher`)}let w=resolveGitDir(S),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),de.switchBranch(E);try{{let e=getActiveBranch();try{if(await de.loadFromDisk(e)){let t=await de.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&ee.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await de.rebuildFromDisk(e);de.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){ee.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Rt=await startWatcher(t,It,ue),fe.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,w)=>{e++,ee.warn({reason:t,code:S,path:w},`[basename-index] skipped entry during seed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Wt.push(`basename-index-partial`))}catch(e){ee.error({err:e},`[basename-index] startup seed failed`),Wt.push(`basename-index`)}}catch(e){ee.error({err:e},`[server] disk bridge watcher failed to start`),Wt.push(`file-watcher`)}try{zt=await startHeadWatcher(S,async({trigger:e})=>{if(ee.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),_e.flushPendingStores(),await ge.flushPendingGitCommit(),setBatchInProgress(!0),me.current){let e=getActiveBranch(),t=resolveGitDir(S),w=t?readBranchFromHead(t)??e:e,E=[];for(let[e,t]of _e.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let S=null;if(t.transact(()=>{S=at(e)},PARK_SNAPSHOT_ORIGIN),S===null)continue;let w=getReconciledBase(e)??S;E.push({docName:e,markdown:S,diskSnapshot:w})}if(E.length>0)try{let t=await parkBranch(me.current,e,SERVICE_WRITER.id,E,w);t&&(incrementPark(),ee.info({count:E.length,branch:e,sha:t.slice(0,8)},`[history] parked ${E.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){ee.error({err:e},`[shadow] park failed`)}}},async e=>{let S=Ft.length,w=e.newBranch??`main`;if(ee.info({kind:e.batchKind,headMoved:e.headMoved,docs:S,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${S}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await Lt(),await ge.flushDeferredStores(`within-branch`),Bt!==null)try{await Bt.reconcileConflictsFromGit()}catch(e){ee.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),Ft.splice(0,Ft.length),switchReconciledBaseScope(w),Ve!==null&&(clearTimeout(Ve),Ve=null),de.switchBranch(w),ue.rebuildDirCount();try{let e=0;oe.clear(),seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,E)=>{e++,ee.warn({reason:t,code:S,path:E,branch:w},`[basename-index] skipped entry during branch-switch reseed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e,branch:w},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Wt.includes(`basename-index-partial`)||Wt.push(`basename-index-partial`))}catch(e){ee.error({err:e,branch:w},`[basename-index] branch-switch reseed failed`)}for(let[e,S]of _e.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let E=safeContentPath(e,t);if(!existsSync(E)){let t=getReconciledBase(e)??``,E=at(e)??``;if(E!==t&&me.current){let t=me.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,H??``,{kind:`external-change-rescue`,docName:e,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:w,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{ee.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),ee.info({docName:e,branch:w},`[branch-switch] tombstone: ${e} (not on ${w})`);continue}let D=readFileSync(E,`utf-8`);st(e,D),setReconciledBase(e,D),ee.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){ee.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}ee.info({branch:w,docCount:_e.documents.size},`[branch-switch] loaded branch ${w} (${_e.documents.size} docs)`);try{if(await de.loadFromDisk(w)){let e=await de.reconcileWithDisk(w);(e.added>0||e.updated>0||e.deleted>0)&&ee.info(e,`[backlinks] branch-switch reconcile for ${w}`)}else await de.rebuildFromDisk(w);de.saveToDisk(w).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${w}:`,e)})}catch(e){ee.error({err:e,branch:w},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(fe.init(),me.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of _e.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let S=await readParkedState(me.current,w,SERVICE_WRITER.id,t);if(!S||S.markdown===S.diskSnapshot)continue;let E=getReconciledBase(t);if(!E)continue;let D=reconcile({docName:t,base:S.diskSnapshot,ours:S.markdown,theirs:E});switch(D.kind){case`merged`:case`clean`:st(t,D.newContent),setReconciledBase(t,D.newContent),e++;break;case`conflicts`:st(t,D.newContent),setReconciledBase(t,D.newContent),incrementConflict(),e++;{let e=_e.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){ee.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&ee.info({count:e,branch:w},`[branch-switch] restored ${e} parked docs on ${w}`)}if(e.oldBranch?.startsWith(`detached-`)&&me.current)try{let t=shadowGit(me.current),S=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(S){for(let e of S.split(`
|
|
3219
3219
|
`))e&&await t.raw(`update-ref`,`-d`,e);ee.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){ee.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ge.flushDeferredStores(`discard-stale`),ye?.emitBranchSwitched(w)}if(e.headMoved&&e.newHead&&me.current&&S>0){let t=H??`.`;try{let S=await commitUpstreamImport(me.current,t,e.oldHead,e.newHead,w);incrementUpstreamImport(),ee.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:S.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${S.slice(0,8)}`)}catch(e){ee.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){ee.error({err:e},`[server] HEAD watcher failed to start`),Wt.push(`head-watcher`)}let D=J?.[0]??`open-knowledge`,O=[`-c`,`credential.helper=!${J&&J.length>1?J.join(` `):D} auth git-credential`];try{Bt=new SyncEngine({projectDir:S,contentDir:t,contentFilter:ue,contentRoot:H,syncEnabled:te(),credentialArgs:O,cc1Broadcaster:ye,setBatchInProgress:e=>{setBatchInProgress(e),e||ge.flushDeferredStores(`within-branch`).catch(e=>{ee.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{ee.info({state:e},`[sync] state → ${e}`)},onAutoDisable:async e=>{ee.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:S,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||ee.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,S)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await Bt.start()}catch(e){ee.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Bt=null}ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`)}return Kt().then(Pe,Ie),{hocuspocus:_e,sessionManager:ve,cc1Broadcaster:ye,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,contentFilter:ue,basenameIndex:oe,serverInstanceId:ne,destroy:Ut,ready:Re,degraded:Wt,lockDir:ae,get syncEngine(){return Bt}}}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let S=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&S.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let w=resolve(e,t);try{existsSync(w)&&statSync(w).isDirectory()&&S.push(`${t}/`)}catch{}}return S}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3;async function bootServer(e){initTelemetry();let{kind:t,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":t};return S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S)),withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,S=e.attachUiSibling??!0,w=e.idleShutdownMs,E=e.log??getLogger(`boot`),D=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,O=e.lockKind??D??`interactive`,{createServer:k}=await import(`node:http`),{updateServerLockPort:j}=await import(`./server-lock-BniQ3qki-DjKtnzVr.mjs`).then(e=>e.a),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){E.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let H=findLegacyRuntimeFiles(B);H.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${H.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let q=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:O,skipStateManifestCheck:e.skipStateManifestCheck}),{hocuspocus:J,destroy:Y,ready:ee,degraded:te,lockDir:ne,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se}=q,ce=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ue=e.port??0,de=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:E}),fe=k();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:q.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0;if(e.reactShellDistDir)try{acquireUiLock(ne,{port:0,worktreeRoot:e.projectDir??e.contentDir})}catch(e){throw await Y().catch(()=>{}),e}let ge=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,_e=mountMcpAndApi({httpServer:fe,hocuspocus:J,mcpHttpHandler:de,log:E,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:ge}),ve=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ye=null;w!==null&&(ye=attachIdleShutdown({httpServer:fe,thresholdMs:w??DEFAULT_IDLE_THRESHOLD_MS,log:E,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ve()})})),await restoreLifecycleFromConflictsJson({hocuspocus:J,projectDir:e.projectDir??e.contentDir,log:E});try{await new Promise((t,S)=>{let w=e=>S(e);fe.once(`error`,w),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,w),t()})})}catch(t){if(e.reactShellDistDir)try{releaseUiLock(ne)}catch(e){E.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await Y().catch(()=>{}),t}let Ce=fe.address(),we=typeof Ce==`object`&&Ce?Ce.port:e.port??0;if(ue=we,j(ne,we),e.reactShellDistDir&&updateUiLockPort(ne,we),S&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ne,log:E})}catch(e){E.warn({err:e},`spawnUiSiblingFn failed`)}let Te=!1,De=async(e,t)=>{let S;try{await Promise.race([t(),new Promise((t,w)=>{S=setTimeout(()=>{w(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),S.unref?.()})])}finally{S!==void 0&&clearTimeout(S)}};return ve=async()=>{if(Te)return;Te=!0;let t=[],S=async(e,S)=>{try{await De(e,S)}catch(S){t.push(S),E.warn({err:S,step:e},`bootServer destroy step failed`)}};try{ye?.detach()}catch(e){t.push(e),E.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await S(`mount.shutdown`,()=>_e.shutdown()),await S(`mcpHttpHandler.close`,()=>de.close()),await S(`mount.wss.close`,()=>new Promise((e,t)=>{_e.wss.close(S=>S?t(S):e())})),await S(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await S(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(S=>S&&S.code!==`ERR_SERVER_NOT_RUNNING`?t(S):e())})),await S(`destroyHocuspocus`,()=>Y()),e.reactShellDistDir&&await S(`releaseUiLock`,async()=>releaseUiLock(ne)),await S(`shutdownTelemetry`,()=>shutdownTelemetry()),t.length>0)throw AggregateError(t,`bootServer destroy completed with errors`)},{httpServer:fe,destroy:ve,lockDir:ne,contentDir:e.contentDir,port:we,ready:ee,degraded:te,didAutoInit:F,serverInstance:q}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:S,log:w}=e,E,D;try{E=new ConflictStore(S),D=E.list()}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(D.length===0)return;let O=null;try{let e=resolveGitDir(S),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){E.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:D.length}));return}let w=(await simpleGit({baseDir:S,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();O=new Set(w?w.split(`
|
|
3220
3220
|
`).map(e=>e.trim()).filter(Boolean):[])}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(O!==null){let e=0;for(let t of D)O.has(t.file)||(E.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:D.length-e})),D=D.filter(e=>O?.has(e.file)),D.length===0)return}for(let e of D){let S=stripDocExtension(e.file),E=null,D=!1;try{E=await t.openDirectConnection(S);let e=E.document;if(!e)continue;let w=e.getMap(`lifecycle`);w.set(`status`,`conflict`),w.set(`reason`,`conflict-markers`),D=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":S}))}catch(e){w.warn({err:e,docName:S},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(E)try{await E.disconnect()}catch(e){w.warn({err:e,docName:S,restored:D},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),S=e.platformName??process.platform,w=e.env??process.env;return S===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):S===`win32`?existsSync(join(w.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),S=0;for(;S<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:S};let w=dirname(t);if(w===t)return null;t=w,S+=1}return null}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,S){super(e,S),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),S=resolve(t,`.git`),w=resolve(S,`HEAD`),E=!1;if(existsSync(S)){if(!statSync(S).isDirectory()||existsSync(w))return{didInit:!1};console.log(`[project-git] detected partial .git/ — running git init to repair`),E=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let D=``;try{D=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let S=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,S,{cause:e})}if(!existsSync(w))throw new ProjectGitInitError(`git init reported success but ${S}/HEAD is missing (partial init detected)`,D);return E?(console.log(`[project-git] backfilled missing .git/HEAD at ${t}`),{didInit:!0,repaired:!0}):(console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0})}async function resolvePackageVersion(e,t){let S;try{S=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(S),w=0;w<32;w+=1){let S=join(t,`package.json`);if(existsSync(S))try{let t=JSON.parse(await readFile$1(S,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let w=dirname(t);if(w===t)return;t=w}}export{assertNeverDiskEvent as $,rewriteWikiLinksForDocumentRename as $n,ALL_EDITOR_IDS as $r,initShadowRepo as $t,MissingOkConfigError as A,url as Ai,readSkillInstallStateSnapshot as An,tracedWriteFile as Ar,createTestLogger as At,STARTER_PACK_IDS as B,releaseUiLock as Bn,writeTargetVersion as Br,formatContributors as Bt,LOG_MD_TEMPLATE as C,array as Ci,parseHocuspocusAuthToken as Cn,tracedMkdir as Cr,createLiveDerivedIndexExtension as Ct,MCP_SERVER_NAME as D,number$1 as Di,readAllTargets as Dn,tracedRmSync as Dr,createServer$1 as Dt,MCP_CONNECTION_ID_HEADER as E,looseObject as Ei,planSeed as En,tracedRenameSync as Er,createPersistenceExtension as Et,SERVICE_WRITER as F,reconcile as Fn,validateCloneInputs as Fr,evictStaleTrackerEntries as Ft,StateManifestError as G,resolveCursorBinaryDefault as Gn,isInitializedNotification as Gr,getLogger as Gt,STATE_MANIFEST_FILENAME as H,resetMetrics as Hn,McpServer as Hr,gcCheckpointRefs as Ht,SKILL_INSTALL_EVENTS_FILE_REL as I,recordContributor as In,validateSkillZip as Ir,extractWikiLinksFromMarkdown as It,acquireUiLock as J,resolvePack as Jn,readConfigSafely as Jr,getTracer as Jt,TagIndex as K,resolveCursorSpawnInvocation as Kn,isJSONRPCRequest as Kr,getMeter as Kt,STARTER_FOLDERS as L,recordSkillInstallEvent as Ln,withSpan as Lr,findEnclosingGitRoot as Lt,PinoLogger as M,NEVER as Mi,readTargetRecordedAt as Mn,updateLastKnownHash as Mr,detectProjectShape as Mt,ProjectGitInitError as N,require_dist$2 as Ni,readTargetVersion as Nn,updateUiLockPort as Nr,ensureProjectGit as Nt,MISSING_OK_CONFIG_MESSAGE as O,object$1 as Oi,readBranchFromHead as On,tracedRmdirSync as Or,createServerObserverExtension as Ot,ROLLBACK_ORIGIN as P,readUiLock as Pn,validateAgentId as Pr,errorResponse as Pt,assertCompatibleStateManifest as Q,rewriteMarkdownLinksForDocumentRename as Qn,MalformedGitPointerError as Qr,incrementServerObserverFire as Qt,STARTER_FOLDER_FRONTMATTER_FILENAME as R,registerAllTools as Rn,withSpanSync as Rr,findEnclosingProjectRoot as Rt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as S,any$1 as Si,parseAuthRejectionWire as Sn,tracedLinkSync as Sr,createExternalChangeHandler as St,MAX_AGENT_SESSIONS as T,literal as Ti,pathToDocName as Tn,tracedRename as Tr,createOsProbe as Tt,SeedPrerequisiteError as U,resolveBundledSkillDir as Un,JSONRPCMessageSchema as Ur,getCurrentMcpLogger as Ut,STARTER_TEMPLATES as V,removeLastKnownHash as Vn,writeTracker as Vr,formatContributorsFrom as Vt,SeedRootDirError as W,resolveContentDir as Wn,LATEST_PROTOCOL_VERSION as Wr,getLocalDir as Wt,applyExternalChange as X,restoreContributors as Xn,writeConfigPatch as Xr,handleSpawnCursor as Xt,applyAgentMarkdownWrite as Y,resolvePackageVersion as Yn,resolveConfigPath as Yr,handleCollabSocketError as Yt,applySeed as Z,restoreLifecycleFromConflictsJson as Zn,GitDirAccessError as Zr,incrementCollabSocketFilteredError as Zt,GIT_UPSTREAM_WRITER as _,CONFIG_SCHEMA_MAJOR_PATH as _i,listStarterPacks as _n,startWatcher as _r,contributorCount as _t,AgentPresenceBroadcaster as a,EXECUTABLE_BLOCKLIST_EXTENSIONS as ai,isAllowedWorkspaceHostHeader as an,safeContentPath as ar,buildSkillZip as at,HocuspocusAuthTokenSchema as b,locateIssue as bi,mountMcpAndApi as bn,toBroadcasterKey as br,createContentFilter as bt,BacklinkIndex as c,ProblemDetailsSchema as ci,isKnownPackId as cn,sanitizeClientName as cr,classifyEvents as ct,CURSOR_BUNDLE_PATHS_BY_PLATFORM as d,colorFromSeed as di,isPathWithinDir as dn,seedBasenameIndex as dr,coercePackId as dt,ASSET_EXTENSIONS as ei,initTelemetry as en,runAuthReposSubprocess as er,attachIdleShutdown as et,ConfigSchema as f,defaultScheduler as fi,isProjectRoot as fn,setActiveSpanAttributes as fr,commitUpstreamImport as ft,FILE_WATCHER_ORIGIN as g,isOrphanMode as gi,listRescueCheckpoints as gn,splitMarkdownBlocks as gr,contentHash as gt,FILE_SYSTEM_WRITER as h,isBranchNotFoundGitError as hi,lastKnownHash as hn,spawnDetached as hr,containsConflictMarkers as ht,AgentFocusBroadcaster as i,EDITOR_LABELS as ii,isAllowedApiOrigin as in,runWithMcpLogger as ir,buildInstructions as it,OBSERVER_SYNC_ORIGIN as j,_coercedNumber as ji,readStateManifest as jn,tracedWriteFileSync as jr,detectClaudeDesktopPresence as jt,McpLogger as k,string$2 as ki,readServerPackageVersion as kn,tracedUnlinkSync as kr,createStreamingErrorWriter as kt,CC1Broadcaster as l,SKILL_STATE_TARGETS as li,isLoopbackAddress as ln,saveInMemoryCheckpoint as lr,classifyFsPath as lt,DEFAULT_PACK_ID as m,iconFromClientName as mi,isSystemDoc as mn,shutdownTelemetry as mr,commitWipFromTree as mt,AGENT_ID_RE as n,DEFAULT_GITHUB_OAUTH_CLIENT_ID as ni,installTestLoggers as nn,runCloneSubprocess as nr,buildAndOpenSkill as nt,AgentSessionCapacityError as o,INLINE_RENDERABLE_EXTENSIONS as oi,isConfigDoc as on,safeSubdir as or,buildStarterFolderFrontmatterYaml as ot,DEFAULT_CHECKPOINT_RETENTION as p,humanFormat as pi,isSelfWrite as pn,shadowGit as pr,commitWip as pt,UiLockCollisionError as q,resolveLockDir as qn,isJSONRPCResultResponse as qr,getMetrics as qt,AGENT_WRITE_ORIGIN as r,DEFAULT_SERVER_HOST as ri,installUserSkill as rn,runDeviceFlowSubprocess as rr,buildExecResult as rt,AgentSessionManager as s,ORPHAN_MODES as si,isHocuspocusAuthRejectionReason as sn,safetyCheckpoint as sr,buildWipTree as st,AGENT_ID_MAX_LEN as t,CC1_CONTRACT_VERSION as ti,installPrettyZodErrors as tn,runAuthStatusSubprocess as tr,bootServer as tt,CONFLICT_MARKER_RE as u,SYSTEM_DOC_NAME as ui,isPairedWriteOrigin as un,saveVersion as ur,clearContributors as ut,HOCUSPOCUS_AUTH_REJECTION_REASONS as v,LOCAL_DIR as vi,loadPrincipal as vn,streamingProblemEvent as vr,createApiExtension as vt,MANAGED_RENAME_ORIGIN as w,boolean$1 as wi,parseKeepaliveConnectionId as wn,tracedMkdirSync as wr,createMcpHttpHandler as wt,INSTALLED_AGENTS_SCHEMES as x,ZodNumber$1 as xi,normalizeFsPath as xn,tracedAppendFileSync as xr,createContentFilterAsync as xt,HocuspocusAuthRejection as y,OK_PROJECT_MARKER as yi,loggerFactory as yn,swapContributors as yr,createAssetServeMiddleware as yt,STARTER_PACKS as z,registerWrite as zn,writeStateManifest as zr,formatAuthRejectionWire as zt};
|
|
3221
|
-
//# sourceMappingURL=dist-
|
|
3221
|
+
//# sourceMappingURL=dist-Dg6O3Q9A.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as e,$n as t,$t as n,A as r,An as i,Ar as a,At as o,B as s,Bn as c,Br as l,Bt as u,C as d,Cn as f,Cr as p,Ct as m,D as h,Dn as g,Dr as _,Dt as v,E as y,En as b,Er as x,Et as S,F as C,Fn as w,Fr as T,Ft as E,G as D,Gn as O,Gt as k,H as A,Hn as j,Ht as M,I as N,In as P,Ir as F,It as I,J as L,Jn as R,Jt as z,K as B,Kn as V,Kt as H,L as U,Ln as W,Lr as G,Lt as K,M as q,Mn as J,Mr as Y,Mt as X,N as Z,Nn as Q,Nr as $,Nt as ee,O as te,On as ne,Or as re,Ot as ie,P as ae,Pn as oe,Pr as se,Pt as ce,Q as le,Qn as ue,Qr as de,Qt as fe,R as pe,Rn as me,Rr as he,Rt as ge,S as _e,Sn as ve,Sr as ye,St as be,T as xe,Tn as Se,Tr as Ce,Tt as we,U as Te,Un as Ee,Ut as De,V as Oe,Vn as ke,Vr as Ae,Vt as je,W as Me,Wn as Ne,Wt as Pe,X as Fe,Xn as Ie,Xt as Le,Y as Re,Yn as ze,Yt as Be,Z as Ve,Zn as He,Zr as Ue,Zt as We,_ as Ge,_n as Ke,_r as qe,_t as Je,a as Ye,an as Xe,ar as Ze,at as Qe,b as $e,bn as et,br as tt,bt as nt,c as rt,cn as it,cr as at,ct as ot,d as st,di as ct,dn as lt,dr as ut,dt,en as ft,er as pt,et as mt,f as ht,fn as gt,fr as _t,ft as vt,g as yt,gi as bt,gn as xt,gr as St,gt as Ct,h as wt,hn as Tt,hr as Et,ht as Dt,i as Ot,in as kt,ir as At,it as jt,j as Mt,jn as Nt,jr as Pt,jt as Ft,k as It,kn as Lt,kr as Rt,kt as zt,l as Bt,li as Vt,ln as Ht,lr as Ut,lt as Wt,m as Gt,mi as Kt,mn as qt,mr as Jt,mt as Yt,n as Xt,nn as Zt,nr as Qt,nt as $t,o as en,on as tn,or as nn,ot as rn,p as an,pn as on,pr as sn,pt as cn,q as ln,qn as un,qt as dn,r as fn,rn as pn,rr as mn,rt as hn,s as gn,si as _n,sn as vn,sr as yn,st as bn,t as xn,ti as Sn,tn as Cn,tr as wn,tt as Tn,u as En,ui as Dn,un as On,ur as kn,ut as An,v as jn,vn as Mn,vr as Nn,vt as Pn,w as Fn,wn as In,wr as Ln,wt as Rn,x as zn,xn as Bn,xr as Vn,xt as Hn,y as Un,yn as Wn,yr as Gn,yt as Kn,z as qn,zn as Jn,zr as Yn,zt as Xn}from"./dist-
|
|
1
|
+
import{$ as e,$n as t,$t as n,A as r,An as i,Ar as a,At as o,B as s,Bn as c,Br as l,Bt as u,C as d,Cn as f,Cr as p,Ct as m,D as h,Dn as g,Dr as _,Dt as v,E as y,En as b,Er as x,Et as S,F as C,Fn as w,Fr as T,Ft as E,G as D,Gn as O,Gt as k,H as A,Hn as j,Ht as M,I as N,In as P,Ir as F,It as I,J as L,Jn as R,Jt as z,K as B,Kn as V,Kt as H,L as U,Ln as W,Lr as G,Lt as K,M as q,Mn as J,Mr as Y,Mt as X,N as Z,Nn as Q,Nr as $,Nt as ee,O as te,On as ne,Or as re,Ot as ie,P as ae,Pn as oe,Pr as se,Pt as ce,Q as le,Qn as ue,Qr as de,Qt as fe,R as pe,Rn as me,Rr as he,Rt as ge,S as _e,Sn as ve,Sr as ye,St as be,T as xe,Tn as Se,Tr as Ce,Tt as we,U as Te,Un as Ee,Ut as De,V as Oe,Vn as ke,Vr as Ae,Vt as je,W as Me,Wn as Ne,Wt as Pe,X as Fe,Xn as Ie,Xt as Le,Y as Re,Yn as ze,Yt as Be,Z as Ve,Zn as He,Zr as Ue,Zt as We,_ as Ge,_n as Ke,_r as qe,_t as Je,a as Ye,an as Xe,ar as Ze,at as Qe,b as $e,bn as et,br as tt,bt as nt,c as rt,cn as it,cr as at,ct as ot,d as st,di as ct,dn as lt,dr as ut,dt,en as ft,er as pt,et as mt,f as ht,fn as gt,fr as _t,ft as vt,g as yt,gi as bt,gn as xt,gr as St,gt as Ct,h as wt,hn as Tt,hr as Et,ht as Dt,i as Ot,in as kt,ir as At,it as jt,j as Mt,jn as Nt,jr as Pt,jt as Ft,k as It,kn as Lt,kr as Rt,kt as zt,l as Bt,li as Vt,ln as Ht,lr as Ut,lt as Wt,m as Gt,mi as Kt,mn as qt,mr as Jt,mt as Yt,n as Xt,nn as Zt,nr as Qt,nt as $t,o as en,on as tn,or as nn,ot as rn,p as an,pn as on,pr as sn,pt as cn,q as ln,qn as un,qt as dn,r as fn,rn as pn,rr as mn,rt as hn,s as gn,si as _n,sn as vn,sr as yn,st as bn,t as xn,ti as Sn,tn as Cn,tr as wn,tt as Tn,u as En,ui as Dn,un as On,ur as kn,ut as An,v as jn,vn as Mn,vr as Nn,vt as Pn,w as Fn,wn as In,wr as Ln,wt as Rn,x as zn,xn as Bn,xr as Vn,xt as Hn,y as Un,yn as Wn,yr as Gn,yt as Kn,z as qn,zn as Jn,zr as Yn,zt as Xn}from"./dist-Dg6O3Q9A.mjs";import{_ as Zn,a as Qn,c as $n,d as er,f as tr,g as nr,i as rr,l as ir,m as ar,n as or,o as sr,p as cr,r as lr,s as ur,t as dr,u as fr}from"./server-lock-BniQ3qki-CadPGoZN.mjs";export{xn as AGENT_ID_MAX_LEN,Xt as AGENT_ID_RE,fn as AGENT_WRITE_ORIGIN,Ot as AgentFocusBroadcaster,Ye as AgentPresenceBroadcaster,en as AgentSessionCapacityError,gn as AgentSessionManager,rt as BacklinkIndex,Bt as CC1Broadcaster,Sn as CC1_CONTRACT_VERSION,En as CONFLICT_MARKER_RE,st as CURSOR_BUNDLE_PATHS_BY_PLATFORM,ht as ConfigSchema,an as DEFAULT_CHECKPOINT_RETENTION,Gt as DEFAULT_PACK_ID,wt as FILE_SYSTEM_WRITER,yt as FILE_WATCHER_ORIGIN,Ge as GIT_UPSTREAM_WRITER,Ue as GitDirAccessError,jn as HOCUSPOCUS_AUTH_REJECTION_REASONS,Un as HocuspocusAuthRejection,$e as HocuspocusAuthTokenSchema,zn as INSTALLED_AGENTS_SCHEMES,_e as LIVE_DERIVED_INDEX_DEBOUNCE_MS,d as LOG_MD_TEMPLATE,Fn as MANAGED_RENAME_ORIGIN,xe as MAX_AGENT_SESSIONS,y as MCP_CONNECTION_ID_HEADER,h as MCP_SERVER_NAME,te as MISSING_OK_CONFIG_MESSAGE,de as MalformedGitPointerError,It as McpLogger,r as MissingOkConfigError,Mt as OBSERVER_SYNC_ORIGIN,_n as ORPHAN_MODES,q as PinoLogger,dr as ProcessLockCollisionError,Z as ProjectGitInitError,ae as ROLLBACK_ORIGIN,or as RUNTIME_VERSION,C as SERVICE_WRITER,N as SKILL_INSTALL_EVENTS_FILE_REL,Vt as SKILL_STATE_TARGETS,U as STARTER_FOLDERS,pe as STARTER_FOLDER_FRONTMATTER_FILENAME,qn as STARTER_PACKS,s as STARTER_PACK_IDS,Oe as STARTER_TEMPLATES,A as STATE_MANIFEST_FILENAME,lr as STATE_SCHEMA_VERSION,Dn as SYSTEM_DOC_NAME,Te as SeedPrerequisiteError,Me as SeedRootDirError,rr as ServerLockCollisionError,D as StateManifestError,B as TagIndex,ln as UiLockCollisionError,Qn as acquireProcessLock,sr as acquireServerLock,L as acquireUiLock,Re as applyAgentMarkdownWrite,Fe as applyExternalChange,Ve as applySeed,le as assertCompatibleStateManifest,e as assertNeverDiskEvent,mt as attachIdleShutdown,Tn as bootServer,$t as buildAndOpenSkill,hn as buildExecResult,jt as buildInstructions,Qe as buildSkillZip,rn as buildStarterFolderFrontmatterYaml,bn as buildWipTree,ot as classifyEvents,Wt as classifyFsPath,An as clearContributors,dt as coercePackId,ct as colorFromSeed,vt as commitUpstreamImport,cn as commitWip,Yt as commitWipFromTree,Dt as containsConflictMarkers,Ct as contentHash,Je as contributorCount,Pn as createApiExtension,Kn as createAssetServeMiddleware,nt as createContentFilter,Hn as createContentFilterAsync,be as createExternalChangeHandler,m as createLiveDerivedIndexExtension,Rn as createMcpHttpHandler,we as createOsProbe,S as createPersistenceExtension,v as createServer,ie as createServerObserverExtension,zt as createStreamingErrorWriter,o as createTestLogger,Ft as detectClaudeDesktopPresence,X as detectProjectShape,ee as ensureProjectGit,ce as errorResponse,E as evictStaleTrackerEntries,I as extractWikiLinksFromMarkdown,K as findEnclosingGitRoot,ge as findEnclosingProjectRoot,Xn as formatAuthRejectionWire,u as formatContributors,je as formatContributorsFrom,M as gcCheckpointRefs,De as getCurrentMcpLogger,Pe as getLocalDir,k as getLogger,H as getMeter,dn as getMetrics,z as getTracer,Be as handleCollabSocketError,Le as handleSpawnCursor,Kt as iconFromClientName,We as incrementCollabSocketFilteredError,fe as incrementServerObserverFire,n as initShadowRepo,ft as initTelemetry,Cn as installPrettyZodErrors,Zt as installTestLoggers,pn as installUserSkill,kt as isAllowedApiOrigin,Xe as isAllowedWorkspaceHostHeader,tn as isConfigDoc,vn as isHocuspocusAuthRejectionReason,it as isKnownPackId,Ht as isLoopbackAddress,bt as isOrphanMode,On as isPairedWriteOrigin,lt as isPathWithinDir,ur as isProcessAlive,gt as isProjectRoot,on as isSelfWrite,qt as isSystemDoc,$n as isValidLockPid,Tt as lastKnownHash,xt as listRescueCheckpoints,Ke as listStarterPacks,Mn as loadPrincipal,ir as lockFilePath,Wn as loggerFactory,et as mountMcpAndApi,Bn as normalizeFsPath,ve as parseAuthRejectionWire,f as parseHocuspocusAuthToken,In as parseKeepaliveConnectionId,Se as pathToDocName,b as planSeed,g as readAllTargets,ne as readBranchFromHead,fr as readProcessLock,er as readProcessLockDetailed,tr as readServerLock,Lt as readServerPackageVersion,i as readSkillInstallStateSnapshot,Nt as readStateManifest,J as readTargetRecordedAt,Q as readTargetVersion,oe as readUiLock,w as reconcile,P as recordContributor,W as recordSkillInstallEvent,me as registerAllTools,Jn as registerWrite,cr as releaseProcessLock,ar as releaseServerLock,c as releaseUiLock,ke as removeLastKnownHash,j as resetMetrics,Ee as resolveBundledSkillDir,Ne as resolveContentDir,O as resolveCursorBinaryDefault,V as resolveCursorSpawnInvocation,un as resolveLockDir,R as resolvePack,ze as resolvePackageVersion,Ie as restoreContributors,He as restoreLifecycleFromConflictsJson,ue as rewriteMarkdownLinksForDocumentRename,t as rewriteWikiLinksForDocumentRename,pt as runAuthReposSubprocess,wn as runAuthStatusSubprocess,Qt as runCloneSubprocess,mn as runDeviceFlowSubprocess,At as runWithMcpLogger,Ze as safeContentPath,nn as safeSubdir,yn as safetyCheckpoint,at as sanitizeClientName,Ut as saveInMemoryCheckpoint,kn as saveVersion,ut as seedBasenameIndex,_t as setActiveSpanAttributes,sn as shadowGit,Jt as shutdownTelemetry,Et as spawnDetached,St as splitMarkdownBlocks,qe as startWatcher,Nn as streamingProblemEvent,Gn as swapContributors,tt as toBroadcasterKey,Vn as tracedAppendFileSync,ye as tracedLinkSync,p as tracedMkdir,Ln as tracedMkdirSync,Ce as tracedRename,x as tracedRenameSync,_ as tracedRmSync,re as tracedRmdirSync,Rt as tracedUnlinkSync,a as tracedWriteFile,Pt as tracedWriteFileSync,Y as updateLastKnownHash,nr as updateProcessLockPort,Zn as updateServerLockPort,$ as updateUiLockPort,se as validateAgentId,T as validateCloneInputs,F as validateSkillZip,G as withSpan,he as withSpanSync,Yn as writeStateManifest,l as writeTargetVersion,Ae as writeTracker};
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as e,d as t,f as n,g as r,h as i,i as a,m as o,r as s,s as c,t as l,u,y as d}from"./init-
|
|
1
|
+
import{b as e,d as t,f as n,g as r,h as i,i as a,m as o,r as s,s as c,t as l,u,y as d}from"./init-zVplvoPG.mjs";import{i as f,n as p,r as m,t as h}from"./src-CfuREFd9.mjs";import{n as g}from"./loader-BZGdcbd-.mjs";import{n as _}from"./preview-Czwk2dja.mjs";export{o as ALL_EDITOR_IDS,i as EDITOR_LABELS,r as EDITOR_TARGETS,l as LAUNCH_CONFIG_NAME,s as classifyExistingMcpEntry,a as detectInstalledEditors,e as initContent,g as loadConfig,m as parseGitHubBlobUrl,f as parseGitUrl,_ as previewContent,c as readExistingMcpEntry,d as resolveProjectRoot,u as scaffoldLaunchJson,p as validateLocalFolderForShare,t as writeEditorMcpConfig,h as writeProjectAiIntegrations,n as writeUserMcpConfigs};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{l as e}from"./init-zVplvoPG.mjs";export{e as runInit};
|